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(hogql): raise a real error when if/multiIf/ifNull/coalesce branches share no common type (#77046)

posthog[bot]7d96268c17f7
diff --git a/posthog/hogql/test/test_type_system.py b/posthog/hogql/test/test_type_system.py
index 447e32df7de8..6d16d7581d6e 100644
--- a/posthog/hogql/test/test_type_system.py
+++ b/posthog/hogql/test/test_type_system.py
@@ -8,6 +8,7 @@ from posthog.hogql.constants import HogQLDialect
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
from posthog.hogql.database.models import FloatArrayDatabaseField
+from posthog.hogql.errors import QueryError
from posthog.hogql.functions.mapping import find_hogql_function
from posthog.hogql.parser import parse_select
from posthog.hogql.printer import print_prepared_ast
@@ -170,6 +171,22 @@ class TestHogQLTypeSystem:
unanalyzable=True
)
+ def test_resolver_raises_on_incompatible_branch_types(self) -> None:
+ for query, function_name in (
+ ("SELECT if(1, false, toDate('2024-01-01'))", "if"),
+ ("SELECT ifNull(false, toDate('2024-01-01'))", "ifNull"),
+ ("SELECT multiIf(1, false, 2, true, toDate('2024-01-01'))", "multiIf"),
+ ("SELECT coalesce(false, toDate('2024-01-01'))", "coalesce"),
+ ):
+ with pytest.raises(QueryError) as exc_info:
+ resolve_types(parse_select(query), self.context, dialect="clickhouse")
+ assert function_name in str(exc_info.value), query
+ assert "Boolean" in str(exc_info.value), query
+ assert "Date" in str(exc_info.value), query
+ # The error carries a source span so the editor can underline the offending branches.
+ assert exc_info.value.start is not None, query
+ assert exc_info.value.end is not None, query
+
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.py
index dbb2b331c134..db6581ce1ac3 100644
--- a/posthog/hogql/type_system.py
+++ b/posthog/hogql/type_system.py
@@ -10,6 +10,7 @@ from typing import TYPE_CHECKING, Literal, Optional, cast
from posthog.hogql import ast
from posthog.hogql.constants import HogQLDialect
+from posthog.hogql.errors import QueryError
if TYPE_CHECKING:
from posthog.hogql.database.models import DatabaseField
@@ -160,6 +161,9 @@ FLOAT_RUNTIME_TYPE = RuntimeType(family="float", bits=64)
DATE_RUNTIME_TYPE = RuntimeType(family="date")
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"})
+
_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)
@@ -726,6 +730,49 @@ def least_common_supertype(types: Sequence[ast.ConstantType], dialect: HogQLDial
return constant_type_from_runtime_type(least_common_runtime_type(runtime_types, dialect=dialect))
+def _branch_supertype_or_raise(
+ branch_types: list[ast.ConstantType],
+ branch_args: Sequence[Optional[ast.Expr]],
+ dialect: HogQLDialect,
+ function_name: str,
+) -> ast.ConstantType:
+ """Like least_common_supertype, but raises a user-facing error naming the conflicting branch
+ types and their source span when a boolean branch is mixed with a non-numeric branch, rather
+ than silently degrading to UnknownType and failing downstream in ClickHouse.
+
+ Scoped to boolean mismatches specifically (the reported symptom: `if(cond, false, someDate)`)
+ rather than raising on every family combination with no explicit unification rule: many
+ generated queries elsewhere in the codebase mix families (e.g. DateTime with a String
+ placeholder, JSON with a String default) that silently degrade to UnknownType today and work
+ fine against ClickHouse, so raising there would be a false positive."""
+ result = least_common_supertype(branch_types, dialect=dialect)
+ if not isinstance(result, ast.UnknownType) or result.unanalyzable:
+ return result
+ known = [
+ (branch_type, branch_args[index] if index < len(branch_args) else None)
+ for index, branch_type in enumerate(branch_types)
+ if not isinstance(branch_type, ast.UnknownType)
+ ]
+ if len(known) < 2:
+ return result
+ families = {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
+ type_names = sorted({branch_type.print_type() for branch_type, _ in known})
+ positions = [
+ (expr.start, expr.end)
+ for _, expr in known
+ if expr is not None and expr.start is not None and expr.end is not None
+ ]
+ start = min((position[0] for position in positions), default=None)
+ end = max((position[1] for position in positions), default=None)
+ raise QueryError(
+ f"Cannot find a common type between `{function_name}` branches of type {' and '.join(type_names)}",
+ start=start,
+ end=end,
+ )
+
+
def least_common_runtime_type(runtime_types: list[RuntimeType], dialect: HogQLDialect = "clickhouse") -> RuntimeType:
nullable = any(type_.nullable for type_ in runtime_types)
# An unanalyzable branch could be any type, so it poisons the result; a vacuous unknown
@@ -987,17 +1034,28 @@ def _infer_generic_function_type(
return ast.BooleanType(nullable=any(arg_type.nullable for arg_type in arg_types))
if normalized_name == "if":
- return least_common_supertype(arg_types[1:], dialect=dialect) if len(arg_types) > 1 else ast.UnknownType()
+ if len(arg_types) <= 1:
+ return ast.UnknownType()
+ branch_types = arg_types[1:]
+ return _branch_supertype_or_raise(branch_types, (args or [])[1:], dialect=dialect, function_name="if")
if normalized_name == "ifnull":
- return least_common_supertype(arg_types, dialect=dialect) if len(arg_types) > 1 else ast.UnknownType()
+ if len(arg_types) <= 1:
+ return ast.UnknownType()
+ return _branch_supertype_or_raise(arg_types, args or [], dialect=dialect, function_name="ifNull")
if normalized_name == "multiif":
if len(arg_types) < 3:
return ast.UnknownType()
- return least_common_supertype([*arg_types[1::2], arg_types[-1]], dialect=dialect)
+ branch_indices = [*range(1, len(arg_types) - 1, 2), len(arg_types) - 1]
+ branch_types = [arg_types[i] for i in branch_indices]
+ branch_args = [args[i] if args is not None and i < len(args) else None for i in branch_indices]
+ return _branch_supertype_or_raise(branch_types, branch_args, dialect=dialect, function_name="multiIf")
+
+ if normalized_name == "coalesce":
+ return _branch_supertype_or_raise(arg_types, args or [], dialect=dialect, function_name="coalesce")
- if normalized_name in {"coalesce", "least", "greatest"}:
+ if normalized_name in {"least", "greatest"}:
return least_common_supertype(arg_types, dialect=dialect)
if normalized_name == "nullif" and arg_types: