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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .changeset/36377-flow-bare-ordering-record-date-arithmetic.md
Original file line number Diff line number Diff line change
@@ -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

<!-- adr-0087: registered flow-condition-bare-ordering-before-record-date-arithmetic-refused -->

**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.
36 changes: 2 additions & 34 deletions packages/formula/src/cel-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down Expand Up @@ -1604,38 +1604,6 @@ export function firstDateTextVerdict(
}
}

/**
* [#34662] Whether the FIRST operator fault the Timestamp typing of a flattened
* condition's `record.<field>` / `previous.<field>` 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<Record<string, FieldCelType>>,
): 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
Expand Down
67 changes: 67 additions & 0 deletions packages/formula/src/validate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1411,3 +1411,70 @@ describe('a flow condition\'s record.<field> / previous.<field> 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' },
]]);
});
});
31 changes: 17 additions & 14 deletions packages/formula/src/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import {
firstDateTextVerdict,
firstTypeMismatch,
inferCelType,
recordRootReadsFaultDateArith,
RECORD_ROOT_READ_RE,
parseCelToAst,
parseCelToAstWithReason,
Expand Down Expand Up @@ -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,
Expand All @@ -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;
Expand Down
53 changes: 53 additions & 0 deletions packages/lint/src/validate-expressions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading