diff --git a/.changeset/38959-flow-condition-verdicts.md b/.changeset/38959-flow-condition-verdicts.md new file mode 100644 index 00000000000..bafdc2bc29d --- /dev/null +++ b/.changeset/38959-flow-condition-verdicts.md @@ -0,0 +1,31 @@ +--- +'@objectstack/formula': minor +'@objectstack/spec': minor +--- + +fix(formula)!: a date-text fault is no longer hidden behind a type-mismatch warning, a text or boolean field read by index (`record['FIELD']`) takes the type-mismatch verdict, and a macro variable ordered against a text literal is no longer refused + +Clause-②: no (narrowing) +Metadata-protocol: narrowed +Skills-docs: none — `skills/objectstack-formula/SKILL.md` rule 5 already states "The build refuses date arithmetic (`end - start`, `date + n`)" and refuses a `date` / `datetime` field in a timestamp-only call, with no exception for a source that also carries a type mismatch; no skill teaches the index spelling, the type-mismatch warning, or ordering a macro variable over date fields + + + +**BREAKING** accept-set narrowing. A flow condition that faults fails the run. Two shapes that published and then failed every run are refused: + +- **A date-text fault behind a type-mismatch warning.** The authoring check reported one finding per source and asked the text / boolean type mismatch first; the date-text check was asked only when that answered nothing. Where the mismatch is a warning, `due_date - borrow_date > duration('1h') && record.title > 5` and `record.active > 5 && isoDate(picked_up_at) == 'x'` published with the warning alone. The more severe verdict now wins: the date-text error is reported instead of the warning, also when the mismatch comes first in the source. The mismatch is a warning, so the change reaches: a flow condition on a flow that is not record-triggered (`date-text-arithmetic-run-may-fail`, `date-text-call-run-may-fail`); a flow condition whose bare name a node can rebind (`bareNamesUnproven`: `date-text-arithmetic-run-fails` / `date-text-call-run-fails` over a `record.FIELD` read, the `-run-may-fail` codes over a bare one); and every record-scoped site that declares no fault outcome (`date-text-arithmetic`, `date-text-call`): a formula field `expression`, a field `visibleWhen` / `settledWhen` / `uiReadonlyWhen`, a field `conditionalFormatting[].condition`, a field group `visibleWhen`, an action `visible` / `disabled` / `pressed`, a sharing rule `condition`, and the object `uiReadonlyWhen`. Where the mismatch is an error already (a record-triggered flow, a sweep of the typed object, a site with a declared fault outcome) it keeps its code. +- **A type mismatch through an index read.** `record['title'] > 5`, `record['active'] + 1 > 3`, `previous['title'] > 5`, `record['title'] > record['active']` passed while their member spellings were judged: a text or boolean field read by index under an arithmetic or ordering operator the run has no overload for (against a number or a boolean), which faults on every row. An index read of `record` / `previous` now takes the text / boolean type-mismatch verdict its member spelling takes (`type-mismatch-run-fails`, `-sweep-run-fails`, or the `-run-may-fail` warning), named as its member spelling is named: by the member spelling, also where a member read sits beside it (`record['title'] > 5 && record.status == 'open'` names `record.title` and takes `type-mismatch-run-fails` under `bareNamesUnproven`, as `record.title > 5 && record.status == 'open'` does; before, it took the warning, and `record['title'] > 5 && record.notes == 'n'` named `record.notes`). Stated limit, carried by #39105: the name is the first field of the faulting type in the field table that the source reads, in either spelling, which need not be the operand (`previous.notes > 5 && record['title'] == 'x'` names `record.title`; it named `previous.notes`). The date-text verdicts an index read took before keep their codes. An ordering of a date read against a text field, which the run answers, with either side read by index keeps the verdict it had: unjudged where no member read is in the source (`record['due_date'] > record['title']`), otherwise the mismatch kept as before, named only by a member read, so under `bareNamesUnproven` it stays the `type-mismatch-run-may-fail` warning (`record.due_date > record['title']`, `record['due_date'] > record['title'] && record.status == 'open'`, `record.due_date > title && record['notes'] == 'n'`). + +Widened in the same change, for flow conditions and record-scoped sites only: a variable a macro binds (`exists`, `all`, `exists_one`, `map`, `filter`) is typed as an element of the list it ranges over, so `[due_date, record.borrow_date].exists(d, d > '2026-01-01')`, which the runtime answers, is no longer refused as a type mismatch; `[title].exists(t, t > 5)` stays refused. A flow value envelope (an `assignment` value, a `create_record` / `update_record` `fields.*` value) keeps the verdict it had: its date-text check stands down where the mismatch check finds a mismatch and asks that check with the macro typing it had before, so `[record.due_date].exists(d, d > '2026-01-01') ? isoDate(record.picked_up_at) : 'x'` as a value registers and validates as it did. That envelope shape is carried by #39107. + +- **Where.** `os validate` / `os build` report an `error`, and a door that runs the same expression pass refuses the write (the flow publish door with `INVALID_METADATA`, 422). For flow conditions `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; no flow value envelope verdict changes, so no stored flow that registered before is refused at registration. The run-time evaluator is unchanged. + +## FROM → TO + +| FROM | TO | +|:---|:---| +| `due_date - borrow_date > duration('1h') && record.title > 5` | `daysBetween(borrow_date, due_date) >= 1 && size(record.title) > 5` | +| `record['title'] > 5` | `size(record['title']) > 5` | +| `record['active'] + 1 > 3` | `record['active'] == true` | + +One-line fix: compare like with like in a flow condition, whichever way a field is spelled; use `size(…)` / `double(…)` to make text a number, `true` / `false` for a boolean, and `daysBetween(a, b)` / `addDays(d, n)` / `date(…)` for a date. diff --git a/packages/formula/src/cel-engine.ts b/packages/formula/src/cel-engine.ts index beb41752562..5d7e1f17546 100644 --- a/packages/formula/src/cel-engine.ts +++ b/packages/formula/src/cel-engine.ts @@ -1003,15 +1003,26 @@ const DATE_TEXT_COMPARISON_OPS: ReadonlySet = new Set([...ORDERING_OPS, * named by none of them, so the comparison keeps the type-mismatch verdict * the Timestamp typing gave it. Each operand's type is read off `env` (the * date-text typing the caller confirmed against) by checking that operand on - * its own; an operand that reads a variable an enclosing macro binds + * its own. [#38959] An operand that reads a variable an enclosing macro binds * (`all`, `exists`, `exists_one`, `map`, `filter`) proves nothing on its own * — in a flattened condition it checks as `dyn`, in record scope not at all — - * so a comparison with one keeps the verdict too, in both scopes. A `dyn` - * counterpart that is not such a variable (a flow variable) is not judged - * here: the Timestamp typing never faulted on it. Unparseable ⇒ `true`: keep - * what the check said. - */ -function comparesDateTextAgainstUndeclared(source: string, env: Environment): boolean { + * so the variable is read as what it ranges over: an element of the macro's + * receiver, `receiver[0]`, checked in the same env. `[due_date, + * record.borrow_date].exists(d, d > '2026-01-01')` orders a date field's text + * against a text literal, as `due_date > '2026-01-01'` does, and the runtime + * answers it; `[due_date].exists(d, d > title)` orders it against a text + * field and keeps the verdict, as `due_date > title` does. Where that element + * does not check (the receiver is no list the env can type), the comparison + * keeps the verdict, as before. A `dyn` counterpart that is not such a + * variable (a flow variable) is not judged here: the Timestamp typing never + * faulted on it. Unparseable ⇒ `true`: keep what the check said. + * + * `macroElements: false` keeps the typing before #38959 (a comparison reading + * a macro variable keeps the verdict): the flow value envelope's stand-down + * gate asks for it, so its answer is the one it gave before (see + * {@link firstTypeMismatch}'s `options`). + */ +function comparesDateTextAgainstUndeclared(source: string, env: Environment, macroElements = true): boolean { let ast: unknown; try { ast = env.parse(rewriteNullableTernary(rewriteIndexedHas(source))).ast; @@ -1035,41 +1046,85 @@ function comparesDateTextAgainstUndeclared(source: string, env: Environment): bo const declared = (node: unknown, type: string | undefined): boolean => type === DATE_TEXT_CEL_TYPE || type === 'google.protobuf.Timestamp' || type === 'dyn' || isTextLiteral(node) || isNullLiteral(node); - /** Whether `node` reads one of the macro-bound variable names in `bound`. */ - const readsBound = (node: unknown, bound: ReadonlySet): boolean => { - if (bound.size === 0) return false; + /** A macro (`list.exists(x, …)`): `rcall` [name, receiver, [variable, …body]] — its parts, or `null`. */ + const macroOf = (v: CelNode): { receiver: unknown; name: string | null; body: unknown[] } | null => { + const args = v.args; + if (v.op !== 'rcall' || !Array.isArray(args) || args.length !== 3 || !Array.isArray(args[2]) + || !COMPREHENSION_MACRO_NAMES.has(String(args[0]))) return null; + const [variable, ...body] = args[2] as unknown[]; + const name = isCelNode(variable) && variable.op === 'id' && typeof variable.args === 'string' ? variable.args : null; + return { receiver: args[1], name, body }; + }; + /** + * [#38959] `node` with each read of a macro-bound variable in `bound` + * replaced by the element it ranges over (`bound`'s value), and whether any + * was. A macro inside `node` that binds the same name shadows it there. + */ + const substitute = (node: unknown, bound: ReadonlyMap): { node: unknown; read: boolean } => { + if (bound.size === 0) return { node, read: false }; + if (Array.isArray(node)) { + const parts = node.map((child) => substitute(child, bound)); + return { node: parts.map((p) => p.node), read: parts.some((p) => p.read) }; + } + if (!isCelNode(node)) return { node, read: false }; + if (node.op === 'id') { + const element = typeof node.args === 'string' ? bound.get(node.args) : undefined; + return element ? { node: element, read: true } : { node, read: false }; + } + const macro = macroOf(node); + if (macro?.name && bound.has(macro.name)) { + const inner = new Map(bound); + inner.delete(macro.name); + const receiver = substitute(macro.receiver, bound); + const body = substitute(macro.body, inner); + const args = node.args as unknown[]; + return { + node: { ...node, args: [args[0], receiver.node, [(args[2] as unknown[])[0], ...(body.node as unknown[])]] }, + read: receiver.read || body.read, + }; + } + const args = substitute(node.args, bound); + return args.read ? { node: { ...node, args: args.node }, read: true } : { node, read: false }; + }; + /** Whether `node` reads one of the macro-bound names in `bound`, an inner rebinding included (the typing before #38959). */ + const readsBound = (node: unknown, bound: ReadonlyMap): boolean => { if (Array.isArray(node)) return node.some((child) => readsBound(child, bound)); if (!isCelNode(node)) return false; if (node.op === 'id') return typeof node.args === 'string' && bound.has(node.args); return readsBound(node.args, bound); }; + /** An element of the list `receiver` computes: `receiver[0]`. */ + const elementOf = (receiver: unknown): CelNode => ({ op: '[]', args: [receiver, { op: 'value', args: 0n }] }); let found = false; - const visit = (v: unknown, bound: ReadonlySet): void => { + const visit = (v: unknown, bound: ReadonlyMap): void => { if (found) return; if (Array.isArray(v)) { for (const child of v) visit(child, bound); return; } if (!isCelNode(v)) return; if (DATE_TEXT_COMPARISON_OPS.has(v.op) && Array.isArray(v.args) && v.args.length === 2) { - const [a, b] = v.args as unknown[]; - if (readsBound(a, bound) || readsBound(b, bound)) { found = true; return; } + // Without `macroElements` a macro variable proves nothing, as before #38959. + if (!macroElements && bound.size > 0 && readsBound(v.args, bound)) { found = true; return; } + const [sa, sb] = (v.args as unknown[]).map((operand) => substitute(operand, bound)); + const [a, b] = [sa.node, sb.node]; const [ta, tb] = [typeOf(a), typeOf(b)]; + // A macro variable whose element does not check proves nothing: keep the verdict. + if ((sa.read && ta === undefined) || (sb.read && tb === undefined)) { found = true; return; } if ((ta === DATE_TEXT_CEL_TYPE && !declared(b, tb)) || (tb === DATE_TEXT_CEL_TYPE && !declared(a, ta))) { found = true; return; } } - // A macro (`list.exists(x, …)`): `rcall` [name, receiver, [variable, …body]]. - const args = v.args; - if (v.op === 'rcall' && Array.isArray(args) && args.length === 3 && Array.isArray(args[2]) - && COMPREHENSION_MACRO_NAMES.has(String(args[0]))) { - const [variable, ...body] = args[2] as unknown[]; - const name = isCelNode(variable) && variable.op === 'id' && typeof variable.args === 'string' ? variable.args : null; - visit(args[1], bound); - visit(body, name ? new Set([...bound, name]) : bound); + const macro = macroOf(v); + if (macro) { + visit(macro.receiver, bound); + if (!macro.name) { visit(macro.body, bound); return; } + const inner = new Map(bound); + inner.set(macro.name, elementOf(substitute(macro.receiver, bound).node)); + visit(macro.body, inner); return; } - visit(args, bound); + visit(v.args, bound); }; - visit(ast, new Set()); + visit(ast, new Map()); return found; } @@ -1261,12 +1316,13 @@ function withoutNames( /** * [#29959, #34662] A `record.` / `previous.` read spelled member-wise — the gate - * of {@link firstTypeMismatch}'s flattened record-root pass. [#35295] It stays - * member-only: that pass answers before the date-text family is asked, so - * opening it to the index spelling would hand an index read the text/boolean - * mismatch verdict, which can stand a date-text refusal down to a warning and - * refuses an ordering against a text field the runtime answers. The date-text - * family has its own gate, {@link RECORD_ROOT_DATE_TEXT_READ_RE}. + * of every verdict of {@link firstTypeMismatch}'s flattened record-root pass. + * [#38959] An index read alone opens that pass too + * ({@link RECORD_ROOT_DATE_TEXT_READ_RE}), for the text/boolean mismatch only: + * date arithmetic against a number stays the date-text family's there, and an + * ordering of a date field against a text field, which the runtime answers, + * stays unjudged. `validate.ts` asks the date-text family over a mismatch + * graded a warning, so the mismatch stands no date-text refusal down. */ export const RECORD_ROOT_READ_RE = /(?` still reads the field and stays typed. + * + * `options.macroElements` (default `true`, #38959): a macro variable ordered + * against a date field's text is typed as an element of the list it ranges + * over. `false` keeps the answer this gave before #38959 — such a comparison + * keeps its mismatch — for a caller that reads a mismatch as its cue to stand + * down (the flow value envelope's date-text check, `validate.ts`), so that + * caller's verdict does not move with the widening. */ export function firstTypeMismatch( source: string, fieldCelTypes: Readonly>, scope: 'record' | 'flattened' = 'record', bareShadowed?: ReadonlySet, + options: { readonly macroElements?: boolean } = {}, ): { operator: string; operands: string; @@ -1405,16 +1472,27 @@ export function firstTypeMismatch( * field against a TEXT field (`record.x < record.start_time`), which no * declared text names: it keeps the verdict it had. * `recordRoots` is the flattened record-root pass's typing (#29959). + * [#38959] `keepUndeclared: false` drops that last exception: the + * record-root pass opened by an index read alone + * ({@link RECORD_ROOT_DATE_TEXT_READ_RE}) does not take it, so + * `record['due_date'] > record['title']`, which the runtime answers, keeps + * the verdict it had before the index spelling reached this pass (clean). + * [#38959] `keptOrdering` records that the last answer was that exception: + * the mismatch kept is the ordering, not a fault the run meets. */ + let keptOrdering = false; const confirmAgainstDateText = ( m: RegExpExecArray, recordRoots?: Readonly>, + keepUndeclared = true, ): RegExpExecArray | null => { + keptOrdering = false; if (!DATE_CEL_TYPES.has(m[1]) && !DATE_CEL_TYPES.has(m[3])) return m; const dateTextEnv = buildTypedEnv(bareTypes, scope, 'date-text', recordRoots); const r = unsoundOverload(dateTextEnv); if (r && textOrBool(r)) return r[1] === DATE_TEXT_CEL_TYPE || r[3] === DATE_TEXT_CEL_TYPE ? m : r; - return comparesDateTextAgainstUndeclared(source, dateTextEnv) ? m : null; + keptOrdering = keepUndeclared && comparesDateTextAgainstUndeclared(source, dateTextEnv, options.macroElements ?? true); + return keptOrdering ? m : null; }; try { const timestampTyped = unsoundOverload(buildTypedEnv(bareTypes, scope)); @@ -1448,9 +1526,23 @@ export function firstTypeMismatch( // written (`root`). The date-text family reaches the roots through // `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; + // [#38959] An index read (`record['title']`) opens this pass too: the typed + // env types it as the member read and the run hands both the same value, + // so `record['title'] > 5` faults on every run as `record.title > 5` does + // and takes its text/boolean mismatch. Where no member read opens the + // pass, an index read takes that verdict and only that one: date + // arithmetic against a number stays the date-text family's (which reaches + // the index spelling under its own code, #35295), and an ordering of a + // date field against a text field, which the runtime answers, stays + // unjudged (`keepUndeclared`). `validate.ts` asks the date-text family + // over a mismatch graded a warning, so opening this pass stands no + // date-text refusal down (#38959). + if (scope !== 'flattened') return null; + const memberRead = RECORD_ROOT_READ_RE.test(source); + if (!memberRead && !RECORD_ROOT_DATE_TEXT_READ_RE.test(source)) return null; const rootTyped = unsoundOverload(buildTypedEnv(bareTypes, 'flattened', 'timestamp', fieldCelTypes)); if (rootTyped && isDateArith(rootTyped)) { + if (!memberRead) return null; const read = offendingRecordRead(source, fieldCelTypes, 'timestamp'); return { operator: rootTyped[2], operands: `${rootTyped[1]} ${rootTyped[2]} ${rootTyped[3]}`, @@ -1459,10 +1551,18 @@ export function firstTypeMismatch( ...(read ? { root: read.root } : {}), }; } - const r = rootTyped && textOrBool(rootTyped) ? confirmAgainstDateText(rootTyped, fieldCelTypes) : null; + const r = rootTyped && textOrBool(rootTyped) ? confirmAgainstDateText(rootTyped, fieldCelTypes, memberRead) : null; const celType = r ? textOrBool(r) : null; if (!r || !celType) return null; - const read = offendingRecordRead(source, fieldCelTypes, celType); + // Either spelling is named, also where a member read opened the pass: + // `record['title'] > 5 && record.status == 'open'` names `record.title`. + // Not for the kept ordering of a date against a text field, which the run + // answers: the name is what proves the read a record's under + // `bareNamesUnproven` (#30025), and an index read takes no part in that + // verdict (#32595, the question item 4 of #38959 leaves open), so only a + // member read is named there, as before #38959, and + // `record.due_date > record['title']` keeps the warning it had. + const read = offendingRecordRead(source, fieldCelTypes, celType, !keptOrdering); return { operator: r[2], operands: `${r[1]} ${r[2]} ${r[3]}`, celType, category: 'type-mismatch', field: read?.field ?? null, diff --git a/packages/formula/src/validate-date-text-arithmetic.test.ts b/packages/formula/src/validate-date-text-arithmetic.test.ts index b19b4b834a9..523798aa622 100644 --- a/packages/formula/src/validate-date-text-arithmetic.test.ts +++ b/packages/formula/src/validate-date-text-arithmetic.test.ts @@ -779,15 +779,14 @@ describe('a flow condition types bare names and record. / previous. reads in one expect(r.ok ? '' : r.error.message, index).toMatch(/no such overload|no matching overload|ISO 8601/); }); - it('the index read takes the date-text verdicts and no other: arithmetic against a number is the date-text refusal, a text mismatch is not judged here', () => { + it('the index read takes the date-text verdicts: arithmetic against a number is the date-text refusal', () => { const got = refusalOf("record['due_date'] + 1 > 5"); expect(got.code).toBe('date-text-arithmetic-run-fails'); expect(param(got, 'reference')).toBe('record.due_date'); const r = run("record['due_date'] + 1 > 5"); expect(r.ok ? '' : r.error.message).toMatch(/no such overload/); - // The text/boolean mismatch pass sees an index read as it did before: never opened to it by this spelling. - const mismatch = check("previous['title'] > 5"); - expect([...mismatch.errors, ...mismatch.warnings].map((e) => e.code)).not.toContainEqual(expect.stringMatching(/^type-mismatch/)); + // [#38959] The text/boolean mismatch now reaches the index read as well: + // pinned in the #38959 `describe` below. }); const NO_OUTCOME: ExprSchemaHint = { ...CONDITION, faultOutcome: undefined }; @@ -856,3 +855,235 @@ describe('a flow condition types bare names and record. / previous. reads in one expect(run(source, extra), source).toEqual({ ok: true, value: true }); }); }); + +// [#38959] Three flow-condition verdicts that disagreed with the run: +// (1) a text/boolean mismatch graded a WARNING (no declared outcome) was asked +// first and the date-text family never was, so a date-text ERROR in the +// same source stood down to the warning and the run faulted; +// (5) the index spelling (`record['title']`) never reached the type-mismatch +// pass, so `record['title'] > 5` passed and faulted on every run; +// (2) a macro variable (`.exists(d, …)`) ordered against a text literal was +// refused as a type mismatch while the run answers it. +// Each run is the engine's scope (`celScope`): bare names, `record` and +// `previous` under `extra`. +describe('flow-condition verdicts agree with the run: severity, the index spelling, macro variables (#38959)', () => { + const fieldTypes = { + title: 'text', borrow_date: 'date', due_date: 'date', picked_up_at: 'datetime', status: 'select', active: 'boolean', + }; + const CONDITION: ExprSchemaHint = { fields: Object.keys(fieldTypes), fieldTypes, faultOutcome: 'run-fails' }; + const NO_OUTCOME: ExprSchemaHint = { fields: Object.keys(fieldTypes), fieldTypes }; + const UNPROVEN: ExprSchemaHint = { ...CONDITION, bareNamesUnproven: true }; + const ROW = { + title: 'Dune', borrow_date: '2026-11-16', due_date: '2026-11-30', picked_up_at: '2026-11-16T09:30:00.000Z', + status: 'open', active: true, + }; + const run = (source: string) => celEngine.evaluate({ dialect: 'cel', source }, { extra: { ...ROW, record: ROW, previous: ROW } }); + const check = (source: string, hint: ExprSchemaHint = CONDITION) => validateExpression('predicate', source, hint); + /** Every code the check answers, errors first, each marked with its grade. */ + const graded = (source: string, hint: ExprSchemaHint = CONDITION) => { + const r = check(source, hint); + return [...r.errors.map((e) => `error:${e.code}`), ...r.warnings.map((e) => `warning:${e.code}`)]; + }; + + // (1) [source, the date-text code on the no-outcome arm] + const HIDDEN: ReadonlyArray = [ + ["due_date - borrow_date > duration('1h') && record.title > 5", 'date-text-arithmetic-run-may-fail'], + ["due_date - borrow_date > duration('1h') && title > 5", 'date-text-arithmetic-run-may-fail'], + // The mismatch met FIRST masks the date-text fault behind it in the check. + ["record.title > 5 && due_date - borrow_date > duration('1h')", 'date-text-arithmetic-run-may-fail'], + ["record.title > 5 && record.due_date - record.borrow_date > duration('1h')", 'date-text-arithmetic-run-may-fail'], + ["record.active > 5 && isoDate(picked_up_at) == 'x'", 'date-text-call-run-may-fail'], + ]; + + it.each(HIDDEN)('a text mismatch warning no longer hides the date-text refusal in %s', (source, code) => { + // No declared outcome: the date-text ERROR wins over the mismatch WARNING. + expect(graded(source, NO_OUTCOME), source).toEqual([`error:${code}`]); + // A declared outcome: the mismatch is an error already and keeps its code. + expect(graded(source, CONDITION), source).toEqual(['error:type-mismatch-run-fails']); + expect(run(source).ok, source).toBe(false); + }); + + it('CONTROL: a text mismatch with no date-text fault beside it stays the warning it was', () => { + for (const source of ['record.title > 5', "record.title > 5 && daysBetween(borrow_date, due_date) > 3", 'title > 5 && due_date > borrow_date']) { + expect(graded(source, NO_OUTCOME), source).toEqual(['warning:type-mismatch-run-may-fail']); + expect(graded(source, CONDITION), source).toEqual(['error:type-mismatch-run-fails']); + } + }); + + it('a bare-name mismatch the run may rebind (bareNamesUnproven) stands no date-text refusal down either', () => { + // A record read faults whatever a node binds: the -run-fails arm; a bare date read takes -run-may-fail. + expect(graded("record.due_date - record.borrow_date > duration('1h') && title > 5", UNPROVEN)).toEqual(['error:date-text-arithmetic-run-fails']); + expect(graded("title > 5 && isoDate(record.picked_up_at) == 'x'", UNPROVEN)).toEqual(['error:date-text-call-run-fails']); + expect(graded("title > 5 && isoDate(picked_up_at) == 'x'", UNPROVEN)).toEqual(['error:date-text-call-run-may-fail']); + expect(graded('title > 5', UNPROVEN)).toEqual(['warning:type-mismatch-run-may-fail']); + }); + + it('a record-scoped site with no declared outcome takes the date-text refusal over the mismatch warning too', () => { + const RECORD: ExprSchemaHint = { scope: 'record', fields: Object.keys(fieldTypes), fieldTypes }; + const source = "record.due_date - record.borrow_date > duration('1h') && record.title > 5"; + expect(graded(source, RECORD)).toEqual(['error:date-text-arithmetic']); + expect(graded("record.title > 5 && isoDate(record.picked_up_at) == 'x'", RECORD)).toEqual(['error:date-text-call']); + expect(graded('record.title > 5', RECORD)).toEqual(['warning:type-mismatch']); + }); + + // (5) [index spelling, its member spelling] + const INDEX_MISMATCH: ReadonlyArray = [ + ["record['title'] > 5", 'record.title > 5'], + ["record['active'] + 1 > 3", 'record.active + 1 > 3'], + ["previous['title'] > 5", 'previous.title > 5'], + ['record["title"] * 2 > 5', 'record.title * 2 > 5'], + ["record['title'] > record['active']", 'record.title > record.active'], + ]; + + it.each(INDEX_MISMATCH)('%s takes the text/boolean mismatch its member spelling takes, on every arm', (index, member) => { + for (const hint of [CONDITION, NO_OUTCOME, UNPROVEN]) { + const [i, m] = [check(index, hint), check(member, hint)]; + expect(graded(index, hint), index).toEqual(graded(member, hint)); + expect(graded(index, hint)[0], index).toMatch(/type-mismatch-run-(?:fails|may-fail)$/); + // Named by the member spelling, as the date-text verdicts name an index read. + expect([...i.errors, ...i.warnings].map((e) => e.params), index).toEqual([...m.errors, ...m.warnings].map((e) => e.params)); + } + expect(run(index).ok, index).toBe(false); + }); + + it('the index read takes the member read\'s verdict whatever that verdict is', () => { + // An ordering of a date read against a number checks as its member spelling does. + for (const [index, member] of [["record['due_date'] > 5", 'record.due_date > 5'], ["record['status'] > 5", 'record.status > 5']]) { + for (const hint of [CONDITION, NO_OUTCOME]) expect(graded(index, hint), index).toEqual(graded(member, hint)); + } + }); + + it('a date-text refusal an index text mismatch masked in the check is refused, on either arm', () => { + const source = "record['title'] > 5 && record['due_date'] - record['borrow_date'] > duration('1h')"; + expect(graded(source, CONDITION)).toEqual(['error:date-text-arithmetic-run-fails']); + expect(graded(source, NO_OUTCOME)).toEqual(['error:date-text-arithmetic-run-may-fail']); + expect(run(source).ok).toBe(false); + }); + + it('a date-text refusal the index spelling took before keeps its code beside an index text mismatch', () => { + // #35295's codes, unchanged now the mismatch pass reads the index spelling too. + for (const [source, family] of [ + ["due_date - borrow_date > duration('1h') && record['title'] > 5", 'date-text-arithmetic'], + ["record['active'] > 5 && isoDate(picked_up_at) == 'x'", 'date-text-call'], + ] as const) { + expect(graded(source, CONDITION), source).toEqual([`error:${family}-run-fails`]); + expect(graded(source, UNPROVEN), source).toEqual([`error:${family}-run-may-fail`]); + expect(graded(source, NO_OUTCOME), source).toEqual([`error:${family}-run-may-fail`]); + } + }); + + // (2) Evaluated on every row: the macro variable ranges over date texts. + const MACRO_RUNS: readonly string[] = [ + "[due_date, record.borrow_date].exists(d, d > '2026-01-01')", + "[due_date, borrow_date].exists(d, d > '2026-01-01')", + "[record.due_date].all(d, d < '2027-01-01')", + "[[due_date]].exists(l, l.exists(d, d > '2026-01-01'))", + "[due_date].map(d, d > '2026-01-01').exists(b, b)", + ]; + + it.each(MACRO_RUNS)('a macro variable ordered against a text literal is not refused: %s', (source) => { + for (const hint of [CONDITION, NO_OUTCOME, UNPROVEN]) expect(check(source, hint), source).toEqual({ ok: true, errors: [], warnings: [] }); + expect(run(source), source).toEqual({ ok: true, value: true }); + }); + + it('a macro variable takes the verdict its element would take written out', () => { + // A real mismatch inside a macro is refused, and faults. + expect(graded('[title].exists(t, t > 5)')).toEqual(['error:type-mismatch-run-fails']); + expect(run('[title].exists(t, t > 5)').ok).toBe(false); + // An inner macro rebinding the name reads its own list. + expect(graded('[due_date].exists(d, [title].exists(d, d > 5))')).toEqual(['error:type-mismatch-run-fails']); + // A date's text ordered against a text field: the verdict `due_date > title` takes. + expect(graded('[due_date].exists(d, d > title)')).toEqual(graded('due_date > title')); + // The inner `map` rebinds `d`: its body reads `[title]`'s element, never the outer date. + expect(graded('[due_date].exists(d, d > [title].map(d, d)[0])')).toEqual(graded('due_date > title')); + expect(graded('[due_date].exists(d, d > [title].map(d, d)[0])')).toEqual(['error:type-mismatch-run-fails']); + expect(graded('[due_date].exists(d, d > title)')).toEqual(['error:type-mismatch-run-fails']); + }); + + it('an inner macro rebinding the name reads its own list: a date ordered against a date is not refused', () => { + // The inner `d` is `[record.borrow_date]`'s element, not the outer one: typed + // through, it is a date's text ordered against a date's text, which the run answers. + const source = "[due_date].exists(d, d >= [record.borrow_date].filter(d, d > '2026-01-01')[0])"; + for (const hint of [CONDITION, NO_OUTCOME, UNPROVEN]) expect(check(source, hint), source).toEqual({ ok: true, errors: [], warnings: [] }); + expect(run(source)).toEqual({ ok: true, value: true }); + }); + + it('over a mismatch warning only the date-text family is taken, never a computed-type verdict', () => { + // A formula value computing a Duration in both branches: the date-text pass + // answers `date-duration-value` there, which the masked mismatch could + // contradict, so the mismatch warning stays the finding. + const RECORD: ExprSchemaHint = { scope: 'record', fields: Object.keys(fieldTypes), fieldTypes }; + const source = 'record.title > 5 ? today() - record.borrow_date : today() - record.due_date'; + const r = validateExpression('value', source, RECORD); + expect([...r.errors.map((e) => `error:${e.code}`), ...r.warnings.map((e) => `warning:${e.code}`)]).toEqual(['warning:type-mismatch']); + // The same Duration with no mismatch beside it is that verdict. + expect(validateExpression('value', 'today() - record.borrow_date', RECORD).errors.map((e) => e.code)).toEqual(['date-duration-value']); + }); + + it('an index read beside a member read takes the verdict and the name its member spelling takes', () => { + // `notes` is a second text field the source reads by member, after `title` in the field table. + const types = { ...fieldTypes, notes: 'text' }; + const arms: readonly ExprSchemaHint[] = [ + { fields: Object.keys(types), fieldTypes: types, faultOutcome: 'run-fails' }, + { fields: Object.keys(types), fieldTypes: types }, + { fields: Object.keys(types), fieldTypes: types, faultOutcome: 'run-fails', bareNamesUnproven: true }, + ]; + for (const [index, member] of [ + ["record['title'] > 5 && record.status == 'open'", "record.title > 5 && record.status == 'open'"], + ["record['title'] > 5 && record.notes == 'n'", "record.title > 5 && record.notes == 'n'"], + ]) { + for (const hint of arms) { + const [i, m] = [check(index, hint), check(member, hint)]; + expect(graded(index, hint), index).toEqual(graded(member, hint)); + const refOf = (e: ExprValidationError) => (e.params as { reference?: string } | undefined)?.reference; + expect([...i.errors, ...i.warnings].map(refOf), index).toEqual(['record.title']); + expect([...m.errors, ...m.warnings].map(refOf), member).toEqual(['record.title']); + } + // Record-triggered and unproven alike: an error, as the index read alone takes. + expect(graded(index, arms[2]), index).toEqual(['error:type-mismatch-run-fails']); + } + }); + + // [#38959, review S3] The ordering of a date against a text field keeps the + // mismatch (#32595) although the run answers it; under `bareNamesUnproven` a + // named `record.FIELD` read is what makes that an error (#30025). An index + // read takes no part in that verdict, so it supplies no name there, and each + // source keeps the warning it had (item 4 of #38959 leaves the verdict open). + it('an index read does not name a kept date-against-text ordering: the warning stays under bareNamesUnproven', () => { + const types = { ...fieldTypes, notes: 'text' }; + const unproven: ExprSchemaHint = { fields: Object.keys(types), fieldTypes: types, faultOutcome: 'run-fails', bareNamesUnproven: true }; + const row = { ...ROW, notes: 'n' }; + for (const source of [ + "record.due_date > record['title']", + "record['due_date'] > record['title'] && record.status == 'open'", + "record.due_date > title && record['notes'] == 'n'", + ]) { + expect(graded(source, unproven), source).toEqual(['warning:type-mismatch-run-may-fail']); + // The run answers it: a date's text ordered against a text. + expect(celEngine.evaluate({ dialect: 'cel', source }, { extra: { ...row, record: row, previous: row } }).ok, source).toBe(true); + } + // CONTROL: the member spelling names the text read and keeps its standing error. + expect(graded('record.due_date > record.title', unproven)).toEqual(['error:type-mismatch-run-fails']); + }); + + // [#38959, review M1] A flow value envelope's date-text check stands down + // where the mismatch check finds a mismatch; it asks that check with the + // macro typing it had before, so typing a macro variable as its element (a + // condition's widening) refuses no value that registered before. The + // envelope shape itself (a macro over a date read beside a date-text fault) + // is carried by #39107. + it('a flow value envelope keeps its verdict: a macro over a date read beside a date-text fault is not newly refused', () => { + const ENVELOPE: ExprSchemaHint = { fieldTypes, flowValueEnvelope: true }; + const envelope = (source: string) => validateExpression('value', { dialect: 'cel', source }, ENVELOPE); + for (const source of [ + "[record.due_date].exists(d, d > '2026-01-01') ? isoDate(record.picked_up_at) : 'x'", + "[record.due_date].exists(d, d > '2026-01-01') && record.due_date - record.borrow_date > duration('1h')", + ]) { + expect(envelope(source), source).toEqual({ ok: true, errors: [], warnings: [] }); + } + // CONTROL: the date-text fault alone is refused in the envelope, as before. + expect(envelope('isoDate(record.picked_up_at)').errors.map((e) => e.code)).toEqual(['date-text-call-value-run-may-fail']); + // CONTROL: the macro alone is no longer refused as a flow condition (the widening). + expect(check("[record.due_date].exists(d, d > '2026-01-01')")).toEqual({ ok: true, errors: [], warnings: [] }); + }); +}); diff --git a/packages/formula/src/validate.ts b/packages/formula/src/validate.ts index b6dbbd4689f..f041cd175e2 100644 --- a/packages/formula/src/validate.ts +++ b/packages/formula/src/validate.ts @@ -25,6 +25,7 @@ import { firstTypeMismatch, inferCelType, RECORD_ROOT_DATE_TEXT_READ_RE, + RECORD_ROOT_READ_RE, parseCelToAst, parseCelToAstWithReason, printCelAst, @@ -590,17 +591,52 @@ function typeSoundnessIssue( if (rootRead && rootRead.root !== undefined) mismatch = rootRead; else outcome = undefined; } - if (!mismatch) { + /** The date-text family's verdict with the fields typed by `types`: the bare names, then the record roots. */ + const dateTextVerdict = (types: Readonly>) => { const bareCelTypes = shadowed - ? Object.fromEntries(Object.entries(celFieldTypes).filter(([name]) => !shadowed.has(name))) - : celFieldTypes; + ? Object.fromEntries(Object.entries(types).filter(([name]) => !shadowed.has(name))) + : types; // [#34363] The `date` fields (never `datetime`) by name: `timestamp()` faults on their text. const dateOnly = new Set(Object.keys(bareCelTypes).filter((name) => fieldTypes[name] === 'date')); const bare = dateTextIssue(source, bareCelTypes, scope, role, dateArm(scope, faultOutcome, bareNamesUnproven), dateOnly); return bare ?? (scope === 'flattened' - ? recordRootDateTextIssue(source, fieldTypes, celFieldTypes, bareCelTypes, role, faultOutcome, bareNamesUnproven) + ? recordRootDateTextIssue(source, fieldTypes, types, bareCelTypes, role, faultOutcome, bareNamesUnproven) : null); - } + }; + if (!mismatch) return dateTextVerdict(celFieldTypes); + /** + * [#38959] A text/boolean mismatch graded a WARNING (no declared outcome) + * never stands a date-text ERROR in the same source down: the more severe + * verdict wins. `due_date - borrow_date > duration('1h') && record.title > 5` + * faults on the date subtraction on every run, yet the mismatch answered + * first and the date-text family was never asked, so the source published + * with the warning alone. Asked here with the full field typing, then with + * only the date fields typed (every text/boolean field `dyn`): the check + * reports its FIRST fault, so a mismatch met first would mask the date-text + * fault behind it (`record.title > 5 && due_date - borrow_date > …`). The + * `dyn` typing adds no fault the full typing lacks at the same operator, it + * only unmasks. Only the date-text family's errors are taken + * (`date-text-arithmetic*` / `date-text-call*`), never a computed-type verdict + * the masked mismatch could contradict. + * + * A mismatch graded an error keeps its code and words, except one an index + * read alone answers (`record['title'] > 5`, no member read in the source: + * the reach `firstTypeMismatch`'s record-root pass gained here). The + * date-text family reached the index spelling first (#35295), so it is + * asked first there too, and every verdict it gave before keeps its code. + */ + const indexReadOnly = mismatch.root !== undefined && !RECORD_ROOT_READ_RE.test(source); + const dateTextOver = (verdict: T) => { + if (verdict.severity !== 'warning' && !indexReadOnly) return verdict; + const datesOnly = Object.fromEntries( + Object.entries(celFieldTypes).map(([name, t]): [string, FieldCelType] => [name, t === 'timestamp' ? t : 'dyn']), + ); + for (const types of [celFieldTypes, datesOnly]) { + const found = dateTextVerdict(types); + if (found && found.severity === 'error' && DATE_TEXT_FAMILY_RE.test(found.issue.code)) return found; + } + return verdict; + }; const reference = mismatch.field ? (mismatch.root !== undefined ? `${mismatch.root}.${mismatch.field}` @@ -659,10 +695,10 @@ function typeSoundnessIssue( const arm = outcome === 'run-fails' && scope === 'flattened' && timeRelativeSweep ? TYPE_MISMATCH_SWEEP_ARM : TYPE_MISMATCH_FAULT_ARMS[outcome]; - return { + return dateTextOver({ severity: 'error', issue: refusal(arm.code, params, source, `${faults}, and here ${arm.clause} ${convert}`), - }; + }); } if (scope === 'flattened') { // [#29959] A flattened condition is a flow's, and the engine's @@ -673,7 +709,7 @@ function typeSoundnessIssue( // record, a parent's record or nothing; a node's inert `condition` — so // the mismatch stays a warning, worded for the run without naming the // flow's kind (the engine's registration log serves it on every flow). - return { + return dateTextOver({ severity: 'warning', issue: refusal( 'type-mismatch-run-may-fail', @@ -684,9 +720,9 @@ function typeSoundnessIssue( `${ref ?? 'the field'} holds ${held} there depends on what the run binds, which this check cannot ` + `prove here, so this is a warning, not a refusal. ${convert}`, ), - }; + }); } - return { + return dateTextOver({ severity: 'warning', issue: refusal( 'type-mismatch', @@ -701,7 +737,7 @@ function typeSoundnessIssue( `against a number. This faults at runtime, so the expression silently evaluates to null ` + `(unless the value happens to be numeric). Use a number field, or drop the arithmetic/comparison.`, ), - }; + }); } /** @@ -998,7 +1034,10 @@ function flowValueEnvelopeDateTextIssue( if (!Object.values(celFieldTypes).includes('timestamp')) return null; const tree = ast(); if (!tree || readRootMembers(tree, ['input']).length > 0) return null; - if (firstTypeMismatch(source, celFieldTypes, 'record')) return null; + // [#38959] With the macro typing it had before (`macroElements: false`): a + // mismatch found there stands this check down, so typing a macro variable as + // its element would turn on refusals a stored flow registered without. + if (firstTypeMismatch(source, celFieldTypes, 'record', undefined, { macroElements: false })) return null; const dateOnly = new Set(Object.keys(fieldTypes).filter((name) => fieldTypes[name] === 'date')); const found = dateTextIssue(source, celFieldTypes, 'record', 'value', 'value-run-may-fail', dateOnly); return found && DATE_TEXT_FAMILY_RE.test(found.issue.code) ? found.issue : null; diff --git a/packages/lint/src/validate-expressions.mismatch-precedence-38959.test.ts b/packages/lint/src/validate-expressions.mismatch-precedence-38959.test.ts new file mode 100644 index 00000000000..5dfe0819d1f --- /dev/null +++ b/packages/lint/src/validate-expressions.mismatch-precedence-38959.test.ts @@ -0,0 +1,83 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38959] A date-text fault is no longer hidden behind a text/boolean type + * mismatch graded a warning. `@objectstack/formula` reports one finding per + * source; it asked the mismatch first and the date-text family only when that + * answered nothing, so where the mismatch is a warning (a record-scoped site + * with no declared fault outcome) a source that faults on its date arithmetic + * on every row published with the warning alone. The more severe verdict now + * wins, at every record-scoped site `check()` serves with no fault outcome: + * a field's `visibleWhen` / `settledWhen` / `uiReadonlyWhen`, a + * `conditionalFormatting` rule's `condition`, a field group's `visibleWhen`, + * an action's `visible` / `disabled` / `pressed`, a sharing rule's + * `condition`, the object's `uiReadonlyWhen` — pinned here at three of them. + * + * Every fixture goes through `ObjectStackSchema.safeParse` first, so no case + * pins a branch an author cannot reach. + */ + +import { describe, it, expect } from 'vitest'; + +import { ObjectStackSchema } from '@objectstack/spec'; + +import { validateStackExpressions } from './validate-expressions.js'; + +const MANIFEST = { id: 'com.example.mismatch-precedence', name: 'mismatch_precedence_probe', version: '1.0.0', type: 'app' } as const; + +function specValid(stack: Record): Record { + const result = ObjectStackSchema.safeParse({ manifest: MANIFEST, ...stack }); + if (!result.success) { + throw new Error( + 'fixture is not spec-valid: ' + + result.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`).join('; '), + ); + } + return result.data as unknown as Record; +} + +/** A loan: two date fields, a text field, and `note` carrying the predicate under test. */ +const loan = (note: Record = {}, rest: Record = {}) => ({ + name: 'library_loan', + label: 'Library loan', + fields: { + title: { type: 'text', label: 'Title' }, + borrow_date: { type: 'date', label: 'Borrowed' }, + due_date: { type: 'date', label: 'Due' }, + note: { type: 'text', label: 'Note', ...note }, + }, + ...rest, +}); + +/** Every finding at `where`, as `severity: message head`. */ +const findingsAt = (stack: Record, where: string) => + validateStackExpressions(specValid(stack)) + .filter((i) => i.where.includes(where)) + .map((i) => `${i.severity ?? 'error'}: ${i.message.split(' — ')[0]}`); + +const HIDDEN = "record.due_date - record.borrow_date > duration('1h') && record.title > 5"; +const MISMATCH_ONLY = 'record.title > 5'; +/** The date-text refusal's head: the arithmetic the runtime cannot do on a date's text. */ +const DATE_TEXT_HEAD = "error: date arithmetic `DateText - DateText`"; + +describe('publish lint: a date-text refusal is not stood down by a mismatch warning at a record-scoped site (#38959)', () => { + it("a field's visibleWhen: the date-text error, not the mismatch warning", () => { + expect(findingsAt({ objects: [loan({ visibleWhen: HIDDEN })] }, "field 'note' visibleWhen")).toEqual([DATE_TEXT_HEAD]); + }); + + it("an action's visible: the date-text error", () => { + const action = { name: 'renew', label: 'Renew', type: 'script', target: 'renew_loan', objectName: 'library_loan', visible: HIDDEN }; + expect(findingsAt({ objects: [loan()], actions: [action] }, "action 'renew' visible")).toEqual([DATE_TEXT_HEAD]); + }); + + it("a sharing rule's condition: the date-text error", () => { + const rule = { name: 'overdue_loans', label: 'Overdue loans', type: 'criteria', object: 'library_loan', condition: HIDDEN, sharedWith: { type: 'position', value: 'librarian' }, accessLevel: 'read' }; + expect(findingsAt({ objects: [loan()], sharingRules: [rule] }, "sharingRule 'overdue_loans'")).toEqual([DATE_TEXT_HEAD]); + }); + + it('CONTROL: the mismatch alone stays the warning it was at the same site', () => { + const found = findingsAt({ objects: [loan({ visibleWhen: MISMATCH_ONLY })] }, "field 'note' visibleWhen"); + expect(found).toHaveLength(1); + expect(found[0]).toMatch(/^warning: /); + }); +}); diff --git a/packages/services/service-automation/src/flow-registration-checks.test.ts b/packages/services/service-automation/src/flow-registration-checks.test.ts index a8df1bafd14..749d9563848 100644 --- a/packages/services/service-automation/src/flow-registration-checks.test.ts +++ b/packages/services/service-automation/src/flow-registration-checks.test.ts @@ -361,3 +361,44 @@ describe('registration: the invalid-expression header names the braces rule only expect(body(mixed)).toContain(body(refusalOf(loanFlow({ assign: DATE_TEXT })))); }); }); + +// [#38959, review M1] Typing a macro variable as an element of its list widens +// flow conditions only: the value envelope's date-text check keeps the answer +// it gave before, so a stored flow whose assignment value joins a macro over a +// date read to a date-text fault registers as it did. That envelope shape is +// carried by #39107. +describe('registration: a macro over a date read in a value envelope registers as before (#38959)', () => { + const LOAN_SCHEMA = { + fields: ['title', 'borrow_date', 'due_date', 'picked_up_at'], + fieldTypes: { title: 'text', borrow_date: 'date', due_date: 'date', picked_up_at: 'datetime' }, + }; + /** A record-triggered flow on `library_loan` assigning `source` as a CEL envelope. */ + const assigning = (source: string) => ({ + name: 'loan_due', label: 'Loan due', type: 'record_change', + nodes: [ + { id: 'start', type: 'start', label: 'Start', config: { objectName: 'library_loan', triggerType: 'record-after-update' } }, + { id: 'set', type: 'assignment', label: 'Set', config: { assignments: { due: { dialect: 'cel', source } } } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'set' }, + { id: 'e2', source: 'set', target: 'end' }, + ], + }); + const registering = (source: string) => () => { + const engine = new AutomationEngine(loggerCapturing([])); + engine.setObjectSchemaResolver((name) => (name === 'library_loan' ? LOAN_SCHEMA : undefined)); + engine.registerFlow('loan_due', assigning(source) as never); + }; + + it.each([ + "[record.due_date].exists(d, d > '2026-01-01') ? isoDate(record.picked_up_at) : 'x'", + "[record.due_date].exists(d, d > '2026-01-01') && record.due_date - record.borrow_date > duration('1h')", + ])('registers %s', (source) => { + expect(registering(source)).not.toThrow(); + }); + + it('control: the date-text fault alone in the same slot is refused at registration, as before', () => { + expect(registering('isoDate(record.picked_up_at)')).toThrow(/date field|does not register/); + }); +}); diff --git a/packages/spec/src/migrations/entries/semantic/19.flow-condition-mismatch-warning-and-index-mismatch-refused.ts b/packages/spec/src/migrations/entries/semantic/19.flow-condition-mismatch-warning-and-index-mismatch-refused.ts new file mode 100644 index 00000000000..fc774534a1f --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/19.flow-condition-mismatch-warning-and-index-mismatch-refused.ts @@ -0,0 +1,73 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// Two flow-condition shapes that published and failed every run are now +// refused (#38959): a date-text fault hidden behind a text or boolean type +// mismatch graded a warning, and a text or boolean type mismatch spelled +// through an index read, record['FIELD'] / previous['FIELD']. A structured +// TODO, not a D2 conversion: what the author meant by the comparison or the +// span is not recorded, and the platform does not guess. +export const entry: SemanticMigration = { + id: 'flow-condition-mismatch-warning-and-index-mismatch-refused', + surface: + 'automation.Flow conditions (a start node config.condition, edges[].condition, a decision node\'s ' + + 'config.conditions[].expression) over the object the flow is typed against, and every record-scoped expression ' + + 'site that declares no fault outcome: a formula field expression, a field visibleWhen / settledWhen / ' + + 'uiReadonlyWhen, a field conditionalFormatting[].condition, a field group visibleWhen, an action visible / ' + + 'disabled / pressed, a sharing rule condition, the object uiReadonlyWhen. Not a flow value envelope (an ' + + 'assignment value, a create_record / update_record fields.* value): its verdict is unchanged. (1) A source that ' + + 'carries both a text or boolean type mismatch graded a warning (a flow that is not record-triggered, a bare name ' + + 'a node can rebind, a record-scoped site with no fault outcome) and a date-text fault: due_date - borrow_date > ' + + 'duration("1h") && record.title > 5, record.active > 5 && isoDate(picked_up_at) == "x". Before, the mismatch ' + + 'warning was the only finding; now the date-text verdict is the finding, an error: date-text-arithmetic-run-may-fail ' + + 'or date-text-call-run-may-fail on a flow that is not record-triggered; under bareNamesUnproven ' + + 'date-text-arithmetic-run-fails or date-text-call-run-fails over a record.FIELD read and the -run-may-fail codes ' + + 'over a bare one; date-text-arithmetic or date-text-call at a record-scoped site. Where the mismatch was an error ' + + 'already (a record-triggered flow, a sweep of the typed object, a site with a declared fault outcome) it keeps its ' + + 'code. (2) A text or boolean field read by index, record[\'FIELD\'] or previous["FIELD"], used with an arithmetic ' + + 'or ordering operator the run has no overload for, so it faults on every row: against a number ' + + '(record[\'title\'] > 5, record[\'active\'] + 1 > 3, previous[\'title\'] > 5) or against a boolean ' + + '(record[\'title\'] > record[\'active\']), also with a member read beside it, record[\'title\'] > 5 && ' + + 'record.status == "open" (before: the warning under bareNamesUnproven, and no field or the wrong one named). It ' + + 'now takes the type-mismatch verdict its member spelling takes (type-mismatch-run-fails, -sweep-run-fails, or the ' + + '-run-may-fail warning), named as its member spelling is: by the member spelling, the first field of the faulting ' + + 'type in the field table the source reads in either spelling, which need not be the operand (stated limit: ' + + 'previous.notes > 5 && record[\'title\'] == "x" names record.title; carried by its own card). Not the shape: an index ' + + 'read\'s date arithmetic against a number and its date-text verdicts, which keep their date-text codes; an ' + + 'ordering of a date read against a text field (which the run answers) with either side read by index, which ' + + 'keeps the verdict it had: unjudged where no member read is in the source (record[\'due_date\'] > ' + + 'record[\'title\']), otherwise the mismatch kept as before, named only by a member read, so under ' + + 'bareNamesUnproven it stays the warning (record.due_date > record[\'title\'], record[\'due_date\'] > ' + + 'record[\'title\'] && record.status == "open", record.due_date > title && record[\'notes\'] == "n"); an ' + + 'operand the field table does not type', + replacement: + 'Compare like with like: a number field, text compared with text, or an explicit conversion (size(record.title) ' + + 'for the length, double(record.title) for the value, which itself faults on text that is not a number); a ' + + 'boolean compared with true or false. For a date: daysBetween(a, b) for the span in whole days, addDays(d, n) / ' + + 'addMonths(d, n) / daysFromNow(n) to shift it, date(...) before a timestamp-only call, and for a span in hours ' + + '(datetime(b) - datetime(a)).getHours()', + reason: + 'A flow condition that faults fails the run (ADR-0032 section 1c). The authoring type check reported one finding ' + + 'per source and asked the text or boolean mismatch first; the date-text family was asked only when that answered ' + + 'nothing, so a mismatch graded a warning stood an every-run date-text fault in the same source down to that ' + + 'warning, and the source published. The more severe verdict now wins: over a warning the date-text family is ' + + 'asked, with the date fields alone typed where the mismatch met first would mask it. Separately, the record-root ' + + 'pass of the mismatch check was gated on the member spelling, so record[\'title\'] > 5 faulted every run and ' + + 'passed; an index read now opens it for the text and boolean mismatch. The date-text verdicts the index read ' + + 'took before keep their codes, and an index read beside a member read is found and named too, except as the ' + + 'name of a kept ordering of a date against a text field, which the run answers. In the same ' + + 'change a macro variable ordered against a text literal ([due_date, record.borrow_date].exists(d, d > ' + + '"2026-01-01"), which the runtime answers) is typed as an element of its list and no longer refused, in a ' + + 'condition and at a record-scoped site; a flow value envelope\'s date-text check, which stands down on a ' + + 'mismatch, keeps the macro typing it had, so no value that registered before is refused (that envelope shape ' + + 'is carried by its own card). There is no mechanical rewrite: what the comparison or the span meant is a ' + + 'judgement about the condition. ADR-0032 / ADR-0087.', + acceptanceCriteria: + 'os validate and os build report no date-text-arithmetic, date-text-call or type-mismatch error on a flow ' + + 'condition or record-scoped expression carrying either shape; POST /api/v1/packages/PKG/publish-drafts publishes ' + + 'the flow; a run passes the condition instead of failing there. A stored flow carrying the shape in a condition ' + + 'still registers (registerFlow logs it as an advisory) and keeps failing at that condition on every run until it ' + + 'is rewritten and published; no flow value envelope verdict changes, so registerFlow refuses no stored flow it ' + + 'registered before.', +};