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): index-ordered paging and bounded counts for large projects (#98695)

Eli Reisman09572c39370f
diff --git a/docs/internal/taxonomic-filter-search.md b/docs/internal/taxonomic-filter-search.md
index 5194b8773bae..fa62d7d759af 100644
--- a/docs/internal/taxonomic-filter-search.md
+++ b/docs/internal/taxonomic-filter-search.md
@@ -35,7 +35,7 @@ Local filtering and rendering still update on each keystroke.
## 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.
+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, except on projects above the large-project threshold, where it stops at the cap in `posthog/taxonomy/definition_search.py`. There the response sets `count_is_capped`, `count` is a lower bound rather than a total, and paging continues while pages come back full rather than ending at the cap. A request that filters by search, stale events, verification, names, tags or `event_type=event_posthog` keeps the exact count, because those filters match too few rows for a bounded count to stop early. Above a second, higher threshold the default order is by name instead of recency, because nothing indexes `last_seen_at`. 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/frontend/src/lib/lemon-ui/PaginationControl/PaginationControl.test.tsx b/frontend/src/lib/lemon-ui/PaginationControl/PaginationControl.test.tsx
new file mode 100644
index 000000000000..dd86e4ff99a5
--- /dev/null
+++ b/frontend/src/lib/lemon-ui/PaginationControl/PaginationControl.test.tsx
@@ -0,0 +1,84 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+
+import { PaginationControl } from './PaginationControl'
+
+function renderLastCountedPage({
+ entryCountIsLowerBound,
+ onForward,
+ setCurrentPage = () => {},
+}: {
+ entryCountIsLowerBound: boolean
+ onForward?: () => void
+ setCurrentPage?: (page: number) => void
+}): void {
+ render(
+ <PaginationControl
+ pagination={{
+ controlled: true,
+ pageSize: 2,
+ currentPage: 2,
+ entryCount: 4,
+ entryCountIsLowerBound,
+ onForward,
+ onBackward: () => {},
+ }}
+ currentPage={2}
+ setCurrentPage={setCurrentPage}
+ pageCount={2}
+ dataSourcePage={['c', 'd']}
+ entryCount={4}
+ entryCountIsLowerBound={entryCountIsLowerBound}
+ currentStartIndex={2}
+ currentEndIndex={4}
+ />
+ )
+}
+
+describe('PaginationControl', () => {
+ // jest.setupAfterEnv does not enable RTL auto-cleanup; unmount between tests so `screen` stays isolated.
+ afterEach(() => {
+ cleanup()
+ })
+
+ it.each([
+ {
+ name: 'an exact count',
+ entryCountIsLowerBound: false,
+ hasNextLink: true,
+ label: '3-4 of 4 entries',
+ next: false,
+ },
+ {
+ name: 'a capped count',
+ entryCountIsLowerBound: true,
+ hasNextLink: true,
+ label: '3-4 of 4+ entries',
+ next: true,
+ },
+ {
+ name: 'a capped count on the true last page',
+ entryCountIsLowerBound: true,
+ hasNextLink: false,
+ label: '3-4 of 4+ entries',
+ next: false,
+ },
+ ])('on the last counted page with $name', ({ entryCountIsLowerBound, hasNextLink, label, next }) => {
+ renderLastCountedPage({ entryCountIsLowerBound, onForward: hasNextLink ? () => {} : undefined })
+
+ expect(screen.getByText(label)).toBeInTheDocument()
+ expect(screen.getByLabelText('Next page')).toHaveAttribute('aria-disabled', String(!next))
+ })
+
+ it('pages past a capped count', () => {
+ const onForward = jest.fn()
+ const setCurrentPage = jest.fn()
+ renderLastCountedPage({ entryCountIsLowerBound: true, onForward, setCurrentPage })
+
+ fireEvent.click(screen.getByLabelText('Next page'))
+
+ expect(onForward).toHaveBeenCalledTimes(1)
+ expect(setCurrentPage).toHaveBeenCalledWith(3)
+ })
+})
diff --git a/frontend/src/lib/lemon-ui/PaginationControl/PaginationControl.tsx b/frontend/src/lib/lemon-ui/PaginationControl/PaginationControl.tsx
index 82fe052a6490..78c5cf8f5c97 100644
--- a/frontend/src/lib/lemon-ui/PaginationControl/PaginationControl.tsx
+++ b/frontend/src/lib/lemon-ui/PaginationControl/PaginationControl.tsx
@@ -20,6 +20,7 @@ export function PaginationControl<T>({
pageCount,
dataSourcePage,
entryCount,
+ entryCountIsLowerBound,
currentStartIndex,
currentEndIndex,
nouns = ['entry', 'entries'],
@@ -28,8 +29,10 @@ export function PaginationControl<T>({
/** Whether pages previous and next are available. */
const isPreviousAvailable: boolean =
currentPage !== null ? currentPage > 1 : !!(pagination?.controlled && pagination.onBackward)
+ // A capped count does not tell where the rows end, so the next handler decides whether another page exists.
+ const lastPage: number = entryCountIsLowerBound ? Infinity : (pageCount as number)
const isNextAvailable: boolean =
- currentPage !== null && pageCount !== null
+ currentPage !== null && pageCount !== null && !entryCountIsLowerBound
? currentPage < pageCount
: !!(pagination?.controlled && pagination.onForward)
/** Whether there's reason to show pagination. */
@@ -45,8 +48,8 @@ export function PaginationControl<T>({
: entryCount === null
? `${currentPageSize} ${currentPageSize === 1 ? nouns[0] : nouns[1]} on this page`
: currentPageSize === 1
- ? `${currentEndIndex} of ${entryCount} ${entryCount === 1 ? nouns[0] : nouns[1]}`
- : `${currentStartIndex + 1}-${currentEndIndex} of ${entryCount} ${nouns[1]}`}
+ ? `${currentEndIndex} of ${entryCount}${entryCountIsLowerBound ? '+' : ''} ${entryCount === 1 ? nouns[0] : nouns[1]}`
+ : `${currentStartIndex + 1}-${currentEndIndex} of ${entryCount}${entryCountIsLowerBound ? '+' : ''} ${nouns[1]}`}
</span>
<LemonButton
icon={<IconChevronLeft />}
@@ -56,7 +59,7 @@ export function PaginationControl<T>({
onClick={() => {
pagination?.controlled && pagination.onBackward?.()
if ((pagination?.controlled && currentPage) || !pagination?.controlled) {
- setCurrentPage(Math.max(1, Math.min(pageCount as number, currentPage as number) - 1))
+ setCurrentPage(Math.max(1, Math.min(lastPage, currentPage as number) - 1))
}
}}
/>
@@ -68,7 +71,7 @@ export function PaginationControl<T>({
onClick={() => {
pagination?.controlled && pagination.onForward?.()
if ((pagination?.controlled && currentPage) || !pagination?.controlled) {
- setCurrentPage(Math.min(pageCount as number, (currentPage as number) + 1))
+ setCurrentPage(Math.min(lastPage, (currentPage as number) + 1))
}
}}
/>
diff --git a/frontend/src/lib/lemon-ui/PaginationControl/types.ts b/frontend/src/lib/lemon-ui/PaginationControl/types.ts
index 6426d41d12b9..ed5a9f9f0162 100644
--- a/frontend/src/lib/lemon-ui/PaginationControl/types.ts
+++ b/frontend/src/lib/lemon-ui/PaginationControl/types.ts
@@ -19,6 +19,8 @@ export interface PaginationManual extends PaginationBase {
currentPage?: number
/** Total entry count for determining current position using `currentPage`. If not set, position is not shown. */
entryCount?: number
+ /** Set when the count stopped at a cap, so `entryCount` is a lower bound and renders as `N+`. */
+ entryCountIsLowerBound?: boolean
/** Next page navigation handler. */
onForward?: () => void
/** Previous page navigation handler. */
@@ -42,4 +44,5 @@ export type PaginationState<T> = {
pageCount: number | null
/** Number of entries in total. */
entryCount: number | null
+ entryCountIsLowerBound?: boolean
}
diff --git a/frontend/src/lib/lemon-ui/PaginationControl/usePagination.test.ts b/frontend/src/lib/lemon-ui/PaginationControl/usePagination.test.ts
index a35f6e0595ff..d49c75835373 100644
--- a/frontend/src/lib/lemon-ui/PaginationControl/usePagination.test.ts
+++ b/frontend/src/lib/lemon-ui/PaginationControl/usePagination.test.ts
@@ -21,6 +21,19 @@ describe('usePagination', () => {
expect(router.values.searchParams.page).toBe(2)
})
+ it('carries the lower-bound flag through for a controlled, capped count', () => {
+ const { result } = renderHook(() =>
+ usePagination(DATA, {
+ controlled: true,
+ pageSize: 1,
+ currentPage: 1,
+ entryCount: 3,
+ entryCountIsLowerBound: true,
+ })
+ )
+ expect(result.current.entryCountIsLowerBound).toBe(true)
+ })
+
it('setCurrentPage leaves the URL alone when useUrl is false', () => {
const { result } = renderHook(() =>
usePagination(DATA, { controlled: true, pageSize: 1, currentPage: 1, entryCount: 3, useUrl: false })
diff --git a/frontend/src/lib/lemon-ui/PaginationControl/usePagination.ts b/frontend/src/lib/lemon-ui/PaginationControl/usePagination.ts
index 0346dd4ad9e2..0e374aef3102 100644
--- a/frontend/src/lib/lemon-ui/PaginationControl/usePagination.ts
+++ b/frontend/src/lib/lemon-ui/PaginationControl/usePagination.ts
@@ -29,6 +29,7 @@ export function usePagination<T>(
)
const entryCount: number | null = pagination?.controlled ? pagination.entryCount || null : dataSource.length
+ const entryCountIsLowerBound = !!(pagination?.controlled && pagination.entryCountIsLowerBound)
const pageCount: number | null =
entryCount && (pagination ? (pagination.pageSize ? Math.ceil(entryCount / pagination.pageSize) : 1) : null)
const currentPage: number | null = pagination?.controlled
@@ -61,6 +62,7 @@ export function usePagination<T>(
currentStartIndex,
currentEndIndex,
entryCount,
+ entryCountIsLowerBound,
setCurrentPage,
}
}
diff --git a/frontend/src/scenes/data-management/events/EventDefinitionsTable.tsx b/frontend/src/scenes/data-management/events/EventDefinitionsTable.tsx
index d7927144dd8f..7cbea7ff060e 100644
--- a/frontend/src/scenes/data-management/events/EventDefinitionsTable.tsx
+++ b/frontend/src/scenes/data-management/events/EventDefinitionsTable.tsx
@@ -230,6 +230,7 @@ export function EventDefinitionsTable(): JSX.Element {
controlled: true,
currentPage: eventDefinitions?.page ?? 1,
entryCount: eventDefinitions?.count ?? 0,
+ entryCountIsLowerBound: eventDefinitions?.count_is_capped === true,
pageSize: EVENT_DEFINITIONS_PER_PAGE,
onForward: eventDefinitions.next
? () => {
diff --git a/frontend/src/scenes/data-management/events/eventDefinitionsTableLogic.ts b/frontend/src/scenes/data-management/events/eventDefinitionsTableLogic.ts
index fef25d21c1f2..19650b7250f4 100644
--- a/frontend/src/scenes/data-management/events/eventDefinitionsTableLogic.ts
+++ b/frontend/src/scenes/data-management/events/eventDefinitionsTableLogic.ts
@@ -15,14 +15,18 @@ import { projectLogic } from 'scenes/projectLogic'
import { AnyPropertyFilter, EventDefinition, EventDefinitionType, PropertyDefinition } from '~/types'
import { eventDefinitionsBulkUpdateVerifiedCreate } from 'products/event_definitions/frontend/generated/api'
-import type { EventDefinitionBulkUpdateVerifiedResponseApi } from 'products/event_definitions/frontend/generated/api.schemas'
+import type {
+ EventDefinitionBulkUpdateVerifiedResponseApi,
+ PaginatedEnterpriseEventDefinitionListApi,
+} from 'products/event_definitions/frontend/generated/api.schemas'
import type {
BulkUpdateTagsUUIDErrorApi,
EventDefinitionBulkUpdateVerifiedItemApi,
} from '../../../../../products/event_definitions/frontend/generated/api.schemas'
-export interface EventDefinitionsPaginatedResponse extends PaginatedResponse<EventDefinition> {
+export interface EventDefinitionsPaginatedResponse
+ extends PaginatedResponse<EventDefinition>, Pick<PaginatedEnterpriseEventDefinitionListApi, 'count_is_capped'> {
current?: string
count?: number
page?: number
diff --git a/posthog/api/event_definition.py b/posthog/api/event_definition.py
index 12d6dd2635be..faf63af2386b 100644
--- a/posthog/api/event_definition.py
+++ b/posthog/api/event_definition.py
@@ -23,7 +23,7 @@ from posthog.api.event_definition_generators.base import EventDefinitionGenerato
from posthog.api.event_definition_generators.golang import GolangGenerator
from posthog.api.event_definition_generators.python import PythonGenerator
from posthog.api.event_definition_generators.typescript import TypeScriptGenerator
-from posthog.api.pagination import PrecountedLimitOffsetPagination
+from posthog.api.pagination import CappedCountLimitOffsetPagination
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.statement_timeout import statement_timeout
@@ -54,7 +54,13 @@ from posthog.taxonomy.definition_listing import (
DefinitionListTimedOut,
definition_read_db_alias,
)
-from posthog.taxonomy.definition_search import search_plan
+from posthog.taxonomy.definition_search import (
+ LARGE_PROJECT_COUNT_CAP,
+ NAME_ORDER_MIN_DEFINITIONS,
+ PROJECT_SCAN_MAX_DEFINITIONS,
+ bounded_count_sql,
+ project_definition_scale,
+)
from posthog.taxonomy.taxonomy import CORE_EVENTS, STALE_EVENT_DAYS
from posthog.utils import get_safe_cache, relative_date_parse
@@ -65,6 +71,20 @@ EVENT_DEFINITIONS_TIMED_OUT_COUNTER = Counter(
"Event definition list requests cancelled by the statement timeout.",
)
+EVENT_DEFINITION_ORDERING_FIELDS = ("name", "last_seen_at", "last_seen_at::date", "created_at", "created_at::date")
+
+# The members the list SQL implements. Nothing here reads the actions table, so `all` and
+# `action_event` would return plain event definitions under a name that promises otherwise.
+EVENT_DEFINITION_LIST_EVENT_TYPES = (
+ EventDefinitionType.EVENT,
+ EventDefinitionType.EVENT_CUSTOM,
+ EventDefinitionType.EVENT_POSTHOG,
+)
+
+# `name` is NOT NULL, so a NULLS clause on it changes no row order but stops the planner from matching
+# the unique index's default order (ASC NULLS LAST): the whole project then sorts before the page is cut.
+_NOT_NULL_ORDER_EXPRESSIONS = frozenset({"name", "length(name)"})
+
class EventDefinitionsTimedOut(DefinitionListTimedOut):
default_code = "event_definitions_timeout"
@@ -126,13 +146,19 @@ def create_event_definitions_count_sql(
event_type: EventDefinitionType,
is_enterprise: bool = False,
conditions: str = "",
+ bounded: bool = False,
) -> 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.
+ base-table columns, so the common count is an index-only scan. A bounded count stops at
+ %(count_cap)s rows, because an exact count over millions of definitions walks the project's whole
+ index range on every page load.
"""
- return f"SELECT count(*) {_event_definitions_source_sql(event_type, is_enterprise, conditions)}"
+ source_sql = _event_definitions_source_sql(event_type, is_enterprise, conditions)
+ if bounded:
+ return bounded_count_sql(source_sql, "posthog_eventdefinition.name")
+ return f"SELECT count(*) {source_sql}"
def create_event_definitions_sql(
@@ -158,7 +184,11 @@ def create_event_definitions_sql(
additional_ordering = []
for order_expression, order_direction in order_expressions:
- if order_expression:
+ if not order_expression:
+ continue
+ if order_expression in _NOT_NULL_ORDER_EXPRESSIONS:
+ additional_ordering.append(f"{order_expression} {order_direction}")
+ else:
additional_ordering.append(
f"{order_expression} {order_direction} NULLS {'FIRST' if order_direction == 'ASC' else 'LAST'}"
)
@@ -391,42 +421,61 @@ class EventDefinitionViewSet(
serializer_class = EventDefinitionSerializer
lookup_field = "id"
filter_backends = [TermSearchFilterBackend]
- pagination_class = PrecountedLimitOffsetPagination
+ pagination_class = CappedCountLimitOffsetPagination
queryset = EventDefinition.objects.all()
search_fields = ["name"]
ordering_fields = ["name", "last_seen_at", "created_at"]
def dangerously_get_queryset(self):
- # `type` = 'all' | 'event' | 'action_event'
- # Allows this endpoint to return lists of event definitions, actions, or both.
- event_type = EventDefinitionType(self.request.GET.get("event_type", EventDefinitionType.EVENT))
+ # Only `event_custom` and `event_posthog` change the rows, in `_event_definitions_source_sql`.
+ event_type = self._requested_event_type()
event_definition_object_manager: Manager = event_definition_model(EE_AVAILABLE).objects
search = self.request.GET.get("search", None)
has_search_terms = bool(search and search.strip())
- plan = (
- search_plan("posthog_eventdefinition", self.project_id, event_definition_object_manager.db)
- if has_search_terms
+ exclude_stale = self.request.GET.get("exclude_stale", "false").lower() == "true"
+ verified_param = self.request.GET.get("verified") if EE_AVAILABLE else None
+ names = [name for value in self.request.query_params.getlist("names") for name in value.split(",") if name]
+ tags_list = self._tags_filter_from_request()
+
+ # A filter that matches few rows makes `ORDER BY name LIMIT` walk most of the project in name order,
+ # probing each row, before it fills a page or reaches the count cap. The recency sort and the exact
+ # count read the project once with a parallel scan instead. So only the filters that leave most
+ # rows matching take the name-ordered, bounded path on a large project.
+ sparse_filter = (
+ has_search_terms
+ or exclude_stale
+ or verified_param is not None
+ or bool(names)
+ or bool(tags_list)
+ or event_type == EventDefinitionType.EVENT_POSTHOG
+ )
+ # The project's size picks the search index and the bounded path, so a request that neither searches
+ # nor can take that path skips the size check and its cache round trip.
+ scale = (
+ project_definition_scale("posthog_eventdefinition", self.project_id, event_definition_object_manager.db)
+ if has_search_terms or not sparse_filter
else None
)
+ large_project = scale is not None and scale.large
+ # A small project is cheaper to search through its own index than through the global trigram index.
search_query, search_kwargs = term_search_filter_sql(
- self.search_fields, search, avoid_trigram_index=plan == "project_scan"
+ self.search_fields, search, avoid_trigram_index=not large_project
)
- params = {"project_id": self.project_id, "is_posthog_event": "$%", **search_kwargs}
- order_expressions = self._ordering_params_from_request()
- has_explicit_ordering = "ordering" in self.request.GET
-
- if has_search_terms and not has_explicit_ordering:
- order_expressions = [("length(name)", "ASC"), *order_expressions]
+ params = {
+ "project_id": self.project_id,
+ "is_posthog_event": "$%",
+ "count_cap": LARGE_PROJECT_COUNT_CAP,
+ **search_kwargs,
+ }
exclude_hidden = self.request.GET.get("exclude_hidden", "false").lower() == "true"
if exclude_hidden and EE_AVAILABLE:
search_query = search_query + " AND (hidden IS NULL OR hidden = false)"
- exclude_stale = self.request.GET.get("exclude_stale", "false").lower() == "true"
if exclude_stale:
# `last_seen_at` is not indexed: the predicate runs after the project-scoped
# pre-filter in `create_event_definitions_sql` has already narrowed the row
@@ -439,8 +488,7 @@ class EventDefinitionViewSet(
)
params["stale_interval"] = f"{STALE_EVENT_DAYS} days"
- verified_param = self.request.GET.get("verified")
- if verified_param is not None and EE_AVAILABLE:
+ if verified_param is not None:
if verified_param.lower() == "true":
search_query = (
search_query + " AND (verified = true OR posthog_eventdefinition.name = ANY(%(core_events)s))"
@@ -460,12 +508,10 @@ class EventDefinitionViewSet(
search_query = search_query + " AND NOT name = ANY(%(excluded_list)s)"
params["excluded_list"] = excluded_list
- names = [name for value in self.request.query_params.getlist("names") for name in value.split(",") if name]
if names:
search_query = search_query + " AND posthog_eventdefinition.name = ANY(%(names)s)"
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.
@@ -480,6 +526,24 @@ class EventDefinitionViewSet(
params["tags"] = tags_list
params["tagged_content_type_id"] = content_type_for(EventDefinition).id
+ bounded = large_project and not sparse_filter
+
+ # Only a field the endpoint can order by counts as an explicit ordering. The events table sends
+ # `ordering=event`, which nothing serves, and it must still get the large-project default.
+ requested_ordering = self._requested_ordering()
+ order_expressions: list[tuple[str, Literal["ASC", "DESC"]]]
+ if bounded and scale is not None and scale.orders_by_name and not requested_ordering:
+ # Nothing indexes `last_seen_at`, so the default recency order sorts every definition the
+ # project has for each page. Name order pages straight from the unique index instead.
+ order_expressions = [("name", "ASC")]
+ else:
+ order_expressions = self._stable_ordering(requested_ordering)
+
+ # Any `ordering` parameter, served or not, keeps search results out of the shortest-name-first order.
+ # The events table sends `ordering=event` with every search and expects its usual order.
+ if has_search_terms and "ordering" not in self.request.GET:
+ order_expressions = [("length(name)", "ASC"), *order_expressions]
+
sql = create_event_definitions_sql(
event_type,
is_enterprise=EE_AVAILABLE,
@@ -487,7 +551,7 @@ class EventDefinitionViewSet(
order_expressions=order_expressions,
)
- paginator = cast(PrecountedLimitOffsetPagination, self.paginator)
+ paginator = cast(CappedCountLimitOffsetPagination, self.paginator)
query = EventDefinitionQuerySerializer(data=self.request.query_params)
query.is_valid(raise_exception=True)
params["limit"] = query.validated_data["limit"]
@@ -497,12 +561,15 @@ class EventDefinitionViewSet(
event_type,
is_enterprise=EE_AVAILABLE,
conditions=search_query,
+ bounded=bounded,
)
# 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[read_db_alias()].cursor() as cursor:
cursor.execute(count_sql, params)
- paginator.set_count(cursor.fetchone()[0])
+ definition_count = cursor.fetchone()[0]
+ # Only a count that reached the cap is a lower bound; a filtered large project can be under it.
+ paginator.set_count(definition_count, is_capped=bounded and definition_count >= LARGE_PROJECT_COUNT_CAP)
return event_definition_object_manager.raw(sql, params=params)
@@ -520,24 +587,31 @@ class EventDefinitionViewSet(
return []
return [tag for tag in decoded if isinstance(tag, str)]
- def _ordering_params_from_request(
- self,
- ) -> list[tuple[str, Literal["ASC", "DESC"]]]:
+ def _requested_event_type(self) -> EventDefinitionType:
+ """The `?event_type=` filter. An unknown value raises out of the enum, which reads as a 500."""
+ try:
+ event_type = EventDefinitionType(self.request.GET.get("event_type", EventDefinitionType.EVENT))
+ except ValueError:
+ raise serializers.ValidationError(
+ {"event_type": f"Not a valid event type. Use one of: {', '.join(EVENT_DEFINITION_LIST_EVENT_TYPES)}."}
+ )
+ # Neither ever returned actions, so both resolve to the rows they already gave.
+ if event_type in (EventDefinitionType.ALL, EventDefinitionType.ACTION_EVENT):
+ return EventDefinitionType.EVENT
+ return event_type
+
+ def _requested_ordering(self) -> list[tuple[str, Literal["ASC", "DESC"]]]:
+ """The `?ordering=` fields this endpoint can serve, in request order. Unknown fields are dropped."""
order_direction: Literal["ASC", "DESC"]
- results = []
+ results: list[tuple[str, Literal["ASC", "DESC"]]] = []
- # API client can send more than one ordering
- orderings = self.request.GET.getlist("ordering")
+ # A client can send more than one ordering as repeated parameters or as one comma-joined value, which is
+ # how the generated client serializes `ordering: string[]`.
+ orderings = [value for raw in self.request.GET.getlist("ordering") for value in raw.split(",")]
for ordering in orderings:
- if ordering and ordering.replace("-", "") in [
- "name",
- "last_seen_at",
- "last_seen_at::date",
- "created_at",
- "created_at::date",
- ]:
+ if ordering and ordering.replace("-", "") in EVENT_DEFINITION_ORDERING_FIELDS:
order = ordering.replace("-", "")
if "-" in ordering:
order_direction = "DESC"
@@ -546,19 +620,82 @@ class EventDefinitionViewSet(
results.append((order, order_direction))
- if not results:
- results = [("last_seen_at::date", "DESC"), ("name", "ASC")]
+ return results
+
+ @staticmethod
+ def _stable_ordering(
+ order_expressions: list[tuple[str, Literal["ASC", "DESC"]]],
+ ) -> list[tuple[str, Literal["ASC", "DESC"]]]:
+ if not order_expressions:
+ order_expressions = [("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"))
+ if not any(expression == "name" for expression, _ in order_expressions):
+ order_expressions = [*order_expressions, ("name", "ASC")]
- return results
+ return order_expressions
@extend_schema(
+ description=(
+ "List the event definitions of a project. On projects with more than "
+ f"{PROJECT_SCAN_MAX_DEFINITIONS} event definitions, `count` stops at {LARGE_PROJECT_COUNT_CAP} and "
+ "`count_is_capped` is true, unless the request sets `search`, `exclude_stale`, `verified`, `names`, "
+ f"`tags` or `event_type=event_posthog`. Projects with more than {NAME_ORDER_MIN_DEFINITIONS} event "
+ "definitions also default to ordering by name under the same condition."
+ ),
parameters=[
+ EventDefinitionQuerySerializer,
+ OpenApiParameter(
+ "search",
+ OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Case-insensitive match on the event name. Every whitespace-separated term has to match.",
+ ),
+ OpenApiParameter(
+ "event_type",
+ OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ enum=[event_type.value for event_type in EVENT_DEFINITION_LIST_EVENT_TYPES],
+ description=(
+ "`event_custom` keeps only names without a `$` prefix and `event_posthog` only names with one. "
+ "Default `event`."
+ ),
+ ),
+ OpenApiParameter(
+ "ordering",
+ OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ many=True,
+ enum=[*EVENT_DEFINITION_ORDERING_FIELDS, *(f"-{field}" for field in EVENT_DEFINITION_ORDERING_FIELDS)],
+ description=(
+ "Sort keys, prefixed with `-` for descending. Default `-last_seen_at::date` then `name`. "
+ f"Projects with more than {NAME_ORDER_MIN_DEFINITIONS} event definitions default to `name`, "
+ "unless the request sets `search`, `exclude_stale`, `verified`, `names`, `tags` or "
+ "`event_type=event_posthog`."
+ ),
+ ),
+ OpenApiParameter(
+ "verified",
+ OpenApiTypes.BOOL,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description=(
+ "When true, keep only verified events and core PostHog events. When false, keep the rest "
+ "(Enterprise only)."
+ ),
+ ),
+ OpenApiParameter(
+ "tags",
+ OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="JSON-encoded list of tag names. Keeps events that carry any of them.",
+ ),
OpenApiParameter(
"exclude_stale",
OpenApiTypes.BOOL,
@@ -586,6 +723,16 @@ class EventDefinitionViewSet(
many=True,
description="Return exact matches for these event names. Pass names as repeated or comma-separated values.",
),
+ OpenApiParameter(
+ "excluded_properties",
+ OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description=(
+ "JSON-encoded list of event names to omit. The name matches the property definitions "
+ "endpoint that shares it."
+ ),
+ ),
],
extensions={"x-product": "event_definitions"},
)
diff --git a/posthog/api/pagination.py b/posthog/api/pagination.py
index 742913c8bd93..cf8967b3dbeb 100644
--- a/posthog/api/pagination.py
+++ b/posthog/api/pagination.py
@@ -3,6 +3,8 @@ from typing import Any, Optional
from django.db.models import QuerySet
from rest_framework.pagination import LimitOffsetPagination
+from rest_framework.response import Response
+from rest_framework.utils.urls import replace_query_param
def stable_queryset_ordering(queryset: QuerySet) -> QuerySet:
@@ -33,10 +35,14 @@ class PrecountedLimitOffsetPagination(LimitOffsetPagination):
"""
count: Optional[int] = None
+ page_size_returned: int = 0
def set_count(self, count: int) -> None:
self.count = count
+ def _offset_is_past_the_end(self) -> bool:
+ return (self.offset or 0) > (self.count or 0)
+
def paginate_queryset(self, queryset, request, view=None) -> Optional[list[Any]]:
if self.count is None:
return super().paginate_queryset(queryset, request, view)
@@ -47,7 +53,49 @@ class PrecountedLimitOffsetPagination(LimitOffsetPagination):
self.offset = self.get_offset(request)
self.request = request
- if self.count == 0 or self.offset > self.count:
+ if self.count == 0 or self._offset_is_past_the_end():
+ self.page_size_returned = 0
return []
- return list(queryset)
+ page = list(queryset)
+ self.page_size_returned = len(page)
+ return page
+
+
+class CappedCountLimitOffsetPagination(PrecountedLimitOffsetPagination):
+ """Pages a view whose count stops at a cap, so `count` is a lower bound rather than a total.
+
+ Kept separate from `PrecountedLimitOffsetPagination` so only the views that cap carry
+ `count_is_capped` in their response schema.
+ """
+
+ count_is_capped: bool = False
+
+ def set_count(self, count: int, is_capped: bool = False) -> None:
+ super().set_count(count)
+ self.count_is_capped = is_capped
+
+ def _offset_is_past_the_end(self) -> bool:
+ # The count is a lower bound, so it says nothing about where the rows end. Only an empty page does.
+ return False if self.count_is_capped else super()._offset_is_past_the_end()
+
+ def get_next_link(self) -> Optional[str]:
+ # The base class drops `next` once `offset + limit >= count`, which a capped count reaches early.
+ if self.count_is_capped and self.limit and self.request and self.page_size_returned >= self.limit:
+ url = self.request.build_absolute_uri()
+ url = replace_query_param(url, self.limit_query_param, self.limit)
+ return replace_query_param(url, self.offset_query_param, (self.offset or 0) + self.limit)
+ return super().get_next_link()
+
+ def get_paginated_response(self, data: Any) -> Response:
+ response = super().get_paginated_response(data)
+ response.data["count_is_capped"] = self.count_is_capped
+ return response
+
+ def get_paginated_response_schema(self, schema: dict) -> dict:
+ paginated = super().get_paginated_response_schema(schema)
+ paginated["properties"]["count_is_capped"] = {
+ "type": "boolean",
+ "description": "True when `count` stopped at a cap, so it is a lower bound and `next` keeps paging past it.",
+ }
+ return paginated
diff --git a/posthog/api/test/test_event_definition.py b/posthog/api/test/test_event_definition.py
index 381db188b333..fadbaed39f64 100644
--- a/posthog/api/test/test_event_definition.py
+++ b/posthog/api/test/test_event_definition.py
@@ -7,6 +7,7 @@ import time_machine
from posthog.test.base import APIBaseTest
from unittest.mock import ANY, patch
+from django.core.cache import cache
from django.db import connection
from django.test import SimpleTestCase
from django.test.utils import CaptureQueriesContext
@@ -16,12 +17,13 @@ import dateutil.parser
from parameterized import parameterized
from rest_framework import status
-from posthog.api.event_definition import create_event_definitions_sql
+from posthog.api.event_definition import create_event_definitions_count_sql, create_event_definitions_sql
from posthog.api.test.test_organization import create_organization
from posthog.api.test.test_team import create_team
from posthog.api.test.test_user import create_user
from posthog.constants import EventDefinitionType
from posthog.models import ActivityLog, EventDefinition, Organization, Tag, Team
+from posthog.taxonomy import definition_search
from products.actions.backend.models.action import Action
@@ -216,6 +218,18 @@ class TestEventDefinitionAPI(APIBaseTest):
("watched_movie", None),
],
),
+ (
+ # The generated client joins `ordering: string[]` with commas.
+ "ordering=-last_seen_at::date,-name",
+ [
+ ("installed_app", "2020-01-01T00:00:00Z"),
+ ("entered_free_trial", "2020-01-01T23:00:00Z"),
+ ("$pageview", "2020-01-01T22:56: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):
@@ -223,6 +237,158 @@ class TestEventDefinitionAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert [(r["name"], r["last_seen_at"]) for r in response.json()["results"]] == expected_results
+ @parameterized.expand(
+ [
+ (
+ "above_the_name_threshold_pages_by_name",
+ "",
+ 2,
+ [
+ "$pageview",
+ "aardvark",
+ "entered_free_trial",
+ "installed_app",
+ "purchase",
+ "rated_app",
+ "watched_movie",
+ ],
+ ),
+ (
+ "below_the_name_threshold_keeps_recency",
+ "",
+ 100,
+ [
+ "$pageview",
+ "entered_free_trial",
+ "installed_app",
+ "purchase",
+ "rated_app",
+ "aardvark",
+ "watched_movie",
+ ],
+ ),
+ (
+ "explicit_order_is_kept",
+ "?ordering=-name",
+ 2,
+ [
+ "watched_movie",
+ "rated_app",
+ "purchase",
+ "installed_app",
+ "entered_free_trial",
+ "aardvark",
+ "$pageview",
+ ],
+ ),
+ (
+ "unknown_ordering_field_is_not_explicit",
+ "?ordering=event",
+ 2,
+ [
+ "$pageview",
+ "aardvark",
+ "entered_free_trial",
+ "installed_app",
+ "purchase",
+ "rated_app",
+ "watched_movie",
+ ],
+ ),
+ ]
+ )
+ def test_large_project_default_order_and_capped_count(
+ self, _name: str, query_string: str, name_order_min: int, expected_names: list[str]
+ ):
+ # Last seen before every fixture, so recency and name order disagree about where it goes.
+ create_event_definitions(
+ {"name": "aardvark", "last_seen_at": datetime.now() - timedelta(days=200)}, team_id=self.demo_team.pk
+ )
+ # The project's size is cached per project, so an earlier request in this class must not decide it.
+ cache.clear()
+ with (
+ patch.object(definition_search, "PROJECT_SCAN_MAX_DEFINITIONS", 2),
+ patch.object(definition_search, "NAME_ORDER_MIN_DEFINITIONS", name_order_min),
+ patch("posthog.api.event_definition.LARGE_PROJECT_COUNT_CAP", 3),
+ ):
+ response = self.client.get(f"/api/projects/@current/event_definitions/{query_string}")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert [r["name"] for r in response.json()["results"]] == expected_names
+ assert response.json()["count"] == 3
+ assert response.json()["count_is_capped"] is True
+
+ @parameterized.expand(
+ [
+ ("search", {"search": "app"}, 2, True),
+ # Postgres applies the stale cutoff with its own clock, which time_machine does not freeze, so every
+ # dated fixture is stale and only the never-seen definition remains.
+ ("exclude_stale", {"exclude_stale": "true"}, 1, False),
+ ("verified", {"verified": "true"}, 1, False),
+ ("names", {"names": "installed_app,purchase"}, 2, False),
+ ("tags", {"tags": '["billing"]'}, 2, False),
+ ("posthog_events", {"event_type": "event_posthog"}, 1, False),
+ ]
+ )
+ def test_large_project_sparse_filter_counts_exactly(
+ self, _name: str, query: dict[str, str], expected_count: int, sizes_the_project: bool
+ ):
+ ids = [str(EventDefinition.objects.get(team=self.demo_team, name=n).id) for n in ("installed_app", "purchase")]
+ self.client.post(
+ f"/api/projects/{self.demo_team.pk}/event_definitions/bulk_update_tags/",
+ {"ids": ids, "action": "add", "tags": ["billing"]},
+ )
+ cache.clear()
+ with (
+ patch.object(definition_search, "PROJECT_SCAN_MAX_DEFINITIONS", 2),
+ patch.object(definition_search, "NAME_ORDER_MIN_DEFINITIONS", 2),
+ patch("posthog.api.event_definition.LARGE_PROJECT_COUNT_CAP", 1),
+ ):
+ response = self.client.get("/api/projects/@current/event_definitions/", data=query)
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["count"] == expected_count
+ assert response.json()["count_is_capped"] is False
+ size_cache_key = f"taxonomy_definition_count:posthog_eventdefinition:{self.demo_team.project_id}"
+ assert (cache.get(size_cache_key) is not None) is sizes_the_project
+
+ def test_capped_count_is_flagged_and_still_pages(self):
+ cache.clear()
+ with (
+ patch.object(definition_search, "PROJECT_SCAN_MAX_DEFINITIONS", 2),
+ patch("posthog.api.event_definition.LARGE_PROJECT_COUNT_CAP", 3),
+ ):
+ response = self.client.get("/api/projects/@current/event_definitions/?limit=3")
+
+ body = response.json()
+ assert response.status_code == status.HTTP_200_OK
+ assert body["count"] == 3
+ assert body["count_is_capped"] is True
+ assert len(body["results"]) == 3
+ assert body["next"] is not None
+
+ def test_capped_count_pages_more_than_one_page_past_the_cap(self):
+ cache.clear()
+ with (
+ patch.object(definition_search, "PROJECT_SCAN_MAX_DEFINITIONS", 2),
+ patch("posthog.api.event_definition.LARGE_PROJECT_COUNT_CAP", 1),
+ ):
+ offsets = [
+ self.client.get(f"/api/projects/@current/event_definitions/?limit=1&offset={o}") for o in (1, 2, 3)
+ ]
+
+ for response in offsets:
+ assert response.status_code == status.HTTP_200_OK
+ assert len(response.json()["results"]) == 1, response.json()
+ assert response.json()["next"] is not None
+
+ def test_uncapped_count_reports_the_flag_as_false(self):
+ cache.clear()
+ response = self.client.get("/api/projects/@current/event_definitions/")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["count_is_capped"] is False
+
@patch("posthoganalytics.capture")
def test_delete_event_definition(self, mock_capture):
event_definition: EventDefinition = EventDefinition.objects.create(team=self.demo_team, name="test_event")
@@ -302,10 +468,13 @@ class TestEventDefinitionAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert response.json()["count"] == 306
+ # The large-project probe is a bounded count that also orders by name, so only the page fetches count here.
page_fetches = [
query["sql"]
for query in captured.captured_queries
- if "FROM posthog_eventdefinition" in query["sql"] and "ORDER BY" in query["sql"]
+ if "FROM posthog_eventdefinition" in query["sql"]
+ and "ORDER BY" in query["sql"]
+ and "count(*)" not in query["sql"]
]
assert page_fetches
assert all("LIMIT 10" in sql for sql in page_fetches)
@@ -393,11 +562,17 @@ class TestEventDefinitionAPI(APIBaseTest):
result_names = [r["name"] for r in response.json()["results"]]
assert result_names == expected_names
- def test_search_keeps_explicit_ordering(self) -> None:
- response = self.client.get("/api/projects/@current/event_definitions/?search=app&ordering=name")
+ @parameterized.expand(
+ [
+ ("served_field", "name", ["installed_app", "rated_app"]),
+ ("events_table_unserved_field", "event", ["installed_app", "rated_app"]),
+ ]
+ )
+ def test_search_keeps_explicit_ordering(self, _name: str, ordering: str, expected_names: list[str]) -> None:
+ response = self.client.get(f"/api/projects/@current/event_definitions/?search=app&ordering={ordering}")
assert response.status_code == status.HTTP_200_OK
result_names = [r["name"] for r in response.json()["results"]]
- assert result_names == ["installed_app", "rated_app"]
+ assert result_names == expected_names
def test_whitespace_search_does_not_change_default_ordering(self) -> None:
default_response = self.client.get("/api/projects/@current/event_definitions/")
@@ -429,6 +604,20 @@ class TestEventDefinitionAPI(APIBaseTest):
assert response.json()["count"] == 1
assert response.json()["results"][0]["name"] == "$pageview"
+ def test_unknown_event_type_is_rejected(self):
+ response = self.client.get("/api/projects/@current/event_definitions/?event_type=events")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == "event_type"
+
+ @parameterized.expand([("all",), ("action_event",)])
+ def test_legacy_event_type_returns_the_same_rows_as_event(self, event_type: str):
+ baseline = self.client.get("/api/projects/@current/event_definitions/?search=app&event_type=event")
+ response = self.client.get(f"/api/projects/@current/event_definitions/?search=app&event_type={event_type}")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert [r["name"] for r in response.json()["results"]] == [r["name"] for r in baseline.json()["results"]]
+
@patch("posthog.settings.EE_AVAILABLE", True)
@patch("posthog.models.Organization.is_feature_available", return_value=True)
def test_update_event_definition_with_taxonomy_entitlement(self, *mocks):
@@ -755,6 +944,21 @@ class TestCreateEventDefinitionsSql(SimpleTestCase):
assert "LEFT JOIN ee_enterpriseeventdefinition" in sql
assert "FULL OUTER JOIN" not in sql
+ def test_not_null_sort_keys_carry_no_nulls_clause(self):
+ # `name ASC NULLS FIRST` cannot use the unique index, whose default order is NULLS LAST.
+ sql = create_event_definitions_sql(
+ EventDefinitionType.EVENT, order_expressions=[("last_seen_at::date", "DESC"), ("name", "ASC")]
+ )
+ assert "last_seen_at::date DESC NULLS LAST" in sql
+ assert "name ASC" in sql
+ assert "name ASC NULLS" not in sql
+
+ def test_bounded_count_stops_at_the_cap(self):
+ sql = create_event_definitions_count_sql(EventDefinitionType.EVENT, bounded=True)
+ assert sql.startswith("SELECT count(*) FROM (SELECT 1")
+ # The ORDER BY keeps the planner on the project-scoped index instead of a sequential scan with LIMIT.
+ assert "ORDER BY posthog_eventdefinition.name LIMIT %(count_cap)s) bounded" in sql
+
class TestEventDefinitionListStatementTimeout(APIBaseTest):
def test_cancelled_list_query_returns_a_retryable_503(self) -> None:
diff --git a/posthog/taxonomy/definition_search.py b/posthog/taxonomy/definition_search.py
index 71d23e76cf4e..a55fa3a84c3f 100644
--- a/posthog/taxonomy/definition_search.py
+++ b/posthog/taxonomy/definition_search.py
@@ -4,6 +4,7 @@ from django.db import connections
from opentelemetry import trace
+from posthog.dataclasses import frozen
from posthog.utils import get_safe_cache, safe_cache_set
DefinitionTable = Literal["posthog_eventdefinition", "posthog_propertydefinition"]
@@ -14,9 +15,61 @@ SearchPlan = Literal["project_scan", "trigram"]
# are level for short terms; the largest projects have millions of rows and must keep the index.
PROJECT_SCAN_MAX_DEFINITIONS = 50_000
-# A project rarely crosses the threshold, and a stale answer only costs query time, never results.
+# Nothing indexes `last_seen_at`, so a recency-ordered event list sorts every definition of the project
+# for each page. Above this many definitions the list defaults to name order, which the unique index
+# returns directly. Below it, the sort stays cheap enough to keep the recency default.
+NAME_ORDER_MIN_DEFINITIONS = 100_000
+
+# A project rarely crosses a threshold, so one count serves it for a day.
+# A stale count costs query time for a project that has grown past a threshold.
+# For a project that has fallen back below one, the stale count also holds the bounded count and the
+# name order it selects, so the list reads as large until the key expires.
SEARCH_PLAN_CACHE_SECONDS = 24 * 60 * 60
+# An exact count over a large project walks its whole index range on every page load. Its list
+# endpoints stop counting here instead; small projects keep exact counts.
+LARGE_PROJECT_COUNT_CAP = 10_000
+
+
+@frozen
+class ProjectDefinitionScale:
+ """How a definition list reads one project's rows, decided from one cached bounded count."""
+
+ large: bool
+ orders_by_name: bool
+
+
+def project_definition_scale(
+ table: Literal["posthog_eventdefinition"], project_id: int, db_alias: str
+) -> ProjectDefinitionScale:
+ """The event list's size check, which counts past the name-order threshold in name order.
+
+ Property search keeps `search_plan` instead. On `posthog_propertydefinition` the name order reads the
+ heap in random order, so a cold count takes several times longer than the unordered one, and property
+ search needs only the `PROJECT_SCAN_MAX_DEFINITIONS` answer.
+ """
+ definition_count = _cached_definition_count(table, project_id, db_alias)
+ scale = ProjectDefinitionScale(
+ large=definition_count > PROJECT_SCAN_MAX_DEFINITIONS,
+ orders_by_name=definition_count > NAME_ORDER_MIN_DEFINITIONS,
+ )
+ # Every reader of the count records it, so a request tells which access path it took.
+ span = trace.get_current_span()
+ span.set_attribute("taxonomy_search_plan", "trigram" if scale.large else "project_scan")
+ span.set_attribute("taxonomy_definition_count", definition_count)
+ return scale
+
+
+def bounded_count_sql(source_sql: str, order_by: str) -> str:
+ """A count over `source_sql` (a FROM/WHERE fragment) that stops at %(count_cap)s rows.
+
+ `order_by` is the key of the index that serves the scope filter in `source_sql` (`name` on both
+ definition tables). Without it, Postgres may satisfy the LIMIT from a sequential scan of the whole
+ table when it estimates the project's rows to be dense enough; ordering by the index key keeps the
+ count on the project-scoped index. The order itself is irrelevant to the count.
+ """
+ return f"SELECT count(*) FROM (SELECT 1 {source_sql} ORDER BY {order_by} LIMIT %(count_cap)s) bounded"
+
def search_plan(table: DefinitionTable, project_id: int, db_alias: str) -> SearchPlan:
"""Picks how a `?search=` on a definitions table should reach the project's rows.
@@ -48,3 +101,25 @@ def _cached_search_plan(table: DefinitionTable, project_id: int, db_alias: str)
plan: SearchPlan = "trigram" if definition_count > PROJECT_SCAN_MAX_DEFINITIONS else "project_scan"
safe_cache_set(cache_key, plan, SEARCH_PLAN_CACHE_SECONDS)
return plan
+
+
+def _cached_definition_count(table: Literal["posthog_eventdefinition"], project_id: int, db_alias: str) -> int:
+ # The key is not `taxonomy_search_plan:*`, which holds a plan name, so a release that reads the count
+ # never reads an entry an earlier release wrote, in either direction.
+ cache_key = f"taxonomy_definition_count:{table}:{project_id}"
+ # A cache outage must only cost the count query, never the search itself.
+ cached = get_safe_cache(cache_key)
+ if cached is not None:
+ return cached
+
+ limit = max(PROJECT_SCAN_MAX_DEFINITIONS, NAME_ORDER_MIN_DEFINITIONS) + 1
+ with connections[db_alias].cursor() as cursor:
+ # Ordering by the index key keeps the probe on the project-scoped index; see `bounded_count_sql`.
+ cursor.execute(
+ f"SELECT count(*) FROM (SELECT 1 FROM {table} WHERE COALESCE(project_id, team_id) = %(project_id)s ORDER BY name LIMIT %(limit)s) bounded",
+ {"project_id": project_id, "limit": limit},
+ )
+ definition_count = cursor.fetchone()[0]
+
+ safe_cache_set(cache_key, definition_count, SEARCH_PLAN_CACHE_SECONDS)
+ return definition_count
diff --git a/posthog/taxonomy/test/test_definition_search.py b/posthog/taxonomy/test/test_definition_search.py
index 55a49df670ad..3bf5852f0820 100644
--- a/posthog/taxonomy/test/test_definition_search.py
+++ b/posthog/taxonomy/test/test_definition_search.py
@@ -1,3 +1,5 @@
+from collections.abc import Callable
+
from posthog.test.base import APIBaseTest, BaseTest
from unittest.mock import patch
@@ -5,11 +7,14 @@ from django.core.cache import cache
from django.db import DEFAULT_DB_ALIAS, connection
from django.test.utils import CaptureQueriesContext
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.sdk.trace.export import SimpleSpanProcessor
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from parameterized import parameterized
from posthog.models import EventDefinition, PropertyDefinition
from posthog.taxonomy import definition_search
-from posthog.taxonomy.definition_search import search_plan
+from posthog.taxonomy.definition_search import project_definition_scale, search_plan
class TestSearchPlan(BaseTest):
@@ -28,6 +33,9 @@ class TestSearchPlan(BaseTest):
def test_plan_follows_the_definition_count(self, _name: str, max_definitions: int, expected: str) -> None:
with patch.object(definition_search, "PROJECT_SCAN_MAX_DEFINITIONS", max_definitions):
assert search_plan("posthog_eventdefinition", self.team.pk, DEFAULT_DB_ALIAS) == expected
+ assert project_definition_scale("posthog_eventdefinition", self.team.pk, DEFAULT_DB_ALIAS).large is (
+ expected == "trigram"
+ )
def test_plan_is_cached_per_table_and_project(self) -> None:
search_plan("posthog_eventdefinition", self.team.pk, DEFAULT_DB_ALIAS)
@@ -44,6 +52,41 @@ class TestSearchPlan(BaseTest):
with patch.object(cache, failing_method, side_effect=ConnectionError("redis down")):
assert search_plan("posthog_eventdefinition", self.team.pk, DEFAULT_DB_ALIAS) == "project_scan"
+ @parameterized.expand(
+ [
+ ("property_search_keeps_the_unordered_count", search_plan, "posthog_propertydefinition", False, 50_001),
+ (
+ "event_list_counts_past_the_name_threshold",
+ project_definition_scale,
+ "posthog_eventdefinition",
+ True,
+ 100_001,
+ ),
+ ]
+ )
+ def test_size_check_statement_per_reader(
+ self, _name: str, check: Callable[..., object], table: str, ordered: bool, limit: int
+ ) -> None:
+ with CaptureQueriesContext(connection) as queries:
+ check(table, self.team.pk, DEFAULT_DB_ALIAS)
+
+ (size_check,) = [q["sql"] for q in queries.captured_queries if "bounded" in q["sql"]]
+ assert f"FROM {table} " in size_check
+ assert ("ORDER BY name" in size_check) is ordered
+ assert f"LIMIT {limit}" in size_check
+
+ @parameterized.expand([("search_plan", search_plan), ("project_definition_scale", project_definition_scale)])
+ def test_plan_is_recorded_on_the_request_span(self, _name: str, read_plan: Callable[..., object]) -> None:
+ exporter = InMemorySpanExporter()
+ provider = TracerProvider()
+ provider.add_span_processor(SimpleSpanProcessor(exporter))
+
+ with provider.get_tracer(__name__).start_as_current_span("definitions_list"):
+ read_plan("posthog_eventdefinition", self.team.pk, DEFAULT_DB_ALIAS)
+
+ attributes = exporter.get_finished_spans()[0].attributes or {}
+ assert attributes["taxonomy_search_plan"] == "project_scan"
+
class TestDefinitionEndpointsUseSearchPlan(APIBaseTest):
def setUp(self) -> None:
diff --git a/products/event_definitions/frontend/generated/api.schemas.ts b/products/event_definitions/frontend/generated/api.schemas.ts
index a1daf7cf710d..95517fcda318 100644
--- a/products/event_definitions/frontend/generated/api.schemas.ts
+++ b/products/event_definitions/frontend/generated/api.schemas.ts
@@ -125,6 +125,8 @@ export interface PaginatedEnterpriseEventDefinitionListApi {
/** @nullable */
previous?: string | null
results: EnterpriseEventDefinitionApi[]
+ /** True when `count` stopped at a cap, so it is a lower bound and `next` keeps paging past it. */
+ count_is_capped?: boolean
}
/**
@@ -289,6 +291,10 @@ export interface PrimaryPropertiesResponseApi {
}
export type EventDefinitionsListParams = {
+ /**
+ * `event_custom` keeps only names without a `$` prefix and `event_posthog` only names with one. Default `event`.
+ */
+ event_type?: EventDefinitionsListEventType
/**
* When true, omit events that have been explicitly hidden by a team admin (Enterprise only).
*/
@@ -297,8 +303,13 @@ export type EventDefinitionsListParams = {
* When true, omit events whose last ingested occurrence is older than 30 days. Events that have never been seen (`last_seen_at` is null) are kept so newly-defined events remain discoverable. Default false. If a search returns zero results with this filter on, retry with `exclude_stale=false` and tell the user the matches are stale.
*/
exclude_stale?: boolean
+ /**
+ * JSON-encoded list of event names to omit. The name matches the property definitions endpoint that shares it.
+ */
+ excluded_properties?: string
/**
* Number of results to return per page.
+ * @minimum 1
*/
limit?: number
/**
@@ -307,10 +318,36 @@ export type EventDefinitionsListParams = {
names?: string[]
/**
* The initial index from which to return the results.
+ * @minimum 0
*/
offset?: number
+ /**
+ * Sort keys, prefixed with `-` for descending. Default `-last_seen_at::date` then `name`. Projects with more than 100000 event definitions default to `name`, unless the request sets `search`, `exclude_stale`, `verified`, `names`, `tags` or `event_type=event_posthog`.
+ */
+ ordering?: string[]
+ /**
+ * Case-insensitive match on the event name. Every whitespace-separated term has to match.
+ */
+ search?: string
+ /**
+ * JSON-encoded list of tag names. Keeps events that carry any of them.
+ */
+ tags?: string
+ /**
+ * When true, keep only verified events and core PostHog events. When false, keep the rest (Enterprise only).
+ */
+ verified?: boolean
}
+export type EventDefinitionsListEventType =
+ (typeof EventDefinitionsListEventType)[keyof typeof EventDefinitionsListEventType]
+
+export const EventDefinitionsListEventType = {
+ Event: 'event',
+ EventCustom: 'event_custom',
+ EventPosthog: 'event_posthog',
+} as const
+
export type EventDefinitionsByNameRetrieveParams = {
/**
* The exact event name to look up
diff --git a/products/event_definitions/frontend/generated/api.ts b/products/event_definitions/frontend/generated/api.ts
index ae673660de00..b985069ec857 100644
--- a/products/event_definitions/frontend/generated/api.ts
+++ b/products/event_definitions/frontend/generated/api.ts
@@ -56,6 +56,9 @@ export const getEventDefinitionsListUrl = (projectId: string, params?: EventDefi
: `/api/projects/${projectId}/event_definitions/`
}
+/**
+ * List the event definitions of a project. On projects with more than 50000 event definitions, `count` stops at 10000 and `count_is_capped` is true, unless the request sets `search`, `exclude_stale`, `verified`, `names`, `tags` or `event_type=event_posthog`. Projects with more than 100000 event definitions also default to ordering by name under the same condition.
+ */
export const eventDefinitionsList = async (
projectId: string,
params?: EventDefinitionsListParams,
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6954602012b1..1c13a1ecc93a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -66092,6 +66092,8 @@ export namespace Schemas {
/** @nullable */
previous?: string | null;
results: EnterpriseEventDefinition[];
+ /** True when `count` stopped at a cap, so it is a lower bound and `next` keeps paging past it. */
+ count_is_capped?: boolean;
}
export interface PaginatedEnterprisePropertyDefinitionList {
@@ -114502,6 +114504,10 @@ export namespace Schemas {
};
export type EventDefinitionsListParams = {
+ /**
+ * `event_custom` keeps only names without a `$` prefix and `event_posthog` only names with one. Default `event`.
+ */
+ event_type?: EventDefinitionsListEventType;
/**
* When true, omit events that have been explicitly hidden by a team admin (Enterprise only).
*/
@@ -114510,8 +114516,13 @@ export namespace Schemas {
* When true, omit events whose last ingested occurrence is older than 30 days. Events that have never been seen (`last_seen_at` is null) are kept so newly-defined events remain discoverable. Default false. If a search returns zero results with this filter on, retry with `exclude_stale=false` and tell the user the matches are stale.
*/
exclude_stale?: boolean;
+ /**
+ * JSON-encoded list of event names to omit. The name matches the property definitions endpoint that shares it.
+ */
+ excluded_properties?: string;
/**
* Number of results to return per page.
+ * @minimum 1
*/
limit?: number;
/**
@@ -114520,10 +114531,36 @@ export namespace Schemas {
names?: string[];
/**
* The initial index from which to return the results.
+ * @minimum 0
*/
offset?: number;
+ /**
+ * Sort keys, prefixed with `-` for descending. Default `-last_seen_at::date` then `name`. Projects with more than 100000 event definitions default to `name`, unless the request sets `search`, `exclude_stale`, `verified`, `names`, `tags` or `event_type=event_posthog`.
+ */
+ ordering?: string[];
+ /**
+ * Case-insensitive match on the event name. Every whitespace-separated term has to match.
+ */
+ search?: string;
+ /**
+ * JSON-encoded list of tag names. Keeps events that carry any of them.
+ */
+ tags?: string;
+ /**
+ * When true, keep only verified events and core PostHog events. When false, keep the rest (Enterprise only).
+ */
+ verified?: boolean;
};
+ export type EventDefinitionsListEventType = typeof EventDefinitionsListEventType[keyof typeof EventDefinitionsListEventType];
+
+
+ export const EventDefinitionsListEventType = {
+ Event: 'event',
+ EventCustom: 'event_custom',
+ EventPosthog: 'event_posthog',
+ } as const;
+
export type EventDefinitionsByNameRetrieveParams = {
/**
* The exact event name to look up