@valerypopoff/rivet2-core 2.0.6 → 2.0.8

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 (34) hide show
  1. package/dist/cjs/bundle.cjs +1440 -769
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/api/createProcessor.js +8 -2
  4. package/dist/esm/model/GraphPreprocessor.js +129 -7
  5. package/dist/esm/model/GraphProcessor.js +204 -82
  6. package/dist/esm/model/NodeExclusionPolicy.js +67 -0
  7. package/dist/esm/model/NodeExecutionPlanner.js +66 -22
  8. package/dist/esm/model/Nodes.js +3 -0
  9. package/dist/esm/model/chat-v2/chatV2Outputs.js +183 -0
  10. package/dist/esm/model/chat-v2/chatV2Pipeline.js +30 -212
  11. package/dist/esm/model/nodes/CodeNewNode.js +207 -0
  12. package/dist/esm/model/nodes/CodeNode.js +11 -10
  13. package/dist/esm/model/nodes/CommentNode.js +1 -1
  14. package/dist/esm/model/nodes/ExpressionNode.js +23 -39
  15. package/dist/esm/model/nodes/HttpCallNode.js +20 -18
  16. package/dist/esm/model/nodes/ObjectNode.js +1 -0
  17. package/dist/esm/model/nodes/ToolNode.js +1 -0
  18. package/dist/esm/model/nodes/codeNodeErrorDiagnostics.js +16 -11
  19. package/dist/esm/model/nodes/jsListCallbackHelpers.js +26 -30
  20. package/dist/esm/model/nodes/jsValueInterpolation.js +56 -2
  21. package/dist/esm/utils/serialization/serialization.js +22 -1
  22. package/dist/types/api/createProcessor.d.ts +8 -2
  23. package/dist/types/model/EditorDefinition.d.ts +2 -0
  24. package/dist/types/model/GraphPreprocessor.d.ts +36 -2
  25. package/dist/types/model/GraphProcessor.d.ts +12 -1
  26. package/dist/types/model/NodeExclusionPolicy.d.ts +21 -0
  27. package/dist/types/model/NodeExecutionPlanner.d.ts +3 -8
  28. package/dist/types/model/Nodes.d.ts +3 -2
  29. package/dist/types/model/ProcessContext.d.ts +2 -2
  30. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +29 -0
  31. package/dist/types/model/nodes/CodeNewNode.d.ts +27 -0
  32. package/dist/types/model/nodes/codeNodeErrorDiagnostics.d.ts +4 -2
  33. package/dist/types/model/nodes/jsValueInterpolation.d.ts +20 -0
  34. package/package.json +1 -1
@@ -6,7 +6,7 @@ import { deserializeProject } from '../utils/serialization/serialization.js';
6
6
  import { GptTokenizerTokenizer } from '../integrations/GptTokenizerTokenizer.js';
7
7
  import { looseDataValuesToDataValues } from './looseDataValue.js';
8
8
  import { resolveProcessSettings } from './processSettings.js';
9
- export function coreCreateProcessor(project, options) {
9
+ export function coreCreateProcessor(project, options, internalOptions = {}) {
10
10
  const { graph, inputs = {}, context = {} } = options;
11
11
  const graphId = graph
12
12
  ? graph in project.graphs
@@ -17,7 +17,13 @@ export function coreCreateProcessor(project, options) {
17
17
  throw new Error(`Graph not found, and no main graph specified.`);
18
18
  }
19
19
  // TODO: Consolidate options into one object
20
- const processor = new GraphProcessor(project, graphId, options.registry ?? globalRivetNodeRegistry, options.includeTrace, { concurrency: options.concurrency });
20
+ const processor = new GraphProcessor(project, graphId, options.registry ?? globalRivetNodeRegistry, options.includeTrace, {
21
+ cacheLoadedProjects: internalOptions.cacheLoadedProjects,
22
+ concurrency: options.concurrency,
23
+ executionPlanCacheMode: internalOptions.executionPlanCacheMode,
24
+ runtimeCache: internalOptions.runtimeCache,
25
+ scheduler: internalOptions.scheduler,
26
+ });
21
27
  if (options.onStart) {
22
28
  processor.on('start', options.onStart);
23
29
  }
@@ -1,7 +1,7 @@
1
1
  import { values } from '../utils/typeSafety.js';
2
2
  import { findStronglyConnectedComponents } from './CycleDetector.js';
3
3
  export function preprocessGraphState(options) {
4
- const { graph, loadedProjects, project, registry, warnOnInvalidGraph } = options;
4
+ const { buildExecutionPlan, graph, loadedProjects, project, registry, warnOnInvalidGraph } = options;
5
5
  const nodeInstances = {};
6
6
  const nodesById = {};
7
7
  const connections = {};
@@ -41,14 +41,49 @@ export function preprocessGraphState(options) {
41
41
  .map((connection) => nodesById[connection.inputNodeId])
42
42
  .filter(Boolean);
43
43
  });
44
- return {
44
+ const nodesNotInCycle = stronglyConnectedComponents.filter((component) => component.length === 1).flat();
45
+ const result = {
45
46
  connections,
46
47
  definitions,
47
48
  nodeInstances,
48
49
  nodesById,
49
- nodesNotInCycle: stronglyConnectedComponents.filter((component) => component.length === 1).flat(),
50
+ nodesNotInCycle,
50
51
  stronglyConnectedComponents,
51
52
  };
53
+ if (!buildExecutionPlan) {
54
+ return result;
55
+ }
56
+ return {
57
+ ...result,
58
+ ...buildGraphExecutionPlan({
59
+ connections,
60
+ definitions,
61
+ graphNodes: graph.nodes,
62
+ nodesById,
63
+ stronglyConnectedComponents,
64
+ }),
65
+ };
66
+ }
67
+ export function isGraphExecutionPlan(preprocessedGraph) {
68
+ return 'inputConnectionByNodeAndPort' in preprocessedGraph;
69
+ }
70
+ export function toReusableGraphExecutionPlan(preprocessedGraph) {
71
+ return {
72
+ connections: preprocessedGraph.connections,
73
+ cycleIndexByNode: preprocessedGraph.cycleIndexByNode,
74
+ definitions: preprocessedGraph.definitions,
75
+ graphNodes: preprocessedGraph.graphNodes,
76
+ inputConnectionByNodeAndPort: preprocessedGraph.inputConnectionByNodeAndPort,
77
+ inputConnectionsByNode: preprocessedGraph.inputConnectionsByNode,
78
+ inputNodesByNode: preprocessedGraph.inputNodesByNode,
79
+ missingRequiredInputsByNode: preprocessedGraph.missingRequiredInputsByNode,
80
+ nodesById: preprocessedGraph.nodesById,
81
+ nodesNotInCycle: preprocessedGraph.nodesNotInCycle,
82
+ outputConnectionsByNodeAndPort: preprocessedGraph.outputConnectionsByNodeAndPort,
83
+ outputNodeResultsByNode: preprocessedGraph.outputNodeResultsByNode,
84
+ startNodes: preprocessedGraph.startNodes,
85
+ stronglyConnectedComponents: preprocessedGraph.stronglyConnectedComponents,
86
+ };
52
87
  }
53
88
  function loadInputOutputDefinitions(options) {
54
89
  const { connections, loadedProjects, nodeInstances, nodesById, project, warnOnInvalidGraph } = options;
@@ -84,14 +119,101 @@ function loadInputOutputDefinitions(options) {
84
119
  }
85
120
  return false;
86
121
  });
87
- for (const nodeConnections of values(connections)) {
122
+ if (invalidConnections.length > 0) {
88
123
  for (const invalidConnection of invalidConnections) {
89
- const invalidConnectionIndex = nodeConnections.indexOf(invalidConnection);
90
- if (invalidConnectionIndex !== -1) {
91
- nodeConnections.splice(invalidConnectionIndex, 1);
124
+ removeConnectionFromNode(connections, invalidConnection, invalidConnection.inputNodeId);
125
+ if (invalidConnection.outputNodeId !== invalidConnection.inputNodeId) {
126
+ removeConnectionFromNode(connections, invalidConnection, invalidConnection.outputNodeId);
92
127
  }
93
128
  }
94
129
  }
95
130
  }
96
131
  return definitions;
97
132
  }
133
+ function removeConnectionFromNode(connections, connection, nodeId) {
134
+ const nodeConnections = connections[nodeId];
135
+ if (!nodeConnections) {
136
+ return;
137
+ }
138
+ const invalidConnectionIndex = nodeConnections.indexOf(connection);
139
+ if (invalidConnectionIndex !== -1) {
140
+ nodeConnections.splice(invalidConnectionIndex, 1);
141
+ }
142
+ }
143
+ function buildGraphExecutionPlan(options) {
144
+ const { connections, definitions, graphNodes, nodesById, stronglyConnectedComponents } = options;
145
+ const cycleIndexByNode = {};
146
+ const inputConnectionByNodeAndPort = {};
147
+ const inputConnectionsByNode = {};
148
+ const inputNodesByNode = {};
149
+ const missingRequiredInputsByNode = {};
150
+ const outputConnectionsByNodeAndPort = {};
151
+ const outputNodeResultsByNode = {};
152
+ stronglyConnectedComponents.forEach((component, index) => {
153
+ for (const node of component) {
154
+ cycleIndexByNode[node.id] = index;
155
+ }
156
+ });
157
+ for (const node of graphNodes) {
158
+ const nodeConnections = connections[node.id] ?? [];
159
+ const inputDefinitions = definitions[node.id]?.inputs ?? [];
160
+ const outputDefinitions = definitions[node.id]?.outputs ?? [];
161
+ const validInputIds = new Set(inputDefinitions.map((definition) => definition.id));
162
+ const validOutputIds = new Set(outputDefinitions.map((definition) => definition.id));
163
+ const inputConnections = nodeConnections.filter((connection) => connection.inputNodeId === node.id && validInputIds.has(connection.inputId));
164
+ const outputConnections = nodeConnections.filter((connection) => connection.outputNodeId === node.id && validOutputIds.has(connection.outputId));
165
+ inputConnectionsByNode[node.id] = inputConnections;
166
+ outputConnectionsByNodeAndPort[node.id] = {};
167
+ inputConnectionByNodeAndPort[node.id] = {};
168
+ for (const connection of inputConnections) {
169
+ inputConnectionByNodeAndPort[node.id][connection.inputId] ??= connection;
170
+ }
171
+ for (const connection of outputConnections) {
172
+ outputConnectionsByNodeAndPort[node.id][connection.outputId] ??= [];
173
+ outputConnectionsByNodeAndPort[node.id][connection.outputId].push(connection);
174
+ }
175
+ inputNodesByNode[node.id] = inputConnections
176
+ .map((connection) => nodesById[connection.outputNodeId])
177
+ .filter((inputNode) => inputNode != null);
178
+ missingRequiredInputsByNode[node.id] = inputDefinitions.filter((input) => input.required && inputConnectionByNodeAndPort[node.id]?.[input.id] == null);
179
+ const outputNodes = [];
180
+ const seenOutputNodeIds = new Set();
181
+ const outputConnectionsByNode = new Map();
182
+ for (const connection of outputConnections) {
183
+ const outputNode = nodesById[connection.inputNodeId];
184
+ if (!outputNode) {
185
+ continue;
186
+ }
187
+ if (!seenOutputNodeIds.has(outputNode.id)) {
188
+ outputNodes.push(outputNode);
189
+ seenOutputNodeIds.add(outputNode.id);
190
+ }
191
+ const nodeConnections = outputConnectionsByNode.get(outputNode.id);
192
+ if (nodeConnections) {
193
+ nodeConnections.push(connection);
194
+ }
195
+ else {
196
+ outputConnectionsByNode.set(outputNode.id, [connection]);
197
+ }
198
+ }
199
+ outputNodeResultsByNode[node.id] = {
200
+ connections: outputConnections,
201
+ connectionsToNodes: outputNodes.map((outputNode) => ({
202
+ connections: outputConnectionsByNode.get(outputNode.id) ?? [],
203
+ node: outputNode,
204
+ })),
205
+ nodes: outputNodes,
206
+ };
207
+ }
208
+ return {
209
+ cycleIndexByNode,
210
+ graphNodes,
211
+ inputConnectionByNodeAndPort,
212
+ inputConnectionsByNode,
213
+ inputNodesByNode,
214
+ missingRequiredInputsByNode,
215
+ outputConnectionsByNodeAndPort,
216
+ outputNodeResultsByNode,
217
+ startNodes: graphNodes.filter((node) => outputNodeResultsByNode[node.id]?.nodes.length === 0),
218
+ };
219
+ }
@@ -1,14 +1,13 @@
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';
12
11
  import { replayExecutionRecording } from './RecordingPlayer.js';
13
12
  import { didLoopControllerBreak, LOOP_NOT_BROKEN_SENTINEL } from './loopControllerBreak.js';
14
13
  import { buildNodeProcessContext } from './ProcessContextBuilder.js';
@@ -16,10 +15,18 @@ import { processSplitRunNode } from './SplitRunProcessor.js';
16
15
  import { getInputNodesTo, getMissingRequiredInputs, getOutputNodesFrom, getStartNodes, getWaitingForInputNode, hasErroredInputNode, } from './NodeExecutionPlanner.js';
17
16
  import { wireSubprocessorEvents, wireSubprocessorLifecycle } from './SubprocessorBridge.js';
18
17
  import { emitDetached } from '../utils/emitDetached.js';
18
+ import { createExcludedNodeOutputs, getControlFlowExclusionDecision, getMissingRequiredInputExclusion, } from './NodeExclusionPolicy.js';
19
19
  // eslint-disable-next-line import/no-cycle -- There has to be a cycle because CodeRunner needs to import the entirety of Rivet
20
20
  import { IsomorphicCodeRunner } from '../integrations/CodeRunner.js';
21
21
  const DEFAULT_NODE_CONCURRENCY = 8;
22
22
  export const DEFAULT_SPLIT_RUN_CONCURRENCY = 4;
23
+ const FAST_ACYCLIC_UNSUPPORTED_NODE_TYPES = new Set([
24
+ 'loopController',
25
+ 'loopUntil',
26
+ 'raceInputs',
27
+ 'userInput',
28
+ 'waitForEvent',
29
+ ]);
23
30
  function normalizeConcurrencyValue(value, fallback) {
24
31
  return typeof value === 'number' && Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallback;
25
32
  }
@@ -45,6 +52,10 @@ export class GraphProcessor {
45
52
  #parent;
46
53
  #registry;
47
54
  #concurrency;
55
+ #executionPlanCacheMode;
56
+ #runtimeCache;
57
+ #cacheLoadedProjects;
58
+ #scheduler;
48
59
  id = nanoid();
49
60
  #includeTrace = true;
50
61
  executor;
@@ -87,7 +98,7 @@ export class GraphProcessor {
87
98
  #loadedProjects = undefined;
88
99
  #definitions = undefined;
89
100
  #scc = undefined;
90
- // @ts-expect-error
101
+ #graphExecutionPlan;
91
102
  #nodesNotInCycle = undefined;
92
103
  #nodeAbortControllers = new Map();
93
104
  #graphInputNodeValues = {};
@@ -115,6 +126,10 @@ export class GraphProcessor {
115
126
  this.#nodesById = {};
116
127
  this.#registry = registry;
117
128
  this.#concurrency = resolveGraphProcessorConcurrency(options?.concurrency);
129
+ this.#executionPlanCacheMode = options?.executionPlanCacheMode ?? 'all';
130
+ this.#runtimeCache = options?.runtimeCache;
131
+ this.#cacheLoadedProjects = options?.cacheLoadedProjects ?? false;
132
+ this.#scheduler = options?.scheduler ?? 'compatible';
118
133
  this.#emitter.bindMethods(this, ['on', 'off', 'once', 'onAny', 'offAny']);
119
134
  this.setExternalFunction('echo', async (value) => ({ type: 'any', value }));
120
135
  this.#emitter.on('globalSet', ({ id, value }) => {
@@ -122,19 +137,53 @@ export class GraphProcessor {
122
137
  });
123
138
  }
124
139
  #preprocessGraph() {
140
+ const runtimeCache = this.#canUseRuntimeExecutionPlanCache() ? this.#runtimeCache : undefined;
141
+ const shouldUseRuntimeCache = runtimeCache != null;
142
+ const cachedPlan = runtimeCache?.executionPlans?.get(this.#graph);
143
+ if (cachedPlan) {
144
+ this.#applyPreprocessedGraph(cachedPlan, { recreateNodeInstances: true });
145
+ return;
146
+ }
125
147
  const preprocessedGraph = preprocessGraphState({
126
148
  graph: this.#graph,
127
149
  loadedProjects: this.#loadedProjects,
128
150
  project: this.#project,
129
151
  registry: this.#registry,
130
152
  warnOnInvalidGraph: this.warnOnInvalidGraph,
153
+ buildExecutionPlan: shouldUseRuntimeCache,
131
154
  });
132
- Object.assign(this.#nodeInstances, preprocessedGraph.nodeInstances);
155
+ if (shouldUseRuntimeCache && isGraphExecutionPlan(preprocessedGraph)) {
156
+ runtimeCache.executionPlans ??= new WeakMap();
157
+ runtimeCache.executionPlans.set(this.#graph, toReusableGraphExecutionPlan(preprocessedGraph));
158
+ }
159
+ this.#applyPreprocessedGraph(preprocessedGraph);
160
+ }
161
+ #canUseRuntimeExecutionPlanCache() {
162
+ if (this.warnOnInvalidGraph || this.#runtimeCache == null) {
163
+ return false;
164
+ }
165
+ if (this.#executionPlanCacheMode === 'subprocessors' && !this.#isSubProcessor) {
166
+ return false;
167
+ }
168
+ if (!this.#cacheLoadedProjects && (this.#project.references?.length ?? 0) > 0) {
169
+ return false;
170
+ }
171
+ return true;
172
+ }
173
+ #applyPreprocessedGraph(preprocessedGraph, options = {}) {
174
+ const nodeInstances = options.recreateNodeInstances || !('nodeInstances' in preprocessedGraph)
175
+ ? this.#createNodeInstances(isGraphExecutionPlan(preprocessedGraph) ? preprocessedGraph.graphNodes : this.#graph.nodes)
176
+ : preprocessedGraph.nodeInstances;
177
+ Object.assign(this.#nodeInstances, nodeInstances);
133
178
  Object.assign(this.#nodesById, preprocessedGraph.nodesById);
134
179
  Object.assign(this.#connections, preprocessedGraph.connections);
135
180
  this.#definitions = preprocessedGraph.definitions;
136
181
  this.#scc = preprocessedGraph.stronglyConnectedComponents;
137
182
  this.#nodesNotInCycle = preprocessedGraph.nodesNotInCycle;
183
+ this.#graphExecutionPlan = isGraphExecutionPlan(preprocessedGraph) ? preprocessedGraph : undefined;
184
+ }
185
+ #createNodeInstances(nodes) {
186
+ return Object.fromEntries(nodes.map((node) => [node.id, this.#registry.createDynamicImpl(node)]));
138
187
  }
139
188
  #emitTraceEvent(eventData) {
140
189
  if (this.#includeTrace) {
@@ -300,7 +349,7 @@ export class GraphProcessor {
300
349
  return;
301
350
  }
302
351
  dependencyNodes.add(nodeId);
303
- const connections = this.#connections[nodeId] ?? [];
352
+ const connections = this.#graphExecutionPlan?.inputConnectionsByNode[nodeId] ?? this.#connections[nodeId] ?? [];
304
353
  for (const connection of connections) {
305
354
  if (connection.inputNodeId === nodeId) {
306
355
  this.#collectDependencyNodesDeep(connection.outputNodeId, dependencyNodes);
@@ -364,7 +413,8 @@ export class GraphProcessor {
364
413
  this.#abortError = undefined;
365
414
  this.#abortSuccessfully = false;
366
415
  this.#nodeAbortControllers = new Map();
367
- this.#loadedProjects = {};
416
+ this.#loadedProjects =
417
+ this.#cacheLoadedProjects && this.#runtimeCache?.loadedProjects ? { ...this.#runtimeCache.loadedProjects } : {};
368
418
  this.#graphInputNodeValues = {};
369
419
  }
370
420
  /** Main function for running a graph. Runs a graph and returns the outputs from the output nodes of the graph. */
@@ -385,9 +435,14 @@ export class GraphProcessor {
385
435
  await this.#emitGraphStart();
386
436
  await this.#emitPreloadedNodeResults();
387
437
  await this.#waitUntilUnpaused();
388
- await this.#queueStartNodes(getStartNodes(this.#executionState, this.#graph.nodes, this.runToNodeIds));
389
- await this.#processingQueue.onIdle();
390
- this.#markUnqueuedNodesIgnored();
438
+ if (this.#canUseFastAcyclicScheduler()) {
439
+ await this.#processFastAcyclicGraph();
440
+ }
441
+ else {
442
+ await this.#queueStartNodes(getStartNodes(this.#executionState, this.#graph.nodes, this.runToNodeIds));
443
+ await this.#processingQueue.onIdle();
444
+ this.#markUnqueuedNodesIgnored();
445
+ }
391
446
  await this.#throwIfGraphErrored();
392
447
  return await this.#finalizeGraphRun();
393
448
  }
@@ -468,6 +523,90 @@ export class GraphProcessor {
468
523
  });
469
524
  }
470
525
  }
526
+ #canUseFastAcyclicScheduler() {
527
+ if (this.#scheduler !== 'fast-acyclic') {
528
+ return false;
529
+ }
530
+ if (this.#hasPreloadedData || this.runToNodeIds || this.slowMode || this.#includeTrace) {
531
+ return false;
532
+ }
533
+ if (this.#nodesNotInCycle.length !== this.#graph.nodes.length) {
534
+ return false;
535
+ }
536
+ if (this.#graph.connections.some((connection) => connection.inputNodeId === connection.outputNodeId)) {
537
+ return false;
538
+ }
539
+ return this.#graph.nodes.every((node) => {
540
+ if (node.isSplitRun) {
541
+ return false;
542
+ }
543
+ return !FAST_ACYCLIC_UNSUPPORTED_NODE_TYPES.has(node.type);
544
+ });
545
+ }
546
+ async #processFastAcyclicGraph() {
547
+ const remainingInputsByNode = new Map();
548
+ const readyNodes = [];
549
+ const queuedNodeIds = new Set();
550
+ for (const node of this.#graph.nodes) {
551
+ const inputNodeIds = new Set();
552
+ for (const inputNode of getInputNodesTo(this.#executionState, node)) {
553
+ inputNodeIds.add(inputNode.id);
554
+ }
555
+ const inputCount = inputNodeIds.size;
556
+ remainingInputsByNode.set(node.id, inputCount);
557
+ if (inputCount === 0) {
558
+ readyNodes.push(node);
559
+ queuedNodeIds.add(node.id);
560
+ }
561
+ }
562
+ await new Promise((resolve, reject) => {
563
+ let activeCount = 0;
564
+ let settled = false;
565
+ const queueReadyOutputs = (outputNodes) => {
566
+ for (const outputNode of outputNodes) {
567
+ const remainingInputs = (remainingInputsByNode.get(outputNode.id) ?? 0) - 1;
568
+ remainingInputsByNode.set(outputNode.id, remainingInputs);
569
+ if (remainingInputs <= 0 && !queuedNodeIds.has(outputNode.id)) {
570
+ readyNodes.push(outputNode);
571
+ queuedNodeIds.add(outputNode.id);
572
+ }
573
+ }
574
+ };
575
+ const settle = () => {
576
+ if (settled) {
577
+ return;
578
+ }
579
+ if (activeCount === 0 && readyNodes.length === 0) {
580
+ settled = true;
581
+ resolve();
582
+ }
583
+ };
584
+ const pump = () => {
585
+ if (settled) {
586
+ return;
587
+ }
588
+ while (activeCount < this.#concurrency.nodeConcurrency && readyNodes.length > 0) {
589
+ const node = readyNodes.shift();
590
+ activeCount += 1;
591
+ void this.#processNodeIfAllInputsAvailable(node, { queueOutputNodes: false })
592
+ .then(queueReadyOutputs)
593
+ .then(() => {
594
+ activeCount -= 1;
595
+ pump();
596
+ settle();
597
+ })
598
+ .catch((error) => {
599
+ if (!settled) {
600
+ settled = true;
601
+ reject(error);
602
+ }
603
+ });
604
+ }
605
+ settle();
606
+ };
607
+ pump();
608
+ });
609
+ }
471
610
  #markUnqueuedNodesIgnored() {
472
611
  if (!this.runToNodeIds) {
473
612
  return;
@@ -527,6 +666,10 @@ export class GraphProcessor {
527
666
  }
528
667
  async #loadProjectReferences() {
529
668
  if ((this.#project.references?.length ?? 0) > 0) {
669
+ if (this.#cacheLoadedProjects && this.#runtimeCache?.loadedProjects) {
670
+ this.#loadedProjects = { ...this.#runtimeCache.loadedProjects };
671
+ return;
672
+ }
530
673
  if (!this.#context.projectReferenceLoader) {
531
674
  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
675
  }
@@ -545,6 +688,9 @@ export class GraphProcessor {
545
688
  for (const reference of this.#project.references) {
546
689
  await loadProject(reference);
547
690
  }
691
+ if (this.#cacheLoadedProjects && this.#runtimeCache) {
692
+ this.#runtimeCache.loadedProjects = { ...this.#loadedProjects };
693
+ }
548
694
  }
549
695
  }
550
696
  /** Returns true if any input node has errored. Optionally emits a trace event. */
@@ -561,10 +707,6 @@ export class GraphProcessor {
561
707
  this.#totalCost += coerceTypeOptional(output['cost'], 'number') ?? 0;
562
708
  }
563
709
  }
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
710
  async #fetchNodeDataAndProcessNode(node) {
569
711
  if (this.#currentlyProcessing.has(node.id) || this.#queuedNodes.has(node.id)) {
570
712
  return;
@@ -602,37 +744,41 @@ export class GraphProcessor {
602
744
  await this.#processNodeIfAllInputsAvailable(node);
603
745
  }
604
746
  /** If all inputs are present, all conditions met, processes the node. */
605
- async #processNodeIfAllInputsAvailable(node) {
747
+ async #processNodeIfAllInputsAvailable(node, options = {}) {
748
+ const { queueOutputNodes = true } = options;
606
749
  const builtInNode = node;
607
750
  const inputNodes = getInputNodesTo(this.#executionState, node);
608
751
  if (this.#shouldSkipNodeProcessing(node, inputNodes)) {
609
- return;
752
+ return [];
610
753
  }
611
754
  const attachedData = this.#getAttachedDataTo(node);
612
755
  if (this.#shouldSkipCompletedRaceNode(node, attachedData)) {
613
- return;
756
+ return [];
614
757
  }
615
758
  const inputValues = this.#getInputValuesForNode(node);
616
- if (this.#excludedDueToControlFlow(node, inputValues, nanoid(), LOOP_NOT_BROKEN_SENTINEL)) {
759
+ const loopExclusion = this.#excludedDueToControlFlow(node, inputValues, nanoid(), LOOP_NOT_BROKEN_SENTINEL, { queueOutputNodes });
760
+ if (loopExclusion) {
617
761
  this.#emitTraceEvent(`Node ${node.title} is excluded due to control flow`);
618
- return;
762
+ return loopExclusion === true ? [] : loopExclusion;
619
763
  }
620
764
  const waitingForInputNode = getWaitingForInputNode(this.#executionState, node, inputNodes, inputValues);
621
765
  if (waitingForInputNode) {
622
766
  this.#emitTraceEvent(`Node ${node.title} is waiting for input node ${waitingForInputNode}`);
623
- return;
767
+ return [];
624
768
  }
625
- if (this.#excludedDueToControlFlow(node, inputValues, nanoid())) {
769
+ const exclusion = this.#excludedDueToControlFlow(node, inputValues, nanoid(), undefined, {
770
+ queueOutputNodes,
771
+ });
772
+ if (exclusion) {
626
773
  this.#emitTraceEvent(`Node ${node.title} is excluded due to control flow`);
627
- return;
774
+ return exclusion === true ? [] : exclusion;
628
775
  }
629
776
  const missingRequiredInputs = this.#getMissingRequiredInputs(node);
630
777
  if (missingRequiredInputs.length > 0) {
631
- this.#excludeNodeWithMissingRequiredInputs(node, inputValues, missingRequiredInputs);
632
- return;
778
+ return this.#excludeNodeWithMissingRequiredInputs(node, inputValues, missingRequiredInputs, { queueOutputNodes });
633
779
  }
634
780
  if (this.#beginNodeProcessing(node, attachedData) === false) {
635
- return;
781
+ return [];
636
782
  }
637
783
  const processId = await this.#processNode(node);
638
784
  if (this.slowMode) {
@@ -646,10 +792,13 @@ export class GraphProcessor {
646
792
  this.#handleLoopControllerPostProcess(node, attachedData);
647
793
  this.#handleCompletedRace(node);
648
794
  if (!this.#assignChildLoopInfo(node, builtInNode, attachedData, processId)) {
649
- return;
795
+ return [];
650
796
  }
651
797
  this.#propagateAttachedDataToOutputNodes(node, attachedData, outputNodes.connectionsToNodes);
652
- this.#queueOutputNodes(node, outputNodes.nodes);
798
+ if (queueOutputNodes) {
799
+ this.#queueOutputNodes(node, outputNodes.nodes);
800
+ }
801
+ return outputNodes.nodes;
653
802
  }
654
803
  #shouldSkipNodeProcessing(node, inputNodes) {
655
804
  if (this.#ignoreNodes.has(node.id)) {
@@ -680,11 +829,11 @@ export class GraphProcessor {
680
829
  }
681
830
  return false;
682
831
  }
683
- #excludeNodeWithMissingRequiredInputs(node, inputValues, missingRequiredInputs) {
684
- const missingInputNames = missingRequiredInputs.map((input) => input.title || input.id).join(', ');
832
+ #excludeNodeWithMissingRequiredInputs(node, inputValues, missingRequiredInputs, options = {}) {
833
+ const exclusion = getMissingRequiredInputExclusion(node, missingRequiredInputs);
685
834
  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');
835
+ this.#emitTraceEvent(exclusion.traceMessage);
836
+ return this.#excludeNode(node, processId, inputValues, exclusion.reason, options);
688
837
  }
689
838
  #beginNodeProcessing(node, attachedData) {
690
839
  if (this.#shouldSkipCompletedRaceNode(node, attachedData)) {
@@ -829,7 +978,7 @@ export class GraphProcessor {
829
978
  async #processSplitRunNode(node, processId) {
830
979
  return processSplitRunNode(node, processId, {
831
980
  getInputValues: (n) => this.#getInputValuesForNode(n),
832
- isExcludedDueToControlFlow: (n, inputs, pid) => this.#excludedDueToControlFlow(n, inputs, pid),
981
+ isExcludedDueToControlFlow: (n, inputs, pid) => this.#excludedDueToControlFlow(n, inputs, pid) !== false,
833
982
  processNodeWithInputData: (n, inputs, idx, pid, partial) => this.#processNodeWithInputData(n, inputs, idx, pid, partial),
834
983
  splitRunConcurrency: this.#concurrency.splitRunConcurrency,
835
984
  accumulateCost: (output) => this.#accumulateCost(output),
@@ -999,7 +1148,11 @@ export class GraphProcessor {
999
1148
  }
1000
1149
  #createSubProcessor(node, index, processId, subGraphId, { signal, project } = {}) {
1001
1150
  const processor = new GraphProcessor(project ?? this.#project, subGraphId, this.#registry, this.#includeTrace, {
1151
+ cacheLoadedProjects: this.#cacheLoadedProjects,
1002
1152
  concurrency: this.#concurrency,
1153
+ executionPlanCacheMode: this.#executionPlanCacheMode,
1154
+ runtimeCache: this.#runtimeCache,
1155
+ scheduler: this.#scheduler,
1003
1156
  });
1004
1157
  processor.executor = this.executor;
1005
1158
  processor.#isSubProcessor = true;
@@ -1067,45 +1220,19 @@ export class GraphProcessor {
1067
1220
  }));
1068
1221
  });
1069
1222
  }
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
- }
1223
+ #excludedDueToControlFlow(node, inputValues, processId, typeOfExclusion, options = {}) {
1224
+ const exclusion = getControlFlowExclusionDecision({ node, inputValues, typeOfExclusion });
1225
+ if (exclusion.action === 'continue') {
1226
+ return false;
1083
1227
  }
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;
1228
+ if (exclusion.action === 'exclude') {
1229
+ this.#emitTraceEvent(exclusion.traceMessage);
1230
+ return this.#excludeNode(node, processId, inputValues, exclusion.reason, options);
1105
1231
  }
1106
- return false;
1232
+ return true;
1107
1233
  }
1108
- #excludeNode(node, processId, inputValues, reason) {
1234
+ #excludeNode(node, processId, inputValues, reason, options = {}) {
1235
+ const { queueOutputNodes = true } = options;
1109
1236
  const attachedData = this.#getAttachedDataTo(node);
1110
1237
  this.#registerNodeInActiveLoop(node, attachedData);
1111
1238
  this.#visitedNodes.add(node.id);
@@ -1114,17 +1241,13 @@ export class GraphProcessor {
1114
1241
  this.#remainingNodes.delete(node.id);
1115
1242
  const outputNodes = getOutputNodesFrom(this.#executionState, node);
1116
1243
  this.#propagateAttachedDataToOutputNodes(node, attachedData, outputNodes.connectionsToNodes);
1117
- this.#queueOutputNodes(node, outputNodes.nodes);
1244
+ if (queueOutputNodes) {
1245
+ this.#queueOutputNodes(node, outputNodes.nodes);
1246
+ }
1247
+ return outputNodes.nodes;
1118
1248
  }
1119
1249
  #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
- }
1250
+ const outputs = createExcludedNodeOutputs(node, this.#definitions[node.id].outputs);
1128
1251
  this.#nodeResults.set(node.id, outputs);
1129
1252
  emitDetached(this.#emitter, 'nodeExcluded', this.#withExecution({
1130
1253
  node,
@@ -1137,10 +1260,8 @@ export class GraphProcessor {
1137
1260
  #getInputValuesForNode(node) {
1138
1261
  const connections = this.#connections[node.id];
1139
1262
  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);
1263
+ const connection = this.#graphExecutionPlan?.inputConnectionByNodeAndPort[node.id]?.[input.id] ??
1264
+ connections?.find((conn) => conn.inputId === input.id && conn.inputNodeId === node.id);
1144
1265
  if (connection) {
1145
1266
  const outputNode = this.#nodeInstances[connection.outputNodeId].chartNode;
1146
1267
  const outputNodeOutputs = this.#nodeResults.get(outputNode.id);
@@ -1155,6 +1276,7 @@ export class GraphProcessor {
1155
1276
  connections: this.#connections,
1156
1277
  definitions: this.#definitions,
1157
1278
  erroredNodes: this.#erroredNodes,
1279
+ executionPlan: this.#graphExecutionPlan,
1158
1280
  loopControllersSeen: this.#loopControllersSeen,
1159
1281
  nodesById: this.#nodesById,
1160
1282
  stronglyConnectedComponents: this.#scc,