: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(endpoints): read materialized columns by their stored names (#116554)
posthog[bot]1ea68b40f81d
diff --git a/products/endpoints/backend/logic/strategies.py b/products/endpoints/backend/logic/strategies.pyindex dffeddb87697..91f6bd14348c 100644--- a/products/endpoints/backend/logic/strategies.py+++ b/products/endpoints/backend/logic/strategies.py@@ -446,8 +446,11 @@ class HogQLEndpointStrategy(EndpointQueryStrategy):try:parsed = parse_select(query_str)if isinstance(parsed, ast.SelectQuery):+ output_names = [column["name"] for column in self.version.columns or []]columns = (- transform_select_for_materialized_table(list(parsed.select), self.team) if parsed.select else None+ transform_select_for_materialized_table(list(parsed.select), output_names)+ if parsed.select+ else None)limit = parsed.limit.value if isinstance(parsed.limit, ast.Constant) else Nonehas_group_by = bool(parsed.group_by)@@ -500,12 +503,12 @@ class HogQLEndpointStrategy(EndpointQueryStrategy):))else:- reagg_select.append(col.expr)+ reagg_select.append(col.labeled_expr)if not col.is_aggregate:group_by_columns.append(col.expr)select_columns = reagg_selectelse:- select_columns = [col.expr for col in original_select]+ select_columns = [col.labeled_expr for col in original_select]select_query = ast.SelectQuery(select=select_columns,diff --git a/products/endpoints/backend/materialization_transforms.py b/products/endpoints/backend/materialization_transforms.pyindex 7ada94700bcd..cc1eff5e6525 100644--- a/products/endpoints/backend/materialization_transforms.py+++ b/products/endpoints/backend/materialization_transforms.py@@ -1292,28 +1292,51 @@ class MaterializedColumn:name: str # the column name the endpoint declares, which a materialized read must keepreaggregate_fn: Optional[str] = None # e.g. "sum" for count/sum, "min" for min, etc.+ @property+ def labeled_expr(self) -> ast.Expr:+ if isinstance(self.expr, ast.Field) and self.expr.chain == [self.name]:+ return self.expr+ return ast.Alias(alias=self.name, expr=self.expr)+++def _declared_name(expr: ast.Expr) -> str:+ return expr.alias if isinstance(expr, ast.Alias) else expr.to_hogql()-def transform_select_for_materialized_table(select_exprs: list[ast.Expr], team: Team) -> list[MaterializedColumn]:++def transform_select_for_materialized_table(+ select_exprs: list[ast.Expr], output_names: list[str]+) -> list[MaterializedColumn]:"""Transform SELECT expressions to reference pre-computed columns in materialized table.+ `output_names` are the names the materialized table stores, in SELECT order. When their+ count does not match `select_exprs`, each column falls back to its alias or HogQL text.+Returns list of MaterializedColumn with re-aggregation metadata.- 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+ Examples, given the stored column each expression reads and the name it declares:+ - count() -> reads "count()", name "count()", is_aggregate=True, reaggregate_fn="sum"+ - count() as total -> reads "total", name "total", is_aggregate=True, reaggregate_fn="sum"+ - toStartOfDay(timestamp) as date -> reads "date", name "date", is_aggregate=False+ - toStartOfDay(timestamp) -> reads "toStartOfDay(toTimeZone(timestamp, 'UTC'))", name "toStartOfDay(timestamp)"+ - e.event -> reads "event", name "event", is_aggregate=False+ - properties.foo.bar -> reads "foo__bar", name "foo__bar", is_aggregate=False"""+ stored_names = (+ output_names if len(output_names) == len(select_exprs) else [_declared_name(expr) for expr in select_exprs]+ )result: list[MaterializedColumn] = []- for expr in select_exprs:+ for expr, stored_name in zip(select_exprs, stored_names):agg_name = _extract_aggregate_name(expr)is_agg = agg_name is not Nonereagg = get_reaggregation(agg_name) if agg_name else Nonereaggregate_fn = reagg.reaggregate_fn if reagg else None- 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+ expr=ast.Field(chain=[stored_name]),+ is_aggregate=is_agg,+ name=stored_name if isinstance(expr, ast.Field) else _declared_name(expr),+ reaggregate_fn=reaggregate_fn,))diff --git a/products/endpoints/backend/tests/test_variable_materialization.py b/products/endpoints/backend/tests/test_variable_materialization.pyindex 268af134fdac..aaca2434d1cd 100644--- a/products/endpoints/backend/tests/test_variable_materialization.py+++ b/products/endpoints/backend/tests/test_variable_materialization.py@@ -4,6 +4,8 @@ import pytestfrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_eventsfrom unittest import mock+from django.test import SimpleTestCase+from parameterized import parameterizedfrom posthog.schema import DataWarehouseNode, TrendsQuery@@ -16,6 +18,7 @@ from posthog.constants import AvailableFeaturefrom posthog.models import OrganizationMembershipfrom products.access_control.backend.models.access_control import AccessControl+from products.endpoints.backend.logic.strategies import strategy_forfrom products.endpoints.backend.materialization_transforms import (MaterializableVariable,MaterializationNotSupportedError,@@ -23,10 +26,10 @@ from products.endpoints.backend.materialization_transforms import (build_endpoint_hogql,transform_query_for_materialization,)+from products.endpoints.backend.models import EndpointVersion+from products.endpoints.backend.tests.conftest import create_endpoint_with_versionfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable-pytestmark = [pytest.mark.django_db]-class TestVariableAnalysis(APIBaseTest):"""Test variable analysis for materialization eligibility."""@@ -1441,7 +1444,7 @@ class TestQueryTransformation(APIBaseTest):assert "event_name" in group_by_part-class TestMaterializedQueryExecution(APIBaseTest):+class TestMaterializedQueryExecution(SimpleTestCase):"""Test that materialized queries handle pre-aggregated data correctly."""def test_materialized_query_selects_precomputed_columns(self):@@ -1482,7 +1485,7 @@ class TestMaterializedQueryExecution(APIBaseTest):parsed = parse_select(query_str)assert isinstance(parsed, ast.SelectQuery)- transformed = transform_select_for_materialized_table(parsed.select, self.team)+ transformed = transform_select_for_materialized_table(parsed.select, [])assert len(transformed) == 2@@ -1504,7 +1507,7 @@ class TestMaterializedQueryExecution(APIBaseTest):parsed = parse_select(query_str)assert isinstance(parsed, ast.SelectQuery)- transformed = transform_select_for_materialized_table(parsed.select, self.team)+ transformed = transform_select_for_materialized_table(parsed.select, [])assert len(transformed) == 1@@ -2171,6 +2174,54 @@ class TestMaterializationEquivalence(ClickhouseTestMixin, APIBaseTest):{"event_name": "$pageview"},)+ @parameterized.expand(+ [+ (+ "qualified_field",+ "SELECT e.event FROM events AS e WHERE distinct_id = {variables.user_id}",+ True,+ ["event"],+ ),+ (+ "nested_properties",+ "SELECT properties.foo.bar, properties.bar FROM events WHERE distinct_id = {variables.user_id}",+ True,+ ["foo__bar", "bar"],+ ),+ (+ "unaliased_calls",+ "SELECT toStartOfDay(timestamp), count() FROM events WHERE distinct_id = {variables.user_id} "+ "GROUP BY toStartOfDay(timestamp)",+ True,+ ["`toStartOfDay(toTimeZone(timestamp, 'UTC'))` AS `toStartOfDay(timestamp)`", "`count()`"],+ ),+ (+ "columns_not_computed",+ "SELECT e.event FROM events AS e WHERE distinct_id = {variables.user_id}",+ False,+ ["`e.event`"],+ ),+ ]+ )+ def test_materialized_read_selects_stored_columns_under_declared_names(+ self, name, query_str, columns_computed, expected_select+ ):+ query = {+ "kind": "HogQLQuery",+ "query": query_str,+ "variables": {"var-1": {"code_name": "user_id", "value": "user_0"}},+ }+ endpoint = create_endpoint_with_version(name=name, team=self.team, query=query, created_by=self.user)+ version = endpoint.versions.get()+ if columns_computed:+ version.columns = EndpointVersion.extract_columns(query, self.team.pk)+ version.save()++ select_query, _ = strategy_for(endpoint, version, self.team).build_materialized_select(table_name="mat")++ assert [expr.to_hogql() for expr in select_query.select] == expected_select+ assert (version.columns is not None) == columns_computed+@pytest.mark.usefixtures("unittest_snapshot")class TestDownstreamTransformSnapshots(APIBaseTest):