: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(event-definitions): bound the list with a statement timeout (#90647)
Phill41875ce5fc6d
diff --git a/ee/hogai/tools/read_taxonomy/mcp_tool.py b/ee/hogai/tools/read_taxonomy/mcp_tool.pyindex 9cf7a9a2b1e3..899555fb9121 100644--- a/ee/hogai/tools/read_taxonomy/mcp_tool.py+++ b/ee/hogai/tools/read_taxonomy/mcp_tool.py@@ -2,8 +2,8 @@ from django.db import OperationalErrorfrom prometheus_client import Counter+from posthog.api.statement_timeout import is_query_canceledfrom posthog.sync import database_sync_to_async-from posthog.taxonomy.property_definition_api import is_query_canceledfrom ee.hogai.chat_agent.query_planner.toolkit import TaxonomyAgentToolkitfrom ee.hogai.mcp_tool import MCPTool, mcp_tool_registrydiff --git a/posthog/api/event_definition.py b/posthog/api/event_definition.pyindex 35adaee838d2..e398d3d903a8 100644--- a/posthog/api/event_definition.py+++ b/posthog/api/event_definition.py@@ -1,6 +1,7 @@from __future__ import annotationsimport uuid+import functoolsfrom collections import defaultdictfrom typing import Any, Literal, Optional, cast@@ -14,6 +15,7 @@ import orjsonimport posthoganalyticsfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_serializer+from prometheus_client import Counterfrom rest_framework import mixins, request, response, serializers, status, viewsetsfrom rest_framework.settings import api_settings@@ -24,6 +26,7 @@ from posthog.api.event_definition_generators.typescript import TypeScriptGeneratfrom posthog.api.pagination import PrecountedLimitOffsetPaginationfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializer+from posthog.api.statement_timeout import statement_timeoutfrom posthog.api.tagged_item import (BULK_UPDATE_TAGS_MAX_IDS,BulkTagActivityContext,@@ -45,12 +48,41 @@ from posthog.models.activity_logging.activity_log import Detail, dict_changes_befrom posthog.models.user import Userfrom posthog.models.utils import UUIDTfrom posthog.settings import EE_AVAILABLE+from posthog.taxonomy.definition_listing import (+ DEFINITION_LIST_STATEMENT_TIMEOUT_MS,+ DefinitionListTimedOut,+ definition_read_db_alias,+)from posthog.taxonomy.definition_search import search_planfrom posthog.taxonomy.taxonomy import CORE_EVENTS, STALE_EVENT_DAYSfrom posthog.utils import get_safe_cache, relative_date_parse# If EE is enabled, we use ee.api.ee_event_definition.EnterpriseEventDefinitionSerializer+EVENT_DEFINITIONS_TIMED_OUT_COUNTER = Counter(+ "event_definitions_list_timed_out_total",+ "Event definition list requests cancelled by the statement timeout.",+)+++class EventDefinitionsTimedOut(DefinitionListTimedOut):+ default_code = "event_definitions_timeout"+ default_detail = "Loading events took too long. Try a narrower search, or try again in a moment."+++def event_definition_model(is_enterprise: bool) -> type[EventDefinition]:+ """The model the list query runs through, which the enterprise extension replaces."""+ if is_enterprise:+ from ee.models.event_definition import EnterpriseEventDefinition++ return EnterpriseEventDefinition+ return EventDefinition+++def read_db_alias() -> str:+ return definition_read_db_alias(event_definition_model(EE_AVAILABLE))+def _event_definitions_source_sql(event_type: EventDefinitionType,@@ -110,18 +142,10 @@ def create_event_definitions_sql() -> str:if order_expressions is None:order_expressions = []- if is_enterprise:- from ee.models import EnterpriseEventDefinition-- ee_model = EnterpriseEventDefinition- else:- # telling mypy to ignore this...- # it's fine to assign EventDefinition- ee_model = EventDefinition # type: ignoreevent_definition_fields = {f'"{f.column}"'- for f in ee_model._meta.get_fields()+ for f in event_definition_model(is_enterprise)._meta.get_fields()if hasattr(f, "column") and f.column not in ["deprecated_tags", "tags"]}# Django relies on PK being present in the result set to tell if it's a saved instance@@ -377,13 +401,7 @@ class EventDefinitionViewSet(# Allows this endpoint to return lists of event definitions, actions, or both.event_type = EventDefinitionType(self.request.GET.get("event_type", EventDefinitionType.EVENT))- event_definition_object_manager: Manager- if EE_AVAILABLE:- from ee.models.event_definition import EnterpriseEventDefinition-- event_definition_object_manager = EnterpriseEventDefinition.objects- else:- event_definition_object_manager = EventDefinition.objects+ event_definition_object_manager: Manager = event_definition_model(EE_AVAILABLE).objectssearch = self.request.GET.get("search", None)has_search_terms = bool(search and search.strip())@@ -479,7 +497,7 @@ class EventDefinitionViewSet()# The count has to run on the connection the page fetch will use, or it describes a# different row set than the one it bounds.- with connections[event_definition_object_manager.db].cursor() as cursor:+ with connections[read_db_alias()].cursor() as cursor:cursor.execute(count_sql, params)paginator.set_count(cursor.fetchone()[0])@@ -569,29 +587,35 @@ class EventDefinitionViewSet(extensions={"x-product": "event_definitions"},)def list(self, request, *args, **kwargs):- queryset = self.filter_queryset(self.get_queryset())- page = self.paginate_queryset(queryset)- objects = page if page is not None else list(queryset)-- # Batch-fetch media preview URLs to avoid N+1 queries in the serializer- event_ids = [obj.id for obj in objects]- media_map: dict[str, list[str]] = defaultdict(list)- if event_ids:- previews = (- ObjectMediaPreview.objects.filter(event_definition_id__in=event_ids)- .select_related("uploaded_media", "exported_asset")- .order_by("-updated_at")- )- for p in previews:- if p.media_url:- media_map[str(p.event_definition_id)].append(p.media_url)+ with statement_timeout(+ read_db_alias(),+ DEFINITION_LIST_STATEMENT_TIMEOUT_MS,+ EventDefinitionsTimedOut,+ EVENT_DEFINITIONS_TIMED_OUT_COUNTER,+ ):+ queryset = self.filter_queryset(self.get_queryset())+ page = self.paginate_queryset(queryset)+ objects = page if page is not None else list(queryset)++ # Batch-fetch media preview URLs to avoid N+1 queries in the serializer+ event_ids = [obj.id for obj in objects]+ media_map: dict[str, list[str]] = defaultdict(list)+ if event_ids:+ previews = (+ ObjectMediaPreview.objects.filter(event_definition_id__in=event_ids)+ .select_related("uploaded_media", "exported_asset")+ .order_by("-updated_at")+ )+ for p in previews:+ if p.media_url:+ media_map[str(p.event_definition_id)].append(p.media_url)- serializer = self.get_serializer(objects, many=True)- serializer.context["media_preview_urls_map"] = media_map+ serializer = self.get_serializer(objects, many=True)+ serializer.context["media_preview_urls_map"] = media_map- if page is not None:- return self.get_paginated_response(serializer.data)- return response.Response(serializer.data)+ if page is not None:+ return self.get_paginated_response(serializer.data)+ return response.Response(serializer.data)def dangerously_get_object(self):# A non-UUID lookup (e.g. the literal "undefined" from a link built without a saveddiff --git a/posthog/api/statement_timeout.py b/posthog/api/statement_timeout.pynew file mode 100644index 000000000000..30e40b6dc970--- /dev/null+++ b/posthog/api/statement_timeout.py@@ -0,0 +1,63 @@+from collections.abc import Iterator+from contextlib import contextmanager++from django.db import OperationalError, connections, transaction+from django.db.backends.base.base import BaseDatabaseWrapper++from prometheus_client import Counter+from rest_framework.exceptions import APIException++# 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"+++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+++def _current_statement_timeout(db: BaseDatabaseWrapper) -> str:+ with db.cursor() as cursor:+ cursor.execute("SHOW statement_timeout")+ return cursor.fetchone()[0]+++def _set_local_statement_timeout(db: BaseDatabaseWrapper, value: str) -> None:+ with db.cursor() as cursor:+ cursor.execute("SET LOCAL statement_timeout = %s", [value])+++@contextmanager+def statement_timeout(+ alias: str,+ timeout_ms: int,+ timed_out: type[APIException],+ timed_out_counter: Counter,+) -> Iterator[None]:+ """Cap every statement on `alias` inside the block, and raise `timed_out` when one is cancelled.++ Everything that runs a query has to sit inside this block, including code that evaluates a+ lazy queryset, because SET LOCAL only lasts until the transaction commits.+ """+ db = connections[alias]+ # Inside an outer transaction this block is only a savepoint, and Postgres keeps a SET LOCAL+ # when a savepoint is released. Putting the outer value back stops the cap leaking past the+ # block. A failed block needs no restore: the rollback undoes the SET LOCAL.+ outer_value = _current_statement_timeout(db) if db.in_atomic_block else None+ try:+ with transaction.atomic(using=alias):+ _set_local_statement_timeout(db, f"{timeout_ms}ms")+ yield+ if outer_value is not None:+ _set_local_statement_timeout(db, outer_value)+ except OperationalError as error:+ if not is_query_canceled(error):+ raise+ timed_out_counter.inc()+ raise timed_out from errordiff --git a/posthog/api/test/test_event_definition.py b/posthog/api/test/test_event_definition.pyindex a84e711d66a3..381db188b333 100644--- a/posthog/api/test/test_event_definition.py+++ b/posthog/api/test/test_event_definition.py@@ -756,6 +756,20 @@ class TestCreateEventDefinitionsSql(SimpleTestCase):assert "FULL OUTER JOIN" not in sql+class TestEventDefinitionListStatementTimeout(APIBaseTest):+ def test_cancelled_list_query_returns_a_retryable_503(self) -> None:+ slow_count_sql = "SELECT count(*) FROM (SELECT pg_sleep(3)) s WHERE %(project_id)s IS NOT NULL"++ with (+ patch("posthog.api.event_definition.create_event_definitions_count_sql", return_value=slow_count_sql),+ patch("posthog.api.event_definition.DEFINITION_LIST_STATEMENT_TIMEOUT_MS", 250),+ ):+ response = self.client.get(f"/api/projects/{self.team.pk}/event_definitions/")++ assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE+ assert response.json()["code"] == "event_definitions_timeout"++class TestEventDefinitionExcludeStale(APIBaseTest):"""Stale filter tests need real wall-clock times so the Postgres NOW() comparisonin `exclude_stale` matches the fixture last_seen_at values. The other test class isdiff --git a/posthog/api/test/test_property_definition.py b/posthog/api/test/test_property_definition.pyindex 6e5588c3ccb5..7a112b80690a 100644--- a/posthog/api/test/test_property_definition.py+++ b/posthog/api/test/test_property_definition.py@@ -4,7 +4,6 @@ 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 parameterized@@ -15,7 +14,6 @@ from posthog.taxonomy.property_definition_api import (PropertyDefinitionQuerySerializer,PropertyDefinitionViewSet,QueryContext,- is_query_canceled,)@@ -1063,10 +1061,7 @@ class TestPropertyDefinitionListStatementTimeout(APIBaseTest):with (patch.object(QueryContext, "as_count_sql", return_value=slow_count_sql),- patch(- "posthog.taxonomy.property_definition_api.PROPERTY_DEFINITIONS_STATEMENT_TIMEOUT_MS",- 250,- ),+ patch("posthog.taxonomy.property_definition_api.DEFINITION_LIST_STATEMENT_TIMEOUT_MS", 250),):response = self.client.get(f"/api/projects/{self.team.pk}/property_definitions/")@@ -1074,36 +1069,6 @@ class TestPropertyDefinitionListStatementTimeout(APIBaseTest):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/api/test/test_statement_timeout.py b/posthog/api/test/test_statement_timeout.pynew file mode 100644index 000000000000..12fb774cbd86--- /dev/null+++ b/posthog/api/test/test_statement_timeout.py@@ -0,0 +1,62 @@+from posthog.test.base import BaseTest++from django.db import DEFAULT_DB_ALIAS, OperationalError, connection+from django.test import SimpleTestCase++from parameterized import parameterized+from prometheus_client import Counter+from rest_framework.exceptions import APIException++from posthog.api.statement_timeout import is_query_canceled, statement_timeout++TEST_TIMED_OUT_COUNTER = Counter("test_statement_timeout_total", "Test only.")+++def current_statement_timeout() -> str:+ with connection.cursor() as cursor:+ cursor.execute("SHOW statement_timeout")+ return cursor.fetchone()[0]+++class TestStatementTimeoutInsideAnOuterTransaction(BaseTest):+ # BaseTest wraps each test in a transaction, so the helper runs as a savepoint here, which is+ # the case where a SET LOCAL would otherwise outlive the block.+ @parameterized.expand([["an explicit cap", "7s"], ["no cap", "0"]])+ def test_puts_the_outer_timeout_back_when_the_block_succeeds(self, _name: str, outer_value: str) -> None:+ with connection.cursor() as cursor:+ cursor.execute("SET LOCAL statement_timeout = %s", [outer_value])++ with statement_timeout(DEFAULT_DB_ALIAS, 250, APIException, TEST_TIMED_OUT_COUNTER):+ assert current_statement_timeout() == "250ms"++ assert current_statement_timeout() == outer_value+++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 Truediff --git a/posthog/taxonomy/definition_listing.py b/posthog/taxonomy/definition_listing.pynew file mode 100644index 000000000000..260d4380c9f2--- /dev/null+++ b/posthog/taxonomy/definition_listing.py@@ -0,0 +1,33 @@+"""What the event and property definition list endpoints share.++Both endpoints list a hand-written query over a table that every tenant shares, so one slow list+can hold a database connection for as long as the caller waits. Bounding the statement sheds that+load at a point we choose and returns a 503 the caller can retry.+"""++from django.db import router+from django.db.models import Model++from rest_framework import status+from rest_framework.exceptions import APIException++# The app database sets no statement_timeout, so without this a slow list keeps consuming database+# CPU until the gateway gives up at 120s, long after the client stopped waiting for it.+DEFINITION_LIST_STATEMENT_TIMEOUT_MS = 25_000+++def definition_read_db_alias(model: type[Model]) -> 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. ReplicaRouter matches on+ # the model's class name, so pass the model the page query itself runs through — the+ # enterprise child, wherever EE is available — not its parent.+ return router.db_for_read(model)+++class DefinitionListTimedOut(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 an empty project. A stable code lets the client tell a timed-out+ # list apart from any other server error and offer a retry instead. Each endpoint subclasses+ # this to name its own code and message.+ status_code = status.HTTP_503_SERVICE_UNAVAILABLEdiff --git a/posthog/taxonomy/property_definition_api.py b/posthog/taxonomy/property_definition_api.pyindex 44d7d87a0875..f659bc282bd3 100644--- a/posthog/taxonomy/property_definition_api.py+++ b/posthog/taxonomy/property_definition_api.py@@ -1,9 +1,10 @@import jsonimport uuid+import functoolsimport dataclassesfrom typing import Any, Optional, Self, Union, cast-from django.db import DEFAULT_DB_ALIAS, OperationalError, connections, router, transaction+from django.db import connectionsfrom django.db.models import Manager, QuerySetfrom django.http import Http404from django.shortcuts import get_object_or_404@@ -11,11 +12,12 @@ from django.shortcuts import get_object_or_404from opentelemetry import tracefrom prometheus_client import Counterfrom rest_framework import mixins, request, response, serializers, status, viewsets-from rest_framework.exceptions import APIException, ValidationError+from rest_framework.exceptions import ValidationErrorfrom posthog.api.documentation import extend_schemafrom posthog.api.pagination import PrecountedLimitOffsetPaginationfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.api.statement_timeout import statement_timeoutfrom posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixinfrom posthog.api.utils import actionfrom posthog.constants import GROUP_TYPES_LIMIT@@ -26,6 +28,11 @@ from posthog.models import EventProperty, PropertyDefinition, Userfrom posthog.models.activity_logging.activity_log import Detail, log_activityfrom posthog.models.utils import UUIDTfrom posthog.settings import EE_AVAILABLE+from posthog.taxonomy.definition_listing import (+ DEFINITION_LIST_STATEMENT_TIMEOUT_MS,+ DefinitionListTimedOut,+ definition_read_db_alias,+)from posthog.taxonomy.definition_search import search_planfrom posthog.taxonomy.taxonomy import (CORE_FILTER_DEFINITIONS_BY_GROUP,@@ -45,18 +52,6 @@ EXCLUDED_EVENT_CORE_PROPERTIES = [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.",@@ -64,29 +59,23 @@ PROPERTY_DEFINITIONS_TIMED_OUT_COUNTER = Counter()-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+class PropertyDefinitionsTimedOut(DefinitionListTimedOut):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 property_definition_model(is_enterprise: bool) -> type[PropertyDefinition]:+ """The model the list query runs through, which the enterprise extension replaces."""+ if is_enterprise:+ from ee.models.property_definition import EnterprisePropertyDefinition+ return EnterprisePropertyDefinition+ return PropertyDefinition-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++def read_db_alias() -> str:+ return definition_read_db_alias(property_definition_model(EE_AVAILABLE))class SeenTogetherQuerySerializer(serializers.Serializer):@@ -640,20 +629,20 @@ class PropertyDefinitionViewSet(order_by_verified = Falseif EE_AVAILABLE:- from ee.models.property_definition import EnterprisePropertyDefinition+ enterprise_model = property_definition_model(EE_AVAILABLE)# Prevent fetching deprecated `tags` field. Tags are separately fetched in TaggedItemSerializerMixinproperty_definition_fields = ", ".join([f'{f.cached_col.alias}."{f.column}"'- for f in EnterprisePropertyDefinition._meta.get_fields()+ for f in enterprise_model._meta.get_fields()if hasattr(f, "column")and f.column not in ["deprecated_tags", "tags"]and hasattr(f, "cached_col")])- queryset = EnterprisePropertyDefinition.objects+ queryset = enterprise_model.objectsorder_by_verified = True@@ -805,27 +794,16 @@ class PropertyDefinitionViewSet(def list(self, 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+ # `event_type` is raw query input, so clamp it to the known set rather than letting a+ # caller mint unbounded Prometheus label values.+ property_type = event_type if event_type in PROPERTY_DEFINITION_TYPES else "unknown"+ with statement_timeout(+ read_db_alias(),+ DEFINITION_LIST_STATEMENT_TIMEOUT_MS,+ PropertyDefinitionsTimedOut,+ PROPERTY_DEFINITIONS_TIMED_OUT_COUNTER.labels(property_type=property_type),+ ):+ response = super().list(request, *args, **kwargs)# Inject virtual event/person/group properties to the end of the resultsif event_type in ["event", "person", "group"]: