: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): paginate event lists in postgres (#93023)
posthog[bot]038ef701ef88
diff --git a/docs/internal/taxonomic-filter-search.md b/docs/internal/taxonomic-filter-search.mdindex 806b969c04da..c1287ec3468b 100644--- a/docs/internal/taxonomic-filter-search.md+++ b/docs/internal/taxonomic-filter-search.md@@ -9,3 +9,9 @@ Scoped property searches return properties associated with the selected events.The expansion count must not delay the scoped results or keep the aggregate reveal barrier closed. It can add an expansion option below the results after they appear. A failed count leaves the scoped results usable, and a count from an earlier search must not affect the current search. Expanding explicitly starts a full-results request and uses the normal list loading state.The legacy implementation separates these requests in `infiniteListLogic.ts`; the rebuilt implementation uses independent resources in `hooks/useGroupList.ts`. Keep this behavior consistent across both implementations.++## Event list pagination++The event definitions API counts matching rows separately and applies `LIMIT` and `OFFSET` in PostgreSQL. The count describes all matches, including matches outside the requested page. Explicit ordering uses the project-unique event name as a final tie-breaker so equal timestamps do not cause skipped or repeated results between pages.++Tag-filtered requests retain ORM pagination after resolving matching event IDs. Both paths preserve the same response fields and project scope, including legacy definitions whose `project_id` is null.diff --git a/posthog/api/event_definition.py b/posthog/api/event_definition.pyindex 9a239ebb1904..9ee5fd05e705 100644--- a/posthog/api/event_definition.py+++ b/posthog/api/event_definition.py@@ -5,7 +5,7 @@ from collections import defaultdictfrom typing import Any, Literal, Optional, castfrom django.core.cache import cache-from django.db import IntegrityError, transaction+from django.db import IntegrityError, connections, transactionfrom django.db.models import Manager, Prefetchfrom django.http import Http404from django.utils import timezone@@ -15,11 +15,13 @@ import posthoganalyticsfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_serializerfrom rest_framework import mixins, request, response, serializers, status, viewsets+from rest_framework.settings import api_settingsfrom posthog.api.event_definition_generators.base import EventDefinitionGeneratorfrom posthog.api.event_definition_generators.golang import GolangGeneratorfrom posthog.api.event_definition_generators.python import PythonGeneratorfrom posthog.api.event_definition_generators.typescript import TypeScriptGenerator+from posthog.api.pagination import PrecountedLimitOffsetPaginationfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.tagged_item import (@@ -49,11 +51,62 @@ from posthog.utils import get_safe_cache, relative_date_parse# If EE is enabled, we use ee.api.ee_event_definition.EnterpriseEventDefinitionSerializer+def _event_definitions_source_sql(+ event_type: EventDefinitionType,+ is_enterprise: bool,+ conditions: str,+) -> str:+ """FROM/JOIN/WHERE shared by the page fetch and the count that pages it."""+ # LEFT, not FULL OUTER. The two return the same rows here, on two independent grounds:+ # `eventdefinition_ptr_id` is the child's primary key and a validated NOT NULL foreign key, so an+ # enterprise row without a base row cannot be committed; and even if one existed, the scope+ # filter below reads base-table columns, so that row's `COALESCE(project_id, team_id)` would be+ # NULL and it would be filtered out regardless of join type.+ # The join type does change the plan. A full join can be neither a nested loop nor a filter+ # pushed into the scan, which leaves a sequential scan of the whole table available to the+ # planner — and it picked that plan in production once statistics shifted.+ enterprise_join = (+ "LEFT JOIN ee_enterpriseeventdefinition ON posthog_eventdefinition.id=ee_enterpriseeventdefinition.eventdefinition_ptr_id"+ if is_enterprise+ else ""+ )++ if event_type == EventDefinitionType.EVENT_CUSTOM:+ conditions += " AND posthog_eventdefinition.name NOT LIKE %(is_posthog_event)s"+ if event_type == EventDefinitionType.EVENT_POSTHOG:+ conditions += " AND posthog_eventdefinition.name LIKE %(is_posthog_event)s"++ # COALESCE(project_id, team_id) is the leading expression of the unique index+ # `event_definition_proj_uniq`, so the planner can seek that index for the project scope and+ # for any `name` equality in `conditions`. The equivalent form+ # `project_id = X OR (project_id IS NULL AND team_id = X)` matches no index at all.+ return f"""+ FROM posthog_eventdefinition+ {enterprise_join}+ WHERE COALESCE(project_id, team_id) = %(project_id)s+ {conditions}+ """+++def create_event_definitions_count_sql(+ event_type: EventDefinitionType,+ is_enterprise: bool = False,+ conditions: str = "",+) -> str:+ """Counts the rows `create_event_definitions_sql` pages over.++ Selecting no column lets Postgres drop the enterprise join whenever `conditions` reads only+ base-table columns, so the common count is an index-only scan.+ """+ return f"SELECT count(*) {_event_definitions_source_sql(event_type, is_enterprise, conditions)}"++def create_event_definitions_sql(event_type: EventDefinitionType,is_enterprise: bool = False,conditions: str = "",order_expressions: Optional[list[tuple[str, Literal["ASC", "DESC"]]]] = None,+ paginated: bool = True,) -> str:if order_expressions is None:order_expressions = []@@ -78,25 +131,6 @@ def create_event_definitions_sql(# split this query's load across hundreds of fingerprints and none of them looks expensive.selected_fields = sorted(event_definition_fields)- # LEFT, not FULL OUTER. The two return the same rows here, on two independent grounds:- # `eventdefinition_ptr_id` is the child's primary key and a validated NOT NULL foreign key, so an- # enterprise row without a base row cannot be committed; and even if one existed, the scope- # filter below reads base-table columns, so that row's `COALESCE(project_id, team_id)` would be- # NULL and it would be filtered out regardless of join type.- # The join type does change the plan. A full join can be neither a nested loop nor a filter- # pushed into the scan, which leaves a sequential scan of the whole table available to the- # planner — and it picked that plan in production once statistics shifted.- enterprise_join = (- "LEFT JOIN ee_enterpriseeventdefinition ON posthog_eventdefinition.id=ee_enterpriseeventdefinition.eventdefinition_ptr_id"- if is_enterprise- else ""- )-- if event_type == EventDefinitionType.EVENT_CUSTOM:- conditions += " AND posthog_eventdefinition.name NOT LIKE %(is_posthog_event)s"- if event_type == EventDefinitionType.EVENT_POSTHOG:- conditions += " AND posthog_eventdefinition.name LIKE %(is_posthog_event)s"-additional_ordering = []for order_expression, order_direction in order_expressions:if order_expression:@@ -104,17 +138,16 @@ def create_event_definitions_sql(f"{order_expression} {order_direction} NULLS {'FIRST' if order_direction == 'ASC' else 'LAST'}")- # COALESCE(project_id, team_id) is the leading expression of the unique index- # `event_definition_proj_uniq`, so the planner can seek that index for the project scope and- # for any `name` equality in `conditions`. The equivalent form- # `project_id = X OR (project_id IS NULL AND team_id = X)` matches no index at all.+ # A `RawQuerySet` has no `count()`, so DRF's paginator counts it with `len()` and slices the+ # result in Python. Without this clause one page of 100 costs a read of every event definition+ # the project has, wide columns included.+ limit_clause = "LIMIT %(limit)s OFFSET %(offset)s" if paginated else ""+return f"""SELECT {",".join(selected_fields)}- FROM posthog_eventdefinition- {enterprise_join}- WHERE COALESCE(project_id, team_id) = %(project_id)s- {conditions}+ {_event_definitions_source_sql(event_type, is_enterprise, conditions)}ORDER BY {",".join(additional_ordering)}+ {limit_clause}"""@@ -284,6 +317,32 @@ class EventDefinitionBulkUpdateVerifiedResponseSerializer(serializers.Serializer)+# Postgres LIMIT and OFFSET take a bigint. DRF accepts arbitrary-size ints, and binding one past+# the bigint range makes Postgres answer with a 500, so clamp them.+POSTGRES_BIGINT_MAX = 2**63 - 1+++class EventDefinitionQuerySerializer(serializers.Serializer):+ limit = serializers.IntegerField(+ required=False,+ min_value=1,+ default=api_settings.PAGE_SIZE,+ help_text="Number of results to return per page.",+ )+ offset = serializers.IntegerField(+ required=False,+ min_value=0,+ default=0,+ help_text="The initial index from which to return the results.",+ )++ def validate_limit(self, value: int) -> int:+ return min(value, POSTGRES_BIGINT_MAX)++ def validate_offset(self, value: int) -> int:+ return min(value, POSTGRES_BIGINT_MAX)++class EventDefinitionViewSet(TeamAndOrgViewSetMixin,TaggedItemViewSetMixin,@@ -309,6 +368,7 @@ class EventDefinitionViewSet(serializer_class = EventDefinitionSerializerlookup_field = "id"filter_backends = [TermSearchFilterBackend]+ pagination_class = PrecountedLimitOffsetPaginationqueryset = EventDefinition.objects.all()search_fields = ["name"]@@ -381,30 +441,53 @@ class EventDefinitionViewSet(search_query = search_query + " AND posthog_eventdefinition.name = ANY(%(names)s)"params["names"] = list(set(names))+ tags_list = self._tags_filter_from_request()sql = create_event_definitions_sql(event_type,is_enterprise=EE_AVAILABLE,conditions=search_query,order_expressions=order_expressions,+ paginated=not tags_list,)- queryset = event_definition_object_manager.raw(sql, params=params)- # Apply tags filter if provided+ if tags_list:+ # The tags filter has to see every match before it can page, so this path keeps the+ # unbounded fetch and lets the paginator page the resulting ORM queryset instead.+ ids = [obj.id for obj in event_definition_object_manager.raw(sql, params=params)]+ return event_definition_object_manager.filter(id__in=ids, tagged_items__tag__name__in=tags_list).distinct()++ paginator = cast(PrecountedLimitOffsetPagination, self.paginator)+ query = EventDefinitionQuerySerializer(data=self.request.query_params)+ query.is_valid(raise_exception=True)+ params["limit"] = query.validated_data["limit"]+ params["offset"] = query.validated_data["offset"]++ count_sql = create_event_definitions_count_sql(+ event_type,+ is_enterprise=EE_AVAILABLE,+ conditions=search_query,+ )+ # 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:+ cursor.execute(count_sql, params)+ paginator.set_count(cursor.fetchone()[0])++ return event_definition_object_manager.raw(sql, params=params)++ def _tags_filter_from_request(self) -> list[str]:tags = self.request.GET.get("tags")- if tags:- try:- tags_list = orjson.loads(tags)- if tags_list:- # Convert raw queryset to regular queryset for filtering- ids = [obj.id for obj in queryset]- queryset = event_definition_object_manager.filter( # type: ignore[assignment]- id__in=ids, tagged_items__tag__name__in=tags_list- ).distinct()- except (orjson.JSONDecodeError, TypeError):- # If the JSON is invalid, ignore the filter- pass-- return queryset+ if not tags:+ return []+ try:+ decoded = orjson.loads(tags)+ except orjson.JSONDecodeError:+ return []+ # Only a list of tag names disables pagination. A bare JSON scalar like `true` or `5`+ # is not iterable and would break the downstream `__in` filter, so ignore it.+ if not isinstance(decoded, list):+ return []+ return [tag for tag in decoded if isinstance(tag, str)]def _ordering_params_from_request(self,@@ -435,6 +518,12 @@ class EventDefinitionViewSet(if not results:results = [("last_seen_at::date", "DESC"), ("name", "ASC")]+ # `name` is unique per project, so it is the tiebreaker that keeps SQL LIMIT/OFFSET paging+ # stable. An explicit `?ordering=` without it can order tied rows differently per page, so a+ # row is paged twice or skipped.+ if not any(expression == "name" for expression, _ in results):+ results.append(("name", "ASC"))+return results@extend_schema(diff --git a/posthog/api/pagination.py b/posthog/api/pagination.pynew file mode 100644index 000000000000..4148a1c7c16a--- /dev/null+++ b/posthog/api/pagination.py@@ -0,0 +1,34 @@+from typing import Any, Optional++from rest_framework.pagination import LimitOffsetPagination+++class PrecountedLimitOffsetPagination(LimitOffsetPagination):+ """Pages a queryset that the view has already bounded with LIMIT and OFFSET.++ `LimitOffsetPagination` counts with `len(queryset)` and then slices the result in Python. A+ `RawQuerySet` answers both by fetching every row, so one page costs a read of the whole result+ set. Views that page in SQL run their own count statement and hand the total over with+ `set_count`. Without a count this behaves exactly like `LimitOffsetPagination`, so a view that+ also returns unbounded querysets keeps working.+ """++ count: Optional[int] = None++ def set_count(self, count: int) -> None:+ self.count = count++ def paginate_queryset(self, queryset, request, view=None) -> Optional[list[Any]]:+ if self.count is None:+ return super().paginate_queryset(queryset, request, view)++ self.limit = self.get_limit(request)+ if self.limit is None:+ return None++ self.offset = self.get_offset(request)+ self.request = request+ if self.count == 0 or self.offset > self.count:+ return []++ return list(queryset)diff --git a/posthog/api/test/test_event_definition.py b/posthog/api/test/test_event_definition.pyindex 72525820a9de..92a12ae898cc 100644--- a/posthog/api/test/test_event_definition.py+++ b/posthog/api/test/test_event_definition.py@@ -7,7 +7,9 @@ from freezegun.api import freeze_timefrom posthog.test.base import APIBaseTestfrom unittest.mock import ANY, patch+from django.db import connectionfrom django.test import SimpleTestCase+from django.test.utils import CaptureQueriesContextfrom django.utils import timezoneimport dateutil.parser@@ -101,6 +103,31 @@ class TestEventDefinitionAPI(APIBaseTest):assert "installed_app" not in result_namesassert "purchase" not in result_names+ @parameterized.expand(+ [+ ("boolean", "true"),+ ("number", "5"),+ ("object", '{"a": 1}'),+ ]+ )+ def test_list_event_definitions_ignores_non_list_tags_filter(self, _name, tags_value):+ response = self.client.get("/api/projects/@current/event_definitions/", data={"tags": tags_value})++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["count"] == len(self.EXPECTED_EVENT_DEFINITIONS)++ @parameterized.expand(+ [+ ("limit", "limit=9223372036854775808"),+ ("offset", "offset=9223372036854775808"),+ ]+ )+ def test_list_event_definitions_accepts_out_of_range_bigint_pagination(self, _name, query_string):+ response = self.client.get(f"/api/projects/@current/event_definitions/?{query_string}")++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["count"] == len(self.EXPECTED_EVENT_DEFINITIONS)+@parameterized.expand([("repeated", "names=installed_app&names=purchase&names=missing_event"),@@ -159,6 +186,17 @@ class TestEventDefinitionAPI(APIBaseTest):("watched_movie", None),],),+ (+ "ordering=-last_seen_at::date",+ [+ ("$pageview", "2020-01-01T22:56:00Z"),+ ("entered_free_trial", "2020-01-01T23:00:00Z"),+ ("installed_app", "2020-01-01T00:00:00Z"),+ ("purchase", "2019-12-30T00:00:00Z"),+ ("rated_app", "2019-12-21T00:00:00Z"),+ ("watched_movie", None),+ ],+ ),])def test_list_event_definitions_ordering(self, query_params, expected_results):@@ -235,6 +273,39 @@ class TestEventDefinitionAPI(APIBaseTest):assert len(response.json()["results"]) == (100 if i < 2 else 6) # Each page has 100 except the last oneassert response.json()["results"][0]["name"] == f"z_event_{event_checkpoints[i]}"+ def test_list_reads_only_the_requested_page_from_postgres(self):+ EventDefinition.objects.bulk_create(+ [EventDefinition(team=self.demo_team, name=f"z_event_{i}") for i in range(1, 301)]+ )++ with CaptureQueriesContext(connection) as captured:+ response = self.client.get("/api/projects/@current/event_definitions/?limit=10")++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["count"] == 306+ page_fetches = [+ query["sql"]+ for query in captured.captured_queries+ if "FROM posthog_eventdefinition" in query["sql"] and "ORDER BY" in query["sql"]+ ]+ assert page_fetches+ assert all("LIMIT 10" in sql for sql in page_fetches)++ expected_names = sorted(f"z_event_{i}" for i in range(1, 301))+ for offset in (0, 11, 300, 301):+ with self.subTest(offset=offset):+ response = self.client.get(+ "/api/projects/@current/event_definitions/",+ data={"search": "z_event", "ordering": "-last_seen_at", "limit": 10, "offset": offset},+ )+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["count"] == 300+ assert [row["name"] for row in response.json()["results"]] == expected_names[offset : offset + 10]++ response = self.client.get("/api/projects/@current/event_definitions/?search=missing_event&limit=10")+ assert response.json()["count"] == 0+ assert response.json()["results"] == []+def test_cant_see_event_definitions_for_another_team(self):org = Organization.objects.create(name="Separate Org")team = Team.objects.create(organization=org, name="Default Project")diff --git a/posthog/taxonomy/property_definition_api.py b/posthog/taxonomy/property_definition_api.pyindex 404c412cd923..183d12c49607 100644--- a/posthog/taxonomy/property_definition_api.py+++ b/posthog/taxonomy/property_definition_api.py@@ -12,9 +12,9 @@ from opentelemetry import tracefrom prometheus_client import Counterfrom rest_framework import mixins, request, response, serializers, status, viewsetsfrom rest_framework.exceptions import APIException, ValidationError-from rest_framework.pagination import LimitOffsetPaginationfrom posthog.api.documentation import extend_schema+from posthog.api.pagination import PrecountedLimitOffsetPaginationfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixinfrom posthog.api.utils import action@@ -580,45 +580,6 @@ class PropertyDefinitionSerializer(TaggedItemSerializerMixin, serializers.ModelSreturn super().update(property_definition, validated_data)-class NotCountingLimitOffsetPaginator(LimitOffsetPagination):- """- The standard LimitOffsetPagination was expensive because there are very many PropertyDefinition models- And we query them using a RawQuerySet that meant for each page of results we loaded all models twice- Once to count them and a second time because we would slice them in memory-- This paginator expects the caller to have counted and paged the queryset- """-- def set_count(self, count: int) -> None:- self.count = count-- def get_count(self, queryset) -> int:- """- Determine an object count, supporting either querysets or regular lists.- """- if self.count is None:- raise Exception("count must be manually set before paginating")-- return self.count-- def paginate_queryset(self, queryset, request, view=None) -> Optional[list[Any]]:- """- Assumes the queryset has already had pagination applied- """- self.count = self.get_count(queryset)- self.limit = self.get_limit(request)- if self.limit is None:- return None-- self.offset = self.get_offset(request)- self.request = request-- if self.count == 0 or self.offset > self.count:- return []-- return list(queryset)--@extend_schema(extensions={"x-product": "core"})class PropertyDefinitionViewSet(TeamAndOrgViewSetMixin,@@ -635,7 +596,7 @@ class PropertyDefinitionViewSet(filter_backends = [TermSearchFilterBackend]ordering = "name"search_fields = ["name"]- pagination_class = NotCountingLimitOffsetPaginator+ pagination_class = PrecountedLimitOffsetPaginationqueryset = PropertyDefinition.objects.all()@staticmethod@@ -697,7 +658,7 @@ class PropertyDefinitionViewSet(span.set_attribute("ee_available", EE_AVAILABLE)- assert isinstance(self.paginator, NotCountingLimitOffsetPaginator)+ assert isinstance(self.paginator, PrecountedLimitOffsetPagination)limit = self.paginator.get_limit(self.request)offset = self.paginator.get_offset(self.request)@@ -865,7 +826,7 @@ class PropertyDefinitionViewSet(# Inject virtual event/person/group properties to the end of the resultsif event_type in ["event", "person", "group"]:paginator = self.paginator- assert isinstance(paginator, NotCountingLimitOffsetPaginator)+ assert isinstance(paginator, PrecountedLimitOffsetPagination)query = PropertyDefinitionQuerySerializer(data=request.query_params)query.is_valid(raise_exception=True)