diff --git a/.changeset/36377-flow-bare-ordering-record-date-arithmetic.md b/.changeset/36377-flow-bare-ordering-record-date-arithmetic.md new file mode 100644 index 00000000000..f399d819511 --- /dev/null +++ b/.changeset/36377-flow-bare-ordering-record-date-arithmetic.md @@ -0,0 +1,27 @@ +--- +'@objectstack/formula': minor +'@objectstack/spec': minor +--- + +fix(formula)!: a flow condition that orders a bare date field against text before date arithmetic on `record.FIELD` or `previous.FIELD` is now refused, as its all-bare and all-root spellings already were + +Clause-②: no (narrowing) +Metadata-protocol: narrowed +Skills-docs: none — `skills/objectstack-formula/SKILL.md` already states "The build refuses `end - start`, `date + n`, `today() + 30`" and names no site or spelling it is limited to, so it now holds for this flow-condition spelling as written + + + +**BREAKING** accept-set narrowing. In a flow condition (a start, edge or `decision` branch condition) the run binds the record's fields under their bare names and also as `record`, with the row before the write as `previous`. A condition that first orders a `date` or `datetime` field's bare name against a text literal and then does arithmetic against a number on a `record.FIELD` / `previous.FIELD` read, such as `due_date > "2026-01-01" && record.due_date + 1 > 5`, passed `os validate` and the publish door with no finding. The flow then failed on every run, because the field reaches the run as its text and the evaluator cannot add a number to it. The all-bare spelling (`due_date > "2026-01-01" && due_date + 1 > 5`) and the all-root spelling (`record.due_date > "2026-01-01" && record.due_date + 1 > 5`) were refused already. + +- **The verdict.** The mixed spelling now gets the all-root spelling's verdict: `date-text-arithmetic-run-fails` on a record-triggered flow or a sweep of the typed object, `date-text-arithmetic-run-may-fail` elsewhere, naming the read as written. A root read keeps the row's arm where bare names are unproven. Where a flow variable holds the bare name, the ordering is not the field's, and the root read's arithmetic takes `date-arithmetic-run-fails`, as `record.due_date + 1 > 5` alone does. +- **Where.** `os validate` / `os build` (`validateStackExpressions`) report an `error`, and the flow publish door refuses the publish with `INVALID_METADATA` (422). `registerFlow` logs it as an advisory and still registers the flow, so a stored flow keeps its run-time behaviour until it is next published. +- **Not refused.** The same bare ordering beside an ordering of the root read (`due_date > "2026-01-01" && record.due_date < today()`), and `daysBetween` / `addDays` over it. The run-time evaluator is unchanged. + +## FROM → TO + +| FROM | TO | +|:---|:---| +| `due_date > "2026-01-01" && record.due_date + 1 > 5` | `due_date > "2026-01-01" && daysBetween(record.due_date, today()) > 5` (days past due) or `due_date > "2026-01-01" && addDays(record.due_date, 1) < today()` (a shifted date) | +| `due_date > "2026-01-01" && previous.due_date - 7 < today()` | `due_date > "2026-01-01" && addDays(previous.due_date, -7) < today()` | + +One-line fix: in a flow condition, never add or subtract a number on a date field read through `record` or `previous`, whatever precedes it; use `daysBetween(a, b)` for a span and `addDays(d, n)` to shift a date. diff --git a/packages/formula/src/cel-engine.ts b/packages/formula/src/cel-engine.ts index dd31fd192c0..9ca42c7b5d6 100644 --- a/packages/formula/src/cel-engine.ts +++ b/packages/formula/src/cel-engine.ts @@ -1427,8 +1427,8 @@ export function firstTypeMismatch( // against a number — `record.due_date + 1` faults on the field's text on // every run exactly as `due_date + 1` does. Either names the read as // written (`root`). The date-text family reaches the roots through - // `validate.ts`'s record-root pass (#34662), which stands down on the - // date-arith shape answered here ({@link recordRootReadsFaultDateArith}). + // `validate.ts`'s record-root pass (#34662), asked only where this answers + // null (#36377). if (scope !== 'flattened' || !RECORD_ROOT_READ_RE.test(source)) return null; const rootTyped = unsoundOverload(buildTypedEnv(bareTypes, 'flattened', 'timestamp', fieldCelTypes)); if (rootTyped && isDateArith(rootTyped)) { @@ -1604,38 +1604,6 @@ export function firstDateTextVerdict( } } -/** - * [#34662] Whether the FIRST operator fault the Timestamp typing of a flattened - * condition's `record.` / `previous.` reads meets (every bare - * name `dyn`) is date/duration arithmetic against a number ({@link isDateArith}) - * — `record.due_date + 1`. That shape is the `date-arithmetic` family's, and it - * is exactly where the bare name's own order stops: {@link firstTypeMismatch} - * answers `date-arith` there (for the root read too, #34946) and the date-text - * check is never asked. Any other - * Timestamp-typing fault — `record.end_date - record.start_date > 3` (a Duration - * ordered against a number), `record.d >= "2026-01-01"` (the text ordering the - * runtime answers) — leaves the bare name's mismatch check at null and the - * date-text check asked, so it does not stand the record-root pass down - * either. `false` when the source does not parse. - */ -export function recordRootReadsFaultDateArith( - source: string, - recordRootTypes: Readonly>, -): boolean { - if (typeof source !== 'string' || !source.trim()) return false; - try { - const result = buildTypedEnv({}, 'flattened', 'timestamp', recordRootTypes) - .parse(rewriteNullableTernary(rewriteIndexedHas(source))).check?.() as - | { valid?: boolean; error?: { message?: string } } - | undefined; - if (result?.valid !== false) return false; - const m = UNSOUND_OVERLOAD_RE.exec(result.error?.message ?? ''); - return m !== null && isDateArith(m); - } catch { - return false; - } -} - /** * cel-js's code for a CALL no overload accepts — `isoDate(string)`, * `string.getFullYear()` — raised by the checker and the evaluator alike diff --git a/packages/formula/src/validate.test.ts b/packages/formula/src/validate.test.ts index cf9b8881765..9ca0e3cceff 100644 --- a/packages/formula/src/validate.test.ts +++ b/packages/formula/src/validate.test.ts @@ -1411,3 +1411,70 @@ describe('a flow condition\'s record. / previous. read takes the d expect(codes('record.title > 5')).toEqual(['type-mismatch-run-fails']); }); }); + +// [#36377] A flow condition that orders the BARE date name against a text +// literal before it does arithmetic on the field's `record.` / `previous.` read +// (`due_date > "2026-01-01" && record.due_date + 1 > 5`) was refused by no pass: +// the Timestamp typing met the ordering first and stood it down for the bare +// name and the record-root pass alike, and the record-root date-text pass stood +// down because the roots' own typing met date arithmetic first, a shape it read +// as answered elsewhere. The run faults on the `YYYY-MM-DD` text every time. The +// mixed spelling now takes the verdict, code and words its all-bare and +// all-root spellings take. +describe('a flow condition that orders the bare date name before date arithmetic on its record. / previous. read is refused (#36377)', () => { + const fieldTypes = { title: 'text', borrow_date: 'date', due_date: 'date', picked_up_at: 'datetime' }; + const CONDITION: ExprSchemaHint = { scope: 'flattened', fields: Object.keys(fieldTypes), fieldTypes, faultOutcome: 'run-fails' }; + const errorsOf = (source: string, hint: ExprSchemaHint = CONDITION) => validateExpression('predicate', source, hint).errors; + const codes = (source: string, hint: ExprSchemaHint = CONDITION) => errorsOf(source, hint).map((e) => e.code); + const verdicts = (source: string, hint: ExprSchemaHint = CONDITION) => + errorsOf(source, hint).map((e) => ({ code: e.code, params: e.params, message: e.message })); + const ROW = { title: 'Dune', borrow_date: '2026-11-16', due_date: '2026-11-30', picked_up_at: '2026-11-16T09:30:00.000Z' }; + const run = (source: string) => celEngine.evaluate({ dialect: 'cel', source }, { ...ROW, record: ROW, previous: ROW }); + + it('refuses the mixed spelling with exactly the verdict the all-root spelling gets, naming the root read', () => { + for (const [root, field, op] of [ + ['record', 'due_date', '+ 1'], ['previous', 'due_date', '- 7'], ['record', 'picked_up_at', '+ 1'], + ] as const) { + const allRoot = `${root}.${field} > "2026-01-01" && ${root}.${field} ${op} > 5`; + const mixed = `${field} > "2026-01-01" && ${root}.${field} ${op} > 5`; + const expected = verdicts(allRoot); + expect(expected.map((v) => v.code), allRoot).toEqual(['date-text-arithmetic-run-fails']); + expect(expected[0].params, allRoot).toMatchObject({ reference: `${root}.${field}` }); + expect(verdicts(mixed), mixed).toEqual(expected); + // Both fault on the field's text on every run. + expect(run(mixed), mixed).toMatchObject({ ok: false }); + } + // The all-bare spelling takes the same code, naming the bare name. + expect(verdicts('due_date > "2026-01-01" && due_date + 1 > 5').map((v) => [v.code, v.params])) + .toEqual([['date-text-arithmetic-run-fails', { operands: 'DateText + int', reference: 'due_date' }]]); + }); + + it('takes the row\'s outcome arm: run-may-fail where none is declared, run-fails kept when bare names are unproven', () => { + const mixed = 'due_date > "2026-01-01" && record.due_date + 1 > 5'; + expect(codes(mixed, { ...CONDITION, faultOutcome: undefined })).toEqual(['date-text-arithmetic-run-may-fail']); + expect(codes(mixed, { ...CONDITION, bareNamesUnproven: true })).toEqual(['date-text-arithmetic-run-fails']); + // A flow variable holding the bare name leaves the bare ordering `dyn`, so the record-root pass meets the + // root read's arithmetic first and answers it under `date-arithmetic`, as for `record.due_date + 1 > 5` alone. + expect(codes(mixed, { ...CONDITION, flowVariables: ['due_date'] })).toEqual(['date-arithmetic-run-fails']); + }); + + it('CONTROL: the arithmetic first keeps its date-arithmetic verdict, and the prescribed rewrites stay clean', () => { + expect(codes('record.due_date + 1 > 5 && due_date > "2026-01-01"')).toEqual(['date-arithmetic-run-fails']); + for (const source of [ + 'due_date > "2026-01-01" && record.due_date < today()', + 'due_date > "2026-01-01" && daysBetween(record.due_date, today()) > 5', + 'due_date > "2026-01-01" && addDays(previous.due_date, -7) < today()', + ]) { + expect(validateExpression('predicate', source, CONDITION), source).toEqual({ ok: true, errors: [], warnings: [] }); + } + }); + + it('the #30025 swap under unproven bare names hands a root read\'s date-arithmetic verdict the row\'s arm', () => { + // The bare text mismatch is not proven the field's; the root read's date arithmetic is, and its answer wins. + const unproven: ExprSchemaHint = { ...CONDITION, bareNamesUnproven: true }; + expect(verdicts('title > 5 && record.due_date + 1 > 5', unproven).map((v) => [v.code, v.params])).toEqual([[ + 'date-arithmetic-run-fails', + { operands: 'google.protobuf.Timestamp + int', reference: 'record.due_date' }, + ]]); + }); +}); diff --git a/packages/formula/src/validate.ts b/packages/formula/src/validate.ts index 6687ae14c3f..9fb19fcb8bd 100644 --- a/packages/formula/src/validate.ts +++ b/packages/formula/src/validate.ts @@ -24,7 +24,6 @@ import { firstDateTextVerdict, firstTypeMismatch, inferCelType, - recordRootReadsFaultDateArith, RECORD_ROOT_READ_RE, parseCelToAst, parseCelToAstWithReason, @@ -920,18 +919,23 @@ const DATE_TEXT_FAMILY_RE = /^date-text-(?:call|arithmetic)(?:-|$)/; * root read, left `dyn`, checked clean. Typed here with every field's type * (a flow variable shadows a bare name, never a root member), every bare name * `dyn`, the same verdict, code and words come back, naming the read as - * written. The order is the bare name's own: there {@link firstTypeMismatch} - * answers `date-arith` when the Timestamp typing's first fault is date/duration - * arithmetic against a number, and the date-text check is asked only once it - * answers null. So the pass stands down exactly where the roots' first - * Timestamp-typing fault is that shape (`record.due_date + 1`, the - * `date-arithmetic` family's, {@link recordRootReadsFaultDateArith}), and on no - * other fault: `record.due_date - record.borrow_date > 3` (a Duration ordered - * against a number) and an expression that orders a date field against a text - * literal before it calls `timestamp()` are judged, as their bare spellings - * are. Only `date-text-call*` / `date-text-arithmetic*` are kept. The outcome arm is - * the row's: a root read keeps the declared outcome whatever binds the bare - * names (#30025), so `bareNamesUnproven` is not asked. + * written. The order is the bare name's own: the date-text check is asked + * only once {@link firstTypeMismatch} answers null, and this pass is reached + * only there, so it never stands down on a shape that check answers (its + * record-root pass answers `record.due_date + 1` under `date-arith`, #34946). + * [#36377] Nor on any other: the roots' own Timestamp typing meeting date + * arithmetic first is no answer. `due_date > "2026-01-01" && record.due_date + 1 > 5` + * orders the bare name against a text literal first, which the runtime answers + * and {@link firstTypeMismatch} stands down on for the bare name and the root + * pass alike, so it answers null and the arithmetic on the root read faults on + * every run; judged here it takes the `date-text-arithmetic` verdict its all-bare + * and all-root spellings take. `record.due_date - record.borrow_date > 3` (a + * Duration ordered against a number) and an expression that orders a date + * field against a text literal before it calls `timestamp()` are judged, as + * their bare spellings are. Only `date-text-call*` / `date-text-arithmetic*` + * are kept. The outcome arm is the row's: a root read keeps the declared + * outcome whatever binds the bare names (#30025), so `bareNamesUnproven` is + * not asked. */ function recordRootDateTextIssue( source: string, @@ -941,7 +945,6 @@ function recordRootDateTextIssue( faultOutcome: ExprSchemaHint['faultOutcome'], ): { issue: ExprValidationError; severity: 'error' | 'warning' } | null { if (!RECORD_ROOT_READ_RE.test(source) || !Object.values(celFieldTypes).includes('timestamp')) return null; - if (recordRootReadsFaultDateArith(source, celFieldTypes)) return null; const dateOnly = new Set(Object.keys(celFieldTypes).filter((name) => fieldTypes[name] === 'date')); const found = dateTextIssue(source, {}, 'flattened', role, dateArm('flattened', faultOutcome, false), dateOnly, celFieldTypes); return found && DATE_TEXT_FAMILY_RE.test(found.issue.code) ? found : null; diff --git a/packages/lint/src/validate-expressions.test.ts b/packages/lint/src/validate-expressions.test.ts index 2c2d33739ea..97ff18ee0bb 100644 --- a/packages/lint/src/validate-expressions.test.ts +++ b/packages/lint/src/validate-expressions.test.ts @@ -7100,6 +7100,59 @@ describe('validateStackExpressions — a flow condition\'s record. / previous. r }); }); +// [#36377] A flow CONDITION that orders the BARE date name against a text +// literal before it does arithmetic on the field's `record.` / `previous.` +// read got zero findings, while its all-bare and all-root spellings were +// refused, and it fails every run on the `YYYY-MM-DD` text. It now takes the +// all-root spelling's finding, at the same path and severity. +describe('validateStackExpressions — a bare date ordering before date arithmetic on a record. / previous. read is refused (#36377)', () => { + const LOAN = { + name: 'library_loan', + fields: { due_date: { type: 'date', required: true }, picked_up_at: { type: 'datetime', required: true } }, + }; + type Site = 'start' | 'edge' | 'decision'; + const stackWith = (site: Site, condition: string) => ({ + objects: [LOAN], + flows: [{ + name: 'loan_due', + nodes: [ + { + id: 'start', type: 'start', + config: { objectName: 'library_loan', triggerType: 'record-after-update', ...(site === 'start' ? { condition } : {}) }, + }, + ...(site === 'decision' + ? [{ id: 'gate', type: 'decision', config: { conditions: [{ label: 'Due', expression: condition }] } }] + : []), + { id: 'end', type: 'end' }, + ], + edges: site === 'decision' + ? [{ id: 'e1', source: 'start', target: 'gate' }, { id: 'e2', source: 'gate', target: 'end' }] + : [{ id: 'e1', source: 'start', target: 'end', ...(site === 'edge' ? { condition } : {}) }], + }], + }); + const shape = (issues: ExprIssue[]) => issues.map((i) => [i.severity, i.path ?? i.where, i.message]); + + it.each(['start', 'edge', 'decision'] as const)( + 'refuses the mixed spelling in a %s condition with the all-root spelling\'s finding', + (site) => { + for (const [root, field, op] of [ + ['record', 'due_date', '+ 1'], ['previous', 'due_date', '- 7'], ['record', 'picked_up_at', '+ 1'], + ] as const) { + const allRoot = validateStackExpressions(stackWith(site, `${root}.${field} > "2026-01-01" && ${root}.${field} ${op} > 5`)); + expect(allRoot.map((i) => i.severity), `${site}: ${root}.${field}`).toEqual(['error']); + const mixed = `${field} > "2026-01-01" && ${root}.${field} ${op} > 5`; + expect(shape(validateStackExpressions(stackWith(site, mixed))), `${site}: ${mixed}`).toEqual(shape(allRoot)); + } + }, + ); + + it('CONTROL: the same bare ordering before an ordering of the root read against today() stays clean', () => { + for (const site of ['start', 'edge', 'decision'] as const) { + expect(validateStackExpressions(stackWith(site, 'due_date > "2026-01-01" && record.due_date < today()')), site).toEqual([]); + } + }); +}); + /** * [ADR-0113 D1, as amended] A `required` field's own `visibleWhen` decides its * requirement on the write, and a predicate the server cannot evaluate counts diff --git a/packages/runtime/src/domains/meta-flow-condition-record-date-text.test.ts b/packages/runtime/src/domains/meta-flow-condition-record-date-text.test.ts index 488d58d3937..e2c1f2a193a 100644 --- a/packages/runtime/src/domains/meta-flow-condition-record-date-text.test.ts +++ b/packages/runtime/src/domains/meta-flow-condition-record-date-text.test.ts @@ -205,3 +205,45 @@ describe('[#34946] the flow publish door refuses date arithmetic on a date field expect(await rig.state('loan_due_ordering')).toEqual(['active']); }, 60_000); }); + +/** + * [#36377] The flow publish door refuses a condition that orders the BARE date + * name against a text literal before it does arithmetic on the field's + * `record.` / `previous.` read. The business case: an administrator publishes a + * record-triggered flow on a loan that runs for loans due this year and a day + * past due (`due_date > "2026-01-01" && record.due_date + 1 > 5`, the date + * written as if it were a number). The run holds the field as its `YYYY-MM-DD` + * text and the evaluator cannot add a number to it, so the flow fails on every + * run; the door refused the all-bare and all-`record.` spellings and published + * the mixed one. Now all three are refused, in the same finding. + */ +describe('[#36377] the flow publish door refuses a bare date ordering before date arithmetic on a record. / previous. read', () => { + /** The door's date-arithmetic findings (both families) on a refused publish. */ + const dateArithmeticIssues = (err: any) => + (err?.issues ?? []).filter((i: any) => i.rule === 'expression-invalid' && /^date arithmetic/.test(i.message)); + + it('⭐ LIT — refuses the mixed spelling with INVALID_METADATA / 422 and the all-root spelling\'s words, leaving the draft', async () => { + const rig = await boot(); + for (const [root, op] of [['record', '+ 1'], ['previous', '- 7']] as const) { + const allRoot: any = await rig.publish(flowOn(`loan_all_${root}`, `${root}.due_date > "2026-01-01" && ${root}.due_date ${op} > 5`)); + const name = `loan_mixed_${root}`; + const err: any = await rig.publish(flowOn(name, `due_date > "2026-01-01" && ${root}.due_date ${op} > 5`)); + expect(err, `${root}: the publish was admitted`).toBeInstanceOf(Error); + expect({ code: err.code, status: err.status }, root).toEqual({ code: 'INVALID_METADATA', status: 422 }); + const issues = dateArithmeticIssues(err); + expect(issues, `${root}: ${JSON.stringify(err.issues)}`).toHaveLength(1); + expect(issues[0].message).toContain(`— \`${root}.due_date\` is a date field, and the runtime holds`); + // The door's message ends by quoting the source; the finding before it is the all-root spelling's. + const finding = (i: any) => String(i.message).split(' — source: ')[0]; + expect(issues.map(finding), root).toEqual(dateArithmeticIssues(allRoot).map(finding)); + expect(await rig.state(name), root).toEqual(['draft']); + } + }, 60_000); + + it('⭐ CONTROL — the same bare ordering before an ordering of the root read against today() publishes', async () => { + const rig = await boot(); + const err = await rig.publish(flowOn('loan_mixed_ordering', 'due_date > "2026-01-01" && record.due_date < today()')); + expect(err?.issues ?? err, 'the door refused').toBeUndefined(); + expect(await rig.state('loan_mixed_ordering')).toEqual(['active']); + }, 60_000); +}); diff --git a/packages/spec/src/migrations/entries/semantic/19.flow-condition-bare-ordering-before-record-date-arithmetic-refused.ts b/packages/spec/src/migrations/entries/semantic/19.flow-condition-bare-ordering-before-record-date-arithmetic-refused.ts new file mode 100644 index 00000000000..2b654825a5e --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.flow-condition-bare-ordering-before-record-date-arithmetic-refused.ts @@ -0,0 +1,43 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// A flow condition that orders a date field's BARE name against a text literal +// before it does arithmetic on the field's record.FIELD / previous.FIELD read +// now takes the date-text-arithmetic verdict its all-bare and all-root +// spellings already took (#36377). A structured TODO, not a D2 conversion: +// which span or shift the author meant is not recorded, and the platform does +// not guess. +export const entry: SemanticMigration = { + id: 'flow-condition-bare-ordering-before-record-date-arithmetic-refused', + surface: + 'automation.Flow conditions (a start node config.condition, edges[].condition, a decision node\'s ' + + 'config.conditions[].expression) that order a date or datetime field of the object the flow is typed against, ' + + 'read by its bare name, against a text literal before they do arithmetic against a number on the same or another ' + + 'such field read through record.FIELD or previous.FIELD (due_date > "2026-01-01" && record.due_date + 1 > 5). ' + + 'The all-bare (due_date > "2026-01-01" && due_date + 1 > 5) and all-root ' + + '(record.due_date > "2026-01-01" && record.due_date + 1 > 5) spellings were refused already. Not the shape: ' + + 'the arithmetic written first (refused already as date-arithmetic), an ordering or equality of the root read ' + + '(record.due_date < today()), or daysBetween / addDays / addMonths over it', + replacement: + 'keep the ordering and replace the arithmetic: daysBetween(a, b) for the span in whole days ' + + '(due_date > "2026-01-01" && daysBetween(record.due_date, today()) > 5), and addDays(d, n) / addMonths(d, n) / ' + + 'daysFromNow(n) to shift a date (addDays(previous.due_date, -7) < today())', + reason: + 'A flow run binds the trigger record twice: its fields flattened to bare names, and the row itself as record, ' + + 'with the row before the write as previous. A date field reaches the run as its YYYY-MM-DD text and a datetime ' + + 'field as its ISO-8601 instant text, so record.due_date + 1 faults the evaluator on every run, and a flow ' + + 'condition that faults fails the run (ADR-0032 section 1c). The authoring type check met the bare ordering ' + + 'against the text literal first, which the runtime answers, and set the whole condition aside; the record-root ' + + 'date-text check then read the root arithmetic as answered by the first check, which had answered nothing, so ' + + 'no finding was given. It now refuses the condition with the code, outcome arm and words the all-root ' + + 'spelling takes (date-text-arithmetic-run-fails / date-text-arithmetic-run-may-fail), naming the read as ' + + 'written. There is no mechanical rewrite: whether the author meant a span in days or a shifted date is a ' + + 'judgement about the condition. ADR-0032 / ADR-0087.', + acceptanceCriteria: + 'os validate and os build report no date-text-arithmetic-run-fails or date-text-arithmetic-run-may-fail finding ' + + 'on a flow condition that orders a bare date name and does arithmetic on a record or previous read of a date ' + + 'field; POST /api/v1/packages/PKG/publish-drafts publishes the flow; a write that should start it runs past ' + + 'the condition instead of failing there. A stored flow carrying the shape still registers (registerFlow logs it ' + + 'as an advisory) and keeps failing at that condition on every run until it is rewritten and published.', +};