: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): propagate required/optional breakdown vars to OpenAPI spec (#68216)
Jovan Sakovic4fc259233ba2
diff --git a/products/endpoints/backend/logic/strategies.py b/products/endpoints/backend/logic/strategies.pyindex d71842f34505..6fadb159e305 100644--- a/products/endpoints/backend/logic/strategies.py+++ b/products/endpoints/backend/logic/strategies.py@@ -285,7 +285,12 @@ def _emit_breakdown_limit_signal(team: Team, endpoint: Endpoint) -> None:# ---------------------------------------------------------------------------FILTERS_OVERRIDE_DEPRECATION_HEADERS = {- "X-PostHog-Warn": "filters_override is deprecated. Use variables instead: https://posthog.com/docs/api/endpoints"+ "X-PostHog-Warn": (+ "filters_override is deprecated. Use variables instead, "+ "or mark the breakdown property as optional on the endpoint "+ "if you want to call /run without supplying its value: "+ "https://posthog.com/docs/api/endpoints"+ )}diff --git a/products/endpoints/backend/openapi.py b/products/endpoints/backend/openapi.pyindex 6ab0d0ff3a26..2ace1f9e5b87 100644--- a/products/endpoints/backend/openapi.py+++ b/products/endpoints/backend/openapi.py@@ -3,7 +3,7 @@ from django.conf import settingsfrom rest_framework.request import Requestfrom products.endpoints.backend.logic.strategies import InsightEndpointStrategy-from products.endpoints.backend.models import Endpoint, EndpointVersion+from products.endpoints.backend.models import Endpoint, EndpointVersion, _breakdown_property_namesfrom products.product_analytics.backend.models.insight_variable import InsightVariableINSIGHT_VARIABLE_TYPE_TO_OPENAPI: dict[str, dict] = {@@ -262,7 +262,7 @@ def _build_component_schemas(endpoint: Endpoint, version: EndpointVersion, team_}# Add variables schema based on query type and materialization state- variables_schema = _build_variables_schema(query, is_materialized, team_id)+ variables_schema = _build_variables_schema(query, is_materialized, team_id, version)if variables_schema:schemas["EndpointRunRequest"]["properties"]["variables"] = {"$ref": "#/components/schemas/Variables",@@ -272,22 +272,20 @@ def _build_component_schemas(endpoint: Endpoint, version: EndpointVersion, team_return schemas-def _get_single_breakdown_property(breakdown_filter: dict) -> str | None:- """Extract breakdown property from either legacy or new format."""- breakdown = breakdown_filter.get("breakdown")- if breakdown:- return breakdown- breakdowns = breakdown_filter.get("breakdowns") or []- if len(breakdowns) == 1:- return breakdowns[0].get("property")- return None+def _build_variables_schema(+ query: dict, is_materialized: bool, team_id: int, version: EndpointVersion | None = None+) -> dict | None:+ """Build schema for variables based on query type and materialization state.--def _build_variables_schema(query: dict, is_materialized: bool, team_id: int) -> dict | None:- """Build schema for variables based on query type and materialization state."""+ Emits a top-level ``required`` array so generated SDKs and clients see which+ variables they MUST send to /run. For insight endpoints this respects+ ``EndpointVersion.optional_breakdown_properties`` — opted-out breakdowns are+ listed as properties but kept out of ``required``, matching the runtime check.+ """query_kind = query.get("kind")properties: dict = {}required: list[str] = []+ optional_breakdowns: set[str] = set(version.optional_breakdown_properties or []) if version is not None else set()if query_kind == "HogQLQuery":variables = query.get("variables", {})@@ -317,24 +315,28 @@ def _build_variables_schema(query: dict, is_materialized: bool, team_id: int) ->properties[code_name]["example"] = default_valueelse:required.append(code_name)+ # Materialized HogQL rejects ANY missing variable at run time, defaults included.+ if is_materialized:+ required = sorted(properties.keys())else:# Insight queries - only include breakdown for supported query typesif query_kind in InsightEndpointStrategy.BREAKDOWN_SUPPORTED_QUERY_TYPES:breakdown_filter = query.get("breakdownFilter") or {}- breakdown = _get_single_breakdown_property(breakdown_filter)- if breakdown:+ for breakdown in _breakdown_property_names(breakdown_filter):+ if breakdown in properties:+ continueproperties[breakdown] = {"type": "string","description": f"Filter by {breakdown} breakdown value","example": "Chrome",}- # Materialized insights resolve the breakdown column at materialization- # time, so callers have to supply the value at execution; non-materialized- # insights can fall back to the saved filter.- if is_materialized:+ # Breakdown variables are enforced at run time on both inline and+ # materialized paths, unless the endpoint owner opted them out.+ if breakdown not in optional_breakdowns:required.append(breakdown)if not is_materialized:+ # Non-materialized also supports date variables — never required.properties["date_from"] = {"type": "string","description": "Filter results from this date (ISO format or relative like '-7d')",diff --git a/products/endpoints/backend/tests/test_openapi_spec.py b/products/endpoints/backend/tests/test_openapi_spec.pyindex 0fcde080554b..ff361401f4b7 100644--- a/products/endpoints/backend/tests/test_openapi_spec.py+++ b/products/endpoints/backend/tests/test_openapi_spec.py@@ -188,10 +188,9 @@ class TestEndpointOpenAPISpec(ClickhouseTestMixin, APIBaseTest):request_schema = spec["components"]["schemas"]["EndpointRunRequest"]self.assertNotIn("variables", request_schema.get("required", []))- def test_build_variables_schema_marks_breakdown_required_on_materialized_insight(self):- """Materialized insights resolve the breakdown column at materialization- time, so callers have to supply the value at execution. Non-materialized- insights fall back to the saved filter so the breakdown stays optional."""+ def test_build_variables_schema_marks_breakdown_required_on_insight(self):+ """Breakdown variables are enforced at run time on both inline and materialized+ insight endpoints, so the spec marks them required on both paths."""from products.endpoints.backend.openapi import _build_variables_schematrends_query = {@@ -208,7 +207,7 @@ class TestEndpointOpenAPISpec(ClickhouseTestMixin, APIBaseTest):schema_non_materialized = _build_variables_schema(trends_query, is_materialized=False, team_id=self.team.id)assert schema_non_materialized is not Noneself.assertIn("$browser", schema_non_materialized["properties"])- self.assertNotIn("required", schema_non_materialized)+ self.assertEqual(schema_non_materialized.get("required"), ["$browser"])def test_openapi_spec_variable_types(self):from products.product_analytics.backend.models.insight_variable import InsightVariable@@ -433,3 +432,205 @@ class TestEndpointOpenAPISpec(ClickhouseTestMixin, APIBaseTest):# Should not have Variables schema since no variables definedself.assertNotIn("Variables", spec["components"]["schemas"])+++class TestEndpointOpenAPIRequiredVariables(ClickhouseTestMixin, APIBaseTest):+ """The Variables schema must surface which variables are required vs optional so+ generated client SDKs reflect the real /run contract. Required breakdowns enforce; optional+ breakdowns may be omitted."""++ def _get(self, name: str) -> dict:+ response = self.client.get(f"/api/environments/{self.team.id}/endpoints/{name}/openapi.json/")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ schemas = response.json()["components"]["schemas"]+ self.assertIn("Variables", schemas, f"Variables schema missing for endpoint '{name}'")+ return schemas["Variables"]++ def _create_trends(self, name: str, breakdowns: list[dict], optional: list[str] | None = None):+ endpoint = create_endpoint_with_version(+ name=name,+ team=self.team,+ query={+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode"}],+ "breakdownFilter": {"breakdowns": breakdowns},+ },+ created_by=self.user,+ is_active=True,+ )+ if optional:+ version = endpoint.versions.first()+ version.optional_breakdown_properties = optional+ version.save(update_fields=["optional_breakdown_properties"])+ return endpoint++ def test_single_breakdown_required_by_default(self):+ self._create_trends("trends_one_breakdown", [{"property": "$browser", "type": "event"}])++ schema = self._get("trends_one_breakdown")+ self.assertIn("$browser", schema["properties"])+ self.assertIn("$browser", schema.get("required", []))++ def test_single_breakdown_omitted_from_required_when_optional(self):+ self._create_trends("trends_one_optional", [{"property": "$browser", "type": "event"}], optional=["$browser"])++ schema = self._get("trends_one_optional")+ # Property is still surfaced so callers can pass it...+ self.assertIn("$browser", schema["properties"])+ # ...but it's NOT in the required list, so generated SDKs leave it optional.+ # Either no `required` key at all, or `required` exists without $browser.+ self.assertNotIn("$browser", schema.get("required", []))++ def test_multi_breakdown_all_emitted_and_all_required_by_default(self):+ """Every breakdown property must be surfaced and land in `required` until explicitly+ marked optional — historically only the first breakdown was emitted."""+ self._create_trends(+ "trends_multi_breakdown",+ [+ {"property": "$browser", "type": "event"},+ {"property": "$os", "type": "event"},+ {"property": "$country", "type": "event"},+ ],+ )++ schema = self._get("trends_multi_breakdown")+ for prop in ("$browser", "$os", "$country"):+ self.assertIn(prop, schema["properties"], f"property {prop} missing")+ self.assertIn(prop, schema.get("required", []), f"property {prop} not marked required")++ def test_multi_breakdown_required_minus_optional(self):+ self._create_trends(+ "trends_multi_one_optional",+ [+ {"property": "$browser", "type": "event"},+ {"property": "$os", "type": "event"},+ ],+ optional=["$browser"],+ )++ schema = self._get("trends_multi_one_optional")+ self.assertIn("$browser", schema["properties"])+ self.assertIn("$os", schema["properties"])+ self.assertIn("$os", schema.get("required", []))+ self.assertNotIn("$browser", schema.get("required", []))++ def test_all_breakdowns_optional_omits_required_array(self):+ self._create_trends(+ "trends_all_optional",+ [+ {"property": "$browser", "type": "event"},+ {"property": "$os", "type": "event"},+ ],+ optional=["$browser", "$os"],+ )++ schema = self._get("trends_all_optional")+ # No required entries — generated SDK treats every variable as optional.+ self.assertNotIn("required", schema)++ def test_date_variables_never_required(self):+ """date_from / date_to are inline-only convenience variables; they always default at+ runtime and must NOT appear in the required array, even when breakdowns are required."""+ self._create_trends("trends_dates_not_required", [{"property": "$browser", "type": "event"}])++ schema = self._get("trends_dates_not_required")+ self.assertIn("date_from", schema["properties"])+ self.assertIn("date_to", schema["properties"])+ self.assertNotIn("date_from", schema.get("required", []))+ self.assertNotIn("date_to", schema.get("required", []))++ def test_hogql_inline_does_not_mark_variables_required(self):+ """Inline HogQL substitutes defaults/NULLs for missing variables — that's a coherent+ contract. The OpenAPI spec must not mark inline HogQL variables required, or generated+ SDKs would reject calls that are legal at runtime."""+ from products.product_analytics.backend.models.insight_variable import InsightVariable++ InsightVariable.objects.create(+ team=self.team,+ id="00000000-0000-0000-0000-0000000000aa",+ code_name="event_name",+ type="String",+ )+ create_endpoint_with_version(+ name="hogql_inline_no_required",+ team=self.team,+ query={+ "kind": "HogQLQuery",+ "query": "SELECT count() FROM events WHERE event = {variables.event_name}",+ "variables": {+ "00000000-0000-0000-0000-0000000000aa": {+ "variableId": "00000000-0000-0000-0000-0000000000aa",+ "code_name": "event_name",+ "value": "$pageview",+ },+ },+ },+ created_by=self.user,+ is_active=True,+ )++ schema = self._get("hogql_inline_no_required")+ self.assertIn("event_name", schema["properties"])+ self.assertNotIn("required", schema)++ def test_hogql_materialized_marks_all_variables_required(self):+ """Materialized HogQL rejects ANY missing variable at run time, defaults included, so the+ spec must mark every variable required — unlike the inline path, which substitutes+ defaults/NULLs and stays optional."""+ from products.endpoints.backend.openapi import _build_variables_schema+ from products.product_analytics.backend.models.insight_variable import InsightVariable++ with_default = InsightVariable.objects.create(+ team=self.team,+ id="00000000-0000-0000-0000-0000000000bb",+ code_name="has_default",+ type="String",+ default_value="fallback",+ )+ no_default = InsightVariable.objects.create(+ team=self.team,+ id="00000000-0000-0000-0000-0000000000cc",+ code_name="event_name",+ type="String",+ )+ query = {+ "kind": "HogQLQuery",+ "query": "SELECT count() FROM events WHERE event = {variables.event_name}",+ "variables": {+ str(with_default.id): {+ "variableId": str(with_default.id),+ "code_name": "has_default",+ "value": "fallback",+ },+ str(no_default.id): {"variableId": str(no_default.id), "code_name": "event_name"},+ },+ }++ schema = _build_variables_schema(query, is_materialized=True, team_id=self.team.id)+ assert schema is not None+ self.assertEqual(schema.get("required"), ["event_name", "has_default"])++ def test_deprecation_warning_mentions_marking_breakdown_optional(self):+ """The X-PostHog-Warn deprecation message must mention the optional opt-in (not just+ 'use variables instead') — marking the breakdown optional is what callers actually want+ if they were relying on permissive behavior."""+ endpoint = create_endpoint_with_version(+ name="hdr_check",+ team=self.team,+ query={+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode"}],+ "breakdownFilter": {"breakdowns": [{"property": "$browser", "type": "event"}]},+ },+ created_by=self.user,+ is_active=True,+ )+ response = self.client.post(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/run/",+ {"filters_override": {"properties": [{"key": "$browser", "value": "Chrome", "type": "event"}]}},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ warn = response.headers.get("X-PostHog-Warn", "")+ self.assertIn("filters_override is deprecated", warn)+ self.assertIn("optional", warn)