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