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(replay): bound session lookups using the uuidv7 session id timestamp (#62770)

Paul D'Ambra6564082eab5f
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 2f4b5c5b80d6..f857b1c12894 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -4416,6 +4416,11 @@ const api = {
async getMatchingEvents(params: string): Promise<MatchingEventsResponse> {
return await new ApiRequest().recordingMatchingEvents().withQueryString(params).get()
},
+ async getCaptureDiagnostics(
+ recordingId: SessionRecordingType['id']
+ ): Promise<{ properties: Record<string, any> | null }> {
+ return await new ApiRequest().recording(recordingId).withAction('capture_diagnostics').get()
+ },
async get(
recordingId: SessionRecordingType['id'],
params: Record<string, any> = {},
diff --git a/frontend/src/mocks/handlers.ts b/frontend/src/mocks/handlers.ts
index 6d57dc74e842..066ca917d4ed 100644
--- a/frontend/src/mocks/handlers.ts
+++ b/frontend/src/mocks/handlers.ts
@@ -226,6 +226,7 @@ export const defaultMocks: Mocks = {
'/api/environments/:team_id/session_recording_playlists': EMPTY_PAGINATED_RESPONSE,
'/api/projects/:team_id/session_recordings': EMPTY_PAGINATED_RESPONSE,
'/api/environments/:team_id/session_recordings': EMPTY_PAGINATED_RESPONSE,
+ '/api/environments/:team_id/session_recordings/:id/capture_diagnostics': { properties: null },
'/api/projects/:team_id/insights/my_last_viewed': EMPTY_PAGINATED_RESPONSE,
'/api/environments/:team_id/insights/my_last_viewed': EMPTY_PAGINATED_RESPONSE,
'api/projects/:team_id/early_access_feature': EMPTY_PAGINATED_RESPONSE,
diff --git a/frontend/src/scenes/session-recordings/SessionsRecordings-activity-modal.stories.tsx b/frontend/src/scenes/session-recordings/SessionsRecordings-activity-modal.stories.tsx
index a6e5c2d6fe92..5ab483b5aee7 100644
--- a/frontend/src/scenes/session-recordings/SessionsRecordings-activity-modal.stories.tsx
+++ b/frontend/src/scenes/session-recordings/SessionsRecordings-activity-modal.stories.tsx
@@ -90,6 +90,9 @@ export const EventExplorerWithModalNotFound: Story = {
get: {
'/api/environments/:team_id/session_recordings/:id': () => [404, { detail: 'Not found.' }],
'/api/environments/:team_id/session_recordings/:id/snapshots': () => [404, { detail: 'Not found.' }],
+ '/api/environments/:team_id/session_recordings/:id/capture_diagnostics': {
+ properties: (eventsQuery.results[0][0] as Record<string, any>).properties,
+ },
},
post: {
'/api/environments/:team_id/query/:kind': eventsQuery,
diff --git a/frontend/src/scenes/session-recordings/SessionsRecordings-player-failure.stories.tsx b/frontend/src/scenes/session-recordings/SessionsRecordings-player-failure.stories.tsx
index 387a831dd8da..8cf2561d51b9 100644
--- a/frontend/src/scenes/session-recordings/SessionsRecordings-player-failure.stories.tsx
+++ b/frontend/src/scenes/session-recordings/SessionsRecordings-player-failure.stories.tsx
@@ -121,6 +121,7 @@ const meta: Meta = {
},
post: {
'/api/environments/:team_id/query/:kind': recordingEventsJson,
+ '/api/environments/:team_id/session_recordings/:id/capture_diagnostics': { properties: null },
},
}),
],
diff --git a/frontend/src/scenes/session-recordings/components/replayCaptureDiagnosticsPanelLogic.ts b/frontend/src/scenes/session-recordings/components/replayCaptureDiagnosticsPanelLogic.ts
index 47b3d2b29695..015d83488707 100644
--- a/frontend/src/scenes/session-recordings/components/replayCaptureDiagnosticsPanelLogic.ts
+++ b/frontend/src/scenes/session-recordings/components/replayCaptureDiagnosticsPanelLogic.ts
@@ -3,8 +3,6 @@ import { lazyLoaders } from 'kea-loaders'
import api from 'lib/api'
-import { hogql } from '~/queries/utils'
-
import type { replayCaptureDiagnosticsPanelLogicType } from './replayCaptureDiagnosticsPanelLogicType'
export interface ReplayCaptureDiagnosticsPanelLogicProps {
@@ -21,24 +19,9 @@ export const replayCaptureDiagnosticsPanelLogic = kea<replayCaptureDiagnosticsPa
lazyLoaders(({ props }) => ({
sessionEventProperties: {
loadSessionEventProperties: async (_, breakpoint): Promise<Record<string, any> | null> => {
- const query = hogql`
-SELECT properties
-FROM events
-WHERE $session_id = ${props.sessionId}
-ORDER BY timestamp DESC
-LIMIT 1`
- const result = await api.queryHogQL(query, {
- scene: 'ReplayCaptureDiagnostics',
- productKey: 'session_replay',
- })
-
+ const result = await api.recordings.getCaptureDiagnostics(props.sessionId)
breakpoint()
-
- const row = result?.results?.[0]?.[0]
- if (!row) {
- return null
- }
- return typeof row === 'string' ? JSON.parse(row) : row
+ return result.properties ?? null
},
},
})),
diff --git a/posthog/session_recordings/queries/session_replay_events.py b/posthog/session_recordings/queries/session_replay_events.py
index 0e0d8e3a7a6f..11efaa3d8b63 100644
--- a/posthog/session_recordings/queries/session_replay_events.py
+++ b/posthog/session_recordings/queries/session_replay_events.py
@@ -1,3 +1,5 @@
+import re
+import json
from datetime import datetime, timedelta
from typing import Optional
@@ -23,6 +25,123 @@ DEFAULT_EVENT_FIELDS = [
"properties.$event_type",
]
+_UUIDV7_SESSION_ID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$", re.IGNORECASE)
+
+# The session id's embedded timestamp comes from the client clock while
+# min_first_timestamp is ingestion-derived, so allow generous slack either side.
+SESSION_ID_CLOCK_SKEW_SLACK = timedelta(days=3)
+
+_EARLIEST_PLAUSIBLE_SESSION_START = datetime(2020, 1, 1, tzinfo=pytz.UTC)
+
+
+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.
+
+ The session_replay_events sort key is (toDate(min_first_timestamp), team_id, session_id),
+ so a session lookup without a date lower bound walks index granules across the table's
+ entire retained date range. SDK session ids are UUIDv7 — their first 48 bits encode the
+ session start in ms — which lets us bound the scan without callers having to know the
+ recording's start time. Returns None (no bound, today's behavior) for ids that don't
+ parse or whose embedded timestamp is implausible (badly skewed client clocks exist).
+ """
+ if not _UUIDV7_SESSION_ID.match(session_id):
+ return None
+ embedded_ms = int(session_id.replace("-", "")[:12], 16)
+ now = now or datetime.now(pytz.UTC)
+ # ms-level precheck: fromtimestamp raises OverflowError/ValueError on
+ # far-future values (48 bits reach the year 10889).
+ if embedded_ms > (now + timedelta(days=1)).timestamp() * 1000:
+ return None
+ embedded_start = datetime.fromtimestamp(embedded_ms / 1000, tz=pytz.UTC)
+ if embedded_start < _EARLIEST_PLAUSIBLE_SESSION_START:
+ return None
+ return embedded_start - SESSION_ID_CLOCK_SKEW_SLACK
+
+
+# Wide window for capture diagnostics when the session id carries no usable
+# timestamp (or the bounded window missed): covers the longest replay retention
+# plan plus slack, so any recording that can still be played can be diagnosed.
+CAPTURE_DIAGNOSTICS_FALLBACK_LOOKBACK = timedelta(days=370)
+
+
+# The capture diagnostics panel only interprets recording-diagnostic properties
+# (see frontend replayCaptureDiagnostics.ts); the response is filtered to these
+# so replay viewers don't receive arbitrary event properties through this endpoint.
+_DIAGNOSTIC_PROPERTY_PREFIX = "$sdk_debug_"
+_DIAGNOSTIC_PROPERTIES = frozenset(
+ {
+ "$has_recording",
+ "$recording_status",
+ "$replay_minimum_duration",
+ "$replay_sample_rate",
+ "$session_recording_remote_config",
+ "$session_recording_start_reason",
+ "$session_recording_url_trigger_activated_session",
+ "$session_recording_url_trigger_status",
+ }
+)
+
+
+def _filter_to_diagnostic_properties(properties: dict) -> dict:
+ return {
+ key: value
+ for key, value in properties.items()
+ if key in _DIAGNOSTIC_PROPERTIES or key.startswith(_DIAGNOSTIC_PROPERTY_PREFIX)
+ }
+
+
+def get_latest_session_event_properties(session_id: str, team: Team) -> Optional[dict]:
+ """The most recent event's recording-diagnostic properties for a session, for the capture diagnostics panel.
+
+ Bounded by a window derived from the UUIDv7 session id so the events sort key
+ can prune the scan; misses (or ids that don't parse) fall back to a
+ retention-wide window so a skewed client clock degrades to a slower lookup
+ rather than missing diagnostics. Deliberate trade-off: when a session has
+ events both inside and outside the bounded window, the in-window latest wins
+ without consulting the fallback.
+ """
+ lower_bound = uuidv7_session_lower_bound(session_id)
+ if lower_bound is not None:
+ # lower_bound is embedded_start - slack; sessions last at most a day,
+ # so embedded_start + 1d + slack closes the window symmetrically.
+ upper_bound = lower_bound + 2 * SESSION_ID_CLOCK_SKEW_SLACK + timedelta(days=1)
+ properties = _latest_session_event_properties_between(session_id, team, lower_bound, upper_bound)
+ if properties is not None:
+ return properties
+ now = datetime.now(pytz.UTC)
+ return _latest_session_event_properties_between(
+ session_id, team, now - CAPTURE_DIAGNOSTICS_FALLBACK_LOOKBACK, now + timedelta(days=1)
+ )
+
+
+def _latest_session_event_properties_between(
+ session_id: str, team: Team, date_from: datetime, date_to: datetime
+) -> Optional[dict]:
+ from posthog.hogql_queries.hogql_query_runner import (
+ HogQLQueryRunner, # noqa: PLC0415 — breaks a circular import, matching this file's other HogQLQueryRunner imports
+ )
+
+ query = HogQLQuery(
+ query="""
+ SELECT properties
+ FROM events
+ WHERE $session_id = {session_id}
+ AND timestamp >= {date_from}
+ AND timestamp <= {date_to}
+ ORDER BY timestamp DESC
+ LIMIT 1
+ """,
+ values={"session_id": session_id, "date_from": date_from, "date_to": date_to},
+ )
+ tag_queries(product=Product.REPLAY, feature=Feature.QUERY, team_id=team.pk)
+ result = HogQLQueryRunner(team=team, query=query).calculate()
+ if not result.results:
+ return None
+ row = result.results[0][0]
+ if not row:
+ return None
+ return _filter_to_diagnostic_properties(json.loads(row) if isinstance(row, str) else row)
+
def seconds_until_midnight():
now = datetime.now(pytz.timezone("UTC"))
@@ -94,9 +213,18 @@ class SessionReplayEvents:
@staticmethod
def _check_exists(session_id: str, team: Team) -> bool:
- tag_queries(product=Product.REPLAY, feature=Feature.QUERY, team_id=team.pk)
- result = sync_execute(
- """
+ date_from = uuidv7_session_lower_bound(session_id)
+ if SessionReplayEvents._check_exists_from(session_id, team, date_from):
+ return True
+ # The bound is a perf optimization, not a correctness gate: a clock
+ # skewed past the slack would make a real recording un-findable, so
+ # fall back to the unbounded scan before reporting not-found.
+ return date_from is not None and SessionReplayEvents._check_exists_from(session_id, team, None)
+
+ @staticmethod
+ def _check_exists_from(session_id: str, team: Team, date_from: Optional[datetime]) -> bool:
+ optional_lower_bound_clause = "AND min_first_timestamp >= %(date_from)s" if date_from else ""
+ query = f"""
SELECT
count(),
min(min_first_timestamp) as start_time,
@@ -108,19 +236,24 @@ class SessionReplayEvents:
team_id = %(team_id)s
AND session_id = %(session_id)s
AND min_first_timestamp <= %(python_now)s
+ {optional_lower_bound_clause}
GROUP BY
session_id
HAVING
expiry_time >= %(python_now)s
AND max(is_deleted) = 0
- """,
+ """
+ tag_queries(product=Product.REPLAY, feature=Feature.QUERY, team_id=team.pk)
+ result = sync_execute(
+ query,
{
"team_id": team.pk,
"session_id": session_id,
+ "date_from": date_from,
"python_now": datetime.now(pytz.timezone("UTC")),
},
)
- return result and result[0][0] > 0
+ return bool(result and result[0][0] > 0)
def sessions_found_with_timestamps(
self, session_ids: list[str], team: Team
@@ -161,11 +294,33 @@ class SessionReplayEvents:
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"))
+ # Only bound the scan when every id parses — a single unparseable id must
+ # still be findable anywhere in the retained range.
+ lower_bounds = [uuidv7_session_lower_bound(session_id, now) for session_id in session_ids]
+ parsed_bounds = [bound for bound in lower_bounds if bound is not None]
+ date_from = min(parsed_bounds) if parsed_bounds and len(parsed_bounds) == len(lower_bounds) else None
+
+ sessions_found = SessionReplayEvents._find_with_timestamps_from(session_ids, team, now, date_from)
+ if date_from is not None:
+ # 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}
+ 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)
+ return sessions_found
+
+ @staticmethod
+ def _find_with_timestamps_from(
+ session_ids: list[str], team: Team, now: datetime, date_from: Optional[datetime]
+ ) -> list[tuple[str, datetime, datetime, datetime]]:
from posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner
- now = datetime.now(pytz.timezone("UTC"))
+ optional_lower_bound_clause = "AND min_first_timestamp >= {date_from}" if date_from else ""
query = HogQLQuery(
- query="""
+ query=f"""
SELECT
session_id,
min(min_first_timestamp) as min_timestamp,
@@ -175,17 +330,19 @@ class SessionReplayEvents:
FROM
raw_session_replay_events
WHERE
- session_id IN {session_ids}
- AND min_first_timestamp <= {now}
+ session_id IN {{session_ids}}
+ AND min_first_timestamp <= {{now}}
+ {optional_lower_bound_clause}
GROUP BY
session_id
HAVING
- expiry_time >= {now}
+ expiry_time >= {{now}}
AND max(is_deleted) = 0
""",
values={
"session_ids": session_ids,
"now": now,
+ "date_from": date_from,
},
)
tag_queries(product=Product.REPLAY, feature=Feature.QUERY, team_id=team.pk)
@@ -317,14 +474,33 @@ class SessionReplayEvents:
team: Team,
recording_start_time: Optional[datetime] = None,
) -> Optional[RecordingMetadata]:
- query = self.get_metadata_query(recording_start_time)
+ if recording_start_time is not None:
+ return self._get_metadata_from(session_id, team, recording_start_time)
+
+ # Most callers don't know the recording's start time (it is only persisted
+ # for pinned recordings); derive a lower bound from the session id instead.
+ # Unlike a real start time it carries clock-skew slack, so on a miss fall
+ # back to the unbounded scan rather than reporting not-found.
+ derived_lower_bound = uuidv7_session_lower_bound(session_id)
+ metadata = self._get_metadata_from(session_id, team, derived_lower_bound)
+ if metadata is None and derived_lower_bound is not None:
+ metadata = self._get_metadata_from(session_id, team, None)
+ return metadata
+
+ def _get_metadata_from(
+ self,
+ session_id: str,
+ team: Team,
+ lower_bound: Optional[datetime],
+ ) -> Optional[RecordingMetadata]:
+ query = self.get_metadata_query(lower_bound)
tag_queries(product=Product.REPLAY, feature=Feature.QUERY, team_id=team.pk)
replay_response: list[tuple] = sync_execute(
query,
{
"team_id": team.pk,
"session_id": session_id,
- "recording_start_time": recording_start_time,
+ "recording_start_time": lower_bound,
"python_now": datetime.now(pytz.timezone("UTC")),
},
)
diff --git a/posthog/session_recordings/queries/test/test_session_replay_events.py b/posthog/session_recordings/queries/test/test_session_replay_events.py
index 7b42c04469a1..f5dac43fb397 100644
--- a/posthog/session_recordings/queries/test/test_session_replay_events.py
+++ b/posthog/session_recordings/queries/test/test_session_replay_events.py
@@ -1,11 +1,17 @@
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event
from django.utils.timezone import now
from dateutil.relativedelta import relativedelta
+from parameterized import parameterized
from posthog.models import Team
-from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents
+from posthog.session_recordings.queries.session_replay_events import (
+ SESSION_ID_CLOCK_SKEW_SLACK,
+ SessionReplayEvents,
+ get_latest_session_event_properties,
+ uuidv7_session_lower_bound,
+)
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
@@ -321,3 +327,171 @@ class SessionReplayEventsQueries(ClickhouseTestMixin, APIBaseTest):
assert sessions == set()
assert min_ts is None
assert max_ts is None
+
+
+def _uuidv7_session_id_for(ts) -> str:
+ ms = int(ts.timestamp() * 1000)
+ hex12 = f"{ms:012x}"
+ return f"{hex12[:8]}-{hex12[8:12]}-7000-8000-000000000000"
+
+
+class TestUuidv7SessionLowerBound(APIBaseTest):
+ @parameterized.expand(
+ [
+ ("uuidv4_id", "7c10ab30-3a9c-4b75-89ce-09e51c826989", None),
+ ("non_uuid_id", "my-custom-session", None),
+ ("implausibly_old_embedded_timestamp", "0000ffff-ffff-7000-8000-000000000000", None),
+ ("far_future_embedded_timestamp", "ffffffff-ffff-7000-8000-000000000000", None),
+ ]
+ )
+ def test_returns_no_bound(self, _name: str, session_id: str, expected: None) -> None:
+ assert uuidv7_session_lower_bound(session_id) is expected
+
+ def test_derives_bound_from_embedded_timestamp(self) -> None:
+ session_start = (now() - relativedelta(days=1)).replace(microsecond=0)
+ bound = uuidv7_session_lower_bound(_uuidv7_session_id_for(session_start))
+ assert bound == session_start - SESSION_ID_CLOCK_SKEW_SLACK
+
+
+class TestSessionLookupUsesUuidv7Bound(ClickhouseTestMixin, APIBaseTest):
+ def test_finds_session_with_uuidv7_id_seeded_at_its_embedded_time(self) -> None:
+ session_start = (now() - relativedelta(days=1)).replace(microsecond=0)
+ session_id = _uuidv7_session_id_for(session_start)
+ produce_replay_summary(
+ session_id=session_id,
+ team_id=self.team.pk,
+ first_timestamp=session_start,
+ last_timestamp=session_start,
+ distinct_id="u1",
+ retention_period_days=30,
+ )
+
+ assert SessionReplayEvents().exists(session_id, self.team) is True
+ assert SessionReplayEvents().get_metadata(session_id, self.team) is not None
+
+ def test_finds_session_seeded_far_before_its_ids_embedded_time_via_unbounded_fallback(self) -> None:
+ # A recording whose events predate the session id's embedded timestamp by more
+ # than the clock-skew slack misses the derived scan window; the lookup retries
+ # unbounded so the recording is still found, just on the slower path.
+ session_start = (now() - relativedelta(days=1)).replace(microsecond=0)
+ session_id = _uuidv7_session_id_for(session_start)
+ produce_replay_summary(
+ session_id=session_id,
+ team_id=self.team.pk,
+ first_timestamp=session_start - relativedelta(days=10),
+ last_timestamp=session_start - relativedelta(days=10),
+ distinct_id="u1",
+ retention_period_days=30,
+ )
+
+ assert SessionReplayEvents().exists(session_id, self.team)
+ assert SessionReplayEvents().get_metadata(session_id, self.team) is not None
+
+ def test_batch_with_mixed_id_formats_finds_all_sessions(self) -> None:
+ # One uuidv7 id and one custom id in the same batch: the unparseable id
+ # disables the bound for the whole batch, so both stay findable.
+ session_start = (now() - relativedelta(days=1)).replace(microsecond=0)
+ uuid_id = _uuidv7_session_id_for(session_start)
+ custom_id = "my-custom-session-id"
+ for session_id in (uuid_id, custom_id):
+ produce_replay_summary(
+ session_id=session_id,
+ team_id=self.team.pk,
+ first_timestamp=session_start,
+ last_timestamp=session_start,
+ distinct_id="u1",
+ retention_period_days=30,
+ )
+
+ found = SessionReplayEvents()._find_with_timestamps([uuid_id, custom_id], self.team)
+
+ assert {session_id for session_id, _, _, _ in found} == {uuid_id, custom_id}
+
+
+class TestGetLatestSessionEventProperties(ClickhouseTestMixin, APIBaseTest):
+ def _seed_event(self, session_id: str, timestamp, marker: str) -> None:
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="d1",
+ timestamp=timestamp,
+ properties={"$session_id": session_id, "$recording_status": marker},
+ )
+
+ @parameterized.expand(
+ [
+ ("event_within_uuidv7_window", True, relativedelta(minutes=0), "bounded"),
+ ("event_outside_uuidv7_window_via_fallback", True, relativedelta(days=10), "fallback"),
+ ("non_uuid_session_id_via_fallback", False, relativedelta(minutes=0), "custom"),
+ ]
+ )
+ def test_finds_event(self, _name: str, uuidv7_id: bool, event_age_before_start, marker: str) -> None:
+ session_start = (now() - relativedelta(minutes=10)).replace(microsecond=0)
+ session_id = _uuidv7_session_id_for(session_start) if uuidv7_id else "my-custom-session-id"
+ self._seed_event(session_id, session_start - event_age_before_start, marker)
+
+ properties = get_latest_session_event_properties(session_id, self.team)
+
+ assert properties is not None
+ assert properties["$recording_status"] == marker
+
+ def test_filters_response_to_diagnostic_properties(self) -> None:
+ session_start = (now() - relativedelta(minutes=10)).replace(microsecond=0)
+ session_id = _uuidv7_session_id_for(session_start)
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id="d1",
+ timestamp=session_start,
+ properties={
+ "$session_id": session_id,
+ "$recording_status": "disabled",
+ "$sdk_debug_replay_internal_buffer_length": 0,
+ "$current_url": "https://example.com/private-path",
+ "email": "[email protected]",
+ },
+ )
+
+ properties = get_latest_session_event_properties(session_id, self.team)
+
+ assert properties == {
+ "$recording_status": "disabled",
+ "$sdk_debug_replay_internal_buffer_length": 0,
+ }
+
+ def test_returns_none_when_session_has_no_events(self) -> None:
+ session_id = _uuidv7_session_id_for(now() - relativedelta(minutes=10))
+
+ assert get_latest_session_event_properties(session_id, self.team) is None
+
+ def test_does_not_leak_another_teams_session(self) -> None:
+ session_start = (now() - relativedelta(minutes=10)).replace(microsecond=0)
+ session_id = _uuidv7_session_id_for(session_start)
+ other_team = Team.objects.create(organization=self.organization, name="other team")
+ _create_event(
+ team=other_team,
+ event="$pageview",
+ distinct_id="d1",
+ timestamp=session_start,
+ properties={"$session_id": session_id, "$recording_status": "secret"},
+ )
+
+ assert get_latest_session_event_properties(session_id, self.team) is None
+
+ response = self.client.get(
+ f"/api/environments/{self.team.id}/session_recordings/{session_id}/capture_diagnostics"
+ )
+ assert response.status_code == 200
+ assert response.json()["properties"] is None
+
+ def test_capture_diagnostics_endpoint_returns_properties(self) -> None:
+ session_start = (now() - relativedelta(minutes=10)).replace(microsecond=0)
+ session_id = _uuidv7_session_id_for(session_start)
+ self._seed_event(session_id, session_start, "endpoint")
+
+ response = self.client.get(
+ f"/api/environments/{self.team.id}/session_recordings/{session_id}/capture_diagnostics"
+ )
+
+ assert response.status_code == 200
+ assert response.json()["properties"]["$recording_status"] == "endpoint"
diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.py
index 6d6788e31e3a..4b3c184398bc 100644
--- a/posthog/session_recordings/session_recording_api.py
+++ b/posthog/session_recordings/session_recording_api.py
@@ -95,7 +95,10 @@ from posthog.session_recordings.ai_data.ai_regex_schema import AiRegexSchema
from posthog.session_recordings.models.session_recording import SessionRecording
from posthog.session_recordings.models.session_recording_event import SessionRecordingViewed
from posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingListFromQuery
-from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents
+from posthog.session_recordings.queries.session_replay_events import (
+ SessionReplayEvents,
+ get_latest_session_event_properties,
+)
from posthog.session_recordings.recordings import recording_s3_client
from posthog.session_recordings.recordings.errors import BlockFetchError, RecordingDeletedError
from posthog.session_recordings.recordings.recording_api_client import RecordingApiClient, recording_api_client
@@ -983,6 +986,14 @@ class SessionRecordingViewSet(
return JsonResponse({"viewed": recording.viewed, "other_viewers": len(recording.viewers or [])})
+ @extend_schema(exclude=True)
+ @action(methods=["GET"], detail=True, url_path="capture_diagnostics")
+ def capture_diagnostics(self, request: request.Request, *args: Any, **kwargs: Any) -> Response:
+ """Latest event properties for the recording's session, for the capture diagnostics panel."""
+ recording = self.get_object()
+ properties = get_latest_session_event_properties(str(recording.session_id), self.team)
+ return Response({"properties": properties})
+
# Returns metadata about the recording
def retrieve(self, request: request.Request, *args: Any, **kwargs: Any) -> Response:
tag_queries(product=Product.REPLAY, feature=Feature.QUERY)