Skip to content

Commit 2087f66

Browse files
committed
fix(formula)!: refuse a flow condition that orders a bare date against text before date arithmetic on its record. read
The bare pass and the record-root pass both met the bare Timestamp-vs-text ordering first and stood it down, and the record-root date-text pass stood down because the roots' own typing met date arithmetic first, a shape it read as answered by firstTypeMismatch. That pass is only reached where firstTypeMismatch answered null, so the stand-down could only ever drop a fault nobody else refused. Drop it (and its now-unused predicate); the mixed spelling takes the all-root spelling's date-text-arithmetic verdict. Claude-Session: https://claude.ai/code/session_01L9qibz2oLCRAYBpwsBBUyG Co-authored-by: Claude <noreply@anthropic.com>
1 parent c826e8a commit 2087f66

7 files changed

Lines changed: 249 additions & 48 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
---
2+
'@objectstack/formula': minor
3+
'@objectstack/spec': minor
4+
---
5+
6+
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
7+
8+
Clause-②: no (narrowing)
9+
Metadata-protocol: narrowed
10+
Skills-docs: none — no page under `skills/**` teaches date arithmetic in a flow condition; `content/docs/data-modeling/formulas.mdx` already names date arithmetic an error, and the refusal's own sentence names the fix
11+
12+
<!-- adr-0087: registered flow-condition-bare-ordering-before-record-date-arithmetic-refused -->
13+
14+
**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.
15+
16+
- **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.
17+
- **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.
18+
- **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.
19+
20+
## FROM → TO
21+
22+
| FROM | TO |
23+
|:---|:---|
24+
| `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) |
25+
| `due_date > "2026-01-01" && previous.due_date - 7 < today()` | `due_date > "2026-01-01" && addDays(previous.due_date, -7) < today()` |
26+
27+
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.

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

Lines changed: 2 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1427,8 +1427,8 @@ export function firstTypeMismatch(
14271427
// against a number — `record.due_date + 1` faults on the field's text on
14281428
// every run exactly as `due_date + 1` does. Either names the read as
14291429
// written (`root`). The date-text family reaches the roots through
1430-
// `validate.ts`'s record-root pass (#34662), which stands down on the
1431-
// date-arith shape answered here ({@link recordRootReadsFaultDateArith}).
1430+
// `validate.ts`'s record-root pass (#34662), asked only where this answers
1431+
// null (#36377).
14321432
if (scope !== 'flattened' || !RECORD_ROOT_READ_RE.test(source)) return null;
14331433
const rootTyped = unsoundOverload(buildTypedEnv(bareTypes, 'flattened', 'timestamp', fieldCelTypes));
14341434
if (rootTyped && isDateArith(rootTyped)) {
@@ -1604,38 +1604,6 @@ export function firstDateTextVerdict(
16041604
}
16051605
}
16061606

1607-
/**
1608-
* [#34662] Whether the FIRST operator fault the Timestamp typing of a flattened
1609-
* condition's `record.<field>` / `previous.<field>` reads meets (every bare
1610-
* name `dyn`) is date/duration arithmetic against a number ({@link isDateArith})
1611-
* — `record.due_date + 1`. That shape is the `date-arithmetic` family's, and it
1612-
* is exactly where the bare name's own order stops: {@link firstTypeMismatch}
1613-
* answers `date-arith` there (for the root read too, #34946) and the date-text
1614-
* check is never asked. Any other
1615-
* Timestamp-typing fault — `record.end_date - record.start_date > 3` (a Duration
1616-
* ordered against a number), `record.d >= "2026-01-01"` (the text ordering the
1617-
* runtime answers) — leaves the bare name's mismatch check at null and the
1618-
* date-text check asked, so it does not stand the record-root pass down
1619-
* either. `false` when the source does not parse.
1620-
*/
1621-
export function recordRootReadsFaultDateArith(
1622-
source: string,
1623-
recordRootTypes: Readonly<Record<string, FieldCelType>>,
1624-
): boolean {
1625-
if (typeof source !== 'string' || !source.trim()) return false;
1626-
try {
1627-
const result = buildTypedEnv({}, 'flattened', 'timestamp', recordRootTypes)
1628-
.parse(rewriteNullableTernary(rewriteIndexedHas(source))).check?.() as
1629-
| { valid?: boolean; error?: { message?: string } }
1630-
| undefined;
1631-
if (result?.valid !== false) return false;
1632-
const m = UNSOUND_OVERLOAD_RE.exec(result.error?.message ?? '');
1633-
return m !== null && isDateArith(m);
1634-
} catch {
1635-
return false;
1636-
}
1637-
}
1638-
16391607
/**
16401608
* cel-js's code for a CALL no overload accepts — `isoDate(string)`,
16411609
* `string.getFullYear()` — raised by the checker and the evaluator alike

‎packages/formula/src/validate.test.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1411,3 +1411,70 @@ describe('a flow condition\'s record.<field> / previous.<field> read takes the d
14111411
expect(codes('record.title > 5')).toEqual(['type-mismatch-run-fails']);
14121412
});
14131413
});
1414+
1415+
// [#36377] A flow condition that orders the BARE date name against a text
1416+
// literal before it does arithmetic on the field's `record.` / `previous.` read
1417+
// (`due_date > "2026-01-01" && record.due_date + 1 > 5`) was refused by no pass:
1418+
// the Timestamp typing met the ordering first and stood it down for the bare
1419+
// name and the record-root pass alike, and the record-root date-text pass stood
1420+
// down because the roots' own typing met date arithmetic first, a shape it read
1421+
// as answered elsewhere. The run faults on the `YYYY-MM-DD` text every time. The
1422+
// mixed spelling now takes the verdict, code and words its all-bare and
1423+
// all-root spellings take.
1424+
describe('a flow condition that orders the bare date name before date arithmetic on its record. / previous. read is refused (#36377)', () => {
1425+
const fieldTypes = { title: 'text', borrow_date: 'date', due_date: 'date', picked_up_at: 'datetime' };
1426+
const CONDITION: ExprSchemaHint = { scope: 'flattened', fields: Object.keys(fieldTypes), fieldTypes, faultOutcome: 'run-fails' };
1427+
const errorsOf = (source: string, hint: ExprSchemaHint = CONDITION) => validateExpression('predicate', source, hint).errors;
1428+
const codes = (source: string, hint: ExprSchemaHint = CONDITION) => errorsOf(source, hint).map((e) => e.code);
1429+
const verdicts = (source: string, hint: ExprSchemaHint = CONDITION) =>
1430+
errorsOf(source, hint).map((e) => ({ code: e.code, params: e.params, message: e.message }));
1431+
const ROW = { title: 'Dune', borrow_date: '2026-11-16', due_date: '2026-11-30', picked_up_at: '2026-11-16T09:30:00.000Z' };
1432+
const run = (source: string) => celEngine.evaluate({ dialect: 'cel', source }, { ...ROW, record: ROW, previous: ROW });
1433+
1434+
it('refuses the mixed spelling with exactly the verdict the all-root spelling gets, naming the root read', () => {
1435+
for (const [root, field, op] of [
1436+
['record', 'due_date', '+ 1'], ['previous', 'due_date', '- 7'], ['record', 'picked_up_at', '+ 1'],
1437+
] as const) {
1438+
const allRoot = `${root}.${field} > "2026-01-01" && ${root}.${field} ${op} > 5`;
1439+
const mixed = `${field} > "2026-01-01" && ${root}.${field} ${op} > 5`;
1440+
const expected = verdicts(allRoot);
1441+
expect(expected.map((v) => v.code), allRoot).toEqual(['date-text-arithmetic-run-fails']);
1442+
expect(expected[0].params, allRoot).toMatchObject({ reference: `${root}.${field}` });
1443+
expect(verdicts(mixed), mixed).toEqual(expected);
1444+
// Both fault on the field's text on every run.
1445+
expect(run(mixed), mixed).toMatchObject({ ok: false });
1446+
}
1447+
// The all-bare spelling takes the same code, naming the bare name.
1448+
expect(verdicts('due_date > "2026-01-01" && due_date + 1 > 5').map((v) => [v.code, v.params]))
1449+
.toEqual([['date-text-arithmetic-run-fails', { operands: 'DateText + int', reference: 'due_date' }]]);
1450+
});
1451+
1452+
it('takes the row\'s outcome arm: run-may-fail where none is declared, run-fails kept when bare names are unproven', () => {
1453+
const mixed = 'due_date > "2026-01-01" && record.due_date + 1 > 5';
1454+
expect(codes(mixed, { ...CONDITION, faultOutcome: undefined })).toEqual(['date-text-arithmetic-run-may-fail']);
1455+
expect(codes(mixed, { ...CONDITION, bareNamesUnproven: true })).toEqual(['date-text-arithmetic-run-fails']);
1456+
// A flow variable holding the bare name leaves the bare ordering `dyn`, so the record-root pass meets the
1457+
// root read's arithmetic first and answers it under `date-arithmetic`, as for `record.due_date + 1 > 5` alone.
1458+
expect(codes(mixed, { ...CONDITION, flowVariables: ['due_date'] })).toEqual(['date-arithmetic-run-fails']);
1459+
});
1460+
1461+
it('CONTROL: the arithmetic first keeps its date-arithmetic verdict, and the prescribed rewrites stay clean', () => {
1462+
expect(codes('record.due_date + 1 > 5 && due_date > "2026-01-01"')).toEqual(['date-arithmetic-run-fails']);
1463+
for (const source of [
1464+
'due_date > "2026-01-01" && record.due_date < today()',
1465+
'due_date > "2026-01-01" && daysBetween(record.due_date, today()) > 5',
1466+
'due_date > "2026-01-01" && addDays(previous.due_date, -7) < today()',
1467+
]) {
1468+
expect(validateExpression('predicate', source, CONDITION), source).toEqual({ ok: true, errors: [], warnings: [] });
1469+
}
1470+
});
1471+
1472+
it('the #30025 swap under unproven bare names hands a root read\'s date-arithmetic verdict the row\'s arm', () => {
1473+
// The bare text mismatch is not proven the field's; the root read's date arithmetic is, and its answer wins.
1474+
const unproven: ExprSchemaHint = { ...CONDITION, bareNamesUnproven: true };
1475+
expect(verdicts('title > 5 && record.due_date + 1 > 5', unproven).map((v) => [v.code, v.params])).toEqual([[
1476+
'date-arithmetic-run-fails',
1477+
{ operands: 'google.protobuf.Timestamp + int', reference: 'record.due_date' },
1478+
]]);
1479+
});
1480+
});

‎packages/formula/src/validate.ts‎

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ import {
2424
firstDateTextVerdict,
2525
firstTypeMismatch,
2626
inferCelType,
27-
recordRootReadsFaultDateArith,
2827
RECORD_ROOT_READ_RE,
2928
parseCelToAst,
3029
parseCelToAstWithReason,
@@ -920,18 +919,23 @@ const DATE_TEXT_FAMILY_RE = /^date-text-(?:call|arithmetic)(?:-|$)/;
920919
* root read, left `dyn`, checked clean. Typed here with every field's type
921920
* (a flow variable shadows a bare name, never a root member), every bare name
922921
* `dyn`, the same verdict, code and words come back, naming the read as
923-
* written. The order is the bare name's own: there {@link firstTypeMismatch}
924-
* answers `date-arith` when the Timestamp typing's first fault is date/duration
925-
* arithmetic against a number, and the date-text check is asked only once it
926-
* answers null. So the pass stands down exactly where the roots' first
927-
* Timestamp-typing fault is that shape (`record.due_date + 1`, the
928-
* `date-arithmetic` family's, {@link recordRootReadsFaultDateArith}), and on no
929-
* other fault: `record.due_date - record.borrow_date > 3` (a Duration ordered
930-
* against a number) and an expression that orders a date field against a text
931-
* literal before it calls `timestamp()` are judged, as their bare spellings
932-
* are. Only `date-text-call*` / `date-text-arithmetic*` are kept. The outcome arm is
933-
* the row's: a root read keeps the declared outcome whatever binds the bare
934-
* names (#30025), so `bareNamesUnproven` is not asked.
922+
* written. The order is the bare name's own: the date-text check is asked
923+
* only once {@link firstTypeMismatch} answers null, and this pass is reached
924+
* only there, so it never stands down on a shape that check answers (its
925+
* record-root pass answers `record.due_date + 1` under `date-arith`, #34946).
926+
* [#36377] Nor on any other: the roots' own Timestamp typing meeting date
927+
* arithmetic first is no answer. `due_date > "2026-01-01" && record.due_date + 1 > 5`
928+
* orders the bare name against a text literal first, which the runtime answers
929+
* and {@link firstTypeMismatch} stands down on for the bare name and the root
930+
* pass alike, so it answers null and the arithmetic on the root read faults on
931+
* every run; judged here it takes the `date-text-arithmetic` verdict its all-bare
932+
* and all-root spellings take. `record.due_date - record.borrow_date > 3` (a
933+
* Duration ordered against a number) and an expression that orders a date
934+
* field against a text literal before it calls `timestamp()` are judged, as
935+
* their bare spellings are. Only `date-text-call*` / `date-text-arithmetic*`
936+
* are kept. The outcome arm is the row's: a root read keeps the declared
937+
* outcome whatever binds the bare names (#30025), so `bareNamesUnproven` is
938+
* not asked.
935939
*/
936940
function recordRootDateTextIssue(
937941
source: string,
@@ -941,7 +945,6 @@ function recordRootDateTextIssue(
941945
faultOutcome: ExprSchemaHint['faultOutcome'],
942946
): { issue: ExprValidationError; severity: 'error' | 'warning' } | null {
943947
if (!RECORD_ROOT_READ_RE.test(source) || !Object.values(celFieldTypes).includes('timestamp')) return null;
944-
if (recordRootReadsFaultDateArith(source, celFieldTypes)) return null;
945948
const dateOnly = new Set(Object.keys(celFieldTypes).filter((name) => fieldTypes[name] === 'date'));
946949
const found = dateTextIssue(source, {}, 'flattened', role, dateArm('flattened', faultOutcome, false), dateOnly, celFieldTypes);
947950
return found && DATE_TEXT_FAMILY_RE.test(found.issue.code) ? found : null;

‎packages/lint/src/validate-expressions.test.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7100,6 +7100,59 @@ describe('validateStackExpressions — a flow condition\'s record. / previous. r
71007100
});
71017101
});
71027102

7103+
// [#36377] A flow CONDITION that orders the BARE date name against a text
7104+
// literal before it does arithmetic on the field's `record.` / `previous.`
7105+
// read got zero findings, while its all-bare and all-root spellings were
7106+
// refused, and it fails every run on the `YYYY-MM-DD` text. It now takes the
7107+
// all-root spelling's finding, at the same path and severity.
7108+
describe('validateStackExpressions — a bare date ordering before date arithmetic on a record. / previous. read is refused (#36377)', () => {
7109+
const LOAN = {
7110+
name: 'library_loan',
7111+
fields: { due_date: { type: 'date', required: true }, picked_up_at: { type: 'datetime', required: true } },
7112+
};
7113+
type Site = 'start' | 'edge' | 'decision';
7114+
const stackWith = (site: Site, condition: string) => ({
7115+
objects: [LOAN],
7116+
flows: [{
7117+
name: 'loan_due',
7118+
nodes: [
7119+
{
7120+
id: 'start', type: 'start',
7121+
config: { objectName: 'library_loan', triggerType: 'record-after-update', ...(site === 'start' ? { condition } : {}) },
7122+
},
7123+
...(site === 'decision'
7124+
? [{ id: 'gate', type: 'decision', config: { conditions: [{ label: 'Due', expression: condition }] } }]
7125+
: []),
7126+
{ id: 'end', type: 'end' },
7127+
],
7128+
edges: site === 'decision'
7129+
? [{ id: 'e1', source: 'start', target: 'gate' }, { id: 'e2', source: 'gate', target: 'end' }]
7130+
: [{ id: 'e1', source: 'start', target: 'end', ...(site === 'edge' ? { condition } : {}) }],
7131+
}],
7132+
});
7133+
const shape = (issues: ExprIssue[]) => issues.map((i) => [i.severity, i.path ?? i.where, i.message]);
7134+
7135+
it.each(['start', 'edge', 'decision'] as const)(
7136+
'refuses the mixed spelling in a %s condition with the all-root spelling\'s finding',
7137+
(site) => {
7138+
for (const [root, field, op] of [
7139+
['record', 'due_date', '+ 1'], ['previous', 'due_date', '- 7'], ['record', 'picked_up_at', '+ 1'],
7140+
] as const) {
7141+
const allRoot = validateStackExpressions(stackWith(site, `${root}.${field} > "2026-01-01" && ${root}.${field} ${op} > 5`));
7142+
expect(allRoot.map((i) => i.severity), `${site}: ${root}.${field}`).toEqual(['error']);
7143+
const mixed = `${field} > "2026-01-01" && ${root}.${field} ${op} > 5`;
7144+
expect(shape(validateStackExpressions(stackWith(site, mixed))), `${site}: ${mixed}`).toEqual(shape(allRoot));
7145+
}
7146+
},
7147+
);
7148+
7149+
it('CONTROL: the same bare ordering before an ordering of the root read against today() stays clean', () => {
7150+
for (const site of ['start', 'edge', 'decision'] as const) {
7151+
expect(validateStackExpressions(stackWith(site, 'due_date > "2026-01-01" && record.due_date < today()')), site).toEqual([]);
7152+
}
7153+
});
7154+
});
7155+
71037156
/**
71047157
* [ADR-0113 D1, as amended] A `required` field's own `visibleWhen` decides its
71057158
* requirement on the write, and a predicate the server cannot evaluate counts

‎packages/runtime/src/domains/meta-flow-condition-record-date-text.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,3 +205,43 @@ describe('[#34946] the flow publish door refuses date arithmetic on a date field
205205
expect(await rig.state('loan_due_ordering')).toEqual(['active']);
206206
}, 60_000);
207207
});
208+
209+
/**
210+
* [#36377] The flow publish door refuses a condition that orders the BARE date
211+
* name against a text literal before it does arithmetic on the field's
212+
* `record.` / `previous.` read. The business case: an administrator publishes a
213+
* record-triggered flow on a loan that runs for loans due this year and a day
214+
* past due (`due_date > "2026-01-01" && record.due_date + 1 > 5`, the date
215+
* written as if it were a number). The run holds the field as its `YYYY-MM-DD`
216+
* text and the evaluator cannot add a number to it, so the flow fails on every
217+
* run; the door refused the all-bare and all-`record.` spellings and published
218+
* the mixed one. Now all three are refused, in the same finding.
219+
*/
220+
describe('[#36377] the flow publish door refuses a bare date ordering before date arithmetic on a record. / previous. read', () => {
221+
/** The door's date-arithmetic findings (both families) on a refused publish. */
222+
const dateArithmeticIssues = (err: any) =>
223+
(err?.issues ?? []).filter((i: any) => i.rule === 'expression-invalid' && /^date arithmetic/.test(i.message));
224+
225+
it('⭐ LIT — refuses the mixed spelling with INVALID_METADATA / 422 and the all-root spelling\'s words, leaving the draft', async () => {
226+
const rig = await boot();
227+
for (const [root, op] of [['record', '+ 1'], ['previous', '- 7']] as const) {
228+
const allRoot: any = await rig.publish(flowOn(`loan_all_${root}`, `${root}.due_date > "2026-01-01" && ${root}.due_date ${op} > 5`));
229+
const name = `loan_mixed_${root}`;
230+
const err: any = await rig.publish(flowOn(name, `due_date > "2026-01-01" && ${root}.due_date ${op} > 5`));
231+
expect(err, `${root}: the publish was admitted`).toBeInstanceOf(Error);
232+
expect({ code: err.code, status: err.status }, root).toEqual({ code: 'INVALID_METADATA', status: 422 });
233+
const issues = dateArithmeticIssues(err);
234+
expect(issues, `${root}: ${JSON.stringify(err.issues)}`).toHaveLength(1);
235+
expect(issues[0].message).toContain(`— \`${root}.due_date\` is a date field, and the runtime holds`);
236+
expect(issues.map((i: any) => i.message), root).toEqual(dateArithmeticIssues(allRoot).map((i: any) => i.message));
237+
expect(await rig.state(name), root).toEqual(['draft']);
238+
}
239+
}, 60_000);
240+
241+
it('⭐ CONTROL — the same bare ordering before an ordering of the root read against today() publishes', async () => {
242+
const rig = await boot();
243+
const err = await rig.publish(flowOn('loan_mixed_ordering', 'due_date > "2026-01-01" && record.due_date < today()'));
244+
expect(err?.issues ?? err, 'the door refused').toBeUndefined();
245+
expect(await rig.state('loan_mixed_ordering')).toEqual(['active']);
246+
}, 60_000);
247+
});

0 commit comments

Comments
 (0)