: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(session-replay): delete replay vision data when a recording is deleted (#101306)
Tue Haulund73e580648a23
diff --git a/nodejs/src/session-replay/recording-api/recording-cleanup.integration.test.ts b/nodejs/src/session-replay/recording-api/recording-cleanup.integration.test.tsnew file mode 100644index 000000000000..f705011075b9--- /dev/null+++ b/nodejs/src/session-replay/recording-api/recording-cleanup.integration.test.ts@@ -0,0 +1,173 @@+import { randomUUID } from 'crypto'++import { defaultConfig } from '~/common/config/config'+import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'+import { createTestTeamFixture } from '~/tests/helpers/sql'++import { RecordingService } from './recording-service'+import { KeyStore, RecordingDecryptor } from './types'++// The unit tests assert the statement text against a mock, so a bad column, cast or CTE would pass+// them. These run the real SQL.+describe('recording cleanup (integration)', () => {+ let postgres: PostgresRouter+ let service: RecordingService+ let teamId: number+ let userId: number++ let scannerId: string+ let targetObservationId: string+ let otherObservationId: string+ let alertId: string++ beforeEach(async () => {+ scannerId = randomUUID()+ targetObservationId = randomUUID()+ otherObservationId = randomUUID()+ alertId = randomUUID()++ postgres = new PostgresRouter(defaultConfig)+ const fixture = await createTestTeamFixture(postgres)+ teamId = fixture.team.id+ userId = fixture.userId++ const keyStore = {+ deleteKey: jest+ .fn()+ .mockResolvedValue({ status: 'deleted', deletedAt: 1700000000, deletedBy: '[email protected]' }),+ } as unknown as KeyStore++ service = new RecordingService(+ {} as never,+ 'test-bucket',+ 'session_recordings',+ keyStore,+ {} as unknown as RecordingDecryptor,+ undefined,+ undefined,+ postgres,+ undefined+ )++ await postgres.query(+ PostgresUse.COMMON_WRITE,+ `INSERT INTO replay_vision_replayscanner+ (id, team_id, name, description, scanner_type, scanner_config, query, sampling_rate,+ sampling_mode, provider, model, enabled, emits_signals, scanner_version, last_swept_at,+ search_suggestions, admission_credits_since_refresh, created_at, updated_at)+ VALUES ($1, $2, 'cleanup-scanner', '', 'monitor', '{}'::jsonb, '{}'::jsonb, 1.0,+ 'comprehensive', 'google', 'gemini-3.8-flash', true, false, 1, now(),+ '{}'::jsonb, 0, now(), now())`,+ [scannerId, teamId],+ 'fixtureScanner'+ )++ for (const [observationId, sessionId] of [+ [targetObservationId, 'session-to-delete'],+ [otherObservationId, 'session-to-keep'],+ ]) {+ await postgres.query(+ PostgresUse.COMMON_WRITE,+ `INSERT INTO replay_vision_replayobservation+ (id, scanner_id, team_id, session_id, status, error_reason, workflow_id,+ scanner_snapshot, scanner_result, triggered_by, created_at, completed_at)+ VALUES ($1, $2, $3, $4, 'succeeded', '', '', '{}'::jsonb, '{}'::jsonb, 'schedule', now(), now())`,+ [observationId, scannerId, teamId, sessionId],+ 'fixtureObservation'+ )+ }++ await postgres.query(+ PostgresUse.COMMON_WRITE,+ `INSERT INTO replay_vision_replayobservationlabel+ (id, observation_id, team_id, is_correct, feedback, created_at, updated_at)+ VALUES ($1, $2, $3, true, '', now(), now())`,+ [randomUUID(), targetObservationId, teamId],+ 'fixtureLabel'+ )+ await postgres.query(+ PostgresUse.COMMON_WRITE,+ `INSERT INTO replay_vision_replayobservationview+ (id, observation_id, team_id, user_id, created_at)+ VALUES ($1, $2, $3, $4, now())`,+ [randomUUID(), targetObservationId, teamId, userId],+ 'fixtureView'+ )+ await postgres.query(+ PostgresUse.COMMON_WRITE,+ `INSERT INTO replay_vision_visionalertconfiguration+ (id, scanner_id, team_id, name, enabled, kind, selection, metric, direction,+ window_days, check_interval_minutes, state, consecutive_failures,+ evaluation_periods, datapoints_to_alarm, cooldown_minutes, created_at, updated_at)+ VALUES ($1, $2, $3, 'cleanup-alert', true, 'match', '{}'::jsonb, 'count', 'above',+ 1, 60, 'not_firing', 0, 1, 1, 0, now(), now())`,+ [alertId, scannerId, teamId],+ 'fixtureAlert'+ )+ await postgres.query(+ PostgresUse.COMMON_WRITE,+ `INSERT INTO replay_vision_visionalertmatch+ (id, alert_id, observation_id, team_id, created_at)+ VALUES ($1, $2, $3, $4, now())`,+ [randomUUID(), alertId, targetObservationId, teamId],+ 'fixtureMatch'+ )+ await postgres.query(+ PostgresUse.COMMON_WRITE,+ `INSERT INTO posthog_exportedasset+ (team_id, export_format, created_at, export_context, is_system, expires_after)+ VALUES ($1, 'video/mp4', now(), $2::jsonb, true, now() + interval '30 days')`,+ [teamId, JSON.stringify({ session_recording_id: 'session-to-delete' })],+ 'fixtureAsset'+ )+ })++ afterEach(async () => {+ await postgres.end()+ })++ const count = async (sql: string, params: unknown[]): Promise<number> => {+ const result = await postgres.query(PostgresUse.COMMON_READ, sql, params, 'assertion')+ return Number(result.rows[0].count)+ }++ it('removes the observation graph for the deleted recording and leaves the rest', async () => {+ await service.deleteRecordings(['session-to-delete'], teamId, '[email protected]')++ expect(+ await count(`SELECT count(*) FROM replay_vision_replayobservation WHERE id = $1`, [targetObservationId])+ ).toBe(0)+ expect(+ await count(`SELECT count(*) FROM replay_vision_replayobservationlabel WHERE observation_id = $1`, [+ targetObservationId,+ ])+ ).toBe(0)+ expect(+ await count(`SELECT count(*) FROM replay_vision_replayobservationview WHERE observation_id = $1`, [+ targetObservationId,+ ])+ ).toBe(0)+ expect(+ await count(`SELECT count(*) FROM replay_vision_visionalertmatch WHERE observation_id = $1`, [+ targetObservationId,+ ])+ ).toBe(0)++ // An observation of a different recording is untouched.+ expect(+ await count(`SELECT count(*) FROM replay_vision_replayobservation WHERE id = $1`, [otherObservationId])+ ).toBe(1)+ })++ it('expires the rendered video for the deleted recording', async () => {+ await service.deleteRecordings(['session-to-delete'], teamId, '[email protected]')++ expect(+ await count(+ `SELECT count(*) FROM posthog_exportedasset+ WHERE team_id = $1 AND expires_after > now()`,+ [teamId]+ )+ ).toBe(0)+ })+})diff --git a/nodejs/src/session-replay/recording-api/recording-service.test.ts b/nodejs/src/session-replay/recording-api/recording-service.test.tsindex a829cd77e224..800f9e7fb6cc 100644--- a/nodejs/src/session-replay/recording-api/recording-service.test.ts+++ b/nodejs/src/session-replay/recording-api/recording-service.test.ts@@ -504,17 +504,29 @@ describe('RecordingService', () => {await service.deleteRecordings(['session-1', 'session-2'], 1, '[email protected]')- // 3 DELETE statements + 1 activity log INSERT- expect(mockPostgres.query).toHaveBeenCalledTimes(4)+ // 4 DELETE statements + 1 asset expiry UPDATE + 1 activity log INSERT+ expect(mockPostgres.query).toHaveBeenCalledTimes(6)expect(mockPostgres.query).toHaveBeenCalledWith(expect.anything(),expect.stringContaining('ee_single_session_summary'),[1, ['session-1', 'session-2']],'deleteSessionSummaries')+ expect(mockPostgres.query).toHaveBeenCalledWith(+ expect.anything(),+ expect.stringContaining('replay_vision_replayobservation'),+ [1, ['session-1', 'session-2']],+ 'deleteReplayVisionObservations'+ )+ expect(mockPostgres.query).toHaveBeenCalledWith(+ expect.anything(),+ expect.stringContaining('posthog_exportedasset'),+ [1, ['"session-1"', '"session-2"']],+ 'expireRenderedRecordingVideos'+ )})- it('excludes already_deleted sessions from postgres batch', async () => {+ it('still cleans up derived data for an already_deleted session', async () => {mockKeyStore.deleteKey.mockResolvedValueOnce({ status: 'deleted', deletedAt: 1700000000, deletedBy: '[email protected]' }).mockResolvedValueOnce({@@ -525,12 +537,14 @@ describe('RecordingService', () => {await service.deleteRecordings(['new-session', 'already-deleted-session'], 1, '[email protected]')- // 3 DELETE statements + 1 activity log INSERT- expect(mockPostgres.query).toHaveBeenCalledTimes(4)+ // 4 DELETE statements + 1 asset expiry UPDATE + 1 activity log INSERT+ expect(mockPostgres.query).toHaveBeenCalledTimes(6)+ // Cleanup is best-effort, so a shred that already happened still gets another pass;+ // otherwise a failed one is never retried.expect(mockPostgres.query).toHaveBeenCalledWith(expect.anything(),expect.stringContaining('ee_single_session_summary'),- [1, ['new-session']],+ [1, ['new-session', 'already-deleted-session']],'deleteSessionSummaries')})@@ -601,7 +615,19 @@ describe('RecordingService', () => {await service.deleteRecordings(['session-1'], 1, '[email protected]')- expect(mockPostgres.query).not.toHaveBeenCalled()+ expect(mockPostgres.query).not.toHaveBeenCalledWith(+ expect.anything(),+ expect.stringContaining('posthog_activitylog'),+ expect.anything(),+ 'logRecordingDeletion'+ )+ // The shred is not repeated, but its derived data still gets a cleanup pass.+ expect(mockPostgres.query).toHaveBeenCalledWith(+ expect.anything(),+ expect.stringContaining('replay_vision_replayobservation'),+ [1, ['session-1']],+ 'deleteReplayVisionObservations'+ )})it('reports success when logActivity fails after shred', async () => {diff --git a/nodejs/src/session-replay/recording-api/recording-service.ts b/nodejs/src/session-replay/recording-api/recording-service.tsindex 3fa7c1cd3973..662148611697 100644--- a/nodejs/src/session-replay/recording-api/recording-service.ts+++ b/nodejs/src/session-replay/recording-api/recording-service.ts@@ -321,6 +321,10 @@ export class RecordingService {await this.propagateDeletion(deleted.map((r) => r.sessionId),+ // A shred that already happened still gets its derived data cleaned up. Cleanup is+ // best-effort, so without this a failed pass is never retried: the next delete of the+ // same recording reports already_deleted and skips it.+ [...deleted, ...alreadyDeleted].map((r) => r.sessionId),teamId,deletedBy)@@ -353,13 +357,18 @@ export class RecordingService {* Failures are non-fatal — the key shred already makes the recording unplayable (410).* Stale metadata from failed propagation is harmless but won't be automatically cleaned up.*/- private async propagateDeletion(sessionIds: string[], teamId: number, deletedBy: string): Promise<void> {- if (sessionIds.length === 0) {+ private async propagateDeletion(+ sessionIds: string[],+ cleanupSessionIds: string[],+ teamId: number,+ deletedBy: string+ ): Promise<void> {+ if (sessionIds.length === 0 && cleanupSessionIds.length === 0) {return}const [kafka, postgres, activity] = await Promise.allSettled([this.emitDeletionEvents(sessionIds, teamId),- this.deletePostgresRecords(sessionIds, teamId),+ this.deletePostgresRecords(cleanupSessionIds, teamId),this.logActivity(sessionIds, teamId, deletedBy),])if (kafka.status === 'rejected') {@@ -399,7 +408,13 @@ export class RecordingService {return}- const tables = ['ee_single_session_summary', 'posthog_exportedrecording', 'posthog_comment'] as const+ const tables = [+ 'ee_single_session_summary',+ 'posthog_exportedrecording',+ 'posthog_comment',+ 'replay_vision_replayobservation',+ 'posthog_exportedasset',+ ] as constconst results = await Promise.allSettled([this.postgres.query(PostgresUse.COMMON_WRITE,@@ -419,6 +434,41 @@ export class RecordingService {[teamId, sessionIds],'deleteRecordingComments'),+ // One statement: the children's foreign keys are NO ACTION, so separate deletes would have to run child-first.+ this.postgres.query(+ PostgresUse.COMMON_WRITE,+ `WITH observations AS (+ SELECT id FROM replay_vision_replayobservation+ WHERE team_id = $1 AND session_id = ANY($2)+ ), deleted_labels AS (+ DELETE FROM replay_vision_replayobservationlabel+ WHERE observation_id IN (SELECT id FROM observations)+ ), deleted_views AS (+ DELETE FROM replay_vision_replayobservationview+ WHERE observation_id IN (SELECT id FROM observations)+ ), deleted_matches AS (+ DELETE FROM replay_vision_visionalertmatch+ WHERE observation_id IN (SELECT id FROM observations)+ )+ DELETE FROM replay_vision_replayobservation+ WHERE id IN (SELECT id FROM observations)`,+ [teamId, sessionIds],+ 'deleteReplayVisionObservations'+ ),+ // Expired, not deleted: the row is the only pointer to the stored object, which the expiry sweep needs.+ this.postgres.query(+ PostgresUse.COMMON_WRITE,+ // `= ANY` over jsonb so the planner can use exportedasset_system_session; a subquery cannot.+ `UPDATE posthog_exportedasset+ SET expires_after = now()+ WHERE team_id = $1+ AND is_system+ AND export_format = 'video/mp4'+ AND expires_after > now()+ AND export_context -> 'session_recording_id' = ANY($2::jsonb[])`,+ [teamId, sessionIds.map((sessionId) => JSON.stringify(sessionId))],+ 'expireRenderedRecordingVideos'+ ),])const failures: string[] = []diff --git a/products/exports/backend/models/exported_asset.py b/products/exports/backend/models/exported_asset.pyindex 5cdb86512bb4..2e345569b218 100644--- a/products/exports/backend/models/exported_asset.py+++ b/products/exports/backend/models/exported_asset.py@@ -32,6 +32,8 @@ EXPORTED_ASSET_PURPOSE_RENDER = "render"EXPORTED_ASSET_PURPOSE_SUBSCRIPTION_DELIVERY = "subscription_delivery"DATASET_EXPORT_KIND = "dataset"+_EXPIRY_DELETE_BATCH = 1000+SEVEN_DAYS = timedelta(days=7)THIRTY_DAYS = timedelta(days=30)SIX_MONTHS = timedelta(days=180)@@ -262,7 +264,32 @@ class ExportedAsset(models.Model):def delete_expired_assets(cls):expired_assets = ExportedAsset.objects_including_ttl_deleted.filter(expires_after__lte=now())logger.info("deleting_expired_assets", count=expired_assets.count())- expired_assets.delete()++ # The file goes first: the row is the only pointer to it.+ stored = expired_assets.exclude(content_location=None).exclude(content_location="").order_by("id")+ # Keyset: a storage outage fails whole chunks, and an exclusion set would grow the predicate+ # by a batch on every pass.+ after_id = None+ while True:+ page = stored if after_id is None else stored.filter(id__gt=after_id)+ chunk = list(page.values_list("id", "content_location")[:_EXPIRY_DELETE_BATCH])+ if not chunk:+ break+ after_id = chunk[-1][0]+ failed = set(object_storage.delete_objects([location for _, location in chunk if location]))+ if failed:+ logger.warning("deleting_expired_assets_object_failures", count=len(failed))+ # A row whose object survived waits for the next run rather than stalling this one.+ deletable = [(asset_id, location) for asset_id, location in chunk if location not in failed]+ if deletable:+ # Matched on location as well as id: a render that finished after the snapshot has+ # already repointed the row at a new object, which this must not drop.+ ExportedAsset.objects_including_ttl_deleted.filter(+ id__in=[asset_id for asset_id, _ in deletable],+ content_location__in=[location for _, location in deletable],+ ).delete()++ expired_assets.filter(Q(content_location=None) | Q(content_location="")).delete()@classmethoddef get_supported_format_values(cls):diff --git a/products/exports/backend/tests/test_exported_asset_model.py b/products/exports/backend/tests/test_exported_asset_model.pyindex 21ab1d21277f..ab80a36a60a2 100644--- a/products/exports/backend/tests/test_exported_asset_model.py+++ b/products/exports/backend/tests/test_exported_asset_model.py@@ -74,6 +74,92 @@ class TestExportedAssetModel(APIBaseTest):assert list(ExportedAsset.objects.filter(id=asset.id)) == []assert list(ExportedAsset.objects_including_ttl_deleted.filter(id=asset.id)) == [asset]+ def test_delete_expired_assets_removes_the_stored_object_first(self) -> None:+ # A row deleted without its file strands the file in the bucket permanently.+ expired = ExportedAsset.objects_including_ttl_deleted.create(+ team=self.team,+ created_by=self.user,+ content_location="exports/mp4/team-1/task-1.mp4",+ expires_after=datetime.now() - timedelta(days=1),+ )+ ExportedAsset.objects.create(+ team=self.team,+ created_by=self.user,+ content_location="exports/mp4/team-1/task-2.mp4",+ expires_after=datetime.now() + timedelta(days=1),+ )++ with patch("posthog.storage.object_storage.delete_objects", return_value=[]) as mock_delete:+ ExportedAsset.delete_expired_assets()++ mock_delete.assert_called_once_with(["exports/mp4/team-1/task-1.mp4"])+ assert not ExportedAsset.objects_including_ttl_deleted.filter(id=expired.id).exists()++ def test_delete_expired_assets_skips_past_a_failing_object(self) -> None:+ # One unreachable key must not stall the rest of the sweep behind it.+ stuck = ExportedAsset.objects_including_ttl_deleted.create(+ team=self.team,+ created_by=self.user,+ content_location="exports/mp4/team-1/stuck.mp4",+ expires_after=datetime.now() - timedelta(days=1),+ )+ following = ExportedAsset.objects_including_ttl_deleted.create(+ team=self.team,+ created_by=self.user,+ content_location="exports/mp4/team-1/following.mp4",+ expires_after=datetime.now() - timedelta(days=1),+ )++ with (+ patch("products.exports.backend.models.exported_asset._EXPIRY_DELETE_BATCH", 1),+ patch(+ "posthog.storage.object_storage.delete_objects",+ side_effect=lambda keys: [k for k in keys if k.endswith("stuck.mp4")],+ ),+ ):+ ExportedAsset.delete_expired_assets()++ assert ExportedAsset.objects_including_ttl_deleted.filter(id=stuck.id).exists()+ assert not ExportedAsset.objects_including_ttl_deleted.filter(id=following.id).exists()++ def test_delete_expired_assets_keeps_a_row_repointed_after_the_snapshot(self) -> None:+ # A render finishing mid-sweep repoints the row at a new object; dropping the row here would+ # strand it.+ expired = ExportedAsset.objects_including_ttl_deleted.create(+ team=self.team,+ created_by=self.user,+ content_location="exports/mp4/team-1/old.mp4",+ expires_after=datetime.now() - timedelta(days=1),+ )++ def repoint(keys: list[str]) -> list[str]:+ ExportedAsset.objects_including_ttl_deleted.filter(id=expired.id).update(+ content_location="exports/mp4/team-1/new.mp4"+ )+ return []++ with patch("posthog.storage.object_storage.delete_objects", side_effect=repoint):+ ExportedAsset.delete_expired_assets()++ assert ExportedAsset.objects_including_ttl_deleted.filter(id=expired.id).exists()++ def test_delete_expired_assets_keeps_the_row_when_the_object_delete_fails(self) -> None:+ # Losing the row here would leave the file unreachable, so the row waits for the next run.+ expired = ExportedAsset.objects_including_ttl_deleted.create(+ team=self.team,+ created_by=self.user,+ content_location="exports/mp4/team-1/task-3.mp4",+ expires_after=datetime.now() - timedelta(days=1),+ )++ with patch(+ "posthog.storage.object_storage.delete_objects",+ return_value=["exports/mp4/team-1/task-3.mp4"],+ ):+ ExportedAsset.delete_expired_assets()++ assert ExportedAsset.objects_including_ttl_deleted.filter(id=expired.id).exists()+def test_delete_expired_assets(self) -> None:assert ExportedAsset.objects.count() == 0