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
26 changes: 26 additions & 0 deletions .changeset/34946-flow-record-date-arithmetic.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
'@objectstack/formula': minor
'@objectstack/spec': minor
---

fix(formula)!: a flow condition that does date arithmetic on `record.FIELD` or `previous.FIELD` is now refused, as the bare field name already was

Clause-②: no (narrowing)
Metadata-protocol: narrowed

<!-- adr-0087: registered flow-condition-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`. The date-arithmetic check judged only the bare name: `due_date + 1 > 5` over a `date` field was refused, but `record.due_date + 1 > 5` passed `os validate` and the publish door. The flow then failed on every run, because a date field reaches the run as its `YYYY-MM-DD` text and the evaluator cannot add a number to it.

- **The verdict.** A `record.FIELD` / `previous.FIELD` read of a `date` or `datetime` field in arithmetic against a number now gets the verdict its bare name gets, with the same code and outcome arm (`date-arithmetic-run-fails` on a record-triggered flow or a sweep of the typed object, `date-arithmetic-run-may-fail` elsewhere). A root read keeps the row's arm where bare names are unproven or a flow variable shadows the bare name. The message names the read as written and prescribes `daysBetween(a, b)` or `addDays(d, n)`.
- **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, as it does for the bare name, and still registers the flow, so a stored flow keeps its run-time behaviour until it is next published.
- **Not refused.** An ordering of the field (`record.due_date < today()`), `daysBetween` / `addDays` over it, and the date-text shapes, which keep their own verdicts. Formula fields and validation rules read `record.FIELD` already and were refused before. The run-time evaluator is unchanged.

## FROM → TO

| FROM | TO |
|:---|:---|
| `record.due_date + 1 > 5` | `daysBetween(record.due_date, today()) > 5` (days past due) or `addDays(record.due_date, 1) < today()` (a shifted date) |
| `previous.due_date - 7 < today()` | `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`; use `daysBetween(a, b)` for a span and `addDays(d, n)` to shift a date.
28 changes: 22 additions & 6 deletions packages/formula/src/cel-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1339,7 +1339,10 @@ export function firstTypeMismatch(
operands: string;
celType: FieldCelType;
field: string | null;
/** [#29959] Set when a flattened condition's mismatch is a `record.<field>` / `previous.<field>` read. */
/**
* [#29959, #34946] Set when a flattened condition's mismatch (`type-mismatch`
* or `date-arith`) is a `record.<field>` / `previous.<field>` read.
*/
root?: 'record' | 'previous';
category: 'date-arith' | 'type-mismatch';
} | null {
Expand Down Expand Up @@ -1419,12 +1422,24 @@ export function firstTypeMismatch(
}
// [#29959] A flattened condition reads the same field as `record.<field>`
// (and `previous.<field>`), which the bare typing above leaves `dyn`. A
// second pass types those roots too, for the text/boolean mismatch only:
// the same verdict the bare name gets. The `date-arith` verdict stays the
// bare name's alone, as before; the date-text family reaches the roots
// through `validate.ts`'s record-root pass (#34662).
// second pass types those roots too, for the verdicts the bare name gets
// here: the text/boolean mismatch, and (#34946) date/duration arithmetic
// 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}).
if (scope !== 'flattened' || !RECORD_ROOT_READ_RE.test(source)) return null;
const rootTyped = unsoundOverload(buildTypedEnv(bareTypes, 'flattened', 'timestamp', fieldCelTypes));
if (rootTyped && isDateArith(rootTyped)) {
const read = offendingRecordRead(source, fieldCelTypes, 'timestamp');
return {
operator: rootTyped[2], operands: `${rootTyped[1]} ${rootTyped[2]} ${rootTyped[3]}`,
celType: 'timestamp', category: 'date-arith',
field: read?.field ?? null,
...(read ? { root: read.root } : {}),
};
}
const r = rootTyped && textOrBool(rootTyped) ? confirmAgainstDateText(rootTyped, fieldCelTypes) : null;
const celType = r ? textOrBool(r) : null;
if (!r || !celType) return null;
Expand Down Expand Up @@ -1595,7 +1610,8 @@ export function firstDateTextVerdict(
* 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 and the date-text check is never asked. Any other
* 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
Expand Down
85 changes: 84 additions & 1 deletion packages/formula/src/validate.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { describe, it, expect } from 'vitest';
import {
validateExpression,
type ExprSchemaHint,
introspectScope,
expectedDialect,
inferExpressionType,
nearestName,
CEL_STDLIB_FUNCTIONS,
} from './validate';
import { buildEnv, firstUndeclaredReference, SCOPE_ROOTS } from './cel-engine';
import { buildEnv, celEngine, firstUndeclaredReference, SCOPE_ROOTS } from './cel-engine';

describe('validateExpression (ADR-0032)', () => {
describe('predicates (CEL)', () => {
Expand Down Expand Up @@ -1328,3 +1329,85 @@ describe('inferExpressionType — coarse value-type of a formula', () => {
expect(inferExpressionType('record')).toBe('unknown');
});
});

// [#34946] A flow condition reads the run's row bare AND through `record.` /
// `previous.` (#29959), and the date-arithmetic verdict (#3306) judged only the
// bare name: `due_date + 1 > 5` was refused while `record.due_date + 1 > 5`
// passed with no finding, and both fault on the `YYYY-MM-DD` text on every run.
// The root read now takes the bare name's verdict, code and arm, naming the
// read as written.
describe('a flow condition\'s record.<field> / previous.<field> read takes the date-arithmetic verdict as its bare name does (#34946)', () => {
/** A record-triggered flow's condition over a loan: the hint `@objectstack/lint` hands a start, edge or decision condition. */
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 }));
/** What the run binds: the row under `record` (and `previous`), and its fields flattened bare. */
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 date arithmetic on a date field through record. and previous. under the bare name\'s code, naming the read', () => {
expect(verdicts('due_date + 1 > 5')).toEqual([{
code: 'date-arithmetic-run-fails',
params: { operands: 'google.protobuf.Timestamp + int', reference: 'due_date' },
}]);
expect(run('due_date + 1 > 5')).toMatchObject({ ok: false });
for (const root of ['record', 'previous'] as const) {
const source = `${root}.due_date + 1 > 5`;
const errors = errorsOf(source);
expect(errors.map((e) => ({ code: e.code, params: e.params })), source).toEqual([{
code: 'date-arithmetic-run-fails',
params: { operands: 'google.protobuf.Timestamp + int', reference: `${root}.due_date` },
}]);
expect(errors[0].message, source).toContain(`date arithmetic \`google.protobuf.Timestamp + int\` — \`${root}.due_date\` is a date`);
expect(errors[0].message, source).toContain('a flow condition that cannot be evaluated fails the run');
// The run faults on the date-only text, exactly as the bare spelling does.
expect(run(source), source).toMatchObject({ ok: false });
}
});

it('CONTROL: a datetime field\'s root reads take exactly the bare name\'s verdict', () => {
const [bare] = verdicts('picked_up_at + 1 > 5');
expect(bare).toEqual({
code: 'date-arithmetic-run-fails',
params: { operands: 'google.protobuf.Timestamp + int', reference: 'picked_up_at' },
});
for (const root of ['record', 'previous'] as const) {
const source = `${root}.picked_up_at + 1 > 5`;
expect(verdicts(source), source).toEqual([{ ...bare, params: { ...bare.params, reference: `${root}.picked_up_at` } }]);
}
});

it('takes the row\'s outcome arm: run-may-fail where none is declared, run-fails kept when bare names are unproven or shadowed', () => {
const undeclared: ExprSchemaHint = { ...CONDITION, faultOutcome: undefined };
expect(codes('due_date + 1 > 5', undeclared)).toEqual(['date-arithmetic-run-may-fail']);
expect(codes('record.due_date + 1 > 5', undeclared)).toEqual(['date-arithmetic-run-may-fail']);
expect(errorsOf('record.due_date + 1 > 5', undeclared)[0].message)
.toContain('this faults wherever `record.due_date` holds the date when the condition runs');
// A node that can bind a name no reader sees moves a bare name's arm, never a root read's.
const unproven: ExprSchemaHint = { ...CONDITION, bareNamesUnproven: true };
expect(codes('due_date + 1 > 5', unproven)).toEqual(['date-arithmetic-run-may-fail']);
expect(codes('record.due_date + 1 > 5', unproven)).toEqual(['date-arithmetic-run-fails']);
// A flow variable holding the bare name is not the field; the root read still is.
const shadowed: ExprSchemaHint = { ...CONDITION, flowVariables: ['due_date'] };
expect(codes('due_date + 1 > 5', shadowed)).toEqual([]);
expect(codes('previous.due_date + 1 > 5', shadowed)).toEqual(['date-arithmetic-run-fails']);
});

it('CONTROL: an ordering against today() and the date-text shapes keep their verdicts, with no second finding', () => {
for (const source of [
'record.due_date < today()', 'previous.due_date < today()', 'date(record.due_date) < now()',
// The rewrites the verdict prescribes (the changeset's FROM → TO).
'daysBetween(record.due_date, today()) > 5', 'addDays(record.due_date, 1) < today()', 'addDays(previous.due_date, -7) < today()',
]) {
expect(validateExpression('predicate', source, CONDITION), source).toEqual({ ok: true, errors: [], warnings: [] });
}
expect(codes('timestamp(record.borrow_date) < now()')).toEqual(['date-text-call-run-fails']);
expect(codes('record.due_date - record.borrow_date > 3')).toEqual(['date-text-arithmetic-run-fails']);
expect(codes("record.due_date - record.borrow_date > duration('24h')")).toEqual(['date-text-arithmetic-run-fails']);
// The text/boolean mismatch the record-root pass already reported is unchanged.
expect(codes('record.title > 5')).toEqual(['type-mismatch-run-fails']);
});
});
8 changes: 6 additions & 2 deletions packages/formula/src/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -519,7 +519,8 @@ const DATE_FAIL_CLOSED_CLAUSE =
* (`date − date + 1`, `today() + 30`) — always faults at runtime and never
* recovers, so it blocks the build. A formula reads that fault as null; a
* flattened (flow) condition's fault fails the run, under the
* `date-arithmetic-run-fails` / `-run-may-fail` codes (#30016), a
* `date-arithmetic-run-fails` / `-run-may-fail` codes (#30016) — its
* `record.<field>` / `previous.<field>` read as its bare name (#34946) — a
* fail-closed site's refuses the write, under `date-arithmetic-fail-closed`
* (#30250), and an advisory rule's skips the rule, under
* `date-arithmetic-fail-open` (#30494, {@link dateArm}).
Expand Down Expand Up @@ -596,7 +597,10 @@ function typeSoundnessIssue(
const use =
`Use \`daysBetween(a, b)\` for the span in whole days, and \`daysFromNow(n)\` / ` +
`\`addDays(d, n)\` / \`addMonths(d, n)\` to shift a date.`;
const arm = dateArm(scope, faultOutcome, bareNamesUnproven);
// [#34946] A `record.<field>` / `previous.<field>` read keeps the row's
// outcome whatever binds the bare names (#30025), as its type mismatch and
// its date-text verdicts do ({@link recordRootDateTextIssue}).
const arm = dateArm(scope, faultOutcome, mismatch.root !== undefined ? false : bareNamesUnproven);
return {
severity: 'error',
issue: arm
Expand Down
84 changes: 84 additions & 0 deletions packages/lint/src/validate-expressions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6966,6 +6966,90 @@ describe('validateStackExpressions — a flow condition\'s record. / previous. r
});
});

// [#34946] A flow CONDITION reads the run's row through `record.<field>` /
// `previous.<field>` as well as through the flattened bare name, and the
// date-arithmetic verdict judged only the bare name: `record.due_date + 1 > 5`
// got zero findings and fails every run on the `YYYY-MM-DD` text, while
// `due_date + 1 > 5` was refused. The root read now takes the same finding,
// at the same path and severity, under the same rule.
describe('validateStackExpressions — a flow condition\'s record. / previous. read takes the date-arithmetic verdict (#34946)', () => {
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 at = (issues: ExprIssue[]) => issues.map((i) => [i.severity, i.path ?? i.where]);

it.each(['start', 'edge', 'decision'] as const)(
'refuses date arithmetic on a date field through record. and previous. in a %s condition, as its bare name is',
(site) => {
const bare = validateStackExpressions(stackWith(site, 'due_date + 1 > 5'));
expect(at(bare)).toHaveLength(1);
expect(bare[0].severity).toBe('error');
expect(bare[0].message.startsWith('date arithmetic `google.protobuf.Timestamp + int` — `due_date` is a date')).toBe(true);
for (const root of ['record', 'previous']) {
const source = `${root}.due_date + 1 > 5`;
const issues = validateStackExpressions(stackWith(site, source));
expect(at(issues), source).toEqual(at(bare));
expect(issues[0].message, source).toBe(bare[0].message.replace('`due_date`', `\`${root}.due_date\``));
}
},
);

it('reports it under the expression rule id, as the bare name is', () => {
for (const source of ['due_date + 1 > 5', 'record.due_date + 1 > 5', 'previous.due_date + 1 > 5']) {
const stack = stackWith('start', source);
// The minimal fixture draws other rules' findings (region shape, sharing); this one's is the date arithmetic's.
const findings = runAuthoringRules('build', { normalized: stack, parsed: stack } as never)
.filter((f) => /^date arithmetic/.test(f.message));
expect(findings.map((f) => [f.rule, f.severity]), source).toEqual([[EXPRESSION_INVALID, 'error']]);
}
});

it('CONTROL: a datetime field\'s root reads take exactly the bare name\'s finding', () => {
for (const site of ['start', 'edge', 'decision'] as const) {
const bare = validateStackExpressions(stackWith(site, 'picked_up_at + 1 > 5'));
for (const root of ['record', 'previous']) {
const source = `${root}.picked_up_at + 1 > 5`;
const issues = validateStackExpressions(stackWith(site, source));
expect(at(issues), `${site}: ${source}`).toEqual(at(bare));
expect(issues.map((i) => i.message), `${site}: ${source}`)
.toEqual(bare.map((i) => i.message.replace('`picked_up_at`', `\`${root}.picked_up_at\``)));
}
}
});

it('CONTROL: an ordering against today() stays clean, and timestamp() over the date keeps its one date-text finding', () => {
for (const site of ['start', 'edge', 'decision'] as const) {
for (const root of ['record', 'previous']) {
expect(validateStackExpressions(stackWith(site, `${root}.due_date < today()`)), `${site}: ${root}`).toEqual([]);
const dateText = validateStackExpressions(stackWith(site, `timestamp(${root}.due_date) < now()`));
expect(dateText.map((i) => i.severity), `${site}: ${root}`).toEqual(['error']);
expect(dateText[0].message).toContain(`\`timestamp(${root}.due_date)\` — \`${root}.due_date\` is a date field`);
}
}
});
});

/**
* [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