@nodetool-ai/kernel 0.7.0-rc.23 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -0
- package/dist/.nodetool-build-stamp +1 -0
- package/dist/actor.d.ts +381 -20
- package/dist/actor.d.ts.map +1 -1
- package/dist/actor.js +1619 -184
- package/dist/actor.js.map +1 -1
- package/dist/correlation-analysis.d.ts +104 -0
- package/dist/correlation-analysis.d.ts.map +1 -0
- package/dist/correlation-analysis.js +833 -0
- package/dist/correlation-analysis.js.map +1 -0
- package/dist/durable-inbox.d.ts +9 -0
- package/dist/durable-inbox.d.ts.map +1 -1
- package/dist/durable-inbox.js +55 -2
- package/dist/durable-inbox.js.map +1 -1
- package/dist/dynamic-slots.d.ts +58 -0
- package/dist/dynamic-slots.d.ts.map +1 -0
- package/dist/dynamic-slots.js +182 -0
- package/dist/dynamic-slots.js.map +1 -0
- package/dist/edge-ids.d.ts +11 -0
- package/dist/edge-ids.d.ts.map +1 -0
- package/dist/edge-ids.js +15 -0
- package/dist/edge-ids.js.map +1 -0
- package/dist/graph-utils.d.ts +12 -0
- package/dist/graph-utils.d.ts.map +1 -1
- package/dist/graph-utils.js +51 -16
- package/dist/graph-utils.js.map +1 -1
- package/dist/graph.d.ts +50 -9
- package/dist/graph.d.ts.map +1 -1
- package/dist/graph.js +308 -101
- package/dist/graph.js.map +1 -1
- package/dist/inbox.d.ts +158 -2
- package/dist/inbox.d.ts.map +1 -1
- package/dist/inbox.js +253 -11
- package/dist/inbox.js.map +1 -1
- package/dist/index.d.ts +13 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -7
- package/dist/index.js.map +1 -1
- package/dist/io.d.ts +103 -6
- package/dist/io.d.ts.map +1 -1
- package/dist/io.js +123 -12
- package/dist/io.js.map +1 -1
- package/dist/loop.d.ts +36 -0
- package/dist/loop.d.ts.map +1 -0
- package/dist/loop.js +166 -0
- package/dist/loop.js.map +1 -0
- package/dist/predicates.d.ts +8 -0
- package/dist/predicates.d.ts.map +1 -0
- package/dist/predicates.js +8 -0
- package/dist/predicates.js.map +1 -0
- package/dist/run-state.d.ts +65 -0
- package/dist/run-state.d.ts.map +1 -0
- package/dist/run-state.js +42 -0
- package/dist/run-state.js.map +1 -0
- package/dist/runner.d.ts +312 -15
- package/dist/runner.d.ts.map +1 -1
- package/dist/runner.js +1219 -156
- package/dist/runner.js.map +1 -1
- package/dist/substitute-validator.d.ts +44 -0
- package/dist/substitute-validator.d.ts.map +1 -0
- package/dist/substitute-validator.js +169 -0
- package/dist/substitute-validator.js.map +1 -0
- package/dist/supervisor.d.ts +148 -0
- package/dist/supervisor.d.ts.map +1 -0
- package/dist/supervisor.js +287 -0
- package/dist/supervisor.js.map +1 -0
- package/dist/trigger-wakeup.d.ts +74 -5
- package/dist/trigger-wakeup.d.ts.map +1 -1
- package/dist/trigger-wakeup.js +167 -45
- package/dist/trigger-wakeup.js.map +1 -1
- package/package.json +27 -9
- package/dist/channel.d.ts +0 -46
- package/dist/channel.d.ts.map +0 -1
- package/dist/channel.js +0 -191
- package/dist/channel.js.map +0 -1
- package/dist/suspendable.d.ts +0 -68
- package/dist/suspendable.d.ts.map +0 -1
- package/dist/suspendable.js +0 -108
- package/dist/suspendable.js.map +0 -1
- package/dist/trigger-manager.d.ts +0 -107
- package/dist/trigger-manager.d.ts.map +0 -1
- package/dist/trigger-manager.js +0 -214
- package/dist/trigger-manager.js.map +0 -1
- package/dist/trigger.d.ts +0 -57
- package/dist/trigger.d.ts.map +0 -1
- package/dist/trigger.js +0 -145
- package/dist/trigger.js.map +0 -1
package/dist/runner.js
CHANGED
|
@@ -14,14 +14,88 @@
|
|
|
14
14
|
* - Completion detection.
|
|
15
15
|
*/
|
|
16
16
|
import { createLogger } from "@nodetool-ai/config";
|
|
17
|
+
import { isBoolean, isCallable, isNumber, isObjectValue, isString } from "./predicates.js";
|
|
17
18
|
import { TypeMetadata } from "@nodetool-ai/protocol";
|
|
19
|
+
import { ensureBounded, redactValue } from "./supervisor.js";
|
|
20
|
+
// Stryker disable next-line StringLiteral: logger name is a diagnostic label, not a behavioural contract
|
|
18
21
|
const log = createLogger("nodetool.kernel.runner");
|
|
19
|
-
|
|
20
|
-
|
|
22
|
+
/** Node type that publishes to a variable channel (see runtime VariableChannel). */
|
|
23
|
+
const SET_VARIABLE_NODE_TYPE = "nodetool.variable.SetVariable";
|
|
24
|
+
/**
|
|
25
|
+
* Minimum interval between edge_update emissions per edge. The first message
|
|
26
|
+
* on an edge always emits (it starts the flow animation); afterwards the
|
|
27
|
+
* counter badge is refreshed at most this often, with the exact final count
|
|
28
|
+
* flushed at run end. Keeps audio-rate streams (~50 chunks/s per edge) from
|
|
29
|
+
* flooding the message transport.
|
|
30
|
+
*/
|
|
31
|
+
const EDGE_UPDATE_MIN_INTERVAL_MS = 1000;
|
|
32
|
+
/**
|
|
33
|
+
* Cap on messages retained for RunResult.messages. Long-running streaming
|
|
34
|
+
* jobs would otherwise accumulate messages without bound; when the cap is
|
|
35
|
+
* hit, the oldest half is dropped (block-wise, so the cost amortizes).
|
|
36
|
+
*/
|
|
37
|
+
const MAX_RETAINED_MESSAGES = 10_000;
|
|
38
|
+
/**
|
|
39
|
+
* Cap on lineages retained per node for `read_node_output`. A supervisor reads
|
|
40
|
+
* the failing invocation's own branch, which is recent; a wide fan-out must not
|
|
41
|
+
* turn the cache into a second copy of the run's data.
|
|
42
|
+
*/
|
|
43
|
+
const MAX_RECORDED_LINEAGES_PER_NODE = 64;
|
|
44
|
+
function hasDefinedOwnProperty(record, key) {
|
|
45
|
+
return (Object.prototype.hasOwnProperty.call(record, key) &&
|
|
46
|
+
record[key] !== undefined);
|
|
47
|
+
}
|
|
48
|
+
/** A value that already carries its own control-event envelope. */
|
|
49
|
+
function isControlEventValue(value) {
|
|
50
|
+
return (typeof value === "object" &&
|
|
51
|
+
value !== null &&
|
|
52
|
+
"event_type" in value &&
|
|
53
|
+
typeof value.event_type === "string");
|
|
54
|
+
}
|
|
55
|
+
/** An output_update whose value is a streamed audio chunk (sample payload). */
|
|
56
|
+
function isAudioChunkOutputUpdate(msg) {
|
|
57
|
+
if (msg.type !== "output_update")
|
|
58
|
+
return false;
|
|
59
|
+
const value = msg.value;
|
|
60
|
+
if (!isObjectValue(value))
|
|
61
|
+
return false;
|
|
62
|
+
const v = value;
|
|
63
|
+
return v.type === "chunk" && v.content_type === "audio";
|
|
64
|
+
}
|
|
65
|
+
// Import span helpers from the narrow `/tracing` subpath, not the package root,
|
|
66
|
+
// so thin consumers (e.g. the in-browser workflow runner) don't drag the
|
|
67
|
+
// provider / python-bridge barrel into their bundle.
|
|
68
|
+
import { withWorkflowSpan } from "@nodetool-ai/runtime/tracing";
|
|
69
|
+
import { LOOP_NODE_TYPE, isControlEdge, isDataEdge } from "@nodetool-ai/protocol";
|
|
21
70
|
import { Graph, GraphValidationError } from "./graph.js";
|
|
22
71
|
import { rewriteBypassedNodes } from "./graph-utils.js";
|
|
72
|
+
import { dynamicSlotPropertyTypes } from "./dynamic-slots.js";
|
|
23
73
|
import { NodeInbox } from "./inbox.js";
|
|
24
74
|
import { NodeActor } from "./actor.js";
|
|
75
|
+
import { syntheticEdgeId } from "./edge-ids.js";
|
|
76
|
+
import { analyzeCorrelation, projectLineageKey } from "./correlation-analysis.js";
|
|
77
|
+
import { lineageRelated } from "./run-state.js";
|
|
78
|
+
/**
|
|
79
|
+
* For workflow sink nodes (`nodetool.output.Output`, Preview), the user-facing
|
|
80
|
+
* key is `properties.name` (workflow output / vvvv pin name). The process
|
|
81
|
+
* result still uses internal handles (e.g. `output`). Map those updates to the
|
|
82
|
+
* logical name so WebSocket clients can route values to the right pins.
|
|
83
|
+
*/
|
|
84
|
+
function clientFacingOutputName(node, handle) {
|
|
85
|
+
const t = node.type ?? "";
|
|
86
|
+
const props = node.properties;
|
|
87
|
+
const workflowKey = props && isString(props.name) && props.name.trim().length > 0
|
|
88
|
+
? props.name.trim()
|
|
89
|
+
: undefined;
|
|
90
|
+
if (t === "nodetool.output.Output" || t.endsWith(".output.Output")) {
|
|
91
|
+
return workflowKey ?? handle;
|
|
92
|
+
}
|
|
93
|
+
if (t === "nodetool.workflows.base_node.Preview" ||
|
|
94
|
+
t.endsWith(".workflows.base_node.Preview")) {
|
|
95
|
+
return workflowKey ?? handle;
|
|
96
|
+
}
|
|
97
|
+
return handle;
|
|
98
|
+
}
|
|
25
99
|
// ---------------------------------------------------------------------------
|
|
26
100
|
// WorkflowRunner
|
|
27
101
|
// ---------------------------------------------------------------------------
|
|
@@ -33,10 +107,14 @@ export class WorkflowRunner {
|
|
|
33
107
|
_inboxes = new Map();
|
|
34
108
|
/** Per-edge message counters (for EdgeUpdate tracking). */
|
|
35
109
|
_edgeCounters = new Map();
|
|
36
|
-
/** Per-edge
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
|
|
110
|
+
/** Per-edge timestamp of the last emitted edge_update (throttling). */
|
|
111
|
+
_edgeCounterLastEmitMs = new Map();
|
|
112
|
+
/** Edges whose counter advanced since their last emitted edge_update. */
|
|
113
|
+
_edgeCounterDirty = new Set();
|
|
114
|
+
/**
|
|
115
|
+
* Static correlation analysis result. Always populated before actors run.
|
|
116
|
+
*/
|
|
117
|
+
_correlation;
|
|
40
118
|
/**
|
|
41
119
|
* Multi-edge list inputs: nodeId → set of handles that aggregate
|
|
42
120
|
* multiple edges into a list.
|
|
@@ -48,11 +126,104 @@ export class WorkflowRunner {
|
|
|
48
126
|
_messages = [];
|
|
49
127
|
/** Cancellation flag. */
|
|
50
128
|
_cancelled = false;
|
|
51
|
-
/**
|
|
129
|
+
/**
|
|
130
|
+
* Actors spawned and not yet finished (including their completion
|
|
131
|
+
* handling). Exposed via {@link liveActorCount} for leak accounting — after
|
|
132
|
+
* a run this must be back to zero, and a harness that can't measure it
|
|
133
|
+
* can't assert it.
|
|
134
|
+
*/
|
|
135
|
+
_liveActors = 0;
|
|
136
|
+
/** Node ids of actors still running; read by quiescence detection. */
|
|
137
|
+
_liveActorIds = new Set();
|
|
138
|
+
/**
|
|
139
|
+
* Outgoing data edges of streaming input nodes that `finishInputStream`
|
|
140
|
+
* has not closed yet. While any is open, values can still arrive from
|
|
141
|
+
* outside the graph, so the graph is never quiescent.
|
|
142
|
+
*/
|
|
143
|
+
_openExternalStreamEdges = new Set();
|
|
144
|
+
/** Schedules a quiescence check; set only for graphs with a Loop node. */
|
|
145
|
+
_scheduleQuiescenceCheck = null;
|
|
146
|
+
/**
|
|
147
|
+
* Latch set by `cancel()` and never cleared by `_resetRunState`. A cancel
|
|
148
|
+
* that lands between construction and `run()` would otherwise be dropped —
|
|
149
|
+
* the reset clears `_cancelled` and swaps the AbortController. `_runImpl`
|
|
150
|
+
* re-applies this latch after the reset so such a run terminates as
|
|
151
|
+
* "cancelled". §17.
|
|
152
|
+
*/
|
|
153
|
+
_cancelRequested = false;
|
|
154
|
+
/**
|
|
155
|
+
* True while a run is in flight. A second concurrent `run()` on the same
|
|
156
|
+
* instance would clobber all shared run state, so `_runImpl` rejects it. §17.
|
|
157
|
+
*/
|
|
158
|
+
_running = false;
|
|
159
|
+
/**
|
|
160
|
+
* Job id used for `edge_update` emissions during a run. Captured from
|
|
161
|
+
* `request.job_id` at the start of `_runImpl` so edge updates and
|
|
162
|
+
* `job_update` messages carry the same id; before a run starts it defaults
|
|
163
|
+
* to the constructor id. §16.
|
|
164
|
+
*/
|
|
165
|
+
_effectiveJobId;
|
|
166
|
+
/** Run-level cancellation signal source; aborted by `cancel()`. */
|
|
167
|
+
_abortController = new AbortController();
|
|
168
|
+
/**
|
|
169
|
+
* Pending response resolvers for sendControlEvent, FIFO per node. The
|
|
170
|
+
* controlled actor processes control events in order and emits outputs in
|
|
171
|
+
* order, so the oldest waiter matches the next output. A single slot per
|
|
172
|
+
* node would let a burst of concurrent control events (e.g. parallel agent
|
|
173
|
+
* tool calls) overwrite an earlier resolver, leaving its promise unsettled
|
|
174
|
+
* forever.
|
|
175
|
+
*/
|
|
52
176
|
_pendingControlResponses = new Map();
|
|
177
|
+
/**
|
|
178
|
+
* Executor instance per node. Resolved once and reused so that the
|
|
179
|
+
* instance initialized in _initializeGraph is the same one that executes
|
|
180
|
+
* (NodeRegistry.resolve constructs a fresh instance per call).
|
|
181
|
+
*/
|
|
182
|
+
_executors = new Map();
|
|
183
|
+
/**
|
|
184
|
+
* Nodes whose actor has finished running. A control event sent to such a
|
|
185
|
+
* node can never be answered (the actor's run loop is gone), so
|
|
186
|
+
* sendControlEvent rejects instead of registering a promise that hangs
|
|
187
|
+
* forever. This guards against an agent dispatching a burst of control
|
|
188
|
+
* tool calls where the controlled node errors (and terminates) partway
|
|
189
|
+
* through.
|
|
190
|
+
*/
|
|
191
|
+
_completedNodes = new Set();
|
|
192
|
+
/** Errors reported by node actors, keyed by node id. */
|
|
193
|
+
_nodeErrors = new Map();
|
|
194
|
+
/**
|
|
195
|
+
* Edge ids whose source has already been marked done on the target inbox.
|
|
196
|
+
* `markSourceDone` decrements an upstream counter, so marking the same edge
|
|
197
|
+
* twice would over-decrement and could prematurely close a handle that still
|
|
198
|
+
* has other open upstreams. Early per-slot EOS (`outputs.complete`) and the
|
|
199
|
+
* final `_sendEOS` both guard against double-marking via this set.
|
|
200
|
+
*/
|
|
201
|
+
_eosSentEdges = new Set();
|
|
202
|
+
/** Supervisor escalations and their verdicts, in decision order. */
|
|
203
|
+
_interventions = [];
|
|
204
|
+
/**
|
|
205
|
+
* Last output of each node per invocation lineage, for `read_node_output`.
|
|
206
|
+
* Only populated on a supervised run — an unsupervised one keeps nothing.
|
|
207
|
+
* Bounded per node: a 10k-item fan-out must not become a 10k-entry cache.
|
|
208
|
+
*/
|
|
209
|
+
_recordedOutputs = new Map();
|
|
210
|
+
/** Undefined on an unsupervised run, so its `RunResult` is unchanged. */
|
|
211
|
+
_recordedInterventions() {
|
|
212
|
+
return this._interventions.length > 0 ? this._interventions : undefined;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* The handle every escalation actually goes through: whatever the caller
|
|
216
|
+
* configured, under the kernel's bounds. Nothing else in the runner reads
|
|
217
|
+
* `_options.supervisor`.
|
|
218
|
+
*/
|
|
219
|
+
_supervisor;
|
|
53
220
|
constructor(jobId, options) {
|
|
54
221
|
this.jobId = jobId;
|
|
222
|
+
this._effectiveJobId = jobId;
|
|
55
223
|
this._options = options;
|
|
224
|
+
this._supervisor = options.supervisor
|
|
225
|
+
? ensureBounded(options.supervisor)
|
|
226
|
+
: undefined;
|
|
56
227
|
}
|
|
57
228
|
// -----------------------------------------------------------------------
|
|
58
229
|
// Public API
|
|
@@ -70,6 +241,27 @@ export class WorkflowRunner {
|
|
|
70
241
|
throw new Error(`Input node not found: ${inputName}`);
|
|
71
242
|
}
|
|
72
243
|
for (const node of inputNodes) {
|
|
244
|
+
// Run the node's own process() so streamed values transform exactly like
|
|
245
|
+
// start params do in _dispatchInputs (StringInput max_length,
|
|
246
|
+
// DocumentFileInput building a DocumentRef, MessageDeconstructor
|
|
247
|
+
// splitting). Otherwise the same input node behaves differently depending
|
|
248
|
+
// on whether the value arrived as a param or was streamed in. This is a
|
|
249
|
+
// live-stream path, so a process() failure throws rather than silently
|
|
250
|
+
// dropping the value.
|
|
251
|
+
const executor = this._resolveExecutor(node);
|
|
252
|
+
let nodeOutputs;
|
|
253
|
+
try {
|
|
254
|
+
nodeOutputs = await executor.process({ value }, this._options.executionContext);
|
|
255
|
+
}
|
|
256
|
+
catch (err) {
|
|
257
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
258
|
+
throw new Error(`Input node "${node.name ?? node.id}" (${node.type}) failed: ${message}`);
|
|
259
|
+
}
|
|
260
|
+
// Same fallback semantics as _dispatchInputs: raw-value dispatch only
|
|
261
|
+
// when process() produced no defined output at all (the test-double
|
|
262
|
+
// case). Once the record carries any real output, a handle it omits
|
|
263
|
+
// stays silent rather than leaking the raw input value onto it.
|
|
264
|
+
const outputsEmpty = !Object.values(nodeOutputs).some((v) => v !== undefined);
|
|
73
265
|
const outgoing = this._graph
|
|
74
266
|
.findOutgoingEdges(node.id)
|
|
75
267
|
.filter(isDataEdge);
|
|
@@ -77,10 +269,20 @@ export class WorkflowRunner {
|
|
|
77
269
|
if (sourceHandle && edge.sourceHandle !== sourceHandle) {
|
|
78
270
|
continue;
|
|
79
271
|
}
|
|
272
|
+
const hasHandleValue = Object.hasOwn(nodeOutputs, edge.sourceHandle) &&
|
|
273
|
+
nodeOutputs[edge.sourceHandle] !== undefined;
|
|
274
|
+
if (!outputsEmpty && !hasHandleValue)
|
|
275
|
+
continue;
|
|
80
276
|
const targetInbox = this._inboxes.get(edge.target);
|
|
81
277
|
if (!targetInbox)
|
|
82
278
|
continue;
|
|
83
|
-
|
|
279
|
+
const handleValue = hasHandleValue
|
|
280
|
+
? nodeOutputs[edge.sourceHandle]
|
|
281
|
+
: value;
|
|
282
|
+
await targetInbox.put(edge.targetHandle, handleValue, {
|
|
283
|
+
source_edge_id: edge.id ??
|
|
284
|
+
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle)
|
|
285
|
+
});
|
|
84
286
|
this._incrementEdgeCounter(edge);
|
|
85
287
|
}
|
|
86
288
|
}
|
|
@@ -104,6 +306,8 @@ export class WorkflowRunner {
|
|
|
104
306
|
if (sourceHandle && edge.sourceHandle !== sourceHandle) {
|
|
105
307
|
continue;
|
|
106
308
|
}
|
|
309
|
+
this._openExternalStreamEdges.delete(edge.id ??
|
|
310
|
+
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle));
|
|
107
311
|
const targetInbox = this._inboxes.get(edge.target);
|
|
108
312
|
if (!targetInbox)
|
|
109
313
|
continue;
|
|
@@ -113,6 +317,13 @@ export class WorkflowRunner {
|
|
|
113
317
|
}
|
|
114
318
|
/**
|
|
115
319
|
* Execute a workflow graph.
|
|
320
|
+
*
|
|
321
|
+
* Requires hydrated descriptors: the actor trusts the behavior flags
|
|
322
|
+
* (`is_streaming_input` & co.) to pick the execution mode, so accepting a
|
|
323
|
+
* raw wire graph here would silently run streaming nodes as one-shot
|
|
324
|
+
* process() calls. Hydrate via `Graph.loadFromDict`, node-sdk's
|
|
325
|
+
* `hydrateGraphNodeFlags(graph, registry)`, or — for graphs constructed in
|
|
326
|
+
* code where the author sets the flags — `withExplicitNodeFlags`.
|
|
116
327
|
*/
|
|
117
328
|
async run(request, graphData) {
|
|
118
329
|
return withWorkflowSpan({
|
|
@@ -122,12 +333,48 @@ export class WorkflowRunner {
|
|
|
122
333
|
}, () => this._runImpl(request, graphData));
|
|
123
334
|
}
|
|
124
335
|
async _runImpl(request, graphData) {
|
|
336
|
+
// Reject a second concurrent run before touching any shared state — a reset
|
|
337
|
+
// here would wipe the in-flight run's inboxes/outputs/messages. §17.
|
|
338
|
+
if (this._running) {
|
|
339
|
+
throw new Error(`WorkflowRunner "${this.jobId}" is already running; ` +
|
|
340
|
+
"create a new runner instance per job");
|
|
341
|
+
}
|
|
342
|
+
this._running = true;
|
|
125
343
|
this._resetRunState();
|
|
344
|
+
this._effectiveJobId = request.job_id ?? this.jobId;
|
|
345
|
+
// A cancel() that landed before this run started set the latch but was
|
|
346
|
+
// undone by _resetRunState (fresh controller, _cancelled cleared). Re-apply
|
|
347
|
+
// it so the run terminates as "cancelled" rather than silently ignoring the
|
|
348
|
+
// request. §17.
|
|
349
|
+
if (this._cancelRequested) {
|
|
350
|
+
this._cancelled = true;
|
|
351
|
+
this._abortController.abort();
|
|
352
|
+
}
|
|
353
|
+
// Publish this run's cancellation signal on the shared context so nodes
|
|
354
|
+
// reached through process()/genProcess() — which receive no NodeInputs —
|
|
355
|
+
// can abort long-running work (agent loops, provider calls) on cancel().
|
|
356
|
+
// _resetRunState mints a fresh controller per run, so this must be
|
|
357
|
+
// re-published each time rather than wired once at construction.
|
|
358
|
+
if (this._options.executionContext) {
|
|
359
|
+
this._options.executionContext.signal = this._abortController.signal;
|
|
360
|
+
this._options.executionContext.triggerEvent =
|
|
361
|
+
request.trigger_event ?? null;
|
|
362
|
+
}
|
|
126
363
|
try {
|
|
127
364
|
log.info("Workflow started", {
|
|
128
365
|
jobId: request.job_id,
|
|
129
366
|
workflowId: request.workflow_id
|
|
130
367
|
});
|
|
368
|
+
// Emit job_update: running before any validation. A run that dies in
|
|
369
|
+
// graph validation still gets the running acknowledgement first, so
|
|
370
|
+
// clients never see a terminal update for a job they were never told
|
|
371
|
+
// started.
|
|
372
|
+
this._emit({
|
|
373
|
+
type: "job_update",
|
|
374
|
+
status: "running",
|
|
375
|
+
job_id: request.job_id,
|
|
376
|
+
workflow_id: request.workflow_id ?? null
|
|
377
|
+
});
|
|
131
378
|
// Rewrite the graph to route around nodes marked
|
|
132
379
|
// `ui_properties.bypassed === true`. Each outgoing edge of a
|
|
133
380
|
// bypassed node is re-attached to the matching upstream source
|
|
@@ -138,20 +385,29 @@ export class WorkflowRunner {
|
|
|
138
385
|
// Python parity: _filter_invalid_edges — silently remove edges
|
|
139
386
|
// whose source or target node doesn't exist in the graph.
|
|
140
387
|
this._filterInvalidEdges();
|
|
141
|
-
//
|
|
142
|
-
|
|
388
|
+
// Static correlation analysis is mandatory. Issues abort the run with
|
|
389
|
+
// a graph validation error before any actor is spawned.
|
|
390
|
+
this._correlation = analyzeCorrelation({
|
|
391
|
+
nodes: this._graph.nodes,
|
|
392
|
+
edges: this._graph.edges
|
|
393
|
+
});
|
|
394
|
+
if (this._correlation.issues.length > 0) {
|
|
395
|
+
const lines = this._correlation.issues.map((i) => ` - ${i.message}`);
|
|
396
|
+
throw new GraphValidationError(`Correlation analysis failed:\n${lines.join("\n")}`, this._correlation.issues
|
|
397
|
+
.filter((i) => !!i.nodeId)
|
|
398
|
+
.map((i) => ({
|
|
399
|
+
nodeId: i.nodeId,
|
|
400
|
+
nodeType: i.nodeType,
|
|
401
|
+
property: i.handle ?? "",
|
|
402
|
+
message: i.message
|
|
403
|
+
})));
|
|
404
|
+
}
|
|
143
405
|
// Validate
|
|
144
406
|
this._graph.validate();
|
|
145
407
|
// Pre-flight node validation: catch missing required fields and
|
|
146
408
|
// unset model selections before spawning any actors.
|
|
147
409
|
this._validateNodes();
|
|
148
|
-
|
|
149
|
-
this._emit({
|
|
150
|
-
type: "job_update",
|
|
151
|
-
status: "running",
|
|
152
|
-
job_id: request.job_id,
|
|
153
|
-
workflow_id: request.workflow_id ?? null
|
|
154
|
-
});
|
|
410
|
+
this._validateRequiredInputs(request.params ?? {});
|
|
155
411
|
// Detect multi-edge list inputs
|
|
156
412
|
this._detectMultiEdgeListInputs();
|
|
157
413
|
// Initialize inboxes
|
|
@@ -163,14 +419,41 @@ export class WorkflowRunner {
|
|
|
163
419
|
// Bind sendControlEvent to processing context so agent nodes can dispatch
|
|
164
420
|
// control events to controlled nodes and await their results.
|
|
165
421
|
if (this._options.executionContext &&
|
|
166
|
-
|
|
422
|
+
isCallable(this._options.executionContext.setSendControlEvent)) {
|
|
167
423
|
this._options.executionContext.setSendControlEvent((targetNodeId, properties) => this.sendControlEvent(targetNodeId, properties));
|
|
168
424
|
}
|
|
425
|
+
// Register Set Variable writers so variable channels know when to close.
|
|
426
|
+
this._registerVariableChannels();
|
|
169
427
|
// Process graph (spawn actors)
|
|
170
428
|
await this._processGraph();
|
|
171
429
|
// Post-completion: drain any edges that still have pending/open state
|
|
172
|
-
this._drainActiveEdges();
|
|
430
|
+
this._enforceCleanEdgeDrain(this._drainActiveEdges());
|
|
431
|
+
// A node failure fails the whole job (Python parity). Actors swallow
|
|
432
|
+
// their own errors so sibling branches can finish, but the final
|
|
433
|
+
// status must not report success when any node errored.
|
|
434
|
+
if (!this._cancelled && this._nodeErrors.size > 0) {
|
|
435
|
+
const error = [...this._nodeErrors]
|
|
436
|
+
.map(([nodeId, msg]) => `Node "${nodeId}" failed: ${msg}`)
|
|
437
|
+
.join("; ");
|
|
438
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
439
|
+
log.error("Workflow failed", { jobId: request.job_id, error });
|
|
440
|
+
this._emit({
|
|
441
|
+
type: "job_update",
|
|
442
|
+
status: "failed",
|
|
443
|
+
job_id: request.job_id,
|
|
444
|
+
workflow_id: request.workflow_id ?? null,
|
|
445
|
+
error
|
|
446
|
+
});
|
|
447
|
+
return {
|
|
448
|
+
outputs: Object.fromEntries(this._outputs),
|
|
449
|
+
messages: this._messages,
|
|
450
|
+
status: "failed",
|
|
451
|
+
error,
|
|
452
|
+
interventions: this._recordedInterventions()
|
|
453
|
+
};
|
|
454
|
+
}
|
|
173
455
|
const status = this._cancelled ? "cancelled" : "completed";
|
|
456
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
174
457
|
log.info("Workflow completed", { jobId: request.job_id, status });
|
|
175
458
|
this._emit({
|
|
176
459
|
type: "job_update",
|
|
@@ -181,11 +464,13 @@ export class WorkflowRunner {
|
|
|
181
464
|
return {
|
|
182
465
|
outputs: Object.fromEntries(this._outputs),
|
|
183
466
|
messages: this._messages,
|
|
184
|
-
status
|
|
467
|
+
status,
|
|
468
|
+
interventions: this._recordedInterventions()
|
|
185
469
|
};
|
|
186
470
|
}
|
|
187
471
|
catch (err) {
|
|
188
472
|
const message = err instanceof Error ? err.message : String(err);
|
|
473
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
189
474
|
log.error("Workflow failed", { jobId: request.job_id, error: message });
|
|
190
475
|
// Drain active edges on error for front-end cleanup
|
|
191
476
|
this._drainActiveEdges();
|
|
@@ -211,27 +496,166 @@ export class WorkflowRunner {
|
|
|
211
496
|
outputs: Object.fromEntries(this._outputs),
|
|
212
497
|
messages: this._messages,
|
|
213
498
|
status: "failed",
|
|
214
|
-
error: message
|
|
499
|
+
error: message,
|
|
500
|
+
interventions: this._recordedInterventions()
|
|
215
501
|
};
|
|
216
502
|
}
|
|
503
|
+
finally {
|
|
504
|
+
this._running = false;
|
|
505
|
+
}
|
|
217
506
|
}
|
|
218
507
|
_resetRunState() {
|
|
219
508
|
this._inboxes = new Map();
|
|
220
509
|
this._edgeCounters = new Map();
|
|
221
|
-
this.
|
|
222
|
-
this.
|
|
510
|
+
this._edgeCounterLastEmitMs = new Map();
|
|
511
|
+
this._edgeCounterDirty = new Set();
|
|
223
512
|
this._multiEdgeListInputs = new Map();
|
|
224
513
|
this._outputs = new Map();
|
|
225
514
|
this._messages = [];
|
|
226
515
|
this._cancelled = false;
|
|
516
|
+
this._abortController = new AbortController();
|
|
227
517
|
this._pendingControlResponses = new Map();
|
|
518
|
+
this._completedNodes = new Set();
|
|
519
|
+
this._executors = new Map();
|
|
520
|
+
this._nodeErrors = new Map();
|
|
521
|
+
this._correlation = undefined;
|
|
522
|
+
this._eosSentEdges = new Set();
|
|
523
|
+
this._liveActorIds = new Set();
|
|
524
|
+
this._openExternalStreamEdges = new Set();
|
|
525
|
+
this._scheduleQuiescenceCheck = null;
|
|
526
|
+
this._interventions = [];
|
|
527
|
+
this._recordedOutputs = new Map();
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* The read-only view a supervisor gets of the run in flight. Built from
|
|
531
|
+
* state the runner already holds, so a run without a supervisor pays for
|
|
532
|
+
* none of it. See docs/workflow-supervisor-design.md §6.
|
|
533
|
+
*/
|
|
534
|
+
_runStateReader() {
|
|
535
|
+
return {
|
|
536
|
+
digest: () => this._runStateDigest(),
|
|
537
|
+
readOutput: (nodeId, lineage) => this._readRecordedOutput(nodeId, lineage)
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
_runStateDigest() {
|
|
541
|
+
// A node error is raw `err.message` — an HTTP failure echoing its URL
|
|
542
|
+
// carries the key it was called with. The digest goes to the supervisor
|
|
543
|
+
// model, so it is redacted here, where the digest is built, exactly as the
|
|
544
|
+
// actor redacts an escalation's `detail`.
|
|
545
|
+
const secrets = this._options.executionContext?.getResolvedSecretValues?.() ??
|
|
546
|
+
new Set();
|
|
547
|
+
const escalationsPerNode = new Map();
|
|
548
|
+
for (const intervention of this._interventions) {
|
|
549
|
+
const nodeId = intervention.escalation.nodeId;
|
|
550
|
+
escalationsPerNode.set(nodeId, (escalationsPerNode.get(nodeId) ?? 0) + 1);
|
|
551
|
+
}
|
|
552
|
+
const nodes = this._graph.nodes.map((node) => {
|
|
553
|
+
const error = this._nodeErrors.get(node.id);
|
|
554
|
+
const done = this._completedNodes.has(node.id);
|
|
555
|
+
const emissions = this._recordedOutputs.get(node.id)?.size ?? 0;
|
|
556
|
+
const state = {
|
|
557
|
+
nodeId: node.id,
|
|
558
|
+
nodeType: node.type,
|
|
559
|
+
status: error !== undefined
|
|
560
|
+
? "failed"
|
|
561
|
+
: done
|
|
562
|
+
? "completed"
|
|
563
|
+
: emissions > 0
|
|
564
|
+
? "running"
|
|
565
|
+
: "pending",
|
|
566
|
+
emissions,
|
|
567
|
+
escalations: escalationsPerNode.get(node.id) ?? 0
|
|
568
|
+
};
|
|
569
|
+
if (error !== undefined) {
|
|
570
|
+
state.error = String(redactValue(error, secrets));
|
|
571
|
+
}
|
|
572
|
+
return state;
|
|
573
|
+
});
|
|
574
|
+
return {
|
|
575
|
+
jobId: this._effectiveJobId,
|
|
576
|
+
nodes,
|
|
577
|
+
costUsd: this._options.executionContext?.getTotalCost?.() ?? 0
|
|
578
|
+
};
|
|
579
|
+
}
|
|
580
|
+
_readRecordedOutput(nodeId, lineage) {
|
|
581
|
+
const perLineage = this._recordedOutputs.get(nodeId);
|
|
582
|
+
if (!perLineage)
|
|
583
|
+
return null;
|
|
584
|
+
// Most specific first: an entry sharing more of the failing invocation's
|
|
585
|
+
// roots is closer to it causally than a single-fire ancestor.
|
|
586
|
+
let best = null;
|
|
587
|
+
for (const [key, outputs] of perLineage) {
|
|
588
|
+
const recorded = key === "" ? [] : key.split(",");
|
|
589
|
+
if (!lineageRelated(recorded, lineage))
|
|
590
|
+
continue;
|
|
591
|
+
if (best === null || recorded.length > best.lineage.length) {
|
|
592
|
+
best = { nodeId, lineage: recorded, outputs };
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
return best;
|
|
228
596
|
}
|
|
229
597
|
/**
|
|
230
|
-
*
|
|
598
|
+
* Remember what a node emitted, keyed by the invocation's lineage, so a
|
|
599
|
+
* supervisor can read a producer's output while deciding a consumer's
|
|
600
|
+
* failure. Off unless the run is supervised.
|
|
231
601
|
*/
|
|
602
|
+
_recordNodeOutput(sourceNodeId, outputs, lineage) {
|
|
603
|
+
const scope = this._correlation?.nodes.get(sourceNodeId)?.invocationScope;
|
|
604
|
+
const key = scope && scope.length > 0 && lineage
|
|
605
|
+
? projectLineageKey(lineage, scope)
|
|
606
|
+
: "";
|
|
607
|
+
let perLineage = this._recordedOutputs.get(sourceNodeId);
|
|
608
|
+
if (!perLineage) {
|
|
609
|
+
perLineage = new Map();
|
|
610
|
+
this._recordedOutputs.set(sourceNodeId, perLineage);
|
|
611
|
+
}
|
|
612
|
+
// Re-inserting moves the key to the end, so the eviction below always
|
|
613
|
+
// drops the least recently emitted lineage rather than a live one.
|
|
614
|
+
perLineage.delete(key);
|
|
615
|
+
perLineage.set(key, outputs);
|
|
616
|
+
while (perLineage.size > MAX_RECORDED_LINEAGES_PER_NODE) {
|
|
617
|
+
const oldest = perLineage.keys().next();
|
|
618
|
+
if (oldest.done)
|
|
619
|
+
break;
|
|
620
|
+
perLineage.delete(oldest.value);
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
/** Actors spawned and not yet finished. Zero before and after a run. */
|
|
624
|
+
get liveActorCount() {
|
|
625
|
+
return this._liveActors;
|
|
626
|
+
}
|
|
627
|
+
/** Control-event responses still waiting on an actor, summed over nodes. */
|
|
628
|
+
get pendingControlResponseCount() {
|
|
629
|
+
let count = 0;
|
|
630
|
+
for (const queue of this._pendingControlResponses.values()) {
|
|
631
|
+
count += queue.length;
|
|
632
|
+
}
|
|
633
|
+
return count;
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* Push property updates into a running node's executor instance (live
|
|
637
|
+
* parameter changes — e.g. turning a synth knob while the patch plays).
|
|
638
|
+
* Returns true when the node's executor exists and supports live updates;
|
|
639
|
+
* false is not an error — the caller's canvas state already holds the new
|
|
640
|
+
* value for the next run.
|
|
641
|
+
*/
|
|
642
|
+
updateNodeProperties(nodeId, properties) {
|
|
643
|
+
const executor = this._executors.get(nodeId);
|
|
644
|
+
if (!executor?.applyProperties)
|
|
645
|
+
return false;
|
|
646
|
+
executor.applyProperties(properties);
|
|
647
|
+
return true;
|
|
648
|
+
}
|
|
232
649
|
cancel() {
|
|
650
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
233
651
|
log.info("Job cancelled", { jobId: this.jobId });
|
|
652
|
+
// Latch the request so a cancel before run() survives _resetRunState. §17.
|
|
653
|
+
this._cancelRequested = true;
|
|
234
654
|
this._cancelled = true;
|
|
655
|
+
// Stop producing loops (generators, pacers) that never wait on inputs —
|
|
656
|
+
// closing inboxes only unblocks consumers. Nodes observe this via
|
|
657
|
+
// `inputs.signal`.
|
|
658
|
+
this._abortController.abort();
|
|
235
659
|
// Close all inboxes to unblock waiting actors
|
|
236
660
|
for (const inbox of this._inboxes.values()) {
|
|
237
661
|
void inbox.closeAll();
|
|
@@ -248,7 +672,9 @@ export class WorkflowRunner {
|
|
|
248
672
|
const validEdges = this._graph.edges.filter((edge) => this._graph.findNode(edge.source) !== undefined &&
|
|
249
673
|
this._graph.findNode(edge.target) !== undefined);
|
|
250
674
|
if (validEdges.length < this._graph.edges.length) {
|
|
675
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
251
676
|
log.warn("Filtered invalid edges", {
|
|
677
|
+
// Stryker disable next-line ArithmeticOperator: diagnostic log arg only
|
|
252
678
|
removed: this._graph.edges.length - validEdges.length,
|
|
253
679
|
remaining: validEdges.length
|
|
254
680
|
});
|
|
@@ -307,17 +733,106 @@ export class WorkflowRunner {
|
|
|
307
733
|
})));
|
|
308
734
|
}
|
|
309
735
|
}
|
|
736
|
+
/** Refuse to start when a required workflow input has no supplied value. */
|
|
737
|
+
_validateRequiredInputs(params) {
|
|
738
|
+
const nodesWithIncomingData = new Set();
|
|
739
|
+
const nodesWithIncomingControl = new Set();
|
|
740
|
+
for (const edge of this._graph.edges) {
|
|
741
|
+
if (isDataEdge(edge)) {
|
|
742
|
+
nodesWithIncomingData.add(edge.target);
|
|
743
|
+
}
|
|
744
|
+
else if (isControlEdge(edge)) {
|
|
745
|
+
nodesWithIncomingControl.add(edge.target);
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
const missingNames = [];
|
|
749
|
+
const issues = [];
|
|
750
|
+
for (const node of this._graph.nodes) {
|
|
751
|
+
if (!node.type.startsWith("nodetool.input."))
|
|
752
|
+
continue;
|
|
753
|
+
if (node.is_streaming_output)
|
|
754
|
+
continue;
|
|
755
|
+
if (nodesWithIncomingData.has(node.id) ||
|
|
756
|
+
nodesWithIncomingControl.has(node.id)) {
|
|
757
|
+
continue;
|
|
758
|
+
}
|
|
759
|
+
const inputName = this._getExternalInputName(node);
|
|
760
|
+
const properties = isObjectValue(node.properties)
|
|
761
|
+
? node.properties
|
|
762
|
+
: {};
|
|
763
|
+
if (hasDefinedOwnProperty(params, inputName) ||
|
|
764
|
+
hasDefinedOwnProperty(properties, "value")) {
|
|
765
|
+
continue;
|
|
766
|
+
}
|
|
767
|
+
if (!missingNames.includes(inputName)) {
|
|
768
|
+
missingNames.push(inputName);
|
|
769
|
+
}
|
|
770
|
+
issues.push({
|
|
771
|
+
nodeId: node.id,
|
|
772
|
+
nodeType: node.type,
|
|
773
|
+
property: "value",
|
|
774
|
+
message: `Missing required workflow input "${inputName}"`
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
if (issues.length > 0) {
|
|
778
|
+
throw new GraphValidationError(`Missing required workflow inputs: ${missingNames.join(", ")}`, issues);
|
|
779
|
+
}
|
|
780
|
+
}
|
|
310
781
|
// -----------------------------------------------------------------------
|
|
311
782
|
// Node initialization
|
|
312
783
|
// -----------------------------------------------------------------------
|
|
784
|
+
/**
|
|
785
|
+
* Initialize every node's executor before any actor runs.
|
|
786
|
+
*
|
|
787
|
+
* A failure here aborts the run before `_processGraph`, so the actors that
|
|
788
|
+
* would normally call `finalize()` never start. Finalize the executors that
|
|
789
|
+
* did initialize, otherwise whatever they opened (python bridge handles,
|
|
790
|
+
* provider clients, file descriptors) leaks for the lifetime of the process.
|
|
791
|
+
* The failure is also re-thrown with the offending node's identity attached —
|
|
792
|
+
* a bare "connect ECONNREFUSED" gives no clue which node to fix.
|
|
793
|
+
*/
|
|
313
794
|
async _initializeGraph() {
|
|
795
|
+
const initialized = [];
|
|
314
796
|
for (const node of this._graph.nodes) {
|
|
315
|
-
const executor = this.
|
|
316
|
-
if (executor.initialize)
|
|
797
|
+
const executor = this._resolveExecutor(node);
|
|
798
|
+
if (!executor.initialize)
|
|
799
|
+
continue;
|
|
800
|
+
try {
|
|
317
801
|
await executor.initialize();
|
|
802
|
+
initialized.push(executor);
|
|
803
|
+
}
|
|
804
|
+
catch (err) {
|
|
805
|
+
await this._finalizeExecutors(initialized);
|
|
806
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
807
|
+
throw new Error(`Node "${node.name ?? node.id}" (${node.type}) failed to initialize: ${message}`, { cause: err });
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
/** Finalize executors, never letting one failure hide another. */
|
|
812
|
+
async _finalizeExecutors(executors) {
|
|
813
|
+
for (const executor of executors) {
|
|
814
|
+
if (!executor.finalize)
|
|
815
|
+
continue;
|
|
816
|
+
try {
|
|
817
|
+
await executor.finalize();
|
|
818
|
+
}
|
|
819
|
+
catch (err) {
|
|
820
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
821
|
+
log.warn("Executor finalize failed during initialization rollback", {
|
|
822
|
+
error: err instanceof Error ? err.message : String(err)
|
|
823
|
+
});
|
|
318
824
|
}
|
|
319
825
|
}
|
|
320
826
|
}
|
|
827
|
+
/** Resolve (and cache) the executor instance for a node. */
|
|
828
|
+
_resolveExecutor(node) {
|
|
829
|
+
let executor = this._executors.get(node.id);
|
|
830
|
+
if (!executor) {
|
|
831
|
+
executor = this._options.resolveExecutor(node);
|
|
832
|
+
this._executors.set(node.id, executor);
|
|
833
|
+
}
|
|
834
|
+
return executor;
|
|
835
|
+
}
|
|
321
836
|
// -----------------------------------------------------------------------
|
|
322
837
|
// Inbox initialization
|
|
323
838
|
// -----------------------------------------------------------------------
|
|
@@ -395,19 +910,64 @@ export class WorkflowRunner {
|
|
|
395
910
|
* After delivery, mark them as done (EOS) since input nodes produce exactly
|
|
396
911
|
* one value.
|
|
397
912
|
*/
|
|
913
|
+
/** Variable-channel name a Set Variable node publishes to (its `name` prop). */
|
|
914
|
+
_variableChannelName(node) {
|
|
915
|
+
const props = isObjectValue(node.properties) ? node.properties : {};
|
|
916
|
+
const raw = props.name;
|
|
917
|
+
return isString(raw) ? raw.trim() : "";
|
|
918
|
+
}
|
|
919
|
+
/**
|
|
920
|
+
* Tell the context how many Set Variable writers each channel has, before any
|
|
921
|
+
* actor runs. A channel with no writers then closes on first read so readers
|
|
922
|
+
* (Get Variable streams, Prompt awaits) end cleanly instead of hanging.
|
|
923
|
+
*/
|
|
924
|
+
_registerVariableChannels() {
|
|
925
|
+
const ctx = this._options.executionContext;
|
|
926
|
+
if (!ctx || !isCallable(ctx.registerChannelWriters)) {
|
|
927
|
+
return;
|
|
928
|
+
}
|
|
929
|
+
for (const node of this._graph.nodes) {
|
|
930
|
+
if (node.type !== SET_VARIABLE_NODE_TYPE) {
|
|
931
|
+
continue;
|
|
932
|
+
}
|
|
933
|
+
const name = this._variableChannelName(node);
|
|
934
|
+
if (name) {
|
|
935
|
+
ctx.registerChannelWriters(name, 1);
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
}
|
|
398
939
|
async _dispatchInputs(params) {
|
|
399
940
|
for (const node of this._graph.nodes) {
|
|
400
941
|
const incoming = this._graph.findDataEdges(node.id);
|
|
401
942
|
if (incoming.length > 0)
|
|
402
943
|
continue; // not an input node
|
|
944
|
+
// A node with an incoming control edge is run by its actor in
|
|
945
|
+
// _processGraph (which only skips actor-spawning when the node has
|
|
946
|
+
// neither data nor control edges). Skipping it here keeps the two
|
|
947
|
+
// predicates in parity — otherwise a controlled input node would be
|
|
948
|
+
// both one-shot dispatched here and spawned as an actor (double run).
|
|
949
|
+
const incomingControl = this._graph
|
|
950
|
+
.findIncomingEdges(node.id)
|
|
951
|
+
.filter(isControlEdge);
|
|
952
|
+
if (incomingControl.length > 0)
|
|
953
|
+
continue;
|
|
403
954
|
if (!this._isExternalInputNode(node))
|
|
404
955
|
continue;
|
|
405
956
|
const inputName = this._getExternalInputName(node);
|
|
406
|
-
const properties = node.properties
|
|
957
|
+
const properties = isObjectValue(node.properties)
|
|
407
958
|
? node.properties
|
|
408
959
|
: {};
|
|
409
|
-
const hasRuntimeParam =
|
|
410
|
-
const hasDefaultValue =
|
|
960
|
+
const hasRuntimeParam = hasDefinedOwnProperty(params, inputName);
|
|
961
|
+
const hasDefaultValue = hasDefinedOwnProperty(properties, "value");
|
|
962
|
+
// A streaming input keeps its edges open for pushInputValue().
|
|
963
|
+
if (node.is_streaming_output) {
|
|
964
|
+
for (const edge of this._graph.findOutgoingEdges(node.id)) {
|
|
965
|
+
if (!isDataEdge(edge))
|
|
966
|
+
continue;
|
|
967
|
+
this._openExternalStreamEdges.add(edge.id ??
|
|
968
|
+
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle));
|
|
969
|
+
}
|
|
970
|
+
}
|
|
411
971
|
// Streaming output input nodes (e.g. RealtimeAudioInput) should NOT
|
|
412
972
|
// push empty defaults — real data will arrive later via pushInputValue().
|
|
413
973
|
// Non-streaming inputs must push their default so downstream nodes can run.
|
|
@@ -416,13 +976,48 @@ export class WorkflowRunner {
|
|
|
416
976
|
continue;
|
|
417
977
|
}
|
|
418
978
|
const value = hasRuntimeParam ? params[inputName] : properties.value;
|
|
979
|
+
// Run the node's own process() so transforming input nodes (e.g.
|
|
980
|
+
// DocumentFileInput building a DocumentRef, StringInput applying
|
|
981
|
+
// max_length, MessageDeconstructor splitting a message) emit their
|
|
982
|
+
// declared per-handle outputs instead of leaking the raw value to
|
|
983
|
+
// every edge. Uses the cached executor instance initialized in
|
|
984
|
+
// _initializeGraph. Test doubles whose process() returns an empty
|
|
985
|
+
// record fall back to raw-value dispatch per handle below; a real
|
|
986
|
+
// process() failure fails the run rather than leaking the raw value.
|
|
987
|
+
const executor = this._resolveExecutor(node);
|
|
988
|
+
let nodeOutputs;
|
|
989
|
+
try {
|
|
990
|
+
nodeOutputs = await executor.process({ value }, this._options.executionContext);
|
|
991
|
+
}
|
|
992
|
+
catch (err) {
|
|
993
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
994
|
+
throw new Error(`Input node "${node.name ?? node.id}" (${node.type}) failed: ${message}`);
|
|
995
|
+
}
|
|
996
|
+
// Raw-value fallback only when process() produced no defined output at
|
|
997
|
+
// all (the documented test-double case, incl. `{}`). Once the record
|
|
998
|
+
// carries any real output, a handle it legitimately omits (e.g. an input
|
|
999
|
+
// with no attachments) stays silent instead of leaking the raw input
|
|
1000
|
+
// value onto that edge. §6. Keyed on `!== undefined` to match the
|
|
1001
|
+
// per-handle check below. The EOS pass below still closes every edge so
|
|
1002
|
+
// downstream nodes complete.
|
|
1003
|
+
const outputsEmpty = !Object.values(nodeOutputs).some((v) => v !== undefined);
|
|
419
1004
|
const outgoing = this._graph
|
|
420
1005
|
.findOutgoingEdges(node.id)
|
|
421
1006
|
.filter(isDataEdge);
|
|
422
1007
|
for (const edge of outgoing) {
|
|
1008
|
+
const hasHandleValue = Object.hasOwn(nodeOutputs, edge.sourceHandle) &&
|
|
1009
|
+
nodeOutputs[edge.sourceHandle] !== undefined;
|
|
1010
|
+
if (!outputsEmpty && !hasHandleValue)
|
|
1011
|
+
continue;
|
|
423
1012
|
const targetInbox = this._inboxes.get(edge.target);
|
|
424
1013
|
if (targetInbox) {
|
|
425
|
-
|
|
1014
|
+
const handleValue = hasHandleValue
|
|
1015
|
+
? nodeOutputs[edge.sourceHandle]
|
|
1016
|
+
: value;
|
|
1017
|
+
await targetInbox.put(edge.targetHandle, handleValue, {
|
|
1018
|
+
source_edge_id: edge.id ??
|
|
1019
|
+
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle)
|
|
1020
|
+
});
|
|
426
1021
|
}
|
|
427
1022
|
this._incrementEdgeCounter(edge);
|
|
428
1023
|
}
|
|
@@ -451,7 +1046,23 @@ export class WorkflowRunner {
|
|
|
451
1046
|
* upstream actors produce data.
|
|
452
1047
|
*/
|
|
453
1048
|
async _processGraph() {
|
|
1049
|
+
// Before any actor can escalate, the supervisor gets its read-only view.
|
|
1050
|
+
// A handle that throws here is a broken supervisor, and a broken
|
|
1051
|
+
// supervisor must never be worse for the run than no supervisor: it
|
|
1052
|
+
// proceeds without a reader and its decisions degrade to `fail`.
|
|
1053
|
+
try {
|
|
1054
|
+
this._supervisor?.attach?.(this._runStateReader());
|
|
1055
|
+
}
|
|
1056
|
+
catch (error) {
|
|
1057
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
1058
|
+
log.warn("Supervisor attach failed; running without a run-state view", {
|
|
1059
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1060
|
+
});
|
|
1061
|
+
}
|
|
1062
|
+
this._installQuiescenceDetection();
|
|
454
1063
|
const actorPromises = [];
|
|
1064
|
+
/** Parallel to `actorPromises` — maps a settled index back to its node. */
|
|
1065
|
+
const actorNodeIds = [];
|
|
455
1066
|
for (const node of this._graph.nodes) {
|
|
456
1067
|
// Skip input-only nodes that have no incoming edges
|
|
457
1068
|
// (they were already handled in _dispatchInputs)
|
|
@@ -465,15 +1076,7 @@ export class WorkflowRunner {
|
|
|
465
1076
|
continue; // pure input node, already dispatched
|
|
466
1077
|
}
|
|
467
1078
|
const inbox = this._inboxes.get(node.id);
|
|
468
|
-
const executor = this.
|
|
469
|
-
// Compute sticky handles: handles fed by non-streaming edges
|
|
470
|
-
// are sticky from the start (Python parity: _analyze_streaming).
|
|
471
|
-
const stickyHandles = new Set();
|
|
472
|
-
for (const edge of incoming) {
|
|
473
|
-
if (!this.edgeStreams(edge)) {
|
|
474
|
-
stickyHandles.add(edge.targetHandle);
|
|
475
|
-
}
|
|
476
|
-
}
|
|
1079
|
+
const executor = this._resolveExecutor(node);
|
|
477
1080
|
// Build control context for controller nodes (Python parity:
|
|
478
1081
|
// _is_controller / _build_control_context). This tells the node
|
|
479
1082
|
// which downstream nodes it controls and their available properties.
|
|
@@ -482,30 +1085,62 @@ export class WorkflowRunner {
|
|
|
482
1085
|
node,
|
|
483
1086
|
inbox,
|
|
484
1087
|
executor,
|
|
485
|
-
sendOutputs: async (nodeId, outputs) => {
|
|
486
|
-
await this._sendMessages(nodeId, outputs);
|
|
1088
|
+
sendOutputs: async (nodeId, outputs, hints) => {
|
|
1089
|
+
await this._sendMessages(nodeId, outputs, hints);
|
|
487
1090
|
},
|
|
488
1091
|
emitMessage: (msg) => {
|
|
489
1092
|
this._emit(msg);
|
|
490
1093
|
},
|
|
491
1094
|
executionContext: this._options.executionContext,
|
|
492
|
-
|
|
493
|
-
controlContext
|
|
1095
|
+
listInputHandles: this._multiEdgeListInputs.get(node.id),
|
|
1096
|
+
controlContext,
|
|
1097
|
+
correlation: this._correlation?.nodes.get(node.id),
|
|
1098
|
+
cancelSignal: this._abortController.signal,
|
|
1099
|
+
signalSlotEos: (sourceNodeId, slot) => this._signalSlotEos(sourceNodeId, slot),
|
|
1100
|
+
supervisor: this._supervisor,
|
|
1101
|
+
onIntervention: (intervention) => this._interventions.push(intervention)
|
|
494
1102
|
});
|
|
495
|
-
|
|
1103
|
+
actorNodeIds.push(node.id);
|
|
1104
|
+
this._liveActors++;
|
|
1105
|
+
this._liveActorIds.add(node.id);
|
|
1106
|
+
actorPromises.push(actor
|
|
1107
|
+
.run()
|
|
1108
|
+
.then(async (result) => {
|
|
1109
|
+
// Nothing will read this inbox again. Wake any upstream actor parked
|
|
1110
|
+
// on a full buffer so it can finish instead of waiting forever for a
|
|
1111
|
+
// consumer that is gone.
|
|
1112
|
+
inbox.releaseBackpressure();
|
|
1113
|
+
if (result.error !== undefined) {
|
|
1114
|
+
this._nodeErrors.set(node.id, result.error);
|
|
1115
|
+
}
|
|
496
1116
|
// After actor completes, send EOS to all downstream inboxes
|
|
497
1117
|
await this._sendEOS(node.id);
|
|
498
|
-
//
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
1118
|
+
// A Set Variable writer finished — when the last writer for a channel
|
|
1119
|
+
// is done, the context closes it so readers (Get Variable / Prompt)
|
|
1120
|
+
// drain and end instead of waiting forever.
|
|
1121
|
+
if (node.type === SET_VARIABLE_NODE_TYPE) {
|
|
1122
|
+
const channelName = this._variableChannelName(node);
|
|
1123
|
+
if (channelName) {
|
|
1124
|
+
this._options.executionContext?.markChannelWriterDone?.(channelName);
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
// The actor's run loop is gone — it can no longer answer control
|
|
1128
|
+
// events. Mark it so future sendControlEvent calls reject fast
|
|
1129
|
+
// rather than hang, and reject any response still waiting on it
|
|
1130
|
+
// (the actor finished without producing the awaited output, e.g.
|
|
1131
|
+
// it errored mid-burst).
|
|
1132
|
+
this._completedNodes.add(node.id);
|
|
1133
|
+
const pendingQueue = this._pendingControlResponses.get(node.id);
|
|
1134
|
+
if (pendingQueue) {
|
|
1135
|
+
this._pendingControlResponses.delete(node.id);
|
|
1136
|
+
for (const pending of pendingQueue) {
|
|
1137
|
+
pending.reject(new Error(result.error ??
|
|
1138
|
+
`Controlled node ${node.id} completed without responding`));
|
|
504
1139
|
}
|
|
505
1140
|
}
|
|
506
1141
|
// If this is an output node, collect the result
|
|
507
1142
|
if (this._isOutputNode(node)) {
|
|
508
|
-
const name =
|
|
1143
|
+
const name = this._outputCollectionKey(node);
|
|
509
1144
|
if (!this._outputs.has(name)) {
|
|
510
1145
|
this._outputs.set(name, []);
|
|
511
1146
|
}
|
|
@@ -515,17 +1150,140 @@ export class WorkflowRunner {
|
|
|
515
1150
|
}
|
|
516
1151
|
}
|
|
517
1152
|
}
|
|
1153
|
+
})
|
|
1154
|
+
// Counts the actor as live until its completion handling (EOS
|
|
1155
|
+
// routing, output collection) is done too — that work can still emit
|
|
1156
|
+
// messages, so an actor is not "gone" before it finishes.
|
|
1157
|
+
.finally(() => {
|
|
1158
|
+
this._liveActors--;
|
|
1159
|
+
this._liveActorIds.delete(node.id);
|
|
1160
|
+
// An actor that exits instead of parking may have been the last
|
|
1161
|
+
// busy one.
|
|
1162
|
+
this._scheduleQuiescenceCheck?.();
|
|
518
1163
|
}));
|
|
519
1164
|
}
|
|
520
|
-
// Wait for
|
|
521
|
-
|
|
1165
|
+
// Wait for every actor, including post-completion routing. `allSettled`
|
|
1166
|
+
// rather than `all`: a throw in one actor's completion handler (EOS
|
|
1167
|
+
// routing, channel bookkeeping, a message-transport failure) must not
|
|
1168
|
+
// return the run while its siblings are still executing — orphaned actors
|
|
1169
|
+
// would keep writing to inboxes and emitting messages after the runner
|
|
1170
|
+
// reported a terminal status.
|
|
1171
|
+
const settled = await Promise.allSettled(actorPromises);
|
|
1172
|
+
for (const [index, outcome] of settled.entries()) {
|
|
1173
|
+
if (outcome.status !== "rejected")
|
|
1174
|
+
continue;
|
|
1175
|
+
const nodeId = actorNodeIds[index];
|
|
1176
|
+
const message = outcome.reason instanceof Error
|
|
1177
|
+
? outcome.reason.message
|
|
1178
|
+
: String(outcome.reason);
|
|
1179
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
1180
|
+
log.error("Actor completion handling failed", { nodeId, error: message });
|
|
1181
|
+
if (!this._nodeErrors.has(nodeId)) {
|
|
1182
|
+
this._nodeErrors.set(nodeId, message);
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
// Backstop: release any reader still waiting on a channel (e.g. a writer
|
|
1186
|
+
// that errored before publishing). Non-cyclic graphs are already closed by
|
|
1187
|
+
// markChannelWriterDone above.
|
|
1188
|
+
this._options.executionContext?.closeAllChannels?.();
|
|
522
1189
|
// Check for in-flight messages after all actors complete (Python parity: _check_pending_inbox_work)
|
|
523
1190
|
const pendingNodes = this._checkPendingInboxWork();
|
|
524
1191
|
if (pendingNodes.length > 0) {
|
|
525
|
-
|
|
1192
|
+
if (this._options.strict && !this._cancelled) {
|
|
1193
|
+
throw new Error(`Strict mode: pending inbox work detected after all actors ` +
|
|
1194
|
+
`completed for node(s): ${pendingNodes.join(", ")}`);
|
|
1195
|
+
}
|
|
1196
|
+
log.warn(
|
|
1197
|
+
// Stryker disable next-line StringLiteral: diagnostic log args only
|
|
1198
|
+
"Pending inbox work detected after all actors completed — possible data loss",
|
|
1199
|
+
// Stryker disable next-line ObjectLiteral: diagnostic log args only
|
|
1200
|
+
{
|
|
526
1201
|
pendingNodes
|
|
527
1202
|
});
|
|
528
1203
|
}
|
|
1204
|
+
// Check for controlled-node control events whose response never arrived
|
|
1205
|
+
// (the target actor completed — or was never reachable — while a
|
|
1206
|
+
// `sendControlEvent` waiter was still registered for it). Every
|
|
1207
|
+
// completion path (actor completion handler, the completion race guard
|
|
1208
|
+
// in `sendControlEvent`) rejects its own waiters, so a non-empty queue
|
|
1209
|
+
// here means a waiter was registered for a node whose actor never ran at
|
|
1210
|
+
// all, or another gap in that bookkeeping — either way, "zero pending
|
|
1211
|
+
// control responses" (§6) is violated.
|
|
1212
|
+
const pendingControlNodes = [...this._pendingControlResponses.entries()]
|
|
1213
|
+
.filter(([, queue]) => queue.length > 0)
|
|
1214
|
+
.map(([nodeId]) => nodeId);
|
|
1215
|
+
if (pendingControlNodes.length > 0) {
|
|
1216
|
+
if (this._options.strict && !this._cancelled) {
|
|
1217
|
+
throw new Error(`Strict mode: pending control-event responses never resolved for ` +
|
|
1218
|
+
`node(s): ${pendingControlNodes.join(", ")}`);
|
|
1219
|
+
}
|
|
1220
|
+
log.warn(
|
|
1221
|
+
// Stryker disable next-line StringLiteral: diagnostic log args only
|
|
1222
|
+
"Pending control-event responses after all actors completed — possible hang",
|
|
1223
|
+
// Stryker disable next-line ObjectLiteral: diagnostic log args only
|
|
1224
|
+
{
|
|
1225
|
+
pendingControlNodes
|
|
1226
|
+
});
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
/**
|
|
1230
|
+
* Detect a quiescent graph for Loop nodes (docs/workflow-loops.md).
|
|
1231
|
+
*
|
|
1232
|
+
* A loop body can finish an iteration without feeding anything back (an
|
|
1233
|
+
* `If` routes the value elsewhere, a filter drops it). EOS cannot announce
|
|
1234
|
+
* that, because the body's EOS waits for the loop to close. So when every
|
|
1235
|
+
* live actor is parked on its inbox, no external stream is open, and some
|
|
1236
|
+
* inbox activity happened since the last notice, each Loop is told the
|
|
1237
|
+
* graph is quiescent and ends the runs still waiting for feedback. A parked
|
|
1238
|
+
* actor is not inside a provider call, a timer, or a write, so nothing can
|
|
1239
|
+
* still produce the value those runs wait for.
|
|
1240
|
+
*
|
|
1241
|
+
* Installed only for graphs that contain a Loop node.
|
|
1242
|
+
*/
|
|
1243
|
+
_installQuiescenceDetection() {
|
|
1244
|
+
const loopIds = this._graph.nodes
|
|
1245
|
+
.filter((n) => n.type === LOOP_NODE_TYPE)
|
|
1246
|
+
.map((n) => n.id);
|
|
1247
|
+
if (loopIds.length === 0)
|
|
1248
|
+
return;
|
|
1249
|
+
let checkScheduled = false;
|
|
1250
|
+
let activitySinceNotice = true;
|
|
1251
|
+
const check = () => {
|
|
1252
|
+
checkScheduled = false;
|
|
1253
|
+
if (this._cancelled || !activitySinceNotice)
|
|
1254
|
+
return;
|
|
1255
|
+
if (this._openExternalStreamEdges.size > 0)
|
|
1256
|
+
return;
|
|
1257
|
+
const liveLoops = loopIds.filter((id) => this._liveActorIds.has(id));
|
|
1258
|
+
if (liveLoops.length === 0)
|
|
1259
|
+
return;
|
|
1260
|
+
for (const id of this._liveActorIds) {
|
|
1261
|
+
if (!this._inboxes.get(id)?.isParked())
|
|
1262
|
+
return;
|
|
1263
|
+
}
|
|
1264
|
+
activitySinceNotice = false;
|
|
1265
|
+
for (const id of liveLoops) {
|
|
1266
|
+
this._inboxes.get(id).notifyQuiescent();
|
|
1267
|
+
}
|
|
1268
|
+
};
|
|
1269
|
+
const schedule = () => {
|
|
1270
|
+
if (checkScheduled)
|
|
1271
|
+
return;
|
|
1272
|
+
checkScheduled = true;
|
|
1273
|
+
// After pending I/O and microtasks: an actor that is about to resume
|
|
1274
|
+
// is no longer parked by the time the check runs.
|
|
1275
|
+
setTimeout(check, 0);
|
|
1276
|
+
};
|
|
1277
|
+
this._scheduleQuiescenceCheck = schedule;
|
|
1278
|
+
const observer = {
|
|
1279
|
+
onPark: schedule,
|
|
1280
|
+
onActivity: () => {
|
|
1281
|
+
activitySinceNotice = true;
|
|
1282
|
+
}
|
|
1283
|
+
};
|
|
1284
|
+
for (const inbox of this._inboxes.values()) {
|
|
1285
|
+
inbox.setObserver(observer);
|
|
1286
|
+
}
|
|
529
1287
|
}
|
|
530
1288
|
// -----------------------------------------------------------------------
|
|
531
1289
|
// Output routing (send_messages equivalent)
|
|
@@ -535,9 +1293,16 @@ export class WorkflowRunner {
|
|
|
535
1293
|
* For control edges: route control events to the __control__ handle.
|
|
536
1294
|
* For data edges: route to the named target handle.
|
|
537
1295
|
*/
|
|
538
|
-
async _sendMessages(sourceNodeId, outputs) {
|
|
1296
|
+
async _sendMessages(sourceNodeId, outputs, routingHints = {}) {
|
|
539
1297
|
if (this._cancelled)
|
|
540
1298
|
return;
|
|
1299
|
+
if (routingHints.skipInvocation) {
|
|
1300
|
+
this._skipInvocationOutputs(sourceNodeId, routingHints.invocationLineage ?? {});
|
|
1301
|
+
return;
|
|
1302
|
+
}
|
|
1303
|
+
if (this._supervisor) {
|
|
1304
|
+
this._recordNodeOutput(sourceNodeId, outputs, routingHints.invocationLineage);
|
|
1305
|
+
}
|
|
541
1306
|
// Handle __control_output__ from controller nodes (Python parity:
|
|
542
1307
|
// send_messages wraps __control_output__ in RunEvent and routes to
|
|
543
1308
|
// all controlled nodes via control edges).
|
|
@@ -575,19 +1340,14 @@ export class WorkflowRunner {
|
|
|
575
1340
|
// recognises them. (Python parity: send_messages wraps
|
|
576
1341
|
// __control_output__ in RunEvent.)
|
|
577
1342
|
let controlEvent;
|
|
578
|
-
if (
|
|
579
|
-
value !== null &&
|
|
580
|
-
"event_type" in value &&
|
|
581
|
-
typeof value.event_type === "string") {
|
|
1343
|
+
if (isControlEventValue(value)) {
|
|
582
1344
|
controlEvent = value;
|
|
583
1345
|
}
|
|
584
|
-
else if (
|
|
1346
|
+
else if (isObjectValue(value)) {
|
|
585
1347
|
// Raw property dict — wrap as RunEvent
|
|
586
1348
|
const raw = value;
|
|
587
1349
|
// Support nested {properties: {...}} shape from LLM output
|
|
588
|
-
const properties = "properties" in raw &&
|
|
589
|
-
typeof raw.properties === "object" &&
|
|
590
|
-
raw.properties !== null
|
|
1350
|
+
const properties = "properties" in raw && isObjectValue(raw.properties)
|
|
591
1351
|
? raw.properties
|
|
592
1352
|
: raw;
|
|
593
1353
|
controlEvent = { event_type: "run", properties };
|
|
@@ -595,15 +1355,39 @@ export class WorkflowRunner {
|
|
|
595
1355
|
else {
|
|
596
1356
|
continue; // skip non-object values
|
|
597
1357
|
}
|
|
598
|
-
await targetInbox.put("__control__", controlEvent);
|
|
599
|
-
// Track that this edge has routed at least one event
|
|
600
1358
|
const ctrlEdgeId = edge.id ??
|
|
601
|
-
|
|
602
|
-
|
|
1359
|
+
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle);
|
|
1360
|
+
await targetInbox.put("__control__", controlEvent, {
|
|
1361
|
+
source_edge_id: ctrlEdgeId
|
|
1362
|
+
});
|
|
1363
|
+
continue;
|
|
1364
|
+
}
|
|
1365
|
+
// Drop signal: send `lineage_done` to the downstream inbox instead of
|
|
1366
|
+
// delivering a value. §5. The actor sets `lineageDoneSlots` when a
|
|
1367
|
+
// stream node calls `outputs.drop()`.
|
|
1368
|
+
if (routingHints.lineageDoneSlots?.has(edge.sourceHandle)) {
|
|
1369
|
+
const targetInboxDrop = this._inboxes.get(edge.target);
|
|
1370
|
+
if (!targetInboxDrop)
|
|
1371
|
+
continue;
|
|
1372
|
+
const lineage = routingHints.perSlotLineage?.[edge.sourceHandle] ?? {};
|
|
1373
|
+
const edgeId = edge.id ??
|
|
1374
|
+
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle);
|
|
1375
|
+
// Use the downstream input handle's static scope so the projection
|
|
1376
|
+
// keys match the actor's bucket key on that handle.
|
|
1377
|
+
const downstreamScope = this._correlation?.nodes
|
|
1378
|
+
.get(edge.target)
|
|
1379
|
+
?.inputs.get(edge.targetHandle)?.scope ?? [];
|
|
1380
|
+
targetInboxDrop.signalLineageDone(edge.targetHandle, {
|
|
1381
|
+
type: "lineage_done",
|
|
1382
|
+
source_edge_id: edgeId,
|
|
1383
|
+
output: edge.sourceHandle,
|
|
1384
|
+
lineage
|
|
1385
|
+
}, downstreamScope);
|
|
603
1386
|
continue;
|
|
604
1387
|
}
|
|
605
1388
|
const value = outputs[edge.sourceHandle];
|
|
606
1389
|
if (value === undefined) {
|
|
1390
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
607
1391
|
log.debug("_sendMessages skip edge (no matching output)", {
|
|
608
1392
|
sourceNodeId,
|
|
609
1393
|
sourceHandle: edge.sourceHandle,
|
|
@@ -613,52 +1397,159 @@ export class WorkflowRunner {
|
|
|
613
1397
|
}
|
|
614
1398
|
const targetInbox = this._inboxes.get(edge.target);
|
|
615
1399
|
if (!targetInbox) {
|
|
1400
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
616
1401
|
log.debug("_sendMessages skip edge (no target inbox)", {
|
|
617
1402
|
target: edge.target
|
|
618
1403
|
});
|
|
619
1404
|
continue;
|
|
620
1405
|
}
|
|
1406
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
621
1407
|
log.debug("_sendMessages delivering", {
|
|
622
1408
|
sourceNodeId,
|
|
623
1409
|
sourceHandle: edge.sourceHandle,
|
|
624
1410
|
target: edge.target,
|
|
625
1411
|
targetHandle: edge.targetHandle
|
|
626
1412
|
});
|
|
627
|
-
|
|
1413
|
+
const edgeId = edge.id ??
|
|
1414
|
+
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle);
|
|
1415
|
+
const lineage = routingHints.perSlotLineage?.[edge.sourceHandle] ??
|
|
1416
|
+
routingHints.invocationLineage;
|
|
1417
|
+
await targetInbox.put(edge.targetHandle, value, {
|
|
1418
|
+
source_edge_id: edgeId,
|
|
1419
|
+
correlation_lineage: lineage
|
|
1420
|
+
});
|
|
628
1421
|
this._incrementEdgeCounter(edge);
|
|
629
1422
|
}
|
|
630
1423
|
// Emit output_update for each produced output handle.
|
|
631
1424
|
// Skip constant and input nodes: the client already holds their value
|
|
632
1425
|
// as a property (or supplied it as a runtime param), so re-sending it
|
|
633
1426
|
// (often a large image/audio payload) is redundant.
|
|
1427
|
+
// Also skip handles with outgoing data edges: the value travels to its
|
|
1428
|
+
// consumer on the edge, and clients only display terminal (unconnected)
|
|
1429
|
+
// handles — Output/Preview nodes and dangling outputs. Without this,
|
|
1430
|
+
// every intermediate module of a streaming patch firehoses the client
|
|
1431
|
+
// (~50 output_updates/s per handle for realtime audio). Nodes whose
|
|
1432
|
+
// output_updates are part of their UI contract even when patched onward
|
|
1433
|
+
// (e.g. the realtime AudioOutput monitor) opt out via the
|
|
1434
|
+
// `always_emit_output_updates` descriptor flag.
|
|
634
1435
|
const sourceNode = this._graph.findNode(sourceNodeId);
|
|
635
1436
|
if (sourceNode &&
|
|
636
1437
|
!sourceNode.type.startsWith("nodetool.constant.") &&
|
|
637
1438
|
!sourceNode.type.startsWith("nodetool.input.")) {
|
|
1439
|
+
const alwaysEmit = Boolean(sourceNode
|
|
1440
|
+
.always_emit_output_updates);
|
|
638
1441
|
const declaredOutputs = sourceNode.outputs ?? {};
|
|
639
1442
|
for (const [handle, value] of Object.entries(outputs)) {
|
|
640
1443
|
if (value === undefined)
|
|
641
1444
|
continue;
|
|
642
1445
|
if (handle === "__control__" || handle === "__control_output__")
|
|
643
1446
|
continue;
|
|
1447
|
+
if (!alwaysEmit &&
|
|
1448
|
+
this._graph.findEdges(sourceNodeId, handle).some(isDataEdge))
|
|
1449
|
+
continue;
|
|
1450
|
+
const outputName = clientFacingOutputName(sourceNode, handle);
|
|
644
1451
|
this._emit({
|
|
645
1452
|
type: "output_update",
|
|
646
1453
|
node_id: sourceNodeId,
|
|
647
1454
|
node_name: sourceNode.name ?? sourceNodeId,
|
|
648
|
-
output_name:
|
|
1455
|
+
output_name: outputName,
|
|
649
1456
|
value,
|
|
650
1457
|
output_type: declaredOutputs[handle] ?? "any",
|
|
651
|
-
metadata: {}
|
|
1458
|
+
metadata: {},
|
|
1459
|
+
// RFC §6: live display feed defaults to "append" (chunk-concatenate),
|
|
1460
|
+
// matching today's hardcoded consumer behavior. Artifacts travel on
|
|
1461
|
+
// generation_complete, so this is display-only.
|
|
1462
|
+
disposition: "append"
|
|
652
1463
|
});
|
|
653
1464
|
}
|
|
654
1465
|
}
|
|
655
|
-
// Resolve pending sendControlEvent promise
|
|
656
|
-
const
|
|
657
|
-
if (
|
|
658
|
-
|
|
1466
|
+
// Resolve the oldest pending sendControlEvent promise for this node.
|
|
1467
|
+
const pendingQueue = this._pendingControlResponses.get(sourceNodeId);
|
|
1468
|
+
if (pendingQueue && pendingQueue.length > 0) {
|
|
1469
|
+
const pending = pendingQueue.shift();
|
|
1470
|
+
if (pendingQueue.length === 0) {
|
|
1471
|
+
this._pendingControlResponses.delete(sourceNodeId);
|
|
1472
|
+
}
|
|
659
1473
|
pending.resolve(outputs);
|
|
660
1474
|
}
|
|
661
1475
|
}
|
|
1476
|
+
/**
|
|
1477
|
+
* A supervisor `skip`: retire one invocation's outputs without emitting.
|
|
1478
|
+
*
|
|
1479
|
+
* Plain non-emission is not enough. Siblings already buffered against the
|
|
1480
|
+
* skipped key would sit at a downstream join forever, and an invocation of an
|
|
1481
|
+
* iteration node would have opened child scopes an aggregate is waiting to
|
|
1482
|
+
* see closed. So both signals go out on every outgoing data edge: the
|
|
1483
|
+
* per-lineage `lineage_done` that unblocks joins, and a `lineage_scope_closed`
|
|
1484
|
+
* per child root the invocation could have minted. Design §5.2.
|
|
1485
|
+
*/
|
|
1486
|
+
_skipInvocationOutputs(sourceNodeId, lineage) {
|
|
1487
|
+
const nodeAnalysis = this._correlation?.nodes.get(sourceNodeId);
|
|
1488
|
+
for (const edge of this._graph.findOutgoingEdges(sourceNodeId)) {
|
|
1489
|
+
if (isControlEdge(edge))
|
|
1490
|
+
continue;
|
|
1491
|
+
const targetInbox = this._inboxes.get(edge.target);
|
|
1492
|
+
if (!targetInbox)
|
|
1493
|
+
continue;
|
|
1494
|
+
const edgeId = edge.id ??
|
|
1495
|
+
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle);
|
|
1496
|
+
for (const root of nodeAnalysis?.outputs.get(edge.sourceHandle)
|
|
1497
|
+
?.possibleChildRoots ?? []) {
|
|
1498
|
+
targetInbox.signalLineageScopeClosed(edge.targetHandle, {
|
|
1499
|
+
type: "lineage_scope_closed",
|
|
1500
|
+
source_edge_id: edgeId,
|
|
1501
|
+
output: edge.sourceHandle,
|
|
1502
|
+
parent_lineage: lineage,
|
|
1503
|
+
closed_root: root
|
|
1504
|
+
},
|
|
1505
|
+
// The parent scope of a minted child root is the invocation scope
|
|
1506
|
+
// the source node fired at — the scope this lineage projects onto.
|
|
1507
|
+
nodeAnalysis?.invocationScope ?? []);
|
|
1508
|
+
}
|
|
1509
|
+
targetInbox.signalLineageDone(edge.targetHandle, {
|
|
1510
|
+
type: "lineage_done",
|
|
1511
|
+
source_edge_id: edgeId,
|
|
1512
|
+
output: edge.sourceHandle,
|
|
1513
|
+
lineage
|
|
1514
|
+
}, this._correlation?.nodes.get(edge.target)?.inputs.get(edge.targetHandle)
|
|
1515
|
+
?.scope ?? []);
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
/**
|
|
1519
|
+
* Mark the source of one data edge done on its target inbox at most once.
|
|
1520
|
+
* `markSourceDone` decrements an upstream counter, so calling it twice for
|
|
1521
|
+
* the same edge would over-decrement and could prematurely close a handle
|
|
1522
|
+
* that still has other open upstreams. Both early per-slot EOS
|
|
1523
|
+
* (`_signalSlotEos`) and the final `_sendEOS` route through this guard.
|
|
1524
|
+
* Returns true if the mark was applied (first time), false if skipped.
|
|
1525
|
+
*/
|
|
1526
|
+
_markEdgeSourceDoneOnce(edge) {
|
|
1527
|
+
const edgeId = edge.id ??
|
|
1528
|
+
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle);
|
|
1529
|
+
if (this._eosSentEdges.has(edgeId))
|
|
1530
|
+
return false;
|
|
1531
|
+
this._eosSentEdges.add(edgeId);
|
|
1532
|
+
const targetInbox = this._inboxes.get(edge.target);
|
|
1533
|
+
if (targetInbox) {
|
|
1534
|
+
targetInbox.markSourceDone(edge.targetHandle);
|
|
1535
|
+
}
|
|
1536
|
+
return true;
|
|
1537
|
+
}
|
|
1538
|
+
/**
|
|
1539
|
+
* Signal early end-of-stream for a single output slot of a node, in
|
|
1540
|
+
* response to `outputs.complete(slot)`. Marks every outgoing edge of
|
|
1541
|
+
* `(nodeId, slot)` done on its target inbox immediately, rather than
|
|
1542
|
+
* waiting for the actor to finish. Idempotent with `_sendEOS` via the
|
|
1543
|
+
* `_eosSentEdges` guard so a handle's upstream count is never
|
|
1544
|
+
* double-decremented.
|
|
1545
|
+
*/
|
|
1546
|
+
_signalSlotEos(nodeId, slot) {
|
|
1547
|
+
for (const edge of this._graph.findEdges(nodeId, slot)) {
|
|
1548
|
+
if (isControlEdge(edge))
|
|
1549
|
+
continue;
|
|
1550
|
+
this._markEdgeSourceDoneOnce(edge);
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
662
1553
|
/**
|
|
663
1554
|
* Signal EOS on all outgoing edges of a completed node.
|
|
664
1555
|
* For control edges: close the __control__ handle of the target.
|
|
@@ -666,6 +1557,11 @@ export class WorkflowRunner {
|
|
|
666
1557
|
*/
|
|
667
1558
|
async _sendEOS(nodeId) {
|
|
668
1559
|
const outgoing = this._graph.findOutgoingEdges(nodeId);
|
|
1560
|
+
// _initializeInboxes counts one __control__ upstream per unique
|
|
1561
|
+
// controller, so decrement once per target — not once per control edge.
|
|
1562
|
+
// Parallel control edges to the same target would otherwise drive the
|
|
1563
|
+
// count to zero while other controllers are still running.
|
|
1564
|
+
const controlTargetsDone = new Set();
|
|
669
1565
|
for (const edge of outgoing) {
|
|
670
1566
|
if (isControlEdge(edge)) {
|
|
671
1567
|
// Always mark __control__ source done when the controller finishes,
|
|
@@ -673,21 +1569,49 @@ export class WorkflowRunner {
|
|
|
673
1569
|
// controlled nodes waiting on iterInput("__control__") regardless
|
|
674
1570
|
// of whether events were routed through the edge or via the manual
|
|
675
1571
|
// sendControlEvent() / dispatchControlEvent() APIs.
|
|
1572
|
+
if (controlTargetsDone.has(edge.target))
|
|
1573
|
+
continue;
|
|
1574
|
+
controlTargetsDone.add(edge.target);
|
|
676
1575
|
const targetInbox = this._inboxes.get(edge.target);
|
|
677
1576
|
if (targetInbox) {
|
|
678
1577
|
targetInbox.markSourceDone("__control__");
|
|
679
1578
|
}
|
|
680
1579
|
continue;
|
|
681
1580
|
}
|
|
1581
|
+
// Mark the source done at most once per edge — early per-slot EOS
|
|
1582
|
+
// (`outputs.complete`) may already have marked it. The rest of the
|
|
1583
|
+
// EOS work (lineage_scope_closed, edge_update) is unconditional.
|
|
1584
|
+
this._markEdgeSourceDoneOnce(edge);
|
|
682
1585
|
const targetInbox = this._inboxes.get(edge.target);
|
|
683
|
-
if (targetInbox) {
|
|
684
|
-
targetInbox.markSourceDone(edge.targetHandle);
|
|
685
|
-
}
|
|
686
1586
|
const edgeId = edge.id ??
|
|
687
|
-
|
|
1587
|
+
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle);
|
|
1588
|
+
// §6 — at source EOS, synthesize `lineage_scope_closed` for every
|
|
1589
|
+
// possible child root the edge could have produced. Downstream
|
|
1590
|
+
// aggregators rely on receiving a close even when zero child tokens
|
|
1591
|
+
// were minted.
|
|
1592
|
+
if (this._correlation && targetInbox) {
|
|
1593
|
+
const nodeAnalysis = this._correlation.nodes.get(nodeId);
|
|
1594
|
+
const outputAnalysis = nodeAnalysis?.outputs.get(edge.sourceHandle);
|
|
1595
|
+
if (outputAnalysis) {
|
|
1596
|
+
for (const root of outputAnalysis.possibleChildRoots) {
|
|
1597
|
+
targetInbox.signalLineageScopeClosed(edge.targetHandle, {
|
|
1598
|
+
type: "lineage_scope_closed",
|
|
1599
|
+
source_edge_id: edgeId,
|
|
1600
|
+
output: edge.sourceHandle,
|
|
1601
|
+
parent_lineage: {},
|
|
1602
|
+
closed_root: root
|
|
1603
|
+
}, []);
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
}
|
|
1607
|
+
// This terminal update carries the exact final counter, so clear any
|
|
1608
|
+
// dirty mark: otherwise _flushEdgeCounters at run end would re-emit
|
|
1609
|
+
// status "active" after "completed" for an edge whose counter advanced
|
|
1610
|
+
// within the throttle window just before its source finished. §1.
|
|
1611
|
+
this._edgeCounterDirty.delete(edgeId);
|
|
688
1612
|
this._emit({
|
|
689
1613
|
type: "edge_update",
|
|
690
|
-
|
|
1614
|
+
job_id: this._effectiveJobId,
|
|
691
1615
|
edge_id: edgeId,
|
|
692
1616
|
status: "completed",
|
|
693
1617
|
counter: this._edgeCounters.get(edgeId) ?? null
|
|
@@ -700,7 +1624,7 @@ export class WorkflowRunner {
|
|
|
700
1624
|
* (Python parity: send_messages special handling of __control_output__.)
|
|
701
1625
|
*/
|
|
702
1626
|
async _routeControlOutput(sourceNodeId, controlOutput) {
|
|
703
|
-
if (!controlOutput
|
|
1627
|
+
if (!isObjectValue(controlOutput))
|
|
704
1628
|
return;
|
|
705
1629
|
const controlEdges = this._graph
|
|
706
1630
|
.findOutgoingEdges(sourceNodeId)
|
|
@@ -710,8 +1634,7 @@ export class WorkflowRunner {
|
|
|
710
1634
|
let properties = controlOutput;
|
|
711
1635
|
// Extract properties if nested inside a metadata wrapper
|
|
712
1636
|
if ("properties" in properties &&
|
|
713
|
-
properties.properties &&
|
|
714
|
-
typeof properties.properties === "object" &&
|
|
1637
|
+
isObjectValue(properties.properties) &&
|
|
715
1638
|
!Array.isArray(properties.properties)) {
|
|
716
1639
|
properties = properties.properties;
|
|
717
1640
|
}
|
|
@@ -720,10 +1643,11 @@ export class WorkflowRunner {
|
|
|
720
1643
|
const targetInbox = this._inboxes.get(edge.target);
|
|
721
1644
|
if (!targetInbox)
|
|
722
1645
|
continue;
|
|
723
|
-
await targetInbox.put("__control__", event);
|
|
724
1646
|
const ctrlEdgeId = edge.id ??
|
|
725
|
-
|
|
726
|
-
|
|
1647
|
+
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle);
|
|
1648
|
+
await targetInbox.put("__control__", event, {
|
|
1649
|
+
source_edge_id: ctrlEdgeId
|
|
1650
|
+
});
|
|
727
1651
|
}
|
|
728
1652
|
}
|
|
729
1653
|
// -----------------------------------------------------------------------
|
|
@@ -759,14 +1683,42 @@ export class WorkflowRunner {
|
|
|
759
1683
|
if (!inbox) {
|
|
760
1684
|
throw new Error(`Target node not found or no inbox: ${targetNodeId}`);
|
|
761
1685
|
}
|
|
1686
|
+
// The target's actor has already finished — nothing will ever read its
|
|
1687
|
+
// inbox again, so a registered response would hang forever. Reject now.
|
|
1688
|
+
if (this._completedNodes.has(targetNodeId)) {
|
|
1689
|
+
throw new Error(`Target node already completed and cannot handle control events: ${targetNodeId}`);
|
|
1690
|
+
}
|
|
1691
|
+
const entry = { resolve: () => { }, reject: () => { } };
|
|
762
1692
|
const promise = new Promise((resolve, reject) => {
|
|
763
|
-
|
|
1693
|
+
entry.resolve = resolve;
|
|
1694
|
+
entry.reject = reject;
|
|
1695
|
+
let queue = this._pendingControlResponses.get(targetNodeId);
|
|
1696
|
+
if (!queue) {
|
|
1697
|
+
queue = [];
|
|
1698
|
+
this._pendingControlResponses.set(targetNodeId, queue);
|
|
1699
|
+
}
|
|
1700
|
+
queue.push(entry);
|
|
764
1701
|
});
|
|
765
1702
|
const event = {
|
|
766
1703
|
event_type: "run",
|
|
767
1704
|
properties
|
|
768
1705
|
};
|
|
769
1706
|
await inbox.put("__control__", event);
|
|
1707
|
+
// The target's actor can finish between the check above and this point —
|
|
1708
|
+
// its completion handler drains `_pendingControlResponses` before this
|
|
1709
|
+
// waiter joined the queue, so nothing would ever settle it. Re-check after
|
|
1710
|
+
// registering and reject rather than hang.
|
|
1711
|
+
if (this._completedNodes.has(targetNodeId)) {
|
|
1712
|
+
const queue = this._pendingControlResponses.get(targetNodeId);
|
|
1713
|
+
const index = queue?.indexOf(entry) ?? -1;
|
|
1714
|
+
if (queue && index >= 0) {
|
|
1715
|
+
queue.splice(index, 1);
|
|
1716
|
+
if (queue.length === 0) {
|
|
1717
|
+
this._pendingControlResponses.delete(targetNodeId);
|
|
1718
|
+
}
|
|
1719
|
+
entry.reject(new Error(`Target node already completed and cannot handle control events: ${targetNodeId}`));
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
770
1722
|
return promise;
|
|
771
1723
|
}
|
|
772
1724
|
// -----------------------------------------------------------------------
|
|
@@ -774,17 +1726,48 @@ export class WorkflowRunner {
|
|
|
774
1726
|
// -----------------------------------------------------------------------
|
|
775
1727
|
_incrementEdgeCounter(edge) {
|
|
776
1728
|
const id = edge.id ??
|
|
777
|
-
|
|
1729
|
+
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle);
|
|
778
1730
|
const counter = (this._edgeCounters.get(id) ?? 0) + 1;
|
|
779
1731
|
this._edgeCounters.set(id, counter);
|
|
1732
|
+
// Per-message edge_updates only drive UI affordances: the flow animation
|
|
1733
|
+
// needs the first message, and the "N streamed" badge doesn't need more
|
|
1734
|
+
// than a few updates per second. Realtime audio streams cross edges at
|
|
1735
|
+
// chunk rate (~50/s per edge), which would otherwise flood the transport.
|
|
1736
|
+
// Emit the first update immediately, throttle the rest, and flush exact
|
|
1737
|
+
// final counters in _flushEdgeCounters() at run end.
|
|
1738
|
+
const now = Date.now();
|
|
1739
|
+
const last = this._edgeCounterLastEmitMs.get(id);
|
|
1740
|
+
if (last !== undefined && now - last < EDGE_UPDATE_MIN_INTERVAL_MS) {
|
|
1741
|
+
this._edgeCounterDirty.add(id);
|
|
1742
|
+
return;
|
|
1743
|
+
}
|
|
1744
|
+
this._edgeCounterLastEmitMs.set(id, now);
|
|
1745
|
+
this._edgeCounterDirty.delete(id);
|
|
780
1746
|
this._emit({
|
|
781
1747
|
type: "edge_update",
|
|
782
|
-
|
|
1748
|
+
job_id: this._effectiveJobId,
|
|
783
1749
|
edge_id: id,
|
|
784
1750
|
status: "active",
|
|
785
1751
|
counter
|
|
786
1752
|
});
|
|
787
1753
|
}
|
|
1754
|
+
/**
|
|
1755
|
+
* Emit the final counter for every edge whose count advanced past its last
|
|
1756
|
+
* throttled edge_update, so the badge ends on the exact total. Called from
|
|
1757
|
+
* _drainActiveEdges (which runs on completion, cancellation and error).
|
|
1758
|
+
*/
|
|
1759
|
+
_flushEdgeCounters() {
|
|
1760
|
+
for (const id of this._edgeCounterDirty) {
|
|
1761
|
+
this._emit({
|
|
1762
|
+
type: "edge_update",
|
|
1763
|
+
job_id: this._effectiveJobId,
|
|
1764
|
+
edge_id: id,
|
|
1765
|
+
status: "active",
|
|
1766
|
+
counter: this._edgeCounters.get(id) ?? null
|
|
1767
|
+
});
|
|
1768
|
+
}
|
|
1769
|
+
this._edgeCounterDirty.clear();
|
|
1770
|
+
}
|
|
788
1771
|
// -----------------------------------------------------------------------
|
|
789
1772
|
// Drain active edges (Python parity: drain_active_edges)
|
|
790
1773
|
// -----------------------------------------------------------------------
|
|
@@ -793,22 +1776,34 @@ export class WorkflowRunner {
|
|
|
793
1776
|
* buffered items or open upstream sources. Called during post-completion
|
|
794
1777
|
* cleanup to ensure front-end consumers stop listening to streams and
|
|
795
1778
|
* clear any spinners.
|
|
1779
|
+
*
|
|
1780
|
+
* Returns the ids of edges found in that leftover state — §6's "zero
|
|
1781
|
+
* pending work" is violated whenever this is non-empty after a normal
|
|
1782
|
+
* (non-error) completion. The caller decides what strict mode does with
|
|
1783
|
+
* that list; this method's own emit-and-continue behavior never changes,
|
|
1784
|
+
* since it also runs on the error/cancellation cleanup path where a
|
|
1785
|
+
* partial graph is expected to have open edges.
|
|
796
1786
|
*/
|
|
797
1787
|
_drainActiveEdges() {
|
|
1788
|
+
const leftoverEdgeIds = [];
|
|
798
1789
|
if (!this._graph || this._graph.edges.length === 0)
|
|
799
|
-
return;
|
|
1790
|
+
return leftoverEdgeIds;
|
|
1791
|
+
// Settle the throttled counters first; a "drained" update below may then
|
|
1792
|
+
// override the status for still-open edges.
|
|
1793
|
+
this._flushEdgeCounters();
|
|
800
1794
|
for (const edge of this._graph.edges) {
|
|
801
1795
|
try {
|
|
802
1796
|
const inbox = this._inboxes.get(edge.target);
|
|
803
1797
|
if (!inbox)
|
|
804
1798
|
continue;
|
|
805
1799
|
const edgeId = edge.id ??
|
|
806
|
-
|
|
1800
|
+
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle);
|
|
807
1801
|
if (inbox.hasBuffered(edge.targetHandle) ||
|
|
808
1802
|
inbox.isOpen(edge.targetHandle)) {
|
|
1803
|
+
leftoverEdgeIds.push(edgeId);
|
|
809
1804
|
this._emit({
|
|
810
1805
|
type: "edge_update",
|
|
811
|
-
|
|
1806
|
+
job_id: this._effectiveJobId,
|
|
812
1807
|
edge_id: edgeId,
|
|
813
1808
|
status: "drained",
|
|
814
1809
|
counter: this._edgeCounters.get(edgeId) ?? null
|
|
@@ -819,48 +1814,36 @@ export class WorkflowRunner {
|
|
|
819
1814
|
// Best effort — ignore errors during draining
|
|
820
1815
|
}
|
|
821
1816
|
}
|
|
1817
|
+
return leftoverEdgeIds;
|
|
822
1818
|
}
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
}
|
|
849
|
-
}
|
|
850
|
-
while (queue.length > 0) {
|
|
851
|
-
const current = queue.shift();
|
|
852
|
-
for (const edge of adjacency.get(current) ?? []) {
|
|
853
|
-
this._streamingEdges.set(this._edgeKey(edge), true);
|
|
854
|
-
if (!visited.has(edge.target)) {
|
|
855
|
-
visited.add(edge.target);
|
|
856
|
-
queue.push(edge.target);
|
|
857
|
-
}
|
|
858
|
-
}
|
|
1819
|
+
/**
|
|
1820
|
+
* Strict-mode gate for `_drainActiveEdges`'s findings (§12). Split out from
|
|
1821
|
+
* its one call site (the success path in `_runImpl`, right after
|
|
1822
|
+
* `_processGraph`) so it is unit-testable without a full graph run: in
|
|
1823
|
+
* practice any leftover edge state this reports was already caught by the
|
|
1824
|
+
* node-level `_checkPendingInboxWork` gate inside `_processGraph` (an
|
|
1825
|
+
* inbox's `hasPendingWork()` covers every handle, edge-targeted ones
|
|
1826
|
+
* included) and would have thrown before this method is ever reached —
|
|
1827
|
+
* this gate exists for the state `_checkPendingInboxWork` cannot see (e.g.
|
|
1828
|
+
* a driver that calls `_drainActiveEdges` directly after bypassing
|
|
1829
|
+
* `_processGraph`) and as a second line of defense should that ordering
|
|
1830
|
+
* ever change.
|
|
1831
|
+
*
|
|
1832
|
+
* A cancelled run, or one with node errors, legitimately
|
|
1833
|
+
* leaves edges mid-flight — that is what the drain reports to the
|
|
1834
|
+
* frontend in every mode. Only a run that is otherwise clean but still has
|
|
1835
|
+
* leftover edge state is a §6 violation ("zero pending work" after a
|
|
1836
|
+
* normal completion).
|
|
1837
|
+
*/
|
|
1838
|
+
_enforceCleanEdgeDrain(leftoverEdgeIds) {
|
|
1839
|
+
if (!this._options.strict ||
|
|
1840
|
+
leftoverEdgeIds.length === 0 ||
|
|
1841
|
+
this._cancelled ||
|
|
1842
|
+
this._nodeErrors.size > 0) {
|
|
1843
|
+
return;
|
|
859
1844
|
}
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
edgeStreams(edge) {
|
|
863
|
-
return this._streamingEdges.get(this._edgeKey(edge)) ?? false;
|
|
1845
|
+
throw new Error(`Strict mode: edge(s) still had buffered/open state after a clean ` +
|
|
1846
|
+
`run completion: ${leftoverEdgeIds.join(", ")}`);
|
|
864
1847
|
}
|
|
865
1848
|
// -----------------------------------------------------------------------
|
|
866
1849
|
// Pending work detection
|
|
@@ -889,20 +1872,72 @@ export class WorkflowRunner {
|
|
|
889
1872
|
return (node.type.startsWith("nodetool.input.") || node.type === "test.Input");
|
|
890
1873
|
}
|
|
891
1874
|
_getExternalInputName(node) {
|
|
892
|
-
const properties = node.properties
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
1875
|
+
const properties = isObjectValue(node.properties) ? node.properties : {};
|
|
1876
|
+
const propertyName = isString(properties.name)
|
|
1877
|
+
? properties.name.trim()
|
|
1878
|
+
: "";
|
|
896
1879
|
if (propertyName) {
|
|
897
1880
|
return propertyName;
|
|
898
1881
|
}
|
|
899
1882
|
return node.name ?? node.id;
|
|
900
1883
|
}
|
|
1884
|
+
/**
|
|
1885
|
+
* Key a terminal node's outputs are collected under.
|
|
1886
|
+
*
|
|
1887
|
+
* DSL-authored graphs carry the public name in the Output node's `name`
|
|
1888
|
+
* *property* (`output({ name: "hook", value })`) — the descriptor's
|
|
1889
|
+
* top-level `name` is absent, and the auto-generated node id (`output`,
|
|
1890
|
+
* `output_2`, …) is all that would remain. Promote the property for
|
|
1891
|
+
* output-typed nodes so a run's outputs are keyed by the name the author
|
|
1892
|
+
* asked for. Mirrors `_getExternalInputName` on the input side and the
|
|
1893
|
+
* websocket runner's `require_terminal_result` rewrite; gating on
|
|
1894
|
+
* `nodetool.output.` keeps other terminal sinks keyed by id.
|
|
1895
|
+
*/
|
|
1896
|
+
_outputCollectionKey(node) {
|
|
1897
|
+
if (isString(node.name) && node.name.trim())
|
|
1898
|
+
return node.name;
|
|
1899
|
+
if (node.type.startsWith("nodetool.output.")) {
|
|
1900
|
+
const properties = isObjectValue(node.properties) ? node.properties : {};
|
|
1901
|
+
const propertyName = isString(properties.name)
|
|
1902
|
+
? properties.name.trim()
|
|
1903
|
+
: "";
|
|
1904
|
+
if (propertyName)
|
|
1905
|
+
return propertyName;
|
|
1906
|
+
}
|
|
1907
|
+
return node.id;
|
|
1908
|
+
}
|
|
901
1909
|
_emit(msg) {
|
|
902
|
-
|
|
1910
|
+
// Retain for RunResult.messages — except the realtime-audio firehose: a
|
|
1911
|
+
// live synth patch emits ~50 audio-chunk output_updates per node per
|
|
1912
|
+
// second, each holding a sample buffer, so retaining them grows the heap
|
|
1913
|
+
// without bound (~25MB/min for a small patch) and the mounting GC
|
|
1914
|
+
// pressure progressively degrades whichever thread runs the kernel.
|
|
1915
|
+
// Streaming delivery (executionContext.emit) is unaffected. A generous
|
|
1916
|
+
// cap backstops other unbounded streams.
|
|
1917
|
+
if (!isAudioChunkOutputUpdate(msg)) {
|
|
1918
|
+
if (this._messages.length >= MAX_RETAINED_MESSAGES) {
|
|
1919
|
+
this._messages = this._messages.slice(this._messages.length - MAX_RETAINED_MESSAGES / 2);
|
|
1920
|
+
}
|
|
1921
|
+
this._messages.push(msg);
|
|
1922
|
+
}
|
|
903
1923
|
if (this._options.executionContext) {
|
|
904
|
-
|
|
1924
|
+
// Message delivery is observation, not execution. A transport that fails
|
|
1925
|
+
// mid-run (a closed WebSocket, a full queue) must not abort the workflow
|
|
1926
|
+
// — `_emit` is called from EOS routing and actor completion handlers,
|
|
1927
|
+
// where a throw would take down the run and orphan sibling actors.
|
|
1928
|
+
try {
|
|
1929
|
+
this._options.executionContext.emit(msg);
|
|
1930
|
+
}
|
|
1931
|
+
catch (err) {
|
|
1932
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
1933
|
+
log.warn("Message emit failed", {
|
|
1934
|
+
jobId: this.jobId,
|
|
1935
|
+
type: msg.type,
|
|
1936
|
+
error: err instanceof Error ? err.message : String(err)
|
|
1937
|
+
});
|
|
1938
|
+
}
|
|
905
1939
|
}
|
|
1940
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
906
1941
|
log.debug("Message emitted", { jobId: this.jobId, type: msg.type });
|
|
907
1942
|
}
|
|
908
1943
|
_resolveInputNodes(inputName) {
|
|
@@ -937,21 +1972,28 @@ export class WorkflowRunner {
|
|
|
937
1972
|
continue;
|
|
938
1973
|
const properties = {};
|
|
939
1974
|
// Extract property info from the node descriptor
|
|
940
|
-
if (targetNode.properties
|
|
1975
|
+
if (isObjectValue(targetNode.properties)) {
|
|
941
1976
|
const props = targetNode.properties;
|
|
942
1977
|
const propTypes = targetNode.propertyTypes ?? {};
|
|
943
1978
|
for (const [propName, propValue] of Object.entries(props)) {
|
|
944
1979
|
if (propName.startsWith("_"))
|
|
945
1980
|
continue; // skip private
|
|
946
1981
|
const meta = targetNode.propertyMeta?.[propName];
|
|
947
|
-
|
|
1982
|
+
const described = {
|
|
948
1983
|
value: propValue,
|
|
949
1984
|
type: propTypes[propName] ??
|
|
950
|
-
typeof propValue
|
|
951
|
-
...(meta?.description ? { description: meta.description } : {}),
|
|
952
|
-
...(meta?.min != null ? { min: meta.min } : {}),
|
|
953
|
-
...(meta?.max != null ? { max: meta.max } : {})
|
|
1985
|
+
typeof propValue
|
|
954
1986
|
};
|
|
1987
|
+
if (meta?.description) {
|
|
1988
|
+
described.description = meta.description;
|
|
1989
|
+
}
|
|
1990
|
+
if (meta?.min != null) {
|
|
1991
|
+
described.min = meta.min;
|
|
1992
|
+
}
|
|
1993
|
+
if (meta?.max != null) {
|
|
1994
|
+
described.max = meta.max;
|
|
1995
|
+
}
|
|
1996
|
+
properties[propName] = described;
|
|
955
1997
|
}
|
|
956
1998
|
}
|
|
957
1999
|
context[targetId] = {
|
|
@@ -974,14 +2016,27 @@ export class WorkflowRunner {
|
|
|
974
2016
|
*/
|
|
975
2017
|
_buildControlActionProperties(node) {
|
|
976
2018
|
const result = {};
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
2019
|
+
const props = (node.properties ?? {});
|
|
2020
|
+
const slotTypes = dynamicSlotPropertyTypes(node.dynamic_inputs);
|
|
2021
|
+
// Declared dynamic slots type their handles; the registry map wins on a
|
|
2022
|
+
// name collision.
|
|
2023
|
+
const propTypes = {
|
|
2024
|
+
...slotTypes,
|
|
2025
|
+
...(node.propertyTypes ?? {})
|
|
2026
|
+
};
|
|
2027
|
+
// Build the schema from registry-declared property types so the LLM sees
|
|
2028
|
+
// every argument the node accepts, even when the node has no saved values.
|
|
2029
|
+
// Fall back to keys present in `properties` for dynamic nodes whose
|
|
2030
|
+
// registry metadata doesn't enumerate every property.
|
|
2031
|
+
const names = new Set([
|
|
2032
|
+
...Object.keys(propTypes),
|
|
2033
|
+
...Object.keys(props)
|
|
2034
|
+
]);
|
|
2035
|
+
for (const name of names) {
|
|
982
2036
|
if (name.startsWith("_"))
|
|
983
2037
|
continue;
|
|
984
2038
|
const declaredType = propTypes[name];
|
|
2039
|
+
const value = props[name];
|
|
985
2040
|
let jsonType = "string";
|
|
986
2041
|
if (declaredType) {
|
|
987
2042
|
const lower = declaredType.toLowerCase();
|
|
@@ -996,21 +2051,29 @@ export class WorkflowRunner {
|
|
|
996
2051
|
else if (lower.startsWith("dict") || lower === "object")
|
|
997
2052
|
jsonType = "object";
|
|
998
2053
|
}
|
|
999
|
-
else if (
|
|
2054
|
+
else if (isNumber(value)) {
|
|
1000
2055
|
jsonType = Number.isInteger(value) ? "integer" : "number";
|
|
1001
2056
|
}
|
|
1002
|
-
else if (
|
|
2057
|
+
else if (isBoolean(value)) {
|
|
1003
2058
|
jsonType = "boolean";
|
|
1004
2059
|
}
|
|
1005
|
-
const
|
|
1006
|
-
|
|
2060
|
+
const slot = node.dynamic_inputs?.[name];
|
|
2061
|
+
const meta = (node.propertyMeta?.[name] ?? slot);
|
|
2062
|
+
const schema = {
|
|
1007
2063
|
type: jsonType,
|
|
1008
2064
|
description: meta?.description ??
|
|
1009
|
-
`Property '${name}' (${declaredType ?? jsonType})
|
|
1010
|
-
default: value,
|
|
1011
|
-
...(meta?.min != null ? { minimum: meta.min } : {}),
|
|
1012
|
-
...(meta?.max != null ? { maximum: meta.max } : {})
|
|
2065
|
+
`Property '${name}' (${declaredType ?? jsonType})`
|
|
1013
2066
|
};
|
|
2067
|
+
if (value !== undefined) {
|
|
2068
|
+
schema.default = value;
|
|
2069
|
+
}
|
|
2070
|
+
if (meta?.min != null) {
|
|
2071
|
+
schema.minimum = meta.min;
|
|
2072
|
+
}
|
|
2073
|
+
if (meta?.max != null) {
|
|
2074
|
+
schema.maximum = meta.max;
|
|
2075
|
+
}
|
|
2076
|
+
result[name] = schema;
|
|
1014
2077
|
}
|
|
1015
2078
|
return result;
|
|
1016
2079
|
}
|