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: pagination on replay collections page (#63497)

Christian Rafferty7404082a9a3f
diff --git a/posthog/session_recordings/session_recording_playlist_api.py b/posthog/session_recordings/session_recording_playlist_api.py
index f536ec819efe..5e33ba9c2055 100644
--- a/posthog/session_recordings/session_recording_playlist_api.py
+++ b/posthog/session_recordings/session_recording_playlist_api.py
@@ -6,7 +6,8 @@ from typing import Any, Optional, cast
from django.contrib.auth.models import AnonymousUser
from django.db import IntegrityError, transaction
-from django.db.models import Count, Q, QuerySet
+from django.db.models import Count, Q, QuerySet, Value
+from django.db.models.functions import Coalesce, Lower, NullIf
from django.utils.timezone import now
import structlog
@@ -15,6 +16,7 @@ from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter
from loginas.utils import is_impersonated_session
+from opentelemetry import trace
from rest_framework import request, response, serializers, viewsets
from rest_framework.exceptions import ValidationError
from rest_framework.pagination import LimitOffsetPagination
@@ -51,6 +53,7 @@ from posthog.session_recordings.synthetic_playlists import (
from posthog.utils import relative_date_parse
logger = structlog.get_logger(__name__)
+tracer = trace.get_tracer(__name__)
PLAYLIST_COUNT_REDIS_PREFIX = "@posthog/replay/playlist_filters_match_count/"
@@ -71,6 +74,54 @@ class SessionRecordingPlaylistPagination(LimitOffsetPagination):
max_limit = PLAYLIST_LIST_MAX_LIMIT
+DEFAULT_PLAYLIST_ORDER = "-last_modified_at"
+# Orders the list endpoint supports. An unrecognised `order` normalises to the
+# default so the DB slice and the synthetic-rank maths can't disagree on an unknown
+# field — and so order_by() can't 500 on malformed input.
+SUPPORTED_PLAYLIST_ORDER_FIELDS = frozenset({"last_modified_at", "created_at", "name"})
+
+
+def resolve_playlist_order(req: request.Request) -> str:
+ """Normalise the requested `order` to a supported value, else the default.
+
+ Single source of truth shared by safely_get_queryset, _order_playlists and
+ _synthetic_global_ranks so the three never drift on what "the order" is.
+ """
+ order = req.GET.get("order") or DEFAULT_PLAYLIST_ORDER
+ return order if order.lstrip("-") in SUPPORTED_PLAYLIST_ORDER_FIELDS else DEFAULT_PLAYLIST_ORDER
+
+
+def playlist_name_sort_expression() -> Coalesce:
+ """DB ordering key for playlist names: case-insensitive, NULL- and empty-safe.
+
+ playlist_name_sort_key is its in-memory twin; the two MUST stay equivalent or
+ pagination silently skips/duplicates rows. NullIf mirrors the Python `or`, which
+ treats an empty name as absent and falls through to derived_name — Coalesce alone
+ only falls through on NULL.
+ """
+ return Coalesce(Lower(NullIf("name", Value(""))), Lower("derived_name"), Value(""))
+
+
+def playlist_name_sort_key(playlist: SessionRecordingPlaylist) -> str:
+ """In-memory twin of playlist_name_sort_expression."""
+ return (playlist.name or playlist.derived_name or "").lower()
+
+
+def parse_non_negative_int(value: Any, default: int) -> int:
+ try:
+ return max(0, int(value))
+ except (TypeError, ValueError):
+ return default
+
+
+def parse_positive_int(value: Any, default: int) -> int:
+ """Like parse_non_negative_int but rejects 0. A limit of 0 makes the paginator's
+ next link point back at the same offset — an infinite-paging loop — so non-positive
+ input falls back to the default, matching DRF's LimitOffsetPagination."""
+ parsed = parse_non_negative_int(value, default)
+ return parsed if parsed > 0 else default
+
+
def create_synthetic_playlist_instance(
synthetic_def: SyntheticPlaylistDefinition, team: Team, user: User
) -> SessionRecordingPlaylist:
@@ -586,80 +637,153 @@ class SessionRecordingPlaylistViewSet(
# Fall back to normal DB lookup
return super().safely_get_object(queryset)
+ @tracer.start_as_current_span("session_recording_playlists_list")
def list(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:
- """Override list to include synthetic playlists"""
- # Get regular DB playlists
+ """Override list to include synthetic playlists.
+
+ Synthetics have no DB row, so we compute each one's position in the merged
+ sort and split the requested page between synthetics and a DB queryset slice.
+ The merge/rank/sort is all in-memory, so each phase is wrapped in a span and
+ the input sizes are recorded as span attributes — a slow response on a team
+ with many playlists then shows up as a wide span against a large db_count.
+ """
+ span = trace.get_current_span()
queryset = self.safely_get_queryset(self.get_queryset())
+ db_count = queryset.count()
- # Apply pagination to DB playlists. The paginator computes the DB count
- # internally, so reuse it rather than issuing a second COUNT(*).
- page = self.paginate_queryset(queryset)
- paginator = cast(LimitOffsetPagination, self.paginator)
- db_count = paginator.count if page is not None and paginator.count is not None else queryset.count()
+ with tracer.start_as_current_span("gather_synthetics"):
+ all_synthetic_playlists = get_all_synthetic_playlists()
+ synthetic_instances = [
+ create_synthetic_playlist_instance(sp, self.team, cast(User, request.user))
+ for sp in all_synthetic_playlists
+ ]
+ filtered_synthetics = self._filter_synthetic_playlists(request, synthetic_instances)
+ sorted_synthetics = self._order_playlists(request, filtered_synthetics)
- # Check if we're on the first page by looking at offset parameter
- # Synthetic playlists should only appear on the first page to avoid duplicates
- offset = int(request.GET.get("offset", 0))
- page_number = int(request.GET.get("page", 1))
- is_first_page = offset == 0 and page_number == 1
-
- # Create synthetic playlist instances
- all_synthetic_playlists = get_all_synthetic_playlists()
- synthetic_instances = [
- create_synthetic_playlist_instance(sp, self.team, cast(User, request.user))
- for sp in all_synthetic_playlists
- ]
+ synth_count = len(sorted_synthetics)
+ total_count = db_count + synth_count
- # Filter synthetic playlists based on request filters
- filtered_synthetics = self._filter_synthetic_playlists(request, synthetic_instances)
+ limit = min(parse_positive_int(request.GET.get("limit"), 100), PLAYLIST_LIST_MAX_LIMIT)
+ offset = parse_non_negative_int(request.GET.get("offset"), 0)
- # Only include synthetic playlists on the first page
- synthetics_to_include = filtered_synthetics if is_first_page else []
+ span.set_attribute("team_id", self.team.id)
+ span.set_attribute("db_count", db_count)
+ span.set_attribute("synth_count", synth_count)
+ span.set_attribute("limit", limit)
+ span.set_attribute("offset", offset)
- # Combine DB and synthetic playlists
- if page is not None:
- combined = list(page) + synthetics_to_include
- else:
- combined = list(queryset) + synthetics_to_include
+ # Pair each synthetic with its global rank at the source so the two never
+ # drift, then split the requested window into in-page synthetics + DB slice.
+ with tracer.start_as_current_span("rank_synthetics"):
+ synth_ranks = self._synthetic_global_ranks(request, queryset, db_count, sorted_synthetics)
+ ranked_synthetics = list(zip(synth_ranks, sorted_synthetics))
+
+ with tracer.start_as_current_span("split_page"):
+ synth_for_page, db_items = self._split_page(offset, limit, ranked_synthetics, queryset)
- # Apply ordering to the combined list
- combined = self._order_playlists(request, combined)
+ with tracer.start_as_current_span("order_combined_page"):
+ combined = self._order_playlists(request, synth_for_page + db_items)
- # Enforce page size on the combined result so synthetic playlists
- # don't cause the response to exceed the requested limit. The paginator
- # already caps DB-backed pages at PLAYLIST_LIST_MAX_LIMIT; clamp here too
- # so the synthetic slice is bounded identically.
- limit = min(int(request.GET.get("limit", 100)), PLAYLIST_LIST_MAX_LIMIT)
- combined = combined[:limit]
+ span.set_attribute("page_size", len(combined))
# Batch-fetch recording counts for the page to avoid the per-playlist
# N+1 queries performed by SessionRecordingPlaylistSerializer.get_recordings_counts.
# On failure we log and attach empty prefetched attrs so the serializer
# short-circuits to default empty counts instead of retrying per-playlist
# (which amplifies load during a Redis/DB partial outage).
- try:
- precompute_recordings_counts(combined, cast(User, request.user), self.team)
- except Exception as e:
- logger.exception(
- "playlist_recordings_counts_precompute_failed",
- team_id=self.team.id,
- page_size=len(combined),
- )
- posthoganalytics.capture_exception(e)
- _attach_empty_recordings_counts(combined)
+ with tracer.start_as_current_span("precompute_recordings_counts"):
+ try:
+ precompute_recordings_counts(combined, cast(User, request.user), self.team)
+ except Exception as e:
+ logger.exception(
+ "playlist_recordings_counts_precompute_failed",
+ team_id=self.team.id,
+ page_size=len(combined),
+ )
+ posthoganalytics.capture_exception(e)
+ _attach_empty_recordings_counts(combined)
- serializer = self.get_serializer(combined, many=True)
+ with tracer.start_as_current_span("serialize"):
+ results = self.get_serializer(combined, many=True).data
- # Calculate total count including synthetic playlists (only counted once on first page)
- total_count = db_count + len(filtered_synthetics)
+ next_link, previous_link = self._pagination_links(request, total_count, limit, offset)
+ return response.Response(
+ {
+ "count": total_count,
+ "next": next_link,
+ "previous": previous_link,
+ "results": results,
+ }
+ )
+
+ def _split_page(
+ self,
+ offset: int,
+ limit: int,
+ ranked_synthetics: builtins.list[tuple[int, SessionRecordingPlaylist]],
+ queryset: QuerySet,
+ ) -> tuple[builtins.list[SessionRecordingPlaylist], builtins.list[SessionRecordingPlaylist]]:
+ """Split one page into its in-window synthetics and the aligned DB slice.
+
+ Synthetics whose global rank falls in [offset, offset+limit) belong on this
+ page; the DB slice fills the rest, shifted left by however many synthetics
+ sort ahead of the page so the two never overlap or leave a gap.
+ """
+ page_end = offset + limit
+ synth_for_page = [s for r, s in ranked_synthetics if offset <= r < page_end]
+ synths_before_page = sum(1 for r, _ in ranked_synthetics if r < offset)
+
+ db_offset = max(0, offset - synths_before_page)
+ db_take = max(0, limit - len(synth_for_page))
+ db_items = list(queryset[db_offset : db_offset + db_take]) if db_take > 0 else []
+ return synth_for_page, db_items
+
+ def _pagination_links(
+ self, request: request.Request, total_count: int, limit: int, offset: int
+ ) -> tuple[Optional[str], Optional[str]]:
+ """next/previous links over the merged total via a directly-seeded paginator."""
+ paginator = SessionRecordingPlaylistPagination()
+ paginator.count = total_count
+ paginator.limit = limit
+ paginator.offset = offset
+ paginator.request = request
+ return paginator.get_next_link(), paginator.get_previous_link()
+
+ def _synthetic_global_ranks(
+ self,
+ request: request.Request,
+ queryset: QuerySet,
+ db_count: int,
+ sorted_synthetics: builtins.list[SessionRecordingPlaylist],
+ ) -> builtins.list[int]:
+ """Return the 0-based position of each synthetic in the global merged sort.
+
+ Timestamp orders put synthetics at one extreme; name order ranks each by the
+ count of DB rows before it (case-insensitive, matching _order_playlists).
+ """
+ if not sorted_synthetics:
+ return []
+
+ order = resolve_playlist_order(request)
+ is_descending = order.startswith("-")
+ sort_field = order.lstrip("-")
+
+ if sort_field == "name":
+ annotated = queryset.annotate(_name_lower=playlist_name_sort_expression())
+ synth_names = [playlist_name_sort_key(s) for s in sorted_synthetics]
+ lookup = "_name_lower__gt" if is_descending else "_name_lower__lt"
+ # One query: a conditional COUNT of DB rows sorting before each synthetic.
+ counts = annotated.aggregate(
+ **{f"c{i}": Count("pk", filter=Q(**{lookup: name})) for i, name in enumerate(synth_names)}
+ )
+ return [counts[f"c{i}"] + i for i in range(len(synth_names))]
- if page is not None:
- # Manually construct paginated response with correct count
- paginated_response = self.get_paginated_response(serializer.data)
- # Override the count with the total including synthetic playlists
- paginated_response.data["count"] = total_count
- return paginated_response
- return response.Response({"count": total_count, "next": None, "previous": None, "results": serializer.data})
+ # resolve_playlist_order guarantees a timestamp field here. Synthetics have no
+ # timestamp, so _order_playlists sorts them to datetime.max — the front of a
+ # descending list, the back of an ascending one.
+ if is_descending:
+ return list(range(len(sorted_synthetics)))
+ return [db_count + i for i in range(len(sorted_synthetics))]
def safely_get_queryset(self, queryset) -> QuerySet:
if not self.action.endswith("update"):
@@ -671,11 +795,18 @@ class SessionRecordingPlaylistViewSet(
queryset = queryset.filter(deleted=False)
queryset = self._filter_request(self.request, queryset)
- order = self.request.GET.get("order", None)
- if order:
- queryset = queryset.order_by(order)
+ # Append a unique "id" tiebreaker: LIMIT/OFFSET needs a total order, or rows with
+ # an equal name/timestamp can be skipped or repeated across pages — including when
+ # a user collection shares a name with a synthetic.
+ order = resolve_playlist_order(self.request)
+ if order.lstrip("-") == "name":
+ # Case-insensitive so the DB order matches _synthetic_global_ranks;
+ # otherwise the rank-derived offsets skip/duplicate items.
+ name_order = playlist_name_sort_expression()
+ name_ordered = name_order.desc() if order.startswith("-") else name_order.asc()
+ queryset = queryset.order_by(name_ordered, "id")
else:
- queryset = queryset.order_by("-last_modified_at")
+ queryset = queryset.order_by(order, "id")
return queryset
@@ -755,12 +886,12 @@ class SessionRecordingPlaylistViewSet(
def _order_playlists(
self, request: request.Request, playlists: builtins.list[SessionRecordingPlaylist]
) -> builtins.list[SessionRecordingPlaylist]:
- order = request.GET.get("order", "-last_modified_at")
+ order = resolve_playlist_order(request)
is_descending = order.startswith("-")
def get_sort_key(playlist: SessionRecordingPlaylist):
if order in ("name", "-name"):
- return (playlist.name or playlist.derived_name or "").lower()
+ return playlist_name_sort_key(playlist)
timestamp = playlist.created_at if order in ("created_at", "-created_at") else playlist.last_modified_at
diff --git a/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr b/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr
index d745aed54da2..a762b893df60 100644
--- a/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr
+++ b/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr
@@ -257,7 +257,8 @@
AND NOT "posthog_sessionrecordingplaylist"."deleted"
AND NOT "posthog_sessionrecordingplaylist"."deleted"
AND "posthog_sessionrecordingplaylist"."type" = 'filters')
- ORDER BY "posthog_sessionrecordingplaylist"."last_modified_at" DESC
+ ORDER BY "posthog_sessionrecordingplaylist"."last_modified_at" DESC,
+ "posthog_sessionrecordingplaylist"."id" ASC
LIMIT 100
'''
# ---
@@ -908,8 +909,9 @@
AND NOT "posthog_sessionrecordingplaylist"."deleted"
AND NOT "posthog_sessionrecordingplaylist"."deleted"
AND "posthog_sessionrecordingplaylist"."type" = 'collection')
- ORDER BY "posthog_sessionrecordingplaylist"."last_modified_at" DESC
- LIMIT 100
+ ORDER BY "posthog_sessionrecordingplaylist"."last_modified_at" DESC,
+ "posthog_sessionrecordingplaylist"."id" ASC
+ LIMIT 93
'''
# ---
# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.21
@@ -1639,8 +1641,9 @@
AND "posthog_sessionrecordingplaylist"."team_id" = 99999
AND NOT "posthog_sessionrecordingplaylist"."deleted"
AND NOT "posthog_sessionrecordingplaylist"."deleted")
- ORDER BY "posthog_sessionrecordingplaylist"."last_modified_at" DESC
- LIMIT 100
+ ORDER BY "posthog_sessionrecordingplaylist"."last_modified_at" DESC,
+ "posthog_sessionrecordingplaylist"."id" ASC
+ LIMIT 93
'''
# ---
# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.37
@@ -1780,6 +1783,61 @@
WHERE "ee_single_session_summary"."team_id" = 99999) subquery
'''
# ---
+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.45
+ '''
+ SELECT "posthog_sessionrecordingviewed"."session_id" AS "session_id"
+ FROM "posthog_sessionrecordingviewed"
+ WHERE ("posthog_sessionrecordingviewed"."team_id" = 99999
+ AND "posthog_sessionrecordingviewed"."user_id" = 99999
+ AND "posthog_sessionrecordingviewed"."session_id" IN ('00000000-0000-0000-0000-000000000000'))
+ '''
+# ---
+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.46
+ '''
+ SELECT COUNT(*) AS "__count"
+ FROM "posthog_sessionrecordingviewed"
+ WHERE ("posthog_sessionrecordingviewed"."team_id" = 99999
+ AND "posthog_sessionrecordingviewed"."user_id" = 99999)
+ '''
+# ---
+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.47
+ '''
+ SELECT COUNT(*)
+ FROM
+ (SELECT DISTINCT "posthog_comment"."item_id" AS "item_id"
+ FROM "posthog_comment"
+ WHERE (NOT "posthog_comment"."deleted"
+ AND "posthog_comment"."scope" = 'Replay'
+ AND "posthog_comment"."team_id" = 99999
+ AND NOT ("posthog_comment"."item_id" IS NULL))) subquery
+ '''
+# ---
+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.48
+ '''
+ SELECT COUNT(*)
+ FROM
+ (SELECT DISTINCT "posthog_sharingconfiguration"."recording_id" AS "recording__session_id"
+ FROM "posthog_sharingconfiguration"
+ WHERE ("posthog_sharingconfiguration"."enabled"
+ AND "posthog_sharingconfiguration"."team_id" = 99999
+ AND NOT ("posthog_sharingconfiguration"."recording_id" IS NULL))) subquery
+ '''
+# ---
+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.49
+ '''
+ SELECT COUNT(*)
+ FROM
+ (SELECT DISTINCT ("posthog_exportedasset"."export_context" -> 'session_recording_id') AS "export_context__session_recording_id"
+ FROM "posthog_exportedasset"
+ WHERE (("posthog_exportedasset"."expires_after" >= '2025-01-01 12:00:00+00:00'::timestamptz
+ OR "posthog_exportedasset"."expires_after" IS NULL)
+ AND "posthog_exportedasset"."team_id" = 99999
+ AND "posthog_exportedasset"."export_context" ? 'session_recording_id'
+ AND NOT (("posthog_exportedasset"."export_context" -> 'session_recording_id') IS NULL)
+ AND NOT (("posthog_exportedasset"."export_context" -> 'session_recording_id') = '""'::jsonb
+ AND "posthog_exportedasset"."export_context" IS NOT NULL))) subquery
+ '''
+# ---
# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.5
'''
SELECT "posthog_team"."id",
@@ -1917,6 +1975,513 @@
LIMIT 21
'''
# ---
+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.50
+ '''
+ SELECT "posthog_datawarehousesavedquery"."created_by_id",
+ "posthog_datawarehousesavedquery"."created_at",
+ "posthog_datawarehousesavedquery"."updated_at",
+ "posthog_datawarehousesavedquery"."deleted",
+ "posthog_datawarehousesavedquery"."deleted_at",
+ "posthog_datawarehousesavedquery"."id",
+ "posthog_datawarehousesavedquery"."name",
+ "posthog_datawarehousesavedquery"."team_id",
+ "posthog_datawarehousesavedquery"."latest_error",
+ "posthog_datawarehousesavedquery"."columns",
+ "posthog_datawarehousesavedquery"."external_tables",
+ "posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."status",
+ "posthog_datawarehousesavedquery"."last_run_at",
+ "posthog_datawarehousesavedquery"."sync_frequency_interval",
+ "posthog_datawarehousesavedquery"."table_id",
+ "posthog_datawarehousesavedquery"."is_materialized",
+ "posthog_datawarehousesavedquery"."deleted_name",
+ "posthog_datawarehousesavedquery"."managed_viewset_id",
+ "posthog_datawarehousesavedquery"."folder_id",
+ "posthog_datawarehousesavedquery"."origin",
+ "posthog_datawarehousesavedquery"."is_test",
+ "posthog_datawarehousesavedquery"."expires_at",
+ "posthog_datawarehousetable"."created_by_id",
+ "posthog_datawarehousetable"."created_at",
+ "posthog_datawarehousetable"."updated_at",
+ "posthog_datawarehousetable"."deleted",
+ "posthog_datawarehousetable"."deleted_at",
+ "posthog_datawarehousetable"."id",
+ "posthog_datawarehousetable"."name",
+ "posthog_datawarehousetable"."format",
+ "posthog_datawarehousetable"."team_id",
+ "posthog_datawarehousetable"."url_pattern",
+ "posthog_datawarehousetable"."queryable_folder",
+ "posthog_datawarehousetable"."credential_id",
+ "posthog_datawarehousetable"."external_data_source_id",
+ "posthog_datawarehousetable"."columns",
+ "posthog_datawarehousetable"."options",
+ "posthog_datawarehousetable"."row_count",
+ "posthog_datawarehousetable"."size_in_s3_mib",
+ "posthog_datawarehousemanagedviewset"."created_by_id",
+ "posthog_datawarehousemanagedviewset"."created_at",
+ "posthog_datawarehousemanagedviewset"."updated_at",
+ "posthog_datawarehousemanagedviewset"."id",
+ "posthog_datawarehousemanagedviewset"."team_id",
+ "posthog_datawarehousemanagedviewset"."kind"
+ FROM "posthog_datawarehousesavedquery"
+ LEFT OUTER JOIN "posthog_datawarehousemanagedviewset" ON ("posthog_datawarehousesavedquery"."managed_viewset_id" = "posthog_datawarehousemanagedviewset"."id")
+ LEFT OUTER JOIN "posthog_datawarehousetable" ON ("posthog_datawarehousesavedquery"."table_id" = "posthog_datawarehousetable"."id")
+ WHERE ("posthog_datawarehousesavedquery"."team_id" = 99999
+ AND NOT ("posthog_datawarehousesavedquery"."deleted"
+ AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL)
+ AND "posthog_datawarehousesavedquery"."managed_viewset_id" IS NULL)
+ ORDER BY "posthog_datawarehousesavedquery"."name" ASC
+ '''
+# ---
+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.51
+ '''
+ SELECT "posthog_datawarehousesavedquery"."created_by_id",
+ "posthog_datawarehousesavedquery"."created_at",
+ "posthog_datawarehousesavedquery"."updated_at",
+ "posthog_datawarehousesavedquery"."deleted",
+ "posthog_datawarehousesavedquery"."deleted_at",
+ "posthog_datawarehousesavedquery"."id",
+ "posthog_datawarehousesavedquery"."name",
+ "posthog_datawarehousesavedquery"."team_id",
+ "posthog_datawarehousesavedquery"."latest_error",
+ "posthog_datawarehousesavedquery"."columns",
+ "posthog_datawarehousesavedquery"."external_tables",
+ "posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."status",
+ "posthog_datawarehousesavedquery"."last_run_at",
+ "posthog_datawarehousesavedquery"."sync_frequency_interval",
+ "posthog_datawarehousesavedquery"."table_id",
+ "posthog_datawarehousesavedquery"."is_materialized",
+ "posthog_datawarehousesavedquery"."deleted_name",
+ "posthog_datawarehousesavedquery"."managed_viewset_id",
+ "posthog_datawarehousesavedquery"."folder_id",
+ "posthog_datawarehousesavedquery"."origin",
+ "posthog_datawarehousesavedquery"."is_test",
+ "posthog_datawarehousesavedquery"."expires_at",
+ "posthog_datawarehousetable"."created_by_id",
+ "posthog_datawarehousetable"."created_at",
+ "posthog_datawarehousetable"."updated_at",
+ "posthog_datawarehousetable"."deleted",
+ "posthog_datawarehousetable"."deleted_at",
+ "posthog_datawarehousetable"."id",
+ "posthog_datawarehousetable"."name",
+ "posthog_datawarehousetable"."format",
+ "posthog_datawarehousetable"."team_id",
+ "posthog_datawarehousetable"."url_pattern",
+ "posthog_datawarehousetable"."queryable_folder",
+ "posthog_datawarehousetable"."credential_id",
+ "posthog_datawarehousetable"."external_data_source_id",
+ "posthog_datawarehousetable"."columns",
+ "posthog_datawarehousetable"."options",
+ "posthog_datawarehousetable"."row_count",
+ "posthog_datawarehousetable"."size_in_s3_mib"
+ FROM "posthog_datawarehousesavedquery"
+ LEFT OUTER JOIN "posthog_datawarehousetable" ON ("posthog_datawarehousesavedquery"."table_id" = "posthog_datawarehousetable"."id")
+ WHERE ("posthog_datawarehousesavedquery"."team_id" = 99999
+ AND "posthog_datawarehousesavedquery"."origin" = 'endpoint'
+ AND NOT ("posthog_datawarehousesavedquery"."deleted"
+ AND "posthog_datawarehousesavedquery"."deleted" IS NOT NULL))
+ '''
+# ---
+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.52
+ '''
+ SELECT "posthog_externaldatasource"."created_by_id",
+ "posthog_externaldatasource"."created_at",
+ "posthog_externaldatasource"."updated_at",
+ "posthog_externaldatasource"."deleted",
+ "posthog_externaldatasource"."deleted_at",
+ "posthog_externaldatasource"."id",
+ "posthog_externaldatasource"."source_id",
+ "posthog_externaldatasource"."connection_id",
+ "posthog_externaldatasource"."destination_id",
+ "posthog_externaldatasource"."team_id",
+ "posthog_externaldatasource"."sync_frequency",
+ "posthog_externaldatasource"."status",
+ "posthog_externaldatasource"."source_type",
+ "posthog_externaldatasource"."job_inputs",
+ "posthog_externaldatasource"."connection_metadata",
+ "posthog_externaldatasource"."are_tables_created",
+ "posthog_externaldatasource"."prefix",
+ "posthog_externaldatasource"."description",
+ "posthog_externaldatasource"."created_via",
+ "posthog_externaldatasource"."access_method",
+ "posthog_externaldatasource"."revenue_analytics_enabled",
+ "posthog_externaldatasourcerevenueanalyticsconfig"."external_data_source_id",
+ "posthog_externaldatasourcerevenueanalyticsconfig"."enabled",
+ "posthog_externaldatasourcerevenueanalyticsconfig"."include_invoiceless_charges"
+ FROM "posthog_externaldatasource"
+ LEFT OUTER JOIN "posthog_externaldatasourcerevenueanalyticsconfig" ON ("posthog_externaldatasource"."id" = "posthog_externaldatasourcerevenueanalyticsconfig"."external_data_source_id")
+ WHERE ("posthog_externaldatasource"."source_type" IN ('Stripe')
+ AND "posthog_externaldatasource"."team_id" = 99999
+ AND NOT ("posthog_externaldatasource"."deleted"
+ AND "posthog_externaldatasource"."deleted" IS NOT NULL))
+ '''
+# ---
+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.53
+ '''
+ SELECT "posthog_datawarehousetable"."created_by_id",
+ "posthog_datawarehousetable"."created_at",
+ "posthog_datawarehousetable"."updated_at",
+ "posthog_datawarehousetable"."deleted",
+ "posthog_datawarehousetable"."deleted_at",
+ "posthog_datawarehousetable"."id",
+ "posthog_datawarehousetable"."name",
+ "posthog_datawarehousetable"."format",
+ "posthog_datawarehousetable"."team_id",
+ "posthog_datawarehousetable"."url_pattern",
+ "posthog_datawarehousetable"."queryable_folder",
+ "posthog_datawarehousetable"."credential_id",
+ "posthog_datawarehousetable"."external_data_source_id",
+ "posthog_datawarehousetable"."columns",
+ "posthog_datawarehousetable"."options",
+ "posthog_datawarehousetable"."row_count",
+ "posthog_datawarehousetable"."size_in_s3_mib"
+ FROM "posthog_datawarehousetable"
+ LEFT OUTER JOIN "posthog_externaldatasource" ON ("posthog_datawarehousetable"."external_data_source_id" = "posthog_externaldatasource"."id")
+ WHERE ("posthog_datawarehousetable"."team_id" = 99999
+ AND NOT ("posthog_datawarehousetable"."deleted"
+ AND "posthog_datawarehousetable"."deleted" IS NOT NULL)
+ AND NOT ("posthog_externaldatasource"."deleted"
+ AND "posthog_externaldatasource"."deleted" IS NOT NULL)
+ AND NOT ("posthog_externaldatasource"."access_method" = 'direct'
+ AND "posthog_externaldatasource"."access_method" IS NOT NULL))
+ ORDER BY "posthog_datawarehousetable"."created_at" DESC
+ '''
+# ---
+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.54
+ '''
+ SELECT "posthog_datawarehousejoin"."created_by_id",
+ "posthog_datawarehousejoin"."created_at",
+ "posthog_datawarehousejoin"."deleted",
+ "posthog_datawarehousejoin"."deleted_at",
+ "posthog_datawarehousejoin"."id",
+ "posthog_datawarehousejoin"."team_id",
+ "posthog_datawarehousejoin"."source_table_name",
+ "posthog_datawarehousejoin"."source_table_key",
+ "posthog_datawarehousejoin"."joining_table_name",
+ "posthog_datawarehousejoin"."joining_table_key",
+ "posthog_datawarehousejoin"."field_name",
+ "posthog_datawarehousejoin"."configuration"
+ FROM "posthog_datawarehousejoin"
+ WHERE ("posthog_datawarehousejoin"."team_id" = 99999
+ AND NOT ("posthog_datawarehousejoin"."deleted"
+ AND "posthog_datawarehousejoin"."deleted" IS NOT NULL))
+ '''
+# ---
+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.55
+ '''
+ SELECT "posthog_team"."id",
+ "posthog_team"."uuid",
+ "posthog_team"."organization_id",
+ "posthog_team"."parent_team_id",
+ "posthog_team"."project_id",
+ "posthog_team"."api_token",
+ "posthog_team"."app_urls",
+ "posthog_team"."name",
+ "posthog_team"."slack_incoming_webhook",
+ "posthog_team"."created_at",
+ "posthog_team"."updated_at",
+ "posthog_team"."anonymize_ips",
+ "posthog_team"."completed_snippet_onboarding",
+ "posthog_team"."has_completed_onboarding_for",
+ "posthog_team"."onboarding_tasks",
+ "posthog_team"."ingested_event",
+ "posthog_team"."ingested_production_event",
+ "posthog_team"."ingested_production_event_last_checked_at",
+ "posthog_team"."person_processing_opt_out",
+ "posthog_team"."secret_api_token",
+ "posthog_team"."secret_api_token_backup",
+ "posthog_team"."session_recording_opt_in",
+ "posthog_team"."session_recording_sample_rate",
+ "posthog_team"."session_recording_minimum_duration_milliseconds",
+ "posthog_team"."session_recording_linked_flag",
+ "posthog_team"."session_recording_network_payload_capture_config",
+ "posthog_team"."session_recording_masking_config",
+ "posthog_team"."session_recording_url_trigger_config",
+ "posthog_team"."session_recording_url_blocklist_config",
+ "posthog_team"."session_recording_event_trigger_config",
+ "posthog_team"."session_recording_trigger_match_type_config",
+ "posthog_team"."session_recording_trigger_groups",
+ "posthog_team"."session_replay_config",
+ "posthog_team"."session_recording_retention_period",
+ "posthog_team"."conversations_enabled",
+ "posthog_team"."conversations_settings",
+ "posthog_team"."proactive_tasks_enabled",
+ "posthog_team"."survey_config",
+ "posthog_team"."surveys_opt_in",
+ "posthog_team"."product_tours_opt_in",
+ "posthog_team"."capture_console_log_opt_in",
+ "posthog_team"."capture_performance_opt_in",
+ "posthog_team"."capture_dead_clicks",
+ "posthog_team"."autocapture_opt_out",
+ "posthog_team"."autocapture_web_vitals_opt_in",
+ "posthog_team"."autocapture_web_vitals_allowed_metrics",
+ "posthog_team"."autocapture_exceptions_opt_in",
+ "posthog_team"."autocapture_exceptions_errors_to_ignore",
+ "posthog_team"."logs_settings",
+ "posthog_team"."llm_gateway_enabled_at",
+ "posthog_team"."llm_gateway_revoked_at",
+ "posthog_team"."heatmaps_opt_in",
+ "posthog_team"."receive_org_level_activity_logs",
+ "posthog_team"."web_analytics_pre_aggregated_tables_enabled",
+ "posthog_team"."web_analytics_pre_aggregated_tables_version",
+ "posthog_team"."flags_persistence_default",
+ "posthog_team"."feature_flag_confirmation_enabled",
+ "posthog_team"."feature_flag_confirmation_message",
+ "posthog_team"."default_evaluation_environments_enabled",
+ "posthog_team"."require_evaluation_environment_tags",
+ "posthog_team"."default_evaluation_contexts_enabled",
+ "posthog_team"."require_evaluation_contexts",
+ "posthog_team"."session_recording_version",
+ "posthog_team"."signup_token",
+ "posthog_team"."is_demo",
+ "posthog_team"."access_control",
+ "posthog_team"."week_start_day",
+ "posthog_team"."inject_web_apps",
+ "posthog_team"."test_account_filters",
+ "posthog_team"."test_account_filters_default_checked",
+ "posthog_team"."path_cleaning_filters",
+ "posthog_team"."timezone",
+ "posthog_team"."data_attributes",
+ "posthog_team"."person_display_name_properties",
+ "posthog_team"."live_events_columns",
+ "posthog_team"."recording_domains",
+ "posthog_team"."human_friendly_comparison_periods",
+ "posthog_team"."cookieless_server_hash_mode",
+ "posthog_team"."primary_dashboard_id",
+ "posthog_team"."default_data_theme",
+ "posthog_team"."extra_settings",
+ "posthog_team"."modifiers",
+ "posthog_team"."correlation_config",
+ "posthog_team"."session_recording_retention_period_days",
+ "posthog_team"."external_data_workspace_id",
+ "posthog_team"."external_data_workspace_last_synced_at",
+ "posthog_team"."api_query_rate_limit",
+ "posthog_team"."revenue_tracking_config",
+ "posthog_team"."drop_events_older_than",
+ "posthog_team"."base_currency",
+ "posthog_team"."experiment_recalculation_time",
+ "posthog_team"."default_experiment_confidence_level",
+ "posthog_team"."default_experiment_stats_method",
+ "posthog_team"."business_model",
+ "posthog_organization"."id",
+ "posthog_organization"."name",
+ "posthog_organization"."slug",
+ "posthog_organization"."logo_media_id",
+ "posthog_organization"."created_at",
+ "posthog_organization"."updated_at",
+ "posthog_organization"."is_active",
+ "posthog_organization"."is_not_active_reason",
+ "posthog_organization"."session_cookie_age",
+ "posthog_organization"."is_member_join_email_enabled",
+ "posthog_organization"."is_ai_data_processing_approved",
+ "posthog_organization"."is_ai_training_opted_in",
+ "posthog_organization"."is_ai_training_locked",
+ "posthog_organization"."is_ai_training_cta_shown",
+ "posthog_organization"."enforce_2fa",
+ "posthog_organization"."members_can_invite",
+ "posthog_organization"."members_can_create_projects",
+ "posthog_organization"."members_can_use_personal_api_keys",
+ "posthog_organization"."allow_publicly_shared_resources",
+ "posthog_organization"."default_role_id",
+ "posthog_organization"."plugins_access_level",
+ "posthog_organization"."for_internal_metrics",
+ "posthog_organization"."default_experiment_stats_method",
+ "posthog_organization"."default_anonymize_ips",
+ "posthog_organization"."is_hipaa",
+ "posthog_organization"."is_pending_deletion",
+ "posthog_organization"."customer_id",
+ "posthog_organization"."available_product_features",
+ "posthog_organization"."usage",
+ "posthog_organization"."never_drop_data",
+ "posthog_organization"."customer_trust_scores",
+ "posthog_organization"."setup_section_2_completed",
+ "posthog_organization"."personalization",
+ "posthog_organization"."domain_whitelist",
+ "posthog_organization"."is_platform"
+ FROM "posthog_team"
+ INNER JOIN "posthog_organization" ON ("posthog_team"."organization_id" = "posthog_organization"."id")
+ WHERE "posthog_team"."id" = 99999
+ ORDER BY "posthog_team"."id" ASC
+ LIMIT 1
+ '''
+# ---
+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.56
+ '''
+ SELECT COUNT(*)
+ FROM
+ (SELECT DISTINCT "ee_single_session_summary"."session_id" AS "session_id"
+ FROM "ee_single_session_summary"
+ WHERE "ee_single_session_summary"."team_id" = 99999) subquery
+ '''
+# ---
+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.57
+ '''
+ SELECT "posthog_datawarehousejoin"."created_by_id",
+ "posthog_datawarehousejoin"."created_at",
+ "posthog_datawarehousejoin"."deleted",
+ "posthog_datawarehousejoin"."deleted_at",
+ "posthog_datawarehousejoin"."id",
+ "posthog_datawarehousejoin"."team_id",
+ "posthog_datawarehousejoin"."source_table_name",
+ "posthog_datawarehousejoin"."source_table_key",
+ "posthog_datawarehousejoin"."joining_table_name",
+ "posthog_datawarehousejoin"."joining_table_key",
+ "posthog_datawarehousejoin"."field_name",
+ "posthog_datawarehousejoin"."configuration"
+ FROM "posthog_datawarehousejoin"
+ WHERE ("posthog_datawarehousejoin"."team_id" = 99999
+ AND NOT ("posthog_datawarehousejoin"."deleted"
+ AND "posthog_datawarehousejoin"."deleted" IS NOT NULL))
+ '''
+# ---
+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.58
+ '''
+ SELECT "posthog_team"."id",
+ "posthog_team"."uuid",
+ "posthog_team"."organization_id",
+ "posthog_team"."parent_team_id",
+ "posthog_team"."project_id",
+ "posthog_team"."api_token",
+ "posthog_team"."app_urls",
+ "posthog_team"."name",
+ "posthog_team"."slack_incoming_webhook",
+ "posthog_team"."created_at",
+ "posthog_team"."updated_at",
+ "posthog_team"."anonymize_ips",
+ "posthog_team"."completed_snippet_onboarding",
+ "posthog_team"."has_completed_onboarding_for",
+ "posthog_team"."onboarding_tasks",
+ "posthog_team"."ingested_event",
+ "posthog_team"."ingested_production_event",
+ "posthog_team"."ingested_production_event_last_checked_at",
+ "posthog_team"."person_processing_opt_out",
+ "posthog_team"."secret_api_token",
+ "posthog_team"."secret_api_token_backup",
+ "posthog_team"."session_recording_opt_in",
+ "posthog_team"."session_recording_sample_rate",
+ "posthog_team"."session_recording_minimum_duration_milliseconds",
+ "posthog_team"."session_recording_linked_flag",
+ "posthog_team"."session_recording_network_payload_capture_config",
+ "posthog_team"."session_recording_masking_config",
+ "posthog_team"."session_recording_url_trigger_config",
+ "posthog_team"."session_recording_url_blocklist_config",
+ "posthog_team"."session_recording_event_trigger_config",
+ "posthog_team"."session_recording_trigger_match_type_config",
+ "posthog_team"."session_recording_trigger_groups",
+ "posthog_team"."session_replay_config",
+ "posthog_team"."session_recording_retention_period",
+ "posthog_team"."conversations_enabled",
+ "posthog_team"."conversations_settings",
+ "posthog_team"."proactive_tasks_enabled",
+ "posthog_team"."survey_config",
+ "posthog_team"."surveys_opt_in",
+ "posthog_team"."product_tours_opt_in",
+ "posthog_team"."capture_console_log_opt_in",
+ "posthog_team"."capture_performance_opt_in",
+ "posthog_team"."capture_dead_clicks",
+ "posthog_team"."autocapture_opt_out",
+ "posthog_team"."autocapture_web_vitals_opt_in",
+ "posthog_team"."autocapture_web_vitals_allowed_metrics",
+ "posthog_team"."autocapture_exceptions_opt_in",
+ "posthog_team"."autocapture_exceptions_errors_to_ignore",
+ "posthog_team"."logs_settings",
+ "posthog_team"."llm_gateway_enabled_at",
+ "posthog_team"."llm_gateway_revoked_at",
+ "posthog_team"."heatmaps_opt_in",
+ "posthog_team"."receive_org_level_activity_logs",
+ "posthog_team"."web_analytics_pre_aggregated_tables_enabled",
+ "posthog_team"."web_analytics_pre_aggregated_tables_version",
+ "posthog_team"."flags_persistence_default",
+ "posthog_team"."feature_flag_confirmation_enabled",
+ "posthog_team"."feature_flag_confirmation_message",
+ "posthog_team"."default_evaluation_environments_enabled",
+ "posthog_team"."require_evaluation_environment_tags",
+ "posthog_team"."default_evaluation_contexts_enabled",
+ "posthog_team"."require_evaluation_contexts",
+ "posthog_team"."session_recording_version",
+ "posthog_team"."signup_token",
+ "posthog_team"."is_demo",
+ "posthog_team"."access_control",
+ "posthog_team"."week_start_day",
+ "posthog_team"."inject_web_apps",
+ "posthog_team"."test_account_filters",
+ "posthog_team"."test_account_filters_default_checked",
+ "posthog_team"."path_cleaning_filters",
+ "posthog_team"."timezone",
+ "posthog_team"."data_attributes",
+ "posthog_team"."person_display_name_properties",
+ "posthog_team"."live_events_columns",
+ "posthog_team"."recording_domains",
+ "posthog_team"."human_friendly_comparison_periods",
+ "posthog_team"."cookieless_server_hash_mode",
+ "posthog_team"."primary_dashboard_id",
+ "posthog_team"."default_data_theme",
+ "posthog_team"."extra_settings",
+ "posthog_team"."modifiers",
+ "posthog_team"."correlation_config",
+ "posthog_team"."session_recording_retention_period_days",
+ "posthog_team"."external_data_workspace_id",
+ "posthog_team"."external_data_workspace_last_synced_at",
+ "posthog_team"."api_query_rate_limit",
+ "posthog_team"."revenue_tracking_config",
+ "posthog_team"."drop_events_older_than",
+ "posthog_team"."base_currency",
+ "posthog_team"."experiment_recalculation_time",
+ "posthog_team"."default_experiment_confidence_level",
+ "posthog_team"."default_experiment_stats_method",
+ "posthog_team"."business_model",
+ "posthog_organization"."id",
+ "posthog_organization"."name",
+ "posthog_organization"."slug",
+ "posthog_organization"."logo_media_id",
+ "posthog_organization"."created_at",
+ "posthog_organization"."updated_at",
+ "posthog_organization"."is_active",
+ "posthog_organization"."is_not_active_reason",
+ "posthog_organization"."session_cookie_age",
+ "posthog_organization"."is_member_join_email_enabled",
+ "posthog_organization"."is_ai_data_processing_approved",
+ "posthog_organization"."is_ai_training_opted_in",
+ "posthog_organization"."is_ai_training_locked",
+ "posthog_organization"."is_ai_training_cta_shown",
+ "posthog_organization"."enforce_2fa",
+ "posthog_organization"."members_can_invite",
+ "posthog_organization"."members_can_create_projects",
+ "posthog_organization"."members_can_use_personal_api_keys",
+ "posthog_organization"."allow_publicly_shared_resources",
+ "posthog_organization"."default_role_id",
+ "posthog_organization"."plugins_access_level",
+ "posthog_organization"."for_internal_metrics",
+ "posthog_organization"."default_experiment_stats_method",
+ "posthog_organization"."default_anonymize_ips",
+ "posthog_organization"."is_hipaa",
+ "posthog_organization"."is_pending_deletion",
+ "posthog_organization"."customer_id",
+ "posthog_organization"."available_product_features",
+ "posthog_organization"."usage",
+ "posthog_organization"."never_drop_data",
+ "posthog_organization"."customer_trust_scores",
+ "posthog_organization"."setup_section_2_completed",
+ "posthog_organization"."personalization",
+ "posthog_organization"."domain_whitelist",
+ "posthog_organization"."is_platform"
+ FROM "posthog_team"
+ INNER JOIN "posthog_organization" ON ("posthog_team"."organization_id" = "posthog_organization"."id")
+ WHERE "posthog_team"."id" = 99999
+ ORDER BY "posthog_team"."id" ASC
+ LIMIT 1
+ '''
+# ---
+# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.59
+ '''
+ SELECT COUNT(*)
+ FROM
+ (SELECT DISTINCT "ee_single_session_summary"."session_id" AS "session_id"
+ FROM "ee_single_session_summary"
+ WHERE "ee_single_session_summary"."team_id" = 99999) subquery
+ '''
+# ---
# name: TestSessionRecordingPlaylist.test_filters_playlist_by_type.6
'''
SELECT "posthog_organizationmembership"."id",
diff --git a/posthog/session_recordings/test/test_session_recording_playlist.py b/posthog/session_recordings/test/test_session_recording_playlist.py
index f9441e93fb1b..093698870d5d 100644
--- a/posthog/session_recordings/test/test_session_recording_playlist.py
+++ b/posthog/session_recordings/test/test_session_recording_playlist.py
@@ -2,6 +2,7 @@ import json
from datetime import UTC, datetime, timedelta
from uuid import uuid4
+import pytest
from freezegun import freeze_time
from posthog.test.base import APIBaseTest, QueryMatchingTest, snapshot_postgres_queries
from unittest import mock
@@ -33,6 +34,8 @@ from posthog.session_recordings.session_recording_playlist_api import (
PLAYLIST_LIST_MAX_LIMIT,
_attach_empty_recordings_counts,
_empty_saved_filters_counts,
+ parse_non_negative_int,
+ parse_positive_int,
precompute_recordings_counts,
)
from posthog.session_recordings.synthetic_playlists import ExpiringPlaylistSource
@@ -1148,6 +1151,218 @@ class TestSessionRecordingPlaylist(APIBaseTest, QueryMatchingTest):
assert result["added_count"] == 2 # Only new ones counted
assert result["total_requested"] == 3
+ @parameterized.expand(
+ [
+ # (order, limit) across the synth/DB boundary, both sort directions.
+ ["desc_boundary", "-last_modified_at", 30],
+ ["desc_smaller", "-last_modified_at", 17],
+ ["asc_boundary", "last_modified_at", 30],
+ ["name_asc", "name", 12],
+ ]
+ )
+ def test_pagination_covers_every_db_playlist_across_pages(self, _name: str, order: str, limit: int) -> None:
+ # Walking every page must return each DB playlist exactly once with no empty
+ # interior pages — synthetics displaced items off page boundaries before the fix.
+ db_playlist_count = 50
+ for i in range(db_playlist_count):
+ SessionRecordingPlaylist.objects.create(
+ team=self.team, name=f"playlist-{i:02d}", created_by=self.user, type="collection"
+ )
+
+ seen_db_ids: list[str] = []
+ seen_synth_ids: set[str] = set()
+ offset = 0
+ total_count: int | None = None
+ while True:
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/session_recording_playlists?order={order}&limit={limit}&offset={offset}"
+ )
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ total_count = data["count"]
+ results = data["results"]
+ # Synthetics may span several pages, so accumulate unique ids across the walk.
+ seen_synth_ids.update(r["short_id"] for r in results if r.get("is_synthetic"))
+
+ assert results, f"page at offset={offset} was unexpectedly empty"
+ if offset + limit < total_count:
+ assert len(results) == limit, "interior pages must be full"
+
+ seen_db_ids.extend(r["short_id"] for r in results if not r.get("is_synthetic"))
+ offset += limit
+ if offset >= total_count:
+ break
+
+ assert len(seen_synth_ids) > 0, "test relies on synthetic playlists being present"
+ assert total_count == db_playlist_count + len(seen_synth_ids)
+ # Every DB playlist appears exactly once — no skips, no duplicates.
+ assert len(seen_db_ids) == db_playlist_count
+ assert len(set(seen_db_ids)) == db_playlist_count
+
+ def test_pagination_returns_displaced_db_playlists_on_later_pages(self) -> None:
+ # The reported bug: synthetics fill slots on page 1, so page 2 came back empty
+ # while count still claimed more. Page 2 must return the displaced DB rows.
+ page_size = 30
+ db_playlist_count = page_size
+ for i in range(db_playlist_count):
+ SessionRecordingPlaylist.objects.create(
+ team=self.team, name=f"playlist-{i:02d}", created_by=self.user, type="collection"
+ )
+
+ page_one = self.client.get(
+ f"/api/projects/{self.team.id}/session_recording_playlists?limit={page_size}&offset=0"
+ )
+ assert page_one.status_code == status.HTTP_200_OK
+ page_one_data = page_one.json()
+ synth_count = sum(1 for r in page_one_data["results"] if r.get("is_synthetic"))
+ total_count = page_one_data["count"]
+ assert synth_count > 0, "test relies on synthetic playlists being present"
+ assert total_count == db_playlist_count + synth_count
+ assert len(page_one_data["results"]) == page_size
+ assert page_one_data["next"] is not None
+ assert page_one_data["previous"] is None
+
+ page_two = self.client.get(
+ f"/api/projects/{self.team.id}/session_recording_playlists?limit={page_size}&offset={page_size}"
+ )
+ assert page_two.status_code == status.HTTP_200_OK
+ page_two_data = page_two.json()
+ assert page_two_data["count"] == total_count
+ # Displaced DB rows must appear here — previously this page was empty.
+ assert len(page_two_data["results"]) == total_count - page_size
+ assert all(not r.get("is_synthetic") for r in page_two_data["results"])
+ assert page_two_data["previous"] is not None
+ assert page_two_data["next"] is None
+
+ # No overlap, and together they cover every DB playlist.
+ page_one_db_ids = {r["short_id"] for r in page_one_data["results"] if not r.get("is_synthetic")}
+ page_two_db_ids = {r["short_id"] for r in page_two_data["results"]}
+ assert page_one_db_ids.isdisjoint(page_two_db_ids)
+ assert len(page_one_db_ids | page_two_db_ids) == db_playlist_count
+
+ def test_pagination_with_name_sort_places_synthetics_by_name(self) -> None:
+ # Under name-ascending, synthetics sit at their alphabetical position, not
+ # unconditionally at the start or end of the merged list.
+ SessionRecordingPlaylist.objects.create(
+ team=self.team, name="aaa-first", created_by=self.user, type="collection"
+ )
+ SessionRecordingPlaylist.objects.create(
+ team=self.team, name="zzz-last", created_by=self.user, type="collection"
+ )
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/session_recording_playlists?order=name&limit=3&offset=0"
+ )
+ assert response.status_code == status.HTTP_200_OK
+ names = [r["name"] for r in response.json()["results"]]
+ # "aaa-first" sorts ahead of every synthetic, so page 1 must include it.
+ assert "aaa-first" in names
+ # "zzz-last" sorts after every synthetic; it must not appear on page 1.
+ assert "zzz-last" not in names
+
+ def test_pagination_with_name_sort_is_case_insensitive(self) -> None:
+ # Rank math and the DB slice must share one case-insensitive order, else mixed-case
+ # names get skipped or duplicated across pages.
+ db_names = ["Banana", "apple", "Cherry", "date", "Elder", "fig", "Grape", "kiwi"]
+ for name in db_names:
+ SessionRecordingPlaylist.objects.create(team=self.team, name=name, created_by=self.user, type="collection")
+
+ page_size = 5
+ seen_db_names: list[str] = []
+ offset = 0
+ while True:
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/session_recording_playlists?order=name&limit={page_size}&offset={offset}"
+ )
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ seen_db_names.extend(r["name"] for r in data["results"] if not r.get("is_synthetic"))
+ offset += page_size
+ if offset >= data["count"]:
+ break
+
+ # Every DB playlist appears exactly once across all pages — no skips, no duplicates.
+ assert sorted(seen_db_names) == sorted(db_names)
+
+ def test_pagination_with_name_ties_across_page_boundary(self) -> None:
+ # Duplicate names (including one colliding with a synthetic, "Expiring soon")
+ # force ties that straddle page boundaries. The unique id tiebreaker must keep
+ # every DB row appearing exactly once — without it the slice skips/repeats rows.
+ created_ids: set[str] = set()
+ for name in ["dup-a", "dup-a", "dup-a", "Expiring soon", "Expiring soon", "dup-z", "dup-z", "dup-z"]:
+ playlist = SessionRecordingPlaylist.objects.create(
+ team=self.team, name=name, created_by=self.user, type="collection"
+ )
+ created_ids.add(playlist.short_id)
+
+ page_size = 3
+ seen: list[str] = []
+ offset = 0
+ while True:
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/session_recording_playlists?order=name&limit={page_size}&offset={offset}"
+ )
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ seen.extend(r["short_id"] for r in data["results"] if not r.get("is_synthetic"))
+ offset += page_size
+ if offset >= data["count"]:
+ break
+
+ assert sorted(seen) == sorted(created_ids)
+ assert len(seen) == len(set(seen))
+
+ def test_pagination_synthetics_only_when_no_db_collections(self) -> None:
+ # No DB rows: the response is exactly the synthetics, and paging across a small
+ # limit returns each once — pins the rank range() branch with zero DB rows.
+ page_size = 3
+ seen: list[str] = []
+ offset = 0
+ total = 0
+ while True:
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/session_recording_playlists?limit={page_size}&offset={offset}"
+ )
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ total = data["count"]
+ assert all(r.get("is_synthetic") for r in data["results"])
+ seen.extend(r["short_id"] for r in data["results"])
+ offset += page_size
+ if offset >= total:
+ break
+
+ assert total > 0
+ assert len(seen) == total
+ assert len(set(seen)) == total
+
+ def test_pagination_with_zero_synthetics(self) -> None:
+ # collection_type=custom filters out all synthetics, exercising the empty-ranks
+ # early return; pure-DB pagination must still return each row exactly once.
+ db_names = [f"custom-{i:02d}" for i in range(8)]
+ for name in db_names:
+ SessionRecordingPlaylist.objects.create(team=self.team, name=name, created_by=self.user, type="collection")
+
+ page_size = 3
+ seen: list[str] = []
+ offset = 0
+ total = 0
+ while True:
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/session_recording_playlists?collection_type=custom&limit={page_size}&offset={offset}"
+ )
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ total = data["count"]
+ assert not any(r.get("is_synthetic") for r in data["results"])
+ seen.extend(r["name"] for r in data["results"])
+ offset += page_size
+ if offset >= total:
+ break
+
+ assert total == len(db_names)
+ assert sorted(seen) == sorted(db_names)
+
class TestSessionRecordingPlaylistPersonalAPIKey(APIBaseTest):
def _create_personal_api_key(self, scopes: list[str], scoped_teams: list[int] | None = None) -> str:
@@ -1453,3 +1668,42 @@ class TestPrecomputeRecordingsCounts(APIBaseTest):
# and by the paginator.)
results = response.json()["results"]
assert len(results) <= PLAYLIST_LIST_MAX_LIMIT
+
+ def test_list_with_zero_limit_does_not_loop_pagination(self) -> None:
+ # limit=0 would make the next link point back at the same offset (infinite paging);
+ # it must fall back to the default page size and terminate.
+ response = self.client.get(f"/api/projects/{self.team.id}/session_recording_playlists?limit=0")
+ assert response.status_code == status.HTTP_200_OK
+ data = response.json()
+ # Default page size (100) comfortably holds the synthetics, so there's no next page
+ # and certainly no self-referential loop.
+ assert data["next"] is None
+ assert len(data["results"]) == data["count"]
+
+
+ "value,expected",
+ [
+ ("30", 30),
+ ("0", 0),
+ ("-5", 0),
+ ("abc", 100),
+ (None, 100),
+ ],
+)
+def test_parse_non_negative_int(value: object, expected: int) -> None:
+ assert parse_non_negative_int(value, 100) == expected
+
+
+ "value,expected",
+ [
+ ("30", 30),
+ ("0", 100), # limit=0 would loop pagination -> default
+ ("-5", 100), # non-positive -> default
+ ("abc", 100),
+ (None, 100),
+ ],
+)
+def test_parse_positive_int(value: object, expected: int) -> None:
+ assert parse_positive_int(value, 100) == expected
diff --git a/products/replay/frontend/generated/api.ts b/products/replay/frontend/generated/api.ts
index 563b18967c16..ef9a202826af 100644
--- a/products/replay/frontend/generated/api.ts
+++ b/products/replay/frontend/generated/api.ts
@@ -60,7 +60,13 @@ export const getSessionRecordingPlaylistsListUrl = (
}
/**
- * Override list to include synthetic playlists
+ * Override list to include synthetic playlists.
+ *
+ * Synthetics have no DB row, so we compute each one's position in the merged
+ * sort and split the requested page between synthetics and a DB queryset slice.
+ * The merge/rank/sort is all in-memory, so each phase is wrapped in a span and
+ * the input sizes are recorded as span attributes — a slow response on a team
+ * with many playlists then shows up as a wide span against a large db_count.
*/
export const sessionRecordingPlaylistsList = async (
projectId: string,
diff --git a/services/mcp/src/generated/replay/api.ts b/services/mcp/src/generated/replay/api.ts
index f9830860f83d..14198c416695 100644
--- a/services/mcp/src/generated/replay/api.ts
+++ b/services/mcp/src/generated/replay/api.ts
@@ -9,7 +9,13 @@
import * as zod from 'zod'
/**
- * Override list to include synthetic playlists
+ * Override list to include synthetic playlists.
+ *
+ * Synthetics have no DB row, so we compute each one's position in the merged
+ * sort and split the requested page between synthetics and a DB queryset slice.
+ * The merge/rank/sort is all in-memory, so each phase is wrapped in a span and
+ * the input sizes are recorded as span attributes — a slow response on a team
+ * with many playlists then shows up as a wide span against a large db_count.
*/
export const SessionRecordingPlaylistsListParams = /* @__PURE__ */ zod.object({
project_id: zod