: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(hogql): fix illegal arg to toFloat64OrZero and others (#61005)
andrew j. mcgeheecde3559bec1b
diff --git a/posthog/hogql/transforms/property_types.py b/posthog/hogql/transforms/property_types.pyindex b0aa32993a66..90e81ef3f8bc 100644--- a/posthog/hogql/transforms/property_types.py+++ b/posthog/hogql/transforms/property_types.py@@ -209,6 +209,13 @@ class PropertySwapper(CloningVisitor):ast.CompareOperationOp.LtEq,}+ # ClickHouse string-parsing conversions (toFloat64OrZero, toInt64OrZero,+ # toFloat64OrDefault) require a String first argument and raise+ # ILLEGAL_TYPE_OF_ARGUMENT on numeric input. When a user explicitly wraps a+ # Numeric-typed property in one of these, we must not auto-convert the property+ # to Float — the raw String value has to flow through for the parser to work.+ _STRING_INPUT_CONVERSIONS: set[str] = {"toFloatOrZero", "toIntOrZero", "toFloatOrDefault"}+def __init__(self,timezone: str,@@ -227,6 +234,7 @@ class PropertySwapper(CloningVisitor):self.setTimeZones = setTimeZonesself._inside_call_depth = 0self._inside_where_depth = 0+ self._suppress_numeric_conversion = Falsedef visit_select_query(self, node: ast.SelectQuery):# We need to track when we're inside WHERE/PREWHERE so that the@@ -293,11 +301,18 @@ class PropertySwapper(CloningVisitor):if rewritten is not None:return rewritten+ # Track whether the immediate enclosing call parses its argument as a+ # string. Re-evaluated per call, so nested non-parsing calls (e.g.+ # toFloatOrZero(toString(prop))) correctly reset the flag.+ saved_suppress = self._suppress_numeric_conversion+ self._suppress_numeric_conversion = node.name in self._STRING_INPUT_CONVERSIONS+self._inside_call_depth += 1try:return super().visit_call(node)finally:self._inside_call_depth -= 1+ self._suppress_numeric_conversion = saved_suppressdef _try_rewrite_json_extract_to_mat_column(self, node: ast.Call) -> ast.Field | None:"""Rewrite safe direct JSON property extraction to use a materialized column.@@ -607,6 +622,12 @@ class PropertySwapper(CloningVisitor):# Add notice about the property type and materialization statusself._add_property_notice(node, property_type, field_type, prop_info.get("dmat"))+ # The user is parsing this property as a string (toFloatOrZero/toIntOrZero/+ # toFloatOrDefault). Those ClickHouse functions require a String argument, so+ # leave the raw materialized-column/JSON value in place rather than casting it.+ if self._suppress_numeric_conversion:+ return node+# Both paths fall through to the wrapper: dmat columns are `Nullable(String)` (the# printer swaps the field to `dmat_string_<idx>`), so they need the same cast as# the JSON fallback.diff --git a/posthog/hogql/transforms/test/test_property_types.py b/posthog/hogql/transforms/test/test_property_types.pyindex 556b27f6f3ed..fd78813f24d8 100644--- a/posthog/hogql/transforms/test/test_property_types.py+++ b/posthog/hogql/transforms/test/test_property_types.py@@ -440,6 +440,31 @@ class TestPropertyTypes(BaseTest):assert printed == self.snapshot+ @parameterized.expand(+ [+ ("to_float_or_zero", "toFloatOrZero(properties.$screen_width)", "toFloat64OrZero"),+ ("to_int_or_zero", "toIntOrZero(properties.$screen_width)", "toInt64OrZero"),+ ("to_float_or_default", "toFloatOrDefault(properties.$screen_width, 0)", "toFloat64OrDefault"),+ ]+ )+ def test_numeric_property_not_double_cast_inside_string_parser(self, _name: str, expr: str, ch_fn: str):+ # toFloat64OrZero/toInt64OrZero/toFloat64OrDefault require a String first argument.+ # A Numeric property must keep its raw string value here instead of being cast to+ # Float, otherwise ClickHouse raises ILLEGAL_TYPE_OF_ARGUMENT on a Float64 argument.+ printed = self._print_select(f"select {expr} from events")+ assert f"{ch_fn}(accurateCastOrNull" not in printed+ assert f"{ch_fn}(" in printed++ def test_numeric_property_still_cast_outside_string_parser(self):+ # Without an explicit string parser, a Numeric property is still cast to Float.+ printed = self._print_select("select properties.$screen_width from events")+ assert "accurateCastOrNull" in printed++ def test_numeric_property_cast_when_explicitly_stringified_inside_parser(self):+ # toString resets the suppression, so the inner Numeric property is cast again.+ printed = self._print_select("select toFloatOrZero(toString(properties.$screen_width)) from events")+ assert "toFloat64OrZero(toString(accurateCastOrNull" in printed+def _print_select(self, select: str) -> str:expr = parse_select(select)query, _ = prepare_and_print_ast(