: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
feat(hogql): infer aggregate combinator return types (#67123)
George Munyoroe75f412a8ce9
diff --git a/posthog/hogql/test/test_type_system.py b/posthog/hogql/test/test_type_system.pyindex 78ce8ed2b653..8b0e18541398 100644--- a/posthog/hogql/test/test_type_system.py+++ b/posthog/hogql/test/test_type_system.py@@ -594,6 +594,99 @@ class TestHogQLTypeSystem:item_type=ast.FloatType(nullable=False),)+ @pytest.mark.parametrize(+ "name,arg_types,expected",+ [+ # -If drops the trailing condition; the base return type is unchanged.+ (+ "sumIf",+ [ast.IntegerType(nullable=False), ast.BooleanType(nullable=False)],+ ast.IntegerType(nullable=False),+ ),+ (+ "maxIf",+ [ast.StringType(nullable=False), ast.BooleanType(nullable=False)],+ ast.StringType(nullable=False),+ ),+ (+ "argMaxIf",+ [ast.StringType(nullable=False), ast.DateTimeType(nullable=False), ast.BooleanType(nullable=False)],+ ast.StringType(nullable=False),+ ),+ (+ "countDistinctIf",+ [ast.IntegerType(nullable=False), ast.BooleanType(nullable=False)],+ ast.IntegerType(nullable=False),+ ),+ # -Array aggregates over array elements; result type matches the base.+ (+ "sumArray",+ [ast.ArrayType(nullable=False, item_type=ast.IntegerType(nullable=False))],+ ast.IntegerType(nullable=False),+ ),+ # -ForEach wraps the base result in an array.+ (+ "sumForEach",+ [ast.ArrayType(nullable=False, item_type=ast.FloatType(nullable=False))],+ ast.ArrayType(nullable=False, item_type=ast.FloatType(nullable=False)),+ ),+ # -OrNull makes the result nullable; -OrDefault forces it non-null.+ ("sumOrNull", [ast.IntegerType(nullable=False)], ast.IntegerType(nullable=True)),+ ("avgOrNull", [ast.IntegerType(nullable=False)], ast.FloatType(nullable=True)),+ ("sumOrDefault", [ast.IntegerType(nullable=True)], ast.IntegerType(nullable=False)),+ (+ "groupArrayIf",+ [ast.StringType(nullable=False), ast.BooleanType(nullable=False)],+ ast.ArrayType(nullable=False, item_type=ast.StringType(nullable=False)),+ ),+ # quantiles already returns an array — the combinator must transform that, not be swallowed+ # by the greedy "quantiles" base match. -ForEach therefore nests it.+ (+ "quantilesForEach",+ [ast.ArrayType(nullable=False, item_type=ast.FloatType(nullable=False))],+ ast.ArrayType(+ nullable=False, item_type=ast.ArrayType(nullable=False, item_type=ast.FloatType(nullable=False))+ ),+ ),+ # Stacked combinators peel outermost-first.+ (+ "quantilesArrayIf",+ [+ ast.ArrayType(nullable=False, item_type=ast.FloatType(nullable=False)),+ ast.BooleanType(nullable=False),+ ],+ ast.ArrayType(nullable=False, item_type=ast.FloatType(nullable=False)),+ ),+ (+ "sumIfOrNull",+ [ast.IntegerType(nullable=False), ast.BooleanType(nullable=False)],+ ast.IntegerType(nullable=True),+ ),+ # -Distinct leaves the base result type unchanged. countDistinct resolves via this path now+ # that it's no longer enumerated in the base set.+ ("countDistinct", [ast.IntegerType(nullable=False)], ast.IntegerType(nullable=False)),+ ],+ )+ def test_resolver_infers_aggregate_combinator_types(+ self, name: str, arg_types: list[ast.ConstantType], expected: ast.ConstantType+ ) -> None:+ assert infer_function_return_type(name, arg_types).return_type == expected++ def test_aggregate_combinator_inference_is_conservative(self) -> None:+ # A name ending in a combinator suffix whose residual is not a known aggregate must stay+ # Unknown rather than be assigned a confidently-wrong type.+ assert (+ infer_function_return_type(+ "notarealaggregateforeach",+ [ast.ArrayType(nullable=False, item_type=ast.FloatType(nullable=False))],+ ).source+ == "unknown"+ )+ # A plain base aggregate (no combinator) is unaffected.+ assert infer_function_return_type("sum", [ast.IntegerType(nullable=False)]).return_type == ast.IntegerType(+ nullable=False+ )+def test_resolver_infers_common_string_function_types(self) -> None:self._assert_first_column_type("SELECT base64Encode('test')", ast.StringType(nullable=False))self._assert_first_column_type("SELECT hex(unhex('DEADBEEF'))", ast.StringType(nullable=False))diff --git a/posthog/hogql/type_system.py b/posthog/hogql/type_system.pyindex 89039d132188..8ef2a04f5020 100644--- a/posthog/hogql/type_system.py+++ b/posthog/hogql/type_system.py@@ -1425,27 +1425,23 @@ def _normalize_array_reduce_aggregate_name(aggregate_name: str) -> str:def _infer_aggregate_function_type(normalized_name: str, arg_types: list[ast.ConstantType]) -> ast.ConstantType | None:+ # A ClickHouse aggregate is a base aggregate plus zero or more stackable combinator suffixes+ # (-If, -Array, -ForEach, -OrNull, -OrDefault, -Distinct, -State, -Merge). Peel known combinators+ # first so the base return type is computed once and each suffix transforms it, instead of+ # enumerating every base×combinator permutation. This must run before the base checks below so a+ # greedy `startswith` match (e.g. "quantiles") can't swallow a combinator such as -ForEach.+ combinator_type = _infer_aggregate_combinator_type(normalized_name, arg_types)+ if combinator_type is not None:+ return combinator_type+state_or_merge_type = _infer_aggregate_state_or_merge_type(normalized_name, arg_types)if state_or_merge_type is not None:return state_or_merge_type- if normalized_name in {- "count",- "countif",- "countdistinct",- "countdistinctif",- "uniq",- "uniqif",- "uniqexact",- "uniqexactif",- "uniqhll12",- "uniqhll12if",- "uniqtheta",- "uniqthetaif",- }:+ if normalized_name in {"count", "uniq", "uniqexact", "uniqhll12", "uniqtheta"}:return ast.IntegerType(nullable=False)- if normalized_name in {"sum", "sumif"} and arg_types:+ if normalized_name == "sum" and arg_types:input_type = arg_types[0]if isinstance(input_type, ast.FloatType):return ast.FloatType(nullable=input_type.nullable)@@ -1460,41 +1456,68 @@ def _infer_aggregate_function_type(normalized_name: str, arg_types: list[ast.Con)if (- normalized_name in {"avg", "avgif", "stddevpop", "stddevsamp", "varpop", "varsamp"}+ normalized_name in {"avg", "stddevpop", "stddevsamp", "varpop", "varsamp"}or normalized_name.startswith("median")or normalized_name.startswith("quantile")) and not _is_aggregate_state_or_merge(normalized_name):return ast.FloatType(nullable=any(arg_type.nullable for arg_type in arg_types))- if (- normalized_name- in {- "min",- "minif",- "max",- "maxif",- "any",- "anyif",- "anylast",- "anylastif",- "argmin",- "argminif",- "argmax",- "argmaxif",- }- and arg_types- ):+ if normalized_name in {"min", "max", "any", "anylast", "argmin", "argmax"} and arg_types:return dataclasses.replace(arg_types[0])- if (- normalized_name in {"grouparray", "array_agg", "groupuniqarray", "grouparrayif", "groupuniqarrayif"}- and arg_types- ):+ if normalized_name in {"grouparray", "array_agg", "groupuniqarray"} and arg_types:return ast.ArrayType(nullable=False, item_type=dataclasses.replace(arg_types[0]))return None+# ClickHouse aggregate combinator suffixes this rule understands. Each one transforms the base+# aggregate's return type. Combinators not listed here (-Map, -Resample, -SimpleState, -MergeState,+# argument-shape variants, …) are deliberately left to fall through to UnknownType rather than risk a+# confidently-wrong type. -State/-Merge keep their dedicated handling in+# _infer_aggregate_state_or_merge_type because they carry/consume AggregateState payloads.+_AGGREGATE_COMBINATOR_SUFFIXES: tuple[str, ...] = ("ordefault", "ornull", "distinct", "foreach", "array", "if")+++def _infer_aggregate_combinator_type(+ normalized_name: str, arg_types: list[ast.ConstantType]+) -> ast.ConstantType | None:+ for suffix in _AGGREGATE_COMBINATOR_SUFFIXES:+ if not normalized_name.endswith(suffix) or len(normalized_name) <= len(suffix):+ continue+ base_name = normalized_name[: -len(suffix)]+ base_arg_types = _aggregate_combinator_base_arg_types(suffix, arg_types)+ # Only accept the peel if what remains is itself a known aggregate (possibly with further+ # combinators). Otherwise the suffix was a coincidence — try the next, then fall through to+ # Unknown. This keeps the rule conservative: a wrong type is worse than no type.+ base_type = _infer_aggregate_function_type(base_name, base_arg_types)+ if base_type is None:+ continue+ return _apply_aggregate_combinator(suffix, base_type)+ return None+++def _aggregate_combinator_base_arg_types(suffix: str, arg_types: list[ast.ConstantType]) -> list[ast.ConstantType]:+ if suffix == "if":+ # -If appends a UInt8 condition the base aggregate never sees.+ return arg_types[:-1]+ if suffix in {"array", "foreach"}:+ # -Array/-ForEach aggregate over array arguments, so the base sees each element type.+ return [infer_array_access_constant_type(arg_type) for arg_type in arg_types]+ return arg_types+++def _apply_aggregate_combinator(suffix: str, base_type: ast.ConstantType) -> ast.ConstantType:+ if suffix == "ornull":+ return dataclasses.replace(base_type, nullable=True)+ if suffix == "ordefault":+ return dataclasses.replace(base_type, nullable=False)+ if suffix == "foreach":+ return ast.ArrayType(nullable=False, item_type=base_type)+ # -If, -Array and -Distinct change which rows/values are aggregated, not the result type.+ return base_type++def _is_aggregate_state_or_merge(normalized_name: str) -> bool:return normalized_name.endswith("state") or normalized_name.endswith("merge") or normalized_name.endswith("mergeif")