: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): reject unmaterializable variable/alias conflicts pre-flight (#65741)
Jovan Sakovica58496e9d5aa
diff --git a/products/endpoints/backend/materialization_transforms.py b/products/endpoints/backend/materialization_transforms.pyindex 67889f34944b..621e99ac0414 100644--- a/products/endpoints/backend/materialization_transforms.py+++ b/products/endpoints/backend/materialization_transforms.py@@ -408,9 +408,86 @@ def analyze_variables_for_materialization(plans[d_cte_name] = planvar.downstream_plans = plans+ # A variable whose code_name collides with a SELECT alias for a different expression+ # can't be materialized (the table would need two columns of that name). This is the one+ # limitation only the transform could detect, so reject it here — sharing the check with+ # the transformer — instead of letting enable_materialization fail mid-transform.+ conflict_reason = _find_alias_conflict(ast_node, result_vars)+ if conflict_reason is not None:+ return False, conflict_reason, []+return True, "OK", result_vars+def _alias_conflict_reason(code_name: str) -> str:+ """Single source of truth for the variable/alias-conflict message, so the analyzer's+ rejection reason and the transformer's exception always read identically."""+ return (+ f"Variable '{code_name}' conflicts with an existing SELECT alias for a different expression. "+ f"Rename the variable or the conflicting column alias."+ )+++def _variable_column_expr(var: MaterializableVariable) -> ast.Expr:+ """Expression a variable contributes to SELECT/GROUP BY, without aliasing.++ Uses the original AST expression when available (e.g. function calls like+ toDate(timestamp) that can't be reconstructed from column_chain). Always returns a fresh+ copy so SELECT and GROUP BY don't share nodes. Wraps with bucket_fn when set.+ """+ if var.column_ast is not None:+ base = CloningVisitor().visit(var.column_ast)+ else:+ base = ast.Field(chain=list(var.column_chain))++ if var.bucket_fn:+ return ast.Call(name=var.bucket_fn, args=[base])++ return base+++def _select_alias_conflict(select: ast.SelectQuery, vars_in_context: list[MaterializableVariable]) -> Optional[str]:+ """code_name of the first variable colliding with a SELECT alias bound to a *different*+ expression, or None. Shared by the analyzer (pre-flight reject) and the transformer+ (enable-time backstop) so both agree on what's unmaterializable."""+ existing_aliases = {+ alias.alias: alias.expr.to_hogql() for alias in select.select or [] if isinstance(alias, ast.Alias)+ }+ for var in vars_in_context:+ existing = existing_aliases.get(var.code_name)+ if existing is not None and existing != _variable_column_expr(var).to_hogql():+ return var.code_name+ return None+++def _context_select(+ ast_node: ast.SelectQuery | ast.SelectSetQuery, cte_name: Optional[str]+) -> Optional[ast.SelectQuery]:+ """The SELECT a variable's columns get added to — the CTE body for CTE-bound variables,+ else the top-level query — mirroring the contexts the transformer visits."""+ if cte_name is None:+ return ast_node if isinstance(ast_node, ast.SelectQuery) else None+ if isinstance(ast_node, ast.SelectQuery) and ast_node.ctes and cte_name in ast_node.ctes:+ body = ast_node.ctes[cte_name].expr+ return body if isinstance(body, ast.SelectQuery) else None+ return None+++def _find_alias_conflict(+ ast_node: ast.SelectQuery | ast.SelectSetQuery, result_vars: list[MaterializableVariable]+) -> Optional[str]:+ """Pre-flight equivalent of the transformer's per-context alias-conflict check: group+ variables by their context and run the shared conflict check on each."""+ contexts: dict[Optional[str], list[MaterializableVariable]] = {}+ for var in result_vars:+ contexts.setdefault(var.cte_name, []).append(var)+ for cte_name, vars_in_context in contexts.items():+ select = _context_select(ast_node, cte_name)+ if select is not None and (conflict := _select_alias_conflict(select, vars_in_context)) is not None:+ return _alias_conflict_reason(conflict)+ return None++def _has_joins(node: ast.SelectQuery) -> bool:"""Check if a SelectQuery has any JOINs (next_join on select_from)."""return node.select_from is not None and node.select_from.next_join is not None@@ -1298,20 +1375,16 @@ class MaterializationTransformer(CloningVisitor):def _add_variable_columns(self, node: ast.SelectQuery, vars_for_context: list[MaterializableVariable]) -> None:"""Add aliased variable columns to SELECT, update GROUP BY, and remove variable WHERE clauses."""- existing_aliases: dict[str, str] = {- expr.alias: expr.expr.to_hogql() for expr in node.select or [] if isinstance(expr, ast.Alias)- }- vars_to_add: list[MaterializableVariable] = []- for var in vars_for_context:- existing_expr = existing_aliases.get(var.code_name)- if existing_expr is not None:- if existing_expr == self._variable_expr(var).to_hogql():- # SELECT already exposes this column under the variable's name- continue- raise ValueError(- f"Variable '{var.code_name}' conflicts with an existing SELECT alias for a different expression"- )- vars_to_add.append(var)+ # Backstop: pre-flight analysis normally rejects this first (analyze_variables_for_materialization),+ # so reaching here means a pre-flight gap. Surfaced as a 400, not a server fault.+ conflict = _select_alias_conflict(node, vars_for_context)+ if conflict is not None:+ raise MaterializationNotSupportedError(_alias_conflict_reason(conflict))++ # A code_name already aliased here is — after the conflict check — the same expression+ # already exposed under that name, so skip it; add the rest.+ existing_alias_names = {expr.alias for expr in node.select or [] if isinstance(expr, ast.Alias)}+ vars_to_add = [var for var in vars_for_context if var.code_name not in existing_alias_names]select_additions = [self._create_column_field(var) for var in vars_to_add]if select_additions:@@ -1384,7 +1457,7 @@ class MaterializationTransformer(CloningVisitor):if use_field_ref:group_by_additions.append(ast.Field(chain=[var.code_name]))else:- group_by_additions.append(self._variable_expr(var))+ group_by_additions.append(_variable_column_expr(var))if node.group_by:node.group_by = [*list(node.group_by), *group_by_additions]@@ -1394,28 +1467,9 @@ class MaterializationTransformer(CloningVisitor):def _create_column_field(self, var: MaterializableVariable) -> ast.Expr:return ast.Alias(alias=var.code_name,- expr=self._variable_expr(var),+ expr=_variable_column_expr(var),)- @staticmethod- def _variable_expr(var: MaterializableVariable) -> ast.Expr:- """Expression used for the variable column without aliasing.-- Uses the original AST expression when available (e.g. for function calls- like toDate(timestamp) that can't be reconstructed from column_chain).- Always returns a fresh copy to avoid sharing AST nodes between SELECT and GROUP BY.- When bucket_fn is set, wraps the column expression with the bucket function.- """- if var.column_ast is not None:- base = CloningVisitor().visit(var.column_ast)- else:- base = ast.Field(chain=list(var.column_chain))-- if var.bucket_fn:- return ast.Call(name=var.bucket_fn, args=[base])-- return base-def _remove_variable_from_where(self, where_node: Optional[ast.Expr]) -> Optional[ast.Expr]:if where_node is None:return Nonediff --git a/products/endpoints/backend/services/materialization.py b/products/endpoints/backend/services/materialization.pyindex 8fca19063f87..07cc5813019f 100644--- a/products/endpoints/backend/services/materialization.py+++ b/products/endpoints/backend/services/materialization.py@@ -155,8 +155,24 @@ class EndpointMaterializationService:# (can_materialize) normally catches these, so reaching here is a backstop.ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="enable", status="validation_error").inc()raise ValidationError(f"Cannot materialize endpoint. Reason: {e}")- except Exception:+ except Exception as e:ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="enable", status="error").inc()+ # Genuine system fault (user-query limitations are handled above). Log + capture so+ # status="error" — which the alert fires on — is never a blind spot.+ logger.exception(+ "Failed to enable endpoint materialization",+ endpoint_name=endpoint.name,+ version=version.version,+ team_id=self.team.pk,+ )+ capture_exception(+ e,+ {+ "product": Product.ENDPOINTS,+ "team_id": self.team.pk,+ "endpoint_name": endpoint.name,+ },+ )# Not a request-validation problem — surface as a server error, not a 400.raise APIException("Failed to enable materialization.")diff --git a/products/endpoints/backend/tests/test_variable_materialization.py b/products/endpoints/backend/tests/test_variable_materialization.pyindex b8de3e322bb6..d3e2b78bf2ba 100644--- a/products/endpoints/backend/tests/test_variable_materialization.py+++ b/products/endpoints/backend/tests/test_variable_materialization.py@@ -1058,7 +1058,11 @@ class TestQueryTransformation(APIBaseTest):assert "{variables" not in transformed_queryassert transformed_query.count("AS profile_id") == 1- def test_transform_variable_alias_collision_with_different_expression(self):+ def test_alias_collision_with_different_expression_rejected_preflight(self):+ # A variable code_name colliding with a SELECT alias for a *different* expression+ # can't be materialized (the table would need two columns named profile_id).+ # Pre-flight must reject it so enabling is never attempted — otherwise the transform+ # fails at enable time with a generic server error.query = {"kind": "HogQLQuery","query": (@@ -1072,9 +1076,38 @@ class TestQueryTransformation(APIBaseTest):},}- _, _, var_infos = analyze_variables_for_materialization(query)+ can_materialize, reason, var_infos = analyze_variables_for_materialization(query)++ assert can_materialize is False+ assert "conflicts with an existing SELECT alias" in reason+ assert var_infos == []++ def test_transform_alias_collision_raises_not_supported(self):+ # Backstop: if the transform is reached directly (bypassing pre-flight) on a colliding+ # query, it raises MaterializationNotSupportedError (a 400), not a bare ValueError (a 500).+ query = {+ "kind": "HogQLQuery",+ "query": (+ "SELECT properties.card_id AS profile_id, count() AS tap_count "+ "FROM events "+ "WHERE properties.profile_id = {variables.profile_id} "+ "GROUP BY profile_id"+ ),+ "variables": {+ "var-1": {"variableId": "var-1", "code_name": "profile_id", "value": ""},+ },+ }++ var_infos = [+ MaterializableVariable(+ variable_id="var-1",+ code_name="profile_id",+ column_chain=["properties", "profile_id"],+ column_expression="properties.profile_id",+ )+ ]- with pytest.raises(ValueError, match="conflicts with an existing SELECT alias"):+ with pytest.raises(MaterializationNotSupportedError, match="conflicts with an existing SELECT alias"):transform_query_for_materialization(query, var_infos, self.team)def test_transform_preserves_order_by(self):