: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(experiments): Reject compound aggregate expressions in HogQL metrics (#86935)
Juraj Majerikcdace84bc52f
diff --git a/products/experiments/backend/hogql_queries/base_query_utils.py b/products/experiments/backend/hogql_queries/base_query_utils.pyindex 06a6d4854402..9d9a51e032b2 100644--- a/products/experiments/backend/hogql_queries/base_query_utils.py+++ b/products/experiments/backend/hogql_queries/base_query_utils.py@@ -2,6 +2,8 @@ from datetime import datetimefrom typing import Literal, Optional, Unionfrom zoneinfo import ZoneInfo+from rest_framework.exceptions import ValidationError+from posthog.schema import (ActionsNode,BaseMathType,@@ -34,6 +36,7 @@ from products.actions.backend.models.action import Actionfrom products.experiments.backend.hogql_queries.hogql_aggregation_utils import (aggregation_needs_numeric_input,build_aggregation_call,+ contains_aggregation,extract_aggregation_and_inner_expr,)from products.experiments.backend.models.experiment import Experiment@@ -148,12 +151,28 @@ def get_source_value_expr(source: Union[EventsNode, ActionsNode, ExperimentDataWif math_hogql:tag_contains_user_hogql()_, inner_expr, _, _ = extract_aggregation_and_inner_expr(math_hogql)+ # The inner expression is evaluated per event row, so any aggregate call+ # left in it (a compound expression like sum(a) / count(), or a nested+ # aggregate) would generate invalid SQL and fail in ClickHouse with+ # NOT_AN_AGGREGATE. Reject it with an actionable error instead.+ if contains_aggregation(inner_expr):+ raise ValidationError(+ "HogQL metric expressions must be a single aggregation, e.g. sum(properties.revenue). "+ "Compound expressions like sum(a) / count() are not supported."+ )return inner_exprelif isinstance(source, ExperimentDataWarehouseNode):metric_property = getattr(source, "math_property", None)if metric_property:tag_contains_user_hogql()- return parse_expr(metric_property)+ parsed = parse_expr(metric_property)+ # Same constraint as math_hogql above: this is a per-row value expression.+ if contains_aggregation(parsed):+ raise ValidationError(+ "Data warehouse metric properties cannot contain aggregate functions; "+ "reference a column or a per-row expression instead."+ )+ return parsed# Default to count - emit 1 so we can easily sum it upreturn ast.Constant(value=1)diff --git a/products/experiments/backend/hogql_queries/hogql_aggregation_utils.py b/products/experiments/backend/hogql_queries/hogql_aggregation_utils.pyindex bd4b0864c602..78a3ea2ed6f5 100644--- a/products/experiments/backend/hogql_queries/hogql_aggregation_utils.py+++ b/products/experiments/backend/hogql_queries/hogql_aggregation_utils.py@@ -3,6 +3,7 @@ from typing import Optional, Unionfrom posthog.hogql import astfrom posthog.hogql.functions.mapping import HOGQL_AGGREGATIONS, HOGQL_CLICKHOUSE_FUNCTIONS, HOGQL_POSTHOG_FUNCTIONSfrom posthog.hogql.parser import parse_expr+from posthog.hogql.visitor import TraversingVisitordef is_aggregation_function(function_name: str) -> bool:@@ -77,6 +78,33 @@ def extract_aggregation_and_inner_expr(return None, expr, None, False+# Registered in HOGQL_AGGREGATIONS for their rewriting behavior but compile to scalar+# expressions — not real aggregates (md5 -> hex(MD5(...))).+_SCALAR_REGISTRY_QUIRKS = frozenset({"md5"})+++class _AggregationFinder(TraversingVisitor):+ def __init__(self):+ super().__init__()+ self.found = False++ def visit_call(self, node: ast.Call):+ if node.name.lower() not in _SCALAR_REGISTRY_QUIRKS and is_aggregation_function(node.name):+ self.found = True+ return+ for arg in node.args:+ self.visit(arg)+ for param in node.params or []:+ self.visit(param)+++def contains_aggregation(expr: ast.Expr) -> bool:+ """Whether a real aggregate call appears anywhere in the expression."""+ finder = _AggregationFinder()+ finder.visit(expr)+ return finder.found++_NON_NUMERIC_AGGREGATIONS = frozenset({"uniq",diff --git a/products/experiments/backend/hogql_queries/test/test_hogql_aggregation_integration.py b/products/experiments/backend/hogql_queries/test/test_hogql_aggregation_integration.pyindex ccd69b88b46e..c0e8d9128971 100644--- a/products/experiments/backend/hogql_queries/test/test_hogql_aggregation_integration.py+++ b/products/experiments/backend/hogql_queries/test/test_hogql_aggregation_integration.py@@ -1,10 +1,13 @@from posthog.test.base import BaseTest-from posthog.schema import EventsNode, ExperimentMeanMetric, ExperimentMetricMathType+from parameterized import parameterized+from rest_framework.exceptions import ValidationError++from posthog.schema import EventsNode, ExperimentDataWarehouseNode, ExperimentMeanMetric, ExperimentMetricMathTypefrom posthog.hogql import ast-from products.experiments.backend.hogql_queries.base_query_utils import get_metric_value+from products.experiments.backend.hogql_queries.base_query_utils import get_metric_value, get_source_value_exprclass TestHogQLAggregationIntegration(BaseTest):@@ -38,3 +41,61 @@ class TestHogQLAggregationIntegration(BaseTest):# Should return the field expression directlyself.assertIsInstance(result_no_agg, ast.Field)self.assertEqual(result_no_agg.chain, ["properties", "revenue"]) # type: ignore[attr-defined]++ @parameterized.expand(+ [+ ("division", "sum(properties.revenue) / count()"),+ ("addition", "sum(properties.a) + sum(properties.b)"),+ ("wrapped", "toFloat(sum(properties.revenue))"),+ ("nested", "avg(sum(properties.revenue))"),+ ]+ )+ def test_rejects_compound_aggregate_expressions(self, _name: str, expr: str):+ # The extracted value expression is evaluated per row; aggregates left inside it+ # (compound or nested) would fail in ClickHouse with NOT_AN_AGGREGATE.+ metric = ExperimentMeanMetric(+ source=EventsNode(event="revenue_event", math=ExperimentMetricMathType.HOGQL, math_hogql=expr)+ )+ with self.assertRaises(ValidationError):+ get_metric_value(metric)++ def test_allows_scalar_md5_despite_registry_quirk(self):+ # md5 lives in HOGQL_AGGREGATIONS for its rewriting but compiles to a scalar —+ # it must not trip the aggregate check.+ metric = ExperimentMeanMetric(+ source=EventsNode(+ event="revenue_event",+ math=ExperimentMetricMathType.HOGQL,+ math_hogql="count(distinct md5(properties.user))",+ )+ )+ result = get_metric_value(metric)+ self.assertIsInstance(result, ast.Call)+ self.assertEqual(result.name, "md5") # type: ignore[attr-defined]++ def test_rejects_aggregates_in_data_warehouse_math_property(self):+ source = ExperimentDataWarehouseNode(+ table_name="payments",+ events_join_key="person_id",+ data_warehouse_join_key="user_id",+ timestamp_field="ts",+ math_property="sum(amount)",+ )+ with self.assertRaises(ValidationError):+ get_source_value_expr(source)++ @parameterized.expand(+ [+ ("plain_column", "amount"),+ ("scalar_md5", "md5(user_id)"),+ ]+ )+ def test_allows_per_row_data_warehouse_math_property(self, _name: str, math_property: str):+ source = ExperimentDataWarehouseNode(+ table_name="payments",+ events_join_key="person_id",+ data_warehouse_join_key="user_id",+ timestamp_field="ts",+ math_property=math_property,+ )+ get_source_value_expr(source)