diff --git a/.changeset/38959-date-text-ordering-code.md b/.changeset/38959-date-text-ordering-code.md new file mode 100644 index 00000000000..082a1574d5e --- /dev/null +++ b/.changeset/38959-date-text-ordering-code.md @@ -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`. diff --git a/packages/formula/src/cel-engine.ts b/packages/formula/src/cel-engine.ts index 5d7e1f17546..b5abcb5dd03 100644 --- a/packages/formula/src/cel-engine.ts +++ b/packages/formula/src/cel-engine.ts @@ -1022,12 +1022,17 @@ const DATE_TEXT_COMPARISON_OPS: ReadonlySet = 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 => { @@ -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): 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; } } @@ -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; } /** @@ -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. @@ -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>, 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 { @@ -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.` @@ -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 diff --git a/packages/formula/src/expression-refusal-codes.test.ts b/packages/formula/src/expression-refusal-codes.test.ts index a89f611ebae..bdd791d8354 100644 --- a/packages/formula/src/expression-refusal-codes.test.ts +++ b/packages/formula/src/expression-refusal-codes.test.ts @@ -774,6 +774,84 @@ const PINS: { readonly [C in ExpressionRefusalCode]: readonly [Pin, ...Pin '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' }), @@ -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'", @@ -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: diff --git a/packages/formula/src/expression-refusal.ts b/packages/formula/src/expression-refusal.ts index e303e141c39..edaf7bcc9ff 100644 --- a/packages/formula/src/expression-refusal.ts +++ b/packages/formula/src/expression-refusal.ts @@ -309,6 +309,34 @@ export interface ExpressionRefusalParams { * under the name is not proven to be the field's value there. */ 'type-mismatch-run-may-fail': TypeMismatchParams; + /** + * [#38959] A date field ordered (`<` `<=` `>` `>=`) against a text + * counterpart no declared text names — a text field read directly or + * through a ternary, or text computed by `+`, `upper(…)`, `string(…)`, + * `isoDate(…)` (#32595, which keeps the verdict). The runtime holds the date + * field as its text, so the comparison evaluates as a text comparison and + * does not fault: it answers by spelling, not by date. One sentence at every + * site, so one code with no outcome suffix (no fault, so no outcome to name), + * graded by the site as the `type-mismatch` verdict there is: a WARNING at a + * formula field, a flow condition with no declared outcome or an unproven + * bare name, and an ERROR at a site that declares its fault outcome (a + * fail-closed site, an advisory rule, a record-triggered flow, a sweep of + * its object). Every param is that comparison's own, wherever else the + * source faults the Timestamp typing first (`'Due: ' + record.due_date == + * 'x' && record.due_date < record.title` names `<`): `operator` is its + * operator — an ordering, or the `==` / `!=` the #32595 walk keeps where a + * date field is equated with such a counterpart beside a fault the Timestamp + * typing meets (`'Due: ' + record.due_date == 'x' && record.due_date == + * record.title`); `operands` are its operand types as the + * Timestamp typing spells them (`google.protobuf.Timestamp > string`); and + * `reference` is its text counterpart as written, present only where that + * counterpart is a text field read (`record.title`, an index read by its + * member spelling, a bare `title` in a flow condition) — absent for computed + * text (`isoDate(today())`), whatever other text field the source reads. + * Served under the `type-mismatch*` codes until this code gave the sentence + * its own name. + */ + 'date-text-ordering': { readonly operands: string; readonly operator: string; readonly reference?: string }; /** * WARNING, never an error: a bare identifier in a flattened condition that * is one typo away from a field. Absent `objectName` reads "the trigger object". @@ -412,6 +440,7 @@ const CODE_TABLE = { 'type-mismatch-sweep-run-fails': true, 'type-mismatch-fail-open': true, 'type-mismatch-run-may-fail': true, + 'date-text-ordering': true, 'field-near-miss': true, 'traversal-bare-and-traversed': true, 'traversal-multi-hop': true, diff --git a/packages/formula/src/validate-date-text-arithmetic.test.ts b/packages/formula/src/validate-date-text-arithmetic.test.ts index 523798aa622..6fb83f8e0c6 100644 --- a/packages/formula/src/validate-date-text-arithmetic.test.ts +++ b/packages/formula/src/validate-date-text-arithmetic.test.ts @@ -245,21 +245,24 @@ describe('a date field\'s text handed to a call, concatenated or ordered against ['value', 'string(record.start_time)', undefined, [], '2026-11-16T01:00:00.000Z'], ['value', 'daysBetween(record.start_day, record.end_day)', undefined, [], 4], ['value', 'isoDate(today())', undefined, [], evaluated('isoDate(today())')], - // Kept as they were: a real fault, and a date field ordered against a text + // A real fault keeps its code: text ordered against a Timestamp. + ['predicate', 'record.title < today()', 'fail-closed', ['type-mismatch-fail-closed'], 'fault'], + // Kept refused, at the same grade: a date field ordered against a text // counterpart that is not a literal, which no declared text names — a text // field read directly or through a ternary, or text computed by `+`, - // `upper`, `string` or `isoDate` (the evaluator compares them string-lex). - ['predicate', 'record.title < today()', 'fail-closed', ['type-mismatch-fail-closed'], 'fault'], - ['predicate', 'record.title < record.start_time', 'fail-closed', ['type-mismatch-fail-closed'], false], - ['predicate', 'record.start_day < (record.flag ? record.title : record.other)', 'fail-closed', ['type-mismatch-fail-closed'], true], - ['predicate', '(record.flag ? record.start_day : record.end_day) < record.title', 'fail-closed', ['type-mismatch-fail-closed'], true], - ['predicate', "record.start_day < record.title + 'x'", 'fail-closed', ['type-mismatch-fail-closed'], true], - ['predicate', 'record.start_day < upper(record.title)', 'fail-closed', ['type-mismatch-fail-closed'], true], - ['predicate', 'record.start_day < string(record.amount)', 'fail-closed', ['type-mismatch-fail-closed'], true], + // `upper`, `string` or `isoDate`. The evaluator compares them string-lex + // and does not fault, so the verdict is served under its own code + // (#38959 item 4), never a `type-mismatch*` sentence that says it faults. + ['predicate', 'record.title < record.start_time', 'fail-closed', ['date-text-ordering'], false], + ['predicate', 'record.start_day < (record.flag ? record.title : record.other)', 'fail-closed', ['date-text-ordering'], true], + ['predicate', '(record.flag ? record.start_day : record.end_day) < record.title', 'fail-closed', ['date-text-ordering'], true], + ['predicate', "record.start_day < record.title + 'x'", 'fail-closed', ['date-text-ordering'], true], + ['predicate', 'record.start_day < upper(record.title)', 'fail-closed', ['date-text-ordering'], true], + ['predicate', 'record.start_day < string(record.amount)', 'fail-closed', ['date-text-ordering'], true], // '2026-11-16' against today() on the fixed clock, '2026-11-12': string-lex, false. - ['predicate', 'record.start_day < isoDate(today())', 'fail-closed', ['type-mismatch-fail-closed'], false], - // A macro-bound variable proves nothing on its own: the comparison keeps its verdict. - ['predicate', '[record.title].exists(x, record.start_day < x)', 'fail-closed', ['type-mismatch-fail-closed'], true], + ['predicate', 'record.start_day < isoDate(today())', 'fail-closed', ['date-text-ordering'], false], + // A macro variable is typed as an element of its list (#38959): a text, so the ordering keeps its verdict. + ['predicate', '[record.title].exists(x, record.start_day < x)', 'fail-closed', ['date-text-ordering'], true], ]; for (const [role, source, outcome, codes, reads] of ROWS) { @@ -346,10 +349,10 @@ describe('a date field\'s text handed to a call, concatenated or ordered against error: { message: expect.stringContaining("no matching overload for 'isoDate(string)'") }, }); expect(validateExpression('predicate', '"Due: " + start_time != ""', flattened).warnings).toEqual([]); - // A macro-bound variable is `dyn` here: it still proves nothing, so the comparison keeps its verdict. + // A macro variable ranging over a text field is a text: the ordering keeps its verdict and its warning grade. const withTitle: ExprSchemaHint = { fields: ['title', 'start_time'], fieldTypes: { title: 'text', start_time: 'datetime' } }; expect(validateExpression('predicate', '[title].exists(x, start_time < x)', withTitle).warnings.map((e) => e.code)) - .toEqual(['type-mismatch-run-may-fail']); + .toEqual(['date-text-ordering']); }); it('without field types the check does not run, as before', () => { @@ -996,8 +999,8 @@ describe('flow-condition verdicts agree with the run: severity, the index spelli expect(graded('[due_date].exists(d, d > title)')).toEqual(graded('due_date > title')); // The inner `map` rebinds `d`: its body reads `[title]`'s element, never the outer date. expect(graded('[due_date].exists(d, d > [title].map(d, d)[0])')).toEqual(graded('due_date > title')); - expect(graded('[due_date].exists(d, d > [title].map(d, d)[0])')).toEqual(['error:type-mismatch-run-fails']); - expect(graded('[due_date].exists(d, d > title)')).toEqual(['error:type-mismatch-run-fails']); + expect(graded('[due_date].exists(d, d > [title].map(d, d)[0])')).toEqual(['error:date-text-ordering']); + expect(graded('[due_date].exists(d, d > title)')).toEqual(['error:date-text-ordering']); }); it('an inner macro rebinding the name reads its own list: a date ordered against a date is not refused', () => { @@ -1044,11 +1047,13 @@ describe('flow-condition verdicts agree with the run: severity, the index spelli } }); - // [#38959, review S3] The ordering of a date against a text field keeps the - // mismatch (#32595) although the run answers it; under `bareNamesUnproven` a + // [#38959, review S3] The ordering of a date against a text field keeps its + // verdict (#32595) although the run answers it; under `bareNamesUnproven` a // named `record.FIELD` read is what makes that an error (#30025). An index // read takes no part in that verdict, so it supplies no name there, and each - // source keeps the warning it had (item 4 of #38959 leaves the verdict open). + // source keeps the warning grade it had. Item 4 of #38959 was ruled (option + // A): the verdict stands and is served under its own code, + // `date-text-ordering`, whose sentence says the run answers it. it('an index read does not name a kept date-against-text ordering: the warning stays under bareNamesUnproven', () => { const types = { ...fieldTypes, notes: 'text' }; const unproven: ExprSchemaHint = { fields: Object.keys(types), fieldTypes: types, faultOutcome: 'run-fails', bareNamesUnproven: true }; @@ -1058,12 +1063,12 @@ describe('flow-condition verdicts agree with the run: severity, the index spelli "record['due_date'] > record['title'] && record.status == 'open'", "record.due_date > title && record['notes'] == 'n'", ]) { - expect(graded(source, unproven), source).toEqual(['warning:type-mismatch-run-may-fail']); + expect(graded(source, unproven), source).toEqual(['warning:date-text-ordering']); // The run answers it: a date's text ordered against a text. expect(celEngine.evaluate({ dialect: 'cel', source }, { extra: { ...row, record: row, previous: row } }).ok, source).toBe(true); } // CONTROL: the member spelling names the text read and keeps its standing error. - expect(graded('record.due_date > record.title', unproven)).toEqual(['error:type-mismatch-run-fails']); + expect(graded('record.due_date > record.title', unproven)).toEqual(['error:date-text-ordering']); }); // [#38959, review M1] A flow value envelope's date-text check stands down @@ -1087,3 +1092,114 @@ describe('flow-condition verdicts agree with the run: severity, the index spelli expect(check("[record.due_date].exists(d, d > '2026-01-01')")).toEqual({ ok: true, errors: [], warnings: [] }); }); }); + +/** + * [#38959 item 4, ruling option A] A date field ordered against a text + * counterpart no declared text names keeps its verdict (#32595) at the grade + * every site gave it, under its own code, `date-text-ordering`: the run holds + * the date field as its text and answers the comparison as a text comparison, + * so the sentence says that, never the `type-mismatch*` sentence that the + * expression faults. A real type mismatch keeps its code. + */ +describe('a date ordered against a text field is served under its own code, with a true sentence (#38959 item 4)', () => { + const fieldTypes = { title: 'text', notes: 'text', due_date: 'date', borrow_date: 'date', picked_up_at: 'datetime' }; + const fields = Object.keys(fieldTypes); + const ROW = { title: 'Dune', notes: 'n', due_date: '2026-11-30', borrow_date: '2026-11-16', picked_up_at: '2026-11-16T09:30:00.000Z' }; + const run = (source: string) => celEngine.evaluate({ dialect: 'cel', source }, { extra: { ...ROW, record: ROW, previous: ROW } }); + /** Every site the verdict is given at, with the grade the `type-mismatch*` code there carried for it. */ + const SITES: ReadonlyArray = [ + ['a formula field', { scope: 'record', fields, fieldTypes }, 'warning'], + ['a fail-closed rule', { scope: 'record', fields, fieldTypes, faultOutcome: 'fail-closed' }, 'error'], + ['an advisory rule', { scope: 'record', fields, fieldTypes, faultOutcome: 'fail-open' }, 'error'], + ['a record-triggered flow', { fields, fieldTypes, faultOutcome: 'run-fails' }, 'error'], + ['a sweep of the object', { fields, fieldTypes, faultOutcome: 'run-fails', timeRelativeSweep: true }, 'error'], + ['a flow with no declared outcome', { fields, fieldTypes }, 'warning'], + ['a flow whose bare names are unproven', { fields, fieldTypes, faultOutcome: 'run-fails', bareNamesUnproven: true }, 'error'], + ]; + /** Every code the check answers, errors first, each marked with its grade. */ + const graded = (source: string, hint: ExprSchemaHint) => { + const r = validateExpression('predicate', source, hint); + return [...r.errors.map((e) => `error:${e.code}`), ...r.warnings.map((e) => `warning:${e.code}`)]; + }; + const only = (source: string, hint: ExprSchemaHint): ExprValidationError => { + const r = validateExpression('predicate', source, hint); + const all = [...r.errors, ...r.warnings]; + expect(all, source).toHaveLength(1); + return all[0]; + }; + + for (const [source, reversed] of [ + ['record.due_date > record.title', 'record.title < record.due_date'], + ['record.picked_up_at >= record.title', 'record.title <= record.picked_up_at'], + ] as const) { + it.each(SITES)(`\`${source}\` and \`${reversed}\` at %s: date-text-ordering, at the grade the site gave it`, (_site, hint, grade) => { + for (const s of [source, reversed]) expect(graded(s, hint), s).toEqual([`${grade}:date-text-ordering`]); + }); + + it(`\`${source}\` and \`${reversed}\`: the sentence says what the run does, and the run does it`, () => { + for (const s of [source, reversed]) { + const e = only(s, SITES[3][1]); + expect(e.code).toBe('date-text-ordering'); + expect(e.params).toMatchObject({ reference: 'record.title' }); + expect(e.message).toMatch(/^date ordered against text `[^`]+` — `[<>]=?` orders a date field against `record\.title`, which holds text\. /); + expect(e.message).toContain('so this comparison evaluates as a text comparison and does not fault'); + expect(e.message).not.toMatch(/the expression faults|fails the run|evaluates to null/); + // The run answers it: it does not fault. + expect(run(s), s).toEqual({ ok: true, value: expect.any(Boolean) }); + } + }); + } + + it('the text comparison is the answer: a date text sorts against the text by spelling', () => { + // '2026-11-30' > 'Dune' is false by character ('2' sorts before 'D'), whatever the dates. + expect(run('record.due_date > record.title')).toEqual({ ok: true, value: false }); + expect(run('record.title < record.due_date')).toEqual({ ok: true, value: false }); + // Only where the text happens to spell a date does that text order agree with the date order. + expect(run("record.due_date > record.notes")).toEqual({ ok: true, value: false }); + expect(celEngine.evaluate({ dialect: 'cel', source: 'record.due_date > record.notes' }, { extra: { record: { ...ROW, notes: '2026-11-01' } } })) + .toEqual({ ok: true, value: true }); + // Both prescriptions check clean at every site and evaluate: the parse compares dates, `string(…)` the texts. + for (const [, hint] of SITES) { + expect(validateExpression('predicate', 'record.due_date > date(record.title)', hint)).toEqual({ ok: true, errors: [], warnings: [] }); + expect(validateExpression('predicate', 'string(record.due_date) > record.title', hint)).toEqual({ ok: true, errors: [], warnings: [] }); + } + expect(run('record.due_date > date(record.title)')).toEqual({ ok: true, value: false }); + expect(celEngine.evaluate({ dialect: 'cel', source: 'record.due_date > date(record.notes)' }, { extra: { record: { ...ROW, notes: '2026-11-01' } } })) + .toEqual({ ok: true, value: true }); + expect(run('string(record.due_date) > record.title')).toEqual({ ok: true, value: false }); + }); + + it.each(SITES)('CONTROL at %s: a real type mismatch keeps its type-mismatch code, and faults', (_site, hint) => { + for (const source of ['record.title > 5', 'record.title < today()']) { + const [got] = graded(source, hint); + expect(got, source).toMatch(/^(?:error|warning):type-mismatch(?:-|$)/); + expect(run(source).ok, source).toBe(false); + } + }); + + it.each(SITES)('at %s the params and sentence are the ordering\'s own in a mixed source (L2 S1)', (_site, hint, grade) => { + // The Timestamp typing faults first on the concatenation (`+`); the ordering is the `<`. + const concat = "'Due: ' + record.due_date == 'x' && record.due_date < record.title"; + expect(graded(concat, hint), concat).toEqual([`${grade}:date-text-ordering`]); + const a = only(concat, hint); + expect(a.params).toEqual({ operands: 'google.protobuf.Timestamp < string', operator: '<', reference: 'record.title' }); + expect(a.message).toMatch(/^date ordered against text `google\.protobuf\.Timestamp < string` — `<` orders a date field against `record\.title`, /); + expect(a.message).toContain('`date(record.title)`'); + // A text field read elsewhere is not the counterpart: `isoDate(today())` is. + const computed = "record.title == 'a' && record.due_date > isoDate(today())"; + expect(graded(computed, hint), computed).toEqual([`${grade}:date-text-ordering`]); + const b = only(computed, hint); + expect(b.params).toEqual({ operands: 'google.protobuf.Timestamp > string', operator: '>' }); + expect(b.message).toContain('`>` orders a date field against a text value.'); + expect(b.message).not.toContain('record.title'); + for (const s of [concat, computed]) expect(run(s), s).toEqual({ ok: true, value: expect.any(Boolean) }); + }); + + it.each(SITES)('at %s a date-text fault in the same source is the finding, never the ordering sentence', (_site, hint) => { + const source = "record.due_date > record.title && record.due_date - record.borrow_date > duration('1h')"; + const [got] = graded(source, hint); + expect(got, source).toMatch(/^error:date-text-arithmetic(?:-|$)/); + // The subtraction faults wherever the ordering holds. + expect(celEngine.evaluate({ dialect: 'cel', source }, { extra: { record: { ...ROW, title: '0' } } }).ok).toBe(false); + }); +}); diff --git a/packages/formula/src/validate.ts b/packages/formula/src/validate.ts index f041cd175e2..94044f90486 100644 --- a/packages/formula/src/validate.ts +++ b/packages/formula/src/validate.ts @@ -551,6 +551,10 @@ const DATE_FAIL_CLOSED_CLAUSE = * worded for the failed run a fault there is (#29959); a flattened * condition's `record.` / `previous.` read is judged as its * bare name is. + * - `date-text-ordering` (#38959 item 4): the one `type-mismatch` the run + * does not fault on — a date field ordered against a text counterpart no + * declared text names (#32595). Graded as the `type-mismatch` verdict at + * the same site is, under one code whose sentence says what the run does. * - `date-text-arithmetic` / `date-duration-value` (**error**, #28944): what * the Timestamp typing passes, re-checked with a date field declared as the * text the runtime holds — see {@link dateTextIssue}; in a flow condition @@ -626,8 +630,15 @@ function typeSoundnessIssue( * asked first there too, and every verdict it gave before keeps its code. */ const indexReadOnly = mismatch.root !== undefined && !RECORD_ROOT_READ_RE.test(source); - const dateTextOver = (verdict: T) => { - if (verdict.severity !== 'warning' && !indexReadOnly) return verdict; + // `always`: asked whatever the grade — the `date-text-ordering` verdict says + // its comparison does not fault, so a date-text fault in the same source + // (`record.due_date > record.title && record.due_date - record.borrow_date > + // duration('1h')`) is the finding, never that sentence. + const dateTextOver = ( + verdict: T, + always = false, + ) => { + if (verdict.severity !== 'warning' && !indexReadOnly && !always) return verdict; const datesOnly = Object.fromEntries( Object.entries(celFieldTypes).map(([name, t]): [string, FieldCelType] => [name, t === 'timestamp' ? t : 'dyn']), ); @@ -666,6 +677,39 @@ function typeSoundnessIssue( ), }; } + if (mismatch.dateTextOrdering) { + // [#38959 item 4] The date-against-text ordering (#32595) keeps its verdict + // and its grade — an error where the site declares its fault outcome, a + // warning where the `type-mismatch` verdict there is one — but not the + // `type-mismatch*` sentence, which says the expression faults: the run + // holds the date field as its text and answers the comparison as a text + // comparison. One sentence at every site, so one code. + // Its params and sentence are the kept comparison's own, never the + // Timestamp typing's first fault: in a mixed source that may sit elsewhere + // (`'Due: ' + record.due_date == 'x' && record.due_date < record.title` + // faults first on `+`), and the field it names need not be the counterpart + // (`record.title == 'a' && record.due_date > isoDate(today())`). + const kept = mismatch.ordering ?? {}; + const operator = kept.operator ?? mismatch.operator; + const operands = kept.operands ?? mismatch.operands; + const counterpartRef = kept.counterpart; + const counterpart = counterpartRef !== undefined ? `\`${counterpartRef}\`, which holds text` : 'a text value'; + const parse = counterpartRef !== undefined ? `\`date(${counterpartRef})\`` : '`date(…)`'; + return dateTextOver({ + severity: outcome !== undefined ? 'error' : 'warning', + issue: refusal( + 'date-text-ordering', + { operands, operator, ...(counterpartRef !== undefined ? { reference: counterpartRef } : {}) }, + source, + `date ordered against text \`${operands}\` — \`${operator}\` orders a date field against ` + + `${counterpart}. 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 ${parse}, which reads null where the text is not a date. To compare the texts on purpose, write the ` + + `date side as \`string(…)\`.`, + ), + }, true); + } const heldKind: 'boolean' | 'text' = mismatch.celType === 'bool' ? 'boolean' : 'text'; const held = heldKind === 'boolean' ? 'a boolean' : 'text'; const subject = ref ? `${ref} holds ${held}` : `${held === 'a boolean' ? 'a boolean' : 'a text'} field`; diff --git a/packages/lint/src/validate-expressions.mismatch-precedence-38959.test.ts b/packages/lint/src/validate-expressions.mismatch-precedence-38959.test.ts index 5dfe0819d1f..7e151517985 100644 --- a/packages/lint/src/validate-expressions.mismatch-precedence-38959.test.ts +++ b/packages/lint/src/validate-expressions.mismatch-precedence-38959.test.ts @@ -81,3 +81,61 @@ describe('publish lint: a date-text refusal is not stood down by a mismatch warn expect(found[0]).toMatch(/^warning: /); }); }); + +/** + * [#38959 item 4, ruling option A] At the publish lint, a date field ordered + * against a text field keeps the grade every flow gave it — an error on a + * record-triggered flow and on a sweep of the typed object, a warning on a + * sweep of another object — under its own sentence: the comparison evaluates + * as a text comparison and does not fault. Where it is the warning a sweep of + * another object softens, the flow still gets the note saying why, as it did + * when the verdict spoke the `type-mismatch-run-may-fail` sentence. + */ +describe('publish lint: a date ordered against a text field keeps its grade under its own sentence (#38959 item 4)', () => { + const ORDERING = 'due_date > title'; + const reminder = { name: 'library_reminder', label: 'Library reminder', fields: { remind_on: { type: 'date', label: 'Remind on' } } }; + const flow = (name: string, start: Record) => ({ + name, + label: name, + type: start.timeRelative ? 'schedule' : 'autolaunched', + status: 'active', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: 'library_loan', condition: ORDERING, ...start } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'end' }], + }); + const stackOf = (f: Record) => ({ objects: [loan(), reminder], flows: [f] }); + const ordering = (name: string, f: Record) => + findingsAt(stackOf(f), `flow '${name}'`).filter((m) => /^(?:error|warning): (?:date ordered against text|type mismatch) `/.test(m)); + + it('a record-triggered flow: still refused, under the sentence that the comparison does not fault', () => { + expect(ordering('on_change', flow('on_change', { triggerType: 'record-after-update' }))).toEqual([ + 'error: date ordered against text `google.protobuf.Timestamp > string`', + ]); + const [issue] = validateStackExpressions(specValid(stackOf(flow('on_change', { triggerType: 'record-after-update' })))) + .filter((i) => i.where.includes("flow 'on_change'")); + expect(issue.message).toContain('so this comparison evaluates as a text comparison and does not fault'); + expect(issue.message).not.toMatch(/the expression faults|fails the run/); + }); + + it('a sweep of the typed object: still refused', () => { + const f = flow('sweep_same', { timeRelative: { object: 'library_loan', dateField: 'due_date', offset: { value: -1, unit: 'days' } } }); + expect(ordering('sweep_same', f)).toEqual(['error: date ordered against text `google.protobuf.Timestamp > string`']); + }); + + it('a sweep of another object: the warning it was, and the note saying why', () => { + const f = flow('sweep_other', { timeRelative: { object: 'library_reminder', dateField: 'remind_on', offset: { value: -1, unit: 'days' } } }); + expect(ordering('sweep_other', f)).toEqual(['warning: date ordered against text `google.protobuf.Timestamp > string`']); + const notes = validateStackExpressions(specValid(stackOf(f))).filter((i) => i.where.endsWith('config.objectName')); + expect(notes.map((i) => [i.severity, i.message.slice(0, 60)])).toEqual([ + ['warning', "this time-relative flow sweeps 'library_reminder' (config.ti"], + ]); + }); + + it('CONTROL: a real type mismatch on the same flow keeps its type-mismatch sentence', () => { + const f = { ...flow('on_change', { triggerType: 'record-after-update' }) }; + (f.nodes[0].config as Record).condition = 'title > 5'; + expect(ordering('on_change', f)).toEqual(['error: type mismatch `string > int`']); + }); +}); diff --git a/packages/lint/src/validate-expressions.ts b/packages/lint/src/validate-expressions.ts index 71dd90fafdd..62f25a8bf58 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -2614,12 +2614,15 @@ export function validateStackExpressions(stack: AnyRec): ExprIssue[] { */ export function runStackExpressionPasses(stack: AnyRec, options: StackExpressionOptions): ExprIssue[] { const issues: ExprIssue[] = []; - // [#30026] How many `type-mismatch-run-may-fail` warnings {@link check} has + // [#30026] How many softened flow-condition warnings {@link check} has // served: a flow whose own count moved is one an author is told why of, // where the reason is the flow's own (the time-relative note in the flow - // walk). Only that code: the date verdicts' `-run-may-fail` arm is an error - // whatever the outcome, so a sweep of another object does not soften it and - // there is nothing to explain. + // walk). Two codes are softened that way: `type-mismatch-run-may-fail`, and + // (#38959 item 4) a `date-text-ordering` warning at a flow condition, which + // is the date-against-text ordering that used to be served as + // `type-mismatch-run-may-fail`. No other code is: the date verdicts' + // `-run-may-fail` arm is an error whatever the outcome, so a sweep of + // another object does not soften it and there is nothing to explain. let runMayFailServed = 0; // [#22019] See {@link StackExpressionOptions.runtimeWriteType}: on an object // write only the passes over the object's own body judge: the field-formula @@ -3109,7 +3112,7 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression issues.push({ where, message: e.message, source: e.source, severity: 'error' }); } for (const w of res.warnings) { - if (w.code === 'type-mismatch-run-may-fail') runMayFailServed++; + if (w.code === 'type-mismatch-run-may-fail' || (w.code === 'date-text-ordering' && scope === 'flattened')) runMayFailServed++; issues.push({ where, message: w.message, source: w.source, severity: 'warning' }); } if (objectName && traversalHydration) refuseStoredMetadataBodyHop(where, raw, objectName, 'rule'); @@ -3916,11 +3919,11 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression message: `this time-relative flow sweeps '${sweepObject}' (config.timeRelative.object), so each run's record is a ` + `row of '${sweepObject}', while its conditions are checked against the fields of '${startObject}' (the ` + - `start node's config.objectName). That is why a type mismatch in its conditions is a warning here and ` + + `start node's config.objectName). That is why a type mismatch, or a date ordered against text, in its conditions is a warning here and ` + `not a refusal: the names hold a '${sweepObject}' row, not the '${startObject}' fields they were checked ` + `against. Set config.objectName to '${sweepObject}', or remove it, as flow-time-relative-object-mismatch ` + `asks of this start: the conditions are then checked ` + - `against the swept object, and a type mismatch in them is refused, as on a record-triggered flow.`, + `against the swept object, and either is refused there, as on a record-triggered flow.`, source: startObject, severity: 'warning', ...(startIndex >= 0 ? { path: `flows[${flowIndex}].nodes[${startIndex}].config.objectName` } : {}),