: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
feat(replay): target direct blocks by team and name fallback causes (#129720)
Tue Haulundf278763a46be
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex b633e1e992ed..2b88ed62d652 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -343,6 +343,13 @@ export class RecordingDeletedError extends Error {}}+export class NotAReplayBlockError extends Error {+ constructor() {+ super('Block fetch returned something other than a block')+ this.name = 'NotAReplayBlockError'+ }+}+function asRecordingDeletedError(e: unknown): unknown {if (e instanceof ApiError && e.status === 410 && e.data?.error === 'recording_deleted') {return new RecordingDeletedError(e.data?.deleted_at ?? null, e.data?.deleted_by ?? null)@@ -4460,7 +4467,7 @@ const api = {}// Without a route to recording-api the app shell answers with HTML, which is not a block.if (!response.headers.get('Content-Type')?.startsWith('application/octet-stream')) {- throw new Error('Block fetch returned something other than a block')+ throw new NotAReplayBlockError()}return new Uint8Array(await response.arrayBuffer())} catch (e) {diff --git a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.test.ts b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.test.tsindex 150fdf26ebd9..d228beb645ee 100644--- a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.test.ts+++ b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.test.ts@@ -1,5 +1,6 @@import { expectLogic } from 'kea-test-utils'import { HttpResponse } from 'msw'+import posthog from 'posthog-js'import { EventType, IncrementalSource, NodeType, mutationData } from 'posthog-js/rrweb-types'import { chunkMutationSnapshot, MUTATION_CHUNK_SIZE } from '@posthog/replay-shared'@@ -178,27 +179,31 @@ describe('snapshotDataLogic', () => {}it.each([- ['reads the block from its url', 200, false, 'loadSnapshotsForSourceSuccess'],+ ['reads the block from its url', 200, false, 'loadSnapshotsForSourceSuccess', null],['falls back to the snapshots endpoint when the block fetch fails',500,true,'loadSnapshotsForSourceSuccess',+ 'http_error',],['falls back when the block route answers with the app shell','html',true,'loadSnapshotsForSourceSuccess',+ 'not_a_block',],- ['shows the recording as deleted on a 410', 410, false, 'loadSnapshotsForSourceFailure'],+ ['shows the recording as deleted on a 410', 410, false, 'loadSnapshotsForSourceFailure', null],['reports a rate limit instead of reading through the snapshots endpoint',429,false,'loadSnapshotsForSourceFailure',+ null,],- ] as const)('%s', async (_, blockStatus, expectsSnapshotsEndpoint, expectedAction) => {+ ] as const)('%s', async (_, blockStatus, expectsSnapshotsEndpoint, expectedAction, fallbackReason) => {+ const capture = jest.spyOn(posthog, 'capture')let snapshotsEndpointBlockReads = 0overrideSessionRecordingMocks({getMocks: {@@ -231,6 +236,13 @@ describe('snapshotDataLogic', () => {expect(snapshotsEndpointBlockReads > 0).toBe(expectsSnapshotsEndpoint)expect(logic.values.isRecordingDeleted).toBe(blockStatus === 410)+ const fallbackEvents = capture.mock.calls.filter(+ ([event]) => event === 'replay direct block fetch fell back'+ )+ expect(fallbackEvents.map(([, properties]) => properties?.reason)).toEqual(+ fallbackReason ? [fallbackReason] : []+ )+ capture.mockRestore()})})diff --git a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsxindex 1d0a643801c8..3dfa4f888ebe 100644--- a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx+++ b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx@@ -20,7 +20,7 @@ import posthog from 'posthog-js'import { keyForSource } from '@posthog/replay-shared'import { SnapshotSourceType, SnapshotStore, SourceLoadingState } from '@posthog/replay-shared'-import api, { ApiError, RecordingDeletedError } from 'lib/api'+import api, { ApiError, NotAReplayBlockError, RecordingDeletedError } from 'lib/api'import 'lib/dayjs'import { parseEncodedSnapshots } from 'scenes/session-recordings/player/snapshot-processing/process-all-snapshots'import { windowIdRegistryLogic } from 'scenes/session-recordings/player/windowIdRegistryLogic'@@ -252,6 +252,24 @@ export type snapshotDataLogicType = MakeLogicType<snapshotDataLogicMeta>+// A fixed set of causes, so the fallback event groups by why the direct read failed.+function directBlockFallbackReason(e: unknown): string {+ if (e instanceof ApiError) {+ return 'http_error'+ }+ if (e instanceof NotAReplayBlockError) {+ return 'not_a_block'+ }+ if (e instanceof DOMException && e.name === 'AbortError') {+ return 'timeout'+ }+ // fetch rejects with a TypeError when the request never got a response.+ if (e instanceof TypeError) {+ return 'network'+ }+ return 'unknown'+}+// Reads a batch straight from recording-api when the listing gave every block a url, so the browser caches each// block. Returns null to use the snapshots endpoint instead, which serves every recording.async function loadBlocksDirectly(@@ -286,7 +304,7 @@ async function loadBlocksDirectly(// Without this, a broken rollout looks healthy while every batch pays for a failed download.posthog.capture('replay direct block fetch fell back', {status: status ?? null,- reason: e instanceof Error ? e.name : 'unknown',+ reason: directBlockFallbackReason(e),block_count: urls.length,})return nulldiff --git a/posthog/session_recordings/recordings/replay_blocks_jwt.py b/posthog/session_recordings/recordings/replay_blocks_jwt.pyindex 81facc2bf957..5d4865d23a9b 100644--- a/posthog/session_recordings/recordings/replay_blocks_jwt.py+++ b/posthog/session_recordings/recordings/replay_blocks_jwt.py@@ -26,8 +26,11 @@ REPLAY_DIRECT_BLOCKS_FLAG = "replay-direct-blocks"def is_direct_blocks_enabled(team_id: int) -> bool:"""Gate for giving the player block urls. The player polls the listing for a live recording, so the check sendsno flag-called event."""- # All deployments share one flag project and team ids repeat across them, so conditions target a deployment by this.- person_properties = {"cloud_deployment": settings.CLOUD_DEPLOYMENT} if settings.CLOUD_DEPLOYMENT else {}+ # Team ids repeat across deployments, so a team condition also names the deployment. A condition on the distinct id+ # cannot be evaluated locally, so team_id is sent as a property for team targeting.+ person_properties: dict[str, str | int] = {"team_id": team_id}+ if settings.CLOUD_DEPLOYMENT:+ person_properties["cloud_deployment"] = settings.CLOUD_DEPLOYMENTtry:return bool(posthoganalytics.feature_enabled(diff --git a/posthog/session_recordings/test/test_session_recording_snapshots_api_blob_v2.py b/posthog/session_recordings/test/test_session_recording_snapshots_api_blob_v2.pyindex ea0aebab5807..aa09c6c33c10 100644--- a/posthog/session_recordings/test/test_session_recording_snapshots_api_blob_v2.py+++ b/posthog/session_recordings/test/test_session_recording_snapshots_api_blob_v2.py@@ -262,7 +262,7 @@ class TestSessionRecordingSnapshotsAPI(APIBaseTest, ClickhouseTestMixin, QueryMaassert urls == [None, None]assert body["block_token"] is Nonefor flag_call in mock_feature_enabled.call_args_list:- assert flag_call.kwargs["person_properties"] == {"cloud_deployment": "DEV"}+ assert flag_call.kwargs["person_properties"] == {"cloud_deployment": "DEV", "team_id": self.team.pk}@parameterized.expand([