Skip to content

Commit 6329e84

Browse files
committed
perf(formula): build each typed check environment once per input, not once per call
The runtime authoring gate type-checks every expression in the stack on each metadata publish, and each check built a fresh typed cel-js environment (registry clone + whole stdlib). Measured on the showcase: 903 builds for 97 distinct inputs per object publish, about 0.5 s of the request idle. This is the slow path that pushed the two field-reorder dogfood cases past the 5 s per-case default on a loaded merge-group shard. Claude-Session: https://claude.ai/code/session_012MmDsP9M4FjNJxrUMf7ESW Co-authored-by: Claude <noreply@anthropic.com>
1 parent 7752cac commit 6329e84

3 files changed

Lines changed: 123 additions & 1 deletion

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/formula': patch
3+
---
4+
5+
perf(formula): the expression type checks build each typed check environment once per input, not once per call
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The type checks behind the authoring rules (`firstTypeMismatch`, `firstDateTextVerdict` and `firstDateTextCall`) built a new typed CEL environment on every call. Each build clones cel-js's registry and registers the whole stdlib again. The runtime authoring gate runs these checks over every expression in the stack each time a metadata item is published, so the cost grows with the size of the stack, not with the size of the item.
11+
12+
Measured on the showcase: one object publish built 903 environments for 97 distinct inputs. That was about 0.5 s of the publish request on an idle machine. The publish request now takes about 1.0 to 1.3 s on an idle machine, down from 1.6 to 1.8 s.
13+
14+
The environments are now kept per input (scope, date typing and field types), up to 512, least recently used first. The checks only parse and type-check against these environments, so a shared one gives the same verdicts as a fresh one. Nothing changes in what the checks report.

‎packages/formula/src/cel-engine.ts‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1088,7 +1088,9 @@ const MACRO_NAMES: ReadonlySet<string> = new Set(['all', 'exists', 'exists_one',
10881088
* conditions). Unlisted identifiers stay `dyn`
10891089
* (`unlistedVariablesAreDyn: true`) so a flow variable never
10901090
* faults — only a typed field misused does.
1091-
* Built per call — cheap, and only used at build time.
1091+
*
1092+
* Memoized on its inputs ({@link TYPED_ENV_CACHE}): the env is a pure function
1093+
* of them and every caller only parses and checks against it.
10921094
*/
10931095
function buildTypedEnv(
10941096
fieldCelTypes: Readonly<Record<string, FieldCelType>>,
@@ -1102,6 +1104,54 @@ function buildTypedEnv(
11021104
* reads the field.
11031105
*/
11041106
recordRootTypes?: Readonly<Record<string, FieldCelType>>,
1107+
): Environment {
1108+
const key = JSON.stringify([scope, temporal, fieldCelTypes, recordRootTypes ?? null]);
1109+
const cached = TYPED_ENV_CACHE.get(key);
1110+
if (cached) {
1111+
// Least-recently-used order: a hit moves to the young end.
1112+
TYPED_ENV_CACHE.delete(key);
1113+
TYPED_ENV_CACHE.set(key, cached);
1114+
return cached;
1115+
}
1116+
const env = createTypedEnv(fieldCelTypes, scope, temporal, recordRootTypes);
1117+
TYPED_ENV_CACHE.set(key, env);
1118+
if (TYPED_ENV_CACHE.size > TYPED_ENV_CACHE_LIMIT) {
1119+
TYPED_ENV_CACHE.delete(TYPED_ENV_CACHE.keys().next().value as string);
1120+
}
1121+
return env;
1122+
}
1123+
1124+
/**
1125+
* [#34756] The typed check envs {@link buildTypedEnv} has built, keyed on its
1126+
* inputs, least recently used first.
1127+
*
1128+
* Building one is not cheap: a fresh cel-js `Environment` clones the global
1129+
* registry and then registers the whole stdlib, the null comparisons and the
1130+
* temporal overloads one signature at a time. The runtime authoring gate runs
1131+
* the expression passes over the WHOLE stack on every metadata publish, and
1132+
* each expression asks for up to three of these envs. Measured on the
1133+
* showcase (one object publish): 903 builds for 97 distinct inputs, about
1134+
* 0.5 s of the publish request on an idle box, before this cache.
1135+
*
1136+
* Sharing an env is sound because nothing registers on one after it is built:
1137+
* every caller only `parse`s and `check`s against it, and neither changes
1138+
* what the env declares. ⛔ A new caller that registers on the returned env
1139+
* would leak that declaration into every later check with the same inputs —
1140+
* build a fresh one with {@link createTypedEnv} instead.
1141+
*
1142+
* Bounded so a long-lived process that sees many distinct field maps keeps a
1143+
* fixed footprint; the limit sits well above the distinct inputs one gate
1144+
* pass over the showcase asks for (97).
1145+
*/
1146+
const TYPED_ENV_CACHE = new Map<string, Environment>();
1147+
const TYPED_ENV_CACHE_LIMIT = 512;
1148+
1149+
/** {@link buildTypedEnv}'s uncached body: a fresh env for these inputs. */
1150+
function createTypedEnv(
1151+
fieldCelTypes: Readonly<Record<string, FieldCelType>>,
1152+
scope: 'record' | 'flattened',
1153+
temporal: TemporalTyping,
1154+
recordRootTypes: Readonly<Record<string, FieldCelType>> | undefined,
11051155
): Environment {
11061156
// `temporal` picks what a `date`/`datetime` field is declared as — see
11071157
// {@link TemporalTyping}.

‎packages/formula/src/cel-env-reuse.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,3 +121,61 @@ describe('#24536 — the per-source program cache answers every row as a fresh p
121121
for (let i = 0; i < 3; i++) expect(celEngine.evaluate(expr, { record: { a: 1 } })).toEqual(first);
122122
});
123123
});
124+
125+
/**
126+
* #34756 — the typed CHECK envs (`firstTypeMismatch`, `firstDateTextVerdict`,
127+
* `firstDateTextCall`) are built once per input, not once per call.
128+
*
129+
* The runtime authoring gate runs these over every expression of the whole
130+
* stack on each metadata publish. Measured on the showcase before the change:
131+
* 903 env builds for 97 distinct inputs per object publish, about 0.5 s of the
132+
* publish request on an idle box.
133+
*/
134+
describe('#34756 — one typed check env per input, not one per call', () => {
135+
const RECORD = { name: 'string', due: 'timestamp', ok: 'bool' } as const;
136+
137+
it('repeated checks of one field map build no new environment', async () => {
138+
const { firstTypeMismatch, firstDateTextVerdict, firstDateTextCall } = await import('./cel-engine');
139+
const sources = ['record.name > 3', 'record.due < record.name', 'record.ok + 1', 'record.name == "x"'];
140+
const run = () => {
141+
for (const s of sources) {
142+
firstTypeMismatch(s, RECORD);
143+
firstTypeMismatch(s.replace(/record\./g, ''), RECORD, 'flattened');
144+
firstDateTextVerdict(s, RECORD);
145+
firstDateTextCall(s, RECORD);
146+
}
147+
};
148+
// Positive control: the first pass builds the envs it needs.
149+
expect(built(run)).toBeGreaterThan(0);
150+
expect(built(() => { for (let i = 0; i < 20; i++) run(); })).toBe(0);
151+
});
152+
153+
it('the field types are part of the key: the same source keeps each map\'s own verdict', async () => {
154+
const { firstTypeMismatch } = await import('./cel-engine');
155+
const source = 'record.score > 3';
156+
for (let i = 0; i < 3; i++) {
157+
expect(firstTypeMismatch(source, { score: 'string' })).toMatchObject({
158+
operator: '>', celType: 'string', category: 'type-mismatch', field: 'score',
159+
});
160+
expect(firstTypeMismatch(source, { score: 'dyn' })).toBeNull();
161+
expect(firstTypeMismatch(source, { score: 'bool' })).toMatchObject({ celType: 'bool', field: 'score' });
162+
}
163+
});
164+
165+
it('the scope and temporal typing are part of the key too', async () => {
166+
const { firstTypeMismatch, firstDateTextVerdict } = await import('./cel-engine');
167+
const fields = { d: 'timestamp' } as const;
168+
for (let i = 0; i < 3; i++) {
169+
// A date field minus a number: refused under the Timestamp typing…
170+
expect(firstTypeMismatch('record.d + 1', fields)).toMatchObject({ category: 'date-arith' });
171+
// …and read through the same field map in flattened scope, bare.
172+
expect(firstTypeMismatch('d + 1', fields, 'flattened')).toMatchObject({ category: 'date-arith' });
173+
// The record scope does not bind a bare name, so there is nothing typed to fault.
174+
expect(firstTypeMismatch('d + 1', fields)).toBeNull();
175+
// The same map and scope under the date-text typing: the operand is the field's text.
176+
expect(firstTypeMismatch('record.d + 1', fields)).toMatchObject({ operands: 'google.protobuf.Timestamp + int' });
177+
expect(firstDateTextVerdict('record.d + 1', fields)).toMatchObject({ kind: 'fault', operands: 'DateText + int' });
178+
expect(firstDateTextVerdict('record.d < "2026-01-01"', fields)).toMatchObject({ kind: 'type', type: 'bool' });
179+
}
180+
});
181+
});

0 commit comments

Comments
 (0)