:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(persons): make the person repair tools write postgres first (#112098)
Eli Reisman4bdc098b4b06
diff --git a/posthog/dags/detach_distinct_id.py b/posthog/dags/detach_distinct_id.pyindex acecd4968be4..93f4498c86bc 100644--- a/posthog/dags/detach_distinct_id.py+++ b/posthog/dags/detach_distinct_id.py@@ -1,9 +1,12 @@"""Dagster job to detach a distinct_id from its person.Three cleanup phases, all required:- 1. Postgres — delete posthog_persondistinctid row (stops future ingestion lookups).- 2. Kafka — publish is_deleted to person_distinct_id2 (stops ClickHouse lookups).- 3. Override — insert into person_distinct_id_overrides so the HogQL query layer+ 1. Postgres: tombstone the posthog_persondistinctid row (stops future ingestion lookups).+ The tombstone version is above both the row's own version and the highest version ClickHouse+ holds for the distinct id, so the ClickHouse tombstone and override win, and a later re-add+ revives the row above them instead of starting at version 0 underneath them.+ 2. Kafka: publish is_deleted to person_distinct_id2 at that exact version (stops ClickHouse lookups).+ 3. Override: insert into person_distinct_id_overrides so the HogQL query layerimmediately re-attributes historical events whose person_id was baked in atingestion time (Person-on-Events). squash_person_overrides later makes itpermanent and removes the override row.@@ -27,6 +30,7 @@ Example Dagster launchpad config (run with dry_run: true first!)::import jsonimport uuid+import shlexfrom datetime import datetimeimport dagster@@ -38,6 +42,8 @@ from posthog.dags.common import JobOwnersfrom posthog.kafka_client.client import _KafkaProducerfrom posthog.kafka_client.topics import KAFKA_PERSON_DISTINCT_ID+KAFKA_DELIVERY_TIMEOUT_SECONDS = 30+class DetachDistinctIdConfig(dagster.Config):"""Configuration for the detach distinct_id job."""@@ -116,21 +122,44 @@ def _count_other_distinct_ids(return row["count"] if isinstance(row, dict) else row[0]-def _delete_distinct_id_row(+def _clickhouse_max_version(team_id: int, distinct_id: str) -> int:+ """Return the highest ClickHouse version of the distinct id across the mapping and override tables, or 0."""+ rows = sync_execute(+ """+ SELECT greatest(+ (SELECT max(version) FROM person_distinct_id2+ WHERE team_id = %(team_id)s AND distinct_id = %(distinct_id)s),+ (SELECT max(version) FROM person_distinct_id_overrides+ WHERE team_id = %(team_id)s AND distinct_id = %(distinct_id)s)+ )+ """,+ {"team_id": team_id, "distinct_id": distinct_id},+ )+ return int(rows[0][0])+++def _tombstone_distinct_id_row(cursor: psycopg2.extensions.cursor,pdi_id: int,+ person_pk: int,+ min_version: int,) -> int:- """Lock and delete the posthog_persondistinctid row. Returns version."""+ """Tombstone the row at ``min_version`` or above while it still belongs to ``person_pk``; return its version."""cursor.execute(- "SELECT version FROM posthog_persondistinctid WHERE id = %s FOR UPDATE",- [pdi_id],+ """+ UPDATE posthog_persondistinctid+ SET is_deleted = true, version = GREATEST(COALESCE(version, 0) + 1, %s)+ WHERE id = %s AND person_id = %s AND is_deleted = false+ RETURNING version+ """,+ [min_version, pdi_id, person_pk],)row = cursor.fetchone()if row is None:- raise RuntimeError(f"posthog_persondistinctid id={pdi_id} disappeared between lookup and delete")- version = row["version"] if isinstance(row, dict) else row[0]- cursor.execute("DELETE FROM posthog_persondistinctid WHERE id = %s", [pdi_id])- return version+ raise RuntimeError(+ f"posthog_persondistinctid id={pdi_id} disappeared or moved off person {person_pk} between lookup and tombstone"+ )+ return row["version"] if isinstance(row, dict) else row[0]def _publish_deletion_to_kafka(@@ -142,19 +171,35 @@ def _publish_deletion_to_kafka() -> None:"""Publish an is_deleted message so ClickHouse person_distinct_id2 drops the mapping.- Uses version + 100, matching _delete_ch_distinct_id in posthog/models/person/util.py.+ ``version`` is the one the Postgres tombstone carries, so a revived mapping lands above it."""- producer.produce(+ result = producer.produce(topic=KAFKA_PERSON_DISTINCT_ID,data={"distinct_id": distinct_id,"person_id": person_uuid,"team_id": team_id,- "version": version + 100,+ "version": version,"is_deleted": 1,},)- producer.flush()+ producer.flush(KAFKA_DELIVERY_TIMEOUT_SECONDS)+ # flush() counts only messages still queued. A failed delivery leaves the queue, so only its result shows it.+ result.get(timeout=0)+++def _undelivered_tombstone_message(team_id: int, distinct_id: str, override_person_uuid: str, version: int) -> str:+ insert_override = (+ "from posthog.dags.detach_distinct_id import _insert_ch_override; "+ f"_insert_ch_override({team_id}, {json.dumps(distinct_id)}, {json.dumps(override_person_uuid)}, {version + 1})"+ )+ return (+ f"Postgres tombstoned distinct_id={distinct_id!r} at version {version}, but Kafka did not deliver the "+ "ClickHouse tombstone, so the override was not inserted. A rerun of this job cannot find the row. "+ "Recover with:\n"+ f" 1. python manage.py sync_persons_to_clickhouse --person-distinct-id --deletes --live-run --team-id {team_id}\n"+ f" 2. python manage.py shell -c {shlex.quote(insert_override)}"+ )def _insert_ch_override(@@ -223,34 +268,45 @@ def detach_distinct_id_op(override_target = config.override_person_id or str(uuid.uuid4())log.info(f"Override target person_id={override_target}")- # --- 3. Delete in Postgres ---+ # --- 3. Tombstone in Postgres ---if config.dry_run:- log.info("[DRY RUN] Would delete posthog_persondistinctid row")+ log.info("[DRY RUN] Would tombstone posthog_persondistinctid row")log.info("[DRY RUN] Would publish Kafka deletion to person_distinct_id2")log.info(f"[DRY RUN] Would insert person_distinct_id_overrides -> {override_target}")persons_database.rollback()return- version = _delete_distinct_id_row(cursor, info["pdi_id"])+ ch_max_version = _clickhouse_max_version(config.team_id, config.distinct_id)+ version = _tombstone_distinct_id_row(+ cursor, info["pdi_id"], person_pk=info["person_pk"], min_version=ch_max_version + 1+ )persons_database.commit()- log.info(f"Deleted posthog_persondistinctid id={info['pdi_id']} (version={version})")+ log.info(+ f"Tombstoned posthog_persondistinctid id={info['pdi_id']} "+ f"(version={version}, ClickHouse max version={ch_max_version})"+ )# --- 4. Sync deletion to ClickHouse via Kafka ---- _publish_deletion_to_kafka(- kafka_producer,- team_id=config.team_id,- distinct_id=config.distinct_id,- person_uuid=info["person_uuid"],- version=version,- )- log.info(f"Published deletion to {KAFKA_PERSON_DISTINCT_ID} (version={version + 100}, is_deleted=1)")+ try:+ _publish_deletion_to_kafka(+ kafka_producer,+ team_id=config.team_id,+ distinct_id=config.distinct_id,+ person_uuid=info["person_uuid"],+ version=version,+ )+ except Exception as e:+ raise dagster.Failure(+ _undelivered_tombstone_message(config.team_id, config.distinct_id, override_target, version)+ ) from e+ log.info(f"Published deletion to {KAFKA_PERSON_DISTINCT_ID} (version={version}, is_deleted=1)")# --- 5. Override: fix person_id baked into historical events (see module docstring) ---_insert_ch_override(team_id=config.team_id,distinct_id=config.distinct_id,override_person_uuid=override_target,- version=version + 100,+ version=version + 1,)log.info(f"Inserted person_distinct_id_overrides: {config.distinct_id!r} -> {override_target}")diff --git a/posthog/dags/tests/test_detach_distinct_id.py b/posthog/dags/tests/test_detach_distinct_id.pyindex be8bf30833c0..f4102bcb4f5a 100644--- a/posthog/dags/tests/test_detach_distinct_id.py+++ b/posthog/dags/tests/test_detach_distinct_id.py@@ -1,19 +1,28 @@import uuid as uuid_moduleimport contextlib+from datetime import datetimefrom uuid import UUIDimport pytestfrom unittest.mock import MagicMock, patch+from confluent_kafka import KafkaError, KafkaException++from posthog.clickhouse.client import sync_executefrom posthog.dags.detach_distinct_id import (_count_other_distinct_ids,- _delete_distinct_id_row,_insert_ch_override,_lookup_distinct_id,_publish_deletion_to_kafka,+ _tombstone_distinct_id_row,detach_distinct_id_job,)from posthog.kafka_client.topics import KAFKA_PERSON_DISTINCT_ID+from posthog.models.person.sql import (+ TRUNCATE_PERSON_DISTINCT_ID2_TABLE_SQL,+ TRUNCATE_PERSON_DISTINCT_ID_OVERRIDES_TABLE_SQL,+)+from posthog.models.person.util import create_person_distinct_idfrom posthog.persons_db import persons_db_connectionPERSON_UUID = "5e00024e-cb68-59f6-821f-6150fcffc431"@@ -35,6 +44,11 @@ def _make_cursor(fetchone_values: list | None = None) -> MagicMock:return cursor+def _override_insert_rows(mock_sync_execute: MagicMock) -> list:+ [insert] = [c for c in mock_sync_execute.call_args_list if "INSERT INTO person_distinct_id_overrides" in c.args[0]]+ return insert.args[1]++class TestLookupDistinctId:def test_returns_row_when_found_tuple(self):cursor = _make_cursor(fetchone_values=[(PDI_ID, PDI_VERSION, PERSON_PK, UUID(PERSON_UUID))])@@ -91,39 +105,32 @@ class TestCountOtherDistinctIds:assert count == 0-class TestDeleteDistinctIdRow:- def test_locks_and_deletes_tuple(self):- cursor = _make_cursor(fetchone_values=[(PDI_VERSION,)])+class TestTombstoneDistinctIdRow:+ @pytest.mark.parametrize("row", [(PDI_VERSION + 1,), {"version": PDI_VERSION + 1}])+ def test_tombstones_the_row_and_returns_the_stamped_version(self, row):+ cursor = _make_cursor(fetchone_values=[row])- version = _delete_distinct_id_row(cursor, PDI_ID)+ version = _tombstone_distinct_id_row(cursor, PDI_ID, person_pk=PERSON_PK, min_version=1)- assert version == PDI_VERSION- assert cursor.execute.call_count == 2- assert "FOR UPDATE" in cursor.execute.call_args_list[0].args[0]- assert "DELETE" in cursor.execute.call_args_list[1].args[0]-- def test_locks_and_deletes_dict(self):- cursor = _make_cursor(fetchone_values=[{"version": PDI_VERSION}])-- version = _delete_distinct_id_row(cursor, PDI_ID)-- assert version == PDI_VERSION- assert cursor.execute.call_count == 2- assert "FOR UPDATE" in cursor.execute.call_args_list[0].args[0]- assert "DELETE" in cursor.execute.call_args_list[1].args[0]+ assert version == PDI_VERSION + 1+ sql = cursor.execute.call_args.args[0]+ assert "UPDATE posthog_persondistinctid" in sql+ assert "is_deleted = true" in sql+ assert "RETURNING version" in sql+ assert "DELETE" not in sqldef test_raises_if_row_disappears(self):cursor = _make_cursor(fetchone_values=[None])with pytest.raises(RuntimeError, match="disappeared"):- _delete_distinct_id_row(cursor, PDI_ID)+ _tombstone_distinct_id_row(cursor, PDI_ID, person_pk=PERSON_PK, min_version=1)class TestPublishDeletionToKafka:- def test_publishes_with_version_plus_100(self):+ def test_publishes_at_the_tombstone_version(self):producer = MagicMock()- _publish_deletion_to_kafka(producer, TEAM_ID, "$posthog_cookieless", PERSON_UUID, PDI_VERSION)+ _publish_deletion_to_kafka(producer, TEAM_ID, "$posthog_cookieless", PERSON_UUID, PDI_VERSION + 1)producer.produce.assert_called_once_with(topic=KAFKA_PERSON_DISTINCT_ID,@@ -131,7 +138,7 @@ class TestPublishDeletionToKafka:"distinct_id": "$posthog_cookieless","person_id": PERSON_UUID,"team_id": TEAM_ID,- "version": PDI_VERSION + 100,+ "version": PDI_VERSION + 1,"is_deleted": 1,},)@@ -141,7 +148,7 @@ class TestPublishDeletionToKafka:class TestInsertChOverride:@patch("posthog.dags.detach_distinct_id.sync_execute")def test_inserts_override_row(self, mock_sync_execute):- _insert_ch_override(TEAM_ID, "$posthog_cookieless", DUMMY_OVERRIDE_UUID, PDI_VERSION + 100)+ _insert_ch_override(TEAM_ID, "$posthog_cookieless", DUMMY_OVERRIDE_UUID, PDI_VERSION + 1)mock_sync_execute.assert_called_once()sql = mock_sync_execute.call_args.args[0]@@ -154,14 +161,14 @@ class TestInsertChOverride:assert row[1] == "$posthog_cookieless"assert row[2] == DUMMY_OVERRIDE_UUIDassert row[3] == 0 # is_deleted- assert row[4] == PDI_VERSION + 100 # version+ assert row[4] == PDI_VERSION + 1 # versionclass TestDetachDistinctIdJob:"""Run the full Dagster job with mock Postgres (psycopg2), Kafka, and ClickHouse(sync_execute). Verifies the three cleanup phases only fire when all safety checks pass."""- def _make_connection(self, lookup_row, other_count, delete_version=PDI_VERSION):+ def _make_connection(self, lookup_row, other_count, tombstone_version=PDI_VERSION + 1):"""Build a mock psycopg2 connection with a cursor that responds to thequeries issued by detach_distinct_id_op in order."""conn = MagicMock(spec=["cursor", "commit", "rollback"])@@ -170,10 +177,10 @@ class TestDetachDistinctIdJob:# The op issues fetchone calls in this order:# 1. _lookup_distinct_id# 2. _count_other_distinct_ids- # 3. _delete_distinct_id_row SELECT FOR UPDATE (only when not dry_run)+ # 3. _tombstone_distinct_id_row UPDATE ... RETURNING (only when not dry_run)fetchone_sequence = [lookup_row, (other_count,)]- if delete_version is not None:- fetchone_sequence.append((delete_version,))+ if tombstone_version is not None:+ fetchone_sequence.append((tombstone_version,))cursor.fetchone.side_effect = fetchone_sequencecursor.__enter__ = MagicMock(return_value=cursor)@@ -212,6 +219,7 @@ class TestDetachDistinctIdJob:@patch("posthog.dags.detach_distinct_id.sync_execute")@patch("posthog.dags.detach_distinct_id.uuid.uuid4", return_value=UUID(DUMMY_OVERRIDE_UUID))def test_detaches_publishes_kafka_and_inserts_override(self, _mock_uuid4, mock_sync_execute):+ mock_sync_execute.return_value = [(0,)]lookup_row = (PDI_ID, PDI_VERSION, PERSON_PK, UUID(PERSON_UUID))conn, cursor = self._make_connection(lookup_row, other_count=2)producer = MagicMock()@@ -230,19 +238,39 @@ class TestDetachDistinctIdJob:assert kafka_data["distinct_id"] == "$posthog_cookieless"assert kafka_data["person_id"] == PERSON_UUIDassert kafka_data["is_deleted"] == 1- assert kafka_data["version"] == PDI_VERSION + 100+ assert kafka_data["version"] == PDI_VERSION + 1producer.flush.assert_called_once()# ClickHouse override- mock_sync_execute.assert_called_once()- override_rows = mock_sync_execute.call_args.args[1]+ override_rows = _override_insert_rows(mock_sync_execute)assert override_rows[0][0] == TEAM_IDassert override_rows[0][1] == "$posthog_cookieless"assert override_rows[0][2] == DUMMY_OVERRIDE_UUID- assert override_rows[0][4] == PDI_VERSION + 100+ assert override_rows[0][4] == PDI_VERSION + 2++ @patch("posthog.dags.detach_distinct_id.sync_execute")+ def test_a_failed_kafka_delivery_fails_the_job_before_the_override(self, mock_sync_execute):+ mock_sync_execute.return_value = [(0,)]+ lookup_row = (PDI_ID, PDI_VERSION, PERSON_PK, UUID(PERSON_UUID))+ conn, _cursor = self._make_connection(lookup_row, other_count=2)+ producer = MagicMock()+ producer.produce.return_value.get.side_effect = KafkaException(KafkaError(KafkaError._MSG_TIMED_OUT)) # type: ignore[attr-defined]++ result = detach_distinct_id_job.execute_in_process(+ run_config=self._run_config(dry_run=False),+ resources={"persons_database": conn, "kafka_producer": producer},+ raise_on_error=False,+ )++ assert not result.success+ conn.commit.assert_called_once()+ assert not [+ c for c in mock_sync_execute.call_args_list if "INSERT INTO person_distinct_id_overrides" in c.args[0]+ ]@patch("posthog.dags.detach_distinct_id.sync_execute")def test_uses_explicit_override_person_id(self, mock_sync_execute):+ mock_sync_execute.return_value = [(0,)]explicit_uuid = "11111111-2222-3333-4444-555555555555"lookup_row = (PDI_ID, PDI_VERSION, PERSON_PK, UUID(PERSON_UUID))conn, cursor = self._make_connection(lookup_row, other_count=2)@@ -254,13 +282,12 @@ class TestDetachDistinctIdJob:)assert result.success- mock_sync_execute.assert_called_once()- override_rows = mock_sync_execute.call_args.args[1]+ override_rows = _override_insert_rows(mock_sync_execute)assert override_rows[0][2] == explicit_uuid@patch("posthog.dags.detach_distinct_id.sync_execute")def test_fails_when_distinct_id_not_found(self, mock_sync_execute):- conn, cursor = self._make_connection(lookup_row=None, other_count=0, delete_version=None)+ conn, cursor = self._make_connection(lookup_row=None, other_count=0, tombstone_version=None)cursor.fetchone.side_effect = [None]producer = MagicMock()@@ -317,7 +344,7 @@ class TestDetachDistinctIdIntegration:Exercises the full Dagster job against real DB rows so cursor return types(tuple vs dict) are tested against production-like conditions.- Kafka and ClickHouse (sync_execute) remain mocked.+ Kafka stays mocked. ClickHouse is mocked except in the live-run test, which needs the real version reads."""@pytest.fixture@@ -333,10 +360,11 @@ class TestDetachDistinctIdIntegration:return Team.objects.create(organization=organization, name="Detach Test Team")@classmethod- def _pdi_exists(cls, pdi_id: int) -> bool:+ def _pdi_state(cls, pdi_id: int) -> tuple[bool, int] | None:with cls._get_persons_conn() as conn, conn.cursor() as cursor:- cursor.execute("SELECT 1 FROM posthog_persondistinctid WHERE id = %s", [pdi_id])- return cursor.fetchone() is not None+ cursor.execute("SELECT is_deleted, version FROM posthog_persondistinctid WHERE id = %s", [pdi_id])+ row = cursor.fetchone()+ return None if row is None else (row[0], row[1])@pytest.fixturedef person_with_two_distinct_ids(self, team):@@ -371,19 +399,23 @@ class TestDetachDistinctIdIntegration:return person, pdi_keep, pdi_detach@staticmethod- def _run_config(team_id: int, person_uuid: str, *, dry_run: bool, distinct_id: str = "$posthog_cookieless") -> dict:- return {- "ops": {- "detach_distinct_id_op": {- "config": {- "team_id": team_id,- "distinct_id": distinct_id,- "expected_person_id": person_uuid,- "dry_run": dry_run,- }- }- }+ def _run_config(+ team_id: int,+ person_uuid: str,+ *,+ dry_run: bool,+ distinct_id: str = "$posthog_cookieless",+ override_person_id: str | None = None,+ ) -> dict:+ config: dict = {+ "team_id": team_id,+ "distinct_id": distinct_id,+ "expected_person_id": person_uuid,+ "dry_run": dry_run,}+ if override_person_id is not None:+ config["override_person_id"] = override_person_id+ return {"ops": {"detach_distinct_id_op": {"config": config}}}@staticmethod@contextlib.contextmanager@@ -395,7 +427,7 @@ class TestDetachDistinctIdIntegration:yield conn@patch("posthog.dags.detach_distinct_id.sync_execute")- def test_dry_run_does_not_delete(self, mock_sync_execute, team, person_with_two_distinct_ids):+ def test_dry_run_does_not_tombstone(self, mock_sync_execute, team, person_with_two_distinct_ids):person, _pdi_keep, pdi_detach = person_with_two_distinct_idsproducer = MagicMock()@@ -406,42 +438,117 @@ class TestDetachDistinctIdIntegration:)assert result.success- assert self._pdi_exists(pdi_detach.id)+ assert self._pdi_state(pdi_detach.id) == (False, pdi_detach.version)producer.produce.assert_not_called()mock_sync_execute.assert_not_called()- @patch("posthog.dags.detach_distinct_id.sync_execute")- def test_live_run_deletes_and_publishes(self, mock_sync_execute, team, person_with_two_distinct_ids):+ @pytest.mark.parametrize(+ "clickhouse_table, expected_version",+ [+ # (table holding a version-20 row for the distinct id, version the tombstone gets)+ (None, 4),+ ("person_distinct_id2", 21),+ ("person_distinct_id_overrides", 21),+ ],+ )+ def test_live_run_tombstones_above_postgres_and_clickhouse(+ self, clickhouse_table, expected_version, team, person_with_two_distinct_ids+ ):person, pdi_keep, pdi_detach = person_with_two_distinct_ids+ override_target = str(uuid_module.uuid4())+ sync_execute(TRUNCATE_PERSON_DISTINCT_ID2_TABLE_SQL)+ sync_execute(TRUNCATE_PERSON_DISTINCT_ID_OVERRIDES_TABLE_SQL())+ if clickhouse_table == "person_distinct_id2":+ create_person_distinct_id(team.id, pdi_detach.distinct_id, str(person.uuid), version=20)+ elif clickhouse_table == "person_distinct_id_overrides":+ _insert_ch_override(team.id, pdi_detach.distinct_id, str(uuid_module.uuid4()), version=20)producer = MagicMock()with self._get_persons_conn() as conn:result = detach_distinct_id_job.execute_in_process(- run_config=self._run_config(team.id, str(person.uuid), dry_run=False),+ run_config=self._run_config(+ team.id, str(person.uuid), dry_run=False, override_person_id=override_target+ ),resources={"persons_database": conn, "kafka_producer": producer},)assert result.success+ assert self._pdi_state(pdi_detach.id) == (True, expected_version)+ assert self._pdi_state(pdi_keep.id) == (False, pdi_keep.version)+ producer.produce.assert_called_once_with(+ topic=KAFKA_PERSON_DISTINCT_ID,+ data={+ "distinct_id": pdi_detach.distinct_id,+ "person_id": str(person.uuid),+ "team_id": team.id,+ "version": expected_version,+ "is_deleted": 1,+ },+ )+ # The overrides MV consumes the same topic, so the published tombstone also lands in the overrides+ # table, after the direct insert.+ tombstone = producer.produce.call_args.kwargs["data"]+ sync_execute(+ """+ INSERT INTO person_distinct_id_overrides+ (team_id, distinct_id, person_id, is_deleted, version, _timestamp, _offset, _partition)+ VALUES+ """,+ [+ (+ tombstone["team_id"],+ tombstone["distinct_id"],+ tombstone["person_id"],+ tombstone["is_deleted"],+ tombstone["version"],+ datetime.now(),+ 0,+ 0,+ )+ ],+ )+ override = sync_execute(+ """+ SELECT person_id, is_deleted, version FROM person_distinct_id_overrides FINAL+ WHERE team_id = %(team_id)s AND distinct_id = %(distinct_id)s+ """,+ {"team_id": team.id, "distinct_id": pdi_detach.distinct_id},+ )+ assert override == [(UUID(override_target), 0, expected_version + 1)]- # PDI row deleted- assert not self._pdi_exists(pdi_detach.id)- # Other PDI untouched- assert self._pdi_exists(pdi_keep.id)+ def test_fails_without_tombstoning_when_the_distinct_id_moves_after_the_lookup(+ self, team, person_with_two_distinct_ids+ ):+ person, _pdi_keep, pdi_detach = person_with_two_distinct_ids+ with self._get_persons_conn() as conn, conn.cursor() as cursor:+ cursor.execute(+ "INSERT INTO posthog_person (team_id, uuid, properties, is_identified, version, created_at, properties_last_updated_at, properties_last_operation) "+ "VALUES (%s, %s, '{}', false, 0, NOW(), '{}', '{}') RETURNING id",+ [team.id, str(uuid_module.uuid4())],+ )+ other_person_id = cursor.fetchone()[0]- # Kafka deletion published- producer.produce.assert_called_once()- kafka_data = producer.produce.call_args.kwargs["data"]- assert kafka_data["distinct_id"] == "$posthog_cookieless"- assert kafka_data["person_id"] == str(person.uuid)- assert kafka_data["team_id"] == team.id- assert kafka_data["is_deleted"] == 1- assert kafka_data["version"] == pdi_detach.version + 100+ def move_then_read(team_id: int, distinct_id: str) -> int:+ with self._get_persons_conn() as conn, conn.cursor() as cursor:+ cursor.execute(+ "UPDATE posthog_persondistinctid SET person_id = %s WHERE id = %s", [other_person_id, pdi_detach.id]+ )+ return 0- # ClickHouse override inserted- mock_sync_execute.assert_called_once()- override_rows = mock_sync_execute.call_args.args[1]- assert override_rows[0][0] == team.id- assert override_rows[0][1] == "$posthog_cookieless"+ producer = MagicMock()+ with (+ patch("posthog.dags.detach_distinct_id._clickhouse_max_version", side_effect=move_then_read),+ self._get_persons_conn() as conn,+ ):+ result = detach_distinct_id_job.execute_in_process(+ run_config=self._run_config(team.id, str(person.uuid), dry_run=False),+ resources={"persons_database": conn, "kafka_producer": producer},+ raise_on_error=False,+ )++ assert not result.success+ assert self._pdi_state(pdi_detach.id) == (False, pdi_detach.version)+ producer.produce.assert_not_called()@patch("posthog.dags.detach_distinct_id.sync_execute")def test_fails_on_person_id_mismatch(self, mock_sync_execute, team, person_with_two_distinct_ids):diff --git a/posthog/management/commands/fix_orphaned_ch_persons.py b/posthog/management/commands/fix_orphaned_ch_persons.pyindex c6230dc659a3..ed3188b70391 100644--- a/posthog/management/commands/fix_orphaned_ch_persons.py+++ b/posthog/management/commands/fix_orphaned_ch_persons.py@@ -6,7 +6,13 @@ from django.core.management.base import BaseCommandimport structlogfrom posthog.kafka_client.routing import flush_all_producers-from posthog.models.person.deletion import OrphanRepairResult, find_orphaned_ch_persons, tombstone_orphaned_ch_persons+from posthog.models.person.deletion import (+ OrphanRepairResult,+ count_live_ch_persons,+ find_orphaned_ch_persons,+ orphan_share_refusal,+ tombstone_orphaned_ch_persons,+)logger = structlog.get_logger(__name__)logger.setLevel(logging.INFO)@@ -40,6 +46,11 @@ class Command(BaseCommand):default=True,help="Report what would change without writing (default: on). Pass --no-dry-run to apply.",)+ parser.add_argument(+ "--force",+ action="store_true",+ help="Apply even when the orphans are more than 5%% of the team's live ClickHouse persons.",+ )def handle(self, *args, **options):run(options)@@ -72,6 +83,13 @@ def run(options) -> None:not_orphaned=not_orphaned,)+ refusal = orphan_share_refusal(team_id, len(orphans), count_live_ch_persons(team_id)) if orphans else None+ if refusal:+ if not dry_run and not options.get("force"):+ logger.error(refusal)+ exit(1)+ logger.warning(refusal)+result = tombstone_orphaned_ch_persons(team_id, orphans, dry_run=dry_run)_log_result(team_id, result)@@ -100,8 +118,7 @@ def _log_result(team_id: int, result: OrphanRepairResult) -> None: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,+ skipped_live_persons=result.skipped_live_persons,reverse_drift_mappings=len(result.reverse_drift_mappings),)if result.reverse_drift_mappings:diff --git a/posthog/management/commands/sync_persons_to_clickhouse.py b/posthog/management/commands/sync_persons_to_clickhouse.pyindex 715c3d1a1c40..fbc726e668ce 100644--- a/posthog/management/commands/sync_persons_to_clickhouse.py+++ b/posthog/management/commands/sync_persons_to_clickhouse.py@@ -15,9 +15,19 @@ from django.core.management.base import BaseCommandimport structlogfrom posthog.clickhouse.client import sync_execute+from posthog.dataclasses import frozenfrom posthog.kafka_client.routing import flush_all_producersfrom posthog.models.group.util import raw_create_group_ch-from posthog.models.person.util import _delete_ch_distinct_id, create_person, create_person_distinct_id+from posthog.models.person.deletion import orphan_share_refusal+from posthog.models.person.util import (+ PERSONHOG_BATCH_SIZE,+ PersonVersionFloor,+ VersionFloorOutcome,+ create_person,+ create_person_distinct_id,+ ensure_person_version_floors,+ set_distinct_id_version_floor,+)from posthog.persons_db import persons_db_connectionlogger = structlog.get_logger(__name__)@@ -45,6 +55,11 @@ class Command(BaseCommand):help="process deletes for data in ClickHouse but not Postgres",)parser.add_argument("--live-run", action="store_true", help="Run changes, default is dry-run")+ parser.add_argument(+ "--force",+ action="store_true",+ help="Process deletes even when persons missing from Postgres are more than 5%% of ClickHouse's.",+ )def handle(self, *args, **options):run(options)@@ -61,7 +76,7 @@ def run(options):team_id = options["team_id"]if options["person"]:- run_person_sync(team_id, live_run, deletes)+ run_person_sync(team_id, live_run, deletes, force=options.get("force", False))if options["person_distinct_id"]:run_distinct_id_sync(team_id, live_run, deletes)@@ -74,7 +89,7 @@ def run(options):logger.info("Kafka producer queue flushed.")-def run_person_sync(team_id: int, live_run: bool, deletes: bool):+def run_person_sync(team_id: int, live_run: bool, deletes: bool, force: bool = False):logger.info("Running person table sync")# lookup what needs to be updated in ClickHouse and send kafka messages for only thosewith persons_db_connection(writer=False) as conn, conn.cursor() as cursor:@@ -130,19 +145,140 @@ def run_person_sync(team_id: int, live_run: bool, deletes: bool):if deletes:logger.info("Processing person deletions")postgres_uuids = {person["uuid"] for person in persons}+ postgres_tombstones = _postgres_person_tombstones(team_id)+ floors: list[PersonVersionFloor] = []for uuid, version in ch_persons_to_version.items():- if uuid not in postgres_uuids:- logger.info(f"Deleting person with uuid={uuid}")- if live_run:- create_person(- uuid=str(uuid),- team_id=team_id,- properties={},- # Keep this tombstone version in sync with deletePerson in- # nodejs/src/common/persons/repositories/postgres-person-repository.ts.- version=int(version or 0) + 100,- is_deleted=True,+ if uuid in postgres_uuids:+ continue+ ch_version = int(version or 0)+ logger.info(f"Deleting person with uuid={uuid} at version {ch_version + 1} or above")+ floors.append(PersonVersionFloor(uuid=UUID(str(uuid)), min_version=ch_version + 1))+ missing = sum(1 for floor in floors if floor.uuid not in postgres_tombstones)+ refusal = orphan_share_refusal(team_id, missing, len(ch_persons_to_version))+ if refusal:+ if live_run and not force:+ logger.error(refusal)+ exit(1)+ logger.warning(refusal)+ if live_run:+ _tombstone_persons_above_clickhouse(team_id, floors)+++def _tombstone_persons_above_clickhouse(team_id: int, floors: list[PersonVersionFloor]) -> None:+ """Raise each person's Postgres tombstone above its ClickHouse version, then publish the version Postgres stores.++ A ClickHouse tombstone above the Postgres version would hide the next revival. A person that+ ensure_person_version_floors finds live on the primary is skipped. Each batch is published before the next+ starts, so a failure leaves no committed tombstone unpublished.+ """+ skipped_live = 0+ undelivered = 0+ try:+ for i in range(0, len(floors), PERSONHOG_BATCH_SIZE):+ for result in ensure_person_version_floors(team_id, floors[i : i + PERSONHOG_BATCH_SIZE]):+ if result.outcome == VersionFloorOutcome.LIVE:+ logger.warning(f"Skipping person uuid={result.uuid}: the Postgres primary holds it live")+ skipped_live += 1+ continue+ _publish_person_tombstone(team_id, result.uuid, result.version)+ finally:+ undelivered = flush_all_producers(5 * 60)+ _exit_if_undelivered(undelivered)+ if skipped_live:+ logger.warning(f"Skipped {skipped_live} persons that the Postgres primary holds live")+++def _exit_if_undelivered(undelivered: int) -> None:+ # Postgres already holds the versions these messages carry, so a rerun republishes them.+ if undelivered:+ logger.error(f"{undelivered} Kafka messages were not delivered; rerun the command to republish them")+ exit(1)+++def _publish_person_tombstone(team_id: int, uuid: UUID, version: int) -> None:+ create_person(uuid=str(uuid), team_id=team_id, properties={}, version=version, is_deleted=True)+++def _postgres_person_tombstones(team_id: int) -> set[UUID]:+ """The persons Postgres holds as tombstones, which orphan_share_refusal must not count as missing."""+ with persons_db_connection(writer=False) as conn, conn.cursor() as cursor:+ cursor.execute("SELECT uuid FROM posthog_person WHERE team_id = %s AND is_deleted = true", [team_id])+ return {uuid for (uuid,) in cursor.fetchall()}+++def _postgres_distinct_id_tombstone_versions(team_id: int) -> dict[str, int]:+ """The version each tombstoned mapping holds in the replica."""+ with persons_db_connection(writer=False) as conn, conn.cursor() as cursor:+ cursor.execute(+ "SELECT distinct_id, version FROM posthog_persondistinctid WHERE team_id = %s AND is_deleted = true",+ [team_id],+ )+ return {distinct_id: int(version or 0) for distinct_id, version in cursor.fetchall()}+++@frozen+class _PrimaryDistinctId:+ person_uuid: UUID+ is_deleted: bool+ version: int+++def _primary_distinct_id_rows(team_id: int, distinct_ids: list[str]) -> dict[str, _PrimaryDistinctId]:+ """The owner, tombstone flag and version the Postgres primary holds for each distinct id.++ SetPersonDistinctIdVersionFloor does not return this, and personhog's primary reads list only live mappings.+ """+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:+ cursor.execute(+ "SELECT pdi.distinct_id, p.uuid, pdi.is_deleted, pdi.version "+ "FROM posthog_persondistinctid pdi JOIN posthog_person p ON p.id = pdi.person_id "+ "WHERE pdi.team_id = %s AND pdi.distinct_id = ANY(%s)",+ [team_id, distinct_ids],+ )+ return {+ distinct_id: _PrimaryDistinctId(person_uuid=uuid, is_deleted=bool(is_deleted), version=int(version or 0))+ for distinct_id, uuid, is_deleted, version in cursor.fetchall()+ }+++def _tombstone_distinct_ids_above_clickhouse(+ team_id: int, ch_versions: dict[str, int], tombstone_versions: dict[str, int]+) -> None:+ """Raise each mapping tombstone above its ClickHouse version, then publish the row the Postgres primary holds.++ A mapping revived since the replica read is published live at its stored version, and a tombstone is+ published only when the primary still holds it.+ """+ distinct_ids = list(ch_versions)+ undelivered = 0+ try:+ for i in range(0, len(distinct_ids), PERSONHOG_BATCH_SIZE):+ batch = distinct_ids[i : i + PERSONHOG_BATCH_SIZE]+ for distinct_id in batch:+ if tombstone_versions[distinct_id] <= ch_versions[distinct_id]:+ set_distinct_id_version_floor(team_id, distinct_id, ch_versions[distinct_id] + 1)+ primary_rows = _primary_distinct_id_rows(team_id, batch)+ for distinct_id in batch:+ row = primary_rows.get(distinct_id)+ if row is None or row.version <= ch_versions[distinct_id]:+ logger.warning(+ f"Skipping distinct ID {distinct_id}: the Postgres primary holds no row above "+ f"ClickHouse version {ch_versions[distinct_id]}")+ continue+ logger.info(+ f"Publishing distinct ID {distinct_id} at version {row.version} (is_deleted={row.is_deleted})"+ )+ create_person_distinct_id(+ team_id=team_id,+ distinct_id=distinct_id,+ person_id=str(row.person_uuid),+ version=row.version,+ is_deleted=row.is_deleted,+ )+ finally:+ undelivered = flush_all_producers(5 * 60)+ _exit_if_undelivered(undelivered)def run_distinct_id_sync(team_id: int, live_run: bool, deletes: bool):@@ -199,11 +335,21 @@ def run_distinct_id_sync(team_id: int, live_run: bool, deletes: bool):if deletes:logger.info("Processing distinct id deletions")postgres_distinct_ids = {pdi["distinct_id"] for pdi in person_distinct_ids}+ tombstone_versions = _postgres_distinct_id_tombstone_versions(team_id)+ ch_versions: dict[str, int] = {}for distinct_id, version in ch_distinct_id_to_version.items():- if distinct_id not in postgres_distinct_ids:- logger.info(f"Deleting distinct ID {distinct_id}")- if live_run:- _delete_ch_distinct_id(team_id, UUID(int=0), distinct_id, version)+ if distinct_id in postgres_distinct_ids:+ continue+ if distinct_id not in tombstone_versions:+ # With no Postgres row there is no version to publish. The ClickHouse deletion sweep removes the+ # mapping only once its owner is deleted, so a mapping with a live owner needs a Postgres restore.+ logger.warning(f"Skipping distinct ID {distinct_id}: Postgres has no row for it")+ continue+ ch_versions[distinct_id] = int(version or 0)+ target_version = max(tombstone_versions[distinct_id], ch_versions[distinct_id] + 1)+ logger.info(f"Deleting distinct ID {distinct_id} at version {target_version} or above")+ if live_run:+ _tombstone_distinct_ids_above_clickhouse(team_id, ch_versions, tombstone_versions)def run_group_sync(team_id: int, live_run: bool):diff --git a/posthog/management/commands/test/test_sync_persons_to_clickhouse.py b/posthog/management/commands/test/test_sync_persons_to_clickhouse.pyindex 2e7f8687a5d9..da98f67fef9b 100644--- a/posthog/management/commands/test/test_sync_persons_to_clickhouse.py+++ b/posthog/management/commands/test/test_sync_persons_to_clickhouse.py@@ -6,6 +6,7 @@ import pytestfrom posthog.test.base import ClickhouseTestMixin, NonAtomicBaseTestfrom unittest import mock+from parameterized import parameterizedfrom psycopg.types.json import Jsonbimport posthog.management.commands.sync_persons_to_clickhouse@@ -24,11 +25,38 @@ from posthog.models.person.sql import (TRUNCATE_PERSON_TABLE_SQL,)from posthog.models.person.util import create_person, create_person_distinct_id+from posthog.personhog_client.fake_client import fake_personhog_clientfrom posthog.persons_db import persons_db_connectionfrom posthog.persons_seed import insert_seed_distinct_id, insert_seed_group, insert_seed_personpytestmark = pytest.mark.persons_db_direct+SYNC_MODULE = posthog.management.commands.sync_persons_to_clickhouse.__name__+++def _raise_distinct_id_version_in_postgres(+ team_id: int, distinct_id: str, min_version: int, *, revive: bool = False+) -> None:+ # The personhog fake keeps its own store, so write the same version update to the persons DB the sync reads.+ with persons_db_connection(writer=True, autocommit=True) as conn, conn.cursor() as cursor:+ cursor.execute(+ "UPDATE posthog_persondistinctid SET version = %s, is_deleted = is_deleted AND NOT %s "+ "WHERE team_id = %s AND distinct_id = %s AND COALESCE(version, 0) < %s",+ [min_version, revive, team_id, distinct_id, min_version],+ )+++def _fail_the_second_call(method):+ requests = []++ def call(request, timeout=None):+ requests.append(request)+ if len(requests) == 2:+ raise RuntimeError("personhog down")+ return method(request, timeout)++ return call, requests+@pytest.mark.eeclass TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):@@ -43,6 +71,15 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):sync_execute(TRUNCATE_PERSON_DISTINCT_ID2_TABLE_SQL)sync_execute(TRUNCATE_GROUPS_TABLE_SQL)+ def _seed_tombstoned_person(self, person_uuid: UUID, version: int) -> None:+ with persons_db_connection(writer=True, autocommit=True) as conn:+ insert_seed_person(conn, team_id=self.team.pk, properties={}, version=version, uuid=person_uuid)+ with conn.cursor() as cursor:+ cursor.execute(+ "UPDATE posthog_person SET is_deleted = true WHERE team_id = %s AND uuid = %s",+ [self.team.pk, person_uuid],+ )+def test_persons_sync(self):person_uuid = uuid4()with persons_db_connection(writer=True, autocommit=True) as conn:@@ -95,15 +132,131 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):properties={"abc": 123},)- run_person_sync(self.team.pk, live_run=True, deletes=True)+ with fake_personhog_client() as personhog:+ # The only ClickHouse person is missing from Postgres, which is over the share limit.+ run_person_sync(self.team.pk, live_run=True, deletes=True, force=True)+ stored = personhog.stored_person(self.team.pk, uuid)+ # Postgres takes the tombstone first, so a later revival lands above the ClickHouse row.+ assert stored is not None and (stored.is_deleted, stored.version) == (True, 6)ch_persons = sync_execute("""SELECT id, team_id, properties, is_identified, version, is_deleted FROM person FINAL WHERE team_id = %(team_id)s""",{"team_id": self.team.pk},)- self.assertEqual(ch_persons, [(UUID(uuid), self.team.pk, "{}", False, 105, True)])+ self.assertEqual(ch_persons, [(UUID(uuid), self.team.pk, "{}", False, 6, True)])++ @parameterized.expand([("persons",), ("distinct_ids",)])+ def test_deletes_fail_when_kafka_leaves_messages_undelivered(self, path):+ if path == "persons":+ create_person(uuid=str(uuid4()), team_id=self.team.pk, version=5, properties={})+ else:+ person_uuid = uuid4()+ with persons_db_connection(writer=True, autocommit=True) as conn:+ person_id = insert_seed_person(conn, team_id=self.team.pk, properties={}, version=0, uuid=person_uuid)+ insert_seed_distinct_id(+ conn, team_id=self.team.pk, person_id=person_id, distinct_id="test-id", version=7+ )+ with conn.cursor() as cursor:+ cursor.execute(+ "UPDATE posthog_persondistinctid SET is_deleted = true WHERE team_id = %s AND distinct_id = %s",+ [self.team.pk, "test-id"],+ )+ create_person_distinct_id(+ team_id=self.team.pk, distinct_id="test-id", person_id=str(person_uuid), is_deleted=False, version=3+ )++ with (+ fake_personhog_client(),+ mock.patch(f"{SYNC_MODULE}.flush_all_producers", return_value=2),+ pytest.raises(SystemExit),+ ):+ if path == "persons":+ run_person_sync(self.team.pk, live_run=True, deletes=True, force=True)+ else:+ run_distinct_id_sync(self.team.pk, live_run=True, deletes=True)++ def test_deletes_refuse_a_large_share_of_persons_missing_from_postgres(self):+ uuid = create_person(uuid=str(uuid4()), team_id=self.team.pk, version=5, properties={"abc": 123})++ with fake_personhog_client() as personhog, self.assertRaises(SystemExit):+ run_person_sync(self.team.pk, live_run=True, deletes=True)++ assert personhog.stored_person(self.team.pk, uuid) is None+ ch_persons = sync_execute(+ "SELECT version, is_deleted FROM person FINAL WHERE team_id = %(team_id)s", {"team_id": self.team.pk}+ )+ self.assertEqual(ch_persons, [(5, False)])++ @parameterized.expand(+ [+ # (name, version of the replica's tombstone, or None when the replica has no row)+ ("missing_from_the_replica", None),+ ("tombstoned_in_the_replica_above_clickhouse", 9),+ ]+ )+ def test_a_person_live_on_the_postgres_primary_is_not_tombstoned(self, _name, replica_tombstone_version):+ uuid = create_person(uuid=str(uuid4()), team_id=self.team.pk, version=5, properties={"abc": 123})+ if replica_tombstone_version is not None:+ self._seed_tombstoned_person(UUID(uuid), replica_tombstone_version)++ # The sync's replica read misses this person, but the primary that personhog reads holds it live.+ with fake_personhog_client() as personhog:+ personhog.add_person(team_id=self.team.pk, person_id=1, uuid=uuid, version=5)+ run_person_sync(self.team.pk, live_run=True, deletes=True, force=True)++ ch_persons = sync_execute(+ "SELECT version, is_deleted FROM person FINAL WHERE team_id = %(team_id)s", {"team_id": self.team.pk}+ )+ self.assertEqual(ch_persons, [(5, False)])++ @parameterized.expand(+ [+ # (name, ClickHouse live version, expected row after the sync)+ ("stored_version_wins", 5, ('{"abc": 123}', 9, True)),+ ("clickhouse_ahead_is_raised_above", 9, ('{"abc": 123}', 10, True)),+ ]+ )+ def test_persons_tombstoned_in_postgres_publish_the_stored_version(self, _name, ch_version, expected):+ person_uuid = uuid4()+ self._seed_tombstoned_person(person_uuid, 9)+ create_person(uuid=str(person_uuid), team_id=self.team.pk, version=ch_version, properties={"abc": 123})++ with fake_personhog_client() as personhog:+ personhog.add_person(team_id=self.team.pk, person_id=1, uuid=str(person_uuid), version=9, is_deleted=True)+ run_person_sync(self.team.pk, live_run=True, deletes=True)++ ch_persons = sync_execute(+ """+ SELECT id, team_id, properties, version, is_deleted FROM person FINAL WHERE team_id = %(team_id)s+ """,+ {"team_id": self.team.pk},+ )+ properties, version, is_deleted = expected+ # The tombstone carries the stored Postgres version, so the next revival lands above it.+ self.assertEqual(+ ch_persons, [(person_uuid, self.team.pk, "{}" if is_deleted else properties, version, is_deleted)]+ )++ def test_a_failed_person_batch_leaves_earlier_batches_published(self):+ for _ in range(2):+ create_person(uuid=str(uuid4()), team_id=self.team.pk, version=2, properties={})++ with fake_personhog_client() as personhog:+ ensure_floors, requests = _fail_the_second_call(personhog.ensure_person_version_floors)+ with (+ mock.patch(f"{SYNC_MODULE}.PERSONHOG_BATCH_SIZE", 1),+ mock.patch.object(personhog, "ensure_person_version_floors", side_effect=ensure_floors),+ self.assertRaises(RuntimeError),+ ):+ run_person_sync(self.team.pk, live_run=True, deletes=True, force=True)++ first, second = (UUID(r.floors[0].person_uuid) for r in requests)+ ch_persons = sync_execute(+ "SELECT id, version, is_deleted FROM person FINAL WHERE team_id = %(team_id)s", {"team_id": self.team.pk}+ )+ self.assertCountEqual(ch_persons, [(first, 3, True), (second, 2, False)])def test_distinct_ids_sync(self):person_uuid = uuid4()@@ -140,7 +293,7 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):)self.assertEqual(ch_person_distinct_ids, [(person_uuid, self.team.pk, "test-id", 0, False)])- def test_distinct_ids_deleted(self):+ def test_distinct_ids_without_a_postgres_row_are_left_alone(self):uuid = uuid4()create_person_distinct_id(team_id=self.team.pk,@@ -157,10 +310,55 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):""",{"team_id": self.team.pk},)- self.assertEqual(- ch_person_distinct_ids,- [(UUID(int=0), self.team.pk, "test-id-7", 107, True)],+ # A tombstone naming the all-zero person would be copied into events by the overrides squash.+ self.assertEqual(ch_person_distinct_ids, [(uuid, self.team.pk, "test-id-7", 7, False)])++ @parameterized.expand(+ [+ # (name, ClickHouse live version, mapping revives during the raise, expected version and is_deleted)+ ("stored_version_wins", 3, False, (7, True)),+ ("clickhouse_ahead_is_raised_above", 7, False, (8, True)),+ ("revived_during_the_raise_is_published_live", 7, True, (8, False)),+ ]+ )+ def test_distinct_ids_tombstoned_in_postgres_publish_the_primary_row(self, _name, ch_version, revives, expected):+ person_uuid = uuid4()+ with persons_db_connection(writer=True, autocommit=True) as conn:+ person_id = insert_seed_person(conn, team_id=self.team.pk, properties={}, version=0, uuid=person_uuid)+ insert_seed_distinct_id(conn, team_id=self.team.pk, person_id=person_id, distinct_id="test-id", version=7)+ with conn.cursor() as cursor:+ cursor.execute(+ "UPDATE posthog_persondistinctid SET is_deleted = true WHERE team_id = %s AND distinct_id = %s",+ [self.team.pk, "test-id"],+ )+ create_person_distinct_id(+ team_id=self.team.pk,+ distinct_id="test-id",+ person_id=str(person_uuid),+ is_deleted=False,+ version=ch_version,+ )++ with mock.patch(+ f"{SYNC_MODULE}.set_distinct_id_version_floor",+ side_effect=lambda *args: _raise_distinct_id_version_in_postgres(*args, revive=revives),+ ):+ run_distinct_id_sync(self.team.pk, live_run=True, deletes=True)++ ch_person_distinct_ids = sync_execute(+ f"""+ SELECT person_id, team_id, distinct_id, version, is_deleted FROM {PERSON_DISTINCT_ID2_TABLE} FINAL WHERE team_id = %(team_id)s+ """,+ {"team_id": self.team.pk},)+ version, is_deleted = expected+ self.assertEqual(ch_person_distinct_ids, [(person_uuid, self.team.pk, "test-id", version, is_deleted)])+ with persons_db_connection(writer=True) as conn, conn.cursor() as cursor:+ cursor.execute(+ "SELECT version, is_deleted FROM posthog_persondistinctid WHERE team_id = %s AND distinct_id = %s",+ [self.team.pk, "test-id"],+ )+ self.assertEqual(cursor.fetchall(), [(version, is_deleted)])@mock.patch(f"{posthog.management.commands.sync_persons_to_clickhouse.__name__}.raw_create_group_ch",@@ -519,8 +717,11 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):"person_override": True,"group": True,"deletes": True,+ # Two of its six ClickHouse persons are missing from Postgres, over the share limit.+ "force": True,}- run(options)+ with fake_personhog_client():+ run(options)ch_persons = sync_execute("""@@ -689,8 +890,8 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):7,False,),- (UUID(deleted_person_1_uuid), self.team.pk, "{}", False, 107, True),- (UUID(deleted_person_2_uuid), self.team.pk, "{}", False, 108, True),+ (UUID(deleted_person_1_uuid), self.team.pk, "{}", False, 8, True),+ (UUID(deleted_person_2_uuid), self.team.pk, "{}", False, 9, True),],)self.assertEqual(@@ -732,8 +933,8 @@ class TestSyncPersonsToClickHouse(NonAtomicBaseTest, ClickhouseTestMixin):15,False,),- (UUID(int=0), self.team.pk, "distinct_id-17", 117, True),- (UUID(int=0), self.team.pk, "distinct_id-18", 118, True),+ (deleted_distinct_id_1_uuid, self.team.pk, "distinct_id-17", 17, False),+ (deleted_distinct_id_2_uuid, self.team.pk, "distinct_id-18", 18, False),],)self.assertEqual(ch_groups, [(2, "group-key", '{"a": 1234}')])diff --git a/posthog/models/person/deletion.py b/posthog/models/person/deletion.pyindex d742d9d23e05..fbc1605713d2 100644--- a/posthog/models/person/deletion.py+++ b/posthog/models/person/deletion.py@@ -9,10 +9,14 @@ from rest_framework.exceptions import NotFoundfrom posthog.clickhouse.client import sync_executefrom posthog.models.person import Personfrom posthog.models.person.util import (+ PERSONHOG_BATCH_SIZE,PersonTombstone,PersonTombstonePublication,+ PersonVersionFloor,+ VersionFloorOutcome,create_person,create_person_distinct_id,+ ensure_person_version_floors,get_person_by_distinct_id,get_person_tombstones,get_persons_by_uuids,@@ -256,13 +260,12 @@ class _Mapping:@dataclass(frozen=False)class OrphanRepairResult:orphaned_person_uuids: list[str]+ # Orphans with no persons-DB row, which get a new persons-DB tombstone above ClickHouse.tombstoned_persons: int = 0- # Orphans that are tombstoned in the persons DB, republished at the versions it holds.+ # Orphans that are tombstoned in the persons DB, raised above ClickHouse when needed and republished.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.- skipped_reassigned_mappings: int = 0+ # Orphans the persons-DB primary holds as live, which a lagging replica read reported as missing.+ skipped_live_persons: int = 0# (distinct_id, winner_uuid) pairs where the CH mapping is tombstoned but the# winning person is live in the persons DB — the opposite drift, handled by# reset_all_deleted_person_distinct_ids, reported here rather than repaired.@@ -270,6 +273,34 @@ class OrphanRepairResult:dry_run: bool = False+# Past this share of live ClickHouse persons missing from the persons DB, the team likely needs a restore.+ORPHAN_TOMBSTONE_SHARE_LIMIT = 0.05+++def count_live_ch_persons(team_id: int) -> int:+ rows = sync_execute(+ """+ SELECT count() FROM (+ SELECT id FROM person WHERE team_id = %(team_id)s GROUP BY id HAVING argMax(is_deleted, version) = 0+ )+ """,+ {"team_id": team_id},+ )+ return int(rows[0][0])+++def orphan_share_refusal(team_id: int, to_tombstone: int, live_ch_persons: int) -> Optional[str]:+ """Return why tombstoning this many ClickHouse-only persons is refused, or None when it is within the limit."""+ if to_tombstone <= ORPHAN_TOMBSTONE_SHARE_LIMIT * live_ch_persons:+ return None+ return (+ f"Refusing to tombstone {to_tombstone} of the {live_ch_persons} live ClickHouse persons of team {team_id}, "+ f"more than {ORPHAN_TOMBSTONE_SHARE_LIMIT:.0%}. A team whose persons-DB persons were lost, for example by "+ "an interrupted project deletion, needs a restore, and tombstoning destroys the ClickHouse copy the restore "+ "reads from. Pass --force only if these persons should really be deleted."+ )++def find_orphaned_ch_persons(team_id: int, uuids: Optional[list[str]] = None) -> list[OrphanedPerson]:"""Return ClickHouse person rows that are live in CH but have no persons-DB row.@@ -296,88 +327,51 @@ def find_orphaned_ch_persons(team_id: int, uuids: Optional[list[str]] = None) ->def tombstone_orphaned_ch_persons(team_id: int, orphans: list[OrphanedPerson], *, dry_run: bool = True) -> OrphanRepairResult:- """Produce ClickHouse tombstones for orphaned persons and the distinct_id- mappings they still win.-- A mapping is only tombstoned when its current CH winner is one of the orphans- 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.+ """Tombstone orphaned persons in the persons DB one version above ClickHouse, then publish those tombstones.++ Each ClickHouse tombstone carries the exact stored version, so a later revival lands above it and a rerun+ republishes the same versions. Distinct ids get no tombstone of their own, because the ClickHouse deletion+ sweep removes every live mapping of a person it deletes."""result = OrphanRepairResult(orphaned_person_uuids=sorted(o.uuid for o in orphans), dry_run=dry_run)if not orphans:return resultorphan_uuids = {o.uuid for o in orphans}- to_tombstone: list[_Mapping] = []- deleted_winners: list[_Mapping] = []- for mapping in _ch_mappings_for_persons(team_id, orphan_uuids):- if mapping.winner_is_deleted:- deleted_winners.append(mapping)- elif mapping.winner_person_id in orphan_uuids:- to_tombstone.append(mapping)- else:- result.skipped_reassigned_mappings += 1-+ deleted_winners = [m for m in _ch_mappings_for_persons(team_id, orphan_uuids) if m.winner_is_deleted]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}-+ stored_by_uuid = {str(t.uuid): t for t in get_person_tombstones(team_id, [UUID(o.uuid) for o in orphans])}if dry_run: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(- uuid=orphan.uuid,- team_id=team_id,- version=orphan.ch_max_version + 100,- created_at=orphan.created_at,- is_deleted=True,- )- result.tombstoned_persons += 1-+ created_at_by_uuid = {o.uuid: o.created_at for o in orphans}+ floors = [PersonVersionFloor(uuid=UUID(o.uuid), min_version=o.ch_max_version + 1) for o in orphans]publication = PersonTombstonePublication(team_id=team_id, source="orphan_repair")- 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,- person_id=mapping.winner_person_id,- version=mapping.max_version + 100,- is_deleted=True,- )- 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()+ try:+ # Each batch commits on its own, so it is published before the next batch starts, and a later failure+ # leaves no committed tombstone unpublished.+ for i in range(0, len(floors), PERSONHOG_BATCH_SIZE):+ to_publish: list[tuple[PersonTombstone, Optional[dt.datetime]]] = []+ for floor in ensure_person_version_floors(team_id, floors[i : i + PERSONHOG_BATCH_SIZE]):+ uuid = str(floor.uuid)+ if floor.outcome == VersionFloorOutcome.LIVE:+ result.skipped_live_persons += 1+ continue+ stored = stored_by_uuid.get(uuid)+ if stored is None:+ result.tombstoned_persons += 1+ else:+ result.republished_persons += 1+ tombstone = PersonTombstone(+ uuid=floor.uuid, version=floor.version, distinct_ids=stored.distinct_ids if stored else []+ )+ to_publish.append((tombstone, created_at_by_uuid[uuid]))+ publication.publish(to_publish)+ finally:+ publication.await_and_ack()if publication.failures:raise publication.failures[0].errorreturn resultdiff --git a/posthog/models/person/test/test_orphaned_ch_persons.py b/posthog/models/person/test/test_orphaned_ch_persons.pyindex e2eccdcea419..27305f7fd83f 100644--- a/posthog/models/person/test/test_orphaned_ch_persons.py+++ b/posthog/models/person/test/test_orphaned_ch_persons.py@@ -6,6 +6,7 @@ from unittest.mock import patchfrom parameterized import parameterizedfrom posthog.clickhouse.client import sync_execute+from posthog.management.commands.fix_orphaned_ch_persons import run as run_orphan_repairfrom posthog.models.person.deletion import OrphanedPerson, find_orphaned_ch_persons, tombstone_orphaned_ch_personsfrom posthog.models.person.util import (create_person as create_person_in_ch,@@ -50,89 +51,118 @@ class TestOrphanedCHPersonRepair(ClickhouseTestMixin, BaseTest):)return str(rows[0][0]), int(rows[0][1]), int(rows[0][2])- def test_orphan_is_tombstoned_and_disappears(self):+ def _stored(self, uuid: str) -> tuple[bool, int] | None:+ person = get_active_fake().stored_person(self.team.pk, uuid)+ return None if person is None else (person.is_deleted, person.version)++ def test_orphan_gets_a_persons_db_tombstone_above_clickhouse_and_disappears(self):uuid = str(uuid4())self._seed_ch_only_person(uuid, ["did-a", "did-b"], version=5)orphans = find_orphaned_ch_persons(self.team.pk, [uuid])- assert [o.uuid for o in orphans] == [uuid]- assert orphans[0].ch_max_version == 5+ assert [(o.uuid, o.ch_max_version) for o in orphans] == [(uuid, 5)]result = tombstone_orphaned_ch_persons(self.team.pk, orphans, dry_run=False)- assert result.tombstoned_persons == 1- assert result.tombstoned_mappings == 2-- is_deleted, version = self._ch_person_state(uuid)- assert is_deleted == 1- assert version == 105 # ch_max_version + 100- # Gone from the live-person read path.+ assert (result.tombstoned_persons, result.republished_persons, result.skipped_live_persons) == (1, 0, 0)+ assert self._stored(uuid) == (True, 6)+ assert self._ch_person_state(uuid) == (1, 6)assert find_orphaned_ch_persons(self.team.pk, [uuid]) == []+ # The ClickHouse deletion sweep removes these with their deleted owner, so the repair writes no mapping row.for did in ("did-a", "did-b"):- _, mapping_deleted, _ = self._ch_mapping_state(did)- assert mapping_deleted == 1+ assert self._ch_mapping_state(did) == (uuid, 0, 0)- @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):+ @parameterized.expand(+ [+ # (name, ClickHouse max version, persons-DB version expected after the repair)+ ("at_or_above_clickhouse", 0, None),+ ("below_a_live_clickhouse_row", 7, 8),+ ]+ )+ def test_person_tombstoned_in_the_persons_db_is_raised_above_clickhouse_and_republished(+ self, _name: str, ch_max_version: int, raised_to: int | None+ ):person = create_person(team=self.team, distinct_ids=["did-t"], properties={})[written] = tombstone_persons_in_postgres(self.team.pk, [person.uuid])+ if ch_max_version:+ create_person_in_ch(uuid=str(person.uuid), team_id=self.team.pk, version=ch_max_version, is_deleted=False)# 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)+ orphan = OrphanedPerson(uuid=str(person.uuid), ch_max_version=ch_max_version, created_at=person.created_at)- result = tombstone_orphaned_ch_persons(self.team.pk, [orphan], dry_run=dry_run)+ result = tombstone_orphaned_ch_persons(self.team.pk, [orphan], dry_run=False)+ version = raised_to or written.versionassert (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._stored(str(person.uuid)) == (True, version)+ assert self._ch_person_state(str(person.uuid)) == (1, 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):+ def test_live_person_reported_as_orphan_by_a_lagging_read_is_left_alone(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 (result.skipped_live_persons, result.tombstoned_persons, result.republished_persons) == (1, 0, 0)assert get_person_tombstones(self.team.pk, [person.uuid]) == []- assert self._ch_person_state(str(person.uuid)) == (1, 100)+ assert self._ch_person_state(str(person.uuid))[0] == 0- 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),- ]+ def test_a_rerun_after_a_failed_publish_republishes_the_tombstone_it_inserted(self):+ uuid = str(uuid4())+ self._seed_ch_only_person(uuid, ["did-o"], version=2)+ orphans = find_orphaned_ch_persons(self.team.pk, [uuid])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)+ assert self._stored(uuid) == (True, 3)+ assert self._ch_person_state(uuid) == (0, 2)++ # The rerun finds the tombstone it inserted and still publishes it.+ result = tombstone_orphaned_ch_persons(self.team.pk, orphans, dry_run=False)++ assert result.republished_persons == 1+ assert self._ch_person_state(uuid) == (1, 3)++ def test_a_failed_batch_leaves_earlier_batches_published(self):+ uuids = [str(uuid4()), str(uuid4())]+ for uuid in uuids:+ self._seed_ch_only_person(uuid, [], version=2)+ orphans = find_orphaned_ch_persons(self.team.pk, uuids)+ fake = get_active_fake()+ ensure_floors = fake.ensure_person_version_floors+ requests = []++ def fail_the_second_batch(request, timeout=None):+ requests.append(request)+ if len(requests) == 2:+ raise RuntimeError("personhog down")+ return ensure_floors(request, timeout)++ with (+ patch("posthog.models.person.deletion.PERSONHOG_BATCH_SIZE", 1),+ patch.object(fake, "ensure_person_version_floors", side_effect=fail_the_second_batch),+ 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+ first, second = (r.floors[0].person_uuid for r in requests)+ assert (self._stored(first), self._ch_person_state(first)) == ((True, 3), (1, 3))+ assert (self._stored(second), self._ch_person_state(second)) == (None, (0, 2))- def test_dry_run_produces_nothing(self):+ def test_dry_run_writes_nothing(self):uuid = str(uuid4())self._seed_ch_only_person(uuid, ["did-a"], version=3)orphans = find_orphaned_ch_persons(self.team.pk, [uuid])+result = tombstone_orphaned_ch_persons(self.team.pk, orphans, dry_run=True)- # Counts reflect what would happen...- assert result.dry_run is True- assert result.tombstoned_persons == 1- assert result.tombstoned_mappings == 1- # ...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"]+ assert (result.dry_run, result.tombstoned_persons) == (True, 1)+ assert self._ch_person_state(uuid) == (0, 3)+ assert self._stored(uuid) is None+ assert not [c for c in get_active_fake().calls if c.method == "ensure_person_version_floors"]def test_live_person_is_never_an_orphan(self):# A person present in the persons DB (seeded into the fake) must not be@@ -150,62 +180,59 @@ class TestOrphanedCHPersonRepair(ClickhouseTestMixin, BaseTest):@parameterized.expand([- # (name, mapping outcome for the shared distinct_id)- ("self_owned_live", "tombstone"),- ("reassigned_to_live_other", "skip_reassigned"),- ("reverse_drift_db_live", "reverse_drift"),+ # (name, how the shared distinct_id's ClickHouse winner looks)+ ("self_owned_live", None),+ ("reassigned_to_live_other", "live_other"),+ ("reverse_drift_db_live", "deleted_mapping_of_live_person"),])- def test_mapping_classification(self, _name: str, outcome: str):+ def test_mappings_are_left_alone_and_reverse_drift_is_reported(self, _name: str, other: str | None):orphan_uuid = str(uuid4())shared_did = "shared-did"-self._seed_ch_only_person(orphan_uuid, [shared_did], version=5)-- other_uuid: str | None = None- if outcome == "skip_reassigned":- # A different, non-deleted CH mapping wins shared_did — reassigned.+ other_uuid = None+ if other == "live_other":other_uuid = str(uuid4())create_person_distinct_id(- team_id=self.team.pk,- distinct_id=shared_did,- person_id=other_uuid,- version=1,- is_deleted=False,+ team_id=self.team.pk, distinct_id=shared_did, person_id=other_uuid, version=1, is_deleted=False)- elif outcome == "reverse_drift":- # A person live in the persons DB whose CH mapping for shared_did is- # tombstoned — the opposite drift, reported not repaired.- other = create_person(team=self.team, distinct_ids=["other-did"], properties={})- other_uuid = str(other.uuid)+ elif other == "deleted_mapping_of_live_person":+ other_uuid = str(create_person(team=self.team, distinct_ids=["other-did"], properties={}).uuid)create_person_distinct_id(- team_id=self.team.pk,- distinct_id=shared_did,- person_id=other_uuid,- version=1,- is_deleted=True,+ team_id=self.team.pk, distinct_id=shared_did, person_id=other_uuid, version=1, is_deleted=True)+ before = self._ch_mapping_state(shared_did)orphans = find_orphaned_ch_persons(self.team.pk, [orphan_uuid])result = tombstone_orphaned_ch_persons(self.team.pk, orphans, dry_run=False)- # The orphan person is always tombstoned regardless of mapping fate.assert result.tombstoned_persons == 1+ assert self._ch_mapping_state(shared_did) == before+ expected_drift = [(shared_did, other_uuid)] if other == "deleted_mapping_of_live_person" else []+ assert result.reverse_drift_mappings == expected_drift- if outcome == "tombstone":- assert result.tombstoned_mappings == 1- assert result.skipped_reassigned_mappings == 0- assert result.reverse_drift_mappings == []- _, mapping_deleted, _ = self._ch_mapping_state(shared_did)- assert mapping_deleted == 1- elif outcome == "skip_reassigned":- assert result.tombstoned_mappings == 0- assert result.skipped_reassigned_mappings == 1- assert result.reverse_drift_mappings == []- winner, mapping_deleted, _ = self._ch_mapping_state(shared_did)- assert winner == other_uuid # untouched, still the live reassignment- assert mapping_deleted == 0- else: # reverse_drift- assert result.tombstoned_mappings == 0- assert result.skipped_reassigned_mappings == 0- assert result.reverse_drift_mappings == [(shared_did, other_uuid)]+ @parameterized.expand(+ [+ # (name, other live ClickHouse persons, --force, expect the repair to run)+ ("over_the_limit_is_refused", 0, False, False),+ ("force_overrides_the_limit", 0, True, True),+ ("within_the_limit_runs", 20, False, True),+ ]+ )+ def test_the_command_refuses_to_tombstone_a_large_share_of_a_team(+ self, _name: str, others: int, force: bool, expect_repair: bool+ ):+ uuid = str(uuid4())+ self._seed_ch_only_person(uuid, ["did-a"], version=5)+ for _ in range(others):+ self._seed_ch_only_person(str(uuid4()), [], version=1)+ options = {"team_id": self.team.pk, "person_uuid": [uuid], "all": False, "dry_run": False, "force": force}++ if expect_repair:+ run_orphan_repair(options)+ else:+ with self.assertRaises(SystemExit):+ run_orphan_repair(options)++ assert self._stored(uuid) == ((True, 6) if expect_repair else None)+ assert self._ch_person_state(uuid) == ((1, 6) if expect_repair else (0, 5))diff --git a/posthog/models/person/test/test_util_personhog.py b/posthog/models/person/test/test_util_personhog.pyindex 6d29eca41ee6..16bf12abd400 100644--- a/posthog/models/person/test/test_util_personhog.py+++ b/posthog/models/person/test/test_util_personhog.py@@ -23,6 +23,7 @@ from posthog.models.person.util import (get_person_ids_and_uuids_by_uuids,get_person_uuids_by_distinct_ids,get_persons_mapped_by_distinct_id,+ set_distinct_id_version_floor,)from posthog.personhog_client.client import personhog_callfrom posthog.personhog_client.fake_client import fake_personhog_client, get_active_fake@@ -646,6 +647,13 @@ class TestVersionRpcHelpers(SimpleTestCase):assert raised.exception.code() == codeassert rpc.call_count == attempts+ def test_a_distinct_id_floor_sends_the_key_and_floor_to_personhog(self):+ with fake_personhog_client() as fake:+ set_distinct_id_version_floor(1, "did", 8)++ [call] = fake.assert_called("set_person_distinct_id_version_floor", times=1)+ assert (call.request.team_id, call.request.distinct_id, call.request.min_version) == (1, "did", 8)+def test_splits_requests_at_the_replica_key_cap(self):uuids = [uuid4() for _ in range(PERSONHOG_BATCH_SIZE + 1)]with fake_personhog_client() as fake:diff --git a/posthog/models/person/util.py b/posthog/models/person/util.pyindex 86c411bb9238..b648b8f49e96 100644--- a/posthog/models/person/util.py+++ b/posthog/models/person/util.py@@ -55,6 +55,7 @@ from posthog.personhog_client.proto import (ListPersonTombstoneQueueRequest,PersonVersionFloor as PersonVersionFloorProto,ReadOptions,+ SetPersonDistinctIdVersionFloorRequest,VersionFloorOutcome as VersionFloorOutcomeProto,)from posthog.settings import TEST@@ -939,16 +940,6 @@ def _flush_person_producers(timeout: float) -> None:producer.flush(max(0.0, deadline - time.monotonic()))-def _delete_ch_distinct_id(team_id: int, uuid: UUID, distinct_id: str, version: int) -> None:- create_person_distinct_id(- team_id=team_id,- distinct_id=distinct_id,- person_id=str(uuid),- version=version + 100,- is_deleted=True,- )--# -- Version floors --_T = TypeVar("_T")@@ -1029,3 +1020,16 @@ def ensure_person_version_floors(team_id: int, floors: Sequence[PersonVersionFloreturn resultsreturn personhog_call("ensure_person_version_floors", personhog_fn)+++def set_distinct_id_version_floor(team_id: int, distinct_id: str, min_version: int) -> None:+ """Raise the Postgres version of the distinct id's row to at least ``min_version``, live or tombstoned.++ The response does not say whether the row is live or tombstoned, so read the row from the primary before+ publishing it.+ """+ request = SetPersonDistinctIdVersionFloorRequest(team_id=team_id, distinct_id=distinct_id, min_version=min_version)+ personhog_call(+ "set_person_distinct_id_version_floor",+ lambda: _get_client().set_person_distinct_id_version_floor(request),+ )