: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): add a command to requeue person deletions that gave up (#117447)
Eli Reismanc31360281663
diff --git a/posthog/management/commands/person_deletion.py b/posthog/management/commands/person_deletion.pynew file mode 100644index 000000000000..f0c2d55cbc83--- /dev/null+++ b/posthog/management/commands/person_deletion.py@@ -0,0 +1,107 @@+"""Queue person deletions that gave up again.++Usage:+ # Export the task's give-up lines as JSONL, then queue their still-live persons (dry run without --apply):+ python manage.py person_deletion requeue --input gave_up.jsonl --apply+ python manage.py person_deletion requeue --team-id 2 --person-uuid <uuid> --gave-up-at 2026-10-19T12:00:00+00:00++The last attempt of `delete_persons_async` logs "delete_persons_async gave up" with every person it left+undeleted, in the fields this command reads: {team_id, person_uuids, delete_profile, delete_recordings,+gave_up_at}. `requeue` queues through the same path as the persons API. It skips persons that no longer+resolve, and persons deleted after `gave_up_at`, which new events have since revived. The line's unmatched+distinct ids only feed the AI training deletion, so this command does not queue them.+"""++import json+import time+from datetime import datetime+from pathlib import Path+from typing import Any++from django.core.management.base import BaseCommand, CommandError, CommandParser++from posthog.models.person.deletion_requeue import PendingDeletion, requeue_deletions+++class Command(BaseCommand):+ help = "Queue person deletions that gave up again (dry run unless --apply)."++ def add_arguments(self, parser: CommandParser) -> None:+ actions = parser.add_subparsers(dest="action", required=True, metavar="action")+ requeue = actions.add_parser("requeue", help="DRY RUN unless --apply. Queue still-live persons again.")+ requeue.add_argument("--input", type=Path, default=None, help="JSONL of give-up log lines.")+ requeue.add_argument("--team-id", type=int, default=None, help="With --person-uuid, a deletion given inline.")+ requeue.add_argument("--person-uuid", action="append", default=[], help="Person to delete. Repeatable.")+ requeue.add_argument(+ "--gave-up-at",+ type=datetime.fromisoformat,+ default=None,+ help="With --team-id: skip persons deleted after this time, because new events revived them.",+ )+ requeue.add_argument(+ "--recordings-only",+ action="store_true",+ help="Delete only the persons' recordings, and keep their profiles.",+ )+ requeue.add_argument("--apply", action="store_true", help="Queue. Without it the command only reports.")++ def _log(self, message: str) -> None:+ self.stdout.write(f"{time.strftime('%H:%M:%S')} {message}")+ self.stdout.flush()++ def handle(self, *args: Any, **options: Any) -> None:+ deletions = self._read_deletions(options)+ unguarded = sum(1 for d in deletions if d.gave_up_at is None)+ if unguarded:+ self._log(f"{unguarded} deletions have no gave_up_at, so revived persons in them are not detected")+ mode = "APPLY" if options["apply"] else "DRY RUN"+ results = requeue_deletions(+ deletions,+ apply=options["apply"],+ recordings_only=options["recordings_only"],+ on_result=lambda r: self._log(+ f"team {r.team_id}: {r.outcome}, {r.live}/{r.requested} persons to delete, {r.revived} revived, "+ f"profile {r.delete_profile}, recordings {r.delete_recordings}"+ ),+ )+ queued = sum(r.live for r in results if r.outcome in ("queued", "would_queue"))+ self._log(f"requeue {mode}: {len(results)} deletions, {queued} live persons")+ if not options["apply"]:+ self._log("Dry run: nothing was queued. Pass --apply to queue.")++ @staticmethod+ def _read_deletions(options: dict[str, Any]) -> list[PendingDeletion]:+ if (options["input"] is None) == (options["team_id"] is None):+ raise CommandError("Pass either --input or --team-id with --person-uuid")+ if options["team_id"] is not None:+ if not options["person_uuid"]:+ raise CommandError("--team-id needs at least one --person-uuid")+ return [+ PendingDeletion(+ team_id=options["team_id"],+ person_uuids=options["person_uuid"],+ delete_profile=True,+ delete_recordings=True,+ source="command_line",+ gave_up_at=options["gave_up_at"],+ )+ ]+ deletions = []+ with options["input"].open() as handle:+ for line_number, line in enumerate(handle, start=1):+ try:+ row = json.loads(line)+ gave_up_at = row.get("gave_up_at")+ deletions.append(+ PendingDeletion(+ team_id=int(row["team_id"]),+ person_uuids=[str(u) for u in row["person_uuids"]],+ delete_profile=bool(row.get("delete_profile", True)),+ delete_recordings=bool(row.get("delete_recordings", True)),+ source=str(row.get("source", "input")),+ gave_up_at=datetime.fromisoformat(gave_up_at) if gave_up_at else None,+ )+ )+ except (KeyError, TypeError, ValueError) as exc:+ raise CommandError(f"{options['input']}:{line_number}: {exc}") from exc+ return deletionsdiff --git a/posthog/models/person/bulk_delete.py b/posthog/models/person/bulk_delete.pyindex 833046b22320..155ac2b2cf88 100644--- a/posthog/models/person/bulk_delete.py+++ b/posthog/models/person/bulk_delete.py@@ -8,6 +8,7 @@ from enum import StrEnumfrom typing import castfrom django.conf import settings+from django.utils import timezoneimport structlogfrom prometheus_client import Counter, Histogram@@ -234,6 +235,10 @@ QUEUED_DELETION_DISTINCT_IDS_PER_BATCH = 20_000# Below the replica's cap of 2,500 distinct IDs per person, so a person that returns this many may have more.TOMBSTONE_DISTINCT_ID_PREFETCH_LIMIT = 100+# A retried or redelivered deletion task finishes within an hour, so an older "deleted" entry is an earlier+# deletion of a revived person, and this deletion gets its own entry.+DELETION_LOG_DEDUPE_WINDOW = timedelta(hours=24)+def tombstone_and_publish_persons_by_uuids(team_id: int, person_uuids: builtins.list[str]) -> int:"""Like tombstone_and_publish_persons, but read distinct IDs in batches, page heavy persons, and bound each RPC."""@@ -522,7 +527,7 @@ def _tombstone_and_delete_persons(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+ # that an earlier attempt already removed. Skip persons that already have a recent deleted# entry so the audit trail does not record the same deletion twice.already_logged = set(ActivityLog.objects.filter(@@ -530,6 +535,7 @@ def _tombstone_and_delete_persons(scope="Person",activity="deleted",item_id__in=[str(person.pk) for person in deleted],+ created_at__gte=timezone.now() - DELETION_LOG_DEDUPE_WINDOW,).values_list("item_id", flat=True))bulk_log_activity(diff --git a/posthog/models/person/deletion_requeue.py b/posthog/models/person/deletion_requeue.pynew file mode 100644index 000000000000..44052af11c78--- /dev/null+++ b/posthog/models/person/deletion_requeue.py@@ -0,0 +1,114 @@+"""Queue person deletions that gave up again, through the path the API uses."""++from __future__ import annotations++from collections.abc import Callable, Sequence+from datetime import datetime+from typing import Literal++from posthog.dataclasses import frozen+from posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.person import Person+from posthog.models.person.util import get_persons_by_uuids+from posthog.models.team import Team+from posthog.tasks.delete_persons import queue_person_deletion++RequeueOutcome = Literal["would_queue", "queued", "skipped_team_gone", "skipped_not_live", "skipped_revived"]+++@frozen+class PendingDeletion:+ team_id: int+ person_uuids: list[str]+ delete_profile: bool+ delete_recordings: bool+ source: str+ # When the deletion gave up. A person deleted after it and live again was revived by new events.+ gave_up_at: datetime | None = None+++@frozen+class RequeueResult:+ team_id: int+ requested: int+ live: int+ revived: int+ outcome: RequeueOutcome+ delete_profile: bool+ delete_recordings: bool+++def requeue_deletions(+ deletions: Sequence[PendingDeletion],+ *,+ apply: bool,+ recordings_only: bool = False,+ on_result: Callable[[RequeueResult], None] = lambda _: None,+) -> list[RequeueResult]:+ """Queue each deletion's still-live persons again, with the same flags unless `recordings_only` is set.++ Only live persons are queued: a person whose profile is already deleted no longer resolves. A live person+ that was deleted after `gave_up_at` came back through new events, so it is left alone rather than+ deleted along with the data recorded since.+ """+ results: list[RequeueResult] = []+ organizations = dict(+ Team.objects.filter(id__in={d.team_id for d in deletions}).values_list("id", "organization_id")+ )+ for deletion in deletions:+ delete_profile = False if recordings_only else deletion.delete_profile+ delete_recordings = True if recordings_only else deletion.delete_recordings+ organization_id = organizations.get(deletion.team_id)+ live = (+ get_persons_by_uuids(deletion.team_id, deletion.person_uuids, distinct_id_limit=0)+ if organization_id+ else []+ )+ revived = _deleted_since(deletion.team_id, live, deletion.gave_up_at)+ pending = [p for p in live if str(p.pk) not in revived]+ if organization_id is None:+ outcome: RequeueOutcome = "skipped_team_gone"+ elif not live:+ outcome = "skipped_not_live"+ elif not pending:+ outcome = "skipped_revived"+ elif not apply:+ outcome = "would_queue"+ else:+ queue_person_deletion(+ deletion.team_id,+ pending,+ delete_profile=delete_profile,+ delete_recordings=delete_recordings,+ actor=None,+ request=None,+ organization_id=organization_id,+ )+ outcome = "queued"+ result = RequeueResult(+ team_id=deletion.team_id,+ requested=len(deletion.person_uuids),+ live=len(pending),+ revived=len(live) - len(pending),+ outcome=outcome,+ delete_profile=delete_profile,+ delete_recordings=delete_recordings,+ )+ on_result(result)+ results.append(result)+ return results+++def _deleted_since(team_id: int, persons: list[Person], since: datetime | None) -> set[str]:+ """Primary keys of the persons with a deletion logged after `since`. The deletion path writes that entry+ only once a tombstone landed, and revival reuses the person's row, so the entry marks a revived person."""+ if since is None or not persons:+ return set()+ item_ids = ActivityLog.objects.filter(+ team_id=team_id,+ scope="Person",+ activity="deleted",+ item_id__in=[str(p.pk) for p in persons],+ created_at__gt=since,+ ).values_list("item_id", flat=True)+ return {item_id for item_id in item_ids if item_id is not None}diff --git a/posthog/models/person/test/test_bulk_delete_helpers.py b/posthog/models/person/test/test_bulk_delete_helpers.pyindex 3205c20fbb76..f7d1028724ea 100644--- a/posthog/models/person/test/test_bulk_delete_helpers.py+++ b/posthog/models/person/test/test_bulk_delete_helpers.py@@ -1,9 +1,12 @@import contextlib+from datetime import timedeltafrom uuid import uuid4from posthog.test.base import BaseTestfrom unittest.mock import AsyncMock, MagicMock, patch+from django.utils import timezone+from confluent_kafka import KafkaErrorfrom parameterized import parameterizedfrom prometheus_client import REGISTRY@@ -341,6 +344,34 @@ class ProcessQueuedPersonDeletionTests(BaseTest):)assert ActivityLog.objects.filter(team_id=self.team.pk, scope="Person", item_id=str(p.pk)).count() == 1+ @parameterized.expand(+ [+ ("a_retry_of_a_recent_deletion", timedelta(hours=1), 1),+ ("a_new_deletion_of_a_revived_person", timedelta(hours=25), 2),+ ]+ )+ def test_logs_a_deletion_once_per_deletion_of_the_person(self, _name: str, earlier_by: timedelta, logged: int):+ p = create_person(team=self.team, distinct_ids=["a"], properties={})+ ActivityLog.objects.create(+ team_id=self.team.pk,+ organization_id=self.organization.id,+ scope="Person",+ activity="deleted",+ item_id=str(p.pk),+ created_at=timezone.now() - earlier_by,+ )+ with _no_publish():+ 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() == logged+def test_logs_deletion_without_a_user_when_the_actor_is_gone(self):p = create_person(team=self.team, distinct_ids=["a"], properties={})with _no_publish():diff --git a/posthog/models/person/test/test_deletion_requeue.py b/posthog/models/person/test/test_deletion_requeue.pynew file mode 100644index 000000000000..317bc66cd24b--- /dev/null+++ b/posthog/models/person/test/test_deletion_requeue.py@@ -0,0 +1,88 @@+from datetime import UTC, datetime, timedelta+from uuid import uuid4++from posthog.test.base import BaseTest+from unittest.mock import patch++from parameterized import parameterized++from posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.person.deletion_requeue import PendingDeletion, requeue_deletions+from posthog.test.persons import create_person++_DELAY = "posthog.tasks.delete_persons.delete_persons_async.delay"+_GAVE_UP_AT = datetime(2026, 10, 19, 12, 0, tzinfo=UTC)+++class TestRequeueDeletions(BaseTest):+ def _deletion(self, team_id: int, uuids: list[str], gave_up_at: datetime | None = None) -> PendingDeletion:+ return PendingDeletion(+ team_id=team_id,+ person_uuids=uuids,+ delete_profile=True,+ delete_recordings=False,+ source="test",+ gave_up_at=gave_up_at,+ )++ @parameterized.expand(+ [+ ("dry_run", False, False, "would_queue", None),+ ("apply", True, False, "queued", (True, False)),+ ("recordings_only", True, True, "queued", (False, True)),+ ]+ )+ def test_queues_only_live_persons_with_the_requested_steps(self, _name, apply, recordings_only, outcome, flags):+ live = create_person(team=self.team, distinct_ids=["live-1"])+ gone = str(uuid4())++ with patch(_DELAY) as delay:+ results = requeue_deletions(+ [self._deletion(self.team.pk, [str(live.uuid), gone])], apply=apply, recordings_only=recordings_only+ )++ assert [(r.outcome, r.requested, r.live) for r in results] == [(outcome, 2, 1)]+ if flags is None:+ delay.assert_not_called()+ else:+ kwargs = delay.call_args.kwargs+ assert kwargs["person_uuids"] == [str(live.uuid)]+ assert (kwargs["delete_profile"], kwargs["delete_recordings"]) == flags++ @parameterized.expand(+ [+ ("deleted_after_the_give_up", timedelta(hours=1), True, "skipped_revived"),+ ("deleted_before_the_give_up", timedelta(hours=-1), True, "queued"),+ ("no_give_up_time", timedelta(hours=1), False, "queued"),+ ]+ )+ def test_leaves_alone_a_person_that_new_events_revived_after_the_give_up(+ self, _name: str, deleted_offset: timedelta, with_gave_up_at: bool, outcome: str+ ):+ person = create_person(team=self.team, distinct_ids=["returning"])+ ActivityLog.objects.create(+ team_id=self.team.pk,+ organization_id=self.organization.pk,+ scope="Person",+ activity="deleted",+ item_id=str(person.pk),+ created_at=_GAVE_UP_AT + deleted_offset,+ )++ with patch(_DELAY) as delay:+ results = requeue_deletions(+ [self._deletion(self.team.pk, [str(person.uuid)], _GAVE_UP_AT if with_gave_up_at else None)],+ apply=True,+ )++ assert [r.outcome for r in results] == [outcome]+ assert delay.called is (outcome == "queued")++ def test_skips_deletions_with_nothing_left_to_queue(self):+ with patch(_DELAY) as delay:+ results = requeue_deletions(+ [self._deletion(self.team.pk, [str(uuid4())]), self._deletion(999_999_999, [str(uuid4())])], apply=True+ )++ delay.assert_not_called()+ assert [r.outcome for r in results] == ["skipped_not_live", "skipped_team_gone"]diff --git a/posthog/tasks/delete_persons.py b/posthog/tasks/delete_persons.pyindex 777dd1ceaee4..3fdac976f837 100644--- a/posthog/tasks/delete_persons.py+++ b/posthog/tasks/delete_persons.py@@ -1,6 +1,7 @@import uuid as uuid_libfrom collections import Counterfrom collections.abc import Iterator+from datetime import UTC, datetimefrom django.http import HttpRequest@@ -33,6 +34,7 @@ class PersonDeletionIncomplete(Exception):# 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+GAVE_UP_LOGGED_DISTINCT_IDS = 1000RETRY_BACKOFF_SECONDS = 60RETRY_BACKOFF_MAX_SECONDS = 600@@ -41,6 +43,32 @@ def _retry_countdown(retries: int) -> int:return min(RETRY_BACKOFF_SECONDS * 2**retries, RETRY_BACKOFF_MAX_SECONDS)+def _log_if_giving_up(+ retries: int,+ team_id: int,+ person_uuids: list[str],+ delete_profile: bool,+ delete_recordings: bool,+ unmatched_distinct_ids: list[str],+) -> None:+ # The last attempt names every person it leaves undeleted, in the fields `person_deletion requeue` reads,+ # because nothing else records which persons a given-up deletion left behind. Unmatched distinct ids only+ # feed the AI training deletion, so they are logged for its owners and requeue does not read them.+ if retries < MAX_DELETION_RETRIES:+ return+ logger.error(+ "delete_persons_async gave up",+ team_id=team_id,+ person_uuids=person_uuids,+ delete_profile=delete_profile,+ delete_recordings=delete_recordings,+ gave_up_at=datetime.now(UTC).isoformat(),+ unmatched_distinct_ids=unmatched_distinct_ids[:GAVE_UP_LOGGED_DISTINCT_IDS],+ unmatched_distinct_id_count=len(unmatched_distinct_ids),+ retries=retries,+ )++def _chunks(items: list[str], size: int) -> Iterator[list[str]]:for i in range(0, len(items), size):yield items[i : i + size]@@ -133,6 +161,7 @@ def delete_persons_async(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)+ _log_if_giving_up(retries, team_id, person_uuids, delete_profile, delete_recordings, unmatched_distinct_ids)raise self.retry(exc=exc, countdown=_retry_countdown(retries))logger.info(@@ -169,6 +198,14 @@ def delete_persons_async(failures_by_step=dict(failures_by_step),failed_person_uuids=failed_uuids[:20],)+ _log_if_giving_up(+ retries,+ team_id,+ failed_uuids,+ delete_profile,+ delete_recordings,+ unmatched_distinct_ids if unmatched_failed else [],+ )# Past max_retries this raises the exception given here instead of scheduling another run.raise self.retry(kwargs={diff --git a/posthog/tasks/test/test_delete_persons.py b/posthog/tasks/test/test_delete_persons.pyindex dd3ce5f414e5..92a818e5a5a9 100644--- a/posthog/tasks/test/test_delete_persons.py+++ b/posthog/tasks/test/test_delete_persons.py@@ -1,4 +1,5 @@-from uuid import uuid4+from datetime import datetime+from uuid import UUID, uuid4from unittest.mock import patch@@ -150,6 +151,45 @@ class TestDeletePersonsAsync(SimpleTestCase):assert retry.call_args.kwargs["exc"] is crashassert "kwargs" not in retry.call_args.kwargs+ @parameterized.expand(+ [+ ("crash_on_an_earlier_attempt", 2, "crash", None, None),+ ("crash_on_the_last_attempt", 3, "crash", ["a", "b"], ["ghost"]),+ ("failures_on_the_last_attempt", 3, "failures", ["00000000-0000-0000-0000-000000000001"], []),+ ]+ )+ def test_the_last_attempt_logs_every_person_it_leaves_undeleted(+ self, _name: str, retries: int, how: str, expected: list[str] | None, unmatched: list[str] | None+ ) -> None:+ failed = PersonProfileDeletionResult(+ deleted_count=1,+ failures=[+ PersonDeletionFailure(+ step=PersonDeletionStep.QUEUE_TRAINING_DELETION,+ person_uuid=UUID("00000000-0000-0000-0000-000000000001"),+ error="x",+ )+ ],+ )+ delete_persons_async.push_request(retries=retries)+ self.addCleanup(delete_persons_async.pop_request)+ with (+ patch.object(delete_persons_async, "retry", side_effect=Retry("retry")),+ patch("posthog.tasks.delete_persons.logger") as log,+ ):+ with self.assertRaises(Retry):+ self._run(RuntimeError("database down") if how == "crash" else failed)++ gave_up = [c for c in log.error.call_args_list if c.args == ("delete_persons_async gave up",)]+ if expected is None:+ assert gave_up == []+ else:+ assert len(gave_up) == 1+ assert gave_up[0].kwargs["person_uuids"] == expected+ assert (gave_up[0].kwargs["team_id"], gave_up[0].kwargs["delete_recordings"]) == (1, True)+ assert datetime.fromisoformat(gave_up[0].kwargs["gave_up_at"]).tzinfo is not None+ assert gave_up[0].kwargs["unmatched_distinct_ids"] == unmatched+@parameterized.expand([("all_deleted", PersonProfileDeletionResult(deleted_count=2)),