: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 persons_dedup safe to point at a production team (#85945)
Eli Reisman116352e50bd2
diff --git a/posthog/management/commands/persons_dedup.py b/posthog/management/commands/persons_dedup.pyindex 13a1984bf0da..e1345a9e700a 100644--- a/posthog/management/commands/persons_dedup.py+++ b/posthog/management/commands/persons_dedup.py@@ -14,25 +14,102 @@ SAFETY MODELEverything rests on one property, verified against the flag and cohort read paths:- A person row owning no posthog_persondistinctid row is unreachable. The product- resolves a person only via distinct_id -> posthog_persondistinctid -> person_id- (rust/feature-flags/src/flags/flag_matching_utils.rs:839 for hash key overrides,- :284 for static cohorts), so nothing keyed to that person_id can be read either.--So a row owning zero distinct IDs can be deleted without changing any product-behaviour, and the feature-flag overrides that cascade away with it were already+ A person row owning no live posthog_persondistinctid row cannot be resolved FROM A+ DISTINCT ID, so nothing keyed to that person_id takes part in flag evaluation, cohort+ matching, or event attribution. Those reads all start from a distinct id+ (rust/common/types/src/person.rs:22 joins posthog_persondistinctid with+ is_deleted = false; flag_matching_utils.rs:845 and :288 build on it).++Say it that precisely, because the shorter version -- "the row is unreachable" -- is not+true. Plenty of paths reach a person by uuid or by bigint id without touching a distinct+id at all: the persons detail API accepts either, and personhog exposes GetPersonByUuid,+GetPersonsByUuids, GetPerson and GetPersons. What makes the delete safe is narrower: a+victim is always rn > 1 within a duplicate (team_id, uuid) group, so a row carrying the+same uuid always survives it. Every uuid-keyed lookup still finds a person; it just finds+the one the product can actually resolve.++Two consequences of that worth stating rather than discovering:++ - get_person_by_uuid takes the first row of an unordered result, so for a duplicated+ uuid it returns an arbitrary member today. Removing the victims makes it deterministic.+ - Static cohort population resolves uuid -> person id and does not deduplicate, so it+ writes membership rows against victims continuously, not historically. Expect the+ post-commit cohort sweep to find rows on an active team. That is the normal case here.++Two gates enforce it from opposite directions, because proving the victims are safe is+not the same as proving the survivor is right:++ GATE_REACHABLE_SQL no row we delete may be reachable+ GATE_SURVIVOR_REACHABLE_SQL if any row in the group is reachable, one we keep must be++DO NOT REORDER THE LOCK AND THE GATE. Ingestion's stranded-row claim path selects exactly+the rows this command deletes -- the unreachable holder of a (team_id, uuid) -- and+repoints it to a live distinct id. It takes FOR UPDATE on that row, and so does+LOCK_VICTIMS_SQL, which is the only reason the two serialize instead of racing. The gate+must stay after the lock. This stopped being hypothetical when+PERSON_CREATE_CLAIM_TEAM_ALLOWLIST was enabled: the teams on it are the teams with+duplicates, so a run against them will meet a claim in flight, and the batch-level prune+is what absorbs it.++So a row owning zero live distinct IDs can be deleted without changing any membership+or flag DECISION, and the feature-flag overrides that cascade away with it were alreadyunreachable. Moving them onto the surviving person would do the opposite: it wouldresurrect dead data and could change which flag variant a live user receives.+One carve-out, because "no product behaviour" would overstate it. Static cohort size+comes from a bare COUNT(*) over posthog_cohortpeople scoped by cohort_id, with no join+to persons, so an unreachable row's memberships are counted today even though no read+path can act on them. Removing that row corrects the displayed count downward. That is+a fix rather than a regression -- the count gates the realtime-evaluation threshold, so+an inflated one can demote a cohort that should qualify -- but it is user-visible, and+it is the one number a dedup run can move.+The three dependent tables behave differently on DELETE in production, which is whythe reachability assertion runs before every delete and again inside the transaction:- posthog_persondistinctid FK NO ACTION -> Postgres blocks the delete- posthog_featureflaghashkeyoverride FK CASCADE -> silently removes overrides- posthog_cohortpeople no FK -> silently orphans rows+ posthog_persondistinctid FK NO ACTION -> Postgres blocks the delete+ posthog_featureflaghashkeyoverride FK CASCADE -> silently removes overrides+ posthog_cohortpeople no FK -> silently orphans rows+ posthog_person_reconciliation_backup no FK -> silently orphans rowsOnly the first fails loudly, so the command cannot rely on the database to catch a-mistake in the other two.+mistake in the other three. The two without a foreign key are deleted explicitly, before+the person row, so a failure there aborts before anything is lost.++A note on what is NOT a reason to keep a row. Being referenced is not the same as being+live. A row owning no distinct ID is dead whatever else points at it, and refusing to+delete it does not protect anything -- it leaves the dead row in place along with cohort+memberships that still count toward the cohort size shown in the product. These repairs+are expensive to run, so every row skipped for a reason that does not survive scrutiny is+a re-run later. n_did = 0 is the safety condition; nothing else is.++BLAST RADIUS OF A DELETED bigint id++Audited across the repo rather than assumed. Two facts do most of the work.++Nothing reassigns the id. posthog_person.id comes from a sequence and there is no setval+anywhere, so a deleted id dangles forever and is never handed to a different person. Every+"wrong person" scenario needs id reuse, so the real failure mode is a dangling reference or+a silent no-op, not mistaken identity.++ClickHouse never stores it. Every person column in every ClickHouse table is UUID-typed --+person, person_distinct_id2, person_static_cohort, cohortpeople, events, the override+dictionary, all of it -- and every Kafka producer sends person.uuid, discarding the bigint.+So a dedup needs no ClickHouse tombstone, but only because the survivor keeps the uuid and+therefore keeps ClickHouse's row backed. GATE_NO_SURVIVOR_SQL is what holds that up: delete+the last row for a uuid and ClickHouse would be left visible-but-unbacked. Do not weaken it.++Outside the persons DB the bigint survives in a handful of places, none of which this+command can repair, and all of which fail safe:++ posthog_activitylog.item_id a Person row's audit trail becomes unreachable; only+ the "deleted" entry carries the uuid to find it by+ Temporal delete-persons input a queued run holding a victim id resolves nothing for+ it and under-deletes silently+ split_person Celery payload raises, retries once, dies+ Dagster run config / event log stale resume watermarks and failure metadata++Drain those queues before a large run rather than reasoning about them mid-flight.Deleted rows and their dependent rows are written to a local JSONL file, fsync'd, afterthe victims are locked and before the delete runs. Locking first matters: an insert into@@ -41,24 +118,34 @@ reading dependents before the lock would let a row appear afterwards, cascade awnever reach the backup. Writing before the delete means a rolled back transaction leavesa harmless superset, and a deleted row can never be missing. Copy that file off the pod;it is the only undo.++TOMBSTONES++A row with is_deleted = true is a tombstone, not a dead row: the write path revives it in+place so the revived key outranks its own ClickHouse tombstone, which needs the version+this row is holding. Deleting one would drop that version floor, so tombstoned rows are+never staged, and they lose the survivor ranking to any live member of their group. That+leaves a group of only tombstoned rows unresolved, which verify reports rather than hides.+No production team can be in that state yet -- every is_deleted writer is gated on a team+allowlist that is only enabled where the unique (team_id, uuid) index already exists."""from __future__ import annotationsimport os-import csvimport jsonimport timefrom datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any+from urllib.parse import urlsplitfrom django.core.management.base import BaseCommand, CommandErrorimport psycopgimport structlog-from posthog.persons_db import persons_db_connection+from posthog.persons_db import persons_db_connection, persons_db_urllogger = structlog.get_logger(__name__)@@ -92,9 +179,17 @@ WITH dups AS (GROUP BY team_id, uuid HAVING count(*) > 1),members AS (- SELECT p.team_id, p.uuid, p.id, p.version, p.is_identified, p.created_at,+ SELECT p.team_id, p.uuid, p.id, p.version, p.is_identified, p.created_at, p.is_deleted,+ -- Two counts, because two different questions. n_did is what the foreign key+ -- sees, so it decides whether a row can be deleted at all: the FK is NO ACTION+ -- and counts tombstoned mappings too, so staging a row with any mapping would+ -- fail the delete. n_did_live is what the product sees -- the flag path requires+ -- pdi.is_deleted = false -- so it decides which row is worth keeping.(SELECT count(*) FROM posthog_persondistinctid pdiWHERE pdi.team_id = p.team_id AND pdi.person_id = p.id) AS n_did,+ (SELECT count(*) FROM posthog_persondistinctid pdi+ WHERE pdi.team_id = p.team_id AND pdi.person_id = p.id+ AND NOT pdi.is_deleted) AS n_did_live,(SELECT count(*) FROM posthog_cohortpeople cpWHERE cp.person_id = p.id) AS n_cohort,(SELECT count(*) FROM posthog_featureflaghashkeyoverride ff@@ -105,6 +200,9 @@ members AS (JOIN dups d ON d.team_id = p.team_id AND d.uuid = p.uuidWHERE p.team_id = %(team)s),+-- refs decides deletability for delete-unreferenced, not who survives: the ranking below+-- puts reachability ahead of it, so n_cohort and n_ff only ever break a tie between rows+-- that are all unreachable. They look load-bearing for survivor choice and are not.scored AS (SELECT *, (n_did + n_cohort + n_ff + n_recon) AS refs FROM members),@@ -112,10 +210,24 @@ ranked AS (SELECT *,row_number() OVER (PARTITION BY team_id, uuid- ORDER BY (n_did > 0) DESC, refs DESC, is_identified DESC,- version DESC NULLS LAST, created_at ASC, id ASC+ ORDER BY is_deleted ASC, (n_did_live > 0) DESC, (n_did > 0) DESC, refs DESC,+ is_identified DESC, version DESC NULLS LAST, created_at ASC, id ASC) AS rnFROM scored+),+-- One row per duplicate group, in the terms the staging queries below use, so+-- classify and verify report exactly what repair will and will not resolve.+per_group AS (+ SELECT uuid,+ count(*) AS members,+ count(*) FILTER (WHERE n_did > 0) AS live_owners,+ count(*) FILTER (WHERE n_did_live > 0) AS reachable_owners,+ count(*) FILTER (WHERE is_deleted) AS tombstoned,+ count(*) FILTER (WHERE n_recon > 0) AS recon_held,+ sum(n_ff)::bigint AS flag_overrides,+ sum(n_cohort)::bigint AS cohort_rows,+ count(*) FILTER (WHERE rn > 1 AND n_did = 0 AND NOT is_deleted) AS stageable+ FROM ranked GROUP BY uuid)"""@@ -132,6 +244,8 @@ SELECTHAVING count(*) FILTER (WHERE refs > 0) > 1) x),(SELECT count(*) FROM (SELECT uuid FROM ranked GROUP BY uuidHAVING count(*) FILTER (WHERE n_did > 0) > 1) x),+ (SELECT count(*) FROM per_group WHERE live_owners > 1 OR members - stageable > 1),+ (SELECT count(*) FROM ranked WHERE is_deleted),COALESCE(sum(n_did), 0), COALESCE(sum(n_cohort), 0), COALESCE(sum(n_ff), 0),COALESCE(sum(n_recon), 0)FROM ranked@@ -143,14 +257,32 @@ STAGE_UNREFERENCED_SQL = (_MEMBERS_CTE+ f"""INSERT INTO {VICTIMS_TABLE} (team_id, id, uuid)-SELECT team_id, id, uuid FROM ranked WHERE rn > 1 AND refs = 0+SELECT team_id, id, uuid FROM ranked WHERE rn > 1 AND refs = 0 AND NOT is_deleted""")# Repair: a non-survivor owning NO distinct IDs. Unreachable by definition, so its-# feature-flag overrides and cohort rows are dead data and may cascade/be removed.-# Groups where two rows own distinct IDs are excluded -- those need a real merge and-# this command refuses to guess.+# feature-flag overrides, cohort rows and reconciliation backup are dead data that go with+# it. n_did = 0 is the whole safety condition and it is doing more work than it looks:+# because it counts tombstoned mappings as well as live ones, no row a foreign key would+# refuse to delete can be staged, and no row the product can still resolve can be either.+#+# Two conditions used to sit here and have been removed, because each refused a delete we+# can prove is safe, and every skipped row is a re-run later:+#+# n_recon = 0+# A reconciliation backup row does not make a person live. Its restore path reads the+# person by id and returns early when the row is gone+# (person_property_reconciliation_restore.py:326), and the caller counts that as a+# skip. So the delete is safe; the backup row goes with the person rather than being+# left to warn on every future restore and retain a deleted person's properties.+#+# uuid IN (groups with at most one distinct-ID owner)+# This never protected a live row -- n_did = 0 already does that, with or without it.+# Its only effect was to skip dead rows that happened to share a group with two live+# ones, leaving known-orphaned rows behind and their cohort memberships still counted.+# The group stays blocked for the merge either way; classify still reports it, because+# that accounting keys on the count of live owners, not on this clause.STAGE_UNREACHABLE_SQL = (_MEMBERS_CTE+ f"""@@ -158,9 +290,50 @@ INSERT INTO {VICTIMS_TABLE} (team_id, id, uuid)SELECT team_id, id, uuid FROM rankedWHERE rn > 1AND n_did = 0- AND n_recon = 0- AND uuid IN (SELECT uuid FROM ranked GROUP BY uuid- HAVING count(*) FILTER (WHERE n_did > 0) <= 1)+ AND NOT is_deleted+"""+)++# Groups repair cannot resolve, counted the way the staging query above decides: a group+# with two live distinct-ID owners needs a real person merge, and a group that keeps more+# than one member after every stageable victim is removed is held by something else+# (reconciliation backup, or a tombstone this command deliberately will not touch).+# verify uses this to tell "dedup is incomplete" from "this is the remainder we accept".+COUNT_BLOCKED_SQL = (+ _MEMBERS_CTE+ + """+SELECT count(*), count(*) FILTER (WHERE live_owners > 1 OR members - stageable > 1)+FROM per_group+"""+)++# Everything needed to resolve a group this command refuses, without re-deriving it: which+# rows are in the group, which of them the product can still reach, what hangs off them, and+# why it was refused. The merge work needs the reachable pair and the override count; the+# reconciliation and tombstone cases need to be told apart from it.+BLOCKED_DETAIL_SQL = (+ _MEMBERS_CTE+ + """+SELECT g.uuid,+ -- Mirrors the WHERE below, branch for branch, so the reason names the condition that+ -- actually refused the group. Two rows owning distinct IDs is the merge case, split by+ -- whether the product can still reach both; a tombstone is the other. A reconciliation+ -- backup row no longer refuses anything, so it is a reported column, not a reason --+ -- ranking it here attributed tombstone-blocked groups to the backup. 'other' should be+ -- unreachable: the survivor ranking puts any row owning a distinct ID first, so a group+ -- with one live owner and no tombstone always resolves down to a single member.+ CASE WHEN g.reachable_owners > 1 THEN 'multiple_reachable_rows'+ WHEN g.live_owners > 1 THEN 'multiple_distinct_id_owners'+ WHEN g.tombstoned > 0 THEN 'tombstoned_member'+ ELSE 'other' END AS reason,+ g.members, g.reachable_owners, g.live_owners, g.tombstoned, g.recon_held,+ g.flag_overrides, g.cohort_rows,+ (SELECT array_agg(r.id ORDER BY r.rn) FROM ranked r WHERE r.uuid = g.uuid) AS member_ids,+ (SELECT array_agg(r.id ORDER BY r.rn) FROM ranked r+ WHERE r.uuid = g.uuid AND r.n_did_live > 0) AS reachable_ids+FROM per_group g+WHERE g.live_owners > 1 OR g.members - g.stageable > 1+ORDER BY g.uuid""")@@ -174,14 +347,62 @@ DELETE FROM {VICTIMS_TABLE} v USING {VICTIMS_TABLE}_batch bWHERE v.team_id = b.team_id AND v.id = b.id"""+# Drop from the staged set the batch members a concurrent writer made undeletable. Aborting+# the whole run instead would discard a staging scan that costs minutes on the large teams,+# and on a team still receiving writes it can stop the run finishing at all. Only the staged+# set is touched -- no person row is modified. Three ways a victim stops being one:+# 1. it no longer exists, because something else removed it;+# 2. it gained a reference since staging, so it is now reachable;+# 3. its group lost the survivor, so the staged victims are all that remains of the key.+# Deleting them would remove it entirely, and it is no longer a duplicate anyway.+# Case 3 must be here as well as in the gate: without it, a concurrent delete of an unstaged+# survivor fails GATE_NO_SURVIVOR_SQL, matches none of the other predicates, and aborts the+# team over a batch that is merely no longer worth deleting.+PRUNE_BATCH_SQL = f"""+DELETE FROM {VICTIMS_TABLE} v+USING {VICTIMS_TABLE}_batch b+WHERE v.team_id = b.team_id AND v.id = b.id+ AND (+ NOT EXISTS (SELECT 1 FROM posthog_person p+ WHERE p.team_id = v.team_id AND p.id = v.id)+ OR EXISTS (SELECT 1 FROM posthog_persondistinctid pdi+ WHERE pdi.team_id = v.team_id AND pdi.person_id = v.id)+ OR (SELECT count(*) FROM posthog_person p+ WHERE p.team_id = v.team_id AND p.uuid = v.uuid)+ <= (SELECT count(*) FROM {VICTIMS_TABLE}_batch b2+ WHERE b2.team_id = v.team_id AND b2.uuid = v.uuid)+ )+"""+# The load-bearing assertion. A victim owning a distinct ID is reachable, so deleting it# would change product behaviour and silently destroy its overrides via the cascade.GATE_REACHABLE_SQL = f"""SELECT count(*) FROM {VICTIMS_TABLE}_batch vWHERE EXISTS (SELECT 1 FROM posthog_persondistinctid pdiWHERE pdi.team_id = v.team_id AND pdi.person_id = v.id)- OR EXISTS (SELECT 1 FROM posthog_person_reconciliation_backup rb- WHERE rb.team_id = v.team_id AND rb.person_id = v.id)+"""++# The mirror of the reachable gate. That one proves no victim is reachable; this proves the+# row we keep is the right one. Staging should already guarantee it -- a victim needs n_did = 0+# -- so this is an assertion, and a non-zero result means the model is wrong rather than that a+# writer raced us. Scoped to the batch's keys, so it costs a handful of index probes rather+# than another pass over the team.+GATE_SURVIVOR_REACHABLE_SQL = f"""+SELECT count(*) FROM (SELECT DISTINCT team_id, uuid FROM {VICTIMS_TABLE}_batch) g+WHERE EXISTS (+ SELECT 1 FROM posthog_person p+ WHERE p.team_id = g.team_id AND p.uuid = g.uuid+ AND EXISTS (SELECT 1 FROM posthog_persondistinctid d+ WHERE d.team_id = p.team_id AND d.person_id = p.id AND NOT d.is_deleted)+ )+ AND NOT EXISTS (+ SELECT 1 FROM posthog_person p+ WHERE p.team_id = g.team_id AND p.uuid = g.uuid+ AND NOT EXISTS (SELECT 1 FROM {VICTIMS_TABLE}_batch b+ WHERE b.team_id = p.team_id AND b.id = p.id)+ AND EXISTS (SELECT 1 FROM posthog_persondistinctid d+ WHERE d.team_id = p.team_id AND d.person_id = p.id AND NOT d.is_deleted)+ )"""GATE_NO_SURVIVOR_SQL = f"""@@ -218,6 +439,10 @@ UNION ALLSELECT 'cohortpeople', cp.id, cp.person_id, cp.cohort_id::text, NULLFROM posthog_cohortpeople cpJOIN {VICTIMS_TABLE}_batch b ON b.id = cp.person_id+UNION ALL+SELECT 'reconciliation_backup', NULL, rb.person_id, rb.job_id::text, rb.properties::text+FROM posthog_person_reconciliation_backup rb+JOIN {VICTIMS_TABLE}_batch b ON b.team_id = rb.team_id AND b.id = rb.person_id"""# Cohort rows have no FK, so the cascade will not remove them. Delete explicitly, before@@ -227,6 +452,16 @@ DELETE FROM posthog_cohortpeople cpUSING {VICTIMS_TABLE}_batch b WHERE cp.person_id = b.id"""+# Same shape, same reason: no FK, so nothing removes these for us. Left behind they would+# warn on every future restore run and keep a deleted person's properties indefinitely.+# The restore path already treats a missing person as a skip, so removing both together is+# the outcome it would reach anyway.+DELETE_RECON_BACKUP_SQL = f"""+DELETE FROM posthog_person_reconciliation_backup rb+USING {VICTIMS_TABLE}_batch b+WHERE rb.team_id = b.team_id AND rb.person_id = b.id+"""+# posthog_cohortpeople has no FK to posthog_person, so nothing at the database level# stops a row appearing for a victim while the delete transaction is open.CHECK_COHORT_ORPHANS_SQL = f"""@@ -251,13 +486,6 @@ USING {VICTIMS_TABLE}_batch bWHERE p.team_id = b.team_id AND p.id = b.id AND p.team_id = %(team)s"""-VERIFY_DUPS_SQL = """-SELECT count(*) FROM (- SELECT uuid FROM posthog_person WHERE team_id = %(team)s- GROUP BY team_id, uuid HAVING count(*) > 1-) x-"""-VERIFY_ORPHANS_SQL = """SELECT count(*) FROM posthog_persondistinctid pdiWHERE pdi.team_id = %(team)s@@ -278,7 +506,11 @@ REQUIRED_PRIVILEGES = (("posthog_cohortpeople", "SELECT"),("posthog_cohortpeople", "DELETE"),("posthog_person_reconciliation_backup", "SELECT"),+ ("posthog_person_reconciliation_backup", "DELETE"),)+# posthog_featureflaghashkeyoverride needs only SELECT: its rows go via the FK's+# ON DELETE CASCADE, and Postgres runs referential actions with the privileges of the+# referencing table's owner rather than the caller's, so no DELETE grant is required.def _check_privileges(conn: psycopg.Connection) -> list[str]:@@ -348,6 +580,37 @@ class Command(BaseCommand):help="pause between batches so writers blocked on our row locks drain (0 disables)",)+ def _assert_explicit_target(self, use_writer: bool) -> None:+ """Refuse to run against a silently defaulted database, and log the one chosen.++ posthog.persons_db falls back to a localhost URL built from PG* when the persons+ URL is unset. That default is right for a developer and wrong for this command: in+ a deployed pod PG* usually point at the main cluster, so an unset variable turns a+ destructive run against the persons database into a destructive run against+ whatever `posthog_persons` resolves to there -- or a confusing connection error.+ The variable is injected by the charts in every deployment, so requiring it costs+ nothing operationally and removes the failure mode entirely. Tests set it in+ conftest; a developer without it gets told which variable to set.+ """+ var = "PERSONS_DB_WRITER_URL" if use_writer else "PERSONS_DB_READER_URL"+ if not os.getenv("PERSONS_DB_WRITER_URL") and not os.getenv("PERSONS_DB_READER_URL"):+ raise CommandError(+ f"{var} is not set, so the persons-DB URL would fall back to a localhost "+ "default built from PG*. Refusing to run: on a deployed pod that default "+ "points somewhere else entirely. Set the variable explicitly."+ )+ # Say out loud which database is about to be modified. The operator is driving this+ # by hand against production, and host plus dbname is what tells them the toolbox+ # is pointed at persons rather than the main cluster.+ parts = urlsplit(persons_db_url(writer=use_writer))+ logger.info(+ "persons_dedup.target",+ host=parts.hostname,+ port=parts.port,+ dbname=(parts.path or "/").lstrip("/"),+ role="writer" if use_writer else "reader",+ )+def handle(self, *args: Any, **options: Any) -> None:team: int = options["team"]mode: str = options["mode"]@@ -371,6 +634,7 @@ class Command(BaseCommand):# load-bearing: a duplicate minted after the read escapes a primary read too,# and the unique index build is the authoritative duplicate check either way.use_writer = mode not in ("classify", "verify") or options["writer"]+ self._assert_explicit_target(use_writer)with persons_db_connection(writer=use_writer, autocommit=True) as conn:with conn.cursor() as cur:@@ -394,7 +658,7 @@ class Command(BaseCommand):)logger.info("persons_dedup.reading_from_replica", team_id=team, replay_lag_seconds=lag_seconds)if mode == "classify":- self._classify(conn, team)+ self._classify(conn, team, Path(options["outdir"]))else:self._verify(conn, team)return@@ -407,7 +671,52 @@ class Command(BaseCommand):stage_sql = STAGE_UNREFERENCED_SQL if mode == "delete-unreferenced" else STAGE_UNREACHABLE_SQLself._run(conn, team, stage_sql, options, apply_changes=apply_changes, mode=mode)- def _classify(self, conn: psycopg.Connection, team: int) -> None:+ BLOCKED_COLUMNS = (+ "uuid",+ "reason",+ "members",+ "reachable_owners",+ "live_owners",+ "tombstoned",+ "recon_held",+ "flag_overrides",+ "cohort_rows",+ "member_ids",+ "reachable_ids",+ )++ def _dump_blocked(self, conn: psycopg.Connection, team: int, outdir: Path) -> dict[str, int]:+ """Write one record per group this command refuses, and return the reason tally.++ The counts alone cannot be acted on: resolving a group needs to know which rows it+ holds, which of them are still reachable, and what hangs off them. Written next to+ the delete backups so a run leaves everything the follow-up work needs.+ """+ with conn.cursor() as cur:+ cur.execute("BEGIN")+ cur.execute("SET LOCAL statement_timeout = 0")+ cur.execute(BLOCKED_DETAIL_SQL, {"team": team})+ rows = cur.fetchall()+ cur.execute("COMMIT")+ if not rows:+ return {}++ outdir.mkdir(parents=True, exist_ok=True)+ stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")+ path = outdir / f"blocked_team_{team}_{stamp}.jsonl"+ tally: dict[str, int] = {}+ fd = os.open(str(path), os.O_CREAT | os.O_WRONLY | os.O_APPEND | os.O_NOFOLLOW, 0o600)+ with os.fdopen(fd, "a", encoding="utf-8") as fh:+ for row in rows:+ record = dict(zip(self.BLOCKED_COLUMNS, row))+ tally[str(record["reason"])] = tally.get(str(record["reason"]), 0) + 1+ fh.write(json.dumps({"team_id": team, **record}, default=str) + "\n")+ fh.flush()+ os.fsync(fh.fileno())+ logger.info("persons_dedup.blocked_detail_written", team_id=team, groups=len(rows), path=str(path))+ return tally++ def _classify(self, conn: psycopg.Connection, team: int, outdir: Path) -> None:# SET LOCAL is transaction-scoped, so this scan keeps its unlimited timeout even# on a connection where the session-level SET was silently dropped by a pooler# (observed on the US census: reader queries canceled at the server's 30-minute@@ -419,7 +728,9 @@ class Command(BaseCommand):row = cur.fetchone()cur.execute("COMMIT")assert row is not None- groups, orphaned, one_ref, needs_merge, multi_did, dids, cohort, ff, recon = (int(v) for v in row)+ groups, orphaned, one_ref, needs_merge, multi_did, blocked, tombstoned, dids, cohort, ff, recon = (+ int(v) for v in row+ )logger.info("persons_dedup.classify",team_id=team,@@ -428,6 +739,10 @@ class Command(BaseCommand):one_referenced=one_ref,needs_merge=needs_merge,groups_with_distinct_ids_on_multiple_rows=multi_did,+ # What repair will leave behind, and therefore what a passing verify accepts.+ blocked_groups=blocked,+ resolvable_groups=groups - blocked,+ tombstoned_members=tombstoned,distinct_ids=dids,cohort_rows=cohort,flag_overrides=ff,@@ -437,21 +752,53 @@ class Command(BaseCommand):logger.warning("persons_dedup.needs_real_merge", team_id=team, groups=multi_did)if recon:logger.warning("persons_dedup.reconciliation_backup_references", team_id=team, recon=recon)+ if tombstoned:+ logger.warning("persons_dedup.tombstoned_members_skipped", team_id=team, members=tombstoned)+ if blocked:+ # A count is not actionable. Write the per-group detail and report the split by+ # reason, so the groups this command refuses can be resolved without re-deriving+ # which rows they hold or why each was refused.+ tally = self._dump_blocked(conn, team, outdir)+ logger.warning("persons_dedup.blocked_by_reason", team_id=team, groups=blocked, **tally)def _verify(self, conn: psycopg.Connection, team: int) -> None:with conn.cursor() as cur:cur.execute("BEGIN")cur.execute("SET LOCAL statement_timeout = 0")- cur.execute(VERIFY_DUPS_SQL, {"team": team})- dups_row = cur.fetchone()+ # Both counts come from one statement on purpose. Read committed takes a fresh+ # snapshot per statement, so counting the groups and the blocked subset separately+ # lets a write land between them -- and since resolvable is the difference, that+ # reports a resolvable group the team does not have, or a negative count. One+ # statement over one snapshot cannot disagree with itself, and it saves a second+ # group-by pass over the whole team.+ cur.execute(COUNT_BLOCKED_SQL, {"team": team})+ blocked_row = cur.fetchone()cur.execute(VERIFY_ORPHANS_SQL, {"team": team})orphans_row = cur.fetchone()cur.execute("COMMIT")- dups = int(dups_row[0]) if dups_row else 0+ dups = int(blocked_row[0]) if blocked_row else 0+ blocked = int(blocked_row[1]) if blocked_row else 0orphans = int(orphans_row[0]) if orphans_row else 0- logger.info("persons_dedup.verify", team_id=team, duplicate_groups=dups, orphaned_distinct_ids=orphans)- if dups or orphans:- raise CommandError(f"team {team}: {dups} duplicate group(s), {orphans} orphaned distinct id(s)")+ resolvable = dups - blocked+ logger.info(+ "persons_dedup.verify",+ team_id=team,+ duplicate_groups=dups,+ blocked_groups=blocked,+ resolvable_groups=resolvable,+ orphaned_distinct_ids=orphans,+ )+ # Exiting non-zero on any remaining group made this unusable as a gate on the teams+ # that matter: the merge-required remainder is expected and is a separate workstream,+ # so a run that leaves only those has done everything this command can do. Only+ # groups repair could still resolve, or orphaned mappings, are a failure.+ if resolvable or orphans:+ raise CommandError(+ f"team {team}: {resolvable} resolvable duplicate group(s), "+ f"{orphans} orphaned distinct id(s); {blocked} group(s) need a real merge"+ )+ if blocked:+ logger.warning("persons_dedup.blocked_remainder", team_id=team, groups=blocked)def _run(self,@@ -502,7 +849,13 @@ class Command(BaseCommand):backup_path = outdir / f"deleted_team_{team}_{mode}_{stamp}.jsonl"deleted = 0+ checked = 0batches = 0+ pruned_total = 0+ # A live-leak team can make a staged victim reachable mid-run, which is expected and+ # is handled per batch below. A large share going that way is not expected and means+ # the staging query and the gate disagree, so stop rather than grind through the set.+ prune_budget = max(20, staged // 100)while True:with conn.cursor() as cur:cur.execute(f"TRUNCATE {VICTIMS_TABLE}_batch")@@ -518,15 +871,22 @@ class Command(BaseCommand):reachable = _scalar(conn, GATE_REACHABLE_SQL)no_survivor = _scalar(conn, GATE_NO_SURVIVOR_SQL)- if reachable or no_survivor:+ wrong_survivor = _scalar(conn, GATE_SURVIVOR_REACHABLE_SQL)+ if reachable or no_survivor or wrong_survivor:raise CommandError(f"gate failed for team {team}: {reachable} victim(s) are reachable, "- f"{no_survivor} group(s) would be emptied. Nothing deleted."+ f"{no_survivor} group(s) would be emptied, {wrong_survivor} group(s) would "+ f"lose their only reachable row. Nothing deleted.")if not apply_changes:- logger.info("persons_dedup.dry_run_batch_ok", team_id=team, victims=in_batch)- return+ # Retire the batch and continue rather than returning: a dry run that stops+ # after one batch gates --batch-size victims out of the whole staged set and+ # still reports success, which on the large teams is a fraction of a percent.+ checked += in_batch+ with conn.cursor() as cur:+ cur.execute(RETIRE_BATCH_SQL)+ continuewith conn.cursor() as cur:cur.execute("BEGIN")@@ -541,14 +901,54 @@ class Command(BaseCommand):locked = cur.rowcount# Re-check inside the transaction: these teams still receive writes, and a# concurrent insert could have made a victim reachable since the pre-flight.+ # Both gates are re-checked, not just reachability, so the failure message+ # below describes what was actually verified.cur.execute(GATE_REACHABLE_SQL)gate_row = cur.fetchone()- if locked != in_batch or (gate_row and gate_row[0]):+ cur.execute(GATE_NO_SURVIVOR_SQL)+ survivor_row = cur.fetchone()+ cur.execute(GATE_SURVIVOR_REACHABLE_SQL)+ wrong_survivor_row = cur.fetchone()+ now_reachable = int(gate_row[0]) if gate_row else 0+ now_emptied = int(survivor_row[0]) if survivor_row else 0+ now_wrong_survivor = int(wrong_survivor_row[0]) if wrong_survivor_row else 0+ # Not prunable, and never a race: staging cannot produce this, so reaching it+ # means the survivor rule and the reachability rule disagree. Stop the team.+ if now_wrong_survivor:cur.execute("ROLLBACK")raise CommandError(- f"in-transaction gate failed for team {team} "- f"(locked {locked}/{in_batch}, reachable {gate_row[0] if gate_row else '?'}); rolled back"+ f"team {team}: {now_wrong_survivor} group(s) would lose their only "+ f"reachable row. This is not a concurrent-writer race; the survivor "+ f"rule is wrong for this data. {deleted} row(s) already deleted."+ )+ if locked != in_batch or now_reachable or now_emptied:+ cur.execute("ROLLBACK")+ logger.warning(+ "persons_dedup.batch_raced",+ team_id=team,+ batch=batches,+ locked=locked,+ staged=in_batch,+ reachable=now_reachable,+ would_empty=now_emptied,)+ pruned = self._prune_batch(conn)+ pruned_total += pruned+ # Nothing pruned means the gate failed for a reason this does not+ # explain, and the next iteration would take the same batch forever.+ if pruned == 0:+ raise CommandError(+ f"in-transaction gate failed for team {team} "+ f"(locked {locked}/{in_batch}, reachable {now_reachable}, "+ f"would empty {now_emptied}) and no victim was prunable; rolled back"+ )+ if pruned_total > prune_budget:+ raise CommandError(+ f"team {team}: {pruned_total} victim(s) became unresolvable mid-run, "+ f"over the {prune_budget} budget; staging and the gate disagree. "+ f"{deleted} row(s) already deleted, rerun to resume"+ )+ continue# Back up after the lock, not before it. An insert into# posthog_featureflaghashkeyoverride takes FOR KEY SHARE on the parent@@ -562,6 +962,7 @@ class Command(BaseCommand):raise CommandError(f"backed up {backed_up} row(s) but staged {in_batch}; rolled back")cur.execute(DELETE_COHORT_SQL)+ cur.execute(DELETE_RECON_BACKUP_SQL)cur.execute(DELETE_PERSONS_SQL, {"team": team})removed = cur.rowcountif removed != in_batch:@@ -598,10 +999,27 @@ class Command(BaseCommand):time.sleep(options["sleep_ms"] / 1000.0)logger.info("persons_dedup.batch_done", team_id=team, batch=batches, deleted=removed, total=deleted)+ if not apply_changes:+ logger.info(+ "persons_dedup.dry_run_ok", team_id=team, mode=mode, batches=batches, checked=checked, staged=staged+ )+ return+logger.info(- "persons_dedup.done", team_id=team, mode=mode, batches=batches, deleted=deleted, backup=str(backup_path)+ "persons_dedup.done",+ team_id=team,+ mode=mode,+ batches=batches,+ deleted=deleted,+ pruned=pruned_total,+ backup=str(backup_path),)+ def _prune_batch(self, conn: psycopg.Connection) -> int:+ with conn.cursor() as cur:+ cur.execute(PRUNE_BATCH_SQL)+ return cur.rowcount+def _backup(self, conn: psycopg.Connection, team: int, path: Path) -> int:"""Write victims and their dependent rows to JSONL, fsync'd, before any delete.@@ -628,13 +1046,3 @@ class Command(BaseCommand):fh.flush()os.fsync(fh.fileno())return len(persons)---def write_summary_csv(path: Path, rows: list[dict[str, Any]]) -> None:- """Helper for operators collating classify output across many teams."""- if not rows:- return- with path.open("w", newline="") as fh:- writer = csv.DictWriter(fh, fieldnames=list(rows[0].keys()))- writer.writeheader()- writer.writerows(rows)diff --git a/posthog/management/commands/test/test_persons_dedup.py b/posthog/management/commands/test/test_persons_dedup.pyindex 6bf37011aa06..e8289d6af27e 100644--- a/posthog/management/commands/test/test_persons_dedup.py+++ b/posthog/management/commands/test/test_persons_dedup.py@@ -1,7 +1,9 @@from __future__ import annotations+import reimport jsonimport uuid as uuid_mod+from contextlib import contextmanagerfrom typing import Anyimport pytest@@ -10,6 +12,7 @@ from django.core.management import call_commandfrom django.core.management.base import CommandErrorimport psycopg+from structlog.testing import capture_logsfrom posthog.management.commands import persons_dedup as persons_dedup_commandfrom posthog.persons_db import persons_db_connection@@ -83,23 +86,70 @@ def _cleanup(conn: psycopg.Connection) -> None:cur.execute("DELETE FROM posthog_person WHERE team_id = %s", (TEAM,))-def _add_person(conn: psycopg.Connection, uuid: str, *, properties: str = "{}", version: int = 0) -> int:+def _add_person(+ conn: psycopg.Connection,+ uuid: str,+ *,+ properties: str = "{}",+ version: int = 0,+ is_identified: bool = False,+ is_deleted: bool = False,+) -> int:with conn.cursor() as cur:cur.execute(- "INSERT INTO posthog_person (created_at, properties, team_id, is_identified, uuid, version) "- "VALUES (now(), %s::jsonb, %s, false, %s, %s) RETURNING id",- (properties, TEAM, uuid, version),+ "INSERT INTO posthog_person "+ "(created_at, properties, team_id, is_identified, uuid, version, is_deleted) "+ "VALUES (now(), %s::jsonb, %s, %s, %s, %s, %s) RETURNING id",+ (properties, TEAM, is_identified, uuid, version, is_deleted),)row = cur.fetchone()assert row is not Nonereturn int(row[0])-def _add_distinct_id(conn: psycopg.Connection, person_id: int, distinct_id: str) -> None:+# One duplicate group: an unreferenced orphan plus the live row that must survive.+def _add_orphan_pair(conn: psycopg.Connection, uuid: str, distinct_id: str) -> int:+ _add_person(conn, uuid)+ live = _add_person(conn, uuid)+ _add_distinct_id(conn, live, distinct_id)+ return live+++def _add_orphan_pair_ids(conn: psycopg.Connection, uuid: str, distinct_id: str) -> tuple[int, int]:+ orphan = _add_person(conn, uuid)+ live = _add_person(conn, uuid)+ _add_distinct_id(conn, live, distinct_id)+ return orphan, live+++# Runs `action` on a second connection at the one moment that matters: after the command has+# cleared its pre-flight gates and before it opens the delete transaction. Every gate-failure+# path is unreachable without this, because staging excludes anything the gates would catch --+# only a concurrent writer can make a staged victim undeletable. Keyed on the gate SQL rather+# than a call count so it stays put if another pre-flight check is added.+@contextmanager+def _concurrent_write_before_delete(monkeypatch, action):+ real_scalar = persons_dedup_command._scalar+ state = {"fired": False}++ def scalar_then_interfere(conn, sql, params=None):+ result = real_scalar(conn, sql, params)+ if not state["fired"] and "victims >= members" in sql:+ state["fired"] = True+ with persons_db_connection(writer=True, autocommit=True) as other:+ action(other)+ return result++ monkeypatch.setattr(persons_dedup_command, "_scalar", scalar_then_interfere)+ yield lambda: state["fired"]+++def _add_distinct_id(conn: psycopg.Connection, person_id: int, distinct_id: str, *, is_deleted: bool = False) -> None:with conn.cursor() as cur:cur.execute(- "INSERT INTO posthog_persondistinctid (team_id, person_id, distinct_id, version) VALUES (%s, %s, %s, 0)",- (TEAM, person_id, distinct_id),+ "INSERT INTO posthog_persondistinctid (team_id, person_id, distinct_id, version, is_deleted) "+ "VALUES (%s, %s, %s, 0, %s)",+ (TEAM, person_id, distinct_id, is_deleted),)@@ -292,25 +342,120 @@ class TestPersonsDedupDeleteOnly:assert _persons(persons_conn) == 1+class TestPersonsDedupBatching:+ # Every other case here stages one or two victims against the default batch size of 500,+ # so the drain loop only ever runs once. A real team runs it hundreds of times, where a+ # bug in the take/retire cycle -- retiring the wrong rows, or not truncating the batch+ # table -- would strand most of that team while still reporting success. These are the+ # only cases where a second populated batch happens at all.+ def test_drains_every_batch_when_victims_exceed_batch_size(self, persons_conn, tmp_path):+ for n in range(5):+ _add_orphan_pair(persons_conn, _uuid(40 + n), f"did-40-{n}")+ assert _persons(persons_conn) == 10++ _run("delete-unreferenced", tmp_path, apply=True, batch_size=2)++ assert _persons(persons_conn) == 5+ assert _dup_groups(persons_conn) == 0+ assert _distinct_ids(persons_conn) == 5+ backed_up = [json.loads(line) for f in tmp_path.glob("*.jsonl") for line in f.read_text().splitlines()]+ assert len([r for r in backed_up if r["_kind"] == "person"]) == 5, "every deleted row must be recoverable"++ def test_dry_run_checks_every_batch_not_just_the_first(self, persons_conn, tmp_path):+ # A dry run that returned after the first batch reported dry_run_batch_ok having+ # gated batch_size victims out of the whole staged set, which an operator reads as+ # clearance for the --apply run that follows.+ for n in range(3):+ _add_orphan_pair(persons_conn, _uuid(50 + n), f"did-50-{n}")++ with capture_logs() as logs:+ _run("delete-unreferenced", tmp_path, batch_size=1)++ assert _persons(persons_conn) == 6, "a dry run must delete nothing"+ assert list(tmp_path.glob("*.jsonl")) == []+ summary = next(entry for entry in logs if entry["event"] == "persons_dedup.dry_run_ok")+ assert summary["checked"] == 3+ assert summary["batches"] == 3+++class TestPersonsDedupConcurrentWriters:+ # The in-transaction gates are the last thing standing between a wrong row and a silent+ # cascade into feature-flag overrides, and they are the only safety checks in this command+ # that a single-threaded test can never reach: staging excludes everything they catch, so+ # they fire only when a concurrent writer changes a staged victim mid-run. These two cases+ # drive that writer deterministically -- no threads, no sleeps.++ def test_a_victim_that_becomes_reachable_is_dropped_and_the_run_continues(+ self, persons_conn, tmp_path, monkeypatch+ ):+ # A returning user attaches a distinct ID to the orphan after it was staged. It is now+ # a live person, so deleting it would take its overrides with it.+ orphan, live = _add_orphan_pair_ids(persons_conn, _uuid(60), "did-60")++ def attach_a_mapping(other):+ _add_distinct_id(other, orphan, "did-60-returning")++ with _concurrent_write_before_delete(monkeypatch, attach_a_mapping) as fired:+ with capture_logs() as logs:+ _run("delete-unreferenced", tmp_path, apply=True)++ assert fired(), "the interfering write never ran; the test proves nothing"+ assert _persons(persons_conn) == 2, "the newly reachable row must not be deleted"+ assert any(entry["event"] == "persons_dedup.batch_raced" for entry in logs)+ assert any(entry["event"] == "persons_dedup.done" for entry in logs), "the run must finish, not abort"++ def test_a_group_that_loses_its_survivor_is_dropped_and_the_run_continues(+ self, persons_conn, tmp_path, monkeypatch+ ):+ # Something else deletes the survivor after staging. The staged victim is now the only+ # row holding that key, so it is no longer a duplicate and must not be deleted either.+ orphan, live = _add_orphan_pair_ids(persons_conn, _uuid(61), "did-61")++ def delete_the_survivor(other):+ with other.cursor() as cur:+ cur.execute("DELETE FROM posthog_persondistinctid WHERE team_id = %s AND person_id = %s", (TEAM, live))+ cur.execute("DELETE FROM posthog_person WHERE team_id = %s AND id = %s", (TEAM, live))++ with _concurrent_write_before_delete(monkeypatch, delete_the_survivor) as fired:+ with capture_logs() as logs:+ _run("delete-unreferenced", tmp_path, apply=True)++ assert fired(), "the interfering write never ran; the test proves nothing"+ remaining = _count(persons_conn, "SELECT id FROM posthog_person WHERE team_id = %s", (TEAM,))+ assert remaining == orphan, "the last row holding the key must survive"+ assert _persons(persons_conn) == 1+ assert any(entry["event"] == "persons_dedup.done" for entry in logs), "the run must finish, not abort"++class TestPersonsDedupRepair:- def test_repairs_the_production_shape(self, persons_conn, tmp_path):- # The shape every merge-required group in the production census shared:- # one row owns the distinct ID, the other owns a flag override, neither owns both.+ # The shape every merge-required group in the production census shared: one row owns the+ # distinct ID, the other owns a flag override, neither owns both. This is also the only+ # place the two write modes disagree, so both arms are pinned here -- repair takes the+ # unreachable row and cascades its dead override away, delete-unreferenced refuses it+ # because the override is a reference. Swapping either staging predicate for the other+ # silently changes which rows a production run destroys.+ @pytest.mark.parametrize(+ "mode,expected_persons,expected_overrides,expected_dup_groups",+ [+ ("repair", 1, 0, 0),+ ("delete-unreferenced", 2, 1, 1),+ ],+ )+ def test_mode_divergence_on_the_production_shape(+ self, persons_conn, tmp_path, mode, expected_persons, expected_overrides, expected_dup_groups+ ):uuid = _uuid(20)live = _add_person(persons_conn, uuid)_add_distinct_id(persons_conn, live, "did-20")stranded = _add_person(persons_conn, uuid)_add_flag_override(persons_conn, stranded, "flag-20")- _run("repair", tmp_path, apply=True)+ _run(mode, tmp_path, apply=True)- assert _dup_groups(persons_conn) == 0- assert _persons(persons_conn) == 1+ assert _persons(persons_conn) == expected_persons+ assert _flag_overrides(persons_conn) == expected_overrides+ assert _dup_groups(persons_conn) == expected_dup_groupsassert _distinct_ids(persons_conn) == 1- # The stranded row's override was unreachable (no distinct ID resolves to it),- # so cascading it away preserves behaviour. Moving it onto the live person would- # instead resurrect dead data and could change that user's flag variant.- assert _flag_overrides(persons_conn) == 0def test_survivor_is_the_distinct_id_owner_even_when_it_is_the_newer_row(self, persons_conn, tmp_path):# Production's actual shape: the distinct id points at the NEWER row in every@@ -401,11 +546,13 @@ class TestPersonsDedupRepair:assert _persons(persons_conn) == 1assert _cohort_rows(persons_conn) == 1- def test_never_deletes_a_row_the_reconciliation_backup_references(self, persons_conn, tmp_path):- # The Dagster property-reconciliation job restores person properties by- # (team_id, person_id) from its pre-image table. Deleting a person it references- # would leave the restore path pointing at a row that no longer exists, so such- # rows are excluded from staging and the group is left for a later pass.+ def test_deletes_an_orphan_the_reconciliation_backup_references_and_takes_the_backup_row(+ self, persons_conn, tmp_path+ ):+ # A reconciliation backup row does not make a person live. Its restore path reads the+ # person by id and treats a missing row as a skip, so refusing this delete only left a+ # dead row behind, plus a backup row that would warn on every future restore and keep+ # the deleted person's properties. Both go together now.uuid = _uuid(27)live = _add_person(persons_conn, uuid)_add_distinct_id(persons_conn, live, "did-27")@@ -414,24 +561,233 @@ class TestPersonsDedupRepair:_run("repair", tmp_path, apply=True)- assert _persons(persons_conn) == 2, "the referenced row must be skipped, not deleted"+ assert _persons(persons_conn) == 1+ assert _dup_groups(persons_conn) == 0+ assert (+ _count(+ persons_conn,+ "SELECT count(*) FROM posthog_person_reconciliation_backup WHERE team_id = %s",+ (TEAM,),+ )+ == 0+ ), "the backup row must not outlive the person it describes"+ records = [json.loads(line) for f in tmp_path.glob("*.jsonl") for line in f.read_text().splitlines()]+ assert any(r["_kind"] == "reconciliation_backup" and r["person_id"] == held for r in records), (+ "the backup row must be recoverable from the undo file"+ )++ def test_deletes_an_orphan_stranded_inside_a_merge_required_group(self, persons_conn, tmp_path):+ # Two live rows need a real merge, which this command refuses. The third row owns no+ # mapping and is dead on exactly the same terms as any other orphan -- its deadness has+ # nothing to do with what the other two are doing. Skipping it left known-dead rows+ # behind whose cohort memberships still counted toward the cohort size shown in the UI.+ uuid = _uuid(90)+ a = _add_person(persons_conn, uuid)+ b = _add_person(persons_conn, uuid)+ _add_distinct_id(persons_conn, a, "did-90a")+ _add_distinct_id(persons_conn, b, "did-90b")+ _add_person(persons_conn, uuid)++ _run("repair", tmp_path, apply=True)++ assert _persons(persons_conn) == 2, "the orphan goes, both live rows stay"+ remaining = _count(+ persons_conn,+ "SELECT count(*) FROM posthog_person WHERE team_id = %s AND id = ANY(%s)",+ (TEAM, [a, b]),+ )+ assert remaining == 2+ assert _dup_groups(persons_conn) == 1, "the group still needs a merge and is still reported"++ def test_the_merge_required_group_is_still_reported_after_its_orphan_is_removed(self, persons_conn, tmp_path):+ uuid = _uuid(91)+ a = _add_person(persons_conn, uuid)+ b = _add_person(persons_conn, uuid)+ _add_distinct_id(persons_conn, a, "did-91a")+ _add_distinct_id(persons_conn, b, "did-91b")+ _add_person(persons_conn, uuid)++ _run("repair", tmp_path, apply=True)+ with capture_logs() as logs:+ _run("verify", tmp_path)++ result = next(entry for entry in logs if entry["event"] == "persons_dedup.verify")+ assert result["blocked_groups"] == 1+ assert result["resolvable_groups"] == 0, "removing the orphan must not make the group look resolvable"++ def test_all_orphan_group_keeps_the_identified_row(self, persons_conn, tmp_path):+ # A sizeable share of real duplicate groups have no member owning a distinct ID, so+ # the leading (n_did > 0) term in the survivor ranking cannot break the tie and the+ # rest of it decides alone. Nothing else exercises that branch, and getting it wrong+ # discards the richer row while keeping an empty one.+ uuid = _uuid(28)+ plain = _add_person(persons_conn, uuid)+ identified = _add_person(persons_conn, uuid, is_identified=True)++ _run("repair", tmp_path, apply=True)++ assert _persons(persons_conn) == 1+ survivor = _count(persons_conn, "SELECT id FROM posthog_person WHERE team_id = %s", (TEAM,))+ assert survivor == identified, "is_identified must outrank the plain row"+ assert plain != identified++ def test_never_deletes_a_tombstoned_row(self, persons_conn, tmp_path):+ # is_deleted is a revival marker, not a dead row: the write path reuses it so the+ # revived key outranks its own ClickHouse tombstone, which needs the version this+ # row holds. Deleting it would drop that version floor silently.+ uuid = _uuid(29)+ live = _add_person(persons_conn, uuid)+ _add_distinct_id(persons_conn, live, "did-29")+ _add_person(persons_conn, uuid, is_deleted=True)++ _run("repair", tmp_path, apply=True)++ assert _persons(persons_conn) == 2, "the tombstone must be left alone"assert _dup_groups(persons_conn) == 1+ def test_a_tombstone_never_outranks_a_live_row(self, persons_conn, tmp_path):+ # Neither row owns a distinct ID, so the leading term of the ranking ties and the+ # tombstone would win on is_identified and version -- making the live row the victim+ # and deleting the only row of the two that can still be revived into service.+ uuid = _uuid(33)+ _add_person(persons_conn, uuid, is_deleted=True, version=99, is_identified=True)+ live = _add_person(persons_conn, uuid)++ _run("repair", tmp_path, apply=True)++ survivors = _count(+ persons_conn, "SELECT count(*) FROM posthog_person WHERE team_id = %s AND id = %s", (TEAM, live)+ )+ assert survivors == 1, "the live row must outrank a higher-version identified tombstone"+ assert _persons(persons_conn) == 2, "and the tombstone itself is never staged"+++class TestPersonsDedupSurvivorSelection:+ def test_a_row_reachable_only_through_a_tombstoned_mapping_loses_to_a_live_one(self, persons_conn, tmp_path):+ # The flag path requires pdi.is_deleted = false, so a tombstoned mapping does not make+ # a person reachable. Ranking on the raw mapping count would tie these two and let the+ # tiebreak keep the row the product cannot see.+ uuid = _uuid(80)+ tombstoned_owner = _add_person(persons_conn, uuid, is_identified=True, version=99)+ _add_distinct_id(persons_conn, tombstoned_owner, "did-80-dead", is_deleted=True)+ live = _add_person(persons_conn, uuid)+ _add_distinct_id(persons_conn, live, "did-80-live")++ _run("classify", tmp_path)++ survivor = _count(+ persons_conn,+ "SELECT id FROM posthog_person p WHERE p.team_id = %s AND p.uuid = %s "+ "AND EXISTS (SELECT 1 FROM posthog_persondistinctid d "+ "WHERE d.person_id = p.id AND NOT d.is_deleted)",+ (TEAM, uuid),+ )+ assert survivor == live+ # Neither is deletable: both own a mapping, so the foreign key would block either way.+ _run("repair", tmp_path, apply=True)+ assert _persons(persons_conn) == 2++ def test_classify_writes_actionable_detail_for_groups_it_refuses(self, persons_conn, tmp_path):+ # A count of blocked groups cannot be acted on. Resolving one needs to know which rows+ # it holds, which are still reachable, and what hangs off them.+ uuid = _uuid(81)+ a = _add_person(persons_conn, uuid)+ b = _add_person(persons_conn, uuid)+ _add_distinct_id(persons_conn, a, "did-81a")+ _add_distinct_id(persons_conn, b, "did-81b")+ _add_flag_override(persons_conn, b, "flag-81")++ _run("classify", tmp_path)++ dumps = list(tmp_path.glob("blocked_team_*.jsonl"))+ assert dumps, "a refused group must leave a record behind"+ records = [json.loads(line) for line in dumps[0].read_text().splitlines()]+ assert len(records) == 1+ record = records[0]+ assert record["reason"] == "multiple_reachable_rows"+ assert record["reachable_owners"] == 2+ assert record["flag_overrides"] == 1+ assert sorted(record["reachable_ids"]) == sorted([a, b]), "both live rows must be named"++ def test_classify_writes_nothing_when_every_group_is_resolvable(self, persons_conn, tmp_path):+ _add_orphan_pair(persons_conn, _uuid(82), "did-82")++ _run("classify", tmp_path)++ assert list(tmp_path.glob("blocked_team_*.jsonl")) == []++ def test_a_reconciliation_backup_row_does_not_claim_the_blocking_reason(self, persons_conn, tmp_path):+ # The backup stopped refusing deletes, so it must not be named as the cause either.+ # This group is held by its tombstone; attributing it to the backup would send the+ # follow-up work at the wrong table.+ uuid = _uuid(83)+ survivor = _add_person(persons_conn, uuid)+ _add_distinct_id(persons_conn, survivor, "did-83")+ tombstoned = _add_person(persons_conn, uuid, is_deleted=True)+ _add_recon_backup_row(persons_conn, tombstoned, uuid)++ _run("classify", tmp_path)++ records = [+ json.loads(line) for dump in tmp_path.glob("blocked_team_*.jsonl") for line in dump.read_text().splitlines()+ ]+ assert len(records) == 1+ assert records[0]["reason"] == "tombstoned_member"+ assert records[0]["recon_held"] == 1, "still reported, just not as the reason"++ def test_two_distinct_id_owners_are_blocked_even_when_one_is_unreachable(self, persons_conn, tmp_path):+ # live_owners is what refuses the group; reachable_owners only says whether the product+ # can still resolve both. A reason keyed on reachable_owners alone called this 'other'.+ uuid = _uuid(84)+ survivor = _add_person(persons_conn, uuid)+ _add_distinct_id(persons_conn, survivor, "did-84")+ dead_owner = _add_person(persons_conn, uuid)+ _add_distinct_id(persons_conn, dead_owner, "did-84-dead", is_deleted=True)++ _run("classify", tmp_path)++ records = [+ json.loads(line) for dump in tmp_path.glob("blocked_team_*.jsonl") for line in dump.read_text().splitlines()+ ]+ assert len(records) == 1+ assert records[0]["reason"] == "multiple_distinct_id_owners"+ assert records[0]["live_owners"] == 2+ assert records[0]["reachable_owners"] == 1+ # And the foreign key is why: the tombstoned mapping still references the row.+ _run("repair", tmp_path, apply=True)+ assert _persons(persons_conn) == 2+class TestPersonsDedupVerify:- def test_verify_fails_while_duplicates_remain(self, persons_conn, tmp_path):- uuid = _uuid(30)+ def test_verify_fails_while_resolvable_duplicates_remain(self, persons_conn, tmp_path):+ # An orphan repair would have taken: work is genuinely outstanding.+ _add_orphan_pair(persons_conn, _uuid(30), "did-30")++ with pytest.raises(CommandError, match="resolvable duplicate group"):+ _run("verify", tmp_path)++ def test_verify_accepts_a_remainder_only_this_command_cannot_resolve(self, persons_conn, tmp_path):+ # Both rows own a distinct ID, so this needs a real person merge -- a separate+ # workstream. Raising here made verify useless as a release gate on exactly the+ # teams that have such groups, because its failure was indistinguishable from+ # "the dedup run did not finish".+ uuid = _uuid(31)a = _add_person(persons_conn, uuid)b = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, a, "did-30a")- _add_distinct_id(persons_conn, b, "did-30b")+ _add_distinct_id(persons_conn, a, "did-31a")+ _add_distinct_id(persons_conn, b, "did-31b")- with pytest.raises(CommandError, match="duplicate group"):+ with capture_logs() as logs:_run("verify", tmp_path)+ result = next(entry for entry in logs if entry["event"] == "persons_dedup.verify")+ assert result["duplicate_groups"] == 1+ assert result["blocked_groups"] == 1+ assert result["resolvable_groups"] == 0+def test_verify_passes_once_clean(self, persons_conn, tmp_path):- person = _add_person(persons_conn, _uuid(31))- _add_distinct_id(persons_conn, person, "did-31")+ person = _add_person(persons_conn, _uuid(32))+ _add_distinct_id(persons_conn, person, "did-32")_run("verify", tmp_path)@@ -453,6 +809,48 @@ class TestPersonsDedupVerify:_run("verify", tmp_path, apply=True)+class TestPersonsDedupTargetGuard:+ def test_refuses_to_run_when_the_persons_url_is_unset(self, monkeypatch, tmp_path):+ # Unset, posthog.persons_db builds a localhost URL from PG*. On a deployed pod those+ # point at the main cluster, so a silent fallback aims a destructive command at the+ # wrong database. It must refuse rather than connect.+ monkeypatch.delenv("PERSONS_DB_WRITER_URL", raising=False)+ monkeypatch.delenv("PERSONS_DB_READER_URL", raising=False)++ with pytest.raises(CommandError, match="PERSONS_DB_WRITER_URL is not set"):+ _run("repair", tmp_path, apply=True)++ def test_logs_the_host_and_dbname_it_is_about_to_modify(self, persons_conn, tmp_path):+ # The operator drives this by hand against production; host plus dbname is how they+ # confirm the toolbox is pointed at persons and not the main cluster.+ with capture_logs() as logs:+ _run("classify", tmp_path)++ target = [entry for entry in logs if entry["event"] == "persons_dedup.target"]+ assert len(target) == 1, "every run must say which database it targets"+ assert target[0]["dbname"]+ assert "password" not in str(target[0]), "the log line must not carry credentials"+++class TestPersonsDedupPrivilegePreflight:+ def test_every_table_the_command_deletes_from_is_probed_for_delete(self):+ # The preflight exists so a missing grant aborts before any work. It is only worth+ # that if it covers every table written to -- a DELETE added without a matching+ # probe fails mid-transaction on the first team whose data reaches it, which is+ # exactly how the reconciliation-backup delete shipped.+ deleted_tables = set()+ for name, sql in vars(persons_dedup_command).items():+ if not name.startswith("DELETE_") or not isinstance(sql, str):+ continue+ match = re.search(r"DELETE\s+FROM\s+([a-z_]+)", sql, re.IGNORECASE)+ assert match, f"{name} does not look like a DELETE statement"+ deleted_tables.add(match.group(1))+ assert deleted_tables, "no DELETE_* constants found -- did they get renamed?"++ probed = {t for t, p in persons_dedup_command.REQUIRED_PRIVILEGES if p == "DELETE"}+ assert deleted_tables <= probed, f"deletes without a DELETE grant probe: {sorted(deleted_tables - probed)}"++class TestPersonsDedupConnectionRouting:# The reads can scan for minutes on large teams; silently moving them back to the# primary is the regression these guard against. Locally the reader URL falls back