: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(replay): replace positional tuple returns with typed objects (#72946)
Arno Hillen2f27722eea95
diff --git a/ee/hogai/session_summaries/local/input_data.py b/ee/hogai/session_summaries/local/input_data.pyindex 5876d0436263..26fdd4fd0464 100644--- a/ee/hogai/session_summaries/local/input_data.py+++ b/ee/hogai/session_summaries/local/input_data.py@@ -8,7 +8,7 @@ import pytzfrom clickhouse_driver import Clientfrom posthog.session_recordings.models.metadata import RecordingMetadata-from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents+from posthog.session_recordings.queries.session_replay_events import SessionEventsPage, SessionReplayEventsdef _get_ch_client_local_reads_prod() -> Client:@@ -101,7 +101,7 @@ def _get_production_session_events_locally(page: int,events_to_ignore: list[str] | None = None,extra_fields: list[str] | None = None,-) -> tuple[list | None, list | None]:+) -> SessionEventsPage:"""Get session events from production, locally, required for testing session summary"""@@ -118,4 +118,5 @@ def _get_production_session_events_locally(with _ch_client_local_reads_prod() as client:rows, columns_with_types = client.execute(interpolated_query, with_column_types=True)columns = [col for col, _ in columns_with_types]- return columns, rows+ # This helper pages by re-querying, so `has_more` is decided by the caller's page loop, not here.+ return SessionEventsPage(columns=columns, rows=rows, has_more=False)diff --git a/ee/hogai/session_summaries/session/input_data.py b/ee/hogai/session_summaries/session/input_data.pyindex 91ece5860123..f73b33d02f13 100644--- a/ee/hogai/session_summaries/session/input_data.py+++ b/ee/hogai/session_summaries/session/input_data.py@@ -59,37 +59,37 @@ def get_session_events(all_events = []columns = Noneevents_obj = SessionReplayEvents()- for page in range(max_pages):+ for page_number in range(max_pages):if not local_reads_prod:team = get_team(team_id=team_id)- page_columns, page_events, _ = events_obj.get_events(+ page = events_obj.get_events(session_id=str(session_id),team=team,metadata=session_metadata,events_to_ignore=events_to_ignore,extra_fields=extra_fields,limit=items_per_page,- page=page,+ page=page_number,)else:- page_columns, page_events = _get_production_session_events_locally(+ page = _get_production_session_events_locally(events_obj=events_obj,session_id=str(session_id),metadata=session_metadata,events_to_ignore=events_to_ignore,extra_fields=extra_fields,limit=items_per_page,- page=page,+ page=page_number,)# Expect columns to be exact for all the page as we don't change the query- if page_columns and not columns:- columns = page_columns+ if page.columns and not columns:+ columns = page.columns# Avoid the next page if no events are returned- if not page_events:+ if not page.rows:break- all_events.extend(page_events)+ all_events.extend(page.rows)# Or we got less than the page size (reached the end)- if len(page_events) < items_per_page:+ if len(page.rows) < items_per_page:breakif not columns:msg = f"No columns found for session_id {session_id}"diff --git a/ee/hogai/session_summaries/session_group/summarize_session_group.py b/ee/hogai/session_summaries/session_group/summarize_session_group.pyindex 2afaccbd4143..7367b8b8a71d 100644--- a/ee/hogai/session_summaries/session_group/summarize_session_group.py+++ b/ee/hogai/session_summaries/session_group/summarize_session_group.py@@ -119,7 +119,7 @@ def partition_sessions_by_recording_existence(session_ids: list[str], team: Teamwhole batch — see ``find_sessions_timestamps`` for the strict variant used by the group flow."""replay_events = SessionReplayEvents()- sessions_found, _, _ = replay_events.sessions_found_with_timestamps(session_ids, team)+ sessions_found = replay_events.sessions_found_with_timestamps(session_ids, team).session_idsfound = [sid for sid in session_ids if sid in sessions_found]missing = [sid for sid in session_ids if sid not in sessions_found]return found, missing@@ -128,7 +128,9 @@ def partition_sessions_by_recording_existence(session_ids: list[str], team: Teamdef find_sessions_timestamps(session_ids: list[str], team: Team) -> tuple[datetime, datetime]:"""Validate that all session IDs exist and belong to the team and return min/max timestamps for the entire list of sessions"""replay_events = SessionReplayEvents()- sessions_found, min_timestamp, max_timestamp = replay_events.sessions_found_with_timestamps(session_ids, team)+ result = replay_events.sessions_found_with_timestamps(session_ids, team)+ sessions_found = result.session_ids+ min_timestamp, max_timestamp = result.min_timestamp, result.max_timestamp# Check for missing sessions. The replay_events table is the source of truth for "did we capture a recording";# a missing row most commonly means the session never produced a recording or the recording has aged out# of retention, not that the caller is hitting the wrong team.diff --git a/ee/hogai/session_summaries/tests/test_input_data.py b/ee/hogai/session_summaries/tests/test_input_data.pyindex a3e3a33dfbed..07e1c0ad046f 100644--- a/ee/hogai/session_summaries/tests/test_input_data.py+++ b/ee/hogai/session_summaries/tests/test_input_data.py@@ -6,6 +6,7 @@ import pytestfrom unittest.mock import MagicMock, patchfrom posthog.session_recordings.models.metadata import RecordingMetadata+from posthog.session_recordings.queries.session_replay_events import SessionEventsPagefrom ee.hogai.session_summaries.session.input_data import (COLUMNS_TO_REMOVE_FROM_LLM_CONTEXT,@@ -550,7 +551,10 @@ def test_get_paginated_session_events(mock_columns = mock_events_columns# Prepare mock pages data (add columns to each page)processed_pages_data = [- (mock_columns, events, False) if events is not None else (None, None, False) for events in pages_data+ SessionEventsPage(columns=mock_columns, rows=events, has_more=False)+ if events is not None+ else SessionEventsPage(columns=None, rows=None, has_more=False)+ for events in pages_data]with (patch("ee.hogai.session_summaries.session.input_data.SessionReplayEvents") as mock_replay_events,diff --git a/ee/hogai/session_summaries/tests/test_summarize_session.py b/ee/hogai/session_summaries/tests/test_summarize_session.pyindex e2bae7650ec6..258a52f64f90 100644--- a/ee/hogai/session_summaries/tests/test_summarize_session.py+++ b/ee/hogai/session_summaries/tests/test_summarize_session.py@@ -5,7 +5,7 @@ from typing import Anyimport pytestfrom unittest.mock import MagicMock, patch-from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents+from posthog.session_recordings.queries.session_replay_events import SessionEventsPage, SessionReplayEventsfrom ee.hogai.session_summaries.session.input_data import EXTRA_SUMMARY_EVENT_FIELDS, get_session_eventsfrom ee.hogai.session_summaries.session.prompt_data import SessionSummaryMetadata, SessionSummaryPromptData@@ -47,7 +47,10 @@ class TestSummarizeSession:# Mock the SessionReplayEvents DB model to return different data for each pagemock_instance = MagicMock()mock_replay_events.return_value = mock_instance- mock_instance.get_events.side_effect = [(None, None, False), (None, None, False)]+ mock_instance.get_events.side_effect = [+ SessionEventsPage(columns=None, rows=None, has_more=False),+ SessionEventsPage(columns=None, rows=None, has_more=False),+ ]with pytest.raises(ValueError, match=f"No columns found for session_id {mock_session_id}"):with patch("ee.hogai.session_summaries.session.input_data.get_team", return_value=mock_team):get_session_events(diff --git a/ee/hogai/tools/replay/summarize_sessions.py b/ee/hogai/tools/replay/summarize_sessions.pyindex 52351c7ca919..807a3ab82e08 100644--- a/ee/hogai/tools/replay/summarize_sessions.py+++ b/ee/hogai/tools/replay/summarize_sessions.py@@ -457,10 +457,10 @@ class SummarizeSessionsTool(MaxTool):from posthog.session_recordings.queries.session_replay_events import SessionReplayEventsreplay_events = SessionReplayEvents()- sessions_found, _, _ = replay_events.sessions_found_with_timestamps(+ sessions_found = replay_events.sessions_found_with_timestamps(session_ids=session_ids,team=self._team,- )+ ).session_idsif not sessions_found:return None# Preserve the original order, filtering out invalid sessionsdiff --git a/posthog/session_recordings/queries/session_replay_events.py b/posthog/session_recordings/queries/session_replay_events.pyindex 11efaa3d8b63..4dcf9def0bb4 100644--- a/posthog/session_recordings/queries/session_replay_events.py+++ b/posthog/session_recordings/queries/session_replay_events.py@@ -1,5 +1,6 @@import reimport json+from dataclasses import dataclassfrom datetime import datetime, timedeltafrom typing import Optional@@ -34,6 +35,34 @@ SESSION_ID_CLOCK_SKEW_SLACK = timedelta(days=3)_EARLIEST_PLAUSIBLE_SESSION_START = datetime(2020, 1, 1, tzinfo=pytz.UTC)+@dataclass(frozen=True)+class SessionEventsPage:+ """One page of a recording's analytics events."""++ columns: list | None+ rows: list | None+ has_more: bool+++@dataclass(frozen=True)+class SessionTimestamps:+ """One session's recording time bounds within the retention period."""++ session_id: str+ min_timestamp: datetime+ max_timestamp: datetime+ expiry_time: datetime+++@dataclass(frozen=True)+class SessionsWithTimestamps:+ """Sessions present in both replay and events tables, with the whole batch's time bounds."""++ session_ids: set[str]+ min_timestamp: Optional[datetime]+ max_timestamp: Optional[datetime]++def uuidv7_session_lower_bound(session_id: str, now: datetime | None = None) -> datetime | None:"""A safe ``min_first_timestamp`` lower bound derived from a UUIDv7 session id.@@ -193,8 +222,7 @@ class SessionReplayEvents:# Query ClickHouse for uncached session IDsfound_sessions = self._find_with_timestamps(uncached_session_ids, team)- # Build a mapping from session_id to expiry_time (tuple is: session_id, min_ts, max_ts, expiry_time)- session_expiry_map = {session_id: expiry_time for session_id, _, _, expiry_time in found_sessions}+ session_expiry_map = {found.session_id: found.expiry_time for found in found_sessions}now = datetime.now(pytz.timezone("UTC"))@@ -255,43 +283,41 @@ class SessionReplayEvents:)return bool(result and result[0][0] > 0)- def sessions_found_with_timestamps(- self, session_ids: list[str], team: Team- ) -> tuple[set[str], Optional[datetime], Optional[datetime]]:+ def sessions_found_with_timestamps(self, session_ids: list[str], team: Team) -> SessionsWithTimestamps:"""Check if sessions exist in both session_replay_events and events tables.- Returns a tuple of (sessions_found, min_timestamp, max_timestamp).Timestamps are for the entire list of sessions, not per session.Sessions must exist in both tables to be included in the result."""if not session_ids:- return set(), None, None+ return SessionsWithTimestamps(session_ids=set(), min_timestamp=None, max_timestamp=None)# Check sessions within TTL in session_replay_eventsfound_sessions = self._find_with_timestamps(session_ids, team)if not found_sessions:- return set(), None, None+ return SessionsWithTimestamps(session_ids=set(), min_timestamp=None, max_timestamp=None)# Calculate min/max timestamps for the entire list of sessions- replay_session_ids = [session_id for session_id, _, _, _ in found_sessions]- min_timestamp = min(ts for _, ts, _, _ in found_sessions)- max_timestamp = max(ts for _, _, ts, _ in found_sessions)+ replay_session_ids = [found.session_id for found in found_sessions]+ min_timestamp = min(found.min_timestamp for found in found_sessions)+ max_timestamp = max(found.max_timestamp for found in found_sessions)# Check which sessions also have events in the events tablesessions_with_events = self._find_sessions_in_events(replay_session_ids, min_timestamp, max_timestamp, team)if not sessions_with_events:- return set(), None, None+ return SessionsWithTimestamps(session_ids=set(), min_timestamp=None, max_timestamp=None)# Filter to only sessions that exist in both tables- session_ids_found = {session_id for session_id, _, _, _ in found_sessions if session_id in sessions_with_events}+ session_ids_found = {found.session_id for found in found_sessions if found.session_id in sessions_with_events}if not session_ids_found:- return set(), None, None+ return SessionsWithTimestamps(session_ids=set(), min_timestamp=None, max_timestamp=None)# Recalculate timestamps for filtered sessions only- min_timestamp = min(ts for session_id, ts, _, _ in found_sessions if session_id in session_ids_found)- max_timestamp = max(ts for session_id, _, ts, _ in found_sessions if session_id in session_ids_found)- return session_ids_found, min_timestamp, max_timestamp+ min_timestamp = min(found.min_timestamp for found in found_sessions if found.session_id in session_ids_found)+ max_timestamp = max(found.max_timestamp for found in found_sessions if found.session_id in session_ids_found)+ return SessionsWithTimestamps(+ session_ids=session_ids_found, min_timestamp=min_timestamp, max_timestamp=max_timestamp+ )@staticmethod- def _find_with_timestamps(session_ids: list[str], team: Team) -> list[tuple[str, datetime, datetime, datetime]]:+ def _find_with_timestamps(session_ids: list[str], team: Team) -> list[SessionTimestamps]:"""Check which session IDs exist in session_replay_events within retention period.- Returns a list of tuples of (session_id, min_timestamp, max_timestamp, expiry_time).Timestamps are per session, not for the entire list of sessions."""now = datetime.now(pytz.timezone("UTC"))@@ -306,7 +332,7 @@ class SessionReplayEvents:# The bound is a perf optimization, not a correctness gate: ids the# bounded scan missed (clock skewed past the slack) get one unbounded# retry before being reported as not-found.- found_ids = {session_id for session_id, _, _, _ in sessions_found}+ found_ids = {found.session_id for found in sessions_found}missing = [session_id for session_id in session_ids if session_id not in found_ids]if missing:sessions_found += SessionReplayEvents._find_with_timestamps_from(missing, team, now, None)@@ -315,7 +341,7 @@ class SessionReplayEvents:@staticmethoddef _find_with_timestamps_from(session_ids: list[str], team: Team, now: datetime, date_from: Optional[datetime]- ) -> list[tuple[str, datetime, datetime, datetime]]:+ ) -> list[SessionTimestamps]:from posthog.hogql_queries.hogql_query_runner import HogQLQueryRunneroptional_lower_bound_clause = "AND min_first_timestamp >= {date_from}" if date_from else ""@@ -349,10 +375,11 @@ class SessionReplayEvents:result = HogQLQueryRunner(team=team, query=query).calculate()if not result.results:return []- sessions_found: list[tuple[str, datetime, datetime, datetime]] = [- (row[0], row[1], row[2], row[4]) for row in result.results+ # Query columns: session_id, min_timestamp, max_timestamp, retention_period_days, expiry_time.+ return [+ SessionTimestamps(session_id=row[0], min_timestamp=row[1], max_timestamp=row[2], expiry_time=row[4])+ for row in result.results]- return sessions_found@staticmethoddef _find_sessions_in_events(@@ -647,8 +674,8 @@ class SessionReplayEvents:extra_fields: list[str] | None = None,limit: int | None = None,page: int = 0,- ) -> tuple[list | None, list | None, bool]:- """Return `(columns, rows, has_more)`. When `limit` is set, fetches one extra row internally to detect whether more pages exist."""+ ) -> SessionEventsPage:+ """Return one page of events. When `limit` is set, fetches one extra row internally to detect whether more pages exist."""from posthog.schema import HogQLQueryResponsefrom posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner@@ -668,8 +695,8 @@ class SessionReplayEvents:).calculate()columns, rows = result.columns, result.resultsif limit is not None and limit > 0 and rows is not None and len(rows) > limit:- return columns, rows[:limit], True- return columns, rows, False+ return SessionEventsPage(columns=columns, rows=rows[:limit], has_more=True)+ return SessionEventsPage(columns=columns, rows=rows, has_more=False)@staticmethoddef get_sessions_from_distinct_id_query(diff --git a/posthog/session_recordings/queries/test/test_session_replay_events.py b/posthog/session_recordings/queries/test/test_session_replay_events.pyindex f5dac43fb397..b9c78f1e5f33 100644--- a/posthog/session_recordings/queries/test/test_session_replay_events.py+++ b/posthog/session_recordings/queries/test/test_session_replay_events.py@@ -1,5 +1,6 @@from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event+from django.core.cache import cachefrom django.utils.timezone import nowfrom dateutil.relativedelta import relativedelta@@ -232,46 +233,51 @@ class SessionReplayEventsQueries(ClickhouseTestMixin, APIBaseTest):assert metadata_dict["3"] is not Nonedef test_sessions_found_with_timestamps(self) -> None:- sessions, min_ts, max_ts = SessionReplayEvents().sessions_found_with_timestamps(+ result = SessionReplayEvents().sessions_found_with_timestamps(session_ids=["1", "2", "3"],team=self.team,)+ sessions, min_ts, max_ts = result.session_ids, result.min_timestamp, result.max_timestampassert sessions == {"1", "2", "3"}assert min_ts == self.base_timeassert max_ts == self.base_time + relativedelta(seconds=3)def test_sessions_found_with_timestamps_partial_match(self) -> None:- sessions, min_ts, max_ts = SessionReplayEvents().sessions_found_with_timestamps(+ result = SessionReplayEvents().sessions_found_with_timestamps(session_ids=["1", "nonexistent", "3"],team=self.team,)+ sessions, min_ts, max_ts = result.session_ids, result.min_timestamp, result.max_timestampassert sessions == {"1", "3"}assert min_ts == self.base_timeassert max_ts == self.base_time + relativedelta(seconds=3)def test_sessions_found_with_timestamps_empty_list(self) -> None:- sessions, min_ts, max_ts = SessionReplayEvents().sessions_found_with_timestamps(+ result = SessionReplayEvents().sessions_found_with_timestamps(session_ids=[],team=self.team,)+ sessions, min_ts, max_ts = result.session_ids, result.min_timestamp, result.max_timestampassert sessions == set()assert min_ts is Noneassert max_ts is Nonedef test_sessions_found_with_timestamps_no_matches(self) -> None:- sessions, min_ts, max_ts = SessionReplayEvents().sessions_found_with_timestamps(+ result = SessionReplayEvents().sessions_found_with_timestamps(session_ids=["nonexistent1", "nonexistent2"],team=self.team,)+ sessions, min_ts, max_ts = result.session_ids, result.min_timestamp, result.max_timestampassert sessions == set()assert min_ts is Noneassert max_ts is Nonedef test_sessions_found_with_timestamps_single_session(self) -> None:- sessions, min_ts, max_ts = SessionReplayEvents().sessions_found_with_timestamps(+ result = SessionReplayEvents().sessions_found_with_timestamps(session_ids=["2"],team=self.team,)+ sessions, min_ts, max_ts = result.session_ids, result.min_timestamp, result.max_timestampassert sessions == {"2"}assert min_ts == self.base_timeassert max_ts == self.base_time + relativedelta(seconds=2)@@ -289,10 +295,11 @@ class SessionReplayEventsQueries(ClickhouseTestMixin, APIBaseTest):ensure_analytics_event_in_session=False,)# Should not include the session without events- sessions, min_ts, max_ts = SessionReplayEvents().sessions_found_with_timestamps(+ result = SessionReplayEvents().sessions_found_with_timestamps(session_ids=["1", "no_events_session"],team=self.team,)+ sessions, min_ts, max_ts = result.session_ids, result.min_timestamp, result.max_timestampassert sessions == {"1"}assert min_ts == self.base_timeassert max_ts == self.base_time@@ -320,10 +327,11 @@ class SessionReplayEventsQueries(ClickhouseTestMixin, APIBaseTest):ensure_analytics_event_in_session=False,)# Should return empty when all sessions lack events- sessions, min_ts, max_ts = SessionReplayEvents().sessions_found_with_timestamps(+ result = SessionReplayEvents().sessions_found_with_timestamps(session_ids=["no_events_1", "no_events_2"],team=self.team,)+ sessions, min_ts, max_ts = result.session_ids, result.min_timestamp, result.max_timestampassert sessions == set()assert min_ts is Noneassert max_ts is None@@ -405,7 +413,29 @@ class TestSessionLookupUsesUuidv7Bound(ClickhouseTestMixin, APIBaseTest):found = SessionReplayEvents()._find_with_timestamps([uuid_id, custom_id], self.team)- assert {session_id for session_id, _, _, _ in found} == {uuid_id, custom_id}+ assert {entry.session_id for entry in found} == {uuid_id, custom_id}+++class TestBatchExists(ClickhouseTestMixin, APIBaseTest):+ def test_maps_each_session_to_existence_and_caches_positives(self) -> None:+ session_start = (now() - relativedelta(days=1)).replace(microsecond=0)+ found_id = _uuidv7_session_id_for(session_start)+ produce_replay_summary(+ session_id=found_id,+ team_id=self.team.pk,+ first_timestamp=session_start,+ last_timestamp=session_start,+ distinct_id="u1",+ retention_period_days=30,+ )++ results = SessionReplayEvents().batch_exists([found_id, "missing-session"], self.team)++ assert results == {found_id: True, "missing-session": False}+ # Found sessions are cached with an expiry-derived (future, positive) TTL, so the entry must exist.+ # Non-existence is never cached, so a recording arriving late is still discoverable.+ assert cache.get(f"session_recording_existence_team_{self.team.pk}_id_{found_id}") is True+ assert cache.get(f"session_recording_existence_team_{self.team.pk}_id_missing-session") is Noneclass TestGetLatestSessionEventProperties(ClickhouseTestMixin, APIBaseTest):diff --git a/posthog/session_recordings/session_recording_playlist_api.py b/posthog/session_recordings/session_recording_playlist_api.pyindex 86cc9161a446..254695365bcc 100644--- a/posthog/session_recordings/session_recording_playlist_api.py+++ b/posthog/session_recordings/session_recording_playlist_api.py@@ -1,6 +1,7 @@import jsonimport builtinsfrom collections import defaultdict+from dataclasses import dataclassfrom datetime import UTC, datetimefrom typing import Any, Optional, cast@@ -69,6 +70,20 @@ CURRENT_USER_VIEWED_CHUNK_SIZE = 5000MAX_SAVED_FILTER_SESSION_IDS_PER_PLAYLIST = 1000+@dataclass(frozen=True)+class PlaylistPageSplit:+ """One list page split into its synthetic playlists and the aligned DB slice."""++ synthetics: builtins.list[SessionRecordingPlaylist]+ db_items: builtins.list[SessionRecordingPlaylist]+++@dataclass(frozen=True)+class PaginationLinks:+ next_link: Optional[str]+ previous_link: Optional[str]++class SessionRecordingPlaylistPagination(LimitOffsetPagination):default_limit = 100max_limit = PLAYLIST_LIST_MAX_LIMIT@@ -679,10 +694,10 @@ class SessionRecordingPlaylistViewSet(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)+ page_split = self._split_page(offset, limit, ranked_synthetics, queryset)with tracer.start_as_current_span("order_combined_page"):- combined = self._order_playlists(request, synth_for_page + db_items)+ combined = self._order_playlists(request, page_split.synthetics + page_split.db_items)span.set_attribute("page_size", len(combined))@@ -706,12 +721,12 @@ class SessionRecordingPlaylistViewSet(with tracer.start_as_current_span("serialize"):results = self.get_serializer(combined, many=True).data- next_link, previous_link = self._pagination_links(request, total_count, limit, offset)+ links = self._pagination_links(request, total_count, limit, offset)return response.Response({"count": total_count,- "next": next_link,- "previous": previous_link,+ "next": links.next_link,+ "previous": links.previous_link,"results": results,})@@ -722,7 +737,7 @@ class SessionRecordingPlaylistViewSet(limit: int,ranked_synthetics: builtins.list[tuple[int, SessionRecordingPlaylist]],queryset: QuerySet,- ) -> tuple[builtins.list[SessionRecordingPlaylist], builtins.list[SessionRecordingPlaylist]]:+ ) -> "PlaylistPageSplit":"""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@@ -736,18 +751,18 @@ class SessionRecordingPlaylistViewSet(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+ return PlaylistPageSplit(synthetics=synth_for_page, db_items=db_items)def _pagination_links(self, request: request.Request, total_count: int, limit: int, offset: int- ) -> tuple[Optional[str], Optional[str]]:+ ) -> "PaginationLinks":"""next/previous links over the merged total via a directly-seeded paginator."""paginator = SessionRecordingPlaylistPagination()paginator.count = total_countpaginator.limit = limitpaginator.offset = offsetpaginator.request = request- return paginator.get_next_link(), paginator.get_previous_link()+ return PaginationLinks(next_link=paginator.get_next_link(), previous_link=paginator.get_previous_link())def _synthetic_global_ranks(self,diff --git a/products/replay_vision/backend/api/observation_progress.py b/products/replay_vision/backend/api/observation_progress.pyindex 88e2ff708367..7851143c8c9c 100644--- a/products/replay_vision/backend/api/observation_progress.py+++ b/products/replay_vision/backend/api/observation_progress.py@@ -2,6 +2,7 @@ import jsonimport timeimport asynciofrom collections.abc import AsyncGenerator+from dataclasses import dataclassfrom typing import Anyfrom uuid import UUID@@ -33,16 +34,22 @@ def _sse_event(label: str, data: str) -> str:return f"event: {label}\ndata: {data}\n\n"+@dataclass(frozen=True)+class _ObservationState:+ status: str+ workflow_id: str++@database_sync_to_async-def _read_observation_state(observation_id: UUID, team_id: int) -> tuple[str, str] | None:- """Returns (status, workflow_id), or None if the row vanished. Team-scoped: the caller already+def _read_observation_state(observation_id: UUID, team_id: int) -> _ObservationState | None:+ """Returns the observation's live state, or None if the row vanished. Team-scoped: the caller alreadyauthorized this observation via get_object(), but the query stays tenant-scoped per the IDOR rule."""row = (ReplayObservation.objects.filter(pk=observation_id, team_id=team_id).values_list("status", "workflow_id").first())- return None if row is None else (row[0], row[1])+ return None if row is None else _ObservationState(status=row[0], workflow_id=row[1])def _fallback_progress(status: str) -> ObservationProgress:@@ -119,7 +126,7 @@ async def stream_observation_progress(observation: ReplayObservation) -> AsyncGeif state is None:yield _sse_event("observation-error", "Observation not found")return- status, workflow_id = state+ status, workflow_id = state.status, state.workflow_idif status in _TERMINAL_STATUSES:yield _sse_event("observation-complete", json.dumps({"status": status}))returndiff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.pyindex 772e6bd8963b..eff5fc1f0391 100644--- a/products/replay_vision/backend/api/observations.py+++ b/products/replay_vision/backend/api/observations.py@@ -1,5 +1,6 @@import jsonimport uuid+from dataclasses import dataclassfrom typing import Any, cast, get_argsfrom zoneinfo import ZoneInfo@@ -604,7 +605,13 @@ class CreateTaskFromObservationResponseSerializer(serializers.Serializer):)-def _observation_task_content(observation: ReplayObservation, scanner: ReplayScanner) -> tuple[str, str]:+@dataclass(frozen=True)+class _TaskContent:+ title: str+ description: str+++def _observation_task_content(observation: ReplayObservation, scanner: ReplayScanner) -> _TaskContent:"""Title and description for a Task created from an observation's finding."""snapshot = observation.scanner_snapshot or {}scanner_name = snapshot.get("name") or scanner.name or "Replay Vision scanner"@@ -625,7 +632,7 @@ def _observation_task_content(observation: ReplayObservation, scanner: ReplayScaf"Scanner: {scanner.id}\n\n"f"{fenced_finding}\n")- return title, description+ return _TaskContent(title=title, description=description)@extend_schema_view(@@ -802,7 +809,7 @@ class ReplayObservationViewSet(user = cast(User, request.user)if not has_tasks_access(user):raise PermissionDenied("Creating a task requires access to PostHog Code.")- title, description = _observation_task_content(observation, scanner)+ content = _observation_task_content(observation, scanner)# Lock the observation row so a client retry or concurrent double submit returns the task the# first call minted instead of creating a duplicate to triage.with transaction.atomic():@@ -813,8 +820,8 @@ class ReplayObservationViewSet(team=self.team,user_id=user.id,origin_product=tasks_facade.TaskOriginProduct.USER_CREATED,- title=title,- description=description,+ title=content.title,+ description=content.description,)locked.created_task_id = task_idlocked.save(update_fields=["created_task_id"])diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex b39d56c4875b..8213bd3b48fd 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -482,7 +482,8 @@ class _ScannerOrderByFilter(OrderByFilter):organization_id = qs.values_list("team__organization_id", flat=True).first()if organization_id is None:return qs.order_by(self._tiebreaker)- period_start, period_end = current_period_bounds(organization_id)+ period = current_period_bounds(organization_id)+ period_start, period_end = period.start, period.endspend = (ReplayObservation.objects.filter(scanner_id=OuterRef("pk"),diff --git a/products/replay_vision/backend/models/vision_action.py b/products/replay_vision/backend/models/vision_action.pyindex 25404e9f20c7..d76400116a0c 100644--- a/products/replay_vision/backend/models/vision_action.py+++ b/products/replay_vision/backend/models/vision_action.py@@ -1,3 +1,4 @@+from dataclasses import dataclassfrom typing import Anyfrom django.core.validators import MinValueValidator@@ -44,6 +45,14 @@ class AlertDirection(models.TextChoices):BELOW = "below", "At or below"+@dataclass(frozen=True)+class _ScheduleKey:+ """Cadence identity: `save()` compares these by equality to detect a schedule change."""++ rrule: str+ timezone: str++class VisionAction(TeamScopedRootMixin, UUIDModel):"""An "and then…" automation over a scanner's observations: gather, (optionally) synthesize, deliver.@@ -159,7 +168,7 @@ class VisionAction(TeamScopedRootMixin, UUIDModel):if not ({"trigger_type", "trigger_config"} & self.get_deferred_fields()):self._cached_schedule_key = self._schedule_key()- def _schedule_key(self) -> tuple[str, str] | None:+ def _schedule_key(self) -> "_ScheduleKey | None":# Both the rrule AND the timezone determine the next fire time, so a change to either must# trigger a recompute — keying on the rrule alone would miss a timezone-only edit.if self.trigger_type != TriggerType.SCHEDULE:@@ -168,17 +177,16 @@ class VisionAction(TeamScopedRootMixin, UUIDModel):rrule = cfg.get("rrule")if not rrule:return None- return (rrule, cfg.get("timezone", "UTC"))+ return _ScheduleKey(rrule=rrule, timezone=cfg.get("timezone", "UTC"))def _recompute_next_run_at(self) -> None:key = self._schedule_key()if key is None:self.next_run_at = Nonereturn- rrule, timezone_str = keystarts_at = self.created_at or timezone.now()occurrences = compute_next_occurrences(- rrule_string=rrule, starts_at=starts_at, timezone_str=timezone_str, count=1+ rrule_string=key.rrule, starts_at=starts_at, timezone_str=key.timezone, count=1)self.next_run_at = occurrences[0] if occurrences else Nonediff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.pyindex 238cf62249cf..f16b8a7847c6 100644--- a/products/replay_vision/backend/quota.py+++ b/products/replay_vision/backend/quota.py@@ -64,8 +64,16 @@ def next_month_start(now: datetime) -> datetime:return start_of_month(now) + relativedelta(months=1)-def _current_month_bounds(now: datetime) -> tuple[datetime, datetime]:- return start_of_month(now), next_month_start(now)+@dataclass(frozen=True)+class BillingPeriod:+ """Half-open [start, end) window observations are counted against."""++ start: datetime+ end: datetime+++def _current_month_bounds(now: datetime) -> BillingPeriod:+ return BillingPeriod(start=start_of_month(now), end=next_month_start(now))def _as_utc(value: datetime) -> datetime:@@ -73,17 +81,17 @@ def _as_utc(value: datetime) -> datetime:return value if value.tzinfo else value.replace(tzinfo=UTC)-def _current_period_bounds(organization: Organization | None, now: datetime) -> tuple[datetime, datetime]:+def _current_period_bounds(organization: Organization | None, now: datetime) -> BillingPeriod:"""The org's active billing period when synced and current, else the calendar month containing `now`."""billing_period = organization.current_billing_period if organization else Noneif billing_period:- billing_period = (_as_utc(billing_period[0]), _as_utc(billing_period[1]))- if billing_period[0] <= now < billing_period[1]:- return billing_period+ synced = BillingPeriod(start=_as_utc(billing_period[0]), end=_as_utc(billing_period[1]))+ if synced.start <= now < synced.end:+ return syncedreturn _current_month_bounds(now)-def current_period_bounds(organization_id: UUID) -> tuple[datetime, datetime]:+def current_period_bounds(organization_id: UUID) -> BillingPeriod:"""The org's active billing period when synced and current, else the current calendar month."""organization = Organization.objects.filter(pk=organization_id).only("usage").first()return _current_period_bounds(organization, datetime.now(UTC))@@ -98,7 +106,8 @@ def credits_used_by_scanner(organization_id: UUID, scanner_ids: list[UUID]) -> d"""if not scanner_ids:return {}- period_start, period_end = current_period_bounds(organization_id)+ period = current_period_bounds(organization_id)+ period_start, period_end = period.start, period.endpairs = Counter(ReplayObservation.objects.filter(scanner_id__in=scanner_ids,@@ -152,7 +161,8 @@ def compute_quota_snapshot(organization_id: UUID) -> QuotaSnapshot:now = datetime.now(UTC)organization = Organization.objects.filter(pk=organization_id).only("usage").first()# Billing is the source of truth once synced, falling back to the env cap and calendar months otherwise.- period_start, period_end = _current_period_bounds(organization, now)+ period = _current_period_bounds(organization, now)+ period_start, period_end = period.start, period.end# Permanently-spent (succeeded) from the immutable ledger; deletes can't refund it.consumed = ReplayObservationUsage.objects.filter(organization_id=organization_id,diff --git a/products/replay_vision/backend/tag_suggestions.py b/products/replay_vision/backend/tag_suggestions.pyindex 38e173e641a9..7972d18c4d97 100644--- a/products/replay_vision/backend/tag_suggestions.py+++ b/products/replay_vision/backend/tag_suggestions.py@@ -9,6 +9,7 @@ categories."""import uuid+from dataclasses import dataclassfrom typing import Literalfrom django.conf import settings@@ -97,7 +98,13 @@ def _observation_signal(scanner: ReplayScanner) -> tuple[list[tuple[str, int]],return freeform, samples-def _product_taxonomy(team: Team) -> tuple[list[str], list[str]]:+@dataclass(frozen=True)+class _ProductTaxonomy:+ events: list[str]+ screens: list[str]+++def _product_taxonomy(team: Team) -> _ProductTaxonomy:"""Custom product events and the screens sessions cover — grounds suggestions in how THIS product works."""events: list[str] = []try:@@ -117,7 +124,7 @@ def _product_taxonomy(team: Team) -> tuple[list[str], list[str]]:screens = [str(row[0]) for row in rows if row and row[0]][:_MAX_TOP_SCREENS]except Exception:logger.warning("replay_vision.suggest_tags.screens_failed", team_id=team.id, exc_info=True)- return events, screens+ return _ProductTaxonomy(events=events, screens=screens)def _sibling_vocabularies(@@ -232,7 +239,7 @@ def _assemble_grounding_evidence("replay_vision.suggest_tags.observation_signal_failed", scanner_id=str(scanner.id), exc_info=True)- events, screens = _product_taxonomy(team)+ taxonomy = _product_taxonomy(team)sibling_tags: list[str] = []if user_access_control is not None:sibling_tags = _sibling_vocabularies(team, scanner.id if scanner is not None else None, user_access_control)@@ -244,8 +251,8 @@ def _assemble_grounding_evidence(allow_freeform_tags=allow_freeform_tags,freeform=freeform,reasoning_samples=reasoning_samples,- events=events,- screens=screens,+ events=taxonomy.events,+ screens=taxonomy.screens,sibling_tags=sibling_tags,)diff --git a/products/replay_vision/backend/temporal/activities/fetch_session_events.py b/products/replay_vision/backend/temporal/activities/fetch_session_events.pyindex 6f15c5702f6c..19055e3544e5 100644--- a/products/replay_vision/backend/temporal/activities/fetch_session_events.py+++ b/products/replay_vision/backend/temporal/activities/fetch_session_events.py@@ -129,22 +129,22 @@ def _fetch_payload(team_id: int, session_id: str) -> ScannerLlmInputs | None:columns: list[str] | None = Noneall_rows: list[list[Any]] = []- for page in itertools.count():- page_columns, page_rows, has_more = events_obj.get_events(+ for page_number in itertools.count():+ page = events_obj.get_events(session_id=session_id,team=team,metadata=metadata,events_to_ignore=_EVENTS_TO_IGNORE,extra_fields=_EXTRA_FIELDS,limit=_EVENTS_PER_PAGE,- page=page,+ page=page_number,)- if page_columns and columns is None:- columns = list(page_columns)- if not page_rows:+ if page.columns and columns is None:+ columns = list(page.columns)+ if not page.rows:break- all_rows.extend(list(row) for row in page_rows)- if not has_more:+ all_rows.extend(list(row) for row in page.rows)+ if not page.has_more:breakif columns is None or not all_rows:diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex 41f239ec9657..33b97ef05588 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -29,7 +29,7 @@ from products.replay_vision.backend.models.replay_scanner import ()from products.replay_vision.backend.models.vision_action import VisionActionfrom products.replay_vision.backend.queries.scanner_candidate_query import SETTLE_INTERVAL-from products.replay_vision.backend.quota import _current_period_bounds+from products.replay_vision.backend.quota import BillingPeriod, _current_period_boundsfrom products.replay_vision.backend.temporal.constants import (APPLY_SCANNER_WORKFLOW_NAME,build_apply_scanner_workflow_id,@@ -2209,4 +2209,4 @@ class TestCurrentPeriodBounds(SimpleTestCase):)def test_period_selection(self, _name: str, usage: dict | None, expected: tuple[datetime, datetime]) -> None:organization = Organization(usage=usage) if usage is not None else None- self.assertEqual(_current_period_bounds(organization, self.NOW), expected)+ self.assertEqual(_current_period_bounds(organization, self.NOW), BillingPeriod(*expected))diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.pyindex f93bea51e3f4..60df11cb3cdc 100644--- a/products/replay_vision/backend/tests/test_temporal.py+++ b/products/replay_vision/backend/tests/test_temporal.py@@ -25,7 +25,7 @@ from temporalio.exceptions import (from posthog.models import Organization, Teamfrom posthog.models.user import Userfrom posthog.redis import get_async_client-from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents+from posthog.session_recordings.queries.session_replay_events import SessionEventsPage, SessionReplayEventsfrom products.exports.backend.models.exported_asset import ExportedAssetfrom products.replay_vision.backend.api.observation_progress import stream_observation_progress@@ -806,7 +806,10 @@ class TestFetchSessionEventsActivity:pages: list[tuple],) -> MagicMock:"""Pages may be 2-tuples (columns, rows) or 3-tuples (columns, rows, has_more); has_more defaults to False."""- normalized = [page if len(page) == 3 else (*page, False) for page in pages]+ normalized = [+ SessionEventsPage(columns=page[0], rows=page[1], has_more=page[2] if len(page) == 3 else False)+ for page in pages+ ]mock_obj = MagicMock(spec=SessionReplayEvents)mock_obj.get_metadata.return_value = metadatamock_obj.get_events.side_effect = normalized