: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): handle failed matching events loads in the player (#117541)
posthog[bot]c1d48caf6ac3
diff --git a/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.test.ts b/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.test.tsindex f4d5131af5f1..f023d4d6a981 100644--- a/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.test.ts+++ b/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.test.ts@@ -1,5 +1,6 @@import { expectLogic } from 'kea-test-utils'import { HttpResponse } from 'msw'+import posthog from 'posthog-js'import { RecordingSnapshot } from '@posthog/replay-shared'@@ -416,6 +417,41 @@ describe('playerInspectorLogic', () => {playerLogic.unmount()})+ it.each([+ [503, false],+ [500, true],+ ])('clears highlights when a reload fails with %s (reported: %s)', async (failureStatus, reported) => {+ let status = 200+ useMocks({+ get: {+ '/api/environments/:team_id/session_recordings/matching_events': () =>+ status === 200+ ? [200, { results: [{ uuid: 'matching-event', timestamp: '2025-01-01T00:00:10.000Z' }] }]+ : [status, { detail: 'A server error occurred.' }],+ },+ })+ const captureException = jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined)++ const { playerLogic, matchingLogic } = mountLogics({+ sessionRecordingId: '1',+ playerKey: `failed-reload-${failureStatus}`,+ matchingEventsMatchType: { matchType: 'backend' as const, filters: DEFAULT_RECORDING_FILTERS },+ })+ await expectLogic(matchingLogic).toDispatchActions(['loadMatchingEventsSuccess'])+ expect(matchingLogic.values.matchingEvents).toHaveLength(1)++ status = failureStatus+ matchingLogic.actions.loadMatchingEvents()+ await expectLogic(matchingLogic)+ .toDispatchActions(['loadMatchingEventsSuccess'])+ .toMatchValues({ matchingEvents: [], matchingEventsSettled: true })+ expect(captureException).toHaveBeenCalledTimes(reported ? 1 : 0)++ captureException.mockRestore()+ matchingLogic.unmount()+ playerLogic.unmount()+ })+it('does not seek when the earliest match falls after the recording ends', async () => {// The matching-events query has slack past the recording window; seeking there would// pin the player to its final frame and trigger end-reached.diff --git a/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.ts b/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.tsindex cec404a49968..5c23db5eec98 100644--- a/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.ts+++ b/frontend/src/scenes/session-recordings/player/inspector/playerInspectorLogic.ts@@ -15,6 +15,7 @@ import {selectors,} from 'kea'import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'import {EventType as RRWebEventType,customEvent,@@ -24,6 +25,7 @@ import {} from 'posthog-js/rrweb-types'import api from 'lib/api'+import { shouldReportApiFailure } from 'lib/api-error'import { getCommentText } from 'lib/components/Comments/commentUtils'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { Dayjs, dayjs } from 'lib/dayjs'@@ -987,12 +989,24 @@ export const playerInspectorLogic = kea<playerInspectorLogicType>([session_ids: [props.sessionRecordingId],}- const response = await api.recordings.getMatchingEvents(toParams(params))+ let results: MatchedRecordingEvent[] = []+ let failure: unknown = null+ try {+ // nosemgrep: prefer-codegen-api-namespaced-replay+ results = (await api.recordings.getMatchingEvents(toParams(params))).results+ } catch (error) {+ // Highlights are optional, so the recording plays on without them.+ // Also clear the previous filters' highlights instead of keeping them.+ failure = error+ }// kea-loaders still dispatches success for a superseded call. Drop this response// when a newer load started while it was in flight, so that it cannot overwrite// the newer events or settle the skip on the previous filters' events.breakpoint()- return response.results+ if (failure && shouldReportApiFailure(failure)) {+ posthog.captureException(failure)+ }+ return results},},],diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.pyindex e1e440062db4..7476e0c52f44 100644--- a/posthog/session_recordings/session_recording_api.py+++ b/posthog/session_recordings/session_recording_api.py@@ -70,7 +70,7 @@ from posthog.auth import ()from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.dataclasses import frozen-from posthog.errors import ExposedCHQueryError+from posthog.errors import CH_TRANSIENT_ERRORS, CHQueryErrorQueryWasCancelled, ExposedCHQueryErrorfrom posthog.event_usage import report_user_actionfrom posthog.exceptions import ClickHouseAtCapacityfrom posthog.exceptions_capture import capture_exception@@ -169,6 +169,17 @@ SESSION_RECORDING_THROTTLED = Counter(_OTEL_PLAYBACK = OtelInstrumentFactory("session-replay-playback")+# The matching events query only reads, so a retry is safe even when ClickHouse stopped it part way.+_MATCHING_EVENTS_RETRYABLE_ERRORS = (*CH_TRANSIENT_ERRORS, CHQueryErrorQueryWasCancelled)+# ABORTED has no dedicated error class. A node that shuts down mid-query raises it.+_CLICKHOUSE_ABORTED_ERROR_CODE = 236+++def _is_retryable_matching_events_error(error: Exception) -> bool:+ if isinstance(error, _MATCHING_EVENTS_RETRYABLE_ERRORS):+ return True+ return isinstance(error, ServerException) and error.code == _CLICKHOUSE_ABORTED_ERROR_CODE+def _count_session_recording_throttled(location: str, auth_type: str) -> None:SESSION_RECORDING_THROTTLED.labels(location=location, auth_type=auth_type).inc()@@ -1014,7 +1025,16 @@ class SessionRecordingViewSet("Must specify at least one event or action filter, or event properties filter",)- results, _, timings, _ = ReplayFiltersEventsSubQuery(query=query, team=self.team).get_event_ids_for_session()+ try:+ results, _, timings, _ = ReplayFiltersEventsSubQuery(+ query=query, team=self.team+ ).get_event_ids_for_session()+ except Exception as e:+ # A transient error that already carries a status (capacity 503, cluster memory 513) keeps it.+ if isinstance(e, exceptions.APIException) or not _is_retryable_matching_events_error(e):+ raise+ logger.warning("matching_events_clickhouse_retryable_error", error_type=type(e).__name__)+ raise ClickHouseAtCapacity() from eresponse = JsonResponse(data=MatchingEventsResponse(diff --git a/posthog/session_recordings/test/test_session_recordings.py b/posthog/session_recordings/test/test_session_recordings.pyindex 15973d6ef894..92651b5d6c19 100644--- a/posthog/session_recordings/test/test_session_recordings.py+++ b/posthog/session_recordings/test/test_session_recordings.py@@ -28,6 +28,7 @@ from posthog.schema import LogEntryPropertyFilter, RecordingsQueryfrom posthog.hogql.errors import QueryError+from posthog.errors import wrap_clickhouse_query_errorfrom posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceededfrom posthog.models import Organization, SessionRecording, Userfrom posthog.models.team import Team@@ -1175,6 +1176,30 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)assert response.status_code == status.HTTP_200_OKassert response.json() == {"results": []}+ @parameterized.expand(+ [+ ("aborted", 236, status.HTTP_503_SERVICE_UNAVAILABLE),+ ("query_was_cancelled", 394, status.HTTP_503_SERVICE_UNAVAILABLE),+ ("timeout_exceeded", 159, status.HTTP_504_GATEWAY_TIMEOUT),+ ("cluster_memory_limit", 241, 513),+ ]+ )+ def test_get_matching_events_clickhouse_failure_status(self, _name: str, code: int, expected_status: int) -> None:+ query_params = [+ f'session_ids=["{str(uuid7())}"]',+ 'events=[{"id": "$pageview", "type": "events", "order": 0, "name": "$pageview"}]',+ ]+ with patch(+ "posthog.session_recordings.session_recording_api.ReplayFiltersEventsSubQuery.get_event_ids_for_session",+ side_effect=wrap_clickhouse_query_error(ServerException("ClickHouse failed", code=code)),+ ):+ response = self.client.get(+ f"/api/projects/{self.team.id}/session_recordings/matching_events?{'&'.join(query_params)}"+ )+ assert response.status_code == expected_status+ if expected_status == status.HTTP_503_SERVICE_UNAVAILABLE:+ assert response.headers["Retry-After"].isdigit()+def test_get_matching_events_with_query(self) -> None:"""both sessions have a pageview, but only the specified session returns a single UUID for the pageview events"""base_time = (now() - relativedelta(days=1)).replace(microsecond=0)