Skip to content

Commit 1200680

Browse files
committed
fix(lint)!: flow-condition type mismatches get a true verdict on every flow, record.x and decision branch
WIP: formula flattened-scope warning arm and record-root typing, lint decision branches through the edge's schema-hint path, MCP validate_expression severity and triggerKind inputs. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WGufzf4UmgvS2cusNbWnvy
1 parent 73a3ef9 commit 1200680

7 files changed

Lines changed: 253 additions & 76 deletions

File tree

‎content/docs/data-modeling/formulas.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ come at two severities: **errors** fail the build; **warnings** are advisory
242242
| **Qualify field references** — a formula / validation / predicate binds only the `record` namespace, so a bare `amount` resolves to nothing and evaluates to `null`. Write `record.amount`. | `amount > 100` → `record.amount > 100` | error |
243243
| **Field must exist** — a typo'd `record.<field>` is flagged with a did-you-mean. | `record.amont` → `record.amount` | error |
244244
| **Unknown function** — a misspelled or nonexistent stdlib call. | `isBlnk(record.x)` | error |
245-
| **Type soundness** — a text or boolean field used with an arithmetic (`+ - * / %`) or ordering (`< > <= >=`) operator against a number faults at runtime unless the text is numeric. In a formula it evaluates to `null`. Where a fault does something else it is an error, worded for what happens: a validation rule, a field `requiredWhen` / `readonlyWhen`, an option `visibleWhen` or a hook `condition` refuses the write; a record-triggered flow's start or edge condition fails the run (the write that fired it still lands); an advisory (`severity: 'warning'` / `'info'`) validation rule is skipped, so it never gives its advisory. Store it as a number field, compare text with text, or convert explicitly (`size(record.name)` for the length; `double(record.name)`, which itself faults on text that is not a number). | `record.title * 2`; `record.name > 5` in a validation rule → `size(record.name) > 5` | warning in a formula or a display predicate; error at the sites named |
245+
| **Type soundness** — a text or boolean field used with an arithmetic (`+ - * / %`) or ordering (`< > <= >=`) operator against a number faults at runtime unless the text is numeric. In a formula it evaluates to `null`. Where a fault does something else it is an error, worded for what happens: a validation rule, a field `requiredWhen` / `readonlyWhen`, an option `visibleWhen` or a hook `condition` refuses the write; a record-triggered flow's start, edge or `decision` branch condition fails the run (the write that fired it still lands), whether it reads the field bare or as `record.<field>`; an advisory (`severity: 'warning'` / `'info'`) validation rule is skipped, so it never gives its advisory. Store it as a number field, compare text with text, or convert explicitly (`size(record.name)` for the length; `double(record.name)`, which itself faults on text that is not a number). | `record.title * 2`; `record.name > 5` in a validation rule → `size(record.name) > 5` | warning in a formula or a display predicate, and in a condition of a flow that is not record-triggered, where the warning says the run fails if the condition faults (what such a flow binds under the name depends on how it is started); error at the sites named |
246246
| **Date arithmetic** — a `date` / `datetime` field used with `+` / `-` against a number (a `YYYY-MM-DD` value is a string at runtime, so this always faulted to `null`). Use the date helpers instead. | `record.end_date - record.start_date + 1` → `daysBetween(record.start_date, record.end_date) + 1`; `today() + 30` → `daysFromNow(30)`; `record.date + n` → `addDays(record.date, n)` | error (#3306) |
247247
| **Date subtraction** — the runtime holds a `date` / `datetime` field as its text (`YYYY-MM-DD`, or an ISO-8601 instant), so subtracting two of them faults and the formula reads `null`; a timestamp minus one computes a duration, which a field reads as `{}`. Use `daysBetween`. A condition may still compare a duration (`today() - record.start_date > duration("72h")`). | `record.end_date - record.start_date` → `daysBetween(record.start_date, record.end_date)`; `today() - record.start_date` → `daysBetween(record.start_date, today())` | error |
248248

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

Lines changed: 82 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -966,6 +966,7 @@ function buildTypedEnv(
966966
fieldCelTypes: Readonly<Record<string, FieldCelType>>,
967967
scope: 'record' | 'flattened',
968968
temporalAsText = false,
969+
flattenedRecordRoots = false,
969970
): Environment {
970971
// `temporalAsText` declares a `date`/`datetime` field as the text the runtime
971972
// holds ({@link DATE_TEXT_CEL_TYPE}) instead of a Timestamp — see
@@ -981,6 +982,18 @@ function buildTypedEnv(
981982
registerStdLib(env, () => new Date(0));
982983
registerNullComparisons(env);
983984
if (temporalAsText) registerDateTextOverloads(env);
985+
if (flattenedRecordRoots) {
986+
// [#29959] A flow run binds the record it was handed as `record` too
987+
// (`seedRunVariables`), beside the flattened bare names, so
988+
// `record.<field>` is the same value as the bare `<field>` and is typed
989+
// the same: the `record`-scope struct, on `record` and `previous`.
990+
const fields: Record<string, string> = {};
991+
for (const [name, t] of Object.entries(fieldCelTypes)) fields[name] = typeName(t);
992+
try { env.registerType('OsRecordScope', { fields }); } catch { /* invalid field name — ignore */ }
993+
for (const root of ['record', 'previous']) {
994+
try { env.registerVariable(root, 'OsRecordScope'); } catch { /* duplicate — ignore */ }
995+
}
996+
}
984997
for (const root of SCOPE_ROOTS) {
985998
try { env.registerVariable(root, 'map'); } catch { /* duplicate — ignore */ }
986999
}
@@ -1038,6 +1051,25 @@ function offendingField(
10381051
return null;
10391052
}
10401053

1054+
/**
1055+
* [#29959] The `record.<field>` / `previous.<field>` read of a field of
1056+
* `celType` in a flattened condition, as written — what
1057+
* {@link firstTypeMismatch}'s record-root pass names. `null` when no such read
1058+
* is spelled member-wise (an index read, say), so the message names no field.
1059+
*/
1060+
function offendingRecordRead(
1061+
source: string,
1062+
fieldCelTypes: Readonly<Record<string, FieldCelType>>,
1063+
celType: FieldCelType,
1064+
): { field: string; root: 'record' | 'previous' } | null {
1065+
for (const [name, t] of Object.entries(fieldCelTypes)) {
1066+
if (t !== celType) continue;
1067+
const m = new RegExp(`(?<![\\w$.])(record|previous)\\.${name}(?![\\w$])`).exec(source);
1068+
if (m) return { field: name, root: m[1] as 'record' | 'previous' };
1069+
}
1070+
return null;
1071+
}
1072+
10411073
/**
10421074
* Tier-4 type-soundness (#1928): detect a `record`-scoped expression that
10431075
* type-checks structurally but faults a runtime operator overload because a
@@ -1079,41 +1111,70 @@ export function firstTypeMismatch(
10791111
source: string,
10801112
fieldCelTypes: Readonly<Record<string, FieldCelType>>,
10811113
scope: 'record' | 'flattened' = 'record',
1082-
): { operator: string; operands: string; celType: FieldCelType; field: string | null; category: 'date-arith' | 'type-mismatch' } | null {
1114+
): {
1115+
operator: string;
1116+
operands: string;
1117+
celType: FieldCelType;
1118+
field: string | null;
1119+
/** [#29959] Set when a flattened condition's mismatch is a `record.<field>` / `previous.<field>` read. */
1120+
root?: 'record' | 'previous';
1121+
category: 'date-arith' | 'type-mismatch';
1122+
} | null {
10831123
if (typeof source !== 'string' || !source.trim()) return null;
10841124
// An all-`dyn` record can never fault an overload — skip the parse entirely.
10851125
if (!Object.values(fieldCelTypes).some((t) => t === 'string' || t === 'bool' || t === 'timestamp')) return null;
1086-
try {
1126+
/** The faulting overload `source` meets in `env`'s typing, or `null`. */
1127+
const unsoundOverload = (env: Environment): RegExpExecArray | null => {
10871128
// A null-guarded numeric branch (`cond ? n : null`) faults cel-js's ternary
10881129
// unifier *before* the check reaches an inner date-arith overload; rewrite it
10891130
// first (same pass the runtime uses) so the real fault surfaces (#3306).
1090-
const env = buildTypedEnv(fieldCelTypes, scope);
10911131
const result = env.parse(rewriteNullableTernary(rewriteIndexedHas(source))).check?.() as
10921132
| { valid?: boolean; error?: { message?: string } }
10931133
| undefined;
10941134
if (!result || result.valid !== false) return null;
1095-
const m = UNSOUND_OVERLOAD_RE.exec(result.error?.message ?? '');
1096-
if (!m) return null;
1097-
const operator = m[2];
1098-
const operands = `${m[1]} ${operator} ${m[3]}`;
1099-
// #3306 — date/duration ARITHMETIC against a number: always nulls, hard error.
1100-
if (ARITH_OPS.has(operator)
1101-
&& ((DATE_CEL_TYPES.has(m[1]) && NUMERIC_CEL_TYPES.has(m[3]))
1102-
|| (NUMERIC_CEL_TYPES.has(m[1]) && DATE_CEL_TYPES.has(m[3])))) {
1135+
return UNSOUND_OVERLOAD_RE.exec(result.error?.message ?? '');
1136+
};
1137+
/** The text/boolean operand type of a faulting overload, or `null`. */
1138+
const textOrBool = (m: RegExpExecArray): FieldCelType | null =>
1139+
m[1] === 'string' || m[1] === 'bool' ? (m[1] as FieldCelType)
1140+
: m[3] === 'string' || m[3] === 'bool' ? (m[3] as FieldCelType)
1141+
: null;
1142+
try {
1143+
const m = unsoundOverload(buildTypedEnv(fieldCelTypes, scope));
1144+
if (m) {
1145+
const operator = m[2];
1146+
const operands = `${m[1]} ${operator} ${m[3]}`;
1147+
// #3306 — date/duration ARITHMETIC against a number: always nulls, hard error.
1148+
if (ARITH_OPS.has(operator)
1149+
&& ((DATE_CEL_TYPES.has(m[1]) && NUMERIC_CEL_TYPES.has(m[3]))
1150+
|| (NUMERIC_CEL_TYPES.has(m[1]) && DATE_CEL_TYPES.has(m[3])))) {
1151+
return {
1152+
operator, operands, celType: 'timestamp', category: 'date-arith',
1153+
field: offendingField(source, fieldCelTypes, 'timestamp', scope),
1154+
};
1155+
}
1156+
// #1928 — text/boolean field in arithmetic/ordering against a number: warning.
1157+
const celType = textOrBool(m);
1158+
if (!celType) return null;
11031159
return {
1104-
operator, operands, celType: 'timestamp', category: 'date-arith',
1105-
field: offendingField(source, fieldCelTypes, 'timestamp', scope),
1160+
operator, operands, celType, category: 'type-mismatch',
1161+
field: offendingField(source, fieldCelTypes, celType, scope),
11061162
};
11071163
}
1108-
// #1928 — text/boolean field in arithmetic/ordering against a number: warning.
1109-
const celType: FieldCelType | null =
1110-
m[1] === 'string' || m[1] === 'bool' ? (m[1] as FieldCelType)
1111-
: m[3] === 'string' || m[3] === 'bool' ? (m[3] as FieldCelType)
1112-
: null;
1113-
if (!celType) return null;
1164+
// [#29959] A flattened condition reads the same field as `record.<field>`
1165+
// (and `previous.<field>`), which the bare typing above leaves `dyn`. A
1166+
// second pass types those roots too, for the text/boolean mismatch only:
1167+
// the same verdict the bare name gets. The date verdicts stay the bare
1168+
// name's alone, as before.
1169+
if (scope !== 'flattened' || !/(?<![\w$.])(?:record|previous)\s*\./.test(source)) return null;
1170+
const r = unsoundOverload(buildTypedEnv(fieldCelTypes, 'flattened', false, true));
1171+
const celType = r ? textOrBool(r) : null;
1172+
if (!r || !celType) return null;
1173+
const read = offendingRecordRead(source, fieldCelTypes, celType);
11141174
return {
1115-
operator, operands, celType, category: 'type-mismatch',
1116-
field: offendingField(source, fieldCelTypes, celType, scope),
1175+
operator: r[2], operands: `${r[1]} ${r[2]} ${r[3]}`, celType, category: 'type-mismatch',
1176+
field: read?.field ?? null,
1177+
...(read ? { root: read.root } : {}),
11171178
};
11181179
} catch {
11191180
// A parse/other fault is the syntax checker's job (celEngine.compile); this

‎packages/formula/src/expression-refusal.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,9 @@ export interface ExpressionRefusalParams {
182182
'date-duration-value': { readonly reference?: string };
183183
/**
184184
* WARNING, never an error: a text or boolean field used with an arithmetic
185-
* or ordering `operator` against a number, at a site where a fault reads
186-
* null (a formula field) or whose fault outcome the caller did not declare.
185+
* or ordering `operator` against a number, at a `record`-scoped site where a
186+
* fault reads null (a formula field) or whose fault outcome the caller did
187+
* not declare. A flattened (flow) condition is `type-mismatch-run-may-fail`.
187188
*/
188189
'type-mismatch': TypeMismatchParams;
189190
/**
@@ -205,6 +206,14 @@ export interface ExpressionRefusalParams {
205206
* advisory never fires.
206207
*/
207208
'type-mismatch-fail-open': TypeMismatchParams;
209+
/**
210+
* [#29959] WARNING, never an error: the same mismatch in a flow condition
211+
* whose caller declared no fault outcome — a flow that is not
212+
* record-triggered, or a node condition nothing evaluates. A flow condition
213+
* that faults fails the run (it never reads null), but what the run binds
214+
* under the name is not proven to be the field's value there.
215+
*/
216+
'type-mismatch-run-may-fail': TypeMismatchParams;
208217
/**
209218
* WARNING, never an error: a bare identifier in a flattened condition that
210219
* is one typo away from a field. Absent `objectName` reads "the trigger object".
@@ -270,6 +279,7 @@ const CODE_TABLE = {
270279
'type-mismatch-fail-closed': true,
271280
'type-mismatch-run-fails': true,
272281
'type-mismatch-fail-open': true,
282+
'type-mismatch-run-may-fail': true,
273283
'field-near-miss': true,
274284
'traversal-bare-and-traversed': true,
275285
'traversal-multi-hop': true,

‎packages/formula/src/validate.ts‎

Lines changed: 53 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ export interface ExprSchemaHint {
235235
* `readonlyWhen`, an option `visibleWhen` on the write path, a hook
236236
* `condition`.
237237
*
238-
* `'run-fails'`: a record-triggered flow's start or edge condition — the
238+
* `'run-fails'`: a record-triggered flow's start, edge or `decision` branch condition — the
239239
* engine's `evaluateCondition` throws on the fault (ADR-0032 §1c), so the
240240
* run fails there, while the record-change trigger isolates the write that
241241
* fired it: the write lands, the flow's work is not done.
@@ -247,9 +247,11 @@ export interface ExprSchemaHint {
247247
* With any of the three, a `type-mismatch` (text or a boolean ordered /
248248
* arithmetic'd against a number) is an ERROR under that outcome's own code
249249
* and wording — the severity the nullable-comparison verdict already has at
250-
* the same sites. Absent: a fault reads as null (a formula field), and
251-
* `type-mismatch` stays the advisory warning whose "evaluates to null" text
252-
* is true there.
250+
* the same sites. Absent at a `record`-scoped site: a fault reads as null (a
251+
* formula field), and `type-mismatch` stays the advisory warning whose
252+
* "evaluates to null" text is true there. Absent at a `'flattened'` (flow)
253+
* site: `type-mismatch-run-may-fail`, a warning saying the run fails where
254+
* the condition faults (#29959) — a flow condition never reads null.
253255
*/
254256
faultOutcome?: ExprFaultOutcome;
255257
}
@@ -382,7 +384,11 @@ const TYPE_MISMATCH_FAULT_ARMS: {
382384
* declares the site's fault outcome (`faultOutcome`, #29904 / #29926):
383385
* there the fault is not a null but a refused write, a failed flow run or a
384386
* rule that never applies, each under its own code
385-
* ({@link TYPE_MISMATCH_FAULT_ARMS}).
387+
* ({@link TYPE_MISMATCH_FAULT_ARMS}). In a flattened (flow) condition with
388+
* no declared outcome it is `type-mismatch-run-may-fail`, still a warning,
389+
* worded for the failed run a fault there is (#29959); a flattened
390+
* condition's `record.<field>` / `previous.<field>` read is judged as its
391+
* bare name is.
386392
* - `date-text-arithmetic` / `date-duration-value` (**error**, #28944): what
387393
* the Timestamp typing passes, re-checked with a date field declared as the
388394
* text the runtime holds — see {@link dateTextIssue}.
@@ -399,7 +405,9 @@ function typeSoundnessIssue(
399405
const mismatch = firstTypeMismatch(source, celFieldTypes, scope);
400406
if (!mismatch) return dateTextIssue(source, celFieldTypes, scope, role);
401407
const reference = mismatch.field
402-
? (scope === 'record' ? `record.${mismatch.field}` : mismatch.field)
408+
? (mismatch.root !== undefined
409+
? `${mismatch.root}.${mismatch.field}`
410+
: scope === 'record' ? `record.${mismatch.field}` : mismatch.field)
403411
: undefined;
404412
const ref = reference !== undefined ? `\`${reference}\`` : null;
405413
if (mismatch.category === 'date-arith') {
@@ -420,35 +428,53 @@ function typeSoundnessIssue(
420428
const heldKind = mismatch.celType === 'bool' ? 'boolean' : 'text';
421429
const held = heldKind === 'boolean' ? 'a boolean' : 'text';
422430
const subject = ref ? `${ref} holds ${held}` : `${held === 'a boolean' ? 'a boolean' : 'a text'} field`;
431+
const params = {
432+
operands: mismatch.operands,
433+
operator: mismatch.operator,
434+
held: heldKind,
435+
...(reference !== undefined ? { reference } : {}),
436+
};
437+
// [#29904] Measured on the evaluator: `record.name > 5` faults on `"abc"`
438+
// and on null, and the ADR-0032 §1c rescue answers only numeric text
439+
// (`"7"`). `size()` answers text; `double()` / `int()` validate clean but
440+
// fault on text that is not a number — so the hint says so.
441+
const operand = reference ?? (heldKind === 'boolean' ? 'the field' : 'the text');
442+
const convert = heldKind === 'boolean'
443+
? 'Compare a boolean with `true` / `false`, or use a number field.'
444+
: `Compare like with like: use a number field, compare text with text, or convert ` +
445+
`explicitly — \`size(${operand})\` for its length, \`double(${operand})\` for its value ` +
446+
`(which itself faults on text that is not a number).`;
447+
const faults =
448+
`type mismatch \`${mismatch.operands}\` — ${subject} but is used with \`${mismatch.operator}\` ` +
449+
`against a number. CEL has no such operation, so wherever the value is not numeric text ` +
450+
`(an empty value included) the expression faults`;
423451
if (faultOutcome !== undefined) {
424-
// [#29904] Measured on the evaluator: `record.name > 5` faults on `"abc"`
425-
// and on null, and the ADR-0032 §1c rescue answers only numeric text
426-
// (`"7"`). `size()` answers text; `double()` / `int()` validate clean but
427-
// fault on text that is not a number — so the hint says so.
428-
const operand = reference ?? (heldKind === 'boolean' ? 'the field' : 'the text');
429-
const convert = heldKind === 'boolean'
430-
? 'Compare a boolean with `true` / `false`, or use a number field.'
431-
: `Compare like with like: use a number field, compare text with text, or convert ` +
432-
`explicitly — \`size(${operand})\` for its length, \`double(${operand})\` for its value ` +
433-
`(which itself faults on text that is not a number).`;
434452
// [#29926] One code per outcome: a code names ONE message template
435453
// (`expression-refusal.ts`), and the three outcomes are three sentences.
436454
const arm = TYPE_MISMATCH_FAULT_ARMS[faultOutcome];
437455
return {
438456
severity: 'error',
457+
issue: refusal(arm.code, params, source, `${faults}, and here ${arm.clause} ${convert}`),
458+
};
459+
}
460+
if (scope === 'flattened') {
461+
// [#29959] A flattened condition is a flow's, and the engine's
462+
// `evaluateCondition` throws on a fault (ADR-0032 §1c) on every flow: it
463+
// never reads null. The caller declared no outcome because what the run
464+
// binds under the name is not proven to be the field's value — a flow
465+
// that is not record-triggered is handed whatever its entrance carries
466+
// (an API request body, an action's partial record, a parent's record,
467+
// or nothing), so the mismatch stays a warning, worded for the run.
468+
return {
469+
severity: 'warning',
439470
issue: refusal(
440-
arm.code,
441-
{
442-
operands: mismatch.operands,
443-
operator: mismatch.operator,
444-
held: heldKind,
445-
...(reference !== undefined ? { reference } : {}),
446-
},
471+
'type-mismatch-run-may-fail',
472+
params,
447473
source,
448-
`type mismatch \`${mismatch.operands}\` — ${subject} but is used with \`${mismatch.operator}\` ` +
449-
`against a number. CEL has no such operation, so wherever the value is not numeric text ` +
450-
`(an empty value included) the expression faults, and here ${arm.clause} ` +
451-
convert,
474+
`${faults}, and a flow condition that faults when it is evaluated fails the run: the flow stops ` +
475+
`at this condition and the work it exists to do is not done (it does not read null). Whether ` +
476+
`${ref ?? 'the field'} holds ${held} there depends on what the run binds — on a flow that is not ` +
477+
`record-triggered, whatever started it — so this is a warning, not a refusal. ${convert}`,
452478
),
453479
};
454480
}

0 commit comments

Comments
 (0)