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