: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(persons): queue bulk person deletion in a celery task (#101908)
Nick Bestb4e5dbeaa61d
diff --git a/posthog/api/person.py b/posthog/api/person.pyindex a1ef8e53e3d4..06fbdb891340 100644--- a/posthog/api/person.py+++ b/posthog/api/person.py@@ -74,6 +74,7 @@ from posthog.rate_limit import ClickHouseBurstRateThrottle, PersonalApiKeyRateThfrom posthog.renderers import SafeJSONRendererfrom posthog.slo.context import JsonValue, SloSpec, slo_operationfrom posthog.slo.types import SloArea, SloOperation+from posthog.tasks.delete_persons import queue_person_deletionfrom posthog.tasks.split_person import split_personfrom posthog.utils import (format_query_params_absolute_url,@@ -279,7 +280,12 @@ class PersonBulkDeleteRequestSerializer(serializers.Serializer):class PersonBulkDeleteResponseSerializer(serializers.Serializer):persons_found = serializers.IntegerField(help_text="Number of persons matched by the provided IDs or distinct IDs.")persons_deleted = serializers.IntegerField(- help_text="Number of person records deleted from the database. 0 if keep_person was true."+ help_text="Number of person records deleted from the database during this request. "+ "0 if keep_person was true or if the deletion was queued (see persons_queued_for_deletion)."+ )+ persons_queued_for_deletion = serializers.IntegerField(+ help_text="Number of persons queued for deletion in the background. Their person records and "+ "distinct IDs are removed shortly after the request completes. 0 if keep_person was true.")events_queued_for_deletion = serializers.BooleanField(help_text="Whether event deletion was requested for the matched persons. "@@ -292,7 +298,12 @@ class PersonBulkDeleteResponseSerializer(serializers.Serializer):deletion_errors = serializers.ListField(child=serializers.DictField(),required=False,- help_text="Persons that could not be deleted. Each entry contains 'person_uuid'. Contact support if this persists.",+ help_text="Persons whose deletion did not fully complete in this request. Each entry contains 'person_uuid' "+ "and 'step', the deletion step that failed for that person. A failed database delete is reported here "+ "rather than as an error response, so a 202 with entries means some or all persons were not deleted. "+ "A 'log_activity' step means the person was deleted but the activity log entry was not written. "+ "Always empty when the deletion was queued (see persons_queued_for_deletion). "+ "Contact support if this persists.",)@@ -834,13 +845,16 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):"""try:person = self.get_object()- # Convert query params to request data format expected by bulk_delete+ # Convert query params to request data format expected by bulk_delete. This path stays+ # synchronous under the queued-deletion flag: the app deletes one person here and reloads+ # the list at once, so the person has to be gone when the response returns.self._bulk_delete_persons(request=request,ids=[str(person.uuid)],delete_events="delete_events" in request.GET,delete_recordings="delete_recordings" in request.GET,keep_person="keep_person" in request.GET,+ allow_queued=False,)return response.Response(status=202)@@ -880,6 +894,7 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):delete_events: bool = False,delete_recordings: bool = False,keep_person: bool = False,+ allow_queued: bool = True,) -> dict[str, Any]:if distinct_ids and ids:raise ValidationError("You must provide either distinct_ids or ids, not both")@@ -890,6 +905,16 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):if not distinct_ids and not ids:raise ValidationError("You need to specify either distinct_ids or ids")+ if allow_queued and settings.PERSON_BULK_DELETE_ASYNC:+ return self._queue_bulk_delete_persons(+ request,+ distinct_ids=distinct_ids,+ ids=ids,+ delete_events=delete_events,+ delete_recordings=delete_recordings,+ keep_person=keep_person,+ )+persons = resolve_persons_for_deletion(self.team_id, ids, distinct_ids)if not keep_person or delete_recordings:queue_person_training_deletion(@@ -909,7 +934,11 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):queue_ai_training_deletion=False,)persons_deleted = result.deleted_count- errors = [{"person_uuid": str(u)} for u in result.errors]+ errors = [+ {"person_uuid": str(failure.person_uuid), "step": failure.step.value}+ for failure in result.failures+ if failure.person_uuid is not None+ ]if delete_events:queue_person_event_deletion(self.team_id, persons, actor=cast(User, request.user))@@ -921,11 +950,50 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):return {"persons_found": len(persons),"persons_deleted": persons_deleted,+ "persons_queued_for_deletion": 0,"events_queued_for_deletion": delete_events and len(persons) > 0,"recordings_queued_for_deletion": delete_recordings and len(persons) > 0,"deletion_errors": errors,}+ def _queue_bulk_delete_persons(+ self,+ request: request.Request,+ *,+ distinct_ids: builtins.list[str] | None,+ ids: builtins.list[str] | None,+ delete_events: bool,+ delete_recordings: bool,+ keep_person: bool,+ ) -> dict[str, Any]:+ """Resolve persons without their distinct IDs and hand every distinct-ID-dependent step to Celery."""+ actor = cast(User, request.user)+ persons = resolve_persons_for_deletion(self.team_id, ids, distinct_ids, with_distinct_ids=False)+ # A requested distinct ID with no person row can still own replay sessions. The task covers+ # every distinct ID of each resolved person, so only those unmatched IDs are handed over.+ matched = {distinct_id for person in persons for distinct_id in person.distinct_ids}+ unmatched = [distinct_id for distinct_id in distinct_ids or [] if distinct_id not in matched]+ if delete_events:+ queue_person_event_deletion(self.team_id, persons, actor=actor)+ persons_queued = queue_person_deletion(+ self.team_id,+ persons,+ delete_profile=not keep_person,+ delete_recordings=delete_recordings,+ actor=actor,+ request=request,+ organization_id=self.organization.id,+ unmatched_distinct_ids=unmatched,+ )+ return {+ "persons_found": len(persons),+ "persons_deleted": 0,+ "persons_queued_for_deletion": persons_queued if not keep_person else 0,+ "events_queued_for_deletion": delete_events and len(persons) > 0,+ "recordings_queued_for_deletion": delete_recordings and len(persons) > 0,+ "deletion_errors": [],+ }+@extend_schema(parameters=[OpenApiParameter(diff --git a/posthog/api/test/test_person_personhog.py b/posthog/api/test/test_person_personhog.pyindex 9c2a1740756c..a2d8e3e8f47c 100644--- a/posthog/api/test/test_person_personhog.py+++ b/posthog/api/test/test_person_personhog.py@@ -7,9 +7,13 @@ person deletion — extracted from test_person.py.from posthog.test.base import APIBaseTestfrom unittest import mock+from django.test import override_settings++from parameterized import parameterizedfrom rest_framework import statusfrom posthog.models import Organization, Team+from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.person.util import get_person_by_uuidfrom posthog.personhog_client.test_helpers import PersonhogTestMixin@@ -387,6 +391,7 @@ class TestBulkDeletePersons(PersonhogTestMixin, APIBaseTest):data = resp.json()assert data["persons_found"] == 2assert data["persons_deleted"] == 2+ assert data["persons_queued_for_deletion"] == 0assert data["deletion_errors"] == []assert data["events_queued_for_deletion"] is Falseassert data["recordings_queued_for_deletion"] is False@@ -396,6 +401,98 @@ class TestBulkDeletePersons(PersonhogTestMixin, APIBaseTest):assert calls[0].request.team_id == self.team.pkassert set(calls[0].request.person_uuids) == {str(p1.uuid), str(p2.uuid)}+ @parameterized.expand([("by_ids",), ("by_distinct_ids",)])+ @override_settings(PERSON_BULK_DELETE_ASYNC=True)+ def test_bulk_delete_async_queues_persons_and_deletes_in_background(self, lookup):+ p1 = self._seed_person(team=self.team, distinct_ids=["did-1"])+ p2 = self._seed_person(team=self.team, distinct_ids=["did-2"])+ payload = {"ids": [str(p1.uuid), str(p2.uuid)]} if lookup == "by_ids" else {"distinct_ids": ["did-1", "did-2"]}++ resp = self.client.post("/api/person/bulk_delete/", payload)++ assert resp.status_code == status.HTTP_202_ACCEPTED+ data = resp.json()+ assert data["persons_found"] == 2+ assert data["persons_deleted"] == 0+ assert data["persons_queued_for_deletion"] == 2+ assert data["deletion_errors"] == []++ # The request must not batch-fetch distinct IDs; only the task pages through them.+ self._assert_personhog_not_called("get_distinct_ids_for_persons")+ self._assert_personhog_called("get_distinct_ids_for_person")+ # Celery runs eagerly in tests, so the queued task has already deleted the persons.+ calls = self._assert_personhog_called("delete_persons")+ if calls:+ assert set(calls[0].request.person_uuids) == {str(p1.uuid), str(p2.uuid)}+ assert get_person_by_uuid(self.team.pk, str(p1.uuid)) is None+ assert get_person_by_uuid(self.team.pk, str(p2.uuid)) is None+ # The task rebuilds the actor and organization from serialized ids; the log row proves it did.+ logs = ActivityLog.objects.filter(team_id=self.team.pk, scope="Person", activity="deleted")+ assert {log.item_id for log in logs} == {str(p1.pk), str(p2.pk)}+ assert {(log.user_id, log.organization_id) for log in logs} == {(self.user.pk, self.organization.id)}++ @override_settings(PERSON_BULK_DELETE_ASYNC=True)+ @mock.patch("posthog.api.person.queue_person_deletion")+ def test_single_person_delete_stays_synchronous_under_the_flag(self, queue_deletion):+ p1 = self._seed_person(team=self.team, distinct_ids=["did-1"])++ resp = self.client.delete(f"/api/person/{p1.uuid}/")++ assert resp.status_code == status.HTTP_202_ACCEPTED+ queue_deletion.assert_not_called()+ self._assert_personhog_called("delete_persons")+ assert get_person_by_uuid(self.team.pk, str(p1.uuid)) is None++ @override_settings(PERSON_BULK_DELETE_ASYNC=True)+ @mock.patch("posthog.models.person.bulk_delete.queue_person_training_deletion")+ @mock.patch("posthog.api.person.queue_person_training_deletion")+ def test_bulk_delete_async_queues_training_deletion_once_per_distinct_id(self, request_side, task_side):+ p1 = self._seed_person(team=self.team, distinct_ids=["did-1", "did-2"])++ resp = self.client.post("/api/person/bulk_delete/", {"distinct_ids": ["did-1", "ghost"]})++ assert resp.status_code == status.HTTP_202_ACCEPTED+ assert resp.json()["persons_found"] == 1+ # Nothing runs the replay session lookup in the request. The task queues the person's full+ # set once and the requested ID that matched no person once.+ request_side.assert_not_called()+ assert sorted(sorted(call.args[1]) for call in task_side.call_args_list) == [["did-1", "did-2"], ["ghost"]]+ assert get_person_by_uuid(self.team.pk, str(p1.uuid)) is None++ @override_settings(PERSON_BULK_DELETE_ASYNC=True)+ @mock.patch("posthog.models.person.bulk_delete.queue_person_training_deletion")+ def test_bulk_delete_async_queues_training_deletion_when_no_person_matches(self, task_side):+ resp = self.client.post("/api/person/bulk_delete/", {"distinct_ids": ["ghost"]})++ assert resp.status_code == status.HTTP_202_ACCEPTED+ assert resp.json()["persons_found"] == 0+ task_side.assert_called_once_with(self.team.pk, ["ghost"])++ @override_settings(PERSON_BULK_DELETE_ASYNC=True)+ def test_bulk_delete_async_keep_person_with_recordings(self):+ p1 = self._seed_person(team=self.team, distinct_ids=["did-1", "did-2"])+ # Snapshot at call time: the task releases each person's IDs once its batch has run.+ started: list[list[str]] = []++ with mock.patch(+ "posthog.models.person.bulk_delete._start_recording_workflows",+ side_effect=lambda _t, persons, *_a: started.extend(sorted(p.distinct_ids) for p in persons),+ ):+ resp = self.client.post(+ "/api/person/bulk_delete/",+ {"ids": [str(p1.uuid)], "keep_person": True, "delete_recordings": True},+ )++ assert resp.status_code == status.HTTP_202_ACCEPTED+ data = resp.json()+ assert data["persons_found"] == 1+ assert data["persons_queued_for_deletion"] == 0+ assert data["recordings_queued_for_deletion"] is True+ self._assert_personhog_not_called("get_distinct_ids_for_persons")+ assert started == [["did-1", "did-2"]]+ assert get_person_by_uuid(self.team.pk, str(p1.uuid)) is not None+ self._assert_personhog_not_called("delete_persons")+def test_bulk_delete_by_distinct_ids(self):p1 = self._seed_person(team=self.team, distinct_ids=["did-1"])p2 = self._seed_person(team=self.team, distinct_ids=["did-2"])@@ -474,8 +571,7 @@ class TestBulkDeletePersons(PersonhogTestMixin, APIBaseTest):data = resp.json()assert data["persons_found"] == 2assert data["persons_deleted"] == 1- assert len(data["deletion_errors"]) == 1- assert data["deletion_errors"][0]["person_uuid"] == str(p1.uuid)+ assert data["deletion_errors"] == [{"person_uuid": str(p1.uuid), "step": "tombstone_clickhouse"}]calls = self._assert_personhog_called("delete_persons")if calls:diff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.pyindex a91a55569da1..40c24edb2966 100644--- a/posthog/dags/data_deletion_requests.py+++ b/posthog/dags/data_deletion_requests.py@@ -66,6 +66,7 @@ from posthog.models.event.sql import (json_property_presence_expr,)from posthog.models.person.bulk_delete import (+ PersonDeletionStep,delete_persons_profile,queue_person_recording_deletion,resolve_persons_for_deletion,@@ -1532,6 +1533,9 @@ def delete_person_profiles_op(submit a follow-up request for them. This mirrors the best-effort semantics of the`POST /api/projects/:id/persons/bulk_delete/` endpoint and avoids flipping the wholerequest to FAILED after upstream events/recordings ops have already done their work.++ The one exception is the batch Postgres delete: when it fails, every tombstoned person is+ still in Postgres, so the op raises and the request finalizes as FAILED for a retry."""if not person_removal.drop_profiles:context.log.info("drop_profiles=False, skipping profile deletion")@@ -1557,6 +1561,15 @@ def delete_person_profiles_op(f"Postgres rows remain for failed UUIDs and can be retried via a follow-up request")metadata["error_uuids"] = dagster.MetadataValue.text(", ".join(str(u) for u in result.errors))+ postgres_failures = [f for f in result.failures if f.step is PersonDeletionStep.DELETE_POSTGRES]+ if postgres_failures:+ raise dagster.Failure(+ description=(+ f"Deletion request {person_removal.request_id}: the Postgres delete failed for "+ f"{len(postgres_failures)} persons ({postgres_failures[0].error})"+ ),+ metadata=metadata,+ )context.add_output_metadata(metadata)return person_removaldiff --git a/posthog/dags/tests/test_data_deletion_requests.py b/posthog/dags/tests/test_data_deletion_requests.pyindex f1f9aa927d28..890efc848413 100644--- a/posthog/dags/tests/test_data_deletion_requests.py+++ b/posthog/dags/tests/test_data_deletion_requests.py@@ -2,7 +2,7 @@ import jsonfrom dataclasses import replacefrom datetime import UTC, datetime, timedeltafrom functools import partial-from uuid import uuid4+from uuid import UUID, uuid4import pytestfrom unittest.mock import patch@@ -59,6 +59,7 @@ from posthog.models.deletion_targets import (placement_for,)from posthog.models.flag_evaluations.sql import FLAG_EVALUATIONS_DATA_TABLE, FLAG_EVALUATIONS_SOURCE_EVENT+from posthog.models.person.bulk_delete import PersonDeletionFailure, PersonDeletionStep, PersonProfileDeletionResultfrom posthog.test.persons import create_personTEAM_ID = 99999@@ -2511,7 +2512,7 @@ def test_delete_person_profiles_op_calls_helper_when_enabled():drop_recordings=False,)with patch("posthog.dags.data_deletion_requests.delete_persons_profile") as deleter:- deleter.return_value = type("R", (), {"deleted_count": 1, "errors": []})()+ deleter.return_value = PersonProfileDeletionResult(deleted_count=1)delete_person_profiles_op(build_op_context(), ctx)deleter.assert_called_once()@@ -2550,7 +2551,14 @@ def test_delete_person_profiles_op_records_per_person_errors_in_metadata():)op_context = build_op_context()with patch("posthog.dags.data_deletion_requests.delete_persons_profile") as deleter:- deleter.return_value = type("R", (), {"deleted_count": 0, "errors": [p_uuid]})()+ deleter.return_value = PersonProfileDeletionResult(+ deleted_count=0,+ failures=[+ PersonDeletionFailure(+ step=PersonDeletionStep.TOMBSTONE_CLICKHOUSE, person_uuid=UUID(p_uuid), error="RuntimeError: x"+ )+ ],+ )with patch.object(op_context.log, "warning") as warn:result = delete_person_profiles_op(op_context, ctx)@@ -2563,7 +2571,42 @@ def test_delete_person_profiles_op_records_per_person_errors_in_metadata():@pytest.mark.django_db-def test_data_deletion_request_person_removal_lifecycle(cluster: ClickhouseCluster):+def test_delete_person_profiles_op_raises_when_the_postgres_delete_fails():+ p_uuid = str(uuid4())+ create_person(team_id=TEAM_ID, uuid=p_uuid, distinct_ids=["a"])+ ctx = PersonRemovalContext(+ request_id=str(uuid4()),+ team_id=TEAM_ID,+ person_uuids=[p_uuid],+ person_distinct_ids=[],+ drop_profiles=True,+ drop_events=False,+ drop_recordings=False,+ )+ tombstone_failed = uuid4()+ with patch("posthog.dags.data_deletion_requests.delete_persons_profile") as deleter:+ deleter.return_value = PersonProfileDeletionResult(+ deleted_count=0,+ failures=[+ PersonDeletionFailure(+ step=PersonDeletionStep.TOMBSTONE_CLICKHOUSE, person_uuid=tombstone_failed, error="RuntimeError: ch"+ ),+ PersonDeletionFailure(+ step=PersonDeletionStep.DELETE_POSTGRES, person_uuid=UUID(p_uuid), error="RuntimeError: down"+ ),+ ],+ )+ with pytest.raises(dagster.Failure, match="Postgres delete failed for 1 persons") as raised:+ delete_person_profiles_op(build_op_context(), ctx)+ # The run metadata still carries every failure, not only the Postgres ones named in the description.+ assert raised.value.metadata["errors"].value == 2+ assert raised.value.metadata["deleted_count"].value == 0+ assert set(str(raised.value.metadata["error_uuids"].value).split(", ")) == {str(tombstone_failed), p_uuid}++[email protected]("postgres_delete_fails", [False, True])+def test_data_deletion_request_person_removal_lifecycle(cluster: ClickhouseCluster, postgres_delete_fails: bool):p_uuid = str(uuid4())create_person(team_id=TEAM_ID, uuid=p_uuid, distinct_ids=["a"])request = DataDeletionRequest.objects.create(@@ -2580,7 +2623,18 @@ def test_data_deletion_request_person_removal_lifecycle(cluster: ClickhouseClustpatch("posthog.dags.data_deletion_requests.delete_persons_profile") as profile,patch("posthog.dags.data_deletion_requests.queue_person_recording_deletion"),):- profile.return_value = type("R", (), {"deleted_count": 1, "errors": []})()+ profile.return_value = (+ PersonProfileDeletionResult(+ deleted_count=0,+ failures=[+ PersonDeletionFailure(+ step=PersonDeletionStep.DELETE_POSTGRES, person_uuid=UUID(p_uuid), error="RuntimeError: down"+ )+ ],+ )+ if postgres_delete_fails+ else PersonProfileDeletionResult(deleted_count=1)+ )result = data_deletion_request_person_removal.execute_in_process(run_config={"ops": {@@ -2588,11 +2642,14 @@ def test_data_deletion_request_person_removal_lifecycle(cluster: ClickhouseClust},},resources={"cluster": cluster},+ raise_on_error=False,)- assert result.success+ # A failed Postgres delete has to reach the request status through the skipped finalize op and+ # the failure hook, not only raise inside the op.+ assert result.success is not postgres_delete_failsrequest.refresh_from_db()- assert request.status == RequestStatus.COMPLETED+ assert request.status == (RequestStatus.FAILED if postgres_delete_fails else RequestStatus.COMPLETED)@pytest.mark.django_dbdiff --git a/posthog/models/person/bulk_delete.py b/posthog/models/person/bulk_delete.pyindex 5223ca2762af..78be1f9b4347 100644--- a/posthog/models/person/bulk_delete.py+++ b/posthog/models/person/bulk_delete.py@@ -1,18 +1,21 @@import uuid as uuid_libimport asyncioimport builtins-from collections.abc import Iterator-from dataclasses import dataclass, field+from collections.abc import Callable, Iterable, Iterator+from dataclasses import fieldfrom datetime import timedelta+from enum import StrEnumfrom typing import castfrom django.conf import settingsimport structlog+from prometheus_client import Counter, Histogramfrom temporalio import common+from posthog.dataclasses import frozenfrom posthog.helpers.impersonation import is_impersonated-from posthog.models.activity_logging.activity_log import Detail, LogActivityEntry, bulk_log_activity+from posthog.models.activity_logging.activity_log import ActivityLog, Detail, LogActivityEntry, bulk_log_activityfrom posthog.models.async_deletion import AsyncDeletion, DeletionTypefrom posthog.models.person import Personfrom posthog.models.person.util import (@@ -20,6 +23,7 @@ from posthog.models.person.util import (_batched_get_distinct_ids_for_persons,_fetch_persons_by_distinct_ids_via_personhog,_fetch_persons_by_uuids_via_personhog,+ _paginated_get_distinct_ids_for_person,delete_person,delete_persons_from_postgres,)@@ -32,28 +36,117 @@ from products.ai_training.backend.facade.api import queue_person_training_deletilogger = structlog.get_logger(__name__)-@dataclass+class PersonDeletionStep(StrEnum):+ """The steps of a person deletion, in the order they run. Each failure names exactly one."""++ RESOLVE_PERSONS = "resolve_persons"+ FETCH_DISTINCT_IDS = "fetch_distinct_ids"+ QUEUE_TRAINING_DELETION = "queue_training_deletion"+ QUEUE_RECORDING_DELETION = "queue_recording_deletion"+ TOMBSTONE_CLICKHOUSE = "tombstone_clickhouse"+ DELETE_POSTGRES = "delete_postgres"+ LOG_ACTIVITY = "log_activity"+++PERSON_DELETION_STEP_FAILURES_COUNTER = Counter(+ "posthog_person_deletion_step_failures_total",+ "Person deletion steps that raised, labelled by the step so a failing dependency is visible on its own.",+ labelnames=["step"],+)++# path: "sync" for the request-time delete, "queued" for the Celery task.+# outcome: "queued" when handed to the task, "deleted" once removed, "failed" per person per attempt.+PERSON_DELETION_PERSONS_COUNTER = Counter(+ "posthog_person_deletion_persons_total",+ "Persons handled by a deletion, by path and per-attempt outcome.",+ labelnames=["path", "outcome"],+)++PERSON_DELETION_DISTINCT_IDS_PER_PERSON = Histogram(+ "posthog_person_deletion_distinct_ids_per_person",+ "Distinct IDs fetched per person by the queued deletion, which shows how wide deleted persons are.",+ buckets=(1, 10, 100, 1_000, 10_000, 100_000, 1_000_000, float("inf")),+)+++def _observe_person_outcomes(path: str, result: "PersonProfileDeletionResult") -> None:+ PERSON_DELETION_PERSONS_COUNTER.labels(path=path, outcome="deleted").inc(result.deleted_count)+ PERSON_DELETION_PERSONS_COUNTER.labels(path=path, outcome="failed").inc(len(result.errors))+++@frozen+class PersonDeletionFailure:+ step: PersonDeletionStep+ # None when the step failed before any person was resolved.+ person_uuid: uuid_lib.UUID | None+ error: str+++@frozenclass PersonProfileDeletionResult:deleted_count: int- errors: list[uuid_lib.UUID] = field(default_factory=list)+ failures: list[PersonDeletionFailure] = field(default_factory=list)++ @property+ def errors(self) -> list[uuid_lib.UUID]:+ """Distinct UUIDs of persons that failed at any step, in first-failure order."""+ seen: dict[uuid_lib.UUID, None] = {}+ for failure in self.failures:+ if failure.person_uuid is not None:+ seen.setdefault(failure.person_uuid, None)+ return list(seen)+++def _record_step_failure(+ failures: builtins.list[PersonDeletionFailure],+ *,+ step: PersonDeletionStep,+ team_id: int,+ exc: Exception,+ person_uuids: Iterable[uuid_lib.UUID | None],+) -> None:+ """Record one step failure. Call from inside the ``except`` block so the traceback is logged."""+ uuids = list(person_uuids) or [None]+ PERSON_DELETION_STEP_FAILURES_COUNTER.labels(step=step.value).inc()+ logger.exception(+ "person_deletion.step_failed",+ step=step.value,+ team_id=team_id,+ person_count=len([u for u in uuids if u is not None]),+ person_uuids=[str(u) for u in uuids[:20] if u is not None],+ error_type=type(exc).__name__,+ )+ error = f"{type(exc).__name__}: {exc}"+ failures.extend(PersonDeletionFailure(step=step, person_uuid=u, error=error) for u in uuids)def resolve_persons_for_deletion(team_id: int,uuids: builtins.list[str] | None,distinct_ids: builtins.list[str] | None,+ *,+ with_distinct_ids: bool = True,) -> builtins.list[Person]:- """Materialize Persons matching either uuids or distinct_ids, via personhog."""+ """Materialize Persons matching either uuids or distinct_ids, via personhog.++ With ``with_distinct_ids`` the fetch of each person's distinct IDs is unbounded, which the+ synchronous callers need because recording deletion wants the full set per person. The+ queued path passes False and pages through them later, inside the task; a person resolved+ by distinct ID then carries only the requested distinct IDs that matched it.+ """from posthog.personhog_client.client import personhog_callif not uuids and not distinct_ids:return []- # Unbounded distinct_ids: downstream recording deletion needs the full set per person.+ limit = None if with_distinct_ids else 0+def _fetch() -> builtins.list[Person]:if uuids:- return _fetch_persons_by_uuids_via_personhog(team_id, uuids)- return _fetch_persons_by_distinct_ids_via_personhog(team_id, cast(builtins.list[str], distinct_ids))+ return _fetch_persons_by_uuids_via_personhog(team_id, uuids, distinct_id_limit=limit)+ return _fetch_persons_by_distinct_ids_via_personhog(+ team_id, cast(builtins.list[str], distinct_ids), distinct_id_limit=limit+ )return personhog_call("resolve_persons_for_deletion", _fetch, caller_tag="persons/deletion-resolve")@@ -69,8 +162,8 @@ def delete_persons_profile() -> PersonProfileDeletionResult:"""Run ClickHouse Kafka tombstones, then a single Postgres batch delete.- Activity logging is performed only when both ``request`` and ``organization_id``- are provided (i.e. from a DRF endpoint). Dagster ops should leave them as None.+ Activity logging is performed only when ``organization_id`` is provided (i.e. from a+ DRF endpoint). Dagster ops should leave it and ``actor`` as None."""from posthog.personhog_client.client import personhog_call@@ -78,8 +171,6 @@ def delete_persons_profile(queue_person_training_deletion(team_id, [distinct_id for person in persons for distinct_id in person.distinct_ids])- deleted: builtins.list[Person] = []- errors: builtins.list[uuid_lib.UUID] = []# A missing map entry (or a failed batch fetch) passes None below, making delete_person# fall back to its own per-person lookup so failure isolation is preserved.distinct_ids_by_person: dict[int, builtins.list[DistinctIdForPerson]] = {}@@ -91,35 +182,340 @@ def delete_persons_profile()except Exception:logger.exception("Batched distinct-id fetch failed, falling back to per-person lookups")++ result = _tombstone_and_delete_persons(+ team_id,+ persons,+ lambda person: distinct_ids_by_person.get(person.pk),+ actor=actor,+ was_impersonated=is_impersonated(request),+ organization_id=organization_id,+ )+ _observe_person_outcomes("sync", result)+ return result+++# Page size for the keyset walk over a person's distinct IDs. Each page is one bounded RPC, so a+# person with hundreds of thousands of distinct IDs no longer hits the personhog request timeout.+QUEUED_DELETION_DISTINCT_ID_PAGE_SIZE = 5000++# A task chunk is sized by person count, which says nothing about how many distinct IDs it holds.+# The deletion steps run once this many distinct IDs are in memory, so several wide persons in one+# chunk cannot pile up on a worker; the bound is this cap plus one person's worth of IDs.+QUEUED_DELETION_DISTINCT_IDS_PER_BATCH = 20_000+++@frozen+class _QueuedDeletionOptions:+ delete_profile: bool+ delete_recordings: bool+ actor: User | None+ was_impersonated: bool+ organization_id: uuid_lib.UUID | None+++def process_queued_person_deletion(+ team_id: int,+ person_uuids: builtins.list[str],+ *,+ delete_profile: bool,+ delete_recordings: bool,+ actor: User | None,+ was_impersonated: bool,+ organization_id: uuid_lib.UUID | None,+ unmatched_distinct_ids: builtins.list[str] | None = None,+) -> PersonProfileDeletionResult:+ """Run every distinct-ID-dependent deletion step for ``person_uuids`` from a background task.++ ``unmatched_distinct_ids`` are requested distinct IDs that resolved to no person. They can+ still own replay sessions, so their training deletion is queued here too; a failure is+ recorded against the training step with no person.++ Persons are re-resolved without distinct IDs, then each person's distinct IDs are paged+ through with keyset pagination. There is no unbounded fallback: a failed page fetch marks+ that person as an error and skips it in every later step, so the caller can retry it.+ Persons that no longer exist (already deleted by an earlier attempt) resolve to nothing.++ Every failure is recorded against the step it happened in. The profile delete only runs+ when the steps before it succeeded, because it removes the distinct IDs a retry of those+ steps would need.+ """+ from posthog.personhog_client.client import personhog_call++ options = _QueuedDeletionOptions(+ delete_profile=delete_profile,+ delete_recordings=delete_recordings,+ actor=actor,+ was_impersonated=was_impersonated,+ organization_id=organization_id,+ )+ failures: builtins.list[PersonDeletionFailure] = []+ requested = [uuid_lib.UUID(u) for u in person_uuids]++ try:+ persons = personhog_call(+ "resolve_persons_for_queued_deletion",+ lambda: _fetch_persons_by_uuids_via_personhog(team_id, person_uuids, distinct_id_limit=0),+ caller_tag="persons/deletion-resolve",+ )+ except Exception as exc:+ _record_step_failure(+ failures, step=PersonDeletionStep.RESOLVE_PERSONS, team_id=team_id, exc=exc, person_uuids=requested+ )+ persons = []++ def _fetch_distinct_ids(person_id: int) -> builtins.list[DistinctIdForPerson]:+ return personhog_call(+ "get_distinct_ids_for_queued_deletion",+ lambda: _paginated_get_distinct_ids_for_person(+ team_id, person_id, page_size=QUEUED_DELETION_DISTINCT_ID_PAGE_SIZE+ ),+ caller_tag="persons/deletion-distinct-ids",+ )++ deleted_count = 0+ batch: builtins.list[Person] = []+ batch_distinct_ids: dict[int, builtins.list[DistinctIdForPerson]] = {}+ batch_distinct_id_count = 0for person in persons:try:- delete_person(person=person, distinct_ids=distinct_ids_by_person.get(person.pk))+ distinct_ids = _fetch_distinct_ids(person.pk)+ except Exception as exc:+ _record_step_failure(+ failures,+ step=PersonDeletionStep.FETCH_DISTINCT_IDS,+ team_id=team_id,+ exc=exc,+ person_uuids=[person.uuid],+ )+ continue+ PERSON_DELETION_DISTINCT_IDS_PER_PERSON.observe(len(distinct_ids))+ person._distinct_ids = [d.id for d in distinct_ids]+ batch.append(person)+ batch_distinct_ids[person.pk] = distinct_ids+ batch_distinct_id_count += len(distinct_ids)+ if batch_distinct_id_count >= QUEUED_DELETION_DISTINCT_IDS_PER_BATCH:+ deleted_count += _run_batch_and_release(team_id, batch, batch_distinct_ids, failures, options)+ batch, batch_distinct_ids, batch_distinct_id_count = [], {}, 0+ if batch:+ deleted_count += _run_batch_and_release(team_id, batch, batch_distinct_ids, failures, options)++ if unmatched_distinct_ids:+ try:+ queue_person_training_deletion(team_id, unmatched_distinct_ids)+ except Exception as exc:+ _record_step_failure(+ failures, step=PersonDeletionStep.QUEUE_TRAINING_DELETION, team_id=team_id, exc=exc, person_uuids=[]+ )++ result = PersonProfileDeletionResult(deleted_count=deleted_count, failures=failures)+ _observe_person_outcomes("queued", result)+ return result+++def _run_batch_and_release(+ team_id: int,+ persons: builtins.list[Person],+ distinct_ids_by_person: dict[int, builtins.list[DistinctIdForPerson]],+ failures: builtins.list[PersonDeletionFailure],+ options: _QueuedDeletionOptions,+) -> int:+ deleted = _run_queued_deletion_steps(team_id, persons, distinct_ids_by_person, failures, options)+ # The resolved person objects outlive the batch, so drop their ID strings too; without this the+ # per-batch memory bound only covers the dataclass wrappers. Any later read raises, on purpose.+ for person in persons:+ person._distinct_ids = None+ return deleted+++# After this many consecutive per-person failures the fallback stops and marks the rest failed,+# so a systemic outage costs a handful of calls per attempt rather than one per person.+_TRAINING_DELETION_FALLBACK_FAILURE_LIMIT = 3+++def _queue_training_deletion_isolating_failures(+ team_id: int,+ persons: builtins.list[Person],+ failures: builtins.list[PersonDeletionFailure],+) -> builtins.list[Person]:+ """Queue training deletion for ``persons`` and return the ones it succeeded for.++ Each call scans replay events for the distinct IDs it is given, so the batch goes out as one+ flattened call. Only when that raises are the persons retried one at a time, which pins the+ failure on the person that causes it instead of blocking the whole batch.+ """+ try:+ queue_person_training_deletion(+ team_id, [distinct_id for person in persons for distinct_id in person.distinct_ids]+ )+ return persons+ except Exception:+ logger.warning(+ "person_deletion.training_deletion_batch_failed",+ team_id=team_id,+ person_count=len(persons),+ reason="retrying per person to isolate the failure",+ )++ queued: builtins.list[Person] = []+ consecutive_failures = 0+ for index, person in enumerate(persons):+ try:+ queue_person_training_deletion(team_id, person.distinct_ids)+ except Exception as exc:+ consecutive_failures += 1+ gave_up = consecutive_failures >= _TRAINING_DELETION_FALLBACK_FAILURE_LIMIT+ _record_step_failure(+ failures,+ step=PersonDeletionStep.QUEUE_TRAINING_DELETION,+ team_id=team_id,+ exc=exc,+ person_uuids=[p.uuid for p in (persons[index:] if gave_up else [person])],+ )+ if gave_up:+ break+ continue+ consecutive_failures = 0+ queued.append(person)+ return queued+++def _run_queued_deletion_steps(+ team_id: int,+ persons: builtins.list[Person],+ distinct_ids_by_person: dict[int, builtins.list[DistinctIdForPerson]],+ failures: builtins.list[PersonDeletionFailure],+ options: _QueuedDeletionOptions,+) -> int:+ """Run the requested steps for persons whose distinct IDs are loaded; returns how many were deleted.++ A person that fails a step is left out of every later step, so a retry redoes that person+ alone.+ """+ eligible = list(persons)+ if options.delete_profile or options.delete_recordings:+ eligible = _queue_training_deletion_isolating_failures(team_id, eligible, failures)+ if options.delete_recordings and eligible:+ try:+ queue_person_recording_deletion(team_id, eligible, actor=options.actor, queue_ai_training_deletion=False)+ except Exception as exc:+ _record_step_failure(+ failures,+ step=PersonDeletionStep.QUEUE_RECORDING_DELETION,+ team_id=team_id,+ exc=exc,+ person_uuids=[person.uuid for person in eligible],+ )+ eligible = []++ if not options.delete_profile or not eligible:+ return 0+ skipped = len(persons) - len(eligible)+ if skipped:+ logger.warning(+ "person_deletion.profile_delete_skipped",+ team_id=team_id,+ person_count=skipped,+ reason="a step before the profile delete failed; those persons stay for the retry",+ )++ result = _tombstone_and_delete_persons(+ team_id,+ eligible,+ lambda person: distinct_ids_by_person[person.pk],+ actor=options.actor,+ was_impersonated=options.was_impersonated,+ organization_id=options.organization_id,+ )+ failures.extend(result.failures)+ return result.deleted_count+++def _tombstone_and_delete_persons(+ team_id: int,+ persons: builtins.list[Person],+ distinct_ids_for: Callable[[Person], builtins.list[DistinctIdForPerson] | None],+ *,+ actor: User | None,+ was_impersonated: bool,+ organization_id: uuid_lib.UUID | None,+) -> PersonProfileDeletionResult:+ """Tombstone each person in ClickHouse, batch-delete the survivors from Postgres, then log the deletions.++ The activity log is written last so that a failed Postgres delete followed by a retry+ does not produce duplicate log rows (and the CDP events they fan out to). Logging needs+ an ``organization_id``; a missing ``actor`` (for example a user removed before a queued+ task ran) still records the deletion, with no user attached. A failed log write is+ recorded as its own step rather than raised: the persons are already gone by then, so+ raising would hide a completed deletion behind an error.+ """+ deleted: builtins.list[Person] = []+ failures: builtins.list[PersonDeletionFailure] = []+ for person in persons:+ try:+ delete_person(person=person, distinct_ids=distinct_ids_for(person))deleted.append(person)- except Exception:- logger.exception("Failed to delete person", person_uuid=str(person.uuid))- errors.append(person.uuid)-- if request is not None and organization_id is not None and actor is not None:- was_impersonated = is_impersonated(request)- bulk_log_activity(- [- LogActivityEntry(- organization_id=organization_id,+ except Exception as exc:+ _record_step_failure(+ failures,+ step=PersonDeletionStep.TOMBSTONE_CLICKHOUSE,+ team_id=team_id,+ exc=exc,+ person_uuids=[person.uuid],+ )++ if deleted:+ try:+ delete_persons_from_postgres(team_id, deleted)+ except Exception as exc:+ _record_step_failure(+ failures,+ step=PersonDeletionStep.DELETE_POSTGRES,+ team_id=team_id,+ exc=exc,+ person_uuids=[person.uuid for person in deleted],+ )+ deleted = []++ if organization_id is not None and deleted:+ try:+ # Person reads are eventually consistent, so a retry can resolve and delete a person+ # that an earlier attempt already removed. Skip persons that already have a deleted+ # entry so the audit trail does not record the same deletion twice.+ already_logged = set(+ ActivityLog.objects.filter(team_id=team_id,- user=cast(User, actor),- was_impersonated=was_impersonated,- item_id=person.pk,scope="Person",activity="deleted",- detail=Detail(name=str(person.uuid)),- )- for person in deleted- ]- )+ item_id__in=[str(person.pk) for person in deleted],+ ).values_list("item_id", flat=True)+ )+ bulk_log_activity(+ [+ LogActivityEntry(+ organization_id=organization_id,+ team_id=team_id,+ user=actor,+ was_impersonated=was_impersonated,+ item_id=person.pk,+ scope="Person",+ activity="deleted",+ detail=Detail(name=str(person.uuid)),+ )+ for person in deleted+ if str(person.pk) not in already_logged+ ]+ )+ except Exception as exc:+ _record_step_failure(+ failures,+ step=PersonDeletionStep.LOG_ACTIVITY,+ team_id=team_id,+ exc=exc,+ person_uuids=[person.uuid for person in deleted],+ )- if deleted:- delete_persons_from_postgres(team_id, deleted)- return PersonProfileDeletionResult(deleted_count=len(deleted), errors=errors)+ return PersonProfileDeletionResult(deleted_count=len(deleted), failures=failures)def queue_person_event_deletion(@@ -203,10 +599,7 @@ def _start_recording_workflows(async def start_all_workflows():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+ async def start_workflow(distinct_ids: builtins.list[str]) -> None: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:@@ -221,6 +614,14 @@ def _start_recording_workflows(),)- await asyncio.gather(*(start_batch(batch) for batch in _chunk_persons(persons)))+ # A single person can carry more distinct IDs than the per-workflow cap, so the batch's+ # distinct IDs are split again here rather than trusting the person-level chunking alone.+ starts = [+ start_workflow(distinct_ids[i : i + _MAX_DISTINCT_IDS_PER_WORKFLOW])+ for batch in _chunk_persons(persons)+ for distinct_ids in [sorted({distinct_id for person in batch for distinct_id in person.distinct_ids})]+ for i in range(0, len(distinct_ids), _MAX_DISTINCT_IDS_PER_WORKFLOW)+ ]+ await asyncio.gather(*starts)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 b58810575459..72b4017e4212 100644--- a/posthog/models/person/test/test_bulk_delete_helpers.py+++ b/posthog/models/person/test/test_bulk_delete_helpers.py@@ -1,17 +1,23 @@+from uuid import uuid4+from posthog.test.base import BaseTestfrom unittest.mock import AsyncMock, MagicMock, patchfrom parameterized import parameterized+from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.async_deletion import AsyncDeletion, DeletionTypefrom posthog.models.person import Personfrom posthog.models.person.bulk_delete import (+ PersonDeletionStep,_start_recording_workflows,delete_persons_profile,+ process_queued_person_deletion,queue_person_event_deletion,queue_person_recording_deletion,resolve_persons_for_deletion,)+from posthog.personhog_client.fake_client import get_active_fakefrom posthog.test.persons import create_person@@ -44,6 +50,14 @@ class ResolvePersonsTests(BaseTest):[resolved] = resolve_persons_for_deletion(self.team.pk, uuids=[str(p.uuid)], distinct_ids=None)assert sorted(resolved.distinct_ids) == ["a", "b"]+ def test_without_distinct_ids_keeps_only_the_requested_ids_that_matched(self):+ p = create_person(team=self.team, distinct_ids=["a", "b", "c"], properties={})+ [resolved] = resolve_persons_for_deletion(+ self.team.pk, uuids=None, distinct_ids=["a", "b", "ghost"], with_distinct_ids=False+ )+ assert resolved.uuid == p.uuid+ assert sorted(resolved.distinct_ids) == ["a", "b"]+def test_returns_empty_when_neither(self):assert resolve_persons_for_deletion(self.team.pk, uuids=None, distinct_ids=None) == []@@ -100,6 +114,49 @@ class DeletePersonsProfileTests(BaseTest):assert ch_delete.call_args.kwargs["distinct_ids"] is Nonepg_delete.assert_called_once_with(self.team.pk, [p])+ def test_reports_a_failed_postgres_delete_per_person_instead_of_raising(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.delete_person"),+ patch(+ "posthog.models.person.bulk_delete.delete_persons_from_postgres",+ side_effect=RuntimeError("personhog down"),+ ),+ ):+ result = delete_persons_profile(+ self.team.pk, [p1, p2], actor=self.user, organization_id=self.organization.id+ )+ assert result.deleted_count == 0+ assert [(f.step, f.person_uuid) for f in result.failures] == [+ (PersonDeletionStep.DELETE_POSTGRES, p1.uuid),+ (PersonDeletionStep.DELETE_POSTGRES, p2.uuid),+ ]+ assert result.errors == [p1.uuid, p2.uuid]+ assert not ActivityLog.objects.filter(team_id=self.team.pk, scope="Person").exists()++ def test_reports_a_failed_activity_log_write_per_person_and_keeps_the_deletion(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.delete_person"),+ patch("posthog.models.person.bulk_delete.delete_persons_from_postgres") as pg_delete,+ patch(+ "posthog.models.person.bulk_delete.bulk_log_activity",+ side_effect=RuntimeError("activity log down"),+ ),+ ):+ result = delete_persons_profile(+ self.team.pk, [p1, p2], actor=self.user, organization_id=self.organization.id+ )+ pg_delete.assert_called_once_with(self.team.pk, [p1, p2])+ assert result.deleted_count == 2+ assert [(f.step, f.person_uuid) for f in result.failures] == [+ (PersonDeletionStep.LOG_ACTIVITY, p1.uuid),+ (PersonDeletionStep.LOG_ACTIVITY, p2.uuid),+ ]+ assert result.errors == [p1.uuid, p2.uuid]+def test_collects_errors_and_skips_failed_persons_in_pg_batch(self):p1 = create_person(team=self.team, distinct_ids=["a"], properties={})p2 = create_person(team=self.team, distinct_ids=["b"], properties={})@@ -116,6 +173,346 @@ class DeletePersonsProfileTests(BaseTest):pg_delete.assert_called_once_with(self.team.pk, [p1])+class ProcessQueuedPersonDeletionTests(BaseTest):+ def test_walks_every_page_of_distinct_ids_and_logs_activity(self):+ p = create_person(team=self.team, distinct_ids=["a", "b", "c", "d", "e"], properties={})+ fake = get_active_fake()+ with (+ patch("posthog.models.person.bulk_delete.QUEUED_DELETION_DISTINCT_ID_PAGE_SIZE", 2),+ patch("posthog.models.person.bulk_delete.delete_person") as ch_delete,+ patch("posthog.models.person.bulk_delete.delete_persons_from_postgres") as pg_delete,+ ):+ result = process_queued_person_deletion(+ self.team.pk,+ [str(p.uuid)],+ delete_profile=True,+ delete_recordings=False,+ actor=self.user,+ was_impersonated=True,+ organization_id=self.organization.id,+ )+ assert result.deleted_count == 1+ assert result.errors == []+ assert sorted(d.id for d in ch_delete.call_args.kwargs["distinct_ids"]) == ["a", "b", "c", "d", "e"]+ assert fake is not None+ fake.assert_called("get_distinct_ids_for_person", times=3)+ pg_delete.assert_called_once()+ assert [person.uuid for person in pg_delete.call_args.args[1]] == [p.uuid]+ log = ActivityLog.objects.get(team_id=self.team.pk, scope="Person", item_id=str(p.pk))+ assert log.activity == "deleted"+ assert log.was_impersonated is True++ def test_does_not_log_a_deletion_twice_when_a_stale_read_resolves_the_person_again(self):+ p = create_person(team=self.team, distinct_ids=["a"], properties={})+ with (+ patch("posthog.models.person.bulk_delete.delete_person"),+ patch("posthog.models.person.bulk_delete.delete_persons_from_postgres"),+ ):+ for _attempt in range(2):+ process_queued_person_deletion(+ self.team.pk,+ [str(p.uuid)],+ delete_profile=True,+ delete_recordings=False,+ actor=self.user,+ was_impersonated=False,+ organization_id=self.organization.id,+ )+ assert ActivityLog.objects.filter(team_id=self.team.pk, scope="Person", item_id=str(p.pk)).count() == 1++ def test_logs_deletion_without_a_user_when_the_actor_is_gone(self):+ p = create_person(team=self.team, distinct_ids=["a"], properties={})+ with (+ patch("posthog.models.person.bulk_delete.delete_person"),+ patch("posthog.models.person.bulk_delete.delete_persons_from_postgres"),+ ):+ process_queued_person_deletion(+ self.team.pk,+ [str(p.uuid)],+ delete_profile=True,+ delete_recordings=False,+ actor=None,+ was_impersonated=False,+ organization_id=self.organization.id,+ )+ log = ActivityLog.objects.get(team_id=self.team.pk, scope="Person", item_id=str(p.pk))+ assert log.user is None++ def test_failed_postgres_delete_is_named_and_not_logged_as_deleted(self):+ p = create_person(team=self.team, distinct_ids=["a"], properties={})+ with (+ patch("posthog.models.person.bulk_delete.delete_person"),+ patch(+ "posthog.models.person.bulk_delete.delete_persons_from_postgres",+ side_effect=RuntimeError("personhog down"),+ ),+ ):+ result = process_queued_person_deletion(+ self.team.pk,+ [str(p.uuid)],+ delete_profile=True,+ delete_recordings=False,+ actor=self.user,+ was_impersonated=False,+ organization_id=self.organization.id,+ )+ assert result.deleted_count == 0+ assert [(f.step, f.person_uuid) for f in result.failures] == [(PersonDeletionStep.DELETE_POSTGRES, p.uuid)]+ assert not ActivityLog.objects.filter(team_id=self.team.pk, scope="Person").exists()++ def test_skips_persons_that_no_longer_exist(self):+ with (+ patch("posthog.models.person.bulk_delete.delete_person") as ch_delete,+ patch("posthog.models.person.bulk_delete.delete_persons_from_postgres") as pg_delete,+ ):+ result = process_queued_person_deletion(+ self.team.pk,+ [str(uuid4())],+ delete_profile=True,+ delete_recordings=False,+ actor=self.user,+ was_impersonated=False,+ organization_id=self.organization.id,+ )+ assert result.deleted_count == 0+ assert result.errors == []+ ch_delete.assert_not_called()+ pg_delete.assert_not_called()++ def test_failed_page_fetch_is_an_error_not_an_unbounded_fallback(self):+ p = create_person(team=self.team, distinct_ids=["a"], properties={})+ with (+ patch(+ "posthog.models.person.bulk_delete._paginated_get_distinct_ids_for_person",+ side_effect=RuntimeError("personhog down"),+ ),+ patch("posthog.models.person.bulk_delete.delete_person") as ch_delete,+ patch("posthog.models.person.bulk_delete.delete_persons_from_postgres") as pg_delete,+ ):+ result = process_queued_person_deletion(+ self.team.pk,+ [str(p.uuid)],+ delete_profile=True,+ delete_recordings=False,+ actor=self.user,+ was_impersonated=False,+ organization_id=self.organization.id,+ )+ assert result.deleted_count == 0+ assert [(f.step, f.person_uuid) for f in result.failures] == [(PersonDeletionStep.FETCH_DISTINCT_IDS, p.uuid)]+ assert "RuntimeError: personhog down" in result.failures[0].error+ ch_delete.assert_not_called()+ pg_delete.assert_not_called()++ def test_unmatched_distinct_ids_queue_training_deletion_and_fail_without_a_person(self):+ with patch(+ "posthog.models.person.bulk_delete.queue_person_training_deletion", side_effect=RuntimeError("down")+ ) as training:+ result = process_queued_person_deletion(+ self.team.pk,+ [],+ delete_profile=True,+ delete_recordings=False,+ actor=self.user,+ was_impersonated=False,+ organization_id=self.organization.id,+ unmatched_distinct_ids=["ghost"],+ )+ training.assert_called_once_with(self.team.pk, ["ghost"])+ assert [(f.step, f.person_uuid) for f in result.failures] == [+ (PersonDeletionStep.QUEUE_TRAINING_DELETION, None)+ ]++ def test_resolve_failure_is_recorded_for_every_requested_person(self):+ uuids = [uuid4(), uuid4()]+ with patch(+ "posthog.models.person.bulk_delete._fetch_persons_by_uuids_via_personhog",+ side_effect=RuntimeError("personhog down"),+ ):+ result = process_queued_person_deletion(+ self.team.pk,+ [str(u) for u in uuids],+ delete_profile=True,+ delete_recordings=False,+ actor=self.user,+ was_impersonated=False,+ organization_id=self.organization.id,+ )+ assert [(f.step, f.person_uuid) for f in result.failures] == [+ (PersonDeletionStep.RESOLVE_PERSONS, u) for u in uuids+ ]++ @parameterized.expand(+ [+ ("training", "queue_person_training_deletion", PersonDeletionStep.QUEUE_TRAINING_DELETION),+ ("recordings", "_start_recording_workflows", PersonDeletionStep.QUEUE_RECORDING_DELETION),+ ]+ )+ def test_failed_prerequisite_step_is_named_and_blocks_the_profile_delete(self, _name, target, step):+ p = create_person(team=self.team, distinct_ids=["a"], properties={})+ patches = {+ "queue_person_training_deletion": patch("posthog.models.person.bulk_delete.queue_person_training_deletion"),+ "_start_recording_workflows": patch("posthog.models.person.bulk_delete._start_recording_workflows"),+ }+ patches[target] = patch(f"posthog.models.person.bulk_delete.{target}", side_effect=RuntimeError("down"))+ with (+ patches["queue_person_training_deletion"],+ patches["_start_recording_workflows"],+ patch("posthog.models.person.bulk_delete.delete_person") as ch_delete,+ patch("posthog.models.person.bulk_delete.delete_persons_from_postgres") as pg_delete,+ ):+ result = process_queued_person_deletion(+ self.team.pk,+ [str(p.uuid)],+ delete_profile=True,+ delete_recordings=True,+ actor=self.user,+ was_impersonated=False,+ organization_id=self.organization.id,+ )+ assert result.deleted_count == 0+ assert [(f.step, f.person_uuid) for f in result.failures] == [(step, p.uuid)]+ ch_delete.assert_not_called()+ pg_delete.assert_not_called()++ def test_runs_the_steps_per_batch_once_the_distinct_id_cap_is_reached(self):+ p1 = create_person(team=self.team, distinct_ids=["a1", "a2", "a3"], properties={})+ p2 = create_person(team=self.team, distinct_ids=["b1", "b2", "b3"], properties={})+ p3 = create_person(team=self.team, distinct_ids=["c1"], properties={})+ with (+ patch("posthog.models.person.bulk_delete.QUEUED_DELETION_DISTINCT_IDS_PER_BATCH", 4),+ patch("posthog.models.person.bulk_delete.queue_person_training_deletion") as training,+ patch("posthog.models.person.bulk_delete.delete_person"),+ patch("posthog.models.person.bulk_delete.delete_persons_from_postgres") as pg_delete,+ ):+ result = process_queued_person_deletion(+ self.team.pk,+ [str(p1.uuid), str(p2.uuid), str(p3.uuid)],+ delete_profile=True,+ delete_recordings=False,+ actor=self.user,+ was_impersonated=False,+ organization_id=self.organization.id,+ )+ assert result.deleted_count == 3+ assert result.failures == []+ # p1 and p2 fill the cap together; p3 runs in a second, smaller batch. Training deletion is one call per batch.+ assert [[person.uuid for person in call.args[1]] for call in pg_delete.call_args_list] == [+ [p1.uuid, p2.uuid],+ [p3.uuid],+ ]+ assert [sorted(call.args[1]) for call in training.call_args_list] == [+ ["a1", "a2", "a3", "b1", "b2", "b3"],+ ["c1"],+ ]++ def test_releases_each_batch_of_distinct_id_strings_after_its_steps_run(self):+ p1 = create_person(team=self.team, distinct_ids=["a1", "a2"], properties={})+ p2 = create_person(team=self.team, distinct_ids=["b1"], properties={})+ seen: list[Person] = []++ def capture(_team_id, persons, *_args, **_kwargs):+ seen.extend(persons)+ return 0++ with patch("posthog.models.person.bulk_delete._run_queued_deletion_steps", side_effect=capture):+ process_queued_person_deletion(+ self.team.pk,+ [str(p1.uuid), str(p2.uuid)],+ delete_profile=True,+ delete_recordings=False,+ actor=self.user,+ was_impersonated=False,+ organization_id=self.organization.id,+ )+ assert {person.uuid for person in seen} == {p1.uuid, p2.uuid}+ assert all(person._distinct_ids is None for person in seen)++ def test_stops_isolating_training_failures_after_repeated_failures(self):+ persons = [create_person(team=self.team, distinct_ids=[f"d{i}"], properties={}) for i in range(5)]+ with (+ patch(+ "posthog.models.person.bulk_delete.queue_person_training_deletion", side_effect=RuntimeError("down")+ ) as training,+ patch("posthog.models.person.bulk_delete.delete_person") as ch_delete,+ patch("posthog.models.person.bulk_delete.delete_persons_from_postgres") as pg_delete,+ ):+ result = process_queued_person_deletion(+ self.team.pk,+ [str(p.uuid) for p in persons],+ delete_profile=True,+ delete_recordings=False,+ actor=self.user,+ was_impersonated=False,+ organization_id=self.organization.id,+ )+ # One flattened call, then per-person calls until the breaker trips; nobody is deleted.+ assert training.call_count == 1 + 3+ assert {f.person_uuid for f in result.failures} == {p.uuid for p in persons}+ assert {f.step for f in result.failures} == {PersonDeletionStep.QUEUE_TRAINING_DELETION}+ ch_delete.assert_not_called()+ pg_delete.assert_not_called()++ def test_failed_training_deletion_for_one_person_does_not_block_the_others(self):+ p1 = create_person(team=self.team, distinct_ids=["bad"], properties={})+ p2 = create_person(team=self.team, distinct_ids=["good"], properties={})++ def training(_team_id, distinct_ids):+ if "bad" in distinct_ids:+ raise RuntimeError("session lookup timed out")++ with (+ patch("posthog.models.person.bulk_delete.queue_person_training_deletion", side_effect=training),+ patch("posthog.models.person.bulk_delete.delete_person") as ch_delete,+ patch("posthog.models.person.bulk_delete.delete_persons_from_postgres") as pg_delete,+ ):+ result = process_queued_person_deletion(+ self.team.pk,+ [str(p1.uuid), str(p2.uuid)],+ delete_profile=True,+ delete_recordings=False,+ actor=self.user,+ was_impersonated=False,+ organization_id=self.organization.id,+ )+ assert result.deleted_count == 1+ assert [(f.step, f.person_uuid) for f in result.failures] == [+ (PersonDeletionStep.QUEUE_TRAINING_DELETION, p1.uuid)+ ]+ assert ch_delete.call_args.kwargs["person"].uuid == p2.uuid+ assert [person.uuid for person in pg_delete.call_args.args[1]] == [p2.uuid]++ def test_recordings_only_pages_distinct_ids_into_workflows_without_deleting(self):+ p = create_person(team=self.team, distinct_ids=["a", "b", "c"], properties={})+ # Snapshot at call time: the processor releases each person's IDs once its batch has run.+ started: list[list[str]] = []+ with (+ patch("posthog.models.person.bulk_delete.QUEUED_DELETION_DISTINCT_ID_PAGE_SIZE", 2),+ patch("posthog.models.person.bulk_delete.queue_person_training_deletion") as training,+ patch(+ "posthog.models.person.bulk_delete._start_recording_workflows",+ side_effect=lambda _t, persons, *_a: started.extend(sorted(p.distinct_ids) for p in persons),+ ),+ patch("posthog.models.person.bulk_delete.delete_person") as ch_delete,+ patch("posthog.models.person.bulk_delete.delete_persons_from_postgres") as pg_delete,+ ):+ result = process_queued_person_deletion(+ self.team.pk,+ [str(p.uuid)],+ delete_profile=False,+ delete_recordings=True,+ actor=self.user,+ was_impersonated=False,+ organization_id=self.organization.id,+ )+ assert result.deleted_count == 0+ assert result.errors == []+ assert sorted(training.call_args.args[1]) == ["a", "b", "c"]+ assert started == [["a", "b", "c"]]+ ch_delete.assert_not_called()+ pg_delete.assert_not_called()++class QueueRecordingDeletionTests(BaseTest):def test_skips_when_no_persons(self):with patch("posthog.models.person.bulk_delete.sync_connect") as conn:@@ -166,8 +563,9 @@ class QueueRecordingDeletionTests(BaseTest):@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),+ ("single_person_over_cap_is_split", [5, 1], 4, 3),+ ("wide_person_splits_into_capped_workflows", [9], 4, 3),+ ("every_distinct_id_own_workflow_when_cap_tiny", [2, 2], 1, 4),])def test_chunks_by_distinct_id_count(self, _name, distinct_id_counts, cap, expected_workflows):diff --git a/posthog/models/person/util.py b/posthog/models/person/util.pyindex e28f136700b4..6c2d4df71ecb 100644--- a/posthog/models/person/util.py+++ b/posthog/models/person/util.py@@ -343,6 +343,23 @@ def create_person_distinct_id(def _fetch_persons_by_distinct_ids_via_personhog(team_id: int, distinct_ids: list[str], *, distinct_id_limit: int | None = None) -> list[Person]:+ # distinct_id_limit=0 skips the per-person distinct-id fetch, like the UUID variant. Each person+ # then carries only the requested distinct IDs that resolved to it, which the lookup RPC already+ # returns, so a caller can tell which requested IDs matched no person at all.+ if distinct_id_limit == 0:+ matched_results = _batched_get_persons_by_distinct_ids(+ team_id, distinct_ids, "get_persons_by_distinct_ids", deduplicate_by_person=False+ )+ matched_by_person: dict[int, list[str]] = {}+ person_by_id: dict[int, person_pb2.Person] = {}+ for r in matched_results:+ person_by_id.setdefault(r.person.id, r.person)+ matched_by_person.setdefault(r.person.id, []).append(r.distinct_id)+ return [+ proto_person_to_model(person, distinct_ids=matched_by_person[person_id])+ for person_id, person in person_by_id.items()+ ]+valid_results = _batched_get_persons_by_distinct_ids(team_id, distinct_ids, "get_persons_by_distinct_ids")person_ids = [r.person.id for r in valid_results]diff --git a/posthog/settings/__init__.py b/posthog/settings/__init__.pyindex 6d37692da373..3b761a2b3672 100644--- a/posthog/settings/__init__.py+++ b/posthog/settings/__init__.py@@ -130,6 +130,10 @@ PERSON_ON_EVENTS_OVERRIDE: bool = get_from_env("PERSON_ON_EVENTS_OVERRIDE", opti# Only written in specific scripts - do not use outside of them.PERSON_ON_EVENTS_V2_OVERRIDE: bool = get_from_env("PERSON_ON_EVENTS_V2_OVERRIDE", optional=True, type_cast=str_to_bool)+# When on, the person bulk delete API hands profile deletion to a Celery task that pages through+# each person's distinct IDs, instead of tombstoning them inline in the request.+PERSON_BULK_DELETE_ASYNC: bool = get_from_env("PERSON_BULK_DELETE_ASYNC", False, type_cast=str_to_bool)+# Events data retention enforcement override (ops kill switch / local + test toggle). When unset (None),# enforcement falls back to the per-project `events-data-retention` cohort flag. When set, forces it on/off everywhere.EVENTS_DATA_RETENTION_ENFORCED: bool | None = get_from_env(diff --git a/posthog/tasks/delete_persons.py b/posthog/tasks/delete_persons.pynew file mode 100644index 000000000000..5839edfc92f5--- /dev/null+++ b/posthog/tasks/delete_persons.py@@ -0,0 +1,178 @@+import uuid as uuid_lib+from collections import Counter+from collections.abc import Iterator++from django.http import HttpRequest++import structlog+from celery import Task, shared_task++from posthog.helpers.impersonation import is_impersonated+from posthog.models.person import Person+from posthog.models.person.bulk_delete import (+ PERSON_DELETION_PERSONS_COUNTER,+ PersonDeletionStep,+ process_queued_person_deletion,+)+from posthog.models.user import User+from posthog.scoping_audit import skip_team_scope_audit+from posthog.tasks.utils import CeleryQueue++logger = structlog.get_logger(__name__)++# Small chunks keep a retry cheap: only the chunk holding a failing person is re-run.+PERSONS_PER_DELETION_TASK = 100+++class PersonDeletionIncomplete(Exception):+ """Raised once the failed persons of a chunk have used up their retries."""+++# Retries per chunk. Failed persons are retried through Celery's retry with the person list+# narrowed to them, never by re-running the original chunk: with the person kept, every person+# still resolves on a retry, so a chunk-wide re-run would start new recording workflows and+# training deletion for persons that already succeeded.+MAX_DELETION_RETRIES = 3+RETRY_BACKOFF_SECONDS = 60+RETRY_BACKOFF_MAX_SECONDS = 600+++def _retry_countdown(retries: int) -> int:+ return min(RETRY_BACKOFF_SECONDS * 2**retries, RETRY_BACKOFF_MAX_SECONDS)+++def _chunks(items: list[str], size: int) -> Iterator[list[str]]:+ for i in range(0, len(items), size):+ yield items[i : i + size]+++def queue_person_deletion(+ team_id: int,+ persons: list[Person],+ *,+ delete_profile: bool,+ delete_recordings: bool,+ actor: User | None,+ request: HttpRequest | None,+ organization_id: uuid_lib.UUID | None,+ unmatched_distinct_ids: list[str] | None = None,+) -> int:+ """Enqueue the distinct-ID-dependent deletion steps for ``persons``; returns how many were queued.++ ``unmatched_distinct_ids`` ride on the first chunk so their replay session lookup runs in the+ task rather than in the request. They are sent even when no person resolved.+ """+ if not (delete_profile or delete_recordings):+ return 0+ uuids = [str(person.uuid) for person in persons]+ PERSON_DELETION_PERSONS_COUNTER.labels(path="queued", outcome="queued").inc(len(uuids))+ chunks = list(_chunks(uuids, PERSONS_PER_DELETION_TASK)) or ([[]] if unmatched_distinct_ids else [])+ was_impersonated = is_impersonated(request)+ for index, chunk in enumerate(chunks):+ delete_persons_async.delay(+ team_id=team_id,+ person_uuids=chunk,+ delete_profile=delete_profile,+ delete_recordings=delete_recordings,+ actor_id=actor.pk if actor is not None else None,+ organization_id=str(organization_id) if organization_id is not None else None,+ was_impersonated=was_impersonated,+ unmatched_distinct_ids=list(unmatched_distinct_ids or []) if index == 0 else [],+ )+ return len(uuids)+++# Late ack plus reject-on-worker-lost redeliver the chunk when a worker restarts or is killed+# mid-run, instead of dropping a deletion the API already reported as queued. Redelivery is safe+# because every step is idempotent and deleted persons no longer resolve. There is deliberately no+# autoretry: a retry always goes through self.retry below, so a failed retry publish is rejected+# rather than re-running the original chunk.+@shared_task(+ bind=True,+ ignore_result=True,+ queue=CeleryQueue.LONG_RUNNING.value,+ acks_late=True,+ reject_on_worker_lost=True,+ max_retries=MAX_DELETION_RETRIES,+)+@skip_team_scope_audit+def delete_persons_async(+ self: Task,+ team_id: int,+ person_uuids: list[str],+ delete_profile: bool,+ delete_recordings: bool,+ actor_id: int | None,+ organization_id: str | None,+ was_impersonated: bool,+ unmatched_distinct_ids: list[str] | None = None,+) -> None:+ unmatched_distinct_ids = unmatched_distinct_ids or []+ retries = self.request.retries+ logger.info(+ "delete_persons_async started",+ team_id=team_id,+ person_count=len(person_uuids),+ unmatched_distinct_id_count=len(unmatched_distinct_ids),+ delete_profile=delete_profile,+ delete_recordings=delete_recordings,+ retries=retries,+ )+ try:+ actor = User.objects.filter(pk=actor_id).first() if actor_id is not None else None+ result = process_queued_person_deletion(+ team_id,+ person_uuids,+ delete_profile=delete_profile,+ delete_recordings=delete_recordings,+ actor=actor,+ was_impersonated=was_impersonated,+ organization_id=uuid_lib.UUID(organization_id) if organization_id else None,+ unmatched_distinct_ids=unmatched_distinct_ids,+ )+ except Exception as exc:+ # Nothing per person was recorded, so the same arguments go round again.+ logger.exception("delete_persons_async crashed", team_id=team_id, retries=retries)+ raise self.retry(exc=exc, countdown=_retry_countdown(retries))++ logger.info(+ "delete_persons_async finished",+ team_id=team_id,+ deleted_count=result.deleted_count,+ error_count=len(result.errors),+ retries=retries,+ )+ if not result.failures:+ return++ failures_by_step = Counter(failure.step.value for failure in result.failures)+ failed_uuids = [str(u) for u in result.errors]+ # A training failure with no person is the unmatched distinct IDs; they come back on the retry.+ unmatched_failed = any(+ f.step is PersonDeletionStep.QUEUE_TRAINING_DELETION and f.person_uuid is None for f in result.failures+ )+ summary = ", ".join(f"{step}={count}" for step, count in failures_by_step.items())+ logger.warning(+ "delete_persons_async retrying failed persons",+ team_id=team_id,+ retries=retries,+ failures_by_step=dict(failures_by_step),+ failed_person_uuids=failed_uuids[:20],+ )+ # Past max_retries this raises the exception given here instead of scheduling another run.+ raise self.retry(+ kwargs={+ "team_id": team_id,+ "person_uuids": failed_uuids,+ "delete_profile": delete_profile,+ "delete_recordings": delete_recordings,+ "actor_id": actor_id,+ "organization_id": organization_id,+ "was_impersonated": was_impersonated,+ "unmatched_distinct_ids": unmatched_distinct_ids if unmatched_failed else [],+ },+ countdown=_retry_countdown(retries),+ exc=PersonDeletionIncomplete(+ f"team {team_id}: {len(failed_uuids)} persons failed after {retries + 1} attempts ({summary})"+ ),+ )diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex 0af23a8fee64..2dcf4c114656 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -25,6 +25,7 @@'posthog.tasks.comment_slack_sync.backfill_comment_slack_thread','posthog.tasks.comment_slack_sync.ingest_slack_discussion_reply','posthog.tasks.comment_slack_sync.mirror_comment_reply_to_slack',+ 'posthog.tasks.delete_persons.delete_persons_async','posthog.tasks.demo_create_data.create_data_for_demo_team','posthog.tasks.early_access_feature.create_waitlist_survey_for_concept_feature','posthog.tasks.early_access_feature.send_events_for_early_access_feature_stage_change',diff --git a/posthog/tasks/test/test_delete_persons.py b/posthog/tasks/test/test_delete_persons.pynew file mode 100644index 000000000000..878dfadb44ff--- /dev/null+++ b/posthog/tasks/test/test_delete_persons.py@@ -0,0 +1,152 @@+from uuid import uuid4++from unittest.mock import patch++from django.test import SimpleTestCase++from celery.exceptions import Retry+from parameterized import parameterized++from posthog.models.person import Person+from posthog.models.person.bulk_delete import PersonDeletionFailure, PersonDeletionStep, PersonProfileDeletionResult+from posthog.tasks.delete_persons import PersonDeletionIncomplete, delete_persons_async, queue_person_deletion+++def _person() -> Person:+ return Person(uuid=uuid4(), team_id=1)+++class TestQueuePersonDeletion(SimpleTestCase):+ def test_splits_persons_across_tasks(self) -> None:+ persons = [_person() for _ in range(3)]+ with (+ patch("posthog.tasks.delete_persons.PERSONS_PER_DELETION_TASK", 2),+ patch("posthog.tasks.delete_persons.delete_persons_async.delay") as delay,+ ):+ queued = queue_person_deletion(+ 1,+ persons,+ delete_profile=True,+ delete_recordings=False,+ actor=None,+ request=None,+ organization_id=None,+ unmatched_distinct_ids=["ghost"],+ )+ assert queued == 3+ assert [len(call.kwargs["person_uuids"]) for call in delay.call_args_list] == [2, 1]+ assert [uuid for call in delay.call_args_list for uuid in call.kwargs["person_uuids"]] == [+ str(p.uuid) for p in persons+ ]+ # Unmatched distinct IDs ride on the first chunk only.+ assert [call.kwargs["unmatched_distinct_ids"] for call in delay.call_args_list] == [["ghost"], []]++ def test_queues_a_task_for_unmatched_distinct_ids_when_no_person_resolved(self) -> None:+ with patch("posthog.tasks.delete_persons.delete_persons_async.delay") as delay:+ queued = queue_person_deletion(+ 1,+ [],+ delete_profile=True,+ delete_recordings=False,+ actor=None,+ request=None,+ organization_id=None,+ unmatched_distinct_ids=["ghost"],+ )+ assert queued == 0+ delay.assert_called_once()+ assert delay.call_args.kwargs["person_uuids"] == []+ assert delay.call_args.kwargs["unmatched_distinct_ids"] == ["ghost"]++ @parameterized.expand(+ [+ ("no_persons", [], True, True),+ ("nothing_to_do", [_person()], False, False),+ ]+ )+ def test_queues_nothing_when_there_is_no_work(+ self, _name: str, persons: list[Person], delete_profile: bool, delete_recordings: bool+ ) -> None:+ with patch("posthog.tasks.delete_persons.delete_persons_async.delay") as delay:+ queued = queue_person_deletion(+ 1,+ persons,+ delete_profile=delete_profile,+ delete_recordings=delete_recordings,+ actor=None,+ request=None,+ organization_id=None,+ )+ assert queued == 0+ delay.assert_not_called()+++class TestDeletePersonsAsync(SimpleTestCase):+ def _run(self, result: PersonProfileDeletionResult | Exception) -> None:+ with patch(+ "posthog.tasks.delete_persons.process_queued_person_deletion",+ side_effect=result if isinstance(result, Exception) else None,+ return_value=None if isinstance(result, Exception) else result,+ ):+ delete_persons_async.run(+ team_id=1,+ person_uuids=["a", "b"],+ delete_profile=False,+ delete_recordings=True,+ actor_id=None,+ organization_id="00000000-0000-0000-0000-00000000000a",+ was_impersonated=True,+ unmatched_distinct_ids=["ghost"],+ )++ def test_retries_only_the_failed_persons(self) -> None:+ failed = uuid4()+ result = PersonProfileDeletionResult(+ deleted_count=0,+ failures=[+ PersonDeletionFailure(+ step=PersonDeletionStep.QUEUE_TRAINING_DELETION, person_uuid=failed, error="RuntimeError: x"+ )+ ],+ )+ with patch.object(delete_persons_async, "retry", side_effect=Retry("retry")) as retry:+ with self.assertRaises(Retry):+ self._run(result)+ kwargs = retry.call_args.kwargs["kwargs"]+ assert kwargs["person_uuids"] == [str(failed)]+ assert kwargs["delete_recordings"] is True+ assert kwargs["organization_id"] == "00000000-0000-0000-0000-00000000000a"+ assert kwargs["was_impersonated"] is True+ assert kwargs["unmatched_distinct_ids"] == []+ assert retry.call_args.kwargs["countdown"] == 60+ assert isinstance(retry.call_args.kwargs["exc"], PersonDeletionIncomplete)+ assert "queue_training_deletion=1" in str(retry.call_args.kwargs["exc"])++ def test_retries_the_unmatched_distinct_ids_when_their_training_step_failed(self) -> None:+ result = PersonProfileDeletionResult(+ deleted_count=0,+ failures=[+ PersonDeletionFailure(+ step=PersonDeletionStep.QUEUE_TRAINING_DELETION, person_uuid=None, error="RuntimeError: x"+ )+ ],+ )+ with patch.object(delete_persons_async, "retry", side_effect=Retry("retry")) as retry:+ with self.assertRaises(Retry):+ self._run(result)+ kwargs = retry.call_args.kwargs["kwargs"]+ assert kwargs["person_uuids"] == []+ assert kwargs["unmatched_distinct_ids"] == ["ghost"]++ def test_retries_the_whole_chunk_when_the_task_crashes_before_recording_anything(self) -> None:+ crash = RuntimeError("database down")+ with patch.object(delete_persons_async, "retry", side_effect=Retry("retry")) as retry:+ with self.assertRaises(Retry):+ self._run(crash)+ assert retry.call_args.kwargs["exc"] is crash+ assert "kwargs" not in retry.call_args.kwargs++ def test_completes_quietly_when_all_deleted(self) -> None:+ with patch.object(delete_persons_async, "retry") as retry:+ self._run(PersonProfileDeletionResult(deleted_count=2))+ retry.assert_not_called()diff --git a/products/ai_training/backend/tests/test_deletion.py b/products/ai_training/backend/tests/test_deletion.pyindex a9249ecbe35a..7ebec4b5e9c6 100644--- a/products/ai_training/backend/tests/test_deletion.py+++ b/products/ai_training/backend/tests/test_deletion.py@@ -31,7 +31,7 @@ class TestAITrainingDeletionOutbox(TestCase):) -> None:person = Person(id=1, uuid=UUID("00000000-0000-0000-0000-000000000007"))person._distinct_ids = ["known", "alias"]- view = MagicMock(team_id=7)+ view = MagicMock(team_id=7, organization=MagicMock(id=UUID("00000000-0000-0000-0000-00000000000a")))request = MagicMock(user=None)temporal = MagicMock()temporal.start_workflow = AsyncMock()diff --git a/products/persons/frontend/generated/api.schemas.ts b/products/persons/frontend/generated/api.schemas.tsindex 7356c0bd4c39..5cfea23c2815 100644--- a/products/persons/frontend/generated/api.schemas.ts+++ b/products/persons/frontend/generated/api.schemas.ts@@ -317,13 +317,15 @@ export type PersonBulkDeleteResponseApiDeletionErrorsItem = { [key: string]: unkexport interface PersonBulkDeleteResponseApi {/** Number of persons matched by the provided IDs or distinct IDs. */persons_found: number- /** Number of person records deleted from the database. 0 if keep_person was true. */+ /** Number of person records deleted from the database during this request. 0 if keep_person was true or if the deletion was queued (see persons_queued_for_deletion). */persons_deleted: number+ /** Number of persons queued for deletion in the background. Their person records and distinct IDs are removed shortly after the request completes. 0 if keep_person was true. */+ persons_queued_for_deletion: number/** Whether event deletion was requested for the matched persons. If a deletion was already queued for a person, it will not be duplicated. */events_queued_for_deletion: boolean/** Whether recording deletion was requested for the matched persons. If a deletion was already queued for a person, it will not be duplicated. */recordings_queued_for_deletion: boolean- /** Persons that could not be deleted. Each entry contains 'person_uuid'. Contact support if this persists. */+ /** Persons whose deletion did not fully complete in this request. Each entry contains 'person_uuid' and 'step', the deletion step that failed for that person. A failed database delete is reported here rather than as an error response, so a 202 with entries means some or all persons were not deleted. A 'log_activity' step means the person was deleted but the activity log entry was not written. Always empty when the deletion was queued (see persons_queued_for_deletion). Contact support if this persists. */deletion_errors?: PersonBulkDeleteResponseApiDeletionErrorsItem[]}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 34a49fcfb810..a224b9b8061b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -74186,13 +74186,15 @@ export namespace Schemas {export interface PersonBulkDeleteResponse {/** Number of persons matched by the provided IDs or distinct IDs. */persons_found: number;- /** Number of person records deleted from the database. 0 if keep_person was true. */+ /** Number of person records deleted from the database during this request. 0 if keep_person was true or if the deletion was queued (see persons_queued_for_deletion). */persons_deleted: number;+ /** Number of persons queued for deletion in the background. Their person records and distinct IDs are removed shortly after the request completes. 0 if keep_person was true. */+ persons_queued_for_deletion: number;/** Whether event deletion was requested for the matched persons. If a deletion was already queued for a person, it will not be duplicated. */events_queued_for_deletion: boolean;/** Whether recording deletion was requested for the matched persons. If a deletion was already queued for a person, it will not be duplicated. */recordings_queued_for_deletion: boolean;- /** Persons that could not be deleted. Each entry contains 'person_uuid'. Contact support if this persists. */+ /** Persons whose deletion did not fully complete in this request. Each entry contains 'person_uuid' and 'step', the deletion step that failed for that person. A failed database delete is reported here rather than as an error response, so a 202 with entries means some or all persons were not deleted. A 'log_activity' step means the person was deleted but the activity log entry was not written. Always empty when the deletion was queued (see persons_queued_for_deletion). Contact support if this persists. */deletion_errors?: PersonBulkDeleteResponseDeletionErrorsItem[];}