:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(persons): repair orphaned ClickHouse person rows (#74468)
Eli Reismandaabe739fc7f
diff --git a/posthog/kafka_client/routing.py b/posthog/kafka_client/routing.pyindex dcc1db561c0f..fc45095e1a19 100644--- a/posthog/kafka_client/routing.py+++ b/posthog/kafka_client/routing.py@@ -293,17 +293,17 @@ async def new_async_producer(return _build_async_producer(resolved)-def flush_all_producers(timeout: Optional[float] = None) -> None:- """Flush every cached sync producer.+def flush_all_producers(timeout: Optional[float] = None) -> int:+ """Flush every cached sync producer, returning the total still-undelivered count.Useful from management commands and other terminating contexts where theprocess is about to exit and may have produced to several topics across- multiple profiles.+ multiple profiles. A non-zero return means some messages were not delivered+ within ``timeout`` — the caller should treat that as a failure."""with _LOCK:producers = list(_SYNC_PRODUCERS.values())- for producer in producers:- producer.flush(timeout)+ return sum(producer.flush(timeout) for producer in producers)def reset_producers() -> None:diff --git a/posthog/management/commands/fix_orphaned_ch_persons.py b/posthog/management/commands/fix_orphaned_ch_persons.pynew file mode 100644index 000000000000..732ed90b5e8f--- /dev/null+++ b/posthog/management/commands/fix_orphaned_ch_persons.py@@ -0,0 +1,112 @@+import logging+import argparse++from django.core.management.base import BaseCommand++import structlog++from posthog.kafka_client.routing import flush_all_producers+from posthog.models.person.deletion import OrphanRepairResult, find_orphaned_ch_persons, tombstone_orphaned_ch_persons++logger = structlog.get_logger(__name__)+logger.setLevel(logging.INFO)++_FLUSH_TIMEOUT_SECONDS = 5 * 60+++class Command(BaseCommand):+ help = (+ "Tombstone ClickHouse person rows that are live in ClickHouse but absent from the persons DB "+ "(the inverse of fix_person_distinct_ids_after_delete). Dry-run by default."+ )++ def add_arguments(self, parser):+ parser.add_argument("--team-id", default=None, type=int, help="Team to repair (required).")+ parser.add_argument(+ "--person-uuid",+ action="append",+ default=None,+ dest="person_uuid",+ help="Scope the repair to this person UUID. Repeat for several; omit with --all.",+ )+ parser.add_argument(+ "--all",+ action="store_true",+ help="Scan every live ClickHouse person for the team (full scan). Mutually exclusive with --person-uuid.",+ )+ parser.add_argument(+ "--dry-run",+ action=argparse.BooleanOptionalAction,+ default=True,+ help="Report what would change without writing (default: on). Pass --no-dry-run to apply.",+ )++ def handle(self, *args, **options):+ run(options)+++def run(options) -> None:+ team_id = options.get("team_id")+ if not team_id:+ logger.error("You must specify --team-id to run this script")+ exit(1)++ uuids = options.get("person_uuid")+ all_persons = options.get("all", False)+ if (not uuids and not all_persons) or (uuids and all_persons):+ logger.error("You must specify exactly one of --person-uuid or --all to run this script")+ exit(1)++ dry_run = options["dry_run"]++ orphans = find_orphaned_ch_persons(team_id, uuids)+ if uuids:+ found = {o.uuid for o in orphans}+ not_orphaned = [u for u in uuids if u not in found]+ if not_orphaned:+ # Requested but not orphaned: either live in the persons DB (safe to leave)+ # or absent from ClickHouse entirely. Never tombstoned by this command.+ logger.warning(+ "Some requested UUIDs are not orphaned (live in persons DB or absent from ClickHouse); skipping them",+ team_id=team_id,+ not_orphaned=not_orphaned,+ )++ result = tombstone_orphaned_ch_persons(team_id, orphans, dry_run=dry_run)+ _log_result(team_id, result)++ if dry_run:+ logger.info("Dry run: no tombstones were produced. Re-run with --no-dry-run to apply.")+ return++ logger.info("Waiting on Kafka producer flush, for up to 5 minutes")+ undelivered = flush_all_producers(_FLUSH_TIMEOUT_SECONDS)+ if undelivered:+ logger.error(+ "Kafka flush left messages undelivered — tombstones may not have landed in ClickHouse",+ team_id=team_id,+ undelivered=undelivered,+ )+ exit(1)+ logger.info("Kafka producer queue flushed.")+++def _log_result(team_id: int, result: OrphanRepairResult) -> None:+ verb = "Would tombstone" if result.dry_run else "Tombstoned"+ logger.info(+ f"{verb} orphaned ClickHouse persons",+ team_id=team_id,+ dry_run=result.dry_run,+ orphaned_persons=len(result.orphaned_person_uuids),+ tombstoned_persons=result.tombstoned_persons,+ tombstoned_mappings=result.tombstoned_mappings,+ skipped_reassigned_mappings=result.skipped_reassigned_mappings,+ reverse_drift_mappings=len(result.reverse_drift_mappings),+ )+ if result.reverse_drift_mappings:+ logger.warning(+ "Found distinct_ids tombstoned in ClickHouse whose person is still live in the persons DB "+ "(reverse drift). Repair these with fix_person_distinct_ids_after_delete, not this command.",+ team_id=team_id,+ reverse_drift=result.reverse_drift_mappings,+ )diff --git a/posthog/models/person/deletion.py b/posthog/models/person/deletion.pyindex b8ff4930a3d9..49974d63e217 100644--- a/posthog/models/person/deletion.py+++ b/posthog/models/person/deletion.py@@ -1,3 +1,5 @@+import datetime as dt+from dataclasses import dataclass, fieldfrom typing import Optionalimport structlog@@ -5,10 +7,13 @@ from rest_framework.exceptions import NotFoundfrom posthog.clickhouse.client import sync_executefrom posthog.models.person import Person-from posthog.models.person.util import create_person, create_person_distinct_id+from posthog.models.person.util import create_person, create_person_distinct_id, get_persons_by_uuidslogger = structlog.get_logger(__name__)+# personhog clamps uuid lookups at 250 per request; batch to match.+_PERSONHOG_UUID_BATCH = 250+def reset_all_deleted_person_distinct_ids(team_id: int, version: int = 2500):# NOTE: Version is arbitrary, we just need to make sure it's higher than any existing version@@ -187,3 +192,205 @@ def _set_person_version_floor_via_personhog(team_id: int, person_id: int, new_veclient.set_person_version_floor(SetPersonVersionFloorRequest(team_id=team_id, person_id=person_id, min_version=new_version))+++# ── Orphaned ClickHouse person repair ────────────────────────────────+#+# The inverse of the reset helpers above: a person can be hard-deleted from the+# persons DB (posthog_person + posthog_persondistinctid) with no matching+# ClickHouse tombstone. The row then stays visible to every ClickHouse-backed+# read path (HogQL `persons`, the UI Persons page) while every persons-DB write+# path 404s. This produces the missing tombstones so ClickHouse agrees with the+# persons DB.+++@dataclass+class OrphanedPerson:+ """A ClickHouse person row that is live in CH but absent from the persons DB."""++ uuid: str+ ch_max_version: int+ created_at: dt.datetime+++@dataclass+class _Mapping:+ """The current ClickHouse winner for a distinct_id (ReplacingMergeTree argMax)."""++ distinct_id: str+ winner_person_id: str+ winner_is_deleted: bool+ max_version: int+++@dataclass+class OrphanRepairResult:+ orphaned_person_uuids: list[str]+ tombstoned_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+ # (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.+ reverse_drift_mappings: list[tuple[str, str]] = field(default_factory=list)+ dry_run: bool = False+++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.++ With ``uuids`` set the search is scoped to those ids (a one-shot repair);+ otherwise every live CH person for the team is checked, which is a full scan.+ """+ candidates = _ch_live_persons(team_id, uuids)+ if not candidates:+ return []++ present_in_db: set[str] = set()+ candidate_uuids = list(candidates)+ for start in range(0, len(candidate_uuids), _PERSONHOG_UUID_BATCH):+ batch = candidate_uuids[start : start + _PERSONHOG_UUID_BATCH]+ present_in_db.update(str(p.uuid) for p in get_persons_by_uuids(team_id, batch, distinct_id_limit=0))++ return [+ OrphanedPerson(uuid=uuid, ch_max_version=max_version, created_at=created_at)+ for uuid, (max_version, created_at) in candidates.items()+ if uuid not in present_in_db+ ]+++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).+ """+ result = OrphanRepairResult(orphaned_person_uuids=sorted(o.uuid for o in orphans), dry_run=dry_run)+ if not orphans:+ return result++ orphan_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++ result.reverse_drift_mappings = _find_reverse_drift(team_id, deleted_winners, orphan_uuids)++ if dry_run:+ result.tombstoned_persons = len(orphans)+ result.tombstoned_mappings = len(to_tombstone)+ return result++ for orphan in orphans:+ # 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++ for mapping in to_tombstone:+ 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++ return result+++_LIVE_PERSONS_BASE = """+ SELECT id, max(version) AS max_version, argMax(created_at, version) AS created_at+ FROM person+ WHERE team_id = %(team_id)s+ GROUP BY id+ HAVING argMax(is_deleted, version) = 0+"""++_LIVE_PERSONS_SCOPED = """+ SELECT id, max(version) AS max_version, argMax(created_at, version) AS created_at+ FROM person+ WHERE team_id = %(team_id)s AND id IN %(uuids)s+ GROUP BY id+ HAVING argMax(is_deleted, version) = 0+"""+++def _ch_live_persons(team_id: int, uuids: Optional[list[str]]) -> dict[str, tuple[int, dt.datetime]]:+ """Map each non-deleted CH person id to its (max_version, created_at)."""+ # Two static query literals rather than an interpolated WHERE — every value is+ # bound through %(...)s params, so there's no user data in the SQL text itself.+ params: dict[str, object] = {"team_id": team_id}+ if uuids is None:+ query = _LIVE_PERSONS_BASE+ else:+ query = _LIVE_PERSONS_SCOPED+ params["uuids"] = list(uuids)++ rows = sync_execute(query, params)+ return {str(row[0]): (int(row[1]), row[2]) for row in rows}+++def _ch_mappings_for_persons(team_id: int, orphan_uuids: set[str]) -> list[_Mapping]:+ """Return the current CH winner for every distinct_id ever tied to an orphan."""+ rows = sync_execute(+ """+ SELECT+ distinct_id,+ argMax(person_id, version) AS winner_person_id,+ argMax(is_deleted, version) AS winner_is_deleted,+ max(version) AS max_version+ FROM person_distinct_id2+ WHERE team_id = %(team_id)s AND distinct_id IN (+ SELECT DISTINCT distinct_id+ FROM person_distinct_id2+ WHERE team_id = %(team_id)s AND person_id IN %(orphans)s+ )+ GROUP BY distinct_id+ """,+ {"team_id": team_id, "orphans": list(orphan_uuids)},+ )+ return [+ _Mapping(+ distinct_id=row[0],+ winner_person_id=str(row[1]),+ winner_is_deleted=bool(row[2]),+ max_version=int(row[3]),+ )+ for row in rows+ ]+++def _find_reverse_drift(team_id: int, deleted_winners: list[_Mapping], orphan_uuids: set[str]) -> list[tuple[str, str]]:+ """Among mappings whose winner is tombstoned, find those whose winning person+ is nonetheless live in the persons DB (CH-deleted / DB-live drift)."""+ winner_uuids = sorted({m.winner_person_id for m in deleted_winners if m.winner_person_id not in orphan_uuids})+ if not winner_uuids:+ return []++ live_in_db: set[str] = set()+ for start in range(0, len(winner_uuids), _PERSONHOG_UUID_BATCH):+ batch = winner_uuids[start : start + _PERSONHOG_UUID_BATCH]+ live_in_db.update(str(p.uuid) for p in get_persons_by_uuids(team_id, batch, distinct_id_limit=0))++ return sorted((m.distinct_id, m.winner_person_id) for m in deleted_winners if m.winner_person_id in live_in_db)diff --git a/posthog/models/person/test/test_orphaned_ch_persons.py b/posthog/models/person/test/test_orphaned_ch_persons.pynew file mode 100644index 000000000000..5ae1739d990a--- /dev/null+++ b/posthog/models/person/test/test_orphaned_ch_persons.py@@ -0,0 +1,160 @@+from uuid import uuid4++from posthog.test.base import BaseTest, ClickhouseTestMixin++from parameterized import parameterized++from posthog.clickhouse.client import sync_execute+from posthog.models.person.deletion import find_orphaned_ch_persons, tombstone_orphaned_ch_persons+from posthog.models.person.util import (+ create_person as create_person_in_ch,+ create_person_distinct_id,+)+from posthog.test.persons import create_person+++class TestOrphanedCHPersonRepair(ClickhouseTestMixin, BaseTest):+ def _seed_ch_only_person(self, uuid: str, distinct_ids: list[str], version: int = 5) -> None:+ # Live in ClickHouse, never seeded into the persons DB (fake) — an orphan.+ create_person_in_ch(+ uuid=uuid,+ team_id=self.team.pk,+ version=version,+ properties={"email": "[email protected]"},+ is_deleted=False,+ )+ for distinct_id in distinct_ids:+ create_person_distinct_id(+ team_id=self.team.pk, distinct_id=distinct_id, person_id=uuid, version=0, is_deleted=False+ )++ def _ch_person_state(self, uuid: str) -> tuple[int, int]:+ rows = sync_execute(+ "SELECT argMax(is_deleted, version), max(version) FROM person FINAL WHERE team_id = %(t)s AND id = %(u)s",+ {"t": self.team.pk, "u": uuid},+ )+ return int(rows[0][0]), int(rows[0][1])++ def _ch_mapping_state(self, distinct_id: str) -> tuple[str, int, int]:+ rows = sync_execute(+ """+ SELECT argMax(person_id, version), argMax(is_deleted, version), max(version)+ FROM person_distinct_id2 FINAL+ WHERE team_id = %(t)s AND distinct_id = %(d)s+ """,+ {"t": self.team.pk, "d": distinct_id},+ )+ return str(rows[0][0]), int(rows[0][1]), int(rows[0][2])++ def test_orphan_is_tombstoned_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++ 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 find_orphaned_ch_persons(self.team.pk, [uuid]) == []+ for did in ("did-a", "did-b"):+ _, mapping_deleted, _ = self._ch_mapping_state(did)+ assert mapping_deleted == 1++ def test_dry_run_produces_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 is untouched.+ is_deleted, version = self._ch_person_state(uuid)+ assert is_deleted == 0+ assert version == 3++ def test_live_person_is_never_an_orphan(self):+ # A person present in the persons DB (seeded into the fake) must not be+ # reported as an orphan even when its uuid is passed explicitly.+ person = create_person(team=self.team, distinct_ids=["live-did"], properties={"email": "[email protected]"})++ orphans = find_orphaned_ch_persons(self.team.pk, [str(person.uuid)])+ assert orphans == []++ result = tombstone_orphaned_ch_persons(self.team.pk, orphans, dry_run=False)++ assert result.tombstoned_persons == 0+ is_deleted, _ = self._ch_person_state(str(person.uuid))+ assert is_deleted == 0++ @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"),+ ]+ )+ def test_mapping_classification(self, _name: str, outcome: str):+ 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 = str(uuid4())+ create_person_distinct_id(+ 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)+ create_person_distinct_id(+ team_id=self.team.pk,+ distinct_id=shared_did,+ person_id=other_uuid,+ version=1,+ is_deleted=True,+ )++ 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++ 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)]