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(endpoints): keep declared column names on materialized reads (#100765)

posthog[bot]3f7e323ec5bd
diff --git a/products/endpoints/backend/logic/strategies.py b/products/endpoints/backend/logic/strategies.py
index 493ff308e66e..a898919b16bd 100644
--- a/products/endpoints/backend/logic/strategies.py
+++ b/products/endpoints/backend/logic/strategies.py
@@ -462,8 +462,10 @@ class HogQLEndpointStrategy(EndpointQueryStrategy):
) -> tuple[ast.SelectQuery, int | None]:
"""Build the base SELECT query against a materialized table.
- Wraps aggregate columns with their reaggregate_fn (e.g. sum("count()"))
- when needed to preserve SQL semantics. This happens in two cases:
+ Wraps aggregate columns with their reaggregate_fn and aliases the result back
+ to the declared column name (e.g. sum("impressions") AS "impressions"), so a
+ materialized read returns the same keys as an inline read. This happens in two
+ cases:
1. Range variables (bucket_fn != None): multiple materialized rows must
be collapsed back into one aggregate per group.
@@ -489,7 +491,12 @@ class HogQLEndpointStrategy(EndpointQueryStrategy):
reagg_select: list[ast.Expr] = []
for col in original_select:
if col.is_aggregate and col.reaggregate_fn:
- reagg_select.append(ast.Call(name=col.reaggregate_fn, args=[col.expr]))
+ reagg_select.append(
+ ast.Alias(
+ alias=col.name,
+ expr=ast.Call(name=col.reaggregate_fn, args=[col.expr]),
+ )
+ )
else:
reagg_select.append(col.expr)
if not col.is_aggregate:
diff --git a/products/endpoints/backend/materialization_transforms.py b/products/endpoints/backend/materialization_transforms.py
index 512ef648649c..7ada94700bcd 100644
--- a/products/endpoints/backend/materialization_transforms.py
+++ b/products/endpoints/backend/materialization_transforms.py
@@ -1283,12 +1283,13 @@ def _extract_aggregate_name(expr: ast.Expr) -> Optional[str]:
return None
-@dataclass
+@frozen
class MaterializedColumn:
"""A column in the materialized table with metadata for read-time re-aggregation."""
expr: ast.Expr
is_aggregate: bool
+ name: str # the column name the endpoint declares, which a materialized read must keep
reaggregate_fn: Optional[str] = None # e.g. "sum" for count/sum, "min" for min, etc.
@@ -1298,10 +1299,10 @@ def transform_select_for_materialized_table(select_exprs: list[ast.Expr], team:
Returns list of MaterializedColumn with re-aggregation metadata.
- Examples:
- - count() -> MaterializedColumn(Field(chain=["count()"]), is_aggregate=True, reaggregate_fn="sum")
- - count() as total -> MaterializedColumn(Field(chain=["total"]), is_aggregate=True, reaggregate_fn="sum")
- - toStartOfDay(timestamp) as date -> MaterializedColumn(Field(chain=["date"]), is_aggregate=False)
+ Examples, given the name each expression contributes to the materialized table:
+ - count() -> name "count()", is_aggregate=True, reaggregate_fn="sum"
+ - count() as total -> name "total", is_aggregate=True, reaggregate_fn="sum"
+ - toStartOfDay(timestamp) as date -> name "date", is_aggregate=False
"""
result: list[MaterializedColumn] = []
for expr in select_exprs:
@@ -1309,11 +1310,12 @@ def transform_select_for_materialized_table(select_exprs: list[ast.Expr], team:
is_agg = agg_name is not None
reagg = get_reaggregation(agg_name) if agg_name else None
reaggregate_fn = reagg.reaggregate_fn if reagg else None
- if isinstance(expr, ast.Alias):
- field = ast.Field(chain=[expr.alias])
- else:
- field = ast.Field(chain=[expr.to_hogql()])
- result.append(MaterializedColumn(expr=field, is_aggregate=is_agg, reaggregate_fn=reaggregate_fn))
+ name = expr.alias if isinstance(expr, ast.Alias) else expr.to_hogql()
+ result.append(
+ MaterializedColumn(
+ expr=ast.Field(chain=[name]), is_aggregate=is_agg, name=name, reaggregate_fn=reaggregate_fn
+ )
+ )
return result
diff --git a/products/endpoints/backend/tests/test_endpoint_execution.py b/products/endpoints/backend/tests/test_endpoint_execution.py
index 7bd3c765ffaf..a572ba00060c 100644
--- a/products/endpoints/backend/tests/test_endpoint_execution.py
+++ b/products/endpoints/backend/tests/test_endpoint_execution.py
@@ -913,8 +913,15 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
self.assertIn("greaterorequals", query_sql)
self.assertIn("less(", query_sql)
- def test_materialized_count_with_range_variables_reaggregates(self):
- """When range variables exist, read-time SQL should re-aggregate with sum()."""
+ @parameterized.expand(
+ [
+ ("bare_aggregate", "count()", "sum(`count()`) AS `count()`"),
+ ("aliased_aggregate", "count() AS impressions", "sum(impressions) AS impressions"),
+ ]
+ )
+ def test_materialized_count_with_range_variables_reaggregates(self, _name, select_expr, expected_select):
+ """When range variables exist, read-time SQL should re-aggregate with sum()
+ and keep the column name the endpoint declares."""
start_var = InsightVariable.objects.create(
team=self.team,
name="Start Timestamp",
@@ -942,7 +949,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
team=self.team,
query={
"kind": "HogQLQuery",
- "query": "SELECT count() FROM events WHERE timestamp >= {variables.start_ts} AND timestamp < {variables.end_ts} AND properties.$host = {variables.host}",
+ "query": f"SELECT {select_expr} FROM events WHERE timestamp >= {{variables.start_ts}} AND timestamp < {{variables.end_ts}} AND properties.$host = {{variables.host}}",
"variables": {
str(start_var.id): {
"variableId": str(start_var.id),
@@ -977,11 +984,12 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
mock_exec.assert_called()
- query_sql = mock_exec.call_args[0][0]["query"]["query"].lower()
- # Re-aggregation: count() column should be wrapped with sum()
- self.assertIn("sum(", query_sql)
+ query_sql = mock_exec.call_args[0][0]["query"]["query"]
+ # Re-aggregation wraps the column with sum(), then aliases it back to the name
+ # the endpoint declares, so a typed client can still parse the rows.
+ self.assertIn(expected_select, query_sql)
# Range variable values should be wrapped with toStartOfDay
- self.assertIn("tostartofday", query_sql)
+ self.assertIn("tostartofday", query_sql.lower())
# =========================================================================
# MATERIALIZED INSIGHT ENDPOINTS