: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): stop the list 500ing and remove its N+1 queries (#76368)
Jovan Sakovicb422015f2381
diff --git a/products/endpoints/backend/logic/materialization.py b/products/endpoints/backend/logic/materialization.pyindex 8338896ff1bb..b19f985fcb58 100644--- a/products/endpoints/backend/logic/materialization.py+++ b/products/endpoints/backend/logic/materialization.py@@ -82,6 +82,11 @@ def prepare_executable_query(saved_query: DataWarehouseSavedQuery) -> None:saved_query.save(update_fields=["query", "updated_at"])+ELIGIBILITY_CHECK_FAILED_REASON = (+ "Couldn't check whether this query can be materialized. Try again, and if it keeps happening contact support."+)++def build_materialization_info(version: EndpointVersion, endpoint_name: str | None = None) -> dict:"""Build the materialization status dict for a version."""if version.saved_query:@@ -97,7 +102,11 @@ def build_materialization_info(version: EndpointVersion, endpoint_name: str | No"saved_query_id": str(version.saved_query.id),}else:- can_mat, reason = version.can_materialize()+ try:+ can_mat, reason = version.can_materialize()+ except Exception as e:+ capture_exception(e, {"endpoint_version_id": str(version.id), "team_id": version.endpoint.team_id})+ can_mat, reason = False, ELIGIBILITY_CHECK_FAILED_REASONresult = {"can_materialize": can_mat,"reason": reason if not can_mat else None,diff --git a/products/endpoints/backend/materialization_transforms.py b/products/endpoints/backend/materialization_transforms.pyindex b830a254713e..7e0b1472e53c 100644--- a/products/endpoints/backend/materialization_transforms.py+++ b/products/endpoints/backend/materialization_transforms.py@@ -11,6 +11,7 @@ from posthog.hogql.functions.aggregations import COMBINATORSfrom posthog.hogql.functions.mapping import find_hogql_aggregationfrom posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.hogql.parser import parse_select+from posthog.hogql.placeholders import find_placeholdersfrom posthog.hogql.printer import prepare_and_print_astfrom posthog.hogql.timings import HogQLTimingsfrom posthog.hogql.visitor import CloningVisitor, TraversingVisitor, clone_expr@@ -37,6 +38,14 @@ class VariableInHavingClauseError(MaterializationNotSupportedError):"""Raised when a variable is used in a HAVING clause, which is not supported for materialization."""+class VariableComparedToPlaceholderExprError(MaterializationNotSupportedError):+ """Raised when a variable is compared against an expression that itself reads a variable.++ That expression would be the materialized key column, which has to be fixed at+ materialization time, so it can't depend on a per-request value.+ """++def inject_series_index(query_ast: ast.SelectQuery | ast.SelectSetQuery) -> None:"""Add a __series_index literal column to each sub-query in a UNION ALL.@@ -305,6 +314,12 @@ def analyze_variables_for_materialization(all_usages = find_all_variable_usages(ast_node, placeholder)except VariableInHavingClauseError:return False, "Variable used in HAVING clause are not supported for materialization.", []+ except VariableComparedToPlaceholderExprError:+ return (+ False,+ "Variable compared against an expression containing another variable is not supported for materialization",+ [],+ )except ValueError as e:capture_exception(e)return False, "Invalid variable usage in WHERE clause.", []@@ -958,6 +973,11 @@ class VariablePlaceholderFinder(TraversingVisitor):self.variable_placeholders.append(node)+def _contains_placeholder(node: ast.Expr) -> bool:+ found = find_placeholders(node)+ return bool(found.has_filters or found.placeholder_fields or found.placeholder_expressions)++def find_variable_in_where(ast_node: ast.SelectQuery | ast.SelectSetQuery, placeholder: ast.Placeholder) -> Optional[VariableUsageInWhere]:@@ -1066,6 +1086,8 @@ class VariableInWhereFinder(TraversingVisitor):))elif isinstance(field_side, ast.Call):+ if _contains_placeholder(field_side):+ raise VariableComparedToPlaceholderExprError()column_chain = self._extract_column_chain_from_call(field_side)self.all_results.append((diff --git a/products/endpoints/backend/models.py b/products/endpoints/backend/models.pyindex 3eb1c8668dcb..980e6279c5f6 100644--- a/products/endpoints/backend/models.py+++ b/products/endpoints/backend/models.py@@ -407,7 +407,7 @@ class Endpoint(CreatedMetaFields, UpdatedMetaFields, DeletedMetaFields, UUIDTMod@propertydef endpoint_path(self) -> str:"""Return the API endpoint path for this endpoint."""- return f"/api/projects/{self.team.id}/endpoints/{self.name}/run"+ return f"/api/projects/{self.team_id}/endpoints/{self.name}/run"def has_query_changed(self, new_query: dict[str, Any]) -> bool:"""Deep comparison to check if query has actually changed.diff --git a/products/endpoints/backend/presentation/views/api.py b/products/endpoints/backend/presentation/views/api.pyindex 6ba0e520e7c4..2ba41e461f5a 100644--- a/products/endpoints/backend/presentation/views/api.py+++ b/products/endpoints/backend/presentation/views/api.py@@ -14,6 +14,7 @@ import reimport dataclassesfrom typing import cast+from django.db.models import Count, F, Prefetchfrom django.shortcuts import get_object_or_404from django_filters.rest_framework import DjangoFilterBackend@@ -272,6 +273,47 @@ class EndpointViewSet(return sorted({ti.tag.name for ti in endpoint.prefetched_tags})return sorted(endpoint.tagged_items.values_list("tag__name", flat=True))+ @staticmethod+ def _with_serialization_prefetches(queryset):+ """Tags are prefetched by TaggedItemViewSetMixin.filter_queryset; repeating them here+ raises a lookup conflict.++ Only the current version is fetched, and the history is counted in the database, so an+ endpoint with a long version history costs the same as a fresh one.+ """+ return (+ queryset.select_related("created_by")+ .prefetch_related(+ Prefetch(+ "versions",+ queryset=EndpointVersion.objects.filter(version=F("endpoint__current_version")).select_related(+ "saved_query"+ ),+ to_attr="prefetched_current_versions",+ ),+ )+ .annotate(versions_count=Count("versions", distinct=True))+ )++ @staticmethod+ def _current_version(endpoint: Endpoint) -> EndpointVersion:+ """Read the current version from the prefetch, falling back to a query.++ The prefetch is empty if `current_version` ever drifts from the versions actually stored,+ so the fallback also covers that.+ """+ prefetched = getattr(endpoint, "prefetched_current_versions", None)+ if prefetched:+ return prefetched[0]+ return endpoint.get_version()++ @staticmethod+ def _versions_count(endpoint: Endpoint) -> int:+ annotated = getattr(endpoint, "versions_count", None)+ if annotated is not None:+ return annotated+ return endpoint.versions.count()+def _serialize(self,obj: Endpoint | EndpointVersion,@@ -286,7 +328,7 @@ class EndpointViewSet(version = objelse:endpoint = obj- version = endpoint.get_version()+ version = self._current_version(endpoint)url = Noneui_url = None@@ -311,7 +353,7 @@ class EndpointViewSet("is_materialized": version.is_materialized,"current_version": endpoint.current_version,"current_version_id": str(version.id),- "versions_count": endpoint.versions.count(),+ "versions_count": self._versions_count(endpoint),"derived_from_insight": endpoint.derived_from_insight,"last_executed_at": endpoint.last_executed_at.isoformat() if endpoint.last_executed_at else None,"materialization": build_materialization_info(version),@@ -343,7 +385,7 @@ class EndpointViewSet()def list(self, request: Request, *args, **kwargs) -> Response:"""List all endpoints for the team."""- queryset = self.filter_queryset(self.get_queryset())+ queryset = self._with_serialization_prefetches(self.filter_queryset(self.get_queryset()))page = self.paginate_queryset(queryset)if page is not None:results = [self._serialize(endpoint, request) for endpoint in page]diff --git a/products/endpoints/backend/tests/test_endpoint.py b/products/endpoints/backend/tests/test_endpoint.pyindex 65c2fa276a41..76fe82bf7240 100644--- a/products/endpoints/backend/tests/test_endpoint.py+++ b/products/endpoints/backend/tests/test_endpoint.py@@ -5,6 +5,9 @@ from freezegun import freeze_timefrom posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom unittest import TestCase, mock+from django.db import connection+from django.test.utils import CaptureQueriesContext+from parameterized import parameterizedfrom rest_framework import status@@ -1886,3 +1889,73 @@ class TestOptionalBreakdownProperties(ClickhouseTestMixin, APIBaseTest):v2 = endpoint.get_version(2)# Explicit list wins — NOT the inherited ["$browser", "$os"].self.assertEqual(v2.optional_breakdown_properties, ["$os"])+++class TestEndpointListResilienceAndQueryCount(ClickhouseTestMixin, APIBaseTest):+ ENDPOINT = "endpoints"++ def _create_endpoints(self, count: int) -> None:+ for i in range(count):+ endpoint = create_endpoint_with_version(+ name=f"list_perf_{i}",+ team=self.team,+ query={+ "kind": "HogQLQuery",+ "query": "SELECT count() AS c FROM events WHERE event = {variables.event_name}",+ "variables": {"v0": {"variableId": "v0", "code_name": "event_name", "value": "$pageview"}},+ },+ created_by=self.user,+ )+ endpoint.versions.update(columns=[{"name": "c", "type": "integer"}])++ def _list_query_count(self, endpoint_count: int) -> int:+ Endpoint.objects.all().delete()+ self._create_endpoints(endpoint_count)+ url = f"/api/environments/{self.team.id}/endpoints/"+ self.client.get(url)+ with CaptureQueriesContext(connection) as ctx:+ response = self.client.get(url)+ self.assertEqual(status.HTTP_200_OK, response.status_code, response.content)+ self.assertEqual(endpoint_count, len(response.json()["results"]))+ return len(ctx.captured_queries)++ def test_list_query_count_does_not_grow_with_endpoint_count(self):+ few = self._list_query_count(2)+ many = self._list_query_count(8)++ self.assertEqual(few, many, f"listing 8 endpoints cost {many} queries vs {few} for 2, so something N+1s")++ def test_list_reports_the_latest_version_and_the_full_history_count(self):+ endpoint = create_endpoint_with_version(+ name="versioned",+ team=self.team,+ query={"kind": "HogQLQuery", "query": "SELECT 1"},+ created_by=self.user,+ )+ for i in range(2, 4):+ self.client.put(+ f"/api/environments/{self.team.id}/endpoints/{endpoint.name}/",+ {"query": {"kind": "HogQLQuery", "query": f"SELECT {i}"}},+ format="json",+ )++ response = self.client.get(f"/api/environments/{self.team.id}/endpoints/")++ self.assertEqual(status.HTTP_200_OK, response.status_code, response.content)+ result = response.json()["results"][0]+ self.assertEqual(3, result["current_version"])+ self.assertEqual(3, result["versions_count"])+ self.assertEqual("SELECT 3", result["query"]["query"])++ def test_list_survives_an_endpoint_whose_eligibility_check_raises(self):+ self._create_endpoints(2)++ with mock.patch.object(EndpointVersion, "can_materialize", side_effect=RuntimeError("boom")):+ response = self.client.get(f"/api/environments/{self.team.id}/endpoints/")++ self.assertEqual(status.HTTP_200_OK, response.status_code, response.content)+ results = response.json()["results"]+ self.assertEqual(2, len(results))+ for result in results:+ self.assertFalse(result["materialization"]["can_materialize"])+ self.assertIn("Couldn't check", result["materialization"]["reason"])diff --git a/products/endpoints/backend/tests/test_variable_materialization.py b/products/endpoints/backend/tests/test_variable_materialization.pyindex d840914ded0d..c7835e34e9cd 100644--- a/products/endpoints/backend/tests/test_variable_materialization.py+++ b/products/endpoints/backend/tests/test_variable_materialization.py@@ -209,6 +209,26 @@ class TestVariableAnalysis(APIBaseTest):assert can_materialize is Trueassert len(var_infos) == 1, f"Expected 1 variable, got {len(var_infos)} (duplicates not deduplicated)"+ def test_variable_compared_against_expression_holding_another_variable(self):+ query = {+ "kind": "HogQLQuery",+ "query": (+ "SELECT count() FROM events "+ "WHERE toDate(toTimeZone(timestamp, {variables.timezone})) >= toDate({variables.date_from})"+ ),+ "variables": {+ "var-1": {"code_name": "timezone", "value": "America/New_York"},+ "var-2": {"code_name": "date_from", "value": "2026-01-01"},+ },+ }++ can_materialize, reason, _ = analyze_variables_for_materialization(query)++ assert can_materialize is False+ assert reason == (+ "Variable compared against an expression containing another variable is not supported for materialization"+ )+def test_multiple_variables_rejects_unsupported_operator(self):query = {"kind": "HogQLQuery",