:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(hogvm): converge string↔temporal comparison across the three VMs (#81443)
Kyle Swank3d59abacedb4
diff --git a/common/hogvm/python/stl/date.py b/common/hogvm/python/stl/date.pyindex 38c858d0cdbc..0724414d1dc7 100644--- a/common/hogvm/python/stl/date.py+++ b/common/hogvm/python/stl/date.py@@ -1,3 +1,4 @@+import reimport datetimefrom typing import Optional@@ -47,10 +48,14 @@ def toUnixTimestamp(date, timezone: Optional[str] = None):year=date["year"], month=date["month"], day=date["day"], tzinfo=pytz.timezone(timezone or "UTC")).timestamp()- date = datetime.datetime.fromisoformat(date)- if timezone:- date = date.astimezone(pytz.timezone(timezone))- return date.timestamp()+ # A naive string is anchored to `timezone` (UTC when unset), matching Rust's+ # `naive_to_seconds(s, zone)` and TypeScript's `fromISO(input, {zone})`. It used to be parsed+ # naive and then `.astimezone`d, which is a no-op for aware input and resolves naive input in the+ # *host's* timezone — so the answer depended on where the process happened to be running.+ parsed = _parse_date_like(date, timezone)+ if parsed is None:+ raise ValueError(f"Could not parse date: {date}")+ return parsed.timestamp()def fromUnixTimestamp(timestamp: int | float):@@ -74,11 +79,84 @@ def toTimeZone(date: dict, timezone: str):}+# [0-9] and never \d: Python's re treats \d as any Unicode decimal digit, which int() then happily+# parses — so e.g. an all-Arabic-Indic-digit date was a valid instant here and rejected by the+# other two VMs. See the canonical grammar in the Rust STL.+DATE_LIKE = re.compile(+ r"""^([0-9]{4})-([0-9]{2})-([0-9]{2})+ (?:+ [Tt\ ]([01][0-9]|2[0-3]):([0-5][0-9])+ (?::([0-5][0-9])(?:[.,]([0-9]{1,9}))?)?+ (Z|z|[+-](?:[01][0-9]|2[0-3])(?::?[0-5][0-9])?)?+ )?\Z""",+ re.VERBOSE,+)+++def _parse_date_like(input: str, timezone: Optional[str] = None) -> Optional[datetime.datetime]:+ """An aware ``datetime`` for a string matching the shared date-like grammar, else None.++ The canonical copy of the grammar lives above ``parse_datetime_to_seconds`` in+ ``rust/common/hogvm/src/stl.rs``; ``common/hogvm/typescript/src/stl/date.ts`` (``parseDateLike``)+ is the third implementation. Change all three together.++ Deliberately not ``datetime.fromisoformat``, which accepts the compact ``20240101`` and ISO-week+ ``2024-W05`` forms that neither of the other two VMs do. More importantly, ``fromisoformat``+ returns a *naive* datetime for input carrying no zone, and ``naive.timestamp()`` resolves it in+ the **host's** timezone — so the Python VM's answer for ``toDateTime('2026-07-01')`` depended on+ where it happened to be running, and disagreed with TypeScript and Rust (both UTC-anchored) by+ the local UTC offset. ``tzinfo`` is always set here, so the result is host-independent.++ ``timezone`` applies only to input carrying no zone of its own; an explicit offset or ``Z`` pins+ the absolute instant regardless.+ """+ match = DATE_LIKE.match(input.strip())+ if not match:+ return None+ year, month, day, hour, minute, second, fraction, offset = match.groups()+ # Sub-millisecond digits are truncated, not rounded, to match luxon and Rust's `timestamp_millis`.+ # Python's `datetime` keeps microseconds, which surfaced as a `result_mismatch` against the Node+ # baseline (see `datetime_to_seconds` in the Rust STL).+ microsecond = int(fraction[:3].ljust(3, "0")) * 1000 if fraction else 0++ try:+ if offset in ("Z", "z"):+ tzinfo: datetime.tzinfo = datetime.UTC+ elif offset:+ digits = offset[1:].replace(":", "")+ delta = datetime.timedelta(hours=int(digits[:2]), minutes=int(digits[2:4] or 0))+ tzinfo = datetime.timezone(-delta if offset[0] == "-" else delta)+ else:+ tzinfo = pytz.timezone(timezone or "UTC")++ naive = datetime.datetime(+ int(year), int(month), int(day), int(hour or 0), int(minute or 0), int(second or 0), microsecond+ )+ except ValueError:+ # Out-of-range calendar date (2024-02-30) or year 0. The tz construction is inside the `try`+ # deliberately: an offset the regex admits but `datetime.timezone` rejects must return None+ # like any other parse failure — this function is called from `unify_comparison_types` on+ # every comparison opcode, where a bare ValueError would escape the VM entirely rather than+ # leaving the operands uncoerced. (An unknown zone *name* still raises — pytz's+ # UnknownTimeZoneError is a KeyError — matching the natives' pre-existing behavior; only+ # they pass a zone, never the comparison path.)+ return None+ # `localize` rather than `tzinfo=` — pytz zones carry a historical LMT offset that only+ # `localize` resolves to the right one for the date in question. `is_dst=True` picks the first+ # of an ambiguous pair during a DST fold, matching Rust's `LocalResult::Ambiguous(dt, _)` and+ # luxon; pytz's default (`is_dst=False`) would pick the second and land an hour off.+ localize = getattr(tzinfo, "localize", None)+ return localize(naive, is_dst=True) if localize else naive.replace(tzinfo=tzinfo)++def toDate(input):if isinstance(input, int) or isinstance(input, float):dt = datetime.datetime.fromtimestamp(input)else:- dt = datetime.datetime.fromisoformat(input)+ parsed = _parse_date_like(input)+ if parsed is None:+ raise ValueError(f"Could not parse date: {input}")+ dt = parsedreturn {"__hogDate__": True,"year": dt.year,@@ -91,7 +169,10 @@ def toDateTime(input):if isinstance(input, int) or isinstance(input, float):dt = float(input)else:- dt = datetime.datetime.fromisoformat(input).timestamp()+ parsed = _parse_date_like(input)+ if parsed is None:+ raise ValueError(f"Could not parse date: {input}")+ dt = parsed.timestamp()return {"__hogDateTime__": True,"dt": dt,@@ -101,10 +182,8 @@ def toDateTime(input):def date_string_to_seconds(input: str) -> Optional[float]:"""Epoch seconds for a date-like string, parsed the same way `toDateTime` would, else None."""- try:- return datetime.datetime.fromisoformat(input).timestamp()- except ValueError:- return None+ parsed = _parse_date_like(input)+ return parsed.timestamp() if parsed else None# From ClickHouse to Pythondiff --git a/common/hogvm/python/test/test_comparison_utils.py b/common/hogvm/python/test/test_comparison_utils.pyindex f660ce031014..e47f7ca9f5cc 100644--- a/common/hogvm/python/test/test_comparison_utils.py+++ b/common/hogvm/python/test/test_comparison_utils.py@@ -152,8 +152,11 @@ class TestUnifyComparisonTypesTemporalOrdering(unittest.TestCase):# wraps the RHS in toDateTime, so the VM ends up unifying a plain ISO string against a HogDateTime# dict. Before this fix, HogDateTime dicts fell through unify_comparison_types unchanged and the# ordering operators tried to compare a str to a dict, raising a TypeError.- later_datetime = to_hog_datetime(1782988689) # 2026-06-28- earlier_datetime = to_hog_datetime(1782518400) # 2026-06-23 00:00:00 UTC+ # These must be the exact instants the labels claim: the equality cases below compare them+ # against the ISO strings, so an approximate value would silently pass the ordering cases (which+ # only need later > earlier) while making the equality cases unprovable.+ later_datetime = to_hog_datetime(1782604800) # 2026-06-28 00:00:00 UTC+ earlier_datetime = to_hog_datetime(1782172800) # 2026-06-23 00:00:00 UTClater_iso_timestamp = "2026-06-28T00:00:00.000Z" # same instant as later_datetimeearlier_iso_timestamp = "2026-06-23T00:00:00.000Z" # same instant as earlier_datetime@@ -173,6 +176,24 @@ class TestUnifyComparisonTypesTemporalOrdering(unittest.TestCase):self.assertEqual(left, "not-a-date")self.assertEqual(right, self.later_datetime)+ # The EQ/NOT_EQ opcodes call unify_comparison_types too, so a bare-field `timestamp ==+ # toDateTime('…')` coerces just like the ordering ops. Pinned here because the Rust VM had to be+ # taught the same thing separately (its `eq_op` only handled the both-temporal case, so it+ # answered false where this answers true) — all six opcodes must agree across the three VMs.+ @parameterized.expand(+ [+ ("string vs HogDateTime", later_iso_timestamp, later_datetime),+ ("HogDateTime vs string", later_datetime, later_iso_timestamp),+ ]+ )+ def test_compares_equal_when_the_same_instant(self, _label, left, right):+ left, right = unify_comparison_types(left, right)+ self.assertEqual(left, right)++ def test_string_and_temporal_at_different_instants_are_not_equal(self):+ left, right = unify_comparison_types(self.earlier_iso_timestamp, self.later_datetime)+ self.assertNotEqual(left, right)+if __name__ == "__main__":unittest.main()diff --git a/common/hogvm/python/test/test_date.py b/common/hogvm/python/test/test_date.pynew file mode 100644index 000000000000..b8f2fb4431e4--- /dev/null+++ b/common/hogvm/python/test/test_date.py@@ -0,0 +1,123 @@+import os+import time+from contextlib import contextmanager++import unittest++from parameterized import parameterized++from common.hogvm.python.stl.date import date_string_to_seconds, toDate, toDateTime, toUnixTimestamp++# The shared date-like grammar. The canonical spec lives above `parse_datetime_to_seconds` in+# `rust/common/hogvm/src/stl.rs`; the same table is driven by `rust/common/hogvm/tests/datetime.rs`+# and `common/hogvm/typescript/src/__tests__/date.test.ts`. All three must agree — before this was+# pinned, only 4 of the original 34 of these inputs produced the same answer in all three VMs.+ACCEPTED = [+ ("2024-01-01", 1704067200),+ ("2024-01-01T00:00:00Z", 1704067200),+ ("2024-01-01t00:00:00z", 1704067200), # RFC3339 says the designators are case-insensitive+ ("2024-01-01T00:00:00.000Z", 1704067200),+ ("2024-01-01T00:00:00", 1704067200), # naive => UTC, never the host zone+ ("2024-01-01 00:00:00", 1704067200), # the ClickHouse form HogQL emits+ ("2024-01-01T00:00", 1704067200),+ ("2024-01-01T00:00:00+05:00", 1704049200),+ ("2024-01-01 00:00:00+05:00", 1704049200),+ ("2024-01-01T00:00:00-0500", 1704085200), # offset without the colon+ ("2024-01-01T00:00:00.123Z", 1704067200.123),+ ("2024-01-01T00:00:00.123456Z", 1704067200.123), # truncated to ms, not rounded+ (" 2024-01-01 ", 1704067200),+ ("2024-01-01T00:00:00+05", 1704049200), # offset hours only+ ("2024-01-01T00:00:00,123Z", 1704067200.123), # comma fraction separator+ ("1960-01-01T00:00:00.123Z", -315619199.877), # pre-epoch: truncation must not flip sign+]++REJECTED = [+ "2024", # luxon accepted these five as instants; a string property could plausibly hold any+ "2024-01",+ "20240101", # `fromisoformat` accepted this and `2024-W05`; the other two VMs never did+ "2024-W05",+ "2024-001",+ "12:30", # luxon resolved this against *today's* date+ "1700000000", # only Rust accepted this, and now only via its explicit native (see its tests)+ "not-a-date",+ "",+ "2024-13-01",+ "2024-02-30",+ "2024-01-01T24:00:00Z", # luxon normalized hour 24 to the next midnight; the others rejected+ "2024-01-01T00:00.123Z", # a fraction requires seconds; luxon rejected what the others took+ "2024-01-01T00:00:00+24:00", # made Python datetime.timezone RAISE out of the comparison path+ "2024-01-01T00:00:00+99:99", # same+ "0000-01-01", # valid to chrono and luxon, not to Python datetime+ "2024-01-01T25:00:00Z", # out-of-range hour+ "2024-01-01T00:60:00Z", # out-of-range minute+ "٢٠٢٤-٠١-٠١", # Unicode digits. \d matches them in the Python/Rust regex engines (never in JS),+ # and int() parses them, so this was a valid instant here and rejected by the other two VMs...+ "2024-01-01T00:00+0١", # ...and these two byte-sliced mid-codepoint in Rust — a panic, not an error+ "2024-01-01T00:00:00.١٢Z",+]+++@contextmanager+def host_timezone(zone: str):+ """Run the body as if the process were in `zone`, restoring the real one afterwards."""+ original = os.environ.get("TZ")+ os.environ["TZ"] = zone+ time.tzset()+ try:+ yield+ finally:+ if original is None:+ del os.environ["TZ"]+ else:+ os.environ["TZ"] = original+ time.tzset()+++class TestDateLikeGrammar(unittest.TestCase):+ @parameterized.expand(ACCEPTED)+ def test_accepts(self, value, expected):+ self.assertAlmostEqual(date_string_to_seconds(value), expected, places=3)+ self.assertAlmostEqual(toDateTime(value)["dt"], expected, places=3)+ self.assertAlmostEqual(toUnixTimestamp(value), expected, places=3)++ @parameterized.expand([(value,) for value in REJECTED])+ def test_rejects(self, value):+ self.assertIsNone(date_string_to_seconds(value))+ with self.assertRaises(ValueError):+ toDateTime(value)++ def test_naive_string_resolves_to_utc_regardless_of_host_timezone(self):+ # Regression: `datetime.fromisoformat(s).timestamp()` resolves a naive datetime in the+ # *host's* zone, so `toDateTime('2026-07-01')` depended on where the process was running and+ # disagreed with the TypeScript and Rust VMs (both UTC-anchored) by the local UTC offset.+ for zone in ("UTC", "America/New_York", "Asia/Tokyo"):+ with self.subTest(zone=zone), host_timezone(zone):+ self.assertEqual(toDateTime("2024-01-01")["dt"], 1704067200)+ self.assertEqual(toDateTime("2024-01-01 00:00:00")["dt"], 1704067200)+ self.assertEqual(date_string_to_seconds("2024-01-01T00:00:00"), 1704067200)+ self.assertEqual(toDate("2024-01-01"), {"__hogDate__": True, "year": 2024, "month": 1, "day": 1})++ def test_explicit_zone_applies_only_to_input_carrying_no_zone_of_its_own(self):+ self.assertEqual(toUnixTimestamp("2024-01-01 00:00:00", "America/New_York"), 1704085200)+ self.assertEqual(toUnixTimestamp("2024-01-01T00:00:00Z", "America/New_York"), 1704067200)++ def test_number_passes_through_as_epoch_seconds_without_parsing(self):+ self.assertEqual(toDateTime(1700000000)["dt"], 1700000000)++ def test_an_unusable_offset_returns_none_rather_than_escaping_the_vm(self):+ # `date_string_to_seconds` is called from `unify_comparison_types` on every comparison+ # opcode, so a bare ValueError here escapes the VM entirely instead of leaving the operands+ # uncoerced. `datetime.timezone` raises for |offset| >= 24h.+ for value in ("2024-01-01T00:00:00+24:00", "2024-01-01T00:00:00+99:99"):+ with self.subTest(value=value):+ self.assertIsNone(date_string_to_seconds(value))++ def test_ambiguous_local_time_takes_the_first_of_the_dst_fold(self):+ # 01:30 happens twice on 2024-11-03 in New York. pytz's `localize` defaults to is_dst=False+ # (the second, -05:00); Rust's `LocalResult::Ambiguous(dt, _)` and luxon both take the first+ # (-04:00), so pytz's default would land an hour off.+ self.assertEqual(toUnixTimestamp("2024-11-03 01:30:00", "America/New_York"), 1730611800)+++if __name__ == "__main__":+ unittest.main()diff --git a/common/hogvm/typescript/src/__tests__/date.test.ts b/common/hogvm/typescript/src/__tests__/date.test.tsnew file mode 100644index 000000000000..587f763b5105--- /dev/null+++ b/common/hogvm/typescript/src/__tests__/date.test.ts@@ -0,0 +1,112 @@+import { dateStringToSeconds, toDate, toDateTime, toUnixTimestamp } from '../stl/date'++/**+ * The shared date-like grammar. The canonical spec lives above `parse_datetime_to_seconds` in+ * `rust/common/hogvm/src/stl.rs`; the same table is driven by `rust/common/hogvm/tests/datetime.rs`+ * and `common/hogvm/python/test/test_date.py`. All three must agree — before this was pinned, only+ * 4 of these 34 inputs produced the same answer in all three VMs.+ */+const ACCEPTED: [string, number][] = [+ ['2024-01-01', 1704067200],+ ['2024-01-01T00:00:00Z', 1704067200],+ ['2024-01-01t00:00:00z', 1704067200], // RFC3339 says the designators are case-insensitive+ ['2024-01-01T00:00:00.000Z', 1704067200],+ ['2024-01-01T00:00:00', 1704067200], // naive => UTC, never the host zone+ ['2024-01-01 00:00:00', 1704067200], // the ClickHouse form HogQL emits; luxon alone rejected it+ ['2024-01-01T00:00', 1704067200],+ ['2024-01-01T00:00:00+05:00', 1704049200],+ ['2024-01-01 00:00:00+05:00', 1704049200],+ ['2024-01-01T00:00:00-0500', 1704085200], // offset without the colon+ ['2024-01-01T00:00:00.123Z', 1704067200.123],+ ['2024-01-01T00:00:00.123456Z', 1704067200.123], // truncated to ms, not rounded+ [' 2024-01-01 ', 1704067200],+ ['2024-01-01T00:00:00+05', 1704049200], // offset hours only+ ['2024-01-01T00:00:00,123Z', 1704067200.123], // comma fraction separator+ ['1960-01-01T00:00:00.123Z', -315619199.877], // pre-epoch: truncation must not flip sign+]++const REJECTED = [+ '2024', // luxon accepted these five as instants; a string property could plausibly hold any+ '2024-01',+ '20240101',+ '2024-W05',+ '2024-001',+ '12:30', // luxon resolved this against *today's* date+ '1700000000', // only Rust accepted this, and now only via its explicit native (see its tests)+ 'not-a-date',+ '',+ '2024-13-01',+ '2024-02-30',+ '2024-01-01T24:00:00Z', // luxon normalized hour 24 to the next midnight; the others rejected+ '2024-01-01T00:00.123Z', // a fraction requires seconds; luxon rejected what the others took+ '2024-01-01T00:00:00+24:00', // made Python datetime.timezone RAISE out of the comparison path+ '2024-01-01T00:00:00+99:99', // same+ '0000-01-01', // valid to chrono and luxon, not to Python datetime+ '2024-01-01T25:00:00Z', // out-of-range hour+ '2024-01-01T00:60:00Z', // out-of-range minute+ '٢٠٢٤-٠١-٠١', // Unicode digits. JS's \d is ASCII-only so these never matched here, but \d matches+ // them in the Python/Rust engines: Python's int() read the first as a real date, and the other+ // two byte-sliced mid-codepoint in Rust — a panic. Pinned in all three tables.+ '2024-01-01T00:00+0١',+ '2024-01-01T00:00:00.١٢Z',+]++describe('date-like string grammar', () => {+ test.each(ACCEPTED)('accepts %s as %d', (input, expected) => {+ expect(dateStringToSeconds(input)).toBeCloseTo(expected, 3)+ expect(toDateTime(input).dt).toBeCloseTo(expected, 3)+ expect(toUnixTimestamp(input)).toBeCloseTo(expected, 3)+ })++ test.each(REJECTED)('rejects %p', (input) => {+ expect(dateStringToSeconds(input)).toBeNull()+ })++ test('a naive string resolves to UTC regardless of the host timezone', () => {+ // Python's `datetime.timestamp()` resolved naive input in the host zone, so the same filter+ // gave different answers on a developer's laptop and in production. Pinned in all three VMs.+ expect(toDateTime('2024-01-01').dt).toBe(1704067200)+ expect(toDate('2024-01-01')).toEqual({+ __hogDate__: true,+ year: 2024,+ month: 1,+ day: 1,+ })+ })++ test('an explicit zone applies only to input carrying no zone of its own', () => {+ expect(toDateTime('2024-01-01 00:00:00', 'America/New_York').dt).toBe(1704085200)+ expect(toDateTime('2024-01-01T00:00:00Z', 'America/New_York').dt).toBe(1704067200)+ })++ test('a number passes through as epoch seconds without parsing', () => {+ expect(toDateTime(1700000000).dt).toBe(1700000000)+ })++ test('unparseable input keeps the pre-existing NaN failure mode', () => {+ // Not a good failure mode, but each VM's is different (Python raises, Rust errors into a+ // null) and converging them is a separate change from converging what parses.+ expect(toDateTime('not-a-date').dt).toBeNaN()+ })++ test.each([[1700000000], [null], [{ a: 1 }], [['x']]])(+ 'non-string input %p yields NaN rather than throwing',+ (input) => {+ // `toUnixTimestamp` guards only the two Hog temporal shapes and passes everything else+ // to the parser, and callers hand it raw event properties — so a non-string has to fall+ // through to the pre-existing NaN, not throw `input.trim is not a function` out of the VM.+ // (A number reaching `toDateTime` is separate: that has an explicit epoch-seconds branch.)+ expect(toUnixTimestamp(input as any)).toBeNaN()+ }+ )++ test.each([[null], [{ a: 1 }], [['x']]])('toDateTime(%p) yields NaN rather than throwing', (input) => {+ expect(toDateTime(input as any).dt).toBeNaN()+ })++ test('an ambiguous local time takes the first of the DST fold', () => {+ // 01:30 happens twice on 2024-11-03 in New York; Rust's `LocalResult::Ambiguous(dt, _)` and+ // luxon take the first (-04:00). Pinned because pytz's `localize` defaults to the second.+ expect(toUnixTimestamp('2024-11-03 01:30:00', 'America/New_York')).toBe(1730611800)+ })+})diff --git a/common/hogvm/typescript/src/__tests__/utils.test.ts b/common/hogvm/typescript/src/__tests__/utils.test.tsindex 31ce7bff20ef..43972db6e2fa 100644--- a/common/hogvm/typescript/src/__tests__/utils.test.ts+++ b/common/hogvm/typescript/src/__tests__/utils.test.ts@@ -9,8 +9,11 @@ describe('hogvm utils', () => {// and the VM's GT opcode does `unifyComparisonTypes(a, b)` then `a > b`. Two HogDateTime objects// fell through unchanged, so `object > object` coerced to "[object Object]" and was always false —// realtime workflow date filters never matched. They must order by epoch seconds.- const laterDateTime = toHogDateTime(1782988689) // 2026-06-28- const earlierDateTime = toHogDateTime(1782518400) // 2026-06-23 00:00:00 UTC+ // These must be the exact instants the labels claim: the equality cases below compare them+ // against the ISO strings, so an approximate value would silently pass the ordering cases+ // (which only need later > earlier) while making the equality cases unprovable.+ const laterDateTime = toHogDateTime(1782604800) // 2026-06-28 00:00:00 UTC+ const earlierDateTime = toHogDateTime(1782172800) // 2026-06-23 00:00:00 UTCconst laterDate = toHogDate(2026, 6, 28) // UTC midnight, exercises the isHogDate branchconst earlierDate = toHogDate(2026, 6, 23)@@ -28,7 +31,7 @@ describe('hogvm utils', () => {})test('equal instants compare equal', () => {- const [a, b] = unifyComparisonTypes(laterDateTime, toHogDateTime(1782988689))+ const [a, b] = unifyComparisonTypes(laterDateTime, toHogDateTime(1782604800))expect(a === b).toBe(true)})@@ -53,6 +56,23 @@ describe('hogvm utils', () => {expect(a).toBe('not-a-date')expect(b).toBe(laterDateTime)})++ // The EQ/NOT_EQ opcodes call unifyComparisonTypes too, so a bare-field `timestamp ==+ // toDateTime('…')` coerces just like the ordering ops. Pinned here because the Rust VM had to+ // be taught the same thing separately (its `eq_op` only handled the both-temporal case, so it+ // answered false where this answers true) — all six opcodes must agree across the three VMs.+ test.each([+ ['string vs HogDateTime', laterIsoTimestamp, laterDateTime],+ ['HogDateTime vs string', laterDateTime, laterIsoTimestamp],+ ])('compares %s equal when they are the same instant', (_label, left, right) => {+ const [a, b] = unifyComparisonTypes(left, right)+ expect(a === b).toBe(true)+ })++ test('a string and a temporal at different instants are not equal', () => {+ const [a, b] = unifyComparisonTypes(earlierIsoTimestamp, laterDateTime)+ expect(a === b).toBe(false)+ })})test('calculateCost', async () => {diff --git a/common/hogvm/typescript/src/stl/date.ts b/common/hogvm/typescript/src/stl/date.tsindex 4d1526dcc390..013701eff11f 100644--- a/common/hogvm/typescript/src/stl/date.ts+++ b/common/hogvm/typescript/src/stl/date.ts@@ -48,7 +48,7 @@ export function toUnixTimestamp(input: HogDateTime | HogDate | string, zone?: stif (isHogDate(input)) {return toHogDateTime(input).dt}- return DateTime.fromISO(input, { zone: zone || 'UTC' }).toSeconds()+ return (parseDateLike(input, zone) ?? INVALID).toSeconds()}export function fromUnixTimestamp(input: number): HogDateTime {@@ -70,8 +70,67 @@ export function toTimeZone(input: HogDateTime, zone: string): HogDateTime | HogDreturn { ...input, zone }}+/**+ * The shared "date-like string" grammar, implemented identically by all three HogVMs. The canonical+ * copy of the spec lives above `parse_datetime_to_seconds` in `rust/common/hogvm/src/stl.rs`;+ * `common/hogvm/python/stl/date.py` (`_parse_date_like`) is the third. Change all three together.+ *+ * input := WS* date ( SEP time zone? )? WS*+ * date := YYYY "-" MM "-" DD # extended format only, YYYY >= 0001+ * SEP := "T" | "t" | " "+ * time := HH ":" MM ( ":" SS frac? )? # HH <= 23; a fraction requires seconds+ * frac := ("." | ",") DIGIT{1,9} # truncated to milliseconds+ * zone := "Z" | "z" | ("+"|"-") HH ( ":"? MM )? # offset HH <= 23, MM <= 59+ *+ * Luxon's `fromISO` is both too permissive and too strict for this. Too permissive: it accepts+ * `2024`, `2024-01`, `20240101`, `2024-W05`, `2024-001`, and a time-only `12:30` that silently+ * resolves to *today's* date — all plausible values of an ordinary string property, and this+ * coercion is implicit, so a false positive changes the meaning of a comparison the filter author+ * never marked as a date comparison. Too strict: it rejects `2024-01-01 00:00:00`, the canonical+ * ClickHouse form that HogQL emits and that Python and Rust both accept — so `toDateTime` on it+ * returned `{dt: NaN}`. Validating against the grammar first fixes both directions.+ */+// [0-9] to stay byte-for-byte parallel with the Rust and Python patterns, where \d is+// Unicode-aware and had to be banned (JS's \d is already ASCII-only).+const DATE_LIKE =+ /^([0-9]{4})(-[0-9]{2}-[0-9]{2})(?:[Tt ]((?:[01][0-9]|2[0-3]):[0-5][0-9])(?::([0-5][0-9])(?:[.,]([0-9]{1,9}))?)?(Z|z|[+-](?:[01][0-9]|2[0-3])(?::?[0-5][0-9])?)?)?$/++/** Luxon `DateTime` for a string matching the shared grammar, else null. `zone` applies only to input carrying no zone of its own. */+export function parseDateLike(input: string, zone?: string): DateTime | null {+ // Callers reach here with whatever an event property held — `toUnixTimestamp(event.properties.x)`+ // passes its argument through unchecked — so a non-string must return null, not throw on `.trim`.+ if (typeof input !== 'string') {+ return null+ }+ const match = DATE_LIKE.exec(input.trim())+ if (!match) {+ return null+ }+ const [, year, monthDay, hourMinute, second, fraction, offset] = match+ // Year 0 is valid to luxon and chrono but not to Python's `datetime`; excluded so the three+ // accept-sets stay identical.+ if (year === '0000') {+ return null+ }+ // Sub-millisecond digits are truncated, not rounded, to match luxon's own precision and Rust's+ // `timestamp_millis`. Keeping microseconds (as Python's `datetime` does) surfaced as a+ // `result_mismatch` against the Node baseline.+ const millis = fraction ? `.${fraction.slice(0, 3).padEnd(3, '0')}` : ''+ // Normalize to strict ISO so luxon's parser accepts it: `T` separator, uppercase `Z`.+ const time = hourMinute ? `T${hourMinute}${second ? `:${second}${millis}` : ''}${offset?.toUpperCase() ?? ''}` : ''+ const dt = DateTime.fromISO(`${year}${monthDay}${time}`, { zone: zone || 'UTC' })+ return dt.isValid ? dt : null+}++// NOTE: unparseable input keeps each VM's *existing* failure mode — here an invalid luxon DateTime+// (so `.year`/`.toSeconds()` are NaN, as before), while Python raises and Rust errors into a null.+// Converging those three is a separate change; this only converges *what parses*.+const INVALID = DateTime.invalid('not a date-like string')+export function toDate(input: string | number): HogDate {- const dt = typeof input === 'number' ? DateTime.fromSeconds(input) : DateTime.fromISO(input)+ // Previously `DateTime.fromISO(input)` with no zone, i.e. the *system* zone — same class of+ // host-dependent bug as Python's, and a day off from `toDateTime` for offsets west of UTC.+ const dt = typeof input === 'number' ? DateTime.fromSeconds(input) : (parseDateLike(input) ?? INVALID)return {__hogDate__: true,year: dt.year,@@ -81,7 +140,7 @@ export function toDate(input: string | number): HogDate {}export function toDateTime(input: string | number, zone?: string): HogDateTime {- const dt = typeof input === 'number' ? input : DateTime.fromISO(input, { zone: zone || 'UTC' }).toSeconds()+ const dt = typeof input === 'number' ? input : (parseDateLike(input, zone) ?? INVALID).toSeconds()return {__hogDateTime__: true,dt: dt,@@ -91,8 +150,7 @@ export function toDateTime(input: string | number, zone?: string): HogDateTime {/** Epoch seconds for a date-like string, parsed the same way `toDateTime` would, else null. */export function dateStringToSeconds(input: string): number | null {- const dt = DateTime.fromISO(input, { zone: 'UTC' })- return dt.isValid ? dt.toSeconds() : null+ return parseDateLike(input)?.toSeconds() ?? null}/** Convert from ClickHouse format string to Luxon format string */diff --git a/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/behavioral_to_datetime_eq.json b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/behavioral_to_datetime_eq.jsonnew file mode 100644index 000000000000..f2a6b755e58e--- /dev/null+++ b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/behavioral_to_datetime_eq.json@@ -0,0 +1,31 @@+{+ "name": "to_datetime_eq_bare_field",+ "oracle": "clickhouse",+ "note": "Bare-field temporal equality: Eq(person.properties.signup_date, toDateTime(\"2024-09-09 08:30:00\")). Only the right side goes through toDateTime, so the VM compares a plain string against a HogDateTime — the equality counterpart of behavioral_to_datetime_ordering. The Rust VM's eq_op used to handle only the both-temporal case and answered false here while the Python/TS VMs answered true; all six comparison opcodes now share one coercion. See the module-level provenance caveat.",+ "bytecode": [+ "_H",+ 1,+ 32,+ "2024-09-09 08:30:00",+ 2,+ "toDateTime",+ 1,+ 32,+ "signup_date",+ 32,+ "properties",+ 32,+ "person",+ 1,+ 3,+ 11+ ],+ "expected_result": true,+ "globals": {+ "person": {+ "properties": {+ "signup_date": "2024-09-09 08:30:00"+ }+ }+ }+}diff --git a/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/behavioral_to_datetime_ordering.json b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/behavioral_to_datetime_ordering.jsonindex 11b63fed9975..8b9d040744c1 100644--- a/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/behavioral_to_datetime_ordering.json+++ b/rust/cohort-stream-processor/tests/fixtures/hogvm_parity/behavioral_to_datetime_ordering.json@@ -1,7 +1,7 @@{"name": "to_datetime_ordering_lt","oracle": "clickhouse",- "note": "toDateTime instant ordering: Lt(toDateTime(toString(person.properties.signup_date)), toDateTime(\"2026-01-01 00:00:00\")). expected_result is the ClickHouse/instant-ordering answer, which the Rust VM matches and the Python/TS reference VMs now also match. See the module-level provenance caveat.",+ "note": "toDateTime instant ordering: Lt(toDateTime(toString(person.properties.signup_date)), toDateTime(\"2026-01-01 00:00:00\")). expected_result is the ClickHouse/instant-ordering answer, which the Rust VM matches and the Python/TS reference VMs now also match. Note both literals use the ClickHouse space-separated form: luxon's fromISO rejects it, so the TS VM used to return a NaN-valued HogDateTime here and could not in fact match — all three now share one date-like grammar (see parse_datetime_to_seconds in rust/common/hogvm/src/stl.rs). See the module-level provenance caveat.","bytecode": ["_H",1,diff --git a/rust/common/hogvm/src/stl.rs b/rust/common/hogvm/src/stl.rsindex 00c50d515f02..4237191f2320 100644--- a/rust/common/hogvm/src/stl.rs+++ b/rust/common/hogvm/src/stl.rs@@ -3,13 +3,16 @@ use std::collections::HashMap;use std::sync::Arc;use base64::Engine as _;-use chrono::{DateTime, Datelike, LocalResult, NaiveDate, NaiveDateTime, TimeZone, Timelike};+use chrono::{+ DateTime, Datelike, FixedOffset, LocalResult, NaiveDate, NaiveDateTime, TimeZone, Timelike,+};use hmac::digest::KeyInit;use hmac::{Hmac, Mac};use indexmap::IndexMap;use md5::Md5;use once_cell::sync::Lazy;use rand::Rng;+use regex::Regex;use serde::de::{MapAccess, SeqAccess, Visitor};use serde_json::{json, Value as JsonValue};use sha1::Sha1;@@ -1571,7 +1574,7 @@ fn to_datetime(vm: &HogVM, args: Vec<HogValue>) -> Result<HogValue, VmError> {let zone = zone.as_deref();let dt_seconds = match args[0].deref(&vm.heap)? {HogLiteral::Number(n) => n.to_float(),- HogLiteral::String(s) => parse_datetime_to_seconds(s, zone)?,+ HogLiteral::String(s) => parse_datetime_native(s, zone)?,other => {return Err(VmError::NativeCallFailed(format!("toDateTime expects a number or string, got {}",@@ -1590,7 +1593,7 @@ fn to_date(vm: &HogVM, args: Vec<HogValue>) -> Result<HogValue, VmError> {assert_argc(&args, 1, "toDate")?;let seconds = match args[0].deref(&vm.heap)? {HogLiteral::Number(n) => n.to_float(),- HogLiteral::String(s) => parse_datetime_to_seconds(s, None)?,+ HogLiteral::String(s) => parse_datetime_native(s, None)?,other => {return Err(VmError::NativeCallFailed(format!("toDate expects a number or string, got {}",@@ -1607,32 +1610,143 @@ fn to_date(vm: &HogVM, args: Vec<HogValue>) -> Result<HogValue, VmError> {)}-const NAIVE_DATETIME_FORMATS: [&str; 2] = ["%Y-%m-%d %H:%M:%S%.f", "%Y-%m-%dT%H:%M:%S%.f"];+/// The shared "date-like string" grammar, implemented identically by all three HogVMs. This is the+/// canonical copy; `common/hogvm/typescript/src/stl/date.ts` (`parseDateLike`) and+/// `common/hogvm/python/stl/date.py` (`_parse_date_like`) mirror it and must be changed together.+///+/// ```text+/// input := WS* date ( SEP time zone? )? WS*+/// date := YYYY "-" MM "-" DD # extended format only, YYYY >= 0001+/// SEP := "T" | "t" | " "+/// time := HH ":" MM ( ":" SS frac? )? # HH <= 23; a fraction requires seconds+/// frac := ("." | ",") DIGIT{1,9} # truncated to milliseconds+/// zone := "Z" | "z" | ("+"|"-") HH ( ":"? MM )? # offset HH <= 23, MM <= 59+/// ```+///+/// No zone ⇒ UTC (or the explicit `zone` argument when one was passed to `toDateTime`), *never* the+/// process-local timezone. The result is `f64` epoch seconds at millisecond resolution.+///+/// Every numeric field is range-bounded here rather than left to each runtime's own parser, because+/// the three disagreed on exactly the leftovers: luxon normalized `24:00` to the next midnight while+/// chrono and `datetime` rejected it, an offset like `+24:00` made Python's `datetime.timezone`+/// *raise* where luxon accepted and chrono rejected, and year `0000` is valid to chrono and luxon+/// but not to `datetime`. A fraction is tied to seconds for the same reason — luxon rejects+/// `HH:MM.sss` where the other two accepted it.+///+/// DIGIT means ASCII `[0-9]`, spelled explicitly and never as `\d`: the Rust and Python regex+/// engines treat `\d` as any Unicode decimal digit (JS's does not), which let Arabic-Indic digits+/// match fields this parser then byte-slices — a panic on a char boundary — and parse as real+/// values through Python's `int()`, another three-way divergence.+///+/// Deliberately rejected everywhere: bare numeric strings, partial dates (`2024`, `2024-01`), the+/// compact basic format (`20240101`), ISO week (`2024-W05`) and ordinal (`2024-001`) dates, and+/// time-only strings. Each of the three VMs used to accept some subset of these — only 4 of 13+/// tested inputs agreed across all three. Because this coercion is *implicit* (it changes the+/// meaning of comparisons the filter author never marked as date comparisons), the grammar is+/// deliberately narrow: it covers exactly what HogQL/ClickHouse and PostHog's filter globals emit+/// (`YYYY-MM-DD`, ClickHouse `YYYY-MM-DD HH:MM:SS`, and JS `YYYY-MM-DDTHH:MM:SS.sssZ`), and every+/// rejected form is either ambiguous with an ordinary string property or vanishingly rare. A+/// time-only `12:30` resolving to *today's* date, as luxon did, is the failure mode to avoid.+///+/// Note this is the grammar for the *implicit* comparison coercion. The explicit `toDateTime`/+/// `toDate` natives accept one form on top of it; see [`parse_datetime_native`].+static DATE_LIKE: Lazy<Regex> = Lazy::new(|| {+ Regex::new(+ r"(?x)+ ^([0-9]{4})-([0-9]{2})-([0-9]{2})+ (?:+ [Tt\x20]([01][0-9]|2[0-3]):([0-5][0-9])+ (?::([0-5][0-9])(?:[.,]([0-9]{1,9}))?)?+ (Z|z|[+-](?:[01][0-9]|2[0-3])(?::?[0-5][0-9])?)?+ )?$",+ )+ .expect("date-like grammar is a valid regex")+});+/// Epoch seconds for a string matching the [`DATE_LIKE`] grammar, else an error.+///+/// `zone` (the 2-arg `toDateTime` form) applies only to input that carries no zone of its own; an+/// explicit offset or `Z` pins the absolute instant regardless.pub(crate) fn parse_datetime_to_seconds(input: &str, zone: Option<&str>) -> Result<f64, VmError> {- let input = input.trim();- // An explicit offset/`Z` pins the absolute instant regardless of `zone`.- if let Ok(dt) = DateTime::parse_from_rfc3339(input) {- return Ok(datetime_to_seconds(dt));+ let unparseable = || VmError::NativeCallFailed(format!("toDateTime could not parse {input:?}"));++ let caps = DATE_LIKE.captures(input.trim()).ok_or_else(unparseable)?;+ let num = |i: usize| caps.get(i).map(|m| m.as_str().parse::<u32>().unwrap_or(0));++ // The regex bounds the time fields; `from_ymd_opt` still has to reject the calendar-invalid+ // dates it can't express (month 13, Feb 30). Year 0 is valid to chrono but not to Python's+ // `datetime`, so it is excluded explicitly to keep the three accept-sets identical.+ let year = caps[1].parse::<i32>().map_err(|_| unparseable())?;+ if year < 1 {+ return Err(unparseable());}- for fmt in NAIVE_DATETIME_FORMATS {- if let Ok(naive) = NaiveDateTime::parse_from_str(input, fmt) {- return naive_to_seconds(naive, zone);+ let date = NaiveDate::from_ymd_opt(+ year,+ num(2).ok_or_else(unparseable)?,+ num(3).ok_or_else(unparseable)?,+ )+ .ok_or_else(unparseable)?;+ // Sub-millisecond digits are truncated, not rounded: the Node HogVM is the ingestion shadow+ // baseline and luxon parses to milliseconds, so keeping microseconds surfaced as a+ // `result_mismatch`. See `datetime_to_seconds`.+ // char-wise truncation, not a byte slice: the regex guarantees ASCII, but a byte slice here+ // panics on a char boundary the moment that guarantee slips.+ let millis = caps+ .get(7)+ .map(|m| format!("{:0<3}", m.as_str().chars().take(3).collect::<String>()))+ .map_or(Ok(0), |s| s.parse::<u32>())+ .map_err(|_| unparseable())?;+ let naive = date+ .and_hms_milli_opt(+ num(4).unwrap_or(0),+ num(5).unwrap_or(0),+ num(6).unwrap_or(0),+ millis,+ )+ .ok_or_else(unparseable)?;++ match caps.get(8).map(|m| m.as_str()) {+ // An explicit offset/`Z` pins the absolute instant regardless of `zone`.+ Some("Z" | "z") => Ok(datetime_to_seconds(naive.and_utc())),+ Some(offset) => {+ let sign = if offset.starts_with('-') { -1 } else { 1 };+ let digits: String = offset[1..].chars().filter(char::is_ascii_digit).collect();+ // `.get`, not an unchecked slice: a non-ASCII digit sneaking past the regex would+ // shrink `digits` below 2 and an unchecked `[..2]` panics out of the VM.+ let hours: i32 = digits+ .get(..2)+ .ok_or_else(unparseable)?+ .parse()+ .map_err(|_| unparseable())?;+ let minutes: i32 = digits.get(2..4).unwrap_or("0").parse().unwrap_or(0);+ let offset = FixedOffset::east_opt(sign * (hours * 3600 + minutes * 60))+ .ok_or_else(unparseable)?;+ let dt = naive+ .and_local_timezone(offset)+ .single()+ .ok_or_else(unparseable)?;+ Ok(datetime_to_seconds(dt))}+ None => naive_to_seconds(naive, zone),}- if let Some(naive) = NaiveDate::parse_from_str(input, "%Y-%m-%d")- .ok()- .and_then(|date| date.and_hms_opt(0, 0, 0))- {- return naive_to_seconds(naive, zone);- }- // A bare numeric string is unix seconds (e.g. an upstream `toString(<number>)`).- if let Ok(seconds) = input.parse::<f64>() {- return Ok(seconds);- }- Err(VmError::NativeCallFailed(format!(- "toDateTime could not parse {input:?}"- )))+}++/// [`parse_datetime_to_seconds`] plus a bare-numeric-string fallback, for the *explicit*+/// `toDateTime`/`toDate` natives only.+///+/// ClickHouse — the parity oracle for the realtime cohort evaluator, the only production consumer+/// that reaches this — reads an all-digit string as a unix timestamp, and the compiled cohort leaf+/// shape `toDateTime(toString(person.properties.X))` relies on it for numeric date properties+/// (`rust/cohort-stream-processor/tests/fixtures/hogvm_parity/`). Dropping it would turn those+/// filters into a `VmError`, which `cohort-core`'s executor collapses to a silent `false`.+///+/// It is deliberately *not* part of [`DATE_LIKE`], because that grammar also drives the implicit+/// string-vs-temporal comparison coercion, where treating every numeric-looking property as an+/// instant would silently change the meaning of comparisons no one marked as date comparisons.+/// The reference Python/TS VMs accept neither form here; this is a documented Rust-only extension+/// of the explicit native, not a divergence introduced by the shared grammar.+fn parse_datetime_native(input: &str, zone: Option<&str>) -> Result<f64, VmError> {+ parse_datetime_to_seconds(input, zone).or_else(|e| input.trim().parse::<f64>().map_err(|_| e))}fn naive_to_seconds(naive: NaiveDateTime, zone: Option<&str>) -> Result<f64, VmError> {@@ -1951,7 +2065,7 @@ fn unix_timestamp_seconds(},None => None,};- return Ok(parse_datetime_to_seconds(s, zone.as_deref()).ok());+ return Ok(parse_datetime_native(s, zone.as_deref()).ok());}temporal_seconds(vm, &args[0], name).map(Some)}diff --git a/rust/common/hogvm/src/values.rs b/rust/common/hogvm/src/values.rsindex 79046630ae76..05e4fb6bc7f7 100644--- a/rust/common/hogvm/src/values.rs+++ b/rust/common/hogvm/src/values.rs@@ -402,7 +402,40 @@ impl HogLiteral {}}-/// Ordering comparison (`Gt`/`Lt`/`GtEq`/`LtEq`) for two literals, three concerns in order:+/// Epoch seconds for both operands when this is a *temporal* comparison, else `None`.+///+/// Two cases count as temporal, and they must stay together: both operands temporal, or exactly one+/// temporal with the other a date-like String. The second case is what a bare-field SQL comparison+/// like `timestamp > toDateTime(...)` produces — only the right-hand side goes through `toDateTime`,+/// so the left stays the filter globals' plain ISO string. The string is parsed by the shared+/// date-like grammar ([`crate::stl::parse_datetime_to_seconds`]); an unparseable one yields `None`+/// so the caller falls back to its ordinary (non-temporal) handling.+///+/// Shared by [`compare_values`] (ordering) and the VM's `eq_op` (equality) so the two cannot drift —+/// the Python/TS reference VMs route all six of `Eq`/`NotEq`/`Gt`/`GtEq`/`Lt`/`LtEq` through one+/// coercion function, and Rust has to agree on the same set.+pub(crate) fn temporal_seconds_pair(+ a: &HogLiteral,+ b: &HogLiteral,+ heap: &VmHeap,+) -> Option<(f64, f64)> {+ let a_secs = a.as_temporal_seconds(heap);+ let b_secs = b.as_temporal_seconds(heap);+ match (a_secs, b_secs) {+ (Some(a_secs), Some(b_secs)) => Some((a_secs, b_secs)),+ (Some(a_secs), None) => match b {+ HogLiteral::String(s) => Some((a_secs, parse_datetime_to_seconds(s, None).ok()?)),+ _ => None,+ },+ (None, Some(b_secs)) => match a {+ HogLiteral::String(s) => Some((parse_datetime_to_seconds(s, None).ok()?, b_secs)),+ _ => None,+ },+ (None, None) => None,+ }+}++/// Ordering comparison (`Gt`/`Lt`/`GtEq`/`LtEq`) for two literals, two concerns in order:////// OPT-IN ONLY: this is reached exclusively from the coercing `compare_op` path, which the VM takes/// only when the context sets [`ExecutionContext::with_coercing_comparisons`](crate::ExecutionContext::with_coercing_comparisons)@@ -410,15 +443,9 @@ impl HogLiteral {/// keeps the legacy path where a non-number operand errors, so this coercion does NOT change their/// behavior. The semantics here match the Python/TS reference VMs (and ClickHouse for temporals).///-/// 1. If *both* operands are temporal ([`HogLiteral::as_temporal_seconds`]) they are ordered by-/// epoch seconds to match ClickHouse and the Python/TS reference VMs; see the [`crate::stl`]-/// module note.-/// 2. If exactly one operand is temporal and the other is a String, the String is parsed the same-/// way `toDateTime` would ([`crate::stl::parse_datetime_to_seconds`]) and compared as epoch-/// seconds — this covers a bare-field SQL comparison like `timestamp > toDateTime(...)`, where the-/// left side never went through `toDateTime` itself. An unparseable string falls through to the-/// generic branches below.-/// 3. Otherwise coerce like Python `unify_comparison_types` / TS `unifyComparisonTypes`: a String+/// 1. A temporal comparison ([`temporal_seconds_pair`]) orders by epoch seconds to match ClickHouse+/// and the Python/TS reference VMs; see the [`crate::stl`] module note.+/// 2. Otherwise coerce like Python `unify_comparison_types` / TS `unifyComparisonTypes`: a String/// coerces to a Number only when the *other* operand is a Number, Bool↔Number maps to `1`/`0`,/// and both-strings compare lexicographically. This is deliberately *not* routed through/// [`HogLiteral::coerce_types`] (the `Eq` contract, which remaps both-strings and must stay put).@@ -428,28 +455,9 @@ pub fn compare_values(b: &HogLiteral,heap: &VmHeap,) -> Result<HogLiteral, VmError> {- let a_secs = a.as_temporal_seconds(heap);- let b_secs = b.as_temporal_seconds(heap);- if let (Some(a_secs), Some(b_secs)) = (a_secs, b_secs) {+ if let Some((a_secs, b_secs)) = temporal_seconds_pair(a, b, heap) {return Num::binary_op(op, &Num::Float(a_secs), &Num::Float(b_secs));}- // A bare-field SQL comparison like `timestamp > toDateTime(...)` puts a plain date-like string- // against a HogDateTime/HogDate object. Parse the string the same way `toDateTime` would rather- // than falling through to the generic branches below, where it would be `CannotCoerce`d.- if let Some(a_secs) = a_secs {- if let HogLiteral::String(s) = b {- if let Ok(b_secs) = parse_datetime_to_seconds(s, None) {- return Num::binary_op(op, &Num::Float(a_secs), &Num::Float(b_secs));- }- }- }- if let Some(b_secs) = b_secs {- if let HogLiteral::String(s) = a {- if let Ok(a_secs) = parse_datetime_to_seconds(s, None) {- return Num::binary_op(op, &Num::Float(a_secs), &Num::Float(b_secs));- }- }- }use HogLiteral::{Boolean, Null, Number, String as HString};match (a, b) {diff --git a/rust/common/hogvm/src/vm.rs b/rust/common/hogvm/src/vm.rsindex 455d725f3ad4..7beccd76a676 100644--- a/rust/common/hogvm/src/vm.rs+++ b/rust/common/hogvm/src/vm.rs@@ -18,8 +18,8 @@ use crate::{},util::{get_json_nested, like, regex_match},values::{- compare_values, Callable, Closure, FromHogLiteral, HogLiteral, HogValue, LocalCallable,- Num, NumOp, Upvalue, UpvalueCell,+ compare_values, temporal_seconds_pair, Callable, Closure, FromHogLiteral, HogLiteral,+ HogValue, LocalCallable, Num, NumOp, Upvalue, UpvalueCell,},};@@ -955,15 +955,18 @@ impl<'a> HogVM<'a> {/// `Eq`/`NotEq` core. The default path is the legacy structural equality every existing/// shared-crate consumer relies on. Only when the context opts into coercing comparisons (the- /// realtime-cohort evaluator) do two Hog temporals compare by epoch seconds to match ClickHouse+ /// realtime-cohort evaluator) does a temporal pair compare by epoch seconds to match ClickHouse/// (`is_date_exact`); every non-temporal pair is unchanged either way.+ ///+ /// "Temporal pair" is [`temporal_seconds_pair`] — the same predicate [`compare_values`] uses for+ /// ordering, so `timestamp == toDateTime(...)` and `timestamp > toDateTime(...)` agree on which+ /// operands are dates. The Python/TS reference VMs route all six comparison opcodes through a+ /// single coercion function, so equality has to cover the bare-field string case too, not just+ /// the both-temporal one.fn eq_op(&self, a: &HogValue, b: &HogValue) -> Result<HogLiteral, VmError> {if self.context.coerce_comparisons {let (lhs, rhs) = (a.deref(&self.heap)?, b.deref(&self.heap)?);- if let (Some(x), Some(y)) = (- lhs.as_temporal_seconds(&self.heap),- rhs.as_temporal_seconds(&self.heap),- ) {+ if let Some((x, y)) = temporal_seconds_pair(lhs, rhs, &self.heap) {return Ok((x == y).into());}}diff --git a/rust/common/hogvm/tests/datetime.rs b/rust/common/hogvm/tests/datetime.rsindex f5de0ee1979e..84ab0348b7c5 100644--- a/rust/common/hogvm/tests/datetime.rs+++ b/rust/common/hogvm/tests/datetime.rs@@ -9,6 +9,7 @@ use serde_json::{json, Value};// Opcode numeric values (mirror common/hogvm/python/operation.py).const OP_CALL_GLOBAL: i64 = 2;const OP_EQ: i64 = 11;+const OP_NOT_EQ: i64 = 12;const OP_GT: i64 = 13;const OP_LT: i64 = 15;const OP_STRING: i64 = 32;@@ -61,6 +62,92 @@ fn returning(fragment: &[Value]) -> Vec<Value> {bc}+/// The shared date-like grammar. The canonical spec is above `parse_datetime_to_seconds` in+/// `src/stl.rs`; the same table is driven by `common/hogvm/python/test/test_date.py` and+/// `common/hogvm/typescript/src/__tests__/date.test.ts`. All three must agree — before this was+/// pinned, only 4 of the original 34 of these inputs produced the same answer in all three VMs.+const ACCEPTED: [(&str, f64); 16] = [+ ("2024-01-01", 1704067200.0),+ ("2024-01-01T00:00:00Z", 1704067200.0),+ ("2024-01-01t00:00:00z", 1704067200.0), // RFC3339 says the designators are case-insensitive+ ("2024-01-01T00:00:00.000Z", 1704067200.0),+ ("2024-01-01T00:00:00", 1704067200.0), // naive => UTC, never the host zone+ ("2024-01-01 00:00:00", 1704067200.0), // the ClickHouse form HogQL emits; luxon alone rejected it+ ("2024-01-01T00:00", 1704067200.0),+ ("2024-01-01T00:00:00+05:00", 1704049200.0),+ ("2024-01-01 00:00:00+05:00", 1704049200.0),+ ("2024-01-01T00:00:00-0500", 1704085200.0), // offset without the colon+ ("2024-01-01T00:00:00.123Z", 1704067200.123),+ ("2024-01-01T00:00:00.123456Z", 1704067200.123), // truncated to ms, not rounded+ (" 2024-01-01 ", 1704067200.0),+ ("2024-01-01T00:00:00+05", 1704049200.0), // offset hours only+ ("2024-01-01T00:00:00,123Z", 1704067200.123), // comma fraction separator+ ("1960-01-01T00:00:00.123Z", -315619199.877), // pre-epoch: truncation must not flip sign+];++const REJECTED: [&str; 21] = [+ "2024", // luxon accepted these five as instants; a string property could plausibly hold any+ "2024-01",+ "20240101", // Python's `fromisoformat` accepted this and `2024-W05`; the others never did+ "2024-W05",+ "2024-001",+ "12:30", // luxon resolved this against *today's* date+ "1700000000", // the explicit toDateTime native still reads this as unix seconds; the implicit+ // comparison coercion must not, and neither reference VM accepts it anywhere+ "not-a-date",+ "",+ "2024-13-01",+ "2024-02-30",+ "2024-01-01T24:00:00Z", // luxon normalized hour 24 to the next midnight; the others rejected+ "2024-01-01T00:00.123Z", // a fraction requires seconds; luxon rejected what the others took+ "2024-01-01T00:00:00+24:00", // made Python datetime.timezone RAISE out of the comparison path+ "2024-01-01T00:00:00+99:99", // same+ "0000-01-01", // valid to chrono and luxon, not to Python datetime+ "2024-01-01T25:00:00Z", // out-of-range hour+ "2024-01-01T00:60:00Z", // out-of-range minute+ "٢٠٢٤-٠١-٠١", // Unicode digits. \d matches them in the Rust/Python regex engines (never in+ // JS), so Python's int() read this one as a real date while the other two VMs rejected it...+ "2024-01-01T00:00+0١", // ...and these two byte-sliced mid-codepoint in Rust — a panic, not an error+ "2024-01-01T00:00:00.١٢Z",+];++/// Does the *implicit* string-vs-temporal coercion — the shared grammar — accept `input`?+///+/// `Lt(<bare string>, toDateTime("9999-12-31"))`: a date-like string coerces to `true`, while an+/// uncoerced String-vs-Object pair reaches the generic arms and is a `CannotCoerce` error. This is+/// the grammar the ACCEPTED/REJECTED tables define, and is deliberately *not* the explicit+/// `toDateTime` native, which accepts bare numeric strings on top of it (see+/// `numeric_strings_are_unix_seconds_to_the_native_but_never_to_the_comparison_coercion`).+fn grammar_accepts(input: &str) -> bool {+ let program = Program::new(compare(+ &[json!(OP_STRING), json!(input)],+ &to_datetime("9999-12-31"),+ OP_LT,+ ))+ .expect("valid program");+ let ctx = ExecutionContext::with_defaults(program)+ .with_globals(json!({}))+ .with_coercing_comparisons();+ matches!(sync_execute(&ctx, false), Ok(Value::Bool(true)))+}++#[test]+fn date_like_accept_set_matches_the_shared_grammar() {+ for (input, expected) in ACCEPTED {+ assert!(grammar_accepts(input), "grammar should accept {input:?}");+ // The native agrees with the grammar on every non-numeric string, so it can supply the value.+ let dt = run(returning(&to_datetime(input)));+ assert_eq!(+ dt["dt"].as_f64().expect("parsed to a number"),+ expected,+ "should accept {input:?}"+ );+ }+ for input in REJECTED {+ assert!(!grammar_accepts(input), "grammar should reject {input:?}");+ }+}+#[test]fn to_datetime_parses_naive_string_as_utc_not_local() {let result = run(returning(&to_datetime("2026-05-13 00:00:00")));@@ -100,6 +187,48 @@ fn to_datetime_arity2_interprets_naive_string_in_the_given_zone() {);}+#[test]+fn numeric_strings_are_unix_seconds_to_the_native_but_never_to_the_comparison_coercion() {+ // ClickHouse — the oracle for the realtime cohort evaluator, the only production consumer of+ // the coercing path — reads an all-digit string as a unix timestamp, and the compiled leaf+ // shape `toDateTime(toString(person.properties.X))` depends on it for numeric date properties.+ // So the explicit native keeps it.+ assert_eq!(+ run(returning(&to_datetime("1700000000")))["dt"]+ .as_f64()+ .unwrap(),+ 1_700_000_000.0+ );++ // But the *implicit* string-vs-temporal coercion must not: treating every numeric-looking+ // property as an instant would silently change the meaning of comparisons nobody marked as date+ // comparisons, and the Python/TS VMs reject it. `Lt` against a far-future date coerces to `true`+ // for a date-like string; an uncoerced String-vs-Object pair is a `CannotCoerce` error instead.+ let far_future = to_datetime("9999-12-31");+ assert_eq!(+ run(compare(+ &[json!(OP_STRING), json!("2024-01-01")],+ &far_future,+ OP_LT+ )),+ Value::Bool(true),+ "a date-like string coerces"+ );+ let program = Program::new(compare(+ &[json!(OP_STRING), json!("1700000000")],+ &far_future,+ OP_LT,+ ))+ .expect("valid program");+ let ctx = ExecutionContext::with_defaults(program)+ .with_globals(json!({}))+ .with_coercing_comparisons();+ assert!(+ sync_execute(&ctx, false).is_err(),+ "a bare numeric string must NOT be coerced to an instant by a comparison"+ );+}+#[test]fn to_datetime_passes_through_a_unix_number() {let bc = returning(&[@@ -192,6 +321,80 @@ fn bare_field_string_orders_against_a_datetime_by_parsing_it() {);}+#[test]+fn bare_field_string_equals_a_datetime_by_parsing_it() {+ // Regression: ordering got the bare-field string treatment but equality did not, so+ // `timestamp == toDateTime('…')` was silently false here while the Python/TS VMs said true —+ // they route all six comparison opcodes through one coercion function. `Eq` and `Gt` must agree+ // on which operands count as dates.+ let bare = |s: &str| vec![json!(OP_STRING), json!(s)];+ let threshold = to_datetime("2026-01-01 00:00:00");++ for (label, string) in [+ ("naive", "2026-01-01 00:00:00"),+ ("iso Z", "2026-01-01T00:00:00.000Z"),+ ("date only", "2026-01-01"),+ ] {+ assert_eq!(+ run(compare(&bare(string), &threshold, OP_EQ)),+ Value::Bool(true),+ "{label}: string on the left"+ );+ assert_eq!(+ run(compare(&threshold, &bare(string), OP_EQ)),+ Value::Bool(true),+ "{label}: string on the right"+ );+ assert_eq!(+ run(compare(&bare(string), &threshold, OP_NOT_EQ)),+ Value::Bool(false),+ "{label}: NotEq is the negation"+ );+ }++ // A different instant, and a string the grammar rejects, both stay unequal rather than erroring.+ assert_eq!(+ run(compare(&bare("2026-01-02"), &threshold, OP_EQ)),+ Value::Bool(false)+ );+ assert_eq!(+ run(compare(&bare("not-a-date"), &threshold, OP_EQ)),+ Value::Bool(false)+ );+}++#[test]+fn legacy_default_does_not_coerce_string_vs_temporal_eq() {+ // The bare-field coercion is gated on `with_coercing_comparisons`, so cymbal's rules engine —+ // which relies on the legacy structural path, and permanently disables a rule on any VmError —+ // is unaffected by the `eq_op` change above.+ let bare = vec![json!(OP_STRING), json!("2026-01-01 00:00:00")];+ let threshold = to_datetime("2026-01-01 00:00:00");+ assert_eq!(run(compare(&bare, &threshold, OP_EQ)), Value::Bool(true));+ assert_eq!(+ run_legacy(compare(&bare, &threshold, OP_EQ)),+ Value::Bool(false),+ "legacy: a String is never structurally equal to a HogDateTime object",+ );+}++#[test]+fn in_does_not_coerce_strings_against_temporals() {+ // Pinning a deliberate gap, not an endorsement: `in` skips the comparison coercion in all three+ // VMs (TS `Array.includes`, Python `in`, Rust `contains` → structural `equals`), so this is+ // consistent today. Rust's `contains` is also NOT gated on `coerce_comparisons` and is shared+ // with `has()` and cymbal, so changing it is a bigger decision than it looks.+ const OP_ARRAY: i64 = 43;+ const OP_IN: i64 = 21;+ let haystack = {+ let mut bc = to_datetime("2026-01-01 00:00:00");+ bc.extend_from_slice(&[json!(OP_ARRAY), json!(1)]);+ bc+ };+ let needle = vec![json!(OP_STRING), json!("2026-01-01 00:00:00")];+ assert_eq!(run(compare(&needle, &haystack, OP_IN)), Value::Bool(false));+}+#[test]fn date_and_datetime_are_mutually_comparable() {let date = vec![