@nodetool-ai/kernel 0.7.0-rc.23 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +51 -0
- package/dist/.nodetool-build-stamp +1 -0
- package/dist/actor.d.ts +381 -20
- package/dist/actor.d.ts.map +1 -1
- package/dist/actor.js +1619 -184
- package/dist/actor.js.map +1 -1
- package/dist/correlation-analysis.d.ts +104 -0
- package/dist/correlation-analysis.d.ts.map +1 -0
- package/dist/correlation-analysis.js +833 -0
- package/dist/correlation-analysis.js.map +1 -0
- package/dist/durable-inbox.d.ts +9 -0
- package/dist/durable-inbox.d.ts.map +1 -1
- package/dist/durable-inbox.js +55 -2
- package/dist/durable-inbox.js.map +1 -1
- package/dist/dynamic-slots.d.ts +58 -0
- package/dist/dynamic-slots.d.ts.map +1 -0
- package/dist/dynamic-slots.js +182 -0
- package/dist/dynamic-slots.js.map +1 -0
- package/dist/edge-ids.d.ts +11 -0
- package/dist/edge-ids.d.ts.map +1 -0
- package/dist/edge-ids.js +15 -0
- package/dist/edge-ids.js.map +1 -0
- package/dist/graph-utils.d.ts +12 -0
- package/dist/graph-utils.d.ts.map +1 -1
- package/dist/graph-utils.js +51 -16
- package/dist/graph-utils.js.map +1 -1
- package/dist/graph.d.ts +50 -9
- package/dist/graph.d.ts.map +1 -1
- package/dist/graph.js +308 -101
- package/dist/graph.js.map +1 -1
- package/dist/inbox.d.ts +158 -2
- package/dist/inbox.d.ts.map +1 -1
- package/dist/inbox.js +253 -11
- package/dist/inbox.js.map +1 -1
- package/dist/index.d.ts +13 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -7
- package/dist/index.js.map +1 -1
- package/dist/io.d.ts +103 -6
- package/dist/io.d.ts.map +1 -1
- package/dist/io.js +123 -12
- package/dist/io.js.map +1 -1
- package/dist/loop.d.ts +36 -0
- package/dist/loop.d.ts.map +1 -0
- package/dist/loop.js +166 -0
- package/dist/loop.js.map +1 -0
- package/dist/predicates.d.ts +8 -0
- package/dist/predicates.d.ts.map +1 -0
- package/dist/predicates.js +8 -0
- package/dist/predicates.js.map +1 -0
- package/dist/run-state.d.ts +65 -0
- package/dist/run-state.d.ts.map +1 -0
- package/dist/run-state.js +42 -0
- package/dist/run-state.js.map +1 -0
- package/dist/runner.d.ts +312 -15
- package/dist/runner.d.ts.map +1 -1
- package/dist/runner.js +1219 -156
- package/dist/runner.js.map +1 -1
- package/dist/substitute-validator.d.ts +44 -0
- package/dist/substitute-validator.d.ts.map +1 -0
- package/dist/substitute-validator.js +169 -0
- package/dist/substitute-validator.js.map +1 -0
- package/dist/supervisor.d.ts +148 -0
- package/dist/supervisor.d.ts.map +1 -0
- package/dist/supervisor.js +287 -0
- package/dist/supervisor.js.map +1 -0
- package/dist/trigger-wakeup.d.ts +74 -5
- package/dist/trigger-wakeup.d.ts.map +1 -1
- package/dist/trigger-wakeup.js +167 -45
- package/dist/trigger-wakeup.js.map +1 -1
- package/package.json +27 -9
- package/dist/channel.d.ts +0 -46
- package/dist/channel.d.ts.map +0 -1
- package/dist/channel.js +0 -191
- package/dist/channel.js.map +0 -1
- package/dist/suspendable.d.ts +0 -68
- package/dist/suspendable.d.ts.map +0 -1
- package/dist/suspendable.js +0 -108
- package/dist/suspendable.js.map +0 -1
- package/dist/trigger-manager.d.ts +0 -107
- package/dist/trigger-manager.d.ts.map +0 -1
- package/dist/trigger-manager.js +0 -214
- package/dist/trigger-manager.js.map +0 -1
- package/dist/trigger.d.ts +0 -57
- package/dist/trigger.d.ts.map +0 -1
- package/dist/trigger.js +0 -145
- package/dist/trigger.js.map +0 -1
package/dist/actor.js
CHANGED
|
@@ -8,15 +8,147 @@
|
|
|
8
8
|
* 2. Streaming input: node drains inbox via iterInput / iterAny.
|
|
9
9
|
* 3. Streaming output: call genProcess() which yields items.
|
|
10
10
|
* 4. Controlled: accept control events, cache inputs for replay.
|
|
11
|
+
* 5. Loop: `nodetool.control.Loop`, run by `runLoop` (loop.ts).
|
|
11
12
|
*
|
|
12
13
|
* Sync modes:
|
|
13
14
|
* - on_any: fire when ANY input handle has data.
|
|
14
15
|
* - zip_all: wait until ALL handles have data (with sticky semantics).
|
|
15
16
|
*/
|
|
16
17
|
import { createLogger } from "@nodetool-ai/config";
|
|
18
|
+
import { isBoolean, isNumber, isObjectValue, isString } from "./predicates.js";
|
|
19
|
+
import { EMPTY_LINEAGE, LOOP_NODE_TYPE, TypeMetadata } from "@nodetool-ai/protocol";
|
|
20
|
+
// Stryker disable next-line StringLiteral: logger name is a diagnostic label, not a behavioural contract
|
|
17
21
|
const log = createLogger("nodetool.kernel.actor");
|
|
18
|
-
import {
|
|
22
|
+
import { createInvocationAccount, inInvocationAccount, isContentFilterRefusal, isRecoverableNodeError, providerFailureDetail } from "@nodetool-ai/runtime";
|
|
23
|
+
import { computeAllowedActions, failureSignature, redactRecord, redactValue } from "./supervisor.js";
|
|
24
|
+
import { hasFullValidatorCoverage, validateSubstituteOutputs } from "./substitute-validator.js";
|
|
25
|
+
// Span helpers via the narrow `/tracing` subpath — keeps the runtime
|
|
26
|
+
// provider / python-bridge barrel out of thin (browser) bundles.
|
|
27
|
+
import { withNodeSpan } from "@nodetool-ai/runtime/tracing";
|
|
19
28
|
import { NodeInputs, NodeOutputs } from "./io.js";
|
|
29
|
+
import { applyDynamicSlotTypes } from "./dynamic-slots.js";
|
|
30
|
+
import { runLoop } from "./loop.js";
|
|
31
|
+
import { iterationRootId, projectLineageKey, tryProjectLineageKey } from "./correlation-analysis.js";
|
|
32
|
+
/** Returned by the recovery loop when a `skip` verdict retired an invocation. */
|
|
33
|
+
const SKIPPED = Symbol("skipped");
|
|
34
|
+
/**
|
|
35
|
+
* A failure that happened while routing values downstream, not while the node
|
|
36
|
+
* was executing. It never escalates: `sendOutputs` delivers to each outgoing
|
|
37
|
+
* edge in turn, so once edge 1 has the value, re-running the node would deliver
|
|
38
|
+
* to it twice. Design §5.1.
|
|
39
|
+
*/
|
|
40
|
+
class RoutingError extends Error {
|
|
41
|
+
cause;
|
|
42
|
+
constructor(cause) {
|
|
43
|
+
super(cause instanceof Error ? cause.message : String(cause));
|
|
44
|
+
this.cause = cause;
|
|
45
|
+
this.name = "RoutingError";
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Canonical lineage keys join `root=index` pairs with `,`. To compute the
|
|
50
|
+
* parent key for a shorter scope, take the first `prefixLength` pairs.
|
|
51
|
+
*/
|
|
52
|
+
export function trimKey(key, prefixLength) {
|
|
53
|
+
// The three guards below are pure fast-paths: each returns exactly what the
|
|
54
|
+
// final `parts.slice(0, prefixLength).join(",")` would compute, so mutating
|
|
55
|
+
// any of them is equivalent.
|
|
56
|
+
// - prefixLength === 0 → slice(0,0).join("") === ""
|
|
57
|
+
// - key === "" → split gives [""], 1 <= prefixLength → key === ""
|
|
58
|
+
// - parts.length <= prefixLength → slice keeps every part → join === key
|
|
59
|
+
// Stryker disable next-line ConditionalExpression: equivalent fast-path (see above)
|
|
60
|
+
if (prefixLength === 0)
|
|
61
|
+
return "";
|
|
62
|
+
// Stryker disable next-line ConditionalExpression,StringLiteral: equivalent fast-path (see above)
|
|
63
|
+
if (key === "")
|
|
64
|
+
return "";
|
|
65
|
+
const parts = key.split(",");
|
|
66
|
+
// Stryker disable next-line ConditionalExpression,EqualityOperator: equivalent fast-path (see above)
|
|
67
|
+
if (parts.length <= prefixLength)
|
|
68
|
+
return key;
|
|
69
|
+
return parts.slice(0, prefixLength).join(",");
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Find every pending max-scope key in `maxBuckets` whose parent (trimmed to
|
|
73
|
+
* `parentLength`) equals `parentKey`. Used when a strict-prefix sticky
|
|
74
|
+
* arrival can unblock pending child firings.
|
|
75
|
+
*/
|
|
76
|
+
export function enumerateCandidateKeysForParent(maxBuckets, _dataHandles, _handleClass, _handleScope, _maxLength, parentKey, parentLength) {
|
|
77
|
+
const out = [];
|
|
78
|
+
const seen = new Set();
|
|
79
|
+
for (const buckets of maxBuckets.values()) {
|
|
80
|
+
for (const key of buckets.keys()) {
|
|
81
|
+
if (seen.has(key))
|
|
82
|
+
continue;
|
|
83
|
+
if (trimKey(key, parentLength) === parentKey) {
|
|
84
|
+
seen.add(key);
|
|
85
|
+
out.push(key);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
export function enumerateAllPendingKeys(maxBuckets) {
|
|
92
|
+
const seen = new Set();
|
|
93
|
+
const out = [];
|
|
94
|
+
for (const buckets of maxBuckets.values()) {
|
|
95
|
+
for (const key of buckets.keys()) {
|
|
96
|
+
if (seen.has(key))
|
|
97
|
+
continue;
|
|
98
|
+
seen.add(key);
|
|
99
|
+
out.push(key);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return out;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* A resolved model property (`{type: "image_model", id, name, provider}`),
|
|
106
|
+
* reduced to the fields that identify it. Which model ran is the one
|
|
107
|
+
* generation setting that is never a scalar, and without it a saved asset
|
|
108
|
+
* cannot say what produced it.
|
|
109
|
+
*/
|
|
110
|
+
function modelReference(value) {
|
|
111
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
const ref = value;
|
|
115
|
+
if (!isString(ref.type) || !ref.type.endsWith("_model"))
|
|
116
|
+
return null;
|
|
117
|
+
if (!isString(ref.id) || ref.id.length === 0)
|
|
118
|
+
return null;
|
|
119
|
+
const out = { type: ref.type, id: ref.id };
|
|
120
|
+
if (isString(ref.name))
|
|
121
|
+
out.name = ref.name;
|
|
122
|
+
if (isString(ref.provider))
|
|
123
|
+
out.provider = ref.provider;
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Pick the persistable input properties from a resolved input dict: scalars
|
|
128
|
+
* (string/number/boolean) plus model references, reduced by
|
|
129
|
+
* {@link modelReference}. Drops every other nested object, array and binary
|
|
130
|
+
* ref so the `generation_complete` event stays small and carries only
|
|
131
|
+
* generation params (prompt, seed, model, …). Reserved keys
|
|
132
|
+
* (`_control_context` and other `_`-prefixed internals) are stripped. Returns
|
|
133
|
+
* `null` when nothing remains.
|
|
134
|
+
*/
|
|
135
|
+
function scalarInputProperties(inputs) {
|
|
136
|
+
const out = {};
|
|
137
|
+
for (const [key, value] of Object.entries(inputs)) {
|
|
138
|
+
if (key.startsWith("_"))
|
|
139
|
+
continue;
|
|
140
|
+
if (isString(value) ||
|
|
141
|
+
isNumber(value) ||
|
|
142
|
+
isBoolean(value)) {
|
|
143
|
+
out[key] = value;
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
const model = modelReference(value);
|
|
147
|
+
if (model)
|
|
148
|
+
out[key] = model;
|
|
149
|
+
}
|
|
150
|
+
return Object.keys(out).length > 0 ? out : null;
|
|
151
|
+
}
|
|
20
152
|
// ---------------------------------------------------------------------------
|
|
21
153
|
// NodeActor
|
|
22
154
|
// ---------------------------------------------------------------------------
|
|
@@ -32,16 +164,65 @@ export class NodeActor {
|
|
|
32
164
|
_latestResult = null;
|
|
33
165
|
/** Collected non-null outputs for streaming-output nodes. */
|
|
34
166
|
_streamingCollectedOutputs = null;
|
|
35
|
-
/** Handles
|
|
36
|
-
|
|
167
|
+
/** Handles where multiple upstream values should be collected into a list. */
|
|
168
|
+
_listInputHandles;
|
|
37
169
|
/** Callback to route outputs downstream. */
|
|
38
170
|
_sendOutputs;
|
|
171
|
+
/**
|
|
172
|
+
* Lineage of the current invocation. Set when the actor consumes input(s)
|
|
173
|
+
* under the correlation flag and the inheritance case is unambiguous
|
|
174
|
+
* (single-edge single-input handle).
|
|
175
|
+
*/
|
|
176
|
+
_currentInvocationLineage;
|
|
177
|
+
/**
|
|
178
|
+
* A node fed by a streaming handle is invoked once per chunk, so logging
|
|
179
|
+
* every invocation at INFO buries the run: one Preview on an agent's chunk
|
|
180
|
+
* output produced 1112 of 1142 lines in a run whose plan, six tasks and
|
|
181
|
+
* twelve steps took 30. The first invocation is the informative one.
|
|
182
|
+
*/
|
|
183
|
+
_executionsLogged = 0;
|
|
184
|
+
/**
|
|
185
|
+
* Most recent envelope consumed per handle during the current gather.
|
|
186
|
+
* Reset before each invocation. Used to compute invocation lineage when
|
|
187
|
+
* the correlation flag is on.
|
|
188
|
+
*/
|
|
189
|
+
_lastEnvelopes = new Map();
|
|
39
190
|
/** Callback to emit processing messages (NodeUpdate, etc.). */
|
|
40
191
|
_emitMessage;
|
|
41
192
|
/** Optional execution context passed into node executors. */
|
|
42
193
|
_executionContext;
|
|
43
194
|
/** Control context for controller nodes (injected as _control_context input). */
|
|
44
195
|
_controlContext;
|
|
196
|
+
/**
|
|
197
|
+
* Static correlation analysis for this node, supplied by the runner.
|
|
198
|
+
*/
|
|
199
|
+
_correlation;
|
|
200
|
+
/**
|
|
201
|
+
* Per-iteration-root, per-parent-key counter for actor-minted iteration
|
|
202
|
+
* tokens. §2 — counters are scoped by `(root id, exact parent lineage)`
|
|
203
|
+
* and never reset for repeated invocations with the same parent key.
|
|
204
|
+
*/
|
|
205
|
+
_iterationCounters = new Map();
|
|
206
|
+
/**
|
|
207
|
+
* Run-level cancellation signal (aborted by `WorkflowRunner.cancel()`),
|
|
208
|
+
* exposed to node code via `NodeInputs.signal`. Defaults to a
|
|
209
|
+
* never-aborted signal for test fixtures.
|
|
210
|
+
*/
|
|
211
|
+
_cancelSignal;
|
|
212
|
+
/**
|
|
213
|
+
* Callback wired by the runner to signal early end-of-stream for a single
|
|
214
|
+
* output slot (`outputs.complete(slot)`). Marks the slot's downstream edges
|
|
215
|
+
* done immediately, rather than waiting for the actor to finish.
|
|
216
|
+
*/
|
|
217
|
+
_signalSlotEos;
|
|
218
|
+
/**
|
|
219
|
+
* Supervisor for this run, if any. Absent means no escalation is ever
|
|
220
|
+
* constructed and the actor behaves exactly as it did before — a clean run
|
|
221
|
+
* with no supervisor costs nothing, because nothing runs.
|
|
222
|
+
*/
|
|
223
|
+
_supervisor;
|
|
224
|
+
/** Records every escalation/verdict pair for `RunResult.interventions`. */
|
|
225
|
+
_onIntervention;
|
|
45
226
|
constructor(opts) {
|
|
46
227
|
this.node = opts.node;
|
|
47
228
|
this.inbox = opts.inbox;
|
|
@@ -49,8 +230,13 @@ export class NodeActor {
|
|
|
49
230
|
this._sendOutputs = opts.sendOutputs;
|
|
50
231
|
this._emitMessage = opts.emitMessage;
|
|
51
232
|
this._executionContext = opts.executionContext;
|
|
52
|
-
this.
|
|
233
|
+
this._listInputHandles = opts.listInputHandles ?? new Set();
|
|
53
234
|
this._controlContext = opts.controlContext ?? null;
|
|
235
|
+
this._correlation = opts.correlation;
|
|
236
|
+
this._cancelSignal = opts.cancelSignal ?? new AbortController().signal;
|
|
237
|
+
this._signalSlotEos = opts.signalSlotEos;
|
|
238
|
+
this._supervisor = opts.supervisor;
|
|
239
|
+
this._onIntervention = opts.onIntervention;
|
|
54
240
|
}
|
|
55
241
|
// -----------------------------------------------------------------------
|
|
56
242
|
// Main execution entry point
|
|
@@ -60,11 +246,16 @@ export class NodeActor {
|
|
|
60
246
|
* Returns the last outputs produced.
|
|
61
247
|
*/
|
|
62
248
|
async run() {
|
|
63
|
-
return withNodeSpan(
|
|
249
|
+
return withNodeSpan(
|
|
250
|
+
// Stryker disable next-line ObjectLiteral: OpenTelemetry span attributes are observability, not a behavioural contract
|
|
251
|
+
{ nodeId: this.node.id, nodeType: this.node.type }, () => this._runImpl());
|
|
64
252
|
}
|
|
65
253
|
async _runImpl() {
|
|
66
254
|
let errorMessage;
|
|
255
|
+
let errorDetail;
|
|
256
|
+
this._executionContext?.clearProviderCost?.();
|
|
67
257
|
try {
|
|
258
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
68
259
|
log.debug("Actor started", {
|
|
69
260
|
nodeId: this.node.id,
|
|
70
261
|
type: this.node.type
|
|
@@ -73,38 +264,22 @@ export class NodeActor {
|
|
|
73
264
|
if (this._executor.preProcess) {
|
|
74
265
|
await this._executor.preProcess();
|
|
75
266
|
}
|
|
76
|
-
|
|
77
|
-
if (this.node.is_streaming_input) {
|
|
78
|
-
if (this._executor.run) {
|
|
79
|
-
// Streaming input mode with run(): node drains inbox via
|
|
80
|
-
// NodeInputs and pushes outputs via NodeOutputs.
|
|
81
|
-
const nodeInputs = new NodeInputs(this.inbox);
|
|
82
|
-
const nodeOutputs = new NodeOutputs({
|
|
83
|
-
sendFn: async (slot, value) => {
|
|
84
|
-
await this._sendOutputs(this.node.id, { [slot]: value });
|
|
85
|
-
}
|
|
86
|
-
});
|
|
87
|
-
await this._executor.run(nodeInputs, nodeOutputs, this._executionContext);
|
|
88
|
-
this._latestResult = nodeOutputs.collected();
|
|
89
|
-
}
|
|
90
|
-
else {
|
|
91
|
-
// Legacy fallback: call process() once with empty inputs.
|
|
92
|
-
const outputs = await this._executor.process({}, this._executionContext);
|
|
93
|
-
this._latestResult = outputs;
|
|
94
|
-
await this._sendOutputs(this.node.id, outputs);
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
else if (this.node.is_controlled) {
|
|
98
|
-
// Controlled mode: wait for control events from inbox
|
|
99
|
-
await this._runControlled();
|
|
100
|
-
}
|
|
101
|
-
else {
|
|
102
|
-
// Standard buffered or streaming-output mode
|
|
103
|
-
await this._runBuffered();
|
|
104
|
-
}
|
|
267
|
+
await this._runExecutionMode();
|
|
105
268
|
}
|
|
106
269
|
catch (err) {
|
|
107
270
|
errorMessage = err instanceof Error ? err.message : String(err);
|
|
271
|
+
// A credential failure carries the provider and the key that failed,
|
|
272
|
+
// so the editor can send the user straight to the screen that fixes it
|
|
273
|
+
// instead of asking them to parse the message.
|
|
274
|
+
const failure = providerFailureDetail(err);
|
|
275
|
+
if (failure) {
|
|
276
|
+
errorDetail = {
|
|
277
|
+
code: failure.code,
|
|
278
|
+
provider: failure.provider,
|
|
279
|
+
secret_key: failure.secretKey
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
108
283
|
log.error("Actor failed", {
|
|
109
284
|
nodeId: this.node.id,
|
|
110
285
|
type: this.node.type,
|
|
@@ -123,9 +298,10 @@ export class NodeActor {
|
|
|
123
298
|
}
|
|
124
299
|
}
|
|
125
300
|
if (errorMessage !== undefined) {
|
|
126
|
-
this._emitNodeStatus("error", undefined, errorMessage);
|
|
301
|
+
this._emitNodeStatus("error", undefined, errorMessage, errorDetail);
|
|
127
302
|
return { outputs: {}, error: errorMessage };
|
|
128
303
|
}
|
|
304
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
129
305
|
log.debug("Actor completed", {
|
|
130
306
|
nodeId: this.node.id,
|
|
131
307
|
type: this.node.type
|
|
@@ -137,61 +313,969 @@ export class NodeActor {
|
|
|
137
313
|
this._emitNodeStatus("completed", skipResult ? undefined : (this._latestResult ?? {}));
|
|
138
314
|
return { outputs: this._latestResult ?? {} };
|
|
139
315
|
}
|
|
316
|
+
/**
|
|
317
|
+
* Run the node in whichever of the four execution modes applies.
|
|
318
|
+
*
|
|
319
|
+
* Trigger entry comes first: when this run was started by a delivered
|
|
320
|
+
* trigger event targeting this node, the node does not listen — it emits the
|
|
321
|
+
* event payload on its declared outputs via emitTriggerEvent() and
|
|
322
|
+
* completes. Runs without a trigger event (user pressed Run in the editor)
|
|
323
|
+
* fall through to the normal modes below, preserving the in-editor
|
|
324
|
+
* live-test experience.
|
|
325
|
+
*/
|
|
326
|
+
async _runExecutionMode() {
|
|
327
|
+
const triggerEvent = this._executionContext?.triggerEvent;
|
|
328
|
+
if (this.node.is_trigger &&
|
|
329
|
+
triggerEvent?.node_id === this.node.id &&
|
|
330
|
+
this._executor.emitTriggerEvent) {
|
|
331
|
+
return this._runTriggerEntry(triggerEvent);
|
|
332
|
+
}
|
|
333
|
+
if (this.node.type === LOOP_NODE_TYPE) {
|
|
334
|
+
return this._runLoopMode();
|
|
335
|
+
}
|
|
336
|
+
if (this.node.is_streaming_input) {
|
|
337
|
+
return this._executor.run
|
|
338
|
+
? this._runStreamingInputMode()
|
|
339
|
+
: this._runStreamingInputWithoutRun();
|
|
340
|
+
}
|
|
341
|
+
if (this.node.is_controlled) {
|
|
342
|
+
// Controlled mode: wait for control events from inbox
|
|
343
|
+
return this._runControlled();
|
|
344
|
+
}
|
|
345
|
+
if (!this._correlation) {
|
|
346
|
+
throw new Error(`Missing correlation analysis for node "${this.node.id}"`);
|
|
347
|
+
}
|
|
348
|
+
return this._runCorrelated(this._correlation);
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Loop mode: the kernel owns iteration, feedback matching, and termination
|
|
352
|
+
* for `nodetool.control.Loop`; the node's process() is never called.
|
|
353
|
+
* docs/workflow-loops.md.
|
|
354
|
+
*/
|
|
355
|
+
async _runLoopMode() {
|
|
356
|
+
if (!this._correlation) {
|
|
357
|
+
throw new Error(`Missing correlation analysis for node "${this.node.id}"`);
|
|
358
|
+
}
|
|
359
|
+
const result = {};
|
|
360
|
+
await runLoop({
|
|
361
|
+
node: this.node,
|
|
362
|
+
inbox: this.inbox,
|
|
363
|
+
analysis: this._correlation,
|
|
364
|
+
emit: async (slot, value, lineage) => {
|
|
365
|
+
result[slot] = value;
|
|
366
|
+
await this._route({ [slot]: value }, { perSlotLineage: { [slot]: lineage } });
|
|
367
|
+
},
|
|
368
|
+
closeSlot: (slot) => this._signalSlotEos?.(this.node.id, slot),
|
|
369
|
+
warn: (message) => this._emitNodeStatus("warning", undefined, message)
|
|
370
|
+
});
|
|
371
|
+
this._latestResult = result;
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Trigger entry: emit the delivered event's payload on the declared output
|
|
375
|
+
* slots and complete. One committed result per trigger event (RFC §5 site
|
|
376
|
+
* parity with the streaming-input run() path).
|
|
377
|
+
*/
|
|
378
|
+
async _runTriggerEntry(event) {
|
|
379
|
+
const nodeOutputs = new NodeOutputs({
|
|
380
|
+
sendFn: async (slot, value) => {
|
|
381
|
+
await this._sendOutputs(this.node.id, { [slot]: value });
|
|
382
|
+
},
|
|
383
|
+
eosCallback: (slot) => {
|
|
384
|
+
this._signalSlotEos?.(this.node.id, slot || "output");
|
|
385
|
+
}
|
|
386
|
+
});
|
|
387
|
+
await this._executor.emitTriggerEvent(event, nodeOutputs);
|
|
388
|
+
this._latestResult = nodeOutputs.collected();
|
|
389
|
+
this._emitGenerationComplete(this._latestResult);
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* Streaming input mode with run(): the node drains the inbox via NodeInputs
|
|
393
|
+
* and pushes outputs via NodeOutputs. Passing _lastEnvelopes as the tracker
|
|
394
|
+
* lets unmigrated filters that call inputs.stream()+outputs.emit() inherit
|
|
395
|
+
* lineage from the single-edge input automatically — matching the buffered
|
|
396
|
+
* rule.
|
|
397
|
+
*/
|
|
398
|
+
async _runStreamingInputMode() {
|
|
399
|
+
const nodeInputs = new NodeInputs(this.inbox, this._lastEnvelopes, this._correlation, this._cancelSignal);
|
|
400
|
+
const nodeOutputs = new NodeOutputs({
|
|
401
|
+
sendFn: async (slot, value, opts) => {
|
|
402
|
+
await this._route({ [slot]: value }, this._streamingEmitHints(slot, opts?.lineage));
|
|
403
|
+
},
|
|
404
|
+
emitGroupFn: async (values, opts) => {
|
|
405
|
+
await this._emitGroup(values, opts?.lineage);
|
|
406
|
+
},
|
|
407
|
+
eosCallback: (slot) => {
|
|
408
|
+
this._signalSlotEos?.(this.node.id, slot || "output");
|
|
409
|
+
},
|
|
410
|
+
dropFn: async (slot, envelope) => {
|
|
411
|
+
// outputs.drop(slot, envelope) → send `lineage_done` on every
|
|
412
|
+
// outgoing edge for `slot` at the envelope's projected key. §5. The
|
|
413
|
+
// drop signal lets downstream joins move past keys that were
|
|
414
|
+
// intentionally filtered out.
|
|
415
|
+
await this._propagateLineageDone(slot, envelope.correlation_lineage);
|
|
416
|
+
}
|
|
417
|
+
});
|
|
418
|
+
await this._runStreamingInput(nodeInputs, nodeOutputs);
|
|
419
|
+
this._latestResult = nodeOutputs.collected();
|
|
420
|
+
// Site #5 (RFC §5): streaming-input run() — one committed result.
|
|
421
|
+
this._emitGenerationComplete(this._latestResult);
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Routing hints for one `outputs.emit()` from a streaming-input node.
|
|
425
|
+
*
|
|
426
|
+
* An explicit lineage from the caller wins outright — they own the lineage
|
|
427
|
+
* shape (e.g. forward(), or a source seeding its own root). Otherwise the
|
|
428
|
+
* emit inherits the invocation lineage, and the slot's own
|
|
429
|
+
* `output_correlation` may override it for that one slot: an `aggregate`
|
|
430
|
+
* output collapses a root from the consumed lineage (the static analyzer
|
|
431
|
+
* drops it from the output scope; the runtime lineage must match), an
|
|
432
|
+
* `iteration` output mints a token per (group, parent_key) so
|
|
433
|
+
* `outputs.emit()` still attaches the new root. A slot declares one kind or
|
|
434
|
+
* the other, so at most one of the two applies.
|
|
435
|
+
*/
|
|
436
|
+
_streamingEmitHints(slot, callerLineage) {
|
|
437
|
+
if (callerLineage !== undefined) {
|
|
438
|
+
return { perSlotLineage: { [slot]: callerLineage } };
|
|
439
|
+
}
|
|
440
|
+
const hints = {};
|
|
441
|
+
const inherited = this._computeInvocationLineage();
|
|
442
|
+
if (inherited !== undefined) {
|
|
443
|
+
hints.invocationLineage = inherited;
|
|
444
|
+
}
|
|
445
|
+
const perSlot = this._maybeCollapseForSlot(slot, hints) ??
|
|
446
|
+
this._maybeMintForSlot(slot, hints);
|
|
447
|
+
if (perSlot !== undefined) {
|
|
448
|
+
hints.perSlotLineage = { [slot]: perSlot };
|
|
449
|
+
}
|
|
450
|
+
return hints;
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Streaming-input node declared without a run() implementation: call
|
|
454
|
+
* process() once with the node's own property values, matching the defaults
|
|
455
|
+
* merge every other execution path applies. process() reads no inbox data,
|
|
456
|
+
* so any value queued on a connected data handle is dropped. Surface that
|
|
457
|
+
* instead of completing silently: the node is misdeclared (registry says
|
|
458
|
+
* is_streaming_input, implementation has no run()). Downgraded to a warning
|
|
459
|
+
* rather than a hard error because existing fixtures rely on the fallback
|
|
460
|
+
* firing with connected inputs.
|
|
461
|
+
*/
|
|
462
|
+
async _runStreamingInputWithoutRun() {
|
|
463
|
+
const droppedHandles = this.inbox
|
|
464
|
+
.handles()
|
|
465
|
+
.filter((h) => h !== "__control__");
|
|
466
|
+
if (droppedHandles.length > 0) {
|
|
467
|
+
const warning = `streaming-input node ${this.node.type} has no run() ` +
|
|
468
|
+
`implementation but has connected inputs ` +
|
|
469
|
+
`(${droppedHandles.join(", ")}); data would be silently dropped`;
|
|
470
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
471
|
+
log.warn(warning, {
|
|
472
|
+
nodeId: this.node.id,
|
|
473
|
+
type: this.node.type
|
|
474
|
+
});
|
|
475
|
+
this._emitNodeStatus("warning", undefined, warning);
|
|
476
|
+
}
|
|
477
|
+
const outputs = await this._executor.process(this._applyDynamicSlots({
|
|
478
|
+
...(this.node.properties ?? {}),
|
|
479
|
+
...(this.node.dynamic_properties ?? {})
|
|
480
|
+
}), this._executionContext);
|
|
481
|
+
this._latestResult = outputs;
|
|
482
|
+
await this._sendOutputs(this.node.id, outputs);
|
|
483
|
+
// Site #3 (RFC §5): legacy single process() — one committed result.
|
|
484
|
+
this._emitGenerationComplete(outputs);
|
|
485
|
+
}
|
|
140
486
|
// -----------------------------------------------------------------------
|
|
141
|
-
//
|
|
487
|
+
// Correlated buffered scheduler (PR 3 of docs/correlation-design.md)
|
|
142
488
|
// -----------------------------------------------------------------------
|
|
143
489
|
/**
|
|
144
|
-
*
|
|
145
|
-
*
|
|
490
|
+
* Project an envelope's lineage onto a static scope, returning the
|
|
491
|
+
* canonical key or `null` if the lineage is incomplete for the scope.
|
|
492
|
+
*/
|
|
493
|
+
_projectKey(envelope, scope) {
|
|
494
|
+
return tryProjectLineageKey(envelope.correlation_lineage, scope);
|
|
495
|
+
}
|
|
496
|
+
/**
|
|
497
|
+
* Mint the next token index for `rootId` under `parentKey` and remember it.
|
|
498
|
+
* Counters never reset within one workflow run, matching §2's rule that
|
|
499
|
+
* repeated invocations with the same parent key continue numbering instead
|
|
500
|
+
* of restarting at 0.
|
|
146
501
|
*/
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
502
|
+
_mintIterationToken(rootId, parentKey) {
|
|
503
|
+
let perRoot = this._iterationCounters.get(rootId);
|
|
504
|
+
if (!perRoot) {
|
|
505
|
+
perRoot = new Map();
|
|
506
|
+
this._iterationCounters.set(rootId, perRoot);
|
|
507
|
+
}
|
|
508
|
+
const next = perRoot.get(parentKey) ?? 0;
|
|
509
|
+
perRoot.set(parentKey, next + 1);
|
|
510
|
+
return next;
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* Correlated buffered scheduler — replaces `_runBuffered` under
|
|
514
|
+
* correlation.
|
|
515
|
+
*
|
|
516
|
+
* Algorithm (v1 of §4):
|
|
517
|
+
* 1. Classify each connected data handle by its static scope:
|
|
518
|
+
* - max-scope: scope length == invocation scope length → bucket per key
|
|
519
|
+
* - strict-prefix sticky: shorter non-empty scope → sticky per projected
|
|
520
|
+
* parent key
|
|
521
|
+
* - empty: empty scope → single sticky entry
|
|
522
|
+
* 2. Find the repeating driver, if any: at most one max-scope handle may be
|
|
523
|
+
* `repeats_per_key`. Static validation already rejects more than one.
|
|
524
|
+
* 3. Pull envelopes via `iterAnyWithEnvelope`. On each arrival:
|
|
525
|
+
* - record into the right bucket,
|
|
526
|
+
* - re-evaluate the keys that could now be ready.
|
|
527
|
+
* 4. For each ready key, gather values and call `_executeWithInputs`.
|
|
528
|
+
*
|
|
529
|
+
* Source nodes (no connected data handles) fire once with empty inputs.
|
|
530
|
+
*/
|
|
531
|
+
async _runCorrelated(analysis) {
|
|
532
|
+
this._inCorrelatedBuffered = true;
|
|
533
|
+
try {
|
|
534
|
+
await this._runCorrelatedImpl(analysis);
|
|
535
|
+
}
|
|
536
|
+
finally {
|
|
537
|
+
this._inCorrelatedBuffered = false;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
async _runCorrelatedImpl(analysis) {
|
|
541
|
+
const dataHandles = this.inbox.handles().filter((h) => h !== "__control__");
|
|
542
|
+
if (dataHandles.length === 0) {
|
|
543
|
+
// Source node: fire once with empty inputs at empty scope.
|
|
152
544
|
await this._executeWithInputs({});
|
|
153
545
|
return;
|
|
154
546
|
}
|
|
155
|
-
|
|
156
|
-
|
|
547
|
+
const handleScope = new Map();
|
|
548
|
+
const handleClass = new Map();
|
|
549
|
+
const handleRepeats = new Map();
|
|
550
|
+
const invocationScope = analysis.invocationScope;
|
|
551
|
+
for (const h of dataHandles) {
|
|
552
|
+
const info = analysis.inputs.get(h);
|
|
553
|
+
const scope = info?.scope ?? [];
|
|
554
|
+
handleScope.set(h, scope);
|
|
555
|
+
handleRepeats.set(h, info?.repeatsPerKey ?? false);
|
|
556
|
+
// A repeating handle at the invocation scope is always "max" so the
|
|
557
|
+
// driver machinery fires once per envelope — including at root scope
|
|
558
|
+
// (both lengths 0, e.g. a chunk stream consumed at top level), where
|
|
559
|
+
// classifying it "empty" would make every chunk overwrite a single
|
|
560
|
+
// sticky slot and the node fire once with only the last chunk.
|
|
561
|
+
if (scope.length === invocationScope.length &&
|
|
562
|
+
(scope.length > 0 || handleRepeats.get(h))) {
|
|
563
|
+
handleClass.set(h, "max");
|
|
564
|
+
}
|
|
565
|
+
else if (scope.length === 0) {
|
|
566
|
+
handleClass.set(h, "empty");
|
|
567
|
+
}
|
|
568
|
+
else {
|
|
569
|
+
handleClass.set(h, "prefix");
|
|
570
|
+
}
|
|
157
571
|
}
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
572
|
+
const driverHandle = (() => {
|
|
573
|
+
for (const h of dataHandles) {
|
|
574
|
+
if (handleClass.get(h) === "max" && handleRepeats.get(h)) {
|
|
575
|
+
return h;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
return null;
|
|
579
|
+
})();
|
|
580
|
+
// Buckets keyed by canonical projected key.
|
|
581
|
+
const maxBuckets = new Map();
|
|
582
|
+
const prefixSticky = new Map();
|
|
583
|
+
const emptySticky = new Map();
|
|
584
|
+
// Handles already warned about empty-scope overwrite (§11): warn once per
|
|
585
|
+
// handle per run so an unmigrated stream collapsing to last-value-wins is
|
|
586
|
+
// visible without flooding the log.
|
|
587
|
+
const emptyStickyWarned = new Set();
|
|
588
|
+
// Multi-edge list inputs accumulate every envelope instead of
|
|
589
|
+
// overwriting; drained as an array when the node fires.
|
|
590
|
+
const emptyListEnvelopes = new Map();
|
|
591
|
+
const prefixListBuckets = new Map();
|
|
592
|
+
const isListInput = (h) => this._listInputHandles.has(h);
|
|
593
|
+
// A list-typed handle's declared element type is itself a list only for
|
|
594
|
+
// deliberate batch-of-batches properties (e.g. "list[list[int]]"); per-edge
|
|
595
|
+
// list values stay nested as one entry each in that case.
|
|
596
|
+
const isNestedListHandle = (h) => {
|
|
597
|
+
const typeStr = this.node.propertyTypes?.[h];
|
|
598
|
+
if (!typeStr)
|
|
599
|
+
return false;
|
|
600
|
+
const meta = TypeMetadata.fromString(typeStr);
|
|
601
|
+
return meta.isListType() && meta.args.length > 0 && meta.args[0].isListType();
|
|
602
|
+
};
|
|
603
|
+
// Aggregate per-edge values into one list for a list-typed handle. A list
|
|
604
|
+
// value arriving on a single edge (e.g. an upstream Image List's Output
|
|
605
|
+
// feeding another Image List's collect input) is spread into the result
|
|
606
|
+
// so its items propagate, rather than nesting the whole list as a single
|
|
607
|
+
// entry — unless the handle's declared type is itself a list of lists.
|
|
608
|
+
const aggregateListValues = (h, items) => {
|
|
609
|
+
if (isNestedListHandle(h))
|
|
610
|
+
return items;
|
|
611
|
+
const out = [];
|
|
612
|
+
for (const item of items) {
|
|
613
|
+
if (Array.isArray(item)) {
|
|
614
|
+
out.push(...item);
|
|
615
|
+
}
|
|
616
|
+
else {
|
|
617
|
+
out.push(item);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
return out;
|
|
621
|
+
};
|
|
622
|
+
for (const h of dataHandles) {
|
|
623
|
+
const cls = handleClass.get(h);
|
|
624
|
+
if (cls === "max")
|
|
625
|
+
maxBuckets.set(h, new Map());
|
|
626
|
+
else if (cls === "prefix") {
|
|
627
|
+
prefixSticky.set(h, new Map());
|
|
628
|
+
if (isListInput(h))
|
|
629
|
+
prefixListBuckets.set(h, new Map());
|
|
630
|
+
}
|
|
631
|
+
else if (cls === "empty" && isListInput(h)) {
|
|
632
|
+
emptyListEnvelopes.set(h, []);
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
const fired = new Set();
|
|
636
|
+
const isReady = (key) => {
|
|
637
|
+
for (const h of dataHandles) {
|
|
638
|
+
const cls = handleClass.get(h);
|
|
639
|
+
if (cls === "max") {
|
|
640
|
+
const bucket = maxBuckets.get(h).get(key);
|
|
641
|
+
if (!bucket || bucket.length === 0) {
|
|
642
|
+
// Not ready. v1 has no side-input sticky at max scope: a
|
|
643
|
+
// non-driver max handle must still have produced for this exact
|
|
644
|
+
// key, so the answer is `false` with or without a repeating
|
|
645
|
+
// driver.
|
|
646
|
+
return false;
|
|
647
|
+
}
|
|
648
|
+
// Multi-edge list inputs aggregate every envelope: wait for the
|
|
649
|
+
// handle to close so we capture the full set.
|
|
650
|
+
if (isListInput(h) && this.inbox.isOpen(h))
|
|
651
|
+
return false;
|
|
652
|
+
}
|
|
653
|
+
else if (cls === "prefix") {
|
|
654
|
+
const parentScope = handleScope.get(h);
|
|
655
|
+
const parentKey = trimKey(key, parentScope.length);
|
|
656
|
+
if (isListInput(h)) {
|
|
657
|
+
// Multi-edge list at prefix scope: wait for close so every
|
|
658
|
+
// envelope routed to this parentKey is captured.
|
|
659
|
+
if (this.inbox.isOpen(h))
|
|
660
|
+
return false;
|
|
661
|
+
const bucket = prefixListBuckets.get(h).get(parentKey);
|
|
662
|
+
if (!bucket || bucket.length === 0)
|
|
663
|
+
return false;
|
|
664
|
+
}
|
|
665
|
+
else {
|
|
666
|
+
const stickyMap = prefixSticky.get(h);
|
|
667
|
+
if (!stickyMap.has(parentKey))
|
|
668
|
+
return false;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
else {
|
|
672
|
+
// empty-scope sticky / list
|
|
673
|
+
if (isListInput(h)) {
|
|
674
|
+
// Multi-edge list at empty scope: wait for close to aggregate.
|
|
675
|
+
if (this.inbox.isOpen(h))
|
|
676
|
+
return false;
|
|
677
|
+
}
|
|
678
|
+
else if (!emptySticky.has(h)) {
|
|
679
|
+
// Allow node properties / dynamic_properties to supply defaults:
|
|
680
|
+
// _executeWithInputs already merges them (and type-checks the
|
|
681
|
+
// ones with a declared slot in dynamic_inputs). So an empty-scope
|
|
682
|
+
// handle without an envelope is treated as "use the node's
|
|
683
|
+
// declared default" if the handle has no open upstream.
|
|
684
|
+
if (this.inbox.isOpen(h))
|
|
685
|
+
return false;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
return true;
|
|
690
|
+
};
|
|
691
|
+
const collect = (key) => {
|
|
692
|
+
const values = {};
|
|
693
|
+
const envelopes = new Map();
|
|
694
|
+
for (const h of dataHandles) {
|
|
695
|
+
const cls = handleClass.get(h);
|
|
696
|
+
if (cls === "max") {
|
|
697
|
+
const bucket = maxBuckets.get(h).get(key);
|
|
698
|
+
if (!bucket || bucket.length === 0)
|
|
699
|
+
continue;
|
|
700
|
+
if (isListInput(h)) {
|
|
701
|
+
// Drain every envelope into a list; pick the last for lineage.
|
|
702
|
+
const drained = bucket.splice(0);
|
|
703
|
+
envelopes.set(h, drained[drained.length - 1]);
|
|
704
|
+
values[h] = aggregateListValues(h, drained.map((e) => e.data));
|
|
705
|
+
maxBuckets.get(h).delete(key);
|
|
706
|
+
}
|
|
707
|
+
else {
|
|
708
|
+
const stickySideInput = driverHandle !== null && h !== driverHandle;
|
|
709
|
+
const env = stickySideInput ? bucket[0] : bucket.shift();
|
|
710
|
+
envelopes.set(h, env);
|
|
711
|
+
values[h] = env.data;
|
|
712
|
+
if (!stickySideInput && bucket.length === 0) {
|
|
713
|
+
maxBuckets.get(h).delete(key);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
else if (cls === "prefix") {
|
|
718
|
+
const parentScope = handleScope.get(h);
|
|
719
|
+
const parentKey = trimKey(key, parentScope.length);
|
|
720
|
+
if (isListInput(h)) {
|
|
721
|
+
const bucket = prefixListBuckets.get(h).get(parentKey);
|
|
722
|
+
if (bucket && bucket.length > 0) {
|
|
723
|
+
envelopes.set(h, bucket[bucket.length - 1]);
|
|
724
|
+
values[h] = aggregateListValues(h, bucket.map((e) => e.data));
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
else {
|
|
728
|
+
const env = prefixSticky.get(h).get(parentKey);
|
|
729
|
+
if (env) {
|
|
730
|
+
envelopes.set(h, env);
|
|
731
|
+
values[h] = env.data;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
else {
|
|
736
|
+
if (isListInput(h)) {
|
|
737
|
+
const envs = emptyListEnvelopes.get(h) ?? [];
|
|
738
|
+
if (envs.length > 0) {
|
|
739
|
+
envelopes.set(h, envs[envs.length - 1]);
|
|
740
|
+
values[h] = aggregateListValues(h, envs.map((e) => e.data));
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
else {
|
|
744
|
+
const env = emptySticky.get(h);
|
|
745
|
+
if (env) {
|
|
746
|
+
envelopes.set(h, env);
|
|
747
|
+
values[h] = env.data;
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
return { values, envelopes };
|
|
753
|
+
};
|
|
754
|
+
const tryFire = async (candidateKeys) => {
|
|
755
|
+
for (const key of candidateKeys) {
|
|
756
|
+
if (driverHandle === null) {
|
|
757
|
+
if (fired.has(key)) {
|
|
758
|
+
// For non-repeating drivers each key fires at most once because
|
|
759
|
+
// bucket consumption strips it. The fired set protects against
|
|
760
|
+
// double-fire when the same key comes from multiple notifications.
|
|
761
|
+
continue;
|
|
762
|
+
}
|
|
763
|
+
if (!isReady(key))
|
|
764
|
+
continue;
|
|
765
|
+
const { values, envelopes } = collect(key);
|
|
766
|
+
// Set per-invocation envelopes so output routing can derive lineage.
|
|
767
|
+
this._lastEnvelopes = envelopes;
|
|
768
|
+
await this._executeWithInputs(values);
|
|
769
|
+
fired.add(key);
|
|
770
|
+
}
|
|
771
|
+
else {
|
|
772
|
+
// Repeating driver: drain the whole backlog for this key, not just
|
|
773
|
+
// one envelope. Envelopes can pile up while a sticky input blocks
|
|
774
|
+
// readiness; firing once per notification would strand the rest in
|
|
775
|
+
// the actor-local bucket (silent data loss). collect() consumes one
|
|
776
|
+
// driver envelope per pass, so this loop terminates.
|
|
777
|
+
while (isReady(key)) {
|
|
778
|
+
const { values, envelopes } = collect(key);
|
|
779
|
+
this._lastEnvelopes = envelopes;
|
|
780
|
+
await this._executeWithInputs(values);
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
};
|
|
785
|
+
// Pre-seed: if any handle starts with no upstream (closed), nothing
|
|
786
|
+
// arrives. Continue and let the loop terminate.
|
|
787
|
+
for await (const [handle, envelope] of this.inbox.iterAnyWithEnvelope()) {
|
|
788
|
+
if (handle === "__control__")
|
|
789
|
+
continue;
|
|
790
|
+
const cls = handleClass.get(handle);
|
|
791
|
+
if (cls === undefined)
|
|
792
|
+
continue;
|
|
793
|
+
if (cls === "max") {
|
|
794
|
+
const scope = handleScope.get(handle);
|
|
795
|
+
const key = this._projectKey(envelope, scope) ?? "";
|
|
796
|
+
const handleBuckets = maxBuckets.get(handle);
|
|
797
|
+
let bucket = handleBuckets.get(key);
|
|
798
|
+
if (!bucket) {
|
|
799
|
+
if (handleBuckets.size >= this.inbox.maxPendingKeys) {
|
|
800
|
+
throw new Error(`Inbox for node "${this.node.id}" exceeded max_pending_keys ` +
|
|
801
|
+
`(${this.inbox.maxPendingKeys}) on handle "${handle}". ` +
|
|
802
|
+
`Likely missing upstream close — see docs/correlation-design.md §6.`);
|
|
803
|
+
}
|
|
804
|
+
bucket = [];
|
|
805
|
+
handleBuckets.set(key, bucket);
|
|
806
|
+
}
|
|
807
|
+
if (bucket.length >= this.inbox.maxPendingMessagesPerKey) {
|
|
808
|
+
throw new Error(`Inbox for node "${this.node.id}" exceeded ` +
|
|
809
|
+
`max_pending_messages_per_key (` +
|
|
810
|
+
`${this.inbox.maxPendingMessagesPerKey}) on handle "${handle}" ` +
|
|
811
|
+
`for key "${key}".`);
|
|
812
|
+
}
|
|
813
|
+
bucket.push(envelope);
|
|
814
|
+
await tryFire([key]);
|
|
815
|
+
}
|
|
816
|
+
else if (cls === "prefix") {
|
|
817
|
+
const parentScope = handleScope.get(handle);
|
|
818
|
+
const parentKey = this._projectKey(envelope, parentScope) ?? "";
|
|
819
|
+
if (isListInput(handle)) {
|
|
820
|
+
const handleBuckets = prefixListBuckets.get(handle);
|
|
821
|
+
let bucket = handleBuckets.get(parentKey);
|
|
822
|
+
if (!bucket) {
|
|
823
|
+
bucket = [];
|
|
824
|
+
handleBuckets.set(parentKey, bucket);
|
|
825
|
+
}
|
|
826
|
+
bucket.push(envelope);
|
|
827
|
+
}
|
|
828
|
+
else {
|
|
829
|
+
prefixSticky.get(handle).set(parentKey, envelope);
|
|
830
|
+
}
|
|
831
|
+
// Try firing any max-scope keys whose parent matches this parentKey.
|
|
832
|
+
const candidates = enumerateCandidateKeysForParent(maxBuckets, dataHandles, handleClass, handleScope, invocationScope.length, parentKey, parentScope.length);
|
|
833
|
+
await tryFire(candidates);
|
|
834
|
+
}
|
|
835
|
+
else {
|
|
836
|
+
if (isListInput(handle)) {
|
|
837
|
+
emptyListEnvelopes.get(handle).push(envelope);
|
|
838
|
+
}
|
|
839
|
+
else {
|
|
840
|
+
if (emptySticky.has(handle) && !emptyStickyWarned.has(handle)) {
|
|
841
|
+
emptyStickyWarned.add(handle);
|
|
842
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
843
|
+
log.warn(`Node "${this.node.id}" handle "${handle}" received multiple ` +
|
|
844
|
+
// Stryker disable next-line StringLiteral: diagnostic log args only
|
|
845
|
+
`values at empty scope; only the last is kept. Declare ` +
|
|
846
|
+
// Stryker disable next-line StringLiteral: diagnostic log args only
|
|
847
|
+
`output_correlation (chunk/iteration) on the upstream output ` +
|
|
848
|
+
// Stryker disable next-line StringLiteral: diagnostic log args only
|
|
849
|
+
`to preserve the stream.`,
|
|
850
|
+
// Stryker disable next-line ObjectLiteral: diagnostic log args only
|
|
851
|
+
{ nodeId: this.node.id, handle });
|
|
852
|
+
}
|
|
853
|
+
emptySticky.set(handle, envelope);
|
|
854
|
+
}
|
|
855
|
+
// Empty-scope arrival can unblock any pending max-scope key.
|
|
856
|
+
const candidates = enumerateAllPendingKeys(maxBuckets);
|
|
857
|
+
await tryFire(candidates);
|
|
858
|
+
}
|
|
166
859
|
}
|
|
860
|
+
// After iteration ends, every handle is closed. Multi-edge list inputs
|
|
861
|
+
// gated on close are now ready: re-fire any pending max-scope keys.
|
|
862
|
+
await tryFire(enumerateAllPendingKeys(maxBuckets));
|
|
863
|
+
// If the node has no max-scope inputs (all empty / prefix), fire once.
|
|
864
|
+
if ([...handleClass.values()].every((c) => c !== "max") && !fired.has("")) {
|
|
865
|
+
// Build values from sticky state.
|
|
866
|
+
const values = {};
|
|
867
|
+
const envelopes = new Map();
|
|
868
|
+
let readyOrAllowed = true;
|
|
869
|
+
for (const h of dataHandles) {
|
|
870
|
+
if (handleClass.get(h) === "prefix") {
|
|
871
|
+
if (isListInput(h)) {
|
|
872
|
+
// Aggregate every envelope across all parentKeys.
|
|
873
|
+
const handleBuckets = prefixListBuckets.get(h);
|
|
874
|
+
const drained = [];
|
|
875
|
+
for (const bucket of handleBuckets.values()) {
|
|
876
|
+
drained.push(...bucket);
|
|
877
|
+
}
|
|
878
|
+
if (drained.length === 0)
|
|
879
|
+
continue;
|
|
880
|
+
envelopes.set(h, drained[drained.length - 1]);
|
|
881
|
+
values[h] = aggregateListValues(h, drained.map((e) => e.data));
|
|
882
|
+
}
|
|
883
|
+
else {
|
|
884
|
+
// Use the only sticky entry, if any.
|
|
885
|
+
const sticky = prefixSticky.get(h);
|
|
886
|
+
if (sticky.size === 0) {
|
|
887
|
+
// No value arrived; defaults will apply in _executeWithInputs.
|
|
888
|
+
continue;
|
|
889
|
+
}
|
|
890
|
+
const first = sticky.values().next().value;
|
|
891
|
+
envelopes.set(h, first);
|
|
892
|
+
values[h] = first.data;
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
else if (isListInput(h)) {
|
|
896
|
+
const envs = emptyListEnvelopes.get(h) ?? [];
|
|
897
|
+
if (envs.length > 0) {
|
|
898
|
+
envelopes.set(h, envs[envs.length - 1]);
|
|
899
|
+
values[h] = aggregateListValues(h, envs.map((e) => e.data));
|
|
900
|
+
}
|
|
901
|
+
else if (this.inbox.isOpen(h)) {
|
|
902
|
+
readyOrAllowed = false;
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
else {
|
|
906
|
+
const env = emptySticky.get(h);
|
|
907
|
+
if (env) {
|
|
908
|
+
envelopes.set(h, env);
|
|
909
|
+
values[h] = env.data;
|
|
910
|
+
}
|
|
911
|
+
else if (this.inbox.isOpen(h)) {
|
|
912
|
+
readyOrAllowed = false;
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
// A node wired to data inputs that received nothing on any of them is on
|
|
917
|
+
// an untaken branch: its upstreams all closed without emitting (an `If`
|
|
918
|
+
// emits only the taken handle, a filter can emit nothing at all). Firing
|
|
919
|
+
// it here would run it on its declared defaults — an Agent node with an
|
|
920
|
+
// empty prompt burning a model call, the untaken half of every
|
|
921
|
+
// conditional doing work nobody asked for. Skip instead, which closes
|
|
922
|
+
// this node's outputs with nothing and cascades the skip downstream.
|
|
923
|
+
//
|
|
924
|
+
// Partial input still fires: a node that got a value on one handle and
|
|
925
|
+
// nothing on another runs with defaults for the missing one, as before.
|
|
926
|
+
// Only "wired to something, received nothing" is treated as untaken.
|
|
927
|
+
const receivedNothing = dataHandles.length > 0 && envelopes.size === 0;
|
|
928
|
+
if (receivedNothing) {
|
|
929
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
930
|
+
log.debug("Skipping node on untaken branch", {
|
|
931
|
+
nodeId: this.node.id,
|
|
932
|
+
type: this.node.type
|
|
933
|
+
});
|
|
934
|
+
}
|
|
935
|
+
else if (readyOrAllowed) {
|
|
936
|
+
this._lastEnvelopes = envelopes;
|
|
937
|
+
await this._executeWithInputs(values);
|
|
938
|
+
fired.add("");
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
// Envelopes still stranded in actor-local buckets at close are invisible to
|
|
942
|
+
// the runner's post-run pending-inbox check (they were already popped). §12.
|
|
943
|
+
// With no repeating driver a key fires at most once, so a second max-scope
|
|
944
|
+
// envelope for an already-fired key is dropped silently; a key that never
|
|
945
|
+
// reached readiness keeps its envelopes too. Warn for both so the loss is
|
|
946
|
+
// not silent. Scheduling is unchanged.
|
|
947
|
+
for (const [handle, buckets] of maxBuckets) {
|
|
948
|
+
for (const [key, bucket] of buckets) {
|
|
949
|
+
if (bucket.length === 0)
|
|
950
|
+
continue;
|
|
951
|
+
if (fired.has(key)) {
|
|
952
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
953
|
+
log.warn(`Node "${this.node.id}" dropped ${bucket.length} envelope(s) on ` +
|
|
954
|
+
// Stryker disable next-line StringLiteral: diagnostic log args only
|
|
955
|
+
`handle "${handle}" for key "${key}" already fired without a ` +
|
|
956
|
+
// Stryker disable next-line StringLiteral: diagnostic log args only
|
|
957
|
+
`repeating driver; declare output_correlation to fan out per ` +
|
|
958
|
+
// Stryker disable next-line StringLiteral: diagnostic log args only
|
|
959
|
+
`item.`,
|
|
960
|
+
// Stryker disable next-line ObjectLiteral: diagnostic log args only
|
|
961
|
+
{ nodeId: this.node.id, handle, key, count: bucket.length });
|
|
962
|
+
}
|
|
963
|
+
else {
|
|
964
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
965
|
+
log.warn(`Node "${this.node.id}" left ${bucket.length} envelope(s) on ` +
|
|
966
|
+
// Stryker disable next-line StringLiteral: diagnostic log args only
|
|
967
|
+
`handle "${handle}" for key "${key}" unfired at close; its ` +
|
|
968
|
+
// Stryker disable next-line StringLiteral: diagnostic log args only
|
|
969
|
+
`inputs never completed for this key.`,
|
|
970
|
+
// Stryker disable next-line ObjectLiteral: diagnostic log args only
|
|
971
|
+
{ nodeId: this.node.id, handle, key, count: bucket.length });
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
// -----------------------------------------------------------------------
|
|
977
|
+
// Correlated invocation lineage and output routing
|
|
978
|
+
// -----------------------------------------------------------------------
|
|
979
|
+
/**
|
|
980
|
+
* Under the correlated scheduler the invocation lineage is the projected
|
|
981
|
+
* lineage of the consumed max-scope envelopes, written canonically. PR 2's
|
|
982
|
+
* fallback (single non-list handle) still applies when the analyzer is not
|
|
983
|
+
* available.
|
|
984
|
+
*/
|
|
985
|
+
_correlatedInvocationLineage() {
|
|
986
|
+
if (!this._correlation)
|
|
987
|
+
return undefined;
|
|
988
|
+
const invocationScope = this._correlation.invocationScope;
|
|
989
|
+
if (invocationScope.length === 0) {
|
|
990
|
+
// For empty-scope nodes the lineage is also empty.
|
|
991
|
+
return EMPTY_LINEAGE;
|
|
992
|
+
}
|
|
993
|
+
// Build a lineage from the longest projection any consumed envelope
|
|
994
|
+
// supplies. Max-scope envelopes have the complete projection; prefix
|
|
995
|
+
// envelopes contribute parent roots only.
|
|
996
|
+
const out = {};
|
|
997
|
+
for (const env of this._lastEnvelopes.values()) {
|
|
998
|
+
for (const root of invocationScope) {
|
|
999
|
+
if (root in env.correlation_lineage) {
|
|
1000
|
+
out[root] = env.correlation_lineage[root];
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
return out;
|
|
167
1005
|
}
|
|
168
1006
|
/**
|
|
169
|
-
*
|
|
170
|
-
*
|
|
1007
|
+
* Build the per-slot lineage map for an emission. Single/forward/chunk
|
|
1008
|
+
* outputs inherit the invocation lineage; iteration outputs mint a token
|
|
1009
|
+
* per group per frame.
|
|
171
1010
|
*/
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
1011
|
+
_correlatedOutputLineage(invocationLineage, emittedHandles) {
|
|
1012
|
+
if (!this._correlation)
|
|
1013
|
+
return undefined;
|
|
1014
|
+
const declared = this.node.output_correlation ?? {};
|
|
1015
|
+
const perSlot = {};
|
|
1016
|
+
const groupTokens = new Map();
|
|
1017
|
+
const invocationScope = this._correlation.invocationScope;
|
|
1018
|
+
const parentKey = invocationScope.length
|
|
1019
|
+
? projectLineageKey(invocationLineage, invocationScope)
|
|
1020
|
+
: "";
|
|
1021
|
+
for (const handle of emittedHandles) {
|
|
1022
|
+
const corr = declared[handle];
|
|
1023
|
+
if (!corr) {
|
|
1024
|
+
perSlot[handle] = invocationLineage;
|
|
178
1025
|
continue;
|
|
179
|
-
|
|
180
|
-
if (
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
1026
|
+
}
|
|
1027
|
+
if (corr.kind === "iteration") {
|
|
1028
|
+
const root = iterationRootId(this.node.id, handle, corr.group);
|
|
1029
|
+
let index = groupTokens.get(root);
|
|
1030
|
+
if (index === undefined) {
|
|
1031
|
+
// Reuse the token already minted for this frame, if any
|
|
1032
|
+
// (`_mintIterationFrameOverrides` mints before _sendOutputs runs).
|
|
1033
|
+
const fromFrame = this._lastMintedFrameTokens.get(root);
|
|
1034
|
+
if (fromFrame !== undefined) {
|
|
1035
|
+
index = fromFrame;
|
|
1036
|
+
}
|
|
1037
|
+
else {
|
|
1038
|
+
index = this._mintIterationToken(root, parentKey);
|
|
1039
|
+
}
|
|
1040
|
+
groupTokens.set(root, index);
|
|
1041
|
+
}
|
|
1042
|
+
perSlot[handle] = { ...invocationLineage, [root]: { index } };
|
|
186
1043
|
}
|
|
187
1044
|
else {
|
|
188
|
-
|
|
1045
|
+
// single/forward/chunk all inherit invocation lineage in v1.
|
|
1046
|
+
// forward outputs route their source envelope's lineage via
|
|
1047
|
+
// outputs.forward(); the static path is invocation lineage.
|
|
1048
|
+
perSlot[handle] = invocationLineage;
|
|
189
1049
|
}
|
|
190
1050
|
}
|
|
1051
|
+
return perSlot;
|
|
1052
|
+
}
|
|
1053
|
+
/**
|
|
1054
|
+
* Coerce and check every input that has a declared dynamic slot on this
|
|
1055
|
+
* node (`dynamic_inputs`). Slots without a declaration are untyped and
|
|
1056
|
+
* pass through untouched. Throws on a value that cannot fit its declared
|
|
1057
|
+
* type; the caller's catch turns that into a node error.
|
|
1058
|
+
*/
|
|
1059
|
+
_applyDynamicSlots(inputs) {
|
|
1060
|
+
return applyDynamicSlotTypes(this.node, inputs);
|
|
191
1061
|
}
|
|
192
1062
|
/**
|
|
193
1063
|
* Execute process or genProcess with the given inputs.
|
|
194
1064
|
*/
|
|
1065
|
+
/**
|
|
1066
|
+
* Run one invocation under the supervisor, if there is one.
|
|
1067
|
+
*
|
|
1068
|
+
* The catch wraps node execution and nothing else. `sendOutputs` routes to
|
|
1069
|
+
* downstream inboxes sequentially, so if edge 1 delivered and edge 2 threw, a
|
|
1070
|
+
* retry would duplicate edge 1's delivery — routing failures therefore fail
|
|
1071
|
+
* the node without escalation. Design §5.1.
|
|
1072
|
+
*
|
|
1073
|
+
* Returns the outputs to route, or `SKIPPED` when the invocation was retired
|
|
1074
|
+
* without emitting.
|
|
1075
|
+
*/
|
|
1076
|
+
async _invokeWithRecovery(inputs, invoke) {
|
|
1077
|
+
for (let attempt = 1;; attempt++) {
|
|
1078
|
+
// A fresh account per attempt: what the previous try spent is not what
|
|
1079
|
+
// this one spent.
|
|
1080
|
+
const account = createInvocationAccount();
|
|
1081
|
+
try {
|
|
1082
|
+
return await inInvocationAccount(account, invoke);
|
|
1083
|
+
}
|
|
1084
|
+
catch (err) {
|
|
1085
|
+
if (!this._supervisor) {
|
|
1086
|
+
if (!this._degradeOnContentFilter(err, false))
|
|
1087
|
+
throw err;
|
|
1088
|
+
await this._skipInvocation();
|
|
1089
|
+
return SKIPPED;
|
|
1090
|
+
}
|
|
1091
|
+
const verdict = await this._escalate(err, inputs, attempt, account, {
|
|
1092
|
+
streamingOutput: false,
|
|
1093
|
+
streamingInput: false,
|
|
1094
|
+
emitted: false
|
|
1095
|
+
});
|
|
1096
|
+
switch (verdict.action) {
|
|
1097
|
+
case "retry":
|
|
1098
|
+
continue;
|
|
1099
|
+
// `_escalate` only returns `substitute` for outputs that passed
|
|
1100
|
+
// validation, so what comes back here is ready to route.
|
|
1101
|
+
case "substitute":
|
|
1102
|
+
return verdict.outputs;
|
|
1103
|
+
case "skip":
|
|
1104
|
+
await this._skipInvocation();
|
|
1105
|
+
return SKIPPED;
|
|
1106
|
+
default:
|
|
1107
|
+
throw err;
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
/**
|
|
1113
|
+
* Build the escalation, ask the supervisor, and enforce the allowed set
|
|
1114
|
+
* against whatever comes back. The schema shown to an agent is UX; this check
|
|
1115
|
+
* is the guarantee — a buggy or third-party handle returning `retry` for an
|
|
1116
|
+
* unsafe node gets `fail`.
|
|
1117
|
+
*/
|
|
1118
|
+
async _escalate(err, inputs, attempt, account, mode) {
|
|
1119
|
+
const escalation = this._buildEscalation(err, inputs, attempt, account, mode);
|
|
1120
|
+
this._emitMessage({
|
|
1121
|
+
type: "supervisor_escalation",
|
|
1122
|
+
node_id: this.node.id,
|
|
1123
|
+
node_name: this.node.name ?? this.node.type,
|
|
1124
|
+
escalation
|
|
1125
|
+
});
|
|
1126
|
+
let outcome;
|
|
1127
|
+
try {
|
|
1128
|
+
outcome = await this._supervisor.decide(escalation, this._cancelSignal);
|
|
1129
|
+
}
|
|
1130
|
+
catch {
|
|
1131
|
+
// A failure *of* the supervisor, which is what the bounds exist to
|
|
1132
|
+
// absorb — same class, and so the same label, as a timed-out decision.
|
|
1133
|
+
outcome = { verdict: { action: "fail" }, decidedBy: "bounds" };
|
|
1134
|
+
}
|
|
1135
|
+
// The record has to name who produced the verdict that was *applied*. When
|
|
1136
|
+
// the kernel overrules a handle, crediting the handle would hide exactly
|
|
1137
|
+
// the case worth finding: a buggy or hostile supervisor. A repair whose
|
|
1138
|
+
// values do not match the node's declared outputs is overruled here, not
|
|
1139
|
+
// after the fact: the intervention must record what happened, and a
|
|
1140
|
+
// rejected repair is a `fail`, not a repair.
|
|
1141
|
+
const allowed = escalation.allowedActions.includes(outcome.verdict.action) &&
|
|
1142
|
+
(outcome.verdict.action !== "substitute" ||
|
|
1143
|
+
(await this._validateSubstitute(outcome.verdict.outputs)));
|
|
1144
|
+
const verdict = allowed ? outcome.verdict : { action: "fail" };
|
|
1145
|
+
const decidedBy = allowed ? outcome.decidedBy : "kernel";
|
|
1146
|
+
this._emitMessage({
|
|
1147
|
+
type: "supervisor_decision",
|
|
1148
|
+
node_id: this.node.id,
|
|
1149
|
+
node_name: this.node.name ?? this.node.type,
|
|
1150
|
+
escalation,
|
|
1151
|
+
verdict,
|
|
1152
|
+
decided_by: decidedBy,
|
|
1153
|
+
cost: outcome.costUsd ?? null
|
|
1154
|
+
});
|
|
1155
|
+
this._onIntervention?.({
|
|
1156
|
+
escalation,
|
|
1157
|
+
verdict,
|
|
1158
|
+
decidedBy,
|
|
1159
|
+
costUsd: outcome.costUsd
|
|
1160
|
+
});
|
|
1161
|
+
return verdict;
|
|
1162
|
+
}
|
|
1163
|
+
/**
|
|
1164
|
+
* Mint the escalation record. Redaction happens *here*, not at some later
|
|
1165
|
+
* prompt: `Escalation` is public — it becomes a message, lands in
|
|
1166
|
+
* `RunResult.interventions`, and crosses the websocket — so no unredacted
|
|
1167
|
+
* instance may exist anywhere in the system. Design §6.1.
|
|
1168
|
+
*/
|
|
1169
|
+
_buildEscalation(err, inputs, attempt, account, mode) {
|
|
1170
|
+
const secrets = this._executionContext?.getResolvedSecretValues?.() ?? new Set();
|
|
1171
|
+
const lineage = this._currentInvocationLineage ?? EMPTY_LINEAGE;
|
|
1172
|
+
const invocationScope = this._correlation?.invocationScope ?? [];
|
|
1173
|
+
const invocationKey = invocationScope.length
|
|
1174
|
+
? projectLineageKey(lineage, invocationScope)
|
|
1175
|
+
: "";
|
|
1176
|
+
const recoverable = isRecoverableNodeError(err) ? err : undefined;
|
|
1177
|
+
const candidateOutput = recoverable
|
|
1178
|
+
? redactValue(recoverable.candidateOutput, secrets)
|
|
1179
|
+
: undefined;
|
|
1180
|
+
const allowedActions = computeAllowedActions({
|
|
1181
|
+
retrySafe: this.node.retry_safe === true,
|
|
1182
|
+
spentCostUsd: account?.costUsd ?? 0,
|
|
1183
|
+
createdAssets: account?.createdAssets ?? false,
|
|
1184
|
+
hasCandidateOutput: recoverable !== undefined,
|
|
1185
|
+
validatorCoverage: hasFullValidatorCoverage(this.node.outputs ?? {},
|
|
1186
|
+
// Resolving a reference against run storage needs a resolver the
|
|
1187
|
+
// kernel does not have yet, so reference-typed outputs are not
|
|
1188
|
+
// substitutable — better than accepting an unresolvable ref.
|
|
1189
|
+
false),
|
|
1190
|
+
...mode
|
|
1191
|
+
});
|
|
1192
|
+
return {
|
|
1193
|
+
nodeId: this.node.id,
|
|
1194
|
+
nodeType: this.node.type,
|
|
1195
|
+
correlationLineage: invocationKey === "" ? [] : invocationKey.split(","),
|
|
1196
|
+
invocationKey,
|
|
1197
|
+
allowedActions,
|
|
1198
|
+
detail: String(redactValue(err instanceof Error ? err.message : String(err), secrets)),
|
|
1199
|
+
failureSignature: recoverable?.code ?? failureSignature(err),
|
|
1200
|
+
candidateOutput,
|
|
1201
|
+
inputs: redactRecord(inputs, secrets),
|
|
1202
|
+
declaredOutputs: this.node.outputs ?? {},
|
|
1203
|
+
attempt,
|
|
1204
|
+
spentCostUsd: account?.costUsd ?? 0,
|
|
1205
|
+
createdAssets: account?.createdAssets ?? false,
|
|
1206
|
+
retrySafe: this.node.retry_safe === true,
|
|
1207
|
+
emitted: mode.emitted
|
|
1208
|
+
};
|
|
1209
|
+
}
|
|
1210
|
+
/**
|
|
1211
|
+
* A repaired value is type-checked against the node's declared outputs
|
|
1212
|
+
* before it enters the graph. An invalid repair is not a repair.
|
|
1213
|
+
*/
|
|
1214
|
+
async _validateSubstitute(outputs) {
|
|
1215
|
+
const declared = this.node.outputs ?? {};
|
|
1216
|
+
const result = await validateSubstituteOutputs(outputs, {
|
|
1217
|
+
declaredOutputs: declared
|
|
1218
|
+
});
|
|
1219
|
+
if (!result.ok) {
|
|
1220
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
1221
|
+
log.warn("Rejected supervisor substitution", {
|
|
1222
|
+
nodeId: this.node.id,
|
|
1223
|
+
issues: result.issues
|
|
1224
|
+
});
|
|
1225
|
+
}
|
|
1226
|
+
return result.ok;
|
|
1227
|
+
}
|
|
1228
|
+
/**
|
|
1229
|
+
* Retire this invocation without emitting: `lineage_done` plus scope closure
|
|
1230
|
+
* on every outgoing edge, so downstream joins move past the skipped key and
|
|
1231
|
+
* aggregates see the scopes the invocation would have opened get closed.
|
|
1232
|
+
*/
|
|
1233
|
+
async _skipInvocation() {
|
|
1234
|
+
await this._sendOutputs(this.node.id, {}, {
|
|
1235
|
+
skipInvocation: true,
|
|
1236
|
+
invocationLineage: this._currentInvocationLineage ?? EMPTY_LINEAGE
|
|
1237
|
+
});
|
|
1238
|
+
}
|
|
1239
|
+
/**
|
|
1240
|
+
* Whether to drop this item instead of the run, after the provider's own
|
|
1241
|
+
* bounded retries failed to get past its content filter. The built-in policy
|
|
1242
|
+
* for an unsupervised run — a supervised one escalates instead, because
|
|
1243
|
+
* putting an agent on the failure path is what `--supervise` is for.
|
|
1244
|
+
*
|
|
1245
|
+
* Veo filtered one shot of a five-shot trailer on an ordinary cinematic
|
|
1246
|
+
* prompt. Failing the node there fails the run and discards the four shots
|
|
1247
|
+
* already generated and paid for, which is worse than delivering a four-shot
|
|
1248
|
+
* cut and saying which shot was refused.
|
|
1249
|
+
*
|
|
1250
|
+
* Only for an invocation that is one item of a fan-out: a non-empty
|
|
1251
|
+
* correlation lineage says an upstream item keyed this invocation, so the
|
|
1252
|
+
* siblings are real work a failure would throw away. A single-shot node has
|
|
1253
|
+
* no siblings to protect and still fails loudly. An invocation that already
|
|
1254
|
+
* emitted is out too — its partial output is downstream, so retiring the
|
|
1255
|
+
* lineage now would tell joins nothing arrived.
|
|
1256
|
+
*/
|
|
1257
|
+
_degradeOnContentFilter(err, emitted) {
|
|
1258
|
+
if (emitted || !isContentFilterRefusal(err))
|
|
1259
|
+
return false;
|
|
1260
|
+
const lineage = this._currentInvocationLineage;
|
|
1261
|
+
if (!lineage || Object.keys(lineage).length === 0)
|
|
1262
|
+
return false;
|
|
1263
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
1264
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
1265
|
+
log.warn("Dropping content-filtered item", {
|
|
1266
|
+
nodeId: this.node.id,
|
|
1267
|
+
type: this.node.type,
|
|
1268
|
+
detail
|
|
1269
|
+
});
|
|
1270
|
+
this._emitMessage({
|
|
1271
|
+
type: "log_update",
|
|
1272
|
+
node_id: this.node.id,
|
|
1273
|
+
node_name: this.node.name ?? this.node.type,
|
|
1274
|
+
severity: "warning",
|
|
1275
|
+
content: `Dropped one item: the provider's content filter refused it and retrying did not clear it. The rest of the run continues. ${detail}`
|
|
1276
|
+
});
|
|
1277
|
+
return true;
|
|
1278
|
+
}
|
|
195
1279
|
async _executeWithInputs(inputs) {
|
|
196
1280
|
// Merge node properties as defaults — edge inputs override.
|
|
197
1281
|
// This matches Python's behavior where process() always receives
|
|
@@ -204,35 +1288,375 @@ export class NodeActor {
|
|
|
204
1288
|
...inputs
|
|
205
1289
|
};
|
|
206
1290
|
}
|
|
1291
|
+
inputs = this._applyDynamicSlots(inputs);
|
|
207
1292
|
// Inject _control_context for controller nodes (Python parity:
|
|
208
1293
|
// process_streaming_node_with_inputs / _is_controller / _build_control_context)
|
|
209
1294
|
if (this._controlContext) {
|
|
210
1295
|
inputs = { ...inputs, _control_context: this._controlContext };
|
|
211
1296
|
}
|
|
212
|
-
|
|
1297
|
+
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
1298
|
+
(this._executionsLogged === 0 ? log.info : log.debug)("Executing node", {
|
|
213
1299
|
nodeId: this.node.id,
|
|
214
1300
|
type: this.node.type,
|
|
215
|
-
|
|
216
|
-
|
|
1301
|
+
inputHandles: Object.keys(inputs),
|
|
1302
|
+
invocation: this._executionsLogged + 1
|
|
217
1303
|
});
|
|
1304
|
+
this._executionsLogged += 1;
|
|
1305
|
+
this._currentInvocationLineage = this._computeInvocationLineage();
|
|
218
1306
|
if (this.node.is_streaming_output && this._executor.genProcess) {
|
|
1307
|
+
await this._executeStreaming(inputs);
|
|
1308
|
+
return;
|
|
1309
|
+
}
|
|
1310
|
+
const outputs = await this._invokeWithRecovery(inputs, () => this._executor.process(inputs, this._executionContext));
|
|
1311
|
+
if (outputs === SKIPPED)
|
|
1312
|
+
return;
|
|
1313
|
+
this._latestResult = outputs;
|
|
1314
|
+
await this._sendOutputs(this.node.id, outputs, this._currentHints(Object.keys(outputs)));
|
|
1315
|
+
// Site #1 (RFC §5): correlated process() — one per ready key, so N/run
|
|
1316
|
+
// for a generator (the primary 6×-collapse fix).
|
|
1317
|
+
this._emitGenerationComplete(outputs, inputs);
|
|
1318
|
+
}
|
|
1319
|
+
/**
|
|
1320
|
+
* The streaming-output invocation, with its own recovery rules.
|
|
1321
|
+
*
|
|
1322
|
+
* Frames are routed inside the generator loop, so "retry" only means
|
|
1323
|
+
* something before the first emit — after that the coherent choices are
|
|
1324
|
+
* ending the stream (keeping what was produced) or failing. Design §5.4.
|
|
1325
|
+
*/
|
|
1326
|
+
async _executeStreaming(inputs) {
|
|
1327
|
+
for (let attempt = 1;; attempt++) {
|
|
1328
|
+
const account = createInvocationAccount();
|
|
1329
|
+
let emitted = false;
|
|
219
1330
|
this._streamingCollectedOutputs = {};
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
1331
|
+
try {
|
|
1332
|
+
await inInvocationAccount(account, async () => {
|
|
1333
|
+
for await (const partial of this._executor.genProcess(inputs, this._executionContext)) {
|
|
1334
|
+
emitted = (await this._routeStreamingFrame(partial)) || emitted;
|
|
1335
|
+
}
|
|
1336
|
+
});
|
|
1337
|
+
}
|
|
1338
|
+
catch (err) {
|
|
1339
|
+
if (err instanceof RoutingError)
|
|
1340
|
+
throw err.cause;
|
|
1341
|
+
if (!this._supervisor) {
|
|
1342
|
+
if (!this._degradeOnContentFilter(err, emitted))
|
|
1343
|
+
throw err;
|
|
1344
|
+
await this._skipInvocation();
|
|
1345
|
+
return;
|
|
1346
|
+
}
|
|
1347
|
+
const verdict = await this._escalate(err, inputs, attempt, account, {
|
|
1348
|
+
streamingOutput: true,
|
|
1349
|
+
streamingInput: false,
|
|
1350
|
+
emitted
|
|
1351
|
+
});
|
|
1352
|
+
switch (verdict.action) {
|
|
1353
|
+
case "retry":
|
|
1354
|
+
continue;
|
|
1355
|
+
case "skip":
|
|
1356
|
+
await this._skipInvocation();
|
|
1357
|
+
return;
|
|
1358
|
+
case "end_stream":
|
|
1359
|
+
this._completeOutputSlots();
|
|
1360
|
+
this._latestResult = { ...(this._streamingCollectedOutputs ?? {}) };
|
|
1361
|
+
// `end_stream` keeps what the stream produced, so the invocation
|
|
1362
|
+
// committed — it just committed early. Skipping the commit marker
|
|
1363
|
+
// would hide those outputs from replay and asset autosave, which
|
|
1364
|
+
// is the "silent data loss dressed as success" the PRD forbids.
|
|
1365
|
+
this._emitGenerationComplete(this._latestResult, inputs);
|
|
1366
|
+
return;
|
|
1367
|
+
default:
|
|
1368
|
+
throw err;
|
|
1369
|
+
}
|
|
227
1370
|
}
|
|
228
1371
|
this._latestResult = { ...(this._streamingCollectedOutputs ?? {}) };
|
|
1372
|
+
// Site #4 (RFC §5): genProcess stream-end — ONCE per stream, carrying the
|
|
1373
|
+
// overwrite-merged _streamingCollectedOutputs. Per-yield partials stay on
|
|
1374
|
+
// output_update (chunks); multi-artifact-per-output-slot streaming is OUT
|
|
1375
|
+
// OF SCOPE (RFC §5 invariant / Decision 1 corollary). Under correlation
|
|
1376
|
+
// this branch runs once per ready key → one generation_complete per key.
|
|
1377
|
+
this._emitGenerationComplete(this._latestResult, inputs);
|
|
1378
|
+
return;
|
|
229
1379
|
}
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
1380
|
+
}
|
|
1381
|
+
/**
|
|
1382
|
+
* The streaming-input invocation. A `run()` node drains its own inbox and may
|
|
1383
|
+
* have consumed messages long before it threw, across arbitrary lineages —
|
|
1384
|
+
* nothing is replayable and there is no single lineage for a skip to target.
|
|
1385
|
+
* So the verdict set here is exactly `end_stream` · `fail`. Design §5.4.
|
|
1386
|
+
*/
|
|
1387
|
+
async _runStreamingInput(nodeInputs, nodeOutputs) {
|
|
1388
|
+
const account = createInvocationAccount();
|
|
1389
|
+
try {
|
|
1390
|
+
await inInvocationAccount(account, () => this._executor.run(nodeInputs, nodeOutputs, this._executionContext));
|
|
1391
|
+
}
|
|
1392
|
+
catch (err) {
|
|
1393
|
+
if (err instanceof RoutingError)
|
|
1394
|
+
throw err.cause;
|
|
1395
|
+
if (!this._supervisor)
|
|
1396
|
+
throw err;
|
|
1397
|
+
const verdict = await this._escalate(err, {}, 1, account, {
|
|
1398
|
+
streamingOutput: false,
|
|
1399
|
+
streamingInput: true,
|
|
1400
|
+
emitted: true
|
|
1401
|
+
});
|
|
1402
|
+
if (verdict.action !== "end_stream")
|
|
1403
|
+
throw err;
|
|
1404
|
+
this._completeOutputSlots();
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
/** Route one yielded frame. Returns true when anything went downstream. */
|
|
1408
|
+
async _routeStreamingFrame(partial) {
|
|
1409
|
+
const routed = this._filterStreamingPartial(partial);
|
|
1410
|
+
if (Object.keys(routed).length === 0)
|
|
1411
|
+
return false;
|
|
1412
|
+
// Strip actor-reserved `index` from iteration groups before routing
|
|
1413
|
+
// (the actor mints the token index; node code is migrating away from
|
|
1414
|
+
// supplying it). §1 — under the correlation scheduler this becomes
|
|
1415
|
+
// a validation error after migration; for now we warn-and-overwrite.
|
|
1416
|
+
const overrides = this._mintIterationFrameOverrides(routed);
|
|
1417
|
+
this._streamingCollectedOutputs ??= {};
|
|
1418
|
+
Object.assign(this._streamingCollectedOutputs, routed);
|
|
1419
|
+
if (overrides)
|
|
1420
|
+
Object.assign(this._streamingCollectedOutputs, overrides);
|
|
1421
|
+
const emit = overrides ? { ...routed, ...overrides } : routed;
|
|
1422
|
+
this._latestResult = { ...this._streamingCollectedOutputs };
|
|
1423
|
+
await this._route(emit, this._currentHints(Object.keys(emit)));
|
|
1424
|
+
return true;
|
|
1425
|
+
}
|
|
1426
|
+
/**
|
|
1427
|
+
* Route values downstream, tagging any failure as a routing failure so the
|
|
1428
|
+
* recovery loops let it through instead of escalating a delivery problem as
|
|
1429
|
+
* if the node had failed.
|
|
1430
|
+
*/
|
|
1431
|
+
async _route(outputs, hints) {
|
|
1432
|
+
try {
|
|
1433
|
+
await this._sendOutputs(this.node.id, outputs, hints);
|
|
1434
|
+
}
|
|
1435
|
+
catch (err) {
|
|
1436
|
+
throw new RoutingError(err);
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
/**
|
|
1440
|
+
* Close every output slot, keeping whatever the stream already emitted —
|
|
1441
|
+
* the `end_stream` verdict. Slots come from the node's declared outputs,
|
|
1442
|
+
* falling back to what the stream actually produced.
|
|
1443
|
+
*/
|
|
1444
|
+
_completeOutputSlots() {
|
|
1445
|
+
const declared = Object.keys(this.node.outputs ?? {});
|
|
1446
|
+
const slots = declared.length
|
|
1447
|
+
? declared
|
|
1448
|
+
: Object.keys(this._streamingCollectedOutputs ?? {});
|
|
1449
|
+
for (const slot of slots) {
|
|
1450
|
+
this._signalSlotEos?.(this.node.id, slot || "output");
|
|
234
1451
|
}
|
|
235
1452
|
}
|
|
1453
|
+
/**
|
|
1454
|
+
* For each iteration group present in `frame`, mint or reuse a token. If
|
|
1455
|
+
* the frame supplies an `index` value for a group that has an `index`
|
|
1456
|
+
* sibling handle declared, overwrite it with the actor-minted index. §1.
|
|
1457
|
+
*
|
|
1458
|
+
* Returns the override map (only the slots that needed mutation) or null
|
|
1459
|
+
* when no iteration groups are in play.
|
|
1460
|
+
*/
|
|
1461
|
+
_mintIterationFrameOverrides(frame) {
|
|
1462
|
+
if (!this._correlation)
|
|
1463
|
+
return null;
|
|
1464
|
+
const declared = this.node.output_correlation;
|
|
1465
|
+
if (!declared)
|
|
1466
|
+
return null;
|
|
1467
|
+
const invocationScope = this._correlation.invocationScope;
|
|
1468
|
+
const parentKey = invocationScope.length && this._currentInvocationLineage
|
|
1469
|
+
? projectLineageKey(this._currentInvocationLineage, invocationScope)
|
|
1470
|
+
: "";
|
|
1471
|
+
// Collect groups whose handles appear in the frame.
|
|
1472
|
+
const groupHandles = new Map(); // group root → handles
|
|
1473
|
+
for (const handle of Object.keys(frame)) {
|
|
1474
|
+
const corr = declared[handle];
|
|
1475
|
+
if (!corr || corr.kind !== "iteration")
|
|
1476
|
+
continue;
|
|
1477
|
+
const root = iterationRootId(this.node.id, handle, corr.group);
|
|
1478
|
+
let arr = groupHandles.get(root);
|
|
1479
|
+
if (!arr) {
|
|
1480
|
+
arr = [];
|
|
1481
|
+
groupHandles.set(root, arr);
|
|
1482
|
+
}
|
|
1483
|
+
arr.push(handle);
|
|
1484
|
+
}
|
|
1485
|
+
if (groupHandles.size === 0)
|
|
1486
|
+
return null;
|
|
1487
|
+
// Each frame mints fresh tokens; clear last frame's bookkeeping.
|
|
1488
|
+
this._lastMintedFrameTokens.clear();
|
|
1489
|
+
const overrides = {};
|
|
1490
|
+
for (const [root, handles] of groupHandles) {
|
|
1491
|
+
const index = this._mintIterationToken(root, parentKey);
|
|
1492
|
+
for (const handle of handles) {
|
|
1493
|
+
if (handle === "index") {
|
|
1494
|
+
overrides[handle] = index;
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
// Stash the minted token so _correlatedOutputLineage reuses it.
|
|
1498
|
+
this._lastMintedFrameTokens.set(root, index);
|
|
1499
|
+
}
|
|
1500
|
+
return Object.keys(overrides).length > 0 ? overrides : null;
|
|
1501
|
+
}
|
|
1502
|
+
/** Tokens minted for the most recent frame, reused by output lineage. */
|
|
1503
|
+
_lastMintedFrameTokens = new Map();
|
|
1504
|
+
/**
|
|
1505
|
+
* Atomically route a frame of values across multiple slots, minting one
|
|
1506
|
+
* shared token per iteration group so sibling handles in the same group
|
|
1507
|
+
* (e.g. Zip's `left` and `right`) end up as one logical item downstream.
|
|
1508
|
+
* §1, §7.
|
|
1509
|
+
*
|
|
1510
|
+
* Algorithm:
|
|
1511
|
+
* 1. Walk every slot in `values` and resolve its `output_correlation`.
|
|
1512
|
+
* 2. For each iteration group present in this frame, mint exactly one
|
|
1513
|
+
* token (per (root, parent_key)) and remember it for the duration of
|
|
1514
|
+
* this emit.
|
|
1515
|
+
* 3. Build a per-slot lineage map that attaches the same token to every
|
|
1516
|
+
* sibling handle in a group. Non-iteration slots inherit the
|
|
1517
|
+
* caller-supplied lineage (or the actor's invocation lineage).
|
|
1518
|
+
* 4. Hand the whole frame to `_sendOutputs` in one call so the runner
|
|
1519
|
+
* routes them as a single atomic delivery.
|
|
1520
|
+
*/
|
|
1521
|
+
async _emitGroup(values, callerLineage) {
|
|
1522
|
+
const declared = this.node.output_correlation ?? {};
|
|
1523
|
+
const parentLineage = callerLineage ?? this._computeInvocationLineage() ?? EMPTY_LINEAGE;
|
|
1524
|
+
const parentKey = this._correlation
|
|
1525
|
+
? projectLineageKey(parentLineage, this._correlation.invocationScope)
|
|
1526
|
+
: "";
|
|
1527
|
+
const groupTokens = new Map(); // root -> minted index
|
|
1528
|
+
const perSlotLineage = {};
|
|
1529
|
+
for (const slot of Object.keys(values)) {
|
|
1530
|
+
const corr = declared[slot];
|
|
1531
|
+
if (corr?.kind === "iteration") {
|
|
1532
|
+
const root = iterationRootId(this.node.id, slot, corr.group);
|
|
1533
|
+
let index = groupTokens.get(root);
|
|
1534
|
+
if (index === undefined) {
|
|
1535
|
+
index = this._mintIterationToken(root, parentKey);
|
|
1536
|
+
groupTokens.set(root, index);
|
|
1537
|
+
}
|
|
1538
|
+
perSlotLineage[slot] = { ...parentLineage, [root]: { index } };
|
|
1539
|
+
}
|
|
1540
|
+
else {
|
|
1541
|
+
perSlotLineage[slot] = parentLineage;
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
await this._sendOutputs(this.node.id, values, {
|
|
1545
|
+
invocationLineage: parentLineage,
|
|
1546
|
+
perSlotLineage
|
|
1547
|
+
});
|
|
1548
|
+
}
|
|
1549
|
+
/**
|
|
1550
|
+
* For `aggregate(innermost)` outputs, drop the collapsed root from the
|
|
1551
|
+
* inherited lineage so the emitted envelope sits at the parent scope.
|
|
1552
|
+
* The static analyzer drops the root from the output scope at graph load;
|
|
1553
|
+
* this is the runtime mirror.
|
|
1554
|
+
*
|
|
1555
|
+
* Returns the rewritten lineage, or `undefined` when no collapse applies.
|
|
1556
|
+
*/
|
|
1557
|
+
_maybeCollapseForSlot(slot, hints) {
|
|
1558
|
+
const corr = this.node.output_correlation?.[slot];
|
|
1559
|
+
if (!corr || corr.kind !== "aggregate")
|
|
1560
|
+
return undefined;
|
|
1561
|
+
if (corr.collapse !== "innermost")
|
|
1562
|
+
return undefined;
|
|
1563
|
+
if (!this._correlation)
|
|
1564
|
+
return undefined;
|
|
1565
|
+
// The source input handle's scope ends with the root to collapse.
|
|
1566
|
+
const sourceInput = this._correlation.inputs.get(corr.source);
|
|
1567
|
+
if (!sourceInput || sourceInput.scope.length === 0)
|
|
1568
|
+
return undefined;
|
|
1569
|
+
const collapsed = sourceInput.scope[sourceInput.scope.length - 1];
|
|
1570
|
+
const base = hints.invocationLineage ?? EMPTY_LINEAGE;
|
|
1571
|
+
if (!(collapsed in base))
|
|
1572
|
+
return base;
|
|
1573
|
+
const out = { ...base };
|
|
1574
|
+
delete out[collapsed];
|
|
1575
|
+
return out;
|
|
1576
|
+
}
|
|
1577
|
+
/**
|
|
1578
|
+
* For stream-mode iteration outputs (e.g. `Zip.pair`), mint a fresh token
|
|
1579
|
+
* whenever `outputs.emit()` is called without an explicit lineage. Each
|
|
1580
|
+
* emit is a logical item, so the token advances per call. Sibling-handle
|
|
1581
|
+
* reuse within a single frame is handled by genProcess via
|
|
1582
|
+
* `_mintIterationFrameOverrides`, or by `outputs.emitGroup()` in stream
|
|
1583
|
+
* mode — see `_emitGroup` above.
|
|
1584
|
+
*/
|
|
1585
|
+
_maybeMintForSlot(slot, hints) {
|
|
1586
|
+
const corr = this.node.output_correlation?.[slot];
|
|
1587
|
+
if (!corr || corr.kind !== "iteration")
|
|
1588
|
+
return undefined;
|
|
1589
|
+
const root = iterationRootId(this.node.id, slot, corr.group);
|
|
1590
|
+
const parentLineage = hints.invocationLineage ?? EMPTY_LINEAGE;
|
|
1591
|
+
const parentKey = this._correlation
|
|
1592
|
+
? projectLineageKey(parentLineage, this._correlation.invocationScope)
|
|
1593
|
+
: "";
|
|
1594
|
+
const index = this._mintIterationToken(root, parentKey);
|
|
1595
|
+
return { ...parentLineage, [root]: { index } };
|
|
1596
|
+
}
|
|
1597
|
+
/**
|
|
1598
|
+
* For each outgoing edge that consumes `slot`, send `signalLineageDone` to
|
|
1599
|
+
* the downstream inbox with the envelope's projected key. §5/§6.
|
|
1600
|
+
*/
|
|
1601
|
+
async _propagateLineageDone(slot, lineage) {
|
|
1602
|
+
// The actor doesn't know the downstream inbox map directly; the runner
|
|
1603
|
+
// owns _sendOutputs. We extend the routing channel by passing a sentinel
|
|
1604
|
+
// value with `__lineage_done__` metadata so the runner can dispatch it.
|
|
1605
|
+
await this._sendOutputs(this.node.id, { [slot]: undefined }, {
|
|
1606
|
+
perSlotLineage: { [slot]: lineage },
|
|
1607
|
+
lineageDoneSlots: new Set([slot])
|
|
1608
|
+
});
|
|
1609
|
+
}
|
|
1610
|
+
/**
|
|
1611
|
+
* True while `_runCorrelated` is the active execution path.
|
|
1612
|
+
*/
|
|
1613
|
+
_inCorrelatedBuffered = false;
|
|
1614
|
+
/**
|
|
1615
|
+
* Build routing hints for the current invocation.
|
|
1616
|
+
*
|
|
1617
|
+
* When correlation analysis is available and the invocation emitted handles,
|
|
1618
|
+
* the actor mints per-slot lineage for those outputs and pairs it with the
|
|
1619
|
+
* invocation lineage. Otherwise it forwards just the invocation lineage,
|
|
1620
|
+
* which the runner applies to outputs that inherit the invocation scope.
|
|
1621
|
+
* Returns undefined when no invocation lineage is known.
|
|
1622
|
+
*/
|
|
1623
|
+
_currentHints(emittedHandles) {
|
|
1624
|
+
if (this._currentInvocationLineage === undefined)
|
|
1625
|
+
return undefined;
|
|
1626
|
+
if (this._correlation && emittedHandles && emittedHandles.length > 0) {
|
|
1627
|
+
const perSlot = this._correlatedOutputLineage(this._currentInvocationLineage, emittedHandles);
|
|
1628
|
+
if (perSlot) {
|
|
1629
|
+
return {
|
|
1630
|
+
invocationLineage: this._currentInvocationLineage,
|
|
1631
|
+
perSlotLineage: perSlot
|
|
1632
|
+
};
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
return { invocationLineage: this._currentInvocationLineage };
|
|
1636
|
+
}
|
|
1637
|
+
/**
|
|
1638
|
+
* Compute the invocation lineage for the current set of consumed
|
|
1639
|
+
* envelopes. Returns undefined when the case is ambiguous.
|
|
1640
|
+
*
|
|
1641
|
+
* In correlated buffered mode the lineage comes from the correlation
|
|
1642
|
+
* scheduler. Otherwise the lineage is taken from the sole consumed data
|
|
1643
|
+
* envelope when exactly one non-control, non-list data handle was consumed;
|
|
1644
|
+
* any other arity is ambiguous and yields undefined.
|
|
1645
|
+
*
|
|
1646
|
+
* The map is NOT cleared here so that streaming-input nodes that emit
|
|
1647
|
+
* multiple times per consumed envelope continue to inherit lineage on
|
|
1648
|
+
* every emit. Buffered gather paths overwrite envelopes per handle on
|
|
1649
|
+
* each iteration, which naturally tracks the latest consumed envelope.
|
|
1650
|
+
*/
|
|
1651
|
+
_computeInvocationLineage() {
|
|
1652
|
+
if (this._correlation && this._inCorrelatedBuffered) {
|
|
1653
|
+
return this._correlatedInvocationLineage();
|
|
1654
|
+
}
|
|
1655
|
+
const dataHandles = [...this._lastEnvelopes.keys()].filter((h) => h !== "__control__" && !this._listInputHandles.has(h));
|
|
1656
|
+
if (dataHandles.length !== 1)
|
|
1657
|
+
return undefined;
|
|
1658
|
+
return this._lastEnvelopes.get(dataHandles[0])?.correlation_lineage;
|
|
1659
|
+
}
|
|
236
1660
|
/**
|
|
237
1661
|
* Controlled execution: wait for control events on __control__ handle.
|
|
238
1662
|
*
|
|
@@ -243,7 +1667,7 @@ export class NodeActor {
|
|
|
243
1667
|
*/
|
|
244
1668
|
async _runControlled() {
|
|
245
1669
|
// Identify data handles (non-control) that need to be populated
|
|
246
|
-
const dataHandles =
|
|
1670
|
+
const dataHandles = this.inbox.handles().filter((h) => h !== "__control__");
|
|
247
1671
|
// Wait for all data handles to have at least one value before
|
|
248
1672
|
// processing the first control event. This ensures that when an
|
|
249
1673
|
// upstream node feeds data into the controlled node, the data
|
|
@@ -264,15 +1688,19 @@ export class NodeActor {
|
|
|
264
1688
|
// Merge node properties as defaults (matching _executeWithInputs behavior)
|
|
265
1689
|
const baseProps = this.node.properties ?? {};
|
|
266
1690
|
const dynProps = this.node.dynamic_properties ?? {};
|
|
267
|
-
const merged = {
|
|
1691
|
+
const merged = this._applyDynamicSlots({
|
|
268
1692
|
...baseProps,
|
|
269
1693
|
...dynProps,
|
|
270
1694
|
...inputs,
|
|
271
1695
|
...this._currentControlProperties
|
|
272
|
-
};
|
|
273
|
-
const outputs = await this._executor.process(merged, this._executionContext);
|
|
1696
|
+
});
|
|
1697
|
+
const outputs = await this._invokeWithRecovery(merged, () => this._executor.process(merged, this._executionContext));
|
|
1698
|
+
if (outputs === SKIPPED)
|
|
1699
|
+
continue;
|
|
274
1700
|
this._latestResult = outputs;
|
|
275
1701
|
await this._sendOutputs(this.node.id, outputs);
|
|
1702
|
+
// Site #2 (RFC §5): controlled-loop process() — one per "run" event.
|
|
1703
|
+
this._emitGenerationComplete(outputs);
|
|
276
1704
|
}
|
|
277
1705
|
}
|
|
278
1706
|
}
|
|
@@ -293,128 +1721,135 @@ export class NodeActor {
|
|
|
293
1721
|
this._cacheBufferedDataInputs();
|
|
294
1722
|
return;
|
|
295
1723
|
}
|
|
296
|
-
// Drain items until
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
1724
|
+
// Drain items until every data handle has a value. A handle whose upstream
|
|
1725
|
+
// sources have all closed with nothing buffered can never be satisfied, so
|
|
1726
|
+
// drop it from `pending` and let the node's declared default apply —
|
|
1727
|
+
// mirroring how `_runCorrelatedImpl` treats a closed empty-scope handle.
|
|
1728
|
+
// Without this the wait blocks forever whenever an upstream completes
|
|
1729
|
+
// without emitting on a data handle (filter/conditional output), stranding
|
|
1730
|
+
// held control events and hanging any controller awaiting sendControlEvent.
|
|
1731
|
+
//
|
|
1732
|
+
// A close wakes the inbox's internal waiters but yields no envelope, so this
|
|
1733
|
+
// is a manual loop over `tryPopAnyWithEnvelope()` + `waitForActivity()`
|
|
1734
|
+
// rather than a for-await: the pruning below must re-run on a closure that
|
|
1735
|
+
// arrives while blocked.
|
|
1736
|
+
//
|
|
1737
|
+
// Control events that arrive first are held aside and re-queued after the
|
|
1738
|
+
// wait: prepending them back while still iterating would make the very next
|
|
1739
|
+
// pop return the same event again — an unbounded microtask spin that
|
|
1740
|
+
// starves the event loop and blocks the upstream data put() forever.
|
|
1741
|
+
const heldControlEvents = [];
|
|
1742
|
+
for (;;) {
|
|
1743
|
+
for (const handle of [...pending]) {
|
|
1744
|
+
if (!this.inbox.isOpen(handle) && !this.inbox.hasBuffered(handle)) {
|
|
1745
|
+
pending.delete(handle);
|
|
1746
|
+
}
|
|
307
1747
|
}
|
|
308
|
-
if (!this._cachedInputs)
|
|
309
|
-
this._cachedInputs = {};
|
|
310
|
-
this._cachedInputs[handle] = item;
|
|
311
|
-
pending.delete(handle);
|
|
312
1748
|
if (pending.size === 0)
|
|
313
1749
|
break;
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
_cacheBufferedDataInputs() {
|
|
322
|
-
const buffers = this.inbox["_buffers"];
|
|
323
|
-
for (const [handle, buf] of buffers) {
|
|
324
|
-
if (handle === "__control__" || buf.length === 0)
|
|
325
|
-
continue;
|
|
326
|
-
// Use the latest buffered value for each data handle
|
|
327
|
-
while (buf.length > 0) {
|
|
328
|
-
const envelope = buf.shift();
|
|
1750
|
+
const popped = this.inbox.tryPopAnyWithEnvelope();
|
|
1751
|
+
if (popped) {
|
|
1752
|
+
const [handle, envelope] = popped;
|
|
1753
|
+
if (handle === "__control__") {
|
|
1754
|
+
heldControlEvents.push(envelope);
|
|
1755
|
+
continue;
|
|
1756
|
+
}
|
|
329
1757
|
if (!this._cachedInputs)
|
|
330
1758
|
this._cachedInputs = {};
|
|
331
1759
|
this._cachedInputs[handle] = envelope.data;
|
|
1760
|
+
pending.delete(handle);
|
|
1761
|
+
continue;
|
|
332
1762
|
}
|
|
1763
|
+
// Nothing left to pop. A closed inbox accepts no further writes, so the
|
|
1764
|
+
// still-pending handles can never be satisfied — stop waiting and let the
|
|
1765
|
+
// node's declared defaults apply, mirroring the iterators' `_closed`
|
|
1766
|
+
// check. Without this a cancelled run parks here forever: `closeAll()`
|
|
1767
|
+
// leaves `_openCounts` untouched, so the pruning above never fires.
|
|
1768
|
+
if (this.inbox.isClosed())
|
|
1769
|
+
break;
|
|
1770
|
+
await this.inbox.waitForActivity();
|
|
1771
|
+
}
|
|
1772
|
+
// Re-queue held control events at the front, preserving arrival order,
|
|
1773
|
+
// so iterInput("__control__") consumes them next.
|
|
1774
|
+
for (let i = heldControlEvents.length - 1; i >= 0; i--) {
|
|
1775
|
+
this.inbox.prepend("__control__", heldControlEvents[i]);
|
|
333
1776
|
}
|
|
334
1777
|
}
|
|
335
|
-
// -----------------------------------------------------------------------
|
|
336
|
-
// Input gathering (sync modes)
|
|
337
|
-
// -----------------------------------------------------------------------
|
|
338
1778
|
/**
|
|
339
|
-
*
|
|
340
|
-
*
|
|
1779
|
+
* Drain all buffered data (non-control) inputs and cache them.
|
|
1780
|
+
* Called before each controlled execution to pick up any data that
|
|
1781
|
+
* arrived while waiting for the next control event.
|
|
341
1782
|
*/
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
if (handles.length === 0)
|
|
346
|
-
return null;
|
|
347
|
-
const result = {};
|
|
348
|
-
let gotNew = false;
|
|
349
|
-
for (const handle of handles) {
|
|
350
|
-
if (this.inbox.hasBuffered(handle)) {
|
|
351
|
-
const popped = this._popHandle(handle);
|
|
352
|
-
if (popped !== undefined) {
|
|
353
|
-
result[handle] = popped;
|
|
354
|
-
this._stickyValues[handle] = popped;
|
|
355
|
-
gotNew = true;
|
|
356
|
-
continue;
|
|
357
|
-
}
|
|
358
|
-
}
|
|
359
|
-
// Use sticky value if handle is closed or marked sticky from streaming analysis
|
|
360
|
-
const isSticky = !this.inbox.isOpen(handle) || this._initialStickyHandles.has(handle);
|
|
361
|
-
if (isSticky && handle in this._stickyValues) {
|
|
362
|
-
result[handle] = this._stickyValues[handle];
|
|
1783
|
+
_cacheBufferedDataInputs() {
|
|
1784
|
+
for (const handle of this.inbox.handles()) {
|
|
1785
|
+
if (handle === "__control__")
|
|
363
1786
|
continue;
|
|
364
|
-
|
|
365
|
-
//
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
if (next.done) {
|
|
370
|
-
// EOS – use sticky if available
|
|
371
|
-
if (handle in this._stickyValues) {
|
|
372
|
-
result[handle] = this._stickyValues[handle];
|
|
373
|
-
continue;
|
|
374
|
-
}
|
|
375
|
-
return null; // no sticky, no data
|
|
376
|
-
}
|
|
377
|
-
result[handle] = next.value;
|
|
378
|
-
this._stickyValues[handle] = next.value;
|
|
379
|
-
gotNew = true;
|
|
380
|
-
await gen.return(undefined);
|
|
1787
|
+
// Use the latest buffered value for each data handle. drainHandle()
|
|
1788
|
+
// (unlike popping the raw buffer) releases backpressure on producers
|
|
1789
|
+
// blocked in put() and keeps the arrival queue consistent.
|
|
1790
|
+
const drained = this.inbox.drainHandle(handle);
|
|
1791
|
+
if (drained.length === 0)
|
|
381
1792
|
continue;
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
return null;
|
|
386
|
-
}
|
|
387
|
-
result[handle] = this._stickyValues[handle];
|
|
1793
|
+
if (!this._cachedInputs)
|
|
1794
|
+
this._cachedInputs = {};
|
|
1795
|
+
this._cachedInputs[handle] = drained[drained.length - 1].data;
|
|
388
1796
|
}
|
|
389
|
-
if (!gotNew)
|
|
390
|
-
return null; // all sticky, no new data
|
|
391
|
-
return result;
|
|
392
|
-
}
|
|
393
|
-
/**
|
|
394
|
-
* Pop a single item from a specific handle's buffer.
|
|
395
|
-
*/
|
|
396
|
-
_popHandle(handle) {
|
|
397
|
-
const buf = this.inbox["_buffers"].get(handle);
|
|
398
|
-
if (!buf || buf.length === 0)
|
|
399
|
-
return undefined;
|
|
400
|
-
const envelope = buf.shift();
|
|
401
|
-
return envelope.data;
|
|
402
1797
|
}
|
|
403
1798
|
// -----------------------------------------------------------------------
|
|
404
1799
|
// Status helpers
|
|
405
1800
|
// -----------------------------------------------------------------------
|
|
406
|
-
_emitNodeStatus(status, result, error) {
|
|
407
|
-
|
|
1801
|
+
_emitNodeStatus(status, result, error, errorDetail) {
|
|
1802
|
+
const head = {
|
|
408
1803
|
type: "node_update",
|
|
409
1804
|
node_id: this.node.id,
|
|
410
1805
|
node_name: this.node.name ?? this.node.type,
|
|
411
1806
|
node_type: this.node.type,
|
|
412
1807
|
status,
|
|
413
1808
|
result: result ?? null,
|
|
414
|
-
error: error ?? null
|
|
415
|
-
|
|
1809
|
+
error: error ?? null
|
|
1810
|
+
};
|
|
1811
|
+
const tail = {
|
|
1812
|
+
properties: isObjectValue(this.node.properties)
|
|
416
1813
|
? this.node.properties
|
|
417
|
-
: null
|
|
1814
|
+
: null,
|
|
1815
|
+
provider_cost: this._executionContext?.getProviderCost?.() ?? null
|
|
1816
|
+
};
|
|
1817
|
+
// Omitted (not null) when absent: every consumer treats a missing
|
|
1818
|
+
// detail as "no structured cause", and the reliability goldens pin
|
|
1819
|
+
// the node_update wire shape for ordinary runs.
|
|
1820
|
+
this._emitMessage(errorDetail
|
|
1821
|
+
? { ...head, error_detail: errorDetail, ...tail }
|
|
1822
|
+
: { ...head, ...tail });
|
|
1823
|
+
}
|
|
1824
|
+
/**
|
|
1825
|
+
* Emit a BARE `generation_complete` for one committed `process()` result
|
|
1826
|
+
* (RFC §4.2 / §5). Routes through the same `_emitMessage` path as
|
|
1827
|
+
* `node_update` (runner `_emit`), so it is NEVER edge-suppressed and is
|
|
1828
|
+
* retained for replay. The actor stamps NO `job_id` and NO `index` — both
|
|
1829
|
+
* are backfilled downstream by the relay (RFC Decision 8).
|
|
1830
|
+
*
|
|
1831
|
+
* Skips `nodetool.constant.*` / `nodetool.input.*` (the same set
|
|
1832
|
+
* `_emitNodeStatus`'s `skipResult` rule covers): those nodes have no
|
|
1833
|
+
* generation. List-valued results are carried as-is — no per-element
|
|
1834
|
+
* fan-out happens in the actor (RFC Decision 1).
|
|
1835
|
+
*/
|
|
1836
|
+
_emitGenerationComplete(outputs, inputs) {
|
|
1837
|
+
if (this.node.type.startsWith("nodetool.constant.") ||
|
|
1838
|
+
this.node.type.startsWith("nodetool.input.")) {
|
|
1839
|
+
return;
|
|
1840
|
+
}
|
|
1841
|
+
this._emitMessage({
|
|
1842
|
+
type: "generation_complete",
|
|
1843
|
+
node_id: this.node.id,
|
|
1844
|
+
node_name: this.node.name ?? this.node.type,
|
|
1845
|
+
node_type: this.node.type,
|
|
1846
|
+
outputs,
|
|
1847
|
+
// Resolved inputs (prompt, seed, model, …) ride along so the relay can
|
|
1848
|
+
// persist them into auto-saved asset metadata. Filtered to scalars plus
|
|
1849
|
+
// model references to keep the event small — binary refs and every other
|
|
1850
|
+
// nested object are dropped.
|
|
1851
|
+
properties: inputs ? scalarInputProperties(inputs) : null
|
|
1852
|
+
// NO job_id, NO index — the runner relay stamps them downstream.
|
|
418
1853
|
});
|
|
419
1854
|
}
|
|
420
1855
|
_filterStreamingPartial(partial) {
|