Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/34756-field-reorder-dogfood-timeout.md
Original file line number Diff line number Diff line change
@@ -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.
52 changes: 51 additions & 1 deletion packages/formula/src/cel-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1088,7 +1088,9 @@ const MACRO_NAMES: ReadonlySet<string> = 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<Record<string, FieldCelType>>,
Expand All @@ -1102,6 +1104,54 @@ function buildTypedEnv(
* reads the field.
*/
recordRootTypes?: Readonly<Record<string, FieldCelType>>,
): 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<string, Environment>();
const TYPED_ENV_CACHE_LIMIT = 512;

/** {@link buildTypedEnv}'s uncached body: a fresh env for these inputs. */
function createTypedEnv(
fieldCelTypes: Readonly<Record<string, FieldCelType>>,
scope: 'record' | 'flattened',
temporal: TemporalTyping,
recordRootTypes: Readonly<Record<string, FieldCelType>> | undefined,
): Environment {
// `temporal` picks what a `date`/`datetime` field is declared as — see
// {@link TemporalTyping}.
Expand Down
58 changes: 58 additions & 0 deletions packages/formula/src/cel-env-reuse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' });
}
});
});
Loading