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.

fix(devex): page error tracking and customer analytics with the shared kit (#126459)

Julian Bez7e656d3cdb5f
diff --git a/products/conversations/backend/api/ai_context.py b/products/conversations/backend/api/ai_context.py
index df96ff93cc57..e42c48ae5893 100644
--- a/products/conversations/backend/api/ai_context.py
+++ b/products/conversations/backend/api/ai_context.py
@@ -9,6 +9,7 @@ from rest_framework.request import Request
from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.paging import PageRequest
from posthog.permissions import TeamMemberLightManagementPermission
from products.access_control.backend.facade.user_access_control import UserAccessControl
@@ -31,15 +32,14 @@ class AIContextAccountPropertySerializer(serializers.Serializer):
def list_account_property_options(team_id: int, user_access_control: UserAccessControl) -> list[dict[str, object]]:
- page, _ = list_custom_property_definitions(
+ page = list_custom_property_definitions(
team_id,
- offset=0,
- limit=MAX_ACCOUNT_PROPERTY_OPTIONS,
+ page=PageRequest(limit=MAX_ACCOUNT_PROPERTY_OPTIONS),
user_access_control=user_access_control,
exclude_group_targets=True,
target_type=ACCOUNT_TARGET_TYPE,
)
- return [{"id": item.id, "name": item.name} for item in page if item.id is not None and item.name]
+ return [{"id": item.id, "name": item.name} for item in page.results if item.id is not None and item.name]
class AIContextAccountPropertiesViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.GenericViewSet):
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 090e7d82b7f3..e920a1ce0dc3 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -72,6 +72,8 @@ from posthog.models.group_type_mapping import get_group_types_for_project
from posthog.models.tag import tagify
from posthog.models.tagged_item import TaggedItem
from posthog.models.team import Team
+from posthog.paging import Page, PageRequest
+from posthog.queryset_paging import select_page
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.conversations.backend.facade.api import (
@@ -1136,14 +1138,10 @@ def _log_customer_profile_config_activity(
)
-def list_customer_profile_configs(
- team_id: int, offset: int, limit: int
-) -> tuple[list[contracts.CustomerProfileConfigView], int]:
- """Profile configs for the team. Returns ``(page, total_count)``."""
+def list_customer_profile_configs(team_id: int, *, page: PageRequest) -> Page[contracts.CustomerProfileConfigView]:
+ """One page of the team's profile configs."""
queryset = CustomerProfileConfig.objects.filter(team_id=team_id)
- total_count = queryset.count()
- page = queryset[offset : offset + limit]
- return [_to_customer_profile_config_view(c) for c in page], total_count
+ return select_page(queryset, page).map(_to_customer_profile_config_view)
def get_customer_profile_config(team_id: int, config_id: str) -> contracts.CustomerProfileConfigView | None:
@@ -1514,28 +1512,20 @@ def _definition_source_view(
return _to_custom_property_source_view(source, user_access_control, enrichment)
-def list_custom_property_definitions(
- team_id: int,
- offset: int,
- limit: int | None,
- *,
- user_access_control: "UserAccessControl",
- exclude_group_targets: bool = False,
- target_type: str | None = None,
-) -> tuple[list[contracts.CustomPropertyDefinitionView], int]:
- """Custom property definitions for the team, ordered by name. Returns ``(page, total_count)``.
-
- ``has_workflow_reference`` is included for every caller. ``references`` carries only workflow
- metadata the caller can read. ``exclude_group_targets`` hides group-target definitions from callers
- without ``group`` read authorization. ``target_type`` narrows the scan to one target, so a caller
- that wants a single target doesn't page over every definition to find it."""
- queryset = CustomPropertyDefinition.objects.for_team(team_id).select_related("source").order_by("name")
+def _custom_property_definitions_queryset(
+ team_id: int, exclude_group_targets: bool, target_type: str | None
+) -> QuerySet[CustomPropertyDefinition]:
+ queryset = CustomPropertyDefinition.objects.for_team(team_id).select_related("source").order_by("name", "pk")
if exclude_group_targets:
queryset = queryset.exclude(target_type=TargetType.GROUP.value)
if target_type is not None:
queryset = queryset.filter(target_type=target_type)
- total_count = queryset.count()
- page = list(queryset[offset : offset + limit] if limit is not None else queryset)
+ return queryset
+
+
+def _to_custom_property_definition_views(
+ team_id: int, page: list[CustomPropertyDefinition], user_access_control: "UserAccessControl"
+) -> list[contracts.CustomPropertyDefinitionView]:
workflow_references = _custom_property_references_by_definition_id(team_id)
references = filter_hog_flow_references_by_access_level(team_id, workflow_references, user_access_control)
sources: list[CustomPropertySource] = []
@@ -1554,7 +1544,38 @@ def list_custom_property_definitions(
enrichment_by_source_id=enrichment,
)
for d in page
- ], total_count
+ ]
+
+
+def list_custom_property_definitions(
+ team_id: int,
+ *,
+ page: PageRequest,
+ user_access_control: "UserAccessControl",
+ exclude_group_targets: bool = False,
+ target_type: str | None = None,
+) -> Page[contracts.CustomPropertyDefinitionView]:
+ """One page of the team's custom property definitions, ordered by name.
+
+ ``has_workflow_reference`` is included for every caller. ``references`` carries only workflow
+ metadata the caller can read. ``exclude_group_targets`` hides group-target definitions from callers
+ without ``group`` read authorization. ``target_type`` narrows the scan to one target, so a caller
+ that wants a single target doesn't page over every definition to find it."""
+ queryset = _custom_property_definitions_queryset(team_id, exclude_group_targets, target_type)
+ selected = select_page(queryset, page)
+ views = _to_custom_property_definition_views(team_id, selected.results, user_access_control)
+ return Page(results=views, count=selected.count)
+
+
+def list_all_custom_property_definitions(
+ team_id: int,
+ *,
+ user_access_control: "UserAccessControl",
+ exclude_group_targets: bool = False,
+) -> list[contracts.CustomPropertyDefinitionView]:
+ """All of the team's custom property definitions, ordered by name, for a caller that needs the whole list."""
+ queryset = _custom_property_definitions_queryset(team_id, exclude_group_targets, None)
+ return _to_custom_property_definition_views(team_id, list(queryset), user_access_control)
def get_custom_property_definition_target_type(team_id: int, definition_id: str) -> str | None:
@@ -2433,13 +2454,12 @@ def trigger_person_property_backfill(
def list_custom_property_sources(
team_id: int,
- offset: int,
- limit: int,
- user_access_control: "UserAccessControl | None" = None,
*,
+ page: PageRequest,
+ user_access_control: "UserAccessControl | None" = None,
exclude_group_targets: bool = False,
-) -> tuple[list[contracts.CustomPropertySourceView], int]:
- """Custom-property sources for the team, newest first. Returns ``(page, total_count)``. Warehouse
+) -> Page[contracts.CustomPropertySourceView]:
+ """One page of the team's custom-property sources, newest first. Warehouse
schedule/run enrichment per source is gated on the caller's warehouse-source viewer access.
``exclude_group_targets`` hides sources feeding a group-target definition from callers without
@@ -2447,13 +2467,13 @@ def list_custom_property_sources(
queryset = CustomPropertySource.objects.for_team(team_id).select_related("definition").order_by("-created_at")
if exclude_group_targets:
queryset = queryset.exclude(definition__target_type=TargetType.GROUP.value)
- total_count = queryset.count()
- page = list(queryset[offset : offset + limit])
- enrichment = _batch_source_enrichment(team_id, page, user_access_control)
- return [
- _to_custom_property_source_view(s, user_access_control, enrichment.get(s.id, _RESOLVE_ENRICHMENT_INLINE))
- for s in page
- ], total_count
+ selected = select_page(queryset, page)
+ enrichment = _batch_source_enrichment(team_id, selected.results, user_access_control)
+ return selected.map(
+ lambda s: _to_custom_property_source_view(
+ s, user_access_control, enrichment.get(s.id, _RESOLVE_ENRICHMENT_INLINE)
+ )
+ )
def get_custom_property_source(
@@ -2659,13 +2679,13 @@ def delete_custom_property_source(
def list_custom_property_sync_runs(
team_id: int,
source_id: str,
- offset: int,
- limit: int,
+ *,
+ page: PageRequest,
user_access_control: "UserAccessControl | None" = None,
include_temporal_urls: bool = False,
search: str | None = None,
-) -> tuple[list[contracts.CustomPropertySyncRunView], int]:
- """Warehouse-backed custom property sync runs for a source, newest first. Returns ``(page, total_count)``.
+) -> Page[contracts.CustomPropertySyncRunView]:
+ """One page of the warehouse-backed custom property sync runs of a source, newest first.
Scoped by team and source, so another team's or source's runs are never returned. Profile-source
histories require viewer access to their warehouse object; account-source histories are visible to
the same callers who can view the source."""
@@ -2689,10 +2709,9 @@ def list_custom_property_sync_runs(
),
)
queryset = queryset.order_by("-created_at")
- total_count = queryset.count()
- page = list(queryset[offset : offset + limit])
- _expire_stale_running_runs(team_id, page)
- return [_to_sync_run_view(run, include_temporal_url=include_temporal_urls) for run in page], total_count
+ selected = select_page(queryset, page)
+ _expire_stale_running_runs(team_id, selected.results)
+ return selected.map(lambda run: _to_sync_run_view(run, include_temporal_url=include_temporal_urls))
FeatureRequestValidationError = _feature_requests_logic.FeatureRequestValidationError
@@ -2742,15 +2761,13 @@ def list_feature_requests(
team_id: int,
user_access_control: "UserAccessControl",
filters: contracts.FeatureRequestListFilters,
- offset: int,
- limit: int,
-) -> tuple[list[contracts.FeatureRequestView], int]:
+ page: PageRequest,
+) -> Page[contracts.FeatureRequestView]:
return _feature_requests_logic.list_feature_requests(
team_id=team_id,
user_access_control=user_access_control,
filters=filters,
- offset=offset,
- limit=limit,
+ page=page,
)
@@ -3016,12 +3033,10 @@ def insight_belongs_to_team(team_id: int, insight_id: int) -> bool:
def list_customer_journeys(
- team_id: int, offset: int, limit: int, user_access_control: "UserAccessControl"
-) -> tuple[list[contracts.CustomerJourneyView], int]:
+ team_id: int, *, page: PageRequest, user_access_control: "UserAccessControl"
+) -> Page[contracts.CustomerJourneyView]:
queryset = user_access_control.filter_queryset_by_access_level(_customer_journeys_queryset(team_id))
- total_count = queryset.count()
- page = queryset[offset : offset + limit]
- return [_to_customer_journey_view(j) for j in page], total_count
+ return select_page(queryset, page).map(_to_customer_journey_view)
def get_customer_journey(
@@ -3846,8 +3861,7 @@ def list_accounts_for_view(
*,
team_id: int,
user_access_control: "UserAccessControl",
- offset: int,
- limit: int,
+ page: PageRequest,
search: str | None = None,
tags: list[str] | None = None,
all_roles_unassigned: bool = False,
@@ -3855,10 +3869,10 @@ def list_accounts_for_view(
include_ignored: bool = False,
ordering: str | None = None,
inactive_last: bool = False,
-) -> tuple[list[contracts.AccountDetails], int]:
+) -> Page[contracts.AccountDetails]:
"""The accounts list endpoint, behind the facade: team + object-level access filtering,
the search / tags / unassigned / ordering query filters, notebook + tag prefetching, and
- pagination. Returns ``(page, total_count)``. ``tags``/``ordering`` are pre-validated by
+ pagination. ``tags``/``ordering`` are pre-validated by
the view; an empty ``tags`` list is treated as "no tag filter" (matches old behavior)."""
queryset = _accounts_queryset(team_id, user_access_control).prefetch_related(
Prefetch("notebooks", queryset=ResourceNotebook.objects.select_related("notebook")),
@@ -3894,10 +3908,7 @@ def list_accounts_for_view(
)
order_fields.insert(0, "is_inactive")
queryset = queryset.order_by(*order_fields)
-
- total_count = queryset.count()
- page = list(queryset[offset : offset + limit])
- return [_to_account_details(a) for a in page], total_count
+ return select_page(queryset, page).map(_to_account_details)
def get_account_for_view(
@@ -4388,12 +4399,11 @@ def list_account_channel_summaries(
account_id: str,
user_access_control: "UserAccessControl",
*,
- offset: int,
- limit: int,
-) -> tuple[list[contracts.AccountChannelSummaryView], int] | None:
- """Stored Slack channel summaries for an accessible account, newest period first.
+ page: PageRequest,
+) -> Page[contracts.AccountChannelSummaryView] | None:
+ """One page of the stored Slack channel summaries of an accessible account, newest period first.
- Returns ``(page, total_count)``, or None when the parent account isn't accessible (→ 404)."""
+ None when the parent account isn't accessible (→ 404)."""
if get_accessible_account_id(team_id, account_id, user_access_control) is None:
return None
queryset = (
@@ -4401,8 +4411,7 @@ def list_account_channel_summaries(
.filter(account_id=account_id)
.order_by("-period_start", "-generated_at")
)
- total_count = queryset.count()
- return [_to_channel_summary_view(s) for s in queryset[offset : offset + limit]], total_count
+ return select_page(queryset, page).map(_to_channel_summary_view)
def _to_channel_summary_view(summary: AccountChannelSummary) -> contracts.AccountChannelSummaryView:
@@ -4560,9 +4569,8 @@ def get_account_support_ticket_messages(
ticket_id: str,
user_access_control: "UserAccessControl",
*,
- offset: int = 0,
- limit: int = 50,
-) -> tuple[list[SupportTicketMessage], int] | None:
+ page: PageRequest,
+) -> Page[SupportTicketMessage] | None:
if get_accessible_account_id(team_id, account_id, user_access_control) is None:
return None
if not user_access_control.check_access_level_for_resource("ticket", "viewer"):
@@ -4570,14 +4578,18 @@ def get_account_support_ticket_messages(
account = _resolve_account(team_id, account_id=account_id)
if account is None or not account.external_id:
return None
- return list_account_ticket_messages(
+ result = list_account_ticket_messages(
team_id,
account.external_id,
ticket_id,
user_access_control,
- offset=offset,
- limit=limit,
+ offset=page.offset,
+ limit=page.limit,
)
+ if result is None:
+ return None
+ messages, count = result
+ return Page(results=messages, count=count)
def get_account_email_threads(
@@ -4585,14 +4597,14 @@ def get_account_email_threads(
account_id: str,
user_access_control: "UserAccessControl",
*,
- offset: int = 0,
- limit: int = 50,
-) -> tuple[list[AccountEmailThreadSummary], int] | None:
+ page: PageRequest,
+) -> Page[AccountEmailThreadSummary] | None:
if get_accessible_account_id(team_id, account_id, user_access_control) is None:
return None
if not user_access_control.check_access_level_for_resource("ticket", "viewer"):
raise ResourceForbiddenError()
- return list_account_email_threads(team_id, account_id, offset=offset, limit=limit)
+ threads, count = list_account_email_threads(team_id, account_id, offset=page.offset, limit=page.limit)
+ return Page(results=threads, count=count)
def get_account_email_thread_messages(
@@ -4601,14 +4613,17 @@ def get_account_email_thread_messages(
thread_id: str,
user_access_control: "UserAccessControl",
*,
- offset: int = 0,
- limit: int = 50,
-) -> tuple[list[AccountEmailThreadMessage], int] | None:
+ page: PageRequest,
+) -> Page[AccountEmailThreadMessage] | None:
if get_accessible_account_id(team_id, account_id, user_access_control) is None:
return None
if not user_access_control.check_access_level_for_resource("ticket", "viewer"):
raise ResourceForbiddenError()
- return list_account_email_thread_messages(team_id, account_id, thread_id, offset=offset, limit=limit)
+ result = list_account_email_thread_messages(team_id, account_id, thread_id, offset=page.offset, limit=page.limit)
+ if result is None:
+ return None
+ messages, count = result
+ return Page(results=messages, count=count)
AccountTrackRuleValidationError = _account_track_rules_logic.AccountTrackRuleValidationError
@@ -4647,10 +4662,8 @@ def preview_account_track_rules(
return _account_track_rules_logic.preview_account_track_rules(team_id, raw_config)
-def list_account_track_rule_runs(
- team_id: int, *, offset: int, limit: int
-) -> tuple[list[contracts.AccountTrackRuleRunView], int]:
- return _account_track_rules_logic.list_account_track_rule_runs(team_id, offset=offset, limit=limit)
+def list_account_track_rule_runs(team_id: int, *, page: PageRequest) -> Page[contracts.AccountTrackRuleRunView]:
+ return _account_track_rules_logic.list_account_track_rule_runs(team_id, page=page)
def trigger_account_track_rule_run(
@@ -4853,10 +4866,9 @@ def list_account_meetings(
account_id: str,
user_access_control: "UserAccessControl",
*,
- offset: int = 0,
- limit: int = 100,
+ page: PageRequest,
search: str | None = None,
-) -> tuple[list[contracts.MeetingView], int] | None:
+) -> Page[contracts.MeetingView] | None:
"""Synced calendar meetings for an accessible account, newest first, optionally
filtered by ``search`` (title or attendee email/name). A recurring series shows each
past occurrence but only its next upcoming one. None when the account isn't
@@ -4882,8 +4894,8 @@ def list_account_meetings(
| Q(participants__email__icontains=search)
| Q(participants__display_name__icontains=search)
).distinct()
- count = queryset.count()
- meetings = list(queryset.order_by("-start_time").prefetch_related("participants")[offset : offset + limit])
+ selected = select_page(queryset.order_by("-start_time").prefetch_related("participants"), page)
+ meetings = selected.results
from products.customer_analytics.backend.logic.gong import ( # noqa: PLC0415 — keeps HogQL off the facade import path
get_gong_urls_by_meeting_id,
@@ -4917,7 +4929,7 @@ def list_account_meetings(
)
for meeting in meetings
]
- return views, count
+ return Page(results=views, count=selected.count)
def list_account_notebooks(
@@ -4942,18 +4954,17 @@ def list_account_notes_for_view(
*,
team_id: int,
user_access_control: "UserAccessControl",
- offset: int,
- limit: int,
+ page: PageRequest,
search: str | None = None,
account_id: UUID | str | None = None,
created_by_ids: list[int] | None = None,
assigned_to_ids: list[int] | None = None,
-) -> tuple[list[contracts.AccountNoteView], int]:
+) -> Page[contracts.AccountNoteView]:
"""Team-wide account notes (internal notebooks linked to accounts), newest-modified first,
restricted to accounts the caller can read. ``search`` matches note title/content (full-text)
and account name (substring). ``account_id`` narrows to one account, ``created_by_ids`` to
notes authored by the given users, ``assigned_to_ids`` to notes on accounts where one of the
- given users actively holds a relationship. Returns ``(page, total_count)``."""
+ given users actively holds a relationship."""
accounts = _accounts_queryset(team_id, user_access_control)
if assigned_to_ids:
# "Assigned to" means any active relationship, matching the accounts list HogQL
@@ -4970,10 +4981,10 @@ def list_account_notes_for_view(
account_id=account_id,
created_by_ids=created_by_ids,
search=search,
- offset=offset,
- limit=limit,
+ offset=page.offset,
+ limit=page.limit,
)
- return [
+ views = [
contracts.AccountNoteView(
short_id=note.short_id,
title=note.title,
@@ -4984,7 +4995,8 @@ def list_account_notes_for_view(
created_by=_notebook_user_to_basic_info(note.created_by),
)
for note in notes
- ], count
+ ]
+ return Page(results=views, count=count)
def get_account_notebook(
@@ -5253,12 +5265,15 @@ def _to_account_relationship(relationship: AccountRelationship) -> contracts.Acc
def list_account_relationship_definitions(
- team_id: int, offset: int = 0, limit: int | None = 100
-) -> tuple[list[contracts.AccountRelationshipDefinition], int]:
+ team_id: int, *, page: PageRequest
+) -> Page[contracts.AccountRelationshipDefinition]:
queryset = AccountRelationshipDefinition.objects.for_team(team_id).order_by("name")
- total_count = queryset.count()
- page = queryset[offset : offset + limit] if limit is not None else queryset
- return [_to_account_relationship_definition(definition) for definition in page], total_count
+ return select_page(queryset, page).map(_to_account_relationship_definition)
+
+
+def list_all_account_relationship_definitions(team_id: int) -> list[contracts.AccountRelationshipDefinition]:
+ queryset = AccountRelationshipDefinition.objects.for_team(team_id).order_by("name", "pk")
+ return [_to_account_relationship_definition(definition) for definition in queryset]
def create_account_relationship_definition(
@@ -5564,17 +5579,15 @@ def list_customer_tasks(
team_id: int,
user_access_control: "UserAccessControl",
filters: contracts.CustomerTaskListFilters,
- offset: int,
- limit: int,
-) -> tuple[list[contracts.CustomerTaskView], int]:
- tasks, count = _customer_tasks_logic.list_customer_tasks(
+ page: PageRequest,
+) -> Page[contracts.CustomerTaskView]:
+ tasks = _customer_tasks_logic.list_customer_tasks(
team_id=team_id,
user_access_control=user_access_control,
filters=filters,
- offset=offset,
- limit=limit,
+ page=page,
)
- return [_to_customer_task_view(task, user_access_control) for task in tasks], count
+ return tasks.map(lambda task: _to_customer_task_view(task, user_access_control))
def get_customer_task(
@@ -5681,21 +5694,18 @@ def list_customer_task_activities(
team_id: int,
task_id: UUID | str,
user_access_control: "UserAccessControl",
- offset: int,
- limit: int,
-) -> tuple[list[contracts.CustomerTaskActivityView], int] | None:
+ page: PageRequest,
+) -> Page[contracts.CustomerTaskActivityView] | None:
result = _customer_tasks_logic.list_customer_task_activities(
team_id=team_id,
task_id=task_id,
user_access_control=user_access_control,
- offset=offset,
- limit=limit,
+ page=page,
)
if result is None:
return None
- return [
- _to_customer_task_activity_view(activity, result.visible_account_ids) for activity in result.activities
- ], result.total_count
+ visible_account_ids = result.visible_account_ids
+ return result.activities.map(lambda activity: _to_customer_task_activity_view(activity, visible_account_ids))
# --- EventStream ---
@@ -5904,11 +5914,8 @@ def _announcements_queryset(team_id: int):
)
-def list_announcements(team_id: int, offset: int, limit: int) -> tuple[list[contracts.AnnouncementView], int]:
- queryset = _announcements_queryset(team_id)
- total_count = queryset.count()
- page = queryset[offset : offset + limit]
- return [_to_announcement_view(a) for a in page], total_count
+def list_announcements(team_id: int, *, page: PageRequest) -> Page[contracts.AnnouncementView]:
+ return select_page(_announcements_queryset(team_id), page).map(_to_announcement_view)
def get_announcement(team_id: int, short_id: str) -> contracts.AnnouncementView | None:
diff --git a/products/customer_analytics/backend/facade/custom_property_source_person_test.py b/products/customer_analytics/backend/facade/custom_property_source_person_test.py
index 7cef8f6c9ff1..8c77d39d0606 100644
--- a/products/customer_analytics/backend/facade/custom_property_source_person_test.py
+++ b/products/customer_analytics/backend/facade/custom_property_source_person_test.py
@@ -9,6 +9,7 @@ from django.utils import timezone
from parameterized import parameterized
from posthog.models import PropertyDefinition
+from posthog.paging import PageRequest
from products.customer_analytics.backend.facade import api
from products.customer_analytics.backend.models import CustomPropertySource, CustomPropertySyncRun, TargetType
@@ -514,7 +515,7 @@ class TestPersonCustomPropertySource(TeamScopedTestMixin, APIBaseTest):
source = self._create(user_access_control=self._uac(allowed=True))
with self.assertRaises(api.ResourceForbiddenError):
api.list_custom_property_sync_runs(
- self.team.id, source.id, offset=0, limit=10, user_access_control=self._uac(allowed=False)
+ self.team.id, source.id, page=PageRequest(limit=10), user_access_control=self._uac(allowed=False)
)
@patch("products.warehouse_sources.backend.facade.temporal.trigger_schema_sync")
@@ -587,9 +588,9 @@ class TestPersonCustomPropertySource(TeamScopedTestMixin, APIBaseTest):
started_at=timezone.now() - age,
)
- views, _ = api.list_custom_property_sync_runs(
- self.team.id, source.id, offset=0, limit=10, user_access_control=self._uac(allowed=True)
- )
+ views = api.list_custom_property_sync_runs(
+ self.team.id, source.id, page=PageRequest(limit=10), user_access_control=self._uac(allowed=True)
+ ).results
assert views[0].status == expected_status
run.refresh_from_db()
@@ -609,11 +610,15 @@ class TestPersonCustomPropertySource(TeamScopedTestMixin, APIBaseTest):
started_at=timezone.now() - (api.STALE_RUNNING_RUN_AFTER + timedelta(minutes=1)),
)
- api.list_custom_property_sources(self.team.id, offset=0, limit=10, user_access_control=self._uac(allowed=False))
+ api.list_custom_property_sources(
+ self.team.id, page=PageRequest(limit=10), user_access_control=self._uac(allowed=False)
+ )
run.refresh_from_db()
assert run.status == "running"
- api.list_custom_property_sources(self.team.id, offset=0, limit=10, user_access_control=self._uac(allowed=True))
+ api.list_custom_property_sources(
+ self.team.id, page=PageRequest(limit=10), user_access_control=self._uac(allowed=True)
+ )
run.refresh_from_db()
assert run.status == "failed"
diff --git a/products/customer_analytics/backend/logic/account_property_runs_test.py b/products/customer_analytics/backend/logic/account_property_runs_test.py
index 53c6fcb19057..b302ed48e598 100644
--- a/products/customer_analytics/backend/logic/account_property_runs_test.py
+++ b/products/customer_analytics/backend/logic/account_property_runs_test.py
@@ -10,6 +10,8 @@ from django.utils import timezone
from parameterized import parameterized
+from posthog.paging import PageRequest
+
from products.customer_analytics.backend.facade import api
from products.customer_analytics.backend.logic.account_property_runs import (
AccountPropertySyncRunContext,
@@ -92,13 +94,9 @@ class TestAccountPropertyRuns(TeamScopedTestMixin, BaseTest):
assert {str(run.workflow_run_id) for run in runs} == {"00000000-0000-4000-8000-000000000001"}
assert {run.attempt for run in runs} == {0}
- views, total_count = api.list_custom_property_sync_runs(
- self.team.id,
- str(self.source.id),
- offset=0,
- limit=10,
- )
- assert total_count == 2
+ runs_page = api.list_custom_property_sync_runs(self.team.id, str(self.source.id), page=PageRequest(limit=10))
+ views = runs_page.results
+ assert runs_page.count == 2
assert {view.account_segment for view in views} == {"tracked", "ignored"}
assert {view.sync_phase for view in views} == {"staging"}
assert {view.job_id for view in views} == {"job-1"}
@@ -106,26 +104,24 @@ class TestAccountPropertyRuns(TeamScopedTestMixin, BaseTest):
assert {view.workflow_run_id for view in views} == {None}
assert {view.temporal_url for view in views} == {None}
- staff_views, _ = api.list_custom_property_sync_runs(
+ staff_views = api.list_custom_property_sync_runs(
self.team.id,
str(self.source.id),
- offset=0,
- limit=10,
+ page=PageRequest(limit=10),
include_temporal_urls=True,
- )
+ ).results
assert {view.workflow_id for view in staff_views} == {"stage-workflow-job-1"}
assert {str(view.workflow_run_id) for view in staff_views} == {"00000000-0000-4000-8000-000000000001"}
assert all(view.temporal_url is not None for view in staff_views)
- search_views, search_count = api.list_custom_property_sync_runs(
+ search_page = api.list_custom_property_sync_runs(
self.team.id,
str(self.source.id),
- offset=0,
- limit=20,
+ page=PageRequest(limit=20),
search="ignored",
)
- assert search_count == 1
- assert [view.account_segment for view in search_views] == ["ignored"]
+ assert search_page.count == 1
+ assert [view.account_segment for view in search_page.results] == ["ignored"]
def test_phase_updates_record_retries_without_regressing_the_sibling(self) -> None:
self._start_runs()
@@ -230,12 +226,9 @@ class TestAccountPropertyRuns(TeamScopedTestMixin, BaseTest):
started_at=timezone.now() - timedelta(hours=7)
)
- views, _ = api.list_custom_property_sync_runs(
- self.team.id,
- str(self.source.id),
- offset=0,
- limit=10,
- )
+ views = api.list_custom_property_sync_runs(
+ self.team.id, str(self.source.id), page=PageRequest(limit=10)
+ ).results
assert {view.status for view in views} == {"running"}
diff --git a/products/customer_analytics/backend/logic/account_track_rules.py b/products/customer_analytics/backend/logic/account_track_rules.py
index 29dfd3be8fbe..b906153c7ed9 100644
--- a/products/customer_analytics/backend/logic/account_track_rules.py
+++ b/products/customer_analytics/backend/logic/account_track_rules.py
@@ -18,6 +18,8 @@ from posthog.exceptions_capture import capture_exception
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
from posthog.models.team import Team
from posthog.models.user import User
+from posthog.paging import Page, PageRequest
+from posthog.queryset_paging import select_page
from products.customer_analytics.backend.facade import contracts
from products.customer_analytics.backend.logic.account_filters import (
@@ -545,11 +547,9 @@ def to_run_view(run: AccountTrackRuleRun) -> contracts.AccountTrackRuleRunView:
)
-def list_account_track_rule_runs(
- team_id: int, *, offset: int, limit: int
-) -> tuple[list[contracts.AccountTrackRuleRunView], int]:
+def list_account_track_rule_runs(team_id: int, *, page: PageRequest) -> Page[contracts.AccountTrackRuleRunView]:
queryset = AccountTrackRuleRun.objects.for_team(team_id).order_by("-created_at")
- return [to_run_view(run) for run in queryset[offset : offset + limit]], queryset.count()
+ return select_page(queryset, page).map(to_run_view)
def list_enabled_account_track_rule_configs(
diff --git a/products/customer_analytics/backend/logic/customer_tasks.py b/products/customer_analytics/backend/logic/customer_tasks.py
index 2456b25b25b5..fdaf198f660e 100644
--- a/products/customer_analytics/backend/logic/customer_tasks.py
+++ b/products/customer_analytics/backend/logic/customer_tasks.py
@@ -14,6 +14,8 @@ from django.utils import timezone
from posthog.dataclasses import frozen
from posthog.models import OrganizationMembership, Team, User
+from posthog.paging import Page, PageRequest
+from posthog.queryset_paging import select_page
from products.access_control.backend.facade import (
api as access_control_api,
@@ -39,8 +41,7 @@ CUSTOMER_TASK_STATUS_CHOICES = CustomerTaskStatus.choices
@frozen
class _CustomerTaskActivityPage:
- activities: list[CustomerTaskActivity]
- total_count: int
+ activities: Page[CustomerTaskActivity]
visible_account_ids: frozenset[str]
@@ -346,9 +347,8 @@ def list_customer_tasks(
team_id: int,
user_access_control: UserAccessControl,
filters: contracts.CustomerTaskListFilters,
- offset: int,
- limit: int,
-) -> tuple[list[CustomerTask], int]:
+ page: PageRequest,
+) -> Page[CustomerTask]:
queryset = _visible_task_queryset(team_id, user_access_control)
if filters.search:
queryset = queryset.filter(Q(name__icontains=filters.search) | Q(description__icontains=filters.search))
@@ -381,8 +381,7 @@ def list_customer_tasks(
queryset = queryset.order_by(F("due_at").asc(nulls_last=True), "-updated_at", "id")
else:
queryset = _apply_ordering(queryset, filters.ordering)
- count = queryset.count()
- return list(queryset[offset : offset + limit]), count
+ return select_page(queryset, page)
def get_customer_task(
@@ -770,7 +769,7 @@ def _list_visible_historical_account_ids(
def list_customer_task_activities(
- *, team_id: int, task_id: UUID | str, user_access_control: UserAccessControl, offset: int, limit: int
+ *, team_id: int, task_id: UUID | str, user_access_control: UserAccessControl, page: PageRequest
) -> _CustomerTaskActivityPage | None:
task = get_customer_task(team_id=team_id, task_id=task_id, user_access_control=user_access_control)
if task is None or not can_access_customer_task_object(
@@ -778,18 +777,13 @@ def list_customer_task_activities(
):
return None
queryset = CustomerTaskActivity.objects.for_team(team_id).filter(task_id=task.id).select_related("actor")
- count = queryset.count()
- activities = list(queryset.order_by("-created_at", "-id")[offset : offset + limit])
+ activities = select_page(queryset.order_by("-created_at", "-id"), page)
visible_account_ids = _list_visible_historical_account_ids(
team_id=team_id,
- activities=activities,
+ activities=activities.results,
user_access_control=user_access_control,
)
- return _CustomerTaskActivityPage(
- activities=activities,
- total_count=count,
- visible_account_ids=visible_account_ids,
- )
+ return _CustomerTaskActivityPage(activities=activities, visible_account_ids=visible_account_ids)
def can_access_customer_task_object(*, task: CustomerTask, user_access_control: UserAccessControl, write: bool) -> bool:
diff --git a/products/customer_analytics/backend/logic/feature_requests.py b/products/customer_analytics/backend/logic/feature_requests.py
index b345430e492e..49d328da8002 100644
--- a/products/customer_analytics/backend/logic/feature_requests.py
+++ b/products/customer_analytics/backend/logic/feature_requests.py
@@ -24,6 +24,8 @@ from django.utils import timezone
from posthog.dataclasses import frozen
from posthog.models import UploadedMedia, User
+from posthog.paging import Page, PageRequest
+from posthog.queryset_paging import select_page
from products.customer_analytics.backend.facade import contracts
from products.customer_analytics.backend.models import (
@@ -640,9 +642,8 @@ def list_feature_requests(
team_id: int,
user_access_control: "UserAccessControl",
filters: contracts.FeatureRequestListFilters,
- offset: int,
- limit: int,
-) -> tuple[list[contracts.FeatureRequestView], int]:
+ page: PageRequest,
+) -> Page[contracts.FeatureRequestView]:
account_filter_ids: tuple[UUID, ...] = ()
if filters.account_ids:
account_filter_ids = tuple(
@@ -657,11 +658,9 @@ def list_feature_requests(
account_filter_ids,
)
queryset = _apply_ordering(queryset, filters.ordering, accessible_account_ids)
- total_count = queryset.count()
- return [
- _to_feature_request_view(item, user_access_control=user_access_control, include_evidence=False)
- for item in queryset[offset : offset + limit]
- ], total_count
+ return select_page(queryset, page).map(
+ lambda item: _to_feature_request_view(item, user_access_control=user_access_control, include_evidence=False)
+ )
def get_feature_request(
diff --git a/products/customer_analytics/backend/presentation/views/announcements.py b/products/customer_analytics/backend/presentation/views/announcements.py
index be56d6719b87..25f685a2e989 100644
--- a/products/customer_analytics/backend/presentation/views/announcements.py
+++ b/products/customer_analytics/backend/presentation/views/announcements.py
@@ -9,6 +9,7 @@ from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework_dataclasses.serializers import DataclassSerializer
+from posthog.api.pagination import FacadeLimitOffsetPagination, facade_page_response
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.event_usage import report_user_action
@@ -21,7 +22,6 @@ from products.customer_analytics.backend.facade.contracts import (
AnnouncementValidationError,
AnnouncementView,
)
-from products.customer_analytics.backend.presentation.views.views import _FacadePaginationMixin
# Duplicated from the model TextChoices so this module imports no product models;
# ENUM_NAME_OVERRIDES matches the generated enums against these by value.
@@ -163,7 +163,6 @@ class AnnouncementSerializer(DataclassSerializer):
class AnnouncementViewSet(
TeamAndOrgViewSetMixin,
- _FacadePaginationMixin,
mixins.CreateModelMixin,
viewsets.ReadOnlyModelViewSet,
):
@@ -171,12 +170,13 @@ class AnnouncementViewSet(
serializer_class = AnnouncementSerializer
queryset = None # data is reached through the facade; declared for router/schema only
lookup_field = "short_id"
+ pagination_class = FacadeLimitOffsetPagination
def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
- return self._paginate_via_facade(
- request,
- lambda offset, limit: api.list_announcements(self.team_id, offset=offset, limit=limit),
- AnnouncementSerializer,
+ return facade_page_response(
+ self,
+ lambda page: api.list_announcements(self.team_id, page=page),
+ serializer_class=AnnouncementSerializer,
)
def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:
diff --git a/products/customer_analytics/backend/presentation/views/customer_tasks.py b/products/customer_analytics/backend/presentation/views/customer_tasks.py
index 87dad1b49710..b5dfd07365a5 100644
--- a/products/customer_analytics/backend/presentation/views/customer_tasks.py
+++ b/products/customer_analytics/backend/presentation/views/customer_tasks.py
@@ -8,17 +8,18 @@ from drf_spectacular.helpers import forced_singular_serializer
from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
-from rest_framework.exceptions import ValidationError
-from rest_framework.pagination import LimitOffsetPagination
+from rest_framework.exceptions import NotFound, ValidationError
from rest_framework.permissions import BasePermission
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView
from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.pagination import FacadeLimitOffsetPagination
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.models import Team, User
from posthog.models.integer_field_bounds import INTEGER_FIELD_MAX
+from posthog.paging import Page, PageRequest
from posthog.permissions import PostHogFeatureFlagPermission, get_authenticator_scoped_team_ids
from products.access_control.backend.facade.user_access_control import UserAccessControl
@@ -315,20 +316,19 @@ class CustomerTaskActivityPageSerializer(serializers.Serializer):
results = CustomerTaskActivitySerializer(many=True, read_only=True, help_text="Activities in this page.")
-def _paginated_response(
- request: Request,
- page: list[Any],
- count: int,
- limit: int,
- offset: int,
- serializer_class: type[serializers.Serializer],
-) -> Response:
- paginator = LimitOffsetPagination()
- paginator.request = request
- paginator.limit = limit
- paginator.offset = offset
- paginator.count = count
- return paginator.get_paginated_response(serializer_class(instance=page, many=True).data)
+class CustomerTaskPagination(FacadeLimitOffsetPagination):
+ """Pages with the limit and offset that the list query serializers validated.
+
+ The serializers own the bounds and return a 400 for a limit outside 1 to 100. The base class
+ parses the raw query params again, which turns an accepted value such as `limit=5.0` into the
+ default limit.
+ """
+
+ def get_limit(self, request: Request) -> int:
+ return cast(ValidatedRequest, request).validated_query_data["limit"]
+
+ def get_offset(self, request: Request) -> int:
+ return cast(ValidatedRequest, request).validated_query_data["offset"]
class CustomerTaskCanonicalTeamAccessPermission(BasePermission):
@@ -387,25 +387,29 @@ class CustomerTaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
data = request.validated_query_data
assigned_to = data.get("assigned_to")
assigned_role_id = _parse_assigned_role_id(assigned_to)
- page, count = api.list_customer_tasks(
- team_id=self.canonical_team_id,
- user_access_control=self.user_access_control,
- filters=contracts.CustomerTaskListFilters(
- search=data.get("search", "").strip() or None,
- account_id=data.get("account_id"),
- assigned_to=None if assigned_role_id else assigned_to,
- assigned_role_id=assigned_role_id,
- statuses=data.get("statuses", ()),
- archive_state=data["archive_state"],
- due_after=data.get("due_after"),
- due_before=data.get("due_before"),
- has_due_at=data.get("has_due_at") if "has_due_at" in request.query_params else None,
- ordering=data.get("ordering"),
+ filters = contracts.CustomerTaskListFilters(
+ search=data.get("search", "").strip() or None,
+ account_id=data.get("account_id"),
+ assigned_to=None if assigned_role_id else assigned_to,
+ assigned_role_id=assigned_role_id,
+ statuses=data.get("statuses", ()),
+ archive_state=data["archive_state"],
+ due_after=data.get("due_after"),
+ due_before=data.get("due_before"),
+ has_due_at=data.get("has_due_at") if "has_due_at" in request.query_params else None,
+ ordering=data.get("ordering"),
+ )
+ return CustomerTaskPagination().get_paginated_facade_response(
+ request,
+ self,
+ lambda page: api.list_customer_tasks(
+ team_id=self.canonical_team_id,
+ user_access_control=self.user_access_control,
+ filters=filters,
+ page=page,
),
- offset=data["offset"],
- limit=data["limit"],
+ serializer_class=CustomerTaskSerializer,
)
- return _paginated_response(request, page, count, data["limit"], data["offset"], CustomerTaskSerializer)
@extend_schema(responses={200: CustomerTaskSerializer, 404: OpenApiResponse(description="Task not found.")})
def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:
@@ -528,18 +532,20 @@ class CustomerTaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
@action(detail=True, methods=["get"])
@validated_request(query_serializer=CustomerTaskActivityQuerySerializer)
def activities(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:
- data = request.validated_query_data
- result = api.list_customer_task_activities(
- team_id=self.canonical_team_id,
- task_id=self.kwargs["pk"],
- user_access_control=self.user_access_control,
- offset=data["offset"],
- limit=data["limit"],
+ def fetch(page: PageRequest) -> Page[contracts.CustomerTaskActivityView]:
+ result = api.list_customer_task_activities(
+ team_id=self.canonical_team_id,
+ task_id=self.kwargs["pk"],
+ user_access_control=self.user_access_control,
+ page=page,
+ )
+ if result is None:
+ raise NotFound("Task not found.")
+ return result
+
+ return CustomerTaskPagination().get_paginated_facade_response(
+ request, self, fetch, serializer_class=CustomerTaskActivitySerializer
)
- if result is None:
- return Response({"detail": "Task not found."}, status=status.HTTP_404_NOT_FOUND)
- page, count = result
- return _paginated_response(request, page, count, data["limit"], data["offset"], CustomerTaskActivitySerializer)
def handle_exception(self, exc: Exception) -> Response:
if isinstance(exc, contracts.CustomerTaskAccountNotFound):
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index 1eba7d332741..3cf82d58e6a3 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -14,7 +14,7 @@ from __future__ import annotations
import json
import builtins
-from collections.abc import Callable, Sequence
+from collections.abc import Sequence
from dataclasses import asdict
from functools import cached_property
from typing import Any, Protocol, cast
@@ -29,8 +29,7 @@ from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
from rest_framework import mixins, status, viewsets
from rest_framework.decorators import action
-from rest_framework.exceptions import PermissionDenied, ValidationError
-from rest_framework.pagination import LimitOffsetPagination
+from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
from rest_framework.permissions import BasePermission, IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
@@ -38,6 +37,7 @@ from rest_framework.serializers import BaseSerializer
from rest_framework.throttling import UserRateThrottle
from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.pagination import FacadeLimitOffsetPagination, facade_page_response
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.tagged_item import TaggedItemViewSetMixin
from posthog.auth import SessionAuthentication, is_mcp_request
@@ -47,6 +47,7 @@ from posthog.helpers.impersonation import is_impersonated
from posthog.models import OrganizationMembership
from posthog.models.team import Team
from posthog.models.user import User
+from posthog.paging import Page, PageRequest
from posthog.permissions import (
AccessControlPermission,
APIScopePermission,
@@ -210,30 +211,11 @@ _ACCOUNT_ID_PARAM = OpenApiParameter(
# NOTE: deliberately no class docstring — a docstring here is inherited as the ViewSets'
# ``__doc__`` and drf-spectacular would surface it as every operation's description (the
# model-backed viewsets had none), drifting the generated clients.
-class AccountEmailThreadMessagePagination(LimitOffsetPagination):
+class AccountEmailThreadMessagePagination(FacadeLimitOffsetPagination):
default_limit = 50
max_limit = 200
-class _FacadePaginationMixin:
- # Drives the standard ``LimitOffsetPagination`` envelope from a facade ``(page, count)``
- # result. The facade does the slicing (offset/limit), so we set the paginator's state
- # directly rather than handing it a queryset — keeping the param names (``limit`` /
- # ``offset``), default page size, and ``count`` / ``next`` / ``previous`` shape identical
- # to the model-backed viewsets.
- def _paginate_via_facade(self, request: Request, fetch, serializer_class) -> Response:
- paginator = self.paginator # type: ignore[attr-defined]
- limit = paginator.get_limit(request)
- offset = paginator.get_offset(request)
- page, count = fetch(offset=offset, limit=limit)
- paginator.request = request
- paginator.limit = limit
- paginator.offset = offset
- paginator.count = count
- serializer = serializer_class(instance=page, many=True)
- return paginator.get_paginated_response(serializer.data)
-
-
def _object_required_level(request: Request, write: bool) -> str | None:
"""The object-level access level to enforce for this request, or ``None`` when the
permission layer would skip the object check (service auth) — mirroring
@@ -275,7 +257,6 @@ class AccountTrackRuleThrottle(UserRateThrottle):
class AccountTrackRuleViewSet(
TeamAndOrgViewSetMixin,
AccessControlViewSetMixin,
- _FacadePaginationMixin,
viewsets.GenericViewSet,
):
scope_object = "customer_analytics"
@@ -415,18 +396,14 @@ class AccountTrackRuleViewSet(
detail=False,
methods=["get"],
url_path="runs",
- pagination_class=LimitOffsetPagination,
+ pagination_class=FacadeLimitOffsetPagination,
required_scopes=["customer_analytics:read"],
)
def runs(self, request: Request, *args, **kwargs) -> Response:
- return self._paginate_via_facade(
- request,
- lambda offset, limit: api.list_account_track_rule_runs(
- self.team_id,
- offset=offset,
- limit=limit,
- ),
- AccountTrackRuleRunSerializer,
+ return facade_page_response(
+ self,
+ lambda page: api.list_account_track_rule_runs(self.team_id, page=page),
+ serializer_class=AccountTrackRuleRunSerializer,
)
@@ -523,7 +500,6 @@ def _feature_request_evidence_input(data: dict[str, Any] | None) -> contracts.Fe
class FeatureRequestViewSet(
TeamAndOrgViewSetMixin,
AccessControlViewSetMixin,
- _FacadePaginationMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
mixins.CreateModelMixin,
@@ -535,6 +511,7 @@ class FeatureRequestViewSet(
queryset = None
permission_classes = [PostHogFeatureFlagPermission]
posthog_feature_flag = CUSTOMER_ANALYTICS_FEATURE_REQUESTS_FLAG
+ pagination_class = FacadeLimitOffsetPagination
@validated_request(
query_serializer=FeatureRequestListQuerySerializer,
@@ -542,9 +519,9 @@ class FeatureRequestViewSet(
)
def list(self, request: ValidatedRequest, *args, **kwargs) -> Response:
data = request.validated_query_data
- return self._paginate_via_facade(
- request,
- lambda offset, limit: api.list_feature_requests(
+ return facade_page_response(
+ self,
+ lambda page: api.list_feature_requests(
team_id=self.team_id,
user_access_control=self.user_access_control,
filters=contracts.FeatureRequestListFilters(
@@ -557,10 +534,9 @@ class FeatureRequestViewSet(
archive_state=data["archive_state"],
ordering=data["request_ordering"],
),
- offset=offset,
- limit=limit,
+ page=page,
),
- FeatureRequestSerializer,
+ serializer_class=FeatureRequestSerializer,
)
def retrieve(self, request: Request, *args, **kwargs) -> Response:
@@ -1182,7 +1158,6 @@ class UserCustomerAnalyticsConfigViewSet(TeamAndOrgViewSetMixin, viewsets.Generi
class CustomerProfileConfigViewSet(
TeamAndOrgViewSetMixin,
- _FacadePaginationMixin,
mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
@@ -1193,12 +1168,13 @@ class CustomerProfileConfigViewSet(
scope_object = "customer_profile_config"
serializer_class = CustomerProfileConfigSerializer
queryset = None # data is reached through the facade; declared for router/schema only
+ pagination_class = FacadeLimitOffsetPagination
def list(self, request: Request, *args, **kwargs) -> Response:
- return self._paginate_via_facade(
- request,
- lambda offset, limit: api.list_customer_profile_configs(self.team_id, offset=offset, limit=limit),
- CustomerProfileConfigSerializer,
+ return facade_page_response(
+ self,
+ lambda page: api.list_customer_profile_configs(self.team_id, page=page),
+ serializer_class=CustomerProfileConfigSerializer,
)
def retrieve(self, request: Request, *args, **kwargs) -> Response:
@@ -1269,30 +1245,25 @@ def _profile_config_write_fields(validated, raw_data: dict) -> dict:
return fields
-class _DefinitionPaginationMixin(_FacadePaginationMixin):
- def _paginate_via_facade(
- self,
- request: Request,
- fetch: Callable[..., tuple[Sequence[object], int]],
- serializer_class: type[BaseSerializer],
- ) -> Response:
- if request.query_params.get("pagination") == "none":
- page, count = fetch(offset=0, limit=None)
- return Response(
- {
- "count": count,
- "next": None,
- "previous": None,
- "results": serializer_class(instance=page, many=True).data,
- }
- )
- return super()._paginate_via_facade(request, fetch, serializer_class)
+def _wants_unpaged_list(request: Request) -> bool:
+ return request.query_params.get("pagination") == "none"
+
+
+def _unpaged_response(rows: Sequence[object], serializer_class: type[BaseSerializer]) -> Response:
+ """The paged response shape with every row on one page, for `?pagination=none`."""
+ return Response(
+ {
+ "count": len(rows),
+ "next": None,
+ "previous": None,
+ "results": serializer_class(instance=rows, many=True).data,
+ }
+ )
class CustomPropertyDefinitionViewSet(
TeamAndOrgViewSetMixin,
AccessControlViewSetMixin,
- _DefinitionPaginationMixin,
mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
@@ -1307,6 +1278,7 @@ class CustomPropertyDefinitionViewSet(
scope_object_read_actions = ["list", "retrieve", "values"]
serializer_class = CustomPropertyDefinitionSerializer
queryset = None # data is reached through the facade; declared for router/schema only
+ pagination_class = FacadeLimitOffsetPagination
@extend_schema(
parameters=[
@@ -1321,16 +1293,22 @@ class CustomPropertyDefinitionViewSet(
def list(self, request: Request, *args, **kwargs) -> Response:
# Callers without group read authorization don't see group-target definitions.
exclude_group_targets = not _has_group_scope(request, write=False)
- return self._paginate_via_facade(
- request,
- lambda offset, limit: api.list_custom_property_definitions(
+ if _wants_unpaged_list(request):
+ definitions = api.list_all_custom_property_definitions(
self.team_id,
- offset=offset,
- limit=limit,
+ user_access_control=_warehouse_scoped_uac(self),
+ exclude_group_targets=exclude_group_targets,
+ )
+ return _unpaged_response(definitions, CustomPropertyDefinitionSerializer)
+ return facade_page_response(
+ self,
+ lambda page: api.list_custom_property_definitions(
+ self.team_id,
+ page=page,
user_access_control=_warehouse_scoped_uac(self),
exclude_group_targets=exclude_group_targets,
),
- CustomPropertyDefinitionSerializer,
+ serializer_class=CustomPropertyDefinitionSerializer,
)
def retrieve(self, request: Request, *args, **kwargs) -> Response:
@@ -1488,12 +1466,12 @@ def _custom_property_option_dicts(options) -> list[dict] | None:
class AccountRelationshipDefinitionViewSet(
TeamAndOrgViewSetMixin,
AccessControlViewSetMixin,
- _DefinitionPaginationMixin,
viewsets.ModelViewSet,
):
scope_object = "account"
serializer_class = AccountRelationshipDefinitionSerializer
queryset = None # data is reached through the facade; declared for router/schema only
+ pagination_class = FacadeLimitOffsetPagination
@extend_schema(
parameters=[
@@ -1506,10 +1484,13 @@ class AccountRelationshipDefinitionViewSet(
]
)
def list(self, request: Request, *args, **kwargs) -> Response:
- return self._paginate_via_facade(
- request,
- lambda offset, limit: api.list_account_relationship_definitions(self.team_id, offset=offset, limit=limit),
- AccountRelationshipDefinitionSerializer,
+ if _wants_unpaged_list(request):
+ definitions = api.list_all_account_relationship_definitions(self.team_id)
+ return _unpaged_response(definitions, AccountRelationshipDefinitionSerializer)
+ return facade_page_response(
+ self,
+ lambda page: api.list_account_relationship_definitions(self.team_id, page=page),
+ serializer_class=AccountRelationshipDefinitionSerializer,
)
def retrieve(self, request: Request, *args, **kwargs) -> Response:
@@ -1598,26 +1579,25 @@ class CustomPropertySourceSyncThrottle(RunSavedQueryRateThrottle):
class CustomPropertySourceViewSet(
TeamAndOrgViewSetMixin,
AccessControlViewSetMixin,
- _FacadePaginationMixin,
viewsets.ModelViewSet,
):
scope_object = "account"
serializer_class = CustomPropertySourceSerializer
queryset = None # data is reached through the facade; declared for router/schema only
+ pagination_class = FacadeLimitOffsetPagination
def list(self, request: Request, *args, **kwargs) -> Response:
# Callers without group read authorization don't see sources feeding group-target definitions.
exclude_group_targets = not _has_group_scope(request, write=False)
- return self._paginate_via_facade(
- request,
- lambda offset, limit: api.list_custom_property_sources(
+ return facade_page_response(
+ self,
+ lambda page: api.list_custom_property_sources(
self.team_id,
- offset=offset,
- limit=limit,
+ page=page,
user_access_control=_warehouse_scoped_uac(self),
exclude_group_targets=exclude_group_targets,
),
- CustomPropertySourceSerializer,
+ serializer_class=CustomPropertySourceSerializer,
)
def retrieve(self, request: Request, *args, **kwargs) -> Response:
@@ -1810,18 +1790,17 @@ class CustomPropertySourceViewSet(
query.is_valid(raise_exception=True)
search = query.validated_data.get("search", "").strip() or None
try:
- return self._paginate_via_facade(
- request,
- lambda offset, limit: api.list_custom_property_sync_runs(
+ return facade_page_response(
+ self,
+ lambda page: api.list_custom_property_sync_runs(
self.team_id,
self.kwargs["pk"],
- offset=offset,
- limit=limit,
+ page=page,
user_access_control=_warehouse_scoped_uac(self),
include_temporal_urls=bool(request.user.is_staff or is_impersonated(request)),
search=search,
),
- CustomPropertySyncRunSerializer,
+ serializer_class=CustomPropertySyncRunSerializer,
)
except api.ResourceForbiddenError:
raise PermissionDenied()
@@ -1830,7 +1809,6 @@ class CustomPropertySourceViewSet(
class CustomerJourneyViewSet(
TeamAndOrgViewSetMixin,
AccessControlViewSetMixin,
- _FacadePaginationMixin,
mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
@@ -1841,14 +1819,15 @@ class CustomerJourneyViewSet(
scope_object = "customer_journey"
serializer_class = CustomerJourneySerializer
queryset = None
+ pagination_class = FacadeLimitOffsetPagination
def list(self, request: Request, *args, **kwargs) -> Response:
- return self._paginate_via_facade(
- request,
- lambda offset, limit: api.list_customer_journeys(
- self.team_id, offset=offset, limit=limit, user_access_control=self.user_access_control
+ return facade_page_response(
+ self,
+ lambda page: api.list_customer_journeys(
+ self.team_id, page=page, user_access_control=self.user_access_control
),
- CustomerJourneySerializer,
+ serializer_class=CustomerJourneySerializer,
)
def retrieve(self, request: Request, *args, **kwargs) -> Response:
@@ -1959,7 +1938,6 @@ class AccountViewSet(
TaggedItemViewSetMixin,
TeamAndOrgViewSetMixin,
AccessControlViewSetMixin,
- _FacadePaginationMixin,
mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
@@ -1970,6 +1948,7 @@ class AccountViewSet(
scope_object = "account"
serializer_class = AccountSerializer
queryset = None
+ pagination_class = FacadeLimitOffsetPagination
bulk_update_tags = None # Mixin action assumes integer PKs; Account uses UUIDs.
ALLOWED_ORDERING = frozenset({"name", "-name", "created_at", "-created_at", "updated_at", "-updated_at"})
@@ -2046,13 +2025,12 @@ class AccountViewSet(
tags = _parse_tags_param(self.request)
ordering = request.query_params.get("ordering")
ordering = ordering if ordering in self.ALLOWED_ORDERING else None
- return self._paginate_via_facade(
- request,
- lambda offset, limit: api.list_accounts_for_view(
+ return facade_page_response(
+ self,
+ lambda page: api.list_accounts_for_view(
team_id=self.team_id,
user_access_control=self.user_access_control,
- offset=offset,
- limit=limit,
+ page=page,
search=request.query_params.get("search", "").strip() or None,
tags=tags,
all_roles_unassigned=request.query_params.get("all_roles_unassigned", "").lower() == "true",
@@ -2061,7 +2039,7 @@ class AccountViewSet(
ordering=ordering,
inactive_last=request.query_params.get("inactive_last", "").lower() == "true",
),
- AccountSerializer,
+ serializer_class=AccountSerializer,
)
@extend_schema(parameters=[_ACCOUNT_ID_PARAM])
@@ -2180,31 +2158,18 @@ class AccountViewSet(
except ValueError:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
- paginator = cast(LimitOffsetPagination, self.paginator)
- limit = paginator.get_limit(request)
- assert limit is not None
- offset = paginator.get_offset(request)
- try:
- result = api.get_account_support_ticket_messages(
- self.team_id,
- self.kwargs["pk"],
- parsed_ticket_id,
- self.user_access_control,
- offset=offset,
- limit=limit,
- )
- except api.ResourceForbiddenError:
- raise PermissionDenied()
- if result is None:
- return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ def fetch(page: PageRequest) -> Page[api.SupportTicketMessage]:
+ try:
+ result = api.get_account_support_ticket_messages(
+ self.team_id, self.kwargs["pk"], parsed_ticket_id, self.user_access_control, page=page
+ )
+ except api.ResourceForbiddenError:
+ raise PermissionDenied()
+ if result is None:
+ raise NotFound()
+ return result
- messages, count = result
- paginator.request = request
- paginator.limit = limit
- paginator.offset = offset
- paginator.count = count
- serializer = SupportTicketMessageSerializer(instance=messages, many=True)
- return paginator.get_paginated_response(serializer.data)
+ return facade_page_response(self, fetch, serializer_class=SupportTicketMessageSerializer)
@extend_schema(parameters=[_ACCOUNT_ID_PARAM], responses={200: AccountEmailThreadSerializer(many=True)})
@action(methods=["GET"], detail=True, url_path="email_threads")
@@ -2212,20 +2177,18 @@ class AccountViewSet(
if api.get_accessible_account_id(self.team_id, self.kwargs["pk"], self.user_access_control) is None:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
- def fetch(offset: int, limit: int) -> tuple[list[api.AccountEmailThreadSummary], int]:
+ def fetch(page: PageRequest) -> Page[api.AccountEmailThreadSummary]:
try:
result = api.get_account_email_threads(
- self.team_id,
- self.kwargs["pk"],
- self.user_access_control,
- offset=offset,
- limit=limit,
+ self.team_id, self.kwargs["pk"], self.user_access_control, page=page
)
except api.ResourceForbiddenError:
raise PermissionDenied()
- return result if result is not None else ([], 0)
+ if result is None:
+ raise NotFound()
+ return result
- return self._paginate_via_facade(request, fetch, AccountEmailThreadSerializer)
+ return facade_page_response(self, fetch, serializer_class=AccountEmailThreadSerializer)
@extend_schema(
operation_id="accounts_email_thread_messages_list",
@@ -2245,31 +2208,18 @@ class AccountViewSet(
except ValueError:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
- paginator = cast(LimitOffsetPagination, self.paginator)
- limit = paginator.get_limit(request)
- assert limit is not None
- offset = paginator.get_offset(request)
- try:
- result = api.get_account_email_thread_messages(
- self.team_id,
- self.kwargs["pk"],
- parsed_thread_id,
- self.user_access_control,
- offset=offset,
- limit=limit,
- )
- except api.ResourceForbiddenError:
- raise PermissionDenied()
- if result is None:
- return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ def fetch(page: PageRequest) -> Page[api.AccountEmailThreadMessage]:
+ try:
+ result = api.get_account_email_thread_messages(
+ self.team_id, self.kwargs["pk"], parsed_thread_id, self.user_access_control, page=page
+ )
+ except api.ResourceForbiddenError:
+ raise PermissionDenied()
+ if result is None:
+ raise NotFound()
+ return result
- messages, count = result
- paginator.request = request
- paginator.limit = limit
- paginator.offset = offset
- paginator.count = count
- serializer = AccountEmailThreadMessageSerializer(instance=messages, many=True)
- return paginator.get_paginated_response(serializer.data)
+ return facade_page_response(self, fetch, serializer_class=AccountEmailThreadMessageSerializer)
@extend_schema(
parameters=[
@@ -2290,18 +2240,15 @@ class AccountViewSet(
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
search = request.query_params.get("search", "").strip() or None
- def fetch(offset: int, limit: int) -> tuple[list[contracts.MeetingView], int]:
+ def fetch(page: PageRequest) -> Page[contracts.MeetingView]:
result = api.list_account_meetings(
- self.team_id,
- self.kwargs["pk"],
- self.user_access_control,
- offset=offset,
- limit=limit,
- search=search,
+ self.team_id, self.kwargs["pk"], self.user_access_control, page=page, search=search
)
- return result if result is not None else ([], 0)
+ if result is None:
+ raise NotFound()
+ return result
- return self._paginate_via_facade(request, fetch, MeetingSerializer)
+ return facade_page_response(self, fetch, serializer_class=MeetingSerializer)
def dangerously_get_required_scopes(self, request: Request, view) -> builtins.list[str] | None:
super_method = getattr(super(), "dangerously_get_required_scopes", None)
@@ -2415,13 +2362,15 @@ class AccountViewSet(
if api.get_accessible_account_id(self.team_id, self.kwargs["pk"], self.user_access_control) is None:
return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
- def fetch(offset: int, limit: int) -> tuple[list[contracts.AccountChannelSummaryView], int]:
+ def fetch(page: PageRequest) -> Page[contracts.AccountChannelSummaryView]:
result = api.list_account_channel_summaries(
- self.team_id, self.kwargs["pk"], self.user_access_control, offset=offset, limit=limit
+ self.team_id, self.kwargs["pk"], self.user_access_control, page=page
)
- return result if result is not None else ([], 0)
+ if result is None:
+ raise NotFound()
+ return result
- return self._paginate_via_facade(request, fetch, AccountChannelSummarySerializer)
+ return facade_page_response(self, fetch, serializer_class=AccountChannelSummarySerializer)
@extend_schema(parameters=[_ACCOUNT_ID_PARAM])
def destroy(self, request: Request, *args, **kwargs) -> Response:
@@ -2612,13 +2561,13 @@ def _parse_uuid_param(request: Request, name: str) -> UUID | None:
class AccountNotesViewSet(
TeamAndOrgViewSetMixin,
AccessControlViewSetMixin,
- _FacadePaginationMixin,
mixins.ListModelMixin,
viewsets.GenericViewSet,
):
scope_object = "account"
serializer_class = AccountNoteSerializer
queryset = None # data is reached through the facade; declared for router/schema only
+ pagination_class = FacadeLimitOffsetPagination
@extend_schema(
parameters=[
@@ -2656,19 +2605,18 @@ class AccountNotesViewSet(
],
)
def list(self, request: Request, *args, **kwargs) -> Response:
- return self._paginate_via_facade(
- request,
- lambda offset, limit: api.list_account_notes_for_view(
+ return facade_page_response(
+ self,
+ lambda page: api.list_account_notes_for_view(
team_id=self.team_id,
user_access_control=self.user_access_control,
- offset=offset,
- limit=limit,
+ page=page,
search=request.query_params.get("search", "").strip() or None,
account_id=_parse_uuid_param(request, "account_id"),
created_by_ids=_parse_int_ids_param(request, "created_by") or None,
assigned_to_ids=_parse_int_ids_param(request, "assigned_to") or None,
),
- AccountNoteSerializer,
+ serializer_class=AccountNoteSerializer,
)
diff --git a/products/customer_analytics/backend/test/test_custom_property_source_disabled_notice.py b/products/customer_analytics/backend/test/test_custom_property_source_disabled_notice.py
index b6c39f40564d..32111b52b5a4 100644
--- a/products/customer_analytics/backend/test/test_custom_property_source_disabled_notice.py
+++ b/products/customer_analytics/backend/test/test_custom_property_source_disabled_notice.py
@@ -7,6 +7,7 @@ from unittest.mock import patch
from posthog.constants import AvailableFeature
from posthog.models import OrganizationMembership
+from posthog.paging import PageRequest
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.access_control.backend.models.access_control import AccessControl
@@ -95,15 +96,14 @@ class TestNotifySourceAutoDisabled(BaseTest):
assert local_due_at.time() == time(23, 59, 59)
access = UserAccessControl(user=self.user, team=self.team)
- tasks, count = list_customer_tasks(
+ tasks = list_customer_tasks(
team_id=self.team.id,
user_access_control=access,
filters=contracts.CustomerTaskListFilters(assigned_to="me"),
- offset=0,
- limit=10,
+ page=PageRequest(limit=10),
)
- assert count == 1
- assert [item.id for item in tasks] == [task.id]
+ assert tasks.count == 1
+ assert [item.id for item in tasks.results] == [task.id]
with patch(
"products.customer_analytics.backend.logic.task_digest_delivery.posthoganalytics.feature_enabled",
return_value=True,
diff --git a/products/customer_analytics/backend/test/test_custom_property_values.py b/products/customer_analytics/backend/test/test_custom_property_values.py
index 6820788bc547..caa37d086888 100644
--- a/products/customer_analytics/backend/test/test_custom_property_values.py
+++ b/products/customer_analytics/backend/test/test_custom_property_values.py
@@ -12,6 +12,7 @@ from parameterized import parameterized
from posthog.models import Team
from posthog.models.scoping import team_scope
+from posthog.paging import PageRequest
from products.customer_analytics.backend.facade import (
api as facade,
@@ -700,16 +701,16 @@ class TestCustomPropertyDefinitionReferences(BaseTest):
workflow = self._create_workflow_setting(str(plan.id))
with team_scope(self.team.id):
- page, _ = facade.list_custom_property_definitions(
- self.team.id, offset=0, limit=50, user_access_control=self._uac()
+ page = facade.list_custom_property_definitions(
+ self.team.id, page=PageRequest(limit=50), user_access_control=self._uac()
)
- by_id = {view.id: view for view in page}
+ by_id = {view.id: view for view in page.results}
assert [(r.id, r.name, r.status, r.type) for r in by_id[plan.id].references] == [
(str(workflow.id), "Onboarding", "active", "workflow")
]
assert by_id[plan.id].has_workflow_reference is True
- unused = next(v for v in page if v.name == "Unused")
+ unused = next(v for v in page.results if v.name == "Unused")
assert unused.references == []
assert unused.has_workflow_reference is False
@@ -719,11 +720,11 @@ class TestCustomPropertyDefinitionReferences(BaseTest):
self._create_workflow_setting(str(uuid4()))
with team_scope(self.team.id):
- page, _ = facade.list_custom_property_definitions(
- self.team.id, offset=0, limit=50, user_access_control=self._uac()
+ page = facade.list_custom_property_definitions(
+ self.team.id, page=PageRequest(limit=50), user_access_control=self._uac()
)
- assert next(v for v in page if v.id == plan.id).references == []
+ assert next(v for v in page.results if v.id == plan.id).references == []
def test_get_attaches_workflow_references_for_single_definition(self):
plan = create_custom_property_definition(team_id=self.team.id, name="Plan")
@@ -765,14 +766,14 @@ class TestCustomPropertyDefinitionReferences(BaseTest):
self._create_workflow_setting(str(plan.id))
with team_scope(self.team.id):
- page, _ = facade.list_custom_property_definitions(
- self.team.id, offset=0, limit=50, user_access_control=self._uac(can_read_workflows=False)
+ page = facade.list_custom_property_definitions(
+ self.team.id, page=PageRequest(limit=50), user_access_control=self._uac(can_read_workflows=False)
)
view = facade.get_custom_property_definition(
self.team.id, str(plan.id), user_access_control=self._uac(can_read_workflows=False)
)
- list_view = next(v for v in page if v.id == plan.id)
+ list_view = next(v for v in page.results if v.id == plan.id)
assert list_view.references == []
assert list_view.has_workflow_reference is True
assert view is not None
diff --git a/products/customer_analytics/backend/test/test_customer_tasks.py b/products/customer_analytics/backend/test/test_customer_tasks.py
index 3d5d2fad75fd..617bc67cb506 100644
--- a/products/customer_analytics/backend/test/test_customer_tasks.py
+++ b/products/customer_analytics/backend/test/test_customer_tasks.py
@@ -995,10 +995,11 @@ class CustomerTaskAPI(APIBaseTest):
"Delta",
}
- def test_list_applies_ordering_limit_and_offset(self) -> None:
+ @parameterized.expand([("2",), ("2.0",)])
+ def test_list_applies_ordering_limit_and_offset(self, limit: str) -> None:
self._create_filtering_dataset()
- response = self.client.get(self.url, {"ordering": "-name", "limit": "2", "offset": "1"})
+ response = self.client.get(self.url, {"ordering": "-name", "limit": limit, "offset": "1"})
assert response.status_code == status.HTTP_200_OK
assert response.json()["count"] == 4
diff --git a/products/customer_analytics/backend/test/test_customer_tasks_hogql.py b/products/customer_analytics/backend/test/test_customer_tasks_hogql.py
index 7cd231fb9440..973fc5391578 100644
--- a/products/customer_analytics/backend/test/test_customer_tasks_hogql.py
+++ b/products/customer_analytics/backend/test/test_customer_tasks_hogql.py
@@ -11,6 +11,7 @@ from posthog.hogql.query import execute_hogql_query
from posthog.models import OrganizationMembership, Team, User
from posthog.models.organization import AvailableFeature
+from posthog.paging import PageRequest
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.access_control.backend.models.access_control import AccessControl
@@ -100,15 +101,14 @@ class TestCustomerTasksHogqlAccess(NonAtomicBaseTest):
active_rows = execute_hogql_query(
"SELECT name FROM system.customer_tasks WHERE archived_at IS NULL", team=self.team, user=viewer
).results
- tasks, count = api.list_customer_tasks(
+ tasks = api.list_customer_tasks(
team_id=self.team.id,
user_access_control=UserAccessControl(user=viewer, team=self.team),
filters=contracts.CustomerTaskListFilters(),
- offset=0,
- limit=100,
+ page=PageRequest(limit=100),
)
- assert {row[0] for row in active_rows} == {task.name for task in tasks} == expected_active_task_names
- assert count == len(expected_active_task_names)
+ assert {row[0] for row in active_rows} == {task.name for task in tasks.results} == expected_active_task_names
+ assert tasks.count == len(expected_active_task_names)
materialization_database = Database.create_for(
team=self.team,
diff --git a/products/customer_analytics/backend/test/test_facade.py b/products/customer_analytics/backend/test/test_facade.py
index 444c93aa8562..d86bce933084 100644
--- a/products/customer_analytics/backend/test/test_facade.py
+++ b/products/customer_analytics/backend/test/test_facade.py
@@ -16,6 +16,7 @@ from posthog.models import Organization, OrganizationMembership, Team, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.tag import Tag
from posthog.models.tagged_item import TaggedItem
+from posthog.paging import PageRequest
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.access_control.backend.models.access_control import AccessControl
@@ -543,11 +544,11 @@ class TestCustomerAnalyticsCRUDFacade(BaseTest):
def test_list_accounts_for_view_filters_by_search(self, _name: str, search: str):
self._create(name="Acme Corp", external_id="acme-1", properties={"email_domains": ["acme.example"]})
self._create(name="Globex", external_id="glx-9")
- page, count = facade.list_accounts_for_view(
- team_id=self.team.id, user_access_control=self._uac(), offset=0, limit=10, search=search
+ page = facade.list_accounts_for_view(
+ team_id=self.team.id, user_access_control=self._uac(), page=PageRequest(limit=10), search=search
)
- assert count == 1
- assert [a.name for a in page] == ["Acme Corp"]
+ assert page.count == 1
+ assert [a.name for a in page.results] == ["Acme Corp"]
# --- CustomerJourney ---
diff --git a/products/customer_analytics/backend/test/test_relationships.py b/products/customer_analytics/backend/test/test_relationships.py
index f012a5998739..f4720b227a97 100644
--- a/products/customer_analytics/backend/test/test_relationships.py
+++ b/products/customer_analytics/backend/test/test_relationships.py
@@ -13,6 +13,7 @@ from parameterized import parameterized
from posthog.models import Team, User
from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.paging import PageRequest
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.customer_analytics.backend.facade import api as facade
@@ -181,8 +182,9 @@ class TestRelationshipFacade(BaseTest):
created = facade.create_account_relationship_definition(
team_id=self.team.id, name="Onboarding manager", description="Runs onboarding", created_by=self.user
)
- listed, total = facade.list_account_relationship_definitions(self.team.id)
- assert total == 1
+ listed_page = facade.list_account_relationship_definitions(self.team.id, page=PageRequest(limit=100))
+ listed = listed_page.results
+ assert listed_page.count == 1
assert [d.id for d in listed] == [created.id]
assert listed[0].description == "Runs onboarding"
assert listed[0].is_single_holder is True
@@ -345,7 +347,7 @@ class TestRelationshipFacade(BaseTest):
team_id=self.team.id, name="CSM", created_by=self.user
)
assert definition.id is not None
- assert facade.list_account_relationship_definitions(other_team.id) == ([], 0)
+ assert facade.list_all_account_relationship_definitions(other_team.id) == []
assert facade.list_account_relationships(team_id=other_team.id, account_id=self.account.id) == []
assert not facade.delete_account_relationship_definition(team_id=other_team.id, definition_id=definition.id)
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index ff6f9c8495ba..1037b6a3d587 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -123,6 +123,13 @@ class TestCustomerProfileConfigViewSet(APIBaseTest):
self.assertIn(str(config1.id), config_ids)
self.assertIn(str(config2.id), config_ids)
+ # one-row pages walk both configs without skipping or repeating one
+ paged_ids = {
+ self.client.get(self.endpoint_base, {"limit": 1, "offset": offset}).json()["results"][0]["id"]
+ for offset in range(2)
+ }
+ self.assertEqual(paged_ids, {str(config1.id), str(config2.id)})
+
def test_retrieve_customer_profile_config(self):
config = CustomerProfileConfig.objects.create(
team=self.team, scope="person", content=self.valid_data["content"], sidebar=self.valid_data["sidebar"]
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index 15d178969612..f2c1be5c124a 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -4899,6 +4899,7 @@ export type AccountNotesListParams = {
created_by?: number[]
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number
/**
@@ -4914,6 +4915,7 @@ export type AccountNotesListParams = {
export type AccountRelationshipDefinitionsListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number
/**
@@ -4936,6 +4938,7 @@ export const AccountRelationshipDefinitionsListPagination = {
export type AccountTrackRulesRunsListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number
/**
@@ -4970,6 +4973,7 @@ export type AccountsListParams = {
include_ignored?: boolean
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number
/**
@@ -5019,6 +5023,7 @@ export type AccountsRelationshipsListParams = {
export type AccountsEmailThreadsListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number
/**
@@ -5030,6 +5035,7 @@ export type AccountsEmailThreadsListParams = {
export type AccountsEmailThreadMessagesListParams = {
/**
* Number of results to return per page.
+ * @maximum 200
*/
limit?: number
/**
@@ -5041,6 +5047,7 @@ export type AccountsEmailThreadMessagesListParams = {
export type AccountsMeetingsListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number
/**
@@ -5056,6 +5063,7 @@ export type AccountsMeetingsListParams = {
export type AccountsSummariesListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number
/**
@@ -5067,6 +5075,7 @@ export type AccountsSummariesListParams = {
export type AccountsSupportTicketMessagesListParams = {
/**
* Number of results to return per page.
+ * @maximum 200
*/
limit?: number
/**
@@ -5087,6 +5096,7 @@ export type AccountsByExternalIdRetrieveParams = {
export type AnnouncementsListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number
/**
@@ -5098,6 +5108,7 @@ export type AnnouncementsListParams = {
export type CustomPropertyDefinitionsListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number
/**
@@ -5131,6 +5142,7 @@ export type CustomPropertyDefinitionsValuesRetrieveParams = {
export type CustomPropertySourcesListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number
/**
@@ -5142,6 +5154,7 @@ export type CustomPropertySourcesListParams = {
export type CustomPropertySourcesRunsListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number
/**
@@ -5157,6 +5170,7 @@ export type CustomPropertySourcesRunsListParams = {
export type CustomerJourneysListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number
/**
@@ -5168,6 +5182,7 @@ export type CustomerJourneysListParams = {
export type CustomerProfileConfigsListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number
/**
@@ -5300,6 +5315,7 @@ export type FeatureRequestsListParams = {
created_by_ids?: number[]
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number
/**
diff --git a/products/error_tracking/backend/facade/api.py b/products/error_tracking/backend/facade/api.py
index 2ec7d6387259..cccd2eabd619 100644
--- a/products/error_tracking/backend/facade/api.py
+++ b/products/error_tracking/backend/facade/api.py
@@ -13,6 +13,8 @@ from django.db.models import QuerySet
import posthoganalytics
from posthog.event_usage import AnalyticsProps, groups
+from posthog.paging import Page, PageRequest
+from posthog.queryset_paging import select_page
from products.access_control.backend.facade.api import valid_role_member_user_ids
@@ -165,13 +167,8 @@ def get_issue(issue_id: UUID, team_id: int) -> contracts.ErrorTrackingIssue:
return _to_issue(issue)
-def list_issues_detailed(
- team_id: int, *, limit: int | None = None, offset: int = 0
-) -> tuple[list[contracts.ErrorTrackingIssue], int]:
- qs = logic.get_issue_detail_queryset(team_id).order_by("-id")
- total = qs.count()
- rows = qs if limit is None else qs[offset : offset + limit]
- return [_to_issue(issue) for issue in rows], total
+def list_issues_detailed(team_id: int, *, page: PageRequest) -> Page[contracts.ErrorTrackingIssue]:
+ return select_page(logic.get_issue_detail_queryset(team_id).order_by("-id"), page).map(_to_issue)
def issue_exists(team_id: int) -> bool:
@@ -259,16 +256,20 @@ def list_spike_events(
date_from: str | None = None,
date_to: str | None = None,
order_by: str | None = None,
- limit: int | None = None,
- offset: int = 0,
- include_total_count: bool = True,
-) -> tuple[list[contracts.ErrorTrackingSpikeEvent], int]:
+ page: PageRequest,
+) -> Page[contracts.ErrorTrackingSpikeEvent]:
qs = logic.list_spike_events(
team_id=team_id, issue_ids=issue_ids, date_from=date_from, date_to=date_to, order_by=order_by
)
- total = qs.count() if include_total_count else 0
- rows = qs if limit is None else qs[offset : offset + limit]
- return [_to_spike_event(event) for event in rows], total
+ return select_page(qs, page).map(_to_spike_event)
+
+
+def list_latest_spike_events(
+ *, team_id: int, date_from: str, date_to: str, limit: int
+) -> list[contracts.ErrorTrackingSpikeEvent]:
+ """Return at most `limit` spike events of a time window, newest first, without a total count."""
+ qs = logic.list_spike_events(team_id=team_id, date_from=date_from, date_to=date_to)
+ return [_to_spike_event(event) for event in qs[:limit]]
def _to_release(release) -> contracts.ErrorTrackingRelease:
@@ -298,13 +299,10 @@ def _to_stack_frame(frame) -> contracts.ErrorTrackingStackFrame:
)
-def list_stack_frames(
- team_id: int, *, limit: int | None = None, offset: int = 0
-) -> tuple[list[contracts.ErrorTrackingStackFrame], int]:
- qs = logic.stack_frame_queryset(team_id)
- total = qs.count()
- rows = qs if limit is None else qs[offset : offset + limit]
- return [_to_stack_frame(frame) for frame in rows], total
+def list_stack_frames(team_id: int, *, page: PageRequest) -> Page[contracts.ErrorTrackingStackFrame]:
+ # Order by created_at so et_frame_team_created_at_idx serves the page. No (team_id, id) index exists.
+ queryset = logic.stack_frame_queryset(team_id).order_by("created_at")
+ return select_page(queryset, page).map(_to_stack_frame)
def get_stack_frame(team_id: int, frame_id: str) -> contracts.ErrorTrackingStackFrame | None:
@@ -318,13 +316,8 @@ def batch_get_stack_frames(
return [_to_stack_frame(frame) for frame in logic.batch_get_stack_frames(team_id, raw_ids, symbol_set)]
-def list_releases(
- team_id: int, *, limit: int | None = None, offset: int = 0
-) -> tuple[list[contracts.ErrorTrackingRelease], int]:
- qs = logic.list_releases(team_id)
- total = qs.count()
- rows = qs if limit is None else qs[offset : offset + limit]
- return [_to_release(release) for release in rows], total
+def list_releases(team_id: int, *, page: PageRequest) -> Page[contracts.ErrorTrackingRelease]:
+ return select_page(logic.list_releases(team_id), page).map(_to_release)
def list_releases_created_between(
@@ -640,9 +633,10 @@ def get_issue_id_for_fingerprint(team_id: int, fingerprint: str) -> UUID | None:
return logic.get_issue_id_for_fingerprint(team_id=team_id, fingerprint=fingerprint)
-def list_fingerprints(team_id: int, issue_id: UUID | None = None) -> list[contracts.ErrorTrackingFingerprint]:
- fingerprints = logic.list_fingerprints(team_id=team_id, issue_id=issue_id)
- return [_to_fingerprint(fingerprint) for fingerprint in fingerprints]
+def list_fingerprints(
+ team_id: int, *, issue_id: UUID | None = None, page: PageRequest
+) -> Page[contracts.ErrorTrackingFingerprint]:
+ return select_page(logic.list_fingerprints(team_id=team_id, issue_id=issue_id), page).map(_to_fingerprint)
def list_first_fingerprints(team_id: int, issue_ids: list[UUID]) -> list[contracts.ErrorTrackingFingerprint]:
diff --git a/products/error_tracking/backend/facade/symbol_sets.py b/products/error_tracking/backend/facade/symbol_sets.py
index b4f1e69342af..12b5f5d99ae7 100644
--- a/products/error_tracking/backend/facade/symbol_sets.py
+++ b/products/error_tracking/backend/facade/symbol_sets.py
@@ -7,6 +7,8 @@ stay off the django.setup() path of the read-oriented main facade.
from typing import Any
from posthog.event_usage import AnalyticsProps
+from posthog.paging import Page, PageRequest
+from posthog.queryset_paging import select_page
from ..logic import symbol_sets as _logic
from . import contracts
@@ -46,19 +48,16 @@ def list_symbol_sets(
search: str | None,
symbol_set_status: str | None,
order_by: str | None,
- limit: int | None,
- offset: int,
-) -> tuple[list[contracts.ErrorTrackingSymbolSet], int]:
- rows, total = _logic.list_symbol_sets(
+ page: PageRequest,
+) -> Page[contracts.ErrorTrackingSymbolSet]:
+ queryset = _logic.list_symbol_sets(
team_id,
ref=ref,
search=search,
symbol_set_status=symbol_set_status,
order_by=order_by,
- limit=limit,
- offset=offset,
)
- return [_to_symbol_set(row) for row in rows], total
+ return select_page(queryset, page).map(_to_symbol_set)
def get_symbol_set(team_id: int, symbol_set_id: str) -> contracts.ErrorTrackingSymbolSet | None:
diff --git a/products/error_tracking/backend/logic/symbol_sets.py b/products/error_tracking/backend/logic/symbol_sets.py
index e3227702eddf..5d59b4164b40 100644
--- a/products/error_tracking/backend/logic/symbol_sets.py
+++ b/products/error_tracking/backend/logic/symbol_sets.py
@@ -13,7 +13,7 @@ from typing import Any
from django.conf import settings
from django.db import OperationalError, transaction
-from django.db.models import Q
+from django.db.models import Q, QuerySet
from django.utils import timezone
import psycopg
@@ -462,9 +462,7 @@ def list_symbol_sets(
search: str | None,
symbol_set_status: str | None,
order_by: str | None,
- limit: int | None,
- offset: int,
-) -> tuple[list[ErrorTrackingSymbolSet], int]:
+) -> QuerySet[ErrorTrackingSymbolSet]:
queryset = ErrorTrackingSymbolSet.objects.filter(team_id=team_id).select_related("release")
if ref:
@@ -485,11 +483,7 @@ def list_symbol_sets(
elif symbol_set_status == "invalid":
queryset = queryset.filter(storage_ptr__isnull=True)
- queryset = queryset.order_by(*SYMBOL_SET_ORDERINGS.get(order_by or "", DEFAULT_SYMBOL_SET_ORDERING))
-
- total = queryset.count()
- rows = queryset if limit is None else queryset[offset : offset + limit]
- return list(rows), total
+ return queryset.order_by(*SYMBOL_SET_ORDERINGS.get(order_by or "", DEFAULT_SYMBOL_SET_ORDERING))
def get_symbol_set(team_id: int, symbol_set_id: str) -> ErrorTrackingSymbolSet | None:
diff --git a/products/error_tracking/backend/presentation/pagination.py b/products/error_tracking/backend/presentation/pagination.py
deleted file mode 100644
index 31318517e0b3..000000000000
--- a/products/error_tracking/backend/presentation/pagination.py
+++ /dev/null
@@ -1,46 +0,0 @@
-from collections.abc import Callable
-from typing import Any
-
-from rest_framework.generics import GenericAPIView
-from rest_framework.pagination import LimitOffsetPagination
-from rest_framework.request import Request
-from rest_framework.response import Response
-
-# A facade fetcher takes (limit, offset) and returns (page_items, total_count).
-# limit is None when pagination is disabled, in which case the whole result set is returned.
-FacadeFetcher = Callable[[int | None, int], tuple[list[Any], int]]
-
-
-def paginate_via_facade(view: GenericAPIView, request: Request, fetch_page: FacadeFetcher) -> Response:
- """Render a DRF ``LimitOffsetPagination`` envelope from a facade function that pushes
- ``LIMIT``/``OFFSET``/``COUNT`` into SQL.
-
- The facade evaluates its queryset into frozen contracts to honor the product boundary, so it
- cannot hand a lazy queryset back to ``paginate_queryset`` — doing so on a materialized list would
- load the entire result set into memory just to slice one page. Instead the facade slices the
- queryset *before* mapping to contracts and returns ``(page_items, total_count)``; this helper
- reads the limit/offset from the request and assembles the standard ``{count, next, previous,
- results}`` envelope, keeping the response shape identical to a queryset-backed list view.
-
- Reusable across product list views (releases, stack frames, spike events — and the symbol-set
- list once it is thinned).
- """
- paginator = view.paginator
- if not isinstance(paginator, LimitOffsetPagination):
- items, _total = fetch_page(None, 0)
- return Response(view.get_serializer(items, many=True).data)
-
- limit = paginator.get_limit(request)
- if limit is None:
- items, _total = fetch_page(None, 0)
- return Response(view.get_serializer(items, many=True).data)
-
- offset = paginator.get_offset(request)
- items, total = fetch_page(limit, offset)
- # Set the count/limit/offset/request the paginator would normally derive in paginate_queryset,
- # so get_paginated_response and the next/previous links resolve correctly.
- paginator.count = total
- paginator.limit = limit
- paginator.offset = offset
- paginator.request = request
- return paginator.get_paginated_response(view.get_serializer(items, many=True).data)
diff --git a/products/error_tracking/backend/presentation/views/fingerprints.py b/products/error_tracking/backend/presentation/views/fingerprints.py
index 4a1d1dcb588f..6285f0d9b948 100644
--- a/products/error_tracking/backend/presentation/views/fingerprints.py
+++ b/products/error_tracking/backend/presentation/views/fingerprints.py
@@ -7,6 +7,7 @@ from rest_framework.exceptions import NotFound, ValidationError
from rest_framework.response import Response
from posthog.api.forbid_destroy_model import ForbidDestroyModel
+from posthog.api.pagination import FacadeLimitOffsetPagination, facade_page_response
from posthog.api.routing import TeamAndOrgViewSetMixin
from products.error_tracking.backend.facade.api import get_fingerprint, get_fingerprint_by_value, list_fingerprints
@@ -24,6 +25,7 @@ class ErrorTrackingFingerprintViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel
scope_object_read_actions = ["list", "retrieve", "resolve"]
scope_object_write_actions: list[str] = []
serializer_class = ErrorTrackingFingerprintSerializer
+ pagination_class = FacadeLimitOffsetPagination
@extend_schema(
parameters=[
@@ -45,15 +47,9 @@ class ErrorTrackingFingerprintViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel
except ValueError as error:
raise ValidationError("issue_id must be a valid UUID") from error
- fingerprints = list_fingerprints(team_id=self.team.id, issue_id=issue_id)
-
- page = self.paginate_queryset(fingerprints)
- if page is not None:
- serializer = self.get_serializer(page, many=True)
- return self.get_paginated_response(serializer.data)
-
- serializer = self.get_serializer(fingerprints, many=True)
- return Response(serializer.data)
+ return facade_page_response(
+ self, lambda page: list_fingerprints(team_id=self.team.id, issue_id=issue_id, page=page)
+ )
@extend_schema(
parameters=[
diff --git a/products/error_tracking/backend/presentation/views/issues.py b/products/error_tracking/backend/presentation/views/issues.py
index 952baaba36e8..873579cef6bb 100644
--- a/products/error_tracking/backend/presentation/views/issues.py
+++ b/products/error_tracking/backend/presentation/views/issues.py
@@ -15,6 +15,7 @@ from rest_framework.response import Response
from posthog.api.documentation import extend_schema, extend_schema_field
from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.pagination import FacadeLimitOffsetPagination, facade_page_response
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
from posthog.event_usage import report_user_action
@@ -29,7 +30,6 @@ from products.error_tracking.backend.facade import (
issues as issues_facade,
summaries as summaries_facade,
)
-from products.error_tracking.backend.presentation.pagination import paginate_via_facade
from products.error_tracking.backend.presentation.views.external_references import (
ErrorTrackingExternalReferenceResultSerializer,
)
@@ -336,6 +336,7 @@ class ErrorTrackingIssueViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, view
"summary_regenerate",
]
serializer_class = ErrorTrackingIssueReadSerializer
+ pagination_class = FacadeLimitOffsetPagination
def _report_issue_change(self, request: request.Request, action: str, properties: dict[str, object]) -> None:
# Captured server-side because the frontend issue events only see the web app.
@@ -349,11 +350,7 @@ class ErrorTrackingIssueViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, view
)
def list(self, request: request.Request, *args: object, **kwargs: object) -> Response:
- return paginate_via_facade(
- self,
- request,
- lambda limit, offset: facade_api.list_issues_detailed(self.team.id, limit=limit, offset=offset),
- )
+ return facade_page_response(self, lambda page: facade_api.list_issues_detailed(self.team.id, page=page))
@extend_schema(
parameters=[
diff --git a/products/error_tracking/backend/presentation/views/releases.py b/products/error_tracking/backend/presentation/views/releases.py
index 7c25db922dfa..9ae432fa2a75 100644
--- a/products/error_tracking/backend/presentation/views/releases.py
+++ b/products/error_tracking/backend/presentation/views/releases.py
@@ -4,6 +4,7 @@ from rest_framework.exceptions import NotFound, ValidationError
from rest_framework.response import Response
from rest_framework_dataclasses.serializers import DataclassSerializer
+from posthog.api.pagination import FacadeLimitOffsetPagination, facade_page_response
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
@@ -11,7 +12,6 @@ from products.error_tracking.backend.facade import (
api as error_tracking_api,
contracts,
)
-from products.error_tracking.backend.presentation.pagination import paginate_via_facade
MAX_HASH_ID_LENGTH = 128
RELEASE_HASH_IN_USE_ERROR_CODE = "release_hash_in_use"
@@ -63,6 +63,7 @@ class ErrorTrackingReleaseViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
scope_object = "error_tracking"
scope_object_read_actions = ["list", "retrieve", "by_hash"]
serializer_class = ErrorTrackingReleaseSerializer
+ pagination_class = FacadeLimitOffsetPagination
def _validated_hash_id(self, hash_id) -> str | None:
if not hash_id:
@@ -73,11 +74,7 @@ class ErrorTrackingReleaseViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
return hash_id
def list(self, request, *args, **kwargs) -> Response:
- return paginate_via_facade(
- self,
- request,
- lambda limit, offset: error_tracking_api.list_releases(self.team.id, limit=limit, offset=offset),
- )
+ return facade_page_response(self, lambda page: error_tracking_api.list_releases(self.team.id, page=page))
def retrieve(self, request, *args, pk=None, **kwargs) -> Response:
release = error_tracking_api.get_release(self.team.id, pk)
diff --git a/products/error_tracking/backend/presentation/views/spike_events.py b/products/error_tracking/backend/presentation/views/spike_events.py
index e0cc19afb587..e99944b2c3ff 100644
--- a/products/error_tracking/backend/presentation/views/spike_events.py
+++ b/products/error_tracking/backend/presentation/views/spike_events.py
@@ -3,13 +3,13 @@ from drf_spectacular.utils import OpenApiParameter, extend_schema
from rest_framework import viewsets
from rest_framework_dataclasses.serializers import DataclassSerializer
+from posthog.api.pagination import FacadeLimitOffsetPagination, facade_page_response
from posthog.api.routing import TeamAndOrgViewSetMixin
from products.error_tracking.backend.facade import (
api as error_tracking_api,
contracts,
)
-from products.error_tracking.backend.presentation.pagination import paginate_via_facade
class ErrorTrackingSpikeEventSerializer(DataclassSerializer):
@@ -20,6 +20,7 @@ class ErrorTrackingSpikeEventSerializer(DataclassSerializer):
class ErrorTrackingSpikeEventViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
scope_object = "error_tracking"
serializer_class = ErrorTrackingSpikeEventSerializer
+ pagination_class = FacadeLimitOffsetPagination
@extend_schema(
parameters=[
@@ -60,16 +61,14 @@ class ErrorTrackingSpikeEventViewSet(TeamAndOrgViewSetMixin, viewsets.GenericVie
date_to = request.query_params.get("date_to")
order_by = request.query_params.get("order_by")
- return paginate_via_facade(
+ return facade_page_response(
self,
- request,
- lambda limit, offset: error_tracking_api.list_spike_events(
+ lambda page: error_tracking_api.list_spike_events(
team_id=self.team.id,
issue_ids=issue_ids or None,
date_from=date_from,
date_to=date_to,
order_by=order_by,
- limit=limit,
- offset=offset,
+ page=page,
),
)
diff --git a/products/error_tracking/backend/presentation/views/stack_frames.py b/products/error_tracking/backend/presentation/views/stack_frames.py
index 96138b246c58..7cb03b2eacdb 100644
--- a/products/error_tracking/backend/presentation/views/stack_frames.py
+++ b/products/error_tracking/backend/presentation/views/stack_frames.py
@@ -5,6 +5,7 @@ from rest_framework.response import Response
from rest_framework_dataclasses.serializers import DataclassSerializer
from posthog.api.forbid_destroy_model import ForbidDestroyModel
+from posthog.api.pagination import FacadeLimitOffsetPagination, facade_page_response
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
@@ -12,7 +13,6 @@ from products.error_tracking.backend.facade import (
api as error_tracking_api,
contracts,
)
-from products.error_tracking.backend.presentation.pagination import paginate_via_facade
class ErrorTrackingStackFrameSerializer(DataclassSerializer):
@@ -41,13 +41,10 @@ class ErrorTrackingStackFrameViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel,
scope_object_read_actions = ["list", "retrieve", "batch_get"]
scope_object_write_actions: list = []
serializer_class = ErrorTrackingStackFrameSerializer
+ pagination_class = FacadeLimitOffsetPagination
def list(self, request, *args, **kwargs):
- return paginate_via_facade(
- self,
- request,
- lambda limit, offset: error_tracking_api.list_stack_frames(self.team.id, limit=limit, offset=offset),
- )
+ return facade_page_response(self, lambda page: error_tracking_api.list_stack_frames(self.team.id, page=page))
def retrieve(self, request, *args, pk=None, **kwargs):
frame = error_tracking_api.get_stack_frame(self.team.id, pk)
diff --git a/products/error_tracking/backend/presentation/views/symbol_sets.py b/products/error_tracking/backend/presentation/views/symbol_sets.py
index def5cc7c0097..e8a3bc2fa49e 100644
--- a/products/error_tracking/backend/presentation/views/symbol_sets.py
+++ b/products/error_tracking/backend/presentation/views/symbol_sets.py
@@ -1,12 +1,13 @@
import posthoganalytics
from drf_spectacular.utils import extend_schema
-from rest_framework import pagination, serializers, status, viewsets
+from rest_framework import serializers, status, viewsets
from rest_framework.exceptions import NotFound, ValidationError
from rest_framework.parsers import FileUploadParser, JSONParser, MultiPartParser
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework_dataclasses.serializers import DataclassSerializer
+from posthog.api.pagination import FacadeLimitOffsetPagination, facade_page_response
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
from posthog.event_usage import get_request_analytics_properties, groups
@@ -16,7 +17,6 @@ from products.error_tracking.backend.facade import (
contracts,
symbol_sets as symbol_sets_facade,
)
-from products.error_tracking.backend.presentation.pagination import paginate_via_facade
BULK_CHECK_UPLOAD_MAX_SYMBOL_SETS = 1000
@@ -203,7 +203,7 @@ class _SymbolSetDownloadResponseSerializer(serializers.Serializer):
)
-class ErrorTrackingSymbolSetPagination(pagination.LimitOffsetPagination):
+class ErrorTrackingSymbolSetPagination(FacadeLimitOffsetPagination):
max_limit = 100
@@ -232,17 +232,15 @@ class ErrorTrackingSymbolSetViewSet(TeamAndOrgViewSetMixin, viewsets.GenericView
query = ErrorTrackingSymbolSetListQuerySerializer(data=request.query_params)
query.is_valid(raise_exception=True)
params = dict(query.validated_data)
- return paginate_via_facade(
+ return facade_page_response(
self,
- request,
- lambda limit, offset: symbol_sets_facade.list_symbol_sets(
+ lambda page: symbol_sets_facade.list_symbol_sets(
self.team.id,
ref=params.get("ref"),
search=params.get("search"),
symbol_set_status=params.get("status"),
order_by=params.get("order_by"),
- limit=limit,
- offset=offset,
+ page=page,
),
)
diff --git a/products/error_tracking/backend/tests/api/test_error_tracking_api.py b/products/error_tracking/backend/tests/api/test_error_tracking_api.py
index a6566790dd04..9f5cadf0664e 100644
--- a/products/error_tracking/backend/tests/api/test_error_tracking_api.py
+++ b/products/error_tracking/backend/tests/api/test_error_tracking_api.py
@@ -601,6 +601,31 @@ class TestErrorTracking(APIBaseTest):
assert response.status_code == expected_status
+ def test_fingerprint_list_pages_one_issue_in_sql(self) -> None:
+ issue = self.create_issue(fingerprints=["first", "second", "third"])
+ self.create_issue(fingerprints=["other_issue"])
+ for day, fingerprint in enumerate(["first", "second", "third"], start=1):
+ ErrorTrackingIssueFingerprintV2.objects.filter(team=self.team, fingerprint=fingerprint).update(
+ created_at=datetime(2025, 1, day, tzinfo=UTC)
+ )
+
+ with CaptureQueriesContext(connection) as queries:
+ response = self.client.get(
+ f"/api/environments/{self.team.id}/error_tracking/fingerprints",
+ data={"issue_id": str(issue.id), "limit": "1", "offset": "1"},
+ )
+
+ assert response.status_code == 200, response.json()
+ body = response.json()
+ assert body["count"] == 3
+ assert [row["fingerprint"] for row in body["results"]] == ["second"]
+ assert body["next"] is not None
+ fingerprint_table = ErrorTrackingIssueFingerprintV2._meta.db_table
+ assert any(
+ fingerprint_table in query["sql"] and "LIMIT 1" in query["sql"].upper()
+ for query in queries.captured_queries
+ )
+
def test_fingerprint_resolve_is_scoped_to_team(self):
other_team = Team.objects.create(organization=self.organization)
other_issue = ErrorTrackingIssue.objects.create(team=other_team)
@@ -1466,6 +1491,16 @@ class TestErrorTracking(APIBaseTest):
self.assertEqual(ErrorTrackingStackFrame.objects.count(), 3)
+ # one-row pages walk the team's frames without skipping or repeating one
+ pages = [
+ self.client.get(
+ f"/api/environments/{self.team.id}/error_tracking/stack_frames", data={"limit": 1, "offset": offset}
+ ).json()
+ for offset in range(2)
+ ]
+ self.assertEqual([page["count"] for page in pages], [2, 2])
+ self.assertEqual({page["results"][0]["raw_id"] for page in pages}, {"raw_id/0", "other_raw_id/0"})
+
# it only fetches stack traces for the specified team
response = self.client.post(f"/api/environments/{self.team.id}/error_tracking/stack_frames/batch_get")
self.assertEqual(len(response.json()["results"]), 2)
diff --git a/products/error_tracking/frontend/generated/api.schemas.ts b/products/error_tracking/frontend/generated/api.schemas.ts
index bbf7ba42ab6e..67276ab61c8b 100644
--- a/products/error_tracking/frontend/generated/api.schemas.ts
+++ b/products/error_tracking/frontend/generated/api.schemas.ts
@@ -2761,6 +2761,7 @@ export type ErrorTrackingFingerprintsListParams = {
issue_id?: string
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number
/**
@@ -2825,6 +2826,7 @@ export type ErrorTrackingGitProviderFileLinksResolveGitlabRetrieveParams = {
export type ErrorTrackingIssuesListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number
/**
@@ -2897,6 +2899,7 @@ export const ErrorTrackingRecommendationsSourceMapsExamplesRetrievePlatform = {
export type ErrorTrackingReleasesListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number
/**
@@ -2920,6 +2923,7 @@ export type ErrorTrackingSpikeEventsListParams = {
issue_ids?: string
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number
/**
@@ -2935,6 +2939,7 @@ export type ErrorTrackingSpikeEventsListParams = {
export type ErrorTrackingStackFramesListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number
/**
@@ -2957,6 +2962,7 @@ export type ErrorTrackingSuppressionRulesListParams = {
export type ErrorTrackingSymbolSetsListParams = {
/**
* Number of results to return per page.
+ * @maximum 100
*/
limit?: number
/**
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.py
index cda08645418b..43104cbfa88a 100644
--- a/products/metrics/backend/facade/api.py
+++ b/products/metrics/backend/facade/api.py
@@ -30,7 +30,7 @@ from posthog.clickhouse.client.connection import Workload
from posthog.hogql_queries.utils.parallel import run_in_parallel_threads
from posthog.models import Team, User
-from products.error_tracking.backend.facade.api import list_spike_events
+from products.error_tracking.backend.facade.api import list_latest_spike_events
from products.metrics.backend.anomaly import characterize_anomaly as _characterize_anomaly
from products.metrics.backend.date_range import metrics_query_date_range
from products.metrics.backend.facade.contracts import (
@@ -662,12 +662,11 @@ def list_metric_error_spikes(*, team: Team, date_from: dt.datetime, date_to: dt.
Team-wide: Error Tracking issues carry no service attribution today, so
this cannot be scoped to the metric's own service yet.
"""
- events, _total = list_spike_events(
+ events = list_latest_spike_events(
team_id=team.id,
date_from=date_from.isoformat(),
date_to=date_to.isoformat(),
limit=_ERROR_SPIKES_LIMIT,
- include_total_count=False,
)
return [
MetricErrorSpike(
diff --git a/products/workflows/backend/test/test_workflow_customer_tasks.py b/products/workflows/backend/test/test_workflow_customer_tasks.py
index cb564d3e55a4..7b767f196155 100644
--- a/products/workflows/backend/test/test_workflow_customer_tasks.py
+++ b/products/workflows/backend/test/test_workflow_customer_tasks.py
@@ -15,6 +15,7 @@ from posthog.constants import AvailableFeature
from posthog.jwt import PosthogJwtAudience, encode_jwt
from posthog.models import OrganizationMembership, Team, User
from posthog.models.team.team import DEPRECATED_ATTRS
+from posthog.paging import PageRequest
from posthog.test.authentication_checks import covers_authentication
from posthog.test.db_context_capturing import capture_db_queries
@@ -54,25 +55,22 @@ class TestWorkflowCustomerTasks(APIBaseTest):
return UserAccessControl(user=self.user, team=team or self.team)
def _get_task_count(self) -> int:
- _, total = api.list_customer_tasks(
+ return api.list_customer_tasks(
team_id=self.team.id,
user_access_control=self._get_user_access_control(),
filters=contracts.CustomerTaskListFilters(archive_state="all"),
- offset=0,
- limit=1,
- )
- return total
+ page=PageRequest(limit=1),
+ ).count
def _get_task_activity_count(self, task_id: UUID | str) -> int:
result = api.list_customer_task_activities(
team_id=self.team.id,
task_id=task_id,
user_access_control=self._get_user_access_control(),
- offset=0,
- limit=1,
+ page=PageRequest(limit=1),
)
assert result is not None
- return result[1]
+ return result.count
def _token(self, **claims: Any) -> str:
return encode_jwt(
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6a107e66c69f..938d8d6532ca 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -130994,6 +130994,7 @@ export namespace Schemas {
created_by?: number[];
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number;
/**
@@ -131009,6 +131010,7 @@ export namespace Schemas {
export type AccountRelationshipDefinitionsListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number;
/**
@@ -131031,6 +131033,7 @@ export namespace Schemas {
export type AccountTrackRulesRunsListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number;
/**
@@ -131065,6 +131068,7 @@ export namespace Schemas {
include_ignored?: boolean;
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number;
/**
@@ -131114,6 +131118,7 @@ export namespace Schemas {
export type AccountsEmailThreadsListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number;
/**
@@ -131125,6 +131130,7 @@ export namespace Schemas {
export type AccountsEmailThreadMessagesListParams = {
/**
* Number of results to return per page.
+ * @maximum 200
*/
limit?: number;
/**
@@ -131136,6 +131142,7 @@ export namespace Schemas {
export type AccountsMeetingsListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number;
/**
@@ -131151,6 +131158,7 @@ export namespace Schemas {
export type AccountsSummariesListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number;
/**
@@ -131162,6 +131170,7 @@ export namespace Schemas {
export type AccountsSupportTicketMessagesListParams = {
/**
* Number of results to return per page.
+ * @maximum 200
*/
limit?: number;
/**
@@ -132405,6 +132414,7 @@ export namespace Schemas {
export type AnnouncementsListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number;
/**
@@ -133705,6 +133715,7 @@ export namespace Schemas {
export type CustomPropertyDefinitionsListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number;
/**
@@ -133738,6 +133749,7 @@ export namespace Schemas {
export type CustomPropertySourcesListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number;
/**
@@ -133749,6 +133761,7 @@ export namespace Schemas {
export type CustomPropertySourcesRunsListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number;
/**
@@ -133764,6 +133777,7 @@ export namespace Schemas {
export type CustomerJourneysListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number;
/**
@@ -133775,6 +133789,7 @@ export namespace Schemas {
export type CustomerProfileConfigsListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number;
/**
@@ -136520,6 +136535,7 @@ export namespace Schemas {
issue_id?: string;
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number;
/**
@@ -136584,6 +136600,7 @@ export namespace Schemas {
export type ErrorTrackingIssuesListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number;
/**
@@ -136656,6 +136673,7 @@ export namespace Schemas {
export type ErrorTrackingReleasesListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number;
/**
@@ -136679,6 +136697,7 @@ export namespace Schemas {
issue_ids?: string;
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number;
/**
@@ -136694,6 +136713,7 @@ export namespace Schemas {
export type ErrorTrackingStackFramesListParams = {
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number;
/**
@@ -136716,6 +136736,7 @@ export namespace Schemas {
export type ErrorTrackingSymbolSetsListParams = {
/**
* Number of results to return per page.
+ * @maximum 100
*/
limit?: number;
/**
@@ -137724,6 +137745,7 @@ export namespace Schemas {
created_by_ids?: number[];
/**
* Number of results to return per page.
+ * @maximum 1000
*/
limit?: number;
/**
diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.ts
index 387d183a02f7..c1a1d603de44 100644
--- a/services/mcp/src/generated/customer_analytics/api.ts
+++ b/services/mcp/src/generated/customer_analytics/api.ts
@@ -16,8 +16,14 @@ export const AccountRelationshipDefinitionsListParams = () => zod.object({
),
})
+export const accountRelationshipDefinitionsListQueryLimitMax = 1000
+
export const AccountRelationshipDefinitionsListQueryParams = () => zod.object({
- limit: zod.number().optional().describe('Number of results to return per page.'),
+ limit: zod
+ .number()
+ .max(accountRelationshipDefinitionsListQueryLimitMax)
+ .optional()
+ .describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
pagination: zod.enum(['none']).optional().describe('Return all definitions in one response when set to none.'),
})
@@ -117,6 +123,7 @@ export const AccountsListParams = () => zod.object({
export const accountsListQueryInactiveLastDefault = false
export const accountsListQueryIncludeChurnedDefault = false
export const accountsListQueryIncludeIgnoredDefault = false
+export const accountsListQueryLimitMax = 1000
export const AccountsListQueryParams = () => zod.object({
all_roles_unassigned: zod
@@ -137,7 +144,7 @@ export const AccountsListQueryParams = () => zod.object({
.boolean()
.default(accountsListQueryIncludeIgnoredDefault)
.describe('Include ignored accounts. Ignored accounts are hidden by default.'),
- limit: zod.number().optional().describe('Number of results to return per page.'),
+ limit: zod.number().max(accountsListQueryLimitMax).optional().describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
ordering: zod.string().optional().describe("Sort order. Defaults to '-created_at'."),
search: zod
@@ -475,8 +482,14 @@ export const AccountsMeetingsListParams = () => zod.object({
),
})
+export const accountsMeetingsListQueryLimitMax = 1000
+
export const AccountsMeetingsListQueryParams = () => zod.object({
- limit: zod.number().optional().describe('Number of results to return per page.'),
+ limit: zod
+ .number()
+ .max(accountsMeetingsListQueryLimitMax)
+ .optional()
+ .describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
search: zod.string().optional().describe('Filter meetings by title or attendee email\/name.'),
})
@@ -490,8 +503,14 @@ export const AccountsSummariesListParams = () => zod.object({
),
})
+export const accountsSummariesListQueryLimitMax = 1000
+
export const AccountsSummariesListQueryParams = () => zod.object({
- limit: zod.number().optional().describe('Number of results to return per page.'),
+ limit: zod
+ .number()
+ .max(accountsSummariesListQueryLimitMax)
+ .optional()
+ .describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
})
@@ -503,8 +522,14 @@ export const AnnouncementsListParams = () => zod.object({
),
})
+export const announcementsListQueryLimitMax = 1000
+
export const AnnouncementsListQueryParams = () => zod.object({
- limit: zod.number().optional().describe('Number of results to return per page.'),
+ limit: zod
+ .number()
+ .max(announcementsListQueryLimitMax)
+ .optional()
+ .describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
})
@@ -562,8 +587,14 @@ export const CustomPropertyDefinitionsListParams = () => zod.object({
),
})
+export const customPropertyDefinitionsListQueryLimitMax = 1000
+
export const CustomPropertyDefinitionsListQueryParams = () => zod.object({
- limit: zod.number().optional().describe('Number of results to return per page.'),
+ limit: zod
+ .number()
+ .max(customPropertyDefinitionsListQueryLimitMax)
+ .optional()
+ .describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
pagination: zod.enum(['none']).optional().describe('Return all definitions in one response when set to none.'),
})
@@ -787,8 +818,14 @@ export const CustomPropertySourcesListParams = () => zod.object({
),
})
+export const customPropertySourcesListQueryLimitMax = 1000
+
export const CustomPropertySourcesListQueryParams = () => zod.object({
- limit: zod.number().optional().describe('Number of results to return per page.'),
+ limit: zod
+ .number()
+ .max(customPropertySourcesListQueryLimitMax)
+ .optional()
+ .describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
})
@@ -948,8 +985,14 @@ export const CustomPropertySourcesRunsListParams = () => zod.object({
),
})
+export const customPropertySourcesRunsListQueryLimitMax = 1000
+
export const CustomPropertySourcesRunsListQueryParams = () => zod.object({
- limit: zod.number().optional().describe('Number of results to return per page.'),
+ limit: zod
+ .number()
+ .max(customPropertySourcesRunsListQueryLimitMax)
+ .optional()
+ .describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
search: zod
.string()
@@ -1420,6 +1463,8 @@ export const FeatureRequestsListParams = () => zod.object({
})
export const featureRequestsListQueryArchiveStateDefault = `active`
+export const featureRequestsListQueryLimitMax = 1000
+
export const featureRequestsListQueryRequestOrderingDefault = `-updated_at`
export const FeatureRequestsListQueryParams = () => zod.object({
@@ -1437,7 +1482,11 @@ export const FeatureRequestsListQueryParams = () => zod.object({
.array(zod.number().min(1))
.optional()
.describe('Creator user IDs to include. Multiple values use OR semantics.'),
- limit: zod.number().optional().describe('Number of results to return per page.'),
+ limit: zod
+ .number()
+ .max(featureRequestsListQueryLimitMax)
+ .optional()
+ .describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
priorities: zod
.array(
diff --git a/services/mcp/src/generated/error_tracking/api.ts b/services/mcp/src/generated/error_tracking/api.ts
index 716c4d4c6297..3a3ccaa58230 100644
--- a/services/mcp/src/generated/error_tracking/api.ts
+++ b/services/mcp/src/generated/error_tracking/api.ts
@@ -15334,10 +15334,16 @@ export const ErrorTrackingSymbolSetsListParams = () => zod.object({
),
})
+export const errorTrackingSymbolSetsListQueryLimitMax = 100
+
export const errorTrackingSymbolSetsListQueryStatusDefault = `all`
export const ErrorTrackingSymbolSetsListQueryParams = () => zod.object({
- limit: zod.number().optional().describe('Number of results to return per page.'),
+ limit: zod
+ .number()
+ .max(errorTrackingSymbolSetsListQueryLimitMax)
+ .optional()
+ .describe('Number of results to return per page.'),
offset: zod.number().optional().describe('The initial index from which to return the results.'),
order_by: zod
.string()
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-symbol-sets-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-symbol-sets-list.json
index af43f2f1197e..18fe0c181043 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-symbol-sets-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/error-tracking-symbol-sets-list.json
@@ -3,6 +3,7 @@
"properties": {
"limit": {
"description": "Number of results to return per page.",
+ "maximum": 100,
"type": "number"
},
"offset": {