Skip to content

Commit 7d6692e

Browse files
fix(formula): a date field compared with addDays(today(), N), date() or timestamp() evaluates like the today() comparison (#38152)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoURTNJL3cZKT49oTxcAixga)_ Fixes #38135 Clause-②: no Metadata-protocol: semantic Skills-docs: none — `skills/objectstack-formula/SKILL.md` already lists `addDays`, `addMonths`, `date`, `datetime` and `timestamp` as returning a timestamp and never tells an author to avoid comparing one with a date field, so what it teaches now holds at run time as written repo:objectstack#3 · os-tesla · session_01L9qibwCgpPyKkN8vfDFgi2 ## 维护者速读 - 用户能看到什么变化:流程、校验规则或公式里拿日期字段和「30 天后」「下个月」这类算出来的日期比较时,现在按字面意思算;以前比大小每次运行都报错,比相等在正好那天也答「不相等」,流程被悄悄跳过。 - 为什么做:属于「表达式校验与作者护栏」,替编写流程的管理员和代写流程的 AI 助手解决「保存通过、运行时却不按预期执行」。 - 出错会怎样:已上线的流程里用了这种写法的,升级后会开始触发(发邮件、建记录等),这正是作者本来想要的;本改动可整体撤回。 - 要你做什么:无。 ## What changes A `date` field reaches a flow condition, a validation rule or a formula as its `YYYY-MM-DD` text. `celEngine.evaluate` converts that text when it meets a Timestamp, in two rewrites in `packages/formula/src/cel-engine.ts`: - the ADR-0032 §1c retry (`rewriteFaultedOperands`, #1530 / #7098) for an ordering that faulted, which asks `operandKind` whether the other side is a Timestamp; - the #3183 equality rewrite (`rewriteTemporalCallEquality`), which asks `isTemporalCall`. Each kept its own hand list: `operandKind` knew `today` / `now` / `daysFromNow` / `daysAgo` plus `date` / `datetime`; `isTemporalCall` knew only the first four. The environment also declares `addDays`, `addMonths`, `addWorkingDays`, `addWorkingHours` and cel-js's `timestamp` as returning a Timestamp, and neither list had them. Measured on `origin/main` 5b8ca36 (`record.due_date = '2026-11-29'`, the day after the run): | condition | before | after | |:---|:---|:---| | `record.due_date < addDays(today(), 30)` | faults: `no such overload` (the text against a `google.protobuf.Timestamp`) | `true` | | `record.due_date < addMonths(today(), 1)`, `< addDays(record.borrow_date, 30)`, `< timestamp("2030-01-01T00:00:00Z")` | faults, same | evaluates | | `record.due_date == addDays(today(), 1)` | **`false`**, no error | `true` | | `record.due_date != addDays(today(), 1)` | **`true`**, no error | `false` | | `record.due_date == date("2026-11-29")`, `== timestamp("2026-11-29T00:00:00Z")` | **`false`**, no error | `true` | | `record.due_date == daysFromNow(1)` (control) | `true` | `true` | Through the flow runtime (`AutomationEngine.execute`, start condition): the ordering returned `success: false` ("condition failed to evaluate as CEL"), and the equality returned `success: true, skipped: true` with the next node run 0 times. All three save doors accept every one of these spellings, before and after (readings in #37848's report). The fix: one set, `timestampReturningFunctions()`, read once from `getDefinitions()` of an environment built by the same constructor the engine evaluates on (global functions whose every overload returns `google.protobuf.Timestamp`). `isTimestampCall` asks it, and both rewrites ask `isTimestampCall`. The two hand lists are gone, the equality rewrite's cheap source gate reads the same set, and a function registered later with a Timestamp return is covered by both rewrites with no edit. None of the three §1c conditions changes (an operator that faults on a mixed pair, a counterpart proven a Timestamp, an operand whose own value is ISO date text), and the equality arm still wraps only a field reference, per occurrence. One existing pin moves, by the seat's ruling that the equality path also takes `date` / `datetime`: the #7168 idempotence case `date(record.due) == previous.due` now rewrites to `date(record.due) == date(previous.due)`. The coerced side is still never wrapped twice. A Date-valued `previous.due` passes through `date()` (still `true`); two ISO texts used to answer a silent `false` and now answer `true`. Null and non-date operands answer as before (measured on both trees: `false` for `==`, `true` for `!=`). - `.changeset/38135-date-field-against-timestamp-call.md`: `minor` for `@objectstack/formula`, both declaration lines, and in plain words that deployed flows whose condition failed or was skipped start firing. ## Tests - `packages/formula/src/cel-overload-retry-scope.test.ts`, new top-level describe: ordering against `addDays(today(), N)` (either side), `addMonths`, `addDays(record.borrowed, 14)`, `timestamp(…)`; answers equal the `daysFromNow(30)` spelling across the boundary days; a datetime field's instant meets `addDays(now(), 1)`; non-date text (`soon`, `7`) stays a fault. - `packages/formula/src/cel-engine.test.ts`, new top-level describe: the rewrite wraps the field opposite `addDays` / `addMonths` / `date` / `datetime` / `timestamp`, and leaves `daysBetween(…) == 0`, `round(…)` and an already-coerced operand alone; `==` / `!=` answer what `daysFromNow(1)` answers on the day and the day before; a string literal beside it keeps its answer. **Drift pin**: enumerates every global Timestamp signature `getDefinitions()` declares, needs a probe row per name (a new function fails it until it has one), checks the set both rewrites ask equals it, and checks each function meets a field holding its own instant under `==`, `!=`, `<` and `<=` (working-day functions with a calendar). - `packages/services/service-automation/src/flow-registration-schema-e2e.test.ts`, new top-level describe (kernel rig, `library_loan.due_date: date`, clock pinned): `record.due_date < addDays(today(), 30)`, `addDays(today(), 30) > record.due_date` and `record.due_date == addDays(today(), 1)` fire the next node exactly as their `daysFromNow` spellings do; a loan outside the bound is skipped, not failed; `registerFlow` accepts the spellings with no date advisory. - Door controls, by the seat's ruling (the doors do not change): `packages/lint/src/validate-expressions.test.ts` (`os validate`'s pass) has no finding for six spellings at start, edge and `decision` conditions; `packages/runtime/src/domains/meta-flow-condition-record-date-text.test.ts` (the publish door on the real `ObjectQL` rig) publishes three spellings and they go `active`. <details><summary>Local runs (head daf4843)</summary> Exit codes captured before any pipe; tests, builds and typechecks under `scripts/pm/os-verify-lock.sh`. - `pnpm --filter @objectstack/formula exec vitest run --maxWorkers=2`: Test Files 72 passed (72), Tests 2181 passed (2181). `pnpm --filter @objectstack/formula run typecheck`: VERDICT command-exit 0 (after a full declaration build of the formula closure). - `packages/services/service-automation`: `vitest run src/flow-registration-schema-e2e.test.ts` Tests 10 passed (10). Against the formula dist built from `main` the two new run pins were red (2 failed, 8 passed), green once the formula dist was rebuilt from this branch: the dist leg of the before/after. - `packages/lint`: `vitest run src/validate-expressions.test.ts -t 38135` Tests 3 passed. `packages/runtime`: `vitest run src/domains/meta-flow-condition-record-date-text.test.ts` Tests 7 passed (7). - `node scripts/pm/dispatch-gates.mjs --commands`: 72 families derived for this diff, all 72 run; `--ran`: "72 derived famil(ies) accounted for — 72 run, 0 NOT-MEASURED (a DERIVED zero — all 72 recorded an exit code and none of them is 3)". Two first answered non-zero for a missing build and passed after the full declaration build (`turbo run build --filter='./packages/**'`): `check:dts-closure` (1, then 0: "265/265 declared declaration file(s) present") and `check:dual-build-cjs-loads` (3, then 0). `check-plugin-teardown-shape --self-test` needed its pinned fixture commit fetched into the shallow clone. - Type-check lanes for `lint`, `runtime` and `service-automation` (test files only) and `test:repo`: CI's. - Dogfood: n/a (no `!` in the title, no `(narrowing)` arm). </details> <details><summary>Ablation (committed first, mutated through scripts/ablation-replace.mjs, restored to the HEAD blob)</summary> Subject: `isTimestampCall` in `packages/formula/src/cel-engine.ts`, which both rewrites ask. Mutation: its set lookup replaced by the old four-name list (`['today', 'daysFromNow', 'daysAgo', 'now'].includes(…)`, marker `ABLATION-38135`); anchor 1 to 0, blob `b3e4963cec31` to `2fdcaff15a3b`. The formula suite imports `./cel-engine` from source, so no dist leg there. Red: `cel-engine.test.ts` + `cel-overload-retry-scope.test.ts` 13 failed / 109 passed: every new ordering and equality case, the CONTROL against `daysFromNow`, the datetime case and the drift pin; the "stays LOUD" case stayed green, as it should. Restored: blob `b3e4963cec31` = `HEAD:packages/formula/src/cel-engine.ts`, `git diff HEAD` empty, marker count 0. </details> ## Acceptance notes - `addWorkingDays` / `addWorkingHours` still fault in a flow condition for the reason they always did (no working calendar outside a formula or a stored field's `expression`); the drift pin exercises them with a calendar. - The Skills-docs line is `none` (see the line's reason). ## Verification Read first, by risk: 1. `packages/formula/src/cel-engine.ts`, `timestampReturningFunctions` / `isTimestampCall`, and the `operandKind` hunk: what counts as a Timestamp counterpart now. 2. The same file, `rewriteTemporalCallEquality`: the gate and the two wrap lines. 3. `packages/formula/src/cel-engine.test.ts`, the moved #7168 idempotence pin. Two-minute check: `pnpm --filter @objectstack/formula exec vitest run --maxWorkers=2 src/cel-engine.test.ts src/cel-overload-retry-scope.test.ts -t 38135` shows 14 passing tests. --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibwCgpPyKkN8vfDFgi2)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent bbe3ced commit 7d6692e

8 files changed

Lines changed: 378 additions & 20 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/formula': minor
3+
---
4+
5+
fix(formula): a date field compared with `addDays(today(), N)`, `addMonths(…)`, `date(…)`, `timestamp(…)` or the working-day functions evaluates the way the `today()` comparison does
6+
7+
Clause-②: no
8+
Metadata-protocol: semantic
9+
10+
A `date` field reaches a flow condition, a validation rule or a formula as its `YYYY-MM-DD` text. The runtime already converts that text when it meets `today()`, `now()`, `daysFromNow()` or `daysAgo()`. It missed every other call that returns a timestamp, though every save door (`os validate`, publish, flow registration) accepted the condition:
11+
12+
- An ordering such as `record.due_date < addDays(today(), 30)` failed on every run with `no such overload: dyn<string> < google.protobuf.Timestamp`. A flow with it as its start condition never ran its steps.
13+
- An equality such as `record.due_date == addDays(today(), 1)` answered `false` on the very day it names (and `!=` answered `true`), with no error, so the flow was skipped as "condition not met". `== date("2026-06-21")` and `== timestamp("2026-06-21T00:00:00Z")` did the same.
14+
15+
Both now answer what the `daysFromNow(N)` spelling of the same comparison answers. The set of functions converted is read from the functions the engine declares as returning a timestamp, so a function added later is covered too.
16+
17+
**What changes for a deployed app.** Nothing to rewrite. A flow, validation rule or formula that already uses one of these comparisons starts behaving as written: a flow whose start or decision condition failed or was skipped on every run now fires on the records the condition names. Review such flows before upgrading if they send email, create records or call out, since they will start doing so. An author who worked around the defect with `date(record.due_date) < addDays(today(), 30)` keeps the same answer.

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

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -562,13 +562,17 @@ as a `YYYY-MM-DD` string, and CEL treats a string and a timestamp as unequal —
562562
the natural "is it due today" predicate used to silently return `false`. The
563563
engine now rewrites temporal `==` / `!=` comparisons (coercing the field operand
564564
with `date(...)`), so `record.due_date == today()` matches on the calendar day.
565-
The counterpart may be a temporal **call** (`today()`, `now()`, `daysFromNow()`,
566-
`daysAgo()`) or a **binding that holds a `Date`** — which covers the
565+
The counterpart may be any **call that returns a timestamp** (`today()`, `now()`,
566+
`daysFromNow()`, `daysAgo()`, `addDays()`, `addMonths()`, `date()`, `datetime()`,
567+
`timestamp()`, `addWorkingDays()`, `addWorkingHours()`; #38135) or a **binding
568+
that holds a `Date`** — which covers the
567569
mixed-provenance comparison `record.due == previous.due`, where `previous`
568570
arrives from the driver as a `Date` while `record` arrives from a JSON payload as
569571
a `YYYY-MM-DD` string (#7168). This applies to formulas, defaults, validation
570-
rules, and hook/flow conditions. Ordering (`< > <= >=`) and string equality
571-
(`record.d == "2026-06-20"`) were always fine. The coercion is deliberately
572+
rules, and hook/flow conditions. Ordering (`< > <= >=`) against any of those
573+
calls converts the field the same way, so `record.due_date < addDays(today(), 30)`
574+
answers what `record.due_date < daysFromNow(30)` answers; string equality
575+
(`record.d == "2026-06-20"`) was always fine. The coercion is deliberately
572576
narrow — it requires one side to be a real `Date` and the other an ISO-8601
573577
date/date-time string — so a non-date string compared against a `Date` still
574578
answers `false` instead of being coerced into a match. This is the read-side

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

Lines changed: 97 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { describe, expect, it } from 'vitest';
22

3-
import { celEngine, rewriteTemporalEquality, collectCelRootIdentifiers } from './cel-engine';
3+
import { buildEnv, celEngine, rewriteTemporalEquality, collectCelRootIdentifiers, timestampReturningFunctions } from './cel-engine';
44
import { CEL_STDLIB_FUNCTIONS } from './validate';
55
import { buildWorkCalendar } from './work-calendar';
66
import type { Expression } from '@objectstack/spec';
@@ -594,8 +594,17 @@ describe('celEngine', () => {
594594
});
595595

596596
it('is idempotent — an already-coerced operand is not re-wrapped', () => {
597+
// [#38135] `date(…)` returns a Timestamp, so the call arm now wraps the
598+
// field opposite it, whatever that field holds; the coerced side is never
599+
// wrapped twice. A Date-valued `previous.due` passes through `date()`.
597600
expect(rewriteTemporalEquality('date(record.due) == previous.due', mixed))
598-
.toBe('date(record.due) == previous.due');
601+
.toBe('date(record.due) == date(previous.due)');
602+
expect(rewriteTemporalEquality('date(record.due) == date(previous.due)', mixed))
603+
.toBe('date(record.due) == date(previous.due)');
604+
expect(celEngine.evaluate(cel('date(record.due) == previous.due'), mixed)).toEqual({ ok: true, value: true });
605+
// Both ISO texts: the coerced side used to meet the other's text and answer a silent false.
606+
expect(celEngine.evaluate(cel('date(record.due) == previous.due'),
607+
{ record: { due: '2026-06-20' }, previous: { due: '2026-06-20' } })).toEqual({ ok: true, value: true });
599608
});
600609

601610
it('composes with the temporal-call arm on one expression', () => {
@@ -850,3 +859,89 @@ describe('collectCelRootIdentifiers', () => {
850859
expect(empty.ok).toBe(false);
851860
});
852861
});
862+
863+
// [#38135] A date field compared with a call that RETURNS a Timestamp other than
864+
// the four clock functions. The business case: a flow that runs on the day a loan
865+
// falls due tomorrow (`record.due_date == addDays(today(), 1)`). The field reaches
866+
// the run as its `YYYY-MM-DD` text; the #3183 equality rewrite paired it only with
867+
// `today` / `now` / `daysFromNow` / `daysAgo`, so the comparison answered a silent
868+
// `false` (and `!=` a silent `true`) on the very day it should match, and the flow
869+
// was skipped as "condition not met". `daysFromNow(1)` matched. Both rewrites now
870+
// ask one set read off the environment's declarations.
871+
describe('a date field compared with any Timestamp-returning call (#38135)', () => {
872+
const now = new Date('2026-06-20T08:00:00Z');
873+
const rec = (due: unknown) => ({ now, record: { due } });
874+
875+
it('the rewrite wraps the field opposite addDays / addMonths / date / datetime / timestamp', () => {
876+
expect(rewriteTemporalEquality('record.due == addDays(today(), 1)')).toBe('date(record.due) == addDays(today(), 1)');
877+
expect(rewriteTemporalEquality('addMonths(today(), 1) != previous.due')).toBe('addMonths(today(), 1) != date(previous.due)');
878+
expect(rewriteTemporalEquality('due == date("2026-06-21")')).toBe('date(due) == date("2026-06-21")');
879+
expect(rewriteTemporalEquality('record.due == datetime("2026-06-21T00:00:00Z")')).toBe('date(record.due) == datetime("2026-06-21T00:00:00Z")');
880+
expect(rewriteTemporalEquality('record.due == timestamp("2026-06-21T00:00:00Z")')).toBe('date(record.due) == timestamp("2026-06-21T00:00:00Z")');
881+
// A call that returns no Timestamp, and an already-coerced operand, are left alone.
882+
for (const src of ['daysBetween(today(), record.due) == 0', 'record.n == round(record.m)', 'date(record.due) == addDays(today(), 1)']) {
883+
expect(rewriteTemporalEquality(src), src).toBe(src);
884+
}
885+
});
886+
887+
it('matches on the day it names, as daysFromNow() does, and misses the day before', () => {
888+
for (const [src, control] of [
889+
['record.due == addDays(today(), 1)', 'record.due == daysFromNow(1)'],
890+
['record.due != addDays(today(), 1)', 'record.due != daysFromNow(1)'],
891+
['record.due == date("2026-06-21")', 'record.due == daysFromNow(1)'],
892+
['record.due == timestamp("2026-06-21T00:00:00Z")', 'record.due == daysFromNow(1)'],
893+
]) {
894+
for (const due of ['2026-06-21', '2026-06-20']) {
895+
expect(celEngine.evaluate(cel(src), rec(due)), `${src} over ${due}`).toEqual(celEngine.evaluate(cel(control), rec(due)));
896+
}
897+
}
898+
expect(celEngine.evaluate(cel('record.due == addDays(today(), 1)'), rec('2026-06-21'))).toEqual({ ok: true, value: true });
899+
expect(celEngine.evaluate(cel('record.due != addDays(today(), 1)'), rec('2026-06-21'))).toEqual({ ok: true, value: false });
900+
});
901+
902+
it('a string literal comparison beside it keeps its own answer', () => {
903+
expect(celEngine.evaluate(cel('record.due == "2026-06-19" || record.due == addDays(today(), 1)'), rec('2026-06-21')))
904+
.toEqual({ ok: true, value: true });
905+
expect(celEngine.evaluate(cel('record.due == "2026-06-19" || record.due == addDays(today(), 1)'), rec('2026-06-18')))
906+
.toEqual({ ok: true, value: false });
907+
});
908+
909+
// Drift pin: the set is read off `getDefinitions()`, so this enumerates every
910+
// global Timestamp signature the environment declares and needs a probe row for
911+
// each NAME. A function added with a Timestamp return fails here until it has
912+
// one, and every row must meet a date field's text under both rewrites.
913+
it('every Timestamp-returning function the environment declares meets a date field\'s text under ==, != and ordering', () => {
914+
const declared = [...new Set(buildEnv(() => now).getDefinitions().functions
915+
.filter((f) => f.receiverType === null && f.returnType === 'google.protobuf.Timestamp')
916+
.map((f) => f.name))].sort();
917+
const probe: Record<string, string> = {
918+
now: 'now()', today: 'today()', daysFromNow: 'daysFromNow(3)', daysAgo: 'daysAgo(3)',
919+
addDays: 'addDays(today(), 3)', addMonths: 'addMonths(today(), 1)',
920+
date: 'date("2026-06-23")', datetime: 'datetime("2026-06-23T10:00:00Z")',
921+
timestamp: 'timestamp("2026-06-23T10:00:00Z")',
922+
addWorkingDays: 'addWorkingDays(today(), 2)', addWorkingHours: 'addWorkingHours(now(), 4)',
923+
};
924+
expect(Object.keys(probe).sort(), 'a probe row per declared Timestamp-returning function').toEqual(declared);
925+
expect([...timestampReturningFunctions()].sort(), 'the set both rewrites ask').toEqual(declared);
926+
const weekday = '09:00-18:00';
927+
const workCalendars = { default: buildWorkCalendar({
928+
code: 'probe', timezone: 'UTC', maintained_from: '2025-01-01', maintained_through: '2027-12-31',
929+
monday_periods: weekday, tuesday_periods: weekday, wednesday_periods: weekday,
930+
thursday_periods: weekday, friday_periods: weekday,
931+
}, []) };
932+
const missed: string[] = [];
933+
for (const name of declared) {
934+
const call = probe[name];
935+
// The field holds the call's own instant as text, the way a datetime field reaches the run.
936+
const text = celEngine.evaluate(cel(`isoDatetime(${call})`), { now, workCalendars });
937+
expect(text.ok, `isoDatetime(${call})`).toBe(true);
938+
if (!text.ok) continue;
939+
const ctx = { now, workCalendars, record: { at: text.value } };
940+
for (const [op, expected] of [['==', true], ['!=', false], ['<', false], ['<=', true]] as const) {
941+
const r = celEngine.evaluate(cel(`record.at ${op} ${call}`), ctx);
942+
if (!(r.ok && r.value === expected)) missed.push(`record.at ${op} ${call}: ${JSON.stringify(r)}`);
943+
}
944+
}
945+
expect(missed).toEqual([]);
946+
});
947+
});

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

Lines changed: 53 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1770,8 +1770,42 @@ export function firstDateTextCall(
17701770
}
17711771
}
17721772

1773-
/** cel-js temporal functions that return a calendar Timestamp (for #3183). */
1774-
const TEMPORAL_FNS = new Set(['today', 'daysFromNow', 'daysAgo', 'now']);
1773+
/** The CEL type name of a Timestamp, as a function declaration spells its return. */
1774+
const TIMESTAMP_CEL_TYPE = 'google.protobuf.Timestamp';
1775+
1776+
/**
1777+
* [#38135] The global functions whose every overload the engine's own
1778+
* environment DECLARES as returning a Timestamp: `today`, `now`, `daysFromNow`,
1779+
* `daysAgo`, `addDays`, `addMonths`, `date`, `datetime`, the working-day pair
1780+
* `addWorkingDays` / `addWorkingHours`, and cel-js's built-in `timestamp`.
1781+
*
1782+
* Read off `getDefinitions()` of an environment built by the one constructor the
1783+
* engine evaluates on, never kept by hand. Both rewrites that coerce a date
1784+
* field's `YYYY-MM-DD` text to meet a Timestamp ask this set through
1785+
* {@link isTimestampCall}: the ADR-0032 §1c ordering retry ({@link operandKind})
1786+
* and the #3183 equality rewrite ({@link rewriteTemporalCallEquality}). Each used
1787+
* to keep its own list (`today` / `now` / `daysFromNow` / `daysAgo`, the retry
1788+
* adding `date` / `datetime`), so a field compared with `addDays(today(), 30)`
1789+
* faulted on every run under `<` and answered a silent `false` under `==`, while
1790+
* the same comparison with `daysFromNow(30)` evaluated. A function registered
1791+
* later with a Timestamp return joins both rewrites with no edit here.
1792+
*
1793+
* A name with ANY overload returning something else is left out: the AST names
1794+
* the function, not the overload, so such a call cannot be proved a Timestamp.
1795+
* Built on first use, as the shared evaluation environment is.
1796+
*/
1797+
let timestampReturningFns: ReadonlySet<string> | undefined;
1798+
export function timestampReturningFunctions(): ReadonlySet<string> {
1799+
if (timestampReturningFns) return timestampReturningFns;
1800+
const returns = new Map<string, boolean>();
1801+
const defs = buildEnvReading(() => UNBOUND).getDefinitions().functions;
1802+
for (const fn of defs) {
1803+
if (fn.receiverType !== null) continue;
1804+
returns.set(fn.name, (returns.get(fn.name) ?? true) && fn.returnType === TIMESTAMP_CEL_TYPE);
1805+
}
1806+
timestampReturningFns = new Set([...returns].filter(([, ts]) => ts).map(([name]) => name));
1807+
return timestampReturningFns;
1808+
}
17751809

17761810
/** A cel-js AST node is `{ op, args }`; `args` is a node[], or a leaf string. */
17771811
type CelNode = { op: string; args: unknown };
@@ -1780,11 +1814,15 @@ function isCelNode(v: unknown): v is CelNode {
17801814
return typeof v === 'object' && v !== null && typeof (v as CelNode).op === 'string';
17811815
}
17821816

1783-
/** True when `node` is a call to a temporal function (`today()`/`daysFromNow(…)`/…). */
1784-
function isTemporalCall(node: unknown): boolean {
1817+
/**
1818+
* True when `node` is a global call that returns a Timestamp (`today()`,
1819+
* `addDays(today(), 30)`, `date("2026-06-20")`, …) — see
1820+
* {@link timestampReturningFunctions}.
1821+
*/
1822+
function isTimestampCall(node: unknown): boolean {
17851823
return isCelNode(node) && node.op === 'call'
17861824
&& Array.isArray(node.args) && typeof node.args[0] === 'string'
1787-
&& TEMPORAL_FNS.has(node.args[0]);
1825+
&& timestampReturningFunctions().has(node.args[0]);
17881826
}
17891827

17901828
/**
@@ -1816,7 +1854,9 @@ function wrapInDate(node: CelNode): CelNode {
18161854
* `YYYY-MM-DD` string and cel-js equality never matches a string against the
18171855
* Timestamp that `today()` etc. return, so the bare comparison silently misses;
18181856
* `date(record.d) == today()` compares two Timestamps and matches on the calendar
1819-
* day. The rewrite is:
1857+
* day. The counterpart is any call {@link isTimestampCall} proves a Timestamp
1858+
* (#38135: `addDays(today(), 1)`, `date("2026-06-20")` and `timestamp(…)` too,
1859+
* which this arm once missed and answered a silent `false` on). The rewrite is:
18201860
* - **per-occurrence** — only the operand paired with a temporal call is wrapped,
18211861
* so `record.d == "2026-06-20" || record.d == today()` keeps the string-literal
18221862
* comparison intact while fixing the temporal one (no field-wide trade-off);
@@ -1840,10 +1880,9 @@ function rewriteTemporalCallEquality(source: string): string {
18401880
if (typeof source !== 'string' || !source.trim()) return source;
18411881
const cached = temporalRewriteCache.get(source);
18421882
if (cached !== undefined) return cached;
1843-
// Cheap gate: a rewrite needs an equality operator AND a temporal call.
1883+
// Cheap gate: a rewrite needs an equality operator AND a Timestamp-returning call.
18441884
const gated = (source.includes('==') || source.includes('!='))
1845-
&& (source.includes('today') || source.includes('daysFromNow')
1846-
|| source.includes('daysAgo') || source.includes('now'));
1885+
&& [...timestampReturningFunctions()].some((fn) => source.includes(fn));
18471886
if (!gated) { rememberRewrite(source, source); return source; }
18481887

18491888
let ast: unknown;
@@ -1859,10 +1898,10 @@ function rewriteTemporalCallEquality(source: string): string {
18591898
if ((node.op === '==' || node.op === '!=') && Array.isArray(node.args) && node.args.length === 2) {
18601899
const args = node.args as unknown[];
18611900
const [left, right] = args;
1862-
// Wrap the field operand paired with a temporal call. Guard `fieldRefName`
1901+
// Wrap the field operand paired with a Timestamp-returning call. Guard `fieldRefName`
18631902
// so we never wrap a literal, another call, or an arithmetic sub-tree.
1864-
if (isTemporalCall(left) && isCelNode(right) && fieldRefName(right)) { args[1] = wrapInDate(right); changed = true; }
1865-
else if (isTemporalCall(right) && isCelNode(left) && fieldRefName(left)) { args[0] = wrapInDate(left); changed = true; }
1903+
if (isTimestampCall(left) && isCelNode(right) && fieldRefName(right)) { args[1] = wrapInDate(right); changed = true; }
1904+
else if (isTimestampCall(right) && isCelNode(left) && fieldRefName(left)) { args[0] = wrapInDate(left); changed = true; }
18661905
}
18671906
if (Array.isArray(node.args)) for (const child of node.args) visit(child);
18681907
};
@@ -2405,10 +2444,10 @@ function valueKind(v: unknown): OperandKind {
24052444
function operandKind(node: unknown, scope: Record<string, unknown>): OperandKind {
24062445
if (!isCelNode(node)) return 'unknown';
24072446
if (node.op === 'value') return valueKind(node.args);
2408-
if (isTemporalCall(node)) return 'temporal';
2447+
// #38135 — every call the environment declares a Timestamp, `addDays(today(), 30)` included.
2448+
if (isTimestampCall(node)) return 'temporal';
24092449
if (node.op === 'call' && Array.isArray(node.args) && typeof node.args[0] === 'string') {
24102450
const fn = node.args[0];
2411-
if (fn === 'date' || fn === 'datetime') return 'temporal';
24122451
if (fn === 'double' || fn === 'int' || fn === 'uint') return 'number';
24132452
return 'unknown';
24142453
}

0 commit comments

Comments
 (0)