@valerypopoff/rivet2-core 2.0.8 → 2.0.10

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 (53) hide show
  1. package/dist/cjs/bundle.cjs +1187 -589
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/api/createProcessor.js +1 -0
  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 +88 -30
  10. package/dist/esm/model/GraphProcessor.js +295 -96
  11. package/dist/esm/model/NodeImpl.js +6 -4
  12. package/dist/esm/model/ProcessContextBuilder.js +2 -17
  13. package/dist/esm/model/RecordingPlayer.js +27 -7
  14. package/dist/esm/model/SplitRunProcessor.js +48 -9
  15. package/dist/esm/model/SubprocessorBridge.js +30 -23
  16. package/dist/esm/model/nodes/DidRunNode.js +12 -7
  17. package/dist/esm/model/nodes/GetGlobalNode.js +14 -4
  18. package/dist/esm/model/nodes/GraphOutputNode.js +31 -2
  19. package/dist/esm/model/nodes/LoopUntilNode.js +18 -45
  20. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +24 -63
  21. package/dist/esm/model/nodes/SetGlobalNode.js +2 -1
  22. package/dist/esm/model/nodes/SubGraphNode.js +22 -63
  23. package/dist/esm/recording/ExecutionRecorder.js +19 -6
  24. package/dist/esm/utils/emitDetached.js +2 -2
  25. package/dist/esm/utils/interpolation.js +41 -1
  26. package/dist/esm/utils/serialization/serialization.js +6 -5
  27. package/dist/esm/utils/serialization/serializationHelpers.js +2 -2
  28. package/dist/esm/utils/serialization/serializationInput.js +48 -0
  29. package/dist/esm/utils/serialization/serializationUtils.js +2 -33
  30. package/dist/esm/utils/serialization/serialization_v2.js +8 -8
  31. package/dist/types/api/createProcessor.d.ts +1 -0
  32. package/dist/types/api/streaming.d.ts +1 -0
  33. package/dist/types/exports.d.ts +1 -0
  34. package/dist/types/model/DebuggerTransportSentinel.d.ts +21 -0
  35. package/dist/types/model/EditorDefinition.d.ts +7 -1
  36. package/dist/types/model/ExecutorProtocol.d.ts +5 -0
  37. package/dist/types/model/GraphAbortReasons.d.ts +23 -0
  38. package/dist/types/model/GraphBoundaryCache.d.ts +27 -0
  39. package/dist/types/model/GraphPreprocessor.d.ts +3 -1
  40. package/dist/types/model/GraphProcessor.d.ts +8 -0
  41. package/dist/types/model/NodeImpl.d.ts +10 -5
  42. package/dist/types/model/Nodes.d.ts +2 -2
  43. package/dist/types/model/ProcessContext.d.ts +3 -0
  44. package/dist/types/model/ProcessContextBuilder.d.ts +4 -20
  45. package/dist/types/model/SplitRunProcessor.d.ts +8 -3
  46. package/dist/types/model/nodes/DidRunNode.d.ts +2 -1
  47. package/dist/types/model/nodes/LoopUntilNode.d.ts +5 -4
  48. package/dist/types/model/nodes/ReferencedGraphAliasNode.d.ts +5 -4
  49. package/dist/types/model/nodes/SubGraphNode.d.ts +6 -5
  50. package/dist/types/recording/RecordedEvents.d.ts +4 -0
  51. package/dist/types/utils/emitDetached.d.ts +2 -2
  52. package/dist/types/utils/serialization/serializationInput.d.ts +7 -0
  53. package/package.json +1 -1
@@ -8,18 +8,21 @@ import { nanoid } from 'nanoid/non-secure';
8
8
  import { coerceTypeOptional } from '../utils/coerceType.js';
9
9
  import { getPluginConfig } from '../utils/index.js';
10
10
  import { isGraphExecutionPlan, preprocessGraphState, toReusableGraphExecutionPlan, } from './GraphPreprocessor.js';
11
+ import { getGraphBoundary, } from './GraphBoundaryCache.js';
11
12
  import { replayExecutionRecording } from './RecordingPlayer.js';
12
13
  import { didLoopControllerBreak, LOOP_NOT_BROKEN_SENTINEL } from './loopControllerBreak.js';
13
14
  import { buildNodeProcessContext } from './ProcessContextBuilder.js';
14
15
  import { processSplitRunNode } from './SplitRunProcessor.js';
15
16
  import { getInputNodesTo, getMissingRequiredInputs, getOutputNodesFrom, getStartNodes, getWaitingForInputNode, hasErroredInputNode, } from './NodeExecutionPlanner.js';
16
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';
17
19
  import { emitDetached } from '../utils/emitDetached.js';
18
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();
23
26
  const FAST_ACYCLIC_UNSUPPORTED_NODE_TYPES = new Set([
24
27
  'loopController',
25
28
  'loopUntil',
@@ -27,6 +30,16 @@ const FAST_ACYCLIC_UNSUPPORTED_NODE_TYPES = new Set([
27
30
  'userInput',
28
31
  'waitForEvent',
29
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
+ }
30
43
  function normalizeConcurrencyValue(value, fallback) {
31
44
  return typeof value === 'number' && Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallback;
32
45
  }
@@ -36,6 +49,21 @@ function resolveGraphProcessorConcurrency(concurrency) {
36
49
  splitRunConcurrency: normalizeConcurrencyValue(concurrency?.splitRunConcurrency, DEFAULT_SPLIT_RUN_CONCURRENCY),
37
50
  };
38
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
+ }
39
67
  export class GraphProcessor {
40
68
  // Per-instance state
41
69
  #graph;
@@ -56,6 +84,8 @@ export class GraphProcessor {
56
84
  #runtimeCache;
57
85
  #cacheLoadedProjects;
58
86
  #scheduler;
87
+ #captureNodeTimings;
88
+ #useSeededExecutionPlanOnNextRun = false;
59
89
  id = nanoid();
60
90
  #includeTrace = true;
61
91
  executor;
@@ -92,6 +122,7 @@ export class GraphProcessor {
92
122
  #aborted = false;
93
123
  #abortSuccessfully = false;
94
124
  #abortError = undefined;
125
+ #successfulAbortTerminalProcessIds = undefined;
95
126
  #totalCost = 0;
96
127
  #ignoreNodes = undefined;
97
128
  #hasPreloadedData = false;
@@ -99,6 +130,7 @@ export class GraphProcessor {
99
130
  #definitions = undefined;
100
131
  #scc = undefined;
101
132
  #graphExecutionPlan;
133
+ #nodeProcessContextBase = undefined;
102
134
  #nodesNotInCycle = undefined;
103
135
  #nodeAbortControllers = new Map();
104
136
  #graphInputNodeValues = {};
@@ -109,13 +141,18 @@ export class GraphProcessor {
109
141
  get isRunning() {
110
142
  return this.#running;
111
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
+ }
112
153
  constructor(project, graphId, registry, includeTrace, options) {
113
154
  this.#project = project;
114
- const graph = graphId
115
- ? project.graphs[graphId]
116
- : project.metadata.mainGraphId
117
- ? project.graphs[project.metadata.mainGraphId]
118
- : undefined;
155
+ const graph = resolveProcessorGraph(project, graphId);
119
156
  if (!graph) {
120
157
  throw new Error(`Graph ${graphId} not found in project`);
121
158
  }
@@ -130,11 +167,16 @@ export class GraphProcessor {
130
167
  this.#runtimeCache = options?.runtimeCache;
131
168
  this.#cacheLoadedProjects = options?.cacheLoadedProjects ?? false;
132
169
  this.#scheduler = options?.scheduler ?? 'compatible';
170
+ this.#captureNodeTimings = options?.captureNodeTimings ?? false;
133
171
  this.#emitter.bindMethods(this, ['on', 'off', 'once', 'onAny', 'offAny']);
134
172
  this.setExternalFunction('echo', async (value) => ({ type: 'any', value }));
135
173
  this.#emitter.on('globalSet', ({ id, value }) => {
136
174
  emitDetached(this.#emitter, `globalSet:${id}`, value);
137
175
  });
176
+ if (options?.initialExecutionPlan) {
177
+ this.#applyPreprocessedGraph(options.initialExecutionPlan, { recreateNodeInstances: true });
178
+ this.#useSeededExecutionPlanOnNextRun = true;
179
+ }
138
180
  }
139
181
  #preprocessGraph() {
140
182
  const runtimeCache = this.#canUseRuntimeExecutionPlanCache() ? this.#runtimeCache : undefined;
@@ -151,6 +193,11 @@ export class GraphProcessor {
151
193
  registry: this.#registry,
152
194
  warnOnInvalidGraph: this.warnOnInvalidGraph,
153
195
  buildExecutionPlan: shouldUseRuntimeCache,
196
+ definitionContext: this.#runtimeCache
197
+ ? {
198
+ getGraphBoundary: (project, graphId) => this.#getGraphBoundary(project, graphId),
199
+ }
200
+ : undefined,
154
201
  });
155
202
  if (shouldUseRuntimeCache && isGraphExecutionPlan(preprocessedGraph)) {
156
203
  runtimeCache.executionPlans ??= new WeakMap();
@@ -159,31 +206,51 @@ export class GraphProcessor {
159
206
  this.#applyPreprocessedGraph(preprocessedGraph);
160
207
  }
161
208
  #canUseRuntimeExecutionPlanCache() {
209
+ return this.#canUseRuntimeExecutionPlanCacheFor(this.#project, this.#isSubProcessor);
210
+ }
211
+ #canUseRuntimeExecutionPlanCacheFor(project, isSubProcessor) {
162
212
  if (this.warnOnInvalidGraph || this.#runtimeCache == null) {
163
213
  return false;
164
214
  }
165
- if (this.#executionPlanCacheMode === 'subprocessors' && !this.#isSubProcessor) {
215
+ if (this.#executionPlanCacheMode === 'subprocessors' && !isSubProcessor) {
166
216
  return false;
167
217
  }
168
- if (!this.#cacheLoadedProjects && (this.#project.references?.length ?? 0) > 0) {
218
+ if (!this.#cacheLoadedProjects && (project.references?.length ?? 0) > 0) {
169
219
  return false;
170
220
  }
171
221
  return true;
172
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
+ }
173
230
  #applyPreprocessedGraph(preprocessedGraph, options = {}) {
174
231
  const nodeInstances = options.recreateNodeInstances || !('nodeInstances' in preprocessedGraph)
175
232
  ? this.#createNodeInstances(isGraphExecutionPlan(preprocessedGraph) ? preprocessedGraph.graphNodes : this.#graph.nodes)
176
233
  : preprocessedGraph.nodeInstances;
177
- Object.assign(this.#nodeInstances, nodeInstances);
178
- Object.assign(this.#nodesById, preprocessedGraph.nodesById);
179
- Object.assign(this.#connections, preprocessedGraph.connections);
234
+ replaceRecordContents(this.#nodeInstances, nodeInstances);
235
+ replaceRecordContents(this.#nodesById, preprocessedGraph.nodesById);
236
+ replaceRecordContents(this.#connections, preprocessedGraph.connections);
180
237
  this.#definitions = preprocessedGraph.definitions;
181
238
  this.#scc = preprocessedGraph.stronglyConnectedComponents;
182
239
  this.#nodesNotInCycle = preprocessedGraph.nodesNotInCycle;
183
240
  this.#graphExecutionPlan = isGraphExecutionPlan(preprocessedGraph) ? preprocessedGraph : undefined;
184
241
  }
242
+ #seededExecutionPlanForNextRun() {
243
+ if (!this.#useSeededExecutionPlanOnNextRun || this.warnOnInvalidGraph) {
244
+ return undefined;
245
+ }
246
+ return this.#graphExecutionPlan;
247
+ }
185
248
  #createNodeInstances(nodes) {
186
- return Object.fromEntries(nodes.map((node) => [node.id, this.#registry.createDynamicImpl(node)]));
249
+ const nodeInstances = {};
250
+ for (const node of nodes) {
251
+ nodeInstances[node.id] = this.#registry.createDynamicImpl(node);
252
+ }
253
+ return nodeInstances;
187
254
  }
188
255
  #emitTraceEvent(eventData) {
189
256
  if (this.#includeTrace) {
@@ -252,7 +319,9 @@ export class GraphProcessor {
252
319
  }
253
320
  this.#abortSuccessfully = successful;
254
321
  this.#abortError = error;
255
- this.#abortController.abort();
322
+ const abortReason = createGraphAbortReason(successful, error);
323
+ this.#abortController.abort(abortReason);
324
+ this.#abortActiveNodeControllers(abortReason);
256
325
  emitDetached(this.#emitter, 'graphAbort', this.#withExecution({ successful, error, graph: this.#graph }));
257
326
  if (!this.#isSubProcessor) {
258
327
  emitDetached(this.#emitter, 'abort', { successful, error });
@@ -394,7 +463,10 @@ export class GraphProcessor {
394
463
  }
395
464
  this.#erroredNodes = new Map();
396
465
  this.#currentlyProcessing = new Set();
397
- 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));
398
470
  this.#pendingUserInputs = {};
399
471
  this.#processingQueue = new PQueue({ concurrency: this.#concurrency.nodeConcurrency });
400
472
  this.#graphOutputs = {};
@@ -405,6 +477,7 @@ export class GraphProcessor {
405
477
  this.#attachedNodeData = new Map();
406
478
  this.#globals ??= new Map();
407
479
  this.#ignoreNodes = new Set();
480
+ this.#nodeProcessContextBase = undefined;
408
481
  this.#abortController = this.#newAbortController();
409
482
  this.#abortController.signal.addEventListener('abort', () => {
410
483
  this.#aborted = true;
@@ -412,9 +485,16 @@ export class GraphProcessor {
412
485
  this.#aborted = false;
413
486
  this.#abortError = undefined;
414
487
  this.#abortSuccessfully = false;
488
+ this.#successfulAbortTerminalProcessIds = new Set();
415
489
  this.#nodeAbortControllers = new Map();
416
490
  this.#loadedProjects =
417
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
+ }
418
498
  this.#graphInputNodeValues = {};
419
499
  }
420
500
  /** Main function for running a graph. Runs a graph and returns the outputs from the output nodes of the graph. */
@@ -431,7 +511,12 @@ export class GraphProcessor {
431
511
  try {
432
512
  this.#initializeGraphRun(context, inputs, contextValues);
433
513
  await this.#loadProjectReferences();
434
- this.#preprocessGraph();
514
+ this.#prepareNodeProcessContextBase();
515
+ const shouldUseSeededExecutionPlan = this.#seededExecutionPlanForNextRun() != null;
516
+ this.#useSeededExecutionPlanOnNextRun = false;
517
+ if (!shouldUseSeededExecutionPlan) {
518
+ this.#preprocessGraph();
519
+ }
435
520
  await this.#emitGraphStart();
436
521
  await this.#emitPreloadedNodeResults();
437
522
  await this.#waitUntilUnpaused();
@@ -474,6 +559,39 @@ export class GraphProcessor {
474
559
  this.#unsubscribeTokenizerError =
475
560
  typeof unsubscribeTokenizerError === 'function' ? unsubscribeTokenizerError : undefined;
476
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
+ }
477
595
  #cleanupTokenizerErrorListener() {
478
596
  const unsubscribeTokenizerError = this.#unsubscribeTokenizerError;
479
597
  this.#unsubscribeTokenizerError = undefined;
@@ -780,7 +898,8 @@ export class GraphProcessor {
780
898
  if (this.#beginNodeProcessing(node, attachedData) === false) {
781
899
  return [];
782
900
  }
783
- const processId = await this.#processNode(node);
901
+ const processResult = await this.#processNode(node);
902
+ const { processId } = processResult;
784
903
  if (this.slowMode) {
785
904
  await new Promise((resolve) => setTimeout(resolve, 250));
786
905
  }
@@ -791,14 +910,16 @@ export class GraphProcessor {
791
910
  const outputNodes = getOutputNodesFrom(this.#executionState, node);
792
911
  this.#handleLoopControllerPostProcess(node, attachedData);
793
912
  this.#handleCompletedRace(node);
794
- if (!this.#assignChildLoopInfo(node, builtInNode, attachedData, processId)) {
913
+ const childLoopInfoError = this.#assignChildLoopInfo(node, builtInNode, attachedData);
914
+ if (childLoopInfoError) {
915
+ await this.#nodeErrored(node, childLoopInfoError, processId);
795
916
  return [];
796
917
  }
797
918
  this.#propagateAttachedDataToOutputNodes(node, attachedData, outputNodes.connectionsToNodes);
798
- if (queueOutputNodes) {
919
+ if (queueOutputNodes && processResult.shouldQueueOutputNodes) {
799
920
  this.#queueOutputNodes(node, outputNodes.nodes);
800
921
  }
801
- return outputNodes.nodes;
922
+ return processResult.shouldQueueOutputNodes ? outputNodes.nodes : [];
802
923
  }
803
924
  #shouldSkipNodeProcessing(node, inputNodes) {
804
925
  if (this.#ignoreNodes.has(node.id)) {
@@ -882,29 +1003,24 @@ export class GraphProcessor {
882
1003
  if (node.type !== 'raceInputs') {
883
1004
  return;
884
1005
  }
885
- const allNodesForRace = [...this.#attachedNodeData.entries()].filter(([, { races }]) => races?.raceIds.includes(`race-${node.id}`));
886
- for (const [nodeId] of allNodesForRace) {
887
- for (const [key, abortController] of this.#nodeAbortControllers.entries()) {
888
- if (key.startsWith(nodeId)) {
889
- this.#emitTraceEvent(`Aborting node ${nodeId} because other race branch won`);
890
- abortController.abort();
891
- }
892
- }
893
- for (const [, nodeAttachedData] of [...this.#attachedNodeData.entries()]) {
894
- if (nodeAttachedData.races?.raceIds.includes(`race-${node.id}`)) {
895
- nodeAttachedData.races.completed = true;
896
- }
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;
897
1011
  }
898
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
+ }
899
1016
  }
900
- #assignChildLoopInfo(node, builtInNode, attachedData, processId) {
1017
+ #assignChildLoopInfo(node, builtInNode, attachedData) {
901
1018
  if (builtInNode.type !== 'loopController') {
902
- return true;
1019
+ return undefined;
903
1020
  }
904
1021
  let childLoopInfo = attachedData.loopInfo;
905
1022
  if (childLoopInfo != null && childLoopInfo.loopControllerId !== builtInNode.id) {
906
- this.#nodeErrored(node, new Error('Nested loops are not supported'), processId);
907
- return false;
1023
+ return new Error('Nested loops are not supported');
908
1024
  }
909
1025
  childLoopInfo = {
910
1026
  propagate: (parent, connectionsFromParent) => {
@@ -918,7 +1034,7 @@ export class GraphProcessor {
918
1034
  iterationCount: (childLoopInfo?.iterationCount ?? 0) + 1,
919
1035
  };
920
1036
  attachedData.loopInfo = childLoopInfo;
921
- return true;
1037
+ return undefined;
922
1038
  }
923
1039
  #propagateAttachedDataToOutputNodes(node, attachedData, outputConnections) {
924
1040
  for (const { node: outputNode, connections: connectionsToOutputNode } of outputConnections) {
@@ -955,17 +1071,9 @@ export class GraphProcessor {
955
1071
  async #processNode(node) {
956
1072
  const processId = nanoid();
957
1073
  if (this.#abortController.signal.aborted) {
958
- this.#nodeErrored(node, new Error('Processing aborted'), processId);
959
- return processId;
960
- }
961
- const inputNodes = getInputNodesTo(this.#executionState, node);
962
- const erroredInputNodes = inputNodes.filter((inputNode) => this.#erroredNodes.has(inputNode.id));
963
- if (erroredInputNodes.length > 0) {
964
- const error = new Error(`Cannot process node ${node.title} (${node.id}) because it depends on errored nodes: ${erroredInputNodes
965
- .map((n) => `${n.title} (${n.id})`)
966
- .join(', ')}`);
967
- this.#nodeErrored(node, error, processId);
968
- return processId;
1074
+ await this.#nodeErrored(node, createGraphAbortErrorFromSignal(this.#abortController.signal), processId);
1075
+ this.#successfulAbortTerminalProcessIds.delete(processId);
1076
+ return { processId, shouldQueueOutputNodes: false };
969
1077
  }
970
1078
  if (node.isSplitRun) {
971
1079
  await this.#processSplitRunNode(node, processId);
@@ -973,7 +1081,8 @@ export class GraphProcessor {
973
1081
  else {
974
1082
  await this.#processNormalNode(node, processId);
975
1083
  }
976
- return processId;
1084
+ const successfulAbortTerminal = this.#successfulAbortTerminalProcessIds.delete(processId);
1085
+ return { processId, shouldQueueOutputNodes: !successfulAbortTerminal };
977
1086
  }
978
1087
  async #processSplitRunNode(node, processId) {
979
1088
  return processSplitRunNode(node, processId, {
@@ -984,11 +1093,18 @@ export class GraphProcessor {
984
1093
  accumulateCost: (output) => this.#accumulateCost(output),
985
1094
  setNodeResults: (nodeId, outputs) => this.#nodeResults.set(nodeId, outputs),
986
1095
  markNodeVisited: (nodeId) => this.#visitedNodes.add(nodeId),
987
- nodeErrored: (n, err, pid) => this.#nodeErrored(n, err, pid),
1096
+ nodeErrored: (n, err, pid, durationMs, splitRunDurationMs) => this.#nodeErrored(n, err, pid, durationMs, splitRunDurationMs),
988
1097
  isAborted: () => this.#aborted,
1098
+ getAbortError: () => createGraphAbortErrorFromSignal(this.#abortController.signal),
989
1099
  emit: (event, data) => {
990
- 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));
991
1105
  },
1106
+ startNodeTiming: this.#captureNodeTimings ? () => this.#startNodeTiming() : undefined,
1107
+ finishNodeTiming: this.#captureNodeTimings ? (start) => this.#finishNodeTiming(start) : undefined,
992
1108
  });
993
1109
  }
994
1110
  async #processNormalNode(node, processId) {
@@ -999,6 +1115,7 @@ export class GraphProcessor {
999
1115
  // Use awaited emit (not emitDetached) so that listeners can yield to the
1000
1116
  // macrotask queue, giving the browser a chance to repaint during execution.
1001
1117
  await this.#emitter.emit('nodeStart', this.#withExecution({ node, inputs: inputValues, processId }));
1118
+ const timingStart = this.#startNodeTiming();
1002
1119
  try {
1003
1120
  const outputValues = await this.#processNodeWithInputData(node, inputValues, 0, processId, (node, partialOutputs, index) => {
1004
1121
  emitDetached(this.#emitter, 'partialOutput', this.#withExecution({ node, outputs: partialOutputs, index, processId }));
@@ -1006,17 +1123,50 @@ export class GraphProcessor {
1006
1123
  this.#nodeResults.set(node.id, outputValues);
1007
1124
  this.#visitedNodes.add(node.id);
1008
1125
  this.#accumulateCost(outputValues);
1009
- 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))));
1010
1131
  }
1011
1132
  catch (error) {
1012
- this.#nodeErrored(node, error, processId);
1133
+ await this.#nodeErrored(node, error, processId, this.#finishNodeTiming(timingStart));
1013
1134
  }
1014
1135
  }
1015
- #nodeErrored(node, e, processId) {
1136
+ async #nodeErrored(node, e, processId, durationMs, splitRunDurationMs) {
1016
1137
  const error = getError(e);
1017
- emitDetached(this.#emitter, 'nodeError', this.#withExecution({ node, error, processId }));
1018
- 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
+ }
1019
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;
1020
1170
  }
1021
1171
  getRootProcessor() {
1022
1172
  let processor = this;
@@ -1037,26 +1187,89 @@ export class GraphProcessor {
1037
1187
  emitDetached(this.#emitter, 'newAbortController', controller);
1038
1188
  return controller;
1039
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
+ }
1040
1249
  async #processNodeWithInputData(node, inputValues, index, processId, partialOutput) {
1041
1250
  const instance = this.#nodeInstances[node.id];
1042
1251
  const nodeAbortController = this.#newAbortController();
1043
- const abortListener = () => {
1044
- nodeAbortController.abort();
1045
- };
1046
- this.#nodeAbortControllers.set(`${node.id}-${processId}`, nodeAbortController);
1047
- 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
+ }
1048
1256
  const context = this.#createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput);
1049
- await this.#waitUntilUnpaused();
1050
1257
  let results;
1051
1258
  try {
1259
+ await this.#waitUntilUnpaused();
1052
1260
  results = await instance.process(inputValues, context);
1053
1261
  }
1054
1262
  finally {
1055
- this.#nodeAbortControllers.delete(`${node.id}-${processId}`);
1056
- this.#abortController.signal.removeEventListener('abort', abortListener);
1263
+ this.#unregisterNodeAbortController(node.id, nodeAbortController);
1057
1264
  }
1265
+ const abortReason = getGraphAbortReasonFromSignal(nodeAbortController.signal);
1058
1266
  if (nodeAbortController.signal.aborted) {
1059
- throw new Error('Aborted');
1267
+ if (isSuccessfulNonRaceGraphAbortReason(abortReason)) {
1268
+ this.#successfulAbortTerminalProcessIds.add(processId);
1269
+ }
1270
+ else {
1271
+ throw createGraphAbortError(abortReason, 'Aborted');
1272
+ }
1060
1273
  }
1061
1274
  return results;
1062
1275
  }
@@ -1066,24 +1279,12 @@ export class GraphProcessor {
1066
1279
  #createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput) {
1067
1280
  const plugin = this.#registry.getPluginFor(node.type);
1068
1281
  return buildNodeProcessContext({
1069
- abortGraph: (error) => {
1070
- void this.abort(error === undefined, error);
1071
- },
1072
1282
  attachedData: this.#getAttachedDataTo(node),
1073
- codeRunner: this.#context.codeRunner ?? new IsomorphicCodeRunner(),
1074
- context: this.#context,
1075
- contextValues: this.#contextValues,
1283
+ base: this.#nodeProcessContextBase,
1076
1284
  createSubProcessor: (subGraphId, options = {}) => this.#createSubProcessor(node, index, processId, subGraphId, options),
1077
1285
  execution: this.#buildExecutionMetadata(),
1078
- executionCache: this.#executionCache,
1079
- executor: this.executor ?? 'nodejs',
1080
1286
  externalFunctions: this.#externalFunctions,
1081
- getGlobal: (id) => this.#globals.get(id),
1082
1287
  getPluginConfig: (name) => getPluginConfig(plugin, this.#context.settings, name),
1083
- graphInputNodeValues: this.#graphInputNodeValues,
1084
- graphInputs: this.#graphInputs,
1085
- graphOutputs: this.#graphOutputs,
1086
- loadedProjects: this.#loadedProjects,
1087
1288
  node,
1088
1289
  nodeAbortController,
1089
1290
  onPartialOutputs: (partialOutputs) => {
@@ -1091,23 +1292,15 @@ export class GraphProcessor {
1091
1292
  this.#emitGraphPartialOutputIfNeeded(node, partialOutputs);
1092
1293
  },
1093
1294
  processId,
1094
- project: this.#project,
1095
- raiseEvent: (event, data) => {
1096
- this.getRootProcessor().raiseEvent(event, data);
1097
- },
1098
1295
  requestUserInput: async (inputStrings, renderingType) => this.#requestUserInput(node, inputStrings, inputValues, renderingType, processId),
1099
1296
  setGlobal: (id, value) => {
1100
1297
  this.#globals.set(id, value);
1101
1298
  emitDetached(this.#emitter, 'globalSet', this.#withExecution({ id, value, processId }));
1102
1299
  },
1103
- tokenizer: this.#getTokenizer(),
1104
- trace: (message) => {
1105
- this.#emitTraceEvent(message);
1106
- },
1107
1300
  waitEvent: async (event) => {
1108
1301
  return new Promise((resolve, reject) => {
1109
1302
  const abortListener = () => {
1110
- reject(new Error('Process aborted'));
1303
+ reject(createGraphAbortErrorFromSignal(nodeAbortController.signal, 'Process aborted'));
1111
1304
  };
1112
1305
  this.#emitter
1113
1306
  .once(`userEvent:${event}`)
@@ -1119,13 +1312,6 @@ export class GraphProcessor {
1119
1312
  nodeAbortController.signal.addEventListener('abort', abortListener, { once: true });
1120
1313
  });
1121
1314
  },
1122
- waitForGlobal: async (id) => {
1123
- if (this.#globals.has(id)) {
1124
- return this.#globals.get(id);
1125
- }
1126
- await this.getRootProcessor().#emitter.once(`globalSet:${id}`);
1127
- return this.#globals.get(id);
1128
- },
1129
1315
  });
1130
1316
  }
1131
1317
  #emitGraphPartialOutputIfNeeded(node, partialOutputs) {
@@ -1147,10 +1333,17 @@ export class GraphProcessor {
1147
1333
  });
1148
1334
  }
1149
1335
  #createSubProcessor(node, index, processId, subGraphId, { signal, project } = {}) {
1150
- 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, {
1151
1342
  cacheLoadedProjects: this.#cacheLoadedProjects,
1343
+ captureNodeTimings: this.#captureNodeTimings,
1152
1344
  concurrency: this.#concurrency,
1153
1345
  executionPlanCacheMode: this.#executionPlanCacheMode,
1346
+ initialExecutionPlan,
1154
1347
  runtimeCache: this.#runtimeCache,
1155
1348
  scheduler: this.#scheduler,
1156
1349
  });
@@ -1199,7 +1392,7 @@ export class GraphProcessor {
1199
1392
  return await new Promise((resolve, reject) => {
1200
1393
  const abortListener = () => {
1201
1394
  delete this.#pendingUserInputs[node.id];
1202
- reject(new Error('Processing aborted'));
1395
+ reject(createGraphAbortErrorFromSignal(this.#abortController.signal));
1203
1396
  };
1204
1397
  this.#pendingUserInputs[node.id] = {
1205
1398
  resolve,
@@ -1247,15 +1440,21 @@ export class GraphProcessor {
1247
1440
  return outputNodes.nodes;
1248
1441
  }
1249
1442
  #markAsExcluded(node, processId, inputValues, reason) {
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) {
1250
1449
  const outputs = createExcludedNodeOutputs(node, this.#definitions[node.id].outputs);
1251
1450
  this.#nodeResults.set(node.id, outputs);
1252
- emitDetached(this.#emitter, 'nodeExcluded', this.#withExecution({
1451
+ return this.#withExecution({
1253
1452
  node,
1254
1453
  processId,
1255
1454
  inputs: inputValues,
1256
1455
  outputs,
1257
1456
  reason,
1258
- }));
1457
+ });
1259
1458
  }
1260
1459
  #getInputValuesForNode(node) {
1261
1460
  const connections = this.#connections[node.id];