: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): add optional_breakdown_properties field (#68213)
Jovan Sakovic89a065c8b077
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex facab6aa68bb..906c649d022a 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -17342,6 +17342,13 @@"name": {"type": "string"},+ "optional_breakdown_properties": {+ "description": "Breakdown property names that may be omitted on /run. Omitted ones return data aggregated across all values of that breakdown.",+ "items": {+ "type": "string"+ },+ "type": "array"+ },"query": {"anyOf": [{diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex ed80b3e809c4..1ef7f9905112 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -2084,6 +2084,11 @@ export interface EndpointRequest {deleted?: boolean/** Tag names to associate with this endpoint. Replaces any existing tags. Omit to leave tags untouched. */tags?: string[]+ /**+ * Breakdown property names that may be omitted on /run. Omitted ones return data aggregated across all values of+ * that breakdown.+ */+ optional_breakdown_properties?: string[]}/**diff --git a/posthog/schema.py b/posthog/schema.pyindex cee4c5a7f55b..db3b238c3a11 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -25336,6 +25336,13 @@ class EndpointRequest(BaseModel):description="Whether this endpoint's query results are materialized to S3",)name: str | None = None+ optional_breakdown_properties: list[str] | None = Field(+ default=None,+ description=(+ "Breakdown property names that may be omitted on /run. Omitted ones return"+ " data aggregated across all values of that breakdown."+ ),+ )query: HogQLQuery | TrendsQuery | RetentionQuery | LifecycleQuery | WebStatsTableQuery | WebOverviewQuery | None = (None)diff --git a/products/endpoints/backend/logic/crud.py b/products/endpoints/backend/logic/crud.pyindex 24e1907022fe..f6648aa53b2c 100644--- a/products/endpoints/backend/logic/crud.py+++ b/products/endpoints/backend/logic/crud.py@@ -123,6 +123,7 @@ class EndpointCrudService:if data.data_freshness_seconds is not Noneelse DEFAULT_DATA_FRESHNESS_SECONDS),+ optional_breakdown_properties=list(data.optional_breakdown_properties or []),created_by=self.user,columns=columns,)@@ -315,6 +316,9 @@ class EndpointCrudService:else DEFAULT_DATA_FRESHNESS_SECONDS)update_fields.append("data_freshness_seconds")+ if "optional_breakdown_properties" in raw_data:+ target_version.optional_breakdown_properties = list(data.optional_breakdown_properties or [])+ update_fields.append("optional_breakdown_properties")# When targeting a specific version, is_active updates the versionif data.is_active is not None and version_targeted:target_version.is_active = data.is_activediff --git a/products/endpoints/backend/logic/strategies.py b/products/endpoints/backend/logic/strategies.pyindex 435afc77f640..3272a7879a04 100644--- a/products/endpoints/backend/logic/strategies.py+++ b/products/endpoints/backend/logic/strategies.py@@ -14,7 +14,6 @@ stay kind-agnostic.import abcimport dataclasses-from collections.abc import Iteratorfrom functools import cached_propertyfrom typing import TYPE_CHECKING, ClassVar, Optional@@ -45,7 +44,7 @@ from products.endpoints.backend.materialization_transforms import (prepare_insight_query_for_endpoint,transform_select_for_materialized_table,)-from products.endpoints.backend.models import Endpoint, EndpointVersion+from products.endpoints.backend.models import Endpoint, EndpointVersion, iter_breakdownsif TYPE_CHECKING:from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery@@ -109,22 +108,6 @@ class PlaceholderPreservingPrinter(HogQLPrinter):# ----------------------------------------------------------------------------def iter_breakdowns(breakdown_filter: dict) -> Iterator[tuple[str, str]]:- """Yield (property_name, property_type) from legacy or new breakdown format.-- Legacy: {"breakdown": "$browser", "breakdown_type": "event"}- New: {"breakdowns": [{"property": "$browser", "type": "event"}]}- """- breakdown = breakdown_filter.get("breakdown")- if breakdown:- yield (breakdown, breakdown_filter.get("breakdown_type", "event"))- return- for b in breakdown_filter.get("breakdowns") or []:- prop = b.get("property")- if prop:- yield (prop, b.get("type", "event"))--def get_breakdown_properties(breakdown_filter: dict) -> list[str]:"""Extract all breakdown property names from either legacy or new format."""return [name for name, _ in iter_breakdowns(breakdown_filter)]diff --git a/products/endpoints/backend/logic/validation.py b/products/endpoints/backend/logic/validation.pyindex e435e2fb5be3..6693b8d0d18b 100644--- a/products/endpoints/backend/logic/validation.py+++ b/products/endpoints/backend/logic/validation.py@@ -11,6 +11,7 @@ from typing import Optionalfrom django.conf import settings+from pydantic import BaseModelfrom rest_framework.exceptions import ValidationErrorfrom posthog.schema import EndpointRequest, HogQLQuery, HogQLVariable@@ -30,8 +31,14 @@ from products.endpoints.backend.constants import (ENDPOINT_NAME_REGEX,VALID_DATA_FRESHNESS_SECONDS,)+from products.endpoints.backend.logic.strategies import BREAKDOWN_SUPPORTED_QUERY_TYPESfrom products.endpoints.backend.materialization_transforms import SUPPORTED_BUCKET_FUNCTIONS, VariablePlaceholderFinder-from products.endpoints.backend.models import Endpoint, can_materialize_query+from products.endpoints.backend.models import (+ Endpoint,+ EndpointVersion,+ _breakdown_property_names,+ can_materialize_query,+)from products.product_analytics.backend.models.insight_variable import InsightVariable@@ -220,6 +227,46 @@ def validate_variable_placeholders(node: ast.AST, variables: Optional[dict[str,)+def validate_optional_breakdown_properties(+ optional_breakdown_properties: list[str] | None,+ query: BaseModel | dict | None,+) -> None:+ """Reject optional_breakdown_properties when the query has no breakdownFilter, or when+ any name isn't an actual breakdown property in the query.++ ``query`` is any of ``EndpointRequest.query``'s pydantic models, or a stored version's+ query dict — typed by contract so this doesn't chase the growing query-kind union.+ """+ if not optional_breakdown_properties:+ return++ query_dict = query.model_dump() if isinstance(query, BaseModel) else query+ query_kind = query_dict.get("kind") if isinstance(query_dict, dict) else None+ if query_kind not in BREAKDOWN_SUPPORTED_QUERY_TYPES:+ raise ValidationError(+ {+ "optional_breakdown_properties": (+ f"Query kind {query_kind!r} does not support breakdowns. "+ f"Supported: {', '.join(sorted(BREAKDOWN_SUPPORTED_QUERY_TYPES))}."+ )+ }+ )++ breakdown_filter = (query_dict.get("breakdownFilter") if isinstance(query_dict, dict) else None) or {}+ known = set(_breakdown_property_names(breakdown_filter))+ unknown = [p for p in optional_breakdown_properties if p not in known]+ if unknown:+ raise ValidationError(+ {+ "optional_breakdown_properties": (+ f"Unknown breakdown propert{'y' if len(unknown) == 1 else 'ies'}: "+ f"{', '.join(repr(p) for p in unknown)}. "+ f"Known: {sorted(known) if known else '(none)'}."+ )+ }+ )++def validate_endpoint_request(data: EndpointRequest, team: Team, user: User, strict: bool = True) -> None:"""Validate a create/update payload. With strict=True, name and query are required."""query = data.query@@ -244,9 +291,16 @@ def validate_endpoint_request(data: EndpointRequest, team: Team, user: User, strvalidate_hogql_query(query, team, user)validate_data_freshness(data.data_freshness_seconds)+ validate_optional_breakdown_properties(data.optional_breakdown_properties, query)-def validate_update_request(data: EndpointRequest, team: Team, user: User, endpoint: Endpoint | None = None) -> None:+def validate_update_request(+ data: EndpointRequest,+ team: Team,+ user: User,+ endpoint: Endpoint | None = None,+ version_number: int | None = None,+) -> None:"""Validate an update payload against the endpoint's resulting state."""validate_data_freshness(data.data_freshness_seconds)@@ -270,3 +324,16 @@ def validate_update_request(data: EndpointRequest, team: Team, user: User, endpoif data.query and isinstance(data.query, HogQLQuery) and data.query.query:sync_hogql_query_variables(data.query, team)validate_hogql_query(data.query, team, user)++ # Validate optional_breakdown_properties against the post-update query when one is supplied,+ # otherwise against the query of the version the update writes to (targeted or current).+ if data.optional_breakdown_properties is not None:+ if data.query is not None:+ validate_optional_breakdown_properties(data.optional_breakdown_properties, data.query)+ elif endpoint is not None:+ try:+ target_query = endpoint.get_version(version_number).query+ except EndpointVersion.DoesNotExist:+ target_query = None # a nonexistent targeted version 404s in the update service+ if target_query is not None:+ validate_optional_breakdown_properties(data.optional_breakdown_properties, target_query)diff --git a/products/endpoints/backend/migrations/0031_endpointversion_optional_breakdown_properties.py b/products/endpoints/backend/migrations/0031_endpointversion_optional_breakdown_properties.pynew file mode 100644index 000000000000..90c3ce473c24--- /dev/null+++ b/products/endpoints/backend/migrations/0031_endpointversion_optional_breakdown_properties.py@@ -0,0 +1,22 @@+# Generated by Django 5.2.14 on 2026-06-05 14:20++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("endpoints", "0030_endpointversion_last_executed_at"),+ ]++ operations = [+ migrations.AddField(+ model_name="endpointversion",+ name="optional_breakdown_properties",+ field=models.JSONField(+ blank=True,+ db_default=[],+ default=list,+ help_text="Breakdown property names that may be omitted on /run. Omitted ones return data aggregated across all values of that breakdown.",+ ),+ ),+ ]diff --git a/products/endpoints/backend/migrations/max_migration.txt b/products/endpoints/backend/migrations/max_migration.txtindex 83eec5a41bfc..10969429e573 100644--- a/products/endpoints/backend/migrations/max_migration.txt+++ b/products/endpoints/backend/migrations/max_migration.txt@@ -1 +1 @@-0030_endpointversion_last_executed_at+0031_endpointversion_optional_breakdown_propertiesdiff --git a/products/endpoints/backend/models.py b/products/endpoints/backend/models.pyindex 2be4b17deba6..526d011df7f0 100644--- a/products/endpoints/backend/models.py+++ b/products/endpoints/backend/models.py@@ -2,6 +2,7 @@ import reimport jsonimport uuidimport logging+from collections.abc import Iteratorfrom typing import Anyfrom django.core.exceptions import ObjectDoesNotExist, ValidationError@@ -125,6 +126,36 @@ def can_materialize_query(query: dict | None) -> tuple[bool, str]:return True, ""+def iter_breakdowns(breakdown_filter: object) -> Iterator[tuple[str, str]]:+ """Yield (property_name, property_type) pairs from either breakdown filter format.++ This is the single canonical extractor — validation, version pruning, and the+ runtime strategies all read breakdown properties through it.++ Legacy: {"breakdown": "$browser", "breakdown_type": "event"} — the value may also+ be a list of names.+ New: {"breakdowns": [{"property": "$browser", "type": "event"}]}+ """+ if not isinstance(breakdown_filter, dict):+ return+ breakdown = breakdown_filter.get("breakdown")+ if breakdown:+ breakdown_type = breakdown_filter.get("breakdown_type") or "event"+ names = breakdown if isinstance(breakdown, list) else [breakdown]+ for name in names:+ if name is not None:+ yield (str(name), breakdown_type)+ return+ for b in breakdown_filter.get("breakdowns") or []:+ if isinstance(b, dict) and b.get("property"):+ yield (str(b["property"]), b.get("type", "event"))+++def _breakdown_property_names(breakdown_filter: object) -> list[str]:+ """Extract breakdown property names from either breakdown filter format."""+ return [name for name, _ in iter_breakdowns(breakdown_filter)]++def validate_endpoint_name(value: str) -> None:"""Validate that the endpoint name is URL-safe and follows naming conventions."""if not re.match(r"^[a-zA-Z][a-zA-Z0-9_-]*$", value):@@ -199,6 +230,15 @@ class EndpointVersion(UpdatedMetaFields, models.Model):blank=True,help_text="When this version was last executed via the run API. Updated with 30-minute granularity.",)+ optional_breakdown_properties = models.JSONField(+ default=list,+ db_default=[],+ blank=True,+ help_text=(+ "Breakdown property names that may be omitted on /run. "+ "Omitted ones return data aggregated across all values of that breakdown."+ ),+ )class Meta:db_table = "endpoints_endpointversion"@@ -388,6 +428,15 @@ class Endpoint(CreatedMetaFields, UpdatedMetaFields, DeletedMetaFields, UUIDTModprevious_version = self.get_version()previous_data_freshness = previous_version.data_freshness_seconds if previous_version else 86400previous_description = previous_version.description if previous_version else ""+ previous_optional_breakdowns = (+ list(previous_version.optional_breakdown_properties or []) if previous_version else []+ )++ # Prune inherited optional list to property names still present in the new query+ # (mirrors how data_freshness_seconds rides along across versions).+ new_breakdown_filter = query.get("breakdownFilter") or {} if isinstance(query, dict) else {}+ new_breakdown_props = set(_breakdown_property_names(new_breakdown_filter))+ pruned_optional_breakdowns = [p for p in previous_optional_breakdowns if p in new_breakdown_props]self.current_version += 1self.save(update_fields=["current_version", "updated_at"])@@ -405,6 +454,7 @@ class Endpoint(CreatedMetaFields, UpdatedMetaFields, DeletedMetaFields, UUIDTModcreated_by=user,data_freshness_seconds=previous_data_freshness,description=previous_description,+ optional_breakdown_properties=pruned_optional_breakdowns,columns=columns,)diff --git a/products/endpoints/backend/presentation/serializers.py b/products/endpoints/backend/presentation/serializers.pyindex 338d4d62d314..9294b1266296 100644--- a/products/endpoints/backend/presentation/serializers.py+++ b/products/endpoints/backend/presentation/serializers.py@@ -76,6 +76,15 @@ class EndpointRequestSerializer(serializers.Serializer):allow_null=True,help_text="List of tag names to associate with this endpoint. Replaces any existing tags.",)+ optional_breakdown_properties = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ allow_null=True,+ help_text=(+ "Breakdown property names that may be omitted on /run. Omitted ones return data aggregated "+ "across all values of that breakdown. Defaults to [] — every breakdown variable is required."+ ),+ )class EndpointMaterializationSerializer(serializers.Serializer):@@ -253,6 +262,13 @@ class EndpointResponseSerializer(serializers.Serializer):child=serializers.CharField(),help_text="Tag names associated with this endpoint.",)+ optional_breakdown_properties = serializers.ListField(+ child=serializers.CharField(),+ help_text=(+ "Breakdown property names that may be omitted on /run. Omitted ones return data aggregated "+ "across all values of that breakdown."+ ),+ )class EndpointRunResponseSerializer(serializers.Serializer):diff --git a/products/endpoints/backend/presentation/views/api.py b/products/endpoints/backend/presentation/views/api.pyindex 962eeb96142e..6ba0e520e7c4 100644--- a/products/endpoints/backend/presentation/views/api.py+++ b/products/endpoints/backend/presentation/views/api.py@@ -318,6 +318,7 @@ class EndpointViewSet("bucket_overrides": version.bucket_overrides,"columns": version.get_columns() if version else [],"tags": self._get_tag_names(endpoint),+ "optional_breakdown_properties": list(version.optional_breakdown_properties or []),}if isinstance(obj, EndpointVersion):@@ -417,9 +418,11 @@ class EndpointViewSet(self.destroy(request, name=name)return Response({"success": True}, status=status.HTTP_200_OK)- validate_update_request(data, self.team, cast(User, request.user), endpoint=endpoint)-version_number = self._parse_version_param(request)+ validate_update_request(+ data, self.team, cast(User, request.user), endpoint=endpoint, version_number=version_number+ )+outcome = EndpointCrudService(self.team, request).update(endpoint, data, request.data, version_number)# When targeting a specific version, return version data; otherwise return endpoint datadiff --git a/products/endpoints/backend/tests/test_endpoint.py b/products/endpoints/backend/tests/test_endpoint.pyindex 1b527cd670e5..65c2fa276a41 100644--- a/products/endpoints/backend/tests/test_endpoint.py+++ b/products/endpoints/backend/tests/test_endpoint.py@@ -1611,3 +1611,278 @@ class TestClickhouseTypeMapping(TestCase):from products.endpoints.backend.models import _clickhouse_type_to_serialized_typeself.assertEqual(_clickhouse_type_to_serialized_type(ch_type), expected)+++class TestOptionalBreakdownProperties(ClickhouseTestMixin, APIBaseTest):+ """PR 1: pure additive plumbing — round-trip, inheritance, validation. No runtime semantics yet."""++ ENDPOINT = "endpoints"++ def setUp(self):+ super().setUp()+ self.trends_with_breakdown = {+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode"}],+ "breakdownFilter": {+ "breakdowns": [+ {"property": "$browser", "type": "event"},+ {"property": "$os", "type": "event"},+ ],+ },+ }++ def _create(self, name: str, query: dict, **extra: Any) -> dict:+ payload: dict[str, Any] = {"name": name, "query": query, **extra}+ response = self.client.post(f"/api/environments/{self.team.id}/endpoints/", payload, format="json")+ self.assertEqual(status.HTTP_201_CREATED, response.status_code, response.json())+ return response.json()++ def test_defaults_to_empty_list_on_create(self):+ data = self._create("ep_default", self.trends_with_breakdown)+ self.assertEqual(data["optional_breakdown_properties"], [])++ endpoint = Endpoint.objects.get(name="ep_default", team=self.team)+ self.assertEqual(endpoint.get_version().optional_breakdown_properties, [])++ def test_round_trip_on_create(self):+ data = self._create(+ "ep_optional",+ self.trends_with_breakdown,+ optional_breakdown_properties=["$browser"],+ )+ self.assertEqual(data["optional_breakdown_properties"], ["$browser"])++ endpoint = Endpoint.objects.get(name="ep_optional", team=self.team)+ self.assertEqual(endpoint.get_version().optional_breakdown_properties, ["$browser"])++ def test_accepts_names_from_legacy_list_breakdown(self):+ legacy_list_query = {+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode"}],+ "breakdownFilter": {"breakdown": ["$browser", "$os"], "breakdown_type": "event"},+ }+ data = self._create(+ "ep_legacy_list",+ legacy_list_query,+ optional_breakdown_properties=["$os"],+ )+ self.assertEqual(data["optional_breakdown_properties"], ["$os"])++ def test_round_trip_on_patch(self):+ self._create("ep_patch", self.trends_with_breakdown)++ response = self.client.patch(+ f"/api/environments/{self.team.id}/endpoints/ep_patch/",+ {"optional_breakdown_properties": ["$os"]},+ format="json",+ )+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())+ self.assertEqual(response.json()["optional_breakdown_properties"], ["$os"])++ endpoint = Endpoint.objects.get(name="ep_patch", team=self.team)+ self.assertEqual(endpoint.get_version().optional_breakdown_properties, ["$os"])++ def test_version_targeted_patch_validates_against_targeted_version(self):+ browser_query = {+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode"}],+ "breakdownFilter": {"breakdowns": [{"property": "$browser", "type": "event"}]},+ }+ os_query = {+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode"}],+ "breakdownFilter": {"breakdowns": [{"property": "$os", "type": "event"}]},+ }+ self._create("ep_target_version", browser_query)+ response = self.client.patch(+ f"/api/environments/{self.team.id}/endpoints/ep_target_version/",+ {"query": os_query},+ format="json",+ )+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())++ # $browser is valid for targeted v1 even though the current (v2) query dropped it.+ response = self.client.patch(+ f"/api/environments/{self.team.id}/endpoints/ep_target_version/?version=1",+ {"optional_breakdown_properties": ["$browser"]},+ format="json",+ )+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())+ endpoint = Endpoint.objects.get(name="ep_target_version", team=self.team)+ self.assertEqual(endpoint.get_version(1).optional_breakdown_properties, ["$browser"])++ # $os is valid for the current version but not for targeted v1.+ response = self.client.patch(+ f"/api/environments/{self.team.id}/endpoints/ep_target_version/?version=1",+ {"optional_breakdown_properties": ["$os"]},+ format="json",+ )+ self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code)++ def test_patch_can_clear(self):+ self._create(+ "ep_clear",+ self.trends_with_breakdown,+ optional_breakdown_properties=["$browser"],+ )++ response = self.client.patch(+ f"/api/environments/{self.team.id}/endpoints/ep_clear/",+ {"optional_breakdown_properties": []},+ format="json",+ )+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())+ self.assertEqual(response.json()["optional_breakdown_properties"], [])++ def test_patch_without_field_keeps_value(self):+ self._create(+ "ep_keep",+ self.trends_with_breakdown,+ optional_breakdown_properties=["$browser"],+ )++ response = self.client.patch(+ f"/api/environments/{self.team.id}/endpoints/ep_keep/",+ {"description": "updated"},+ format="json",+ )+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())+ self.assertEqual(response.json()["optional_breakdown_properties"], ["$browser"])++ def test_rejects_unknown_property_name(self):+ response = self.client.post(+ f"/api/environments/{self.team.id}/endpoints/",+ {+ "name": "ep_bad_prop",+ "query": self.trends_with_breakdown,+ "optional_breakdown_properties": ["$does_not_exist"],+ },+ format="json",+ )+ self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code, response.json())+ self.assertEqual(response.json().get("attr"), "optional_breakdown_properties")++ def test_rejects_for_hogql_query(self):+ response = self.client.post(+ f"/api/environments/{self.team.id}/endpoints/",+ {+ "name": "ep_hogql",+ "query": {"kind": "HogQLQuery", "query": "SELECT 1"},+ "optional_breakdown_properties": ["$browser"],+ },+ format="json",+ )+ self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code, response.json())+ self.assertEqual(response.json().get("attr"), "optional_breakdown_properties")++ def test_rejects_for_query_kind_without_breakdown_support(self):+ # LifecycleQuery has no breakdown support+ response = self.client.post(+ f"/api/environments/{self.team.id}/endpoints/",+ {+ "name": "ep_lifecycle",+ "query": {"kind": "LifecycleQuery", "series": [{"kind": "EventsNode"}]},+ "optional_breakdown_properties": ["$browser"],+ },+ format="json",+ )+ self.assertEqual(status.HTTP_400_BAD_REQUEST, response.status_code, response.json())+ self.assertEqual(response.json().get("attr"), "optional_breakdown_properties")++ def test_inheritance_on_query_change_prunes_to_existing_breakdowns(self):+ self._create(+ "ep_inherit",+ self.trends_with_breakdown,+ optional_breakdown_properties=["$browser", "$os"],+ )++ # New query drops $os from the breakdown list+ new_query = {+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode"}],+ "breakdownFilter": {"breakdowns": [{"property": "$browser", "type": "event"}]},+ }+ response = self.client.patch(+ f"/api/environments/{self.team.id}/endpoints/ep_inherit/",+ {"query": new_query},+ format="json",+ )+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())++ endpoint = Endpoint.objects.get(name="ep_inherit", team=self.team)+ self.assertEqual(endpoint.current_version, 2)+ v2 = endpoint.get_version(2)+ # $os was pruned because it isn't in the new query's breakdownFilter+ self.assertEqual(v2.optional_breakdown_properties, ["$browser"])++ def test_inheritance_drops_to_empty_when_no_breakdowns_in_new_query(self):+ self._create(+ "ep_inherit_drop",+ self.trends_with_breakdown,+ optional_breakdown_properties=["$browser"],+ )++ # New query has no breakdownFilter at all+ new_query = {"kind": "TrendsQuery", "series": [{"kind": "EventsNode"}]}+ response = self.client.patch(+ f"/api/environments/{self.team.id}/endpoints/ep_inherit_drop/",+ {"query": new_query},+ format="json",+ )+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())++ v2 = Endpoint.objects.get(name="ep_inherit_drop", team=self.team).get_version(2)+ self.assertEqual(v2.optional_breakdown_properties, [])++ def test_version_detail_includes_optional_breakdown_properties(self):+ """`_serialize` is shared between the endpoint and version-detail paths — make sure the+ field surfaces on GET /endpoints/{name}/?version=N too, not just /endpoints/{name}/."""+ self._create(+ "ep_version_detail",+ self.trends_with_breakdown,+ optional_breakdown_properties=["$browser"],+ )++ response = self.client.get(+ f"/api/environments/{self.team.id}/endpoints/ep_version_detail/?version=1",+ )+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())+ body = response.json()+ self.assertEqual(body["version"], 1)+ self.assertEqual(body["optional_breakdown_properties"], ["$browser"])++ def test_explicit_list_overrides_pruned_inheritance_on_query_change(self):+ """When PATCH carries both a new query AND an explicit optional_breakdown_properties,+ the explicit value wins — it doesn't get clobbered by the inheritance pruning that+ runs as part of create_new_version()."""+ self._create(+ "ep_explicit_override",+ self.trends_with_breakdown,+ optional_breakdown_properties=["$browser", "$os"],+ )++ # New query keeps both breakdowns but bumps breakdown_limit so has_query_changed() trips+ # and create_new_version() actually runs (the path whose pruning we're testing against).+ new_query = {+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode"}],+ "breakdownFilter": {+ "breakdowns": [+ {"property": "$browser", "type": "event"},+ {"property": "$os", "type": "event"},+ ],+ "breakdown_limit": 10,+ },+ }+ response = self.client.patch(+ f"/api/environments/{self.team.id}/endpoints/ep_explicit_override/",+ {"query": new_query, "optional_breakdown_properties": ["$os"]},+ format="json",+ )+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())++ endpoint = Endpoint.objects.get(name="ep_explicit_override", team=self.team)+ self.assertEqual(endpoint.current_version, 2)+ v2 = endpoint.get_version(2)+ # Explicit list wins — NOT the inherited ["$browser", "$os"].+ self.assertEqual(v2.optional_breakdown_properties, ["$os"])diff --git a/products/endpoints/frontend/generated/api.schemas.ts b/products/endpoints/frontend/generated/api.schemas.tsindex da67dc2a520d..c115434b7e49 100644--- a/products/endpoints/frontend/generated/api.schemas.ts+++ b/products/endpoints/frontend/generated/api.schemas.ts@@ -176,6 +176,8 @@ export interface EndpointResponseApi {columns: EndpointColumnApi[]/** Tag names associated with this endpoint. */tags: string[]+ /** Breakdown property names that may be omitted on /run. Omitted ones return data aggregated across all values of that breakdown. */+ optional_breakdown_properties: string[]}export interface PaginatedEndpointResponseListApi {@@ -249,6 +251,11 @@ export interface EndpointRequestApi {* @nullable*/tags?: string[] | null+ /**+ * Breakdown property names that may be omitted on /run. Omitted ones return data aggregated across all values of that breakdown. Defaults to [] — every breakdown variable is required.+ * @nullable+ */+ optional_breakdown_properties?: string[] | null}/**@@ -326,6 +333,8 @@ export interface EndpointVersionResponseApi {columns: EndpointColumnApi[]/** Tag names associated with this endpoint. */tags: string[]+ /** Breakdown property names that may be omitted on /run. Omitted ones return data aggregated across all values of that breakdown. */+ optional_breakdown_properties: string[]/** Version number. */version: number/** Version unique identifier (UUID). */@@ -405,6 +414,11 @@ export interface PatchedEndpointRequestApi {* @nullable*/tags?: string[] | null+ /**+ * Breakdown property names that may be omitted on /run. Omitted ones return data aggregated across all values of that breakdown. Defaults to [] — every breakdown variable is required.+ * @nullable+ */+ optional_breakdown_properties?: string[] | null}/**diff --git a/products/endpoints/frontend/generated/api.zod.ts b/products/endpoints/frontend/generated/api.zod.tsindex c7a3dbfaa471..8ad7c2c48318 100644--- a/products/endpoints/frontend/generated/api.zod.ts+++ b/products/endpoints/frontend/generated/api.zod.ts@@ -52,6 +52,12 @@ export const EndpointsCreateBody = /* @__PURE__ */ zod.array(zod.string()).nullish().describe('List of tag names to associate with this endpoint. Replaces any existing tags.'),+ optional_breakdown_properties: zod+ .array(zod.string())+ .nullish()+ .describe(+ 'Breakdown property names that may be omitted on \/run. Omitted ones return data aggregated across all values of that breakdown. Defaults to [] — every breakdown variable is required.'+ ),}).describe('Schema for creating\/updating endpoints. OpenAPI docs only — validation uses Pydantic.')@@ -98,6 +104,12 @@ export const EndpointsUpdateBody = /* @__PURE__ */ zod.array(zod.string()).nullish().describe('List of tag names to associate with this endpoint. Replaces any existing tags.'),+ optional_breakdown_properties: zod+ .array(zod.string())+ .nullish()+ .describe(+ 'Breakdown property names that may be omitted on \/run. Omitted ones return data aggregated across all values of that breakdown. Defaults to [] — every breakdown variable is required.'+ ),}).describe('Schema for creating\/updating endpoints. OpenAPI docs only — validation uses Pydantic.')@@ -144,6 +156,12 @@ export const EndpointsPartialUpdateBody = /* @__PURE__ */ zod.array(zod.string()).nullish().describe('List of tag names to associate with this endpoint. Replaces any existing tags.'),+ optional_breakdown_properties: zod+ .array(zod.string())+ .nullish()+ .describe(+ 'Breakdown property names that may be omitted on \/run. Omitted ones return data aggregated across all values of that breakdown. Defaults to [] — every breakdown variable is required.'+ ),}).describe('Schema for creating\/updating endpoints. OpenAPI docs only — validation uses Pydantic.')diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c4b206407543..c31d3e8c07cb 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -19151,6 +19151,11 @@ export namespace Schemas {* @nullable*/tags?: string[] | null;+ /**+ * Breakdown property names that may be omitted on /run. Omitted ones return data aggregated across all values of that breakdown. Defaults to [] — every breakdown variable is required.+ * @nullable+ */+ optional_breakdown_properties?: string[] | null;}/**@@ -19228,6 +19233,8 @@ export namespace Schemas {columns: EndpointColumn[];/** Tag names associated with this endpoint. */tags: string[];+ /** Breakdown property names that may be omitted on /run. Omitted ones return data aggregated across all values of that breakdown. */+ optional_breakdown_properties: string[];}/**@@ -19361,6 +19368,8 @@ export namespace Schemas {columns: EndpointColumn[];/** Tag names associated with this endpoint. */tags: string[];+ /** Breakdown property names that may be omitted on /run. Omitted ones return data aggregated across all values of that breakdown. */+ optional_breakdown_properties: string[];/** Version number. */version: number;/** Version unique identifier (UUID). */@@ -37967,6 +37976,11 @@ export namespace Schemas {* @nullable*/tags?: string[] | null;+ /**+ * Breakdown property names that may be omitted on /run. Omitted ones return data aggregated across all values of that breakdown. Defaults to [] — every breakdown variable is required.+ * @nullable+ */+ optional_breakdown_properties?: string[] | null;}/**diff --git a/services/mcp/src/generated/endpoints/api.ts b/services/mcp/src/generated/endpoints/api.tsindex 9d0fe057e208..3ed25681cd41 100644--- a/services/mcp/src/generated/endpoints/api.ts+++ b/services/mcp/src/generated/endpoints/api.ts@@ -77,6 +77,12 @@ export const EndpointsCreateBody = /* @__PURE__ */ zod.array(zod.string()).nullish().describe('List of tag names to associate with this endpoint. Replaces any existing tags.'),+ optional_breakdown_properties: zod+ .array(zod.string())+ .nullish()+ .describe(+ 'Breakdown property names that may be omitted on /run. Omitted ones return data aggregated across all values of that breakdown. Defaults to [] — every breakdown variable is required.'+ ),}).describe('Schema for creating/updating endpoints. OpenAPI docs only — validation uses Pydantic.')@@ -144,6 +150,12 @@ export const EndpointsPartialUpdateBody = /* @__PURE__ */ zod.array(zod.string()).nullish().describe('List of tag names to associate with this endpoint. Replaces any existing tags.'),+ optional_breakdown_properties: zod+ .array(zod.string())+ .nullish()+ .describe(+ 'Breakdown property names that may be omitted on /run. Omitted ones return data aggregated across all values of that breakdown. Defaults to [] — every breakdown variable is required.'+ ),}).describe('Schema for creating/updating endpoints. OpenAPI docs only — validation uses Pydantic.')diff --git a/services/mcp/src/tools/generated/endpoints.ts b/services/mcp/src/tools/generated/endpoints.tsindex fde86186329f..46e2dad828a4 100644--- a/services/mcp/src/tools/generated/endpoints.ts+++ b/services/mcp/src/tools/generated/endpoints.ts@@ -33,6 +33,7 @@ const EndpointCreateSchema = EndpointsCreateBody.omit({version: true,bucket_overrides: true,deleted: true,+ optional_breakdown_properties: true,})const endpointCreate = (): ToolBase<typeof EndpointCreateSchema, WithPostHogUrl<Schemas.EndpointResponse>> => ({@@ -244,8 +245,13 @@ const endpointRun = (): ToolBase<typeof EndpointRunSchema, WithPostHogUrl<Schema})const EndpointUpdateSchema = EndpointsPartialUpdateParams.omit({ project_id: true }).extend(- EndpointsPartialUpdateBody.omit({ name: true, derived_from_insight: true, bucket_overrides: true, deleted: true })- .shape+ EndpointsPartialUpdateBody.omit({+ name: true,+ derived_from_insight: true,+ bucket_overrides: true,+ deleted: true,+ optional_breakdown_properties: true,+ }).shape)const endpointUpdate = (): ToolBase<typeof EndpointUpdateSchema, WithPostHogUrl<Schemas.EndpointResponse>> => ({