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(api): stabilize paginated list ordering (#104980)

Paul D'Ambraeda371d15b74
diff --git a/posthog/api/pagination.py b/posthog/api/pagination.py
index 4148a1c7c16a..742913c8bd93 100644
--- a/posthog/api/pagination.py
+++ b/posthog/api/pagination.py
@@ -1,8 +1,27 @@
from typing import Any, Optional
+from django.db.models import QuerySet
+
from rest_framework.pagination import LimitOffsetPagination
+def stable_queryset_ordering(queryset: QuerySet) -> QuerySet:
+ """Add the primary key as a final ordering term for a paginated queryset."""
+ if queryset.query.is_sliced or queryset.query.group_by is not None:
+ return queryset
+
+ ordering = queryset.query.order_by or queryset.query.extra_order_by or queryset.model._meta.ordering
+ if not ordering:
+ return queryset.order_by("pk")
+
+ primary_key = queryset.model._meta.pk.name
+ if any(str(term).lstrip("-") in {"pk", primary_key} for term in ordering):
+ return queryset
+
+ direction = "-" if str(ordering[0]).startswith("-") else ""
+ return queryset.order_by(*ordering, f"{direction}pk")
+
+
class PrecountedLimitOffsetPagination(LimitOffsetPagination):
"""Pages a queryset that the view has already bounded with LIMIT and OFFSET.
diff --git a/posthog/api/routing.py b/posthog/api/routing.py
index f89e9c5384e0..757a59cecf2d 100644
--- a/posthog/api/routing.py
+++ b/posthog/api/routing.py
@@ -1,4 +1,5 @@
import sys
+from collections.abc import Sequence
from functools import cached_property, lru_cache
from typing import TYPE_CHECKING, Any, Literal, Optional, cast
from uuid import UUID
@@ -12,6 +13,7 @@ from rest_framework.viewsets import GenericViewSet
from rest_framework_extensions.routers import ExtendedDefaultRouter, NestedRegistryItem
from rest_framework_extensions.settings import extensions_api_settings
+from posthog.api.pagination import stable_queryset_ordering
from posthog.api.utils import get_token
from posthog.auth import (
DelegatedOAuthAccessTokenAuthentication,
@@ -369,6 +371,11 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):
finally:
self._in_get_queryset = False
+ def paginate_queryset(self, queryset: QuerySet | Sequence) -> Sequence | None:
+ if self.paginator is not None and isinstance(queryset, QuerySet):
+ queryset = stable_queryset_ordering(queryset)
+ return super().paginate_queryset(queryset)
+
def _filter_queryset_by_access_level(self, queryset: QuerySet) -> QuerySet:
if self.action != "list":
# NOTE: If we are getting an individual object then we don't filter it out here - this is handled by the permission logic
diff --git a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
index f186fe88fd66..b374c2aab15a 100644
--- a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
+++ b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
@@ -4033,7 +4033,8 @@
AND NOT ("posthog_dashboard"."deleted")
AND NOT ("posthog_dashboard"."creation_mode" = 'unlisted'))
ORDER BY "posthog_dashboard"."pinned" DESC,
- "posthog_dashboard"."name" ASC
+ "posthog_dashboard"."name" ASC,
+ "posthog_dashboard"."id" DESC
LIMIT 300
'''
# ---
@@ -16348,7 +16349,8 @@
AND NOT ("posthog_dashboard"."deleted")
AND NOT ("posthog_dashboard"."creation_mode" = 'unlisted'))
ORDER BY "posthog_dashboard"."pinned" DESC,
- "posthog_dashboard"."name" ASC
+ "posthog_dashboard"."name" ASC,
+ "posthog_dashboard"."id" DESC
LIMIT 100
'''
# ---
diff --git a/posthog/api/test/test_routing.py b/posthog/api/test/test_routing.py
index fdc682855e61..9b3034298ef5 100644
--- a/posthog/api/test/test_routing.py
+++ b/posthog/api/test/test_routing.py
@@ -7,6 +7,8 @@ from datetime import timedelta
import pytest
from posthog.test.base import APIBaseTest
+from django.db.models import Count
+from django.db.models.functions import Lower
from django.test import override_settings
from django.urls import include, path
from django.utils import timezone
@@ -18,8 +20,10 @@ from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
+from posthog.api.pagination import stable_queryset_ordering
from posthog.api.routing import DefaultRouterPlusPlus, RouterRegistry, TeamAndOrgViewSetMixin
from posthog.auth import ProjectSecretAPIKeyAuthentication
+from posthog.models.file_system.file_system import FileSystem
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.organization import Organization
from posthog.models.personal_api_key import PersonalAPIKey
@@ -50,6 +54,32 @@ class ScopedFooViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
serializer_class = AnnotationSerializer
+class OrderedFooViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
+ scope_object = "INTERNAL"
+ queryset = Annotation.objects.filter(date_marker__isnull=False).order_by("date_marker")
+ serializer_class = AnnotationSerializer
+
+
+def test_stable_queryset_ordering_adds_a_primary_key_tiebreaker() -> None:
+ queryset = stable_queryset_ordering(Annotation.objects.order_by("date_marker"))
+
+ assert queryset.query.order_by == ("date_marker", "pk")
+
+ expression_queryset = stable_queryset_ordering(FileSystem.objects.order_by(Lower("path")))
+
+ assert expression_queryset.query.order_by[-1] == "pk"
+
+
+def test_stable_queryset_ordering_leaves_sliced_and_grouped_querysets_unchanged() -> None:
+ sliced_queryset = Annotation.objects.order_by("date_marker")[:1]
+
+ assert stable_queryset_ordering(sliced_queryset) is sliced_queryset
+
+ grouped_queryset = Annotation.objects.values("team_id").annotate(count=Count("id")).order_by("team_id")
+
+ assert stable_queryset_ordering(grouped_queryset).query.order_by == ("team_id",)
+
+
test_router = DefaultRouterPlusPlus()
# A team_id-nested parent (distinct from the project_id-nested one below) so the mixin's
@@ -58,6 +88,8 @@ test_router = DefaultRouterPlusPlus()
# which would mask the team_id-lookup behavior these tests cover.
test_team_nested_router = test_router.register(r"team_nested", FooViewSet, "team_nested")
test_team_nested_router.register(r"foos", FooViewSet, "team_nested_foos", ["team_id"])
+test_ordered_router = test_router.register(r"team_ordered", OrderedFooViewSet, "team_ordered")
+test_ordered_router.register(r"foos", OrderedFooViewSet, "team_ordered_foos", ["team_id"])
test_projects_router = test_router.register(r"projects", FooViewSet, "projects")
test_projects_router.register(r"foos", FooViewSet, "project_foos", ["project_id"])
@@ -138,6 +170,19 @@ class TestTeamAndOrgViewSetMixin(APIBaseTest):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()["count"], 1) # Just current_team_annotation
+ def test_team_nested_pagination_adds_primary_key_tiebreaker(self):
+ marker = timezone.now()
+ first = Annotation.objects.create(team=self.team, organization=self.organization, date_marker=marker)
+ second = Annotation.objects.create(team=self.team, organization=self.organization, date_marker=marker)
+
+ first_page = self.client.get(f"/api/team_ordered/{self.team.id}/foos/?limit=1")
+ second_page = self.client.get(f"/api/team_ordered/{self.team.id}/foos/?limit=1&offset=1")
+
+ self.assertEqual(first_page.status_code, 200)
+ self.assertEqual(second_page.status_code, 200)
+ self.assertEqual(first_page.json()["results"][0]["id"], first.id)
+ self.assertEqual(second_page.json()["results"][0]["id"], second.id)
+
def test_project_nested_filtering(self):
response = self.client.get(f"/api/projects/{self.team.id}/foos/")
self.assertEqual(response.status_code, 200)
diff --git a/posthog/api/user.py b/posthog/api/user.py
index dab96da13af0..91670d7bbb79 100644
--- a/posthog/api/user.py
+++ b/posthog/api/user.py
@@ -1020,7 +1020,7 @@ class UserViewSet(
time_sensitive_allow_actions = ["hedgehog_config"]
filter_backends = [DjangoFilterBackend]
filterset_fields = ["is_staff", "email"]
- queryset = User.objects.filter(is_active=True)
+ queryset = User.objects.filter(is_active=True).order_by("id")
lookup_field = "uuid"
def dangerously_get_required_scopes(self, request, view) -> list[str] | None:
diff --git a/products/cdp/backend/api/test/__snapshots__/test_plugin.ambr b/products/cdp/backend/api/test/__snapshots__/test_plugin.ambr
index 65f810a9146a..dd3ec1a77aff 100644
--- a/products/cdp/backend/api/test/__snapshots__/test_plugin.ambr
+++ b/products/cdp/backend/api/test/__snapshots__/test_plugin.ambr
@@ -337,6 +337,7 @@
INNER JOIN "posthog_team" U1 ON (U0."team_id" = U1."id")
WHERE (NOT U0."deleted"
AND U1."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid)))
+ ORDER BY "posthog_plugin"."id" ASC
LIMIT 100
'''
# ---
@@ -770,6 +771,7 @@
INNER JOIN "posthog_team" U1 ON (U0."team_id" = U1."id")
WHERE (NOT U0."deleted"
AND U1."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid)))
+ ORDER BY "posthog_plugin"."id" ASC
LIMIT 100
'''
# ---
@@ -1212,6 +1214,7 @@
INNER JOIN "posthog_team" U1 ON (U0."team_id" = U1."id")
WHERE (NOT U0."deleted"
AND U1."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid)))
+ ORDER BY "posthog_plugin"."id" ASC
LIMIT 100
'''
# ---
diff --git a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
index ffb357cadbd4..053e325e2097 100644
--- a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
+++ b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
@@ -1217,7 +1217,8 @@
LEFT OUTER JOIN "posthog_user" ON ("posthog_dashboarditem"."created_by_id" = "posthog_user"."id")
WHERE ("posthog_team"."project_id" = 99999
AND NOT ("posthog_dashboarditem"."deleted"))
- ORDER BY "posthog_dashboarditem"."order" ASC
+ ORDER BY "posthog_dashboarditem"."order" ASC,
+ "posthog_dashboarditem"."id" ASC
LIMIT 100
'''
# ---