Skip to content

Commit d0c69cc

Browse files
author
hzq
committed
Prepare all selected foreach arguments before dispatch
Resolve argument references and expressions for the selected items as part of bounded preflight. Reuse prepared arguments for retries, leave unused fallbacks lazy, and retain the existing dispatch-time tool authorization.
1 parent 2724b41 commit d0c69cc

7 files changed

Lines changed: 278 additions & 82 deletions

File tree

‎docs/language.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -272,7 +272,7 @@ A step can be followed by modifiers, each at most once. An item predicate follow
272272

273273
The source length is checked **before** filtering. All predicates of one map are checked before its first tool call. Rejected items have no tool call, approval or fallback. If only source items 1 and 3 match step `send`, their execution IDs are `send_1` and `send_3`; the result is a compact array in source order. No matches yields `[]`. A false whole-step `when` still yields `{skipped: true}`. Neither loop limits nor tool budgets increase.
274274

275-
Each `foreach` preflight shares a **1,048,576-item collection budget** across its source snapshot and all predicates, including reference copies and template serialization in those predicates. The per-expression limit still applies. If the preflight exceeds its budget, it raises `expression_budget_exceeded` before dispatching any item in that loop.
275+
Each `foreach` preflight shares a **1,048,576-item collection budget** across its source snapshot, predicates, and the arguments of selected items. Reference copies and template serialization count, and the per-expression limit still applies. All selected arguments are resolved before the first item is dispatched, and reused on retries. Prepared argument strings and keys may occupy up to **24 MiB of UTF-8 text** per loop. An invalid reference or excess work or text fails preflight before any item is dispatched. Unselected arguments and unused fallbacks are not evaluated, and tool-specific validation and authorization still apply at dispatch.
276276

277277
`retry` and `timeout` are allowed only on read-only or `idempotent-write` tools; otherwise compilation reports `unsafe_graph_retry`. While waiting for approval, when the run is cancelled, or when the outcome of a side effect is unknown, there is no retry, and the failure is not hidden by a fallback value.
278278

‎docs/zh-CN/language.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -272,7 +272,7 @@ agent "agent/delegates" {
272272

273273
**先检查原列表长度,再筛选。** 同一循环全部条件算完才开始派发;不匹配项不执行工具、不创建审批、不走回退。例如步骤 `send` 只有原索引 1、3 匹配,则执行编号是 `send_1`、`send_3`;返回数组按原顺序紧凑排列。全不匹配返回 `[]`,整个步骤的 `when` 为假仍返回 `{skipped: true}`。循环上限和工具预算都不变。网关通过 `GET /health` 的 `foreach-where-v1` 声明支持此语法,在 JSON 图中对应 `foreach.where`。
274274

275-
一次 `foreach` 预检的源列表快照和全部条件共用 **1,048,576 项集合预算**,包括条件中的引用复制和模板序列化。单个表达式原有的上限仍然有效。预检超限时返回 `expression_budget_exceeded`,不会派发该循环的任何一项。
275+
一次 `foreach` 的源列表快照、全部条件和选中项的参数共用 **1,048,576 项集合预算**。引用复制和模板序列化也计入,单个表达式原有上限仍然有效。第一项派发前会解析全部选中项的参数,重试复用解析结果。每个循环准备的参数字符串及键名最多占 **24 MiB UTF-8 文本**。引用无效或超出预算时,该循环不会派发任何一项。未选中项的参数和未触发的回退不解析;工具自己的参数校验和授权仍在派发时执行。
276276

277277
`retry` 与 `timeout` 只允许用在只读或 `idempotent-write` 的工具上,否则编译期报 `unsafe_graph_retry`。等待审批、运行取消、副作用结果未知时不会重试,也不会被回退值掩盖。
278278

‎src/lang/expression-budget.ts‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import { Fault } from '../core/util.js';
2+
import { LIMITS } from '../core/limits.js';
23

34
export const EXPRESSION_COLLECTION_LIMIT = 262_144;
45
export const FOREACH_COLLECTION_LIMIT = 4 * EXPRESSION_COLLECTION_LIMIT;
6+
export const FOREACH_ARGUMENT_TEXT_BYTES = LIMITS.nodeMessageBytes;
57

68
export class CollectionBudget {
79
constructor(
@@ -14,12 +16,14 @@ export class CollectionBudget {
1416
if (this.remaining < 0) throw new Fault('expression_budget_exceeded', this.message);
1517
}
1618

17-
visitShape(value: unknown, preserveAliases = false): void {
19+
visitShape(value: unknown, preserveAliases = false, onText?: (text: string) => void): void {
20+
if (typeof value === 'string') onText?.(value);
1821
if (!value || typeof value !== 'object') return;
1922
const stack = [value];
2023
const seen = preserveAliases ? new WeakSet<object>(stack) : undefined;
2124
const enqueue = (obj: object, key: string | number) => {
2225
const v: unknown = Object.getOwnPropertyDescriptor(obj, key)?.value;
26+
if (onText && typeof v === 'string') onText(v);
2327
if (v && typeof v === 'object' && !seen?.has(v)) {
2428
seen?.add(v);
2529
stack.push(v);
@@ -33,12 +37,32 @@ export class CollectionBudget {
3337
} else {
3438
const keys = Object.keys(next);
3539
this.scan(keys.length);
36-
for (const key of keys) enqueue(next, key);
40+
for (const key of keys) {
41+
onText?.(key);
42+
enqueue(next, key);
43+
}
3744
}
3845
}
3946
}
4047
}
4148

49+
/** Limit the text retained for a prepared map in addition to its collection slots. */
50+
export class PreparedArgumentsBudget {
51+
private remaining: number = FOREACH_ARGUMENT_TEXT_BYTES;
52+
53+
constructor(private readonly collection: CollectionBudget) {}
54+
55+
reserve(value: Record<string, unknown>): void {
56+
this.collection.visitShape(value, true, (text) => {
57+
if (text.length > this.remaining || (this.remaining -= Buffer.byteLength(text)) < 0)
58+
throw new Fault(
59+
'expression_budget_exceeded',
60+
'Foreach prepared argument text exceeded its byte budget.',
61+
);
62+
});
63+
}
64+
}
65+
4266
/** Charge variable-sized data work independently of the size of the expression AST. */
4367
export class ExpressionBudget extends CollectionBudget {
4468
private nodes = 0;

‎src/lang/graph-invocation.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { ElapsedRunDeadline, Fault, faultOf, StepCheckpointFailure } from '../core/util.js';
2+
import { ApprovalSuspension, SchedulingSuspension } from '../core/suspension.js';
3+
import type { GraphStep } from './graph-schema.js';
4+
5+
// A whole-run interruption or an unconfirmed effect must not become a per-step retry or fallback.
6+
export const stopInvocation = (err: unknown, signal: AbortSignal) =>
7+
signal.aborted ||
8+
err instanceof ApprovalSuspension ||
9+
err instanceof SchedulingSuspension ||
10+
err instanceof ElapsedRunDeadline ||
11+
err instanceof StepCheckpointFailure ||
12+
faultOf(err).uncertain === true;
13+
14+
/** 执行一个叶子步骤。第三个参数是这一次尝试的中止信号:整个运行中止或本步骤超时都会触发。 */
15+
export type GraphLeafExecutor = (
16+
step: GraphStep,
17+
args: Record<string, unknown>,
18+
signal: AbortSignal,
19+
) => Promise<unknown>;
20+
21+
export async function invokeWithTimeout(
22+
step: GraphStep,
23+
args: Record<string, unknown>,
24+
signal: AbortSignal,
25+
execute: GraphLeafExecutor,
26+
): Promise<unknown> {
27+
if (step.timeout_ms === undefined) return execute(step, args, signal);
28+
const attempt = new AbortController();
29+
const forward = () => attempt.abort();
30+
signal.addEventListener('abort', forward, { once: true });
31+
let expired = false;
32+
const timer = setTimeout(() => {
33+
expired = true;
34+
attempt.abort();
35+
}, step.timeout_ms);
36+
try {
37+
return await execute(step, args, attempt.signal);
38+
} catch (err) {
39+
// 超时把这次尝试中止了:报成明确的超时,而不是笼统的「已取消」。
40+
if (expired && !stopInvocation(err, signal))
41+
throw new Fault(
42+
'step_timeout',
43+
`Step '${step.id}' exceeded its ${step.timeout_ms} ms timeout.`,
44+
504,
45+
);
46+
throw err;
47+
} finally {
48+
clearTimeout(timer);
49+
signal.removeEventListener('abort', forward);
50+
}
51+
}

‎src/lang/graph.ts‎

Lines changed: 58 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,18 @@
11
import { GRAPH_LIMITS } from '../core/limits.js';
22
import { setImmediate as yieldTurn } from 'node:timers/promises';
33
import { graphSchema, publishedGraphSchema, type GraphStep } from './graph-schema.js';
4+
import { invokeWithTimeout, stopInvocation, type GraphLeafExecutor } from './graph-invocation.js';
45
export { graphSchema, type GraphStep } from './graph-schema.js';
6+
export type { GraphLeafExecutor } from './graph-invocation.js';
57
import type {
68
AgentDefinition,
79
DelegateBinding,
810
Effect,
911
ToolBinding,
1012
WorkflowDefinition,
1113
} from '../core/contracts.js';
12-
import {
13-
ElapsedRunDeadline,
14-
Fault,
15-
checkAbort,
16-
faultOf,
17-
sleep,
18-
StepCheckpointFailure,
19-
} from '../core/util.js';
20-
import {
21-
ApprovalSuspension,
22-
SchedulingSuspension,
23-
collectSuspensions,
24-
} from '../core/suspension.js';
14+
import { Fault, checkAbort, sleep } from '../core/util.js';
15+
import { ApprovalSuspension, collectSuspensions } from '../core/suspension.js';
2516
import { JsonSchemas } from '../core/schemas.js';
2617
import {
2718
BORROW_FIRST_ARGUMENT,
@@ -34,6 +25,7 @@ import {
3425
CollectionBudget,
3526
ExpressionBudget,
3627
FOREACH_COLLECTION_LIMIT,
28+
PreparedArgumentsBudget,
3729
} from './expression-budget.js';
3830

3931
export function graphEffect(
@@ -1018,22 +1010,15 @@ export function resolveReferences(
10181010
return Object.fromEntries(entries.map(([k, v]) => [k, resolveReferences(v, results, shared)]));
10191011
}
10201012

1021-
// A whole-run interruption or an unconfirmed effect must not become a per-step retry or fallback.
1022-
const stopInvocation = (err: unknown, signal: AbortSignal) =>
1023-
signal.aborted ||
1024-
err instanceof ApprovalSuspension ||
1025-
err instanceof SchedulingSuspension ||
1026-
err instanceof ElapsedRunDeadline ||
1027-
err instanceof StepCheckpointFailure ||
1028-
faultOf(err).uncertain === true;
1029-
10301013
async function runSingleInvocation(
10311014
step: GraphStep,
10321015
scope: Map<string, unknown>,
10331016
signal: AbortSignal,
10341017
execute: GraphLeafExecutor,
1018+
prepared?: Record<string, unknown>,
10351019
): Promise<unknown> {
1036-
const resolvedArgs = resolveReferences(step.arguments, scope) as Record<string, unknown>;
1020+
const resolvedArgs =
1021+
prepared ?? (resolveReferences(step.arguments, scope) as Record<string, unknown>);
10371022
const attempts = 1 + (step.retry?.attempts ?? 0);
10381023
let failure: unknown;
10391024
for (let attempt = 0; attempt < attempts; attempt++) {
@@ -1066,45 +1051,6 @@ async function runSingleInvocation(
10661051
}
10671052
}
10681053

1069-
/** 执行一个叶子步骤。第三个参数是这一次尝试的中止信号:整个运行中止或本步骤超时都会触发。 */
1070-
export type GraphLeafExecutor = (
1071-
step: GraphStep,
1072-
args: Record<string, unknown>,
1073-
signal: AbortSignal,
1074-
) => Promise<unknown>;
1075-
1076-
async function invokeWithTimeout(
1077-
step: GraphStep,
1078-
args: Record<string, unknown>,
1079-
signal: AbortSignal,
1080-
execute: GraphLeafExecutor,
1081-
): Promise<unknown> {
1082-
if (step.timeout_ms === undefined) return execute(step, args, signal);
1083-
const attempt = new AbortController();
1084-
const forward = () => attempt.abort();
1085-
signal.addEventListener('abort', forward, { once: true });
1086-
let expired = false;
1087-
const timer = setTimeout(() => {
1088-
expired = true;
1089-
attempt.abort();
1090-
}, step.timeout_ms);
1091-
try {
1092-
return await execute(step, args, attempt.signal);
1093-
} catch (err) {
1094-
// 超时把这次尝试中止了:报成明确的超时,而不是笼统的「已取消」。
1095-
if (expired && !stopInvocation(err, signal))
1096-
throw new Fault(
1097-
'step_timeout',
1098-
`Step '${step.id}' exceeded its ${step.timeout_ms} ms timeout.`,
1099-
504,
1100-
);
1101-
throw err;
1102-
} finally {
1103-
clearTimeout(timer);
1104-
signal.removeEventListener('abort', forward);
1105-
}
1106-
}
1107-
11081054
export async function executeGraph(
11091055
steps: GraphStep[],
11101056
concurrency: number,
@@ -1127,6 +1073,7 @@ export async function executeGraph(
11271073
items?: unknown[];
11281074
selected?: number[];
11291075
mapped?: unknown[];
1076+
prepared?: Array<Record<string, unknown> | undefined>;
11301077
};
11311078
type Completion = {
11321079
state: State;
@@ -1180,21 +1127,34 @@ export async function executeGraph(
11801127
const approvals = new Set<string>();
11811128
let remaining = steps.length;
11821129
let stopping = false;
1183-
let filterUntil: number | undefined;
1130+
let preflightUntil: number | undefined;
1131+
const checkpoint = () => {
1132+
preflightUntil ??= performance.now() + 4;
1133+
if (performance.now() < preflightUntil) return undefined;
1134+
return yieldTurn().then(() => {
1135+
checkAbort(signal);
1136+
preflightUntil = performance.now() + 4;
1137+
});
1138+
};
11841139
const complete = (state: State, value: unknown) => {
11851140
results.set(state.step.id, value);
11861141
delete state.items;
11871142
delete state.selected;
1143+
delete state.prepared;
11881144
remaining--;
11891145
for (const dependent of state.dependents) {
11901146
if (--dependent.waiting === 0) ready.push(dependent);
11911147
}
11921148
};
1149+
const stop = () => {
1150+
stopping = true;
1151+
for (const state of states.values()) delete state.prepared;
1152+
};
11931153
const fail = (reason: unknown) => {
11941154
failures.push({ status: 'rejected', reason });
11951155
if (reason instanceof ApprovalSuspension) {
11961156
reason.approvalIds.forEach((id) => approvals.add(id));
1197-
} else stopping = true;
1157+
} else stop();
11981158
};
11991159

12001160
while (ready.length || active) {
@@ -1233,15 +1193,11 @@ export async function executeGraph(
12331193
if (step.foreach.where !== undefined) {
12341194
// Validate all predicates before dispatching any side effect of this map.
12351195
state.selected = [];
1236-
filterUntil ??= performance.now() + 4;
12371196
for (const [index, item] of state.items.entries()) {
12381197
// Even an all-false graph must let cancellation and active siblings run.
1239-
if (performance.now() >= filterUntil) {
1240-
await yieldTurn();
1241-
checkAbort(signal);
1242-
if (stopping) break;
1243-
filterUntil = performance.now() + 4;
1244-
}
1198+
const wait = checkpoint();
1199+
if (wait) await wait;
1200+
if (stopping) break;
12451201
if (
12461202
resolveReferences(
12471203
step.foreach.where,
@@ -1253,29 +1209,56 @@ export async function executeGraph(
12531209
}
12541210
if (stopping) break;
12551211
}
1256-
state.mapped = new Array(state.selected?.length ?? items.length);
1257-
if (!state.mapped.length) {
1212+
const count = state.selected?.length ?? items.length;
1213+
if (!count) {
12581214
complete(state, []);
12591215
continue;
12601216
}
1217+
const argumentBudget = new PreparedArgumentsBudget(preflight);
1218+
const prepared: Array<Record<string, unknown>> = [];
1219+
for (let slot = 0; slot < count; slot++) {
1220+
const wait = checkpoint();
1221+
if (wait) await wait;
1222+
if (stopping) break;
1223+
const index = state.selected?.[slot] ?? slot;
1224+
const scope = itemScope(step.foreach.as, state.items[index], index);
1225+
const args = resolveReferences(step.arguments, scope, preflight);
1226+
if (!args || typeof args !== 'object' || Array.isArray(args))
1227+
throw new Fault(
1228+
'invalid_tool_arguments',
1229+
'Foreach arguments must resolve to an object.',
1230+
);
1231+
argumentBudget.reserve(args as Record<string, unknown>);
1232+
prepared.push(args as Record<string, unknown>);
1233+
}
1234+
const wait = checkpoint();
1235+
if (wait) await wait;
1236+
checkAbort(signal);
1237+
if (stopping) break;
1238+
state.mapped = new Array(count);
1239+
state.prepared = prepared;
12611240
}
12621241
}
12631242
const slot = state.next++,
12641243
index = state.selected?.[slot] ?? slot;
1244+
const prepared = state.prepared?.[slot];
12651245
let scope = results;
12661246
let invocation = step;
12671247
if (step.foreach) {
1248+
if (!prepared) throw new Fault('invalid_graph', 'Foreach arguments were not prepared.');
1249+
state.prepared![slot] = undefined;
12681250
scope = itemScope(step.foreach.as, state.items![index], index);
12691251
invocation = { ...step, id: `${step.id}_${index}` };
12701252
// One item per visit keeps sibling maps inside the same concurrency budget.
12711253
if (state.next < state.mapped!.length) ready.push(state);
12721254
}
12731255
active++;
1274-
void runSingleInvocation(invocation, scope, signal, execute).then(
1256+
void runSingleInvocation(invocation, scope, signal, execute, prepared).then(
12751257
(value) => publish({ state, index: slot, outcome: { status: 'fulfilled', value } }),
12761258
(reason) => {
12771259
// Fence admissions immediately, before the consumer drains a successful sibling.
12781260
state.blocked = true;
1261+
delete state.prepared;
12791262
fail(reason);
12801263
publish({ state, index: slot, outcome: { status: 'rejected', reason } });
12811264
},
@@ -1303,7 +1286,7 @@ export async function executeGraph(
13031286
boundary([...approvals]);
13041287
} catch (error) {
13051288
fail(error);
1306-
stopping = true;
1289+
stop();
13071290
}
13081291
}
13091292
}

0 commit comments

Comments
 (0)