Skip to content
15 changes: 15 additions & 0 deletions .changeset/38959-date-text-ordering-code.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'@objectstack/formula': patch
'@objectstack/lint': patch
---

fix(formula): a date ordered against a text field gets its own refusal code, `date-text-ordering`, with a sentence that says what the run does (#38959 item 4)

Clause-②: yes
Metadata-protocol: none

**What changed.** `validateExpression` keeps refusing a date or datetime field ordered (`<`, `<=`, `>`, `>=`) against a text counterpart that is not a literal — a text field read directly or through a ternary, or text computed by `+`, `upper(…)`, `string(…)` or `isoDate(…)` (the #32595 verdict, unchanged) — at the same grade at every site: an error where the site declares its fault outcome (a fail-closed rule, an advisory rule, a record-triggered flow, a time-relative sweep of the typed object), a warning elsewhere (a formula field, a flow condition with no declared outcome, an unproven bare name). Until now it was served under the `type-mismatch*` code of the site, whose sentence says the field is "used against a number" and that "the expression faults". Neither is true: the runtime holds a date field as its text, so the comparison evaluates as a text comparison and does not fault. It is now served under one new code in the closed `EXPRESSION_REFUSAL_CODES` set, `date-text-ordering`, with params `operands`, `operator` and, when the counterpart is a field read, `reference`. Its sentence says that the comparison is answered by spelling, not by date, and prescribes `date(…)` to compare dates or `string(…)` on the date side to compare text on purpose.

**The code move, for a consumer that matches the old code on this shape.** Where you matched `type-mismatch`, `type-mismatch-fail-closed`, `type-mismatch-fail-open`, `type-mismatch-run-fails`, `type-mismatch-sweep-run-fails` or `type-mismatch-run-may-fail` and the source orders a date field against text, the refusal now carries `date-text-ordering`; it arrives in `errors[]` or `warnings[]` exactly as the old one did. Add a catalogue row for `date-text-ordering`: its params carry no `held`. A real type mismatch (text or a boolean against a number, text against `today()`) keeps its `type-mismatch*` code. Where the same source also holds a date-text fault (`record.due_date > record.title && record.due_date - record.borrow_date > duration('1h')`), that fault's `date-text-arithmetic*` / `date-text-call*` error is the finding at every site, as it already was where the ordering was a warning; where the ordering was an error this moves the code from `type-mismatch*` to the date-text one, at the same grade.

**`@objectstack/lint`.** A time-relative flow that sweeps another object than the one its conditions are typed against still gets its note saying why a condition's verdict is a warning there, when that warning is `date-text-ordering`, as it did when the same verdict was served as `type-mismatch-run-may-fail`.
92 changes: 79 additions & 13 deletions packages/formula/src/cel-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1022,12 +1022,17 @@ const DATE_TEXT_COMPARISON_OPS: ReadonlySet<string> = new Set([...ORDERING_OPS,
* gate asks for it, so its answer is the one it gave before (see
* {@link firstTypeMismatch}'s `options`).
*/
function comparesDateTextAgainstUndeclared(source: string, env: Environment, macroElements = true): boolean {
function comparesDateTextAgainstUndeclared(
source: string,
env: Environment,
macroElements = true,
scope: 'record' | 'flattened' = 'record',
): KeptDateTextComparison | null {
let ast: unknown;
try {
ast = env.parse(rewriteNullableTernary(rewriteIndexedHas(source))).ast;
} catch {
return true;
return {};
}
/** The CEL type `node` checks to on its own, or `undefined` when it does not check. */
const typeOf = (node: unknown): string | undefined => {
Expand Down Expand Up @@ -1095,21 +1100,41 @@ function comparesDateTextAgainstUndeclared(source: string, env: Environment, mac
};
/** An element of the list `receiver` computes: `receiver[0]`. */
const elementOf = (receiver: unknown): CelNode => ({ op: '[]', args: [receiver, { op: 'value', args: 0n }] });
let found = false;
// [#38959 item 4] The comparison that keeps the verdict is reported, so the
// operator, operands and counterpart named are its own, never the Timestamp
// typing's first fault elsewhere in the source (`'Due: ' + record.due_date
// == 'x' && record.due_date < record.title` names `<`, not `+`).
let kept: KeptDateTextComparison | null = null;
/** A side's type as the Timestamp typing spells it: a date field's text is a Timestamp there. */
const spelled = (t: string | undefined): string =>
t === DATE_TEXT_CEL_TYPE ? 'google.protobuf.Timestamp' : t ?? 'dyn';
const visit = (v: unknown, bound: ReadonlyMap<string, CelNode>): void => {
if (found) return;
if (kept) return;
if (Array.isArray(v)) { for (const child of v) visit(child, bound); return; }
if (!isCelNode(v)) return;
if (DATE_TEXT_COMPARISON_OPS.has(v.op) && Array.isArray(v.args) && v.args.length === 2) {
// Without `macroElements` a macro variable proves nothing, as before #38959.
if (!macroElements && bound.size > 0 && readsBound(v.args, bound)) { found = true; return; }
if (!macroElements && bound.size > 0 && readsBound(v.args, bound)) { kept = { operator: v.op }; return; }
const [sa, sb] = (v.args as unknown[]).map((operand) => substitute(operand, bound));
const [a, b] = [sa.node, sb.node];
const [ta, tb] = [typeOf(a), typeOf(b)];
// A macro variable whose element does not check proves nothing: keep the verdict.
if ((sa.read && ta === undefined) || (sb.read && tb === undefined)) { found = true; return; }
if ((ta === DATE_TEXT_CEL_TYPE && !declared(b, tb)) || (tb === DATE_TEXT_CEL_TYPE && !declared(a, ta))) {
found = true;
if ((sa.read && ta === undefined) || (sb.read && tb === undefined)) {
kept = { operator: v.op, operands: `${spelled(ta)} ${v.op} ${spelled(tb)}` };
return;
}
const dateFirst = ta === DATE_TEXT_CEL_TYPE && !declared(b, tb);
if (dateFirst || (tb === DATE_TEXT_CEL_TYPE && !declared(a, ta))) {
const [other, otherType] = dateFirst ? [b, tb] : [a, ta];
// The counterpart is named only where it is a text field read; a
// computed text (`isoDate(today())`, `upper(…)`) or a macro's element
// is no reference to parse.
const read = otherType === 'string' ? typedFieldRef(other, scope) : null;
kept = {
operator: v.op,
operands: `${spelled(ta)} ${v.op} ${spelled(tb)}`,
...(read ? { counterpart: read.written } : {}),
};
return;
}
}
Expand All @@ -1125,7 +1150,21 @@ function comparesDateTextAgainstUndeclared(source: string, env: Environment, mac
visit(v.args, bound);
};
visit(ast, new Map());
return found;
return kept;
}

/**
* [#38959 item 4] The comparison {@link comparesDateTextAgainstUndeclared}
* found keeping the #32595 verdict, as written: its `operator`, its
* `operands` spelled as the Timestamp typing spells them, and `counterpart`,
* the text field read it orders the date against (`record.title`, `title`),
* present only where the counterpart is one. Every member is absent where no
* comparison is reported (an unparseable source keeps the verdict unnamed).
*/
interface KeptDateTextComparison {
readonly operator?: string;
readonly operands?: string;
readonly counterpart?: string;
}

/**
Expand Down Expand Up @@ -1431,6 +1470,25 @@ export function firstTypeMismatch(
*/
root?: 'record' | 'previous';
category: 'date-arith' | 'type-mismatch';
/**
* [#38959] Set when the `type-mismatch` is the ordering of a date field's
* text against a text counterpart no declared text names (#32595,
* {@link comparesDateTextAgainstUndeclared}): the verdict stands, but the
* run answers that comparison as a text comparison and does not fault, so
* `validate.ts` serves it under its own code (`date-text-ordering`), not a
* `type-mismatch*` sentence that says the expression faults.
*/
dateTextOrdering?: true;
/**
* [#38959 item 4] With `dateTextOrdering`, the comparison that keeps the
* verdict, as written — its operator, its operands and its text counterpart
* ({@link KeptDateTextComparison}). `operator`, `operands` and `field` above
* are the Timestamp typing's first fault, which a mixed source need not
* place on that comparison (`'Due: ' + record.due_date == 'x' &&
* record.due_date < record.title` faults first on `+`), and `field` keeps the
* grade it gives (#30025), so the sentence reads this instead.
*/
ordering?: KeptDateTextComparison;
} | null {
if (typeof source !== 'string' || !source.trim()) return null;
// An all-`dyn` record can never fault an overload — skip the parse entirely.
Expand Down Expand Up @@ -1481,17 +1539,22 @@ export function firstTypeMismatch(
* the mismatch kept is the ordering, not a fault the run meets.
*/
let keptOrdering = false;
let kept: KeptDateTextComparison | null = null;
const confirmAgainstDateText = (
m: RegExpExecArray,
recordRoots?: Readonly<Record<string, FieldCelType>>,
keepUndeclared = true,
): RegExpExecArray | null => {
keptOrdering = false;
kept = null;
if (!DATE_CEL_TYPES.has(m[1]) && !DATE_CEL_TYPES.has(m[3])) return m;
const dateTextEnv = buildTypedEnv(bareTypes, scope, 'date-text', recordRoots);
const r = unsoundOverload(dateTextEnv);
if (r && textOrBool(r)) return r[1] === DATE_TEXT_CEL_TYPE || r[3] === DATE_TEXT_CEL_TYPE ? m : r;
keptOrdering = keepUndeclared && comparesDateTextAgainstUndeclared(source, dateTextEnv, options.macroElements ?? true);
kept = keepUndeclared
? comparesDateTextAgainstUndeclared(source, dateTextEnv, options.macroElements ?? true, scope)
: null;
keptOrdering = kept !== null;
return keptOrdering ? m : null;
};
try {
Expand All @@ -1515,6 +1578,7 @@ export function firstTypeMismatch(
return {
operator, operands, celType, category: 'type-mismatch',
field: offendingField(source, bareTypes, celType, scope),
...(keptOrdering ? { dateTextOrdering: true as const, ordering: kept ?? {} } : {}),
};
}
// [#29959] A flattened condition reads the same field as `record.<field>`
Expand Down Expand Up @@ -1559,14 +1623,16 @@ export function firstTypeMismatch(
// Not for the kept ordering of a date against a text field, which the run
// answers: the name is what proves the read a record's under
// `bareNamesUnproven` (#30025), and an index read takes no part in that
// verdict (#32595, the question item 4 of #38959 leaves open), so only a
// member read is named there, as before #38959, and
// `record.due_date > record['title']` keeps the warning it had.
// verdict (#32595, which stands; item 4 of #38959 gave it its own code,
// `date-text-ordering`), so only a member read is named there, as before
// #38959, and `record.due_date > record['title']` keeps the warning grade
// it had.
const read = offendingRecordRead(source, fieldCelTypes, celType, !keptOrdering);
return {
operator: r[2], operands: `${r[1]} ${r[2]} ${r[3]}`, celType, category: 'type-mismatch',
field: read?.field ?? null,
...(read ? { root: read.root } : {}),
...(keptOrdering ? { dateTextOrdering: true as const, ordering: kept ?? {} } : {}),
};
} catch {
// A parse/other fault is the syntax checker's job (celEngine.compile); this
Expand Down
84 changes: 82 additions & 2 deletions packages/formula/src/expression-refusal-codes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -774,6 +774,84 @@ const PINS: { readonly [C in ExpressionRefusalCode]: readonly [Pin<C>, ...Pin<C>
'Compare a boolean with `true` / `false`, or use a number field.',
},
],
// [#38959 item 4] A date field ordered against a text counterpart (#32595):
// the run answers it as a text comparison, so one sentence at every site,
// graded by the site — the warning a formula field gives, the error a
// record-triggered flow gives — and a counterpart that is no field read
// names none.
'date-text-ordering': [
{
produce: () =>
onlyWarning('predicate', 'record.due > record.name', { scope: 'record', fieldTypes: { due: 'date', name: 'text' } }),
params: { operands: 'google.protobuf.Timestamp > string', operator: '>', reference: 'record.name' },
message:
'date ordered against text `google.protobuf.Timestamp > string` — `>` orders a date field against ' +
'`record.name`, which holds text. The runtime holds a date field as its text (`YYYY-MM-DD`; a datetime as ' +
'its ISO-8601 instant), so this comparison evaluates as a text comparison and does not fault: it answers ' +
'which text sorts first, character by character, not which date is later. To compare dates, parse the text ' +
'first with `date(record.name)`, which reads null where the text is not a date. To compare the texts on ' +
'purpose, write the date side as `string(…)`.',
},
{
produce: () =>
onlyError('predicate', 'name <= due', {
scope: 'flattened', fields: ['due', 'name'], fieldTypes: { due: 'date', name: 'text' }, faultOutcome: 'run-fails',
}),
params: { operands: 'string <= google.protobuf.Timestamp', operator: '<=', reference: 'name' },
message:
'date ordered against text `string <= google.protobuf.Timestamp` — `<=` orders a date field against ' +
'`name`, which holds text. The runtime holds a date field as its text (`YYYY-MM-DD`; a datetime as ' +
'its ISO-8601 instant), so this comparison evaluates as a text comparison and does not fault: it answers ' +
'which text sorts first, character by character, not which date is later. To compare dates, parse the text ' +
'first with `date(name)`, which reads null where the text is not a date. To compare the texts on ' +
'purpose, write the date side as `string(…)`.',
},
{
produce: () =>
onlyWarning('predicate', 'isoDate(today()) < due', { scope: 'flattened', fields: ['due'], fieldTypes: { due: 'date' } }),
params: { operands: 'string < google.protobuf.Timestamp', operator: '<' },
message:
'date ordered against text `string < google.protobuf.Timestamp` — `<` orders a date field against ' +
'a text value. The runtime holds a date field as its text (`YYYY-MM-DD`; a datetime as ' +
'its ISO-8601 instant), so this comparison evaluates as a text comparison and does not fault: it answers ' +
'which text sorts first, character by character, not which date is later. To compare dates, parse the text ' +
'first with `date(…)`, which reads null where the text is not a date. To compare the texts on ' +
'purpose, write the date side as `string(…)`.',
},
// [#38959 item 4, L2 S1] The params are the ordering's own in a mixed
// source: the Timestamp typing faults first on the concatenation (`+`),
// yet the operator, operands and counterpart named are the `<`'s.
{
produce: () =>
onlyWarning('predicate', "'Due: ' + record.due == 'x' && record.due < record.name", {
scope: 'record', fieldTypes: { due: 'date', name: 'text' },
}),
params: { operands: 'google.protobuf.Timestamp < string', operator: '<', reference: 'record.name' },
message:
'date ordered against text `google.protobuf.Timestamp < string` — `<` orders a date field against ' +
'`record.name`, which holds text. The runtime holds a date field as its text (`YYYY-MM-DD`; a datetime as ' +
'its ISO-8601 instant), so this comparison evaluates as a text comparison and does not fault: it answers ' +
'which text sorts first, character by character, not which date is later. To compare dates, parse the text ' +
'first with `date(record.name)`, which reads null where the text is not a date. To compare the texts on ' +
'purpose, write the date side as `string(…)`.',
},
// [L2 S1] A text field read elsewhere in the source is not the
// counterpart: `isoDate(today())` is computed text, so no reference.
{
produce: () =>
onlyError('predicate', "record.name == 'a' && record.due > isoDate(today())", {
scope: 'record', fieldTypes: { due: 'date', name: 'text' }, faultOutcome: 'fail-closed',
}),
params: { operands: 'google.protobuf.Timestamp > string', operator: '>' },
message:
'date ordered against text `google.protobuf.Timestamp > string` — `>` orders a date field against ' +
'a text value. The runtime holds a date field as its text (`YYYY-MM-DD`; a datetime as ' +
'its ISO-8601 instant), so this comparison evaluates as a text comparison and does not fault: it answers ' +
'which text sorts first, character by character, not which date is later. To compare dates, parse the text ' +
'first with `date(…)`, which reads null where the text is not a date. To compare the texts on ' +
'purpose, write the date side as `string(…)`.',
},
],
'field-near-miss': [
{
produce: () => onlyWarning('predicate', "stauts == 'x'", { fields: ['status'], objectName: 'deal' }),
Expand Down Expand Up @@ -1012,6 +1090,8 @@ const SWEEP_SOURCES: readonly string[] = [
"timestamp(record.close_date) + duration('24h')",
'isoDate(close_date) == "2026-01-01"',
'record.name > 5',
// [#38959 item 4] A date field ordered against a text field: `date-text-ordering`.
'record.close_date < record.name',
'record.active + 1 > 5',
"record.account == 'a1' && record.account.name == 'x'",
"record.account.owner.name == 'x'",
Expand Down Expand Up @@ -1153,8 +1233,8 @@ function refusalKey(said: ExprValidationError): string {
}

/**
* The validateExpression sweep's budget. The case is synchronous: 6,144
* validateExpression calls (3 roles x 128 inputs x 16 schemas), most of the
* The validateExpression sweep's budget. The case is synchronous: one
* validateExpression call per role x input x schema, most of the
* time in building a typed CEL environment for each call. Its work is the
* sweep's breadth, which is the claim, so the breadth stays; only re-judging
* duplicate refusals was cut (see the case). Readings of the case, in ms:
Expand Down
Loading
Loading