Skip to content

Commit 01316bb

Browse files
committed
fix(formula): date-text-ordering names the ordering's own operator, operands and counterpart (#38959 item 4, L2 S1)
In a mixed source the Timestamp typing's first fault need not be the kept ordering, and the first text field need not be its counterpart. The #32595 walk now reports the comparison it keeps (an ordering first, then an equality), and validate.ts reads the params and sentence from it. Grade and code are unchanged: field and root, which grade under bareNamesUnproven, are untouched. Lint: the #30026 counter comment and note say which codes are softened. Claude-Session: https://claude.ai/code/session_01QSeKYnrQ7UMtHofKQVjcH2 Co-authored-by: Claude <noreply@anthropic.com>
1 parent 0fee6f4 commit 01316bb

6 files changed

Lines changed: 160 additions & 28 deletions

File tree

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

Lines changed: 74 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1022,12 +1022,17 @@ const DATE_TEXT_COMPARISON_OPS: ReadonlySet<string> = new Set([...ORDERING_OPS,
10221022
* gate asks for it, so its answer is the one it gave before (see
10231023
* {@link firstTypeMismatch}'s `options`).
10241024
*/
1025-
function comparesDateTextAgainstUndeclared(source: string, env: Environment, macroElements = true): boolean {
1025+
function comparesDateTextAgainstUndeclared(
1026+
source: string,
1027+
env: Environment,
1028+
macroElements = true,
1029+
scope: 'record' | 'flattened' = 'record',
1030+
): KeptDateTextComparison | null {
10261031
let ast: unknown;
10271032
try {
10281033
ast = env.parse(rewriteNullableTernary(rewriteIndexedHas(source))).ast;
10291034
} catch {
1030-
return true;
1035+
return {};
10311036
}
10321037
/** The CEL type `node` checks to on its own, or `undefined` when it does not check. */
10331038
const typeOf = (node: unknown): string | undefined => {
@@ -1095,21 +1100,50 @@ function comparesDateTextAgainstUndeclared(source: string, env: Environment, mac
10951100
};
10961101
/** An element of the list `receiver` computes: `receiver[0]`. */
10971102
const elementOf = (receiver: unknown): CelNode => ({ op: '[]', args: [receiver, { op: 'value', args: 0n }] });
1103+
// [#38959 item 4] The whole source is walked, not stopped at the first
1104+
// comparison that keeps the verdict: the one reported is the first ORDERING
1105+
// (`<` `<=` `>` `>=`), then the first equality, so the operator, operands and
1106+
// counterpart named are the comparison's own, never the Timestamp typing's
1107+
// first fault elsewhere in the source (`'Due: ' + record.due_date == 'x' &&
1108+
// record.due_date < record.title` names `<`, not `+`).
10981109
let found = false;
1110+
let ordering: KeptDateTextComparison | undefined;
1111+
let equality: KeptDateTextComparison | undefined;
1112+
/** A side's type as the Timestamp typing spells it: a date field's text is a Timestamp there. */
1113+
const spelled = (t: string | undefined): string =>
1114+
t === DATE_TEXT_CEL_TYPE ? 'google.protobuf.Timestamp' : t ?? 'dyn';
1115+
const keep = (v: CelNode, kept: KeptDateTextComparison): void => {
1116+
found = true;
1117+
if (ORDERING_OPS.has(v.op)) ordering ??= kept;
1118+
else equality ??= kept;
1119+
};
10991120
const visit = (v: unknown, bound: ReadonlyMap<string, CelNode>): void => {
1100-
if (found) return;
1121+
if (ordering) return;
11011122
if (Array.isArray(v)) { for (const child of v) visit(child, bound); return; }
11021123
if (!isCelNode(v)) return;
11031124
if (DATE_TEXT_COMPARISON_OPS.has(v.op) && Array.isArray(v.args) && v.args.length === 2) {
11041125
// Without `macroElements` a macro variable proves nothing, as before #38959.
1105-
if (!macroElements && bound.size > 0 && readsBound(v.args, bound)) { found = true; return; }
1126+
if (!macroElements && bound.size > 0 && readsBound(v.args, bound)) { keep(v, { operator: v.op }); return; }
11061127
const [sa, sb] = (v.args as unknown[]).map((operand) => substitute(operand, bound));
11071128
const [a, b] = [sa.node, sb.node];
11081129
const [ta, tb] = [typeOf(a), typeOf(b)];
11091130
// A macro variable whose element does not check proves nothing: keep the verdict.
1110-
if ((sa.read && ta === undefined) || (sb.read && tb === undefined)) { found = true; return; }
1111-
if ((ta === DATE_TEXT_CEL_TYPE && !declared(b, tb)) || (tb === DATE_TEXT_CEL_TYPE && !declared(a, ta))) {
1112-
found = true;
1131+
if ((sa.read && ta === undefined) || (sb.read && tb === undefined)) {
1132+
keep(v, { operator: v.op, operands: `${spelled(ta)} ${v.op} ${spelled(tb)}` });
1133+
return;
1134+
}
1135+
const dateFirst = ta === DATE_TEXT_CEL_TYPE && !declared(b, tb);
1136+
if (dateFirst || (tb === DATE_TEXT_CEL_TYPE && !declared(a, ta))) {
1137+
const [other, otherType] = dateFirst ? [b, tb] : [a, ta];
1138+
// The counterpart is named only where it is a text field read; a
1139+
// computed text (`isoDate(today())`, `upper(…)`) or a macro's element
1140+
// is no reference to parse.
1141+
const read = otherType === 'string' ? typedFieldRef(other, scope) : null;
1142+
keep(v, {
1143+
operator: v.op,
1144+
operands: `${spelled(ta)} ${v.op} ${spelled(tb)}`,
1145+
...(read ? { counterpart: read.written } : {}),
1146+
});
11131147
return;
11141148
}
11151149
}
@@ -1125,7 +1159,21 @@ function comparesDateTextAgainstUndeclared(source: string, env: Environment, mac
11251159
visit(v.args, bound);
11261160
};
11271161
visit(ast, new Map());
1128-
return found;
1162+
return found ? ordering ?? equality ?? {} : null;
1163+
}
1164+
1165+
/**
1166+
* [#38959 item 4] The comparison {@link comparesDateTextAgainstUndeclared}
1167+
* found keeping the #32595 verdict, as written: its `operator`, its
1168+
* `operands` spelled as the Timestamp typing spells them, and `counterpart`,
1169+
* the text field read it orders the date against (`record.title`, `title`),
1170+
* present only where the counterpart is one. Every member is absent where no
1171+
* comparison is reported (an unparseable source keeps the verdict unnamed).
1172+
*/
1173+
interface KeptDateTextComparison {
1174+
readonly operator?: string;
1175+
readonly operands?: string;
1176+
readonly counterpart?: string;
11291177
}
11301178

11311179
/**
@@ -1440,6 +1488,16 @@ export function firstTypeMismatch(
14401488
* `type-mismatch*` sentence that says the expression faults.
14411489
*/
14421490
dateTextOrdering?: true;
1491+
/**
1492+
* [#38959 item 4] With `dateTextOrdering`, the comparison that keeps the
1493+
* verdict, as written — its operator, its operands and its text counterpart
1494+
* ({@link KeptDateTextComparison}). `operator`, `operands` and `field` above
1495+
* are the Timestamp typing's first fault, which a mixed source need not
1496+
* place on that comparison (`'Due: ' + record.due_date == 'x' &&
1497+
* record.due_date < record.title` faults first on `+`), and `field` keeps the
1498+
* grade it gives (#30025), so the sentence reads this instead.
1499+
*/
1500+
ordering?: KeptDateTextComparison;
14431501
} | null {
14441502
if (typeof source !== 'string' || !source.trim()) return null;
14451503
// An all-`dyn` record can never fault an overload — skip the parse entirely.
@@ -1490,17 +1548,22 @@ export function firstTypeMismatch(
14901548
* the mismatch kept is the ordering, not a fault the run meets.
14911549
*/
14921550
let keptOrdering = false;
1551+
let kept: KeptDateTextComparison | null = null;
14931552
const confirmAgainstDateText = (
14941553
m: RegExpExecArray,
14951554
recordRoots?: Readonly<Record<string, FieldCelType>>,
14961555
keepUndeclared = true,
14971556
): RegExpExecArray | null => {
14981557
keptOrdering = false;
1558+
kept = null;
14991559
if (!DATE_CEL_TYPES.has(m[1]) && !DATE_CEL_TYPES.has(m[3])) return m;
15001560
const dateTextEnv = buildTypedEnv(bareTypes, scope, 'date-text', recordRoots);
15011561
const r = unsoundOverload(dateTextEnv);
15021562
if (r && textOrBool(r)) return r[1] === DATE_TEXT_CEL_TYPE || r[3] === DATE_TEXT_CEL_TYPE ? m : r;
1503-
keptOrdering = keepUndeclared && comparesDateTextAgainstUndeclared(source, dateTextEnv, options.macroElements ?? true);
1563+
kept = keepUndeclared
1564+
? comparesDateTextAgainstUndeclared(source, dateTextEnv, options.macroElements ?? true, scope)
1565+
: null;
1566+
keptOrdering = kept !== null;
15041567
return keptOrdering ? m : null;
15051568
};
15061569
try {
@@ -1524,7 +1587,7 @@ export function firstTypeMismatch(
15241587
return {
15251588
operator, operands, celType, category: 'type-mismatch',
15261589
field: offendingField(source, bareTypes, celType, scope),
1527-
...(keptOrdering ? { dateTextOrdering: true as const } : {}),
1590+
...(keptOrdering ? { dateTextOrdering: true as const, ordering: kept ?? {} } : {}),
15281591
};
15291592
}
15301593
// [#29959] A flattened condition reads the same field as `record.<field>`
@@ -1578,7 +1641,7 @@ export function firstTypeMismatch(
15781641
operator: r[2], operands: `${r[1]} ${r[2]} ${r[3]}`, celType, category: 'type-mismatch',
15791642
field: read?.field ?? null,
15801643
...(read ? { root: read.root } : {}),
1581-
...(keptOrdering ? { dateTextOrdering: true as const } : {}),
1644+
...(keptOrdering ? { dateTextOrdering: true as const, ordering: kept ?? {} } : {}),
15821645
};
15831646
} catch {
15841647
// A parse/other fault is the syntax checker's job (celEngine.compile); this

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

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -818,6 +818,39 @@ const PINS: { readonly [C in ExpressionRefusalCode]: readonly [Pin<C>, ...Pin<C>
818818
'first with `date(…)`, which reads null where the text is not a date. To compare the texts on ' +
819819
'purpose, write the date side as `string(…)`.',
820820
},
821+
// [#38959 item 4, L2 S1] The params are the ordering's own in a mixed
822+
// source: the Timestamp typing faults first on the concatenation (`+`),
823+
// yet the operator, operands and counterpart named are the `<`'s.
824+
{
825+
produce: () =>
826+
onlyWarning('predicate', "'Due: ' + record.due == 'x' && record.due < record.name", {
827+
scope: 'record', fieldTypes: { due: 'date', name: 'text' },
828+
}),
829+
params: { operands: 'google.protobuf.Timestamp < string', operator: '<', reference: 'record.name' },
830+
message:
831+
'date ordered against text `google.protobuf.Timestamp < string` — `<` orders a date field against ' +
832+
'`record.name`, which holds text. The runtime holds a date field as its text (`YYYY-MM-DD`; a datetime as ' +
833+
'its ISO-8601 instant), so this comparison evaluates as a text comparison and does not fault: it answers ' +
834+
'which text sorts first, character by character, not which date is later. To compare dates, parse the text ' +
835+
'first with `date(record.name)`, which reads null where the text is not a date. To compare the texts on ' +
836+
'purpose, write the date side as `string(…)`.',
837+
},
838+
// [L2 S1] A text field read elsewhere in the source is not the
839+
// counterpart: `isoDate(today())` is computed text, so no reference.
840+
{
841+
produce: () =>
842+
onlyError('predicate', "record.name == 'a' && record.due > isoDate(today())", {
843+
scope: 'record', fieldTypes: { due: 'date', name: 'text' }, faultOutcome: 'fail-closed',
844+
}),
845+
params: { operands: 'google.protobuf.Timestamp > string', operator: '>' },
846+
message:
847+
'date ordered against text `google.protobuf.Timestamp > string` — `>` orders a date field against ' +
848+
'a text value. The runtime holds a date field as its text (`YYYY-MM-DD`; a datetime as ' +
849+
'its ISO-8601 instant), so this comparison evaluates as a text comparison and does not fault: it answers ' +
850+
'which text sorts first, character by character, not which date is later. To compare dates, parse the text ' +
851+
'first with `date(…)`, which reads null where the text is not a date. To compare the texts on ' +
852+
'purpose, write the date side as `string(…)`.',
853+
},
821854
],
822855
'field-near-miss': [
823856
{

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

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -321,10 +321,18 @@ export interface ExpressionRefusalParams {
321321
* formula field, a flow condition with no declared outcome or an unproven
322322
* bare name, and an ERROR at a site that declares its fault outcome (a
323323
* fail-closed site, an advisory rule, a record-triggered flow, a sweep of
324-
* its object). `operands` are the CEL operand types as the Timestamp typing
325-
* reports them (`google.protobuf.Timestamp > string`), and `reference` is
326-
* the text counterpart as written, when it is a field read. Served under the
327-
* `type-mismatch*` codes until this code gave the sentence its own name.
324+
* its object). Every param is that comparison's own, wherever else the
325+
* source faults the Timestamp typing first (`'Due: ' + record.due_date ==
326+
* 'x' && record.due_date < record.title` names `<`): `operator` is its
327+
* operator — an ordering wherever the source holds one, else the `==` / `!=`
328+
* the #32595 walk also keeps; `operands` are its operand types as the
329+
* Timestamp typing spells them (`google.protobuf.Timestamp > string`); and
330+
* `reference` is its text counterpart as written, present only where that
331+
* counterpart is a text field read (`record.title`, an index read by its
332+
* member spelling, a bare `title` in a flow condition) — absent for computed
333+
* text (`isoDate(today())`), whatever other text field the source reads.
334+
* Served under the `type-mismatch*` codes until this code gave the sentence
335+
* its own name.
328336
*/
329337
'date-text-ordering': { readonly operands: string; readonly operator: string; readonly reference?: string };
330338
/**

‎packages/formula/src/validate-date-text-arithmetic.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1177,6 +1177,25 @@ describe('a date ordered against a text field is served under its own code, with
11771177
}
11781178
});
11791179

1180+
it.each(SITES)('at %s the params and sentence are the ordering\'s own in a mixed source (L2 S1)', (_site, hint, grade) => {
1181+
// The Timestamp typing faults first on the concatenation (`+`); the ordering is the `<`.
1182+
const concat = "'Due: ' + record.due_date == 'x' && record.due_date < record.title";
1183+
expect(graded(concat, hint), concat).toEqual([`${grade}:date-text-ordering`]);
1184+
const a = only(concat, hint);
1185+
expect(a.params).toEqual({ operands: 'google.protobuf.Timestamp < string', operator: '<', reference: 'record.title' });
1186+
expect(a.message).toMatch(/^date ordered against text `google\.protobuf\.Timestamp < string` — `<` orders a date field against `record\.title`, /);
1187+
expect(a.message).toContain('`date(record.title)`');
1188+
// A text field read elsewhere is not the counterpart: `isoDate(today())` is.
1189+
const computed = "record.title == 'a' && record.due_date > isoDate(today())";
1190+
expect(graded(computed, hint), computed).toEqual([`${grade}:date-text-ordering`]);
1191+
const b = only(computed, hint);
1192+
expect(b.params).toEqual({ operands: 'google.protobuf.Timestamp > string', operator: '>' });
1193+
expect(b.message).toContain('`>` orders a date field against a text value.');
1194+
expect(b.message).not.toContain('record.title');
1195+
expect(run(concat), concat).toEqual({ ok: true, value: expect.any(Boolean) });
1196+
expect(run(computed), computed).toEqual({ ok: true, value: expect.any(Boolean) });
1197+
});
1198+
11801199
it.each(SITES)('at %s a date-text fault in the same source is the finding, never the ordering sentence', (_site, hint) => {
11811200
const source = "record.due_date > record.title && record.due_date - record.borrow_date > duration('1h')";
11821201
const [got] = graded(source, hint);

‎packages/formula/src/validate.ts‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -684,15 +684,24 @@ function typeSoundnessIssue(
684684
// `type-mismatch*` sentence, which says the expression faults: the run
685685
// holds the date field as its text and answers the comparison as a text
686686
// comparison. One sentence at every site, so one code.
687-
const counterpart = ref ? `${ref}, which holds text` : 'a text value';
688-
const parse = reference !== undefined ? `\`date(${reference})\`` : '`date(…)`';
687+
// Its params and sentence are the kept comparison's own, never the
688+
// Timestamp typing's first fault: in a mixed source that may sit elsewhere
689+
// (`'Due: ' + record.due_date == 'x' && record.due_date < record.title`
690+
// faults first on `+`), and the field it names need not be the counterpart
691+
// (`record.title == 'a' && record.due_date > isoDate(today())`).
692+
const kept = mismatch.ordering ?? {};
693+
const operator = kept.operator ?? mismatch.operator;
694+
const operands = kept.operands ?? mismatch.operands;
695+
const counterpartRef = kept.counterpart;
696+
const counterpart = counterpartRef !== undefined ? `\`${counterpartRef}\`, which holds text` : 'a text value';
697+
const parse = counterpartRef !== undefined ? `\`date(${counterpartRef})\`` : '`date(…)`';
689698
return dateTextOver({
690699
severity: outcome !== undefined ? 'error' : 'warning',
691700
issue: refusal(
692701
'date-text-ordering',
693-
{ operands: mismatch.operands, operator: mismatch.operator, ...(reference !== undefined ? { reference } : {}) },
702+
{ operands, operator, ...(counterpartRef !== undefined ? { reference: counterpartRef } : {}) },
694703
source,
695-
`date ordered against text \`${mismatch.operands}\` — \`${mismatch.operator}\` orders a date field against ` +
704+
`date ordered against text \`${operands}\` — \`${operator}\` orders a date field against ` +
696705
`${counterpart}. The runtime holds a date field as its text (\`YYYY-MM-DD\`; a datetime as its ISO-8601 ` +
697706
`instant), so this comparison evaluates as a text comparison and does not fault: it answers which text ` +
698707
`sorts first, character by character, not which date is later. To compare dates, parse the text first ` +

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

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2614,15 +2614,15 @@ export function validateStackExpressions(stack: AnyRec): ExprIssue[] {
26142614
*/
26152615
export function runStackExpressionPasses(stack: AnyRec, options: StackExpressionOptions): ExprIssue[] {
26162616
const issues: ExprIssue[] = [];
2617-
// [#30026] How many `type-mismatch-run-may-fail` warnings {@link check} has
2617+
// [#30026] How many softened flow-condition warnings {@link check} has
26182618
// served: a flow whose own count moved is one an author is told why of,
26192619
// where the reason is the flow's own (the time-relative note in the flow
2620-
// walk). Only that code, and (#38959 item 4) `date-text-ordering` served as
2621-
// a warning at a flow condition, the date-against-text ordering that verdict
2622-
// was served under before it had its own code, softened the same way: the
2623-
// date verdicts' `-run-may-fail` arm is an error whatever the outcome, so a
2624-
// sweep of another object does not soften it and there is nothing to
2625-
// explain.
2620+
// walk). Two codes are softened that way: `type-mismatch-run-may-fail`, and
2621+
// (#38959 item 4) a `date-text-ordering` warning at a flow condition, which
2622+
// is the date-against-text ordering that used to be served as
2623+
// `type-mismatch-run-may-fail`. No other code is: the date verdicts'
2624+
// `-run-may-fail` arm is an error whatever the outcome, so a sweep of
2625+
// another object does not soften it and there is nothing to explain.
26262626
let runMayFailServed = 0;
26272627
// [#22019] See {@link StackExpressionOptions.runtimeWriteType}: on an object
26282628
// write only the passes over the object's own body judge: the field-formula
@@ -3919,11 +3919,11 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression
39193919
message:
39203920
`this time-relative flow sweeps '${sweepObject}' (config.timeRelative.object), so each run's record is a ` +
39213921
`row of '${sweepObject}', while its conditions are checked against the fields of '${startObject}' (the ` +
3922-
`start node's config.objectName). That is why a type mismatch in its conditions is a warning here and ` +
3922+
`start node's config.objectName). That is why a type mismatch, or a date ordered against text, in its conditions is a warning here and ` +
39233923
`not a refusal: the names hold a '${sweepObject}' row, not the '${startObject}' fields they were checked ` +
39243924
`against. Set config.objectName to '${sweepObject}', or remove it, as flow-time-relative-object-mismatch ` +
39253925
`asks of this start: the conditions are then checked ` +
3926-
`against the swept object, and a type mismatch in them is refused, as on a record-triggered flow.`,
3926+
`against the swept object, and either is refused there, as on a record-triggered flow.`,
39273927
source: startObject,
39283928
severity: 'warning',
39293929
...(startIndex >= 0 ? { path: `flows[${flowIndex}].nodes[${startIndex}].config.objectName` } : {}),

0 commit comments

Comments
 (0)