: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): stop rejecting boolean branches beside property accesses (#81892)
Sam Penningtonf69d78147eaf
diff --git a/posthog/hogql/test/test_type_system.py b/posthog/hogql/test/test_type_system.pyindex 6d16d7581d6e..c6db5f4fb475 100644--- a/posthog/hogql/test/test_type_system.py+++ b/posthog/hogql/test/test_type_system.py@@ -12,6 +12,7 @@ from posthog.hogql.errors import QueryErrorfrom posthog.hogql.functions.mapping import find_hogql_functionfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.printer import print_prepared_ast+from posthog.hogql.property_metadata import PropertyMetadatafrom posthog.hogql.resolver import resolve_typesfrom posthog.hogql.transforms.type_aware_simplification import simplify_redundant_type_operationsfrom posthog.hogql.type_diagnostics import (@@ -187,6 +188,27 @@ class TestHogQLTypeSystem:assert exc_info.value.start is not None, queryassert exc_info.value.end is not None, query+ def test_resolver_allows_boolean_branches_beside_property_accesses(self) -> None:+ # A property access reads as the parent JSON column's type whenever no property-definition+ # metadata is loaded, so treating that as a real conflict rejects queries ClickHouse runs.+ for query in (+ "SELECT coalesce(properties.blocked, false) FROM events",+ "SELECT ifNull(properties.blocked, false) FROM events",+ "SELECT if(1, false, properties.blocked) FROM events",+ "SELECT multiIf(1, false, 2, true, properties.blocked) FROM events",+ "SELECT coalesce(properties.blocked, properties.plan = 'paid') FROM events",+ "SELECT coalesce(person.properties.blocked, false) FROM events",+ ):+ node = cast(ast.SelectQuery, resolve_types(self._select(query), self.context, dialect="clickhouse"))+ column_type = node.select[0].type+ assert column_type is not None+ assert column_type.resolve_constant_type(self.context) == ast.UnknownType(), query++ # A loaded property definition types the property confidently enough to conflict with the+ # boolean branch, so only the property-access check keeps this query from being rejected.+ self.context.property_metadata = PropertyMetadata(event_properties={"signup": {"type": "DateTime"}})+ self._assert_first_column_type("SELECT coalesce(properties.signup, false) FROM events", ast.UnknownType())+def test_resolver_poisons_only_unanalyzable_branches(self) -> None:# An unmapped function (throwIf) infers as unanalyzable, poisoning the unifying call's type...for query in ("SELECT ifNull(throwIf(0, 'x'), 1)", "SELECT if(1, throwIf(0, 'x'), 1)"):diff --git a/posthog/hogql/type_system.py b/posthog/hogql/type_system.pyindex db6581ce1ac3..76327c099897 100644--- a/posthog/hogql/type_system.py+++ b/posthog/hogql/type_system.py@@ -164,6 +164,11 @@ DATETIME_RUNTIME_TYPE = RuntimeType(family="datetime")# Families least_common_runtime_type() already unifies with boolean (bool literals read as 0/1)._BOOLEAN_COMPATIBLE_FAMILIES: frozenset[RuntimeTypeFamily] = frozenset({"boolean", "integer", "float", "decimal"})+# JSON is what a property access falls back to when no property-definition metadata is available,+# and it also covers native JSON/Dynamic columns. Either way the family says nothing about the type+# ClickHouse ends up with, so a mismatch against it is never trustworthy enough to raise on.+_UNTRUSTWORTHY_BRANCH_FAMILIES: frozenset[RuntimeTypeFamily] = frozenset({"json"})+_INTEGER_RE = re.compile(r"^(U?Int)(8|16|32|64|128|256)$", re.IGNORECASE)_FLOAT_RE = re.compile(r"^Float(32|64)$", re.IGNORECASE)@@ -730,6 +735,25 @@ def least_common_supertype(types: Sequence[ast.ConstantType], dialect: HogQLDialreturn constant_type_from_runtime_type(least_common_runtime_type(runtime_types, dialect=dialect))+def _branch_type_is_untrustworthy(branch_type: ast.ConstantType, expr: Optional[ast.Expr]) -> bool:+ """Whether a branch's inferred type is too weak a signal to raise a user-facing error over.++ A property access (`properties.blocked`) is typed from property-definition metadata, which the+ resolver frequently does not have loaded - it then falls back to the JSON type of the parent+ `properties` column, regardless of what the property actually holds. The printer resolves the+ physical read separately, so `coalesce(properties.blocked, false)` reaches ClickHouse with two+ compatible branches even though inference reports JSON and Boolean.++ Every property access is skipped, not only the metadata-missing fallback: a loaded property+ definition types the property from the values seen so far, which is still a guess about what a+ given row holds, so it is no safer to raise on than the JSON fallback."""+ if runtime_type_from_constant_type(branch_type).family in _UNTRUSTWORTHY_BRANCH_FAMILIES:+ return True+ while isinstance(expr, ast.Alias):+ expr = expr.expr+ return expr is not None and isinstance(expr.type, ast.PropertyType)++def _branch_supertype_or_raise(branch_types: list[ast.ConstantType],branch_args: Sequence[Optional[ast.Expr]],@@ -744,7 +768,9 @@ def _branch_supertype_or_raise(rather than raising on every family combination with no explicit unification rule: manygenerated queries elsewhere in the codebase mix families (e.g. DateTime with a Stringplaceholder, JSON with a String default) that silently degrade to UnknownType today and work- fine against ClickHouse, so raising there would be a false positive."""+ fine against ClickHouse, so raising there would be a false positive. Branches whose inferred+ type is a guess rather than a fact are skipped for the same reason - see+ _branch_type_is_untrustworthy."""result = least_common_supertype(branch_types, dialect=dialect)if not isinstance(result, ast.UnknownType) or result.unanalyzable:return result@@ -755,6 +781,8 @@ def _branch_supertype_or_raise(]if len(known) < 2:return result+ if any(_branch_type_is_untrustworthy(branch_type, expr) for branch_type, expr in known):+ return resultfamilies = {runtime_type_from_constant_type(branch_type).family for branch_type, _ in known}if "boolean" not in families or not (families - _BOOLEAN_COMPATIBLE_FAMILIES):return result