: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(taxonomy): time out slow property definition list queries (#78607)
Eli Reismanacf066f16596
diff --git a/posthog/api/test/test_property_definition.py b/posthog/api/test/test_property_definition.pyindex 041e47afa7bf..fcb0e7da16ef 100644--- a/posthog/api/test/test_property_definition.py+++ b/posthog/api/test/test_property_definition.py@@ -4,13 +4,19 @@ from typing import Any, Optional, Union, castfrom posthog.test.base import APIBaseTestfrom unittest.mock import ANY, patch+from django.db import OperationalErrorfrom django.test import SimpleTestCasefrom parameterized import parameterizedfrom rest_framework import statusfrom posthog.models import ActivityLog, EventDefinition, EventProperty, Organization, PropertyDefinition, Team-from posthog.taxonomy.property_definition_api import PropertyDefinitionQuerySerializer, PropertyDefinitionViewSet+from posthog.taxonomy.property_definition_api import (+ PropertyDefinitionQuerySerializer,+ PropertyDefinitionViewSet,+ QueryContext,+ is_query_canceled,+)def exclude_virtual_properties(results: list) -> list:@@ -1037,6 +1043,56 @@ class TestPropertyDefinitionAPI(APIBaseTest):assert "$virt_bot_name" in virtual_names+class TestPropertyDefinitionListStatementTimeout(APIBaseTest):+ def test_cancelled_list_query_returns_a_retryable_503(self) -> None:+ # Postgres cancels the statement, psycopg raises, and Django re-raises it as a bare+ # OperationalError. Without the handler that renders as a 500, which the taxonomic filter+ # shows as "no properties" rather than as a failure the user can retry.+ slow_count_sql = "SELECT count(*) AS full_count FROM (SELECT pg_sleep(3)) s WHERE %(project_id)s IS NOT NULL"++ with (+ patch.object(QueryContext, "as_count_sql", return_value=slow_count_sql),+ patch(+ "posthog.taxonomy.property_definition_api.PROPERTY_DEFINITIONS_STATEMENT_TIMEOUT_MS",+ 250,+ ),+ ):+ response = self.client.get(f"/api/projects/{self.team.pk}/property_definitions/")++ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE+ assert response.json()["code"] == "property_definitions_timeout"+++class TestIsQueryCanceled(SimpleTestCase):+ @staticmethod+ def _wrapped_error(**attrs: str) -> OperationalError:+ # Django surfaces the driver's error as its own OperationalError with the original attached+ # as __cause__, which is where the SQLSTATE lives.+ cause = Exception("canceling statement due to statement timeout")+ for name, value in attrs.items():+ setattr(cause, name, value)+ error = OperationalError("canceling statement due to statement timeout")+ error.__cause__ = cause+ return error++ @parameterized.expand(+ [+ ["psycopg3 exposes sqlstate", {"sqlstate": "57014"}, True],+ ["psycopg2 exposes pgcode", {"pgcode": "57014"}, True],+ ["a dropped connection is not a cancellation", {"sqlstate": "08006"}, False],+ ["a driver error carrying no sqlstate", {}, False],+ ]+ )+ def test_recognises_only_a_cancelled_statement(self, _name: str, attrs: dict[str, str], expected: bool) -> None:+ assert is_query_canceled(self._wrapped_error(**attrs)) is expected++ def test_recognises_the_code_on_the_error_itself(self) -> None:+ error = OperationalError("canceling statement due to statement timeout")+ error.sqlstate = "57014" # type: ignore[attr-defined]++ assert is_query_canceled(error) is True++class TestPropertyDefinitionQuerySerializer(SimpleTestCase):@parameterized.expand([diff --git a/posthog/taxonomy/property_definition_api.py b/posthog/taxonomy/property_definition_api.pyindex a8885e95b4df..e30bb0633016 100644--- a/posthog/taxonomy/property_definition_api.py+++ b/posthog/taxonomy/property_definition_api.py@@ -3,15 +3,16 @@ import uuidimport dataclassesfrom typing import Any, Optional, Self, Union, cast-from django.db import connection, models+from django.db import DEFAULT_DB_ALIAS, OperationalError, connections, models, router, transactionfrom django.db.models import Manager, QuerySetfrom django.db.models.functions import Coalescefrom django.http import Http404from django.shortcuts import get_object_or_404from opentelemetry import trace+from prometheus_client import Counterfrom rest_framework import mixins, request, response, serializers, status, viewsets-from rest_framework.exceptions import ValidationError+from rest_framework.exceptions import APIException, ValidationErrorfrom rest_framework.pagination import LimitOffsetPaginationfrom posthog.api.documentation import extend_schema@@ -39,6 +40,51 @@ EXCLUDED_EVENT_CORE_PROPERTIES = [prop for prop in CORE_FILTER_DEFINITIONS_BY_GROUP["event_properties"].keys() if not prop.startswith("$")]+PROPERTY_DEFINITION_TYPES = ["event", "person", "group", "session"]++# Listing runs two raw queries (a count, then a page fetch) that take seconds on projects with+# very many property definitions. The app database sets no statement_timeout, so a slow one keeps+# consuming database CPU for the full request until the gateway gives up at 120s, long after the+# client stopped waiting for it. Bounding each statement well below that ceiling sheds the load+# instead of queueing it, and returns a 503 the caller can retry or report.+PROPERTY_DEFINITIONS_STATEMENT_TIMEOUT_MS = 25_000++# Postgres reports a statement cancelled by statement_timeout as SQLSTATE 57014. psycopg2 exposes+# it as `pgcode` and psycopg3 as `sqlstate`, and Django re-raises either as its own+# OperationalError, so both attribute names have to be checked on the error and on its cause.+QUERY_CANCELED_SQLSTATE = "57014"++PROPERTY_DEFINITIONS_TIMED_OUT_COUNTER = Counter(+ "property_definitions_list_timed_out_total",+ "Property definition list requests cancelled by the statement timeout.",+ labelnames=["property_type"],+)+++class PropertyDefinitionsTimedOut(APIException):+ # The taxonomic filter renders a failed list the same way as an empty one, so a generic 5xx here+ # reads to the user as "this project has no properties". A stable code lets the client tell a+ # timed-out list apart from any other server error and offer a retry instead.+ status_code = status.HTTP_503_SERVICE_UNAVAILABLE+ default_code = "property_definitions_timeout"+ default_detail = "Loading properties took too long. Try a narrower search, or try again in a moment."+++def read_db_alias() -> str:+ # The page fetch is an ORM RawQuerySet, so it follows the read router (see ReplicaRouter's+ # opt-in list). The count query and the statement timeout have to land on that same connection+ # or they describe a different session than the one doing the work.+ return router.db_for_read(PropertyDefinition) or DEFAULT_DB_ALIAS+++def is_query_canceled(error: BaseException) -> bool:+ for exc in (error, error.__cause__):+ if exc is None:+ continue+ if (getattr(exc, "sqlstate", None) or getattr(exc, "pgcode", None)) == QUERY_CANCELED_SQLSTATE:+ return True+ return False+class SeenTogetherQuerySerializer(serializers.Serializer):event_names: serializers.ListField = serializers.ListField(child=serializers.CharField(), required=True)@@ -53,7 +99,7 @@ class PropertyDefinitionQuerySerializer(serializers.Serializer):)type = serializers.ChoiceField(- choices=["event", "person", "group", "session"],+ choices=PROPERTY_DEFINITION_TYPES,help_text="What property definitions to return",default="event",)@@ -722,7 +768,7 @@ class PropertyDefinitionViewSet(span.set_attribute("joins_event_property", query_context.should_join_event_property)with tracer.start_as_current_span("property_definitions_count_query") as count_span:- with connection.cursor() as cursor:+ with connections[read_db_alias()].cursor() as cursor:cursor.execute(query_context.as_count_sql(), query_context.params)full_count = cursor.fetchone()[0]count_span.set_attribute("full_count", full_count)@@ -796,10 +842,30 @@ class PropertyDefinitionViewSet(@extend_schema(parameters=[PropertyDefinitionQuerySerializer])def list(self, request, *args, **kwargs):- response = super().list(request, *args, **kwargs)-event_type = request.query_params.get("type", "event")+ # Both raw queries and the serialization that reads their rows have to sit inside this+ # transaction, because SET LOCAL only lasts until it commits and the page fetch is a lazy+ # RawQuerySet that the paginator does not evaluate until super().list() serializes it.+ alias = read_db_alias()+ try:+ with transaction.atomic(using=alias):+ with connections[alias].cursor() as cursor:+ cursor.execute(+ "SET LOCAL statement_timeout = %s",+ [PROPERTY_DEFINITIONS_STATEMENT_TIMEOUT_MS],+ )+ response = super().list(request, *args, **kwargs)+ except OperationalError as error:+ if not is_query_canceled(error):+ raise+ # `event_type` is raw query input, so clamp it to the known set rather than letting a+ # caller mint unbounded Prometheus label values.+ PROPERTY_DEFINITIONS_TIMED_OUT_COUNTER.labels(+ property_type=event_type if event_type in PROPERTY_DEFINITION_TYPES else "unknown"+ ).inc()+ raise PropertyDefinitionsTimedOut from error+# Inject virtual event/person/group properties to the end of the resultsif event_type in ["event", "person", "group"]:paginator = self.paginator