Skip to content

Commit b861dcb

Browse files
author
hzq
committed
Bound collection work in OAA expressions
Charge array scans and value copies independently of AST steps. Borrow read-only inputs for collection operations, detach returned values, and keep short-circuit and small-slice behavior intact.
1 parent 4f7f811 commit b861dcb

6 files changed

Lines changed: 347 additions & 61 deletions

File tree

‎docs/language.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,7 @@ agent "agent/step-block" {
316316
- In `$(input.limit ?? 10)`, use 10 only when the field is missing or null. The operator returns the value itself, preserving 0, false and empty strings, and does not evaluate an unused default. Both operands are still checked at compile time. It binds below `||` and above `? :`; parenthesize mixed expressions for readability. Older runtimes need an upgrade before using this syntax.
317317
- `$(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.
318318
- `$(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.
319+
- 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`.
319320

320321
```oaa
321322
agent "agent/values" {

‎docs/zh-CN/language.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,7 @@ agent "agent/step-block" {
316316
- `$(input.limit ?? 10)` 只在字段缺失或为 `null` 时取 10;左侧为 0、`false`、空字符串时保留原值,且不计算右侧。两侧仍须通过编译期检查。它的优先级低于 `||`、高于 `? :`,混用时建议加括号。使用此语法前请升级旧版运行时。
317317
- `$(input.rows[input.pick] ?? "missing")` 用计算出来的零基下标读取一个数组元素。只接受非负安全整数;无效或越界的下标、缺失的元素、非数组目标都返回 `null`。不会读取对象属性,也不会把数字字符串强转为下标。下标优先于算术,可连续取嵌套数组。使用前检查 `GET /health` 中的 `graph-array-index-v1`,并升级安装这类能力包的 worker。
318318
- `$(input.rows[input.pick].title ?? "missing")` 可直接读取选中对象的固定字段,不需要扫描整列。后缀 `.字段` 和 `[...]` 同优先级,可以交替使用。只读取对象自有的数据字段,不读取继承属性、getter、方法或 `constructor` 等保留名称。字段缺失或目标不是对象时返回 `null`,不支持动态对象键。使用前检查 `GET /health` 中的 `graph-static-field-v1`,并升级安装这类能力包的 worker。
319+
- 每个表达式另有 262,144 项的集合遍历和数据复制预算。遍历数组前按长度预扣,`slice` 只按选中范围计费,读取数组 `len` 不扫描元素。短路跳过的分支不计费,超限抛出 `expression_budget_exceeded`,不会返回 `null`。
319320

320321
```oaa
321322
agent "agent/values" {

‎src/lang/expression-budget.ts‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import { Fault } from '../core/util.js';
2+
3+
export const EXPRESSION_COLLECTION_LIMIT = 262_144;
4+
5+
/** Charge variable-sized data work independently of the size of the expression AST. */
6+
export class ExpressionBudget {
7+
private nodes = 0;
8+
private remaining = EXPRESSION_COLLECTION_LIMIT;
9+
10+
node(): void {
11+
if (++this.nodes > 1024)
12+
throw new Fault('expression_budget_exceeded', 'Expression evaluation exceeded step budget.');
13+
}
14+
15+
scan(slots: number): void {
16+
this.remaining -= slots;
17+
if (this.remaining < 0)
18+
throw new Fault(
19+
'expression_budget_exceeded',
20+
'Expression collection work exceeded its item budget.',
21+
);
22+
}
23+
24+
visitShape(value: unknown, preserveAliases = false): void {
25+
if (!value || typeof value !== 'object') return;
26+
const stack = [value];
27+
const seen = preserveAliases ? new WeakSet<object>(stack) : undefined;
28+
const enqueue = (obj: object, key: string | number) => {
29+
const v: unknown = Object.getOwnPropertyDescriptor(obj, key)?.value;
30+
if (v && typeof v === 'object' && !seen?.has(v)) {
31+
seen?.add(v);
32+
stack.push(v);
33+
}
34+
};
35+
while (stack.length) {
36+
const next = stack.pop()!;
37+
if (Array.isArray(next)) {
38+
this.scan(next.length);
39+
for (let i = 0; i < next.length; i++) enqueue(next, i);
40+
} else {
41+
const keys = Object.keys(next);
42+
this.scan(keys.length);
43+
for (const key of keys) enqueue(next, key);
44+
}
45+
}
46+
}
47+
48+
copy(value: unknown): unknown {
49+
// Budget failures are not missing values and must not be swallowed by ?? defaults.
50+
this.visitShape(value, true);
51+
try {
52+
return structuredClone(value);
53+
} catch {
54+
return null;
55+
}
56+
}
57+
}

‎src/lang/expression-builtins.ts‎

Lines changed: 125 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { Fault } from '../core/util.js';
2+
import type { ExpressionBudget } from './expression-budget.js';
23

34
export const SAFE_FUNCTIONS = new Set([
45
'len',
@@ -26,18 +27,62 @@ export const SAFE_FUNCTIONS = new Set([
2627
'json',
2728
]);
2829

29-
export function evalBuiltinCall(name: string, args: unknown[]): unknown {
30+
// Borrow only a read-only first argument; the evaluator still detaches results that may alias it.
31+
export const BORROW_FIRST_ARGUMENT = new Set([
32+
'len',
33+
'keys',
34+
'has',
35+
'includes',
36+
'join',
37+
'slice',
38+
'pluck',
39+
'compact',
40+
'unique',
41+
'sum',
42+
'avg',
43+
]);
44+
export const MAY_RETURN_BORROWED_VALUES = new Set(['slice', 'pluck', 'compact', 'unique']);
45+
46+
function arrayIndex(value: number, length: number): number {
47+
const whole = Math.trunc(value);
48+
return Math.min(length, Math.max(0, whole < 0 ? length + whole : whole));
49+
}
50+
51+
function toNumeric(value: unknown, budget: ExpressionBudget): number {
52+
if (Array.isArray(value)) budget.visitShape(value);
53+
return Number(value);
54+
}
55+
56+
function toText(value: unknown, budget: ExpressionBudget): string {
57+
if (Array.isArray(value)) budget.visitShape(value);
58+
return String(value);
59+
}
60+
61+
export function expressionArrayIncludes(
62+
array: unknown[],
63+
value: unknown,
64+
budget: ExpressionBudget,
65+
): boolean {
66+
budget.scan(array.length);
67+
return Array.prototype.includes.call(array, value);
68+
}
69+
70+
export function evalBuiltinCall(name: string, args: unknown[], budget: ExpressionBudget): unknown {
3071
switch (name) {
3172
case 'len': {
3273
const v = args[0];
3374
if (typeof v === 'string' || Array.isArray(v)) return v.length;
34-
if (v && typeof v === 'object') return Object.keys(v).length;
75+
if (v && typeof v === 'object') {
76+
const count = Object.keys(v).length;
77+
budget.scan(count);
78+
return count;
79+
}
3580
return 0;
3681
}
3782
case 'includes': {
3883
const [haystack, needle] = args;
3984
if (typeof haystack === 'string') return haystack.includes(String(needle ?? ''));
40-
if (Array.isArray(haystack)) return haystack.includes(needle);
85+
if (Array.isArray(haystack)) return expressionArrayIncludes(haystack, needle, budget);
4186
return false;
4287
}
4388
case 'startsWith':
@@ -51,11 +96,11 @@ export function evalBuiltinCall(name: string, args: unknown[]): unknown {
5196
case 'trim':
5297
return typeof args[0] === 'string' ? args[0].trim() : '';
5398
case 'min': {
54-
const nums = args.map(Number).filter((n) => !Number.isNaN(n));
99+
const nums = args.map((value) => toNumeric(value, budget)).filter((n) => !Number.isNaN(n));
55100
return nums.length ? Math.min(...nums) : null;
56101
}
57102
case 'max': {
58-
const nums = args.map(Number).filter((n) => !Number.isNaN(n));
103+
const nums = args.map((value) => toNumeric(value, budget)).filter((n) => !Number.isNaN(n));
59104
return nums.length ? Math.max(...nums) : null;
60105
}
61106
case 'round':
@@ -67,10 +112,14 @@ export function evalBuiltinCall(name: string, args: unknown[]): unknown {
67112
if (item !== null && item !== undefined) return item;
68113
}
69114
return null;
70-
case 'keys':
71-
return args[0] && typeof args[0] === 'object' && !Array.isArray(args[0])
72-
? Object.keys(args[0] as Record<string, unknown>)
73-
: [];
115+
case 'keys': {
116+
const keys =
117+
args[0] && typeof args[0] === 'object' && !Array.isArray(args[0])
118+
? Object.keys(args[0] as Record<string, unknown>)
119+
: [];
120+
budget.scan(keys.length);
121+
return keys;
122+
}
74123
case 'has':
75124
return (
76125
Boolean(args[0]) &&
@@ -83,28 +132,41 @@ export function evalBuiltinCall(name: string, args: unknown[]): unknown {
83132
case 'join': {
84133
const [arr, sep] = args;
85134
if (!Array.isArray(arr)) return '';
86-
const out = arr
87-
.map((x) => (x === null || x === undefined ? '' : String(x)))
88-
.join(String(sep ?? ','));
89-
if (out.length > 65536) {
90-
throw new Fault('expression_budget_exceeded', 'Joined string exceeds 64 KiB.');
135+
budget.scan(arr.length);
136+
const separator = toText(sep ?? ',', budget);
137+
let out = '';
138+
for (let i = 0; i < arr.length; i++) {
139+
const between = i ? separator : '';
140+
const item: unknown = arr[i];
141+
const text = item === null || item === undefined ? '' : toText(item, budget);
142+
if (out.length + between.length + text.length > 65536)
143+
throw new Fault('expression_budget_exceeded', 'Joined string exceeds 64 KiB.');
144+
out += between + text;
91145
}
92146
return out;
93147
}
94148
case 'split': {
95149
const [str, sep] = args;
96150
if (typeof str !== 'string') return [];
97-
return str.split(String(sep ?? ',')).slice(0, 256);
151+
return str.split(toText(sep ?? ',', budget), 256);
98152
}
99153
case 'slice': {
100154
const [target, start, end] = args;
101-
const s = Number(start ?? 0);
102-
const e = end === undefined ? undefined : Number(end);
155+
const s = toNumeric(start ?? 0, budget);
156+
const e = end === undefined ? undefined : toNumeric(end, budget);
103157
if (Array.isArray(target) || typeof target === 'string') {
104-
return target.slice(
105-
Number.isNaN(s) ? 0 : s,
106-
e !== undefined && !Number.isNaN(e) ? e : undefined,
107-
);
158+
const first = Number.isNaN(s) ? 0 : s;
159+
const last = e !== undefined && !Number.isNaN(e) ? e : undefined;
160+
if (typeof target === 'string') return target.slice(first, last);
161+
const start = arrayIndex(first, target.length);
162+
const size = Math.max(0, arrayIndex(last ?? target.length, target.length) - start);
163+
budget.scan(size);
164+
const result = Array<unknown>(size);
165+
for (let i = 0; i < size; i++) {
166+
const slot = Object.getOwnPropertyDescriptor(target, start + i);
167+
if (slot && 'value' in slot) result[i] = slot.value;
168+
}
169+
return result;
108170
}
109171
return [];
110172
}
@@ -116,28 +178,51 @@ export function evalBuiltinCall(name: string, args: unknown[]): unknown {
116178
['__proto__', 'prototype', 'constructor'].includes(key)
117179
)
118180
return [];
119-
return arr.map((item) =>
120-
item && typeof item === 'object' && Object.hasOwn(item as object, key)
121-
? (item as Record<string, unknown>)[key]
122-
: null,
123-
);
181+
budget.scan(arr.length);
182+
const values = Array<unknown>(arr.length);
183+
for (let i = 0; i < arr.length; i++) {
184+
const slot = Object.getOwnPropertyDescriptor(arr, i);
185+
if (!slot || !('value' in slot)) continue;
186+
const item: unknown = slot.value;
187+
const field =
188+
item && typeof item === 'object' ? Object.getOwnPropertyDescriptor(item, key) : undefined;
189+
values[i] = field && 'value' in field ? field.value : null;
190+
}
191+
return values;
192+
}
193+
case 'compact': {
194+
if (!Array.isArray(args[0])) return [];
195+
budget.scan(args[0].length);
196+
const items: unknown[] = [];
197+
for (let i = 0; i < args[0].length; i++) {
198+
const x: unknown = Object.getOwnPropertyDescriptor(args[0], i)?.value;
199+
if (x !== null && x !== undefined && x !== false && x !== '') items.push(x);
200+
}
201+
return items;
202+
}
203+
case 'unique': {
204+
if (!Array.isArray(args[0])) return [];
205+
budget.scan(args[0].length);
206+
const values = new Set<unknown>();
207+
for (let i = 0; i < args[0].length; i++)
208+
values.add(Object.getOwnPropertyDescriptor(args[0], i)?.value);
209+
return [...values];
124210
}
125-
case 'compact':
126-
return Array.isArray(args[0])
127-
? args[0].filter((x) => x !== null && x !== undefined && x !== false && x !== '')
128-
: [];
129-
case 'unique':
130-
return Array.isArray(args[0]) ? [...new Set(args[0])] : [];
131211
case 'sum':
132-
return Array.isArray(args[0])
133-
? args[0].reduce((acc: number, v) => acc + (Number(v) || 0), 0)
134-
: 0;
135-
case 'avg':
136-
return Array.isArray(args[0]) && args[0].length > 0
137-
? args[0].reduce((acc: number, v) => acc + (Number(v) || 0), 0) / args[0].length
138-
: 0;
139-
case 'json':
212+
case 'avg': {
213+
if (!Array.isArray(args[0]) || !args[0].length) return 0;
214+
budget.scan(args[0].length);
215+
const total = Array.prototype.reduce.call(
216+
args[0],
217+
(acc: unknown, v: unknown) => (acc as number) + (toNumeric(v, budget) || 0),
218+
0,
219+
) as number;
220+
return name === 'avg' ? total / args[0].length : total;
221+
}
222+
case 'json': {
223+
budget.visitShape(args[0]);
140224
return JSON.stringify(args[0] ?? null);
225+
}
141226
default:
142227
throw new Fault('invalid_expression', `Unknown safe function: ${name}`);
143228
}

0 commit comments

Comments
 (0)