From 6329e84a080bc7d1591c706a342db37a86a8a5ff Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 14:21:57 +0000 Subject: [PATCH] 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 --- .../34756-field-reorder-dogfood-timeout.md | 14 +++++ packages/formula/src/cel-engine.ts | 52 ++++++++++++++++- packages/formula/src/cel-env-reuse.test.ts | 58 +++++++++++++++++++ 3 files changed, 123 insertions(+), 1 deletion(-) create mode 100644 .changeset/34756-field-reorder-dogfood-timeout.md diff --git a/.changeset/34756-field-reorder-dogfood-timeout.md b/.changeset/34756-field-reorder-dogfood-timeout.md new file mode 100644 index 00000000000..575b8090e13 --- /dev/null +++ b/.changeset/34756-field-reorder-dogfood-timeout.md @@ -0,0 +1,14 @@ +--- +'@objectstack/formula': patch +--- + +perf(formula): the expression type checks build each typed check environment once per input, not once per call + +Clause-②: no +Metadata-protocol: none + +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. + +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. + +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. diff --git a/packages/formula/src/cel-engine.ts b/packages/formula/src/cel-engine.ts index e4d83827d46..c6b75e00e9a 100644 --- a/packages/formula/src/cel-engine.ts +++ b/packages/formula/src/cel-engine.ts @@ -1088,7 +1088,9 @@ const MACRO_NAMES: ReadonlySet = new Set(['all', 'exists', 'exists_one', * conditions). Unlisted identifiers stay `dyn` * (`unlistedVariablesAreDyn: true`) so a flow variable never * faults — only a typed field misused does. - * Built per call — cheap, and only used at build time. + * + * Memoized on its inputs ({@link TYPED_ENV_CACHE}): the env is a pure function + * of them and every caller only parses and checks against it. */ function buildTypedEnv( fieldCelTypes: Readonly>, @@ -1102,6 +1104,54 @@ function buildTypedEnv( * reads the field. */ recordRootTypes?: Readonly>, +): Environment { + const key = JSON.stringify([scope, temporal, fieldCelTypes, recordRootTypes ?? null]); + const cached = TYPED_ENV_CACHE.get(key); + if (cached) { + // Least-recently-used order: a hit moves to the young end. + TYPED_ENV_CACHE.delete(key); + TYPED_ENV_CACHE.set(key, cached); + return cached; + } + const env = createTypedEnv(fieldCelTypes, scope, temporal, recordRootTypes); + TYPED_ENV_CACHE.set(key, env); + if (TYPED_ENV_CACHE.size > TYPED_ENV_CACHE_LIMIT) { + TYPED_ENV_CACHE.delete(TYPED_ENV_CACHE.keys().next().value as string); + } + return env; +} + +/** + * [#34756] The typed check envs {@link buildTypedEnv} has built, keyed on its + * inputs, least recently used first. + * + * Building one is not cheap: a fresh cel-js `Environment` clones the global + * registry and then registers the whole stdlib, the null comparisons and the + * temporal overloads one signature at a time. The runtime authoring gate runs + * the expression passes over the WHOLE stack on every metadata publish, and + * each expression asks for up to three of these envs. Measured on the + * showcase (one object publish): 903 builds for 97 distinct inputs, about + * 0.5 s of the publish request on an idle box, before this cache. + * + * Sharing an env is sound because nothing registers on one after it is built: + * every caller only `parse`s and `check`s against it, and neither changes + * what the env declares. ⛔ A new caller that registers on the returned env + * would leak that declaration into every later check with the same inputs — + * build a fresh one with {@link createTypedEnv} instead. + * + * Bounded so a long-lived process that sees many distinct field maps keeps a + * fixed footprint; the limit sits well above the distinct inputs one gate + * pass over the showcase asks for (97). + */ +const TYPED_ENV_CACHE = new Map(); +const TYPED_ENV_CACHE_LIMIT = 512; + +/** {@link buildTypedEnv}'s uncached body: a fresh env for these inputs. */ +function createTypedEnv( + fieldCelTypes: Readonly>, + scope: 'record' | 'flattened', + temporal: TemporalTyping, + recordRootTypes: Readonly> | undefined, ): Environment { // `temporal` picks what a `date`/`datetime` field is declared as — see // {@link TemporalTyping}. diff --git a/packages/formula/src/cel-env-reuse.test.ts b/packages/formula/src/cel-env-reuse.test.ts index 34978bb9997..637fa08c32e 100644 --- a/packages/formula/src/cel-env-reuse.test.ts +++ b/packages/formula/src/cel-env-reuse.test.ts @@ -121,3 +121,61 @@ describe('#24536 — the per-source program cache answers every row as a fresh p for (let i = 0; i < 3; i++) expect(celEngine.evaluate(expr, { record: { a: 1 } })).toEqual(first); }); }); + +/** + * #34756 — the typed CHECK envs (`firstTypeMismatch`, `firstDateTextVerdict`, + * `firstDateTextCall`) are built once per input, not once per call. + * + * The runtime authoring gate runs these over every expression of the whole + * stack on each metadata publish. Measured on the showcase before the change: + * 903 env builds for 97 distinct inputs per object publish, about 0.5 s of the + * publish request on an idle box. + */ +describe('#34756 — one typed check env per input, not one per call', () => { + const RECORD = { name: 'string', due: 'timestamp', ok: 'bool' } as const; + + it('repeated checks of one field map build no new environment', async () => { + const { firstTypeMismatch, firstDateTextVerdict, firstDateTextCall } = await import('./cel-engine'); + const sources = ['record.name > 3', 'record.due < record.name', 'record.ok + 1', 'record.name == "x"']; + const run = () => { + for (const s of sources) { + firstTypeMismatch(s, RECORD); + firstTypeMismatch(s.replace(/record\./g, ''), RECORD, 'flattened'); + firstDateTextVerdict(s, RECORD); + firstDateTextCall(s, RECORD); + } + }; + // Positive control: the first pass builds the envs it needs. + expect(built(run)).toBeGreaterThan(0); + expect(built(() => { for (let i = 0; i < 20; i++) run(); })).toBe(0); + }); + + it('the field types are part of the key: the same source keeps each map\'s own verdict', async () => { + const { firstTypeMismatch } = await import('./cel-engine'); + const source = 'record.score > 3'; + for (let i = 0; i < 3; i++) { + expect(firstTypeMismatch(source, { score: 'string' })).toMatchObject({ + operator: '>', celType: 'string', category: 'type-mismatch', field: 'score', + }); + expect(firstTypeMismatch(source, { score: 'dyn' })).toBeNull(); + expect(firstTypeMismatch(source, { score: 'bool' })).toMatchObject({ celType: 'bool', field: 'score' }); + } + }); + + it('the scope and temporal typing are part of the key too', async () => { + const { firstTypeMismatch, firstDateTextVerdict } = await import('./cel-engine'); + const fields = { d: 'timestamp' } as const; + for (let i = 0; i < 3; i++) { + // A date field minus a number: refused under the Timestamp typing… + expect(firstTypeMismatch('record.d + 1', fields)).toMatchObject({ category: 'date-arith' }); + // …and read through the same field map in flattened scope, bare. + expect(firstTypeMismatch('d + 1', fields, 'flattened')).toMatchObject({ category: 'date-arith' }); + // The record scope does not bind a bare name, so there is nothing typed to fault. + expect(firstTypeMismatch('d + 1', fields)).toBeNull(); + // The same map and scope under the date-text typing: the operand is the field's text. + expect(firstTypeMismatch('record.d + 1', fields)).toMatchObject({ operands: 'google.protobuf.Timestamp + int' }); + expect(firstDateTextVerdict('record.d + 1', fields)).toMatchObject({ kind: 'fault', operands: 'DateText + int' }); + expect(firstDateTextVerdict('record.d < "2026-01-01"', fields)).toMatchObject({ kind: 'type', type: 'bool' }); + } + }); +});