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): show a recording as deleted the moment it is deleted (#128111)

Tue Haulund88f7e965cb27
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 2c24f00d5d94..2a773a3b49ec 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -345,6 +345,13 @@ export class RecordingDeletedError extends Error {
}
}
+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)
+ }
+ return e
+}
+
const CSRF_COOKIE_NAME = 'posthog_csrftoken'
export function getCookie(name: string): string | null {
@@ -4383,7 +4390,11 @@ const api = {
recordingId: SessionRecordingType['id'],
headers: Record<string, string> = {}
): Promise<SessionRecordingSnapshotResponse> {
- return await new ApiRequest().recording(recordingId).withAction('snapshots').get({ headers })
+ try {
+ return await new ApiRequest().recording(recordingId).withAction('snapshots').get({ headers })
+ } catch (e) {
+ throw asRecordingDeletedError(e)
+ }
},
async getSnapshots(
@@ -4399,10 +4410,7 @@ const api = {
.withQueryString(params)
.getResponse({ headers })
} catch (e) {
- if (e instanceof ApiError && e.status === 410 && e.data?.error === 'recording_deleted') {
- throw new RecordingDeletedError(e.data?.deleted_at ?? null, e.data?.deleted_by ?? null)
- }
- throw e
+ throw asRecordingDeletedError(e)
}
const contentBuffer = new Uint8Array(await response.arrayBuffer())
diff --git a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.test.ts b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.test.ts
index 2a6c230816b6..3934be2e73f2 100644
--- a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.test.ts
+++ b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.test.ts
@@ -63,6 +63,26 @@ describe('snapshotDataLogic', () => {
expect(logic.values.recordingDeletedBy).toBe(null)
})
+ it('marks the recording deleted when the sources listing returns 410, and a later block load keeps it so', async () => {
+ overrideSessionRecordingMocks({
+ getMocks: {
+ '/api/environments/:team_id/session_recordings/:id/snapshots': () => [
+ 410,
+ { error: 'recording_deleted', deleted_at: 1700000000, deleted_by: '[email protected]' },
+ ],
+ },
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.loadSnapshotSources()
+ })
+ .toDispatchActions(['loadSnapshotSourcesFailure'])
+ .toMatchValues({ isRecordingDeleted: true, recordingDeletedBy: '[email protected]' })
+
+ logic.actions.loadSnapshotsForSourceSuccess({ sources: [BLOB_SOURCE] })
+ expect(logic.values.isRecordingDeleted).toBe(true)
+ })
+
it('recordingDeletedAt is null when deleted_at is not provided', () => {
const error = new RecordingDeletedError(null, null)
logic.actions.loadSnapshotsForSourceFailure('Recording deleted', error)
diff --git a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx
index 54693bc0a6f5..a075bc396404 100644
--- a/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx
+++ b/frontend/src/scenes/session-recordings/player/snapshotDataLogic.tsx
@@ -62,11 +62,13 @@ export interface snapshotDataLogicValues {
pollingInterval: number
recordingDeletedAt: number | null
recordingDeletedBy: string | null
+ recordingDeletedError: RecordingDeletedError | null
replayProxyToken: string | null
seekTarget: SeekTarget | null
snapshotLoadError: Error | null
snapshotLoadErrorKind: SnapshotLoadErrorKind | null
snapshotSources: SessionRecordingSnapshotSource[] | null
+ snapshotSourcesLoadError: Error | null
snapshotSourcesLoading: boolean
snapshotStore: SnapshotStore
snapshotsForSource: SessionRecordingSnapshotSourceResponse | null
@@ -227,9 +229,13 @@ export interface snapshotDataLogicMeta {
) => number
snapshotStore: (storeVersion: number) => SnapshotStore
sourceLoadingStates: (storeVersion: number) => SourceLoadingState[]
- isRecordingDeleted: (snapshotLoadError: Error | null) => boolean
- recordingDeletedAt: (snapshotLoadError: Error | null) => number | null
- recordingDeletedBy: (snapshotLoadError: Error | null) => string | null
+ recordingDeletedError: (
+ snapshotSourcesLoadError: Error | null,
+ snapshotLoadError: Error | null
+ ) => RecordingDeletedError | null
+ isRecordingDeleted: (recordingDeletedError: RecordingDeletedError | null) => boolean
+ recordingDeletedAt: (recordingDeletedError: RecordingDeletedError | null) => number | null
+ recordingDeletedBy: (recordingDeletedError: RecordingDeletedError | null) => string | null
isSnapshotUnauthorized: (snapshotLoadError: Error | null) => boolean
snapshotLoadErrorKind: (snapshotLoadError: Error | null) => SnapshotLoadErrorKind | null
}
@@ -338,6 +344,14 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([
loadSnapshotsForSourceFailure: (_, { errorObject }) => errorObject ?? null,
},
],
+ // Kept apart from snapshotLoadError, so a later block load cannot clear a deletion the listing reported.
+ snapshotSourcesLoadError: [
+ null as Error | null,
+ {
+ loadSnapshotSourcesSuccess: () => null,
+ loadSnapshotSourcesFailure: (_, { errorObject }) => errorObject ?? null,
+ },
+ ],
})),
loaders(({ values, props, cache, actions }) => ({
snapshotSources: [
@@ -641,7 +655,7 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([
},
loadNextSnapshotSource: async (_, breakpoint) => {
- if (!cache.playerActive) {
+ if (!cache.playerActive || values.isRecordingDeleted) {
return
}
if (values.snapshotsForSourceLoading) {
@@ -735,31 +749,31 @@ export const snapshotDataLogic = kea<snapshotDataLogicType>([
},
],
- isRecordingDeleted: [
- (s) => [s.snapshotLoadError],
- (snapshotLoadError: Error | null): boolean => {
- return snapshotLoadError instanceof RecordingDeletedError
+ recordingDeletedError: [
+ (s) => [s.snapshotSourcesLoadError, s.snapshotLoadError],
+ (sourcesError: Error | null, blocksError: Error | null): RecordingDeletedError | null => {
+ if (sourcesError instanceof RecordingDeletedError) {
+ return sourcesError
+ }
+ return blocksError instanceof RecordingDeletedError ? blocksError : null
},
],
+ isRecordingDeleted: [
+ (s) => [s.recordingDeletedError],
+ (recordingDeletedError: RecordingDeletedError | null): boolean => recordingDeletedError !== null,
+ ],
+
recordingDeletedAt: [
- (s) => [s.snapshotLoadError],
- (snapshotLoadError: Error | null): number | null => {
- if (snapshotLoadError instanceof RecordingDeletedError) {
- return snapshotLoadError.deletedAt
- }
- return null
- },
+ (s) => [s.recordingDeletedError],
+ (recordingDeletedError: RecordingDeletedError | null): number | null =>
+ recordingDeletedError?.deletedAt ?? null,
],
recordingDeletedBy: [
- (s) => [s.snapshotLoadError],
- (snapshotLoadError: Error | null): string | null => {
- if (snapshotLoadError instanceof RecordingDeletedError) {
- return snapshotLoadError.deletedBy
- }
- return null
- },
+ (s) => [s.recordingDeletedError],
+ (recordingDeletedError: RecordingDeletedError | null): string | null =>
+ recordingDeletedError?.deletedBy ?? null,
],
// A missing session doesn't resolve by retrying, so a source failing this way should
diff --git a/posthog/session_recordings/recordings/recording_api_client.py b/posthog/session_recordings/recordings/recording_api_client.py
index 74be81087aff..1059caeefb1a 100644
--- a/posthog/session_recordings/recordings/recording_api_client.py
+++ b/posthog/session_recordings/recordings/recording_api_client.py
@@ -20,6 +20,19 @@ from posthog.session_recordings.recordings.recording_api_jwt import (
logger = structlog.get_logger(__name__)
+async def _recording_deleted_error(response: aiohttp.ClientResponse) -> RecordingDeletedError:
+ # A 410 means deleted whatever its body says, so a body that is not JSON must not hide the deletion.
+ try:
+ data = await response.json(content_type=None)
+ except ValueError:
+ data = {}
+ if not isinstance(data, dict):
+ data = {}
+ return RecordingDeletedError(
+ "Recording has been deleted", deleted_at=data.get("deleted_at"), deleted_by=data.get("deleted_by")
+ )
+
+
class RecordingApiClient:
"""
Async client for fetching recording blocks via the Recording API.
@@ -47,19 +60,15 @@ class RecordingApiClient:
if response.status == 404:
raise BlockFetchError("Block not found")
if response.status == 410:
- data = await response.json()
- deleted_at = data.get("deleted_at")
- deleted_by = data.get("deleted_by")
+ error = await _recording_deleted_error(response)
logger.info(
"recording_api_client.recording_deleted",
session_id=session_id,
team_id=team_id,
- deleted_at=deleted_at,
- deleted_by=deleted_by,
- )
- raise RecordingDeletedError(
- "Recording has been deleted", deleted_at=deleted_at, deleted_by=deleted_by
+ deleted_at=error.deleted_at,
+ deleted_by=error.deleted_by,
)
+ raise error
response.raise_for_status()
return await response.read()
except (RecordingDeletedError, BlockFetchError):
@@ -82,6 +91,8 @@ class RecordingApiClient:
async with self.session.get(url, headers=recording_api_auth_headers(team_id, "read")) as response:
if response.status == 404:
return []
+ if response.status == 410:
+ raise await _recording_deleted_error(response)
response.raise_for_status()
data = await response.json()
return data.get("blocks", [])
@@ -110,10 +121,7 @@ class RecordingApiClient:
}
async with self.session.post(url, json=body, headers=recording_api_auth_headers(team_id, "write")) as response:
if response.status == 410:
- data = await response.json()
- raise RecordingDeletedError(
- "Recording has been deleted", deleted_at=data.get("deleted_at"), deleted_by=data.get("deleted_by")
- )
+ raise await _recording_deleted_error(response)
response.raise_for_status()
data = await response.json()
return [base64.b64decode(block) for block in data["blocks"]]
diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.py
index 96f77aae8af0..f43107abeec4 100644
--- a/posthog/session_recordings/session_recording_api.py
+++ b/posthog/session_recordings/session_recording_api.py
@@ -1746,7 +1746,8 @@ class SessionRecordingViewSet(
with _OTEL_PLAYBACK.timed_histogram_twin(GATHER_RECORDING_SOURCES_HISTOGRAM, {"blob_version": "v2"}):
with timer("list_blocks__gather_session_recording_sources"):
- blocks = list_blocks(recording)
+ # Uncached, so a recording deleted a moment ago fails here before the player asks for any block.
+ blocks = list_blocks(recording, use_cache=False)
for i, block in enumerate(blocks):
sources.append(
diff --git a/posthog/session_recordings/session_recording_v2_service.py b/posthog/session_recordings/session_recording_v2_service.py
index 5cee1312130c..57e2c70ed943 100644
--- a/posthog/session_recordings/session_recording_v2_service.py
+++ b/posthog/session_recordings/session_recording_v2_service.py
@@ -8,7 +8,7 @@ from asgiref.sync import async_to_sync
from prometheus_client import Counter
from posthog.session_recordings.models.session_recording import SessionRecording
-from posthog.session_recordings.recordings.errors import RecordingApiConfigurationError
+from posthog.session_recordings.recordings.errors import RecordingApiConfigurationError, RecordingDeletedError
from posthog.session_recordings.recordings.recording_api_client import recording_api_client
logger = structlog.get_logger(__name__)
@@ -81,44 +81,28 @@ def _cache_blocks(cache_key: str | None, blocks: list[RecordingBlock]) -> None:
cache.set(cache_key, blocks, timeout=FIVE_SECONDS)
-def list_blocks(recording: SessionRecording) -> list[RecordingBlock]:
+def list_blocks(recording: SessionRecording, use_cache: bool = True) -> list[RecordingBlock]:
"""
Returns a list of recording blocks fetched from the recording-api.
Results are cached to avoid excessive calls.
"""
- cache_key, cached_blocks = _get_cached_blocks(recording)
- if cached_blocks is not None:
- return cached_blocks
+ return async_to_sync(list_blocks_async)(recording, use_cache=use_cache)
- try:
- blocks = async_to_sync(fetch_blocks_from_recording_api)(recording.session_id, recording.team_id)
- except RecordingApiConfigurationError:
- # An empty listing is how a caller learns a recording has no blocks. A missing setting means no
- # call was made at all, and no retry will change that, so it must not be reported as no blocks.
- raise
- except Exception:
- logger.exception(
- "recording_api_list_blocks_failed",
- session_id=recording.session_id,
- team_id=recording.team_id,
- )
- return []
-
- _cache_blocks(cache_key, blocks)
- return blocks
-
-async def list_blocks_async(recording: SessionRecording) -> list[RecordingBlock]:
+async def list_blocks_async(recording: SessionRecording, use_cache: bool = True) -> list[RecordingBlock]:
"""
Async version of list_blocks, safe to call from within a running event loop.
+ Pass use_cache=False where a deletion must show at once: the recording-api reports it, a cached listing does not.
"""
- cache_key, cached_blocks = _get_cached_blocks(recording)
+ cache_key, cached_blocks = _get_cached_blocks(recording) if use_cache else (listing_cache_key(recording), None)
if cached_blocks is not None:
return cached_blocks
try:
blocks = await fetch_blocks_from_recording_api(recording.session_id, recording.team_id)
- except RecordingApiConfigurationError:
+ except (RecordingApiConfigurationError, RecordingDeletedError):
+ # An empty listing is how a caller learns a recording has no blocks. A missing setting means no
+ # call was made at all, and a deleted recording must say so before the player reaches cached blocks.
raise
except Exception:
logger.exception(
diff --git a/posthog/session_recordings/test/recordings/test_recording_api_client.py b/posthog/session_recordings/test/recordings/test_recording_api_client.py
index dbb0f7e3e183..3de3ff183a18 100644
--- a/posthog/session_recordings/test/recordings/test_recording_api_client.py
+++ b/posthog/session_recordings/test/recordings/test_recording_api_client.py
@@ -128,24 +128,31 @@ class TestFetchBlock:
)
@pytest.mark.asyncio
- @pytest.mark.parametrize("deleted_at", [1700000000, None])
- async def test_410_raises_recording_deleted_error(self, client, mock_session, deleted_at):
+ @pytest.mark.parametrize("call", ["fetch_block", "list_blocks"])
+ @pytest.mark.parametrize(
+ "body,deleted_at",
+ [
+ ({"error": "recording_deleted", "deleted_at": 1700000000}, 1700000000),
+ ({"error": "recording_deleted", "deleted_at": None}, None),
+ (ValueError("not JSON"), None),
+ ],
+ )
+ async def test_410_raises_recording_deleted_error(self, client, mock_session, call, body, deleted_at):
mock_response = AsyncMock()
mock_response.status = 410
- mock_response.json = AsyncMock(return_value={"error": "Recording has been deleted", "deleted_at": deleted_at})
+ mock_response.json = (
+ AsyncMock(side_effect=body) if isinstance(body, Exception) else AsyncMock(return_value=body)
+ )
mock_response.__aenter__ = AsyncMock(return_value=mock_response)
mock_response.__aexit__ = AsyncMock(return_value=None)
mock_session.get = MagicMock(return_value=mock_response)
with pytest.raises(RecordingDeletedError, match="Recording has been deleted") as exc_info:
- await client.fetch_block(
- "key",
- 0,
- 100,
- "session-123",
- 1,
- )
+ if call == "fetch_block":
+ await client.fetch_block("key", 0, 100, "session-123", 1)
+ else:
+ await client.list_blocks("session-123", 1)
assert exc_info.value.deleted_at == deleted_at
@pytest.mark.asyncio
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.py
index cdb8e691baf1..188f674b1414 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
@@ -14,7 +14,7 @@ from posthog.models.utils import generate_random_token_personal, hash_key_value,
from posthog.session_recordings.models.session_recording_event import SessionRecordingViewed
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
from posthog.session_recordings.recordings.errors import RecordingDeletedError
-from posthog.session_recordings.session_recording_v2_service import RecordingBlock
+from posthog.session_recordings.session_recording_v2_service import RecordingBlock, listing_cache_key
class TestSessionRecordingSnapshotsAPI(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest):
@@ -977,3 +977,40 @@ class TestSessionRecordingSnapshotsAPI(APIBaseTest, ClickhouseTestMixin, QueryMa
assert self.client.get(url).status_code == status.HTTP_200_OK
assert self.client.get(url).status_code == expected_status_over_quota
cache.clear()
+
+ @patch(
+ "posthog.session_recordings.session_recording_v2_service.fetch_blocks_from_recording_api",
+ new_callable=AsyncMock,
+ )
+ @patch(
+ "posthog.session_recordings.queries.session_replay_events.SessionReplayEvents.exists",
+ return_value=True,
+ )
+ @patch("posthog.session_recordings.session_recording_api.SessionRecording.get_or_build")
+ def test_sources_listing_reports_a_deletion_despite_a_cached_listing(
+ self,
+ mock_get_session_recording,
+ _mock_exists,
+ mock_fetch_blocks,
+ ):
+ session_id = str(uuid7())
+ recording = SessionRecording(session_id=session_id, team=self.team, deleted=False)
+ mock_get_session_recording.return_value = recording
+ cache.set(
+ listing_cache_key(recording),
+ [
+ RecordingBlock(
+ key="key0",
+ start_byte=0,
+ end_byte=100,
+ start_timestamp="2024-01-01T00:00:00Z",
+ end_timestamp="2024-01-01T00:01:00Z",
+ )
+ ],
+ )
+ mock_fetch_blocks.side_effect = RecordingDeletedError("Recording has been deleted", deleted_at=1700000000)
+
+ response = self.client.get(f"/api/projects/{self.team.pk}/session_recordings/{session_id}/snapshots/")
+
+ assert response.status_code == status.HTTP_410_GONE
+ assert response.json()["error"] == "recording_deleted"
diff --git a/posthog/session_recordings/test/test_session_recording_v2_service.py b/posthog/session_recordings/test/test_session_recording_v2_service.py
index 144958449140..9a6feea099f3 100644
--- a/posthog/session_recordings/test/test_session_recording_v2_service.py
+++ b/posthog/session_recordings/test/test_session_recording_v2_service.py
@@ -6,7 +6,7 @@ from asgiref.sync import async_to_sync
from parameterized import parameterized
from posthog.session_recordings.models.session_recording import SessionRecording
-from posthog.session_recordings.recordings.errors import RecordingApiConfigurationError
+from posthog.session_recordings.recordings.errors import RecordingApiConfigurationError, RecordingDeletedError
from posthog.session_recordings.session_recording_v2_service import (
FIVE_SECONDS,
RecordingBlock,
@@ -77,16 +77,30 @@ class TestSessionRecordingV2Service(TestCase):
assert blocks == []
- @parameterized.expand([("sync", False), ("async", True)])
+ @parameterized.expand(
+ [
+ (f"{error_name}_{mode}", use_async, error)
+ for mode, use_async in (("sync", False), ("async", True))
+ for error_name, error in (
+ ("missing_url", RecordingApiConfigurationError("RECORDING_API_URL is not configured")),
+ ("deleted", RecordingDeletedError("Recording has been deleted", deleted_at=1700000000)),
+ )
+ ]
+ )
+ @patch("posthog.session_recordings.session_recording_v2_service.cache")
@patch("posthog.session_recordings.session_recording_v2_service.fetch_blocks_from_recording_api")
- def test_missing_recording_api_url_is_not_reported_as_no_blocks(self, _name, use_async, mock_fetch):
- mock_fetch.side_effect = RecordingApiConfigurationError("RECORDING_API_URL is not configured")
+ def test_errors_that_are_not_an_empty_listing_propagate_uncached(
+ self, _name, use_async, error, mock_fetch, mock_cache
+ ):
+ mock_cache.get.return_value = None
+ mock_fetch.side_effect = error
- with self.assertRaises(RecordingApiConfigurationError):
+ with self.assertRaises(type(error)):
if use_async:
async_to_sync(list_blocks_async)(self.recording)
else:
list_blocks(self.recording)
+ mock_cache.set.assert_not_called()
@patch("posthog.session_recordings.session_recording_v2_service.fetch_blocks_from_recording_api")
def test_list_blocks_returns_empty_list_when_no_blocks(self, mock_fetch):
diff --git a/posthog/temporal/session_replay/copy_recording/activities.py b/posthog/temporal/session_replay/copy_recording/activities.py
index 396e3e378e0d..6deebcb9f14d 100644
--- a/posthog/temporal/session_replay/copy_recording/activities.py
+++ b/posthog/temporal/session_replay/copy_recording/activities.py
@@ -230,7 +230,10 @@ async def _copy_session_recording(input: CopySessionInput) -> CopySessionResult:
log.info("copy_recording.already_copied")
return CopySessionResult(session_id=input.session_id, status="already_copied")
- source_blocks = await fetch_blocks_from_recording_api(input.session_id, input.source_team_id)
+ try:
+ source_blocks = await fetch_blocks_from_recording_api(input.session_id, input.source_team_id)
+ except RecordingDeletedError as e:
+ raise ApplicationError("Recording was deleted", non_retryable=True) from e
if not source_blocks:
log.warning("copy_recording.source_not_found")
return CopySessionResult(session_id=input.session_id, status="not_found")
diff --git a/posthog/temporal/tests/session_replay/copy_recording/test_activities.py b/posthog/temporal/tests/session_replay/copy_recording/test_activities.py
index 63231ea94d18..fda7f4829c11 100644
--- a/posthog/temporal/tests/session_replay/copy_recording/test_activities.py
+++ b/posthog/temporal/tests/session_replay/copy_recording/test_activities.py
@@ -15,6 +15,7 @@ from temporalio.testing import ActivityEnvironment
from posthog.models import Organization, Team
from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
+from posthog.session_recordings.recordings.errors import RecordingDeletedError
from posthog.session_recordings.session_recording_v2_service import RecordingBlock
from posthog.temporal.session_replay.copy_recording.activities import copy_session_recording
from posthog.temporal.session_replay.copy_recording.types import CopySessionInput, CopySessionResult
@@ -64,7 +65,9 @@ class TestCopySessionRecording(ClickhouseTestMixin, APIBaseTest):
]
flush_persons_and_events()
- def _run(self, target_team_id: int | None = None) -> tuple[CopySessionResult, MagicMock, AsyncMock]:
+ def _run(
+ self, target_team_id: int | None = None, listing: AsyncMock | None = None
+ ) -> tuple[CopySessionResult, MagicMock, AsyncMock]:
client = MagicMock()
client.fetch_block = AsyncMock(side_effect=lambda key, *_: f"plain-{key[-20:]}".encode())
client.encrypt_blocks = AsyncMock(side_effect=lambda _s, _t, blocks, _r: [b"sealed:" + b for b in blocks])
@@ -73,7 +76,7 @@ class TestCopySessionRecording(ClickhouseTestMixin, APIBaseTest):
client_cm.__aexit__ = AsyncMock(return_value=None)
upload = AsyncMock()
with (
- patch(f"{ACTIVITIES}.fetch_blocks_from_recording_api", AsyncMock(return_value=self.blocks)),
+ patch(f"{ACTIVITIES}.fetch_blocks_from_recording_api", listing or AsyncMock(return_value=self.blocks)),
patch(f"{ACTIVITIES}.recording_api_client", return_value=client_cm),
patch(f"{ACTIVITIES}._upload", upload),
):
@@ -154,3 +157,10 @@ class TestCopySessionRecording(ClickhouseTestMixin, APIBaseTest):
assert error.exception.non_retryable
assert SessionReplayEvents().get_metadata("s1", other_team) is None
+
+ def test_refuses_a_deleted_source_without_retrying(self) -> None:
+ with self.assertRaises(ApplicationError) as error:
+ self._run(listing=AsyncMock(side_effect=RecordingDeletedError("Recording has been deleted")))
+
+ assert error.exception.non_retryable
+ assert SessionReplayEvents().get_metadata("s1", self.target_team) is None
diff --git a/products/replay_vision/backend/temporal/activities/fetch_session_network.py b/products/replay_vision/backend/temporal/activities/fetch_session_network.py
index d065d78a7c4c..b446be8ebb00 100644
--- a/products/replay_vision/backend/temporal/activities/fetch_session_network.py
+++ b/products/replay_vision/backend/temporal/activities/fetch_session_network.py
@@ -9,7 +9,7 @@ from temporalio import activity
from temporalio.exceptions import ApplicationError
from posthog.session_recordings.models.session_recording import SessionRecording
-from posthog.session_recordings.recordings.errors import RecordingApiConfigurationError
+from posthog.session_recordings.recordings.errors import RecordingApiConfigurationError, RecordingDeletedError
from posthog.session_recordings.recordings.recording_api_client import recording_api_client
from posthog.session_recordings.session_recording_v2_service import RecordingBlock, list_blocks_async
@@ -95,7 +95,11 @@ async def fetch_session_network_activity(inputs: FetchSessionNetworkInputs) -> N
async def _load_payload(team_id: int, session_id: str) -> SessionNetworkPayload:
recording = await sync_to_async(_build_recording)(team_id, session_id)
- blocks = await list_blocks_async(recording)
+ try:
+ blocks = await list_blocks_async(recording)
+ except RecordingDeletedError:
+ # A deleted recording has no network data to read, and retrying cannot bring it back.
+ return SessionNetworkPayload()
if not blocks:
return SessionNetworkPayload()
diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.py
index 0fd8ba5ac653..8905ee04875e 100644
--- a/products/replay_vision/backend/tests/test_temporal.py
+++ b/products/replay_vision/backend/tests/test_temporal.py
@@ -39,6 +39,7 @@ from posthog.models import Organization, Team
from posthog.models.user import User
from posthog.redis import get_async_client
from posthog.session_recordings.queries.session_replay_events import SessionEventsPage, SessionReplayEvents
+from posthog.session_recordings.recordings.errors import RecordingDeletedError
from posthog.session_recordings.session_recording_v2_service import RecordingBlock
from posthog.temporal.session_replay.rasterize_recording.activities.stuck_counter import (
BumpStuckCounterInput,
@@ -2624,6 +2625,19 @@ class TestFetchSessionNetworkActivity:
# A block bigger than the whole budget still gets read, on its own.
assert len(mod._next_batch([block(mod._MAX_BATCH_COMPRESSED_BYTES * 4)], 0)) == 1
+ @pytest.mark.asyncio
+ async def test_a_deleted_recording_reads_as_no_network_data(self) -> None:
+ from products.replay_vision.backend.temporal.activities import fetch_session_network as mod
+
+ with (
+ patch.object(mod, "list_blocks_async", AsyncMock(side_effect=RecordingDeletedError("deleted"))),
+ patch.object(mod, "_collect", AsyncMock()) as collect,
+ ):
+ payload = await mod._load_payload(team_id=1, session_id="sess-1")
+
+ assert collect.await_count == 0
+ assert payload == SessionNetworkPayload()
+
@pytest.mark.asyncio
async def test_a_listing_over_the_size_ceiling_is_refused(self) -> None:
from products.replay_vision.backend.temporal.activities import fetch_session_network as mod