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(subscriptions): break list sort ties on id (#101567)

posthog[bot]885a787544e0
diff --git a/ee/api/subscription.py b/ee/api/subscription.py
index 50a499d3587f..0098e5effb64 100644
--- a/ee/api/subscription.py
+++ b/ee/api/subscription.py
@@ -1,6 +1,6 @@
import uuid
import asyncio
-from collections.abc import Callable, Iterable
+from collections.abc import Callable, Iterable, Sequence
from typing import Any, ClassVar, Optional
from django.conf import settings
@@ -1521,6 +1521,21 @@ def _subscription_is_ai_prompt(subscription_id: str | int, team_id: int) -> bool
)
+class StableOrderingFilter(filters.OrderingFilter):
+ """`OrderingFilter` that appends `id` to every ordering, so tied rows keep one fixed position.
+
+ Limit-offset pagination runs a separate query for each page. No sortable column here is unique:
+ one creator owns many subscriptions, titles repeat, and unscheduled rows share a null delivery
+ date. Without a unique last key, Postgres can put a tied row on two pages, or on no page at all.
+ """
+
+ def get_ordering(self, request, queryset, view) -> Sequence[str] | None:
+ ordering = super().get_ordering(request, queryset, view)
+ if not ordering:
+ return ordering
+ return [*ordering, "-id" if ordering[-1].startswith("-") else "id"]
+
+
@extend_schema_view(
list=extend_schema(
extensions={"x-product": "subscriptions"},
@@ -1601,7 +1616,7 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.M
scope_object = "subscription"
queryset = Subscription.objects.all()
serializer_class = SubscriptionSerializer
- filter_backends = [filters.SearchFilter, filters.OrderingFilter]
+ filter_backends = [filters.SearchFilter, StableOrderingFilter]
search_fields = [
"title",
"insight__name",
diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.py
index 9752a9267981..36f6eda7e8b1 100644
--- a/ee/api/test/test_subscription.py
+++ b/ee/api/test/test_subscription.py
@@ -1689,6 +1689,42 @@ class TestSubscriptionTemporal(APILicensedTest):
desc_ids = [row["id"] for row in desc_res.json()["results"]]
assert desc_ids.index(first_id) < desc_ids.index(second_id)
+ @parameterized.expand(
+ [
+ (None, "DESC"),
+ ("created_at", "ASC"),
+ ("-created_at", "DESC"),
+ ("title", "ASC"),
+ ("-title", "DESC"),
+ ("next_delivery_date", "ASC"),
+ ("-created_by__email", "DESC"),
+ ]
+ )
+ def test_list_subscriptions_break_sort_ties_on_id(self, ordering, expected_direction):
+ first = self._create_subscription(title="Tied subscription")
+ second = self._create_subscription(title="Tied subscription")
+ assert first.status_code == status.HTTP_201_CREATED
+ assert second.status_code == status.HTTP_201_CREATED
+ first_id = first.json()["id"]
+ second_id = second.json()["id"]
+ tied_at = datetime(2030, 1, 1, tzinfo=UTC)
+ Subscription.objects.filter(id__in=[first_id, second_id]).update(
+ created_at=tied_at,
+ next_delivery_date=tied_at,
+ )
+
+ params = {"limit": 1}
+ if ordering:
+ params["ordering"] = ordering
+ first_page = self.client.get(f"/api/projects/{self.team.id}/subscriptions/", params)
+ second_page = self.client.get(f"/api/projects/{self.team.id}/subscriptions/", {**params, "offset": 1})
+ assert first_page.status_code == status.HTTP_200_OK
+ assert second_page.status_code == status.HTTP_200_OK
+
+ page_ids = [first_page.json()["results"][0]["id"], second_page.json()["results"][0]["id"]]
+ expected_ids = [first_id, second_id] if expected_direction == "ASC" else [second_id, first_id]
+ assert page_ids == expected_ids
+
@parameterized.expand(
[
("title",),