Skip to content

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

fix(persons): unblock persons_dedup on Aurora, make repairs resumable (#86849)

Eli Reismana851a37642d3
diff --git a/posthog/management/commands/persons_dedup.py b/posthog/management/commands/persons_dedup.py
index e1345a9e700a..4b92fd585dad 100644
--- a/posthog/management/commands/persons_dedup.py
+++ b/posthog/management/commands/persons_dedup.py
@@ -3,131 +3,102 @@
Production has no unique index on (team_id, uuid) even though
rust/persons_migrations/20251113000001 declares one, and person UUIDs are derived
deterministically from (team_id, primary distinct_id). Any actor that removes a
-posthog_persondistinctid row while leaving its person behind therefore lets the next
-event mint a second person row with an identical (team_id, uuid).
+posthog_persondistinctid row while leaving its person behind therefore lets the next event
+mint a second person row with an identical (team_id, uuid).
-This command resolves those groups so the unique index can be built. It never creates,
-drops or alters an index -- that is separate work, gated on `--mode verify` reporting
-zero remaining groups.
+This command resolves those groups so the unique index can be built. It never creates, drops
+or alters an index; that is separate work, gated on `--mode verify` reporting zero resolvable
+groups.
SAFETY MODEL
-Everything rests on one property, verified against the flag and cohort read paths:
+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).
- 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).
+"The row is unreachable" would overstate it, because the persons detail API and personhog's
+GetPersonByUuid and friends reach a person by uuid or bigint id without touching a distinct
+id. What makes the delete safe is narrower: a victim is always rn > 1 within its duplicate
+group, so a row carrying the same uuid always survives it. Every uuid-keyed lookup still finds
+a person, just the one the product can actually resolve.
-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 gates enforce this from opposite directions, because proving the victims are safe is not
+the same as proving the survivor is right:
-Two consequences of that worth stating rather than discovering:
+ 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
- - 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.
+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 teams on
+PERSON_CREATE_CLAIM_TEAM_ALLOWLIST 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.
-Two gates enforce it from opposite directions, because proving the victims are safe is
-not the same as proving the survivor is right:
+n_did = 0 is the safety condition and nothing else is. Being referenced is not the same as
+being live: a row owning no distinct ID is dead whatever else points at it, and skipping it
+only leaves cohort memberships that still count toward the 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.
- 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
+DEPENDENT TABLES
-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 already
-unreachable. Moving them onto the surviving person would do the opposite: it would
-resurrect 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 why
-the reachability assertion runs before every delete and again inside the transaction:
+These behave differently on DELETE in production, which is why the 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_person_reconciliation_backup no FK -> silently orphans rows
-Only the first fails loudly, so the command cannot rely on the database to catch a
-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.
+Only the first fails loudly, so the one without a foreign key is deleted explicitly and before
+the person row, letting a failure there abort before anything is lost. In production the
+override FK is DEFERRABLE INITIALLY DEFERRED, so that cascade runs at COMMIT rather than at the
+DELETE, and the transaction's statement_timeout has to cover it.
-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.
+One user-visible effect. Static cohort size comes from a bare COUNT(*) over
+posthog_cohortpeople with no join to persons, so an unreachable row's memberships are counted
+today. Removing that row corrects the displayed count downward, which also un-demotes a cohort
+that the inflated count pushed past the realtime-evaluation threshold. Static cohort population
+resolves uuid to person id without deduplicating, so expect the post-commit cohort sweep to
+find rows on an active team.
BLAST RADIUS OF A DELETED bigint id
-Audited across the repo rather than assumed. Two facts do most of the work.
+posthog_person.id comes from a sequence and nothing calls setval, 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.
-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 stores only person.uuid, never the bigint, so a dedup needs no ClickHouse tombstone.
+That holds only because the survivor keeps the uuid: delete the last row for a uuid and
+ClickHouse is left visible but unbacked. GATE_NO_SURVIVOR_SQL prevents that. Do not weaken it.
-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 places this command cannot repair, all of which
+fail safe. Drain these before a large run rather than reasoning about them mid-flight:
-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
+ posthog_activitylog.item_id the audit trail becomes reachable only by uuid
+ Temporal delete-persons input a queued run 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.
+BACKUPS
-Deleted rows and their dependent rows are written to a local JSONL file, fsync'd, after
-the victims are locked and before the delete runs. Locking first matters: an insert into
-posthog_featureflaghashkeyoverride takes FOR KEY SHARE on the parent person row, so
-reading dependents before the lock would let a row appear afterwards, cascade away, and
-never reach the backup. Writing before the delete means a rolled back transaction leaves
-a harmless superset, and a deleted row can never be missing. Copy that file off the pod;
-it is the only undo.
+Deleted rows and their dependents are written to a local JSONL file, fsync'd, after the victims
+are locked and before the delete runs. Locking first matters: an insert into
+posthog_featureflaghashkeyoverride takes FOR KEY SHARE on the parent person row, so reading
+dependents before the lock would let a row appear afterwards, cascade away, and never reach the
+backup. Writing before the delete means a rolled back or retried batch leaves a harmless
+superset, while 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.
+A row with is_deleted = true is a tombstone rather than 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
+holds. Deleting one would drop that version floor, so tombstoned rows are never staged and lose
+the survivor ranking to any live member of their group. A group of only tombstoned rows stays
+unresolved, which verify reports rather than hides.
"""
from __future__ import annotations
@@ -135,16 +106,20 @@ from __future__ import annotations
import os
import json
import time
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
from datetime import UTC, datetime
from pathlib import Path
-from typing import Any
+from typing import Any, TypeVar
from urllib.parse import urlsplit
+from uuid import UUID
from django.core.management.base import BaseCommand, CommandError
import psycopg
import structlog
+from posthog.dataclasses import frozen
from posthog.persons_db import persons_db_connection, persons_db_url
logger = structlog.get_logger(__name__)
@@ -166,25 +141,18 @@ PERSON_COLUMNS = (
"is_deleted",
)
-# Reference counts per member row of a duplicate group.
-# posthog_person_reconciliation_backup (the Dagster property-reconciliation pre-image
-# table) is counted defensively: a row it references stops being deletable. The
-# personhog lifecycle/shadow tables are deliberately NOT consulted -- personhog does not
-# run in production, its tables are empty there, and their ACLs are owner-only, so a
-# subquery against them fails with permission denied for the operator role.
-_MEMBERS_CTE = """
-WITH dups AS (
- SELECT team_id, uuid FROM posthog_person
- WHERE team_id = %(team)s
- GROUP BY team_id, uuid HAVING count(*) > 1
-),
+# Reference counts per member row of a duplicate group. Only tables a live read path can reach
+# are consulted: the personhog lifecycle and shadow tables are owner-only, so a subquery against
+# them fails with permission denied for the operator role.
+_MEMBERS_CTE_TEMPLATE = """
+{dups}
members AS (
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.
+ -- 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, so staging a row
+ -- with any mapping would fail the delete. n_did_live is what the product sees,
+ -- because the flag path requires pdi.is_deleted = false, so it decides which row
+ -- is worth keeping.
(SELECT count(*) FROM posthog_persondistinctid pdi
WHERE pdi.team_id = p.team_id AND pdi.person_id = p.id) AS n_did,
(SELECT count(*) FROM posthog_persondistinctid pdi
@@ -193,9 +161,7 @@ members AS (
(SELECT count(*) FROM posthog_cohortpeople cp
WHERE cp.person_id = p.id) AS n_cohort,
(SELECT count(*) FROM posthog_featureflaghashkeyoverride ff
- WHERE ff.team_id = p.team_id AND ff.person_id = p.id) AS n_ff,
- (SELECT count(*) FROM posthog_person_reconciliation_backup rb
- WHERE rb.team_id = p.team_id AND rb.person_id = p.id) AS n_recon
+ WHERE ff.team_id = p.team_id AND ff.person_id = p.id) AS n_ff
FROM posthog_person p
JOIN dups d ON d.team_id = p.team_id AND d.uuid = p.uuid
WHERE p.team_id = %(team)s
@@ -204,7 +170,7 @@ members AS (
-- 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
+ SELECT *, (n_did + n_cohort + n_ff) AS refs FROM members
),
ranked AS (
SELECT *,
@@ -216,14 +182,17 @@ ranked AS (
FROM 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.
+-- classify and verify report exactly what repair will and will not resolve. Every
+-- number classify reports is derivable from here, so it aggregates this once rather
+-- than making a separate pass over `ranked` per statistic.
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,
+ count(*) FILTER (WHERE refs > 0) AS referenced_members,
+ sum(n_did)::bigint AS distinct_ids,
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
@@ -231,111 +200,208 @@ per_group AS (
)
"""
-CLASSIFY_SQL = (
- _MEMBERS_CTE
- + """
-SELECT
- (SELECT count(*) FROM (SELECT uuid FROM ranked GROUP BY uuid) x),
- (SELECT count(*) FROM (SELECT uuid FROM ranked GROUP BY uuid
- HAVING count(*) FILTER (WHERE refs > 0) = 0) x),
- (SELECT count(*) FROM (SELECT uuid FROM ranked GROUP BY uuid
- HAVING count(*) FILTER (WHERE refs > 0) = 1) x),
- (SELECT count(*) FROM (SELECT uuid FROM ranked GROUP BY uuid
- HAVING count(*) FILTER (WHERE refs > 0) > 1) x),
- (SELECT count(*) FROM (SELECT uuid FROM ranked GROUP BY uuid
- HAVING 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
+# Unpaged: find the duplicate groups by aggregating the team's whole slice of
+# posthog_person in one statement, holding one snapshot for as long as that takes.
+_DUPS_BY_SCAN = """
+WITH dups AS (
+ SELECT team_id, uuid FROM posthog_person
+ WHERE team_id = %(team)s
+ GROUP BY team_id, uuid HAVING count(*) > 1
+),"""
+
+# Paged: the caller already knows this page's duplicate uuids, so the group-by disappears and
+# every statement below starts from a short explicit list. PAGE_UUIDS_SQL does the scanning,
+# once, and its LIMIT is what bounds the snapshot.
+_DUPS_FROM_LIST = """
+WITH dups AS (
+ SELECT %(team)s::integer AS team_id, t.uuid
+ FROM unnest(%(uuids)s::uuid[]) AS t(uuid)
+),"""
+
+# The duplicate uuids in one slice of the uuid space, which the statements below then start
+# from. Slicing trades total work for a bounded snapshot, so it is off by default:
+#
+# Slicing bounds how long any one snapshot is held, and slices the range rather than LIMITing
+# the group count because a LIMIT bounds only the rows returned, so on a team whose duplicates
+# are sparse one page would scan almost the whole team to fill its quota.
+#
+# Total work is about the same either way. EXPLAIN against prod-US shows the slice driver
+# as a partition-pruned Index Only Scan whose slices tile the team's index range once, and
+# the statements below driving from the uuid list with `uuid = d.uuid` as an Index Cond, so
+# they probe rather than scan at any slice size. It is off by default only because slicing
+# has never run against production, not because it is expensive.
+#
+# Balanced because person uuids are UUIDv5, so their leading bytes are hash output and spread
+# evenly (nodejs/src/ingestion/common/persons/person-uuid.ts). Exact because
+# posthog_person.uuid is immutable in production, so a group falls in one slice for all time.
+# Do not slice on posthog_persondistinctid.person_id, which the claim path rewrites.
+#
+# A sliced total is a sum over snapshots rather than a census at one instant. The only group it
+# can miss is one created after its slice was read, which a single-statement census misses too.
+SLICE_UUIDS_SQL = """
+SELECT uuid FROM posthog_person
+WHERE team_id = %(team)s AND uuid >= %(lo)s AND uuid <= %(hi)s
+GROUP BY team_id, uuid HAVING count(*) > 1
+ORDER BY uuid
"""
+
+_UUID_SPACE = 1 << 128
+
+
+@frozen
+class UuidSlice:
+ """A closed range of the uuid space. SLICE_UUIDS_SQL matches both ends."""
+
+ first: UUID
+ last: UUID
+
+
+def _uuid_slices(count: int) -> Iterator[UuidSlice]:
+ """Contiguous, non-overlapping ranges covering the whole uuid space."""
+ step = _UUID_SPACE // count
+ for index in range(count):
+ last = _UUID_SPACE - 1 if index == count - 1 else (index + 1) * step - 1
+ yield UuidSlice(first=UUID(int=index * step), last=UUID(int=last))
+
+
+def _sql(tail: str, *, paged: bool) -> str:
+ return _MEMBERS_CTE_TEMPLATE.format(dups=_DUPS_FROM_LIST if paged else _DUPS_BY_SCAN) + tail
+
+
+def _read_in_txn(conn: psycopg.Connection, sql: str, params: dict, *, step: str) -> Any:
+ """One statement in its own transaction with no timeout.
+
+ SET LOCAL keeps the unlimited timeout transaction-scoped, so it survives a connection whose
+ session-level SET a pooler dropped.
+ """
+
+ def read() -> Any:
+ with conn.cursor() as cur:
+ cur.execute("BEGIN")
+ cur.execute("SET LOCAL statement_timeout = 0")
+ cur.execute(sql, params)
+ rows = cur.fetchall()
+ cur.execute("COMMIT")
+ return rows
+
+ return _retry_replica_conflict(conn, step, read)
+
+
+def _census_pages(conn: psycopg.Connection, team: int, slices: int, *, pid: int) -> Iterator[dict[str, Any]]:
+ """Yield query params for each slice that holds at least one duplicate group.
+
+ slices <= 1 yields a single unpaged page, which is the fallback if slicing ever misbehaves
+ against production.
+ """
+ if slices <= 1:
+ yield {"team": team}
+ return
+ for index, uuid_slice in enumerate(_uuid_slices(slices), start=1):
+ params = {"team": team, "lo": uuid_slice.first, "hi": uuid_slice.last}
+ rows = _read_in_txn(conn, SLICE_UUIDS_SQL, params, step="slice_uuids")
+ if not rows:
+ continue
+ uuids = [row[0] for row in rows]
+ logger.info("persons_dedup.slice", team_id=team, slice=index, of=slices, groups=len(uuids), pid=pid)
+ yield {"team": team, "uuids": uuids}
+
+
+# Positional, matching the SELECT list below. Slicing sums these across slices, so every
+# column has to be a count or a sum; anything order-dependent would not compose.
+CLASSIFY_COLUMNS = (
+ "dup_groups",
+ "all_orphaned",
+ "one_referenced",
+ "needs_merge",
+ "groups_with_distinct_ids_on_multiple_rows",
+ "blocked_groups",
+ "tombstoned_members",
+ "distinct_ids",
+ "cohort_rows",
+ "flag_overrides",
)
+CLASSIFY_TAIL = """
+SELECT
+ count(*),
+ count(*) FILTER (WHERE referenced_members = 0),
+ count(*) FILTER (WHERE referenced_members = 1),
+ count(*) FILTER (WHERE referenced_members > 1),
+ count(*) FILTER (WHERE live_owners > 1),
+ count(*) FILTER (WHERE live_owners > 1 OR members - stageable > 1),
+ COALESCE(sum(tombstoned), 0),
+ COALESCE(sum(distinct_ids), 0),
+ COALESCE(sum(cohort_rows), 0),
+ COALESCE(sum(flag_overrides), 0)
+FROM per_group
+"""
+
# Delete-only: a non-survivor that nothing at all references.
-STAGE_UNREFERENCED_SQL = (
- _MEMBERS_CTE
- + f"""
+_STAGE_UNREFERENCED_TAIL = f"""
INSERT INTO {VICTIMS_TABLE} (team_id, id, uuid)
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, 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"""
+# Repair: a non-survivor owning NO distinct IDs. Unreachable by definition, so its feature-flag
+# overrides and cohort rows are dead data that go with it. n_did = 0 does more work than it
+# looks: because it counts tombstoned mappings as well as live ones, it excludes both rows a
+# foreign key would refuse to delete and rows the product can still resolve.
+_STAGE_UNREACHABLE_TAIL = f"""
INSERT INTO {VICTIMS_TABLE} (team_id, id, uuid)
SELECT team_id, id, uuid FROM ranked
WHERE rn > 1
AND n_did = 0
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).
+# than one member after every stageable victim is removed is held by 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
- + """
+COUNT_BLOCKED_TAIL = """
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
- + """
+# tombstone case needs to be told apart from it.
+BLOCKED_DETAIL_TAIL = """,
+-- `ranked` is referenced more than once, so Postgres materializes it without an index.
+-- Aggregating the ids here costs one grouped pass; correlating a subquery against
+-- `ranked` per blocked group would re-scan that whole tuplestore each time.
+group_ids AS (
+ SELECT uuid,
+ array_agg(id ORDER BY rn) AS member_ids,
+ array_agg(id ORDER BY rn) FILTER (WHERE n_did_live > 0) AS reachable_ids
+ FROM ranked GROUP BY uuid
+)
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.
+ -- Mirrors the WHERE below branch for branch, so the reason names the condition that
+ -- actually refused the group. '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 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.members, g.reachable_owners, g.live_owners, g.tombstoned,
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
+ ids.member_ids, ids.reachable_ids
FROM per_group g
+JOIN group_ids ids ON ids.uuid = g.uuid
WHERE g.live_owners > 1 OR g.members - g.stageable > 1
ORDER BY g.uuid
"""
-)
+
+# Victims a previous run already deleted, dropped at load time so they never reach the gates.
+RECONCILE_CHECKPOINT_SQL = f"""
+DELETE FROM {VICTIMS_TABLE} v
+WHERE v.team_id = %(team)s
+ AND NOT EXISTS (SELECT 1 FROM posthog_person p WHERE p.team_id = v.team_id AND p.id = v.id)
+"""
TAKE_BATCH_SQL = f"""
INSERT INTO {VICTIMS_TABLE}_batch (team_id, id, uuid)
@@ -347,10 +413,10 @@ DELETE FROM {VICTIMS_TABLE} v USING {VICTIMS_TABLE}_batch b
WHERE 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:
+# Drop from the staged set the batch members a concurrent writer made undeletable. Only the
+# staged set is touched; no person row is modified. Aborting instead would discard a staging
+# scan that costs minutes, and on a team still receiving writes could stop the run finishing at
+# all. 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.
@@ -382,11 +448,11 @@ WHERE EXISTS (SELECT 1 FROM posthog_persondistinctid pdi
WHERE pdi.team_id = v.team_id AND pdi.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.
+# The mirror of the reachable gate: that one proves no victim is reachable, this proves the
+# row we keep is the right one. Staging already guarantees it because a victim needs n_did = 0,
+# so 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 (
@@ -414,6 +480,13 @@ SELECT count(*) FROM (
) g WHERE victims >= members
"""
+# All three gates in one statement so they share a snapshot. Run separately under READ
+# COMMITTED each takes its own, so a writer landing in between can produce a failure
+# message describing a state that never existed at any instant.
+GATES_SQL = f"""
+SELECT ({GATE_REACHABLE_SQL}), ({GATE_NO_SURVIVOR_SQL}), ({GATE_SURVIVOR_REACHABLE_SQL})
+"""
+
LOCK_VICTIMS_SQL = f"""
SELECT p.id FROM posthog_person p
JOIN {VICTIMS_TABLE}_batch v ON v.team_id = p.team_id AND v.id = p.id
@@ -439,10 +512,6 @@ UNION ALL
SELECT 'cohortpeople', cp.id, cp.person_id, cp.cohort_id::text, NULL
FROM posthog_cohortpeople cp
JOIN {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
@@ -452,16 +521,6 @@ DELETE FROM posthog_cohortpeople cp
USING {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"""
@@ -494,34 +553,56 @@ WHERE pdi.team_id = %(team)s
"""
-# Every (table, privilege) pair the command exercises. Probed up front so a missing
-# grant aborts cleanly before any work, instead of surfacing as a raw permission
-# error mid-CTE (lifecycle_op_person in production is owner-only, which is exactly
-# how such a gap presents).
-REQUIRED_PRIVILEGES = (
+# Probed up front so a missing grant aborts before any work rather than surfacing as a
+# raw permission error mid-CTE. Scoped by mode: demanding DELETE for a read-only census
+# would block classify and verify on grants they never exercise.
+READ_PRIVILEGES = (
("posthog_person", "SELECT"),
- ("posthog_person", "DELETE"),
("posthog_persondistinctid", "SELECT"),
("posthog_featureflaghashkeyoverride", "SELECT"),
("posthog_cohortpeople", "SELECT"),
+)
+# posthog_featureflaghashkeyoverride needs no DELETE: its rows go via the FK's ON DELETE
+# CASCADE, and Postgres runs referential actions as the referencing table's owner.
+WRITE_PRIVILEGES = (
+ *READ_PRIVILEGES,
+ ("posthog_person", "DELETE"),
("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.
+# Aurora cancels a long read-only query on a reader with 40001, or drops the session with
+# 57P01, when the reader has to catch up. statement_timeout = 0 does not prevent either.
+REPLICA_CONFLICT_SQLSTATES = frozenset({"40001", "57P01"})
+# Exponent base for the retry backoff. A module constant so tests can drive the retry path
+# without waiting on it.
+REPLICA_RETRY_BACKOFF_BASE_S = 2.0
+
+# Contention with live ingestion, not a defect: expiry means back off and take the batch
+# again. QueryCanceled here is always a server-side timeout, because psycopg converts an
+# operator interrupt into KeyboardInterrupt, which is a BaseException and passes through.
+WRITE_RETRY_ERRORS = (
+ psycopg.errors.LockNotAvailable,
+ psycopg.errors.QueryCanceled,
+ psycopg.errors.DeadlockDetected,
+)
-def _check_privileges(conn: psycopg.Connection) -> list[str]:
- missing = []
- with conn.cursor() as cur:
- for table, privilege in REQUIRED_PRIVILEGES:
- cur.execute("SELECT has_table_privilege(%s, %s)", (table, privilege))
- row = cur.fetchone()
- if not (row and row[0]):
- missing.append(f"{privilege} on {table}")
- return missing
+T = TypeVar("T")
+
+
+def _check_privileges(conn: psycopg.Connection, required: tuple[tuple[str, str], ...]) -> list[str]:
+ values = ", ".join(["(%s, %s)"] * len(required))
+ sql = f"SELECT t.tbl, t.priv, has_table_privilege(t.tbl::text, t.priv::text) FROM (VALUES {values}) AS t(tbl, priv)"
+ params = [value for pair in required for value in pair]
+ try:
+ with conn.cursor() as cur:
+ cur.execute(sql, params)
+ rows = cur.fetchall()
+ except psycopg.errors.UndefinedTable as exc:
+ raise CommandError(
+ f"a table this command needs is missing from the persons database: {exc}. "
+ "Check that rust/persons_migrations has been applied here."
+ ) from exc
+ return [f"{priv} on {tbl}" for tbl, priv, granted in rows if not granted]
def _scalar(conn: psycopg.Connection, sql: str, params: dict | None = None) -> int:
@@ -531,15 +612,110 @@ def _scalar(conn: psycopg.Connection, sql: str, params: dict | None = None) -> i
return int(row[0]) if row else 0
+@frozen
+class GateViolations:
+ """What each safety gate objects to in this batch. All zero means safe to delete."""
+
+ reachable_victims: int
+ groups_left_empty: int
+ groups_losing_reachable_row: int
+
+
+def _gates(conn: psycopg.Connection) -> GateViolations:
+ """A missing row raises rather than reading as zero, because zero means "safe to delete"."""
+ with conn.cursor() as cur:
+ cur.execute(GATES_SQL)
+ row = cur.fetchone()
+ if row is None:
+ raise CommandError("gate query returned no row; refusing to delete")
+ return GateViolations(
+ reachable_victims=int(row[0]),
+ groups_left_empty=int(row[1]),
+ groups_losing_reachable_row=int(row[2]),
+ )
+
+
+def _verify_failures(*, resolvable: int, orphans: int, require_no_orphans: bool) -> list[str]:
+ """What makes a team fail the gate.
+
+ Orphaned mappings are reported but do not gate by default: repair can neither create one
+ (a victim needs zero distinct IDs, and the FK is NO ACTION) nor remove one, since the
+ command holds no DELETE grant on posthog_persondistinctid. Failing on them would block
+ the rollout on damage this command cannot fix.
+ """
+ failures = []
+ if resolvable:
+ failures.append(f"{resolvable} resolvable duplicate group(s)")
+ if orphans and require_no_orphans:
+ failures.append(f"{orphans} orphaned distinct id(s)")
+ return failures
+
+
+def _rollback_quietly(conn: psycopg.Connection) -> None:
+ try:
+ with conn.cursor() as cur:
+ cur.execute("ROLLBACK")
+ except psycopg.Error:
+ pass
+
+
+def _is_replica(conn: psycopg.Connection) -> bool | None:
+ """None when the platform will not answer.
+
+ Aurora documents aurora_replica_status() as its own way to tell a reader from a writer
+ and says nothing about pg_is_in_recovery(), so treat the answer as advisory. Nothing
+ load-bearing may depend on it: a statement whose only consumer is a log field must not
+ be able to end a run.
+ """
+ try:
+ return bool(_scalar(conn, "SELECT CASE WHEN pg_is_in_recovery() THEN 1 ELSE 0 END"))
+ except psycopg.Error as exc:
+ logger.warning("persons_dedup.recovery_probe_unavailable", sqlstate=exc.sqlstate, error=str(exc))
+ return None
+
+
+def _retry_replica_conflict(conn: psycopg.Connection, step: str, run: Callable[[], T], *, attempts: int = 3) -> T:
+ """Retry a read that a replica cancelled to resolve a replication conflict.
+
+ The failed statement leaves the transaction aborted, so roll back before retrying or the
+ next BEGIN fails with 25P02.
+ """
+ for attempt in range(1, attempts + 1):
+ try:
+ return run()
+ except psycopg.Error as exc:
+ if exc.sqlstate not in REPLICA_CONFLICT_SQLSTATES or attempt == attempts:
+ raise
+ _rollback_quietly(conn)
+ logger.warning("persons_dedup.replica_conflict_retry", step=step, attempt=attempt, sqlstate=exc.sqlstate)
+ time.sleep(min(30.0, REPLICA_RETRY_BACKOFF_BASE_S**attempt))
+ raise AssertionError("unreachable")
+
+
+@contextmanager
+def _step(name: str, **fields: Any) -> Iterator[None]:
+ """Bracket a statement that can run for many minutes.
+
+ Without a start line a slow scan and a hung one look identical from the terminal. The
+ backend pid is here so that after an interrupt the operator can confirm in
+ pg_stat_activity that the query really stopped: psycopg cancels server-side, but it
+ opens a fresh connection to do so and gives up after five seconds.
+ """
+ logger.info("persons_dedup.step_started", step=name, **fields)
+ started = time.monotonic()
+ try:
+ yield
+ finally:
+ logger.info("persons_dedup.step_finished", step=name, elapsed_s=round(time.monotonic() - started, 1), **fields)
+
+
def _check_session_stability(conn: psycopg.Connection) -> None:
"""Abort if the connection does not behave like one stable backend session.
- The US census run proved this failure mode is real: queries were canceled at the
- server's 30-minute statement_timeout even though the session had SET it to 0,
- which is the signature of a pooler (pgbouncer transaction mode, proxy multiplexing)
- routing consecutive statements to different backends. On such a connection this
- command is unusable -- its temp tables and session settings silently vanish between
- statements. Detect it up front instead of failing intermittently mid-run.
+ A pooler in transaction mode routes consecutive statements to different backends, which
+ silently discards this command's temp tables and session settings. The signature is a
+ statement canceled at the server's default statement_timeout despite the session having set
+ it to 0. Detect it up front instead of failing intermittently mid-run.
"""
pids = set()
for _ in range(3):
@@ -559,6 +735,10 @@ def _check_session_stability(conn: psycopg.Connection) -> None:
)
+# Pure reads: no --apply, and the operator picks the endpoint with --reader/--writer.
+READ_MODES = ("classify", "verify")
+
+
class Command(BaseCommand):
help = "Resolve duplicate (team_id, uuid) rows in posthog_person. Dry run unless --apply."
@@ -569,7 +749,12 @@ class Command(BaseCommand):
parser.add_argument(
"--writer",
action="store_true",
- help="read from the primary instead of the reader replica (classify/verify only)",
+ help="classify/verify: read from the primary (verify's default)",
+ )
+ parser.add_argument(
+ "--reader",
+ action="store_true",
+ help="classify/verify: read from the reader replica (classify's default)",
)
parser.add_argument("--batch-size", type=int, default=500)
parser.add_argument("--outdir", default="persons_dedup_backups")
@@ -579,18 +764,62 @@ class Command(BaseCommand):
default=200,
help="pause between batches so writers blocked on our row locks drain (0 disables)",
)
+ parser.add_argument(
+ "--lock-timeout-ms",
+ type=int,
+ default=2000,
+ help="cap on waiting for a victim's row lock; 0 waits forever and blocks ingestion for as long",
+ )
+ parser.add_argument(
+ "--txn-statement-timeout-ms",
+ type=int,
+ default=300_000,
+ help="cap on each statement inside the delete transaction; 0 holds row locks for as long as it takes",
+ )
+ parser.add_argument(
+ "--max-lock-retries",
+ type=int,
+ default=100,
+ help="give up after this many batches lost to lock contention",
+ )
+ parser.add_argument(
+ "--resume-from",
+ help="skip staging and load the victims still to delete from a checkpoint file",
+ )
+ parser.add_argument(
+ "--checkpoint-every",
+ type=int,
+ default=25,
+ help="rewrite the checkpoint of victims still to delete every N batches (0 disables)",
+ )
+ parser.add_argument(
+ "--census-slices",
+ type=int,
+ default=1,
+ help=(
+ "split the duplicate census into this many uuid slices to bound how long any one "
+ "snapshot is held. About the same total work as 1; opt-in only because it has not "
+ "run against production yet"
+ ),
+ )
+ parser.add_argument(
+ "--require-no-orphans",
+ action="store_true",
+ help=(
+ "verify: also check for orphaned distinct IDs and fail on them. Off by default "
+ "because repair cannot create or remove one and the scan costs several times the "
+ "rest of verify"
+ ),
+ )
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.
+ posthog.persons_db falls back to a localhost URL built from PG* when the persons URL is
+ unset, and on a deployed pod PG* usually point at the main cluster. That would turn a
+ destructive run against the persons database into one against whatever
+ `posthog_persons` resolves to there. Host and dbname are logged because that is what
+ tells the operator the toolbox is pointed at persons and not the main cluster.
"""
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"):
@@ -616,11 +845,14 @@ class Command(BaseCommand):
mode: str = options["mode"]
apply_changes: bool = options["apply"]
- if mode in ("classify", "verify") and apply_changes:
+ if mode in READ_MODES and apply_changes:
raise CommandError(f"--apply is meaningless for --mode {mode}")
- if mode not in ("classify", "verify") and options["writer"]:
- raise CommandError(f"--writer is meaningless for --mode {mode}; it always uses the writer")
+ if options["reader"] and options["writer"]:
+ raise CommandError("--reader and --writer are mutually exclusive")
+
+ if mode not in READ_MODES and (options["reader"] or options["writer"]):
+ raise CommandError(f"--reader/--writer are meaningless for --mode {mode}; it always uses the writer")
# LIMIT 0 stages nothing and the loop exits reporting success, which reads as
# "nothing to do" on a team that still has duplicates. A negative value reaches
@@ -628,48 +860,88 @@ class Command(BaseCommand):
if options["batch_size"] < 1:
raise CommandError("--batch-size must be at least 1")
- # classify and verify are pure reads whose scans can run for minutes on large
- # teams, so they default to the reader replica to keep that load off the
- # primary. Replica staleness is bounded to replay lag (logged below) and is not
- # 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"]
+ for flag in ("lock_timeout_ms", "txn_statement_timeout_ms", "max_lock_retries"):
+ if options[flag] < 0:
+ raise CommandError(f"--{flag.replace('_', '-')} cannot be negative")
+
+ if options["census_slices"] < 1:
+ raise CommandError("--census-slices must be at least 1")
+
+ if options["checkpoint_every"] < 0:
+ raise CommandError("--checkpoint-every cannot be negative")
+
+ if options["resume_from"] and mode in READ_MODES:
+ raise CommandError(f"--resume-from is meaningless for --mode {mode}; it stages nothing")
+
+ # Both read modes default to the replica. The census scans the team's whole slice of
+ # posthog_person, and holding that snapshot on the primary pins the xmin horizon and
+ # delays vacuum on the hottest table in ingestion. Staleness is one-directional and
+ # therefore safe: a replica lags behind deletes, so it can only over-report
+ # duplicates, never miss them.
+ reader_configured = bool(os.getenv("PERSONS_DB_READER_URL"))
+ if mode not in READ_MODES or options["writer"]:
+ use_writer = True
+ elif options["reader"]:
+ if not reader_configured:
+ raise CommandError(
+ "--reader needs PERSONS_DB_READER_URL to be set. Without it the persons-DB "
+ "URL falls back to the writer, so this read would run on the primary. Set "
+ "the variable, or pass --writer if the primary is what you want."
+ )
+ use_writer = False
+ else:
+ use_writer = not reader_configured
+ if use_writer:
+ logger.warning("persons_dedup.no_reader_configured", mode=mode)
self._assert_explicit_target(use_writer)
with persons_db_connection(writer=use_writer, autocommit=True) as conn:
with conn.cursor() as cur:
cur.execute("SET statement_timeout = 0")
- missing = _check_privileges(conn)
+ backend_pid = _scalar(conn, "SELECT pg_backend_pid()")
+ on_replica = _is_replica(conn)
+
+ missing = _check_privileges(conn, READ_PRIVILEGES if mode in READ_MODES else WRITE_PRIVILEGES)
if missing:
raise CommandError(
"operator role lacks required grants: " + ", ".join(missing) + ". "
"Ask for the grants before running; nothing was changed."
)
- if mode in ("classify", "verify"):
- # A verify run seconds after a repair can see the pre-repair state on a
- # lagging replica; surfacing the lag lets the operator tell a stale read
- # from a real failure (or rerun with --writer).
- if not use_writer and _scalar(conn, "SELECT CASE WHEN pg_is_in_recovery() THEN 1 ELSE 0 END"):
- lag_seconds = _scalar(
- conn,
- "SELECT COALESCE(EXTRACT(EPOCH FROM now() - pg_last_xact_replay_timestamp()), 0)::bigint",
- )
- logger.info("persons_dedup.reading_from_replica", team_id=team, replay_lag_seconds=lag_seconds)
+ if mode in READ_MODES:
+ # Warn rather than abort: single-node deployments point both URLs at the same
+ # database, so this is normal there and the read is harmless either way. The
+ # operator still needs to know the load did not go where they asked.
+ if options["reader"] and on_replica is False:
+ logger.warning("persons_dedup.reader_is_the_primary", mode=mode)
+ if on_replica:
+ logger.info("persons_dedup.reading_from_replica", team_id=team)
if mode == "classify":
- self._classify(conn, team, Path(options["outdir"]))
+ self._classify(
+ conn, team, Path(options["outdir"]), pid=backend_pid, slices=options["census_slices"]
+ )
else:
- self._verify(conn, team)
+ self._verify(
+ conn,
+ team,
+ pid=backend_pid,
+ slices=options["census_slices"],
+ from_replica=bool(on_replica),
+ require_no_orphans=options["require_no_orphans"],
+ )
return
- if _scalar(conn, "SELECT CASE WHEN pg_is_in_recovery() THEN 1 ELSE 0 END"):
+ # A None probe means the platform would not say. Carry on rather than abort: a
+ # real replica rejects the DELETE as a read-only transaction before anything is
+ # removed, so that error is the actual backstop.
+ if on_replica:
raise CommandError("connected to a replica; this mode needs the writer")
_check_session_stability(conn)
- stage_sql = STAGE_UNREFERENCED_SQL if mode == "delete-unreferenced" else STAGE_UNREACHABLE_SQL
- self._run(conn, team, stage_sql, options, apply_changes=apply_changes, mode=mode)
+ stage_tail = _STAGE_UNREFERENCED_TAIL if mode == "delete-unreferenced" else _STAGE_UNREACHABLE_TAIL
+ self._run(conn, team, stage_tail, options, apply_changes=apply_changes, mode=mode, pid=backend_pid)
BLOCKED_COLUMNS = (
"uuid",
@@ -678,33 +950,20 @@ class Command(BaseCommand):
"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.
+ def _append_blocked(self, team: int, path: Path, rows: list, tally: dict[str, int]) -> None:
+ """Append one record per group this command refuses, and count it by reason.
- 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.
+ 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] = {}
+ path.parent.mkdir(parents=True, exist_ok=True)
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:
@@ -713,72 +972,82 @@ class Command(BaseCommand):
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
- # default despite SET statement_timeout = 0).
- with conn.cursor() as cur:
- cur.execute("BEGIN")
- cur.execute("SET LOCAL statement_timeout = 0")
- cur.execute(CLASSIFY_SQL, {"team": team})
- row = cur.fetchone()
- cur.execute("COMMIT")
- assert row is not None
- groups, orphaned, one_ref, needs_merge, multi_did, blocked, tombstoned, dids, cohort, ff, recon = (
- int(v) for v in row
- )
+
+ def _classify(self, conn: psycopg.Connection, team: int, outdir: Path, *, pid: int, slices: int) -> None:
+ counts = dict.fromkeys(CLASSIFY_COLUMNS, 0)
+ tally: dict[str, int] = {}
+ stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
+ blocked_path = outdir / f"blocked_team_{team}_{stamp}.jsonl"
+
+ with _step("classify", team_id=team, pid=pid, slices=slices):
+ for params in _census_pages(conn, team, slices, pid=pid):
+ paged = "uuids" in params
+ rows = _read_in_txn(conn, _sql(CLASSIFY_TAIL, paged=paged), params, step="classify")
+ assert rows, "the classify aggregate always returns exactly one row"
+ page = dict(zip(CLASSIFY_COLUMNS, (int(v) for v in rows[0])))
+ for name, value in page.items():
+ counts[name] += value
+ # A count is not actionable. Resolving a refused group needs the rows it holds,
+ # which of them are reachable, and what hangs off them, so the detail is written
+ # per slice rather than re-derived later.
+ if page["blocked_groups"]:
+ detail = _read_in_txn(conn, _sql(BLOCKED_DETAIL_TAIL, paged=paged), params, step="blocked_detail")
+ self._append_blocked(team, blocked_path, detail, tally)
+
logger.info(
"persons_dedup.classify",
team_id=team,
- dup_groups=groups,
- all_orphaned=orphaned,
- 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,
- reconciliation_rows=recon,
+ resolvable_groups=counts["dup_groups"] - counts["blocked_groups"],
+ **counts,
)
- if multi_did:
- 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)
+ if counts["groups_with_distinct_ids_on_multiple_rows"]:
+ logger.warning(
+ "persons_dedup.needs_real_merge",
+ team_id=team,
+ groups=counts["groups_with_distinct_ids_on_multiple_rows"],
+ )
+ if counts["tombstoned_members"]:
+ logger.warning(
+ "persons_dedup.tombstoned_members_skipped", team_id=team, members=counts["tombstoned_members"]
+ )
+ if counts["blocked_groups"]:
+ logger.info("persons_dedup.blocked_detail_written", team_id=team, path=str(blocked_path))
+ logger.warning("persons_dedup.blocked_by_reason", team_id=team, groups=counts["blocked_groups"], **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")
- # 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(blocked_row[0]) if blocked_row else 0
- blocked = int(blocked_row[1]) if blocked_row else 0
- orphans = int(orphans_row[0]) if orphans_row else 0
+ def _verify(
+ self,
+ conn: psycopg.Connection,
+ team: int,
+ *,
+ pid: int,
+ slices: int,
+ from_replica: bool,
+ require_no_orphans: bool,
+ ) -> None:
+ dups = 0
+ blocked = 0
+ # Both counts come from one statement per slice on purpose. Read committed takes a fresh
+ # snapshot per statement, so counting the groups and the blocked subset separately would
+ # let a write land between them, and resolvable is their difference, so it could come
+ # out negative.
+ with _step("verify_groups", team_id=team, pid=pid, slices=slices):
+ for params in _census_pages(conn, team, slices, pid=pid):
+ rows = _read_in_txn(
+ conn, _sql(COUNT_BLOCKED_TAIL, paged="uuids" in params), params, step="verify_groups"
+ )
+ dups += int(rows[0][0])
+ blocked += int(rows[0][1])
+
+ # Only when asked. This walks the team's whole distinct-id slice and anti-joins it
+ # against every person row, which on prod-US costs several times the duplicate census and
+ # sorts tens of millions of rows. It stopped gating the rollout, so paying for it on every
+ # verify buys nothing. Its own transaction because it is an independent invariant.
+ orphans = 0
+ if require_no_orphans:
+ with _step("verify_orphans", team_id=team, pid=pid):
+ orphans_rows = _read_in_txn(conn, VERIFY_ORPHANS_SQL, {"team": team}, step="verify_orphans")
+ orphans = int(orphans_rows[0][0]) if orphans_rows else 0
resolvable = dups - blocked
logger.info(
"persons_dedup.verify",
@@ -786,17 +1055,21 @@ class Command(BaseCommand):
duplicate_groups=dups,
blocked_groups=blocked,
resolvable_groups=resolvable,
- orphaned_distinct_ids=orphans,
+ orphaned_distinct_ids=orphans if require_no_orphans else None,
)
- # 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"
- )
+ # The gate is "nothing repair could still resolve". The merge-required remainder is
+ # expected and is separate work, so leaving only those means this command is done.
+ failures = _verify_failures(resolvable=resolvable, orphans=orphans, require_no_orphans=require_no_orphans)
+ if failures:
+ message = f"team {team}: {' and '.join(failures)} remain; {blocked} group(s) need a real merge."
+ if from_replica:
+ message += (
+ " This read came from the reader replica, which may not have applied the "
+ "most recent deletes yet. Rerun to confirm, or pass --writer to read the primary."
+ )
+ raise CommandError(message)
+ if orphans:
+ logger.warning("persons_dedup.orphaned_distinct_ids", team_id=team, orphans=orphans)
if blocked:
logger.warning("persons_dedup.blocked_remainder", team_id=team, groups=blocked)
@@ -804,12 +1077,15 @@ class Command(BaseCommand):
self,
conn: psycopg.Connection,
team: int,
- stage_sql: str,
+ stage_tail: str,
options: dict,
*,
apply_changes: bool,
mode: str,
+ pid: int,
) -> None:
+ slices: int = options["census_slices"]
+ resume_from = Path(options["resume_from"]) if options["resume_from"] else None
if not apply_changes:
logger.info("persons_dedup.dry_run", team_id=team, mode=mode)
@@ -824,14 +1100,21 @@ class Command(BaseCommand):
)
cur.execute(f"TRUNCATE {VICTIMS_TABLE}")
cur.execute(f"TRUNCATE {VICTIMS_TABLE}_batch")
- # The staging scan reads every duplicate group for the team and can run for
- # minutes on the large ones; SET LOCAL keeps its timeout immunity
- # transaction-scoped rather than trusting the session-level SET.
- cur.execute("BEGIN")
- cur.execute("SET LOCAL statement_timeout = 0")
- cur.execute(stage_sql, {"team": team})
- staged = cur.rowcount
- cur.execute("COMMIT")
+ if resume_from:
+ staged = self._load_checkpoint(conn, team, resume_from)
+ logger.info("persons_dedup.resumed", team_id=team, victims=staged, source=str(resume_from))
+ else:
+ # One transaction per slice. Unsliced, this is the longest-held snapshot in the
+ # write path, and it runs on the primary, where it pins the xmin horizon for the
+ # whole census.
+ staged = 0
+ with _step("stage", team_id=team, mode=mode, pid=pid, slices=slices):
+ for params in _census_pages(conn, team, slices, pid=pid):
+ cur.execute("BEGIN")
+ cur.execute("SET LOCAL statement_timeout = 0")
+ cur.execute(_sql(stage_tail, paged="uuids" in params), params)
+ staged += cur.rowcount
+ cur.execute("COMMIT")
# Temp tables get no autovacuum or autoanalyze. Without this index every
# TAKE_BATCH full-scans and sorts the victims table, and the retired rows
# only go dead, so the scan never gets cheaper as the run progresses. Built
@@ -847,11 +1130,16 @@ class Command(BaseCommand):
outdir.mkdir(parents=True, exist_ok=True)
stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
backup_path = outdir / f"deleted_team_{team}_{mode}_{stamp}.jsonl"
+ # Stable name, rewritten in place, because only the newest one is worth resuming from.
+ checkpoint_path = outdir / f"remaining_team_{team}_{mode}.csv"
+ if apply_changes:
+ self._write_checkpoint(conn, checkpoint_path, team=team, staged=staged)
deleted = 0
checked = 0
batches = 0
pruned_total = 0
+ lock_retries = 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.
@@ -869,15 +1157,37 @@ class Command(BaseCommand):
break
batches += 1
- reachable = _scalar(conn, GATE_REACHABLE_SQL)
- no_survivor = _scalar(conn, GATE_NO_SURVIVOR_SQL)
- wrong_survivor = _scalar(conn, GATE_SURVIVOR_REACHABLE_SQL)
- if reachable or no_survivor or wrong_survivor:
+ gates = _gates(conn)
+ # Not prunable and never a race: staging cannot produce this, so reaching it means
+ # the survivor rule and the reachability rule disagree for this data.
+ if gates.groups_losing_reachable_row:
raise CommandError(
- f"gate failed for team {team}: {reachable} victim(s) are reachable, "
- f"{no_survivor} group(s) would be emptied, {wrong_survivor} group(s) would "
- f"lose their only reachable row. Nothing deleted."
+ f"team {team}: {gates.groups_losing_reachable_row} group(s) would lose their "
+ f"only reachable row. The survivor rule is wrong for this data. {deleted} "
+ f"row(s) already deleted."
+ )
+ if gates.reachable_victims or gates.groups_left_empty:
+ # A writer got here first, or the staged set came from a checkpoint written before
+ # one did. Drop those victims rather than the run, the same way the
+ # in-transaction gate does.
+ logger.warning(
+ "persons_dedup.batch_raced",
+ team_id=team,
+ batch=batches,
+ gate="pre-flight",
+ reachable=gates.reachable_victims,
+ would_empty=gates.groups_left_empty,
+ )
+ pruned_total = self._absorb_raced_batch(
+ conn,
+ team=team,
+ deleted=deleted,
+ pruned_total=pruned_total,
+ prune_budget=prune_budget,
+ detail=f"pre-flight gate failed for team {team} (reachable "
+ f"{gates.reachable_victims}, would empty {gates.groups_left_empty})",
)
+ continue
if not apply_changes:
# Retire the batch and continue rather than returning: a dry run that stops
@@ -888,98 +1198,109 @@ class Command(BaseCommand):
cur.execute(RETIRE_BATCH_SQL)
continue
- with conn.cursor() as cur:
- cur.execute("BEGIN")
- cur.execute("SET LOCAL lock_timeout = '2s'")
- # The session runs with statement_timeout = 0 for the big staging scan;
- # inside the write transaction we hold FOR UPDATE row locks that live
- # ingestion can block on (updatePersonsBatch matches persons by
- # (team_id, uuid), which duplicates share), so every statement here
- # must be bounded.
- cur.execute("SET LOCAL statement_timeout = '5min'")
- cur.execute(LOCK_VICTIMS_SQL, {"team": team})
- 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()
- 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"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,
+ batch_started = time.monotonic()
+ try:
+ with conn.cursor() as cur:
+ cur.execute("BEGIN")
+ # The session runs unbounded for the staging census, but inside this
+ # transaction we hold FOR UPDATE locks that live ingestion blocks on
+ # (updatePersonsBatch matches persons by (team_id, uuid), which duplicates
+ # share), so every statement here is bounded. set_config(..., true) is
+ # SET LOCAL with a bound parameter. statement_timeout also covers COMMIT,
+ # where the feature-flag override cascade runs when its FK is deferred.
+ cur.execute("SELECT set_config('lock_timeout', %s, true)", (f"{options['lock_timeout_ms']}ms",))
+ cur.execute(
+ "SELECT set_config('statement_timeout', %s, true)",
+ (f"{options['txn_statement_timeout_ms']}ms",),
)
- 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:
+ cur.execute(LOCK_VICTIMS_SQL, {"team": team})
+ 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.
+ now = _gates(conn)
+ # 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.groups_losing_reachable_row:
+ cur.execute("ROLLBACK")
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"
+ f"team {team}: {now.groups_losing_reachable_row} group(s) would lose "
+ f"their only reachable row. This is not a concurrent-writer race; the "
+ f"survivor rule is wrong for this data. {deleted} row(s) already deleted."
+ )
+ if locked != in_batch or now.reachable_victims or now.groups_left_empty:
+ cur.execute("ROLLBACK")
+ logger.warning(
+ "persons_dedup.batch_raced",
+ team_id=team,
+ batch=batches,
+ gate="in-transaction",
+ locked=locked,
+ staged=in_batch,
+ reachable=now.reachable_victims,
+ would_empty=now.groups_left_empty,
)
- if pruned_total > prune_budget:
+ pruned_total = self._absorb_raced_batch(
+ conn,
+ team=team,
+ deleted=deleted,
+ pruned_total=pruned_total,
+ prune_budget=prune_budget,
+ detail=f"in-transaction gate failed for team {team} (locked "
+ f"{locked}/{in_batch}, reachable {now.reachable_victims}, would empty "
+ f"{now.groups_left_empty})",
+ )
+ continue
+
+ # Back up after the lock, not before it. An insert into
+ # posthog_featureflaghashkeyoverride takes FOR KEY SHARE on the parent
+ # person row, so the FOR UPDATE above blocks one; reading dependents
+ # earlier would let a row appear afterwards, get cascaded, and never
+ # reach the backup. Still written and fsync'd before the delete, so a
+ # rollback leaves a superset rather than a gap.
+ backed_up = self._backup(conn, team, backup_path)
+ if backed_up != in_batch:
+ cur.execute("ROLLBACK")
+ raise CommandError(f"backed up {backed_up} row(s) but staged {in_batch}; rolled back")
+
+ cur.execute(DELETE_COHORT_SQL)
+ cur.execute(DELETE_PERSONS_SQL, {"team": team})
+ removed = cur.rowcount
+ if removed != in_batch:
+ cur.execute("ROLLBACK")
+ raise CommandError(f"deleted {removed} but staged {in_batch}; rolled back")
+
+ # posthog_cohortpeople has no foreign key, so the row lock above cannot
+ # block an insert into it. A cohort recalculation could have added a row
+ # after DELETE_COHORT_SQL ran, which would survive as an orphan.
+ cur.execute(CHECK_COHORT_ORPHANS_SQL)
+ orphan_row = cur.fetchone()
+ if orphan_row and orphan_row[0]:
+ cur.execute("ROLLBACK")
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"
+ f"{orphan_row[0]} cohort row(s) appeared for a victim mid-transaction; rolled back"
)
- continue
-
- # Back up after the lock, not before it. An insert into
- # posthog_featureflaghashkeyoverride takes FOR KEY SHARE on the parent
- # person row, so the FOR UPDATE above blocks one; reading dependents
- # earlier would let a row appear afterwards, get cascaded, and never
- # reach the backup. Still written and fsync'd before the delete, so a
- # rollback leaves a superset rather than a gap.
- backed_up = self._backup(conn, team, backup_path)
- if backed_up != in_batch:
- cur.execute("ROLLBACK")
- 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.rowcount
- if removed != in_batch:
- cur.execute("ROLLBACK")
- raise CommandError(f"deleted {removed} but staged {in_batch}; rolled back")
-
- # posthog_cohortpeople has no foreign key, so the row lock above cannot
- # block an insert into it. A cohort recalculation could have added a row
- # after DELETE_COHORT_SQL ran, which would survive as an orphan.
- cur.execute(CHECK_COHORT_ORPHANS_SQL)
- orphan_row = cur.fetchone()
- if orphan_row and orphan_row[0]:
- cur.execute("ROLLBACK")
+ cur.execute("COMMIT")
+ except WRITE_RETRY_ERRORS as exc:
+ # Contention with live ingestion, not a defect. The batch table still holds
+ # the same rows, so taking it again after a pause is idempotent; aborting
+ # here would throw away a staging census that costs minutes.
+ _rollback_quietly(conn)
+ lock_retries += 1
+ logger.warning(
+ "persons_dedup.batch_contended",
+ team_id=team,
+ batch=batches,
+ sqlstate=exc.sqlstate,
+ retries=lock_retries,
+ )
+ if lock_retries > options["max_lock_retries"]:
raise CommandError(
- f"{orphan_row[0]} cohort row(s) appeared for a victim mid-transaction; rolled back"
- )
- cur.execute("COMMIT")
+ f"team {team}: gave up after {lock_retries} batch(es) lost to lock "
+ f"contention, last {exc.sqlstate}. {deleted} row(s) were deleted. "
+ f"Rerun to resume, or raise --max-lock-retries."
+ ) from exc
+ time.sleep(max(options["sleep_ms"], 250) / 1000.0)
+ continue
with conn.cursor() as cur:
cur.execute(SWEEP_COHORT_ORPHANS_SQL)
@@ -995,9 +1316,18 @@ class Command(BaseCommand):
with conn.cursor() as cur:
cur.execute(RETIRE_BATCH_SQL)
deleted += removed
+ if options["checkpoint_every"] and batches % options["checkpoint_every"] == 0:
+ self._write_checkpoint(conn, checkpoint_path, team=team, staged=staged - deleted)
if options["sleep_ms"] > 0:
time.sleep(options["sleep_ms"] / 1000.0)
- logger.info("persons_dedup.batch_done", team_id=team, batch=batches, deleted=removed, total=deleted)
+ logger.info(
+ "persons_dedup.batch_done",
+ team_id=team,
+ batch=batches,
+ deleted=removed,
+ total=deleted,
+ elapsed_s=round(time.monotonic() - batch_started, 2),
+ )
if not apply_changes:
logger.info(
@@ -1012,9 +1342,89 @@ class Command(BaseCommand):
batches=batches,
deleted=deleted,
pruned=pruned_total,
+ lock_retries=lock_retries,
backup=str(backup_path),
)
+ def _write_checkpoint(self, conn: psycopg.Connection, path: Path, *, team: int, staged: int) -> None:
+ """Record the victims still to delete, so an interrupted run resumes without re-staging.
+
+ Written to a temporary file and renamed, so a crash mid-write cannot leave a truncated
+ checkpoint behind. Resuming from a stale one is safe because staging is not
+ authoritative: the gates and the prune re-verify every victim per batch, so a row that
+ has since been deleted or become reachable is dropped rather than acted on.
+ """
+ partial = path.with_suffix(path.suffix + ".partial")
+ fd = os.open(str(partial), os.O_CREAT | os.O_WRONLY | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
+ with os.fdopen(fd, "wb") as fh:
+ with (
+ conn.cursor() as cur,
+ cur.copy(
+ f"COPY (SELECT team_id, id, uuid FROM {VICTIMS_TABLE} ORDER BY uuid, id) TO STDOUT (FORMAT csv)"
+ ) as copy,
+ ):
+ for block in copy:
+ fh.write(block)
+ fh.flush()
+ os.fsync(fh.fileno())
+ os.replace(partial, path)
+ logger.info("persons_dedup.checkpoint", team_id=team, remaining=staged, path=str(path))
+
+ def _load_checkpoint(self, conn: psycopg.Connection, team: int, path: Path) -> int:
+ """Refill the staged set from a checkpoint instead of re-running the census."""
+ with conn.cursor() as cur:
+ with (
+ open(path, "rb") as fh,
+ cur.copy(f"COPY {VICTIMS_TABLE} (team_id, id, uuid) FROM STDIN (FORMAT csv)") as copy,
+ ):
+ while block := fh.read(1 << 16):
+ copy.write(block)
+ # A checkpoint from another team would delete rows nobody asked about, and the gates
+ # would not catch it because they only ever look at the staged set.
+ foreign = _scalar(conn, f"SELECT count(*) FROM {VICTIMS_TABLE} WHERE team_id <> %(team)s", {"team": team})
+ if foreign:
+ raise CommandError(
+ f"{path} holds {foreign} victim(s) for a different team. Refusing to run: pass the "
+ f"checkpoint written for team {team}."
+ )
+ # Drop the ones a previous run already deleted. The batch gates would prune these anyway,
+ # but every prune counts against a budget meant for staging and the gate disagreeing, so a
+ # checkpoint written a few batches before the interruption could exhaust it on rows whose
+ # absence is expected.
+ with conn.cursor() as cur:
+ cur.execute(RECONCILE_CHECKPOINT_SQL, {"team": team})
+ gone = cur.rowcount
+ if gone:
+ logger.info("persons_dedup.checkpoint_reconciled", team_id=team, already_deleted=gone)
+ return _scalar(conn, f"SELECT count(*) FROM {VICTIMS_TABLE}")
+
+ def _absorb_raced_batch(
+ self,
+ conn: psycopg.Connection,
+ *,
+ team: int,
+ deleted: int,
+ pruned_total: int,
+ prune_budget: int,
+ detail: str,
+ ) -> int:
+ """Drop the staged victims a writer made undeletable, and return the new pruned total.
+
+ Nothing prunable means the gate failed for a reason this does not explain, and retrying
+ would take the same batch forever.
+ """
+ pruned = self._prune_batch(conn)
+ pruned_total += pruned
+ if pruned == 0:
+ raise CommandError(f"{detail} and no victim was prunable; nothing further deleted")
+ if pruned_total > prune_budget:
+ raise CommandError(
+ f"team {team}: {pruned_total} victim(s) became unresolvable mid-run, over the "
+ f"{prune_budget} budget; staging and the gate disagree. {deleted} row(s) already "
+ f"deleted, rerun to resume"
+ )
+ return pruned_total
+
def _prune_batch(self, conn: psycopg.Connection) -> int:
with conn.cursor() as cur:
cur.execute(PRUNE_BATCH_SQL)
diff --git a/posthog/management/commands/test/test_persons_dedup.py b/posthog/management/commands/test/test_persons_dedup.py
index e8289d6af27e..6717ad461dbb 100644
--- a/posthog/management/commands/test/test_persons_dedup.py
+++ b/posthog/management/commands/test/test_persons_dedup.py
@@ -82,7 +82,6 @@ def _cleanup(conn: psycopg.Connection) -> None:
(TEAM,),
)
cur.execute("DELETE FROM posthog_persondistinctid WHERE team_id = %s", (TEAM,))
- cur.execute("DELETE FROM posthog_person_reconciliation_backup WHERE team_id = %s", (TEAM,))
cur.execute("DELETE FROM posthog_person WHERE team_id = %s", (TEAM,))
@@ -125,22 +124,23 @@ def _add_orphan_pair_ids(conn: psycopg.Connection, uuid: str, distinct_id: str)
# 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.
+# only a concurrent writer can make a staged victim undeletable.
@contextmanager
def _concurrent_write_before_delete(monkeypatch, action):
- real_scalar = persons_dedup_command._scalar
+ real_gates = persons_dedup_command._gates
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:
+ def gates_then_interfere(conn):
+ result = real_gates(conn)
+ # The pre-flight is the first gate call and the in-transaction re-check is the second,
+ # so firing after the first lands the write in the only window the gates can catch.
+ if not state["fired"]:
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)
+ monkeypatch.setattr(persons_dedup_command, "_gates", gates_then_interfere)
yield lambda: state["fired"]
@@ -188,14 +188,17 @@ def _orphaned_cohort_rows(conn: psycopg.Connection, cohort_id: int = 4242) -> in
)
-def _add_recon_backup_row(conn: psycopg.Connection, person_id: int, uuid: str) -> None:
+def _orphan_a_distinct_id(conn: psycopg.Connection, person_id: int) -> None:
+ # Production's foreign keys are NOT VALID, so orphaned mappings predate them and a normal
+ # insert cannot make one. session_replication_role = replica disables the FK triggers for this
+ # session, which deletes the person out from under its mapping without dropping all 64
+ # per-partition constraints. Needs a superuser, which the dev and CI Postgres role is.
with conn.cursor() as cur:
- cur.execute(
- "INSERT INTO posthog_person_reconciliation_backup "
- "(job_id, team_id, person_id, uuid, properties, is_identified, created_at, pending_operations) "
- "VALUES ('test-job', %s, %s, %s, '{}'::jsonb, false, now(), '{}'::jsonb)",
- (TEAM, person_id, uuid),
- )
+ cur.execute("SET session_replication_role = 'replica'")
+ try:
+ cur.execute("DELETE FROM posthog_person WHERE team_id = %s AND id = %s", (TEAM, person_id))
+ finally:
+ cur.execute("SET session_replication_role = 'origin'")
def _count(conn: psycopg.Connection, sql: str, params: tuple = ()) -> int:
@@ -546,36 +549,6 @@ class TestPersonsDedupRepair:
assert _persons(persons_conn) == 1
assert _cohort_rows(persons_conn) == 1
- 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")
- held = _add_person(persons_conn, uuid)
- _add_recon_backup_row(persons_conn, held, uuid)
-
- _run("repair", tmp_path, apply=True)
-
- 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
@@ -716,15 +689,13 @@ class TestPersonsDedupSurvivorSelection:
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.
+ def test_a_tombstoned_member_is_named_as_the_blocking_reason(self, persons_conn, tmp_path):
+ # A group whose only extra member is a tombstone is refused, and the reason has to name
+ # the tombstone so the follow-up work is not sent 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)
+ _add_person(persons_conn, uuid, is_deleted=True)
_run("classify", tmp_path)
@@ -733,7 +704,6 @@ class TestPersonsDedupSurvivorSelection:
]
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
@@ -753,6 +723,10 @@ class TestPersonsDedupSurvivorSelection:
assert records[0]["reason"] == "multiple_distinct_id_owners"
assert records[0]["live_owners"] == 2
assert records[0]["reachable_owners"] == 1
+ # Ordered by survivor rank, so the first id is the row the product can still resolve.
+ # A transposed FILTER or ORDER BY in the aggregate would point the merge at the wrong row.
+ assert records[0]["member_ids"] == [survivor, dead_owner]
+ assert records[0]["reachable_ids"] == [survivor]
# And the foreign key is why: the tombstoned mapping still references the row.
_run("repair", tmp_path, apply=True)
assert _persons(persons_conn) == 2
@@ -836,8 +810,7 @@ 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.
+ # probe fails mid-transaction on the first team whose data reaches it.
deleted_tables = set()
for name, sql in vars(persons_dedup_command).items():
if not name.startswith("DELETE_") or not isinstance(sql, str):
@@ -847,24 +820,35 @@ class TestPersonsDedupPrivilegePreflight:
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"}
+ probed = {t for t, p in persons_dedup_command.WRITE_PRIVILEGES if p == "DELETE"}
assert deleted_tables <= probed, f"deletes without a DELETE grant probe: {sorted(deleted_tables - probed)}"
+ def test_read_modes_do_not_demand_delete_grants(self):
+ # classify and verify delete nothing, so probing DELETE would block them on a
+ # read-only role for grants they never exercise.
+ assert {p for _, p in persons_dedup_command.READ_PRIVILEGES} == {"SELECT"}
+ assert set(persons_dedup_command.READ_PRIVILEGES) <= set(persons_dedup_command.WRITE_PRIVILEGES)
+
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
- # to the writer, so the routed kwarg is the only observable difference.
+ # Both read modes default to the replica so a multi-minute census never holds a snapshot
+ # on the primary. Silently moving either one back is the regression these guard against.
+ # Locally the reader URL falls back to the writer, so the routed kwarg is the only
+ # observable difference.
@pytest.mark.parametrize(
"mode,kwargs,expected_writer",
[
("classify", {}, False),
- ("verify", {}, False),
+ ("classify", {"reader": True}, False),
("classify", {"writer": True}, True),
+ ("verify", {}, False),
+ ("verify", {"writer": True}, True),
+ ("verify", {"reader": True}, False),
("repair", {"apply": True}, True),
+ ("delete-unreferenced", {"apply": True}, True),
],
)
- def test_read_modes_use_the_reader_unless_writer_is_forced(
+ def test_each_read_mode_honors_the_endpoint_the_operator_asks_for(
self, persons_conn, tmp_path, monkeypatch, mode, kwargs, expected_writer
):
requested = []
@@ -880,6 +864,444 @@ class TestPersonsDedupConnectionRouting:
assert requested == [expected_writer]
- def test_writer_flag_is_rejected_for_write_modes(self, persons_conn, tmp_path):
+ @pytest.mark.parametrize("mode", ["classify", "verify"])
+ def test_asking_for_both_endpoints_at_once_is_rejected(self, persons_conn, tmp_path, mode):
+ # Neither flag wins by precedence; the operator is told to pick one rather than
+ # finding out afterwards which endpoint actually served the answer.
+ with pytest.raises(CommandError, match="mutually exclusive"):
+ _run(mode, tmp_path, reader=True, writer=True)
+
+ @pytest.mark.parametrize("mode", ["repair", "delete-unreferenced"])
+ @pytest.mark.parametrize("flag", ["reader", "writer"])
+ def test_endpoint_flags_are_rejected_on_the_write_modes(self, persons_conn, tmp_path, mode, flag):
+ # A write mode has no endpoint choice. Accepting --reader would imply one exists,
+ # and accepting --writer would imply the default was something else.
with pytest.raises(CommandError, match="always uses the writer"):
- _run("repair", tmp_path, writer=True)
+ _run(mode, tmp_path, apply=True, **{flag: True})
+
+ def test_a_replica_read_says_so_in_the_log(self, persons_conn, tmp_path, monkeypatch):
+ # The operator needs to know which endpoint answered when two runs disagree. Local
+ # Postgres is a primary, so pg_is_in_recovery() is stubbed to reach the branch.
+ real_scalar = persons_dedup_command._scalar
+
+ def in_recovery(conn, sql, params=None):
+ if "pg_is_in_recovery" in sql:
+ return 1
+ return real_scalar(conn, sql, params)
+
+ monkeypatch.setattr(persons_dedup_command, "_scalar", in_recovery)
+
+ with capture_logs() as logs:
+ _run("classify", tmp_path)
+
+ replica_lines = [entry for entry in logs if entry["event"] == "persons_dedup.reading_from_replica"]
+ assert replica_lines, "a replica read must be announced"
+ assert replica_lines[0]["team_id"] == TEAM
+
+ def test_a_primary_read_is_not_announced_as_a_replica_read(self, persons_conn, tmp_path):
+ with capture_logs() as logs:
+ _run("verify", tmp_path, writer=True)
+
+ assert not [entry for entry in logs if entry["event"] == "persons_dedup.reading_from_replica"]
+
+
+class TestPersonsDedupClassifyCounters:
+ # classify's numbers decide how much work the rollout thinks is outstanding, and nothing
+ # else asserts them. One fixture holding every group shape at once, because the counters
+ # are computed in a single aggregate and a wrong FILTER shows up as one field disagreeing.
+ def _seed_every_shape(self, conn) -> None:
+ # No refs at all: both rows are orphans.
+ _add_person(conn, _uuid(90))
+ _add_person(conn, _uuid(90))
+
+ # One reachable survivor plus one orphan. Resolvable.
+ survivor = _add_person(conn, _uuid(91))
+ _add_distinct_id(conn, survivor, "did-91")
+ _add_person(conn, _uuid(91))
+
+ # Two reachable rows: needs a real person merge.
+ a = _add_person(conn, _uuid(92))
+ b = _add_person(conn, _uuid(92))
+ _add_distinct_id(conn, a, "did-92a")
+ _add_distinct_id(conn, b, "did-92b")
+
+ # Held by a tombstone, which repair will not touch.
+ live = _add_person(conn, _uuid(93))
+ _add_distinct_id(conn, live, "did-93")
+ _add_person(conn, _uuid(93), is_deleted=True)
+
+ # Referenced by everything except a distinct ID, so still resolvable.
+ keeper = _add_person(conn, _uuid(94))
+ _add_distinct_id(conn, keeper, "did-94")
+ held = _add_person(conn, _uuid(94))
+ _add_cohort_member(conn, held)
+ _add_flag_override(conn, held, "flag-94")
+
+ def test_classify_reports_every_counter_for_every_group_shape(self, persons_conn, tmp_path):
+ self._seed_every_shape(persons_conn)
+
+ with capture_logs() as logs:
+ _run("classify", tmp_path)
+
+ result = next(entry for entry in logs if entry["event"] == "persons_dedup.classify")
+ assert result["dup_groups"] == 5
+ assert result["all_orphaned"] == 1, "only uuid(90) has no referenced member"
+ assert result["one_referenced"] == 2, "uuid(91) and uuid(93)"
+ assert result["needs_merge"] == 2, "uuid(92) and uuid(94), which counts the held refs"
+ assert result["groups_with_distinct_ids_on_multiple_rows"] == 1, "only uuid(92)"
+ assert result["blocked_groups"] == 2, "uuid(92) needs a merge, uuid(93) holds a tombstone"
+ assert result["resolvable_groups"] == 3
+ assert result["tombstoned_members"] == 1
+ assert result["distinct_ids"] == 5
+ assert result["cohort_rows"] == 1
+ assert result["flag_overrides"] == 1
+
+ def test_a_long_step_is_bracketed_so_progress_is_visible(self, persons_conn, tmp_path):
+ # A census emits nothing while it runs, so without these a slow scan and a hung one
+ # look identical. The pid is what lets an operator check pg_stat_activity after an
+ # interrupt.
+ _add_orphan_pair(persons_conn, _uuid(95), "did-95")
+
+ with capture_logs() as logs:
+ _run("classify", tmp_path)
+
+ started = next(e for e in logs if e["event"] == "persons_dedup.step_started" and e["step"] == "classify")
+ finished = next(e for e in logs if e["event"] == "persons_dedup.step_finished" and e["step"] == "classify")
+ assert isinstance(started["pid"], int)
+ assert finished["elapsed_s"] >= 0
+
+
+class TestPersonsDedupContention:
+ def test_a_lock_timeout_retries_the_batch_and_reports_the_budget(self, persons_conn, tmp_path):
+ # Ingestion holds locks on exactly these rows by design, so expiry is a normal event.
+ # Letting LockNotAvailable escape ends the run and discards the staging census.
+ victim, _survivor = _add_orphan_pair_ids(persons_conn, _uuid(96), "did-96")
+
+ with persons_db_connection(writer=True, autocommit=True) as blocker:
+ with blocker.cursor() as cur:
+ cur.execute("BEGIN")
+ cur.execute("SELECT id FROM posthog_person WHERE team_id = %s AND id = %s FOR UPDATE", (TEAM, victim))
+ try:
+ with pytest.raises(CommandError, match="lock contention") as raised:
+ _run("repair", tmp_path, apply=True, lock_timeout_ms=50, max_lock_retries=1)
+ finally:
+ cur.execute("ROLLBACK")
+
+ # Budget of 1 means it took the batch again before giving up, rather than dying on
+ # first contact.
+ assert "2 batch(es)" in str(raised.value)
+ assert _persons(persons_conn) == 2, "nothing may be deleted when the lock was never held"
+
+
+class TestPersonsDedupPlatformErrors:
+ def test_an_unavailable_recovery_probe_does_not_end_the_run(self, persons_conn, tmp_path, monkeypatch):
+ # The probe only labels a log line. Aurora withholds some introspection functions, and
+ # letting one abort the run is how the previous failure shipped.
+ real_scalar = persons_dedup_command._scalar
+
+ def refuse_recovery_probe(conn, sql, params=None):
+ if "pg_is_in_recovery" in sql:
+ raise psycopg.errors.FeatureNotSupported("not supported on this platform")
+ return real_scalar(conn, sql, params)
+
+ monkeypatch.setattr(persons_dedup_command, "_scalar", refuse_recovery_probe)
+ _add_orphan_pair(persons_conn, _uuid(97), "did-97")
+ with capture_logs() as logs:
+ _run("classify", tmp_path)
+
+ assert [e for e in logs if e["event"] == "persons_dedup.recovery_probe_unavailable"]
+ assert [e for e in logs if e["event"] == "persons_dedup.classify"], "the census still ran"
+
+ def test_a_replica_conflict_is_retried_and_other_errors_are_not(self, persons_conn, monkeypatch):
+ # Aurora cancels long reads on a reader to resolve replication conflicts, which
+ # statement_timeout = 0 does not prevent. Losing a finished census to that is worse
+ # than waiting. Anything else must surface immediately.
+ monkeypatch.setattr(persons_dedup_command, "REPLICA_RETRY_BACKOFF_BASE_S", 0.0)
+ calls = {"n": 0}
+
+ def conflict_once():
+ calls["n"] += 1
+ if calls["n"] == 1:
+ raise psycopg.errors.SerializationFailure("canceling statement due to conflict with recovery")
+ return "census"
+
+ assert persons_dedup_command._retry_replica_conflict(persons_conn, "test", conflict_once) == "census"
+ assert calls["n"] == 2
+
+ def always_undefined():
+ raise psycopg.errors.UndefinedTable("no such table")
+
+ with pytest.raises(psycopg.errors.UndefinedTable):
+ persons_dedup_command._retry_replica_conflict(persons_conn, "test", always_undefined)
+
+ def test_a_persistent_replica_conflict_eventually_surfaces(self, persons_conn, monkeypatch):
+ monkeypatch.setattr(persons_dedup_command, "REPLICA_RETRY_BACKOFF_BASE_S", 0.0)
+
+ def always_conflict():
+ raise psycopg.errors.SerializationFailure("canceling statement due to conflict with recovery")
+
+ with pytest.raises(psycopg.errors.SerializationFailure):
+ persons_dedup_command._retry_replica_conflict(persons_conn, "test", always_conflict, attempts=2)
+
+
+class TestPersonsDedupVerifyGate:
+ def test_an_orphaned_mapping_does_not_fail_the_gate_and_is_not_scanned_for(self, persons_conn, tmp_path):
+ # repair can neither create an orphaned mapping nor remove one, so gating on it blocked
+ # the rollout on damage this command cannot fix. The scan costs several times the rest of
+ # verify, so once it stopped gating there was no reason to keep paying for it.
+ doomed = _add_person(persons_conn, _uuid(98))
+ _add_distinct_id(persons_conn, doomed, "did-98")
+ _orphan_a_distinct_id(persons_conn, doomed)
+
+ with capture_logs() as logs:
+ _run("verify", tmp_path)
+
+ assert not [e for e in logs if e["event"] == "persons_dedup.step_started" and e["step"] == "verify_orphans"]
+ assert next(e for e in logs if e["event"] == "persons_dedup.verify")["orphaned_distinct_ids"] is None
+
+ def test_require_no_orphans_runs_the_scan_and_reports_the_count(self, persons_conn, tmp_path):
+ doomed = _add_person(persons_conn, _uuid(97))
+ _add_distinct_id(persons_conn, doomed, "did-97")
+ _orphan_a_distinct_id(persons_conn, doomed)
+
+ with capture_logs() as logs:
+ with pytest.raises(CommandError, match="orphaned distinct id"):
+ _run("verify", tmp_path, require_no_orphans=True)
+
+ assert next(e for e in logs if e["event"] == "persons_dedup.verify")["orphaned_distinct_ids"] == 1
+
+ def test_require_no_orphans_restores_the_stricter_gate(self, persons_conn, tmp_path):
+ doomed = _add_person(persons_conn, _uuid(99))
+ _add_distinct_id(persons_conn, doomed, "did-99")
+ _orphan_a_distinct_id(persons_conn, doomed)
+
+ with pytest.raises(CommandError, match="orphaned distinct id"):
+ _run("verify", tmp_path, require_no_orphans=True)
+
+ # The matrix runs against the decision itself, so the combinations do not each need a
+ # seeded orphan.
+ @pytest.mark.parametrize(
+ "resolvable,orphans,require_no_orphans,expected",
+ [
+ (0, 0, False, []),
+ (0, 3, False, []),
+ (0, 3, True, ["3 orphaned distinct id(s)"]),
+ (2, 0, False, ["2 resolvable duplicate group(s)"]),
+ (2, 3, False, ["2 resolvable duplicate group(s)"]),
+ (2, 3, True, ["2 resolvable duplicate group(s)", "3 orphaned distinct id(s)"]),
+ ],
+ )
+ def test_orphans_gate_only_when_required(self, resolvable, orphans, require_no_orphans, expected):
+ assert (
+ persons_dedup_command._verify_failures(
+ resolvable=resolvable, orphans=orphans, require_no_orphans=require_no_orphans
+ )
+ == expected
+ )
+
+
+class TestPersonsDedupReaderEndpoint:
+ def test_reader_is_refused_when_no_reader_url_is_configured(self, persons_conn, tmp_path, monkeypatch):
+ # The persons-DB URL silently falls back to the writer, so without this the flag whose
+ # whole purpose is keeping a census off the primary would put it on the primary.
+ monkeypatch.delenv("PERSONS_DB_READER_URL", raising=False)
+
+ with pytest.raises(CommandError, match="PERSONS_DB_READER_URL"):
+ _run("classify", tmp_path, reader=True)
+
+ def test_reader_on_a_primary_session_warns_instead_of_aborting(self, persons_conn, tmp_path):
+ # Single-node deployments point both URLs at one database, so --reader landing on the
+ # primary is normal there. The read is harmless; only the silence would be a problem.
+ with capture_logs() as logs:
+ _run("classify", tmp_path, reader=True)
+
+ assert [e for e in logs if e["event"] == "persons_dedup.reader_is_the_primary"]
+
+ def test_the_default_read_falls_back_to_the_writer_and_says_so(self, persons_conn, tmp_path, monkeypatch):
+ monkeypatch.delenv("PERSONS_DB_READER_URL", raising=False)
+
+ with capture_logs() as logs:
+ _run("classify", tmp_path)
+
+ assert [e for e in logs if e["event"] == "persons_dedup.no_reader_configured"]
+
+
+def _spread_uuid(index: int, total: int) -> str:
+ # _uuid() returns tiny integers, which all land in the first uuid slice, so a fixture built
+ # from it would never exercise slicing. These sit in widely separated regions of the space.
+ return str(uuid_mod.UUID(int=index * ((1 << 128) // total) + 7))
+
+
+class TestPersonsDedupCensusSlicing:
+ # Slicing the uuid space must not change any answer. 1 is the unsliced fallback; the larger
+ # counts put slice boundaries between the fixture's groups.
+ SLICES = [1, 2, 3, 64]
+ SHAPES = 5
+
+ def _seed(self, conn) -> None:
+ for shape in range(self.SHAPES):
+ uuid = _spread_uuid(shape, self.SHAPES)
+ a = _add_person(conn, uuid)
+ b = _add_person(conn, uuid, is_deleted=(shape == 3))
+ if shape >= 1:
+ _add_distinct_id(conn, a, f"spread-{shape}a")
+ if shape == 2:
+ _add_distinct_id(conn, b, f"spread-{shape}b")
+ if shape == 4:
+ _add_cohort_member(conn, b)
+ _add_flag_override(conn, b, f"spread-flag-{shape}")
+
+ @pytest.mark.parametrize("slices", SLICES)
+ def test_classify_reports_the_same_totals_at_any_slice_count(self, persons_conn, tmp_path, slices):
+ self._seed(persons_conn)
+
+ with capture_logs() as logs:
+ _run("classify", tmp_path, census_slices=slices)
+
+ result = next(e for e in logs if e["event"] == "persons_dedup.classify")
+ assert {key: result[key] for key in persons_dedup_command.CLASSIFY_COLUMNS} == {
+ "dup_groups": 5,
+ "all_orphaned": 1,
+ "one_referenced": 2,
+ "needs_merge": 2,
+ "groups_with_distinct_ids_on_multiple_rows": 1,
+ "blocked_groups": 2,
+ "tombstoned_members": 1,
+ "distinct_ids": 5,
+ "cohort_rows": 1,
+ "flag_overrides": 1,
+ }
+ assert result["resolvable_groups"] == 3
+
+ @pytest.mark.parametrize("slices", SLICES)
+ def test_blocked_detail_is_the_same_at_any_slice_count(self, persons_conn, tmp_path, slices):
+ # Written per slice, so a boundary between two blocked groups must not drop or duplicate
+ # either one.
+ self._seed(persons_conn)
+
+ _run("classify", tmp_path, census_slices=slices)
+
+ records = [
+ json.loads(line) for dump in tmp_path.glob("blocked_team_*.jsonl") for line in dump.read_text().splitlines()
+ ]
+ assert sorted(r["reason"] for r in records) == ["multiple_reachable_rows", "tombstoned_member"]
+ assert len({r["uuid"] for r in records}) == 2, "one record per blocked group, no duplicates"
+
+ @pytest.mark.parametrize("slices", SLICES)
+ def test_verify_counts_the_same_at_any_slice_count(self, persons_conn, tmp_path, slices):
+ self._seed(persons_conn)
+
+ with capture_logs() as logs:
+ with pytest.raises(CommandError):
+ _run("verify", tmp_path, census_slices=slices)
+
+ result = next(e for e in logs if e["event"] == "persons_dedup.verify")
+ assert result["duplicate_groups"] == 5
+ assert result["blocked_groups"] == 2
+ assert result["resolvable_groups"] == 3
+
+ @pytest.mark.parametrize("slices", SLICES)
+ def test_repair_stages_and_deletes_the_same_victims_at_any_slice_count(self, persons_conn, tmp_path, slices):
+ # Staging runs one transaction per slice, so a boundary must not leave a victim unstaged.
+ for shape in range(self.SHAPES):
+ _add_orphan_pair(persons_conn, _spread_uuid(shape, self.SHAPES), f"spread-repair-{shape}")
+ assert _persons(persons_conn) == 10
+
+ with capture_logs() as logs:
+ _run("repair", tmp_path, apply=True, census_slices=slices)
+
+ assert _persons(persons_conn) == 5, "every orphan is staged and deleted whatever the slicing"
+ assert _dup_groups(persons_conn) == 0
+ assert next(e for e in logs if e["event"] == "persons_dedup.staged")["victims"] == 5
+
+
+class TestPersonsDedupResume:
+ def test_a_run_can_resume_from_its_checkpoint_without_restaging(self, persons_conn, tmp_path, monkeypatch):
+ # An interrupted run used to lose the whole staging census. The checkpoint holds the
+ # victims still to delete, so a rerun picks up where it stopped.
+ for shape in range(4):
+ _add_orphan_pair(persons_conn, _uuid(300 + shape), f"did-300-{shape}")
+ assert _persons(persons_conn) == 8
+
+ # Stop the run after its first batch, the way a lost connection or a Ctrl-C would.
+ real_prune = persons_dedup_command.Command._prune_batch
+
+ class Stop(Exception):
+ pass
+
+ calls = {"n": 0}
+ real_write = persons_dedup_command.Command._write_checkpoint
+
+ def stop_after_second_checkpoint(self, conn, path, *, team, staged):
+ real_write(self, conn, path, team=team, staged=staged)
+ calls["n"] += 1
+ if calls["n"] == 2:
+ raise Stop()
+
+ monkeypatch.setattr(persons_dedup_command.Command, "_write_checkpoint", stop_after_second_checkpoint)
+ with pytest.raises(Stop):
+ _run("repair", tmp_path, apply=True, batch_size=1, checkpoint_every=1)
+
+ monkeypatch.setattr(persons_dedup_command.Command, "_prune_batch", real_prune)
+ monkeypatch.undo()
+ deleted_first = 8 - _persons(persons_conn)
+ assert deleted_first == 1, "one batch of one victim landed before the stop"
+
+ checkpoint = tmp_path / f"remaining_team_{TEAM}_repair.csv"
+ assert checkpoint.exists()
+ assert len(checkpoint.read_text().splitlines()) == 3, "the three victims still to delete"
+
+ with capture_logs() as logs:
+ _run("repair", tmp_path, apply=True, resume_from=str(checkpoint))
+
+ assert next(e for e in logs if e["event"] == "persons_dedup.resumed")["victims"] == 3
+ assert not [e for e in logs if e["event"] == "persons_dedup.step_started" and e["step"] == "stage"], (
+ "resuming must not re-run the census"
+ )
+ assert _persons(persons_conn) == 4
+ assert _dup_groups(persons_conn) == 0
+
+ def test_a_stale_checkpoint_entry_is_pruned_rather_than_deleted(self, persons_conn, tmp_path):
+ # Staging is not authoritative; the gates are. A victim that became reachable after the
+ # checkpoint was written must be dropped, not deleted.
+ victim, _survivor = _add_orphan_pair_ids(persons_conn, _uuid(310), "did-310")
+ checkpoint = tmp_path / "stale.csv"
+ checkpoint.write_text(f"{TEAM},{victim},{_uuid(310)}\n")
+
+ _add_distinct_id(persons_conn, victim, "did-310-rescued")
+
+ _run("repair", tmp_path, apply=True, resume_from=str(checkpoint))
+
+ assert _persons(persons_conn) == 2, "the rescued row must survive"
+
+ def test_a_checkpoint_for_another_team_is_refused(self, persons_conn, tmp_path):
+ # The gates only ever look at the staged set, so they cannot catch this.
+ checkpoint = tmp_path / "wrong-team.csv"
+ checkpoint.write_text(f"{TEAM + 1},999999,{_uuid(311)}\n")
+
+ with pytest.raises(CommandError, match="different team"):
+ _run("repair", tmp_path, apply=True, resume_from=str(checkpoint))
+
+ def test_resume_from_is_rejected_for_read_modes(self, persons_conn, tmp_path):
+ with pytest.raises(CommandError, match="meaningless"):
+ _run("classify", tmp_path, resume_from="/nonexistent")
+
+ def test_a_checkpoint_naming_already_deleted_victims_is_reconciled_not_pruned(self, persons_conn, tmp_path):
+ # Every prune counts against a budget meant for staging and the gate disagreeing, so a
+ # checkpoint written a few batches before the interruption must not spend it on rows whose
+ # absence is expected.
+ victim, _survivor = _add_orphan_pair_ids(persons_conn, _uuid(320), "did-320")
+ live_victim, _live_survivor = _add_orphan_pair_ids(persons_conn, _uuid(321), "did-321")
+ with persons_conn.cursor() as cur:
+ cur.execute("DELETE FROM posthog_person WHERE team_id = %s AND id = %s", (TEAM, victim))
+
+ checkpoint = tmp_path / "with-deleted.csv"
+ checkpoint.write_text(f"{TEAM},{victim},{_uuid(320)}\n{TEAM},{live_victim},{_uuid(321)}\n")
+
+ with capture_logs() as logs:
+ _run("repair", tmp_path, apply=True, resume_from=str(checkpoint))
+
+ assert next(e for e in logs if e["event"] == "persons_dedup.checkpoint_reconciled")["already_deleted"] == 1
+ assert next(e for e in logs if e["event"] == "persons_dedup.staged")["victims"] == 1
+ assert not [e for e in logs if e["event"] == "persons_dedup.batch_raced"], "no prune budget spent"
+ assert _persons(persons_conn) == 2