: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): make toBool null-safe to avoid UUID boolean cast errors (#63220)
George Munyoro5540077003bb
diff --git a/posthog/hogql/database/schema/util/test/test_person_where_clause_extractor.py b/posthog/hogql/database/schema/util/test/test_person_where_clause_extractor.pyindex 626948074e2b..d7125c20b2b5 100644--- a/posthog/hogql/database/schema/util/test/test_person_where_clause_extractor.py+++ b/posthog/hogql/database/schema/util/test/test_person_where_clause_extractor.py@@ -220,6 +220,6 @@ class TestPersonWhereClauseExtractor(ClickhouseTestMixin, APIBaseTest):)actual = self.print_query("SELECT * FROM events WHERE person.properties.person_boolean = false")assert (- f"ifNull(equals(toBool(transform(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties"+ f"ifNull(equals(accurateCastOrNull(transform(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties"in actual)diff --git a/posthog/hogql/functions/aggregations.py b/posthog/hogql/functions/aggregations.pyindex f498ab8f7846..f6ef250432ba 100644--- a/posthog/hogql/functions/aggregations.py+++ b/posthog/hogql/functions/aggregations.py@@ -145,7 +145,7 @@ HOGQL_AGGREGATIONS: dict[str, HogQLFunctionMeta] = {using_placeholder_arguments=True,),"every": HogQLFunctionMeta(- "toBool(min({}))",+ "accurateCastOrNull(min({}), 'Bool')",1,1,aggregate=True,diff --git a/posthog/hogql/functions/clickhouse/conversions.py b/posthog/hogql/functions/clickhouse/conversions.pyindex 002b99ec6924..996c0c76f4a7 100644--- a/posthog/hogql/functions/clickhouse/conversions.py+++ b/posthog/hogql/functions/clickhouse/conversions.py@@ -105,7 +105,7 @@ TYPE_CONVERSION_FUNCTIONS: dict[str, HogQLFunctionMeta] = {"toNullableString": HogQLFunctionMeta("accurateCastOrNull", 1, 1, suffix_args=[ast.Constant(value="Nullable(String)")]),- "toBool": HogQLFunctionMeta("toBool", 1, 1),+ "toBool": HogQLFunctionMeta("accurateCastOrNull", 1, 1, suffix_args=[ast.Constant(value="Bool")]),"toJSONString": HogQLFunctionMeta("toJSONString", 1, 1),"parseDateTime": HogQLFunctionMeta("parseDateTimeOrNull", 2, 3, tz_aware=True),"parseDateTimeBestEffort": HogQLFunctionMeta("parseDateTime64BestEffortOrNull", 1, 2, tz_aware=True),diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.pyindex 9ef6628065b6..5a9aacf89979 100644--- a/posthog/hogql/printer/test/test_printer.py+++ b/posthog/hogql/printer/test/test_printer.py@@ -1240,6 +1240,18 @@ class TestPrinter(BaseTest):"groupArraySampleIf(5, 123456)(events.event, isNotNull(events.event))",)+ @parameterized.expand(+ [+ ("toBool", "toBool(uuid)", "accurateCastOrNull(events.uuid, %(hogql_val_0)s)"),+ ("every", "every(uuid)", "accurateCastOrNull(min(events.uuid), 'Bool')"),+ ]+ )+ def test_to_bool_is_null_safe(self, _name: str, expr: str, expected: str) -> None:+ # Boolean casts must not hard-fail on non-boolean input (e.g. a UUID-shaped string).+ # They route through accurateCastOrNull so unparseable values become NULL instead+ # of raising "Cannot parse boolean value here" and failing the whole query.+ self.assertEqual(self._expr(expr), expected)+def test_expr_parse_errors(self):self._assert_expr_error("", "Empty query")self._assert_expr_error("avg(bla)", "Unable to resolve field: bla")@@ -2509,18 +2521,21 @@ class TestPrinter(BaseTest):)assert generated_sql_statements1 == (f"SELECT "- "ifNull(equals(toBool(transform(toString(nullIf(nullIf(events.mat_is_boolean, ''), 'null')), %(hogql_val_0)s, %(hogql_val_1)s, NULL)), 1), 0), "- "ifNull(equals(toBool(transform(toString(nullIf(nullIf(events.mat_is_boolean, ''), 'null')), %(hogql_val_2)s, %(hogql_val_3)s, NULL)), 0), 0), "- "isNull(toBool(transform(toString(nullIf(nullIf(events.mat_is_boolean, ''), 'null')), %(hogql_val_4)s, %(hogql_val_5)s, NULL))) "+ "ifNull(equals(accurateCastOrNull(transform(toString(nullIf(nullIf(events.mat_is_boolean, ''), 'null')), %(hogql_val_0)s, %(hogql_val_1)s, NULL), %(hogql_val_2)s), 1), 0), "+ "ifNull(equals(accurateCastOrNull(transform(toString(nullIf(nullIf(events.mat_is_boolean, ''), 'null')), %(hogql_val_3)s, %(hogql_val_4)s, NULL), %(hogql_val_5)s), 0), 0), "+ "isNull(accurateCastOrNull(transform(toString(nullIf(nullIf(events.mat_is_boolean, ''), 'null')), %(hogql_val_6)s, %(hogql_val_7)s, NULL), %(hogql_val_8)s)) "f"FROM events WHERE equals(events.team_id, {self.team.pk}) LIMIT {MAX_SELECT_RETURNED_ROWS}")assert context.values == {"hogql_val_0": ["true", "false"],"hogql_val_1": [1, 0],- "hogql_val_2": ["true", "false"],- "hogql_val_3": [1, 0],- "hogql_val_4": ["true", "false"],- "hogql_val_5": [1, 0],+ "hogql_val_2": "Bool",+ "hogql_val_3": ["true", "false"],+ "hogql_val_4": [1, 0],+ "hogql_val_5": "Bool",+ "hogql_val_6": ["true", "false"],+ "hogql_val_7": [1, 0],+ "hogql_val_8": "Bool",}@patch("posthog.hogql.transforms.clickhouse_property_resolution.get_materialized_column_for_property")diff --git a/posthog/hogql/test/test_type_system.py b/posthog/hogql/test/test_type_system.pyindex 3335340df405..0d869661de48 100644--- a/posthog/hogql/test/test_type_system.py+++ b/posthog/hogql/test/test_type_system.py@@ -209,6 +209,8 @@ class TestHogQLTypeSystem:self._assert_first_column_type("SELECT accurateCastOrNull('1', 'Int64')", ast.IntegerType(nullable=True))self._assert_first_column_type("SELECT accurateCast('2024-01-01', 'Date')", ast.DateType(nullable=False))self._assert_first_column_type("SELECT accurateCast('1', 'Nullable(Int64)')", ast.IntegerType(nullable=True))+ # toBool renders as accurateCastOrNull, so it can be NULL on parse failure even for non-null input+ self._assert_first_column_type("SELECT toBool(event) FROM events", ast.BooleanType(nullable=True))self._assert_first_column_type("SELECT reinterpretAsUInt64('12345678')", ast.IntegerType(nullable=False))self._assert_first_column_type("SELECT reinterpretAsFloat64('12345678')", ast.FloatType(nullable=False))self._assert_first_column_type("SELECT reinterpretAsUUID('1234567890123456')", ast.UUIDType(nullable=False))diff --git a/posthog/hogql/transforms/test/__snapshots__/test_property_types.ambr b/posthog/hogql/transforms/test/__snapshots__/test_property_types.ambrindex 573fb5ff70e3..c71d091786b0 100644--- a/posthog/hogql/transforms/test/__snapshots__/test_property_types.ambr+++ b/posthog/hogql/transforms/test/__snapshots__/test_property_types.ambr@@ -2,7 +2,7 @@# name: TestPropertyTypes.test_data_warehouse_person_property_types'''- SELECT persons__extended_properties.string_prop AS string_prop, persons__extended_properties.int_prop AS int_prop, toBool(transform(toString(persons__extended_properties.bool_prop), %(hogql_val_8)s, %(hogql_val_9)s, NULL)) AS bool_prop+ SELECT persons__extended_properties.string_prop AS string_prop, persons__extended_properties.int_prop AS int_prop, accurateCastOrNull(transform(toString(persons__extended_properties.bool_prop), %(hogql_val_8)s, %(hogql_val_9)s, NULL), %(hogql_val_10)s) AS bool_propFROM (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, %(hogql_val_0)s), ''), 'null'), '^"|"$', '')), person.version), 1) AS persons___properties___email, person.id AS idFROM person@@ -19,7 +19,7 @@# name: TestPropertyTypes.test_group_boolean_property_types'''- SELECT ifNull(equals(toBool(transform(toString(events__group_0.properties___group_boolean), %(hogql_val_2)s, %(hogql_val_3)s, NULL)), 1), 0), ifNull(equals(toBool(transform(toString(events__group_0.properties___group_boolean), %(hogql_val_4)s, %(hogql_val_5)s, NULL)), 0), 0), isNull(toBool(transform(toString(events__group_0.properties___group_boolean), %(hogql_val_6)s, %(hogql_val_7)s, NULL)))+ SELECT ifNull(equals(accurateCastOrNull(transform(toString(events__group_0.properties___group_boolean), %(hogql_val_2)s, %(hogql_val_3)s, NULL), %(hogql_val_4)s), 1), 0), ifNull(equals(accurateCastOrNull(transform(toString(events__group_0.properties___group_boolean), %(hogql_val_5)s, %(hogql_val_6)s, NULL), %(hogql_val_7)s), 0), 0), isNull(accurateCastOrNull(transform(toString(events__group_0.properties___group_boolean), %(hogql_val_8)s, %(hogql_val_9)s, NULL), %(hogql_val_10)s))FROM events LEFT JOIN (SELECT tupleElement(argMax(tuple(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(groups.group_properties, %(hogql_val_0)s), ''), 'null'), '^"|"$', '')), toTimeZone(groups._timestamp, %(hogql_val_1)s)), 1) AS properties___group_boolean, groups.group_type_index AS index, groups.group_key AS keyFROM groups@@ -66,7 +66,7 @@# name: TestPropertyTypes.test_resolve_property_types_event'''- SELECT multiply(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_0)s), ''), 'null'), '^"|"$', ''), %(hogql_val_1)s), accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_2)s), ''), 'null'), '^"|"$', ''), %(hogql_val_3)s)), toBool(transform(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_4)s), ''), 'null'), '^"|"$', '')), %(hogql_val_5)s, %(hogql_val_6)s, NULL)) AS bool+ SELECT multiply(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_0)s), ''), 'null'), '^"|"$', ''), %(hogql_val_1)s), accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_2)s), ''), 'null'), '^"|"$', ''), %(hogql_val_3)s)), accurateCastOrNull(transform(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, %(hogql_val_4)s), ''), 'null'), '^"|"$', '')), %(hogql_val_5)s, %(hogql_val_6)s, NULL), %(hogql_val_7)s) AS boolFROM eventsWHERE equals(events.team_id, 420)LIMIT 50000diff --git a/posthog/hogql/transforms/test/test_property_types.py b/posthog/hogql/transforms/test/test_property_types.pyindex 7da477f75534..556b27f6f3ed 100644--- a/posthog/hogql/transforms/test/test_property_types.py+++ b/posthog/hogql/transforms/test/test_property_types.py@@ -373,7 +373,7 @@ class TestPropertyTypes(BaseTest):)assert printed == self.snapshotassert (- "SELECT ifNull(equals(toBool(transform(toString(events__group_0.properties___group_boolean), hogvar, hogvar, NULL)), 1), 0), ifNull(equals(toBool(transform(toString(events__group_0.properties___group_boolean), hogvar, hogvar, NULL)), 0), 0), isNull(toBool(transform(toString(events__group_0.properties___group_boolean), hogvar, hogvar, NULL)))"+ "SELECT ifNull(equals(accurateCastOrNull(transform(toString(events__group_0.properties___group_boolean), hogvar, hogvar, NULL), hogvar), 1), 0), ifNull(equals(accurateCastOrNull(transform(toString(events__group_0.properties___group_boolean), hogvar, hogvar, NULL), hogvar), 0), 0), isNull(accurateCastOrNull(transform(toString(events__group_0.properties___group_boolean), hogvar, hogvar, NULL), hogvar))"in re.sub(r"%\(hogql_val_\d+\)s", "hogvar", printed))diff --git a/posthog/hogql/type_system.py b/posthog/hogql/type_system.pyindex 6ac75b7762c9..2b9928c2d56d 100644--- a/posthog/hogql/type_system.py+++ b/posthog/hogql/type_system.py@@ -1283,6 +1283,7 @@ def _conversion_nullable(normalized_name: str, arg_types: list[ast.ConstantType]return any(arg_type.nullable for arg_type in arg_types) or normalized_name in {"toint","tofloat",+ "tobool","touuid","todecimal","parsedatetime",