Skip to content

Commit 2a84d67

Browse files
author
hzq
committed
Reduce array scanning overhead during graph resolution
1 parent e592347 commit 2a84d67

4 files changed

Lines changed: 249 additions & 16 deletions

File tree

‎bench/graph-reference-copy.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import assert from 'node:assert/strict';
2+
import path from 'node:path';
3+
import { pathToFileURL } from 'node:url';
4+
import { resolveReferences } from '../src/lang/graph.js';
5+
6+
// After building, pass a previous compiled graph.js to compare both versions in one process.
7+
const baseline = process.argv[2];
8+
const versions: [string, typeof resolveReferences][] = [];
9+
if (baseline)
10+
versions.push([
11+
'baseline',
12+
(await import(pathToFileURL(path.resolve(baseline)).href)).resolveReferences,
13+
]);
14+
versions.push(['current', resolveReferences]);
15+
const range = (n: number) => Array.from({ length: n }, (_, i) => i);
16+
const workloads: [string, unknown, number, boolean?][] = [
17+
['scalar', 42, 40_000],
18+
['dense-64', range(64), 10_000],
19+
['dense-4096', range(4096), 450],
20+
['dense-65536', range(65_536), 30],
21+
['nested-4096', { items: range(4096) }, 350],
22+
['mixed-4096', [...range(4095), { tag: 'last' }], 350],
23+
['records-1024', range(1024).map((n) => ({ n })), 100],
24+
['sparse-4096', Object.assign(Array(4096), { 99: 1 }), 500],
25+
['template-512', range(512), 600, true],
26+
];
27+
const rows: Record<string, string | number>[] = [];
28+
for (const [workload, value, iterations, template] of workloads) {
29+
const scope = new Map([['source', value]]);
30+
const args = { data: template ? { $template: '{{source}}' } : { $ref: 'source' } };
31+
const expected = { data: template ? JSON.stringify(value) : value };
32+
const samples = new Map(versions.map(([name]) => [name, [] as number[]]));
33+
for (let batch = 0; batch < 11; batch++) {
34+
for (const [name, resolve] of batch % 2 ? [...versions].reverse() : versions) {
35+
let result: unknown;
36+
const start = process.hrtime.bigint();
37+
for (let i = 0; i < iterations; i++) result = resolve(args, scope);
38+
const us = Number(process.hrtime.bigint() - start) / iterations / 1000;
39+
assert.deepEqual(result, expected);
40+
if (!template && value && typeof value === 'object')
41+
assert.notEqual((result as { data: unknown }).data, value);
42+
if (batch >= 2) samples.get(name)!.push(us);
43+
}
44+
}
45+
for (const [implementation, times] of samples) {
46+
times.sort((a, b) => a - b);
47+
rows.push({ workload, implementation, iterations, medianUs: +times[4]!.toFixed(3) });
48+
}
49+
}
50+
console.log(JSON.stringify({ node: process.version, batches: 9, rows }, null, 2));

‎src/lang/expression-budget.ts‎

Lines changed: 42 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { types } from 'node:util';
12
import { Fault } from '../core/util.js';
23
import { LIMITS } from '../core/limits.js';
34

@@ -8,6 +9,29 @@ export const FOREACH_ARGUMENT_TEXT_BYTES = LIMITS.nodeMessageBytes;
89
export const GRAPH_EXPANSION_TEXT_BYTES = LIMITS.nodeMessageBytes;
910
export const EXPRESSION_JSON_TEXT_BYTES = GRAPH_EXPANSION_TEXT_BYTES;
1011

12+
// On an own key this intrinsic detects a getter without invoking it or allocating a descriptor.
13+
const lookupGetter = Object.getOwnPropertyDescriptor(Object.prototype, '__lookupGetter__')
14+
?.value as ((this: object, key: string | number) => unknown) | undefined;
15+
16+
function inspectArray(array: unknown[], length: number, enqueue: (v: unknown) => void): boolean {
17+
if (typeof lookupGetter !== 'function' || types.isProxy(array)) {
18+
for (let i = 0; i < length; i++) enqueue(Object.getOwnPropertyDescriptor(array, i)?.value);
19+
return false;
20+
}
21+
let flat = true;
22+
for (let i = 0; i < length; i++) {
23+
if (!Object.hasOwn(array, i)) continue;
24+
if (lookupGetter.call(array, i) !== undefined) {
25+
flat = false;
26+
continue;
27+
}
28+
const member = array[i];
29+
if (member !== null && typeof member === 'object') flat = false;
30+
enqueue(member);
31+
}
32+
return flat;
33+
}
34+
1135
export class CollectionBudget {
1236
constructor(
1337
private remaining: number,
@@ -19,33 +43,41 @@ export class CollectionBudget {
1943
if (this.remaining < 0) throw new Fault('expression_budget_exceeded', this.message);
2044
}
2145

22-
visitShape(value: unknown, preserveAliases = false, onText?: (text: string) => void): void {
46+
/** Returns true for a root array with no indexed getters or object values at inspection. */
47+
visitShape(value: unknown, preserveAliases = false, onText?: (text: string) => void): boolean {
2348
if (typeof value === 'string') onText?.(value);
24-
if (!value || typeof value !== 'object') return;
49+
if (!value || typeof value !== 'object') return false;
2550
const stack = [value];
26-
const seen = preserveAliases ? new WeakSet<object>(stack) : undefined;
27-
const enqueue = (obj: object, key: string | number) => {
28-
const v: unknown = Object.getOwnPropertyDescriptor(obj, key)?.value;
51+
let flatRoot = false;
52+
let seen: WeakSet<object> | undefined;
53+
const enqueue = (v: unknown) => {
2954
if (onText && typeof v === 'string') onText(v);
30-
if (v && typeof v === 'object' && !seen?.has(v)) {
31-
seen?.add(v);
55+
if (v && typeof v === 'object') {
56+
if (preserveAliases) {
57+
seen ??= new WeakSet([value]);
58+
if (seen.has(v)) return;
59+
seen.add(v);
60+
}
3261
stack.push(v);
3362
}
3463
};
3564
while (stack.length) {
3665
const next = stack.pop()!;
3766
if (Array.isArray(next)) {
38-
this.scan(next.length);
39-
for (let i = 0; i < next.length; i++) enqueue(next, i);
67+
const length = next.length;
68+
this.scan(length);
69+
const flat = inspectArray(next, length, enqueue);
70+
if (next === value) flatRoot = flat;
4071
} else {
4172
const keys = Object.keys(next);
4273
this.scan(keys.length);
4374
for (const key of keys) {
4475
onText?.(key);
45-
enqueue(next, key);
76+
enqueue(Object.getOwnPropertyDescriptor(next, key)?.value);
4677
}
4778
}
4879
}
80+
return flatRoot;
4981
}
5082
}
5183

‎src/lang/graph.ts‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -968,12 +968,17 @@ export function validateWorkflows(
968968
return { effects, workflowPlans };
969969
}
970970

971-
function copyResolvedValue(value: unknown, shared: CollectionBudget): unknown {
971+
function copyResolvedValue(value: unknown, shared: CollectionBudget, forTemplate = false): unknown {
972972
const type = typeof value;
973973
if (value === null || (type !== 'object' && type !== 'function' && type !== 'symbol'))
974974
return value;
975-
shared.visitShape(value, true);
976-
return structuredClone(value);
975+
const flatArray = shared.visitShape(value, true);
976+
const copy: unknown = structuredClone(value);
977+
if (forTemplate) {
978+
if (flatArray && Array.isArray(copy)) shared.scan(copy.length);
979+
else shared.visitShape(copy);
980+
}
981+
return copy;
977982
}
978983

979984
export function resolveReferences(
@@ -1013,9 +1018,7 @@ export function resolveReferences(
10131018
const [name, pointer] = ref.split('#');
10141019
if (!results.has(name!))
10151020
throw new Fault('invalid_reference', 'Referenced step has not completed.');
1016-
const val = copyResolvedValue(pointerTarget(results.get(name!), pointer), shared);
1017-
shared.visitShape(val);
1018-
return val;
1021+
return copyResolvedValue(pointerTarget(results.get(name!), pointer), shared, true);
10191022
};
10201023
return renderBoundedTemplate(o.$template, lookup, expansion);
10211024
}

‎test/graph-array-copy.test.ts‎

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
import assert from 'node:assert/strict';
2+
import test from 'node:test';
3+
import { CollectionBudget, ExpressionBudget } from '../src/lang/expression-budget.js';
4+
import { resolveReferences } from '../src/lang/graph.js';
5+
6+
function copy(source: unknown[], slots = 1_048_576): unknown[] {
7+
return resolveReferences(
8+
{ $ref: 'source' },
9+
new Map([['source', source]]),
10+
new CollectionBudget(slots, 'fixture budget'),
11+
) as unknown[];
12+
}
13+
14+
test('graph and expression array copies keep native cloning without allocating one descriptor per slot', (t) => {
15+
const source = Array.from<unknown>({ length: 64 }).fill(1);
16+
source.splice(8, 8, false, -0, NaN, 3n, '', null, undefined, 'text');
17+
const native = t.mock.method(globalThis, 'structuredClone');
18+
const describe = t.mock.method(Object, 'getOwnPropertyDescriptor');
19+
const a = copy(source, source.length);
20+
const b = new ExpressionBudget().copy(source) as unknown[];
21+
assert.notEqual(a, b);
22+
assert.notEqual(a, source);
23+
assert.deepEqual(a, source);
24+
assert.deepEqual(b, source);
25+
a[0] = 7;
26+
assert.equal(b[0], 1);
27+
assert.equal(source[0], 1);
28+
assert.equal(native.mock.calls.filter(({ arguments: args }) => args[0] === source).length, 2);
29+
if (typeof Reflect.get(Object.prototype, '__lookupGetter__') === 'function')
30+
assert.equal(describe.mock.calls.filter(({ arguments: args }) => args[0] === source).length, 0);
31+
});
32+
33+
test('flat template arrays pay the exact second charge without a second walk', (t) => {
34+
const source = Array.from({ length: 64 }, (_, i) => i);
35+
const scope = new Map([['source', source]]);
36+
const template = { $template: '{{source}}' };
37+
const budget = new CollectionBudget(2 * source.length, 'template slots');
38+
const walk = t.mock.method(budget, 'visitShape');
39+
assert.equal(resolveReferences(template, scope, budget), JSON.stringify(source));
40+
if (typeof Reflect.get(Object.prototype, '__lookupGetter__') === 'function')
41+
assert.equal(walk.mock.callCount(), 1);
42+
assert.throws(
43+
() => resolveReferences(template, scope, new CollectionBudget(127, 'template slots')),
44+
{
45+
code: 'expression_budget_exceeded',
46+
},
47+
);
48+
});
49+
50+
test('a template checks the cloned descendants when an indexed getter supplies an object', () => {
51+
let reads = 0;
52+
const source = Array(4).fill(1);
53+
Object.defineProperty(source, 2, {
54+
enumerable: true,
55+
get() {
56+
reads++;
57+
return { n: [2, 3] };
58+
},
59+
});
60+
const scope = new Map([['source', source]]);
61+
const render = (slots: number) =>
62+
resolveReferences(
63+
{ $template: '{{source}}' },
64+
scope,
65+
new CollectionBudget(slots, 'template slots'),
66+
);
67+
assert.equal(render(11), '[1,1,{"n":[2,3]},1]');
68+
assert.throws(() => render(10), { code: 'expression_budget_exceeded' });
69+
assert.equal(reads, 2);
70+
});
71+
72+
test('mixed arrays keep alias and cycle identity and charge each nested object once per copy', () => {
73+
const leaf = { n: 1 };
74+
const source: unknown[] = Array(32).fill(null);
75+
source[27] = leaf;
76+
source[28] = leaf;
77+
source[31] = source;
78+
const cloned = copy(source, 33);
79+
assert.equal(cloned[27], cloned[28]);
80+
assert.notEqual(cloned[27], leaf);
81+
assert.equal(cloned[31], cloned);
82+
assert.throws(() => copy(source, 32), { code: 'expression_budget_exceeded' });
83+
});
84+
85+
test('copy preflight does not read accessors and native cloning reads them once in order', () => {
86+
const reads: number[] = [];
87+
const source: unknown[] = Array(64).fill(0);
88+
Object.defineProperty(source, 10, {
89+
enumerable: true,
90+
get() {
91+
reads.push(10);
92+
source[11] = 'changed';
93+
return 10;
94+
},
95+
});
96+
Object.defineProperty(source, 37, {
97+
enumerable: true,
98+
get() {
99+
reads.push(37);
100+
return 37;
101+
},
102+
});
103+
source[63] = { nested: true };
104+
assert.throws(() => copy(source, 64), { code: 'expression_budget_exceeded' });
105+
assert.deepEqual(reads, []);
106+
const cloned = copy(source, 65);
107+
assert.deepEqual(reads, [10, 37]);
108+
assert.equal(cloned[10], 10);
109+
assert.equal(cloned[11], 'changed');
110+
assert.equal(cloned[37], 37);
111+
});
112+
113+
test('sparse, non-enumerable and named array properties retain native clone behavior', () => {
114+
const sparse: unknown[] = Array(64);
115+
sparse[9] = 'only';
116+
Object.defineProperty(sparse, 12, { value: { field: true } });
117+
Object.defineProperty(sparse, '__proto__', { enumerable: true, value: { tag: 'own' } });
118+
Object.defineProperty(sparse, '062', { enumerable: true, value: 'named' });
119+
assert.deepEqual(copy(sparse), structuredClone(sparse));
120+
assert.throws(() => copy(sparse, 64), { code: 'expression_budget_exceeded' });
121+
const noncloneable = Array(32).fill(1);
122+
noncloneable[31] = Symbol('not cloneable');
123+
assert.throws(() => copy(noncloneable), { name: 'DataCloneError' });
124+
assert.equal(new ExpressionBudget().copy(noncloneable), null);
125+
let proxyReads = 0;
126+
const proxy = new Proxy(Array(32).fill(1), {
127+
get(target, key, receiver) {
128+
if (key !== 'length') proxyReads++;
129+
return Reflect.get(target, key, receiver);
130+
},
131+
});
132+
assert.throws(() => copy(proxy), { name: 'DataCloneError' });
133+
assert.equal(proxyReads, 0);
134+
});
135+
136+
test('a named field cannot disguise a hole or cause an inherited getter to be read', () => {
137+
const source = Array<unknown>(32).fill(0);
138+
delete source[7];
139+
Object.defineProperty(source, '007', { enumerable: true, value: 'named' });
140+
const proto = Object.create(Array.prototype);
141+
Object.defineProperty(proto, 7, { get: () => assert.fail('inherited getter ran') });
142+
Object.setPrototypeOf(source, proto);
143+
assert.equal(Object.keys(source).length, source.length);
144+
const cloned = copy(source, 32);
145+
assert.equal(Object.hasOwn(cloned, 7), false);
146+
assert.equal(Object.getOwnPropertyDescriptor(cloned, '007')?.value, 'named');
147+
assert.equal(Object.getPrototypeOf(cloned), Array.prototype);
148+
});

0 commit comments

Comments
 (0)