Skip to content

Commit 97b9d1e

Browse files
fix(formula)!: a flow condition's record. / previous. date arithmetic is refused as its bare name is (#36333)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1X8UqWLrzTYpuat8L5eLdf2c)_ Fixes #34946 Clause-②: no (narrowing) Metadata-protocol: narrowed Skills-docs: none — `skills/objectstack-formula/SKILL.md` already states "No date arithmetic. The build refuses `date + n` and `end - start`" and names no site it is limited to, so it now holds for a flow condition's `record.FIELD` / `previous.FIELD` reads as written repo:objectstack#4 · os-project-manager · session_01FEkQ5pb2t8Z8C64PkPyVt1 ## 维护者速读 - 用户能看到什么变化:作者在校验或发布流程时,若流程条件通过「当前记录」或「修改前记录」读取日期字段并直接加减数字,现在会和直接写字段名一样被拒,并提示改用按天计算的函数;以前这种写法能通过校验,运行时却每次失败。 - 为什么做:属于「表达式校验与作者护栏」,替编写流程的管理员和代写流程的 AI 助手解决「校验通过、流程每次运行都出错」的问题,与已修好的日期文本同类问题是同一族。 - 出错会怎样:若误判,作者在校验或发布流程时会看到一条拒绝;已保存的流程照常加载、照常注册,只在下次发布时要求改写;本改动可整体撤回。 - 要你做什么:这是收紧已接受写法的破坏性变更,需要你本人审阅、批准并亲手合并。L1 ACCEPT 7076562103,全量测试 0 失败 7076550688,契约 PASS 7076631700(座位 7,head f278fec);一个不阻塞的遗留写法(main 上同样存在,不是回归)和三个小问题另立 #36377 跟进。 ## What changes A flow condition (start, edge, `decision` branch) is evaluated over a scope where the run's row is bound twice: its fields flattened to bare names, and the row itself as `record` (with the row before the write as `previous`). The date-arithmetic verdict typed the bare names only. `firstTypeMismatch`'s flattened record-root pass typed `record.FIELD` / `previous.FIELD` but kept only the text/boolean mismatch, so `record.due_date + 1 > 5` passed while `due_date + 1 > 5` was refused, and both fault at run time on the `YYYY-MM-DD` text on every run. Measured through `validateStackExpressions` (the `os validate` body) on a record-triggered flow (`record-after-update`), object `library_loan` with `due_date: date` and `picked_up_at: datetime` (both `required`), start condition: | start condition | before (`origin/main` 28ba01f) | after (this head) | |:---|:---|:---| | `due_date + 1 > 5` | 1 error, date arithmetic `google.protobuf.Timestamp + int`, `due_date` | 1 error (unchanged) | | `record.due_date + 1 > 5` | 0 | 1 error, same verdict, `record.due_date` named | | `previous.due_date + 1 > 5` | 0 | 1 error, same verdict, `previous.due_date` named | | `picked_up_at + 1 > 5` (CONTROL, datetime) | 1 error, `picked_up_at` | 1 error (unchanged) | | `record.picked_up_at + 1 > 5` (CONTROL) | 0 | 1 error, matching the bare name | | `previous.picked_up_at + 1 > 5` (CONTROL) | 0 | 1 error, matching the bare name | | `record.due_date < today()` (CONTROL) | 0 | 0 | | `timestamp(record.due_date) < now()` (CONTROL, date-text) | 1 error, date-text call | 1 error (unchanged, no second finding) | The datetime control: a `datetime` field is a Timestamp in the type check exactly as a `date` field is, and its bare name already took the date-arithmetic verdict, so its root reads now take that verdict too, word for word with the reference swapped. That is the dispatch's control ("keep whatever verdict the bare name gets for a datetime"). - `packages/formula/src/cel-engine.ts`, `firstTypeMismatch`: the record-root pass now answers `category: 'date-arith'` when its first operator fault is date/duration arithmetic against a number (`isDateArith`), with `field` and `root` from `offendingRecordRead(…, 'timestamp')`. The text/boolean branch is unchanged. The comment that said the `date-arith` verdict "stays the bare name's alone" is corrected, and the `root` field's doc and `recordRootReadsFaultDateArith`'s doc say the root read is answered there too. - `packages/formula/src/validate.ts`, `typeSoundnessIssue`: a root read's date verdict takes the row's arm (`dateArm` with `bareNamesUnproven` false), as the root read's type mismatch (#30025) and date-text verdicts (`recordRootDateTextIssue`) already do. So `record.due_date + 1 > 5` stays `date-arithmetic-run-fails` where bare names are unproven or a flow variable shadows `due_date`. The bare name's arm is unchanged. - No double report: `recordRootDateTextIssue` runs only when `firstTypeMismatch` answers null, and it already stood down on this exact shape (`recordRootReadsFaultDateArith`). The #34662 date-text pins are green and unchanged. - `packages/spec/src/migrations/entries/semantic/18.flow-condition-record-date-arithmetic-refused.ts`: the ADR-0087 semantic entry (a structured TODO; no mechanical rewrite, since a span in days and a shifted date are different intents), modelled on `18.cel-list-equality-refused.ts`. - `.changeset/34946-flow-record-date-arithmetic.md`: `minor` for `@objectstack/formula` and `@objectstack/spec` (`Metadata-protocol: narrowed` grades `minor`; spec ships the new ADR-0087 entry in its generated migration registry), the declaration lines, the **BREAKING** banner, a FROM to TO table, and `adr-0087: registered flow-condition-record-date-arithmetic-refused`. Reach (the dispatch asked to stop if the narrowing reached beyond flow conditions): the flattened scope is used only by flow conditions. `@objectstack/lint` passes it for start, edge and `decision` conditions, `@objectstack/service-automation`'s `registerFlow` (advisory only) and the MCP `validate_expression` tool's `flow_condition` site. Formula fields, validation rules, hooks and actions are `record`-scoped, where `record.due_date + 1` was already refused (`date-arithmetic`, `-fail-closed`, `-fail-open`). No widening was needed. ## Tests - `packages/formula/src/validate.test.ts`, new top-level describe (#34946): `record.` and `previous.` date arithmetic refused under `date-arithmetic-run-fails` with full params (`operands`, `reference` naming the read), and the evaluator faults on them over the run's scope. CONTROL: the datetime field's root reads equal the bare name's verdict. Arms: `run-may-fail` with no declared outcome, `run-fails` kept on a root read when bare names are unproven or shadowed. CONTROL: `record.due_date < today()`, `previous.due_date < today()`, `date(record.due_date) < now()` and the prescribed rewrites (`daysBetween(record.due_date, today()) > 5`, `addDays(record.due_date, 1) < today()`, `addDays(previous.due_date, -7) < today()`) are clean. The date-text shapes keep their one finding (`date-text-call-run-fails`, `date-text-arithmetic-run-fails`) and `record.title > 5` keeps `type-mismatch-run-fails`. - `packages/lint/src/validate-expressions.test.ts`, new top-level describe: start, edge and `decision` conditions refuse `record.` / `previous.` at the bare name's path and severity, with the bare name's message and the reference swapped. Reported under `expression-invalid` through `runAuthoringRules('build', …)`, the rule body the runtime publish door runs. CONTROL: datetime root reads equal the bare name's findings at all three sites; `record.due_date < today()` stays clean; `timestamp(record.due_date) < now()` keeps exactly one date-text finding. - `packages/services/service-automation/src/flow-registration-schema-e2e.test.ts`, new top-level describe: `registerFlow` logs the date-arithmetic advisory for `record.` / `previous.` as for the bare name and still registers. CONTROL: an ordering against `today()` is not advised. - `packages/runtime/src/domains/meta-flow-condition-record-date-text.test.ts`, new top-level describe (#34946, added at `f278fece6f`): the publish door (`publishMetaItem` over the real `ObjectQL` engine) refuses the bare name, `record.due_date` and `previous.due_date` date arithmetic with `INVALID_METADATA` / 422 and one date-arithmetic issue naming the read, leaving the item draft. CONTROL: a datetime field's root reads take the same refusal; `record.due_date < today()` publishes and goes active. The loan fixture gains one required `date` field `due_date`. Runs at `f278fece6f`: 4/4 passed; ablating the cel-engine record-root `isDateArith` branch turns exactly the 2 new tests red, restored to the HEAD blob with `git diff HEAD` empty and `ablation-dist-preflight --absent` clean. Publish door, first measured on head 4426723 as a scratch copy of the same rig (now committed as the pin above): | start condition | publish | date-arithmetic finding | row state | |:---|:---|:---|:---| | `due_date + 1 > 5` | `INVALID_METADATA` / 422 | `expression-invalid`, `due_date` | draft | | `record.due_date + 1 > 5` | `INVALID_METADATA` / 422 | `expression-invalid`, `record.due_date` | draft | | `previous.due_date + 1 > 5` | `INVALID_METADATA` / 422 | `expression-invalid`, `previous.due_date` | draft | | `picked_up_at + 1 > 5` (CONTROL) | `INVALID_METADATA` / 422 | `expression-invalid`, `picked_up_at` | draft | | `record.picked_up_at + 1 > 5` (CONTROL) | `INVALID_METADATA` / 422 | `expression-invalid`, `record.picked_up_at` | draft | | `previous.picked_up_at + 1 > 5` (CONTROL) | `INVALID_METADATA` / 422 | `expression-invalid`, `previous.picked_up_at` | draft | | `record.due_date < today()` (CONTROL) | published | none | active | At `f278fece6f` (the patch round: changeset regrade and the runtime pin): runtime pin 4/4 and its ablation as above; `dispatch-gates --commands` 98 families derived (one more than at 4426723: `check:route-envelope`); the families for the changed paths (`check-adr-0087-registration`, `check-changeset-no-major`, `check-empty-changeset`, `check:cross-package-test-inputs`, `check:test-source-alias`, `check:tier-file-adoption`, `check:route-envelope`) exit 0; `overlap-check` clean. The runs below and the dogfood battery are from 4426723; the patch round changed only the changeset and a runtime test file. <details><summary>Local runs (head 4426723)</summary> All under `scripts/pm/os-verify-lock.sh`, exit codes captured before any pipe: - `pnpm --filter @objectstack/formula build` exit 0; `pnpm --filter @objectstack/formula test` exit 0, Test Files 70 passed (70), Tests 2067 passed (2067); `pnpm --filter @objectstack/formula typecheck` exit 0 (test layer: 7 errors held in `test-typecheck-debt.json`, unchanged). - `pnpm --filter @objectstack/lint exec vitest run --maxWorkers=2 src/validate-expressions.test.ts` exit 0, Tests 529 passed (529). - `pnpm --filter @objectstack/service-automation exec vitest run --maxWorkers=2 src/flow-registration-schema-e2e.test.ts` exit 0, Tests 7 passed (7). - `pnpm --filter @objectstack/spec exec vitest run --maxWorkers=2 src/migrations` exit 0, Test Files 5 passed (5), Tests 198 passed (198) (spec built with the new entry; `gen:migration-registry` runs in its build). - `node scripts/pm/dispatch-gates.mjs --commands` derived 97 families for this diff; all 97 run locally, reconciled with `--ran`: "97 derived, 97 run, 0 NOT-MEASURED, 0 UNRUN". `pnpm check:dual-build-cjs-loads` first answered PREREQUISITE NOT MET (exit 3, no full build yet), then exit 0 after `check:type-check-debt` built the tree; every other family exit 0 on the first run. - Dogfood battery (the `!` title), on head 4426723: `pnpm --filter @objectstack/dogfood test` under the lock, VERDICT command-exit 0, Test Files 484 passed, 3 skipped (487), Tests 4107 passed, 68 skipped (4175), no failure. - `test:repo` (vitest `repo` project) not run locally: the diff touches none of its tests; it is CI's (`Test Core`). </details> <details><summary>Ablations (each committed first, mutated through scripts/ablation-replace.mjs, restored to the HEAD blob)</summary> 1. Subject: the new `isDateArith` branch of the record-root pass (`packages/formula/src/cel-engine.ts`). Anchor `if (rootTyped && isDateArith(rootTyped)) {` replaced by a never-true guard carrying `ABLATED_34946` (anchor 1 to 0, blob `8eb099d83f32` to `4975d5dd3077`), formula rebuilt, `ablation-dist-preflight.mjs @objectstack/formula ABLATED_34946` exit 0 (the marker reached `dist/`, which the lint and service-automation suites read). Red: formula `validate.test.ts` 3 failed / 236 passed (the three #34946 verdict tests; the CONTROL for orderings and date-text stayed green), lint 5 failed / 524 passed (all five non-ordering #34946 tests), service-automation 1 failed / 6 passed (the advisory test). Restored: blob back to `8eb099d83f32` = `HEAD:packages/formula/src/cel-engine.ts`, `git diff HEAD` empty, rebuilt, preflight `--absent` exit 0, lint 529/529 again. 2. Subject: the root read's arm in `typeSoundnessIssue` (`packages/formula/src/validate.ts`). Anchor `dateArm(scope, faultOutcome, mismatch.root !== undefined ? false : bareNamesUnproven)` replaced by `dateArm(scope, faultOutcome, bareNamesUnproven ...)` (blob `aeedf005910e` to `b35d7d64bb2a`). Red: formula `validate.test.ts` 1 failed / 146 passed, the arm test (`record.due_date + 1 > 5` under unproven bare names). Restored: blob `aeedf005910e` = HEAD, `git diff HEAD` empty, 147/147. </details> ## Acceptance notes - Kept as before, deliberately: where bare names are unproven and a source holds both a bare-name date-arithmetic fault and a root-read one (`due_date + 1 > 5 && record.due_date + 1 > 5`), the first (bare) verdict is reported, at `date-arithmetic-run-may-fail`. Still an error; the swap-to-the-root-read step `typeSoundnessIssue` does for a bare type mismatch was not extended to the date verdict. - The field a multi-date expression names is best effort, as for the bare name: `offendingRecordRead` names the first `timestamp` field read through a root, in field-map order. - Declarations follow the two closest precedents in this family (#34935, #36207): `Metadata-protocol: narrowed` with a `minor` changeset (regraded at `f278fece6f`). - Carried by #36377: contract review 7076631700 S1 (a bare date ordering against text AND-ed before a `record.` date arithmetic still passes; measured first on that card) and nits N1–N3. ## Verification Read first, by risk: 1. `packages/formula/src/cel-engine.ts`, the new `isDateArith` branch of `firstTypeMismatch`'s record-root pass (the narrowing itself). 2. `packages/formula/src/validate.ts`, the `dateArm` call in `typeSoundnessIssue` (the root read's arm). 3. `packages/spec/src/migrations/entries/semantic/18.flow-condition-record-date-arithmetic-refused.ts` (the upgrade-guide text). Two-minute check: `pnpm --filter @objectstack/formula exec vitest run --maxWorkers=2 src/validate.test.ts -t 34946` shows 4 passing tests. --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5pb2t8Z8C64PkPyVt1)_ <!-- signed: repo:objectstack#4 · os-project-manager · session_01FEkQ5krBqrrgxCYgjXmfbv --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 7b9e229 commit 97b9d1e

8 files changed

Lines changed: 386 additions & 9 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
'@objectstack/formula': minor
3+
'@objectstack/spec': minor
4+
---
5+
6+
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
7+
8+
Clause-②: no (narrowing)
9+
Metadata-protocol: narrowed
10+
11+
<!-- adr-0087: registered flow-condition-record-date-arithmetic-refused -->
12+
13+
**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.
14+
15+
- **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)`.
16+
- **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.
17+
- **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.
18+
19+
## FROM → TO
20+
21+
| FROM | TO |
22+
|:---|:---|
23+
| `record.due_date + 1 > 5` | `daysBetween(record.due_date, today()) > 5` (days past due) or `addDays(record.due_date, 1) < today()` (a shifted date) |
24+
| `previous.due_date - 7 < today()` | `addDays(previous.due_date, -7) < today()` |
25+
26+
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.

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

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1339,7 +1339,10 @@ export function firstTypeMismatch(
13391339
operands: string;
13401340
celType: FieldCelType;
13411341
field: string | null;
1342-
/** [#29959] Set when a flattened condition's mismatch is a `record.<field>` / `previous.<field>` read. */
1342+
/**
1343+
* [#29959, #34946] Set when a flattened condition's mismatch (`type-mismatch`
1344+
* or `date-arith`) is a `record.<field>` / `previous.<field>` read.
1345+
*/
13431346
root?: 'record' | 'previous';
13441347
category: 'date-arith' | 'type-mismatch';
13451348
} | null {
@@ -1419,12 +1422,24 @@ export function firstTypeMismatch(
14191422
}
14201423
// [#29959] A flattened condition reads the same field as `record.<field>`
14211424
// (and `previous.<field>`), which the bare typing above leaves `dyn`. A
1422-
// second pass types those roots too, for the text/boolean mismatch only:
1423-
// the same verdict the bare name gets. The `date-arith` verdict stays the
1424-
// bare name's alone, as before; the date-text family reaches the roots
1425-
// through `validate.ts`'s record-root pass (#34662).
1425+
// second pass types those roots too, for the verdicts the bare name gets
1426+
// here: the text/boolean mismatch, and (#34946) date/duration arithmetic
1427+
// against a number — `record.due_date + 1` faults on the field's text on
1428+
// every run exactly as `due_date + 1` does. Either names the read as
1429+
// 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}).
14261432
if (scope !== 'flattened' || !RECORD_ROOT_READ_RE.test(source)) return null;
14271433
const rootTyped = unsoundOverload(buildTypedEnv(bareTypes, 'flattened', 'timestamp', fieldCelTypes));
1434+
if (rootTyped && isDateArith(rootTyped)) {
1435+
const read = offendingRecordRead(source, fieldCelTypes, 'timestamp');
1436+
return {
1437+
operator: rootTyped[2], operands: `${rootTyped[1]} ${rootTyped[2]} ${rootTyped[3]}`,
1438+
celType: 'timestamp', category: 'date-arith',
1439+
field: read?.field ?? null,
1440+
...(read ? { root: read.root } : {}),
1441+
};
1442+
}
14281443
const r = rootTyped && textOrBool(rootTyped) ? confirmAgainstDateText(rootTyped, fieldCelTypes) : null;
14291444
const celType = r ? textOrBool(r) : null;
14301445
if (!r || !celType) return null;
@@ -1595,7 +1610,8 @@ export function firstDateTextVerdict(
15951610
* name `dyn`) is date/duration arithmetic against a number ({@link isDateArith})
15961611
* — `record.due_date + 1`. That shape is the `date-arithmetic` family's, and it
15971612
* is exactly where the bare name's own order stops: {@link firstTypeMismatch}
1598-
* answers `date-arith` there and the date-text check is never asked. Any other
1613+
* answers `date-arith` there (for the root read too, #34946) and the date-text
1614+
* check is never asked. Any other
15991615
* Timestamp-typing fault — `record.end_date - record.start_date > 3` (a Duration
16001616
* ordered against a number), `record.d >= "2026-01-01"` (the text ordering the
16011617
* runtime answers) — leaves the bare name's mismatch check at null and the

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

Lines changed: 84 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
import { describe, it, expect } from 'vitest';
22
import {
33
validateExpression,
4+
type ExprSchemaHint,
45
introspectScope,
56
expectedDialect,
67
inferExpressionType,
78
nearestName,
89
CEL_STDLIB_FUNCTIONS,
910
} from './validate';
10-
import { buildEnv, firstUndeclaredReference, SCOPE_ROOTS } from './cel-engine';
11+
import { buildEnv, celEngine, firstUndeclaredReference, SCOPE_ROOTS } from './cel-engine';
1112

1213
describe('validateExpression (ADR-0032)', () => {
1314
describe('predicates (CEL)', () => {
@@ -1328,3 +1329,85 @@ describe('inferExpressionType — coarse value-type of a formula', () => {
13281329
expect(inferExpressionType('record')).toBe('unknown');
13291330
});
13301331
});
1332+
1333+
// [#34946] A flow condition reads the run's row bare AND through `record.` /
1334+
// `previous.` (#29959), and the date-arithmetic verdict (#3306) judged only the
1335+
// bare name: `due_date + 1 > 5` was refused while `record.due_date + 1 > 5`
1336+
// passed with no finding, and both fault on the `YYYY-MM-DD` text on every run.
1337+
// The root read now takes the bare name's verdict, code and arm, naming the
1338+
// read as written.
1339+
describe('a flow condition\'s record.<field> / previous.<field> read takes the date-arithmetic verdict as its bare name does (#34946)', () => {
1340+
/** A record-triggered flow's condition over a loan: the hint `@objectstack/lint` hands a start, edge or decision condition. */
1341+
const fieldTypes = { title: 'text', borrow_date: 'date', due_date: 'date', picked_up_at: 'datetime' };
1342+
const CONDITION: ExprSchemaHint = { scope: 'flattened', fields: Object.keys(fieldTypes), fieldTypes, faultOutcome: 'run-fails' };
1343+
const errorsOf = (source: string, hint: ExprSchemaHint = CONDITION) => validateExpression('predicate', source, hint).errors;
1344+
const codes = (source: string, hint: ExprSchemaHint = CONDITION) => errorsOf(source, hint).map((e) => e.code);
1345+
const verdicts = (source: string, hint: ExprSchemaHint = CONDITION) =>
1346+
errorsOf(source, hint).map((e) => ({ code: e.code, params: e.params }));
1347+
/** What the run binds: the row under `record` (and `previous`), and its fields flattened bare. */
1348+
const ROW = { title: 'Dune', borrow_date: '2026-11-16', due_date: '2026-11-30', picked_up_at: '2026-11-16T09:30:00.000Z' };
1349+
const run = (source: string) => celEngine.evaluate({ dialect: 'cel', source }, { ...ROW, record: ROW, previous: ROW });
1350+
1351+
it('refuses date arithmetic on a date field through record. and previous. under the bare name\'s code, naming the read', () => {
1352+
expect(verdicts('due_date + 1 > 5')).toEqual([{
1353+
code: 'date-arithmetic-run-fails',
1354+
params: { operands: 'google.protobuf.Timestamp + int', reference: 'due_date' },
1355+
}]);
1356+
expect(run('due_date + 1 > 5')).toMatchObject({ ok: false });
1357+
for (const root of ['record', 'previous'] as const) {
1358+
const source = `${root}.due_date + 1 > 5`;
1359+
const errors = errorsOf(source);
1360+
expect(errors.map((e) => ({ code: e.code, params: e.params })), source).toEqual([{
1361+
code: 'date-arithmetic-run-fails',
1362+
params: { operands: 'google.protobuf.Timestamp + int', reference: `${root}.due_date` },
1363+
}]);
1364+
expect(errors[0].message, source).toContain(`date arithmetic \`google.protobuf.Timestamp + int\` — \`${root}.due_date\` is a date`);
1365+
expect(errors[0].message, source).toContain('a flow condition that cannot be evaluated fails the run');
1366+
// The run faults on the date-only text, exactly as the bare spelling does.
1367+
expect(run(source), source).toMatchObject({ ok: false });
1368+
}
1369+
});
1370+
1371+
it('CONTROL: a datetime field\'s root reads take exactly the bare name\'s verdict', () => {
1372+
const [bare] = verdicts('picked_up_at + 1 > 5');
1373+
expect(bare).toEqual({
1374+
code: 'date-arithmetic-run-fails',
1375+
params: { operands: 'google.protobuf.Timestamp + int', reference: 'picked_up_at' },
1376+
});
1377+
for (const root of ['record', 'previous'] as const) {
1378+
const source = `${root}.picked_up_at + 1 > 5`;
1379+
expect(verdicts(source), source).toEqual([{ ...bare, params: { ...bare.params, reference: `${root}.picked_up_at` } }]);
1380+
}
1381+
});
1382+
1383+
it('takes the row\'s outcome arm: run-may-fail where none is declared, run-fails kept when bare names are unproven or shadowed', () => {
1384+
const undeclared: ExprSchemaHint = { ...CONDITION, faultOutcome: undefined };
1385+
expect(codes('due_date + 1 > 5', undeclared)).toEqual(['date-arithmetic-run-may-fail']);
1386+
expect(codes('record.due_date + 1 > 5', undeclared)).toEqual(['date-arithmetic-run-may-fail']);
1387+
expect(errorsOf('record.due_date + 1 > 5', undeclared)[0].message)
1388+
.toContain('this faults wherever `record.due_date` holds the date when the condition runs');
1389+
// A node that can bind a name no reader sees moves a bare name's arm, never a root read's.
1390+
const unproven: ExprSchemaHint = { ...CONDITION, bareNamesUnproven: true };
1391+
expect(codes('due_date + 1 > 5', unproven)).toEqual(['date-arithmetic-run-may-fail']);
1392+
expect(codes('record.due_date + 1 > 5', unproven)).toEqual(['date-arithmetic-run-fails']);
1393+
// A flow variable holding the bare name is not the field; the root read still is.
1394+
const shadowed: ExprSchemaHint = { ...CONDITION, flowVariables: ['due_date'] };
1395+
expect(codes('due_date + 1 > 5', shadowed)).toEqual([]);
1396+
expect(codes('previous.due_date + 1 > 5', shadowed)).toEqual(['date-arithmetic-run-fails']);
1397+
});
1398+
1399+
it('CONTROL: an ordering against today() and the date-text shapes keep their verdicts, with no second finding', () => {
1400+
for (const source of [
1401+
'record.due_date < today()', 'previous.due_date < today()', 'date(record.due_date) < now()',
1402+
// The rewrites the verdict prescribes (the changeset's FROM → TO).
1403+
'daysBetween(record.due_date, today()) > 5', 'addDays(record.due_date, 1) < today()', 'addDays(previous.due_date, -7) < today()',
1404+
]) {
1405+
expect(validateExpression('predicate', source, CONDITION), source).toEqual({ ok: true, errors: [], warnings: [] });
1406+
}
1407+
expect(codes('timestamp(record.borrow_date) < now()')).toEqual(['date-text-call-run-fails']);
1408+
expect(codes('record.due_date - record.borrow_date > 3')).toEqual(['date-text-arithmetic-run-fails']);
1409+
expect(codes("record.due_date - record.borrow_date > duration('24h')")).toEqual(['date-text-arithmetic-run-fails']);
1410+
// The text/boolean mismatch the record-root pass already reported is unchanged.
1411+
expect(codes('record.title > 5')).toEqual(['type-mismatch-run-fails']);
1412+
});
1413+
});

‎packages/formula/src/validate.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -535,7 +535,8 @@ const DATE_FAIL_CLOSED_CLAUSE =
535535
* (`date − date + 1`, `today() + 30`) — always faults at runtime and never
536536
* recovers, so it blocks the build. A formula reads that fault as null; a
537537
* flattened (flow) condition's fault fails the run, under the
538-
* `date-arithmetic-run-fails` / `-run-may-fail` codes (#30016), a
538+
* `date-arithmetic-run-fails` / `-run-may-fail` codes (#30016) — its
539+
* `record.<field>` / `previous.<field>` read as its bare name (#34946) — a
539540
* fail-closed site's refuses the write, under `date-arithmetic-fail-closed`
540541
* (#30250), and an advisory rule's skips the rule, under
541542
* `date-arithmetic-fail-open` (#30494, {@link dateArm}).
@@ -612,7 +613,10 @@ function typeSoundnessIssue(
612613
const use =
613614
`Use \`daysBetween(a, b)\` for the span in whole days, and \`daysFromNow(n)\` / ` +
614615
`\`addDays(d, n)\` / \`addMonths(d, n)\` to shift a date.`;
615-
const arm = dateArm(scope, faultOutcome, bareNamesUnproven);
616+
// [#34946] A `record.<field>` / `previous.<field>` read keeps the row's
617+
// outcome whatever binds the bare names (#30025), as its type mismatch and
618+
// its date-text verdicts do ({@link recordRootDateTextIssue}).
619+
const arm = dateArm(scope, faultOutcome, mismatch.root !== undefined ? false : bareNamesUnproven);
616620
return {
617621
severity: 'error',
618622
issue: arm

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

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6966,6 +6966,90 @@ describe('validateStackExpressions — a flow condition\'s record. / previous. r
69666966
});
69676967
});
69686968

6969+
// [#34946] A flow CONDITION reads the run's row through `record.<field>` /
6970+
// `previous.<field>` as well as through the flattened bare name, and the
6971+
// date-arithmetic verdict judged only the bare name: `record.due_date + 1 > 5`
6972+
// got zero findings and fails every run on the `YYYY-MM-DD` text, while
6973+
// `due_date + 1 > 5` was refused. The root read now takes the same finding,
6974+
// at the same path and severity, under the same rule.
6975+
describe('validateStackExpressions — a flow condition\'s record. / previous. read takes the date-arithmetic verdict (#34946)', () => {
6976+
const LOAN = {
6977+
name: 'library_loan',
6978+
fields: { due_date: { type: 'date', required: true }, picked_up_at: { type: 'datetime', required: true } },
6979+
};
6980+
type Site = 'start' | 'edge' | 'decision';
6981+
const stackWith = (site: Site, condition: string) => ({
6982+
objects: [LOAN],
6983+
flows: [{
6984+
name: 'loan_due',
6985+
nodes: [
6986+
{
6987+
id: 'start', type: 'start',
6988+
config: { objectName: 'library_loan', triggerType: 'record-after-update', ...(site === 'start' ? { condition } : {}) },
6989+
},
6990+
...(site === 'decision'
6991+
? [{ id: 'gate', type: 'decision', config: { conditions: [{ label: 'Due', expression: condition }] } }]
6992+
: []),
6993+
{ id: 'end', type: 'end' },
6994+
],
6995+
edges: site === 'decision'
6996+
? [{ id: 'e1', source: 'start', target: 'gate' }, { id: 'e2', source: 'gate', target: 'end' }]
6997+
: [{ id: 'e1', source: 'start', target: 'end', ...(site === 'edge' ? { condition } : {}) }],
6998+
}],
6999+
});
7000+
const at = (issues: ExprIssue[]) => issues.map((i) => [i.severity, i.path ?? i.where]);
7001+
7002+
it.each(['start', 'edge', 'decision'] as const)(
7003+
'refuses date arithmetic on a date field through record. and previous. in a %s condition, as its bare name is',
7004+
(site) => {
7005+
const bare = validateStackExpressions(stackWith(site, 'due_date + 1 > 5'));
7006+
expect(at(bare)).toHaveLength(1);
7007+
expect(bare[0].severity).toBe('error');
7008+
expect(bare[0].message.startsWith('date arithmetic `google.protobuf.Timestamp + int` — `due_date` is a date')).toBe(true);
7009+
for (const root of ['record', 'previous']) {
7010+
const source = `${root}.due_date + 1 > 5`;
7011+
const issues = validateStackExpressions(stackWith(site, source));
7012+
expect(at(issues), source).toEqual(at(bare));
7013+
expect(issues[0].message, source).toBe(bare[0].message.replace('`due_date`', `\`${root}.due_date\``));
7014+
}
7015+
},
7016+
);
7017+
7018+
it('reports it under the expression rule id, as the bare name is', () => {
7019+
for (const source of ['due_date + 1 > 5', 'record.due_date + 1 > 5', 'previous.due_date + 1 > 5']) {
7020+
const stack = stackWith('start', source);
7021+
// The minimal fixture draws other rules' findings (region shape, sharing); this one's is the date arithmetic's.
7022+
const findings = runAuthoringRules('build', { normalized: stack, parsed: stack } as never)
7023+
.filter((f) => /^date arithmetic/.test(f.message));
7024+
expect(findings.map((f) => [f.rule, f.severity]), source).toEqual([[EXPRESSION_INVALID, 'error']]);
7025+
}
7026+
});
7027+
7028+
it('CONTROL: a datetime field\'s root reads take exactly the bare name\'s finding', () => {
7029+
for (const site of ['start', 'edge', 'decision'] as const) {
7030+
const bare = validateStackExpressions(stackWith(site, 'picked_up_at + 1 > 5'));
7031+
for (const root of ['record', 'previous']) {
7032+
const source = `${root}.picked_up_at + 1 > 5`;
7033+
const issues = validateStackExpressions(stackWith(site, source));
7034+
expect(at(issues), `${site}: ${source}`).toEqual(at(bare));
7035+
expect(issues.map((i) => i.message), `${site}: ${source}`)
7036+
.toEqual(bare.map((i) => i.message.replace('`picked_up_at`', `\`${root}.picked_up_at\``)));
7037+
}
7038+
}
7039+
});
7040+
7041+
it('CONTROL: an ordering against today() stays clean, and timestamp() over the date keeps its one date-text finding', () => {
7042+
for (const site of ['start', 'edge', 'decision'] as const) {
7043+
for (const root of ['record', 'previous']) {
7044+
expect(validateStackExpressions(stackWith(site, `${root}.due_date < today()`)), `${site}: ${root}`).toEqual([]);
7045+
const dateText = validateStackExpressions(stackWith(site, `timestamp(${root}.due_date) < now()`));
7046+
expect(dateText.map((i) => i.severity), `${site}: ${root}`).toEqual(['error']);
7047+
expect(dateText[0].message).toContain(`\`timestamp(${root}.due_date)\` — \`${root}.due_date\` is a date field`);
7048+
}
7049+
}
7050+
});
7051+
});
7052+
69697053
/**
69707054
* [ADR-0113 D1, as amended] A `required` field's own `visibleWhen` decides its
69717055
* requirement on the write, and a predicate the server cannot evaluate counts

0 commit comments

Comments
 (0)