@valerypopoff/rivet2-core 2.0.7 → 2.0.9

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.
Files changed (63) hide show
  1. package/dist/cjs/bundle.cjs +1757 -789
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/api/createProcessor.js +9 -2
  4. package/dist/esm/api/streaming.js +1 -0
  5. package/dist/esm/exports.js +1 -0
  6. package/dist/esm/model/DebuggerTransportSentinel.js +78 -0
  7. package/dist/esm/model/GraphAbortReasons.js +69 -0
  8. package/dist/esm/model/GraphBoundaryCache.js +92 -0
  9. package/dist/esm/model/GraphPreprocessor.js +212 -32
  10. package/dist/esm/model/GraphProcessor.js +493 -172
  11. package/dist/esm/model/NodeExclusionPolicy.js +67 -0
  12. package/dist/esm/model/NodeExecutionPlanner.js +66 -22
  13. package/dist/esm/model/NodeImpl.js +6 -4
  14. package/dist/esm/model/ProcessContextBuilder.js +2 -17
  15. package/dist/esm/model/RecordingPlayer.js +27 -7
  16. package/dist/esm/model/SplitRunProcessor.js +48 -9
  17. package/dist/esm/model/SubprocessorBridge.js +30 -23
  18. package/dist/esm/model/chat-v2/chatV2Outputs.js +183 -0
  19. package/dist/esm/model/chat-v2/chatV2Pipeline.js +30 -212
  20. package/dist/esm/model/nodes/CodeNewNode.js +1 -1
  21. package/dist/esm/model/nodes/CodeNode.js +1 -1
  22. package/dist/esm/model/nodes/GetGlobalNode.js +14 -4
  23. package/dist/esm/model/nodes/GraphOutputNode.js +31 -2
  24. package/dist/esm/model/nodes/HttpCallNode.js +20 -18
  25. package/dist/esm/model/nodes/LoopUntilNode.js +18 -45
  26. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +24 -63
  27. package/dist/esm/model/nodes/SetGlobalNode.js +2 -1
  28. package/dist/esm/model/nodes/SubGraphNode.js +22 -63
  29. package/dist/esm/model/nodes/codeNodeErrorDiagnostics.js +2 -3
  30. package/dist/esm/recording/ExecutionRecorder.js +19 -6
  31. package/dist/esm/utils/emitDetached.js +2 -2
  32. package/dist/esm/utils/interpolation.js +41 -1
  33. package/dist/esm/utils/serialization/serialization.js +6 -5
  34. package/dist/esm/utils/serialization/serializationHelpers.js +2 -2
  35. package/dist/esm/utils/serialization/serializationInput.js +48 -0
  36. package/dist/esm/utils/serialization/serializationUtils.js +2 -33
  37. package/dist/esm/utils/serialization/serialization_v2.js +8 -8
  38. package/dist/types/api/createProcessor.d.ts +9 -2
  39. package/dist/types/api/streaming.d.ts +1 -0
  40. package/dist/types/exports.d.ts +1 -0
  41. package/dist/types/model/DebuggerTransportSentinel.d.ts +21 -0
  42. package/dist/types/model/EditorDefinition.d.ts +2 -0
  43. package/dist/types/model/ExecutorProtocol.d.ts +5 -0
  44. package/dist/types/model/GraphAbortReasons.d.ts +23 -0
  45. package/dist/types/model/GraphBoundaryCache.d.ts +27 -0
  46. package/dist/types/model/GraphPreprocessor.d.ts +39 -3
  47. package/dist/types/model/GraphProcessor.d.ts +20 -1
  48. package/dist/types/model/NodeExclusionPolicy.d.ts +21 -0
  49. package/dist/types/model/NodeExecutionPlanner.d.ts +3 -8
  50. package/dist/types/model/NodeImpl.d.ts +10 -5
  51. package/dist/types/model/Nodes.d.ts +2 -2
  52. package/dist/types/model/ProcessContext.d.ts +3 -0
  53. package/dist/types/model/ProcessContextBuilder.d.ts +4 -20
  54. package/dist/types/model/SplitRunProcessor.d.ts +8 -3
  55. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +29 -0
  56. package/dist/types/model/nodes/LoopUntilNode.d.ts +5 -4
  57. package/dist/types/model/nodes/ReferencedGraphAliasNode.d.ts +5 -4
  58. package/dist/types/model/nodes/SubGraphNode.d.ts +6 -5
  59. package/dist/types/model/nodes/codeNodeErrorDiagnostics.d.ts +1 -2
  60. package/dist/types/recording/RecordedEvents.d.ts +4 -0
  61. package/dist/types/utils/emitDetached.d.ts +2 -2
  62. package/dist/types/utils/serialization/serializationInput.d.ts +7 -0
  63. package/package.json +1 -1
@@ -1,25 +1,45 @@
1
- import { getScalarTypeOf, } from './DataValue.js';
2
- import { IF_PORT, } from './NodeBase.js';
1
+ import {} from './DataValue.js';
2
+ import {} from './NodeBase.js';
3
3
  import PQueue from '../utils/pQueueCompat.js';
4
4
  import { getError } from '../utils/errors.js';
5
5
  import Emittery from 'emittery';
6
- import { entries } from '../utils/typeSafety.js';
7
6
  import {} from './Project.js';
8
7
  import { nanoid } from 'nanoid/non-secure';
9
8
  import { coerceTypeOptional } from '../utils/coerceType.js';
10
9
  import { getPluginConfig } from '../utils/index.js';
11
- import { preprocessGraphState } from './GraphPreprocessor.js';
10
+ import { isGraphExecutionPlan, preprocessGraphState, toReusableGraphExecutionPlan, } from './GraphPreprocessor.js';
11
+ import { getGraphBoundary, } from './GraphBoundaryCache.js';
12
12
  import { replayExecutionRecording } from './RecordingPlayer.js';
13
13
  import { didLoopControllerBreak, LOOP_NOT_BROKEN_SENTINEL } from './loopControllerBreak.js';
14
14
  import { buildNodeProcessContext } from './ProcessContextBuilder.js';
15
15
  import { processSplitRunNode } from './SplitRunProcessor.js';
16
16
  import { getInputNodesTo, getMissingRequiredInputs, getOutputNodesFrom, getStartNodes, getWaitingForInputNode, hasErroredInputNode, } from './NodeExecutionPlanner.js';
17
17
  import { wireSubprocessorEvents, wireSubprocessorLifecycle } from './SubprocessorBridge.js';
18
+ import { createGraphAbortError, createGraphAbortErrorFromSignal, createGraphAbortReason, getAbortSignalReason, getGraphAbortReasonFromError, getGraphAbortReasonFromSignal, isAbortLikeError, isRaceLoserGraphAbortReason, isSuccessfulNonRaceGraphAbortReason, RACE_LOSER_EXCLUSION_REASON, SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON, } from './GraphAbortReasons.js';
18
19
  import { emitDetached } from '../utils/emitDetached.js';
20
+ import { createExcludedNodeOutputs, getControlFlowExclusionDecision, getMissingRequiredInputExclusion, } from './NodeExclusionPolicy.js';
19
21
  // eslint-disable-next-line import/no-cycle -- There has to be a cycle because CodeRunner needs to import the entirety of Rivet
20
22
  import { IsomorphicCodeRunner } from '../integrations/CodeRunner.js';
21
23
  const DEFAULT_NODE_CONCURRENCY = 8;
22
24
  export const DEFAULT_SPLIT_RUN_CONCURRENCY = 4;
25
+ const DEFAULT_ISOMORPHIC_CODE_RUNNER = new IsomorphicCodeRunner();
26
+ const FAST_ACYCLIC_UNSUPPORTED_NODE_TYPES = new Set([
27
+ 'loopController',
28
+ 'loopUntil',
29
+ 'raceInputs',
30
+ 'userInput',
31
+ 'waitForEvent',
32
+ ]);
33
+ function getMonotonicTimeMs() {
34
+ return globalThis.performance?.now?.() ?? Date.now();
35
+ }
36
+ function withOptionalDuration(payload, durationMs, splitRunDurationMs) {
37
+ return {
38
+ ...payload,
39
+ ...(durationMs === undefined ? {} : { durationMs }),
40
+ ...(splitRunDurationMs === undefined ? {} : { splitRunDurationMs }),
41
+ };
42
+ }
23
43
  function normalizeConcurrencyValue(value, fallback) {
24
44
  return typeof value === 'number' && Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallback;
25
45
  }
@@ -29,6 +49,21 @@ function resolveGraphProcessorConcurrency(concurrency) {
29
49
  splitRunConcurrency: normalizeConcurrencyValue(concurrency?.splitRunConcurrency, DEFAULT_SPLIT_RUN_CONCURRENCY),
30
50
  };
31
51
  }
52
+ function resolveProcessorGraph(project, graphId) {
53
+ if (graphId) {
54
+ return project.graphs[graphId];
55
+ }
56
+ return project.metadata.mainGraphId ? project.graphs[project.metadata.mainGraphId] : undefined;
57
+ }
58
+ function replaceRecordContents(target, source) {
59
+ if (target === source) {
60
+ return;
61
+ }
62
+ for (const key of Object.keys(target)) {
63
+ delete target[key];
64
+ }
65
+ Object.assign(target, source);
66
+ }
32
67
  export class GraphProcessor {
33
68
  // Per-instance state
34
69
  #graph;
@@ -45,6 +80,12 @@ export class GraphProcessor {
45
80
  #parent;
46
81
  #registry;
47
82
  #concurrency;
83
+ #executionPlanCacheMode;
84
+ #runtimeCache;
85
+ #cacheLoadedProjects;
86
+ #scheduler;
87
+ #captureNodeTimings;
88
+ #useSeededExecutionPlanOnNextRun = false;
48
89
  id = nanoid();
49
90
  #includeTrace = true;
50
91
  executor;
@@ -81,13 +122,15 @@ export class GraphProcessor {
81
122
  #aborted = false;
82
123
  #abortSuccessfully = false;
83
124
  #abortError = undefined;
125
+ #successfulAbortTerminalProcessIds = undefined;
84
126
  #totalCost = 0;
85
127
  #ignoreNodes = undefined;
86
128
  #hasPreloadedData = false;
87
129
  #loadedProjects = undefined;
88
130
  #definitions = undefined;
89
131
  #scc = undefined;
90
- // @ts-expect-error
132
+ #graphExecutionPlan;
133
+ #nodeProcessContextBase = undefined;
91
134
  #nodesNotInCycle = undefined;
92
135
  #nodeAbortControllers = new Map();
93
136
  #graphInputNodeValues = {};
@@ -98,13 +141,18 @@ export class GraphProcessor {
98
141
  get isRunning() {
99
142
  return this.#running;
100
143
  }
144
+ #startNodeTiming() {
145
+ return this.#captureNodeTimings ? getMonotonicTimeMs() : undefined;
146
+ }
147
+ #finishNodeTiming(start) {
148
+ if (start == null) {
149
+ return undefined;
150
+ }
151
+ return Math.max(0, getMonotonicTimeMs() - start);
152
+ }
101
153
  constructor(project, graphId, registry, includeTrace, options) {
102
154
  this.#project = project;
103
- const graph = graphId
104
- ? project.graphs[graphId]
105
- : project.metadata.mainGraphId
106
- ? project.graphs[project.metadata.mainGraphId]
107
- : undefined;
155
+ const graph = resolveProcessorGraph(project, graphId);
108
156
  if (!graph) {
109
157
  throw new Error(`Graph ${graphId} not found in project`);
110
158
  }
@@ -115,26 +163,94 @@ export class GraphProcessor {
115
163
  this.#nodesById = {};
116
164
  this.#registry = registry;
117
165
  this.#concurrency = resolveGraphProcessorConcurrency(options?.concurrency);
166
+ this.#executionPlanCacheMode = options?.executionPlanCacheMode ?? 'all';
167
+ this.#runtimeCache = options?.runtimeCache;
168
+ this.#cacheLoadedProjects = options?.cacheLoadedProjects ?? false;
169
+ this.#scheduler = options?.scheduler ?? 'compatible';
170
+ this.#captureNodeTimings = options?.captureNodeTimings ?? false;
118
171
  this.#emitter.bindMethods(this, ['on', 'off', 'once', 'onAny', 'offAny']);
119
172
  this.setExternalFunction('echo', async (value) => ({ type: 'any', value }));
120
173
  this.#emitter.on('globalSet', ({ id, value }) => {
121
174
  emitDetached(this.#emitter, `globalSet:${id}`, value);
122
175
  });
176
+ if (options?.initialExecutionPlan) {
177
+ this.#applyPreprocessedGraph(options.initialExecutionPlan, { recreateNodeInstances: true });
178
+ this.#useSeededExecutionPlanOnNextRun = true;
179
+ }
123
180
  }
124
181
  #preprocessGraph() {
182
+ const runtimeCache = this.#canUseRuntimeExecutionPlanCache() ? this.#runtimeCache : undefined;
183
+ const shouldUseRuntimeCache = runtimeCache != null;
184
+ const cachedPlan = runtimeCache?.executionPlans?.get(this.#graph);
185
+ if (cachedPlan) {
186
+ this.#applyPreprocessedGraph(cachedPlan, { recreateNodeInstances: true });
187
+ return;
188
+ }
125
189
  const preprocessedGraph = preprocessGraphState({
126
190
  graph: this.#graph,
127
191
  loadedProjects: this.#loadedProjects,
128
192
  project: this.#project,
129
193
  registry: this.#registry,
130
194
  warnOnInvalidGraph: this.warnOnInvalidGraph,
195
+ buildExecutionPlan: shouldUseRuntimeCache,
196
+ definitionContext: this.#runtimeCache
197
+ ? {
198
+ getGraphBoundary: (project, graphId) => this.#getGraphBoundary(project, graphId),
199
+ }
200
+ : undefined,
131
201
  });
132
- Object.assign(this.#nodeInstances, preprocessedGraph.nodeInstances);
133
- Object.assign(this.#nodesById, preprocessedGraph.nodesById);
134
- Object.assign(this.#connections, preprocessedGraph.connections);
202
+ if (shouldUseRuntimeCache && isGraphExecutionPlan(preprocessedGraph)) {
203
+ runtimeCache.executionPlans ??= new WeakMap();
204
+ runtimeCache.executionPlans.set(this.#graph, toReusableGraphExecutionPlan(preprocessedGraph));
205
+ }
206
+ this.#applyPreprocessedGraph(preprocessedGraph);
207
+ }
208
+ #canUseRuntimeExecutionPlanCache() {
209
+ return this.#canUseRuntimeExecutionPlanCacheFor(this.#project, this.#isSubProcessor);
210
+ }
211
+ #canUseRuntimeExecutionPlanCacheFor(project, isSubProcessor) {
212
+ if (this.warnOnInvalidGraph || this.#runtimeCache == null) {
213
+ return false;
214
+ }
215
+ if (this.#executionPlanCacheMode === 'subprocessors' && !isSubProcessor) {
216
+ return false;
217
+ }
218
+ if (!this.#cacheLoadedProjects && (project.references?.length ?? 0) > 0) {
219
+ return false;
220
+ }
221
+ return true;
222
+ }
223
+ #getGraphBoundary(project, graphId) {
224
+ if (!this.#runtimeCache) {
225
+ return getGraphBoundary(project, graphId);
226
+ }
227
+ this.#runtimeCache.graphBoundaries ??= new WeakMap();
228
+ return getGraphBoundary(project, graphId, this.#runtimeCache.graphBoundaries);
229
+ }
230
+ #applyPreprocessedGraph(preprocessedGraph, options = {}) {
231
+ const nodeInstances = options.recreateNodeInstances || !('nodeInstances' in preprocessedGraph)
232
+ ? this.#createNodeInstances(isGraphExecutionPlan(preprocessedGraph) ? preprocessedGraph.graphNodes : this.#graph.nodes)
233
+ : preprocessedGraph.nodeInstances;
234
+ replaceRecordContents(this.#nodeInstances, nodeInstances);
235
+ replaceRecordContents(this.#nodesById, preprocessedGraph.nodesById);
236
+ replaceRecordContents(this.#connections, preprocessedGraph.connections);
135
237
  this.#definitions = preprocessedGraph.definitions;
136
238
  this.#scc = preprocessedGraph.stronglyConnectedComponents;
137
239
  this.#nodesNotInCycle = preprocessedGraph.nodesNotInCycle;
240
+ this.#graphExecutionPlan = isGraphExecutionPlan(preprocessedGraph) ? preprocessedGraph : undefined;
241
+ }
242
+ #seededExecutionPlanForNextRun() {
243
+ if (!this.#useSeededExecutionPlanOnNextRun || this.warnOnInvalidGraph) {
244
+ return undefined;
245
+ }
246
+ return this.#graphExecutionPlan;
247
+ }
248
+ #createNodeInstances(nodes) {
249
+ const nodeInstances = {};
250
+ for (const node of nodes) {
251
+ nodeInstances[node.id] = this.#registry.createDynamicImpl(node);
252
+ }
253
+ return nodeInstances;
138
254
  }
139
255
  #emitTraceEvent(eventData) {
140
256
  if (this.#includeTrace) {
@@ -203,7 +319,9 @@ export class GraphProcessor {
203
319
  }
204
320
  this.#abortSuccessfully = successful;
205
321
  this.#abortError = error;
206
- this.#abortController.abort();
322
+ const abortReason = createGraphAbortReason(successful, error);
323
+ this.#abortController.abort(abortReason);
324
+ this.#abortActiveNodeControllers(abortReason);
207
325
  emitDetached(this.#emitter, 'graphAbort', this.#withExecution({ successful, error, graph: this.#graph }));
208
326
  if (!this.#isSubProcessor) {
209
327
  emitDetached(this.#emitter, 'abort', { successful, error });
@@ -300,7 +418,7 @@ export class GraphProcessor {
300
418
  return;
301
419
  }
302
420
  dependencyNodes.add(nodeId);
303
- const connections = this.#connections[nodeId] ?? [];
421
+ const connections = this.#graphExecutionPlan?.inputConnectionsByNode[nodeId] ?? this.#connections[nodeId] ?? [];
304
422
  for (const connection of connections) {
305
423
  if (connection.inputNodeId === nodeId) {
306
424
  this.#collectDependencyNodesDeep(connection.outputNodeId, dependencyNodes);
@@ -345,7 +463,10 @@ export class GraphProcessor {
345
463
  }
346
464
  this.#erroredNodes = new Map();
347
465
  this.#currentlyProcessing = new Set();
348
- this.#remainingNodes = new Set(this.#graph.nodes.map((n) => n.id));
466
+ const seededExecutionPlan = this.#seededExecutionPlanForNextRun();
467
+ this.#remainingNodes = new Set(seededExecutionPlan
468
+ ? seededExecutionPlan.nodeIds
469
+ : this.#graph.nodes.map((node) => node.id));
349
470
  this.#pendingUserInputs = {};
350
471
  this.#processingQueue = new PQueue({ concurrency: this.#concurrency.nodeConcurrency });
351
472
  this.#graphOutputs = {};
@@ -356,6 +477,7 @@ export class GraphProcessor {
356
477
  this.#attachedNodeData = new Map();
357
478
  this.#globals ??= new Map();
358
479
  this.#ignoreNodes = new Set();
480
+ this.#nodeProcessContextBase = undefined;
359
481
  this.#abortController = this.#newAbortController();
360
482
  this.#abortController.signal.addEventListener('abort', () => {
361
483
  this.#aborted = true;
@@ -363,8 +485,16 @@ export class GraphProcessor {
363
485
  this.#aborted = false;
364
486
  this.#abortError = undefined;
365
487
  this.#abortSuccessfully = false;
488
+ this.#successfulAbortTerminalProcessIds = new Set();
366
489
  this.#nodeAbortControllers = new Map();
367
- this.#loadedProjects = {};
490
+ this.#loadedProjects =
491
+ this.#cacheLoadedProjects && this.#runtimeCache?.loadedProjects ? { ...this.#runtimeCache.loadedProjects } : {};
492
+ // Referenced projects can be reloaded per run when loaded-project caching is disabled.
493
+ if (!this.#cacheLoadedProjects && (this.#project.references?.length ?? 0) > 0) {
494
+ if (this.#runtimeCache) {
495
+ this.#runtimeCache.graphBoundaries = undefined;
496
+ }
497
+ }
368
498
  this.#graphInputNodeValues = {};
369
499
  }
370
500
  /** Main function for running a graph. Runs a graph and returns the outputs from the output nodes of the graph. */
@@ -381,13 +511,23 @@ export class GraphProcessor {
381
511
  try {
382
512
  this.#initializeGraphRun(context, inputs, contextValues);
383
513
  await this.#loadProjectReferences();
384
- this.#preprocessGraph();
514
+ this.#prepareNodeProcessContextBase();
515
+ const shouldUseSeededExecutionPlan = this.#seededExecutionPlanForNextRun() != null;
516
+ this.#useSeededExecutionPlanOnNextRun = false;
517
+ if (!shouldUseSeededExecutionPlan) {
518
+ this.#preprocessGraph();
519
+ }
385
520
  await this.#emitGraphStart();
386
521
  await this.#emitPreloadedNodeResults();
387
522
  await this.#waitUntilUnpaused();
388
- await this.#queueStartNodes(getStartNodes(this.#executionState, this.#graph.nodes, this.runToNodeIds));
389
- await this.#processingQueue.onIdle();
390
- this.#markUnqueuedNodesIgnored();
523
+ if (this.#canUseFastAcyclicScheduler()) {
524
+ await this.#processFastAcyclicGraph();
525
+ }
526
+ else {
527
+ await this.#queueStartNodes(getStartNodes(this.#executionState, this.#graph.nodes, this.runToNodeIds));
528
+ await this.#processingQueue.onIdle();
529
+ this.#markUnqueuedNodesIgnored();
530
+ }
391
531
  await this.#throwIfGraphErrored();
392
532
  return await this.#finalizeGraphRun();
393
533
  }
@@ -419,6 +559,39 @@ export class GraphProcessor {
419
559
  this.#unsubscribeTokenizerError =
420
560
  typeof unsubscribeTokenizerError === 'function' ? unsubscribeTokenizerError : undefined;
421
561
  }
562
+ #prepareNodeProcessContextBase() {
563
+ this.#nodeProcessContextBase = {
564
+ ...this.#context,
565
+ abortGraph: (error) => {
566
+ void this.abort(error === undefined, error);
567
+ },
568
+ codeRunner: this.#context.codeRunner ?? DEFAULT_ISOMORPHIC_CODE_RUNNER,
569
+ contextValues: this.#contextValues,
570
+ executionCache: this.#executionCache,
571
+ executor: this.executor ?? 'nodejs',
572
+ getGlobal: (id) => this.#globals.get(id),
573
+ getGraphBoundary: (project, graphId) => this.#getGraphBoundary(project, graphId),
574
+ graphInputNodeValues: this.#graphInputNodeValues,
575
+ graphInputs: this.#graphInputs,
576
+ graphOutputs: this.#graphOutputs,
577
+ project: this.#project,
578
+ raiseEvent: (event, data) => {
579
+ this.getRootProcessor().raiseEvent(event, data);
580
+ },
581
+ referencedProjects: this.#loadedProjects,
582
+ tokenizer: this.#getTokenizer(),
583
+ trace: (message) => {
584
+ this.#emitTraceEvent(message);
585
+ },
586
+ waitForGlobal: async (id) => {
587
+ if (this.#globals.has(id)) {
588
+ return this.#globals.get(id);
589
+ }
590
+ await this.getRootProcessor().#emitter.once(`globalSet:${id}`);
591
+ return this.#globals.get(id);
592
+ },
593
+ };
594
+ }
422
595
  #cleanupTokenizerErrorListener() {
423
596
  const unsubscribeTokenizerError = this.#unsubscribeTokenizerError;
424
597
  this.#unsubscribeTokenizerError = undefined;
@@ -468,6 +641,90 @@ export class GraphProcessor {
468
641
  });
469
642
  }
470
643
  }
644
+ #canUseFastAcyclicScheduler() {
645
+ if (this.#scheduler !== 'fast-acyclic') {
646
+ return false;
647
+ }
648
+ if (this.#hasPreloadedData || this.runToNodeIds || this.slowMode || this.#includeTrace) {
649
+ return false;
650
+ }
651
+ if (this.#nodesNotInCycle.length !== this.#graph.nodes.length) {
652
+ return false;
653
+ }
654
+ if (this.#graph.connections.some((connection) => connection.inputNodeId === connection.outputNodeId)) {
655
+ return false;
656
+ }
657
+ return this.#graph.nodes.every((node) => {
658
+ if (node.isSplitRun) {
659
+ return false;
660
+ }
661
+ return !FAST_ACYCLIC_UNSUPPORTED_NODE_TYPES.has(node.type);
662
+ });
663
+ }
664
+ async #processFastAcyclicGraph() {
665
+ const remainingInputsByNode = new Map();
666
+ const readyNodes = [];
667
+ const queuedNodeIds = new Set();
668
+ for (const node of this.#graph.nodes) {
669
+ const inputNodeIds = new Set();
670
+ for (const inputNode of getInputNodesTo(this.#executionState, node)) {
671
+ inputNodeIds.add(inputNode.id);
672
+ }
673
+ const inputCount = inputNodeIds.size;
674
+ remainingInputsByNode.set(node.id, inputCount);
675
+ if (inputCount === 0) {
676
+ readyNodes.push(node);
677
+ queuedNodeIds.add(node.id);
678
+ }
679
+ }
680
+ await new Promise((resolve, reject) => {
681
+ let activeCount = 0;
682
+ let settled = false;
683
+ const queueReadyOutputs = (outputNodes) => {
684
+ for (const outputNode of outputNodes) {
685
+ const remainingInputs = (remainingInputsByNode.get(outputNode.id) ?? 0) - 1;
686
+ remainingInputsByNode.set(outputNode.id, remainingInputs);
687
+ if (remainingInputs <= 0 && !queuedNodeIds.has(outputNode.id)) {
688
+ readyNodes.push(outputNode);
689
+ queuedNodeIds.add(outputNode.id);
690
+ }
691
+ }
692
+ };
693
+ const settle = () => {
694
+ if (settled) {
695
+ return;
696
+ }
697
+ if (activeCount === 0 && readyNodes.length === 0) {
698
+ settled = true;
699
+ resolve();
700
+ }
701
+ };
702
+ const pump = () => {
703
+ if (settled) {
704
+ return;
705
+ }
706
+ while (activeCount < this.#concurrency.nodeConcurrency && readyNodes.length > 0) {
707
+ const node = readyNodes.shift();
708
+ activeCount += 1;
709
+ void this.#processNodeIfAllInputsAvailable(node, { queueOutputNodes: false })
710
+ .then(queueReadyOutputs)
711
+ .then(() => {
712
+ activeCount -= 1;
713
+ pump();
714
+ settle();
715
+ })
716
+ .catch((error) => {
717
+ if (!settled) {
718
+ settled = true;
719
+ reject(error);
720
+ }
721
+ });
722
+ }
723
+ settle();
724
+ };
725
+ pump();
726
+ });
727
+ }
471
728
  #markUnqueuedNodesIgnored() {
472
729
  if (!this.runToNodeIds) {
473
730
  return;
@@ -527,6 +784,10 @@ export class GraphProcessor {
527
784
  }
528
785
  async #loadProjectReferences() {
529
786
  if ((this.#project.references?.length ?? 0) > 0) {
787
+ if (this.#cacheLoadedProjects && this.#runtimeCache?.loadedProjects) {
788
+ this.#loadedProjects = { ...this.#runtimeCache.loadedProjects };
789
+ return;
790
+ }
530
791
  if (!this.#context.projectReferenceLoader) {
531
792
  throw new Error('Project references are set, but no projectReferenceLoader is set in the context. Since this project uses project references, you must provide a projectReferenceLoader in the context.');
532
793
  }
@@ -545,6 +806,9 @@ export class GraphProcessor {
545
806
  for (const reference of this.#project.references) {
546
807
  await loadProject(reference);
547
808
  }
809
+ if (this.#cacheLoadedProjects && this.#runtimeCache) {
810
+ this.#runtimeCache.loadedProjects = { ...this.#loadedProjects };
811
+ }
548
812
  }
549
813
  }
550
814
  /** Returns true if any input node has errored. Optionally emits a trace event. */
@@ -561,10 +825,6 @@ export class GraphProcessor {
561
825
  this.#totalCost += coerceTypeOptional(output['cost'], 'number') ?? 0;
562
826
  }
563
827
  }
564
- /** Checks if a data value represents a control-flow-excluded signal. */
565
- #isControlFlowExcluded(value) {
566
- return value != null && getScalarTypeOf(value.type) === 'control-flow-excluded';
567
- }
568
828
  async #fetchNodeDataAndProcessNode(node) {
569
829
  if (this.#currentlyProcessing.has(node.id) || this.#queuedNodes.has(node.id)) {
570
830
  return;
@@ -602,39 +862,44 @@ export class GraphProcessor {
602
862
  await this.#processNodeIfAllInputsAvailable(node);
603
863
  }
604
864
  /** If all inputs are present, all conditions met, processes the node. */
605
- async #processNodeIfAllInputsAvailable(node) {
865
+ async #processNodeIfAllInputsAvailable(node, options = {}) {
866
+ const { queueOutputNodes = true } = options;
606
867
  const builtInNode = node;
607
868
  const inputNodes = getInputNodesTo(this.#executionState, node);
608
869
  if (this.#shouldSkipNodeProcessing(node, inputNodes)) {
609
- return;
870
+ return [];
610
871
  }
611
872
  const attachedData = this.#getAttachedDataTo(node);
612
873
  if (this.#shouldSkipCompletedRaceNode(node, attachedData)) {
613
- return;
874
+ return [];
614
875
  }
615
876
  const inputValues = this.#getInputValuesForNode(node);
616
- if (this.#excludedDueToControlFlow(node, inputValues, nanoid(), LOOP_NOT_BROKEN_SENTINEL)) {
877
+ const loopExclusion = this.#excludedDueToControlFlow(node, inputValues, nanoid(), LOOP_NOT_BROKEN_SENTINEL, { queueOutputNodes });
878
+ if (loopExclusion) {
617
879
  this.#emitTraceEvent(`Node ${node.title} is excluded due to control flow`);
618
- return;
880
+ return loopExclusion === true ? [] : loopExclusion;
619
881
  }
620
882
  const waitingForInputNode = getWaitingForInputNode(this.#executionState, node, inputNodes, inputValues);
621
883
  if (waitingForInputNode) {
622
884
  this.#emitTraceEvent(`Node ${node.title} is waiting for input node ${waitingForInputNode}`);
623
- return;
885
+ return [];
624
886
  }
625
- if (this.#excludedDueToControlFlow(node, inputValues, nanoid())) {
887
+ const exclusion = this.#excludedDueToControlFlow(node, inputValues, nanoid(), undefined, {
888
+ queueOutputNodes,
889
+ });
890
+ if (exclusion) {
626
891
  this.#emitTraceEvent(`Node ${node.title} is excluded due to control flow`);
627
- return;
892
+ return exclusion === true ? [] : exclusion;
628
893
  }
629
894
  const missingRequiredInputs = this.#getMissingRequiredInputs(node);
630
895
  if (missingRequiredInputs.length > 0) {
631
- this.#excludeNodeWithMissingRequiredInputs(node, inputValues, missingRequiredInputs);
632
- return;
896
+ return this.#excludeNodeWithMissingRequiredInputs(node, inputValues, missingRequiredInputs, { queueOutputNodes });
633
897
  }
634
898
  if (this.#beginNodeProcessing(node, attachedData) === false) {
635
- return;
899
+ return [];
636
900
  }
637
- const processId = await this.#processNode(node);
901
+ const processResult = await this.#processNode(node);
902
+ const { processId } = processResult;
638
903
  if (this.slowMode) {
639
904
  await new Promise((resolve) => setTimeout(resolve, 250));
640
905
  }
@@ -645,11 +910,16 @@ export class GraphProcessor {
645
910
  const outputNodes = getOutputNodesFrom(this.#executionState, node);
646
911
  this.#handleLoopControllerPostProcess(node, attachedData);
647
912
  this.#handleCompletedRace(node);
648
- if (!this.#assignChildLoopInfo(node, builtInNode, attachedData, processId)) {
649
- return;
913
+ const childLoopInfoError = this.#assignChildLoopInfo(node, builtInNode, attachedData);
914
+ if (childLoopInfoError) {
915
+ await this.#nodeErrored(node, childLoopInfoError, processId);
916
+ return [];
650
917
  }
651
918
  this.#propagateAttachedDataToOutputNodes(node, attachedData, outputNodes.connectionsToNodes);
652
- this.#queueOutputNodes(node, outputNodes.nodes);
919
+ if (queueOutputNodes && processResult.shouldQueueOutputNodes) {
920
+ this.#queueOutputNodes(node, outputNodes.nodes);
921
+ }
922
+ return processResult.shouldQueueOutputNodes ? outputNodes.nodes : [];
653
923
  }
654
924
  #shouldSkipNodeProcessing(node, inputNodes) {
655
925
  if (this.#ignoreNodes.has(node.id)) {
@@ -680,11 +950,11 @@ export class GraphProcessor {
680
950
  }
681
951
  return false;
682
952
  }
683
- #excludeNodeWithMissingRequiredInputs(node, inputValues, missingRequiredInputs) {
684
- const missingInputNames = missingRequiredInputs.map((input) => input.title || input.id).join(', ');
953
+ #excludeNodeWithMissingRequiredInputs(node, inputValues, missingRequiredInputs, options = {}) {
954
+ const exclusion = getMissingRequiredInputExclusion(node, missingRequiredInputs);
685
955
  const processId = nanoid();
686
- this.#emitTraceEvent(`Excluding node ${node.title} because required inputs are not connected: ${missingInputNames}`);
687
- this.#excludeNode(node, processId, inputValues, 'missing required input');
956
+ this.#emitTraceEvent(exclusion.traceMessage);
957
+ return this.#excludeNode(node, processId, inputValues, exclusion.reason, options);
688
958
  }
689
959
  #beginNodeProcessing(node, attachedData) {
690
960
  if (this.#shouldSkipCompletedRaceNode(node, attachedData)) {
@@ -733,29 +1003,24 @@ export class GraphProcessor {
733
1003
  if (node.type !== 'raceInputs') {
734
1004
  return;
735
1005
  }
736
- const allNodesForRace = [...this.#attachedNodeData.entries()].filter(([, { races }]) => races?.raceIds.includes(`race-${node.id}`));
737
- for (const [nodeId] of allNodesForRace) {
738
- for (const [key, abortController] of this.#nodeAbortControllers.entries()) {
739
- if (key.startsWith(nodeId)) {
740
- this.#emitTraceEvent(`Aborting node ${nodeId} because other race branch won`);
741
- abortController.abort();
742
- }
743
- }
744
- for (const [, nodeAttachedData] of [...this.#attachedNodeData.entries()]) {
745
- if (nodeAttachedData.races?.raceIds.includes(`race-${node.id}`)) {
746
- nodeAttachedData.races.completed = true;
747
- }
1006
+ const raceId = `race-${node.id}`;
1007
+ const allNodesForRace = [...this.#attachedNodeData.entries()].filter(([, { races }]) => races?.raceIds.includes(raceId));
1008
+ for (const [, nodeAttachedData] of allNodesForRace) {
1009
+ if (nodeAttachedData.races?.raceIds.includes(raceId)) {
1010
+ nodeAttachedData.races.completed = true;
748
1011
  }
749
1012
  }
1013
+ for (const [nodeId] of allNodesForRace) {
1014
+ this.#abortNodeControllersForNode(nodeId, `Aborting node ${nodeId} because other race branch won`, createGraphAbortReason(true, RACE_LOSER_EXCLUSION_REASON));
1015
+ }
750
1016
  }
751
- #assignChildLoopInfo(node, builtInNode, attachedData, processId) {
1017
+ #assignChildLoopInfo(node, builtInNode, attachedData) {
752
1018
  if (builtInNode.type !== 'loopController') {
753
- return true;
1019
+ return undefined;
754
1020
  }
755
1021
  let childLoopInfo = attachedData.loopInfo;
756
1022
  if (childLoopInfo != null && childLoopInfo.loopControllerId !== builtInNode.id) {
757
- this.#nodeErrored(node, new Error('Nested loops are not supported'), processId);
758
- return false;
1023
+ return new Error('Nested loops are not supported');
759
1024
  }
760
1025
  childLoopInfo = {
761
1026
  propagate: (parent, connectionsFromParent) => {
@@ -769,7 +1034,7 @@ export class GraphProcessor {
769
1034
  iterationCount: (childLoopInfo?.iterationCount ?? 0) + 1,
770
1035
  };
771
1036
  attachedData.loopInfo = childLoopInfo;
772
- return true;
1037
+ return undefined;
773
1038
  }
774
1039
  #propagateAttachedDataToOutputNodes(node, attachedData, outputConnections) {
775
1040
  for (const { node: outputNode, connections: connectionsToOutputNode } of outputConnections) {
@@ -806,17 +1071,9 @@ export class GraphProcessor {
806
1071
  async #processNode(node) {
807
1072
  const processId = nanoid();
808
1073
  if (this.#abortController.signal.aborted) {
809
- this.#nodeErrored(node, new Error('Processing aborted'), processId);
810
- return processId;
811
- }
812
- const inputNodes = getInputNodesTo(this.#executionState, node);
813
- const erroredInputNodes = inputNodes.filter((inputNode) => this.#erroredNodes.has(inputNode.id));
814
- if (erroredInputNodes.length > 0) {
815
- const error = new Error(`Cannot process node ${node.title} (${node.id}) because it depends on errored nodes: ${erroredInputNodes
816
- .map((n) => `${n.title} (${n.id})`)
817
- .join(', ')}`);
818
- this.#nodeErrored(node, error, processId);
819
- return processId;
1074
+ await this.#nodeErrored(node, createGraphAbortErrorFromSignal(this.#abortController.signal), processId);
1075
+ this.#successfulAbortTerminalProcessIds.delete(processId);
1076
+ return { processId, shouldQueueOutputNodes: false };
820
1077
  }
821
1078
  if (node.isSplitRun) {
822
1079
  await this.#processSplitRunNode(node, processId);
@@ -824,22 +1081,30 @@ export class GraphProcessor {
824
1081
  else {
825
1082
  await this.#processNormalNode(node, processId);
826
1083
  }
827
- return processId;
1084
+ const successfulAbortTerminal = this.#successfulAbortTerminalProcessIds.delete(processId);
1085
+ return { processId, shouldQueueOutputNodes: !successfulAbortTerminal };
828
1086
  }
829
1087
  async #processSplitRunNode(node, processId) {
830
1088
  return processSplitRunNode(node, processId, {
831
1089
  getInputValues: (n) => this.#getInputValuesForNode(n),
832
- isExcludedDueToControlFlow: (n, inputs, pid) => this.#excludedDueToControlFlow(n, inputs, pid),
1090
+ isExcludedDueToControlFlow: (n, inputs, pid) => this.#excludedDueToControlFlow(n, inputs, pid) !== false,
833
1091
  processNodeWithInputData: (n, inputs, idx, pid, partial) => this.#processNodeWithInputData(n, inputs, idx, pid, partial),
834
1092
  splitRunConcurrency: this.#concurrency.splitRunConcurrency,
835
1093
  accumulateCost: (output) => this.#accumulateCost(output),
836
1094
  setNodeResults: (nodeId, outputs) => this.#nodeResults.set(nodeId, outputs),
837
1095
  markNodeVisited: (nodeId) => this.#visitedNodes.add(nodeId),
838
- nodeErrored: (n, err, pid) => this.#nodeErrored(n, err, pid),
1096
+ nodeErrored: (n, err, pid, durationMs, splitRunDurationMs) => this.#nodeErrored(n, err, pid, durationMs, splitRunDurationMs),
839
1097
  isAborted: () => this.#aborted,
1098
+ getAbortError: () => createGraphAbortErrorFromSignal(this.#abortController.signal),
840
1099
  emit: (event, data) => {
841
- emitDetached(this.#emitter, event, this.#withExecution(data));
1100
+ if (event === 'partialOutput') {
1101
+ emitDetached(this.#emitter, event, this.#withExecution(data));
1102
+ return;
1103
+ }
1104
+ return this.#emitter.emit(event, this.#withExecution(data));
842
1105
  },
1106
+ startNodeTiming: this.#captureNodeTimings ? () => this.#startNodeTiming() : undefined,
1107
+ finishNodeTiming: this.#captureNodeTimings ? (start) => this.#finishNodeTiming(start) : undefined,
843
1108
  });
844
1109
  }
845
1110
  async #processNormalNode(node, processId) {
@@ -850,6 +1115,7 @@ export class GraphProcessor {
850
1115
  // Use awaited emit (not emitDetached) so that listeners can yield to the
851
1116
  // macrotask queue, giving the browser a chance to repaint during execution.
852
1117
  await this.#emitter.emit('nodeStart', this.#withExecution({ node, inputs: inputValues, processId }));
1118
+ const timingStart = this.#startNodeTiming();
853
1119
  try {
854
1120
  const outputValues = await this.#processNodeWithInputData(node, inputValues, 0, processId, (node, partialOutputs, index) => {
855
1121
  emitDetached(this.#emitter, 'partialOutput', this.#withExecution({ node, outputs: partialOutputs, index, processId }));
@@ -857,17 +1123,50 @@ export class GraphProcessor {
857
1123
  this.#nodeResults.set(node.id, outputValues);
858
1124
  this.#visitedNodes.add(node.id);
859
1125
  this.#accumulateCost(outputValues);
860
- await this.#emitter.emit('nodeFinish', this.#withExecution({ node, outputs: outputValues, processId }));
1126
+ await this.#emitter.emit('nodeFinish', this.#withExecution(withOptionalDuration({
1127
+ node,
1128
+ outputs: outputValues,
1129
+ processId,
1130
+ }, this.#finishNodeTiming(timingStart))));
861
1131
  }
862
1132
  catch (error) {
863
- this.#nodeErrored(node, error, processId);
1133
+ await this.#nodeErrored(node, error, processId, this.#finishNodeTiming(timingStart));
864
1134
  }
865
1135
  }
866
- #nodeErrored(node, e, processId) {
1136
+ async #nodeErrored(node, e, processId, durationMs, splitRunDurationMs) {
867
1137
  const error = getError(e);
868
- emitDetached(this.#emitter, 'nodeError', this.#withExecution({ node, error, processId }));
869
- this.#emitTraceEvent(`Node ${node.title} (${node.id}-${processId}) errored: ${error.stack}`);
1138
+ const exclusionReason = this.#getErrorExclusionReason(node, error, processId);
1139
+ if (exclusionReason) {
1140
+ await this.#emitNodeExcluded(node, processId, this.#getInputValuesForNode(node), exclusionReason);
1141
+ this.#emitTraceEvent(`Node ${node.title} (${node.id}-${processId}) was excluded: ${exclusionReason}`);
1142
+ return;
1143
+ }
870
1144
  this.#erroredNodes.set(node.id, error);
1145
+ await this.#emitter.emit('nodeError', this.#withExecution(withOptionalDuration({ node, error, processId }, durationMs, splitRunDurationMs)));
1146
+ this.#emitTraceEvent(`Node ${node.title} (${node.id}-${processId}) errored: ${error.stack}`);
1147
+ }
1148
+ #getErrorExclusionReason(node, error, processId) {
1149
+ if (this.#getAttachedDataTo(node).races?.completed) {
1150
+ return RACE_LOSER_EXCLUSION_REASON;
1151
+ }
1152
+ const abortReason = getGraphAbortReasonFromError(error);
1153
+ if (isRaceLoserGraphAbortReason(abortReason)) {
1154
+ return RACE_LOSER_EXCLUSION_REASON;
1155
+ }
1156
+ if (isSuccessfulNonRaceGraphAbortReason(abortReason)) {
1157
+ this.#successfulAbortTerminalProcessIds.add(processId);
1158
+ return SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON;
1159
+ }
1160
+ if (this.#abortSuccessfully && isAbortLikeError(error)) {
1161
+ const exclusionReason = this.#abortError === RACE_LOSER_EXCLUSION_REASON
1162
+ ? RACE_LOSER_EXCLUSION_REASON
1163
+ : SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON;
1164
+ if (exclusionReason === SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON) {
1165
+ this.#successfulAbortTerminalProcessIds.add(processId);
1166
+ }
1167
+ return exclusionReason;
1168
+ }
1169
+ return undefined;
871
1170
  }
872
1171
  getRootProcessor() {
873
1172
  let processor = this;
@@ -888,26 +1187,89 @@ export class GraphProcessor {
888
1187
  emitDetached(this.#emitter, 'newAbortController', controller);
889
1188
  return controller;
890
1189
  }
1190
+ #registerNodeAbortController(nodeId, abortController) {
1191
+ const existingAbortControllers = this.#nodeAbortControllers.get(nodeId);
1192
+ if (!existingAbortControllers) {
1193
+ this.#nodeAbortControllers.set(nodeId, abortController);
1194
+ return;
1195
+ }
1196
+ if (existingAbortControllers instanceof Set) {
1197
+ existingAbortControllers.add(abortController);
1198
+ return;
1199
+ }
1200
+ if (existingAbortControllers === abortController) {
1201
+ return;
1202
+ }
1203
+ this.#nodeAbortControllers.set(nodeId, new Set([existingAbortControllers, abortController]));
1204
+ }
1205
+ #unregisterNodeAbortController(nodeId, abortController) {
1206
+ const existingAbortControllers = this.#nodeAbortControllers.get(nodeId);
1207
+ if (!existingAbortControllers) {
1208
+ return;
1209
+ }
1210
+ if (existingAbortControllers === abortController) {
1211
+ this.#nodeAbortControllers.delete(nodeId);
1212
+ return;
1213
+ }
1214
+ if (!(existingAbortControllers instanceof Set)) {
1215
+ return;
1216
+ }
1217
+ existingAbortControllers.delete(abortController);
1218
+ if (existingAbortControllers.size === 0) {
1219
+ this.#nodeAbortControllers.delete(nodeId);
1220
+ }
1221
+ else if (existingAbortControllers.size === 1) {
1222
+ this.#nodeAbortControllers.set(nodeId, existingAbortControllers.values().next().value);
1223
+ }
1224
+ }
1225
+ #abortNodeControllersForNode(nodeId, traceMessage, reason) {
1226
+ const abortControllerEntry = this.#nodeAbortControllers.get(nodeId);
1227
+ if (!abortControllerEntry) {
1228
+ return;
1229
+ }
1230
+ if (!(abortControllerEntry instanceof Set)) {
1231
+ if (traceMessage) {
1232
+ this.#emitTraceEvent(traceMessage);
1233
+ }
1234
+ abortControllerEntry.abort(reason);
1235
+ return;
1236
+ }
1237
+ for (const abortController of abortControllerEntry) {
1238
+ if (traceMessage) {
1239
+ this.#emitTraceEvent(traceMessage);
1240
+ }
1241
+ abortController.abort(reason);
1242
+ }
1243
+ }
1244
+ #abortActiveNodeControllers(reason) {
1245
+ for (const nodeId of [...this.#nodeAbortControllers.keys()]) {
1246
+ this.#abortNodeControllersForNode(nodeId, undefined, reason);
1247
+ }
1248
+ }
891
1249
  async #processNodeWithInputData(node, inputValues, index, processId, partialOutput) {
892
1250
  const instance = this.#nodeInstances[node.id];
893
1251
  const nodeAbortController = this.#newAbortController();
894
- const abortListener = () => {
895
- nodeAbortController.abort();
896
- };
897
- this.#nodeAbortControllers.set(`${node.id}-${processId}`, nodeAbortController);
898
- this.#abortController.signal.addEventListener('abort', abortListener);
1252
+ this.#registerNodeAbortController(node.id, nodeAbortController);
1253
+ if (this.#abortController.signal.aborted) {
1254
+ nodeAbortController.abort(getAbortSignalReason(this.#abortController.signal));
1255
+ }
899
1256
  const context = this.#createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput);
900
- await this.#waitUntilUnpaused();
901
1257
  let results;
902
1258
  try {
1259
+ await this.#waitUntilUnpaused();
903
1260
  results = await instance.process(inputValues, context);
904
1261
  }
905
1262
  finally {
906
- this.#nodeAbortControllers.delete(`${node.id}-${processId}`);
907
- this.#abortController.signal.removeEventListener('abort', abortListener);
1263
+ this.#unregisterNodeAbortController(node.id, nodeAbortController);
908
1264
  }
1265
+ const abortReason = getGraphAbortReasonFromSignal(nodeAbortController.signal);
909
1266
  if (nodeAbortController.signal.aborted) {
910
- throw new Error('Aborted');
1267
+ if (isSuccessfulNonRaceGraphAbortReason(abortReason)) {
1268
+ this.#successfulAbortTerminalProcessIds.add(processId);
1269
+ }
1270
+ else {
1271
+ throw createGraphAbortError(abortReason, 'Aborted');
1272
+ }
911
1273
  }
912
1274
  return results;
913
1275
  }
@@ -917,24 +1279,12 @@ export class GraphProcessor {
917
1279
  #createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput) {
918
1280
  const plugin = this.#registry.getPluginFor(node.type);
919
1281
  return buildNodeProcessContext({
920
- abortGraph: (error) => {
921
- void this.abort(error === undefined, error);
922
- },
923
1282
  attachedData: this.#getAttachedDataTo(node),
924
- codeRunner: this.#context.codeRunner ?? new IsomorphicCodeRunner(),
925
- context: this.#context,
926
- contextValues: this.#contextValues,
1283
+ base: this.#nodeProcessContextBase,
927
1284
  createSubProcessor: (subGraphId, options = {}) => this.#createSubProcessor(node, index, processId, subGraphId, options),
928
1285
  execution: this.#buildExecutionMetadata(),
929
- executionCache: this.#executionCache,
930
- executor: this.executor ?? 'nodejs',
931
1286
  externalFunctions: this.#externalFunctions,
932
- getGlobal: (id) => this.#globals.get(id),
933
1287
  getPluginConfig: (name) => getPluginConfig(plugin, this.#context.settings, name),
934
- graphInputNodeValues: this.#graphInputNodeValues,
935
- graphInputs: this.#graphInputs,
936
- graphOutputs: this.#graphOutputs,
937
- loadedProjects: this.#loadedProjects,
938
1288
  node,
939
1289
  nodeAbortController,
940
1290
  onPartialOutputs: (partialOutputs) => {
@@ -942,23 +1292,15 @@ export class GraphProcessor {
942
1292
  this.#emitGraphPartialOutputIfNeeded(node, partialOutputs);
943
1293
  },
944
1294
  processId,
945
- project: this.#project,
946
- raiseEvent: (event, data) => {
947
- this.getRootProcessor().raiseEvent(event, data);
948
- },
949
1295
  requestUserInput: async (inputStrings, renderingType) => this.#requestUserInput(node, inputStrings, inputValues, renderingType, processId),
950
1296
  setGlobal: (id, value) => {
951
1297
  this.#globals.set(id, value);
952
1298
  emitDetached(this.#emitter, 'globalSet', this.#withExecution({ id, value, processId }));
953
1299
  },
954
- tokenizer: this.#getTokenizer(),
955
- trace: (message) => {
956
- this.#emitTraceEvent(message);
957
- },
958
1300
  waitEvent: async (event) => {
959
1301
  return new Promise((resolve, reject) => {
960
1302
  const abortListener = () => {
961
- reject(new Error('Process aborted'));
1303
+ reject(createGraphAbortErrorFromSignal(nodeAbortController.signal, 'Process aborted'));
962
1304
  };
963
1305
  this.#emitter
964
1306
  .once(`userEvent:${event}`)
@@ -970,13 +1312,6 @@ export class GraphProcessor {
970
1312
  nodeAbortController.signal.addEventListener('abort', abortListener, { once: true });
971
1313
  });
972
1314
  },
973
- waitForGlobal: async (id) => {
974
- if (this.#globals.has(id)) {
975
- return this.#globals.get(id);
976
- }
977
- await this.getRootProcessor().#emitter.once(`globalSet:${id}`);
978
- return this.#globals.get(id);
979
- },
980
1315
  });
981
1316
  }
982
1317
  #emitGraphPartialOutputIfNeeded(node, partialOutputs) {
@@ -998,8 +1333,19 @@ export class GraphProcessor {
998
1333
  });
999
1334
  }
1000
1335
  #createSubProcessor(node, index, processId, subGraphId, { signal, project } = {}) {
1001
- const processor = new GraphProcessor(project ?? this.#project, subGraphId, this.#registry, this.#includeTrace, {
1336
+ const subprocessorProject = project ?? this.#project;
1337
+ const subprocessorGraph = resolveProcessorGraph(subprocessorProject, subGraphId);
1338
+ const initialExecutionPlan = subprocessorGraph && this.#canUseRuntimeExecutionPlanCacheFor(subprocessorProject, true)
1339
+ ? this.#runtimeCache?.executionPlans?.get(subprocessorGraph)
1340
+ : undefined;
1341
+ const processor = new GraphProcessor(subprocessorProject, subGraphId, this.#registry, this.#includeTrace, {
1342
+ cacheLoadedProjects: this.#cacheLoadedProjects,
1343
+ captureNodeTimings: this.#captureNodeTimings,
1002
1344
  concurrency: this.#concurrency,
1345
+ executionPlanCacheMode: this.#executionPlanCacheMode,
1346
+ initialExecutionPlan,
1347
+ runtimeCache: this.#runtimeCache,
1348
+ scheduler: this.#scheduler,
1003
1349
  });
1004
1350
  processor.executor = this.executor;
1005
1351
  processor.#isSubProcessor = true;
@@ -1046,7 +1392,7 @@ export class GraphProcessor {
1046
1392
  return await new Promise((resolve, reject) => {
1047
1393
  const abortListener = () => {
1048
1394
  delete this.#pendingUserInputs[node.id];
1049
- reject(new Error('Processing aborted'));
1395
+ reject(createGraphAbortErrorFromSignal(this.#abortController.signal));
1050
1396
  };
1051
1397
  this.#pendingUserInputs[node.id] = {
1052
1398
  resolve,
@@ -1067,45 +1413,19 @@ export class GraphProcessor {
1067
1413
  }));
1068
1414
  });
1069
1415
  }
1070
- #excludedDueToControlFlow(node, inputValues, processId, typeOfExclusion = undefined) {
1071
- if (node.disabled) {
1072
- this.#emitTraceEvent(`Excluding node ${node.title} because it's disabled`);
1073
- this.#excludeNode(node, processId, inputValues, 'disabled');
1074
- return true;
1075
- }
1076
- if (node.isConditional && typeOfExclusion === undefined) {
1077
- const ifValue = coerceTypeOptional(inputValues[IF_PORT.id], 'boolean');
1078
- if (ifValue === false) {
1079
- this.#emitTraceEvent(`Excluding node ${node.title} because if port is false`);
1080
- this.#excludeNode(node, processId, inputValues, 'if port is false');
1081
- return true;
1082
- }
1416
+ #excludedDueToControlFlow(node, inputValues, processId, typeOfExclusion, options = {}) {
1417
+ const exclusion = getControlFlowExclusionDecision({ node, inputValues, typeOfExclusion });
1418
+ if (exclusion.action === 'continue') {
1419
+ return false;
1083
1420
  }
1084
- const inputsWithValues = entries(inputValues);
1085
- const controlFlowExcludedValues = inputsWithValues.filter(([, value]) => this.#isControlFlowExcluded(value) && (!typeOfExclusion || value.value === typeOfExclusion));
1086
- const inputIsExcludedValue = inputsWithValues.length > 0 && controlFlowExcludedValues.length > 0;
1087
- const isWaitingForLoop = controlFlowExcludedValues.some((value) => value?.[1]?.value === LOOP_NOT_BROKEN_SENTINEL);
1088
- const nodesAllowedToConsumeExcludedValue = [
1089
- 'if',
1090
- 'ifElse',
1091
- 'coalesce',
1092
- 'graphOutput',
1093
- 'raceInputs',
1094
- 'loopController',
1095
- ];
1096
- const allowedToConsumedExcludedValue = nodesAllowedToConsumeExcludedValue.includes(node.type) && !isWaitingForLoop;
1097
- if (inputIsExcludedValue && !allowedToConsumedExcludedValue) {
1098
- if (!isWaitingForLoop) {
1099
- if (inputIsExcludedValue) {
1100
- this.#emitTraceEvent(`Excluding node ${node.title} because of control flow. Input is has excluded value: ${controlFlowExcludedValues[0]?.[0]}`);
1101
- }
1102
- this.#excludeNode(node, processId, inputValues, 'input is excluded value');
1103
- }
1104
- return true;
1421
+ if (exclusion.action === 'exclude') {
1422
+ this.#emitTraceEvent(exclusion.traceMessage);
1423
+ return this.#excludeNode(node, processId, inputValues, exclusion.reason, options);
1105
1424
  }
1106
- return false;
1425
+ return true;
1107
1426
  }
1108
- #excludeNode(node, processId, inputValues, reason) {
1427
+ #excludeNode(node, processId, inputValues, reason, options = {}) {
1428
+ const { queueOutputNodes = true } = options;
1109
1429
  const attachedData = this.#getAttachedDataTo(node);
1110
1430
  this.#registerNodeInActiveLoop(node, attachedData);
1111
1431
  this.#visitedNodes.add(node.id);
@@ -1114,33 +1434,33 @@ export class GraphProcessor {
1114
1434
  this.#remainingNodes.delete(node.id);
1115
1435
  const outputNodes = getOutputNodesFrom(this.#executionState, node);
1116
1436
  this.#propagateAttachedDataToOutputNodes(node, attachedData, outputNodes.connectionsToNodes);
1117
- this.#queueOutputNodes(node, outputNodes.nodes);
1437
+ if (queueOutputNodes) {
1438
+ this.#queueOutputNodes(node, outputNodes.nodes);
1439
+ }
1440
+ return outputNodes.nodes;
1118
1441
  }
1119
1442
  #markAsExcluded(node, processId, inputValues, reason) {
1120
- const outputs = {};
1121
- for (const output of this.#definitions[node.id].outputs) {
1122
- outputs[output.id] = { type: 'control-flow-excluded', value: undefined };
1123
- }
1124
- // Prevent infinite loop, a control-flow-excluded to loop controller shouldn't set the break port, let the loop controller handle it
1125
- if (node.type === 'loopController') {
1126
- outputs['break'] = { type: 'control-flow-excluded', value: LOOP_NOT_BROKEN_SENTINEL };
1127
- }
1443
+ emitDetached(this.#emitter, 'nodeExcluded', this.#createNodeExcludedEvent(node, processId, inputValues, reason));
1444
+ }
1445
+ async #emitNodeExcluded(node, processId, inputValues, reason) {
1446
+ await this.#emitter.emit('nodeExcluded', this.#createNodeExcludedEvent(node, processId, inputValues, reason));
1447
+ }
1448
+ #createNodeExcludedEvent(node, processId, inputValues, reason) {
1449
+ const outputs = createExcludedNodeOutputs(node, this.#definitions[node.id].outputs);
1128
1450
  this.#nodeResults.set(node.id, outputs);
1129
- emitDetached(this.#emitter, 'nodeExcluded', this.#withExecution({
1451
+ return this.#withExecution({
1130
1452
  node,
1131
1453
  processId,
1132
1454
  inputs: inputValues,
1133
1455
  outputs,
1134
1456
  reason,
1135
- }));
1457
+ });
1136
1458
  }
1137
1459
  #getInputValuesForNode(node) {
1138
1460
  const connections = this.#connections[node.id];
1139
1461
  return this.#definitions[node.id].inputs.reduce((values, input) => {
1140
- if (!connections) {
1141
- return values;
1142
- }
1143
- const connection = connections.find((conn) => conn.inputId === input.id && conn.inputNodeId === node.id);
1462
+ const connection = this.#graphExecutionPlan?.inputConnectionByNodeAndPort[node.id]?.[input.id] ??
1463
+ connections?.find((conn) => conn.inputId === input.id && conn.inputNodeId === node.id);
1144
1464
  if (connection) {
1145
1465
  const outputNode = this.#nodeInstances[connection.outputNodeId].chartNode;
1146
1466
  const outputNodeOutputs = this.#nodeResults.get(outputNode.id);
@@ -1155,6 +1475,7 @@ export class GraphProcessor {
1155
1475
  connections: this.#connections,
1156
1476
  definitions: this.#definitions,
1157
1477
  erroredNodes: this.#erroredNodes,
1478
+ executionPlan: this.#graphExecutionPlan,
1158
1479
  loopControllersSeen: this.#loopControllersSeen,
1159
1480
  nodesById: this.#nodesById,
1160
1481
  stronglyConnectedComponents: this.#scc,