@valerypopoff/rivet2-core 2.0.10 → 2.1.0

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 (68) hide show
  1. package/dist/cjs/bundle.cjs +1762 -274
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/api/createProcessor.js +1 -0
  4. package/dist/esm/exports.js +4 -0
  5. package/dist/esm/model/GraphBoundaryCache.js +36 -4
  6. package/dist/esm/model/GraphBoundaryEffects.js +32 -0
  7. package/dist/esm/model/GraphPreprocessor.js +6 -4
  8. package/dist/esm/model/GraphProcessor.js +344 -118
  9. package/dist/esm/model/NodeGraph.js +1 -1
  10. package/dist/esm/model/NodePrefabResolver.js +57 -0
  11. package/dist/esm/model/Nodes.js +4 -1
  12. package/dist/esm/model/ProcessContextBuilder.js +3 -1
  13. package/dist/esm/model/UiGraph.js +113 -0
  14. package/dist/esm/model/UiGraphRendererStyles.js +208 -0
  15. package/dist/esm/model/chat/openAIChatRuntime.js +0 -1
  16. package/dist/esm/model/chat-v2/aiSdkBridge.js +100 -2
  17. package/dist/esm/model/chat-v2/chatV2Pipeline.js +35 -31
  18. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -1
  19. package/dist/esm/model/chat-v2/providerOptions.js +5 -1
  20. package/dist/esm/model/nodes/CoalesceNode.js +1 -1
  21. package/dist/esm/model/nodes/CompareNode.js +15 -14
  22. package/dist/esm/model/nodes/GraphOutputNode.js +1 -0
  23. package/dist/esm/model/nodes/LLMChatV2Node.js +62 -17
  24. package/dist/esm/model/nodes/NodePrefabInstanceNode.js +39 -0
  25. package/dist/esm/model/nodes/PromptNode.js +2 -1
  26. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +49 -7
  27. package/dist/esm/model/nodes/SubGraphNode.js +42 -5
  28. package/dist/esm/utils/index.js +2 -0
  29. package/dist/esm/utils/jsonValueToDataValue.js +48 -0
  30. package/dist/esm/utils/projectComparison/connections.js +57 -0
  31. package/dist/esm/utils/projectComparison/graphs.js +60 -0
  32. package/dist/esm/utils/projectComparison/nodes.js +53 -0
  33. package/dist/esm/utils/projectComparison/summaries.js +60 -0
  34. package/dist/esm/utils/projectComparison/values.js +40 -0
  35. package/dist/esm/utils/projectComparison.js +73 -0
  36. package/dist/esm/utils/serialization/serializationHelpers.js +24 -3
  37. package/dist/esm/utils/serialization/serialization_v4.js +30 -0
  38. package/dist/types/api/createProcessor.d.ts +2 -1
  39. package/dist/types/exports.d.ts +5 -0
  40. package/dist/types/model/EditorDefinition.d.ts +1 -0
  41. package/dist/types/model/ExecutorProtocol.d.ts +13 -3
  42. package/dist/types/model/GraphBoundaryCache.d.ts +9 -3
  43. package/dist/types/model/GraphBoundaryEffects.d.ts +9 -0
  44. package/dist/types/model/GraphProcessor.d.ts +20 -0
  45. package/dist/types/model/NodeBase.d.ts +5 -0
  46. package/dist/types/model/NodeBodySpec.d.ts +1 -0
  47. package/dist/types/model/NodePrefabResolver.d.ts +13 -0
  48. package/dist/types/model/Nodes.d.ts +5 -4
  49. package/dist/types/model/ProcessContext.d.ts +5 -1
  50. package/dist/types/model/ProcessContextBuilder.d.ts +4 -2
  51. package/dist/types/model/Project.d.ts +9 -0
  52. package/dist/types/model/UiGraph.d.ts +84 -0
  53. package/dist/types/model/UiGraphRendererStyles.d.ts +2 -0
  54. package/dist/types/model/chat-v2/aiSdkBridge.d.ts +1 -0
  55. package/dist/types/model/chat-v2/chatV2Types.d.ts +23 -1
  56. package/dist/types/model/nodes/CompareNode.d.ts +4 -0
  57. package/dist/types/model/nodes/LLMChatV2Node.d.ts +2 -1
  58. package/dist/types/model/nodes/NodePrefabInstanceNode.d.ts +13 -0
  59. package/dist/types/model/nodes/SubGraphNode.d.ts +2 -0
  60. package/dist/types/utils/index.d.ts +2 -0
  61. package/dist/types/utils/jsonValueToDataValue.d.ts +2 -0
  62. package/dist/types/utils/projectComparison/connections.d.ts +5 -0
  63. package/dist/types/utils/projectComparison/graphs.d.ts +3 -0
  64. package/dist/types/utils/projectComparison/nodes.d.ts +5 -0
  65. package/dist/types/utils/projectComparison/summaries.d.ts +4 -0
  66. package/dist/types/utils/projectComparison/values.d.ts +5 -0
  67. package/dist/types/utils/projectComparison.d.ts +77 -0
  68. package/package.json +1 -1
@@ -9,6 +9,7 @@ import { coerceTypeOptional } from '../utils/coerceType.js';
9
9
  import { getPluginConfig } from '../utils/index.js';
10
10
  import { isGraphExecutionPlan, preprocessGraphState, toReusableGraphExecutionPlan, } from './GraphPreprocessor.js';
11
11
  import { getGraphBoundary, } from './GraphBoundaryCache.js';
12
+ import { applyFrozenGraphBoundaryEffects, ensureGraphCostOutput } from './GraphBoundaryEffects.js';
12
13
  import { replayExecutionRecording } from './RecordingPlayer.js';
13
14
  import { didLoopControllerBreak, LOOP_NOT_BROKEN_SENTINEL } from './loopControllerBreak.js';
14
15
  import { buildNodeProcessContext } from './ProcessContextBuilder.js';
@@ -20,6 +21,45 @@ import { emitDetached } from '../utils/emitDetached.js';
20
21
  import { createExcludedNodeOutputs, getControlFlowExclusionDecision, getMissingRequiredInputExclusion, } from './NodeExclusionPolicy.js';
21
22
  // eslint-disable-next-line import/no-cycle -- There has to be a cycle because CodeRunner needs to import the entirety of Rivet
22
23
  import { IsomorphicCodeRunner } from '../integrations/CodeRunner.js';
24
+ export function cloneFrozenNodeOutputs(outputs) {
25
+ if (typeof structuredClone !== 'function') {
26
+ throw new Error('Frozen node output cloning requires structuredClone support');
27
+ }
28
+ return structuredClone(outputs);
29
+ }
30
+ export function cloneFrozenNodeOutputsByGraph(outputsByGraph) {
31
+ return Object.fromEntries(Object.entries(outputsByGraph).map(([graphId, outputsByNode]) => [
32
+ graphId,
33
+ outputsByNode
34
+ ? Object.fromEntries(Object.entries(outputsByNode).map(([nodeId, outputInstances]) => [
35
+ nodeId,
36
+ outputInstances?.map((outputs) => cloneFrozenNodeOutputs(outputs)),
37
+ ]))
38
+ : undefined,
39
+ ]));
40
+ }
41
+ export function hasFrozenNodeOutputs(outputsByGraph) {
42
+ if (!outputsByGraph) {
43
+ return false;
44
+ }
45
+ return Object.values(outputsByGraph).some((outputsByNode) => Object.values(outputsByNode ?? {}).some((outputInstances) => (outputInstances?.length ?? 0) > 0));
46
+ }
47
+ export function createFrozenNodeOutputResolver(outputsByGraph) {
48
+ if (!hasFrozenNodeOutputs(outputsByGraph)) {
49
+ return undefined;
50
+ }
51
+ const countersByGraphRunAndNode = new Map();
52
+ return ({ execution, graphId, node }) => {
53
+ const outputInstances = outputsByGraph?.[graphId]?.[node.id];
54
+ if (!outputInstances?.length) {
55
+ return undefined;
56
+ }
57
+ const counterKey = `${execution.graphRunId}:${graphId}:${node.id}`;
58
+ const currentIndex = countersByGraphRunAndNode.get(counterKey) ?? 0;
59
+ countersByGraphRunAndNode.set(counterKey, currentIndex + 1);
60
+ return cloneFrozenNodeOutputs(outputInstances[Math.min(currentIndex, outputInstances.length - 1)]);
61
+ };
62
+ }
23
63
  const DEFAULT_NODE_CONCURRENCY = 8;
24
64
  export const DEFAULT_SPLIT_RUN_CONCURRENCY = 4;
25
65
  const DEFAULT_ISOMORPHIC_CODE_RUNNER = new IsomorphicCodeRunner();
@@ -84,7 +124,9 @@ export class GraphProcessor {
84
124
  #runtimeCache;
85
125
  #cacheLoadedProjects;
86
126
  #scheduler;
127
+ #runtimeProfiler;
87
128
  #captureNodeTimings;
129
+ #frozenNodeOutputResolver;
88
130
  #useSeededExecutionPlanOnNextRun = false;
89
131
  id = nanoid();
90
132
  #includeTrace = true;
@@ -131,6 +173,7 @@ export class GraphProcessor {
131
173
  #scc = undefined;
132
174
  #graphExecutionPlan;
133
175
  #nodeProcessContextBase = undefined;
176
+ #runToRelevantNodeIds;
134
177
  #nodesNotInCycle = undefined;
135
178
  #nodeAbortControllers = new Map();
136
179
  #graphInputNodeValues = {};
@@ -150,6 +193,38 @@ export class GraphProcessor {
150
193
  }
151
194
  return Math.max(0, getMonotonicTimeMs() - start);
152
195
  }
196
+ #startRuntimeProfile() {
197
+ return this.#runtimeProfiler ? getMonotonicTimeMs() : undefined;
198
+ }
199
+ #finishRuntimeProfile(bucket, start) {
200
+ if (start == null || !this.#runtimeProfiler) {
201
+ return;
202
+ }
203
+ try {
204
+ this.#runtimeProfiler.addDuration(bucket, Math.max(0, getMonotonicTimeMs() - start));
205
+ }
206
+ catch {
207
+ // Runtime profiling is diagnostic only and must not affect graph execution.
208
+ }
209
+ }
210
+ #profileRuntimeSync(bucket, run) {
211
+ const start = this.#startRuntimeProfile();
212
+ try {
213
+ return run();
214
+ }
215
+ finally {
216
+ this.#finishRuntimeProfile(bucket, start);
217
+ }
218
+ }
219
+ async #profileRuntimeAsync(bucket, run) {
220
+ const start = this.#startRuntimeProfile();
221
+ try {
222
+ return await run();
223
+ }
224
+ finally {
225
+ this.#finishRuntimeProfile(bucket, start);
226
+ }
227
+ }
153
228
  constructor(project, graphId, registry, includeTrace, options) {
154
229
  this.#project = project;
155
230
  const graph = resolveProcessorGraph(project, graphId);
@@ -167,6 +242,7 @@ export class GraphProcessor {
167
242
  this.#runtimeCache = options?.runtimeCache;
168
243
  this.#cacheLoadedProjects = options?.cacheLoadedProjects ?? false;
169
244
  this.#scheduler = options?.scheduler ?? 'compatible';
245
+ this.#runtimeProfiler = options?.runtimeProfiler;
170
246
  this.#captureNodeTimings = options?.captureNodeTimings ?? false;
171
247
  this.#emitter.bindMethods(this, ['on', 'off', 'once', 'onAny', 'offAny']);
172
248
  this.setExternalFunction('echo', async (value) => ({ type: 'any', value }));
@@ -179,31 +255,39 @@ export class GraphProcessor {
179
255
  }
180
256
  }
181
257
  #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;
258
+ const profileStart = this.#startRuntimeProfile();
259
+ try {
260
+ const runtimeCache = this.#canUseRuntimeExecutionPlanCache() ? this.#runtimeCache : undefined;
261
+ const shouldUseRuntimeCache = runtimeCache != null;
262
+ const cachedPlan = runtimeCache?.executionPlans?.get(this.#graph);
263
+ if (cachedPlan && runtimeCache?.executionPlanNodePrefabs?.get(this.#graph) === this.#project.nodePrefabs) {
264
+ this.#applyPreprocessedGraph(cachedPlan, { recreateNodeInstances: true });
265
+ return;
266
+ }
267
+ const preprocessedGraph = preprocessGraphState({
268
+ graph: this.#graph,
269
+ loadedProjects: this.#loadedProjects,
270
+ project: this.#project,
271
+ registry: this.#registry,
272
+ warnOnInvalidGraph: this.warnOnInvalidGraph,
273
+ buildExecutionPlan: shouldUseRuntimeCache,
274
+ definitionContext: this.#runtimeCache
275
+ ? {
276
+ getGraphBoundary: (project, graphId) => this.#getGraphBoundary(project, graphId),
277
+ }
278
+ : undefined,
279
+ });
280
+ if (shouldUseRuntimeCache && isGraphExecutionPlan(preprocessedGraph)) {
281
+ runtimeCache.executionPlans ??= new WeakMap();
282
+ runtimeCache.executionPlanNodePrefabs ??= new WeakMap();
283
+ runtimeCache.executionPlans.set(this.#graph, toReusableGraphExecutionPlan(preprocessedGraph));
284
+ runtimeCache.executionPlanNodePrefabs.set(this.#graph, this.#project.nodePrefabs);
285
+ }
286
+ this.#applyPreprocessedGraph(preprocessedGraph);
188
287
  }
189
- const preprocessedGraph = preprocessGraphState({
190
- graph: this.#graph,
191
- loadedProjects: this.#loadedProjects,
192
- project: this.#project,
193
- registry: this.#registry,
194
- warnOnInvalidGraph: this.warnOnInvalidGraph,
195
- buildExecutionPlan: shouldUseRuntimeCache,
196
- definitionContext: this.#runtimeCache
197
- ? {
198
- getGraphBoundary: (project, graphId) => this.#getGraphBoundary(project, graphId),
199
- }
200
- : undefined,
201
- });
202
- if (shouldUseRuntimeCache && isGraphExecutionPlan(preprocessedGraph)) {
203
- runtimeCache.executionPlans ??= new WeakMap();
204
- runtimeCache.executionPlans.set(this.#graph, toReusableGraphExecutionPlan(preprocessedGraph));
288
+ finally {
289
+ this.#finishRuntimeProfile('preprocessGraph', profileStart);
205
290
  }
206
- this.#applyPreprocessedGraph(preprocessedGraph);
207
291
  }
208
292
  #canUseRuntimeExecutionPlanCache() {
209
293
  return this.#canUseRuntimeExecutionPlanCacheFor(this.#project, this.#isSubProcessor);
@@ -229,7 +313,9 @@ export class GraphProcessor {
229
313
  }
230
314
  #applyPreprocessedGraph(preprocessedGraph, options = {}) {
231
315
  const nodeInstances = options.recreateNodeInstances || !('nodeInstances' in preprocessedGraph)
232
- ? this.#createNodeInstances(isGraphExecutionPlan(preprocessedGraph) ? preprocessedGraph.graphNodes : this.#graph.nodes)
316
+ ? this.#createNodeInstances(isGraphExecutionPlan(preprocessedGraph)
317
+ ? preprocessedGraph.graphNodes
318
+ : Object.values(preprocessedGraph.nodesById))
233
319
  : preprocessedGraph.nodeInstances;
234
320
  replaceRecordContents(this.#nodeInstances, nodeInstances);
235
321
  replaceRecordContents(this.#nodesById, preprocessedGraph.nodesById);
@@ -395,6 +481,9 @@ export class GraphProcessor {
395
481
  this.#visitedNodes.add(nodeId);
396
482
  this.#hasPreloadedData = true;
397
483
  }
484
+ setFrozenNodeOutputResolver(resolver) {
485
+ this.#frozenNodeOutputResolver = resolver;
486
+ }
398
487
  /** Gets all node IDs that a given node ID depends on being complete before the given node ID can start. */
399
488
  getDependencyNodesDeep(nodeId) {
400
489
  this.#ensureGraphPreprocessed();
@@ -478,6 +567,7 @@ export class GraphProcessor {
478
567
  this.#globals ??= new Map();
479
568
  this.#ignoreNodes = new Set();
480
569
  this.#nodeProcessContextBase = undefined;
570
+ this.#runToRelevantNodeIds = undefined;
481
571
  this.#abortController = this.#newAbortController();
482
572
  this.#abortController.signal.addEventListener('abort', () => {
483
573
  this.#aborted = true;
@@ -509,32 +599,30 @@ export class GraphProcessor {
509
599
  throw new Error('Cannot process graph while already processing');
510
600
  }
511
601
  try {
512
- this.#initializeGraphRun(context, inputs, contextValues);
513
- await this.#loadProjectReferences();
514
- this.#prepareNodeProcessContextBase();
602
+ this.#profileRuntimeSync('initializeGraphRun', () => this.#initializeGraphRun(context, inputs, contextValues));
603
+ await this.#profileRuntimeAsync('loadProjectReferences', () => this.#loadProjectReferences());
604
+ this.#profileRuntimeSync('prepareNodeProcessContextBase', () => this.#prepareNodeProcessContextBase());
515
605
  const shouldUseSeededExecutionPlan = this.#seededExecutionPlanForNextRun() != null;
516
606
  this.#useSeededExecutionPlanOnNextRun = false;
517
607
  if (!shouldUseSeededExecutionPlan) {
518
608
  this.#preprocessGraph();
519
609
  }
520
- await this.#emitGraphStart();
521
- await this.#emitPreloadedNodeResults();
522
- await this.#waitUntilUnpaused();
610
+ await this.#profileRuntimeAsync('emitGraphStart', () => this.#emitGraphStart());
611
+ await this.#profileRuntimeAsync('emitPreloadedNodeResults', () => this.#emitPreloadedNodeResults());
612
+ await this.#profileRuntimeAsync('waitUntilUnpaused', () => this.#waitUntilUnpaused());
523
613
  if (this.#canUseFastAcyclicScheduler()) {
524
- await this.#processFastAcyclicGraph();
614
+ await this.#profileRuntimeAsync('processFastAcyclicGraph', () => this.#processFastAcyclicGraph());
525
615
  }
526
616
  else {
527
- await this.#queueStartNodes(getStartNodes(this.#executionState, this.#graph.nodes, this.runToNodeIds));
528
- await this.#processingQueue.onIdle();
529
- this.#markUnqueuedNodesIgnored();
617
+ await this.#profileRuntimeAsync('processCompatibleGraph', () => this.#processCompatibleGraph());
530
618
  }
531
- await this.#throwIfGraphErrored();
532
- return await this.#finalizeGraphRun();
619
+ await this.#profileRuntimeAsync('throwIfGraphErrored', () => this.#throwIfGraphErrored());
620
+ return await this.#profileRuntimeAsync('finalizeGraphRun', () => this.#finalizeGraphRun());
533
621
  }
534
622
  finally {
535
623
  this.#running = false;
536
624
  this.#cleanupTokenizerErrorListener();
537
- await this.#emitFinishIfNeeded();
625
+ await this.#profileRuntimeAsync('emitFinish', () => this.#emitFinishIfNeeded());
538
626
  }
539
627
  }
540
628
  async #emitFinishIfNeeded() {
@@ -641,6 +729,11 @@ export class GraphProcessor {
641
729
  });
642
730
  }
643
731
  }
732
+ async #processCompatibleGraph() {
733
+ await this.#queueStartNodes(getStartNodes(this.#executionState, this.#graph.nodes, this.runToNodeIds));
734
+ await this.#processingQueue.onIdle();
735
+ this.#markUnqueuedNodesIgnored();
736
+ }
644
737
  #canUseFastAcyclicScheduler() {
645
738
  if (this.#scheduler !== 'fast-acyclic') {
646
739
  return false;
@@ -662,14 +755,29 @@ export class GraphProcessor {
662
755
  });
663
756
  }
664
757
  async #processFastAcyclicGraph() {
758
+ const relevantNodeIds = new Set();
759
+ const nodesToVisit = [...getStartNodes(this.#executionState, this.#graph.nodes)];
760
+ for (let index = 0; index < nodesToVisit.length; index += 1) {
761
+ const node = nodesToVisit[index];
762
+ if (relevantNodeIds.has(node.id)) {
763
+ continue;
764
+ }
765
+ relevantNodeIds.add(node.id);
766
+ nodesToVisit.push(...getInputNodesTo(this.#executionState, node));
767
+ }
768
+ const inputNodeIdsByNode = new Map();
665
769
  const remainingInputsByNode = new Map();
666
770
  const readyNodes = [];
667
771
  const queuedNodeIds = new Set();
668
772
  for (const node of this.#graph.nodes) {
773
+ if (!relevantNodeIds.has(node.id)) {
774
+ continue;
775
+ }
669
776
  const inputNodeIds = new Set();
670
777
  for (const inputNode of getInputNodesTo(this.#executionState, node)) {
671
778
  inputNodeIds.add(inputNode.id);
672
779
  }
780
+ inputNodeIdsByNode.set(node.id, inputNodeIds);
673
781
  const inputCount = inputNodeIds.size;
674
782
  remainingInputsByNode.set(node.id, inputCount);
675
783
  if (inputCount === 0) {
@@ -680,8 +788,11 @@ export class GraphProcessor {
680
788
  await new Promise((resolve, reject) => {
681
789
  let activeCount = 0;
682
790
  let settled = false;
683
- const queueReadyOutputs = (outputNodes) => {
791
+ const queueReadyOutputs = (node, outputNodes) => {
684
792
  for (const outputNode of outputNodes) {
793
+ if (!relevantNodeIds.has(outputNode.id) || !inputNodeIdsByNode.get(outputNode.id)?.has(node.id)) {
794
+ continue;
795
+ }
685
796
  const remainingInputs = (remainingInputsByNode.get(outputNode.id) ?? 0) - 1;
686
797
  remainingInputsByNode.set(outputNode.id, remainingInputs);
687
798
  if (remainingInputs <= 0 && !queuedNodeIds.has(outputNode.id)) {
@@ -707,7 +818,7 @@ export class GraphProcessor {
707
818
  const node = readyNodes.shift();
708
819
  activeCount += 1;
709
820
  void this.#processNodeIfAllInputsAvailable(node, { queueOutputNodes: false })
710
- .then(queueReadyOutputs)
821
+ .then((outputNodes) => queueReadyOutputs(node, outputNodes))
711
822
  .then(() => {
712
823
  activeCount -= 1;
713
824
  pump();
@@ -767,12 +878,7 @@ export class GraphProcessor {
767
878
  throw error;
768
879
  }
769
880
  async #finalizeGraphRun() {
770
- if (this.#graphOutputs['cost'] == null) {
771
- this.#graphOutputs['cost'] = {
772
- type: 'number',
773
- value: this.#totalCost,
774
- };
775
- }
881
+ ensureGraphCostOutput(this.#graphOutputs, this.#totalCost);
776
882
  const outputValues = this.#graphOutputs;
777
883
  this.#running = false;
778
884
  await this.#emitter.emit('graphFinish', this.#withExecution({ graph: this.#graph, outputs: outputValues }));
@@ -826,46 +932,56 @@ export class GraphProcessor {
826
932
  }
827
933
  }
828
934
  async #fetchNodeDataAndProcessNode(node) {
829
- if (this.#currentlyProcessing.has(node.id) || this.#queuedNodes.has(node.id)) {
830
- return;
831
- }
832
- if (this.#nodeResults.has(node.id) || this.#erroredNodes.has(node.id)) {
833
- return;
834
- }
835
- const inputNodes = getInputNodesTo(this.#executionState, node);
836
- if (this.#hasErroredInputNode(node, inputNodes)) {
837
- return;
838
- }
839
- this.#emitTraceEvent(`Node ${node.title} has input nodes: ${inputNodes.map((n) => n.title).join(', ')}`);
840
- const attachedData = this.#getAttachedDataTo(node);
841
- if (node.type === 'raceInputs' || attachedData.races) {
842
- for (const inputNode of inputNodes) {
843
- const inputNodeAttachedData = this.#getAttachedDataTo(inputNode);
844
- const raceIds = new Set([...(attachedData.races?.raceIds ?? [])]);
845
- if (node.type === 'raceInputs') {
846
- raceIds.add(`race-${node.id}`);
935
+ const profileStart = this.#startRuntimeProfile();
936
+ try {
937
+ if (this.#currentlyProcessing.has(node.id) || this.#queuedNodes.has(node.id)) {
938
+ return;
939
+ }
940
+ if (this.#nodeResults.has(node.id) || this.#erroredNodes.has(node.id)) {
941
+ return;
942
+ }
943
+ const inputNodesProfileStart = this.#startRuntimeProfile();
944
+ const inputNodes = getInputNodesTo(this.#executionState, node);
945
+ this.#finishRuntimeProfile('getInputNodesTo', inputNodesProfileStart);
946
+ if (this.#hasErroredInputNode(node, inputNodes)) {
947
+ return;
948
+ }
949
+ this.#emitTraceEvent(`Node ${node.title} has input nodes: ${inputNodes.map((n) => n.title).join(', ')}`);
950
+ const attachedData = this.#getAttachedDataTo(node);
951
+ if (node.type === 'raceInputs' || attachedData.races) {
952
+ for (const inputNode of inputNodes) {
953
+ const inputNodeAttachedData = this.#getAttachedDataTo(inputNode);
954
+ const raceIds = new Set([...(attachedData.races?.raceIds ?? [])]);
955
+ if (node.type === 'raceInputs') {
956
+ raceIds.add(`race-${node.id}`);
957
+ }
958
+ inputNodeAttachedData.races = {
959
+ propagate: false,
960
+ raceIds: [...raceIds],
961
+ completed: false,
962
+ };
847
963
  }
848
- inputNodeAttachedData.races = {
849
- propagate: false,
850
- raceIds: [...raceIds],
851
- completed: false,
852
- };
853
964
  }
965
+ this.#queuedNodes.add(node.id);
966
+ void this.#processingQueue.addAll(inputNodes.map((inputNode) => {
967
+ return async () => {
968
+ this.#emitTraceEvent(`Fetching required data for node ${inputNode.title} (${inputNode.id})`);
969
+ await this.#fetchNodeDataAndProcessNode(inputNode);
970
+ };
971
+ }));
972
+ await this.#processNodeIfAllInputsAvailable(node);
973
+ }
974
+ finally {
975
+ this.#finishRuntimeProfile('fetchNodeDataAndProcessNode', profileStart);
854
976
  }
855
- this.#queuedNodes.add(node.id);
856
- void this.#processingQueue.addAll(inputNodes.map((inputNode) => {
857
- return async () => {
858
- this.#emitTraceEvent(`Fetching required data for node ${inputNode.title} (${inputNode.id})`);
859
- await this.#fetchNodeDataAndProcessNode(inputNode);
860
- };
861
- }));
862
- await this.#processNodeIfAllInputsAvailable(node);
863
977
  }
864
978
  /** If all inputs are present, all conditions met, processes the node. */
865
979
  async #processNodeIfAllInputsAvailable(node, options = {}) {
866
980
  const { queueOutputNodes = true } = options;
867
981
  const builtInNode = node;
982
+ const inputNodesProfileStart = this.#startRuntimeProfile();
868
983
  const inputNodes = getInputNodesTo(this.#executionState, node);
984
+ this.#finishRuntimeProfile('getInputNodesTo', inputNodesProfileStart);
869
985
  if (this.#shouldSkipNodeProcessing(node, inputNodes)) {
870
986
  return [];
871
987
  }
@@ -873,7 +989,9 @@ export class GraphProcessor {
873
989
  if (this.#shouldSkipCompletedRaceNode(node, attachedData)) {
874
990
  return [];
875
991
  }
992
+ const inputValuesProfileStart = this.#startRuntimeProfile();
876
993
  const inputValues = this.#getInputValuesForNode(node);
994
+ this.#finishRuntimeProfile('getInputValuesForNode', inputValuesProfileStart);
877
995
  const loopExclusion = this.#excludedDueToControlFlow(node, inputValues, nanoid(), LOOP_NOT_BROKEN_SENTINEL, { queueOutputNodes });
878
996
  if (loopExclusion) {
879
997
  this.#emitTraceEvent(`Node ${node.title} is excluded due to control flow`);
@@ -898,7 +1016,14 @@ export class GraphProcessor {
898
1016
  if (this.#beginNodeProcessing(node, attachedData) === false) {
899
1017
  return [];
900
1018
  }
901
- const processResult = await this.#processNode(node);
1019
+ const processProfileStart = this.#startRuntimeProfile();
1020
+ let processResult;
1021
+ try {
1022
+ processResult = await this.#processNode(node, inputValues);
1023
+ }
1024
+ finally {
1025
+ this.#finishRuntimeProfile('nodeDispatch', processProfileStart);
1026
+ }
902
1027
  const { processId } = processResult;
903
1028
  if (this.slowMode) {
904
1029
  await new Promise((resolve) => setTimeout(resolve, 250));
@@ -907,7 +1032,9 @@ export class GraphProcessor {
907
1032
  this.#visitedNodes.add(node.id);
908
1033
  this.#currentlyProcessing.delete(node.id);
909
1034
  this.#remainingNodes.delete(node.id);
1035
+ const outputNodesProfileStart = this.#startRuntimeProfile();
910
1036
  const outputNodes = getOutputNodesFrom(this.#executionState, node);
1037
+ this.#finishRuntimeProfile('getOutputNodesFrom', outputNodesProfileStart);
911
1038
  this.#handleLoopControllerPostProcess(node, attachedData);
912
1039
  this.#handleCompletedRace(node);
913
1040
  const childLoopInfoError = this.#assignChildLoopInfo(node, builtInNode, attachedData);
@@ -917,7 +1044,9 @@ export class GraphProcessor {
917
1044
  }
918
1045
  this.#propagateAttachedDataToOutputNodes(node, attachedData, outputNodes.connectionsToNodes);
919
1046
  if (queueOutputNodes && processResult.shouldQueueOutputNodes) {
1047
+ const queueOutputsProfileStart = this.#startRuntimeProfile();
920
1048
  this.#queueOutputNodes(node, outputNodes.nodes);
1049
+ this.#finishRuntimeProfile('queueOutputNodes', queueOutputsProfileStart);
921
1050
  }
922
1051
  return processResult.shouldQueueOutputNodes ? outputNodes.nodes : [];
923
1052
  }
@@ -1068,18 +1197,22 @@ export class GraphProcessor {
1068
1197
  }
1069
1198
  return nodeData;
1070
1199
  }
1071
- async #processNode(node) {
1200
+ async #processNode(node, inputValues) {
1072
1201
  const processId = nanoid();
1073
1202
  if (this.#abortController.signal.aborted) {
1074
1203
  await this.#nodeErrored(node, createGraphAbortErrorFromSignal(this.#abortController.signal), processId);
1075
1204
  this.#successfulAbortTerminalProcessIds.delete(processId);
1076
1205
  return { processId, shouldQueueOutputNodes: false };
1077
1206
  }
1078
- if (node.isSplitRun) {
1207
+ const frozenOutputs = this.#resolveFrozenNodeOutputs(node, inputValues, processId);
1208
+ if (frozenOutputs) {
1209
+ await this.#processFrozenNode(node, processId, inputValues, frozenOutputs);
1210
+ }
1211
+ else if (node.isSplitRun) {
1079
1212
  await this.#processSplitRunNode(node, processId);
1080
1213
  }
1081
1214
  else {
1082
- await this.#processNormalNode(node, processId);
1215
+ await this.#processNormalNode(node, processId, inputValues);
1083
1216
  }
1084
1217
  const successfulAbortTerminal = this.#successfulAbortTerminalProcessIds.delete(processId);
1085
1218
  return { processId, shouldQueueOutputNodes: !successfulAbortTerminal };
@@ -1107,11 +1240,37 @@ export class GraphProcessor {
1107
1240
  finishNodeTiming: this.#captureNodeTimings ? (start) => this.#finishNodeTiming(start) : undefined,
1108
1241
  });
1109
1242
  }
1110
- async #processNormalNode(node, processId) {
1111
- const inputValues = this.#getInputValuesForNode(node);
1112
- if (this.#excludedDueToControlFlow(node, inputValues, processId)) {
1243
+ #resolveFrozenNodeOutputs(node, inputValues, processId) {
1244
+ return this.#frozenNodeOutputResolver?.({
1245
+ execution: this.#buildExecutionMetadata(),
1246
+ graphId: this.#graph.metadata.id,
1247
+ inputs: inputValues,
1248
+ node,
1249
+ processId,
1250
+ });
1251
+ }
1252
+ async #processFrozenNode(node, processId, inputValues, outputValues) {
1253
+ await this.#emitter.emit('nodeStart', this.#withExecution({ node, inputs: inputValues, processId }));
1254
+ const timingStart = this.#startNodeTiming();
1255
+ this.#nodeResults.set(node.id, outputValues);
1256
+ this.#visitedNodes.add(node.id);
1257
+ this.#accumulateCost(outputValues);
1258
+ this.#applyFrozenNodeDataflowEffects(node, outputValues, processId);
1259
+ await this.#emitter.emit('nodeFinish', this.#withExecution(withOptionalDuration({
1260
+ node,
1261
+ outputs: outputValues,
1262
+ processId,
1263
+ }, this.#finishNodeTiming(timingStart))));
1264
+ }
1265
+ #applyFrozenNodeDataflowEffects(node, outputValues, processId) {
1266
+ const setGlobalEffect = applyFrozenGraphBoundaryEffects(this.#graphOutputs, node, outputValues);
1267
+ if (!setGlobalEffect) {
1113
1268
  return;
1114
1269
  }
1270
+ this.#globals.set(setGlobalEffect.variableId, setGlobalEffect.value);
1271
+ emitDetached(this.#emitter, 'globalSet', this.#withExecution({ id: setGlobalEffect.variableId, value: setGlobalEffect.value, processId }));
1272
+ }
1273
+ async #processNormalNode(node, processId, inputValues) {
1115
1274
  // Use awaited emit (not emitDetached) so that listeners can yield to the
1116
1275
  // macrotask queue, giving the browser a chance to repaint during execution.
1117
1276
  await this.#emitter.emit('nodeStart', this.#withExecution({ node, inputs: inputValues, processId }));
@@ -1253,11 +1412,19 @@ export class GraphProcessor {
1253
1412
  if (this.#abortController.signal.aborted) {
1254
1413
  nodeAbortController.abort(getAbortSignalReason(this.#abortController.signal));
1255
1414
  }
1415
+ const createContextProfileStart = this.#startRuntimeProfile();
1256
1416
  const context = this.#createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput);
1417
+ this.#finishRuntimeProfile('createNodeProcessContext', createContextProfileStart);
1257
1418
  let results;
1258
1419
  try {
1259
1420
  await this.#waitUntilUnpaused();
1260
- results = await instance.process(inputValues, context);
1421
+ const implementationProfileStart = this.#startRuntimeProfile();
1422
+ try {
1423
+ results = await instance.process(inputValues, context);
1424
+ }
1425
+ finally {
1426
+ this.#finishRuntimeProfile('nodeImplementation', implementationProfileStart);
1427
+ }
1261
1428
  }
1262
1429
  finally {
1263
1430
  this.#unregisterNodeAbortController(node.id, nodeAbortController);
@@ -1279,12 +1446,14 @@ export class GraphProcessor {
1279
1446
  #createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput) {
1280
1447
  const plugin = this.#registry.getPluginFor(node.type);
1281
1448
  return buildNodeProcessContext({
1449
+ activeOutputPortIds: this.#getActiveOutputPortIds(node),
1282
1450
  attachedData: this.#getAttachedDataTo(node),
1283
1451
  base: this.#nodeProcessContextBase,
1284
1452
  createSubProcessor: (subGraphId, options = {}) => this.#createSubProcessor(node, index, processId, subGraphId, options),
1285
1453
  execution: this.#buildExecutionMetadata(),
1286
1454
  externalFunctions: this.#externalFunctions,
1287
1455
  getPluginConfig: (name) => getPluginConfig(plugin, this.#context.settings, name),
1456
+ isDirectRunTarget: this.runToNodeIds?.includes(node.id) ?? false,
1288
1457
  node,
1289
1458
  nodeAbortController,
1290
1459
  onPartialOutputs: (partialOutputs) => {
@@ -1314,6 +1483,42 @@ export class GraphProcessor {
1314
1483
  },
1315
1484
  });
1316
1485
  }
1486
+ #getActiveOutputPortIds(node) {
1487
+ const outputConnections = getOutputNodesFrom(this.#executionState, node).connectionsToNodes;
1488
+ if (outputConnections.length === 0) {
1489
+ return new Set();
1490
+ }
1491
+ const runToRelevantNodeIds = this.#getRunToRelevantNodeIds();
1492
+ const activeOutputPortIds = new Set();
1493
+ for (const { node: outputNode, connections } of outputConnections) {
1494
+ if (outputNode.disabled) {
1495
+ continue;
1496
+ }
1497
+ if (runToRelevantNodeIds && !runToRelevantNodeIds.has(outputNode.id)) {
1498
+ continue;
1499
+ }
1500
+ for (const connection of connections) {
1501
+ activeOutputPortIds.add(connection.outputId);
1502
+ }
1503
+ }
1504
+ return activeOutputPortIds;
1505
+ }
1506
+ #getRunToRelevantNodeIds() {
1507
+ if (!this.runToNodeIds) {
1508
+ return undefined;
1509
+ }
1510
+ if (this.#runToRelevantNodeIds) {
1511
+ return this.#runToRelevantNodeIds;
1512
+ }
1513
+ const relevantNodeIds = new Set();
1514
+ for (const runToNodeId of this.runToNodeIds) {
1515
+ for (const dependencyNodeId of this.getDependencyNodesDeep(runToNodeId)) {
1516
+ relevantNodeIds.add(dependencyNodeId);
1517
+ }
1518
+ }
1519
+ this.#runToRelevantNodeIds = relevantNodeIds;
1520
+ return relevantNodeIds;
1521
+ }
1317
1522
  #emitGraphPartialOutputIfNeeded(node, partialOutputs) {
1318
1523
  const { useAsGraphPartialOutput } = node.data ?? {};
1319
1524
  if (!(useAsGraphPartialOutput && this.#executor && this.#parent)) {
@@ -1338,15 +1543,23 @@ export class GraphProcessor {
1338
1543
  const initialExecutionPlan = subprocessorGraph && this.#canUseRuntimeExecutionPlanCacheFor(subprocessorProject, true)
1339
1544
  ? this.#runtimeCache?.executionPlans?.get(subprocessorGraph)
1340
1545
  : undefined;
1341
- const processor = new GraphProcessor(subprocessorProject, subGraphId, this.#registry, this.#includeTrace, {
1342
- cacheLoadedProjects: this.#cacheLoadedProjects,
1343
- captureNodeTimings: this.#captureNodeTimings,
1344
- concurrency: this.#concurrency,
1345
- executionPlanCacheMode: this.#executionPlanCacheMode,
1346
- initialExecutionPlan,
1347
- runtimeCache: this.#runtimeCache,
1348
- scheduler: this.#scheduler,
1349
- });
1546
+ const createProfileStart = this.#startRuntimeProfile();
1547
+ let processor;
1548
+ try {
1549
+ processor = new GraphProcessor(subprocessorProject, subGraphId, this.#registry, this.#includeTrace, {
1550
+ cacheLoadedProjects: this.#cacheLoadedProjects,
1551
+ captureNodeTimings: this.#captureNodeTimings,
1552
+ concurrency: this.#concurrency,
1553
+ executionPlanCacheMode: this.#executionPlanCacheMode,
1554
+ initialExecutionPlan,
1555
+ runtimeCache: this.#runtimeCache,
1556
+ runtimeProfiler: this.#runtimeProfiler,
1557
+ scheduler: this.#scheduler,
1558
+ });
1559
+ }
1560
+ finally {
1561
+ this.#finishRuntimeProfile('createSubProcessor', createProfileStart);
1562
+ }
1350
1563
  processor.executor = this.executor;
1351
1564
  processor.#isSubProcessor = true;
1352
1565
  processor.#executionCache = this.#executionCache;
@@ -1354,38 +1567,51 @@ export class GraphProcessor {
1354
1567
  processor.#contextValues = this.#contextValues;
1355
1568
  processor.#parent = this;
1356
1569
  processor.#globals = this.#globals;
1570
+ processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
1357
1571
  processor.#executor = {
1358
1572
  nodeId: node.id,
1359
1573
  parentGraphId: this.#graph.metadata.id,
1360
1574
  index,
1361
1575
  processId,
1362
1576
  };
1363
- wireSubprocessorEvents(processor, this.#emitter, {
1364
- isPaused: () => this.#isPaused,
1365
- pause: () => {
1366
- void this.pause();
1367
- },
1368
- resume: () => {
1369
- void this.resume();
1370
- },
1371
- });
1577
+ const wireEventsProfileStart = this.#startRuntimeProfile();
1578
+ try {
1579
+ wireSubprocessorEvents(processor, this.#emitter, {
1580
+ isPaused: () => this.#isPaused,
1581
+ pause: () => {
1582
+ void this.pause();
1583
+ },
1584
+ resume: () => {
1585
+ void this.resume();
1586
+ },
1587
+ });
1588
+ }
1589
+ finally {
1590
+ this.#finishRuntimeProfile('wireSubProcessorEvents', wireEventsProfileStart);
1591
+ }
1372
1592
  this.#subprocessors.add(processor);
1373
- wireSubprocessorLifecycle(processor, {
1374
- signal,
1375
- parentAbortSignal: this.#abortController.signal,
1376
- onParentPause: (listener) => {
1377
- this.on('pause', listener);
1378
- return () => {
1379
- this.off('pause', listener);
1380
- };
1381
- },
1382
- onParentResume: (listener) => {
1383
- this.on('resume', listener);
1384
- return () => {
1385
- this.off('resume', listener);
1386
- };
1387
- },
1388
- });
1593
+ const wireLifecycleProfileStart = this.#startRuntimeProfile();
1594
+ try {
1595
+ wireSubprocessorLifecycle(processor, {
1596
+ signal,
1597
+ parentAbortSignal: this.#abortController.signal,
1598
+ onParentPause: (listener) => {
1599
+ this.on('pause', listener);
1600
+ return () => {
1601
+ this.off('pause', listener);
1602
+ };
1603
+ },
1604
+ onParentResume: (listener) => {
1605
+ this.on('resume', listener);
1606
+ return () => {
1607
+ this.off('resume', listener);
1608
+ };
1609
+ },
1610
+ });
1611
+ }
1612
+ finally {
1613
+ this.#finishRuntimeProfile('wireSubProcessorLifecycle', wireLifecycleProfileStart);
1614
+ }
1389
1615
  return processor;
1390
1616
  }
1391
1617
  async #requestUserInput(node, inputStrings, inputValues, renderingType, processId) {