Skip to content

Commit 1ee45d7

Browse files
author
hzq
committed
Bound graph json output during serialization
Use the bounded serializer for json() expressions and share the expected text allowance with templates in foreach preflight. Preserve native JSON output and avoid completing oversized results.
1 parent b0a6dc3 commit 1ee45d7

9 files changed

Lines changed: 234 additions & 70 deletions

‎docs/language.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ The source length is checked **before** filtering. All predicates of one map are
274274

275275
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

277-
Preflight checks template expansion while it is being rendered, including interpolated JSON. Argument templates use the remaining prepared-text allowance, and predicate templates share a separate **24 MiB UTF-8 expansion budget** per loop. Exceeding either allowance stops rendering without dispatching an item.
277+
Preflight checks text expansion while rendering templates and serializing `json()` expressions, including interpolated JSON. Argument expansions use the remaining prepared-text allowance; predicate expansions share a separate **24 MiB UTF-8 budget** per loop. Exceeding either allowance stops before completing the oversized text or dispatching an item.
278278

279279
`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.
280280

@@ -321,6 +321,7 @@ agent "agent/step-block" {
321321
- `$(input.rows[input.pick] ?? "missing")` selects one array element using a computed zero-based index. Only non-negative safe integers are accepted; an invalid or out-of-range index, a missing element, or a non-array target yields `null`. It does not look up object properties or coerce numeric strings. Subscripts bind before arithmetic and can be chained for nested arrays. Require `graph-array-index-v1` in `GET /health` and upgrade any workers that install such bundles.
322322
- `$(input.rows[input.pick].title ?? "missing")` reads a fixed field from the selected object without scanning the array. Postfix `.field` binds like `[...]` and can be chained with it. It reads only own data fields, not inherited properties, getters, methods, or reserved names such as `constructor`. A missing field or a non-object target yields `null`; dynamic object keys are not supported. Check `graph-static-field-v1` in `GET /health` and upgrade workers that install bundles using the syntax.
323323
- Each expression has a separate 262,144-item budget for collection scans and value copies. Array scans reserve their length before iterating; `slice` reserves only the selected range, and array `len` does not scan its elements. Unused short-circuit branches do not spend the budget. Exceeding it raises `expression_budget_exceeded`, not `null`.
324+
- Outside `foreach` preflight, each expression also allows up to **24 MiB UTF-8** across the `json()` calls it actually executes. The serializer checks before producing oversized output.
324325

325326
```oaa
326327
agent "agent/values" {

‎docs/zh-CN/language.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ agent "agent/delegates" {
274274

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

277-
预检在模板拼接时检查文本额度,插值里的 JSON 也计入。参数模板使用尚未占用的预留文本额度;同一个循环的条件模板另共用 **24 MiB UTF-8 展开预算**。任一额度用尽时停止拼接,不派发循环项。
277+
预检在模板拼接和表达式 `json()` 序列化时检查文本额度,模板插入的 JSON 也计入。参数展开使用尚未占用的预留文本额度;同一循环的条件展开另共用 **24 MiB UTF-8 预算**。任一额度超限时不会生成完整的超大文本,也不会派发循环项。
278278

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

@@ -321,6 +321,7 @@ agent "agent/step-block" {
321321
- `$(input.rows[input.pick] ?? "missing")` 用计算出来的零基下标读取一个数组元素。只接受非负安全整数;无效或越界的下标、缺失的元素、非数组目标都返回 `null`。不会读取对象属性,也不会把数字字符串强转为下标。下标优先于算术,可连续取嵌套数组。使用前检查 `GET /health` 中的 `graph-array-index-v1`,并升级安装这类能力包的 worker。
322322
- `$(input.rows[input.pick].title ?? "missing")` 可直接读取选中对象的固定字段,不需要扫描整列。后缀 `.字段` 和 `[...]` 同优先级,可以交替使用。只读取对象自有的数据字段,不读取继承属性、getter、方法或 `constructor` 等保留名称。字段缺失或目标不是对象时返回 `null`,不支持动态对象键。使用前检查 `GET /health` 中的 `graph-static-field-v1`,并升级安装这类能力包的 worker。
323323
- 每个表达式另有 262,144 项的集合遍历和数据复制预算。遍历数组前按长度预扣,`slice` 只按选中范围计费,读取数组 `len` 不扫描元素。短路跳过的分支不计费,超限抛出 `expression_budget_exceeded`,不会返回 `null`。
324+
- 在 `foreach` 预检之外,每个表达式里实际执行的 `json()` 调用合计最多生成 **24 MiB UTF-8** 文本。检查发生在序列化过程中,不会等超大结果生成后才报错。
324325

325326
```oaa
326327
agent "agent/values" {

‎src/lang/bounded-json.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import type { TextBudget } from './expression-budget.js';
2+
3+
export const isHighSurrogate = (code: number) => code >= 0xd800 && code <= 0xdbff;
4+
export const isLowSurrogate = (code: number) => code >= 0xdc00 && code <= 0xdfff;
5+
6+
function chargeQuoted(text: string, budget: TextBudget): void {
7+
budget.check(text.length + 2);
8+
budget.charge(2);
9+
for (let from = 0; from < text.length;) {
10+
let to = Math.min(text.length, from + 4096);
11+
if (
12+
to < text.length &&
13+
isHighSurrogate(text.charCodeAt(to - 1)) &&
14+
isLowSurrogate(text.charCodeAt(to))
15+
)
16+
to--;
17+
budget.charge(Buffer.byteLength(JSON.stringify(text.slice(from, to))) - 2);
18+
from = to;
19+
}
20+
}
21+
22+
function unbox(value: unknown): unknown {
23+
if (value instanceof String) return String.prototype.valueOf.call(value);
24+
if (value instanceof Number) return Number.prototype.valueOf.call(value);
25+
if (value instanceof Boolean) return Boolean.prototype.valueOf.call(value);
26+
return value;
27+
}
28+
29+
export function stringifyBounded(value: unknown, budget: TextBudget): string | undefined {
30+
const emitted = new WeakSet<object>();
31+
let root = true;
32+
// The replacer charges the native serializer before it emits each property or element.
33+
return JSON.stringify(value, function (this: object, key, member: unknown) {
34+
const parentIsArray = Array.isArray(this);
35+
const omitted =
36+
member === undefined || typeof member === 'symbol' || typeof member === 'function';
37+
const isRoot = root;
38+
root = false;
39+
if (omitted && !parentIsArray) return member;
40+
if (!isRoot) {
41+
if (emitted.has(this)) budget.charge(1);
42+
emitted.add(this);
43+
if (!parentIsArray) {
44+
chargeQuoted(key, budget);
45+
budget.charge(1);
46+
}
47+
}
48+
const scalar = unbox(member);
49+
if (omitted)
50+
budget.charge(4); // Empty array slots serialize as null.
51+
else if (typeof scalar === 'string') chargeQuoted(scalar, budget);
52+
else if (scalar && typeof scalar === 'object') {
53+
budget.charge(2);
54+
emitted.delete(scalar); // A reused object has its own comma count each time it is visited.
55+
} else budget.charge(JSON.stringify(scalar).length);
56+
return member;
57+
});
58+
}

‎src/lang/expression-budget.ts‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { LIMITS } from '../core/limits.js';
44
export const EXPRESSION_COLLECTION_LIMIT = 262_144;
55
export const FOREACH_COLLECTION_LIMIT = 4 * EXPRESSION_COLLECTION_LIMIT;
66
export const FOREACH_ARGUMENT_TEXT_BYTES = LIMITS.nodeMessageBytes;
7+
export const EXPRESSION_JSON_TEXT_BYTES = LIMITS.nodeMessageBytes;
78

89
export class CollectionBudget {
910
constructor(
@@ -80,9 +81,9 @@ export class PreparedArgumentsBudget {
8081

8182
constructor(private readonly collection: CollectionBudget) {}
8283

83-
templateDraft(): TextBudget {
84+
expansionDraft(): TextBudget {
8485
// Rendering gets a provisional allowance; reserve charges the complete argument only once.
85-
return this.text.draft('Foreach argument template expansion exceeded its byte budget.');
86+
return this.text.draft('Foreach argument text expansion exceeded its byte budget.');
8687
}
8788

8889
reserve(value: Record<string, unknown>): void {
@@ -94,10 +95,20 @@ export class PreparedArgumentsBudget {
9495
export class ExpressionBudget extends CollectionBudget {
9596
private nodes = 0;
9697

97-
constructor(private readonly shared?: CollectionBudget) {
98+
constructor(
99+
private readonly shared?: CollectionBudget,
100+
private expansion?: TextBudget,
101+
) {
98102
super(EXPRESSION_COLLECTION_LIMIT, 'Expression collection work exceeded its item budget.');
99103
}
100104

105+
jsonText(): TextBudget {
106+
return (this.expansion ??= new TextBudget(
107+
EXPRESSION_JSON_TEXT_BYTES,
108+
'Expression JSON output exceeded its byte budget.',
109+
));
110+
}
111+
101112
node(): void {
102113
if (++this.nodes > 1024)
103114
throw new Fault('expression_budget_exceeded', 'Expression evaluation exceeded step budget.');

‎src/lang/expression-builtins.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { Fault } from '../core/util.js';
22
import type { ExpressionBudget } from './expression-budget.js';
3+
import { stringifyBounded } from './bounded-json.js';
34

45
export const SAFE_FUNCTIONS = new Set([
56
'len',
@@ -221,7 +222,7 @@ export function evalBuiltinCall(name: string, args: unknown[], budget: Expressio
221222
}
222223
case 'json': {
223224
budget.visitShape(args[0]);
224-
return JSON.stringify(args[0] ?? null);
225+
return stringifyBounded(args[0] ?? null, budget.jsonText());
225226
}
226227
default:
227228
throw new Fault('invalid_expression', `Unknown safe function: ${name}`);

‎src/lang/graph.ts‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -615,11 +615,12 @@ export function evaluateSafeExpr(
615615
expr: string,
616616
results: Map<string, unknown>,
617617
shared?: CollectionBudget,
618+
expansion?: TextBudget,
618619
): unknown {
619620
const s = expr.trim();
620621
if (!s) return null;
621622
const ast = parseExprAst(s);
622-
return evalAstNode(ast, results, new ExpressionBudget(shared));
623+
return evalAstNode(ast, results, new ExpressionBudget(shared, expansion));
623624
}
624625

625626
export function validateSafeExpression(expr: string): void {
@@ -974,11 +975,11 @@ export function resolveReferences(
974975
value: unknown,
975976
results: Map<string, unknown>,
976977
shared?: CollectionBudget,
977-
templateBudget?: TextBudget,
978+
expansion?: TextBudget,
978979
): unknown {
979980
if (Array.isArray(value)) {
980981
shared?.scan(value.length);
981-
return value.map((v) => resolveReferences(v, results, shared, templateBudget));
982+
return value.map((v) => resolveReferences(v, results, shared, expansion));
982983
}
983984
if (!value || typeof value !== 'object') return value;
984985
const o = value as Record<string, unknown>;
@@ -1005,19 +1006,19 @@ export function resolveReferences(
10051006
shared?.visitShape(val);
10061007
return val;
10071008
};
1008-
if (templateBudget) return renderBoundedTemplate(o.$template, lookup, templateBudget);
1009+
if (expansion) return renderBoundedTemplate(o.$template, lookup, expansion);
10091010
return o.$template.replaceAll(templateReferences, (_match, ref: string) => {
10101011
const val = lookup(ref);
10111012
return typeof val === 'object' && val !== null ? JSON.stringify(val) : String(val ?? '');
10121013
});
10131014
}
10141015
if ('$expr' in o && typeof o.$expr === 'string') {
1015-
return evaluateSafeExpr(o.$expr, results, shared);
1016+
return evaluateSafeExpr(o.$expr, results, shared, expansion);
10161017
}
10171018
const entries = Object.entries(o);
10181019
shared?.scan(entries.length);
10191020
return Object.fromEntries(
1020-
entries.map(([k, v]) => [k, resolveReferences(v, results, shared, templateBudget)]),
1021+
entries.map(([k, v]) => [k, resolveReferences(v, results, shared, expansion)]),
10211022
);
10221023
}
10231024

@@ -1205,7 +1206,7 @@ export async function executeGraph(
12051206
// Validate all predicates before dispatching any side effect of this map.
12061207
const predicateText = new TextBudget(
12071208
FOREACH_ARGUMENT_TEXT_BYTES,
1208-
'Foreach predicate template expansion exceeded its byte budget.',
1209+
'Foreach predicate text expansion exceeded its byte budget.',
12091210
);
12101211
state.selected = [];
12111212
for (const [index, item] of state.items.entries()) {
@@ -1242,7 +1243,7 @@ export async function executeGraph(
12421243
step.arguments,
12431244
scope,
12441245
preflight,
1245-
argumentBudget.templateDraft(),
1246+
argumentBudget.expansionDraft(),
12461247
);
12471248
if (!args || typeof args !== 'object' || Array.isArray(args))
12481249
throw new Fault(

‎src/lang/template-text.ts‎

Lines changed: 3 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,59 +1,8 @@
11
import type { TextBudget } from './expression-budget.js';
2-
3-
const high = (code: number) => code >= 0xd800 && code <= 0xdbff;
4-
const low = (code: number) => code >= 0xdc00 && code <= 0xdfff;
2+
import { isHighSurrogate, isLowSurrogate, stringifyBounded } from './bounded-json.js';
53

64
export const templateReferences = /\{\{(\$?[A-Za-z0-9_-]+(?:#[^}]*)?)\}\}/g;
75

8-
function chargeQuoted(text: string, budget: TextBudget): void {
9-
budget.check(text.length + 2);
10-
budget.charge(2);
11-
for (let from = 0; from < text.length;) {
12-
let to = Math.min(text.length, from + 4096);
13-
if (to < text.length && high(text.charCodeAt(to - 1)) && low(text.charCodeAt(to))) to--;
14-
budget.charge(Buffer.byteLength(JSON.stringify(text.slice(from, to))) - 2);
15-
from = to;
16-
}
17-
}
18-
19-
function unbox(value: unknown): unknown {
20-
if (value instanceof String) return String.prototype.valueOf.call(value);
21-
if (value instanceof Number) return Number.prototype.valueOf.call(value);
22-
if (value instanceof Boolean) return Boolean.prototype.valueOf.call(value);
23-
return value;
24-
}
25-
26-
function stringifyBounded(value: object, budget: TextBudget): string | undefined {
27-
const emitted = new WeakSet<object>();
28-
let root = true;
29-
// The replacer charges the native serializer before it emits each property or element.
30-
return JSON.stringify(value, function (this: object, key, member: unknown) {
31-
const parentIsArray = Array.isArray(this);
32-
const omitted =
33-
member === undefined || typeof member === 'symbol' || typeof member === 'function';
34-
const isRoot = root;
35-
root = false;
36-
if (omitted && !parentIsArray) return member;
37-
if (!isRoot) {
38-
if (emitted.has(this)) budget.charge(1);
39-
emitted.add(this);
40-
if (!parentIsArray) {
41-
chargeQuoted(key, budget);
42-
budget.charge(1);
43-
}
44-
}
45-
const scalar = unbox(member);
46-
if (omitted)
47-
budget.charge(4); // Empty array slots serialize as null.
48-
else if (typeof scalar === 'string') chargeQuoted(scalar, budget);
49-
else if (scalar && typeof scalar === 'object') {
50-
budget.charge(2);
51-
emitted.delete(scalar); // A reused object has its own comma count each time it is visited.
52-
} else budget.charge(JSON.stringify(scalar).length);
53-
return member;
54-
});
55-
}
56-
576
/** Check before concatenating segments, including JSON values expanded into the template. */
587
export function renderBoundedTemplate(
598
template: string,
@@ -73,12 +22,12 @@ export function renderBoundedTemplate(
7322
const append = (text: string) => {
7423
if (!text.length) return;
7524
// Two segments can together form one UTF-8 code point, even across an empty substitution.
76-
if (leadingSurrogate && low(text.charCodeAt(0))) {
25+
if (leadingSurrogate && isLowSurrogate(text.charCodeAt(0))) {
7726
push(leadingSurrogate + text[0]);
7827
leadingSurrogate = '';
7928
text = text.slice(1);
8029
} else flush();
81-
if (high(text.charCodeAt(text.length - 1))) {
30+
if (isHighSurrogate(text.charCodeAt(text.length - 1))) {
8231
leadingSurrogate = text.at(-1)!;
8332
text = text.slice(0, -1);
8433
}

0 commit comments

Comments
 (0)