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(trends): strip outer user alias from math=hogql expression (#60087)

Sam Penningtonda8118a2ffc9
diff --git a/posthog/hogql_queries/insights/trends/aggregation_operations.py b/posthog/hogql_queries/insights/trends/aggregation_operations.py
index 81378988d3ad..cdff40063e93 100644
--- a/posthog/hogql_queries/insights/trends/aggregation_operations.py
+++ b/posthog/hogql_queries/insights/trends/aggregation_operations.py
@@ -74,11 +74,19 @@ class AggregationOperations(DataWarehouseInsightQueryMixin):
def select_aggregation(self) -> ast.Expr:
if self.series.math == "hogql" and self.series.math_hogql is not None:
+ parsed = parse_expr(self.series.math_hogql)
+ # An outer alias on the user expression (`avg(x) as foo`) is shadowed by the
+ # `AS total` wrap added downstream. If we leave it in place, ClickHouse's
+ # new analyzer expands `ORDER BY total` into a copy of the SELECT expression
+ # with the inner alias stripped, producing two AST-different `AS total`
+ # projections and a MULTIPLE_EXPRESSIONS_FOR_ALIAS rejection.
+ if isinstance(parsed, ast.Alias):
+ parsed = parsed.expr
# Wrap in ifNull to handle empty result sets - formulas can't handle NULL values
return ast.Call(
name="ifNull",
args=[
- ast.Call(name="toFloat", args=[parse_expr(self.series.math_hogql)]),
+ ast.Call(name="toFloat", args=[parsed]),
ast.Constant(value=0),
],
)
diff --git a/posthog/hogql_queries/insights/trends/test/test_aggregation_operations.py b/posthog/hogql_queries/insights/trends/test/test_aggregation_operations.py
index 3c58d704d39c..aa0f199813fd 100644
--- a/posthog/hogql_queries/insights/trends/test/test_aggregation_operations.py
+++ b/posthog/hogql_queries/insights/trends/test/test_aggregation_operations.py
@@ -117,6 +117,38 @@ def test_requiring_query_orchestration(
assert res == result
+ "math_hogql",
+ [
+ "avg((properties.duration_seconds)/60) as avg_duration_mins",
+ "avg((properties.duration_seconds)/60) AS avg_duration_mins",
+ "sum(properties.amount) as total_amount",
+ ],
+)
+def test_hogql_math_strips_outer_user_alias(math_hogql: str):
+ """The user's outer alias on a `math=hogql` expression is shadowed by the downstream
+ `AS total` wrap. Leaving it in place causes ClickHouse's new analyzer to reject the
+ query with MULTIPLE_EXPRESSIONS_FOR_ALIAS (code 179) because `ORDER BY total` expands
+ into a copy of the SELECT expression with the inner alias stripped, producing two
+ AST-different `AS total` projections.
+ """
+ team = Team()
+ series = EventsNode(event="$pageview", math="hogql", math_hogql=math_hogql)
+ query_date_range = QueryDateRange(date_range=None, interval=None, now=datetime.now(), team=team)
+
+ agg_ops = AggregationOperations(team, series, ChartDisplayType.ACTIONS_LINE_GRAPH, query_date_range, False)
+ result = agg_ops.select_aggregation()
+
+ assert isinstance(result, ast.Call)
+ assert result.name == "ifNull"
+ to_float = result.args[0]
+ assert isinstance(to_float, ast.Call)
+ assert to_float.name == "toFloat"
+ # The expression inside toFloat must NOT be an Alias; the user's `as foo` is stripped.
+ assert not isinstance(to_float.args[0], ast.Alias)
+
+
@pytest.mark.django_db
def test_math_multiplier_with_sum():
team = Team()