@eagleoutice/flowr 2.13.12 → 2.13.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -43,7 +43,7 @@ It offers a wide variety of features, for example:
43
43
 
44
44
  ```shell
45
45
  $ docker run -it --rm eagleoutice/flowr # or npm run flowr
46
- flowR repl v2.13.11, R grammar v14 (tree-sitter engine)
46
+ flowR repl v2.13.12, R grammar v14 (tree-sitter engine)
47
47
  R> :query @linter "read.csv(\"/root/x.txt\")"
48
48
  ```
49
49
 
@@ -52,17 +52,17 @@ It offers a wide variety of features, for example:
52
52
 
53
53
 
54
54
  ```text
55
- Query: linter (6 ms)
55
+ Query: linter (25 ms)
56
56
  ╰ Deprecated Functions (deprecated-functions): no findings
57
57
  ╰ File Path Validity (file-path-validity):
58
58
  ╰ certain:
59
59
  ╰ Path `/root/x.txt` at 1.1-23
60
- ╰ Metadata: totalReads: 1, totalUnknown: 0, totalWritesBeforeAlways: 0, totalValid: 0, searchTimeMs: 0, processTimeMs: 1
60
+ ╰ Metadata: totalReads: 1, totalUnknown: 0, totalWritesBeforeAlways: 0, totalValid: 0, searchTimeMs: 2, processTimeMs: 1
61
61
  ╰ Seeded Randomness (seeded-randomness): no findings
62
62
  ╰ Absolute Paths (absolute-file-paths):
63
63
  ╰ certain:
64
64
  ╰ Path `/root/x.txt` at 1.1-23
65
- ╰ Metadata: totalConsidered: 1, totalUnknown: 0, searchTimeMs: 1, processTimeMs: 0
65
+ ╰ Metadata: totalConsidered: 1, totalUnknown: 0, searchTimeMs: 1, processTimeMs: 1
66
66
  ╰ Unused Definitions (unused-definitions): no findings
67
67
  ╰ Network Functions (network-functions): no findings
68
68
  ╰ Dataframe Access Validation (dataframe-access-validation): no findings
@@ -73,7 +73,7 @@ It offers a wide variety of features, for example:
73
73
  ╰ Roxygen Arguments (roxygen-arguments): no findings
74
74
  ╰ No Leaked Credentials (no-leaked-credentials): no findings
75
75
  ╰ Undefined Symbol (undefined-symbol): no findings
76
- All queries together required ≈6 ms (1ms accuracy, total 6 ms)
76
+ All queries together required ≈25 ms (1ms accuracy, total 25 ms)
77
77
  ```
78
78
 
79
79
 
@@ -95,17 +95,17 @@ It offers a wide variety of features, for example:
95
95
 
96
96
  _Results (prettified and summarized):_
97
97
 
98
- Query: **linter** (6 ms)\
98
+ Query: **linter** (374 ms)\
99
99
     ╰ **Deprecated Functions** (deprecated-functions): _no findings_\
100
100
     ╰ **File Path Validity** (file-path-validity):\
101
101
         ╰ certain:\
102
102
             ╰ Path `/root/x.txt` at 1.1-23\
103
-        ╰ _Metadata_: totalReads: 1, totalUnknown: 0, totalWritesBeforeAlways: 0, totalValid: 0, searchTimeMs: 1, processTimeMs: 0\
103
+        ╰ _Metadata_: totalReads: 1, totalUnknown: 0, totalWritesBeforeAlways: 0, totalValid: 0, searchTimeMs: 4, processTimeMs: 1\
104
104
     ╰ **Seeded Randomness** (seeded-randomness): _no findings_\
105
105
     ╰ **Absolute Paths** (absolute-file-paths):\
106
106
         ╰ certain:\
107
107
             ╰ Path `/root/x.txt` at 1.1-23\
108
-        ╰ _Metadata_: totalConsidered: 1, totalUnknown: 0, searchTimeMs: 1, processTimeMs: 0\
108
+        ╰ _Metadata_: totalConsidered: 1, totalUnknown: 0, searchTimeMs: 2, processTimeMs: 0\
109
109
     ╰ **Unused Definitions** (unused-definitions): _no findings_\
110
110
     ╰ **Network Functions** (network-functions): _no findings_\
111
111
     ╰ **Dataframe Access Validation** (dataframe-access-validation): _no findings_\
@@ -116,11 +116,11 @@ It offers a wide variety of features, for example:
116
116
     ╰ **Roxygen Arguments** (roxygen-arguments): _no findings_\
117
117
     ╰ **No Leaked Credentials** (no-leaked-credentials): _no findings_\
118
118
     ╰ **Undefined Symbol** (undefined-symbol): _no findings_\
119
- _All queries together required ≈6 ms (1ms accuracy, total 7 ms)_
119
+ _All queries together required ≈374 ms (1ms accuracy, total 375 ms)_
120
120
 
121
121
  <details> <summary style="color:gray">Show Detailed Results as Json</summary>
122
122
 
123
- The analysis required _6.6 ms_ (including parsing and normalization and the query) within the generation environment.
123
+ The analysis required _375.2 ms_ (including parsing and normalization and the query) within the generation environment.
124
124
 
125
125
  In general, the JSON contains the Ids of the nodes in question as they are present in the normalized AST or the dataflow graph of flowR.
126
126
  Please consult the [Interface](https://github.com/flowr-analysis/flowr/wiki/Interface) wiki page for more information on how to get those.
@@ -137,8 +137,8 @@ It offers a wide variety of features, for example:
137
137
  ".meta": {
138
138
  "totalCalls": 0,
139
139
  "totalFunctionDefinitions": 0,
140
- "searchTimeMs": 2,
141
- "processTimeMs": 0
140
+ "searchTimeMs": 3,
141
+ "processTimeMs": 284
142
142
  }
143
143
  },
144
144
  "file-path-validity": {
@@ -160,8 +160,8 @@ It offers a wide variety of features, for example:
160
160
  "totalUnknown": 0,
161
161
  "totalWritesBeforeAlways": 0,
162
162
  "totalValid": 0,
163
- "searchTimeMs": 1,
164
- "processTimeMs": 0
163
+ "searchTimeMs": 4,
164
+ "processTimeMs": 1
165
165
  }
166
166
  },
167
167
  "seeded-randomness": {
@@ -172,8 +172,8 @@ It offers a wide variety of features, for example:
172
172
  "callsWithAssignmentProducers": 0,
173
173
  "callsWithNonConstantProducers": 0,
174
174
  "callsWithOtherBranchProducers": 0,
175
- "searchTimeMs": 0,
176
- "processTimeMs": 0
175
+ "searchTimeMs": 1,
176
+ "processTimeMs": 1
177
177
  }
178
178
  },
179
179
  "absolute-file-paths": {
@@ -192,7 +192,7 @@ It offers a wide variety of features, for example:
192
192
  ".meta": {
193
193
  "totalConsidered": 1,
194
194
  "totalUnknown": 0,
195
- "searchTimeMs": 1,
195
+ "searchTimeMs": 2,
196
196
  "processTimeMs": 0
197
197
  }
198
198
  },
@@ -209,8 +209,8 @@ It offers a wide variety of features, for example:
209
209
  ".meta": {
210
210
  "totalCalls": 0,
211
211
  "totalFunctionDefinitions": 0,
212
- "searchTimeMs": 0,
213
- "processTimeMs": 0
212
+ "searchTimeMs": 2,
213
+ "processTimeMs": 1
214
214
  }
215
215
  },
216
216
  "dataframe-access-validation": {
@@ -220,7 +220,7 @@ It offers a wide variety of features, for example:
220
220
  "numAccesses": 0,
221
221
  "totalAccessed": 0,
222
222
  "searchTimeMs": 0,
223
- "processTimeMs": 0
223
+ "processTimeMs": 4
224
224
  }
225
225
  },
226
226
  "dead-code": {
@@ -235,7 +235,7 @@ It offers a wide variety of features, for example:
235
235
  ".meta": {
236
236
  "numOfUselessLoops": 0,
237
237
  "searchTimeMs": 0,
238
- "processTimeMs": 0
238
+ "processTimeMs": 1
239
239
  }
240
240
  },
241
241
  "problematic-inputs": {
@@ -249,7 +249,7 @@ It offers a wide variety of features, for example:
249
249
  "results": [],
250
250
  ".meta": {
251
251
  "consideredNodes": 0,
252
- "searchTimeMs": 0,
252
+ "searchTimeMs": 1,
253
253
  "processTimeMs": 0
254
254
  }
255
255
  },
@@ -281,16 +281,16 @@ It offers a wide variety of features, for example:
281
281
  "subscript": 0
282
282
  },
283
283
  "searchTimeMs": 0,
284
- "processTimeMs": 1
284
+ "processTimeMs": 65
285
285
  }
286
286
  }
287
287
  },
288
288
  ".meta": {
289
- "timing": 6
289
+ "timing": 374
290
290
  }
291
291
  },
292
292
  ".meta": {
293
- "timing": 6
293
+ "timing": 374
294
294
  }
295
295
  }
296
296
  ```
@@ -354,7 +354,7 @@ It offers a wide variety of features, for example:
354
354
 
355
355
  ```shell
356
356
  $ docker run -it --rm eagleoutice/flowr # or npm run flowr
357
- flowR repl v2.13.11, R grammar v14 (tree-sitter engine)
357
+ flowR repl v2.13.12, R grammar v14 (tree-sitter engine)
358
358
  R> :query @static-slice (11@sum) file://test/testfiles/example.R
359
359
  ```
360
360
 
@@ -368,7 +368,7 @@ It offers a wide variety of features, for example:
368
368
  N <- 10
369
369
  for(i in 1:(N-1)) sum <- sum + i + w
370
370
  sum
371
- All queries together required ≈2 ms (1ms accuracy, total 2 ms)
371
+ All queries together required ≈81 ms (1ms accuracy, total 82 ms)
372
372
  ```
373
373
 
374
374
 
@@ -383,7 +383,7 @@ It offers a wide variety of features, for example:
383
383
  </details>
384
384
 
385
385
  * 🚀 **fast call-graph, data-, and control-flow graphs**\
386
- Within just [<i><span title="This measurement is automatically fetched from the latest benchmark!">109.6 ms</span></i> (as of Aug 9, 2026)](https://flowr-analysis.github.io/flowr/wiki/stats/benchmark),
386
+ Within just [<i><span title="This measurement is automatically fetched from the latest benchmark!">81.7 ms</span></i> (as of Aug 10, 2026)](https://flowr-analysis.github.io/flowr/wiki/stats/benchmark),
387
387
  _flowR_ can analyze the data- and control-flow of the average real-world R&nbsp;script. See the [benchmarks](https://flowr-analysis.github.io/flowr/wiki/stats/benchmark) for more information,
388
388
  and consult the [wiki pages](https://github.com/flowr-analysis/flowr/wiki/Dataflow-Graph) for more details on the [dataflow graphs](https://github.com/flowr-analysis/flowr/wiki/Dataflow-Graph) as well as [call graphs](https://github.com/flowr-analysis/flowr/wiki/Dataflow-Graph#perspectives-cg).
389
389
 
@@ -419,7 +419,7 @@ It offers a wide variety of features, for example:
419
419
 
420
420
  ```shell
421
421
  $ docker run -it --rm eagleoutice/flowr # or npm run flowr
422
- flowR repl v2.13.11, R grammar v14 (tree-sitter engine)
422
+ flowR repl v2.13.12, R grammar v14 (tree-sitter engine)
423
423
  R> :dataflow* test/testfiles/example.R
424
424
  ```
425
425
 
@@ -692,7 +692,7 @@ It offers a wide variety of features, for example:
692
692
  ```
693
693
 
694
694
 
695
- (The analysis required _1.7 ms_ (including parse and normalize, using the [tree-sitter](https://github.com/flowr-analysis/flowr/wiki/Engines) engine) within the generation environment. No [signature database](https://github.com/flowr-analysis/flowr/wiki/Signature-Database) is mounted for these generated graphs, so `library()` calls attach no package exports; base-R names are still qualified via the generated base-package store (e.g. `acf` as `stats::acf`).)
695
+ (The analysis required _3.8 ms_ (including parse and normalize, using the [tree-sitter](https://github.com/flowr-analysis/flowr/wiki/Engines) engine) within the generation environment. No [signature database](https://github.com/flowr-analysis/flowr/wiki/Signature-Database) is mounted for these generated graphs, so `library()` calls attach no package exports; base-R names are still qualified via the generated base-package store (e.g. `acf` as `stats::acf`).)
696
696
 
697
697
 
698
698
 
package/config.js CHANGED
@@ -437,14 +437,20 @@ exports.FlowrConfig = {
437
437
  gas: joi_1.default.object({
438
438
  thresholds: joi_1.default.object({
439
439
  memory: joi_1.default.object({
440
- problematic: joi_1.default.number().min(0).max(1).optional().description('Heap fraction (0-1) above which Problematic is returned.'),
441
- critical: joi_1.default.number().min(0).max(1).optional().description('Heap fraction (0-1) above which Critical is returned.')
442
- }).optional().description('Heap-usage fraction thresholds (0-1).'),
440
+ problematic: joi_1.default.number().min(0).max(1).optional().description('Heap fraction (0-1) above which Problematic is returned, for every feature without an entry of its own.'),
441
+ critical: joi_1.default.number().min(0).max(1).optional().description('Heap fraction (0-1) above which Critical is returned, for every feature without an entry of its own.')
442
+ }).pattern(joi_1.default.string(), joi_1.default.object({
443
+ problematic: joi_1.default.number().min(0).max(1).optional().description('Heap fraction (0-1) above which Problematic is returned for this feature.'),
444
+ critical: joi_1.default.number().min(0).max(1).optional().description('Heap fraction (0-1) above which Critical is returned for this feature.')
445
+ })).optional().description('Heap-usage fraction thresholds (0-1), either shared or given per feature key (with `default` covering the rest).'),
443
446
  timeMs: joi_1.default.object({
444
- problematic: joi_1.default.number().min(0).optional().description('Elapsed ms above which Problematic is returned.'),
445
- critical: joi_1.default.number().min(0).optional().description('Elapsed ms above which Critical is returned.')
446
- }).optional().description('Elapsed analysis time thresholds in milliseconds.')
447
- }).optional().description('Shared thresholds for all gas checks (scaled by per-feature factor).'),
447
+ problematic: joi_1.default.number().min(0).optional().description('Elapsed ms above which Problematic is returned, for every feature without an entry of its own.'),
448
+ critical: joi_1.default.number().min(0).optional().description('Elapsed ms above which Critical is returned, for every feature without an entry of its own.')
449
+ }).pattern(joi_1.default.string(), joi_1.default.object({
450
+ problematic: joi_1.default.number().min(0).optional().description('Elapsed ms above which Problematic is returned for this feature.'),
451
+ critical: joi_1.default.number().min(0).optional().description('Elapsed ms above which Critical is returned for this feature.')
452
+ })).optional().description('Elapsed analysis time thresholds in milliseconds, either shared or given per feature key (with `default` covering the rest).')
453
+ }).optional().description('Thresholds for all gas checks (scaled by per-feature factor), boundable per feature.'),
448
454
  features: joi_1.default.object().pattern(joi_1.default.string(), joi_1.default.number().min(0).optional()).optional().description('Per-feature sensitivity factors. 0 or absent disables gas checking for that feature. A factor of 2 makes the feature twice as sensitive. Recognised keys: `source`, `side-effect-linking`, `linter`, `slicer`.'),
449
455
  heapProvider: joi_1.default.function().optional().description('Custom heap statistics source (programmatic configs only), overriding the built-in v8/performance.memory detection.')
450
456
  }).optional().description(`Resource-usage guard (gas) configuration. All feature factors default to 0 (disabled). See ${gas_1.GasWikiRef}.`)
@@ -456,12 +456,18 @@ ${ctx.hierarchy(flowr_analyzer_gas_context_1.FlowrAnalyzerGasContext, { showImpl
456
456
  Expensive analysis sites ask for the current resource pressure with
457
457
  ${ctx.linkM(flowr_analyzer_gas_context_1.FlowrAnalyzerGasContext, 'checkGas', { codeFont: true, realNameWrapper: 'i' })}, passing the name of the feature they are about to run
458
458
  (see ${ctx.link('GasFeatureKey')}), and may then degrade or skip their work.
459
- The level combines the current heap usage and the time elapsed since the analysis started (or since the last
460
- ${ctx.linkM(flowr_analyzer_context_1.FlowrAnalyzerContext, 'reset')}, which also resets the gas clock via
461
- ${ctx.linkM(flowr_analyzer_gas_context_1.FlowrAnalyzerGasContext, 'reset', { codeFont: true, realNameWrapper: 'i' })}),
462
- each scaled by the per-feature factor from \`config.gas.features\`.
459
+ The level combines the current heap usage and the time elapsed within the contingent of the current operation,
460
+ each scaled by the per-feature factor from \`config.gas.features\` and compared against the thresholds
461
+ configured for that key (see ${ctx.link('GasThresholdSpec')}).
463
462
  Registered ${ctx.link(flowr_analyzer_gas_plugin_1.FlowrAnalyzerGasPlugin)}s may escalate the level for any key.
464
463
 
464
+ Every operation gets a contingent of its own, and anything beginning a new analysis (an added file, a cache
465
+ invalidation, a ${ctx.linkM(flowr_analyzer_context_1.FlowrAnalyzerContext, 'reset')}) restarts it. To restart it between your own
466
+ phases, call ${ctx.linkM(flowr_analyzer_gas_context_1.FlowrAnalyzerGasContext, 'reset', { codeFont: true, realNameWrapper: 'i' })} on the
467
+ writeable context (\`analyzer.context().gas.reset()\`). To bound a single call, pass \`gas\` overrides to it
468
+ (\`analyzer.query([...], { gas: { slicer: { critical: 30_000 } } })\`) or derive a bounded view with
469
+ ${ctx.linkM(flowr_analyzer_gas_context_1.FlowrAnalyzerGasContext, 'scope', { codeFont: true, realNameWrapper: 'i' })}.
470
+
465
471
  ${(0, doc_structure_1.block)({
466
472
  type: 'NOTE',
467
473
  content: `
@@ -593,6 +593,64 @@ scaled_elapsed = elapsed_ms * factor
593
593
  A factor of \`2\` makes the check twice as sensitive: it triggers \`Problematic\` when the heap
594
594
  is at 35% (= 0.7 / 2) instead of 70%.
595
595
 
596
+ ### Per-Feature Thresholds
597
+
598
+ A dataflow extraction, a linter pass and a static slice are not worth the same allowance, so each dimension
599
+ of \`config.gas.thresholds\` may be bounded per feature key (see ${ctx.link('GasThresholdSpec')}), with
600
+ \`default\` covering the keys that have no entry of their own:
601
+
602
+ \`\`\`json
603
+ {
604
+ "gas": {
605
+ "thresholds": {
606
+ "timeMs": {
607
+ "default": { "problematic": 60000, "critical": 120000 },
608
+ "slicer": { "problematic": 24000, "critical": 30000 }
609
+ }
610
+ },
611
+ "features": {
612
+ "slicer": 1
613
+ }
614
+ }
615
+ }
616
+ \`\`\`
617
+
618
+ An entry only has to name the bounds it changes; the rest falls back to \`default\` and then to a directly
619
+ given \`{ problematic, critical }\` pair, which stays valid and still means "the same bound for everything".
620
+
621
+ ### Per-Operation Contingents
622
+
623
+ The elapsed-time bound is *not* measured from the creation of the analyzer. Each analysis run (parse,
624
+ normalize, dataflow) and each ${ctx.link(static_slicer_1.staticSlice.name)} runs against a contingent of its own, so analysing
625
+ a project and then asking for twenty slices gives twenty-one contingents, not one clock the analysis spent.
626
+
627
+ Anything beginning a new analysis restarts it too: an added file, a cache invalidation, a re-parse, or an
628
+ explicit ${ctx.linkM(flowr_analyzer_1.FlowrAnalyzer, 'reset')}. Operations in flight keep theirs, as restarting a running
629
+ traversal's clock would defeat the guard bounding it. To split your *own* phases, call
630
+ ${ctx.linkM(flowr_analyzer_gas_context_1.FlowrAnalyzerGasContext, 'reset', { codeFont: true, realNameWrapper: 'i' })} on the writeable
631
+ context (\`analyzer.context().gas.reset()\`) - supported API, not an internal hook.
632
+
633
+ ### Bounding a Single Call
634
+
635
+ Bounds for one call, keyed by the same feature names and measured from that call (see ${ctx.link('GasOverrides')}):
636
+
637
+ ${(0, doc_code_1.codeBlock)('ts', `await analyzer.query([{ type: 'static-slice', criteria: ['12@product'] }], {
638
+ gas: { slicer: { critical: 30_000 } }
639
+ });`)}
640
+
641
+ Bare \`problematic\`/\`critical\` numbers are elapsed milliseconds; use \`timeMs\`/\`memory\` to be explicit and
642
+ \`factor\` for the sensitivity. Naming a feature enables gas for it even when \`config.gas.features\` disables
643
+ it (pass \`factor: 0\` to keep it off). ${ctx.linkM(flowr_analyzer_1.FlowrAnalyzer, 'runFull')} and
644
+ ${ctx.linkM(flowr_analyzer_1.FlowrAnalyzer, 'runSearch')} take the same, and read-only holders of a context can derive a
645
+ bounded view with ${ctx.linkM(flowr_analyzer_gas_context_1.FlowrAnalyzerGasContext, 'scope', { codeFont: true, realNameWrapper: 'i' })}.
646
+
647
+ ### When the Slicer Runs Out
648
+
649
+ A slice cut short comes back with \`stoppedEarly\` and a \`progress\` saying how far it got (see
650
+ ${ctx.link('SliceProgress')}). A \`frontier\` of \`0\` means the queue drained after all; a small \`frontier\`
651
+ next to a large \`visited\` says little is missing. Without it a truncated slice is all-or-nothing, and
652
+ "as far as flowR got" is not "what is independent", so it would have to be discarded.
653
+
596
654
  ### Known Feature Keys
597
655
 
598
656
  ${ctx.doc('GasFeatureKey')}
package/gas.d.ts CHANGED
@@ -33,7 +33,7 @@ export declare const GasFeatureKey: {
33
33
  readonly Slicer: "slicer";
34
34
  };
35
35
  export type GasFeatureKey = typeof GasFeatureKey[keyof typeof GasFeatureKey];
36
- /** Paired low/high thresholds used inside {@link FlowrGasThresholds}. */
36
+ /** Paired low/high thresholds used inside {@link GasThresholdSpec}. */
37
37
  export interface GasThresholdPair extends MergeableRecord {
38
38
  /** Returns {@link GasLevel.Problematic} when reached (after factor scaling). */
39
39
  readonly problematic: number;
@@ -41,16 +41,66 @@ export interface GasThresholdPair extends MergeableRecord {
41
41
  readonly critical: number;
42
42
  }
43
43
  /**
44
- * Thresholds for {@link GasLevel} transitions used by {@link ReadOnlyFlowrAnalyzerGasContext.checkGas}.
45
- * Memory values are fractions of the heap limit reported by the active heap source (0-1), time values are in milliseconds.
44
+ * Thresholds for one gas dimension, either as one pair for every feature or split per {@link GasFeatureKey}:
45
+ *
46
+ * ```ts
47
+ * timeMs: {
48
+ * default: { problematic: 60_000, critical: 120_000 },
49
+ * slicer: { problematic: 24_000, critical: 30_000 }
50
+ * }
51
+ * ```
52
+ *
53
+ * Per bound, a feature entry wins over `default`, which wins over the direct pair. A bound nowhere given never triggers.
54
+ */
55
+ export interface GasThresholdSpec extends MergeableRecord {
56
+ /** Shared bound, for every feature without a more specific entry. */
57
+ readonly problematic?: number;
58
+ /** Shared bound, for every feature without a more specific entry. */
59
+ readonly critical?: number;
60
+ /** Bounds for the features that have no entry of their own. */
61
+ readonly default?: Partial<GasThresholdPair>;
62
+ /** Bounds for one {@link GasFeatureKey}. */
63
+ readonly [feature: string]: number | Partial<GasThresholdPair> | undefined;
64
+ }
65
+ /**
66
+ * Thresholds for {@link GasLevel} transitions used by {@link ReadOnlyFlowrAnalyzerGasContext.checkGas}, each
67
+ * dimension boundable per feature (see {@link GasThresholdSpec}).
46
68
  * See the [Gas (Resource Guard)](https://github.com/flowr-analysis/flowr/wiki/Core#gas-resource-guard) wiki section.
47
69
  */
48
70
  export interface FlowrGasThresholds extends MergeableRecord {
49
71
  /** Heap-usage fraction thresholds (0-1, before factor scaling). */
50
- readonly memory: GasThresholdPair;
72
+ readonly memory: GasThresholdSpec;
51
73
  /** Elapsed analysis time thresholds in milliseconds (before factor scaling). */
52
- readonly timeMs: GasThresholdPair;
74
+ readonly timeMs: GasThresholdSpec;
75
+ }
76
+ /** Gas bounds for one feature within a single call, see {@link GasOverrides}. */
77
+ export interface GasFeatureOverride extends MergeableRecord {
78
+ /** Elapsed ms, shorthand for `timeMs.problematic`. */
79
+ readonly problematic?: number;
80
+ /** Elapsed ms, shorthand for `timeMs.critical`. */
81
+ readonly critical?: number;
82
+ /** Overrides `config.gas.thresholds.timeMs` for this call. */
83
+ readonly timeMs?: Partial<GasThresholdPair>;
84
+ /** Overrides `config.gas.thresholds.memory` for this call. */
85
+ readonly memory?: Partial<GasThresholdPair>;
86
+ /** Sensitivity factor, defaulting to the configured one, or `1` if the feature is disabled. */
87
+ readonly factor?: number;
53
88
  }
89
+ /**
90
+ * Gas bounds for a single call, keyed by {@link GasFeatureKey}, measured from that call:
91
+ *
92
+ * ```ts
93
+ * analyzer.query([...], { gas: { slicer: { critical: 30_000 } } });
94
+ * ```
95
+ *
96
+ * Naming a feature enables gas for it even when `config.gas.features` disables it; pass `factor: 0` to keep it off.
97
+ */
98
+ export type GasOverrides = {
99
+ /** Bounds for the features that have no entry of their own. */
100
+ readonly default?: GasFeatureOverride;
101
+ /** Bounds for one {@link GasFeatureKey}. */
102
+ readonly [feature: string]: GasFeatureOverride | undefined;
103
+ };
54
104
  /** Heap statistics used for gas memory checks (field names follow the v8 API). */
55
105
  export interface GasHeapStatistics {
56
106
  readonly used_heap_size: number;
@@ -68,7 +118,7 @@ export interface GasHeapStatistics {
68
118
  * See the [Gas (Resource Guard)](https://github.com/flowr-analysis/flowr/wiki/Core#gas-resource-guard) wiki section.
69
119
  */
70
120
  export interface FlowrGasConfig extends MergeableRecord {
71
- /** Shared thresholds scaled by each feature factor before comparison. */
121
+ /** Thresholds scaled by each feature factor before comparison, optionally bounded per feature (see {@link GasThresholdSpec}). */
72
122
  readonly thresholds: FlowrGasThresholds;
73
123
  /** Per-feature sensitivity factors. Missing or `0` disables checking with zero overhead. */
74
124
  readonly features: Record<string, number | undefined>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eagleoutice/flowr",
3
- "version": "2.13.12",
3
+ "version": "2.13.13",
4
4
  "description": "Static Dataflow Analyzer and Program Slicer for the R Programming Language",
5
5
  "types": "dist/src/index.d.ts",
6
6
  "repository": {
@@ -34,6 +34,7 @@ export declare class FlowrAnalyzerCache<Parser extends KnownParser> extends Flow
34
34
  private get;
35
35
  reset(): void;
36
36
  private runTapeUntil;
37
+ private stepTapeUntil;
37
38
  private storeIncrementalSnapshotIfAvailable;
38
39
  /**
39
40
  * Get the parse output for the request, parsing if necessary.
@@ -70,6 +70,10 @@ class FlowrAnalyzerCache extends flowr_cache_1.FlowrCache {
70
70
  if (force) {
71
71
  this.reset();
72
72
  }
73
+ /* the contingent belongs to the analysis, so stepping the tape starts one of its own */
74
+ return this.args.context.gas.withGas(undefined, () => this.stepTapeUntil(until));
75
+ }
76
+ async stepTapeUntil(until) {
73
77
  let g;
74
78
  while ((g = until()) === undefined && this.pipeline.hasNextStep()) {
75
79
  await this.pipeline.nextStep();
@@ -202,12 +202,15 @@ class FlowrAnalyzerContext {
202
202
  /** delegate request addition */
203
203
  addRequests(requests) {
204
204
  this.files.addRequests(requests);
205
+ this.gas.reset();
205
206
  }
206
207
  addFile(f) {
207
208
  this.files.addFile(f);
209
+ this.gas.reset();
208
210
  }
209
211
  addFiles(f) {
210
212
  this.files.addFiles(f);
213
+ this.gas.reset();
211
214
  }
212
215
  /**
213
216
  * Get a read-only version of this context.
@@ -233,6 +236,8 @@ class FlowrAnalyzerContext {
233
236
  this.files.receive(event);
234
237
  this.deps.receive(event);
235
238
  this.inc.receive(event);
239
+ /* what became stale is analyzed again, and that gets the full contingent */
240
+ this.gas.receive(event);
236
241
  }
237
242
  }
238
243
  exports.FlowrAnalyzerContext = FlowrAnalyzerContext;
@@ -1,6 +1,7 @@
1
- import { type FlowrGasConfig, GasLevel } from '../../gas';
1
+ import { type FlowrGasConfig, GasLevel, type GasOverrides } from '../../gas';
2
2
  import type { FlowrAnalyzerGasPlugin } from '../plugins/gas-plugins/flowr-analyzer-gas-plugin';
3
3
  import type { FlowrAnalyzerContext } from './flowr-analyzer-context';
4
+ import type { InvalidationEvent, InvalidationEventReceiver } from '../cache/flowr-cache';
4
5
  /** Read-only gas context exposed via `ctx.gas`. */
5
6
  export interface ReadOnlyFlowrAnalyzerGasContext {
6
7
  readonly name: string;
@@ -8,21 +9,74 @@ export interface ReadOnlyFlowrAnalyzerGasContext {
8
9
  * Returns the resource-pressure level for `key` (`config.gas.features[key]`).
9
10
  * Returns `GasLevel.Normal` with zero overhead when the feature factor is 0 or absent
10
11
  * and no gas plugins are registered (plugins are always consulted and may escalate any key).
12
+ *
13
+ * Measured from the start of the enclosing contingent, against the thresholds configured for `key`
14
+ * (see {@link GasThresholdSpec}), not one allowance shared by everything the analyzer does.
11
15
  */
12
16
  checkGas(key: string): GasLevel;
17
+ /**
18
+ * A view with a fresh contingent, measured from this call, for one operation to run against.
19
+ * The enclosing bounds still apply, `overrides` winning over them. Derives a new object rather than
20
+ * mutating this one, so it is safe for nested and concurrent work.
21
+ */
22
+ scope(overrides?: GasOverrides): ReadOnlyFlowrAnalyzerGasContext;
23
+ }
24
+ /**
25
+ * The gas context as the owner of the analyzer sees it, reachable via `analyzer.context().gas`.
26
+ * Adds the operations that restart a contingent to {@link ReadOnlyFlowrAnalyzerGasContext}.
27
+ */
28
+ export interface WriteableFlowrAnalyzerGasContext extends ReadOnlyFlowrAnalyzerGasContext {
29
+ /** see {@link FlowrAnalyzerGasContext#reset} */
30
+ reset(): void;
31
+ /** see {@link FlowrAnalyzerGasContext#withGas} */
32
+ withGas<T>(overrides: GasOverrides | undefined, fn: () => T): T;
13
33
  }
14
34
  /** Checks heap and elapsed-time pressure for named analysis features. See {@link ReadOnlyFlowrAnalyzerGasContext}. */
15
- export declare class FlowrAnalyzerGasContext implements ReadOnlyFlowrAnalyzerGasContext {
35
+ export declare class FlowrAnalyzerGasContext implements WriteableFlowrAnalyzerGasContext, InvalidationEventReceiver {
16
36
  readonly name = "flowr-analyzer-gas-context";
17
- private startTime;
37
+ /** what a gas check falls back to when no operation declared a contingent of its own */
38
+ private readonly base;
39
+ /** the contingents of the operations in flight, innermost last */
40
+ private readonly frames;
18
41
  private readonly config;
19
42
  private readonly ctx;
20
43
  private readonly plugins;
21
44
  constructor(ctx: FlowrAnalyzerContext, config: FlowrGasConfig | undefined, plugins: readonly FlowrAnalyzerGasPlugin[]);
22
- /** Restart the elapsed-time counter (called when the owning context is reset). */
45
+ /**
46
+ * Restart the contingent, so what follows is measured from now. Supported API: call it between phases
47
+ * that should each get the full allowance (`analyzer.context().gas.reset()`).
48
+ *
49
+ * flowR calls it itself whenever a new analysis begins, so a caller only has to split its *own* phases.
50
+ * Operations in flight keep their contingent, as restarting a running traversal's clock would defeat the
51
+ * guard bounding it.
52
+ */
23
53
  reset(): void;
54
+ /** A new analysis makes the spent contingent irrelevant. */
55
+ receive(_event: InvalidationEvent): void;
56
+ /**
57
+ * Run `fn` against a fresh contingent bounded by `overrides`, ending when it settles if `fn` is async.
58
+ * Every check while `fn` runs sees it, however deep, which is how the bounds reach sites that only ever
59
+ * get a context handed to them.
60
+ *
61
+ * Being ambient, concurrent operations on one analyzer see whichever started last, so prefer
62
+ * {@link scope} wherever the context can be threaded through.
63
+ */
64
+ withGas<T>(overrides: GasOverrides | undefined, fn: () => T): T;
65
+ scope(overrides?: GasOverrides): ReadOnlyFlowrAnalyzerGasContext;
66
+ private derive;
67
+ private viewOf;
68
+ private drop;
69
+ private activeScope;
70
+ /**
71
+ * The innermost layer stating this bound wins, the configured thresholds apply when none does.
72
+ * Resolved per bound, so a layer naming only `critical` leaves `problematic` to the layer outside it.
73
+ */
74
+ private bound;
75
+ /** An override naming the feature enables it even when the config disables it. */
76
+ private factorFor;
24
77
  private memoryLevel;
25
78
  private static maxLevel;
26
79
  private timeLevel;
27
80
  checkGas(key: string): GasLevel;
81
+ private levelFor;
28
82
  }
@@ -28,10 +28,39 @@ function tryGetHeapStatistics() {
28
28
  }
29
29
  return heapStatisticsProvider ? heapStatisticsProvider() : undefined;
30
30
  }
31
+ function isPair(v) {
32
+ return typeof v === 'object' && v !== null;
33
+ }
34
+ /** feature entry, then `default`, then the shared pair */
35
+ function configuredBound(spec, feature, bound) {
36
+ const own = spec?.[feature];
37
+ if (isPair(own) && own[bound] !== undefined) {
38
+ return own[bound];
39
+ }
40
+ const fallback = spec?.default?.[bound];
41
+ if (fallback !== undefined) {
42
+ return fallback;
43
+ }
44
+ const shared = spec?.[bound];
45
+ return typeof shared === 'number' ? shared : undefined;
46
+ }
47
+ /** a bare number is an elapsed-time bound in ms */
48
+ function overriddenBound(entry, dim, bound) {
49
+ return entry?.[dim]?.[bound] ?? (dim === 'timeMs' ? entry?.[bound] : undefined);
50
+ }
51
+ function entryOf(layer, key) {
52
+ return layer[key] ?? layer.default;
53
+ }
54
+ function isThenable(v) {
55
+ return typeof v?.then === 'function';
56
+ }
31
57
  /** Checks heap and elapsed-time pressure for named analysis features. See {@link ReadOnlyFlowrAnalyzerGasContext}. */
32
58
  class FlowrAnalyzerGasContext {
33
59
  name = 'flowr-analyzer-gas-context';
34
- startTime;
60
+ /** what a gas check falls back to when no operation declared a contingent of its own */
61
+ base;
62
+ /** the contingents of the operations in flight, innermost last */
63
+ frames = [];
35
64
  config;
36
65
  ctx;
37
66
  plugins;
@@ -39,22 +68,113 @@ class FlowrAnalyzerGasContext {
39
68
  this.ctx = ctx;
40
69
  this.config = config;
41
70
  this.plugins = plugins;
42
- this.startTime = Date.now();
71
+ this.base = { startTime: Date.now(), layers: [] };
43
72
  }
44
- /** Restart the elapsed-time counter (called when the owning context is reset). */
73
+ /**
74
+ * Restart the contingent, so what follows is measured from now. Supported API: call it between phases
75
+ * that should each get the full allowance (`analyzer.context().gas.reset()`).
76
+ *
77
+ * flowR calls it itself whenever a new analysis begins, so a caller only has to split its *own* phases.
78
+ * Operations in flight keep their contingent, as restarting a running traversal's clock would defeat the
79
+ * guard bounding it.
80
+ */
45
81
  reset() {
46
- this.startTime = Date.now();
82
+ this.base.startTime = Date.now();
83
+ }
84
+ /** A new analysis makes the spent contingent irrelevant. */
85
+ receive(_event) {
86
+ this.reset();
87
+ }
88
+ /**
89
+ * Run `fn` against a fresh contingent bounded by `overrides`, ending when it settles if `fn` is async.
90
+ * Every check while `fn` runs sees it, however deep, which is how the bounds reach sites that only ever
91
+ * get a context handed to them.
92
+ *
93
+ * Being ambient, concurrent operations on one analyzer see whichever started last, so prefer
94
+ * {@link scope} wherever the context can be threaded through.
95
+ */
96
+ withGas(overrides, fn) {
97
+ const frame = this.derive(overrides);
98
+ this.frames.push(frame);
99
+ let result;
100
+ try {
101
+ result = fn();
102
+ }
103
+ catch (e) {
104
+ this.drop(frame);
105
+ throw e;
106
+ }
107
+ if (isThenable(result)) {
108
+ return result.then(v => {
109
+ this.drop(frame);
110
+ return v;
111
+ }, (e) => {
112
+ this.drop(frame);
113
+ throw e;
114
+ });
115
+ }
116
+ this.drop(frame);
117
+ return result;
118
+ }
119
+ scope(overrides) {
120
+ return this.viewOf(this.derive(overrides));
47
121
  }
48
- memoryLevel(factor, t) {
122
+ derive(overrides, from) {
123
+ const inherited = (from ?? this.activeScope()).layers;
124
+ return { startTime: Date.now(), layers: overrides ? [...inherited, overrides] : inherited };
125
+ }
126
+ viewOf(scope) {
127
+ return {
128
+ name: `${this.name}:scope`,
129
+ checkGas: key => this.levelFor(key, scope),
130
+ scope: o => this.viewOf(this.derive(o, scope))
131
+ };
132
+ }
133
+ drop(frame) {
134
+ const idx = this.frames.lastIndexOf(frame);
135
+ if (idx >= 0) {
136
+ this.frames.splice(idx, 1);
137
+ }
138
+ }
139
+ activeScope() {
140
+ return this.frames.length > 0 ? this.frames[this.frames.length - 1] : this.base;
141
+ }
142
+ /**
143
+ * The innermost layer stating this bound wins, the configured thresholds apply when none does.
144
+ * Resolved per bound, so a layer naming only `critical` leaves `problematic` to the layer outside it.
145
+ */
146
+ bound(scope, key, dim, bound) {
147
+ for (let i = scope.layers.length - 1; i >= 0; i--) {
148
+ const stated = overriddenBound(entryOf(scope.layers[i], key), dim, bound);
149
+ if (stated !== undefined) {
150
+ return stated;
151
+ }
152
+ }
153
+ return configuredBound(this.config?.thresholds?.[dim], key, bound) ?? Number.POSITIVE_INFINITY;
154
+ }
155
+ /** An override naming the feature enables it even when the config disables it. */
156
+ factorFor(scope, key) {
157
+ const configured = this.config?.features?.[key] ?? 0;
158
+ let named = false;
159
+ for (let i = scope.layers.length - 1; i >= 0; i--) {
160
+ const entry = entryOf(scope.layers[i], key);
161
+ if (entry?.factor !== undefined) {
162
+ return entry.factor;
163
+ }
164
+ named ||= entry !== undefined;
165
+ }
166
+ return named ? configured || 1 : configured;
167
+ }
168
+ memoryLevel(factor, key, scope) {
49
169
  const stats = this.config?.heapProvider ? this.config.heapProvider() : tryGetHeapStatistics();
50
170
  if (stats === undefined || stats.heap_size_limit <= 0) {
51
171
  return 0 /* GasLevel.Normal */;
52
172
  }
53
173
  const ratio = (stats.used_heap_size / stats.heap_size_limit) * factor;
54
- if (ratio >= t.memory.critical) {
174
+ if (ratio >= this.bound(scope, key, 'memory', 'critical')) {
55
175
  return 2 /* GasLevel.Critical */;
56
176
  }
57
- if (ratio >= t.memory.problematic) {
177
+ if (ratio >= this.bound(scope, key, 'memory', 'problematic')) {
58
178
  return 1 /* GasLevel.Problematic */;
59
179
  }
60
180
  return 0 /* GasLevel.Normal */;
@@ -62,27 +182,29 @@ class FlowrAnalyzerGasContext {
62
182
  static maxLevel(a, b) {
63
183
  return a >= b ? a : b;
64
184
  }
65
- timeLevel(factor, t) {
66
- const elapsed = (Date.now() - this.startTime) * factor;
67
- if (elapsed >= t.timeMs.critical) {
185
+ timeLevel(factor, key, scope) {
186
+ const elapsed = (Date.now() - scope.startTime) * factor;
187
+ if (elapsed >= this.bound(scope, key, 'timeMs', 'critical')) {
68
188
  return 2 /* GasLevel.Critical */;
69
189
  }
70
- if (elapsed >= t.timeMs.problematic) {
190
+ if (elapsed >= this.bound(scope, key, 'timeMs', 'problematic')) {
71
191
  return 1 /* GasLevel.Problematic */;
72
192
  }
73
193
  return 0 /* GasLevel.Normal */;
74
194
  }
75
195
  checkGas(key) {
76
- const factor = this.config?.features?.[key];
196
+ return this.levelFor(key, this.activeScope());
197
+ }
198
+ levelFor(key, scope) {
199
+ const factor = this.factorFor(scope, key);
77
200
  if (!factor && this.plugins.length === 0) {
78
201
  return 0 /* GasLevel.Normal */;
79
202
  }
80
203
  let level = 0 /* GasLevel.Normal */;
81
204
  if (factor) {
82
- const t = this.config.thresholds;
83
- level = FlowrAnalyzerGasContext.maxLevel(level, this.memoryLevel(factor, t));
205
+ level = FlowrAnalyzerGasContext.maxLevel(level, this.memoryLevel(factor, key, scope));
84
206
  if (level < 2 /* GasLevel.Critical */) {
85
- level = FlowrAnalyzerGasContext.maxLevel(level, this.timeLevel(factor, t));
207
+ level = FlowrAnalyzerGasContext.maxLevel(level, this.timeLevel(factor, key, scope));
86
208
  }
87
209
  }
88
210
  for (const plugin of this.plugins) {
@@ -19,6 +19,19 @@ import type { FlowrFileProvider } from './context/flowr-file';
19
19
  import type { Tree } from 'web-tree-sitter';
20
20
  import type { CallGraph } from '../dataflow/graph/call-graph';
21
21
  import type { InvalidationEvent } from './cache/flowr-cache';
22
+ import type { GasOverrides } from '../gas';
23
+ /** Options for a single analyzer operation, bounding what it may cost. */
24
+ export interface FlowrAnalysisOptions {
25
+ /**
26
+ * Gas bounds for this call (see {@link GasOverrides}), measured from it rather than against whatever the
27
+ * analyzer already spent, and winning over `config.gas.thresholds` for its duration:
28
+ *
29
+ * ```ts
30
+ * analyzer.query([...], { gas: { slicer: { critical: 30_000 } } });
31
+ * ```
32
+ */
33
+ readonly gas?: GasOverrides;
34
+ }
22
35
  /**
23
36
  * Extends the {@link ReadonlyFlowrAnalysisProvider} with methods that allow modifying the analyzer state.
24
37
  */
@@ -133,17 +146,22 @@ export interface ReadonlyFlowrAnalysisProvider<Parser extends KnownParser = Know
133
146
  peekCallGraph(): CallGraph | undefined;
134
147
  /**
135
148
  * Access the query API for the request.
136
- * @param query - The list of queries.
149
+ * @param query - The list of queries.
150
+ * @param options - Bounds for this call, see {@link FlowrAnalysisOptions}.
137
151
  */
138
- query<Types extends SupportedQueryTypes = SupportedQueryTypes>(query: Queries<Types>): Promise<QueryResults<Types>>;
152
+ query<Types extends SupportedQueryTypes = SupportedQueryTypes>(query: Queries<Types>, options?: FlowrAnalysisOptions): Promise<QueryResults<Types>>;
139
153
  /**
140
154
  * Run a search on the current analysis.
155
+ * @param search - The search to run.
156
+ * @param options - Bounds for this call, see {@link FlowrAnalysisOptions}.
141
157
  */
142
- runSearch<Search extends FlowrSearchLike>(search: Search): Promise<GetSearchElements<SearchOutput<Search>>>;
158
+ runSearch<Search extends FlowrSearchLike>(search: Search, options?: FlowrAnalysisOptions): Promise<GetSearchElements<SearchOutput<Search>>>;
143
159
  /**
144
160
  * This executes all steps of the core analysis (parse, normalize, dataflow).
161
+ * @param force - Do not use the cache, instead force a new analysis.
162
+ * @param options - Bounds for this call, see {@link FlowrAnalysisOptions}.
145
163
  */
146
- runFull(force?: boolean): Promise<void>;
164
+ runFull(force?: boolean, options?: FlowrAnalysisOptions): Promise<void>;
147
165
  /** This is the config used for the analyzer */
148
166
  flowrConfig: FlowrConfig;
149
167
  /** Merge a runtime update into the base config and invalidate the derived config and cached analysis, so it takes effect. */
@@ -202,13 +220,13 @@ export declare class FlowrAnalyzer<Parser extends KnownParser = KnownParser> imp
202
220
  peekNormalize(): NonNullable<AnalyzerCacheType<Parser>['normalize']> | undefined;
203
221
  dataflow(force?: boolean): Promise<NonNullable<AnalyzerCacheType<Parser>['dataflow']>>;
204
222
  peekDataflow(): NonNullable<AnalyzerCacheType<Parser>['dataflow']> | undefined;
205
- runFull(force?: boolean): Promise<void>;
223
+ runFull(force?: boolean, options?: FlowrAnalysisOptions): Promise<void>;
206
224
  controlflow(simplifications?: readonly CfgSimplificationPassName[], kind?: CfgKind, force?: boolean): Promise<ControlFlowInformation>;
207
225
  peekControlflow(simplifications?: readonly CfgSimplificationPassName[], kind?: CfgKind): ControlFlowInformation | undefined;
208
226
  callGraph(force?: boolean): Promise<CallGraph>;
209
227
  peekCallGraph(): CallGraph | undefined;
210
- query<Types extends SupportedQueryTypes = SupportedQueryTypes>(query: Queries<Types>): Promise<QueryResults<Types>>;
211
- runSearch<Search extends FlowrSearchLike>(search: Search): Promise<GetSearchElements<SearchOutput<Search>>>;
228
+ query<Types extends SupportedQueryTypes = SupportedQueryTypes>(query: Queries<Types>, options?: FlowrAnalysisOptions): Promise<QueryResults<Types>>;
229
+ runSearch<Search extends FlowrSearchLike>(search: Search, options?: FlowrAnalysisOptions): Promise<GetSearchElements<SearchOutput<Search>>>;
212
230
  /**
213
231
  * Free the cached analyses (including any WASM-backed parse trees) and close the parser.
214
232
  * Closing is only required for an RShell/remote engine, but this also frees the cached parse trees.
@@ -136,8 +136,8 @@ class FlowrAnalyzer {
136
136
  peekDataflow() {
137
137
  return this.cache.peekDataflow();
138
138
  }
139
- async runFull(force) {
140
- await this.dataflow(force);
139
+ async runFull(force, options) {
140
+ await this.ctx.gas.withGas(options?.gas, () => this.dataflow(force));
141
141
  return;
142
142
  }
143
143
  async controlflow(simplifications, kind, force) {
@@ -152,11 +152,11 @@ class FlowrAnalyzer {
152
152
  peekCallGraph() {
153
153
  return this.cache.peekCallGraph();
154
154
  }
155
- async query(query) {
156
- return (0, query_1.executeQueries)({ analyzer: this }, query);
155
+ async query(query, options) {
156
+ return this.ctx.gas.withGas(options?.gas, () => (0, query_1.executeQueries)({ analyzer: this }, query));
157
157
  }
158
- async runSearch(search) {
159
- return (0, flowr_search_executor_1.runSearch)(search, this);
158
+ async runSearch(search, options) {
159
+ return this.ctx.gas.withGas(options?.gas, () => (0, flowr_search_executor_1.runSearch)(search, this));
160
160
  }
161
161
  /**
162
162
  * Free the cached analyses (including any WASM-backed parse trees) and close the parser.
@@ -13,6 +13,17 @@ export interface NodeToSlice {
13
13
  /** if we add a function call, we may need it only for its side effects (e.g., a redefinition of a global variable), if so, 'returns' links will not be traced */
14
14
  readonly onlyForSideEffects: boolean;
15
15
  }
16
+ /**
17
+ * How far a traversal got before it was cut short, so a caller can judge a truncated slice instead of
18
+ * having to drop it: a `frontier` of `0` means the queue drained after all, and a small `frontier` next to
19
+ * a large `visited` says little is missing.
20
+ */
21
+ export interface SliceProgress {
22
+ /** queue entries the traversal expanded */
23
+ readonly visited: number;
24
+ /** entries still queued when it stopped */
25
+ readonly frontier: number;
26
+ }
16
27
  /**
17
28
  * The result of the slice step
18
29
  */
@@ -36,6 +47,8 @@ export interface SliceResult {
36
47
  * {@link result} is what was reached until then and not the complete slice.
37
48
  */
38
49
  readonly stoppedEarly?: boolean;
50
+ /** How far the traversal got, set exactly when {@link stoppedEarly} is. */
51
+ readonly progress?: SliceProgress;
39
52
  /**
40
53
  * The names the slice reads without defining them, so running it on its own would fail with
41
54
  * `object 'x' not found`. Empty when the slice is closed under the names it uses.
@@ -8,6 +8,7 @@ import type { DataflowInformation } from '../../dataflow/info';
8
8
  import type { DataflowGraph } from '../../dataflow/graph/graph';
9
9
  import type { ReadOnlyFlowrAnalyzerContext } from '../../project/context/flowr-analyzer-context';
10
10
  import { SliceDirection } from '../../util/slice-direction';
11
+ import type { GasOverrides } from '../../gas';
11
12
  export declare const slicerLogger: import("tslog").Logger<import("tslog").ILogObj>;
12
13
  /** Options for {@link staticSlice}. */
13
14
  export interface StaticSliceOptions {
@@ -41,6 +42,11 @@ export interface StaticSliceOptions {
41
42
  * Defaults to `false` (slicing stops at the function-definition boundary, the historic behavior).
42
43
  */
43
44
  readonly includeCallees?: boolean;
45
+ /**
46
+ * Gas bounds for this slice (see {@link GasOverrides}), on top of the enclosing operation's.
47
+ * A slice always gets a contingent of its own, so it is never billed for the analysis or the slices before it.
48
+ */
49
+ readonly gas?: GasOverrides;
44
50
  }
45
51
  /**
46
52
  * Computes the node ids to include in a static slice, starting from the given seed ids.
@@ -55,7 +61,7 @@ export declare function staticSlice(options: StaticSliceOptions): Readonly<Slice
55
61
  * reduced to that set and its edges are inverted in a single pass via {@link Dataflow.reduceAndInvertGraph}.
56
62
  * The forward traversal then runs only within that subgraph, avoiding nodes that cannot contribute to the dice.
57
63
  */
58
- export declare function staticDice(ctx: ReadOnlyFlowrAnalyzerContext, info: DataflowInformation, ast: NormalizedAst, startIds: readonly NodeId[], endIds: readonly NodeId[], threshold?: number, includeCallees?: boolean): Readonly<SliceResult>;
64
+ export declare function staticDice(ctx: ReadOnlyFlowrAnalyzerContext, info: DataflowInformation, ast: NormalizedAst, startIds: readonly NodeId[], endIds: readonly NodeId[], threshold?: number, includeCallees?: boolean, gas?: GasOverrides): Readonly<SliceResult>;
59
65
  /**
60
66
  * Updates the potential addition for the given target node in the visiting queue.
61
67
  * This describes vertices that might be added *if* another path reaches them.
@@ -40,7 +40,7 @@ function staticSlice(options) {
40
40
  graph = df_helper_1.Dataflow.invertGraph(graph, ctx.env.makeCleanEnv());
41
41
  }
42
42
  }
43
- const queue = new visiting_queue_1.VisitingQueue(threshold, cache, id => graph.hasVertex(id), ctx.gas);
43
+ const queue = new visiting_queue_1.VisitingQueue(threshold, cache, id => graph.hasVertex(id), ctx.gas.scope(options.gas));
44
44
  let minNesting = Number.MAX_SAFE_INTEGER;
45
45
  const sliceSeedIds = new Set();
46
46
  // every node ships the call environment which registers the calling environment
@@ -176,12 +176,12 @@ function freeNamesOf(slice, graph) {
176
176
  * reduced to that set and its edges are inverted in a single pass via {@link Dataflow.reduceAndInvertGraph}.
177
177
  * The forward traversal then runs only within that subgraph, avoiding nodes that cannot contribute to the dice.
178
178
  */
179
- function staticDice(ctx, info, ast, startIds, endIds, threshold = 75, includeCallees = false) {
179
+ function staticDice(ctx, info, ast, startIds, endIds, threshold = 75, includeCallees = false, gas) {
180
180
  (0, assert_1.guard)(startIds.length > 0 && endIds.length > 0, 'must have at least one start and one end id for dicing');
181
- const backward = staticSlice({ ctx, info, ast, ids: endIds, direction: slice_direction_1.SliceDirection.Backward, threshold, includeCallees });
181
+ const backward = staticSlice({ ctx, info, ast, ids: endIds, direction: slice_direction_1.SliceDirection.Backward, threshold, includeCallees, gas });
182
182
  // reduce to backward result and invert edges in one pass; original info kept for sliceForCall
183
183
  const invertedReduced = df_helper_1.Dataflow.reduceAndInvertGraph(info.graph, backward.result, ctx.env.makeCleanEnv());
184
- const forward = staticSlice({ ctx, info, ast, ids: startIds, direction: slice_direction_1.SliceDirection.Backward, threshold, sliceGraph: invertedReduced });
184
+ const forward = staticSlice({ ctx, info, ast, ids: startIds, direction: slice_direction_1.SliceDirection.Backward, threshold, sliceGraph: invertedReduced, gas });
185
185
  // explicit intersection handles seed nodes that landed outside the reduced graph
186
186
  const result = new Set();
187
187
  for (const id of forward.result) {
@@ -193,7 +193,13 @@ function staticDice(ctx, info, ast, startIds, endIds, threshold = 75, includeCal
193
193
  timesHitThreshold: forward.timesHitThreshold + backward.timesHitThreshold,
194
194
  result,
195
195
  slicedFor: [...startIds, ...endIds],
196
- ...(forward.stoppedEarly || backward.stoppedEarly ? { stoppedEarly: true } : {})
196
+ ...(forward.stoppedEarly || backward.stoppedEarly ? {
197
+ stoppedEarly: true,
198
+ progress: {
199
+ visited: (forward.progress?.visited ?? 0) + (backward.progress?.visited ?? 0),
200
+ frontier: (forward.progress?.frontier ?? 0) + (backward.progress?.frontier ?? 0)
201
+ }
202
+ } : {})
197
203
  };
198
204
  }
199
205
  function extendSlices(results, ast) {
@@ -19,6 +19,8 @@ export declare class VisitingQueue {
19
19
  private readonly gas?;
20
20
  private stoppedEarly;
21
21
  private untilGasCheck;
22
+ /** entries dequeued, see {@link SliceProgress} */
23
+ private visited;
22
24
  constructor(threshold: number, cache?: Map<Fingerprint, Set<NodeId>>, isGraphVertex?: (id: NodeId) => boolean, gas?: ReadOnlyFlowrAnalyzerGasContext);
23
25
  /**
24
26
  * Adds a node to the queue if it has not been seen before.
@@ -38,5 +40,5 @@ export declare class VisitingQueue {
38
40
  private outOfGas;
39
41
  hasId(id: NodeId): boolean;
40
42
  memoizeCallTargets(id: NodeId, targets: () => Set<DataflowGraphVertexInfo>): Set<DataflowGraphVertexInfo>;
41
- status(): Readonly<Pick<SliceResult, 'timesHitThreshold' | 'result' | 'stoppedEarly'>>;
43
+ status(): Readonly<Pick<SliceResult, 'timesHitThreshold' | 'result' | 'stoppedEarly' | 'progress'>>;
42
44
  }
@@ -24,6 +24,8 @@ class VisitingQueue {
24
24
  gas;
25
25
  stoppedEarly = false;
26
26
  untilGasCheck = 0;
27
+ /** entries dequeued, see {@link SliceProgress} */
28
+ visited = 0;
27
29
  constructor(threshold, cache, isGraphVertex, gas) {
28
30
  this.threshold = threshold;
29
31
  this.cache = cache;
@@ -64,6 +66,7 @@ class VisitingQueue {
64
66
  }
65
67
  }
66
68
  next() {
69
+ this.visited++;
67
70
  return this.queue.pop();
68
71
  }
69
72
  /** Whether there is anything left to visit, which the traversal is out of gas for as soon as it is exhausted. */
@@ -98,7 +101,7 @@ class VisitingQueue {
98
101
  return {
99
102
  timesHitThreshold: this.timesHitThreshold,
100
103
  result: new Set([...this.seen.values(), ...this.seenByCache]),
101
- ...(this.stoppedEarly ? { stoppedEarly: true } : {})
104
+ ...(this.stoppedEarly ? { stoppedEarly: true, progress: { visited: this.visited, frontier: this.queue.length } } : {})
102
105
  };
103
106
  }
104
107
  }
package/util/version.js CHANGED
@@ -42,7 +42,7 @@ const assert_1 = require("./assert");
42
42
  const sigdb_download_1 = require("../project/sigdb/sigdb-download");
43
43
  const doc_files_1 = require("../documentation/doc-util/doc-files");
44
44
  // this is automatically replaced with the current version by release-it
45
- const version = '2.13.12';
45
+ const version = '2.13.13';
46
46
  // this is automatically replaced with the release date by release-it (regex-bumper, see package.json)
47
47
  const versionDate = '2026-07-15T07:13:44Z';
48
48
  /**