: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
feat(endpoints): respect optional breakdown variables on materialized endpoints (#68214)
Jovan Sakovic4039df026ed9
diff --git a/products/endpoints/backend/logic/strategies.py b/products/endpoints/backend/logic/strategies.pyindex 3272a7879a04..d71842f34505 100644--- a/products/endpoints/backend/logic/strategies.py+++ b/products/endpoints/backend/logic/strategies.py@@ -325,7 +325,10 @@ class EndpointQueryStrategy(abc.ABC):"""Variables that MUST be provided when running against the materialized table.SECURITY: materialized tables contain rows for every variable value; omitting- a variable would return unfiltered data.+ a variable would return unfiltered data. Endpoint owners can opt individual+ breakdown properties out via ``EndpointVersion.optional_breakdown_properties``;+ omitting an optional breakdown returns data aggregated across all values of+ that dimension."""@abc.abstractmethod@@ -611,8 +614,11 @@ class InsightEndpointStrategy(EndpointQueryStrategy):return alloweddef required_materialized_variables(self) -> set[str]:+ # Breakdown properties are required unless explicitly marked optional.if self.query_kind in self.BREAKDOWN_SUPPORTED_QUERY_TYPES:- return set(get_breakdown_properties(self._breakdown_filter))+ all_breakdowns = set(get_breakdown_properties(self._breakdown_filter))+ optional = set(self.version.optional_breakdown_properties or [])+ return all_breakdowns - optionalreturn set()def can_serve_variables_from_materialized(self, requested: set[str]) -> bool:@@ -622,10 +628,12 @@ class InsightEndpointStrategy(EndpointQueryStrategy):return requested.issubset(allowed_props)def materialized_filters_override_satisfies_required(self, data: EndpointRunRequest) -> bool:- # apply_materialized_filters applies only the first property's value as a single breakdown- # filter, so filters_override can only satisfy a single-breakdown endpoint. A multi-breakdown- # endpoint would leave the other breakdowns unfiltered — require variables (one per breakdown).- if len(self.required_materialized_variables()) != 1:+ # apply_materialized_filters applies only the first property's value as a single positionless+ # breakdown filter, so filters_override can only satisfy an endpoint with exactly ONE breakdown+ # overall. Gate on the total breakdown count, not the required count: with optional breakdowns+ # subtracted, a multi-breakdown endpoint can have one required variable left, but a single+ # has(breakdown_value, ...) predicate would leave the required dimension unconstrained.+ if len(get_breakdown_properties(self._breakdown_filter)) != 1:return Falsefo = data.filters_overrideif not (fo and fo.properties):diff --git a/products/endpoints/backend/tests/test_endpoint_materialization.py b/products/endpoints/backend/tests/test_endpoint_materialization.pyindex 9cae326eb7e2..46ba77ca5238 100644--- a/products/endpoints/backend/tests/test_endpoint_materialization.py+++ b/products/endpoints/backend/tests/test_endpoint_materialization.py@@ -1216,6 +1216,28 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())self.assertIn("Required variable", str(response.json()))+ def test_materialized_multi_breakdown_one_optional_filters_override_does_not_bypass_required(self):+ # SECURITY: with one of two breakdowns optional, exactly one REQUIRED variable remains — but+ # filters_override still applies a single positionless filter, so it must not satisfy the+ # required check on a multi-breakdown endpoint (the required dimension would go unconstrained).+ endpoint = self._create_materialized_trends_endpoint(+ name="trends_multi_optional_fo",+ breakdowns=[+ {"property": "$os", "type": "event"},+ {"property": "$browser", "type": "event"},+ ],+ optional=["$browser"],+ )++ with mock.patch.object(EndpointExecutionService, "_execute_query_and_respond", return_value=Response({})):+ response = self.client.post(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run",+ {"filters_override": {"properties": [{"key": "$os", "type": "event", "value": "Mac OS X"}]}},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())+ self.assertIn("Required variable", str(response.json()))+def test_materialized_hogql_endpoint_with_variable_executes_correctly(self):"""Test that HogQL endpoints with variables work when materialized.@@ -1645,6 +1667,168 @@ class TestEndpointMaterialization(ClickhouseTestMixin, APIBaseTest):"EndpointVersion must be linked to the saved query before materialization is scheduled",)+ def _create_materialized_trends_endpoint(self, name: str, breakdowns: list[dict], optional: list[str]):+ """Shared helper for the optional-breakdown tests. Stands up a materialized TrendsQuery+ endpoint whose saved_query is in COMPLETED status with a backing DataWarehouseTable —+ the same minimal setup `test_materialized_insight_endpoint_with_breakdown_executes_correctly`+ uses to drive the materialized read path."""+ trends_query = {+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode", "event": "$pageview", "math": "total"}],+ "dateRange": {"date_from": "-7d"},+ "interval": "day",+ "breakdownFilter": {"breakdowns": breakdowns, "breakdown_limit": 5},+ }++ _create_event(team=self.team, event="$pageview", distinct_id="user1")+ flush_persons_and_events()++ endpoint = create_endpoint_with_version(+ name=name,+ team=self.team,+ query=trends_query,+ created_by=self.user,+ is_active=True,+ )+ # Persist the optional list on the live version.+ version = endpoint.versions.first()+ version.optional_breakdown_properties = optional+ version.save(update_fields=["optional_breakdown_properties"])++ response = self.client.patch(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",+ {"is_materialized": True, "data_freshness_seconds": 43200},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())++ version.refresh_from_db()+ saved_query = version.saved_query+ assert saved_query is not None+ saved_query.status = DataWarehouseSavedQuery.Status.COMPLETED+ saved_query.last_run_at = timezone.now()+ saved_query.table = DataWarehouseTable.objects.create(+ team=self.team,+ name=name,+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern=f"s3://test-bucket/{name}",+ )+ saved_query.save()+ return endpoint++ def test_optional_breakdown_materialized_allows_missing_variable(self):+ """Materialized endpoint with $browser marked optional should accept /run with no variables — and+ the resulting HogQL should NOT include a $browser WHERE filter (aggregate across all values)."""+ endpoint = self._create_materialized_trends_endpoint(+ name="trends_browser_optional",+ breakdowns=[{"property": "$browser", "type": "event"}],+ optional=["$browser"],+ )++ with mock.patch.object(+ EndpointExecutionService, "_execute_query_and_respond", return_value=Response({})+ ) as mock_exec:+ response = self.client.post(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run",+ {},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ mock_exec.assert_called()+ query_payload = mock_exec.call_args[0][0]["query"]+ self.assertEqual(query_payload["kind"], "HogQLQuery")+ # No breakdown_value WHERE filter when the dimension is optional and absent.+ self.assertNotIn("has(breakdown_value", query_payload["query"].lower())++ def test_optional_breakdown_materialized_still_allows_explicit_value(self):+ """Even though $browser is optional, callers can still pass it and get a filtered result."""+ endpoint = self._create_materialized_trends_endpoint(+ name="trends_browser_opt_explicit",+ breakdowns=[{"property": "$browser", "type": "event"}],+ optional=["$browser"],+ )++ with mock.patch.object(+ EndpointExecutionService, "_execute_query_and_respond", return_value=Response({})+ ) as mock_exec:+ response = self.client.post(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run",+ {"variables": {"$browser": "Chrome"}},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ mock_exec.assert_called()+ query_sql = mock_exec.call_args[0][0]["query"]["query"].lower()+ self.assertIn("has(breakdown_value", query_sql)+ self.assertIn("chrome", query_sql)++ def test_required_breakdown_still_400s_when_missing(self):+ """Without the flag, behavior is unchanged — missing breakdown var on a materialized endpoint+ is still rejected. This is the regression check on the security wall."""+ endpoint = self._create_materialized_trends_endpoint(+ name="trends_browser_required",+ breakdowns=[{"property": "$browser", "type": "event"}],+ optional=[],+ )++ response = self.client.post(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run",+ {},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())+ self.assertIn("$browser", response.json().get("detail", ""))++ def test_multi_breakdown_one_required_one_optional_only_required_provided(self):+ """The headline path: 2 breakdowns, $os required and $browser optional. Caller passes only+ $os. Expect 200, $os filter applied, no $browser filter — aggregate across all browsers."""+ endpoint = self._create_materialized_trends_endpoint(+ name="trends_multi_one_optional",+ breakdowns=[+ {"property": "$os", "type": "event"},+ {"property": "$browser", "type": "event"},+ ],+ optional=["$browser"],+ )++ with mock.patch.object(+ EndpointExecutionService, "_execute_query_and_respond", return_value=Response({})+ ) as mock_exec:+ response = self.client.post(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run",+ {"variables": {"$os": "Mac OS X"}},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ mock_exec.assert_called()+ query_sql = mock_exec.call_args[0][0]["query"]["query"].lower()+ # The $os filter lands on breakdown_value[N]; the $browser filter does NOT appear at all+ # — there's only one positional breakdown_value index referenced.+ self.assertEqual(query_sql.count("breakdown_value["), 1)+ self.assertIn("mac os x", query_sql)++ def test_multi_breakdown_one_required_one_optional_missing_required_rejected(self):+ """Inverse of the above: optional $browser is fine, but missing required $os 400s."""+ endpoint = self._create_materialized_trends_endpoint(+ name="trends_multi_missing_required",+ breakdowns=[+ {"property": "$os", "type": "event"},+ {"property": "$browser", "type": "event"},+ ],+ optional=["$browser"],+ )++ response = self.client.post(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run",+ {},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())+ # Required missing list should mention $os, not $browser.+ detail = response.json().get("detail", "")+ self.assertIn("$os", detail)+ self.assertNotIn("$browser", detail)+def test_build_endpoint_hogql_performs_no_db_writes(self):_create_event(team=self.team, event="$pageview", distinct_id="u1")flush_persons_and_events()diff --git a/products/endpoints/backend/tests/test_insight_response_parity.py b/products/endpoints/backend/tests/test_insight_response_parity.pyindex 2a69444c355c..caa193d7ddb3 100644--- a/products/endpoints/backend/tests/test_insight_response_parity.py+++ b/products/endpoints/backend/tests/test_insight_response_parity.py@@ -700,3 +700,65 @@ class TestInsightResponseParity(ClickhouseTestMixin, APIBaseTest):endpoint.get_version().query,self.team,)++ def test_materialized_trends_optional_breakdown_returns_all_values(self):+ """PR 2 verification: with `$browser` marked optional and the caller passing no variables,+ the materialized read skips the WHERE filter and returns rows for every browser value.+ The insight transformer must group those rows into per-breakdown-value series without+ tripping MaterializedSeriesMismatchError.++ This is the "all values back from API" path the plan flags as unverified — the materialized+ rows look identical to a filtered read, but no variable filter has narrowed the set first.+ """+ endpoint = create_endpoint_with_version(+ name="trends_optional_breakdown_all_values",+ team=self.team,+ query=TrendsQuery(+ series=[EventsNode(event="$pageview")],+ breakdownFilter=BreakdownFilter(breakdowns=[Breakdown(property="$browser", type=BreakdownType.EVENT)]),+ dateRange={"date_from": "2026-01-01", "date_to": "2026-01-10"},+ ).model_dump(),+ created_by=self.user,+ is_active=True,+ )++ self._materialize_endpoint(endpoint)+ version = endpoint.versions.first()+ version.optional_breakdown_properties = ["$browser"]+ version.save(update_fields=["optional_breakdown_properties"])++ dates = [date(2026, 1, d) for d in range(1, 11)]+ # The materialized table emits one row per (series_index, breakdown_value).+ # No variable filter ⇒ rows for every breakdown value flow back unfiltered.+ flat_response = HogQLQueryResponse(+ results=[+ (dates, [1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0], ["Chrome"]),+ (dates, [0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0], ["Safari"]),+ (dates, [0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0], ["Firefox"]),+ ],+ columns=["date", "total", "breakdown_value"],+ types=["Array(Date)", "Array(Float64)", "Array(String)"],+ hasMore=False,+ )++ # Caller passes no variables — relies on $browser being optional.+ with mock.patch(+ "products.endpoints.backend.logic.execution.process_query_model",+ return_value=flat_response,+ ):+ mat_resp = self._run_endpoint(endpoint)++ # Must NOT 400 (optional was respected) and must NOT raise MaterializedSeriesMismatchError.+ assert mat_resp.status_code == status.HTTP_200_OK, mat_resp.json()+ mat_results = mat_resp.json()["results"]++ # One result entry per breakdown value the table emitted.+ assert len(mat_results) == 3, f"Expected one series per browser value, got {len(mat_results)}"+ # breakdown_value is a list (multi-breakdown shape, single element here).+ browsers = {(bv[0] if isinstance(bv := r.get("breakdown_value"), list) else bv) for r in mat_results}+ assert browsers == {"Chrome", "Safari", "Firefox"}, browsers++ # Shape parity with the inline path.+ for r in mat_results:+ for field in TRENDS_REQUIRED_FIELDS:+ assert field in r, f"Materialized response missing '{field}': {r}"