Skip to content

Commit 99ff16c

Browse files
committed
fix(formula): the type-soundness gate checks date subtraction against the text the runtime holds
A date or datetime field reaches the evaluator as its text, so subtracting two of them faults (the formula reads null) and a timestamp minus one computes a Duration, which a field serialises as {}. The gate declared the field a Timestamp and passed both. What that typing passes is now re-checked with the field declared as its text (DateText), refused as date-text-arithmetic or, for a formula value, date-duration-value. The + 1 shape keeps its existing words. Claude-Session: https://claude.ai/code/session_01FEkQ5nXr5BHHskLQ7qUH5x Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 135054e commit 99ff16c

6 files changed

Lines changed: 400 additions & 8 deletions

File tree

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

Lines changed: 123 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -965,7 +965,13 @@ const UNSOUND_OVERLOAD_RE = /no such overload:\s*([\w.]+)\s*(<=|>=|<|>|\+|-|\*|\
965965
function buildTypedEnv(
966966
fieldCelTypes: Readonly<Record<string, FieldCelType>>,
967967
scope: 'record' | 'flattened',
968+
temporalAsText = false,
968969
): Environment {
970+
// `temporalAsText` declares a `date`/`datetime` field as the text the runtime
971+
// holds ({@link DATE_TEXT_CEL_TYPE}) instead of a Timestamp — see
972+
// {@link firstDateTextVerdict}.
973+
const typeName = (t: FieldCelType): string =>
974+
temporalAsText && t === 'timestamp' ? DATE_TEXT_CEL_TYPE : celTypeName(t);
969975
if (scope === 'flattened') {
970976
const env = new Environment({
971977
unlistedVariablesAreDyn: true,
@@ -974,13 +980,14 @@ function buildTypedEnv(
974980
});
975981
registerStdLib(env, () => new Date(0));
976982
registerNullComparisons(env);
983+
if (temporalAsText) registerDateTextOverloads(env);
977984
for (const root of SCOPE_ROOTS) {
978985
try { env.registerVariable(root, 'map'); } catch { /* duplicate — ignore */ }
979986
}
980987
// Fields are bound bare at top level; a name that collides with a root
981988
// (unlikely) is skipped by the duplicate guard.
982989
for (const [name, t] of Object.entries(fieldCelTypes)) {
983-
try { env.registerVariable(name, celTypeName(t)); } catch { /* duplicate / reserved — ignore */ }
990+
try { env.registerVariable(name, typeName(t)); } catch { /* duplicate / reserved — ignore */ }
984991
}
985992
return env;
986993
}
@@ -991,8 +998,9 @@ function buildTypedEnv(
991998
});
992999
registerStdLib(env, () => new Date(0));
9931000
registerNullComparisons(env);
1001+
if (temporalAsText) registerDateTextOverloads(env);
9941002
const fields: Record<string, string> = {};
995-
for (const [name, t] of Object.entries(fieldCelTypes)) fields[name] = celTypeName(t);
1003+
for (const [name, t] of Object.entries(fieldCelTypes)) fields[name] = typeName(t);
9961004
try { env.registerType('OsRecordScope', { fields }); } catch { /* invalid field name — ignore */ }
9971005
// The record namespaces carry the typed struct; every other root stays a
9981006
// `map` (dyn members) so a reference through it never faults.
@@ -1051,7 +1059,10 @@ function offendingField(
10511059
* {@link UNSOUND_OVERLOAD_RE}), and concatenation (`"Due: " + date` → runtime
10521060
* string+string) are all runtime-tolerated, so they are never flagged. Two
10531061
* date fields (`date − date` → Duration, `date + date` → runtime string concat)
1054-
* also aren't flagged — only date/duration paired with a NUMBER.
1062+
* also aren't flagged HERE — only date/duration paired with a NUMBER. This
1063+
* typing declares a date field a Timestamp, which the runtime never holds;
1064+
* {@link firstDateTextVerdict} re-checks what this passes with the field
1065+
* declared as its text, and catches `date − date` there (#28944).
10551066
* - Equality (`==` / `!=`) is excluded ({@link UNSOUND_OVERLOAD_RE}): a
10561067
* heterogeneous equality is runtime-safe.
10571068
*
@@ -1111,6 +1122,115 @@ export function firstTypeMismatch(
11111122
}
11121123
}
11131124

1125+
/**
1126+
* The CEL type a `date` / `datetime` field is declared as by
1127+
* {@link firstDateTextVerdict}: what the runtime actually holds for it. Every
1128+
* read door hands a `Field.date` out as its `YYYY-MM-DD` text and a
1129+
* `Field.datetime` as its canonical ISO-8601 instant text (the SQL driver folds
1130+
* every dialect's storage to that text, ADR-0053 D-F1), so in an evaluated
1131+
* expression the operand is a string, never a Timestamp. A named type rather
1132+
* than plain `string` because the evaluator treats this text differently from a
1133+
* text field's: it coerces it to a date where the other operand is a Timestamp
1134+
* (`rewriteFaultedOperands`), which a text field's value never gets.
1135+
*/
1136+
const DATE_TEXT_CEL_TYPE = 'DateText';
1137+
1138+
/**
1139+
* Declare, for the check-only env, the overloads the evaluator ANSWERS on a
1140+
* date field's text — and only those, so every other operator on it faults the
1141+
* check exactly where it faults the evaluator (measured on cel-js 8.0.0 through
1142+
* `celEngine.evaluate` over `{ d: '2026-11-01', at: '2026-11-01T10:00:00.000Z' }`):
1143+
* - ordering against another date field or a text literal → string-lex, and
1144+
* against a Timestamp → the text operand is coerced to a date: `bool`;
1145+
* - equality against the same → `bool` (equality never faults);
1146+
* - a Timestamp minus the text, or the text minus a Timestamp → the text
1147+
* operand is coerced to a date, and the answer is a `Duration`;
1148+
* - `+` with text, or with another date field's text → string concatenation.
1149+
* NOT declared, because the evaluator faults on them and the field reads null:
1150+
* the text minus the text (`record.end_date - record.start_date`, either kind),
1151+
* the text with a number (`record.d + 1`), with a Duration
1152+
* (`record.d - duration('24h')`) and a Timestamp plus the text.
1153+
* Handlers are no-ops: this env is checked, never evaluated.
1154+
*/
1155+
function registerDateTextOverloads(env: Environment): void {
1156+
const T = DATE_TEXT_CEL_TYPE;
1157+
const TS = 'google.protobuf.Timestamp';
1158+
const declare = (signature: string): void => {
1159+
try { env.registerOperator(signature, () => null); } catch { /* already/invalid — ignore */ }
1160+
};
1161+
try { env.registerType(T, { fields: {} }); } catch { /* already registered — ignore */ }
1162+
for (const op of ['<', '<=', '>', '>=', '==']) {
1163+
for (const other of [T, TS, 'string']) {
1164+
declare(`${T} ${op} ${other}: bool`);
1165+
if (other !== T) declare(`${other} ${op} ${T}: bool`);
1166+
}
1167+
}
1168+
declare(`${T} == null: bool`);
1169+
declare(`null == ${T}: bool`);
1170+
declare(`${TS} - ${T}: google.protobuf.Duration`);
1171+
declare(`${T} - ${TS}: google.protobuf.Duration`);
1172+
declare(`${T} + ${T}: string`);
1173+
declare(`${T} + string: string`);
1174+
declare(`string + ${T}: string`);
1175+
}
1176+
1177+
/**
1178+
* A verdict of the date-text check ({@link firstDateTextVerdict}):
1179+
* - `fault` — arithmetic on a date field's text that the evaluator cannot
1180+
* answer, so the expression faults and the field reads null;
1181+
* - `type` — the expression checks clean, and `type` is the CEL type it
1182+
* computes (`google.protobuf.Duration` for `today() - record.start_date`).
1183+
*/
1184+
export type DateTextVerdict =
1185+
| { readonly kind: 'fault'; readonly operator: string; readonly operands: string; readonly field: string | null }
1186+
| { readonly kind: 'type'; readonly type: string; readonly field: string | null };
1187+
1188+
/**
1189+
* #28944 — type-check `source` with every `date`/`datetime` field declared as
1190+
* the text the runtime holds ({@link DATE_TEXT_CEL_TYPE}), not as the Timestamp
1191+
* {@link firstTypeMismatch} declares it.
1192+
*
1193+
* The Timestamp typing reads `record.end_date - record.start_date` as a legal
1194+
* `Duration`, so it is blind to the two shapes that cannot produce a value: the
1195+
* evaluator faults on the subtraction of two date texts (the field reads null),
1196+
* and `today() - record.start_date` evaluates to a `Duration`, which a field
1197+
* serialises as `{}`. Declared as what it is, the first faults this check
1198+
* exactly where it faults the evaluator, and the second's computed type is
1199+
* `Duration`; the caller words both. Nothing is matched in the source text.
1200+
*
1201+
* It answers only what the Timestamp typing passes: the caller asks
1202+
* {@link firstTypeMismatch} first, so a shape that check already refuses (the
1203+
* `… + 1` of `(record.end_date - record.start_date) + 1`) keeps its words.
1204+
*
1205+
* Returns `null` when the source does not parse, or the check faults on
1206+
* anything other than arithmetic with a date field's text — that is another
1207+
* check's to report, and this one never guesses.
1208+
*/
1209+
export function firstDateTextVerdict(
1210+
source: string,
1211+
fieldCelTypes: Readonly<Record<string, FieldCelType>>,
1212+
scope: 'record' | 'flattened' = 'record',
1213+
): DateTextVerdict | null {
1214+
if (typeof source !== 'string' || !source.trim()) return null;
1215+
try {
1216+
const env = buildTypedEnv(fieldCelTypes, scope, true);
1217+
const result = env.parse(rewriteNullableTernary(rewriteIndexedHas(source))).check?.() as
1218+
| { valid?: boolean; type?: unknown; error?: { message?: string } }
1219+
| undefined;
1220+
if (!result) return null;
1221+
const field = offendingField(source, fieldCelTypes, 'timestamp', scope);
1222+
if (result.valid !== false) {
1223+
return typeof result.type === 'string' ? { kind: 'type', type: result.type, field } : null;
1224+
}
1225+
const m = UNSOUND_OVERLOAD_RE.exec(result.error?.message ?? '');
1226+
if (!m || !ARITH_OPS.has(m[2]) || (m[1] !== DATE_TEXT_CEL_TYPE && m[3] !== DATE_TEXT_CEL_TYPE)) return null;
1227+
return { kind: 'fault', operator: m[2], operands: `${m[1]} ${m[2]} ${m[3]}`, field };
1228+
} catch {
1229+
// A parse/other fault is the syntax checker's job (celEngine.compile).
1230+
return null;
1231+
}
1232+
}
1233+
11141234
/** cel-js temporal functions that return a calendar Timestamp (for #3183). */
11151235
const TEMPORAL_FNS = new Set(['today', 'daysFromNow', 'daysAgo', 'now']);
11161236

‎packages/formula/src/expression-refusal-codes.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,53 @@ const PINS: { readonly [C in ExpressionRefusalCode]: readonly [Pin<C>, ...Pin<C>
305305
'in whole days, and `daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` to shift a date.',
306306
},
307307
],
308+
'date-text-arithmetic': [
309+
{
310+
produce: () =>
311+
onlyError('value', 'record.end_date - record.start_date', {
312+
scope: 'record',
313+
fieldTypes: { start_date: 'date', end_date: 'date' },
314+
}),
315+
params: { operands: 'DateText - DateText', reference: 'record.start_date' },
316+
message:
317+
'date arithmetic `DateText - DateText` — `record.start_date` is a date field, and the runtime holds a date field ' +
318+
'as its text (`YYYY-MM-DD`, or an ISO-8601 instant for a date-time), which CEL can\'t do arithmetic on: this ' +
319+
'faults at runtime, so the field silently evaluates to null. Use `daysBetween(a, b)` for the span in whole days, ' +
320+
'and `daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` to shift a date.',
321+
},
322+
{
323+
produce: () =>
324+
onlyError('predicate', 'end_at - start_at > duration("1h")', {
325+
fields: ['start_at', 'end_at'],
326+
fieldTypes: { start_at: 'datetime', end_at: 'datetime' },
327+
}),
328+
params: { operands: 'DateText - DateText', reference: 'start_at' },
329+
message:
330+
'date arithmetic `DateText - DateText` — `start_at` is a date field, and the runtime holds a date field ' +
331+
'as its text (`YYYY-MM-DD`, or an ISO-8601 instant for a date-time), which CEL can\'t do arithmetic on: this ' +
332+
'faults at runtime, so the field silently evaluates to null. Use `daysBetween(a, b)` for the span in whole days, ' +
333+
'and `daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` to shift a date.',
334+
},
335+
],
336+
'date-duration-value': [
337+
{
338+
produce: () =>
339+
onlyError('value', 'today() - record.start_date', { scope: 'record', fieldTypes: { start_date: 'date' } }),
340+
params: { reference: 'record.start_date' },
341+
message:
342+
'date arithmetic — this computes a `google.protobuf.Duration` from `record.start_date`, and a field can\'t hold ' +
343+
'a duration: it reads `{}` at runtime. Use `daysBetween(a, b)` for the span in whole days, and ' +
344+
'`daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` to shift a date.',
345+
},
346+
{
347+
produce: () => onlyError('value', 'today() - daysAgo(3)', { scope: 'record', fieldTypes: { name: 'text' } }),
348+
params: {},
349+
message:
350+
'date arithmetic — this computes a `google.protobuf.Duration`, and a field can\'t hold ' +
351+
'a duration: it reads `{}` at runtime. Use `daysBetween(a, b)` for the span in whole days, and ' +
352+
'`daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` to shift a date.',
353+
},
354+
],
308355
'type-mismatch': [
309356
{
310357
produce: () => onlyWarning('predicate', 'record.name > 5', { scope: 'record', fieldTypes: { name: 'text' } }),
@@ -460,6 +507,8 @@ const SWEEP_SOURCES: readonly string[] = [
460507
"current_user.positions.contains('zzz')",
461508
'record.close_date + 1',
462509
'close_date + 1 > 3',
510+
'record.close_date - record.close_date',
511+
'today() - record.close_date',
463512
'record.name > 5',
464513
'record.active + 1 > 5',
465514
"record.account == 'a1' && record.account.name == 'x'",

‎packages/formula/src/expression-refusal.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,19 @@ export interface ExpressionRefusalParams {
155155
* operand types; `reference` is the field as written, when it is known.
156156
*/
157157
'date-arithmetic': { readonly operands: string; readonly reference?: string };
158+
/**
159+
* Arithmetic on a date field's runtime TEXT that the evaluator cannot answer
160+
* (`record.end_date - record.start_date`), judged with the field declared as
161+
* that text. `operands` are the CEL operand types (the text is `DateText`);
162+
* `reference` is the field as written, when it is known.
163+
*/
164+
'date-text-arithmetic': { readonly operands: string; readonly reference?: string };
165+
/**
166+
* A formula that computes a `google.protobuf.Duration`
167+
* (`today() - record.start_date`), which a field reads as `{}`. `reference`
168+
* is the date field it is computed from, when the expression names one.
169+
*/
170+
'date-duration-value': { readonly reference?: string };
158171
/**
159172
* WARNING, never an error: a text or boolean field used with an arithmetic
160173
* or ordering `operator` against a number.
@@ -224,6 +237,8 @@ const CODE_TABLE = {
224237
'unbound-root': true,
225238
'bare-reference': true,
226239
'date-arithmetic': true,
240+
'date-text-arithmetic': true,
241+
'date-duration-value': true,
227242
'type-mismatch': true,
228243
'field-near-miss': true,
229244
'traversal-bare-and-traversed': true,

0 commit comments

Comments
 (0)