Skip to content

: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.

fix(hogvm): coerce date-like strings against temporal values in comparisons (#77352)

posthog[bot]e7dc25ae2e51
diff --git a/common/hogvm/python/stl/date.py b/common/hogvm/python/stl/date.py
index e94b51a69df7..38c858d0cdbc 100644
--- a/common/hogvm/python/stl/date.py
+++ b/common/hogvm/python/stl/date.py
@@ -99,6 +99,14 @@ 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
+
+
# From ClickHouse to Python
token_translations = {
"a": "%a",
diff --git a/common/hogvm/python/test/test_comparison_utils.py b/common/hogvm/python/test/test_comparison_utils.py
index 9c4dcac7bae0..f660ce031014 100644
--- a/common/hogvm/python/test/test_comparison_utils.py
+++ b/common/hogvm/python/test/test_comparison_utils.py
@@ -1,5 +1,8 @@
import unittest
+from parameterized import parameterized
+
+from common.hogvm.python.stl.date import to_hog_datetime
from common.hogvm.python.utils import unify_comparison_types
@@ -144,5 +147,32 @@ class TestUnifyComparisonTypes(unittest.TestCase):
self.fail(f"Float conversion error should not occur: {e}")
+class TestUnifyComparisonTypesTemporalOrdering(unittest.TestCase):
+ # Regression: a hand-written SQL trigger filter like `timestamp > toDateTime('2026-06-01')` only
+ # 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
+ later_iso_timestamp = "2026-06-28T00:00:00.000Z" # same instant as later_datetime
+ earlier_iso_timestamp = "2026-06-23T00:00:00.000Z" # same instant as earlier_datetime
+
+ @parameterized.expand(
+ [
+ ("HogDateTime vs HogDateTime", later_datetime, earlier_datetime),
+ ("string vs HogDateTime", later_iso_timestamp, earlier_datetime),
+ ("HogDateTime vs string", later_datetime, earlier_iso_timestamp),
+ ]
+ )
+ def test_orders_chronologically(self, _label, later, earlier):
+ left, right = unify_comparison_types(later, earlier)
+ self.assertGreater(left, right)
+
+ def test_non_date_string_against_temporal_value_falls_through_unchanged(self):
+ left, right = unify_comparison_types("not-a-date", self.later_datetime)
+ self.assertEqual(left, "not-a-date")
+ self.assertEqual(right, self.later_datetime)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/common/hogvm/python/utils.py b/common/hogvm/python/utils.py
index 562f29ea31ea..e114498501dc 100644
--- a/common/hogvm/python/utils.py
+++ b/common/hogvm/python/utils.py
@@ -2,12 +2,24 @@ from typing import Any
import re2
+from common.hogvm.python.objects import is_hog_date, is_hog_datetime
+from common.hogvm.python.stl.date import date_string_to_seconds, to_hog_datetime
+
_CASE_INSENSITIVE_OPTS = re2.Options()
_CASE_INSENSITIVE_OPTS.case_sensitive = False
COST_PER_UNIT = 8
+def _temporal_seconds(value: Any) -> float | None:
+ """Epoch seconds for a Hog datetime/date value, else None. A bare HogDate is UTC midnight."""
+ if is_hog_datetime(value):
+ return value["dt"]
+ if is_hog_date(value):
+ return to_hog_datetime(value)["dt"]
+ return None
+
+
class HogVMException(Exception):
pass
@@ -149,6 +161,25 @@ def calculate_cost(object, marked: set | None = None) -> int:
def unify_comparison_types(left, right):
+ # Two temporal values order by epoch seconds (matching ClickHouse and the TS/Rust VMs). Without
+ # this a HogDateTime/HogDate dict falls through unchanged and ordering operators end up comparing
+ # dicts, which Python can't order.
+ left_seconds = _temporal_seconds(left)
+ right_seconds = _temporal_seconds(right)
+ if left_seconds is not None and right_seconds is not None:
+ return left_seconds, right_seconds
+ # 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 string/number branches below, which leave it unordered.
+ if left_seconds is not None and isinstance(right, str):
+ right_seconds_from_string = date_string_to_seconds(right)
+ if right_seconds_from_string is not None:
+ return left_seconds, right_seconds_from_string
+ if right_seconds is not None and isinstance(left, str):
+ left_seconds_from_string = date_string_to_seconds(left)
+ if left_seconds_from_string is not None:
+ return left_seconds_from_string, right_seconds
+
# Handle boolean cases FIRST since bool is a subclass of int in Python
if isinstance(left, bool) and isinstance(right, str):
# Convert string to boolean: 'true'/'false' strings, or truthy/falsy
diff --git a/common/hogvm/typescript/src/__tests__/utils.test.ts b/common/hogvm/typescript/src/__tests__/utils.test.ts
index 0c9db4581274..31ce7bff20ef 100644
--- a/common/hogvm/typescript/src/__tests__/utils.test.ts
+++ b/common/hogvm/typescript/src/__tests__/utils.test.ts
@@ -31,6 +31,28 @@ describe('hogvm utils', () => {
const [a, b] = unifyComparisonTypes(laterDateTime, toHogDateTime(1782988689))
expect(a === b).toBe(true)
})
+
+ // Regression: a hand-written SQL trigger filter like `timestamp > toDateTime('2026-06-01')`
+ // only wraps the RHS in toDateTime, so the VM ends up unifying a plain ISO string against a
+ // HogDateTime object. Before this fix temporalSeconds(string) was null, the pair fell through
+ // unchanged, and `string > object` was always false — the trigger silently never fired.
+ const laterIsoTimestamp = '2026-06-28T00:00:00.000Z' // same instant as laterDateTime
+ const earlierIsoTimestamp = '2026-06-23T00:00:00.000Z' // same instant as earlierDateTime
+
+ test.each([
+ ['string vs HogDateTime', laterIsoTimestamp, earlierDateTime],
+ ['HogDateTime vs string', laterDateTime, earlierIsoTimestamp],
+ ])('orders %s chronologically by parsing the string as a date', (_label, later, earlier) => {
+ const [a, b] = unifyComparisonTypes(later, earlier)
+ expect(a > b).toBe(true)
+ expect(a < b).toBe(false)
+ })
+
+ test('a non-date string against a temporal value falls through unchanged', () => {
+ const [a, b] = unifyComparisonTypes('not-a-date', laterDateTime)
+ expect(a).toBe('not-a-date')
+ expect(b).toBe(laterDateTime)
+ })
})
test('calculateCost', async () => {
diff --git a/common/hogvm/typescript/src/stl/date.ts b/common/hogvm/typescript/src/stl/date.ts
index 55054425342d..4d1526dcc390 100644
--- a/common/hogvm/typescript/src/stl/date.ts
+++ b/common/hogvm/typescript/src/stl/date.ts
@@ -89,6 +89,12 @@ 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
+}
+
/** Convert from ClickHouse format string to Luxon format string */
const tokenTranslations: Record<string, string> = {
a: 'EEE',
diff --git a/common/hogvm/typescript/src/utils.ts b/common/hogvm/typescript/src/utils.ts
index 514906d94309..650c6d1bd3c5 100644
--- a/common/hogvm/typescript/src/utils.ts
+++ b/common/hogvm/typescript/src/utils.ts
@@ -1,5 +1,5 @@
import { isHogDate, isHogDateTime } from './objects'
-import { toHogDate, toHogDateTime } from './stl/date'
+import { dateStringToSeconds, toHogDate, toHogDateTime } from './stl/date'
/** Epoch seconds for a Hog datetime/date value, else null. A bare HogDate is UTC midnight. */
function temporalSeconds(value: any): number | null {
@@ -224,6 +224,22 @@ export function unifyComparisonTypes(left: any, right: any): [any, any] {
if (leftSeconds !== null && rightSeconds !== null) {
return [leftSeconds, rightSeconds]
}
+ // A bare-field SQL comparison like `timestamp > toDateTime(...)` puts a plain date-like string
+ // (e.g. the filter globals' ISO `timestamp`) against a HogDateTime/HogDate object. Parse the
+ // string the same way `toDateTime` would rather than falling through to the generic branches
+ // below, where `object > string` stays unordered and silently evaluates to false.
+ if (leftSeconds !== null && typeof right === 'string') {
+ const rightSecondsFromString = dateStringToSeconds(right)
+ if (rightSecondsFromString !== null) {
+ return [leftSeconds, rightSecondsFromString]
+ }
+ }
+ if (rightSeconds !== null && typeof left === 'string') {
+ const leftSecondsFromString = dateStringToSeconds(left)
+ if (leftSecondsFromString !== null) {
+ return [leftSecondsFromString, rightSeconds]
+ }
+ }
if (typeof left === 'number' && typeof right === 'string') {
return [left, Number(right)]
}
diff --git a/nodejs/src/cdp/utils/hog-function-filtering.test.ts b/nodejs/src/cdp/utils/hog-function-filtering.test.ts
index c8c13ceec2b0..509d38eda867 100644
--- a/nodejs/src/cdp/utils/hog-function-filtering.test.ts
+++ b/nodejs/src/cdp/utils/hog-function-filtering.test.ts
@@ -357,5 +357,46 @@ describe('hog-function-filtering', () => {
// Should execute bytecode because properties filters are present
expect(result.match).toBe(true)
})
+
+ describe('SQL date comparison trigger filter', () => {
+ // Regression: a hand-written SQL trigger filter like `timestamp > toDateTime('2024-01-01')`
+ // only wraps the RHS in toDateTime, so the VM compares the filter globals' plain ISO
+ // `timestamp` against a HogDateTime object. Before the fix in
+ // common/hogvm/typescript/src/utils.ts, that comparison was always false and the trigger
+ // silently never fired for any live event.
+ const timestampAfterJan2024 = [
+ '_H',
+ 1,
+ 32,
+ '2024-01-01',
+ 2,
+ 'toDateTime',
+ 1,
+ 32,
+ 'timestamp',
+ 1,
+ 1,
+ 13, // GT
+ ]
+
+ test.each([
+ ['2025-01-01T00:00:00.000Z', true],
+ ['2023-01-01T00:00:00.000Z', false],
+ ])('event timestamp %s matches: %s', async (timestamp, expectedMatch) => {
+ mockHogFunction.filters = {
+ filter_test_accounts: false,
+ bytecode: timestampAfterJan2024,
+ }
+ mockFilterGlobals.timestamp = timestamp
+
+ const result = await filterFunctionInstrumented({
+ fn: mockHogFunction,
+ filters: mockHogFunction.filters,
+ filterGlobals: mockFilterGlobals,
+ })
+
+ expect(result.match).toBe(expectedMatch)
+ })
+ })
})
})
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.json
index e3f4d30ececa..11b63fed9975 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 the Rust VM matches; the Python/TS reference VMs cannot order Hog temporals, so this is a Rust-vs-ClickHouse oracle, not a cross-runtime one. 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. See the module-level provenance caveat.",
"bytecode": [
"_H",
1,
diff --git a/rust/cohort-stream-processor/tests/hogvm_parity.rs b/rust/cohort-stream-processor/tests/hogvm_parity.rs
index 2c57ad0b2d93..8431160cd988 100644
--- a/rust/cohort-stream-processor/tests/hogvm_parity.rs
+++ b/rust/cohort-stream-processor/tests/hogvm_parity.rs
@@ -5,10 +5,10 @@
//! enshrine a wrong answer. An optional shared corpus at
//! `../common/hogvm/__tests__/cohort_bytecode` is also loaded when present.
//!
-//! Provenance note: the temporal fixtures (`toDateTime`/`toDate` ordering) are a Rust-vs-ClickHouse
-//! oracle, not a Python one — the reference Python/TS VMs return `false` for Hog temporal ordering,
-//! so `expected_result` reflects the ClickHouse/instant-ordering answer the Rust VM deliberately
-//! matches; see `rust/common/hogvm/tests/datetime.rs`.
+//! Provenance note: the temporal fixtures (`toDateTime`/`toDate` ordering) snapshot the
+//! ClickHouse/instant-ordering answer, which the Rust VM deliberately matches and the Python/TS
+//! reference VMs now also match (both order Hog temporals by epoch seconds); see
+//! `rust/common/hogvm/tests/datetime.rs`.
use std::fs;
use std::path::{Path, PathBuf};
diff --git a/rust/common/hogvm/src/stl.rs b/rust/common/hogvm/src/stl.rs
index 199da3ac6165..00c50d515f02 100644
--- a/rust/common/hogvm/src/stl.rs
+++ b/rust/common/hogvm/src/stl.rs
@@ -1555,9 +1555,9 @@ fn hog_date_epoch_days(heap: &VmHeap, obj: &IndexMap<String, HogValue>) -> Resul
/// `toDateTime(input[, zone])` → a Hog DateTime object `{ __hogDateTime__: true, dt, zone }`.
///
/// To match ClickHouse (the parity oracle), this VM orders Hog temporals by `dt` seconds
-/// ([`crate::values::compare_values`]) — the reference Python/TS HogVMs cannot order them, so their
-/// `is_date_before`/`is_date_after` always return `false`. Naive strings parse as UTC (or `zone` for
-/// the 2-arg form), not the process-local timezone; an explicit offset/`Z` is honored as written.
+/// ([`crate::values::compare_values`]), matching the Python/TS reference VMs' `unify_comparison_types`/
+/// `unifyComparisonTypes`. Naive strings parse as UTC (or `zone` for the 2-arg form), not the
+/// process-local timezone; an explicit offset/`Z` is honored as written.
fn to_datetime(vm: &HogVM, args: Vec<HogValue>) -> Result<HogValue, VmError> {
if args.is_empty() || args.len() > 2 {
return Err(VmError::NativeCallFailed(
@@ -1609,7 +1609,7 @@ 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"];
-fn parse_datetime_to_seconds(input: &str, zone: Option<&str>) -> Result<f64, VmError> {
+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) {
diff --git a/rust/common/hogvm/src/values.rs b/rust/common/hogvm/src/values.rs
index eae320e6d054..79046630ae76 100644
--- a/rust/common/hogvm/src/values.rs
+++ b/rust/common/hogvm/src/values.rs
@@ -8,6 +8,7 @@ use crate::{
context::Symbol,
error::VmError,
memory::{HeapReference, VmHeap},
+ stl::parse_datetime_to_seconds,
vm::MAX_JSON_SERDE_DEPTH,
};
@@ -401,7 +402,7 @@ impl HogLiteral {
}
}
-/// Ordering comparison (`Gt`/`Lt`/`GtEq`/`LtEq`) for two literals, two concerns in order:
+/// Ordering comparison (`Gt`/`Lt`/`GtEq`/`LtEq`) for two literals, three 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,9 +411,14 @@ impl HogLiteral {
/// 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 — the reference Python/TS HogVMs can't and so always return
-/// `false`; see the [`crate::stl`] module note.
-/// 2. Otherwise coerce like Python `unify_comparison_types` / TS `unifyComparisonTypes`: a String
+/// 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
/// 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).
@@ -422,10 +428,28 @@ pub fn compare_values(
b: &HogLiteral,
heap: &VmHeap,
) -> Result<HogLiteral, VmError> {
- if let (Some(a_secs), Some(b_secs)) = (a.as_temporal_seconds(heap), b.as_temporal_seconds(heap))
- {
+ 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) {
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/tests/datetime.rs b/rust/common/hogvm/tests/datetime.rs
index 0c0a17f92200..f5de0ee1979e 100644
--- a/rust/common/hogvm/tests/datetime.rs
+++ b/rust/common/hogvm/tests/datetime.rs
@@ -1,6 +1,6 @@
//! Coverage for the `toDateTime`/`toDate` natives and Hog-temporal comparison. This VM orders
-//! temporals by `dt` seconds to match ClickHouse (the reference Python/TS HogVMs cannot order them);
-//! naive strings parse as UTC, not the process-local timezone.
+//! temporals by `dt` seconds to match ClickHouse, matching the Python/TS reference VMs; naive
+//! strings parse as UTC, not the process-local timezone.
use chrono::{NaiveDate, TimeZone, Utc};
use hogvm::{sync_execute, ExecutionContext, Program};
@@ -173,6 +173,25 @@ fn legacy_default_compares_temporals_structurally_not_by_epoch() {
);
}
+#[test]
+fn bare_field_string_orders_against_a_datetime_by_parsing_it() {
+ // Regression: a hand-written SQL trigger filter like `timestamp > toDateTime('2026-01-01')`
+ // only wraps the RHS in toDateTime, so the VM compares a bare String literal (the filter globals'
+ // ISO `timestamp`) against a HogDateTime object. Before this fix, exactly one side being temporal
+ // fell straight to `CannotCoerce` — the trigger's filter would error, not silently pass, but it
+ // never matched by ordering either.
+ let bare_timestamp = vec![json!(OP_STRING), json!("2026-06-28T00:00:00.000Z")];
+ let threshold = to_datetime("2026-01-01 00:00:00");
+ assert_eq!(
+ run(compare(&bare_timestamp, &threshold, OP_GT)),
+ Value::Bool(true)
+ );
+ assert_eq!(
+ run(compare(&threshold, &bare_timestamp, OP_GT)),
+ Value::Bool(false)
+ );
+}
+
#[test]
fn date_and_datetime_are_mutually_comparable() {
let date = vec![