Skip to content
Merged
27 changes: 27 additions & 0 deletions .changeset/34662-flow-record-date-text.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
---
'@objectstack/formula': minor
---

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

Clause-②: no (narrowing)
Metadata-protocol: narrowed
Skills-docs: none — `skills/objectstack-formula/SKILL.md` already states the `date-text-call` rule (a `date` / `datetime` field handed to a timestamp-only call, and `timestamp()` over a `date` field) with `record.FIELD` spellings and names no site it is limited to, so it now holds for a flow condition's root reads as written

<!-- adr-0087: not-required (already-registered formula-timestamp-date-only-refused, formula-date-text-call-refused, formula-date-subtraction-refused) The three semantic entries already carry these verdicts, their codes and their rewrites to the upgrade guide, and each entry's surface already names flow conditions among the CEL predicates judged with the object's field types, with record.FIELD spellings as its examples. This change makes that text true for a flow condition that reads the field through record or previous, where only the bare field name was judged before; the verdicts, codes, rewrites and acceptance criteria are the entries' own. No id is added, no key is added, removed or re-shaped, and nothing an author wrote is rewritten. -->

**BREAKING** accept-set narrowing, shipped as `minor`. 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-text checks judged only the bare name. `timestamp(borrow_date) < now()` over a `date` field was refused, but `timestamp(record.borrow_date) < now()` 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, which `timestamp()` does not parse.

- **The verdicts.** A `record.FIELD` / `previous.FIELD` read in a flow condition now gets the date-text checks its bare name gets, with the same code and outcome arm (`date-text-call-run-fails` / `date-text-arithmetic-run-fails` on a record-triggered flow or a sweep of the typed object, `-run-may-fail` elsewhere). The message names the read as written and prescribes `date(record.FIELD)`, or `isoDate(addDays(record.FIELD, N))` to shift by whole days. This covers the calls the text cannot take (`timestamp(record.FIELD)` over a `date` field, `isoDate(record.FIELD)` over a `date` or `datetime` field) and arithmetic on the text (`record.end_date - record.start_date`).
- **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 running until it is next published.
- **Not refused.** `timestamp()` over a `datetime` field. A shape the Timestamp typing already faults on (`record.due_date + 1`), which is another verdict's. An `input.FIELD` read. The run-time evaluator is unchanged.

## FROM → TO

| FROM | TO |
|:---|:---|
| `timestamp(record.borrow_date) < now()` | `date(record.borrow_date) < now()` |
| `timestamp(previous.borrow_date) < now()` | `date(previous.borrow_date) < now()` |
| `isoDate(record.picked_up_at) == '2026-11-16'` | `isoDate(date(record.picked_up_at)) == '2026-11-16'` |

One-line fix: in a flow condition, parse a date field with `date(record.FIELD)` before comparing it with a timestamp, never `timestamp(record.FIELD)`.
108 changes: 89 additions & 19 deletions packages/formula/src/cel-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1255,6 +1255,14 @@ function withoutNames(
return out;
}

/**
* [#29959, #34662] A `record.` / `previous.` read spelled member-wise — the gate
* of every flattened record-root pass ({@link firstTypeMismatch}'s and
* `validate.ts`'s date-text one), so the two can never disagree on whether a
* source reads a root.
*/
export const RECORD_ROOT_READ_RE = /(?<![\w$.])(?:record|previous)\s*\./;

/**
* [#29959] The `record.<field>` / `previous.<field>` read of a field of
* `celType` in a flattened condition, as written — what
Expand Down Expand Up @@ -1408,9 +1416,10 @@ 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 verdicts stay the bare
// name's alone, as before.
if (scope !== 'flattened' || !/(?<![\w$.])(?:record|previous)\s*\./.test(source)) return null;
// 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).
if (scope !== 'flattened' || !RECORD_ROOT_READ_RE.test(source)) return null;
const rootTyped = unsoundOverload(buildTypedEnv(bareTypes, 'flattened', 'timestamp', fieldCelTypes));
const r = rootTyped && textOrBool(rootTyped) ? confirmAgainstDateText(rootTyped, fieldCelTypes) : null;
const celType = r ? textOrBool(r) : null;
Expand Down Expand Up @@ -1510,10 +1519,15 @@ function registerDateTextAnswersOnString(env: Environment): void {
* answer, so the expression faults and the field reads null;
* - `type` — the expression checks clean, and `type` is the CEL type it
* computes (`google.protobuf.Duration` for `today() - record.start_date`).
* `root` is set on the flattened record-root pass (`recordRootTypes`, #34662)
* when `field` is named by its `record.<field>` / `previous.<field>` read.
*/
export type DateTextVerdict =
| { readonly kind: 'fault'; readonly operator: string; readonly operands: string; readonly field: string | null }
| { readonly kind: 'type'; readonly type: string; readonly field: string | null };
| {
readonly kind: 'fault'; readonly operator: string; readonly operands: string; readonly field: string | null;
readonly root?: 'record' | 'previous';
}
| { readonly kind: 'type'; readonly type: string; readonly field: string | null; readonly root?: 'record' | 'previous' };

/**
* #28944 — type-check `source` with every `date`/`datetime` field declared as
Expand All @@ -1535,32 +1549,73 @@ export type DateTextVerdict =
* Returns `null` when the source does not parse, or the check faults on
* anything other than arithmetic with a date field's text — that is another
* check's to report, and this one never guesses.
*
* [#34662] `recordRootTypes` (flattened scope only) types a flow condition's
* `record.<field>` / `previous.<field>` reads as well, the record-root pass
* {@link firstTypeMismatch} runs for the text/boolean mismatch: the field is
* then named by its root read (`root`) wherever one is spelled member-wise.
*/
export function firstDateTextVerdict(
source: string,
fieldCelTypes: Readonly<Record<string, FieldCelType>>,
scope: 'record' | 'flattened' = 'record',
recordRootTypes?: Readonly<Record<string, FieldCelType>>,
): DateTextVerdict | null {
if (typeof source !== 'string' || !source.trim()) return null;
const rootTypes = scope === 'flattened' ? recordRootTypes : undefined;
try {
const env = buildTypedEnv(fieldCelTypes, scope, 'date-text');
const env = buildTypedEnv(fieldCelTypes, scope, 'date-text', rootTypes);
const result = env.parse(rewriteNullableTernary(rewriteIndexedHas(source))).check?.() as
| { valid?: boolean; type?: unknown; error?: { message?: string } }
| undefined;
if (!result) return null;
const field = offendingField(source, fieldCelTypes, 'timestamp', scope);
const read = rootTypes ? offendingRecordRead(source, rootTypes, 'timestamp') : null;
const named = read
? { field: read.field, root: read.root }
: { field: offendingField(source, fieldCelTypes, 'timestamp', scope) };
if (result.valid !== false) {
return typeof result.type === 'string' ? { kind: 'type', type: result.type, field } : null;
return typeof result.type === 'string' ? { kind: 'type', type: result.type, ...named } : null;
}
const m = UNSOUND_OVERLOAD_RE.exec(result.error?.message ?? '');
if (!m || !ARITH_OPS.has(m[2]) || (m[1] !== DATE_TEXT_CEL_TYPE && m[3] !== DATE_TEXT_CEL_TYPE)) return null;
return { kind: 'fault', operator: m[2], operands: `${m[1]} ${m[2]} ${m[3]}`, field };
return { kind: 'fault', operator: m[2], operands: `${m[1]} ${m[2]} ${m[3]}`, ...named };
} catch {
// A parse/other fault is the syntax checker's job (celEngine.compile).
return null;
}
}

/**
* [#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 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 Expand Up @@ -1622,24 +1677,39 @@ export interface DateTextCall {
* wrap the field for, so the rewrite is `date(<field>)` in place of the call,
* and `shift` carries the whole-day shift the stdlib teaches,
* `isoDate(addDays(<field>, N))`, which reads the date text as it is.
*
* [#34662] `recordRootTypes` (flattened scope only): a flow condition's
* `record.<field>` / `previous.<field>` reads are typed with these, as
* {@link firstDateTextVerdict}'s record-root pass types them, and a root read
* qualifies by them alone (an `input.<field>` read then does not qualify: a
* flow does not bind `input` to the row the types describe). Absent, every
* reference is judged by `fieldCelTypes`, exactly as before.
*/
export function firstDateTextCall(
source: string,
fieldCelTypes: Readonly<Record<string, FieldCelType>>,
scope: 'record' | 'flattened' = 'record',
dateOnlyFields: ReadonlySet<string> = new Set(),
recordRootTypes?: Readonly<Record<string, FieldCelType>>,
): DateTextCall | null {
if (typeof source !== 'string' || !source.trim()) return null;
const dateFields: Record<string, FieldCelType> = {};
let any = false;
for (const [name, t] of Object.entries(fieldCelTypes)) {
dateFields[name] = t === 'timestamp' ? 'timestamp' : 'dyn';
any ||= t === 'timestamp';
}
const textTyping = (types: Readonly<Record<string, FieldCelType>>): Record<string, FieldCelType> =>
Object.fromEntries(Object.entries(types).map(([name, t]) => [name, t === 'timestamp' ? 'timestamp' : 'dyn']));
const dateFields = textTyping(fieldCelTypes);
const rootDateFields = scope === 'flattened' && recordRootTypes ? textTyping(recordRootTypes) : undefined;
/** The date-text typing a reference is judged by: its root's, on the record-root pass. */
const typingOf = (written: string): Record<string, FieldCelType> | undefined => {
if (!rootDateFields) return dateFields;
const root = written.includes('.') ? written.slice(0, written.indexOf('.')) : undefined;
return root === undefined ? dateFields : root === 'record' || root === 'previous' ? rootDateFields : undefined;
};
const isDate = (name: string, types: Record<string, FieldCelType> | undefined): boolean =>
types?.[name] === 'timestamp';
const any = [dateFields, rootDateFields].some((types) => types && Object.values(types).includes('timestamp'));
if (!any) return null;
const anyDateOnly = [...dateOnlyFields].some((name) => dateFields[name] === 'timestamp');
const anyDateOnly = [...dateOnlyFields].some((name) => isDate(name, dateFields) || isDate(name, rootDateFields));
try {
const env = buildTypedEnv(dateFields, scope, 'text');
const env = buildTypedEnv(dateFields, scope, 'text', rootDateFields);
const parsed = env.parse(rewriteNullableTernary(rewriteIndexedHas(source)));
// The whole expression checking clean is the common case: nothing to find,
// unless a date-only field can reach `timestamp()`, which checks clean.
Expand All @@ -1655,7 +1725,7 @@ export function firstDateTextCall(
};
const dateRef = (node: unknown): string | null => {
const ref = typedFieldRef(node, scope);
return ref && dateFields[ref.name] === 'timestamp' ? ref.written : null;
return ref && isDate(ref.name, typingOf(ref.written)) ? ref.written : null;
};
let verdict: DateTextCall | null = null;
const visit = (v: unknown): void => {
Expand All @@ -1672,7 +1742,7 @@ export function firstDateTextCall(
// [#34363] `timestamp(<date-only field>)`: clean on the text, faults on it.
if (v.op === 'call' && Array.isArray(args) && args[0] === 'timestamp' && operands?.length === 1) {
const ref = typedFieldRef(operands[0], scope);
if (ref && dateFields[ref.name] === 'timestamp' && dateOnlyFields.has(ref.name)) {
if (ref && isDate(ref.name, typingOf(ref.written)) && dateOnlyFields.has(ref.name)) {
const rewrite = wrapInDate(operands[0] as CelNode);
if (checkOf(rewrite) === true) {
verdict = {
Expand Down
Loading
Loading