Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(persons): publish clickhouse tombstones at the versions the replica wrote (#102725)

Nick Best045da381e79d
diff --git a/posthog/api/person.py b/posthog/api/person.py
index ae5c2ed7a9e5..43cc07b67a6d 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -305,8 +305,9 @@ class PersonBulkDeleteResponseSerializer(serializers.Serializer):
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. Failures are reported here rather than as an "
"error status, so a 202 with entries means those persons were not deleted and the request should be "
- "retried for them, except entries whose step is 'log_activity': that person was deleted, but the "
- "activity log entry was not written. "
+ "retried for them. Two steps are exceptions, and retrying won't find these persons. For 'log_activity', "
+ "the person was deleted, but the activity log entry was not written. For 'publish_clickhouse_tombstone', "
+ "the person was deleted, but it can still show in analytics until a weekly cleanup job removes it. "
"Always empty when the deletion was queued (see persons_queued_for_deletion). "
"Contact support if this persists.",
)
diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.py
index b0f701ffe22d..9ecd4b1a00be 100644
--- a/posthog/api/test/test_person.py
+++ b/posthog/api/test/test_person.py
@@ -36,6 +36,7 @@ from posthog.constants import AvailableFeature
from posthog.hogql_queries.serialized_actors import get_serialized_people
from posthog.models import Organization, Person, PropertyDefinition, Team
from posthog.models.async_deletion import AsyncDeletion, DeletionType
+from posthog.models.person.bulk_delete import PersonDeletionFailure, PersonDeletionStep, PersonProfileDeletionResult
from posthog.models.person.missing_person import uuidFromDistinctId
from posthog.models.person.sql import PERSON_DISTINCT_ID2_TABLE
from posthog.models.person.util import (
@@ -760,6 +761,23 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(data["code"], "person_deletion_failed")
self.assertIn("delete_postgres", data["detail"])
+ @parameterized.expand(
+ [
+ ("publish_failed", PersonDeletionStep.PUBLISH_CLICKHOUSE_TOMBSTONE, 1, status.HTTP_202_ACCEPTED),
+ ("tombstone_call_failed", PersonDeletionStep.TOMBSTONE_POSTGRES, 0, 503),
+ ]
+ )
+ def test_delete_person_fails_only_when_the_tombstone_did_not_land(self, _name, failed_step, deleted, expected):
+ person = _create_person(team=self.team, distinct_ids=["person_1"], immediate=True)
+ failures = [PersonDeletionFailure(step=failed_step, person_uuid=person.uuid, error="down")]
+ with mock.patch(
+ "posthog.api.person.delete_persons_profile",
+ return_value=PersonProfileDeletionResult(deleted_count=deleted, failures=failures),
+ ):
+ response = self.client.delete(f"/api/person/{person.uuid}/")
+
+ self.assertEqual(response.status_code, expected)
+
@time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_delete_person_and_events(self):
person = _create_person(
diff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.py
index a51027aa9a73..46fc86e839b4 100644
--- a/posthog/dags/data_deletion_requests.py
+++ b/posthog/dags/data_deletion_requests.py
@@ -1542,8 +1542,10 @@ def delete_person_profiles_op(
`POST /api/projects/:id/persons/bulk_delete/` endpoint and avoids flipping the whole
request 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.
+ The one exception is the batch Postgres delete or tombstone: when it fails, those persons are
+ still live in Postgres, so the op raises and the request finalizes as FAILED for a retry. A
+ failed ClickHouse publish after a Postgres tombstone does not raise, because the person is
+ deleted and the weekly deletion sweep republishes it.
"""
if not person_removal.drop_profiles:
context.log.info("drop_profiles=False, skipping profile deletion")
@@ -1564,12 +1566,13 @@ def delete_person_profiles_op(
"errors": dagster.MetadataValue.int(len(result.errors)),
}
if result.errors:
- context.log.warning(
- f"Person profile deletion had {len(result.errors)} per-person failures; "
- f"Postgres rows remain for failed UUIDs and can be retried via a follow-up request"
- )
+ context.log.warning(f"Person profile deletion had {len(result.errors)} per-person failures")
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]
+ postgres_failures = [
+ f
+ for f in result.failures
+ if f.step in (PersonDeletionStep.DELETE_POSTGRES, PersonDeletionStep.TOMBSTONE_POSTGRES)
+ ]
if postgres_failures:
raise dagster.Failure(
description=(
diff --git a/posthog/dags/tests/test_data_deletion_requests.py b/posthog/dags/tests/test_data_deletion_requests.py
index ebb69b092c20..cc6141aa17c8 100644
--- a/posthog/dags/tests/test_data_deletion_requests.py
+++ b/posthog/dags/tests/test_data_deletion_requests.py
@@ -2792,6 +2792,38 @@ def test_property_removal_where_omits_event_filter_when_delete_all_events():
assert "events" not in params
+ "failed_step,raises",
+ [
+ (PersonDeletionStep.TOMBSTONE_POSTGRES, True),
+ (PersonDeletionStep.PUBLISH_CLICKHOUSE_TOMBSTONE, False),
+ ],
+)
+def test_delete_person_profiles_op_raises_only_when_the_person_is_still_live(failed_step, raises):
+ 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,
+ )
+ with patch("posthog.dags.data_deletion_requests.delete_persons_profile") as deleter:
+ deleter.return_value = PersonProfileDeletionResult(
+ deleted_count=0 if raises else 1,
+ failures=[PersonDeletionFailure(step=failed_step, person_uuid=UUID(p_uuid), error="down")],
+ )
+ if raises:
+ with pytest.raises(dagster.Failure, match="Postgres delete failed for 1 persons"):
+ delete_person_profiles_op(build_op_context(), ctx)
+ else:
+ assert delete_person_profiles_op(build_op_context(), ctx) is ctx
+
+
@pytest.mark.parametrize(
"document,prop,expected",
[
diff --git a/posthog/kafka_client/client.py b/posthog/kafka_client/client.py
index 9a421dba85e4..fd7d75228ebf 100644
--- a/posthog/kafka_client/client.py
+++ b/posthog/kafka_client/client.py
@@ -77,7 +77,7 @@ def _log_delivery_failure(topic: str, error_name: str, msg: Optional[Message]) -
)
-@dataclass
+@dataclass(frozen=False)
class ProduceResult:
"""
A Future-like wrapper for confluent-kafka delivery results.
@@ -95,6 +95,9 @@ class ProduceResult:
self._message = message
self._event.set()
+ def done(self) -> bool:
+ return self._event.is_set()
+
def get(self, timeout: Optional[float] = None) -> Optional[Message]:
"""
Wait for the produce to complete and return the result.
@@ -476,11 +479,13 @@ class ClickhouseProducer:
can target the cluster mapped in TOPIC_ROUTING.
"""
- def produce(self, sql: str, topic: str, data: dict[str, Any]):
+ def produce(self, sql: str, topic: str, data: dict[str, Any]) -> ProduceResult:
if settings.TEST:
sync_execute(sql, data)
- return
+ result = ProduceResult(topic=topic)
+ result.set_result(None, None)
+ return result
# Lazy import: routing imports from this module.
from posthog.kafka_client.routing import get_producer
- get_producer(topic=topic).produce(topic=topic, data=data)
+ return get_producer(topic=topic).produce(topic=topic, data=data)
diff --git a/posthog/management/commands/fix_orphaned_ch_persons.py b/posthog/management/commands/fix_orphaned_ch_persons.py
index 732ed90b5e8f..c6230dc659a3 100644
--- a/posthog/management/commands/fix_orphaned_ch_persons.py
+++ b/posthog/management/commands/fix_orphaned_ch_persons.py
@@ -99,6 +99,7 @@ def _log_result(team_id: int, result: OrphanRepairResult) -> None:
dry_run=result.dry_run,
orphaned_persons=len(result.orphaned_person_uuids),
tombstoned_persons=result.tombstoned_persons,
+ republished_persons=result.republished_persons,
tombstoned_mappings=result.tombstoned_mappings,
skipped_reassigned_mappings=result.skipped_reassigned_mappings,
reverse_drift_mappings=len(result.reverse_drift_mappings),
diff --git a/posthog/models/person/bulk_delete.py b/posthog/models/person/bulk_delete.py
index 78be1f9b4347..5783e1e000c4 100644
--- a/posthog/models/person/bulk_delete.py
+++ b/posthog/models/person/bulk_delete.py
@@ -20,12 +20,16 @@ from posthog.models.async_deletion import AsyncDeletion, DeletionType
from posthog.models.person import Person
from posthog.models.person.util import (
DistinctIdForPerson,
+ PersonTombstone,
+ PersonTombstonePublication,
_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,
+ get_person_tombstones,
+ tombstone_persons_in_postgres,
)
from posthog.models.user import User
from posthog.temporal.common.client import sync_connect
@@ -37,7 +41,12 @@ logger = structlog.get_logger(__name__)
class PersonDeletionStep(StrEnum):
- """The steps of a person deletion, in the order they run. Each failure names exactly one."""
+ """The steps of a person deletion, in the order they run. Each failure names exactly one.
+
+ TOMBSTONE_CLICKHOUSE and DELETE_POSTGRES belong to the order without PERSON_DELETE_TOMBSTONE,
+ and TOMBSTONE_POSTGRES and PUBLISH_CLICKHOUSE_TOMBSTONE to the order with it. Each value has
+ one meaning, so a consumer can act on a failure without reading the setting.
+ """
RESOLVE_PERSONS = "resolve_persons"
FETCH_DISTINCT_IDS = "fetch_distinct_ids"
@@ -45,9 +54,16 @@ class PersonDeletionStep(StrEnum):
QUEUE_RECORDING_DELETION = "queue_recording_deletion"
TOMBSTONE_CLICKHOUSE = "tombstone_clickhouse"
DELETE_POSTGRES = "delete_postgres"
+ TOMBSTONE_POSTGRES = "tombstone_postgres"
+ PUBLISH_CLICKHOUSE_TOMBSTONE = "publish_clickhouse_tombstone"
LOG_ACTIVITY = "log_activity"
+# Steps that run after the person's profile is deleted. A retry cannot resolve the person again,
+# so a failure here is reported but never retried.
+STEPS_AFTER_DELETION = frozenset({PersonDeletionStep.PUBLISH_CLICKHOUSE_TOMBSTONE, PersonDeletionStep.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.",
@@ -90,8 +106,17 @@ class PersonProfileDeletionResult:
@property
def errors(self) -> list[uuid_lib.UUID]:
"""Distinct UUIDs of persons that failed at any step, in first-failure order."""
+ return self._person_uuids(self.failures)
+
+ @property
+ def retryable_errors(self) -> list[uuid_lib.UUID]:
+ """Distinct UUIDs of persons that failed before their profile was deleted, so a retry can still find them."""
+ return self._person_uuids(f for f in self.failures if f.step not in STEPS_AFTER_DELETION)
+
+ @staticmethod
+ def _person_uuids(failures: Iterable[PersonDeletionFailure]) -> list[uuid_lib.UUID]:
seen: dict[uuid_lib.UUID, None] = {}
- for failure in self.failures:
+ for failure in failures:
if failure.person_uuid is not None:
seen.setdefault(failure.person_uuid, None)
return list(seen)
@@ -105,16 +130,17 @@ def _record_step_failure(
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."""
+ """Record one step failure with its traceback."""
uuids = list(person_uuids) or [None]
PERSON_DELETION_STEP_FAILURES_COUNTER.labels(step=step.value).inc()
- logger.exception(
+ logger.error(
"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__,
+ exc_info=exc,
)
error = f"{type(exc).__name__}: {exc}"
failures.extend(PersonDeletionFailure(step=step, person_uuid=u, error=error) for u in uuids)
@@ -171,17 +197,20 @@ def delete_persons_profile(
queue_person_training_deletion(
team_id, [distinct_id for person in persons for distinct_id in person.distinct_ids]
)
- # 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]] = {}
- try:
- distinct_ids_by_person = personhog_call(
- "get_distinct_ids_for_deletion",
- lambda: _batched_get_distinct_ids_for_persons(team_id, [person.pk for person in persons]),
- caller_tag="persons/deletion-distinct-ids",
- )
- except Exception:
- logger.exception("Batched distinct-id fetch failed, falling back to per-person lookups")
+ # The tombstone path gets the distinct IDs and their versions back from personhog, and it
+ # sizes its calls from the distinct IDs the resolve loaded, so only delete_person needs these.
+ if not settings.PERSON_DELETE_TOMBSTONE:
+ # 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.
+ try:
+ distinct_ids_by_person = personhog_call(
+ "get_distinct_ids_for_deletion",
+ lambda: _batched_get_distinct_ids_for_persons(team_id, [person.pk for person in persons]),
+ caller_tag="persons/deletion-distinct-ids",
+ )
+ except Exception:
+ logger.exception("Batched distinct-id fetch failed, falling back to per-person lookups")
result = _tombstone_and_delete_persons(
team_id,
@@ -440,7 +469,11 @@ def _tombstone_and_delete_persons(
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.
+ """Delete each person from Postgres and ClickHouse, then log the deletions.
+
+ Under ``PERSON_DELETE_TOMBSTONE`` the Postgres rows are tombstoned first and ClickHouse
+ gets tombstones at the versions the replica wrote. Otherwise ClickHouse is tombstoned at
+ version + 100 first and the survivors are hard-deleted from Postgres.
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
@@ -449,33 +482,11 @@ def _tombstone_and_delete_persons(
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 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 settings.PERSON_DELETE_TOMBSTONE:
+ deleted = _tombstone_persons_at_exact_versions(team_id, persons, failures)
+ else:
+ deleted = _tombstone_then_hard_delete_persons(team_id, persons, distinct_ids_for, failures)
if organization_id is not None and deleted:
try:
@@ -518,6 +529,146 @@ def _tombstone_and_delete_persons(
return PersonProfileDeletionResult(deleted_count=len(deleted), failures=failures)
+def _tombstone_then_hard_delete_persons(
+ team_id: int,
+ persons: builtins.list[Person],
+ distinct_ids_for: Callable[[Person], builtins.list[DistinctIdForPerson] | None],
+ failures: builtins.list[PersonDeletionFailure],
+) -> builtins.list[Person]:
+ """ClickHouse tombstones at version + 100 first, then one hard delete of the survivors.
+
+ ClickHouse goes first so a person whose tombstones failed keeps its Postgres row for the
+ retry.
+ """
+ deleted: builtins.list[Person] = []
+ for person in persons:
+ try:
+ delete_person(person=person, distinct_ids=distinct_ids_for(person))
+ deleted.append(person)
+ except Exception as exc:
+ _record_step_failure(
+ failures,
+ step=PersonDeletionStep.TOMBSTONE_CLICKHOUSE,
+ team_id=team_id,
+ exc=exc,
+ person_uuids=[person.uuid],
+ )
+ if not deleted:
+ return []
+ 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],
+ )
+ return []
+ return deleted
+
+
+def _tombstone_persons_at_exact_versions(
+ team_id: int,
+ persons: builtins.list[Person],
+ failures: builtins.list[PersonDeletionFailure],
+) -> builtins.list[Person]:
+ """Tombstone Postgres first, then publish ClickHouse tombstones at the versions it wrote.
+
+ Postgres goes first because only the replica knows the versions. A person whose Postgres
+ tombstone landed is deleted, so it is counted and logged even when the ClickHouse publish
+ fails; that failure gets its own step and the weekly deletion sweep republishes it.
+ """
+ deleted: builtins.list[Person] = []
+ person_by_uuid = {person.uuid: person for person in persons}
+ publication = PersonTombstonePublication(team_id=team_id)
+
+ for batch in _batches_by_distinct_id_count(persons):
+ uuids = [person.uuid for person in batch]
+ try:
+ tombstones = tombstone_persons_in_postgres(team_id, uuids)
+ except Exception as exc:
+ tombstones = _committed_tombstones(team_id, uuids, exc, failures)
+ to_publish = [
+ (tombstone, person_by_uuid[tombstone.uuid].created_at)
+ for tombstone in tombstones
+ if tombstone.uuid in person_by_uuid
+ ]
+ deleted.extend(person_by_uuid[tombstone.uuid] for tombstone, _ in to_publish)
+ publication.publish(to_publish)
+
+ publication.await_and_ack()
+ for failure in publication.failures:
+ _record_step_failure(
+ failures,
+ step=PersonDeletionStep.PUBLISH_CLICKHOUSE_TOMBSTONE,
+ team_id=team_id,
+ exc=failure.error,
+ person_uuids=[failure.person_uuid],
+ )
+ return deleted
+
+
+class PersonTombstoneStateUnknown(Exception):
+ """The tombstone RPC failed, and so did the check for what it committed before failing."""
+
+
+def _committed_tombstones(
+ team_id: int,
+ person_uuids: builtins.list[uuid_lib.UUID],
+ exc: Exception,
+ failures: builtins.list[PersonDeletionFailure],
+) -> builtins.list[PersonTombstone]:
+ """Return the tombstones a failed RPC committed, and record every other person as a failure.
+
+ When the check itself fails, every person in the batch is recorded, under an error that
+ says the state is unknown rather than still live: a person the RPC did commit is deleted
+ and queued for the weekly sweep, but not counted or logged here.
+ """
+ try:
+ stored = get_person_tombstones(team_id, person_uuids)
+ except Exception as check_exc:
+ logger.warning(
+ "person_deletion.committed_tombstone_check_failed",
+ team_id=team_id,
+ person_count=len(person_uuids),
+ exc_info=True,
+ )
+ stored = []
+ exc = PersonTombstoneStateUnknown(
+ f"{type(exc).__name__}: {exc}; the committed-tombstone check failed too: "
+ f"{type(check_exc).__name__}: {check_exc}"
+ )
+ committed = {tombstone.uuid for tombstone in stored}
+ uncommitted = [u for u in person_uuids if u not in committed]
+ if uncommitted:
+ _record_step_failure(
+ failures, step=PersonDeletionStep.TOMBSTONE_POSTGRES, team_id=team_id, exc=exc, person_uuids=uncommitted
+ )
+ return stored
+
+
+def _batches_by_distinct_id_count(persons: builtins.list[Person]) -> Iterator[builtins.list[Person]]:
+ """Group persons so one RPC carries at most QUEUED_DELETION_DISTINCT_IDS_PER_BATCH distinct IDs.
+
+ Every caller resolves persons with their distinct IDs loaded, and Person.distinct_ids raises
+ when they are not, so a person never counts as narrower than it is. A single person wider than
+ the budget goes alone.
+ """
+ batch: builtins.list[Person] = []
+ count = 0
+ for person in persons:
+ width = len(person.distinct_ids)
+ if batch and count + width > QUEUED_DELETION_DISTINCT_IDS_PER_BATCH:
+ yield batch
+ batch, count = [], 0
+ batch.append(person)
+ count += width
+ if batch:
+ yield batch
+
+
def queue_person_event_deletion(
team_id: int,
persons: builtins.list[Person],
diff --git a/posthog/models/person/deletion.py b/posthog/models/person/deletion.py
index 49974d63e217..fb18e2feed07 100644
--- a/posthog/models/person/deletion.py
+++ b/posthog/models/person/deletion.py
@@ -1,13 +1,21 @@
import datetime as dt
from dataclasses import dataclass, field
from typing import Optional
+from uuid import UUID
import structlog
from rest_framework.exceptions import NotFound
from posthog.clickhouse.client import sync_execute
from posthog.models.person import Person
-from posthog.models.person.util import create_person, create_person_distinct_id, get_persons_by_uuids
+from posthog.models.person.util import (
+ PersonTombstone,
+ PersonTombstonePublication,
+ create_person,
+ create_person_distinct_id,
+ get_person_tombstones,
+ get_persons_by_uuids,
+)
logger = structlog.get_logger(__name__)
@@ -223,10 +231,12 @@ class _Mapping:
max_version: int
-@dataclass
+@dataclass(frozen=False)
class OrphanRepairResult:
orphaned_person_uuids: list[str]
tombstoned_persons: int = 0
+ # Orphans that are tombstoned in the persons DB, republished at the versions it holds.
+ republished_persons: int = 0
tombstoned_mappings: int = 0
# distinct_id now won by a different, non-deleted CH mapping — left untouched
# so the repair never resurrects-then-deletes a mapping that has been reassigned.
@@ -271,6 +281,14 @@ def tombstone_orphaned_ch_persons(
and is not already deleted. Mappings reassigned to another live person are
skipped; mappings whose deleted winner is live in the persons DB are reported
as reverse drift (not touched).
+
+ Persons DB reads skip tombstoned rows, so a person that a deletion tombstoned in the
+ persons DB without publishing to ClickHouse also looks like an orphan. Such a person is
+ republished at the versions the persons DB holds instead of version + 100. A version
+ + 100 tombstone would stay above the version that a later revival writes, so the
+ revived person would stay hidden in ClickHouse. The lookup is read-only because the
+ orphan read is eventually consistent: a live person can be reported as an orphan, and
+ it must not be tombstoned in the persons DB for that.
"""
result = OrphanRepairResult(orphaned_person_uuids=sorted(o.uuid for o in orphans), dry_run=dry_run)
if not orphans:
@@ -289,12 +307,24 @@ def tombstone_orphaned_ch_persons(
result.reverse_drift_mappings = _find_reverse_drift(team_id, deleted_winners, orphan_uuids)
+ # Raises rather than falling back to version + 100 for every orphan.
+ stored = get_person_tombstones(team_id, [UUID(o.uuid) for o in orphans])
+ stored_by_uuid = {str(t.uuid): t for t in stored}
+
if dry_run:
- result.tombstoned_persons = len(orphans)
- result.tombstoned_mappings = len(to_tombstone)
+ result.republished_persons = sum(1 for o in orphans if o.uuid in stored_by_uuid)
+ result.tombstoned_persons = len(orphans) - result.republished_persons
+ result.tombstoned_mappings = sum(1 for m in to_tombstone if m.winner_person_id not in stored_by_uuid)
return result
+ republished: set[str] = set()
+ to_republish: list[tuple[PersonTombstone, Optional[dt.datetime]]] = []
for orphan in orphans:
+ tombstone = stored_by_uuid.get(orphan.uuid)
+ if tombstone is not None:
+ to_republish.append((tombstone, orphan.created_at))
+ republished.add(orphan.uuid)
+ continue
# No persons-DB row exists, so derive the tombstone from ClickHouse. Version
# + 100 makes the delete win over normal updates; stays below split's + 101.
create_person(
@@ -306,7 +336,14 @@ def tombstone_orphaned_ch_persons(
)
result.tombstoned_persons += 1
+ publication = PersonTombstonePublication(team_id=team_id)
+ publication.publish(to_republish)
+ result.republished_persons = len(to_republish)
+
for mapping in to_tombstone:
+ if mapping.winner_person_id in republished:
+ # The republish already produced this distinct ID at the stored version.
+ continue
create_person_distinct_id(
team_id=team_id,
distinct_id=mapping.distinct_id,
@@ -316,6 +353,11 @@ def tombstone_orphaned_ch_persons(
)
result.tombstoned_mappings += 1
+ # Wait only after the mapping rows are produced. A rerun skips a person whose version + 100
+ # row already landed, so a raise before this loop would leave its mappings live for good.
+ publication.await_and_ack()
+ if publication.failures:
+ raise publication.failures[0].error
return result
diff --git a/posthog/models/person/test/test_bulk_delete_helpers.py b/posthog/models/person/test/test_bulk_delete_helpers.py
index 72b4017e4212..b95bc1104dc4 100644
--- a/posthog/models/person/test/test_bulk_delete_helpers.py
+++ b/posthog/models/person/test/test_bulk_delete_helpers.py
@@ -1,10 +1,15 @@
+import contextlib
from uuid import uuid4
from posthog.test.base import BaseTest
from unittest.mock import AsyncMock, MagicMock, patch
+from django.test import override_settings
+
+from confluent_kafka import KafkaError
from parameterized import parameterized
+from posthog.kafka_client.client import ProduceResult
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.async_deletion import AsyncDeletion, DeletionType
from posthog.models.person import Person
@@ -17,7 +22,9 @@ from posthog.models.person.bulk_delete import (
queue_person_recording_deletion,
resolve_persons_for_deletion,
)
+from posthog.models.person.util import TOMBSTONE_DELIVERY_TIMEOUT_SECONDS, tombstone_persons_in_postgres
from posthog.personhog_client.fake_client import get_active_fake
+from posthog.personhog_client.proto import DeletePersonsMode
from posthog.test.persons import create_person
@@ -173,6 +180,165 @@ class DeletePersonsProfileTests(BaseTest):
pg_delete.assert_called_once_with(self.team.pk, [p1])
+@override_settings(PERSON_DELETE_TOMBSTONE=True)
+class TombstoneDeletePersonsProfileTests(BaseTest):
+ def test_tombstones_postgres_first_then_publishes_clickhouse_at_the_returned_versions_and_acks(self):
+ p = create_person(team=self.team, distinct_ids=["a"], properties={})
+ fake = get_active_fake()
+ with (
+ patch("posthog.models.person.bulk_delete.delete_person") as legacy_ch_delete,
+ patch("posthog.models.person.util.publish_person_tombstone", return_value=[]) as publish,
+ ):
+ result = delete_persons_profile(self.team.pk, [p], actor=self.user)
+
+ assert result.deleted_count == 1
+ assert result.errors == []
+ legacy_ch_delete.assert_not_called()
+ request = next(call.request for call in reversed(fake.calls) if call.method == "delete_persons")
+ assert request.mode == DeletePersonsMode.DELETE_PERSONS_MODE_TOMBSTONE
+ publish.assert_called_once()
+ tombstone = publish.call_args.args[1]
+ # Exactly what the replica wrote: the fake bumps version 0 to 1 on both rows.
+ assert (tombstone.uuid, tombstone.version) == (p.uuid, 1)
+ assert [(d.id, d.version) for d in tombstone.distinct_ids] == [("a", 1)]
+ assert publish.call_args.kwargs["created_at"] == p.created_at
+ assert fake.tombstone_queue == {}
+
+ @parameterized.expand([("produce_raises",), ("delivery_fails",)])
+ def test_counts_and_logs_a_person_whose_clickhouse_publish_failed_and_keeps_it_queued(self, case):
+ p = create_person(team=self.team, distinct_ids=["a"], properties={})
+ undelivered = ProduceResult(topic="clickhouse_person")
+ undelivered.set_result(KafkaError(-192, "Local: Message timed out"), None)
+ publish = (
+ patch("posthog.models.person.util.publish_person_tombstone", side_effect=RuntimeError("kafka down"))
+ if case == "produce_raises"
+ else patch("posthog.models.person.util.publish_person_tombstone", return_value=[undelivered])
+ )
+ with publish:
+ result = delete_persons_profile(self.team.pk, [p], actor=self.user, organization_id=self.organization.id)
+
+ # The Postgres tombstone is the deletion; the failed publish is reported on its own step.
+ assert result.deleted_count == 1
+ assert [(f.step, f.person_uuid) for f in result.failures] == [
+ (PersonDeletionStep.PUBLISH_CLICKHOUSE_TOMBSTONE, p.uuid)
+ ]
+ assert ActivityLog.objects.filter(team_id=self.team.pk, scope="Person", item_id=str(p.pk)).exists()
+ assert list(get_active_fake().tombstone_queue) == [(self.team.pk, str(p.uuid))]
+
+ @parameterized.expand([("delivered", True), ("timed_out", False)])
+ def test_waits_once_for_kafka_delivery_before_acking(self, _name, delivered):
+ p = create_person(team=self.team, distinct_ids=["a"], properties={})
+ pending = ProduceResult(topic="clickhouse_person")
+ producer = MagicMock()
+ if delivered:
+ producer.flush.side_effect = lambda timeout: pending.set_result(None, None)
+ with (
+ patch("posthog.models.person.util.publish_person_tombstone", return_value=[pending]),
+ patch("posthog.models.person.util.get_producer", return_value=producer),
+ ):
+ result = delete_persons_profile(self.team.pk, [p], actor=self.user, organization_id=self.organization.id)
+
+ # Both person topics resolve to this one producer, so it is flushed once, inside the delivery timeout.
+ producer.flush.assert_called_once()
+ assert 0 < producer.flush.call_args.args[0] <= TOMBSTONE_DELIVERY_TIMEOUT_SECONDS
+ assert result.deleted_count == 1
+ if delivered:
+ assert result.failures == []
+ assert get_active_fake().tombstone_queue == {}
+ else:
+ assert [(f.step, f.person_uuid) for f in result.failures] == [
+ (PersonDeletionStep.PUBLISH_CLICKHOUSE_TOMBSTONE, p.uuid)
+ ]
+ assert list(get_active_fake().tombstone_queue) == [(self.team.pk, str(p.uuid))]
+
+ @parameterized.expand(
+ [
+ ("not_committed", False, False),
+ ("committed_before_failing", True, False),
+ ("committed_but_the_check_fails_too", True, True),
+ ]
+ )
+ def test_a_failed_tombstone_rpc_counts_only_the_persons_it_did_not_commit(self, _name, committed, check_fails):
+ p = create_person(team=self.team, distinct_ids=["a"], properties={})
+
+ def tombstone_then_fail(team_id, uuids):
+ if committed:
+ tombstone_persons_in_postgres(team_id, uuids)
+ raise RuntimeError("personhog down")
+
+ check = (
+ patch("posthog.models.person.bulk_delete.get_person_tombstones", side_effect=RuntimeError("still down"))
+ if check_fails
+ else contextlib.nullcontext()
+ )
+ with (
+ patch("posthog.models.person.bulk_delete.tombstone_persons_in_postgres", side_effect=tombstone_then_fail),
+ patch("posthog.models.person.util.publish_person_tombstone", return_value=[]) as publish,
+ check,
+ ):
+ result = delete_persons_profile(self.team.pk, [p], actor=self.user)
+
+ if committed and not check_fails:
+ assert result.deleted_count == 1
+ assert result.failures == []
+ assert publish.call_args.args[1].uuid == p.uuid
+ return
+
+ assert result.deleted_count == 0
+ assert [(f.step, f.person_uuid) for f in result.failures] == [(PersonDeletionStep.TOMBSTONE_POSTGRES, p.uuid)]
+ publish.assert_not_called()
+ if check_fails:
+ # The error names the unknown state, and the queue row leaves the publish to the weekly sweep.
+ assert result.failures[0].error.startswith("PersonTombstoneStateUnknown: RuntimeError: personhog down")
+ assert list(get_active_fake().tombstone_queue) == [(self.team.pk, str(p.uuid))]
+
+ @parameterized.expand(
+ [
+ # (name, budget, distinct IDs per person, persons per RPC call)
+ ("each_over_budget_alone", 3, [2, 2, 2], [[0], [1], [2]]),
+ ("exactly_at_budget_stays_together", 4, [2, 2, 2], [[0, 1], [2]]),
+ ("wider_than_budget_goes_alone", 3, [1, 5, 1], [[0], [1], [2]]),
+ ]
+ )
+ def test_splits_the_rpc_by_distinct_id_budget_and_waits_for_delivery_once(self, _name, budget, widths, expected):
+ persons = [
+ create_person(team=self.team, distinct_ids=[f"d{i}-{j}" for j in range(width)], properties={})
+ for i, width in enumerate(widths)
+ ]
+ with (
+ patch("posthog.models.person.bulk_delete.QUEUED_DELETION_DISTINCT_IDS_PER_BATCH", budget),
+ # Sizing reads the distinct IDs the resolve loaded, so a failed fetch cannot shrink a person to one.
+ patch(
+ "posthog.models.person.bulk_delete._batched_get_distinct_ids_for_persons",
+ side_effect=RuntimeError("personhog down"),
+ ),
+ patch(
+ "posthog.models.person.bulk_delete.tombstone_persons_in_postgres",
+ wraps=tombstone_persons_in_postgres,
+ ) as rpc,
+ patch("posthog.models.person.util.publish_person_tombstone", return_value=[]),
+ ):
+ delete_persons_profile(self.team.pk, persons, actor=self.user)
+
+ assert [call.args[1] for call in rpc.call_args_list] == [[persons[i].uuid for i in batch] for batch in expected]
+ # However many RPC batches, one delivery wait and one ack for the whole request.
+ acks = [call.request for call in get_active_fake().calls if call.method == "ack_person_tombstones"]
+ assert [len(ack.tombstones) for ack in acks] == [len(persons)]
+
+ def test_a_failed_queue_ack_is_only_logged(self):
+ p = create_person(team=self.team, distinct_ids=["a"], properties={})
+ with (
+ patch("posthog.models.person.util.publish_person_tombstone", return_value=[]),
+ patch("posthog.models.person.util.ack_person_tombstones", side_effect=RuntimeError("personhog down")),
+ ):
+ result = delete_persons_profile(self.team.pk, [p], actor=self.user)
+
+ # The person is deleted and published; the row stays queued for the weekly sweep to clear.
+ assert result.deleted_count == 1
+ assert result.failures == []
+ assert list(get_active_fake().tombstone_queue) == [(self.team.pk, str(p.uuid))]
+
+
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={})
@@ -202,6 +368,33 @@ class ProcessQueuedPersonDeletionTests(BaseTest):
assert log.activity == "deleted"
assert log.was_impersonated is True
+ @override_settings(PERSON_DELETE_TOMBSTONE=True)
+ def test_tombstones_at_exact_versions_with_every_paged_distinct_id(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 legacy_ch_delete,
+ patch("posthog.models.person.util.publish_person_tombstone", return_value=[]) as publish,
+ ):
+ 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 == 1
+ assert result.errors == []
+ legacy_ch_delete.assert_not_called()
+ request = next(call.request for call in reversed(fake.calls) if call.method == "delete_persons")
+ assert request.mode == DeletePersonsMode.DELETE_PERSONS_MODE_TOMBSTONE
+ assert sorted(d.id for d in publish.call_args.args[1].distinct_ids) == ["a", "b", "c", "d", "e"]
+ assert fake.tombstone_queue == {}
+ assert ActivityLog.objects.filter(team_id=self.team.pk, scope="Person", item_id=str(p.pk)).exists()
+
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 (
diff --git a/posthog/models/person/test/test_orphaned_ch_persons.py b/posthog/models/person/test/test_orphaned_ch_persons.py
index 5ae1739d990a..e2eccdcea419 100644
--- a/posthog/models/person/test/test_orphaned_ch_persons.py
+++ b/posthog/models/person/test/test_orphaned_ch_persons.py
@@ -1,15 +1,19 @@
from uuid import uuid4
from posthog.test.base import BaseTest, ClickhouseTestMixin
+from unittest.mock import patch
from parameterized import parameterized
from posthog.clickhouse.client import sync_execute
-from posthog.models.person.deletion import find_orphaned_ch_persons, tombstone_orphaned_ch_persons
+from posthog.models.person.deletion import OrphanedPerson, find_orphaned_ch_persons, tombstone_orphaned_ch_persons
from posthog.models.person.util import (
create_person as create_person_in_ch,
create_person_distinct_id,
+ get_person_tombstones,
+ tombstone_persons_in_postgres,
)
+from posthog.personhog_client.fake_client import get_active_fake
from posthog.test.persons import create_person
@@ -68,6 +72,52 @@ class TestOrphanedCHPersonRepair(ClickhouseTestMixin, BaseTest):
_, mapping_deleted, _ = self._ch_mapping_state(did)
assert mapping_deleted == 1
+ @parameterized.expand([("dry_run", True), ("apply", False)])
+ def test_person_tombstoned_in_the_persons_db_is_republished_at_its_stored_versions(self, _name: str, dry_run: bool):
+ person = create_person(team=self.team, distinct_ids=["did-t"], properties={})
+ [written] = tombstone_persons_in_postgres(self.team.pk, [person.uuid])
+ # The fake still reads tombstoned persons, so the orphan is built the way a real read reports it.
+ orphan = OrphanedPerson(uuid=str(person.uuid), ch_max_version=0, created_at=person.created_at)
+
+ result = tombstone_orphaned_ch_persons(self.team.pk, [orphan], dry_run=dry_run)
+
+ assert (result.republished_persons, result.tombstoned_persons) == (1, 0)
+ if dry_run:
+ assert self._ch_person_state(str(person.uuid))[0] == 0
+ return
+ assert self._ch_person_state(str(person.uuid)) == (1, written.version)
+ assert self._ch_mapping_state("did-t")[1:] == (1, written.distinct_ids[0].version)
+
+ def test_live_person_reported_as_orphan_by_a_lagging_read_stays_live_in_the_persons_db(self):
+ person = create_person(team=self.team, distinct_ids=["did-l"], properties={})
+ orphan = OrphanedPerson(uuid=str(person.uuid), ch_max_version=0, created_at=person.created_at)
+
+ result = tombstone_orphaned_ch_persons(self.team.pk, [orphan], dry_run=False)
+
+ assert (result.republished_persons, result.tombstoned_persons) == (0, 1)
+ assert get_person_tombstones(self.team.pk, [person.uuid]) == []
+ assert self._ch_person_state(str(person.uuid)) == (1, 100)
+
+ def test_a_failed_republish_still_tombstones_the_true_orphans_mappings(self):
+ orphan_uuid = str(uuid4())
+ self._seed_ch_only_person(orphan_uuid, ["did-o"])
+ person = create_person(team=self.team, distinct_ids=["did-t"], properties={})
+ tombstone_persons_in_postgres(self.team.pk, [person.uuid])
+ orphans = [
+ *find_orphaned_ch_persons(self.team.pk, [orphan_uuid]),
+ OrphanedPerson(uuid=str(person.uuid), ch_max_version=0, created_at=person.created_at),
+ ]
+
+ with (
+ patch("posthog.models.person.util.publish_person_tombstone", side_effect=RuntimeError("kafka down")),
+ self.assertRaises(RuntimeError),
+ ):
+ tombstone_orphaned_ch_persons(self.team.pk, orphans, dry_run=False)
+
+ # A rerun would not revisit this orphan, so its mapping has to be tombstoned on this run.
+ assert self._ch_person_state(orphan_uuid)[0] == 1
+ assert self._ch_mapping_state("did-o")[1] == 1
+
def test_dry_run_produces_nothing(self):
uuid = str(uuid4())
self._seed_ch_only_person(uuid, ["did-a"], version=3)
@@ -78,10 +128,11 @@ class TestOrphanedCHPersonRepair(ClickhouseTestMixin, BaseTest):
assert result.dry_run is True
assert result.tombstoned_persons == 1
assert result.tombstoned_mappings == 1
- # ...but ClickHouse is untouched.
+ # ...but ClickHouse and the persons DB are untouched.
is_deleted, version = self._ch_person_state(uuid)
assert is_deleted == 0
assert version == 3
+ assert not [c for c in get_active_fake().calls if c.method == "delete_persons"]
def test_live_person_is_never_an_orphan(self):
# A person present in the persons DB (seeded into the fake) must not be
diff --git a/posthog/models/person/util.py b/posthog/models/person/util.py
index 0c5d7c178b7f..8cd352795f9e 100644
--- a/posthog/models/person/util.py
+++ b/posthog/models/person/util.py
@@ -1,11 +1,13 @@
from __future__ import annotations
import json
+import time
import datetime
import contextvars
+from collections.abc import Sequence
from concurrent.futures import ThreadPoolExecutor
-from dataclasses import dataclass
-from typing import TYPE_CHECKING, Optional, Union
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Any, Optional, Union
from uuid import UUID
from zoneinfo import ZoneInfo
@@ -16,7 +18,9 @@ import structlog
from dateutil.parser import isoparse
from posthog.clickhouse.client import sync_execute
-from posthog.kafka_client.client import ClickhouseProducer
+from posthog.dataclasses import frozen
+from posthog.kafka_client.client import ClickhouseProducer, ProduceResult
+from posthog.kafka_client.routing import get_producer
from posthog.kafka_client.topics import KAFKA_PERSON, KAFKA_PERSON_DISTINCT_ID
from posthog.models.person import Person
from posthog.models.person.sql import (
@@ -30,6 +34,9 @@ from posthog.personhog_client.client import personhog_call, require_personhog_cl
from posthog.personhog_client.converters import proto_person_to_model
from posthog.personhog_client.metrics import PERSONHOG_TEAM_MISMATCH_TOTAL, get_client_name
from posthog.personhog_client.proto import (
+ AckedPersonTombstone,
+ AckPersonTombstonesRequest,
+ DeletePersonsMode,
DeletePersonsRequest,
GetDistinctIdsForPersonRequest,
GetDistinctIdsForPersonsRequest,
@@ -38,6 +45,8 @@ from posthog.personhog_client.proto import (
GetPersonRequest,
GetPersonsByDistinctIdsInTeamRequest,
GetPersonsByUuidsRequest,
+ GetPersonTombstonesRequest,
+ ListPersonTombstoneQueueRequest,
ReadOptions,
)
from posthog.settings import TEST
@@ -277,6 +286,33 @@ def create_person(
created_at: Optional[datetime.datetime] = None,
last_seen_at: Optional[datetime.datetime] = None,
) -> str:
+ data = _person_row(
+ team_id=team_id,
+ version=version,
+ uuid=uuid,
+ properties=properties,
+ is_identified=is_identified,
+ is_deleted=is_deleted,
+ timestamp=timestamp,
+ created_at=created_at,
+ last_seen_at=last_seen_at,
+ )
+ ClickhouseProducer().produce(topic=KAFKA_PERSON, sql=INSERT_PERSON_SQL, data=data)
+ return data["id"]
+
+
+def _person_row(
+ *,
+ team_id: int,
+ version: int,
+ uuid: Optional[str] = None,
+ properties: Optional[dict] = None,
+ is_identified: bool = False,
+ is_deleted: bool = False,
+ timestamp: Optional[Union[datetime.datetime, str]] = None,
+ created_at: Optional[datetime.datetime] = None,
+ last_seen_at: Optional[datetime.datetime] = None,
+) -> dict[str, Any]:
if properties is None:
properties = {}
if uuid:
@@ -315,9 +351,7 @@ def create_person(
"_timestamp": timestamp.strftime("%Y-%m-%d %H:%M:%S"),
"last_seen_at": last_seen_at_formatted,
}
- p = ClickhouseProducer()
- p.produce(topic=KAFKA_PERSON, sql=INSERT_PERSON_SQL, data=data)
- return uuid
+ return data
def create_person_distinct_id(
@@ -326,9 +360,8 @@ def create_person_distinct_id(
person_id: str,
version=0,
is_deleted: bool = False,
-) -> None:
- p = ClickhouseProducer()
- p.produce(
+) -> ProduceResult:
+ return ClickhouseProducer().produce(
topic=KAFKA_PERSON_DISTINCT_ID,
sql=INSERT_PERSON_DISTINCT_ID2,
data={
@@ -671,20 +704,231 @@ def get_person_uuids_and_matched_distinct_ids(team_id: int, distinct_ids: list[s
def delete_persons_from_postgres(team_id: int, persons: list[Person]) -> None:
- """Delete Person rows (and associated PersonDistinctId rows) via the personhog RPC.
+ """Remove Person rows (and associated PersonDistinctId rows) via the personhog RPC.
- Processes in batches of 1000 (the RPC maximum).
+ Processes in batches of 1000 (the RPC maximum). Asks for a hard delete explicitly: the
+ caller has already published ClickHouse tombstones at version + 100, so the replica's own
+ default must not turn this into a tombstone.
"""
def personhog_fn() -> None:
uuids = [str(p.uuid) for p in persons]
for i in range(0, len(uuids), 1000):
batch = uuids[i : i + 1000]
- _get_client().delete_persons(DeletePersonsRequest(team_id=team_id, person_uuids=batch))
+ _get_client().delete_persons(
+ DeletePersonsRequest(
+ team_id=team_id, person_uuids=batch, mode=DeletePersonsMode.DELETE_PERSONS_MODE_HARD
+ )
+ )
personhog_call("delete_persons", personhog_fn)
+@frozen
+class PersonTombstone:
+ """The versions the replica wrote when it tombstoned one person."""
+
+ uuid: UUID
+ version: int
+ distinct_ids: list[DistinctIdForPerson]
+
+
+def _to_tombstone(t: person_pb2.TombstonedPerson) -> PersonTombstone:
+ return PersonTombstone(
+ uuid=UUID(t.person_uuid),
+ version=int(t.version),
+ distinct_ids=[DistinctIdForPerson(id=d.distinct_id, version=int(d.version)) for d in t.distinct_ids],
+ )
+
+
+def tombstone_persons_in_postgres(team_id: int, person_uuids: list[UUID]) -> list[PersonTombstone]:
+ """Tombstone Person rows via the personhog RPC and return the versions it wrote.
+
+ Batches of 1000, the RPC maximum. An already tombstoned person comes back with the
+ versions it holds; one that no longer exists comes back with nothing.
+ """
+
+ def personhog_fn() -> list[PersonTombstone]:
+ tombstones: list[PersonTombstone] = []
+ uuids = [str(u) for u in person_uuids]
+ for i in range(0, len(uuids), 1000):
+ batch = uuids[i : i + 1000]
+ response = _get_client().delete_persons(
+ DeletePersonsRequest(
+ team_id=team_id, person_uuids=batch, mode=DeletePersonsMode.DELETE_PERSONS_MODE_TOMBSTONE
+ )
+ )
+ tombstones.extend(_to_tombstone(t) for t in response.tombstones)
+ return tombstones
+
+ return personhog_call("tombstone_persons", personhog_fn)
+
+
+@frozen
+class QueuedPersonTombstone:
+ team_id: int
+ person_uuid: UUID
+ person_version: int
+ tombstoned_at_ms: int
+
+
+def get_person_tombstones(team_id: int, person_uuids: list[UUID]) -> list[PersonTombstone]:
+ def personhog_fn() -> list[PersonTombstone]:
+ tombstones: list[PersonTombstone] = []
+ uuids = [str(u) for u in person_uuids]
+ for i in range(0, len(uuids), 1000):
+ response = _get_client().get_person_tombstones(
+ GetPersonTombstonesRequest(team_id=team_id, person_uuids=uuids[i : i + 1000])
+ )
+ tombstones.extend(_to_tombstone(t) for t in response.tombstones)
+ return tombstones
+
+ return personhog_call("get_person_tombstones", personhog_fn)
+
+
+def list_person_tombstone_queue(
+ after: tuple[int, UUID] | None, limit: int, team_id: int | None = None
+) -> list[QueuedPersonTombstone]:
+ def personhog_fn() -> list[QueuedPersonTombstone]:
+ request = ListPersonTombstoneQueueRequest(
+ after_team_id=after[0] if after else 0,
+ after_person_uuid=str(after[1]) if after else "",
+ limit=limit,
+ )
+ if team_id is not None:
+ request.team_id = team_id
+ response = _get_client().list_person_tombstone_queue(request)
+ return [
+ QueuedPersonTombstone(
+ team_id=int(e.team_id),
+ person_uuid=UUID(e.person_uuid),
+ person_version=int(e.person_version),
+ tombstoned_at_ms=int(e.tombstoned_at),
+ )
+ for e in response.entries
+ ]
+
+ return personhog_call("list_person_tombstone_queue", personhog_fn)
+
+
+def ack_person_tombstones(team_id: int, acked: list[tuple[UUID, int]]) -> int:
+ def personhog_fn() -> int:
+ cleared = 0
+ for i in range(0, len(acked), 1000):
+ response = _get_client().ack_person_tombstones(
+ AckPersonTombstonesRequest(
+ team_id=team_id,
+ tombstones=[
+ AckedPersonTombstone(person_uuid=str(uuid), version=version)
+ for uuid, version in acked[i : i + 1000]
+ ],
+ )
+ )
+ cleared += int(response.cleared_count)
+ return cleared
+
+ return personhog_call("ack_person_tombstones", personhog_fn)
+
+
+def publish_person_tombstone(
+ team_id: int, tombstone: PersonTombstone, created_at: Optional[datetime.datetime] = None
+) -> list[ProduceResult]:
+ """Produce ClickHouse deletion rows at exactly the versions the Postgres tombstone holds.
+
+ The rows outrank every earlier update of the person, and a revival at the next version
+ outranks them in turn, which is what makes the version + 100 offset unnecessary.
+ """
+ person_row = _person_row(
+ team_id=team_id, version=tombstone.version, uuid=str(tombstone.uuid), created_at=created_at, is_deleted=True
+ )
+ results = [ClickhouseProducer().produce(topic=KAFKA_PERSON, sql=INSERT_PERSON_SQL, data=person_row)]
+ for distinct_id in tombstone.distinct_ids:
+ results.append(
+ create_person_distinct_id(
+ team_id=team_id,
+ distinct_id=distinct_id.id,
+ person_id=str(tombstone.uuid),
+ version=distinct_id.version,
+ is_deleted=True,
+ )
+ )
+ return results
+
+
+TOMBSTONE_DELIVERY_TIMEOUT_SECONDS = 10
+
+
+@frozen
+class PersonTombstonePublishFailure:
+ person_uuid: UUID
+ error: Exception
+
+
+@frozen(frozen=False)
+class PersonTombstonePublication:
+ """ClickHouse tombstone rows produced for one team, waiting for delivery and the queue ack.
+
+ ``publish`` produces the rows for a batch of tombstones and returns without waiting.
+ ``await_and_ack`` waits once for Kafka to deliver everything produced so far, then acks
+ the delivered persons off the tombstone queue. Publish every batch first and wait once,
+ so a request pays the delivery timeout once instead of once per batch.
+
+ A person that fails to produce or deliver is reported in ``failures`` and stays queued for
+ the weekly sweep. A failed ack is only logged, because the sweep republishes those rows too.
+ """
+
+ team_id: int
+ failures: list[PersonTombstonePublishFailure] = field(default_factory=list)
+ _pending: list[tuple[PersonTombstone, list[ProduceResult]]] = field(default_factory=list, init=False, repr=False)
+
+ def publish(self, tombstones: Sequence[tuple[PersonTombstone, Optional[datetime.datetime]]]) -> None:
+ for tombstone, created_at in tombstones:
+ try:
+ results = publish_person_tombstone(self.team_id, tombstone, created_at=created_at)
+ except Exception as exc:
+ self.failures.append(PersonTombstonePublishFailure(person_uuid=tombstone.uuid, error=exc))
+ continue
+ self._pending.append((tombstone, results))
+
+ def await_and_ack(self) -> None:
+ pending, self._pending = self._pending, []
+ if not pending:
+ return
+
+ if not all(result.done() for _, results in pending for result in results):
+ _flush_person_producers(TOMBSTONE_DELIVERY_TIMEOUT_SECONDS)
+
+ delivered: list[tuple[UUID, int]] = []
+ for tombstone, results in pending:
+ try:
+ for result in results:
+ result.get(timeout=0)
+ except Exception as exc:
+ self.failures.append(PersonTombstonePublishFailure(person_uuid=tombstone.uuid, error=exc))
+ continue
+ delivered.append((tombstone.uuid, tombstone.version))
+ if not delivered:
+ return
+ try:
+ ack_person_tombstones(self.team_id, delivered)
+ except Exception:
+ logger.warning(
+ "person_tombstones.ack_failed", team_id=self.team_id, person_count=len(delivered), exc_info=True
+ )
+
+
+def _flush_person_producers(timeout: float) -> None:
+ """Flush each producer behind the person topics once, within one shared deadline.
+
+ Both topics normally route to the same producer. Flushing it once per topic would wait
+ for the full timeout twice while the brokers are unreachable.
+ """
+ deadline = time.monotonic() + timeout
+ producers = {id(p): p for p in (get_producer(topic=KAFKA_PERSON), get_producer(topic=KAFKA_PERSON_DISTINCT_ID))}
+ for producer in producers.values():
+ producer.flush(max(0.0, deadline - time.monotonic()))
+
+
def delete_person(person: Person, distinct_ids: list[DistinctIdForPerson] | None = None) -> None:
"""Produce ClickHouse deletion tombstones for a person and its distinct_ids.
diff --git a/posthog/settings/__init__.py b/posthog/settings/__init__.py
index d34a9cae32c5..cb8bd61492f6 100644
--- a/posthog/settings/__init__.py
+++ b/posthog/settings/__init__.py
@@ -134,6 +134,10 @@ PERSON_ON_EVENTS_V2_OVERRIDE: bool = get_from_env("PERSON_ON_EVENTS_V2_OVERRIDE"
# 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)
+# Person deletes tombstone the Postgres rows (version kept, properties scrubbed) and publish the
+# ClickHouse tombstones at the versions the replica wrote, instead of hard-deleting and guessing
+# version + 100. Ingestion must revive tombstones for every team before this is on.
+PERSON_DELETE_TOMBSTONE: bool = get_from_env("PERSON_DELETE_TOMBSTONE", 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.
diff --git a/posthog/tasks/delete_persons.py b/posthog/tasks/delete_persons.py
index 5839edfc92f5..777dd1ceaee4 100644
--- a/posthog/tasks/delete_persons.py
+++ b/posthog/tasks/delete_persons.py
@@ -146,12 +146,22 @@ def delete_persons_async(
return
failures_by_step = Counter(failure.step.value for failure in result.failures)
- failed_uuids = [str(u) for u in result.errors]
+ failed_uuids = [str(u) for u in result.retryable_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())
+ if not failed_uuids and not unmatched_failed:
+ # Every failed person is deleted and no longer resolves, so a retry would find nothing. The
+ # step's own metric reports the failure, and the deletion sweep repairs an unpublished tombstone.
+ logger.warning(
+ "delete_persons_async finished with failures a retry cannot fix",
+ team_id=team_id,
+ retries=retries,
+ failures_by_step=dict(failures_by_step),
+ )
+ return
logger.warning(
"delete_persons_async retrying failed persons",
team_id=team_id,
diff --git a/posthog/tasks/test/test_delete_persons.py b/posthog/tasks/test/test_delete_persons.py
index 878dfadb44ff..dd3ce5f414e5 100644
--- a/posthog/tasks/test/test_delete_persons.py
+++ b/posthog/tasks/test/test_delete_persons.py
@@ -102,11 +102,15 @@ class TestDeletePersonsAsync(SimpleTestCase):
def test_retries_only_the_failed_persons(self) -> None:
failed = uuid4()
result = PersonProfileDeletionResult(
- deleted_count=0,
+ deleted_count=1,
failures=[
PersonDeletionFailure(
step=PersonDeletionStep.QUEUE_TRAINING_DELETION, person_uuid=failed, error="RuntimeError: x"
- )
+ ),
+ # Deleted, only its publish failed: a retry would not find it, so it is left out.
+ PersonDeletionFailure(
+ step=PersonDeletionStep.PUBLISH_CLICKHOUSE_TOMBSTONE, person_uuid=uuid4(), error="TimeoutError"
+ ),
],
)
with patch.object(delete_persons_async, "retry", side_effect=Retry("retry")) as retry:
@@ -146,7 +150,34 @@ class TestDeletePersonsAsync(SimpleTestCase):
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:
+ @parameterized.expand(
+ [
+ ("all_deleted", PersonProfileDeletionResult(deleted_count=2)),
+ (
+ "publish_failed_after_deletion",
+ PersonProfileDeletionResult(
+ deleted_count=2,
+ failures=[
+ PersonDeletionFailure(
+ step=PersonDeletionStep.PUBLISH_CLICKHOUSE_TOMBSTONE, person_uuid=uuid4(), error="x"
+ )
+ ],
+ ),
+ ),
+ (
+ "activity_log_failed_after_deletion",
+ PersonProfileDeletionResult(
+ deleted_count=2,
+ failures=[
+ PersonDeletionFailure(step=PersonDeletionStep.LOG_ACTIVITY, person_uuid=uuid4(), error="x")
+ ],
+ ),
+ ),
+ ]
+ )
+ def test_completes_quietly_when_every_person_is_deleted(
+ self, _name: str, result: PersonProfileDeletionResult
+ ) -> None:
with patch.object(delete_persons_async, "retry") as retry:
- self._run(PersonProfileDeletionResult(deleted_count=2))
+ self._run(result)
retry.assert_not_called()
diff --git a/products/persons/frontend/generated/api.schemas.ts b/products/persons/frontend/generated/api.schemas.ts
index 4a4d771fa636..b65d9c0fdf72 100644
--- a/products/persons/frontend/generated/api.schemas.ts
+++ b/products/persons/frontend/generated/api.schemas.ts
@@ -362,7 +362,7 @@ export interface PersonBulkDeleteResponseApi {
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 whose deletion did not fully complete in this request. Each entry contains 'person_uuid' and 'step', the deletion step that failed for that person. Failures are reported here rather than as an error status, so a 202 with entries means those persons were not deleted and the request should be retried for them, except entries whose step is 'log_activity': that 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. */
+ /** 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. Failures are reported here rather than as an error status, so a 202 with entries means those persons were not deleted and the request should be retried for them. Two steps are exceptions, and retrying won't find these persons. For 'log_activity', the person was deleted, but the activity log entry was not written. For 'publish_clickhouse_tombstone', the person was deleted, but it can still show in analytics until a weekly cleanup job removes it. 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.ts
index d3aae6756993..e6f9b209ece2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -78345,7 +78345,7 @@ export namespace Schemas {
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 whose deletion did not fully complete in this request. Each entry contains 'person_uuid' and 'step', the deletion step that failed for that person. Failures are reported here rather than as an error status, so a 202 with entries means those persons were not deleted and the request should be retried for them, except entries whose step is 'log_activity': that 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. */
+ /** 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. Failures are reported here rather than as an error status, so a 202 with entries means those persons were not deleted and the request should be retried for them. Two steps are exceptions, and retrying won't find these persons. For 'log_activity', the person was deleted, but the activity log entry was not written. For 'publish_clickhouse_tombstone', the person was deleted, but it can still show in analytics until a weekly cleanup job removes it. Always empty when the deletion was queued (see persons_queued_for_deletion). Contact support if this persists. */
deletion_errors?: PersonBulkDeleteResponseDeletionErrorsItem[];
}