Skip to content

: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.

perf(event-definitions): page the tag filter in SQL (#95823)

posthog[bot]60547433fd19
diff --git a/posthog/api/event_definition.py b/posthog/api/event_definition.py
index a893d0494f9f..35adaee838d2 100644
--- a/posthog/api/event_definition.py
+++ b/posthog/api/event_definition.py
@@ -107,7 +107,6 @@ def create_event_definitions_sql(
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 = []
@@ -142,13 +141,11 @@ def create_event_definitions_sql(
# 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)}
{_event_definitions_source_sql(event_type, is_enterprise, conditions)}
ORDER BY {",".join(additional_ordering)}
- {limit_clause}
+ LIMIT %(limit)s OFFSET %(offset)s
"""
@@ -450,20 +447,25 @@ class EventDefinitionViewSet(
params["names"] = list(set(names))
tags_list = self._tags_filter_from_request()
+ if tags_list:
+ # EXISTS, not a join: it keeps one row per definition, so the page stays a page and
+ # the count stays a count, with no DISTINCT over the whole result set.
+ search_query = (
+ search_query
+ + " AND EXISTS (SELECT 1 FROM posthog_taggeditem"
+ + " JOIN posthog_tag ON posthog_tag.id = posthog_taggeditem.tag_id"
+ + " WHERE posthog_taggeditem.event_definition_id = posthog_eventdefinition.id"
+ + " AND posthog_tag.name = ANY(%(tags)s))"
+ )
+ params["tags"] = tags_list
+
sql = create_event_definitions_sql(
event_type,
is_enterprise=EE_AVAILABLE,
conditions=search_query,
order_expressions=order_expressions,
- paginated=not tags_list,
)
- 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)
diff --git a/posthog/api/test/test_event_definition.py b/posthog/api/test/test_event_definition.py
index 92a12ae898cc..50bf090ab4ec 100644
--- a/posthog/api/test/test_event_definition.py
+++ b/posthog/api/test/test_event_definition.py
@@ -116,6 +116,25 @@ class TestEventDefinitionAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert response.json()["count"] == len(self.EXPECTED_EVENT_DEFINITIONS)
+ def test_list_event_definitions_filtered_by_tag_pages_in_sql(self):
+ # The tag filter used to read every definition in the project to collect ids. It now pages in
+ # SQL, so the page has to stay bounded, the count has to cover every match, and a definition
+ # that carries two of the filtered tags must still appear once.
+ bulk_url = f"/api/projects/{self.demo_team.pk}/event_definitions/bulk_update_tags/"
+ tagged_names = ["installed_app", "purchase"]
+ ids = [str(EventDefinition.objects.get(team=self.demo_team, name=name).id) for name in tagged_names]
+ self.client.post(bulk_url, {"ids": ids, "action": "add", "tags": ["billing"]})
+ self.client.post(bulk_url, {"ids": ids[:1], "action": "add", "tags": ["revenue"]})
+
+ response = self.client.get(
+ f"/api/projects/{self.demo_team.pk}/event_definitions/",
+ data={"tags": '["billing", "revenue"]', "limit": "1"},
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["count"] == len(tagged_names)
+ assert [result["name"] for result in response.json()["results"]] == ["installed_app"]
+
@parameterized.expand(
[
("limit", "limit=9223372036854775808"),