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.

chore(persons): remove the legacy +100 person deletion order (#110207)

Nick Best84acb3324743
diff --git a/posthog/api/test/test_person.py b/posthog/api/test/test_person.py
index 8e3c7671cae4..fc0070defe0c 100644
--- a/posthog/api/test/test_person.py
+++ b/posthog/api/test/test_person.py
@@ -733,7 +733,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
"SELECT version, is_deleted, properties FROM person FINAL WHERE team_id = %(team_id)s and id = %(uuid)s",
{"team_id": self.team.pk, "uuid": person.uuid},
)
- self.assertEqual([(100, 1, "{}")], ch_persons)
+ self.assertEqual([(1, 1, "{}")], ch_persons)
# No async deletion is scheduled
self.assertEqual(AsyncDeletion.objects.filter(team_id=self.team.id).count(), 0)
ch_events = sync_execute(
@@ -744,7 +744,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
@parameterized.expand(
[
- ("postgres_delete_fails", "posthog.models.person.bulk_delete.delete_persons_from_postgres", 503, False),
+ ("postgres_tombstone_fails", "posthog.models.person.bulk_delete.tombstone_persons_in_postgres", 503, False),
("activity_log_fails", "posthog.models.person.bulk_delete.bulk_log_activity", 202, True),
]
)
@@ -759,7 +759,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
if expected_status == 503:
data = response.json()
self.assertEqual(data["code"], "person_deletion_failed")
- self.assertIn("delete_postgres", data["detail"])
+ self.assertIn("tombstone_postgres", data["detail"])
@parameterized.expand(
[
@@ -799,7 +799,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
"SELECT version, is_deleted, properties FROM person FINAL WHERE team_id = %(team_id)s and id = %(uuid)s",
{"team_id": self.team.pk, "uuid": person.uuid},
)
- self.assertEqual([(100, 1, "{}")], ch_persons)
+ self.assertEqual([(1, 1, "{}")], ch_persons)
# async deletion scheduled and executed
async_deletion = cast(AsyncDeletion, AsyncDeletion.objects.filter(team_id=self.team.id).first())
@@ -846,7 +846,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
"SELECT version, is_deleted, properties FROM person FINAL WHERE team_id = %(team_id)s and id = %(uuid)s",
{"team_id": self.team.pk, "uuid": person.uuid},
)
- self.assertEqual([(100, 1, "{}")], ch_persons)
+ self.assertEqual([(1, 1, "{}")], ch_persons)
# async deletion scheduled and executed
async_deletion = cast(AsyncDeletion, AsyncDeletion.objects.filter(team_id=self.team.id).first())
@@ -893,7 +893,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
"SELECT version, is_deleted, properties FROM person FINAL WHERE team_id = %(team_id)s and id = %(uuid)s",
{"team_id": self.team.pk, "uuid": person.uuid},
)
- self.assertEqual([(100, 1, "{}")], ch_persons)
+ self.assertEqual([(1, 1, "{}")], ch_persons)
# async deletion scheduled and executed
async_deletion = cast(AsyncDeletion, AsyncDeletion.objects.filter(team_id=self.team.id).first())
@@ -938,7 +938,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
"SELECT version, is_deleted, properties FROM person FINAL WHERE team_id = %(team_id)s and id = %(uuid)s",
{"team_id": self.team.pk, "uuid": person.uuid},
)
- self.assertEqual([(100, 1, "{}")], ch_persons)
+ self.assertEqual([(1, 1, "{}")], ch_persons)
# No async deletion is scheduled
self.assertEqual(AsyncDeletion.objects.filter(team_id=self.team.id).count(), 0)
ch_events = sync_execute(
@@ -1144,9 +1144,8 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(data["count"], 1)
self.assertEqual(data["results"][0]["person_uuid"], str(person1.uuid))
- @mock.patch("posthog.models.person.bulk_delete.delete_person")
- def test_bulk_delete_partial_failure(self, mock_delete_person):
- """Test that bulk_delete continues when a single person fails to delete and reports errors"""
+ @mock.patch("posthog.models.person.util.publish_person_tombstone")
+ def test_bulk_delete_partial_publish_failure_reports_the_person_and_still_counts_it_deleted(self, mock_publish):
person1 = _create_person(
team=self.team,
distinct_ids=["person_1"],
@@ -1158,8 +1157,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
immediate=True,
)
- # Make delete_person fail on the first person, succeed on the second
- mock_delete_person.side_effect = [Exception("DB connection lost"), None]
+ mock_publish.side_effect = [Exception("Kafka produce failed"), []]
response = self.client.post(
f"/api/person/bulk_delete/",
@@ -1169,17 +1167,18 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)
data = response.json()
self.assertEqual(data["persons_found"], 2)
- self.assertEqual(data["persons_deleted"], 1)
+ # Both Postgres tombstones landed; the failed publish is reported, not counted as a missed delete.
+ self.assertEqual(data["persons_deleted"], 2)
self.assertEqual(len(data["deletion_errors"]), 1)
self.assertEqual(data["deletion_errors"][0]["person_uuid"], str(person1.uuid))
- self.assertEqual(data["deletion_errors"][0]["step"], "tombstone_clickhouse")
+ self.assertEqual(data["deletion_errors"][0]["step"], "publish_clickhouse_tombstone")
self.assertNotIn("detail", data["deletion_errors"][0])
@mock.patch(
- "posthog.models.person.bulk_delete.delete_persons_from_postgres",
+ "posthog.models.person.bulk_delete.tombstone_persons_in_postgres",
side_effect=Exception("DB connection lost"),
)
- def test_bulk_delete_total_failure_reports_every_person(self, _mock_delete_from_postgres):
+ def test_bulk_delete_total_failure_reports_every_person(self, _mock_tombstone):
person1 = _create_person(team=self.team, distinct_ids=["person_1"], immediate=True)
person2 = _create_person(team=self.team, distinct_ids=["person_2"], immediate=True)
@@ -1193,7 +1192,7 @@ class TestPerson(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
sorted(error["person_uuid"] for error in data["deletion_errors"]),
sorted([str(person1.uuid), str(person2.uuid)]),
)
- self.assertEqual({error["step"] for error in data["deletion_errors"]}, {"delete_postgres"})
+ self.assertEqual({error["step"] for error in data["deletion_errors"]}, {"tombstone_postgres"})
self.assertIsNotNone(get_person_by_uuid(self.team.pk, str(person1.uuid)))
self.assertIsNotNone(get_person_by_uuid(self.team.pk, str(person2.uuid)))
diff --git a/posthog/api/test/test_person_personhog.py b/posthog/api/test/test_person_personhog.py
index a2d8e3e8f47c..aab2eaf031ca 100644
--- a/posthog/api/test/test_person_personhog.py
+++ b/posthog/api/test/test_person_personhog.py
@@ -554,26 +554,3 @@ class TestBulkDeletePersons(PersonhogTestMixin, APIBaseTest):
assert list(calls[0].request.person_uuids) == [str(p1.uuid)]
# Other team's person should be untouched
assert get_person_by_uuid(other_team.pk, str(other_person.uuid)) is not None
-
- @mock.patch("posthog.models.person.bulk_delete.delete_person")
- def test_bulk_delete_partial_failure_only_deletes_successful_from_postgres(self, mock_delete_person):
- p1 = self._seed_person(team=self.team, distinct_ids=["did-1"])
- p2 = self._seed_person(team=self.team, distinct_ids=["did-2"])
-
- mock_delete_person.side_effect = [Exception("CH write failed"), None]
-
- resp = self.client.post(
- "/api/person/bulk_delete/",
- {"ids": [str(p1.uuid), str(p2.uuid)]},
- )
-
- assert resp.status_code == status.HTTP_202_ACCEPTED
- data = resp.json()
- assert data["persons_found"] == 2
- assert data["persons_deleted"] == 1
- assert data["deletion_errors"] == [{"person_uuid": str(p1.uuid), "step": "tombstone_clickhouse"}]
-
- calls = self._assert_personhog_called("delete_persons")
- if calls:
- # Only the successful person should be sent to personhog for PG deletion
- assert list(calls[0].request.person_uuids) == [str(p2.uuid)]
diff --git a/posthog/async_migrations/test/test_0007_persons_and_groups_on_events_backfill.py b/posthog/async_migrations/test/test_0007_persons_and_groups_on_events_backfill.py
index 1ee6837105ab..d7c3c62f7a68 100644
--- a/posthog/async_migrations/test/test_0007_persons_and_groups_on_events_backfill.py
+++ b/posthog/async_migrations/test/test_0007_persons_and_groups_on_events_backfill.py
@@ -11,9 +11,12 @@ from posthog.clickhouse.client import query_with_columns, sync_execute
from posthog.models.async_migration import AsyncMigration, AsyncMigrationError, MigrationStatus
from posthog.models.event.util import create_event
from posthog.models.group.util import create_group
-from posthog.models.person.util import create_person, create_person_distinct_id, delete_person
+from posthog.models.person.util import create_person, create_person_distinct_id
from posthog.models.utils import UUIDT
-from posthog.test.persons import create_person as create_test_person
+from posthog.test.persons import (
+ create_person as create_test_person,
+ delete_person,
+)
pytestmark = pytest.mark.async_migrations
diff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.py
index e99e5f27d72b..be43715ecc0b 100644
--- a/posthog/dags/data_deletion_requests.py
+++ b/posthog/dags/data_deletion_requests.py
@@ -1578,7 +1578,7 @@ def delete_person_profiles_op(
context: dagster.OpExecutionContext,
person_removal: PersonRemovalContext,
) -> PersonRemovalContext:
- """Tombstone Person rows in CH and delete from Postgres, last.
+ """Tombstone Person rows in Postgres and publish the ClickHouse tombstones, last.
On per-person failures, errors are recorded in op metadata and the request is allowed to
transition to COMPLETED — Postgres rows remain for the failed UUIDs and the operator can
@@ -1586,10 +1586,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 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.
+ The one exception is the Postgres 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")
@@ -1612,15 +1612,11 @@ def delete_person_profiles_op(
if result.errors:
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 in (PersonDeletionStep.DELETE_POSTGRES, PersonDeletionStep.TOMBSTONE_POSTGRES)
- ]
+ postgres_failures = [f for f in result.failures if f.step == PersonDeletionStep.TOMBSTONE_POSTGRES]
if postgres_failures:
raise dagster.Failure(
description=(
- f"Deletion request {person_removal.request_id}: the Postgres delete failed for "
+ f"Deletion request {person_removal.request_id}: the Postgres tombstone failed for "
f"{len(postgres_failures)} persons ({postgres_failures[0].error})"
),
metadata=metadata,
diff --git a/posthog/dags/tests/test_data_deletion_requests.py b/posthog/dags/tests/test_data_deletion_requests.py
index ffe5d248a47b..dc85646d3a1d 100644
--- a/posthog/dags/tests/test_data_deletion_requests.py
+++ b/posthog/dags/tests/test_data_deletion_requests.py
@@ -2648,7 +2648,9 @@ def test_delete_person_profiles_op_records_per_person_errors_in_metadata():
deleted_count=0,
failures=[
PersonDeletionFailure(
- step=PersonDeletionStep.TOMBSTONE_CLICKHOUSE, person_uuid=UUID(p_uuid), error="RuntimeError: x"
+ step=PersonDeletionStep.PUBLISH_CLICKHOUSE_TOMBSTONE,
+ person_uuid=UUID(p_uuid),
+ error="RuntimeError: x",
)
],
)
@@ -2664,7 +2666,7 @@ def test_delete_person_profiles_op_records_per_person_errors_in_metadata():
@pytest.mark.django_db
-def test_delete_person_profiles_op_raises_when_the_postgres_delete_fails():
+def test_delete_person_profiles_op_raises_when_the_postgres_tombstone_fails():
p_uuid = str(uuid4())
create_person(team_id=TEAM_ID, uuid=p_uuid, distinct_ids=["a"])
ctx = PersonRemovalContext(
@@ -2682,14 +2684,16 @@ def test_delete_person_profiles_op_raises_when_the_postgres_delete_fails():
deleted_count=0,
failures=[
PersonDeletionFailure(
- step=PersonDeletionStep.TOMBSTONE_CLICKHOUSE, person_uuid=tombstone_failed, error="RuntimeError: ch"
+ step=PersonDeletionStep.PUBLISH_CLICKHOUSE_TOMBSTONE,
+ person_uuid=tombstone_failed,
+ error="RuntimeError: ch",
),
PersonDeletionFailure(
- step=PersonDeletionStep.DELETE_POSTGRES, person_uuid=UUID(p_uuid), error="RuntimeError: down"
+ step=PersonDeletionStep.TOMBSTONE_POSTGRES, person_uuid=UUID(p_uuid), error="RuntimeError: down"
),
],
)
- with pytest.raises(dagster.Failure, match="Postgres delete failed for 1 persons") as raised:
+ with pytest.raises(dagster.Failure, match="Postgres tombstone 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
@@ -2698,8 +2702,8 @@ def test_delete_person_profiles_op_raises_when_the_postgres_delete_fails():
@pytest.mark.django_db
[email protected]("postgres_delete_fails", [False, True])
-def test_data_deletion_request_person_removal_lifecycle(cluster: ClickhouseCluster, postgres_delete_fails: bool):
[email protected]("postgres_tombstone_fails", [False, True])
+def test_data_deletion_request_person_removal_lifecycle(cluster: ClickhouseCluster, postgres_tombstone_fails: bool):
p_uuid = str(uuid4())
create_person(team_id=TEAM_ID, uuid=p_uuid, distinct_ids=["a"])
request = DataDeletionRequest.objects.create(
@@ -2721,11 +2725,11 @@ def test_data_deletion_request_person_removal_lifecycle(cluster: ClickhouseClust
deleted_count=0,
failures=[
PersonDeletionFailure(
- step=PersonDeletionStep.DELETE_POSTGRES, person_uuid=UUID(p_uuid), error="RuntimeError: down"
+ step=PersonDeletionStep.TOMBSTONE_POSTGRES, person_uuid=UUID(p_uuid), error="RuntimeError: down"
)
],
)
- if postgres_delete_fails
+ if postgres_tombstone_fails
else PersonProfileDeletionResult(deleted_count=1)
)
result = data_deletion_request_person_removal.execute_in_process(
@@ -2740,9 +2744,9 @@ def test_data_deletion_request_person_removal_lifecycle(cluster: ClickhouseClust
# 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_fails
+ assert result.success is not postgres_tombstone_fails
request.refresh_from_db()
- assert request.status == (RequestStatus.FAILED if postgres_delete_fails else RequestStatus.COMPLETED)
+ assert request.status == (RequestStatus.FAILED if postgres_tombstone_fails else RequestStatus.COMPLETED)
@pytest.mark.django_db
@@ -2900,7 +2904,7 @@ def test_delete_person_profiles_op_raises_only_when_the_person_is_still_live(fai
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"):
+ with pytest.raises(dagster.Failure, match="Postgres tombstone failed for 1 persons"):
delete_person_profiles_op(build_op_context(), ctx)
else:
assert delete_person_profiles_op(build_op_context(), ctx) is ctx
diff --git a/posthog/dags/tests/test_person_pg_cleanup_drain.py b/posthog/dags/tests/test_person_pg_cleanup_drain.py
index 3d6c6c10a0e5..3106182572a6 100644
--- a/posthog/dags/tests/test_person_pg_cleanup_drain.py
+++ b/posthog/dags/tests/test_person_pg_cleanup_drain.py
@@ -28,11 +28,7 @@ from posthog.dags.person_pg_cleanup_drain import (
pg_recovery,
)
from posthog.personhog_client.fake_client import FakePersonHogClient, get_active_fake
-from posthog.personhog_client.proto import (
- DeleteTombstonedPersonsRequest,
- DeleteTombstonedPersonsResponse,
- GetPersonByUuidRequest,
-)
+from posthog.personhog_client.proto import DeleteTombstonedPersonsRequest, DeleteTombstonedPersonsResponse
from posthog.persons_db import persons_db_url
TEAM_A = 4242
@@ -132,7 +128,7 @@ def seed_big(fake: FakePersonHogClient, team_id: int, person_id: int, distinct_i
def present(fake: FakePersonHogClient, team_id: int, uuid: str) -> bool:
- return fake.get_person_by_uuid(GetPersonByUuidRequest(team_id=team_id, uuid=uuid)).HasField("person")
+ return fake.stored_person(team_id, uuid) is not None
def delete_requests(fake: FakePersonHogClient) -> list:
@@ -140,7 +136,8 @@ def delete_requests(fake: FakePersonHogClient) -> list:
def distinct_id_count(fake: FakePersonHogClient, team_id: int, uuid: str) -> int:
- person = fake.get_person_by_uuid(GetPersonByUuidRequest(team_id=team_id, uuid=uuid)).person
+ person = fake.stored_person(team_id, uuid)
+ assert person is not None
return len(fake._distinct_ids.get((team_id, person.id), []))
diff --git a/posthog/models/person/bulk_delete.py b/posthog/models/person/bulk_delete.py
index 37ef05313141..788da14c3671 100644
--- a/posthog/models/person/bulk_delete.py
+++ b/posthog/models/person/bulk_delete.py
@@ -1,7 +1,7 @@
import uuid as uuid_lib
import asyncio
import builtins
-from collections.abc import Callable, Iterable, Iterator
+from collections.abc import Iterable, Iterator
from dataclasses import field
from datetime import timedelta
from enum import StrEnum
@@ -10,7 +10,7 @@ from typing import cast
from django.conf import settings
import structlog
-from prometheus_client import Counter, Gauge, Histogram
+from prometheus_client import Counter, Histogram
from temporalio import common
from posthog.dataclasses import frozen
@@ -22,12 +22,9 @@ 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,
)
@@ -41,19 +38,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.
-
- 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.
- """
+ """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"
TOMBSTONE_POSTGRES = "tombstone_postgres"
PUBLISH_CLICKHOUSE_TOMBSTONE = "publish_clickhouse_tombstone"
LOG_ACTIVITY = "log_activity"
@@ -78,21 +68,6 @@ PERSON_DELETION_PERSONS_COUNTER = Counter(
labelnames=["path", "outcome"],
)
-# Every process sets the same value from its settings; max exports it once under multiprocess mode.
-PERSON_DELETE_TOMBSTONE_ENABLED = Gauge(
- "posthog_person_delete_tombstone_enabled",
- "1 when PERSON_DELETE_TOMBSTONE is on: deletes tombstone Postgres first and publish ClickHouse at the stored versions.",
- multiprocess_mode="max",
-)
-PERSON_DELETE_TOMBSTONE_ENABLED.set(1 if settings.PERSON_DELETE_TOMBSTONE else 0)
-
-# mode: "tombstone" under PERSON_DELETE_TOMBSTONE, "legacy" otherwise, per person a delete attempted.
-PERSON_DELETION_MODE_COUNTER = Counter(
- "posthog_person_deletion_mode_persons_total",
- "Persons a profile delete attempted, by deletion order.",
- labelnames=["mode"],
-)
-
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.",
@@ -201,36 +176,19 @@ def delete_persons_profile(
organization_id=None,
queue_ai_training_deletion: bool = True,
) -> PersonProfileDeletionResult:
- """Run ClickHouse Kafka tombstones, then a single Postgres batch delete.
+ """Tombstone the persons in Postgres and publish their ClickHouse tombstones.
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
-
if queue_ai_training_deletion:
queue_person_training_deletion(
team_id, [distinct_id for person in persons for distinct_id in person.distinct_ids]
)
- distinct_ids_by_person: dict[int, builtins.list[DistinctIdForPerson]] = {}
- # 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,
persons,
- lambda person: distinct_ids_by_person.get(person.pk),
actor=actor,
was_impersonated=is_impersonated(request),
organization_id=organization_id,
@@ -319,7 +277,6 @@ def process_queued_person_deletion(
deleted_count = 0
batch: builtins.list[Person] = []
- batch_distinct_ids: dict[int, builtins.list[DistinctIdForPerson]] = {}
batch_distinct_id_count = 0
for person in persons:
try:
@@ -336,13 +293,12 @@ def process_queued_person_deletion(
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
+ deleted_count += _run_batch_and_release(team_id, batch, failures, options)
+ batch, batch_distinct_id_count = [], 0
if batch:
- deleted_count += _run_batch_and_release(team_id, batch, batch_distinct_ids, failures, options)
+ deleted_count += _run_batch_and_release(team_id, batch, failures, options)
if unmatched_distinct_ids:
try:
@@ -360,11 +316,10 @@ def process_queued_person_deletion(
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)
+ deleted = _run_queued_deletion_steps(team_id, persons, 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:
@@ -427,7 +382,6 @@ def _queue_training_deletion_isolating_failures(
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:
@@ -466,7 +420,6 @@ def _run_queued_deletion_steps(
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,
@@ -478,19 +431,14 @@ def _run_queued_deletion_steps(
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:
- """Delete each person from Postgres and ClickHouse, then log the deletions.
+ """Tombstone each person in Postgres, publish the ClickHouse tombstones, 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
+ The activity log is written last so that a failed Postgres tombstone 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
@@ -498,12 +446,7 @@ def _tombstone_and_delete_persons(
raising would hide a completed deletion behind an error.
"""
failures: builtins.list[PersonDeletionFailure] = []
- if settings.PERSON_DELETE_TOMBSTONE:
- PERSON_DELETION_MODE_COUNTER.labels(mode="tombstone").inc(len(persons))
- deleted = _tombstone_persons_at_exact_versions(team_id, persons, failures)
- else:
- PERSON_DELETION_MODE_COUNTER.labels(mode="legacy").inc(len(persons))
- deleted = _tombstone_then_hard_delete_persons(team_id, persons, distinct_ids_for, failures)
+ deleted = _tombstone_persons_at_exact_versions(team_id, persons, failures)
if organization_id is not None and deleted:
try:
@@ -546,46 +489,6 @@ 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],
diff --git a/posthog/models/person/test/test_bulk_delete_helpers.py b/posthog/models/person/test/test_bulk_delete_helpers.py
index 484098015bc6..4acd99bf7999 100644
--- a/posthog/models/person/test/test_bulk_delete_helpers.py
+++ b/posthog/models/person/test/test_bulk_delete_helpers.py
@@ -4,8 +4,6 @@ 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 prometheus_client import REGISTRY
@@ -23,7 +21,11 @@ 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.models.person.util import (
+ TOMBSTONE_DELIVERY_TIMEOUT_SECONDS,
+ PersonTombstone,
+ 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
@@ -33,6 +35,15 @@ def _sample(name: str, **labels: str) -> float:
return REGISTRY.get_sample_value(name, labels) or 0.0
+def _no_publish():
+ # Keeps the Kafka produce out of the test; the fake personhog client still tombstones and acks.
+ return patch("posthog.models.person.util.publish_person_tombstone", return_value=[])
+
+
+def _rpc():
+ return patch("posthog.models.person.bulk_delete.tombstone_persons_in_postgres", wraps=tombstone_persons_in_postgres)
+
+
def _person_with_distinct_ids(*distinct_ids: str) -> Person:
# Unsaved Person with distinct_ids cached, so reads stay in-memory in the async fan-out.
person = Person()
@@ -93,116 +104,15 @@ class QueueEventDeletionTests(BaseTest):
class DeletePersonsProfileTests(BaseTest):
- def test_deletes_persons_via_helpers(self):
- p = create_person(team=self.team, distinct_ids=["a"], properties={})
- legacy_before = _sample("posthog_person_deletion_mode_persons_total", mode="legacy")
- 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 = delete_persons_profile(self.team.pk, [p], actor=self.user)
- assert result.deleted_count == 1
- assert _sample("posthog_person_deletion_mode_persons_total", mode="legacy") == legacy_before + 1
- assert result.errors == []
- ch_delete.assert_called_once()
- assert ch_delete.call_args.kwargs["person"] == p
- assert [d.id for d in ch_delete.call_args.kwargs["distinct_ids"]] == ["a"]
- pg_delete.assert_called_once_with(self.team.pk, [p])
-
- @parameterized.expand(
- [
- ("batch_fetch_fails", {"side_effect": RuntimeError("personhog down")}),
- ("person_missing_from_batch", {"return_value": {}}),
- ]
- )
- def test_falls_back_to_per_person_lookup(self, _name, batch_behavior):
- p = create_person(team=self.team, distinct_ids=["a"], properties={})
- with (
- patch("posthog.models.person.bulk_delete._batched_get_distinct_ids_for_persons", **batch_behavior),
- 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 = delete_persons_profile(self.team.pk, [p], actor=self.user)
- assert result.deleted_count == 1
- assert result.errors == []
- assert ch_delete.call_args.kwargs["distinct_ids"] is None
- pg_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={})
- with (
- patch(
- "posthog.models.person.bulk_delete.delete_person",
- side_effect=[None, RuntimeError("boom")],
- ),
- patch("posthog.models.person.bulk_delete.delete_persons_from_postgres") as pg_delete,
- ):
- result = delete_persons_profile(self.team.pk, [p1, p2], actor=self.user)
- assert result.deleted_count == 1
- assert [str(e) for e in result.errors] == [str(p2.uuid)]
- 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()
- mode_before = _sample("posthog_person_deletion_mode_persons_total", mode="tombstone")
acked_before = _sample("posthog_person_tombstone_acks_total", outcome="acked")
- 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,
- ):
+ with _no_publish() 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()
@@ -212,7 +122,6 @@ class TombstoneDeletePersonsProfileTests(BaseTest):
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 == {}
- assert _sample("posthog_person_deletion_mode_persons_total", mode="tombstone") == mode_before + 1
assert _sample("posthog_person_tombstone_acks_total", outcome="acked") == acked_before + 1
@parameterized.expand([("produce_raises",), ("delivery_fails",)])
@@ -286,20 +195,23 @@ class TombstoneDeletePersonsProfileTests(BaseTest):
)
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,
+ _no_publish() as publish,
check,
):
- result = delete_persons_profile(self.team.pk, [p], actor=self.user)
+ result = delete_persons_profile(self.team.pk, [p], actor=self.user, organization_id=self.organization.id)
+ logged = ActivityLog.objects.filter(team_id=self.team.pk, scope="Person", item_id=str(p.pk)).exists()
if committed and not check_fails:
assert result.deleted_count == 1
assert result.failures == []
assert publish.call_args.args[1].uuid == p.uuid
+ assert logged
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()
+ assert not logged
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")
@@ -320,11 +232,6 @@ class TombstoneDeletePersonsProfileTests(BaseTest):
]
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,
@@ -353,15 +260,35 @@ class TombstoneDeletePersonsProfileTests(BaseTest):
assert list(get_active_fake().tombstone_queue) == [(self.team.pk, str(p.uuid))]
assert _sample("posthog_person_tombstone_acks_total", outcome="ack_failed") == failed_before + 1
+ 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 (
+ _no_publish(),
+ 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
+ )
+ 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]
+ assert get_active_fake().tombstone_queue == {}
+
class ProcessQueuedPersonDeletionTests(BaseTest):
- def test_walks_every_page_of_distinct_ids_and_logs_activity(self):
+ def test_walks_every_page_of_distinct_ids_tombstones_at_exact_versions_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,
+ _no_publish() as publish,
):
result = process_queued_person_deletion(
self.team.pk,
@@ -374,47 +301,23 @@ class ProcessQueuedPersonDeletionTests(BaseTest):
)
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
-
- @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()
+ 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={})
+ # The fake hides a tombstoned person, so leave it live and report the tombstone from the patch.
+ stale_tombstones = [PersonTombstone(uuid=p.uuid, version=1, distinct_ids=[])]
with (
- patch("posthog.models.person.bulk_delete.delete_person"),
- patch("posthog.models.person.bulk_delete.delete_persons_from_postgres"),
+ patch("posthog.models.person.bulk_delete.tombstone_persons_in_postgres", return_value=stale_tombstones),
+ _no_publish(),
):
for _attempt in range(2):
process_queued_person_deletion(
@@ -430,10 +333,7 @@ class ProcessQueuedPersonDeletionTests(BaseTest):
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"),
- ):
+ with _no_publish():
process_queued_person_deletion(
self.team.pk,
[str(p.uuid)],
@@ -446,14 +346,11 @@ class ProcessQueuedPersonDeletionTests(BaseTest):
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):
+ def test_failed_postgres_tombstone_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"),
- ),
+ with patch(
+ "posthog.models.person.bulk_delete.tombstone_persons_in_postgres",
+ side_effect=RuntimeError("personhog down"),
):
result = process_queued_person_deletion(
self.team.pk,
@@ -465,13 +362,12 @@ class ProcessQueuedPersonDeletionTests(BaseTest):
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 [(f.step, f.person_uuid) for f in result.failures] == [(PersonDeletionStep.TOMBSTONE_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,
+ _rpc() as rpc,
):
result = process_queued_person_deletion(
self.team.pk,
@@ -484,8 +380,7 @@ class ProcessQueuedPersonDeletionTests(BaseTest):
)
assert result.deleted_count == 0
assert result.errors == []
- ch_delete.assert_not_called()
- pg_delete.assert_not_called()
+ rpc.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={})
@@ -494,8 +389,7 @@ class ProcessQueuedPersonDeletionTests(BaseTest):
"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,
+ _rpc() as rpc,
):
result = process_queued_person_deletion(
self.team.pk,
@@ -509,8 +403,7 @@ class ProcessQueuedPersonDeletionTests(BaseTest):
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()
+ rpc.assert_not_called()
def test_unmatched_distinct_ids_queue_training_deletion_and_fail_without_a_person(self):
with patch(
@@ -566,8 +459,7 @@ class ProcessQueuedPersonDeletionTests(BaseTest):
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,
+ _rpc() as rpc,
):
result = process_queued_person_deletion(
self.team.pk,
@@ -580,8 +472,7 @@ class ProcessQueuedPersonDeletionTests(BaseTest):
)
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()
+ rpc.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={})
@@ -590,8 +481,8 @@ class ProcessQueuedPersonDeletionTests(BaseTest):
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,
+ _rpc() as rpc,
+ _no_publish(),
):
result = process_queued_person_deletion(
self.team.pk,
@@ -605,10 +496,7 @@ class ProcessQueuedPersonDeletionTests(BaseTest):
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(u for call in rpc.call_args_list for u in call.args[1]) == sorted([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"],
@@ -642,8 +530,7 @@ class ProcessQueuedPersonDeletionTests(BaseTest):
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,
+ _rpc() as rpc,
):
result = process_queued_person_deletion(
self.team.pk,
@@ -658,8 +545,7 @@ class ProcessQueuedPersonDeletionTests(BaseTest):
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()
+ rpc.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={})
@@ -671,8 +557,7 @@ class ProcessQueuedPersonDeletionTests(BaseTest):
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,
+ _rpc() as rpc,
):
result = process_queued_person_deletion(
self.team.pk,
@@ -687,8 +572,7 @@ class ProcessQueuedPersonDeletionTests(BaseTest):
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]
+ assert rpc.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={})
@@ -701,8 +585,7 @@ class ProcessQueuedPersonDeletionTests(BaseTest):
"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,
+ _rpc() as rpc,
):
result = process_queued_person_deletion(
self.team.pk,
@@ -717,8 +600,7 @@ class ProcessQueuedPersonDeletionTests(BaseTest):
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()
+ rpc.assert_not_called()
class QueueRecordingDeletionTests(BaseTest):
diff --git a/posthog/models/person/test/test_delete_persons_personhog.py b/posthog/models/person/test/test_delete_persons_personhog.py
index 87aeca6efc35..93b75c1e9ace 100644
--- a/posthog/models/person/test/test_delete_persons_personhog.py
+++ b/posthog/models/person/test/test_delete_persons_personhog.py
@@ -1,69 +1,14 @@
-"""Tests for person deletion via personhog RPC.
-
-Covers routing and RPC behavior for:
-- delete_persons_from_postgres (API delete path)
-- _delete_persons_for_teams (team deletion path)
-"""
+"""Routing and RPC behavior of _delete_persons_for_teams (team deletion path)."""
from posthog.test.base import BaseTest
-from unittest.mock import MagicMock, patch
+from unittest.mock import patch
from django.test import SimpleTestCase
-from posthog.models.person.util import delete_persons_from_postgres, get_person_by_distinct_id, get_person_by_uuid
from posthog.models.team.util import _delete_persons_for_teams
from posthog.personhog_client.fake_client import fake_personhog_client
from posthog.test.persons import create_person
-# ── Routing tests for delete_persons_from_postgres ──────────────────
-
-
-class TestDeletePersonsFromPostgresRouting(SimpleTestCase):
- def test_routes_to_personhog(self):
- mock_person = MagicMock()
- mock_person.uuid = "550e8400-e29b-41d4-a716-446655440000"
- mock_person.delete = MagicMock()
-
- with fake_personhog_client():
- delete_persons_from_postgres(team_id=1, persons=[mock_person])
-
- mock_person.delete.assert_not_called()
-
- def test_personhog_sends_correct_uuids(self):
- mock_persons = []
- for uuid in ["uuid-1", "uuid-2", "uuid-3"]:
- p = MagicMock()
- p.uuid = uuid
- mock_persons.append(p)
-
- with fake_personhog_client() as fake:
- delete_persons_from_postgres(team_id=42, persons=mock_persons) # type: ignore[arg-type]
-
- calls = fake.assert_called("delete_persons", times=1)
- req = calls[0].request
- assert req.team_id == 42
- assert list(req.person_uuids) == ["uuid-1", "uuid-2", "uuid-3"]
-
- def test_personhog_batches_over_1000(self):
- mock_persons = []
- for i in range(1500):
- p = MagicMock()
- p.uuid = f"uuid-{i}"
- mock_persons.append(p)
-
- with fake_personhog_client() as fake:
- delete_persons_from_postgres(team_id=1, persons=mock_persons) # type: ignore[arg-type]
-
- calls = fake.assert_called("delete_persons", times=2)
- assert len(list(calls[0].request.person_uuids)) == 1000
- assert len(list(calls[1].request.person_uuids)) == 500
-
- def test_empty_persons_list_is_noop(self):
- with fake_personhog_client() as fake:
- delete_persons_from_postgres(team_id=1, persons=[])
- fake.assert_not_called("delete_persons")
-
-
# ── Routing tests for _delete_persons_for_teams ─────────────────────
@@ -79,19 +24,6 @@ class TestDeletePersonsForTeamsRouting(SimpleTestCase):
# ── RPC behavior tests (personhog fake with real test data) ─────────
-class TestDeletePersonsFromPostgresRPC(BaseTest):
- def test_multiple_persons_deleted(self):
- p1 = create_person(team=self.team, distinct_ids=["a"])
- p2 = create_person(team=self.team, distinct_ids=["b"])
-
- delete_persons_from_postgres(self.team.pk, [p1, p2])
-
- 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
- assert get_person_by_distinct_id(self.team.pk, "a") is None
- assert get_person_by_distinct_id(self.team.pk, "b") is None
-
-
class TestDeletePersonsForTeamsRPC(BaseTest):
def test_personhog_path_calls_batch_rpc_per_team(self):
other_team = self.organization.teams.create(name="Other Team")
diff --git a/posthog/models/person/util.py b/posthog/models/person/util.py
index c3b89aafcc73..ad45c08c9f5b 100644
--- a/posthog/models/person/util.py
+++ b/posthog/models/person/util.py
@@ -704,27 +704,6 @@ 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:
- """Remove Person rows (and associated PersonDistinctId rows) via the personhog RPC.
-
- 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, 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."""
@@ -953,49 +932,6 @@ def _flush_person_producers(timeout: float) -> None:
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.
-
- ``distinct_ids`` can be prefetched in batch (see ``delete_persons_profile``) to
- avoid one RPC per person; when omitted it is fetched here.
- """
- # This is racy https://github.com/PostHog/posthog/issues/11590
- if distinct_ids is None:
- distinct_ids = _get_distinct_ids_with_version(person)
- _delete_person(person.team_id, person.uuid, int(person.version or 0), person.created_at)
- for distinct_id in distinct_ids:
- _delete_ch_distinct_id(person.team_id, person.uuid, distinct_id.id, distinct_id.version)
-
-
-def _delete_person(
- team_id: int,
- uuid: UUID,
- version: int,
- created_at: Optional[datetime.datetime] = None,
-) -> None:
- create_person(
- uuid=str(uuid),
- team_id=team_id,
- # Version + 100 ensures delete takes precedence over normal updates.
- # Keep in sync with:
- # - plugin-server/src/utils/db/utils.ts:152 (generateKafkaPersonUpdateMessage)
- # - posthog/models/person/person.py:112 (split_person uses version + 101 to override deletes)
- version=version + 100,
- created_at=created_at,
- is_deleted=True,
- )
-
-
-def _get_distinct_ids_with_version(person: Person) -> list[DistinctIdForPerson]:
- def personhog_fn() -> list[DistinctIdForPerson]:
- resp = _get_client().get_distinct_ids_for_person(
- GetDistinctIdsForPersonRequest(team_id=person.team_id, person_id=person.pk)
- )
- return [DistinctIdForPerson(id=d.distinct_id, version=int(d.version or 0)) for d in resp.distinct_ids]
-
- return personhog_call("get_distinct_ids_with_version", personhog_fn)
-
-
def _delete_ch_distinct_id(team_id: int, uuid: UUID, distinct_id: str, version: int) -> None:
create_person_distinct_id(
team_id=team_id,
diff --git a/posthog/models/test/test_person_model.py b/posthog/models/test/test_person_model.py
index 315cda78d28b..d264b96a9336 100644
--- a/posthog/models/test/test_person_model.py
+++ b/posthog/models/test/test_person_model.py
@@ -2,10 +2,8 @@ from uuid import uuid4
from posthog.test.base import BaseTest
-from posthog.clickhouse.client import sync_execute
from posthog.models.event.util import create_event
-from posthog.models.person.util import delete_person
-from posthog.test.persons import add_distinct_id, create_person
+from posthog.test.persons import create_person
def _create_event(**kwargs):
@@ -20,31 +18,3 @@ class TestPerson(BaseTest):
person_anonymous = create_person(team=self.team)
self.assertEqual(person_identified.is_identified, True)
self.assertEqual(person_anonymous.is_identified, False)
-
- def test_delete_person(self):
- person = create_person(
- team=self.team, version=15
- ) # version be > 0 to check that we don't just assume 0 in deletes
- delete_person(person)
- ch_persons = sync_execute(
- "SELECT toString(id), version, is_deleted, properties FROM person FINAL WHERE team_id = %(team_id)s and id = %(uuid)s",
- {"team_id": self.team.pk, "uuid": person.uuid},
- )
- self.assertEqual(ch_persons, [(str(person.uuid), 115, 1, "{}")])
-
- def test_delete_ch_distinct_ids(self):
- person = create_person(team=self.team)
- add_distinct_id(person=person, distinct_id="distinct_id1", version=15)
-
- ch_distinct_ids = sync_execute(
- "SELECT is_deleted FROM person_distinct_id2 FINAL WHERE team_id = %(team_id)s and distinct_id = %(distinct_id)s",
- {"team_id": self.team.pk, "distinct_id": "distinct_id1"},
- )
- self.assertEqual(ch_distinct_ids, [(0,)])
-
- delete_person(person)
- ch_distinct_ids = sync_execute(
- "SELECT toString(person_id), version, is_deleted FROM person_distinct_id2 FINAL WHERE team_id = %(team_id)s and distinct_id = %(distinct_id)s",
- {"team_id": self.team.pk, "distinct_id": "distinct_id1"},
- )
- self.assertEqual(ch_distinct_ids, [(str(person.uuid), 115, 1)])
diff --git a/posthog/personhog_client/fake_client.py b/posthog/personhog_client/fake_client.py
index 42ff3b14a024..307a3b9735eb 100644
--- a/posthog/personhog_client/fake_client.py
+++ b/posthog/personhog_client/fake_client.py
@@ -114,8 +114,6 @@ class FakePersonHogClient:
is_deleted: bool = False,
tombstoned_distinct_ids: list[str] | None = None,
) -> person_pb2.Person:
- # Unlike the replica, the fake returns tombstoned persons on reads, so tests can inspect
- # what a delete left in place.
person = person_pb2.Person(
id=person_id,
uuid=uuid,
@@ -134,6 +132,8 @@ class FakePersonHogClient:
self._persons_by_uuid[(team_id, uuid)] = person
for did in distinct_ids or []:
self._persons_by_distinct_id[(team_id, did)] = person
+ # A re-added mapping is live again, as a revival upsert makes it in the replica.
+ self._tombstoned_distinct_ids.discard((team_id, did))
self._distinct_ids.setdefault((team_id, person_id), []).append(
person_pb2.DistinctIdWithVersion(distinct_id=did, version=(distinct_id_versions or {}).get(did, 0))
)
@@ -207,9 +207,28 @@ class FakePersonHogClient:
def close(self) -> None:
pass
+ # Reads mirror the replica, which filters tombstoned persons and mappings out of every person
+ # lookup. The tombstone RPCs below read the internal dicts, so they still see the tombstones.
+ @staticmethod
+ def _live(person: person_pb2.Person | None) -> person_pb2.Person | None:
+ return None if person is None or person.is_deleted else person
+
+ def _live_by_distinct_id(self, team_id: int, distinct_id: str) -> person_pb2.Person | None:
+ if (team_id, distinct_id) in self._tombstoned_distinct_ids:
+ return None
+ return self._live(self._persons_by_distinct_id.get((team_id, distinct_id)))
+
+ def stored_person(self, team_id: int, uuid: str) -> person_pb2.Person | None:
+ """The stored row, tombstoned or not, for tests that check what a delete left in place."""
+ return self._persons_by_uuid.get((team_id, uuid))
+
+ def stored_person_by_distinct_id(self, team_id: int, distinct_id: str) -> person_pb2.Person | None:
+ """The person a stored mapping points at, tombstoned or not."""
+ return self._persons_by_distinct_id.get((team_id, distinct_id))
+
def get_person(self, request: person_pb2.GetPersonRequest) -> person_pb2.GetPersonResponse:
self.calls.append(_Call("get_person", request))
- person = self._persons_by_id.get((request.team_id, request.person_id))
+ person = self._live(self._persons_by_id.get((request.team_id, request.person_id)))
return person_pb2.GetPersonResponse(person=person)
def get_persons(self, request: person_pb2.GetPersonsRequest) -> person_pb2.PersonsResponse:
@@ -217,7 +236,7 @@ class FakePersonHogClient:
found = []
missing = []
for pid in request.person_ids:
- person = self._persons_by_id.get((request.team_id, pid))
+ person = self._live(self._persons_by_id.get((request.team_id, pid)))
if person:
found.append(person)
else:
@@ -226,7 +245,7 @@ class FakePersonHogClient:
def get_person_by_uuid(self, request: person_pb2.GetPersonByUuidRequest) -> person_pb2.GetPersonResponse:
self.calls.append(_Call("get_person_by_uuid", request))
- person = self._persons_by_uuid.get((request.team_id, request.uuid))
+ person = self._live(self._persons_by_uuid.get((request.team_id, request.uuid)))
return person_pb2.GetPersonResponse(person=person)
def get_persons_by_uuids(self, request: person_pb2.GetPersonsByUuidsRequest) -> person_pb2.PersonsResponse:
@@ -234,7 +253,7 @@ class FakePersonHogClient:
found = []
missing_ids: list[int] = []
for uuid in request.uuids:
- person = self._persons_by_uuid.get((request.team_id, uuid))
+ person = self._live(self._persons_by_uuid.get((request.team_id, uuid)))
if person:
found.append(person)
return person_pb2.PersonsResponse(persons=found, missing_ids=missing_ids)
@@ -243,7 +262,7 @@ class FakePersonHogClient:
self, request: person_pb2.GetPersonByDistinctIdRequest
) -> person_pb2.GetPersonResponse:
self.calls.append(_Call("get_person_by_distinct_id", request))
- person = self._persons_by_distinct_id.get((request.team_id, request.distinct_id))
+ person = self._live_by_distinct_id(request.team_id, request.distinct_id)
return person_pb2.GetPersonResponse(person=person)
def get_persons_by_distinct_ids_in_team(
@@ -252,7 +271,7 @@ class FakePersonHogClient:
self.calls.append(_Call("get_persons_by_distinct_ids_in_team", request))
results = []
for did in request.distinct_ids:
- person = self._persons_by_distinct_id.get((request.team_id, did))
+ person = self._live_by_distinct_id(request.team_id, did)
if person:
results.append(person_pb2.PersonWithDistinctIds(distinct_id=did, person=person))
return person_pb2.PersonsByDistinctIdsInTeamResponse(results=results)
diff --git a/posthog/personhog_client/test_fake_client.py b/posthog/personhog_client/test_fake_client.py
index 3bc998918941..943186dbb231 100644
--- a/posthog/personhog_client/test_fake_client.py
+++ b/posthog/personhog_client/test_fake_client.py
@@ -509,9 +509,10 @@ class TestFakePersonHogClientDeleteTombstonedPersons:
)
def _present(self, uuid: str) -> bool:
- return self.client.get_person_by_uuid(
- person_pb2.GetPersonByUuidRequest(team_id=self.TEAM_ID, uuid=uuid)
- ).HasField("person")
+ return self.client.stored_person(self.TEAM_ID, uuid) is not None
+
+ def _mapped(self, distinct_id: str) -> bool:
+ return self.client.stored_person_by_distinct_id(self.TEAM_ID, distinct_id) is not None
@pytest.mark.parametrize(
"uuid,expected,expect_present",
@@ -537,9 +538,7 @@ class TestFakePersonHogClientDeleteTombstonedPersons:
deleted_count=1, rows_deleted=1
)
assert not self._present("big")
- assert not self.client.get_person_by_distinct_id(
- person_pb2.GetPersonByDistinctIdRequest(team_id=self.TEAM_ID, distinct_id="o-0")
- ).HasField("person")
+ assert not self._mapped("o-0")
def test_small_persons_in_the_same_request_never_wait_behind_a_big_one(self):
# tombstoned (2 rows) and blocked (2 rows) are admitted first, in id order, leaving 2
@@ -570,9 +569,7 @@ class TestFakePersonHogClientDeleteTombstonedPersons:
assert resp == person_pb2.DeleteTombstonedPersonsResponse(blocked_person_uuids=["big-live"])
for distinct_id in ("x-0", "x-4"):
- assert self.client.get_person_by_distinct_id(
- person_pb2.GetPersonByDistinctIdRequest(team_id=self.TEAM_ID, distinct_id=distinct_id)
- ).HasField("person")
+ assert self._mapped(distinct_id)
def test_max_rows_defaults_and_clamps_like_the_server(self):
self.client.tombstoned_delete_max_rows = 3
@@ -592,10 +589,7 @@ class TestFakePersonHogClientDeleteTombstonedPersons:
assert self._delete("tombstoned").deleted_count == 1
- by_did = self.client.get_person_by_distinct_id(
- person_pb2.GetPersonByDistinctIdRequest(team_id=self.TEAM_ID, distinct_id="t-1")
- )
- assert not by_did.HasField("person")
+ assert not self._mapped("t-1")
membership = self.client.check_cohort_membership(
cohort_pb2.CheckCohortMembershipRequest(person_id=1, cohort_ids=[9])
)
@@ -603,6 +597,24 @@ class TestFakePersonHogClientDeleteTombstonedPersons:
assert self.client.count_cohort_members(cohort_pb2.CountCohortMembersRequest(cohort_ids=[9])).count == 0
assert self._delete("tombstoned") == person_pb2.DeleteTombstonedPersonsResponse()
+ def test_a_re_added_distinct_id_resolves_to_its_new_person(self):
+ self.client.delete_persons(
+ person_pb2.DeletePersonsRequest(
+ team_id=self.TEAM_ID, person_uuids=["live"], mode=person_pb2.DELETE_PERSONS_MODE_TOMBSTONE
+ )
+ )
+ hidden = self.client.get_person_by_distinct_id(
+ person_pb2.GetPersonByDistinctIdRequest(team_id=self.TEAM_ID, distinct_id="l-1")
+ )
+ assert not hidden.HasField("person")
+
+ self.client.add_person(team_id=self.TEAM_ID, person_id=9, uuid="revived", distinct_ids=["l-1"])
+
+ resolved = self.client.get_person_by_distinct_id(
+ person_pb2.GetPersonByDistinctIdRequest(team_id=self.TEAM_ID, distinct_id="l-1")
+ )
+ assert resolved.person.uuid == "revived"
+
def test_wrong_team_touches_nothing(self):
resp = self.client.delete_tombstoned_persons(
person_pb2.DeleteTombstonedPersonsRequest(team_id=self.TEAM_ID + 1, person_uuids=["tombstoned"])
@@ -637,10 +649,8 @@ class TestFakePersonHogClientDeleteTombstonedPersons:
assert resp.tombstones[0].version == 1
assert [(d.distinct_id, d.version) for d in resp.tombstones[0].distinct_ids] == [("l-1", 1)]
assert [(d.distinct_id, d.version) for d in resp.tombstones[1].distinct_ids] == [("t-1", 0), ("t-2", 0)]
- stored = self.client.get_person_by_uuid(
- person_pb2.GetPersonByUuidRequest(team_id=self.TEAM_ID, uuid="live")
- ).person
- assert stored.is_deleted
+ stored = self.client.stored_person(self.TEAM_ID, "live")
+ assert stored is not None and stored.is_deleted
assert stored.version == 1
hard = self.client.delete_persons(
diff --git a/posthog/settings/__init__.py b/posthog/settings/__init__.py
index faaa14a1e368..82730400150b 100644
--- a/posthog/settings/__init__.py
+++ b/posthog/settings/__init__.py
@@ -135,10 +135,6 @@ 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/test/persons.py b/posthog/test/persons.py
index 7e868814e608..cdddbf30ff75 100644
--- a/posthog/test/persons.py
+++ b/posthog/test/persons.py
@@ -407,9 +407,8 @@ def _create_person_in_persons_db(create_kwargs: dict[str, Any], dids: list[str])
def delete_person(person: Person) -> None:
"""Soft-delete a person in ClickHouse and unseed the personhog fake.
- Mirrors posthog.models.person.util.delete_person: writes CH tombstones with
- version + 100 (so the delete wins over normal updates) for the person and each
- of its distinct IDs, then removes it from the fake.
+ Writes CH tombstones at version + 100 for the person and each of its distinct IDs, so the
+ delete wins over any row a test wrote before it, then removes the person from the fake.
"""
fake = _get_active_fake()
if fake is None:
diff --git a/products/ai_training/backend/tests/test_deletion.py b/products/ai_training/backend/tests/test_deletion.py
index 7ebec4b5e9c6..a59165230874 100644
--- a/products/ai_training/backend/tests/test_deletion.py
+++ b/products/ai_training/backend/tests/test_deletion.py
@@ -43,9 +43,7 @@ class TestAITrainingDeletionOutbox(TestCase):
return_value=MagicMock(results=[[session_id]]),
) as lookup,
patch("posthog.api.person.resolve_persons_for_deletion", return_value=[person]),
- patch("posthog.models.person.bulk_delete._batched_get_distinct_ids_for_persons", return_value={}),
- patch("posthog.models.person.bulk_delete.delete_person"),
- patch("posthog.models.person.bulk_delete.delete_persons_from_postgres"),
+ patch("posthog.models.person.util.publish_person_tombstone", return_value=[]),
patch("posthog.models.person.bulk_delete.sync_connect", return_value=temporal),
):
PersonViewSet._bulk_delete_persons(