: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
fix(replay): report ongoing on the single-recording endpoint (#74071)
Arno Hillen5bd6fd09be25
diff --git a/posthog/session_recordings/models/metadata.py b/posthog/session_recordings/models/metadata.pyindex 5f1f6dcc42e8..251e03741eee 100644--- a/posthog/session_recordings/models/metadata.py+++ b/posthog/session_recordings/models/metadata.py@@ -4,6 +4,10 @@ from typing import Literal, Optional, TypedDict, UnionSnapshotData = dictWindowId = Optional[str]+# A session counts as ongoing when replay data for it was last ingested within this window.+# Shared so the listing query and the single-recording metadata query agree on "ongoing".+ONGOING_SESSION_WINDOW_MINUTES = 5+class RecordingSegment(TypedDict):start_time: datetime@@ -59,6 +63,7 @@ class RecordingMetadata(TypedDict):retention_period_days: Optional[int]expiry_time: datetimerecording_ttl: int+ ongoing: boolclass RecordingMatchingEvents(TypedDict):diff --git a/posthog/session_recordings/models/session_recording.py b/posthog/session_recordings/models/session_recording.pyindex b87621009e53..889caeabddcd 100644--- a/posthog/session_recordings/models/session_recording.py+++ b/posthog/session_recordings/models/session_recording.py@@ -137,6 +137,7 @@ class SessionRecording(UUIDTModel):self.retention_period_days = metadata["retention_period_days"]self.expiry_time = metadata["expiry_time"]self.recording_ttl = metadata["recording_ttl"]+ self.ongoing = metadata["ongoing"]return Truediff --git a/posthog/session_recordings/queries/session_recording_list_from_query.py b/posthog/session_recordings/queries/session_recording_list_from_query.pyindex 2b08f8aeed57..98a279edf781 100644--- a/posthog/session_recordings/queries/session_recording_list_from_query.py+++ b/posthog/session_recordings/queries/session_recording_list_from_query.py@@ -22,6 +22,7 @@ from posthog.hogql.property import property_to_exprfrom posthog.exceptions_capture import capture_exceptionfrom posthog.hogql_queries.insights.paginators import HogQLCursorPaginator, HogQLHasMorePaginatorfrom posthog.models import Team, User+from posthog.session_recordings.models.metadata import ONGOING_SESSION_WINDOW_MINUTESfrom posthog.session_recordings.queries.sub_queries.base_query import SessionRecordingsListingBaseQueryfrom posthog.session_recordings.queries.sub_queries.cohort_subquery import CohortPropertyGroupsSubQueryfrom posthog.session_recordings.queries.sub_queries.events_subquery import ReplayFiltersEventsSubQuery@@ -240,7 +241,7 @@ class SessionRecordingListFromQuery(SessionRecordingsListingBaseQuery):left=ast.Call(name="max", args=[ast.Field(chain=["s", "_timestamp"])]),right=ast.Constant(# provided in a placeholder, so we can pass now from python to make tests easier 🙈- value=datetime.now(UTC) - timedelta(minutes=5),+ value=datetime.now(UTC) - timedelta(minutes=ONGOING_SESSION_WINDOW_MINUTES),),op=ast.CompareOperationOp.GtEq,),diff --git a/posthog/session_recordings/queries/session_replay_events.py b/posthog/session_recordings/queries/session_replay_events.pyindex 4dcf9def0bb4..e4ce8fa61c17 100644--- a/posthog/session_recordings/queries/session_replay_events.py+++ b/posthog/session_recordings/queries/session_replay_events.py@@ -13,7 +13,7 @@ from posthog.schema import HogQLQueryfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.models.team import Team-from posthog.session_recordings.models.metadata import RecordingMetadata+from posthog.session_recordings.models.metadata import ONGOING_SESSION_WINDOW_MINUTES, RecordingMetadataDEFAULT_EVENT_FIELDS = ["event",@@ -442,7 +442,8 @@ class SessionReplayEvents:groupArrayArray(block_urls) as block_urls,max(retention_period_days) as retention_period_days,dateTrunc('DAY', start_time) + toIntervalDay(coalesce(retention_period_days, 30)) as expiry_time,- dateDiff('DAY', toDateTime(%(python_now)s), expiry_time) as recording_ttl+ dateDiff('DAY', toDateTime(%(python_now)s), expiry_time) as recording_ttl,+ max(_timestamp) >= toDateTime(%(python_now)s) - INTERVAL {ongoing_window_minutes} MINUTE as ongoingFROMsession_replay_eventsPREWHERE@@ -462,6 +463,7 @@ class SessionReplayEvents:"AND min_first_timestamp >= %(recording_start_time)s" if recording_start_time else ""),optional_format_clause=(f"FORMAT {format}" if format else ""),+ ongoing_window_minutes=ONGOING_SESSION_WINDOW_MINUTES,)return query@@ -493,6 +495,7 @@ class SessionReplayEvents:retention_period_days=replay[18],expiry_time=replay[19],recording_ttl=replay[20],+ ongoing=bool(replay[21]),)def get_metadata(@@ -578,7 +581,8 @@ class SessionReplayEvents:groupArrayArray(block_urls) as block_urls,max(retention_period_days) as retention_period_days,dateTrunc('DAY', start_time) + toIntervalDay(coalesce(retention_period_days, 30)) as expiry_time,- dateDiff('DAY', toDateTime(%(python_now)s), expiry_time) as recording_ttl+ dateDiff('DAY', toDateTime(%(python_now)s), expiry_time) as recording_ttl,+ max(_timestamp) >= toDateTime(%(python_now)s) - INTERVAL {ONGOING_SESSION_WINDOW_MINUTES} MINUTE as ongoingFROMsession_replay_eventsPREWHEREdiff --git a/posthog/session_recordings/queries/test/test_session_replay_events.py b/posthog/session_recordings/queries/test/test_session_replay_events.pyindex b9c78f1e5f33..020d2273d420 100644--- a/posthog/session_recordings/queries/test/test_session_replay_events.py+++ b/posthog/session_recordings/queries/test/test_session_replay_events.py@@ -96,6 +96,7 @@ class SessionReplayEventsQueries(ClickhouseTestMixin, APIBaseTest):"start_time": self.base_time,"snapshot_source": "web","snapshot_library": None,+ "ongoing": True,}def test_get_metadata_with_block(self) -> None:@@ -121,6 +122,7 @@ class SessionReplayEventsQueries(ClickhouseTestMixin, APIBaseTest):"mouse_activity_count": 300,"snapshot_source": "web","snapshot_library": None,+ "ongoing": True,}def test_get_metadata_with_multiple_blocks(self) -> None:@@ -152,6 +154,7 @@ class SessionReplayEventsQueries(ClickhouseTestMixin, APIBaseTest):"recording_ttl": 364,"snapshot_source": "web","snapshot_library": None,+ "ongoing": True,}def test_get_nonexistent_metadata(self) -> None:@@ -198,6 +201,7 @@ class SessionReplayEventsQueries(ClickhouseTestMixin, APIBaseTest):"start_time": self.base_time,"snapshot_source": "web","snapshot_library": None,+ "ongoing": True,}assert metadata_dict["2"] == {"active_seconds": 1.234,@@ -220,6 +224,7 @@ class SessionReplayEventsQueries(ClickhouseTestMixin, APIBaseTest):"recording_ttl": 89,"snapshot_source": "web","snapshot_library": None,+ "ongoing": True,}def test_get_group_metadata_handles_nonexistent_sessions(self) -> None:diff --git a/posthog/session_recordings/test/test_session_recordings.py b/posthog/session_recordings/test/test_session_recordings.pyindex d24c2f422cc2..302e51fed14d 100644--- a/posthog/session_recordings/test/test_session_recordings.py+++ b/posthog/session_recordings/test/test_session_recordings.py@@ -823,7 +823,8 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)"recording_ttl": 29,"snapshot_source": "web","snapshot_library": None,- "ongoing": None,+ # ingestion just happened in this test, so the session still counts as ongoing+ "ongoing": True,"activity_score": None,"has_summary": False,"summary_outcome": None,@@ -831,6 +832,31 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)"matches_filters": True,}+ @parameterized.expand(+ [+ ("recently_ingested", 1, True),+ ("ingested_long_ago", 30, False),+ ]+ )+ def test_single_session_recording_reports_ongoing(+ self, _name: str, ingested_minutes_ago: int, expected_ongoing: bool+ ) -> None:+ session_recording_id = str(uuid7())+ base_time = (now() - relativedelta(minutes=45)).replace(microsecond=0)+ produce_replay_summary(+ session_id=session_recording_id,+ team_id=self.team.pk,+ first_timestamp=base_time.isoformat(),+ last_timestamp=(base_time + relativedelta(seconds=30)).isoformat(),+ distinct_id="d1",+ kafka_timestamp=now() - timedelta(minutes=ingested_minutes_ago),+ )++ response = self.client.get(f"/api/projects/{self.team.id}/session_recordings/{session_recording_id}")++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["ongoing"] is expected_ongoing+@freeze_time("2023-01-01T12:00:00.000Z")def test_get_single_session_recording_metadata_has_summary_true(self):try: