: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): cap delete-recordings fan-out, back off on clickhouse 202 (#66778)
Tue Haulund2f8865cd84b5
diff --git a/posthog/models/person/bulk_delete.py b/posthog/models/person/bulk_delete.pyindex ce572005a9b2..c9825a5235a1 100644--- a/posthog/models/person/bulk_delete.py+++ b/posthog/models/person/bulk_delete.py@@ -1,6 +1,7 @@import uuid as uuid_libimport asyncioimport builtins+from collections.abc import Iteratorfrom dataclasses import dataclass, fieldfrom datetime import timedeltafrom typing import cast@@ -127,30 +128,56 @@ def queue_person_recording_deletion(_start_recording_workflows(team_id, persons, actor, reason)+# Batch persons per workflow (not one each) to bound concurrent ClickHouse load queries; cap distinct IDs per chunk to stay under Temporal's payload limit.+_RECORDING_DELETION_PERSONS_PER_WORKFLOW = 100+_MAX_CONCURRENT_WORKFLOW_STARTS = 20+_MAX_DISTINCT_IDS_PER_WORKFLOW = 2000+++def _chunk_persons(persons: builtins.list[Person]) -> Iterator[builtins.list[Person]]:+ """Group persons into workflow batches, bounded by both person and distinct-ID count."""+ batch: builtins.list[Person] = []+ batch_distinct_ids = 0+ for person in persons:+ person_distinct_ids = len(person.distinct_ids)+ over_caps = len(batch) >= _RECORDING_DELETION_PERSONS_PER_WORKFLOW or (+ batch_distinct_ids + person_distinct_ids > _MAX_DISTINCT_IDS_PER_WORKFLOW+ )+ if batch and over_caps:+ yield batch+ batch = []+ batch_distinct_ids = 0+ batch.append(person)+ batch_distinct_ids += person_distinct_ids+ if batch:+ yield batch++def _start_recording_workflows(team_id: int,persons: builtins.list[Person],actor: User | None,reason: str,) -> None:- """Kick off one ``delete-recordings-with-person`` workflow per person.+ """Kick off ``delete-recordings-with-person`` workflows, batching persons per run.The Temporal connection is established here (rather than in the caller) sothat tests patching this seam don't need to mock ``sync_connect`` separately."""temporal = sync_connect()+ config = DeletionConfig(deleted_by=getattr(actor, "email", None) or "", reason=reason)async def start_all_workflows():- tasks = []- for person in persons:- workflow_input = RecordingsWithPersonInput(- distinct_ids=person.distinct_ids,- team_id=team_id,- config=DeletionConfig(deleted_by=getattr(actor, "email", None), reason=reason),- )- workflow_id = f"delete-recordings-{team_id}-person-{person.uuid}-{uuid_lib.uuid4()}"- tasks.append(- temporal.start_workflow(+ semaphore = asyncio.Semaphore(_MAX_CONCURRENT_WORKFLOW_STARTS)++ async def start_batch(batch: builtins.list[Person]) -> None:+ distinct_ids = sorted({distinct_id for person in batch for distinct_id in person.distinct_ids})+ if not distinct_ids:+ return+ workflow_input = RecordingsWithPersonInput(distinct_ids=distinct_ids, team_id=team_id, config=config)+ workflow_id = f"delete-recordings-{team_id}-persons-{uuid_lib.uuid4()}"+ async with semaphore:+ await temporal.start_workflow("delete-recordings-with-person",workflow_input,id=workflow_id,@@ -160,7 +187,7 @@ def _start_recording_workflows(initial_interval=timedelta(minutes=1),),)- )- await asyncio.gather(*tasks)++ await asyncio.gather(*(start_batch(batch) for batch in _chunk_persons(persons)))asyncio.run(start_all_workflows())diff --git a/posthog/models/person/test/test_bulk_delete_helpers.py b/posthog/models/person/test/test_bulk_delete_helpers.pyindex 3460dcd7cee8..d2f7f679684e 100644--- a/posthog/models/person/test/test_bulk_delete_helpers.py+++ b/posthog/models/person/test/test_bulk_delete_helpers.py@@ -1,8 +1,12 @@from posthog.test.base import BaseTest-from unittest.mock import patch+from unittest.mock import AsyncMock, MagicMock, patch++from parameterized import parameterizedfrom posthog.models.async_deletion import AsyncDeletion, DeletionType+from posthog.models.person import Personfrom posthog.models.person.bulk_delete import (+ _start_recording_workflows,delete_persons_profile,queue_person_event_deletion,queue_person_recording_deletion,@@ -11,6 +15,13 @@ from posthog.models.person.bulk_delete import (from posthog.test.persons import create_person+def _person_with_distinct_ids(*distinct_ids: str) -> Person:+ # Unsaved Person with distinct_ids cached, so reads stay in-memory in the async fan-out.+ person = Person()+ person._distinct_ids = list(distinct_ids)+ return person++class ResolvePersonsTests(BaseTest):def test_resolves_by_uuid(self):p = create_person(team=self.team, distinct_ids=["a"], properties={})@@ -90,7 +101,7 @@ class QueueRecordingDeletionTests(BaseTest):queue_person_recording_deletion(self.team.pk, [], actor=self.user)conn.assert_not_called()- def test_starts_workflow_per_person(self):+ def test_queue_delegates_to_start_recording_workflows(self):p1 = create_person(team=self.team, distinct_ids=["a"], properties={})p2 = create_person(team=self.team, distinct_ids=["b"], properties={})with patch("posthog.models.person.bulk_delete._start_recording_workflows") as start:@@ -98,3 +109,64 @@ class QueueRecordingDeletionTests(BaseTest):start.assert_called_once()(_, persons, _, _) = start.call_args.argsassert {p.uuid for p in persons} == {p1.uuid, p2.uuid}++ @parameterized.expand(+ [+ ("single_batch_under_limit", 3, 100, 1),+ ("splits_across_batch_boundary", 3, 2, 2),+ ("one_workflow_per_full_batch", 5, 2, 3),+ ]+ )+ def test_batches_persons_into_workflows(self, _name, num_persons, batch_size, expected_workflows):+ persons = [_person_with_distinct_ids(f"did-{i}") for i in range(num_persons)]+ client = MagicMock()+ client.start_workflow = AsyncMock()+ with (+ patch("posthog.models.person.bulk_delete.sync_connect", return_value=client),+ patch("posthog.models.person.bulk_delete._RECORDING_DELETION_PERSONS_PER_WORKFLOW", batch_size),+ ):+ _start_recording_workflows(self.team.pk, persons, self.user, "test reason")++ assert client.start_workflow.call_count == expected_workflows+ started_distinct_ids = {+ distinct_id for call in client.start_workflow.call_args_list for distinct_id in call.args[1].distinct_ids+ }+ assert started_distinct_ids == {f"did-{i}" for i in range(num_persons)}+ assert all(call.args[0] == "delete-recordings-with-person" for call in client.start_workflow.call_args_list)++ def test_skips_batch_with_no_distinct_ids(self):+ person = _person_with_distinct_ids()+ client = MagicMock()+ client.start_workflow = AsyncMock()+ with patch("posthog.models.person.bulk_delete.sync_connect", return_value=client):+ _start_recording_workflows(self.team.pk, [person], self.user, "test reason")+ client.start_workflow.assert_not_called()++ @parameterized.expand(+ [+ ("packs_until_distinct_id_cap", [2, 2, 2], 4, 2),+ ("single_person_over_cap_stands_alone", [5, 1], 4, 2),+ ("each_person_own_workflow_when_cap_tiny", [2, 2], 1, 2),+ ]+ )+ def test_chunks_by_distinct_id_count(self, _name, distinct_id_counts, cap, expected_workflows):+ persons = [+ _person_with_distinct_ids(*[f"p{i}-d{j}" for j in range(count)])+ for i, count in enumerate(distinct_id_counts)+ ]+ client = MagicMock()+ client.start_workflow = AsyncMock()+ with (+ patch("posthog.models.person.bulk_delete.sync_connect", return_value=client),+ patch("posthog.models.person.bulk_delete._MAX_DISTINCT_IDS_PER_WORKFLOW", cap),+ ):+ _start_recording_workflows(self.team.pk, persons, self.user, "test reason")+ assert client.start_workflow.call_count == expected_workflows++ def test_uses_empty_deleted_by_when_actor_missing(self):+ client = MagicMock()+ client.start_workflow = AsyncMock()+ with patch("posthog.models.person.bulk_delete.sync_connect", return_value=client):+ _start_recording_workflows(self.team.pk, [_person_with_distinct_ids("a")], None, "test reason")+ client.start_workflow.assert_called_once()+ assert client.start_workflow.call_args.args[1].config.deleted_by == ""diff --git a/posthog/temporal/session_replay/delete_recordings/workflow.py b/posthog/temporal/session_replay/delete_recordings/workflow.pyindex eb8454ebd85d..45d8e83ba6d8 100644--- a/posthog/temporal/session_replay/delete_recordings/workflow.py+++ b/posthog/temporal/session_replay/delete_recordings/workflow.py@@ -36,6 +36,19 @@ from posthog.temporal.session_replay.delete_recordings.types import (RecordingsWithTeamInput,)+# Back off on transient ClickHouse overload (Code 202); fail fast on deterministic errors that won't recover.+_LOAD_RECORDINGS_RETRY_POLICY = common.RetryPolicy(+ maximum_attempts=8,+ initial_interval=timedelta(seconds=2),+ backoff_coefficient=2.0,+ maximum_interval=timedelta(seconds=30),+ non_retryable_error_types=[+ "LoadRecordingError",+ "ClickHouseMemoryLimitExceededError",+ "ClickHouseTooManyBytesError",+ ],+)+async def _delete_page(page: LoadRecordingsPage,@@ -122,7 +135,7 @@ class DeleteRecordingsWithPersonWorkflow(PostHogWorkflow):),start_to_close_timeout=timedelta(minutes=2),schedule_to_close_timeout=timedelta(minutes=30),- retry_policy=common.RetryPolicy(maximum_attempts=2, initial_interval=timedelta(minutes=1)),+ retry_policy=_LOAD_RECORDINGS_RETRY_POLICY,)await _delete_page(page, input.team_id, input.config, progress)@@ -168,7 +181,7 @@ class DeleteRecordingsWithTeamWorkflow(PostHogWorkflow):),start_to_close_timeout=timedelta(minutes=2),schedule_to_close_timeout=timedelta(minutes=30),- retry_policy=common.RetryPolicy(maximum_attempts=2, initial_interval=timedelta(minutes=1)),+ retry_policy=_LOAD_RECORDINGS_RETRY_POLICY,)await _delete_page(page, input.team_id, input.config, progress)@@ -213,7 +226,7 @@ class DeleteRecordingsWithQueryWorkflow(PostHogWorkflow):),start_to_close_timeout=timedelta(minutes=15),schedule_to_close_timeout=timedelta(hours=1),- retry_policy=common.RetryPolicy(maximum_attempts=2, initial_interval=timedelta(minutes=2)),+ retry_policy=_LOAD_RECORDINGS_RETRY_POLICY,)await _delete_page(page, input.team_id, input.config, progress)