: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 OR/multi-column variables before materializing (#64840)
Jovan Sakovic7b4082791037
diff --git a/products/endpoints/backend/materialization_transforms.py b/products/endpoints/backend/materialization_transforms.pyindex 35cf5cfbfdf4..67889f34944b 100644--- a/products/endpoints/backend/materialization_transforms.py+++ b/products/endpoints/backend/materialization_transforms.py@@ -23,7 +23,15 @@ from posthog.models.team import TeamENDPOINT_BREAKDOWN_LIMIT = 10_000-class VariableInHavingClauseError(ValueError):+class MaterializationNotSupportedError(ValueError):+ """Raised when a query uses a construct materialization can't transform.++ This is a user-input limitation (a 400), not a server fault — callers should surface+ it as a validation error rather than letting it bubble up as an unhandled exception.+ """+++class VariableInHavingClauseError(MaterializationNotSupportedError):"""Raised when a variable is used in a HAVING clause, which is not supported for materialization."""@@ -124,6 +132,7 @@ class VariableUsageInWhere:operator: ast.CompareOperationOpcolumn_ast: Optional[ast.Expr] = Nonevalue_wrapper_fns: Optional[list[str]] = None+ in_or: bool = False # True when this usage sits inside an OR within the WHERE clauseRANGE_OPS = frozenset(@@ -276,6 +285,19 @@ def analyze_variables_for_materialization(if not all_usages:return False, "Variable not used in WHERE clause", []+ # A variable nested in an OR can't be lifted into a single materialized key column:+ # removing its predicate (as the transform does) would change the result set.+ if any(usage.in_or for _, usage in all_usages):+ return False, "Variables in OR conditions are not supported for materialization", []++ # A variable compared against more than one column has no single bucket key to+ # materialize on (the transform would silently keep only the first usage).+ distinct_columns = {+ tuple(usage.column_chain) if usage.column_chain else usage.column_expression for _, usage in all_usages+ }+ if len(distinct_columns) > 1:+ return False, "Variable compared against multiple columns is not supported for materialization", []+# Determine CTE context for this variablecte_names = {cte_name for cte_name, _ in all_usages}if len(cte_names) > 1:@@ -868,6 +890,7 @@ class VariableInWhereFinder(TraversingVisitor):self.target = target_placeholderself.all_results: list[tuple[Optional[str], VariableUsageInWhere]] = []self.in_where = False+ self._or_depth = 0self._current_cte_name: Optional[str] = None@property@@ -891,9 +914,20 @@ class VariableInWhereFinder(TraversingVisitor):self._current_cte_name = prev_cteif node.where:- self.in_where = True+ prev_in_where, prev_or_depth = self.in_where, self._or_depth+ self.in_where, self._or_depth = True, 0self.visit(node.where)- self.in_where = False+ self.in_where, self._or_depth = prev_in_where, prev_or_depth++ def visit_or(self, node: ast.Or):+ # Only OR nesting within a WHERE clause matters for materialization.+ track = self.in_where+ if track:+ self._or_depth += 1+ for expr in node.exprs:+ self.visit(expr)+ if track:+ self._or_depth -= 1def visit_compare_operation(self, node: ast.CompareOperation):if not self.in_where:@@ -923,6 +957,7 @@ class VariableInWhereFinder(TraversingVisitor):column_expression=".".join(column_chain),operator=node.op,value_wrapper_fns=wrapper_fns,+ in_or=self._or_depth > 0,),))@@ -937,6 +972,7 @@ class VariableInWhereFinder(TraversingVisitor):operator=node.op,column_ast=field_side if not column_chain else None,value_wrapper_fns=wrapper_fns,+ in_or=self._or_depth > 0,),))@@ -1400,7 +1436,7 @@ class MaterializationTransformer(CloningVisitor):return ast.And(exprs=filtered_exprs)if isinstance(where_node, ast.Or):- raise ValueError("Variables in OR conditions not supported")+ raise MaterializationNotSupportedError("Variables in OR conditions not supported")return where_nodediff --git a/products/endpoints/backend/services/materialization.py b/products/endpoints/backend/services/materialization.pyindex 81c388cb7236..8fca19063f87 100644--- a/products/endpoints/backend/services/materialization.py+++ b/products/endpoints/backend/services/materialization.py@@ -30,6 +30,7 @@ from products.data_modeling.backend.models.datawarehouse_saved_query import Datafrom products.data_modeling.backend.services.saved_query_dag_sync import delete_node_from_dag, sync_saved_query_to_dagfrom products.endpoints.backend.constants import DATA_FRESHNESS_BUCKETSfrom products.endpoints.backend.materialization_transforms import (+ MaterializationNotSupportedError,_extract_aggregate_name,analyze_variables_for_materialization,build_endpoint_hogql,@@ -149,8 +150,9 @@ class EndpointMaterializationService:except ValidationError:ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="enable", status="validation_error").inc()raise- except ExposedHogQLError as e:- # A bad user query, not a system fault — surface as a 400.+ except (ExposedHogQLError, MaterializationNotSupportedError) as e:+ # A bad user query, not a system fault — surface as a 400. Pre-flight validation+ # (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:diff --git a/products/endpoints/backend/tests/test_variable_materialization.py b/products/endpoints/backend/tests/test_variable_materialization.pyindex d528a6425b0e..b8de3e322bb6 100644--- a/products/endpoints/backend/tests/test_variable_materialization.py+++ b/products/endpoints/backend/tests/test_variable_materialization.py@@ -10,6 +10,8 @@ from posthog.hogql.parser import parse_selectfrom products.endpoints.backend.materialization_transforms import (DownstreamCTEShape,+ MaterializableVariable,+ MaterializationNotSupportedError,_build_cte_read_graph,_classify_downstream_cte,_downstream_ctes,@@ -227,18 +229,59 @@ class TestVariableAnalysis(APIBaseTest):assert len(var_infos) == 1assert var_infos[0].column_chain == ["event"]- def test_variable_in_or_condition_blocked(self):- query = {- "kind": "HogQLQuery",- "query": "SELECT count() FROM events WHERE event = {variables.event_name} OR event = '$pageview'",- "variables": {"var-1": {"code_name": "event_name", "value": "$identify"}},- }+ @parameterized.expand(+ [+ # Variable inside an OR can't be lifted into a single materialized key column.+ (+ "or_condition",+ "SELECT count() FROM events WHERE event = {variables.event_name} OR event = '$pageview'",+ {"var-1": {"code_name": "event_name", "value": "$identify"}},+ False,+ "OR conditions",+ 0,+ ),+ # Reproduction of a real failure: same variable across two OR branches, two+ # different columns, one branch using ILIKE.+ (+ "or_with_multiple_columns",+ "SELECT count() FROM events\n"+ "WHERE (event = '$pageview' AND properties.$current_url ILIKE CONCAT('%/refer?p_ref=', {variables.playeruuid}, '%'))\n"+ " OR (event = 'referral-impression' AND properties.referrer_uuid = {variables.playeruuid})",+ {"var-1": {"code_name": "playeruuid", "value": "191e674e"}},+ False,+ "OR conditions",+ 0,+ ),+ # Same variable, two AND'd branches, but two different columns — no single bucket key.+ (+ "multiple_columns",+ "SELECT count() FROM events WHERE properties.a = {variables.v} AND properties.b = {variables.v}",+ {"var-1": {"code_name": "v", "value": "x"}},+ False,+ "multiple columns",+ 0,+ ),+ # An OR that doesn't contain the variable must not trip the OR guard.+ (+ "or_without_variable_allowed",+ "SELECT count() FROM events WHERE event = {variables.event_name} AND (properties.a = '1' OR properties.b = '2')",+ {"var-1": {"code_name": "event_name", "value": "$pageview"}},+ True,+ "OK",+ 1,+ ),+ ]+ )+ def test_or_and_multi_column_variable_analysis(+ self, _name, query_str, variables, expected_can_materialize, expected_reason, expected_var_count+ ):+ query = {"kind": "HogQLQuery", "query": query_str, "variables": variables}can_materialize, reason, var_infos = analyze_variables_for_materialization(query)- if can_materialize and var_infos:- with pytest.raises(ValueError, match="OR conditions not supported"):- transform_query_for_materialization(query, var_infos, self.team)+ assert can_materialize is expected_can_materialize+ assert expected_reason in reason+ assert len(var_infos) == expected_var_countdef test_variable_with_parentheses(self):query = {@@ -1229,10 +1272,18 @@ class TestQueryTransformation(APIBaseTest):},}- _, _, var_infos = analyze_variables_for_materialization(query)- assert len(var_infos) >= 1+ # Analysis now rejects OR up-front, so feed the transform a hand-built var_info to+ # confirm the transform itself still guards against OR as a backstop.+ var_infos = [+ MaterializableVariable(+ variable_id="var-123",+ code_name="event_name",+ column_chain=["event"],+ column_expression="event",+ )+ ]- with pytest.raises(ValueError, match="OR conditions not supported"):+ with pytest.raises(MaterializationNotSupportedError, match="OR conditions not supported"):transform_query_for_materialization(query, var_infos, self.team)def test_transform_preserves_specific_columns_in_select(self):@@ -1831,9 +1882,9 @@ class TestCTEVariableAnalysis(APIBaseTest):can_materialize, reason, var_infos = analyze_variables_for_materialization(query)- if can_materialize and var_infos:- with pytest.raises(ValueError, match="OR conditions not supported"):- transform_query_for_materialization(query, var_infos, self.team)+ assert can_materialize is False+ assert "OR conditions" in reason+ assert var_infos == []def test_two_ctes_one_variable_each_different_vars_allowed(self):query = {