:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(persons): tombstone outside the drain and remove dormant person tools (#111380)
Eli Reisman6d7e70b1801c
diff --git a/posthog/dags/clickhouse_cleanup.py b/posthog/dags/clickhouse_cleanup.pyindex b5df5151902d..2c8c7f9a7529 100644--- a/posthog/dags/clickhouse_cleanup.py+++ b/posthog/dags/clickhouse_cleanup.py@@ -721,9 +721,8 @@ def recheck_revived_persons(name: str) -> dagster.OpDefinition:The checkpoints sit at phase boundaries rather than inside the mutation, because a mutationover an unpartitioned table runs long and re-checking mid-flight cannot retract work already- applied. A person revived inside that window has already lost its distinct id rows;- reset_deleted_person_distinct_ids and the sync_person_distinct_ids workflow republish them- from Postgres.+ applied. A person revived inside that window has already lost its distinct id rows; find and+ restore them with `manage.py person_divergence scan swept` and `repair`."""@dagster.op(name=name)diff --git a/posthog/management/commands/backfill_distinct_id_overrides.py b/posthog/management/commands/backfill_distinct_id_overrides.pydeleted file mode 100644index 5d259d58809d..000000000000--- a/posthog/management/commands/backfill_distinct_id_overrides.py+++ /dev/null@@ -1,108 +0,0 @@-from __future__ import annotations--import logging-from collections.abc import Sequence-from dataclasses import dataclass--from django.core.management.base import BaseCommand, CommandError--import structlog--from posthog.clickhouse.client.execute import sync_execute-from posthog.models.team.team import Team--logger = structlog.get_logger(__name__)---@dataclass-class Backfill:- team_id: int-- def execute(self, dry_run: bool = False) -> None:- logger.info("Starting %r...", self)-- query = """- SELECT- team_id,- distinct_id,- argMax(person_id, version),- argMax(is_deleted, version),- max(version)- FROM person_distinct_id2- WHERE- team_id = %(team_id)s- AND version > 0- GROUP BY team_id, distinct_id- """-- parameters = {- "team_id": self.team_id,- }-- if dry_run:- [(count,)] = sync_execute(f"SELECT count() FROM ({query})", parameters)- logger.info("%r would have inserted %r records.", self, count)- else:- # XXX: Nothing useful to report here, unfortunately... all that is- # returned is an empty result set.- sync_execute(- f"""- INSERT INTO person_distinct_id_overrides- (team_id, distinct_id, person_id, is_deleted, version)- {query}- """,- parameters,- )-- # XXX: The RETURNING set isn't really useful here, but this QuerySet- # needs to be iterated over to force execution, so we might as well- # return something...- updated_teams = list(- # nosemgrep: python.django.security.audit.raw-query.avoid-raw-sql (parameterized, admin-only management command)- Team.objects.raw(- """- UPDATE posthog_team- SET extra_settings = COALESCE(extra_settings, '{}'::jsonb) || '{"distinct_id_overrides_backfilled": true}'::jsonb- WHERE id = %s- RETURNING *- """,- [self.team_id],- )- )- assert not len(updated_teams) > 1-- logger.info("Completed %r!", self)---class Command(BaseCommand):- help = "Backfill person_distinct_id_overrides records."-- def add_arguments(self, parser):- parser.add_argument(- "--team-id",- required=False,- type=int,- dest="team_id_list",- action="append",- help="team(s) to backfill (defaults to all un-backfilled teams)",- )- parser.add_argument(- "--live-run", action="store_true", help="actually execute INSERT queries (default is dry-run)"- )-- def handle(self, *, live_run: bool, team_id_list: Sequence[int] | None, **options):- logger.setLevel(logging.INFO)-- if team_id_list is not None:- team_ids = set(team_id_list)- existing_team_ids = set(Team.objects.filter(id__in=team_ids).values_list("id", flat=True))- if existing_team_ids != team_ids:- raise CommandError(f"Teams with ids {team_ids - existing_team_ids!r} do not exist")- else:- team_ids = set(- Team.objects.exclude(extra_settings__distinct_id_overrides_backfilled=True).values_list("id", flat=True)- )-- logger.info("Starting backfill for %s teams...", len(team_ids))- for team_id in team_ids:- Backfill(team_id).execute(dry_run=not live_run)diff --git a/posthog/management/commands/backfill_persons_and_groups_on_events.py b/posthog/management/commands/backfill_persons_and_groups_on_events.pydeleted file mode 100644index 48131d7769e6..000000000000--- a/posthog/management/commands/backfill_persons_and_groups_on_events.py+++ /dev/null@@ -1,206 +0,0 @@-# ruff: noqa: T201 allow print statements--import logging-from time import sleep-from typing import Any-from uuid import uuid4--from django.conf import settings-from django.core.management.base import BaseCommand--import structlog--from posthog.clickhouse.client import sync_execute-from posthog.clickhouse.query_tagging import reset_query_tags, tag_queries-from posthog.models.event.sql import EVENTS_DATA_TABLE-from posthog.models.group.sql import GROUPS_TABLE-from posthog.models.person.sql import PERSON_DISTINCT_ID2_TABLE, PERSONS_TABLE-from posthog.settings import CLICKHOUSE_CLUSTER, CLICKHOUSE_DATABASE-from posthog.settings.data_stores import CLICKHOUSE_PASSWORD--"""-WARNING: This script is in Alpha! Make sure you know what you're doing before running it with --live-run set.--Pre-requisites:--- `allow_nondeterministic_mutations` should be set to 1 on the current user's profile--Approach:--1. Create dictionaries for groups, persons, and person distinct ID tables--These dictionaries will source data from the target Replicated tables, so they are guaranteed to be consistent across nodes.-We keep a small cache in memory of 1000 frequently accessed keys for each dictionary. We hit the source table for values not in the cache.--2. Alter table to update values according to the dictionaries--With the dictionaries in place, we run an ALTER TABLE backfill. Note that this will have to rewrite a lot of data.-This backfill will look up values in the dictionaries and set the corresponding columns to them.-Also note that minor inconsitencies can occur from distinct IDs and properties changing during the backfill.--3. Drop the dictionaries-"""---logger = structlog.get_logger(__name__)-logger.setLevel(logging.INFO)--backfill_query_id = str(uuid4())---GROUPS_DICT_TABLE_NAME = f"{GROUPS_TABLE}_dict"-PERSONS_DICT_TABLE_NAME = f"{PERSONS_TABLE}_dict"-PERSON_DISTINCT_IDS_DICT_TABLE_NAME = f"{PERSON_DISTINCT_ID2_TABLE}_dict"--ACCESS_CONFIG = f"DB '{CLICKHOUSE_DATABASE}' USER 'default' PASSWORD '{CLICKHOUSE_PASSWORD}'"--GROUPS_DICTIONARY_SQL = f"""-CREATE DICTIONARY IF NOT EXISTS {GROUPS_DICT_TABLE_NAME}-ON CLUSTER '{CLICKHOUSE_CLUSTER}'-(- group_key String,- group_properties String-)-PRIMARY KEY group_key-SOURCE(CLICKHOUSE(TABLE {GROUPS_TABLE} {ACCESS_CONFIG}))-LAYOUT(complex_key_cache(size_in_cells 10000))-Lifetime(60000)-"""---PERSON_DISTINCT_IDS_DICTIONARY_SQL = f"""-CREATE DICTIONARY IF NOT EXISTS {PERSON_DISTINCT_IDS_DICT_TABLE_NAME}-ON CLUSTER '{CLICKHOUSE_CLUSTER}'-(- distinct_id String,- person_id UUID-)-PRIMARY KEY distinct_id-SOURCE(CLICKHOUSE(TABLE {PERSON_DISTINCT_ID2_TABLE} {ACCESS_CONFIG}))-LAYOUT(complex_key_direct())-"""--PERSONS_DICTIONARY_SQL = f"""-CREATE DICTIONARY IF NOT EXISTS {PERSONS_DICT_TABLE_NAME}-ON CLUSTER '{CLICKHOUSE_CLUSTER}'-(- id UUID,- properties String-)-PRIMARY KEY id-SOURCE(CLICKHOUSE(TABLE {PERSONS_TABLE} {ACCESS_CONFIG}))-LAYOUT(complex_key_direct())-"""--backfill_settings = "SETTINGS mutations_sync = 2" if settings.TEST else ""--BACKFILL_SQL = f"""-ALTER TABLE {EVENTS_DATA_TABLE()}-ON CLUSTER '{CLICKHOUSE_CLUSTER}'-UPDATE- person_id=toUUID(dictGet('{CLICKHOUSE_DATABASE}.{PERSON_DISTINCT_IDS_DICT_TABLE_NAME}', 'person_id', tuple(distinct_id))),- person_properties=dictGetString('{CLICKHOUSE_DATABASE}.{PERSONS_DICT_TABLE_NAME}', 'properties', tuple(toUUID(dictGet('{CLICKHOUSE_DATABASE}.{PERSON_DISTINCT_IDS_DICT_TABLE_NAME}', 'person_id', tuple(distinct_id))))),- group0_properties=dictGetString('{CLICKHOUSE_DATABASE}.{GROUPS_DICT_TABLE_NAME}', 'group_properties', tuple($group_0)),- group1_properties=dictGetString('{CLICKHOUSE_DATABASE}.{GROUPS_DICT_TABLE_NAME}', 'group_properties', tuple($group_1)),- group2_properties=dictGetString('{CLICKHOUSE_DATABASE}.{GROUPS_DICT_TABLE_NAME}', 'group_properties', tuple($group_2)),- group3_properties=dictGetString('{CLICKHOUSE_DATABASE}.{GROUPS_DICT_TABLE_NAME}', 'group_properties', tuple($group_3)),- group4_properties=dictGetString('{CLICKHOUSE_DATABASE}.{GROUPS_DICT_TABLE_NAME}', 'group_properties', tuple($group_4))-WHERE team_id = %(team_id)s-{backfill_settings}-"""--GET_QUERY_ID_SQL = f"""-SELECT query_id-FROM system.query_log-WHERE- query_start_time > (now() - INTERVAL 10 MINUTE) AND- query LIKE '%backfill:{backfill_query_id}%' AND- query NOT LIKE '%query_log%'-LIMIT 1-"""---query_number = 0---def print_and_execute_query(sql: str, name: str, dry_run: bool, timeout=180, query_args=None) -> Any:- if query_args is None:- query_args = {}- global query_number-- if not settings.TEST:- print(f"> {query_number}. {name}", end="\n\n")- print(sql, end="\n")- print("---------------------------------", end="\n\n")-- query_number = query_number + 1-- if not dry_run:- res = sync_execute(sql, settings={"max_execution_time": timeout}, args=query_args)- return res-- return None---def run_backfill(options):- if not options["team_id"]:- logger.error("You must specify --team-id to run this script")- exit(1)-- dry_run = not options["live_run"]-- if dry_run:- print("Dry run. Queries to run:", end="\n\n")-- print_and_execute_query(GROUPS_DICTIONARY_SQL, "GROUPS_DICTIONARY_SQL", dry_run)- print_and_execute_query(- PERSON_DISTINCT_IDS_DICTIONARY_SQL,- "PERSON_DISTINCT_IDS_DICTIONARY_SQL",- dry_run,- )- print_and_execute_query(PERSONS_DICTIONARY_SQL, "PERSONS_DICTIONARY_SQL", dry_run)-- tag_queries(kind="backfill", id=backfill_query_id)- print_and_execute_query(- BACKFILL_SQL,- "BACKFILL_SQL",- dry_run,- 0,- {"team_id": options["team_id"], "id": backfill_query_id},- )- reset_query_tags()-- if dry_run or settings.TEST:- return-- # it can take a little while for the query to show up on the query_log- sleep(10)- query_id_res = print_and_execute_query(GET_QUERY_ID_SQL, "GET_QUERY_ID_SQL", dry_run)-- if query_id_res:- query_id = query_id_res[0][0]- print()- print(- f"Backfill running. Cancel backfill by running:\n`KILL QUERY ON CLUSTER {CLICKHOUSE_CLUSTER} WHERE query_id='{query_id}'`"- )---class Command(BaseCommand):- help = "Backfill persons and groups data on events for a given team"-- def add_arguments(self, parser):- parser.add_argument(- "--team-id",- default=None,- type=str,- help="Specify a team to backfill data for.",- )-- parser.add_argument(- "--live-run",- action="store_true",- help="Opts out of default 'dry run' mode and actually runs the queries.",- )-- def handle(self, *args, **options):- run_backfill(options)diff --git a/posthog/management/commands/persons_dedup.py b/posthog/management/commands/persons_dedup.pydeleted file mode 100644index 3adea84dc366..000000000000--- a/posthog/management/commands/persons_dedup.py+++ /dev/null@@ -1,1615 +0,0 @@-"""Resolve duplicate (team_id, uuid) rows in posthog_person, one team at a time.--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).--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--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.--Two gates enforce this from opposite directions, because proving the victims are safe is not-the same as proving the survivor is right:-- GATE_REACHABLE_SQL no row we delete may be reachable- GATE_SURVIVOR_REACHABLE_SQL if any row in the group is reachable, one we keep must be--DO NOT REORDER THE LOCK AND THE GATE. Ingestion's stranded-row claim path selects exactly the-rows this command deletes, the unreachable holder of a (team_id, uuid), and repoints it to a-live distinct id. It takes FOR UPDATE on that row and so does LOCK_VICTIMS_SQL, which is the-only reason the two serialize instead of racing. The 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.--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.--DEPENDENT TABLES--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--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.--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--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.--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.--THE SURVIVOR'S VERSION--Keeping the uuid backed is not the same as keeping it current. The ClickHouse `person` table is-ReplacingMergeTree(version) keyed on (team_id, uuid), and every read path resolves a person with-argMax(..., version), so the highest version ever written under that uuid wins. Both members of-a duplicate group wrote under the same key with independent counters, and the survivor rule-ranks reachability above version, so the row we keep is routinely the lower-versioned one. Its-later property updates then lose to a row we just deleted, and ClickHouse serves stale-properties for as long as the gap takes to close -- which for a large gap is never.--The raise lifts a lone survivor above the victims removed with it so its next update outranks-them. It is not a ClickHouse write: nothing here produces to Kafka, so ClickHouse converges on-the survivor's next ordinary property update rather than immediately. A group with more than one-survivor is merge-required and is left alone, because giving both the same version makes their-ClickHouse rows tie instead of resolve.--It is on by default, because a run that omits it leaves the divergence in place silently.---no-raise-survivor-version opts out, which also drops the UPDATE and the wider lock this takes-on rows live ingestion writes, and gives up the correction for that run.--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:-- 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--BACKUPS--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 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--import os-import json-import time-import logging-import argparse-from collections.abc import Callable, Iterator-from contextlib import contextmanager-from datetime import UTC, datetime-from pathlib import Path-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__)-# The posthoganalytics SDK claims the "posthog" logger name and clamps it to WARNING at-# client init, so every INFO record this command emits is dropped and a run leaves no log.-logging.getLogger(__name__).setLevel(logging.INFO)--VICTIMS_TABLE = "pg_temp.persons_dedup_victims"--PERSON_COLUMNS = (- "id",- "created_at",- "properties",- "team_id",- "is_user_id",- "is_identified",- "uuid",- "properties_last_updated_at",- "properties_last_operation",- "version",- "last_seen_at",- "is_deleted",-)--# 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,- -- 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- WHERE pdi.team_id = p.team_id AND pdi.person_id = p.id- AND NOT pdi.is_deleted) AS n_did_live,- (SELECT count(*) FROM posthog_cohortpeople 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- 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-),--- refs decides deletability for delete-unreferenced, not who survives: the ranking below--- puts reachability ahead of it, so n_cohort and n_ff only ever break a tie between rows--- that are all unreachable. They look load-bearing for survivor choice and are not.-scored AS (- SELECT *, (n_did + n_cohort + n_ff) AS refs FROM members-),-ranked AS (- SELECT *,- row_number() OVER (- PARTITION BY team_id, uuid- ORDER BY is_deleted ASC, (n_did_live > 0) DESC, (n_did > 0) DESC, refs DESC,- is_identified DESC, version DESC NULLS LAST, created_at ASC, id ASC- ) AS rn- 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. 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 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- FROM ranked GROUP BY uuid-)-"""--# 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_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 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 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_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-# 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. '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.flag_overrides, g.cohort_rows,- 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)-SELECT team_id, id, uuid FROM {VICTIMS_TABLE} ORDER BY uuid, id LIMIT %(batch)s-"""--RETIRE_BATCH_SQL = f"""-DELETE FROM {VICTIMS_TABLE} v USING {VICTIMS_TABLE}_batch b-WHERE v.team_id = b.team_id AND v.id = b.id-"""--# 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.-# Deleting them would remove it entirely, and it is no longer a duplicate anyway.-# Case 3 must be here as well as in the gate: without it, a concurrent delete of an unstaged-# survivor fails GATE_NO_SURVIVOR_SQL, matches none of the other predicates, and aborts the-# team over a batch that is merely no longer worth deleting.-PRUNE_BATCH_SQL = f"""-DELETE FROM {VICTIMS_TABLE} v-USING {VICTIMS_TABLE}_batch b-WHERE v.team_id = b.team_id AND v.id = b.id- AND (- NOT EXISTS (SELECT 1 FROM posthog_person p- WHERE p.team_id = v.team_id AND p.id = v.id)- OR EXISTS (SELECT 1 FROM posthog_persondistinctid pdi- WHERE pdi.team_id = v.team_id AND pdi.person_id = v.id)- OR (SELECT count(*) FROM posthog_person p- WHERE p.team_id = v.team_id AND p.uuid = v.uuid)- <= (SELECT count(*) FROM {VICTIMS_TABLE}_batch b2- WHERE b2.team_id = v.team_id AND b2.uuid = v.uuid)- )-"""--# The load-bearing assertion. A victim owning a distinct ID is reachable, so deleting it-# would change product behaviour and silently destroy its overrides via the cascade.-GATE_REACHABLE_SQL = f"""-SELECT count(*) FROM {VICTIMS_TABLE}_batch v-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 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 (- SELECT 1 FROM posthog_person p- WHERE p.team_id = g.team_id AND p.uuid = g.uuid- AND EXISTS (SELECT 1 FROM posthog_persondistinctid d- WHERE d.team_id = p.team_id AND d.person_id = p.id AND NOT d.is_deleted)- )- AND NOT EXISTS (- SELECT 1 FROM posthog_person p- WHERE p.team_id = g.team_id AND p.uuid = g.uuid- AND NOT EXISTS (SELECT 1 FROM {VICTIMS_TABLE}_batch b- WHERE b.team_id = p.team_id AND b.id = p.id)- AND EXISTS (SELECT 1 FROM posthog_persondistinctid d- WHERE d.team_id = p.team_id AND d.person_id = p.id AND NOT d.is_deleted)- )-"""--GATE_NO_SURVIVOR_SQL = f"""-SELECT count(*) FROM (- SELECT v.team_id, v.uuid, count(*) AS victims,- (SELECT count(*) FROM posthog_person p- WHERE p.team_id = v.team_id AND p.uuid = v.uuid) AS members- FROM {VICTIMS_TABLE}_batch v GROUP BY v.team_id, v.uuid-) 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-WHERE p.team_id = %(team)s-FOR UPDATE-"""--# --raise-survivor-version only. Takes every lock the batch will need -- victims and the-# survivors the raise updates -- in one ordered statement, before the gates and the backup.-#-# Without it the transaction locks victims, spends the gates and an fsync'd backup, and only-# then reaches for the survivor. Ingestion's updatePersonsBatch matches on (team_id, uuid)-# (nodejs postgres-person-repository.ts), so one of its statements needs both rows: if it takes-# the survivor and blocks on our victim while we are still writing the backup, the two deadlock.-# Postgres would abort one and the batch would retry, but it can bounce an ingestion write too.-#-# Collapsing both acquisitions into one statement leaves no window between them. ORDER BY id-# makes our order deterministic; ingestion's order inside its own statement is the planner's, so-# this narrows the race rather than removing it, and DeadlockDetected stays the backstop.-LOCK_BATCH_GROUPS_SQL = f"""-SELECT p.id FROM posthog_person p-WHERE p.team_id = %(team)s- AND EXISTS (SELECT 1 FROM {VICTIMS_TABLE}_batch b- WHERE b.team_id = p.team_id AND b.uuid = p.uuid)-ORDER BY p.id-FOR UPDATE-"""--FETCH_PERSONS_SQL = f"""-SELECT {", ".join("p." + c for c in PERSON_COLUMNS)}-FROM posthog_person p-JOIN {VICTIMS_TABLE}_batch v ON v.team_id = p.team_id AND v.id = p.id-WHERE p.team_id = %(team)s ORDER BY p.uuid, p.id-"""--# Dependent rows the delete will remove. Captured so the backup covers everything lost,-# not just the person row.-FETCH_DEPENDENTS_SQL = f"""-SELECT 'featureflaghashkeyoverride' AS tbl, ff.id, ff.person_id,- ff.feature_flag_key AS k, ff.hash_key AS v-FROM posthog_featureflaghashkeyoverride ff-JOIN {VICTIMS_TABLE}_batch b ON b.team_id = ff.team_id AND b.id = ff.person_id-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-"""--# Cohort rows have no FK, so the cascade will not remove them. Delete explicitly, before-# the person row, so a failure here aborts before anything is lost.-DELETE_COHORT_SQL = f"""-DELETE FROM posthog_cohortpeople cp-USING {VICTIMS_TABLE}_batch b WHERE cp.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"""-SELECT count(*) FROM posthog_cohortpeople cp-JOIN {VICTIMS_TABLE}_batch b ON cp.person_id = b.id-"""--# Post-commit sweep. posthog_cohortpeople has no FK, so a cohort insert takes no lock-# on the person row and can commit between the in-transaction check's snapshot and our-# commit. This runs after commit with a fresh snapshot, so it sees any row that raced-# us; scoped to the batch's victims, whose persons are now provably gone.-SWEEP_COHORT_ORPHANS_SQL = f"""-DELETE FROM posthog_cohortpeople cp-USING {VICTIMS_TABLE}_batch b-WHERE cp.person_id = b.id-RETURNING cp.id, cp.cohort_id, cp.person_id-"""--DELETE_PERSONS_SQL = f"""-DELETE FROM posthog_person p-USING {VICTIMS_TABLE}_batch b-WHERE p.team_id = b.team_id AND p.id = b.id AND p.team_id = %(team)s-"""--# Headroom above the ceiling we can see. ClickHouse's ceiling for a uuid can exceed every-# version currently in Postgres, because a member deleted before this command existed also-# wrote under the same key. Matches the margin the delete paths already use for the same-# reason (posthog/models/person/deletion.py and the nodejs person repository).-SURVIVOR_VERSION_MARGIN = 100--# The batch's duplicate groups, the highest version among the victims we are about to remove,-# and each group's survivors. Shared by the dry-run count and the update so both describe the-# same rows. Victims are locked by the time this runs, so their versions cannot move under it.-_SURVIVOR_VERSION_CTE = f"""-WITH victim_ceiling AS (- SELECT b.team_id, b.uuid, max(COALESCE(p.version, 0)) AS ceiling- FROM {VICTIMS_TABLE}_batch b- JOIN posthog_person p ON p.team_id = b.team_id AND p.id = b.id- GROUP BY b.team_id, b.uuid-),-survivor AS (- SELECT c.ceiling, s.id AS survivor_id, s.team_id, COALESCE(s.version, 0) AS survivor_version,- count(*) OVER (PARTITION BY c.team_id, c.uuid) AS survivors_in_group- FROM victim_ceiling c- JOIN posthog_person s ON s.team_id = c.team_id AND s.uuid = c.uuid- WHERE NOT EXISTS (SELECT 1 FROM {VICTIMS_TABLE}_batch b2- WHERE b2.team_id = s.team_id AND b2.id = s.id)-)-"""--# Only a lone survivor can be raised: a group with two survivors is merge-required, and giving-# both the same version would make their ClickHouse rows tie rather than resolve. Those go to-# the merge pass untouched.-_LONE_SURVIVOR_PREDICATE = """- AND v.survivors_in_group = 1-"""--# The version guard reads p.version, the live row, not the CTE's survivor_version.-#-# LOCK_BATCH_GROUPS_SQL already holds FOR UPDATE on this row, so nothing can move it under us-# and the two are equal in practice. The distinction still matters: read committed re-checks an-# UPDATE's qual against the latest tuple after taking the row lock, and that re-check sees a new-# p.version but not a new CTE, which is evaluated once. Guarding on the CTE would make this-# statement correct only because of a lock three statements earlier, and silently wrong if-# anyone reordered the transaction. Guarding on p.version makes it safe on its own, and a-# survivor a writer pushed above the ceiling is skipped rather than lowered.-RAISE_SURVIVOR_VERSION_SQL = f"""-{_SURVIVOR_VERSION_CTE}-UPDATE posthog_person p-SET version = v.ceiling + {SURVIVOR_VERSION_MARGIN}-FROM survivor v-WHERE p.team_id = %(team)s AND p.id = v.survivor_id-{_LONE_SURVIVOR_PREDICATE}- AND COALESCE(p.version, 0) <= v.ceiling-"""--# The dry-run count has no row to re-check, so it reads the same snapshot the CTE took.-COUNT_SURVIVOR_VERSION_SQL = f"""-{_SURVIVOR_VERSION_CTE}-SELECT count(*) FROM survivor v-WHERE v.team_id = %(team)s-{_LONE_SURVIVOR_PREDICATE}- AND v.survivor_version <= v.ceiling-"""--VERIFY_ORPHANS_SQL = """-SELECT count(*) FROM posthog_persondistinctid pdi-WHERE pdi.team_id = %(team)s- AND NOT EXISTS (SELECT 1 FROM posthog_person p- WHERE p.team_id = pdi.team_id AND p.id = pdi.person_id)-"""---# 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_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"),-)-# Only --raise-survivor-version writes to a person row, so the grant is only required then.-SURVIVOR_VERSION_PRIVILEGES = (- *WRITE_PRIVILEGES,- ("posthog_person", "UPDATE"),-)--# 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,-)--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:- with conn.cursor() as cur:- cur.execute(sql, params or {})- row = cur.fetchone()- 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.-- 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):- pids.add(_scalar(conn, "SELECT pg_backend_pid()"))- with conn.cursor() as cur:- cur.execute("CREATE TEMP TABLE persons_dedup_canary (n int)")- cur.execute("INSERT INTO persons_dedup_canary VALUES (1)")- canary = _scalar(conn, "SELECT count(*) FROM persons_dedup_canary")- with conn.cursor() as cur:- cur.execute("DROP TABLE IF EXISTS persons_dedup_canary")- if len(pids) != 1 or canary != 1:- raise CommandError(- "connection is not session-stable (pooled/multiplexed): "- f"saw backend pids {sorted(pids)}, temp-table canary={canary}. "- "Temp tables and session settings will not survive between statements. "- "Use a direct writer endpoint, not a transaction-pooled one."- )---# 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."-- def add_arguments(self, parser: Any) -> None:- parser.add_argument("--mode", required=True, choices=["classify", "delete-unreferenced", "repair", "verify"])- parser.add_argument("--team", type=int, required=True)- parser.add_argument("--apply", action="store_true", help="actually delete; omit for a dry run")- parser.add_argument(- "--writer",- action="store_true",- 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")- parser.add_argument(- "--sleep-ms",- type=int,- 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(- "--raise-survivor-version",- action=argparse.BooleanOptionalAction,- default=True,- help=(- "raise a lone survivor's version above the versions of the victims removed with "- "it, so its later property updates outrank their ClickHouse rows instead of "- "being ignored. On by default: leaving it off silently leaves the survivor's "- "ClickHouse row stale. --no-raise-survivor-version opts out, which also drops "- "the UPDATE and the wider lock on rows live ingestion writes"- ),- )- 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, 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"):- raise CommandError(- f"{var} is not set, so the persons-DB URL would fall back to a localhost "- "default built from PG*. Refusing to run: on a deployed pod that default "- "points somewhere else entirely. Set the variable explicitly."- )- # Say out loud which database is about to be modified. The operator is driving this- # by hand against production, and host plus dbname is what tells them the toolbox- # is pointed at persons rather than the main cluster.- parts = urlsplit(persons_db_url(writer=use_writer))- logger.info(- "persons_dedup.target",- host=parts.hostname,- port=parts.port,- dbname=(parts.path or "/").lstrip("/"),- role="writer" if use_writer else "reader",- )-- def handle(self, *args: Any, **options: Any) -> None:- team: int = options["team"]- mode: str = options["mode"]- apply_changes: bool = options["apply"]-- if mode in READ_MODES and apply_changes:- raise CommandError(f"--apply is meaningless for --mode {mode}")-- 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- # Postgres as a raw syntax error.- if options["batch_size"] < 1:- raise CommandError("--batch-size must be at least 1")-- 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")-- backend_pid = _scalar(conn, "SELECT pg_backend_pid()")- on_replica = _is_replica(conn)-- required_privileges: tuple[tuple[str, str], ...]- if mode in READ_MODES:- required_privileges = READ_PRIVILEGES- elif options["raise_survivor_version"]:- required_privileges = SURVIVOR_VERSION_PRIVILEGES- else:- required_privileges = WRITE_PRIVILEGES- missing = _check_privileges(conn, required_privileges)- if missing:- raise CommandError(- "operator role lacks required grants: " + ", ".join(missing) + ". "- "Ask for the grants before running; nothing was changed."- )-- 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"]), pid=backend_pid, slices=options["census_slices"]- )- else:- self._verify(- conn,- team,- pid=backend_pid,- slices=options["census_slices"],- from_replica=bool(on_replica),- require_no_orphans=options["require_no_orphans"],- )- return-- # 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_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",- "reason",- "members",- "reachable_owners",- "live_owners",- "tombstoned",- "flag_overrides",- "cohort_rows",- "member_ids",- "reachable_ids",- )-- 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.- """- 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:- record = dict(zip(self.BLOCKED_COLUMNS, row))- tally[str(record["reason"])] = tally.get(str(record["reason"]), 0) + 1- fh.write(json.dumps({"team_id": team, **record}, default=str) + "\n")- fh.flush()- os.fsync(fh.fileno())-- 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,- # What repair will leave behind, and therefore what a passing verify accepts.- resolvable_groups=counts["dup_groups"] - counts["blocked_groups"],- **counts,- )- 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,- *,- 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",- team_id=team,- duplicate_groups=dups,- blocked_groups=blocked,- resolvable_groups=resolvable,- orphaned_distinct_ids=orphans if require_no_orphans else None,- )- # 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)-- def _run(- self,- conn: psycopg.Connection,- team: int,- 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)-- with conn.cursor() as cur:- cur.execute(- "CREATE TEMP TABLE IF NOT EXISTS persons_dedup_victims "- "(team_id integer NOT NULL, id bigint NOT NULL, uuid uuid NOT NULL, PRIMARY KEY (team_id, id))"- )- cur.execute(- "CREATE TEMP TABLE IF NOT EXISTS persons_dedup_victims_batch "- "(team_id integer NOT NULL, id bigint NOT NULL, uuid uuid NOT NULL, PRIMARY KEY (team_id, id))"- )- cur.execute(f"TRUNCATE {VICTIMS_TABLE}")- cur.execute(f"TRUNCATE {VICTIMS_TABLE}_batch")- 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- # after the staging insert so it is one bulk build, not per-row maintenance.- cur.execute(f"CREATE INDEX IF NOT EXISTS persons_dedup_victims_uuid_id_idx ON {VICTIMS_TABLE} (uuid, id)")- cur.execute(f"ANALYZE {VICTIMS_TABLE}")-- logger.info("persons_dedup.staged", team_id=team, mode=mode, victims=staged)- if staged == 0:- return-- outdir = Path(options["outdir"])- 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- raised = 0- # A live-leak team can make a staged victim reachable mid-run, which is expected and- # is handled per batch below. A large share going that way is not expected and means- # the staging query and the gate disagree, so stop rather than grind through the set.- prune_budget = max(20, staged // 100)- while True:- with conn.cursor() as cur:- cur.execute(f"TRUNCATE {VICTIMS_TABLE}_batch")- cur.execute(TAKE_BATCH_SQL, {"batch": options["batch_size"]})- in_batch = cur.rowcount- # With no stats on the batch table the planner can pick a hash join and- # seq-scan posthog_cohortpeople inside the lock-holding transaction,- # instead of probing its person_id index once per victim.- cur.execute(f"ANALYZE {VICTIMS_TABLE}_batch")- if in_batch == 0:- break- batches += 1-- 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"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- # after one batch gates --batch-size victims out of the whole staged set and- # still reports success, which on the large teams is a fraction of a percent.- checked += in_batch- with conn.cursor() as cur:- if options["raise_survivor_version"]:- raised += _scalar(conn, COUNT_SURVIVOR_VERSION_SQL, {"team": team})- cur.execute(RETIRE_BATCH_SQL)- continue-- batch_started = time.monotonic()- raised_in_batch = 0- 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",),- )- # Takes the survivors' locks too, so the raise later in this transaction- # adds no second acquisition point. Runs first, and LOCK_VICTIMS_SQL below- # then re-locks rows already held, which costs nothing and keeps its- # rowcount check meaning exactly what it did before.- if options["raise_survivor_version"]:- cur.execute(LOCK_BATCH_GROUPS_SQL, {"team": team})- 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"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,- )- 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")-- # Before the delete, while the victims' versions are still readable, and- # inside it, so a rollback takes the raise with it.- if options["raise_survivor_version"]:- cur.execute(RAISE_SURVIVOR_VERSION_SQL, {"team": team})- raised_in_batch = cur.rowcount- 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"{orphan_row[0]} cohort row(s) appeared for a victim mid-transaction; rolled back"- )- 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"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)- raced = cur.fetchall()- if raced:- # These rows were inserted after the backup was written, so record them- # in the log; they reference persons that no longer exist either way.- logger.warning(- "persons_dedup.cohort_rows_raced_the_delete",- team_id=team,- rows=[{"id": r[0], "cohort_id": r[1], "person_id": r[2]} for r in raced],- )- with conn.cursor() as cur:- cur.execute(RETIRE_BATCH_SQL)- deleted += removed- # Only after the commit: a batch lost to lock contention is retried, and counting- # the rolled-back raise here would double it.- raised += raised_in_batch- 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,- survivors_raised=raised_in_batch if options["raise_survivor_version"] else None,- elapsed_s=round(time.monotonic() - batch_started, 2),- )-- if not apply_changes:- logger.info(- "persons_dedup.dry_run_ok",- team_id=team,- mode=mode,- batches=batches,- checked=checked,- staged=staged,- survivors_to_raise=raised if options["raise_survivor_version"] else None,- )- return-- logger.info(- "persons_dedup.done",- team_id=team,- mode=mode,- batches=batches,- deleted=deleted,- pruned=pruned_total,- lock_retries=lock_retries,- survivors_raised=raised if options["raise_survivor_version"] else None,- 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)- return cur.rowcount-- def _backup(self, conn: psycopg.Connection, team: int, path: Path) -> int:- """Write victims and their dependent rows to JSONL, fsync'd, before any delete.-- Ordering is the guarantee: a rolled back delete leaves a superset in the file,- but a deleted row can never be missing from it.- """- with conn.cursor() as cur:- cur.execute(FETCH_PERSONS_SQL, {"team": team})- persons = cur.fetchall()- cur.execute(FETCH_DEPENDENTS_SQL)- dependents = cur.fetchall()-- # The backup holds person properties. Create owner-only and refuse symlinks, so- # a shared pod filesystem or a swapped path cannot expose or redirect it.- 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 persons:- fh.write(json.dumps({"_kind": "person", **dict(zip(PERSON_COLUMNS, row))}, default=str) + "\n")- for tbl, row_id, person_id, k, v in dependents:- fh.write(- json.dumps({"_kind": tbl, "id": row_id, "person_id": person_id, "key": k, "value": v}, default=str)- + "\n"- )- fh.flush()- os.fsync(fh.fileno())- return len(persons)diff --git a/posthog/management/commands/setup_orphan_test_data.py b/posthog/management/commands/setup_orphan_test_data.pydeleted file mode 100644index bb8594387eec..000000000000--- a/posthog/management/commands/setup_orphan_test_data.py+++ /dev/null@@ -1,235 +0,0 @@-"""-Management command to create test data for sync_person_distinct_ids workflow.--Creates orphaned persons in ClickHouse with various scenarios:-- Fixable: Person in CH + PG, DID only in PG (should be synced)-- Truly orphaned: Person in CH + PG, no DID anywhere (report only)-- CH-only orphan: Person only in CH (should be marked deleted)--Usage:- python manage.py setup_orphan_test_data --team-id 1- python manage.py setup_orphan_test_data --team-id 1 --fixable 5 --truly-orphaned 3 --ch-only 2- python manage.py setup_orphan_test_data --team-id 1 --cleanup # Remove test data-"""--import uuid--from django.conf import settings-from django.core.management.base import BaseCommand--from posthog.clickhouse.client.execute import sync_execute-from posthog.models import Team-from posthog.persons_db import persons_db_connection-from posthog.persons_seed import PERSON_DISTINCT_ID_TABLE, insert_seed_distinct_id, insert_seed_person---class Command(BaseCommand):- help = "Create test data for sync_person_distinct_ids workflow"-- def add_arguments(self, parser):- parser.add_argument(- "--team-id",- type=int,- required=True,- help="Team ID to create test data for",- )- parser.add_argument(- "--fixable",- type=int,- default=3,- help="Number of fixable orphans (person in CH+PG, DID only in PG)",- )- parser.add_argument(- "--truly-orphaned",- type=int,- default=2,- help="Number of truly orphaned (person in CH+PG, no DID anywhere)",- )- parser.add_argument(- "--ch-only",- type=int,- default=2,- help="Number of CH-only orphans (person only in CH, not in PG)",- )- parser.add_argument(- "--cleanup",- action="store_true",- help="Remove test data instead of creating it",- )- parser.add_argument(- "--prefix",- type=str,- default="test-orphan",- help="Prefix for test distinct IDs (default: test-orphan)",- )-- def handle(self, *args, **options):- team_id = options["team_id"]- prefix = options["prefix"]-- try:- team = Team.objects.get(id=team_id)- except Team.DoesNotExist:- self.stderr.write(self.style.ERROR(f"Team {team_id} does not exist"))- return-- if options["cleanup"]:- self.cleanup_test_data(team, prefix)- else:- self.create_test_data(- team=team,- prefix=prefix,- fixable_count=options["fixable"],- truly_orphaned_count=options["truly_orphaned"],- ch_only_count=options["ch_only"],- )-- def create_test_data(- self,- team: Team,- prefix: str,- fixable_count: int,- truly_orphaned_count: int,- ch_only_count: int,- ):- self.stdout.write(f"\nCreating test orphan data for team {team.id}...")- self.stdout.write(f" Fixable orphans: {fixable_count}")- self.stdout.write(f" Truly orphaned: {truly_orphaned_count}")- self.stdout.write(f" CH-only orphans: {ch_only_count}")-- created_persons: list[tuple[str, str, str | None]] = []-- # autocommit so each seeded row lands immediately, matching the prior per-create ORM behavior.- with persons_db_connection(writer=True, autocommit=True) as conn:- # 1. Fixable orphans: Person in CH + PG, DID only in PG- self.stdout.write(self.style.WARNING("\n[Fixable Orphans]"))- for i in range(fixable_count):- person_uuid = str(uuid.uuid4())- distinct_id = f"{prefix}-fixable-{i}-{person_uuid[:8]}"-- # Create person in PostgreSQL with distinct ID- person_id = insert_seed_person(- conn,- team_id=team.id,- properties={"test_type": "fixable", "index": i},- uuid=person_uuid,- )- insert_seed_distinct_id(conn, team_id=team.id, person_id=person_id, distinct_id=distinct_id)-- # Create person in ClickHouse WITHOUT distinct ID- self._insert_person_to_ch(team.id, person_uuid, version=0)- # Deliberately NOT inserting distinct_id to CH-- created_persons.append(("fixable", person_uuid, distinct_id))- self.stdout.write(f" Created: {person_uuid[:8]}... -> {distinct_id}")-- # 2. Truly orphaned: Person in CH + PG, no DID anywhere- self.stdout.write(self.style.WARNING("\n[Truly Orphaned]"))- for i in range(truly_orphaned_count):- person_uuid = str(uuid.uuid4())-- # Create person in PostgreSQL WITHOUT distinct ID- insert_seed_person(- conn,- team_id=team.id,- properties={"test_type": "truly_orphaned", "index": i},- uuid=person_uuid,- )-- # Create person in ClickHouse WITHOUT distinct ID- self._insert_person_to_ch(team.id, person_uuid, version=0)-- created_persons.append(("truly_orphaned", person_uuid, None))- self.stdout.write(f" Created: {person_uuid[:8]}... (no DID)")-- # 3. CH-only orphans: Person only in CH, not in PG- self.stdout.write(self.style.WARNING("\n[CH-Only Orphans]"))- for _ in range(ch_only_count):- person_uuid = str(uuid.uuid4())-- # Create person ONLY in ClickHouse- self._insert_person_to_ch(team.id, person_uuid, version=0)- # Deliberately NOT creating in PostgreSQL-- created_persons.append(("ch_only", person_uuid, None))- self.stdout.write(f" Created: {person_uuid[:8]}... (CH only)")-- # Summary- self.stdout.write(self.style.SUCCESS(f"\n✓ Created {len(created_persons)} test orphans"))- self.stdout.write("\nTo verify orphans exist, run:")- self.stdout.write(- f" python manage.py start_temporal_workflow sync-person-distinct-ids '{{\"team_id\": {team.id}}}'"- )-- self.stdout.write("\nTo clean up test data:")- self.stdout.write(f" python manage.py setup_orphan_test_data --team-id {team.id} --cleanup --prefix {prefix}")-- def cleanup_test_data(self, team: Team, prefix: str):- self.stdout.write(f"\nCleaning up test data for team {team.id} with prefix '{prefix}'...")-- # Escape LIKE wildcards so the prefix matches literally, mirroring Django's __startswith.- like_prefix = prefix.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"-- with persons_db_connection(writer=True, autocommit=True) as conn, conn.cursor() as cursor:- # Find test persons by their seeded test_type property.- cursor.execute(- f"SELECT uuid FROM {settings.PERSON_TABLE_NAME} "- "WHERE team_id = %s AND properties->>'test_type' IN ('fixable', 'truly_orphaned')",- (team.id,),- )- pg_uuids = [str(row[0]) for row in cursor.fetchall()]-- cursor.execute(- f"DELETE FROM {PERSON_DISTINCT_ID_TABLE} WHERE team_id = %s AND distinct_id LIKE %s",- (team.id, like_prefix),- )- deleted_dids = cursor.rowcount-- cursor.execute(- f"DELETE FROM {settings.PERSON_TABLE_NAME} "- "WHERE team_id = %s AND properties->>'test_type' IN ('fixable', 'truly_orphaned')",- (team.id,),- )- deleted_persons = cursor.rowcount-- self.stdout.write(f" Deleted {deleted_persons} persons from PostgreSQL")- self.stdout.write(f" Deleted {deleted_dids} distinct IDs from PostgreSQL")-- # Mark as deleted in ClickHouse (we can't truly delete, but can mark is_deleted=1)- if pg_uuids:- sync_execute(- """- INSERT INTO person (id, team_id, is_deleted, version, _timestamp, _offset)- SELECT id, team_id, 1, version + 100, now(), 0- FROM person FINAL- WHERE team_id = %(team_id)s AND id IN %(uuid_list)s- """,- {"team_id": team.id, "uuid_list": pg_uuids},- )- self.stdout.write(f" Marked {len(pg_uuids)} persons as deleted in ClickHouse")-- # Also mark any CH-only orphans with test properties- # (We can identify them by checking for properties.test_type which we didn't set for CH-only,- # but we can still clean up based on recent creation or by running the workflow)-- self.stdout.write(self.style.SUCCESS("\n✓ Cleanup complete"))- self.stdout.write("\nNote: CH-only orphans (without PG records) may still exist.")- self.stdout.write("Run the workflow with delete_ch_only_orphans=true to clean them up:")- self.stdout.write(- f" python manage.py start_temporal_workflow sync-person-distinct-ids "- f'\'{{"team_id": {team.id}, "dry_run": false, "delete_ch_only_orphans": true, "categorize_orphans": true}}\''- )-- def _insert_person_to_ch(self, team_id: int, person_uuid: str, version: int = 0):- """Insert a person directly into ClickHouse person table."""- sync_execute(- """- INSERT INTO person (id, team_id, properties, is_deleted, is_identified, version, _timestamp, _offset)- VALUES (%(uuid)s, %(team_id)s, '{}', 0, 0, %(version)s, now(), 0)- """,- {- "uuid": person_uuid,- "team_id": team_id,- "version": version,- },- )diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex fbdb6fc2dc32..dac2add4e669 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -133,10 +133,6 @@ from posthog.temporal.session_replay.surfacing_scoring_sweep import (SURFACING_SCORING_SWEEP_WORKFLOWS,)from posthog.temporal.sync_events_retention import SYNC_EVENTS_RETENTION_ACTIVITIES, SYNC_EVENTS_RETENTION_WORKFLOWS-from posthog.temporal.sync_person_distinct_ids import (- ACTIVITIES as SYNC_PERSON_DISTINCT_IDS_ACTIVITIES,- WORKFLOWS as SYNC_PERSON_DISTINCT_IDS_WORKFLOWS,-)from posthog.temporal.tests.utils.workflow import (ACTIVITIES as TEST_ACTIVITIES,WORKFLOWS as TEST_WORKFLOWS,@@ -371,7 +367,6 @@ _task_queue_specs = [+ PRODUCT_ANALYTICS_WORKFLOWS+ LLM_ANALYTICS_WORKFLOWS+ DLQ_REPLAY_WORKFLOWS- + SYNC_PERSON_DISTINCT_IDS_WORKFLOWS+ EXPERIMENTS_WORKFLOWS+ EXPERIMENT_CANARY_WORKFLOWS+ EXPERIMENT_ENROLLMENT_CENSUS_WORKFLOWS@@ -399,7 +394,6 @@ _task_queue_specs = [+ PRODUCT_ANALYTICS_ACTIVITIES+ LLM_ANALYTICS_ACTIVITIES+ DLQ_REPLAY_ACTIVITIES- + SYNC_PERSON_DISTINCT_IDS_ACTIVITIES+ EXPERIMENTS_ACTIVITIES+ EXPERIMENT_CANARY_ACTIVITIES+ EXPERIMENT_ENROLLMENT_CENSUS_ACTIVITIESdiff --git a/posthog/management/commands/start_temporal_workflow.py b/posthog/management/commands/start_temporal_workflow.pyindex dbeb8daee17f..f8a41ad92e2a 100644--- a/posthog/management/commands/start_temporal_workflow.py+++ b/posthog/management/commands/start_temporal_workflow.py@@ -23,7 +23,6 @@ from posthog.temporal.session_replay.rasterize_recording import RASTERIZE_RECORDfrom posthog.temporal.session_replay.replay_count_metrics import REPLAY_COUNT_METRICS_WORKFLOWSfrom posthog.temporal.session_replay.surfacing_scoring_sweep import SURFACING_SCORING_SWEEP_WORKFLOWSfrom posthog.temporal.sync_events_retention import SYNC_EVENTS_RETENTION_WORKFLOWS-from posthog.temporal.sync_person_distinct_ids import WORKFLOWS as SYNC_PERSON_DISTINCT_IDS_WORKFLOWSfrom posthog.temporal.tests.utils.workflow import WORKFLOWS as TEST_WORKFLOWSfrom posthog.temporal.usage_report import WORKFLOWS as USAGE_REPORTS_WORKFLOWSfrom posthog.temporal.weekly_digest import WORKFLOWS as WEEKLY_DIGEST_WORKFLOWS@@ -148,7 +147,6 @@ class Command(BaseCommand):+ AI_WORKFLOWS+ CONVERSATION_BACKFILL_WORKFLOWS+ SALESFORCE_ENRICHMENT_WORKFLOWS- + SYNC_PERSON_DISTINCT_IDS_WORKFLOWS+ TEST_WORKFLOWS+ COUNT_PLAYLIST_ITEMS_WORKFLOWS+ DELETE_RECORDINGS_WORKFLOWSdiff --git a/posthog/management/commands/test/test_backfill_distinct_id_overrides.py b/posthog/management/commands/test/test_backfill_distinct_id_overrides.pydeleted file mode 100644index 997667384f28..000000000000--- a/posthog/management/commands/test/test_backfill_distinct_id_overrides.py+++ /dev/null@@ -1,57 +0,0 @@-import uuid-import operator--from posthog.test.base import BaseTest, ClickhouseTestMixin--from posthog.clickhouse.client.execute import sync_execute-from posthog.management.commands.backfill_distinct_id_overrides import Backfill---class ExecuteBackfillTestCase(ClickhouseTestMixin, BaseTest):- def __run_test_backfill(self, dry_run: bool) -> None:- distinct_id = "override-me"-- rows_for_distinct_id = [- {"team_id": self.team.id, "distinct_id": distinct_id, "person_id": uuid.uuid4(), "version": version}- for version in range(3)- ]-- # never were overridden (version = 0), so no overrides should be created- rows_to_ignore = [- {"team_id": self.team.id, "distinct_id": f"ignore-me/{i}", "person_id": uuid.uuid4(), "version": 0}- for i in range(5)- ]-- sync_execute(- "INSERT INTO person_distinct_id2 (team_id, distinct_id, person_id, version) VALUES",- [*rows_for_distinct_id, *rows_to_ignore],- )-- # nothing should be in the override table yet- assert sync_execute(- "SELECT count() FROM person_distinct_id_overrides WHERE team_id = %(team_id)s",- {"team_id": self.team.id},- ) == [(0,)]-- Backfill(self.team.id).execute(dry_run=dry_run)-- read_columns = ["team_id", "distinct_id", "person_id", "version"]- distinct_id_override_rows = sync_execute(- f"""- SELECT {", ".join(read_columns)}- FROM person_distinct_id_overrides- WHERE team_id = %(team_id)s- """,- {"team_id": self.team.id},- )-- if not dry_run:- assert distinct_id_override_rows == [operator.itemgetter(*read_columns)(rows_for_distinct_id[-1])]- else:- assert distinct_id_override_rows == []-- def test_execute_backfill(self) -> None:- self.__run_test_backfill(dry_run=False)-- def test_execute_backfill_dry_run(self) -> None:- self.__run_test_backfill(dry_run=True)diff --git a/posthog/management/commands/test/test_backfill_persons_and_groups_on_events.py b/posthog/management/commands/test/test_backfill_persons_and_groups_on_events.pydeleted file mode 100644index ecd74aa515c1..000000000000--- a/posthog/management/commands/test/test_backfill_persons_and_groups_on_events.py+++ /dev/null@@ -1,109 +0,0 @@-from time import sleep-from uuid import UUID, uuid4--import pytest-from posthog.test.base import BaseTest, ClickhouseTestMixin--from django.conf import settings--from posthog.clickhouse.client import sync_execute-from posthog.conftest import create_clickhouse_tables-from posthog.management.commands.backfill_persons_and_groups_on_events import run_backfill-from posthog.models.event.sql import EVENTS_DATA_TABLE---def create_test_events(properties=""):- sync_execute(- f"""- INSERT INTO {EVENTS_DATA_TABLE()} (event, team_id, uuid, timestamp, distinct_id, properties)- VALUES- ('event1', 1, '{str(uuid4())}', now(), 'some_distinct_id', '{properties}')- ('event2', 1, '{str(uuid4())}', now(), 'some_distinct_id', '{properties}')- """- )---class TestBackfillPersonsAndGroupsOnEvents(BaseTest, ClickhouseTestMixin):- def tearDown(self):- self.recreate_database()- super().tearDown()-- def recreate_database(self):- sync_execute(f"DROP DATABASE {settings.CLICKHOUSE_DATABASE} SYNC")- sync_execute(f"CREATE DATABASE {settings.CLICKHOUSE_DATABASE}")- create_clickhouse_tables()-- def test_person_backfill(self):- self.recreate_database()-- create_test_events()-- person_id = uuid4()- person_props = '{ "foo": "bar" }'- sync_execute(- f"""- INSERT INTO person (id, team_id, properties)- VALUES- ('{str(person_id)}', 1, '{person_props}')- """- )-- sync_execute(- f"""- INSERT INTO person_distinct_id2 (person_id, distinct_id, team_id)- VALUES- ('{str(person_id)}', 'some_distinct_id', 1)- """- )-- events_before = sync_execute("select event, person_id, person_properties from events")- self.assertEqual(- events_before,- [- ("event1", UUID("00000000-0000-0000-0000-000000000000"), ""),- ("event2", UUID("00000000-0000-0000-0000-000000000000"), ""),- ],- )-- run_backfill({"team_id": 1, "live_run": True})-- # even running the backfill synchronusly on tests seems to not be enough to ensure it's done yet- sleep(10)-- events_after = sync_execute("select event, person_id, person_properties from events")- self.assertEqual(- events_after,- [- ("event1", person_id, '{ "foo": "bar" }'),- ("event2", person_id, '{ "foo": "bar" }'),- ],- )-- def test_groups_backfill(self):- self.recreate_database()-- create_test_events('{ "$group_0": "my_group" }')-- group_props = '{ "foo": "bar" }'- sync_execute(- f"""- INSERT INTO groups (group_type_index, group_key, group_properties)- VALUES- (0, 'my_group', '{group_props}')- """- )-- events_before = sync_execute("select event, $group_0, group0_properties from events")- self.assertEqual(events_before, [("event1", "my_group", ""), ("event2", "my_group", "")])-- run_backfill({"team_id": 1, "live_run": True})-- # even running the backfill synchronusly on tests seems to not be enough to ensure it's done yet- sleep(10)-- events_after = sync_execute("select event, $group_0, group0_properties from events")- self.assertEqual(- events_after,- [("event1", "my_group", group_props), ("event2", "my_group", group_props)],- )diff --git a/posthog/management/commands/test/test_persons_dedup.py b/posthog/management/commands/test/test_persons_dedup.pydeleted file mode 100644index 0659f35f0abe..000000000000--- a/posthog/management/commands/test/test_persons_dedup.py+++ /dev/null@@ -1,1531 +0,0 @@-from __future__ import annotations--import re-import json-import uuid as uuid_mod-import logging-from contextlib import contextmanager-from typing import Any--import pytest--from django.core.management import call_command-from django.core.management.base import CommandError--import psycopg-from structlog.testing import capture_logs--from posthog.management.commands import persons_dedup as persons_dedup_command-from posthog.persons_db import persons_db_connection--pytestmark = pytest.mark.django_db--TEAM = 987654--# The test database declares a UNIQUE (team_id, uuid) index, so it physically rejects the-# duplicate rows these tests need to seed. Drop to a non-unique index for the fixture and-# restore it afterwards. The duplicates this command repairs accumulated while production-# carried a non-unique index. Production enforces uniqueness, so the command operates on-# historical rows rather than newly created ones.-DROP_UNIQUE_UUID_INDEX = "DROP INDEX IF EXISTS posthog_person_new_uuid_idx"-CREATE_NON_UNIQUE_UUID_INDEX = "CREATE INDEX posthog_person_new_uuid_idx ON posthog_person (team_id, uuid)"-RESTORE_UNIQUE_UUID_INDEX = "CREATE UNIQUE INDEX posthog_person_new_uuid_idx ON posthog_person (team_id, uuid)"--# Production also carries foreign keys that rust/persons_migrations does NOT declare,-# and their ON DELETE behaviour is what makes this command dangerous or safe. Without-# recreating that drift here every safety assertion below would pass vacuously.-PROD_FK_DRIFT = [- (- "posthog_persondistinctid",- "test_pdi_person_fk",- "FOREIGN KEY (team_id, person_id) REFERENCES posthog_person(team_id, id) NOT VALID",- ),- (- "posthog_featureflaghashkeyoverride",- "test_ff_person_fk",- "FOREIGN KEY (team_id, person_id) REFERENCES posthog_person(team_id, id) ON DELETE CASCADE NOT VALID",- ),-]---def _uuid(n: int) -> str:- return str(uuid_mod.UUID(int=n))---def persons_conn():- with persons_db_connection(writer=True, autocommit=True) as conn:- _cleanup(conn)- with conn.cursor() as cur:- cur.execute(DROP_UNIQUE_UUID_INDEX)- cur.execute(CREATE_NON_UNIQUE_UUID_INDEX)- for table, name, definition in PROD_FK_DRIFT:- with conn.cursor() as cur:- cur.execute(f"ALTER TABLE {table} DROP CONSTRAINT IF EXISTS {name}")- cur.execute(f"ALTER TABLE {table} ADD CONSTRAINT {name} {definition}")- try:- yield conn- finally:- for table, name, _ in PROD_FK_DRIFT:- with conn.cursor() as cur:- cur.execute(f"ALTER TABLE {table} DROP CONSTRAINT IF EXISTS {name}")- _cleanup(conn)- with conn.cursor() as cur:- cur.execute(DROP_UNIQUE_UUID_INDEX)- cur.execute(RESTORE_UNIQUE_UUID_INDEX)---def _cleanup(conn: psycopg.Connection) -> None:- with conn.cursor() as cur:- cur.execute("DELETE FROM posthog_featureflaghashkeyoverride WHERE team_id = %s", (TEAM,))- cur.execute(- "DELETE FROM posthog_cohortpeople WHERE person_id IN (SELECT id FROM posthog_person WHERE team_id = %s)",- (TEAM,),- )- cur.execute("DELETE FROM posthog_persondistinctid WHERE team_id = %s", (TEAM,))- cur.execute("DELETE FROM posthog_person WHERE team_id = %s", (TEAM,))---def _add_person(- conn: psycopg.Connection,- uuid: str,- *,- properties: str = "{}",- version: int = 0,- is_identified: bool = False,- is_deleted: bool = False,-) -> int:- with conn.cursor() as cur:- cur.execute(- "INSERT INTO posthog_person "- "(created_at, properties, team_id, is_identified, uuid, version, is_deleted) "- "VALUES (now(), %s::jsonb, %s, %s, %s, %s, %s) RETURNING id",- (properties, TEAM, is_identified, uuid, version, is_deleted),- )- row = cur.fetchone()- assert row is not None- return int(row[0])---# One duplicate group: an unreferenced orphan plus the live row that must survive.-def _add_orphan_pair(conn: psycopg.Connection, uuid: str, distinct_id: str) -> int:- _add_person(conn, uuid)- live = _add_person(conn, uuid)- _add_distinct_id(conn, live, distinct_id)- return live---def _add_orphan_pair_ids(conn: psycopg.Connection, uuid: str, distinct_id: str) -> tuple[int, int]:- orphan = _add_person(conn, uuid)- live = _add_person(conn, uuid)- _add_distinct_id(conn, live, distinct_id)- return orphan, live---# Runs `action` on a second connection at the one moment that matters: after the command has-# cleared its pre-flight gates and before it opens the delete transaction. Every gate-failure-# path is unreachable without this, because staging excludes anything the gates would catch ---# only a concurrent writer can make a staged victim undeletable.-@contextmanager-def _concurrent_write_before_delete(monkeypatch, action):- real_gates = persons_dedup_command._gates- state = {"fired": False}-- 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, "_gates", gates_then_interfere)- yield lambda: state["fired"]---def _add_distinct_id(conn: psycopg.Connection, person_id: int, distinct_id: str, *, is_deleted: bool = False) -> None:- with conn.cursor() as cur:- cur.execute(- "INSERT INTO posthog_persondistinctid (team_id, person_id, distinct_id, version, is_deleted) "- "VALUES (%s, %s, %s, 0, %s)",- (TEAM, person_id, distinct_id, is_deleted),- )---def _add_flag_override(conn: psycopg.Connection, person_id: int, key: str, hash_key: str = "h") -> None:- with conn.cursor() as cur:- cur.execute(- "INSERT INTO posthog_featureflaghashkeyoverride (team_id, person_id, feature_flag_key, hash_key) "- "VALUES (%s, %s, %s, %s)",- (TEAM, person_id, key, hash_key),- )---def _add_cohort_member(conn: psycopg.Connection, person_id: int, cohort_id: int = 4242) -> None:- with conn.cursor() as cur:- cur.execute(- "INSERT INTO posthog_cohortpeople (cohort_id, person_id, version) VALUES (%s, %s, 0)",- (cohort_id, person_id),- )---def _cohort_rows(conn: psycopg.Connection) -> int:- return _count(- conn,- "SELECT count(*) FROM posthog_cohortpeople WHERE person_id IN "- "(SELECT id FROM posthog_person WHERE team_id = %s)",- (TEAM,),- )---def _orphaned_cohort_rows(conn: psycopg.Connection, cohort_id: int = 4242) -> int:- return _count(- conn,- "SELECT count(*) FROM posthog_cohortpeople cp WHERE cp.cohort_id = %s "- "AND NOT EXISTS (SELECT 1 FROM posthog_person p WHERE p.id = cp.person_id)",- (cohort_id,),- )---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("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:- with conn.cursor() as cur:- cur.execute(sql, params)- row = cur.fetchone()- return int(row[0]) if row else 0---def _persons(conn: psycopg.Connection) -> int:- return _count(conn, "SELECT count(*) FROM posthog_person WHERE team_id = %s", (TEAM,))---def _flag_overrides(conn: psycopg.Connection) -> int:- return _count(conn, "SELECT count(*) FROM posthog_featureflaghashkeyoverride WHERE team_id = %s", (TEAM,))---def _distinct_ids(conn: psycopg.Connection) -> int:- return _count(conn, "SELECT count(*) FROM posthog_persondistinctid WHERE team_id = %s", (TEAM,))---def _dup_groups(conn: psycopg.Connection) -> int:- return _count(- conn,- "SELECT count(*) FROM (SELECT uuid FROM posthog_person WHERE team_id = %s GROUP BY uuid HAVING count(*) > 1) x",- (TEAM,),- )---def _run(mode: str, tmp_path: Any, **kwargs: Any) -> None:- kwargs.setdefault("sleep_ms", 0)- call_command("persons_dedup", mode=mode, team=TEAM, outdir=str(tmp_path), **kwargs)---class TestPersonsDedupFixture:- def test_fixture_reproduces_the_production_cascade(self, persons_conn, tmp_path):- # Guards the fixture itself. If the prod FK drift is ever reconciled into- # rust/persons_migrations and this ALTER stops matching production, every safety- # test below would silently start passing for the wrong reason.- person = _add_person(persons_conn, _uuid(1))- _add_flag_override(persons_conn, person, "flag-a")- assert _flag_overrides(persons_conn) == 1-- with persons_conn.cursor() as cur:- cur.execute("DELETE FROM posthog_person WHERE team_id = %s AND id = %s", (TEAM, person))-- assert _flag_overrides(persons_conn) == 0, "prod FK is ON DELETE CASCADE; fixture must reproduce it"-- def test_fixture_reproduces_the_missing_unique_index(self, persons_conn, tmp_path):- # The whole defect: production allows two rows to share (team_id, uuid). The- # tracked migrations declare that index UNIQUE, so if this fixture ever stops- # recreating it non-unique, every duplicate scenario below becomes unseedable- # and the suite would fail loudly rather than pass vacuously.- uuid = _uuid(3)- _add_person(persons_conn, uuid)- _add_person(persons_conn, uuid)-- assert _dup_groups(persons_conn) == 1-- def test_fixture_reproduces_the_production_delete_block(self, persons_conn, tmp_path):- person = _add_person(persons_conn, _uuid(2))- _add_distinct_id(persons_conn, person, "did-block")-- with pytest.raises(psycopg.errors.ForeignKeyViolation):- with persons_conn.cursor() as cur:- cur.execute("DELETE FROM posthog_person WHERE team_id = %s AND id = %s", (TEAM, person))---class TestPersonsDedupDeleteOnly:- def test_deletes_unreferenced_duplicate_and_keeps_the_live_row(self, persons_conn, tmp_path):- uuid = _uuid(10)- orphan = _add_person(persons_conn, uuid, properties='{"email": "keep"}')- live = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, live, "did-10")-- _run("delete-unreferenced", tmp_path, apply=True)-- assert _dup_groups(persons_conn) == 0- assert _persons(persons_conn) == 1- assert _distinct_ids(persons_conn) == 1- remaining = _count(persons_conn, "SELECT id FROM posthog_person WHERE team_id = %s", (TEAM,))- assert remaining == live, "the row owning the distinct id must survive, not the orphan"- assert orphan != live-- def test_refuses_to_delete_a_referenced_row(self, persons_conn, tmp_path):- # Both rows own a distinct ID, so neither is unreachable. Nothing may be removed.- uuid = _uuid(11)- a = _add_person(persons_conn, uuid)- b = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, a, "did-11a")- _add_distinct_id(persons_conn, b, "did-11b")-- _run("delete-unreferenced", tmp_path, apply=True)-- assert _persons(persons_conn) == 2- assert _dup_groups(persons_conn) == 1-- def test_dry_run_writes_nothing(self, persons_conn, tmp_path):- uuid = _uuid(12)- _add_person(persons_conn, uuid)- live = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, live, "did-12")-- _run("delete-unreferenced", tmp_path)-- assert _persons(persons_conn) == 2- assert list(tmp_path.glob("*.jsonl")) == []-- def test_backup_captures_deleted_person_properties(self, persons_conn, tmp_path):- uuid = _uuid(13)- _add_person(persons_conn, uuid, properties='{"email": "gone"}')- live = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, live, "did-13")-- _run("delete-unreferenced", tmp_path, apply=True)-- lines = [line for f in tmp_path.glob("*.jsonl") for line in f.read_text().splitlines()]- persons = [json.loads(line) for line in lines]- assert any(p["_kind"] == "person" and p["properties"] == {"email": "gone"} for p in persons)-- def test_backup_file_is_owner_only(self, persons_conn, tmp_path):- # The backup holds person properties; on a shared pod filesystem a default-umask- # 0644 file would expose them to any local account.- uuid = _uuid(15)- _add_person(persons_conn, uuid)- live = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, live, "did-15")-- _run("delete-unreferenced", tmp_path, apply=True)-- files = list(tmp_path.glob("*.jsonl"))- assert files, "apply must write a backup file"- assert (files[0].stat().st_mode & 0o777) == 0o600-- def test_is_idempotent(self, persons_conn, tmp_path):- uuid = _uuid(14)- _add_person(persons_conn, uuid)- live = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, live, "did-14")-- _run("delete-unreferenced", tmp_path, apply=True)- _run("delete-unreferenced", tmp_path, apply=True)-- assert _persons(persons_conn) == 1---class TestPersonsDedupBatching:- # Every other case here stages one or two victims against the default batch size of 500,- # so the drain loop only ever runs once. A real team runs it hundreds of times, where a- # bug in the take/retire cycle -- retiring the wrong rows, or not truncating the batch- # table -- would strand most of that team while still reporting success. These are the- # only cases where a second populated batch happens at all.- def test_drains_every_batch_when_victims_exceed_batch_size(self, persons_conn, tmp_path):- for n in range(5):- _add_orphan_pair(persons_conn, _uuid(40 + n), f"did-40-{n}")- assert _persons(persons_conn) == 10-- _run("delete-unreferenced", tmp_path, apply=True, batch_size=2)-- assert _persons(persons_conn) == 5- assert _dup_groups(persons_conn) == 0- assert _distinct_ids(persons_conn) == 5- backed_up = [json.loads(line) for f in tmp_path.glob("*.jsonl") for line in f.read_text().splitlines()]- assert len([r for r in backed_up if r["_kind"] == "person"]) == 5, "every deleted row must be recoverable"-- def test_dry_run_checks_every_batch_not_just_the_first(self, persons_conn, tmp_path):- # A dry run that returned after the first batch reported dry_run_batch_ok having- # gated batch_size victims out of the whole staged set, which an operator reads as- # clearance for the --apply run that follows.- for n in range(3):- _add_orphan_pair(persons_conn, _uuid(50 + n), f"did-50-{n}")-- with capture_logs() as logs:- _run("delete-unreferenced", tmp_path, batch_size=1)-- assert _persons(persons_conn) == 6, "a dry run must delete nothing"- assert list(tmp_path.glob("*.jsonl")) == []- summary = next(entry for entry in logs if entry["event"] == "persons_dedup.dry_run_ok")- assert summary["checked"] == 3- assert summary["batches"] == 3---class TestPersonsDedupConcurrentWriters:- # The in-transaction gates are the last thing standing between a wrong row and a silent- # cascade into feature-flag overrides, and they are the only safety checks in this command- # that a single-threaded test can never reach: staging excludes everything they catch, so- # they fire only when a concurrent writer changes a staged victim mid-run. These two cases- # drive that writer deterministically -- no threads, no sleeps.-- def test_a_victim_that_becomes_reachable_is_dropped_and_the_run_continues(- self, persons_conn, tmp_path, monkeypatch- ):- # A returning user attaches a distinct ID to the orphan after it was staged. It is now- # a live person, so deleting it would take its overrides with it.- orphan, live = _add_orphan_pair_ids(persons_conn, _uuid(60), "did-60")-- def attach_a_mapping(other):- _add_distinct_id(other, orphan, "did-60-returning")-- with _concurrent_write_before_delete(monkeypatch, attach_a_mapping) as fired:- with capture_logs() as logs:- _run("delete-unreferenced", tmp_path, apply=True)-- assert fired(), "the interfering write never ran; the test proves nothing"- assert _persons(persons_conn) == 2, "the newly reachable row must not be deleted"- assert any(entry["event"] == "persons_dedup.batch_raced" for entry in logs)- assert any(entry["event"] == "persons_dedup.done" for entry in logs), "the run must finish, not abort"-- def test_a_group_that_loses_its_survivor_is_dropped_and_the_run_continues(- self, persons_conn, tmp_path, monkeypatch- ):- # Something else deletes the survivor after staging. The staged victim is now the only- # row holding that key, so it is no longer a duplicate and must not be deleted either.- orphan, live = _add_orphan_pair_ids(persons_conn, _uuid(61), "did-61")-- def delete_the_survivor(other):- with other.cursor() as cur:- cur.execute("DELETE FROM posthog_persondistinctid WHERE team_id = %s AND person_id = %s", (TEAM, live))- cur.execute("DELETE FROM posthog_person WHERE team_id = %s AND id = %s", (TEAM, live))-- with _concurrent_write_before_delete(monkeypatch, delete_the_survivor) as fired:- with capture_logs() as logs:- _run("delete-unreferenced", tmp_path, apply=True)-- assert fired(), "the interfering write never ran; the test proves nothing"- remaining = _count(persons_conn, "SELECT id FROM posthog_person WHERE team_id = %s", (TEAM,))- assert remaining == orphan, "the last row holding the key must survive"- assert _persons(persons_conn) == 1- assert any(entry["event"] == "persons_dedup.done" for entry in logs), "the run must finish, not abort"---class TestPersonsDedupRepair:- # The shape every merge-required group in the production census shared: one row owns the- # distinct ID, the other owns a flag override, neither owns both. This is also the only- # place the two write modes disagree, so both arms are pinned here -- repair takes the- # unreachable row and cascades its dead override away, delete-unreferenced refuses it- # because the override is a reference. Swapping either staging predicate for the other- # silently changes which rows a production run destroys.- @pytest.mark.parametrize(- "mode,expected_persons,expected_overrides,expected_dup_groups",- [- ("repair", 1, 0, 0),- ("delete-unreferenced", 2, 1, 1),- ],- )- def test_mode_divergence_on_the_production_shape(- self, persons_conn, tmp_path, mode, expected_persons, expected_overrides, expected_dup_groups- ):- uuid = _uuid(20)- live = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, live, "did-20")- stranded = _add_person(persons_conn, uuid)- _add_flag_override(persons_conn, stranded, "flag-20")-- _run(mode, tmp_path, apply=True)-- assert _persons(persons_conn) == expected_persons- assert _flag_overrides(persons_conn) == expected_overrides- assert _dup_groups(persons_conn) == expected_dup_groups- assert _distinct_ids(persons_conn) == 1-- def test_survivor_is_the_distinct_id_owner_even_when_it_is_the_newer_row(self, persons_conn, tmp_path):- # Production's actual shape: the distinct id points at the NEWER row in every- # measured group, and the stranded older row is the one carrying the override.- # Ranking must prefer the distinct-id owner, not the oldest or lowest id --- # picking the wrong survivor would delete the row the product can still reach.- uuid = _uuid(24)- stranded = _add_person(persons_conn, uuid)- _add_flag_override(persons_conn, stranded, "flag-24")- live = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, live, "did-24")-- _run("repair", tmp_path, apply=True)-- assert _persons(persons_conn) == 1- survivor = _count(persons_conn, "SELECT id FROM posthog_person WHERE team_id = %s", (TEAM,))- assert survivor == live, "the row owning the distinct id must survive even when it is newer"- assert _distinct_ids(persons_conn) == 1-- def test_leaves_a_reachable_override_alone(self, persons_conn, tmp_path):- # Same shape, except the override sits on the row that owns the distinct ID, so- # it IS reachable and must survive untouched.- uuid = _uuid(21)- live = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, live, "did-21")- _add_flag_override(persons_conn, live, "flag-21")- _add_person(persons_conn, uuid)-- _run("repair", tmp_path, apply=True)-- assert _persons(persons_conn) == 1- assert _flag_overrides(persons_conn) == 1-- def test_refuses_groups_where_two_rows_own_distinct_ids(self, persons_conn, tmp_path):- uuid = _uuid(22)- a = _add_person(persons_conn, uuid)- b = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, a, "did-22a")- _add_distinct_id(persons_conn, b, "did-22b")- _add_flag_override(persons_conn, b, "flag-22")-- _run("repair", tmp_path, apply=True)-- assert _persons(persons_conn) == 2- assert _flag_overrides(persons_conn) == 1-- def test_backup_captures_cascaded_flag_overrides(self, persons_conn, tmp_path):- uuid = _uuid(23)- live = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, live, "did-23")- stranded = _add_person(persons_conn, uuid)- _add_flag_override(persons_conn, stranded, "flag-23", hash_key="hk-23")-- _run("repair", tmp_path, apply=True)-- lines = [line for f in tmp_path.glob("*.jsonl") for line in f.read_text().splitlines()]- records = [json.loads(line) for line in lines]- assert any(- r["_kind"] == "featureflaghashkeyoverride" and r["key"] == "flag-23" and r["value"] == "hk-23"- for r in records- ), "a cascaded override must be recoverable from the backup"-- def test_removes_and_backs_up_a_stranded_cohort_membership(self, persons_conn, tmp_path):- # posthog_cohortpeople has no foreign key, so the cascade will not clear it and a- # missed delete leaves a row pointing at a person that no longer exists.- uuid = _uuid(25)- live = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, live, "did-25")- stranded = _add_person(persons_conn, uuid)- _add_cohort_member(persons_conn, stranded)-- _run("repair", tmp_path, apply=True)-- assert _persons(persons_conn) == 1- assert _orphaned_cohort_rows(persons_conn) == 0- records = [json.loads(line) for f in tmp_path.glob("*.jsonl") for line in f.read_text().splitlines()]- assert any(r["_kind"] == "cohortpeople" and r["person_id"] == stranded for r in records)-- def test_keeps_a_reachable_cohort_membership(self, persons_conn, tmp_path):- uuid = _uuid(26)- live = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, live, "did-26")- _add_cohort_member(persons_conn, live)- _add_person(persons_conn, uuid)-- _run("repair", tmp_path, apply=True)-- assert _persons(persons_conn) == 1- assert _cohort_rows(persons_conn) == 1-- def test_deletes_an_orphan_stranded_inside_a_merge_required_group(self, persons_conn, tmp_path):- # Two live rows need a real merge, which this command refuses. The third row owns no- # mapping and is dead on exactly the same terms as any other orphan -- its deadness has- # nothing to do with what the other two are doing. Skipping it left known-dead rows- # behind whose cohort memberships still counted toward the cohort size shown in the UI.- uuid = _uuid(90)- a = _add_person(persons_conn, uuid)- b = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, a, "did-90a")- _add_distinct_id(persons_conn, b, "did-90b")- _add_person(persons_conn, uuid)-- _run("repair", tmp_path, apply=True)-- assert _persons(persons_conn) == 2, "the orphan goes, both live rows stay"- remaining = _count(- persons_conn,- "SELECT count(*) FROM posthog_person WHERE team_id = %s AND id = ANY(%s)",- (TEAM, [a, b]),- )- assert remaining == 2- assert _dup_groups(persons_conn) == 1, "the group still needs a merge and is still reported"-- def test_the_merge_required_group_is_still_reported_after_its_orphan_is_removed(self, persons_conn, tmp_path):- uuid = _uuid(91)- a = _add_person(persons_conn, uuid)- b = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, a, "did-91a")- _add_distinct_id(persons_conn, b, "did-91b")- _add_person(persons_conn, uuid)-- _run("repair", tmp_path, apply=True)- with capture_logs() as logs:- _run("verify", tmp_path)-- result = next(entry for entry in logs if entry["event"] == "persons_dedup.verify")- assert result["blocked_groups"] == 1- assert result["resolvable_groups"] == 0, "removing the orphan must not make the group look resolvable"-- def test_all_orphan_group_keeps_the_identified_row(self, persons_conn, tmp_path):- # A sizeable share of real duplicate groups have no member owning a distinct ID, so- # the leading (n_did > 0) term in the survivor ranking cannot break the tie and the- # rest of it decides alone. Nothing else exercises that branch, and getting it wrong- # discards the richer row while keeping an empty one.- uuid = _uuid(28)- plain = _add_person(persons_conn, uuid)- identified = _add_person(persons_conn, uuid, is_identified=True)-- _run("repair", tmp_path, apply=True)-- assert _persons(persons_conn) == 1- survivor = _count(persons_conn, "SELECT id FROM posthog_person WHERE team_id = %s", (TEAM,))- assert survivor == identified, "is_identified must outrank the plain row"- assert plain != identified-- def test_never_deletes_a_tombstoned_row(self, persons_conn, tmp_path):- # is_deleted is a revival marker, not a dead row: the write path reuses it so the- # revived key outranks its own ClickHouse tombstone, which needs the version this- # row holds. Deleting it would drop that version floor silently.- uuid = _uuid(29)- live = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, live, "did-29")- _add_person(persons_conn, uuid, is_deleted=True)-- _run("repair", tmp_path, apply=True)-- assert _persons(persons_conn) == 2, "the tombstone must be left alone"- assert _dup_groups(persons_conn) == 1-- def test_a_tombstone_never_outranks_a_live_row(self, persons_conn, tmp_path):- # Neither row owns a distinct ID, so the leading term of the ranking ties and the- # tombstone would win on is_identified and version -- making the live row the victim- # and deleting the only row of the two that can still be revived into service.- uuid = _uuid(33)- _add_person(persons_conn, uuid, is_deleted=True, version=99, is_identified=True)- live = _add_person(persons_conn, uuid)-- _run("repair", tmp_path, apply=True)-- survivors = _count(- persons_conn, "SELECT count(*) FROM posthog_person WHERE team_id = %s AND id = %s", (TEAM, live)- )- assert survivors == 1, "the live row must outrank a higher-version identified tombstone"- assert _persons(persons_conn) == 2, "and the tombstone itself is never staged"---class TestPersonsDedupSurvivorSelection:- def test_a_row_reachable_only_through_a_tombstoned_mapping_loses_to_a_live_one(self, persons_conn, tmp_path):- # The flag path requires pdi.is_deleted = false, so a tombstoned mapping does not make- # a person reachable. Ranking on the raw mapping count would tie these two and let the- # tiebreak keep the row the product cannot see.- uuid = _uuid(80)- tombstoned_owner = _add_person(persons_conn, uuid, is_identified=True, version=99)- _add_distinct_id(persons_conn, tombstoned_owner, "did-80-dead", is_deleted=True)- live = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, live, "did-80-live")-- _run("classify", tmp_path)-- survivor = _count(- persons_conn,- "SELECT id FROM posthog_person p WHERE p.team_id = %s AND p.uuid = %s "- "AND EXISTS (SELECT 1 FROM posthog_persondistinctid d "- "WHERE d.person_id = p.id AND NOT d.is_deleted)",- (TEAM, uuid),- )- assert survivor == live- # Neither is deletable: both own a mapping, so the foreign key would block either way.- _run("repair", tmp_path, apply=True)- assert _persons(persons_conn) == 2-- def test_classify_writes_actionable_detail_for_groups_it_refuses(self, persons_conn, tmp_path):- # A count of blocked groups cannot be acted on. Resolving one needs to know which rows- # it holds, which are still reachable, and what hangs off them.- uuid = _uuid(81)- a = _add_person(persons_conn, uuid)- b = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, a, "did-81a")- _add_distinct_id(persons_conn, b, "did-81b")- _add_flag_override(persons_conn, b, "flag-81")-- _run("classify", tmp_path)-- dumps = list(tmp_path.glob("blocked_team_*.jsonl"))- assert dumps, "a refused group must leave a record behind"- records = [json.loads(line) for line in dumps[0].read_text().splitlines()]- assert len(records) == 1- record = records[0]- assert record["reason"] == "multiple_reachable_rows"- assert record["reachable_owners"] == 2- assert record["flag_overrides"] == 1- assert sorted(record["reachable_ids"]) == sorted([a, b]), "both live rows must be named"-- def test_classify_writes_nothing_when_every_group_is_resolvable(self, persons_conn, tmp_path):- _add_orphan_pair(persons_conn, _uuid(82), "did-82")-- _run("classify", tmp_path)-- assert list(tmp_path.glob("blocked_team_*.jsonl")) == []-- def test_a_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")- _add_person(persons_conn, uuid, is_deleted=True)-- _run("classify", tmp_path)-- records = [- json.loads(line) for dump in tmp_path.glob("blocked_team_*.jsonl") for line in dump.read_text().splitlines()- ]- assert len(records) == 1- assert records[0]["reason"] == "tombstoned_member"-- def test_two_distinct_id_owners_are_blocked_even_when_one_is_unreachable(self, persons_conn, tmp_path):- # live_owners is what refuses the group; reachable_owners only says whether the product- # can still resolve both. A reason keyed on reachable_owners alone called this 'other'.- uuid = _uuid(84)- survivor = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, survivor, "did-84")- dead_owner = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, dead_owner, "did-84-dead", is_deleted=True)-- _run("classify", tmp_path)-- records = [- json.loads(line) for dump in tmp_path.glob("blocked_team_*.jsonl") for line in dump.read_text().splitlines()- ]- assert len(records) == 1- assert records[0]["reason"] == "multiple_distinct_id_owners"- assert records[0]["live_owners"] == 2- assert records[0]["reachable_owners"] == 1- # 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---def _version(conn: psycopg.Connection, person_id: int) -> int:- return _count(conn, "SELECT version FROM posthog_person WHERE id = %s", (person_id,))---class TestPersonsDedupSurvivorVersionFloor:- # ClickHouse keys person rows on (team_id, uuid) and resolves them with argMax(..., version),- # so both members of a duplicate group compete under one key. The survivor rule ranks- # reachability above version, so the row we keep is routinely the lower-versioned one and its- # later updates lose to the row we just deleted. These cover the raise that prevents that.-- @pytest.mark.parametrize(- "victim_version,survivor_version,raised",- [(1500, 3, True), (5, 5, True), (5, 88, False)],- ids=["survivor below the ceiling", "survivor level with it", "survivor above it"],- )- def test_a_survivor_is_raised_only_when_a_victim_outranks_it(- self, persons_conn, tmp_path, victim_version, survivor_version, raised- ):- # Level with the ceiling still has to be raised: equal versions tie in ClickHouse and- # ReplacingMergeTree picks between them arbitrarily, so the survivor has to end up- # strictly above. Tightening the guard to a strict "<" would leave that tie standing.- # Above the ceiling is left alone rather than inflated for no gain.- uuid = _uuid(200 if raised else 202)- orphan = _add_person(persons_conn, uuid, version=victim_version)- survivor = _add_person(persons_conn, uuid, version=survivor_version)- _add_distinct_id(persons_conn, survivor, f"did-{200 if raised else 202}")-- _run("delete-unreferenced", tmp_path, apply=True, raise_survivor_version=True)-- assert _persons(persons_conn) == 1- assert _count(persons_conn, "SELECT count(*) FROM posthog_person WHERE id = %s", (orphan,)) == 0- expected = victim_version + persons_dedup_command.SURVIVOR_VERSION_MARGIN if raised else survivor_version- assert _version(persons_conn, survivor) == expected-- def test_the_raise_clears_every_victim_in_a_group_not_just_one(self, persons_conn, tmp_path):- # The ceiling is a max over the group's victims. Taking any single victim's version- # would leave the survivor below a sibling that also wrote to the same ClickHouse key.- uuid = _uuid(201)- _add_person(persons_conn, uuid, version=40)- _add_person(persons_conn, uuid, version=900)- _add_person(persons_conn, uuid, version=7)- survivor = _add_person(persons_conn, uuid, version=0)- _add_distinct_id(persons_conn, survivor, "did-201")-- _run("delete-unreferenced", tmp_path, apply=True, raise_survivor_version=True)-- assert _persons(persons_conn) == 1- assert _version(persons_conn, survivor) == 900 + persons_dedup_command.SURVIVOR_VERSION_MARGIN-- def test_a_survivor_already_above_its_victims_is_left_alone(self, persons_conn, tmp_path):- # Raising unconditionally would inflate the counter of every survivor that never had- # the problem, for no gain.- uuid = _uuid(202)- _add_person(persons_conn, uuid, version=5)- survivor = _add_person(persons_conn, uuid, version=88)- _add_distinct_id(persons_conn, survivor, "did-202")-- _run("delete-unreferenced", tmp_path, apply=True, raise_survivor_version=True)-- assert _version(persons_conn, survivor) == 88-- def test_a_merge_required_group_keeps_both_versions_untouched(self, persons_conn, tmp_path):- # Two reachable rows plus an unreachable third. Repair may remove the third, but giving- # both survivors the same version would make their ClickHouse rows tie rather than- # resolve, so the group is left for the merge pass.- uuid = _uuid(203)- unreachable = _add_person(persons_conn, uuid, version=770)- a = _add_person(persons_conn, uuid, version=2)- b = _add_person(persons_conn, uuid, version=4)- _add_distinct_id(persons_conn, a, "did-203a")- _add_distinct_id(persons_conn, b, "did-203b")-- _run("repair", tmp_path, apply=True, raise_survivor_version=True)-- assert _count(persons_conn, "SELECT count(*) FROM posthog_person WHERE id = %s", (unreachable,)) == 0- assert _version(persons_conn, a) == 2- assert _version(persons_conn, b) == 4-- @pytest.mark.parametrize(- "kwargs,raised",- [({}, True), ({"raise_survivor_version": False}, False)],- ids=["on by default", "--no-raise-survivor-version opts out"],- )- def test_the_raise_is_on_unless_a_run_opts_out(self, persons_conn, tmp_path, kwargs, raised):- # A run that has to remember a flag to stay correct will eventually forget it, and the- # cost of forgetting is a survivor whose ClickHouse row never updates again. The opt-out- # still has to work, because it is the rollback if the wider lock ever contends.- uuid = _uuid(204)- _add_person(persons_conn, uuid, version=600)- survivor = _add_person(persons_conn, uuid, version=1)- _add_distinct_id(persons_conn, survivor, "did-204")-- _run("delete-unreferenced", tmp_path, apply=True, **kwargs)-- assert _persons(persons_conn) == 1- expected = 600 + persons_dedup_command.SURVIVOR_VERSION_MARGIN if raised else 1- assert _version(persons_conn, survivor) == expected-- def test_a_dry_run_counts_the_raises_without_making_them(self, persons_conn, tmp_path):- # The flag has to be measurable before it writes to a row live ingestion also writes.- uuid = _uuid(205)- _add_person(persons_conn, uuid, version=500)- survivor = _add_person(persons_conn, uuid, version=0)- _add_distinct_id(persons_conn, survivor, "did-205")-- with capture_logs() as logs:- _run("delete-unreferenced", tmp_path, raise_survivor_version=True)-- assert _persons(persons_conn) == 2, "a dry run deletes nothing"- assert _version(persons_conn, survivor) == 0, "a dry run raises nothing"- dry = [log for log in logs if log["event"] == "persons_dedup.dry_run_ok"]- assert dry and dry[0]["survivors_to_raise"] == 1-- def test_the_raise_is_rolled_back_with_the_delete(self, persons_conn, tmp_path, monkeypatch):- # The raise sits inside the delete transaction. If a later statement aborts it, a- # survivor left carrying a raised version would claim a ClickHouse ceiling for rows- # that were never removed.- uuid = _uuid(206)- _add_person(persons_conn, uuid, version=300)- survivor = _add_person(persons_conn, uuid, version=0)- _add_distinct_id(persons_conn, survivor, "did-206")-- def _explode(*args: Any, **kwargs: Any) -> None:- raise RuntimeError("boom")-- monkeypatch.setattr(persons_dedup_command.Command, "_backup", _explode)- with pytest.raises(RuntimeError):- _run("delete-unreferenced", tmp_path, apply=True, raise_survivor_version=True)-- assert _persons(persons_conn) == 2- assert _version(persons_conn, survivor) == 0-- @pytest.mark.parametrize(- "raise_flag,expect_locked",- [(True, True), (False, False)],- ids=["flag on locks the survivor", "flag off leaves it alone"],- )- def test_the_survivor_lock_is_taken_up_front_and_only_when_asked(- self, persons_conn, tmp_path, monkeypatch, raise_flag, expect_locked- ):- # The raise runs after the gates and an fsync'd backup. Taking the survivor's lock there- # rather than up front reopens a deadlock: ingestion's updatePersonsBatch matches on- # (team_id, uuid), so one statement needs both rows, and it can hold the survivor while- # blocking on our victim. Probing during the backup proves the lock is already held.- # The off case guards the other half -- the wider lock must not be paid by runs that did- # not ask for it.- uuid = _uuid(207 if raise_flag else 208)- _add_person(persons_conn, uuid, version=400)- survivor = _add_person(persons_conn, uuid, version=0)- _add_distinct_id(persons_conn, survivor, f"did-{207 if raise_flag else 208}")-- observed: dict[str, Any] = {}- real_backup = persons_dedup_command.Command._backup-- def backup_then_probe(self, conn, team, path):- result = real_backup(self, conn, team, path)- with persons_db_connection(writer=True, autocommit=True) as other:- with other.cursor() as cur:- # Session-level, not SET LOCAL: this connection is in autocommit, where- # LOCAL is discarded with the implicit transaction and the probe would- # wait forever instead of failing fast.- cur.execute("SET lock_timeout = '250ms'")- try:- cur.execute("SELECT id FROM posthog_person WHERE id = %s FOR UPDATE", (survivor,))- observed["locked"] = False- except psycopg.errors.LockNotAvailable:- observed["locked"] = True- return result-- monkeypatch.setattr(persons_dedup_command.Command, "_backup", backup_then_probe)- _run("delete-unreferenced", tmp_path, apply=True, raise_survivor_version=raise_flag)-- assert observed["locked"] is expect_locked- expected_version = 400 + persons_dedup_command.SURVIVOR_VERSION_MARGIN if raise_flag else 0- assert _version(persons_conn, survivor) == expected_version-- def test_the_update_grant_is_only_required_when_the_flag_is_set(self):- # The command runs today without UPDATE on posthog_person. Demanding it unconditionally- # would abort every run whose role was granted exactly what the old modes needed.- assert ("posthog_person", "UPDATE") not in persons_dedup_command.WRITE_PRIVILEGES- assert ("posthog_person", "UPDATE") in persons_dedup_command.SURVIVOR_VERSION_PRIVILEGES- assert set(persons_dedup_command.WRITE_PRIVILEGES) < set(persons_dedup_command.SURVIVOR_VERSION_PRIVILEGES)---class TestPersonsDedupVerify:- def test_verify_fails_while_resolvable_duplicates_remain(self, persons_conn, tmp_path):- # An orphan repair would have taken: work is genuinely outstanding.- _add_orphan_pair(persons_conn, _uuid(30), "did-30")-- with pytest.raises(CommandError, match="resolvable duplicate group"):- _run("verify", tmp_path)-- def test_verify_accepts_a_remainder_only_this_command_cannot_resolve(self, persons_conn, tmp_path):- # Both rows own a distinct ID, so this needs a real person merge -- a separate- # workstream. Raising here made verify useless as a release gate on exactly the- # teams that have such groups, because its failure was indistinguishable from- # "the dedup run did not finish".- uuid = _uuid(31)- a = _add_person(persons_conn, uuid)- b = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, a, "did-31a")- _add_distinct_id(persons_conn, b, "did-31b")-- with capture_logs() as logs:- _run("verify", tmp_path)-- result = next(entry for entry in logs if entry["event"] == "persons_dedup.verify")- assert result["duplicate_groups"] == 1- assert result["blocked_groups"] == 1- assert result["resolvable_groups"] == 0-- def test_verify_passes_once_clean(self, persons_conn, tmp_path):- person = _add_person(persons_conn, _uuid(32))- _add_distinct_id(persons_conn, person, "did-32")-- _run("verify", tmp_path)-- def test_batch_size_must_be_positive(self, persons_conn, tmp_path):- # LIMIT 0 stages nothing, so the run would exit reporting success on a team that- # still has duplicates -- indistinguishable from "already clean".- uuid = _uuid(32)- _add_person(persons_conn, uuid)- live = _add_person(persons_conn, uuid)- _add_distinct_id(persons_conn, live, "did-32")-- with pytest.raises(CommandError, match="at least 1"):- _run("delete-unreferenced", tmp_path, apply=True, batch_size=0)-- assert _persons(persons_conn) == 2-- def test_apply_is_rejected_for_read_only_modes(self, persons_conn, tmp_path):- with pytest.raises(CommandError, match="meaningless"):- _run("verify", tmp_path, apply=True)---class TestPersonsDedupTargetGuard:- def test_refuses_to_run_when_the_persons_url_is_unset(self, monkeypatch, tmp_path):- # Unset, posthog.persons_db builds a localhost URL from PG*. On a deployed pod those- # point at the main cluster, so a silent fallback aims a destructive command at the- # wrong database. It must refuse rather than connect.- monkeypatch.delenv("PERSONS_DB_WRITER_URL", raising=False)- monkeypatch.delenv("PERSONS_DB_READER_URL", raising=False)-- with pytest.raises(CommandError, match="PERSONS_DB_WRITER_URL is not set"):- _run("repair", tmp_path, apply=True)-- def test_logs_the_host_and_dbname_it_is_about_to_modify(self, persons_conn, tmp_path):- # The operator drives this by hand against production; host plus dbname is how they- # confirm the toolbox is pointed at persons and not the main cluster.- with capture_logs() as logs:- _run("classify", tmp_path)-- target = [entry for entry in logs if entry["event"] == "persons_dedup.target"]- assert len(target) == 1, "every run must say which database it targets"- assert target[0]["dbname"]- assert "password" not in str(target[0]), "the log line must not carry credentials"---class TestPersonsDedupLogVisibility:- def test_info_records_survive_the_posthog_logger_clamp(self):- # posthoganalytics calls logging.getLogger("posthog").setLevel(WARNING) at client init,- # which happens during django.setup(). Without an explicit level on this module's logger- # every INFO record is dropped, and three production runs of this command left no record- # of what they did. structlog's capture_logs() replaces the processor chain, so it cannot- # see this -- the assertion has to go through a real stdlib handler.- parent = logging.getLogger("posthog")- module_logger = logging.getLogger(persons_dedup_command.__name__)- captured: list[logging.LogRecord] = []-- class _Collector(logging.Handler):- def emit(self, record: logging.LogRecord) -> None:- captured.append(record)-- handler = _Collector()- original_level = parent.level- original_disabled = module_logger.disabled- original_global_disable = logging.root.manager.disable- parent.setLevel(logging.WARNING)- # Unrelated suites in the same worker reconfigure logging globally (dictConfig with- # disable_existing_loggers, logging.disable), which suppresses every record regardless- # of level. Clear both so the assertion isolates the one thing this test guards: the- # module's own level beating the parent clamp.- module_logger.disabled = False- logging.disable(logging.NOTSET)- module_logger.addHandler(handler)- try:- persons_dedup_command.logger.info("persons_dedup.log_visibility_probe", team_id=1)- finally:- module_logger.removeHandler(handler)- module_logger.disabled = original_disabled- logging.disable(original_global_disable)- parent.setLevel(original_level)-- assert captured, "INFO records are dropped, so a production run would leave no log"- assert captured[0].levelno == logging.INFO---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.- deleted_tables = set()- for name, sql in vars(persons_dedup_command).items():- if not name.startswith("DELETE_") or not isinstance(sql, str):- continue- match = re.search(r"DELETE\s+FROM\s+([a-z_]+)", sql, re.IGNORECASE)- assert match, f"{name} does not look like a DELETE statement"- deleted_tables.add(match.group(1))- assert deleted_tables, "no DELETE_* constants found -- did they get renamed?"-- probed = {t for t, p in persons_dedup_command.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:- # 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),- ("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_each_read_mode_honors_the_endpoint_the_operator_asks_for(- self, persons_conn, tmp_path, monkeypatch, mode, kwargs, expected_writer- ):- requested = []- real_connection = persons_db_connection-- def spy(*, writer: bool = True, autocommit: bool = False):- requested.append(writer)- return real_connection(writer=writer, autocommit=autocommit)-- monkeypatch.setattr(persons_dedup_command, "persons_db_connection", spy)-- _run(mode, tmp_path, **kwargs)-- assert requested == [expected_writer]-- @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(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) == 2diff --git a/posthog/models/person/bulk_delete.py b/posthog/models/person/bulk_delete.pyindex 788da14c3671..0589892560e9 100644--- a/posthog/models/person/bulk_delete.py+++ b/posthog/models/person/bulk_delete.py@@ -197,6 +197,30 @@ def delete_persons_profile(return result+class PersonTombstoneFailed(Exception):+ """The Postgres tombstone failed for some persons, so they are still live and a retry must resolve them again."""+++def tombstone_and_publish_persons(team_id: int, persons: builtins.list[Person]) -> int:+ """Raise PersonTombstoneFailed when a Postgres tombstone fails, because that person is still live.++ A failed ClickHouse publish does not raise: the ClickHouse deletion sweep republishes from the tombstone queue.+ """+ result = delete_persons_profile(+ team_id,+ persons,+ actor=None,+ queue_ai_training_deletion=False,+ )+ if result.retryable_errors:+ first = next(f for f in result.failures if f.step not in STEPS_AFTER_DELETION)+ raise PersonTombstoneFailed(+ f"Postgres tombstone failed for {len(result.retryable_errors)} of {len(persons)} persons in team "+ f"{team_id}: {first.error}"+ )+ return result.deleted_count++# Page size for the keyset walk over a person's distinct IDs. Each page is one bounded RPC, so a# person with hundreds of thousands of distinct IDs no longer hits the personhog request timeout.QUEUED_DELETION_DISTINCT_ID_PAGE_SIZE = 5000@@ -207,6 +231,54 @@ QUEUED_DELETION_DISTINCT_ID_PAGE_SIZE = 5000QUEUED_DELETION_DISTINCT_IDS_PER_BATCH = 20_000+# Below the replica's cap of 2,500 distinct IDs per person, so a person that returns this many may have more.+TOMBSTONE_DISTINCT_ID_PREFETCH_LIMIT = 100+++def tombstone_and_publish_persons_by_uuids(team_id: int, person_uuids: builtins.list[str]) -> int:+ """Like tombstone_and_publish_persons, but read distinct IDs in batches, page heavy persons, and bound each RPC."""+ from posthog.personhog_client.client import personhog_call++ def _fetch_distinct_ids(person_id: int) -> builtins.list[DistinctIdForPerson]:+ return personhog_call(+ "get_distinct_ids_for_tombstone",+ lambda: _paginated_get_distinct_ids_for_person(+ team_id, person_id, page_size=QUEUED_DELETION_DISTINCT_ID_PAGE_SIZE+ ),+ caller_tag="persons/deletion-distinct-ids",+ )++ persons = personhog_call(+ "resolve_persons_for_deletion",+ lambda: _fetch_persons_by_uuids_via_personhog(+ team_id, person_uuids, distinct_id_limit=TOMBSTONE_DISTINCT_ID_PREFETCH_LIMIT+ ),+ caller_tag="persons/deletion-resolve",+ )+ tombstoned = 0+ batch: builtins.list[Person] = []+ batch_distinct_id_count = 0+ for person in persons:+ if len(person._distinct_ids or []) >= TOMBSTONE_DISTINCT_ID_PREFETCH_LIMIT:+ person._distinct_ids = [d.id for d in _fetch_distinct_ids(person.pk)]+ batch.append(person)+ batch_distinct_id_count += len(person._distinct_ids or [])+ if batch_distinct_id_count >= QUEUED_DELETION_DISTINCT_IDS_PER_BATCH:+ tombstoned += _tombstone_batch_and_release(team_id, batch)+ batch, batch_distinct_id_count = [], 0+ if batch:+ tombstoned += _tombstone_batch_and_release(team_id, batch)+ return tombstoned+++def _tombstone_batch_and_release(team_id: int, persons: builtins.list[Person]) -> int:+ tombstoned = tombstone_and_publish_persons(team_id, persons)+ # The resolved persons outlive their batch, so drop their ID strings to hold one batch of them at a time.+ for person in persons:+ person._distinct_ids = None+ return tombstoned++@frozenclass _QueuedDeletionOptions:delete_profile: booldiff --git a/posthog/models/person/test/test_bulk_delete_helpers.py b/posthog/models/person/test/test_bulk_delete_helpers.pyindex 4acd99bf7999..3205c20fbb76 100644--- a/posthog/models/person/test/test_bulk_delete_helpers.py+++ b/posthog/models/person/test/test_bulk_delete_helpers.py@@ -20,6 +20,7 @@ from posthog.models.person.bulk_delete import (queue_person_event_deletion,queue_person_recording_deletion,resolve_persons_for_deletion,+ tombstone_and_publish_persons,)from posthog.models.person.util import (TOMBSTONE_DELIVERY_TIMEOUT_SECONDS,@@ -183,7 +184,7 @@ class DeletePersonsProfileTests(BaseTest):def test_a_failed_tombstone_rpc_counts_only_the_persons_it_did_not_commit(self, _name, committed, check_fails):p = create_person(team=self.team, distinct_ids=["a"], properties={})- def tombstone_then_fail(team_id, uuids):+ def tombstone_then_fail(team_id, uuids, **_):if committed:tombstone_persons_in_postgres(team_id, uuids)raise RuntimeError("personhog down")@@ -282,6 +283,15 @@ class DeletePersonsProfileTests(BaseTest):assert get_active_fake().tombstone_queue == {}+class TombstoneAndPublishPersonsTests(BaseTest):+ def test_a_failed_clickhouse_publish_does_not_raise_and_stays_queued_for_the_sweep(self):+ p = create_person(team=self.team, distinct_ids=["a"], properties={})+ with patch("posthog.models.person.util.publish_person_tombstone", side_effect=RuntimeError("kafka down")):+ assert tombstone_and_publish_persons(self.team.pk, [p]) == 1++ assert list(get_active_fake().tombstone_queue) == [(self.team.pk, str(p.uuid))]++class ProcessQueuedPersonDeletionTests(BaseTest):def test_walks_every_page_of_distinct_ids_tombstones_at_exact_versions_and_logs_activity(self):p = create_person(team=self.team, distinct_ids=["a", "b", "c", "d", "e"], properties={})diff --git a/posthog/temporal/AGENTS.md b/posthog/temporal/AGENTS.mdindex 4a5e18b4f10d..cc376acdeb0e 100644--- a/posthog/temporal/AGENTS.md+++ b/posthog/temporal/AGENTS.md@@ -30,7 +30,7 @@ The semgrep rule `temporal-logger-no-keyword-fields` blocks this at review time.- [`data_imports/`](../../products/warehouse_sources/backend/temporal/data_imports/README.md) — data warehouse import pipelines (moved to the warehouse_sources product).- [`data_modeling/`](./data_modeling/AGENTS.md) — v1 frozen / v2 active split.- [`signals emission`](../../products/signals/backend/emission/AGENTS.md) — signal emission for data-imports events (moved to the signals product).-- [`sync_person_distinct_ids/`](./sync_person_distinct_ids/README.md), [`experiments/`](./experiments/README.md), [`weekly_digest/`](./weekly_digest/README.md), [`ingestion_acceptance_test/`](./ingestion_acceptance_test/README.md), [`health_checks/`](./health_checks/README.md), [`ai_observability/trace_summarization/`](./ai_observability/trace_summarization/README.md) — each has its own README for context.+- [`experiments/`](./experiments/README.md), [`weekly_digest/`](./weekly_digest/README.md), [`ingestion_acceptance_test/`](./ingestion_acceptance_test/README.md), [`health_checks/`](./health_checks/README.md), [`ai_observability/trace_summarization/`](./ai_observability/trace_summarization/README.md) — each has its own README for context.## Local eval scriptsdiff --git a/posthog/temporal/delete_persons/delete_persons_workflow.py b/posthog/temporal/delete_persons/delete_persons_workflow.pyindex e5dacdf38e6d..1ec7158ebf02 100644--- a/posthog/temporal/delete_persons/delete_persons_workflow.py+++ b/posthog/temporal/delete_persons/delete_persons_workflow.py@@ -8,6 +8,7 @@ import dataclassesimport temporalio.commonimport temporalio.activityimport temporalio.workflow+import temporalio.exceptionsfrom structlog import get_loggerfrom posthog.temporal.common.base import PostHogWorkflow@@ -15,9 +16,8 @@ from posthog.temporal.common.heartbeat import HeartbeaterLOGGER = get_logger(__name__)-# Personhog RPC request caps (see proto/personhog/types/v1/person.proto).+# Personhog RPC request cap (see proto/personhog/types/v1/person.proto).GET_PERSONS_MAX_IDS = 250-DELETE_PERSONS_MAX_UUIDS = 1000def _chunked(items: list, size: int) -> typing.Iterator[list]:@@ -27,15 +27,14 @@ def _chunked(items: list, size: int) -> typing.Iterator[list]:def _delete_specific_persons_via_personhog(team_id: int, person_ids: list[int]) -> int:- """Delete specific persons by id via personhog.+ """Tombstone specific persons by id via personhog and publish their ClickHouse tombstones.- Resolves ids -> uuids with GetPersons (capped at 250/call) and deletes with- DeletePersons (capped at 1000/call). DeletePersons cascades the per-person- cohortpeople cleanup, so no separate cohort delete is needed here.+ A hard delete would leave live ClickHouse rows above the version 0 a re-created person starts at."""+ from posthog.models.person.bulk_delete import tombstone_and_publish_persons_by_uuidsfrom posthog.personhog_client.caller_tag import personhog_caller_tagfrom posthog.personhog_client.client import get_personhog_client- from posthog.personhog_client.proto import DeletePersonsMode, DeletePersonsRequest, GetPersonsRequest+ from posthog.personhog_client.proto import GetPersonsRequestclient = get_personhog_client()if client is None:@@ -46,20 +45,31 @@ def _delete_specific_persons_via_personhog(team_id: int, person_ids: list[int])for id_chunk in _chunked(person_ids, GET_PERSONS_MAX_IDS):persons_resp = client.get_persons(GetPersonsRequest(team_id=team_id, person_ids=id_chunk))uuids.extend(person.uuid for person in persons_resp.persons)+ if not uuids:+ return 0++ return tombstone_and_publish_persons_by_uuids(team_id, uuids)- deleted = 0- for uuid_chunk in _chunked(uuids, DELETE_PERSONS_MAX_UUIDS):- # A purge publishes no ClickHouse tombstones, so the rows must go rather than- # stay behind as tombstones nothing would ever sweep.- delete_resp = client.delete_persons(- DeletePersonsRequest(- team_id=team_id,- person_uuids=uuid_chunk,- mode=DeletePersonsMode.DELETE_PERSONS_MODE_HARD,- )- )- deleted += delete_resp.deleted_count- return deleted++def _require_team_deleted(team_id: int) -> None:+ """Refuse whole-team mode unless the team row is gone or queued for ClickHouse deletion.++ Whole-team mode hard-deletes and publishes no ClickHouse tombstones, which is safe only once no person+ can be re-created and the deletes job removes the team's ClickHouse rows.+ """+ from posthog.models.async_deletion import AsyncDeletion, DeletionType+ from posthog.models.team import Team++ if not Team.objects.filter(id=team_id).exists():+ return+ if AsyncDeletion.objects.filter(deletion_type=DeletionType.Team, key=str(team_id)).exists():+ return+ raise temporalio.exceptions.ApplicationError(+ f"Team {team_id} is not deleted. Whole-team mode would hard-delete live persons and leave "+ "their ClickHouse rows live. Pass person_ids to tombstone specific persons instead.",+ type="TeamNotDeleted",+ non_retryable=True,+ )def _delete_team_persons_batch_via_personhog(team_id: int, batch_size: int) -> int:@@ -68,6 +78,8 @@ def _delete_team_persons_batch_via_personhog(team_id: int, batch_size: int) -> ifrom posthog.personhog_client.client import get_personhog_clientfrom posthog.personhog_client.proto import DeletePersonsBatchForTeamRequest+ _require_team_deleted(team_id)+client = get_personhog_client()if client is None:raise RuntimeError("personhog client not configured")@@ -96,7 +108,7 @@ async def preclean_cohort_members_activity(inputs: PrecleanCohortMembersActivityposthog_cohortpeople has no FK to posthog_person, so it must be cleared explicitly.For a whole-team delete we use the existing by-cohort RPC path (the same one the- team-teardown flow uses); the per-person DeletePersons cascade covers the by-ids mode.+ team-teardown flow uses); the per-person tombstone covers the by-ids mode."""from django.db import close_old_connections@@ -105,6 +117,7 @@ async def preclean_cohort_members_activity(inputs: PrecleanCohortMembersActivityasync with Heartbeater():logger = LOGGER.bind(team_id=inputs.team_id)await asyncio.to_thread(close_old_connections)+ await asyncio.to_thread(_require_team_deleted, inputs.team_id)await asyncio.to_thread(_delete_cohort_members_for_all_teams, [inputs.team_id])await logger.ainfo("Cleared cohort memberships for team")@@ -177,10 +190,8 @@ class DeletePersonsWorkflowInputs:class DeletePersonsWorkflow(PostHogWorkflow):"""Workflow to delete persons and their dependent rows from the persons database via personhog.- All deletion goes through personhog RPCs (no direct database connection). For a- whole-team delete, cohort memberships are cleared up front by cohort and persons are- then removed in batches; for a delete scoped to specific person_ids, GetPersons +- DeletePersons handle persons, distinct_ids, and per-person cohort memberships together.+ Whole-team mode clears cohort memberships and hard-deletes in batches, only for a deleted team; by-ids mode+ tombstones the persons and publishes their ClickHouse tombstones."""def __init__(self) -> None:@@ -204,7 +215,7 @@ class DeletePersonsWorkflow(PostHogWorkflow):await temporalio.workflow.wait_condition(lambda: self.confirmed)# Whole-team deletes clear cohort memberships by cohort up front; the by-ids path- # relies on the per-person DeletePersons cascade instead.+ # relies on the per-person tombstone clearing them instead.if not inputs.person_ids:await temporalio.workflow.execute_activity(preclean_cohort_members_activity,diff --git a/posthog/temporal/sync_person_distinct_ids/README.md b/posthog/temporal/sync_person_distinct_ids/README.mddeleted file mode 100644index 43145d9db53c..000000000000--- a/posthog/temporal/sync_person_distinct_ids/README.md+++ /dev/null@@ -1,229 +0,0 @@-# Sync Person Distinct IDs Workflow--Temporal workflow to fix dangling persons in ClickHouse by syncing missing distinct IDs from PostgreSQL.--## Problem--Persons can exist in ClickHouse `person` table with `is_deleted = 0` but have no corresponding `person_distinct_id2` records. This can happen due to race conditions or incomplete data migrations.--### Orphan Categories--| Category | Person in CH | Person in PG | DID in CH | DID in PG | Action |-| ------------------- | ------------ | ------------ | --------- | --------- | -------------------------------- |-| **Fixable** | Yes | Yes | No | Yes | Sync DID to CH |-| **Truly orphaned** | Yes | Yes | No | No | Report only |-| **CH-only orphans** | Yes | No | No | N/A | Mark as deleted in CH (optional) |--## Solution--This workflow:--1. Finds orphaned persons in ClickHouse (persons without distinct IDs)-2. Looks up their distinct IDs in PostgreSQL-3. Syncs missing `person_distinct_id2` records to ClickHouse via Kafka-4. Optionally marks CH-only orphans (no PG data) as deleted in ClickHouse--## Workflow Inputs--```python-class SyncPersonDistinctIdsWorkflowInputs:- team_id: int- batch_size: int = 100- dry_run: bool = True # Safe by default- delete_ch_only_orphans: bool = False # If True, mark CH-only orphans as deleted (requires categorize_orphans=True)- categorize_orphans: bool = False # If True, run extra query to distinguish truly orphaned vs CH-only- limit: int | None = None # Max persons to process (for testing)- person_ids: list[str] | None = None # Specific person UUIDs to process (for testing)-```--## Workflow Result--```python-class SyncPersonDistinctIdsWorkflowResult:- team_id: int- total_orphaned_persons: int- persons_with_pg_distinct_ids: int # Fixable - have DIDs in PG- distinct_ids_synced: int- persons_without_pg_data: int # Truly orphaned + CH-only combined- persons_truly_orphaned: int # In PG but no DIDs (only if categorize_orphans=True)- persons_ch_only: int # Not in PG at all (only if categorize_orphans=True)- persons_marked_deleted: int # Only if delete_ch_only_orphans=True and dry_run=False- dry_run: bool-```--**Note:** When `categorize_orphans=True`, the workflow runs an extra query to distinguish between truly orphaned persons (exist in PG but have no DIDs) and CH-only orphans (don't exist in PG at all). This is useful for reporting but adds query overhead.--## Activities--| Activity | Purpose | Database |-| ------------------------------ | ------------------------------------------------------------ | ----------- |-| `find_orphaned_persons` | Query CH for all persons without distinct IDs (single query) | ClickHouse |-| `lookup_pg_distinct_ids` | Find distinct IDs for person UUIDs | PostgreSQL |-| `sync_distinct_ids_to_ch` | Write missing distinct IDs via Kafka | Kafka -> CH |-| `mark_ch_only_orphans_deleted` | Set is_deleted=1 for persons without PG data | Kafka -> CH |--### Workflow Logic--1. **Single CH query** to get all orphaned person UUIDs (result set is small - just UUIDs)-2. **Batch processing** of PG lookups and CH writes (these are the expensive parts)--This avoids inefficient OFFSET pagination - instead of N queries each scanning O(n) rows, we do 1 query for discovery + batched processing.--## Behavior Matrix--| dry_run | delete_ch_only_orphans | Sync DIDs? | Mark orphans deleted? |-| ------- | ---------------------- | ---------- | --------------------- |-| true | false | No (log) | No |-| true | true | No (log) | No (log) |-| false | false | **Yes** | No |-| false | true | **Yes** | **Yes** |--**Note:** `delete_ch_only_orphans=true` requires `categorize_orphans=true`. This ensures we only delete persons that are confirmed to be CH-only (not in PG at all), not truly orphaned persons (in PG but without DIDs).--## CLI Usage--```bash-# Dry run (default, safe) - reports what would be done-python manage.py start_temporal_workflow sync-person-distinct-ids \- '{"team_id": 2}'--# Dry run with limit - process only first 10 orphans (for testing)-python manage.py start_temporal_workflow sync-person-distinct-ids \- '{"team_id": 2, "limit": 10}'--# Dry run for specific persons (for testing)-python manage.py start_temporal_workflow sync-person-distinct-ids \- '{"team_id": 2, "person_ids": ["uuid-1", "uuid-2"]}'--# Dry run with delete_ch_only_orphans - shows what would be marked deleted too-python manage.py start_temporal_workflow sync-person-distinct-ids \- '{"team_id": 2, "delete_ch_only_orphans": true, "categorize_orphans": true}'--# Dry run with categorization - reports truly orphaned vs CH-only separately-python manage.py start_temporal_workflow sync-person-distinct-ids \- '{"team_id": 2, "categorize_orphans": true}'--# Production: sync only (don't mark CH-only orphans as deleted)-python manage.py start_temporal_workflow sync-person-distinct-ids \- '{"team_id": 2, "dry_run": false}' \- --workflow-id "sync-person-distinct-ids-team-2"--# Production: sync AND mark CH-only orphans as deleted-python manage.py start_temporal_workflow sync-person-distinct-ids \- '{"team_id": 2, "dry_run": false, "delete_ch_only_orphans": true, "categorize_orphans": true}' \- --workflow-id "sync-person-distinct-ids-team-2"-```--## Key Queries--### Find orphaned persons (ClickHouse)--```sql-SELECT id AS person_id, team_id, created_at, version-FROM person FINAL-WHERE team_id = %(team_id)s- AND is_deleted = 0- AND id NOT IN (- SELECT DISTINCT person_id FROM person_distinct_id2 FINAL- WHERE team_id = %(team_id)s- )-ORDER BY created_at ASC-LIMIT %(limit)s -- optional-```--### Lookup distinct IDs (PostgreSQL)--```sql-SELECT p.uuid::text, pdi.distinct_id, COALESCE(pdi.version, 0)-FROM posthog_person p-JOIN posthog_persondistinctid pdi ON pdi.person_id = p.id-WHERE p.team_id = %(team_id)s- AND p.uuid = ANY(%(person_uuids)s::uuid[])-```--## Local Testing--A management command is provided to create test orphan data for local development.--### Setup test data--```bash-# Create default test orphans (3 fixable, 2 truly orphaned, 2 CH-only)-python manage.py setup_orphan_test_data --team-id 1--# Create custom counts-python manage.py setup_orphan_test_data --team-id 1 \- --fixable 5 \- --truly-orphaned 3 \- --ch-only 2--# Use custom prefix for distinct IDs-python manage.py setup_orphan_test_data --team-id 1 --prefix my-test-```--### Run the workflow--```bash-# Dry run - see what would be synced/deleted-python manage.py start_temporal_workflow sync-person-distinct-ids \- '{"team_id": 1}'--# Actually sync fixable orphans-python manage.py start_temporal_workflow sync-person-distinct-ids \- '{"team_id": 1, "dry_run": false}'--# Sync + mark CH-only orphans as deleted-python manage.py start_temporal_workflow sync-person-distinct-ids \- '{"team_id": 1, "dry_run": false, "delete_ch_only_orphans": true, "categorize_orphans": true}'-```--### Verify results--```sql--- Check for remaining orphans in ClickHouse-SELECT id, team_id, is_deleted, version-FROM person FINAL-WHERE team_id = 1- AND is_deleted = 0- AND id NOT IN (- SELECT DISTINCT person_id FROM person_distinct_id2 FINAL WHERE team_id = 1- );---- Check synced distinct IDs-SELECT person_id, distinct_id, version, is_deleted-FROM person_distinct_id2 FINAL-WHERE team_id = 1- AND distinct_id LIKE 'test-orphan%';-```--### Cleanup test data--```bash-python manage.py setup_orphan_test_data --team-id 1 --cleanup-```--### Test scenarios--| Scenario | Command | Expected Result |-| ---------------- | ------------------------------------------------------------------------------------------------ | -------------------------------------------- |-| Dry run | `'{"team_id": 1}'` | Logs counts, no changes |-| Categorized | `'{"team_id": 1, "categorize_orphans": true}'` | Reports truly orphaned vs CH-only separately |-| Sync only | `'{"team_id": 1, "dry_run": false}'` | Fixable orphans get DIDs synced |-| Sync + delete | `'{"team_id": 1, "dry_run": false, "delete_ch_only_orphans": true, "categorize_orphans": true}'` | DIDs synced + CH-only marked deleted |-| Limit | `'{"team_id": 1, "limit": 2}'` | Only process first 2 orphans |-| Specific persons | `'{"team_id": 1, "person_ids": ["uuid-1"]}'` | Only process specified UUIDs |--## Design Decisions--1. **Single team per workflow** - Run separate instances for different teams (simpler, better isolation)-2. **Batch size 100** - Balances throughput vs memory-3. **Idempotent** - `person_distinct_id2` uses `ReplacingMergeTree` with version dedup-4. **Dry run by default** - Safe; logs what would happen without making changes-5. **Mark CH-only orphans deleted opt-in** - Destructive action requires explicit flag-6. **Categorization opt-in** - Extra query to distinguish truly orphaned vs CH-only; off by default to avoid overhead-7. **Heartbeating** - All activities use `Heartbeater` for long operations-8. **Persons database** - Uses `PERSONS_DB_READER_URL` for PostgreSQL queries (persons tables are in a separate database)-9. **Per-distinct-ID versions** - Each distinct ID has its own version (not per-person), preserved when syncing to ClickHouse-10. **Version-aware deletion** - Uses `current_version + 1` when marking persons as deleted to ensure ClickHouse's ReplacingMergeTree picks up the deletiondiff --git a/posthog/temporal/sync_person_distinct_ids/__init__.py b/posthog/temporal/sync_person_distinct_ids/__init__.pydeleted file mode 100644index a4e48276bf80..000000000000--- a/posthog/temporal/sync_person_distinct_ids/__init__.py+++ /dev/null@@ -1,18 +0,0 @@-from posthog.temporal.sync_person_distinct_ids.activities import (- find_orphaned_persons,- lookup_pg_distinct_ids,- mark_ch_only_orphans_deleted,- sync_distinct_ids_to_ch,-)-from posthog.temporal.sync_person_distinct_ids.workflow import SyncPersonDistinctIdsWorkflow--WORKFLOWS = [- SyncPersonDistinctIdsWorkflow,-]--ACTIVITIES = [- find_orphaned_persons,- lookup_pg_distinct_ids,- sync_distinct_ids_to_ch,- mark_ch_only_orphans_deleted,-]diff --git a/posthog/temporal/sync_person_distinct_ids/activities.py b/posthog/temporal/sync_person_distinct_ids/activities.pydeleted file mode 100644index 8fdf62e144c5..000000000000--- a/posthog/temporal/sync_person_distinct_ids/activities.py+++ /dev/null@@ -1,377 +0,0 @@-import json-import dataclasses--import temporalio.activity-from psycopg import sql-from structlog import get_logger--from posthog.models.person.util import create_person, create_person_distinct_id-from posthog.persons_db import persons_db_aconnection-from posthog.temporal.common.clickhouse import get_client-from posthog.temporal.common.heartbeat import Heartbeater--LOGGER = get_logger(__name__)---class OrphanedPerson:- """Represents an orphaned person from ClickHouse."""-- person_id: str- team_id: int- created_at: str- version: int---class FindOrphanedPersonsInputs:- """Inputs for the find_orphaned_persons activity."""-- team_id: int- limit: int | None = None- person_ids: list[str] | None = None # If provided, only check these specific persons---class FindOrphanedPersonsResult:- """Result of finding orphaned persons in ClickHouse."""-- orphaned_persons: list[OrphanedPerson]---async def find_orphaned_persons(inputs: FindOrphanedPersonsInputs) -> FindOrphanedPersonsResult:- """Find all persons in ClickHouse that have no corresponding distinct IDs.-- This runs a single query to get all orphaned persons for the team.- The result set is small (just UUIDs + metadata), so it's efficient to fetch all at once.- Batching happens in the workflow when processing (PG lookups, CH writes).- """- async with Heartbeater() as heartbeater:- logger = LOGGER.bind(team_id=inputs.team_id, limit=inputs.limit, person_ids_count=len(inputs.person_ids or []))- await logger.ainfo("Finding orphaned persons in ClickHouse")-- heartbeater.details = ("Finding all orphaned persons",)-- limit_clause = f"LIMIT {inputs.limit}" if inputs.limit else ""- person_ids_clause = "AND id IN %(person_ids)s" if inputs.person_ids else ""-- # We use argMax/max with GROUP BY instead of FINAL for more consistent deduplication.- # FINAL can return inconsistent results depending on merge state, which could cause- # persons with valid distinct_ids to be incorrectly identified as orphaned.- # Note: We use aliases (tid, ver) that differ from column names to avoid ClickHouse- # confusing output aliases with column references in WHERE/HAVING/argMax clauses.- query = f"""- SELECT- id AS person_id,- any(team_id) AS tid,- toString(argMax(created_at, version)) AS created_at,- max(version) AS ver- FROM person- WHERE team_id = %(team_id)s- {person_ids_clause}- GROUP BY id- HAVING argMax(is_deleted, version) = 0- AND id NOT IN (- SELECT person_id- FROM person_distinct_id2- WHERE team_id = %(team_id)s- GROUP BY person_id, distinct_id- HAVING argMax(is_deleted, version) = 0- )- ORDER BY created_at ASC- {limit_clause}- FORMAT JSONEachRow- """-- query_params: dict = {"team_id": inputs.team_id}- if inputs.person_ids:- query_params["person_ids"] = inputs.person_ids-- async with get_client(team_id=inputs.team_id) as client:- response = await client.read_query(- query,- query_parameters=query_params,- )-- orphaned_persons: list[OrphanedPerson] = []-- if response:- lines = response.decode("utf-8").strip().split("\n")- for line in lines:- if line:- data = json.loads(line)- orphaned_persons.append(- OrphanedPerson(- person_id=data["person_id"],- team_id=int(data["tid"]),- created_at=data["created_at"],- version=int(data["ver"]),- )- )-- await logger.ainfo("Found orphaned persons", count=len(orphaned_persons))- return FindOrphanedPersonsResult(orphaned_persons=orphaned_persons)---class PersonDistinctIdMapping:- """Maps a person UUID to their distinct IDs from PostgreSQL.-- Each distinct ID has its own version, as versions are per-DID and increment- during merges when DIDs move between persons.- """-- person_uuid: str- distinct_id_versions: dict[str, int] # Maps distinct_id -> version---class LookupPgDistinctIdsInputs:- """Inputs for the lookup_pg_distinct_ids activity."""-- team_id: int- person_uuids: list[str]- categorize_not_found: bool = False # If True, run extra query to distinguish truly orphaned vs CH-only- pg_statement_timeout_seconds: int = 5---class LookupPgDistinctIdsResult:- """Result of looking up distinct IDs in PostgreSQL."""-- mappings: list[PersonDistinctIdMapping]- persons_not_found: list[str] # All persons without DIDs in PG (truly orphaned + CH-only)- persons_truly_orphaned: list[str] # Persons in PG but without DIDs (only populated if categorize_not_found=True)- persons_ch_only: list[str] # Persons not in PG at all (only populated if categorize_not_found=True)---async def lookup_pg_distinct_ids(inputs: LookupPgDistinctIdsInputs) -> LookupPgDistinctIdsResult:- """Look up distinct IDs in PostgreSQL for given person UUIDs."""- async with Heartbeater() as heartbeater:- logger = LOGGER.bind(team_id=inputs.team_id, person_count=len(inputs.person_uuids))- await logger.ainfo("Looking up distinct IDs in PostgreSQL")-- heartbeater.details = (f"Looking up {len(inputs.person_uuids)} persons in PostgreSQL",)-- query = """- SELECT- p.uuid::text as person_uuid,- pdi.distinct_id,- COALESCE(pdi.version, 0) as version- FROM posthog_person p- JOIN posthog_persondistinctid pdi- ON pdi.person_id = p.id- AND pdi.team_id = p.team_id- WHERE p.team_id = %s- AND p.uuid IN (SELECT unnest(%s::uuid[]))- AND p.is_deleted = false- AND pdi.is_deleted = false- ORDER BY p.uuid, pdi.id- """- params = [inputs.team_id, inputs.person_uuids]-- async with persons_db_aconnection(writer=False) as conn:- # Set statement timeout to avoid long-running queries- timeout_stmt = sql.SQL("SET statement_timeout = {}").format(- sql.Literal(f"{inputs.pg_statement_timeout_seconds}s")- )- await conn.execute(timeout_stmt)- async with conn.cursor() as cursor:- await cursor.execute(query, params)- rows = await cursor.fetchall()-- person_to_distinct_ids: dict[str, dict[str, int]] = {}- for row in rows:- person_uuid, distinct_id, version = row- if person_uuid not in person_to_distinct_ids:- person_to_distinct_ids[person_uuid] = {}- person_to_distinct_ids[person_uuid][distinct_id] = version-- mappings: list[PersonDistinctIdMapping] = []- persons_not_found: list[str] = []-- for person_uuid in inputs.person_uuids:- if person_uuid in person_to_distinct_ids:- mappings.append(- PersonDistinctIdMapping(- person_uuid=person_uuid,- distinct_id_versions=person_to_distinct_ids[person_uuid],- )- )- else:- persons_not_found.append(person_uuid)-- # Categorize persons_not_found into truly orphaned vs CH-only (optional extra query)- persons_truly_orphaned: list[str] = []- persons_ch_only: list[str] = []-- if inputs.categorize_not_found and persons_not_found:- heartbeater.details = (f"Categorizing {len(persons_not_found)} persons not found",)-- # Find which of the not-found persons exist in PG (without DIDs)- categorize_query = """- SELECT uuid::text- FROM posthog_person- WHERE team_id = %s- AND uuid IN (SELECT unnest(%s::uuid[]))- AND is_deleted = false- """- params = [inputs.team_id, persons_not_found]-- async with persons_db_aconnection(writer=False) as conn:- timeout_stmt = sql.SQL("SET statement_timeout = {}").format(- sql.Literal(f"{inputs.pg_statement_timeout_seconds}s")- )- await conn.execute(timeout_stmt)- async with conn.cursor() as cursor:- await cursor.execute(categorize_query, params)- rows = await cursor.fetchall()-- persons_in_pg = {row[0] for row in rows}-- for person_uuid in persons_not_found:- if person_uuid in persons_in_pg:- persons_truly_orphaned.append(person_uuid)- else:- persons_ch_only.append(person_uuid)-- await logger.ainfo(- "PostgreSQL lookup complete",- found=len(mappings),- truly_orphaned=len(persons_truly_orphaned),- ch_only=len(persons_ch_only),- )- else:- await logger.ainfo(- "PostgreSQL lookup complete",- found=len(mappings),- not_found=len(persons_not_found),- )-- return LookupPgDistinctIdsResult(- mappings=mappings,- persons_not_found=persons_not_found,- persons_truly_orphaned=persons_truly_orphaned,- persons_ch_only=persons_ch_only,- )---class SyncDistinctIdsToChInputs:- """Inputs for the sync_distinct_ids_to_ch activity."""-- team_id: int- mappings: list[PersonDistinctIdMapping]- dry_run: bool---class SyncDistinctIdsToChResult:- """Result of syncing distinct IDs to ClickHouse."""-- distinct_ids_synced: int- persons_synced: int---async def sync_distinct_ids_to_ch(inputs: SyncDistinctIdsToChInputs) -> SyncDistinctIdsToChResult:- """Sync missing distinct IDs to ClickHouse via Kafka."""- async with Heartbeater() as heartbeater:- logger = LOGGER.bind(team_id=inputs.team_id, mapping_count=len(inputs.mappings), dry_run=inputs.dry_run)-- total_distinct_ids = sum(len(m.distinct_id_versions) for m in inputs.mappings)- heartbeater.details = (f"Syncing {total_distinct_ids} distinct IDs to ClickHouse",)-- if inputs.dry_run:- await logger.ainfo(- "DRY RUN: Would sync distinct IDs to ClickHouse",- persons=len(inputs.mappings),- distinct_ids=total_distinct_ids,- )- for mapping in inputs.mappings:- await logger.ainfo(- "DRY RUN: Would sync",- person_uuid=mapping.person_uuid,- distinct_id_versions=mapping.distinct_id_versions,- )- return SyncDistinctIdsToChResult(- distinct_ids_synced=total_distinct_ids,- persons_synced=len(inputs.mappings),- )-- await logger.ainfo(- "Syncing distinct IDs to ClickHouse",- persons=len(inputs.mappings),- distinct_ids=total_distinct_ids,- )-- for mapping in inputs.mappings:- for distinct_id, version in mapping.distinct_id_versions.items():- create_person_distinct_id(- team_id=inputs.team_id,- distinct_id=distinct_id,- person_id=mapping.person_uuid,- version=version,- is_deleted=False,- )-- await logger.ainfo(- "Synced distinct IDs to ClickHouse",- persons=len(inputs.mappings),- distinct_ids=total_distinct_ids,- )-- return SyncDistinctIdsToChResult(- distinct_ids_synced=total_distinct_ids,- persons_synced=len(inputs.mappings),- )---class MarkChOnlyOrphansDeletedInputs:- """Inputs for the mark_ch_only_orphans_deleted activity."""-- team_id: int- person_versions: dict[str, int] # Maps person_uuid -> current version- dry_run: bool---class MarkChOnlyOrphansDeletedResult:- """Result of marking CH-only orphans as deleted."""-- persons_marked_deleted: int---async def mark_ch_only_orphans_deleted(inputs: MarkChOnlyOrphansDeletedInputs) -> MarkChOnlyOrphansDeletedResult:- """Mark persons without PostgreSQL data as deleted in ClickHouse."""- async with Heartbeater() as heartbeater:- logger = LOGGER.bind(team_id=inputs.team_id, person_count=len(inputs.person_versions), dry_run=inputs.dry_run)-- heartbeater.details = (f"Marking {len(inputs.person_versions)} CH-only orphans as deleted",)-- if inputs.dry_run:- await logger.ainfo(- "DRY RUN: Would mark CH-only orphans as deleted",- count=len(inputs.person_versions),- )- for person_uuid, version in inputs.person_versions.items():- await logger.ainfo("DRY RUN: Would mark as deleted", person_uuid=person_uuid, version=version)- return MarkChOnlyOrphansDeletedResult(persons_marked_deleted=len(inputs.person_versions))-- await logger.ainfo("Marking CH-only orphans as deleted", count=len(inputs.person_versions))-- for person_uuid, current_version in inputs.person_versions.items():- create_person(- uuid=person_uuid,- team_id=inputs.team_id,- version=current_version + 1,- is_deleted=True,- )-- await logger.ainfo("Marked CH-only orphans as deleted", count=len(inputs.person_versions))-- return MarkChOnlyOrphansDeletedResult(persons_marked_deleted=len(inputs.person_versions))diff --git a/posthog/temporal/sync_person_distinct_ids/workflow.py b/posthog/temporal/sync_person_distinct_ids/workflow.pydeleted file mode 100644index db86836783b5..000000000000--- a/posthog/temporal/sync_person_distinct_ids/workflow.py+++ /dev/null@@ -1,211 +0,0 @@-import json-import typing-import datetime as dt-import dataclasses--import temporalio.common-import temporalio.workflow--from posthog.temporal.common.base import PostHogWorkflow-from posthog.temporal.sync_person_distinct_ids.activities import (- FindOrphanedPersonsInputs,- LookupPgDistinctIdsInputs,- MarkChOnlyOrphansDeletedInputs,- SyncDistinctIdsToChInputs,- find_orphaned_persons,- lookup_pg_distinct_ids,- mark_ch_only_orphans_deleted,- sync_distinct_ids_to_ch,-)---class SyncPersonDistinctIdsWorkflowInputs:- """Inputs for the SyncPersonDistinctIds workflow.-- Attributes:- team_id: Team ID to process orphaned persons for.- batch_size: Number of persons to process per activity batch.- dry_run: If True, only log what would be synced without making changes.- delete_ch_only_orphans: If True, mark CH-only orphans as deleted.- categorize_orphans: If True, run extra query to distinguish truly orphaned vs CH-only.- limit: Max persons to process (for testing).- person_ids: Specific person UUIDs to process (for testing).- """-- team_id: int- batch_size: int = 100- dry_run: bool = True- delete_ch_only_orphans: bool = False- categorize_orphans: bool = False- limit: int | None = None- person_ids: list[str] | None = None- pg_statement_timeout_seconds: int = 5-- def __post_init__(self):- if self.delete_ch_only_orphans and not self.categorize_orphans:- raise ValueError(- "delete_ch_only_orphans=True requires categorize_orphans=True. "- "Without categorization, we cannot distinguish CH-only orphans from "- "truly orphaned persons (in PG but without DIDs)."- )-- @property- def properties_to_log(self) -> dict[str, typing.Any]:- return {- "team_id": self.team_id,- "batch_size": self.batch_size,- "dry_run": self.dry_run,- "delete_ch_only_orphans": self.delete_ch_only_orphans,- "categorize_orphans": self.categorize_orphans,- "limit": self.limit,- "person_ids_count": len(self.person_ids) if self.person_ids else 0,- "pg_statement_timeout_seconds": self.pg_statement_timeout_seconds,- }---class SyncPersonDistinctIdsWorkflowResult:- """Result of the SyncPersonDistinctIds workflow.-- Attributes:- team_id: The team that was processed.- total_orphaned_persons: Total count of orphaned persons found in ClickHouse.- persons_with_pg_distinct_ids: Count of persons that have distinct IDs in PostgreSQL (fixable).- distinct_ids_synced: Count of distinct IDs that were synced to ClickHouse.- persons_without_pg_data: Count of persons without DIDs in PG (truly orphaned + CH-only).- persons_truly_orphaned: Count of persons in PG but without DIDs (only if categorize_orphans=True).- persons_ch_only: Count of persons not in PG at all (only if categorize_orphans=True).- persons_marked_deleted: Count of persons marked as deleted in CH.- dry_run: Whether this was a dry run.- """-- team_id: int- total_orphaned_persons: int- persons_with_pg_distinct_ids: int- distinct_ids_synced: int- persons_without_pg_data: int- persons_truly_orphaned: int- persons_ch_only: int- persons_marked_deleted: int- dry_run: bool--[email protected](name="sync-person-distinct-ids")-class SyncPersonDistinctIdsWorkflow(PostHogWorkflow):- """Workflow to sync missing person distinct IDs from PostgreSQL to ClickHouse.-- This workflow:- 1. Finds orphaned persons in ClickHouse (persons without distinct IDs)- 2. Looks up their distinct IDs in PostgreSQL- 3. Syncs the missing distinct IDs to ClickHouse via Kafka- 4. Optionally marks CH-only orphans (no PG data) as deleted- """-- @staticmethod- def parse_inputs(inputs: list[str]) -> SyncPersonDistinctIdsWorkflowInputs:- """Parse inputs from the management command CLI."""- loaded = json.loads(inputs[0])- return SyncPersonDistinctIdsWorkflowInputs(**loaded)-- @temporalio.workflow.run- async def run(self, inputs: SyncPersonDistinctIdsWorkflowInputs) -> SyncPersonDistinctIdsWorkflowResult:- """Execute the sync workflow."""- persons_with_pg_ids = 0- distinct_ids_synced = 0- persons_without_pg_data = 0- persons_truly_orphaned = 0- persons_ch_only = 0- persons_marked_deleted = 0-- retry_policy = temporalio.common.RetryPolicy(- initial_interval=dt.timedelta(seconds=10),- maximum_interval=dt.timedelta(minutes=2),- maximum_attempts=5,- )-- # Step 1: Find orphaned persons in ClickHouse- # This also fetches versions needed for deletion (ClickHouse needs version+1 to override)- find_result = await temporalio.workflow.execute_activity(- find_orphaned_persons,- FindOrphanedPersonsInputs(- team_id=inputs.team_id,- limit=inputs.limit,- person_ids=inputs.person_ids, # Filter to specific persons if provided- ),- start_to_close_timeout=dt.timedelta(minutes=10),- heartbeat_timeout=dt.timedelta(seconds=60),- retry_policy=retry_policy,- )- person_uuids = [p.person_id for p in find_result.orphaned_persons]- person_versions = {p.person_id: p.version for p in find_result.orphaned_persons}-- total_orphaned = len(person_uuids)-- # Step 2: Process in batches (PG lookups and CH writes are the expensive parts)- for i in range(0, len(person_uuids), inputs.batch_size):- batch_uuids = person_uuids[i : i + inputs.batch_size]-- # Look up distinct IDs in PostgreSQL- lookup_result = await temporalio.workflow.execute_activity(- lookup_pg_distinct_ids,- LookupPgDistinctIdsInputs(- team_id=inputs.team_id,- person_uuids=batch_uuids,- categorize_not_found=inputs.categorize_orphans,- pg_statement_timeout_seconds=inputs.pg_statement_timeout_seconds,- ),- start_to_close_timeout=dt.timedelta(minutes=5),- heartbeat_timeout=dt.timedelta(seconds=30),- retry_policy=retry_policy,- )-- persons_with_pg_ids += len(lookup_result.mappings)- persons_without_pg_data += len(lookup_result.persons_not_found)- persons_truly_orphaned += len(lookup_result.persons_truly_orphaned)- persons_ch_only += len(lookup_result.persons_ch_only)-- # Sync distinct IDs to ClickHouse- if lookup_result.mappings:- sync_result = await temporalio.workflow.execute_activity(- sync_distinct_ids_to_ch,- SyncDistinctIdsToChInputs(- team_id=inputs.team_id,- mappings=lookup_result.mappings,- dry_run=inputs.dry_run,- ),- start_to_close_timeout=dt.timedelta(minutes=10),- heartbeat_timeout=dt.timedelta(seconds=60),- retry_policy=retry_policy,- )- distinct_ids_synced += sync_result.distinct_ids_synced-- # Mark CH-only orphans as deleted (if enabled)- # Validation ensures categorize_orphans=True when delete_ch_only_orphans=True- if inputs.delete_ch_only_orphans and lookup_result.persons_ch_only:- # Build version map for persons to delete- delete_versions = {uuid: person_versions.get(uuid, 0) for uuid in lookup_result.persons_ch_only}- delete_result = await temporalio.workflow.execute_activity(- mark_ch_only_orphans_deleted,- MarkChOnlyOrphansDeletedInputs(- team_id=inputs.team_id,- person_versions=delete_versions,- dry_run=inputs.dry_run,- ),- start_to_close_timeout=dt.timedelta(minutes=10),- heartbeat_timeout=dt.timedelta(seconds=60),- retry_policy=retry_policy,- )- persons_marked_deleted += delete_result.persons_marked_deleted-- return SyncPersonDistinctIdsWorkflowResult(- team_id=inputs.team_id,- total_orphaned_persons=total_orphaned,- persons_with_pg_distinct_ids=persons_with_pg_ids,- distinct_ids_synced=distinct_ids_synced,- persons_without_pg_data=persons_without_pg_data,- persons_truly_orphaned=persons_truly_orphaned,- persons_ch_only=persons_ch_only,- persons_marked_deleted=persons_marked_deleted,- dry_run=inputs.dry_run,- )diff --git a/posthog/temporal/tests/delete_persons/test_delete_persons_workflow.py b/posthog/temporal/tests/delete_persons/test_delete_persons_workflow.pyindex 25cfcd6d5618..296a1fa5b2bf 100644--- a/posthog/temporal/tests/delete_persons/test_delete_persons_workflow.py+++ b/posthog/temporal/tests/delete_persons/test_delete_persons_workflow.py@@ -1,10 +1,16 @@import uuid as uuid_libimport pytest+from unittest.mock import patchfrom asgiref.sync import sync_to_async+from temporalio.exceptions import ApplicationError+from posthog.models.async_deletion import AsyncDeletion, DeletionType+from posthog.models.person import Person, bulk_delete+from posthog.models.person.bulk_delete import PersonTombstoneFailedfrom posthog.personhog_client.fake_client import fake_personhog_client+from posthog.personhog_client.proto import DeletePersonsModefrom posthog.temporal.delete_persons.delete_persons_workflow import (DeletePersonsActivityInputs,PrecleanCohortMembersActivityInputs,@@ -17,10 +23,15 @@ from products.cohorts.backend.models.cohort import Cohortpytestmark = pytest.mark.django_db+def _no_publish():+ return patch("posthog.models.person.util.publish_person_tombstone", return_value=[])++class TestDeletePersonsActivity:- async def test_by_ids_resolves_uuids_then_deletes(self, activity_environment):- with fake_personhog_client() as fake:- fake.add_person(team_id=1, person_id=10, uuid=str(uuid_lib.uuid4()), distinct_ids=["d1"])+ async def test_by_ids_tombstones_and_publishes_at_the_postgres_version(self, activity_environment):+ person_uuid = str(uuid_lib.uuid4())+ with fake_personhog_client() as fake, _no_publish() as publish:+ fake.add_person(team_id=1, person_id=10, uuid=person_uuid, version=3, distinct_ids=["d1"])deleted, should_continue = await activity_environment.run(delete_persons_activity,@@ -29,12 +40,69 @@ class TestDeletePersonsActivity:assert deleted == 1assert should_continue is False- # by-ids mode resolves ids -> uuids before deleting (cohortpeople via DeletePersons cascade)- fake.assert_called("get_persons")- fake.assert_called("delete_persons")+ modes = {call.request.mode for call in fake.calls if call.method == "delete_persons"}+ assert modes == {DeletePersonsMode.DELETE_PERSONS_MODE_TOMBSTONE}+ stored = fake._persons_by_uuid[(1, person_uuid)]+ assert (stored.is_deleted, stored.version) == (True, 4)+ publish.assert_called_once()+ tombstone = publish.call_args.args[1]+ assert (str(tombstone.uuid), tombstone.version) == (person_uuid, 4)+ assert [(d.id, d.version) for d in tombstone.distinct_ids] == [("d1", 1)]+ assert fake.tombstone_queue == {}++ async def test_by_ids_reads_distinct_ids_in_one_batch_and_pages_only_heavy_persons(self, activity_environment):+ counted: dict[int, int] = {}++ def record_batch(team_id: int, persons: list[Person]) -> int:+ counted.update({person.pk: len(person.distinct_ids) for person in persons})+ return real_tombstone(team_id, persons)++ real_tombstone = bulk_delete.tombstone_and_publish_persons+ with (+ fake_personhog_client() as fake,+ _no_publish(),+ patch("posthog.models.person.bulk_delete.TOMBSTONE_DISTINCT_ID_PREFETCH_LIMIT", 3),+ patch("posthog.models.person.bulk_delete.QUEUED_DELETION_DISTINCT_ID_PAGE_SIZE", 2),+ patch("posthog.models.person.bulk_delete.QUEUED_DELETION_DISTINCT_IDS_PER_BATCH", 3),+ patch.object(bulk_delete, "tombstone_and_publish_persons", side_effect=record_batch),+ ):+ fake.add_person(team_id=1, person_id=10, uuid=str(uuid_lib.uuid4()), distinct_ids=["10-a", "10-b"])+ fake.add_person(+ team_id=1, person_id=11, uuid=str(uuid_lib.uuid4()), distinct_ids=["11-a", "11-b", "11-c", "11-d"]+ )++ deleted, _ = await activity_environment.run(+ delete_persons_activity,+ DeletePersonsActivityInputs(team_id=1, person_ids=[10, 11], batch_size=1000),+ )++ assert deleted == 2+ batched = [call.request for call in fake.calls if call.method == "get_distinct_ids_for_persons"]+ assert [(sorted(request.person_ids), request.limit_per_person) for request in batched] == [([10, 11], 3)]+ paged = [call.request.person_id for call in fake.calls if call.method == "get_distinct_ids_for_person"]+ assert set(paged) == {11}+ assert counted == {10: 2, 11: 4}+ assert all(len(call.request.person_uuids) == 1 for call in fake.calls if call.method == "delete_persons")++ async def test_by_ids_raises_and_leaves_persons_live_when_the_postgres_tombstone_fails(self, activity_environment):+ person_uuid = str(uuid_lib.uuid4())+ with fake_personhog_client() as fake, _no_publish() as publish:+ fake.add_person(team_id=1, person_id=10, uuid=person_uuid, distinct_ids=["d1"])++ with (+ patch.object(fake, "delete_persons", side_effect=RuntimeError("replica down")),+ pytest.raises(PersonTombstoneFailed),+ ):+ await activity_environment.run(+ delete_persons_activity,+ DeletePersonsActivityInputs(team_id=1, person_ids=[10], batch_size=1000),+ )++ assert fake._persons_by_uuid[(1, person_uuid)].is_deleted is False+ publish.assert_not_called()async def test_by_ids_should_continue_when_more_remain(self, activity_environment):- with fake_personhog_client() as fake:+ with fake_personhog_client() as fake, _no_publish():for pid in (1, 2, 3):fake.add_person(team_id=1, person_id=pid, uuid=str(uuid_lib.uuid4()), distinct_ids=[f"d{pid}"])@@ -62,12 +130,52 @@ class TestDeletePersonsActivity:fake.assert_called("delete_persons_batch_for_team")-# transaction=True so the Cohort committed below is visible to the activity's threaded ORM read+def _mark_team_deleted(team_id: int) -> None:+ AsyncDeletion.objects.create(deletion_type=DeletionType.Team, team_id=team_id, key=str(team_id))+++# transaction=True so the rows committed below are visible to the activity's threaded ORM read# (asyncio.to_thread gets a fresh connection that can't see a rolled-back test transaction).[email protected]_db(transaction=True)+class TestWholeTeamModeRefusesLiveTeams:+ @pytest.mark.parametrize("whole_team_activity", ["preclean", "delete"])+ async def test_refuses_a_live_team_before_deleting_anything(self, activity_environment, ateam, whole_team_activity):+ cohort = await sync_to_async(Cohort.objects.create)(team=ateam, name="live-team")+ with fake_personhog_client() as fake:+ fake.add_person(team_id=ateam.id, person_id=1, uuid=str(uuid_lib.uuid4()))+ fake.add_cohort_membership(person_id=1, cohort_id=cohort.id)++ with pytest.raises(ApplicationError) as refused:+ if whole_team_activity == "preclean":+ await activity_environment.run(+ preclean_cohort_members_activity, PrecleanCohortMembersActivityInputs(team_id=ateam.id)+ )+ else:+ await activity_environment.run(+ delete_persons_activity, DeletePersonsActivityInputs(team_id=ateam.id, batch_size=10)+ )++ assert refused.value.non_retryable+ fake.assert_not_called("delete_cohort_members_bulk")+ fake.assert_not_called("delete_persons_batch_for_team")++ async def test_deletes_once_the_team_is_queued_for_clickhouse_deletion(self, activity_environment, ateam):+ await sync_to_async(_mark_team_deleted)(ateam.id)+ with fake_personhog_client() as fake:+ fake.add_person(team_id=ateam.id, person_id=1, uuid=str(uuid_lib.uuid4()))++ deleted, _ = await activity_environment.run(+ delete_persons_activity, DeletePersonsActivityInputs(team_id=ateam.id, batch_size=10)+ )++ assert deleted == 1++@pytest.mark.django_db(transaction=True)class TestPrecleanCohortMembersActivity:async def test_clears_team_cohort_memberships(self, activity_environment, ateam):cohort = await sync_to_async(Cohort.objects.create)(team=ateam, name="preclean-test")+ await sync_to_async(_mark_team_deleted)(ateam.id)with fake_personhog_client() as fake:fake.add_cohort_membership(person_id=5, cohort_id=cohort.id)@@ -81,6 +189,7 @@ class TestPrecleanCohortMembersActivity:assert (cohort.id, 5) not in fake._cohort_membersasync def test_noop_when_team_has_no_cohorts(self, activity_environment, ateam):+ await sync_to_async(_mark_team_deleted)(ateam.id)with fake_personhog_client() as fake:await activity_environment.run(preclean_cohort_members_activity,diff --git a/posthog/temporal/tests/sync_person_distinct_ids/__init__.py b/posthog/temporal/tests/sync_person_distinct_ids/__init__.pydeleted file mode 100644index e69de29bb2d1..000000000000diff --git a/posthog/temporal/tests/sync_person_distinct_ids/conftest.py b/posthog/temporal/tests/sync_person_distinct_ids/conftest.pydeleted file mode 100644index 6d56412e8852..000000000000--- a/posthog/temporal/tests/sync_person_distinct_ids/conftest.py+++ /dev/null@@ -1,138 +0,0 @@-"""Shared fixtures and utilities for sync_person_distinct_ids tests."""--import uuid-from datetime import datetime--import pytest--from posthog.clickhouse.client.execute import sync_execute--# ============================================================================-# ClickHouse Helper Functions-# ============================================================================---def insert_person_to_ch(team_id: int, person_uuid: str, version: int = 0, is_deleted: int = 0) -> None:- """Insert a person directly into ClickHouse person table."""- sync_execute(- """- INSERT INTO person (id, team_id, properties, is_deleted, is_identified, version, _timestamp, _offset)- VALUES (%(uuid)s, %(team_id)s, '{}', %(is_deleted)s, 0, %(version)s, now(), 0)- """,- {- "uuid": person_uuid,- "team_id": team_id,- "version": version,- "is_deleted": is_deleted,- },- )---def insert_persons_to_ch_batch(team_id: int, person_uuids: list[str], version: int = 0, is_deleted: int = 0) -> None:- """Insert multiple persons directly into ClickHouse person table in a single batch."""- if not person_uuids:- return- now = datetime.now()- values = [(person_uuid, team_id, "{}", is_deleted, 0, version, now, 0) for person_uuid in person_uuids]- sync_execute(- "INSERT INTO person (id, team_id, properties, is_deleted, is_identified, version, _timestamp, _offset) VALUES",- values,- )---def insert_distinct_id_to_ch(team_id: int, person_uuid: str, distinct_id: str, version: int = 0) -> None:- """Insert a distinct ID directly into ClickHouse person_distinct_id2 table."""- sync_execute(- """- INSERT INTO person_distinct_id2 (team_id, distinct_id, person_id, is_deleted, version, _timestamp, _offset, _partition)- VALUES (%(team_id)s, %(distinct_id)s, %(person_id)s, 0, %(version)s, now(), 0, 0)- """,- {- "team_id": team_id,- "distinct_id": distinct_id,- "person_id": person_uuid,- "version": version,- },- )---def get_ch_person(team_id: int, person_uuid: str) -> dict | None:- """Get a person from ClickHouse."""- result = sync_execute(- """- SELECT id, team_id, is_deleted, version- FROM person FINAL- WHERE team_id = %(team_id)s AND id = %(person_uuid)s- """,- {"team_id": team_id, "person_uuid": person_uuid},- )- if result:- return {"id": result[0][0], "team_id": result[0][1], "is_deleted": result[0][2], "version": result[0][3]}- return None---def get_ch_distinct_id(team_id: int, distinct_id: str) -> dict | None:- """Get a distinct ID from ClickHouse."""- result = sync_execute(- """- SELECT person_id, distinct_id, version, is_deleted- FROM person_distinct_id2 FINAL- WHERE team_id = %(team_id)s AND distinct_id = %(distinct_id)s- """,- {"team_id": team_id, "distinct_id": distinct_id},- )- if result:- return {- "person_id": result[0][0],- "distinct_id": result[0][1],- "version": result[0][2],- "is_deleted": result[0][3],- }- return None---def cleanup_ch_test_data(team_id: int, person_uuids: list[str], distinct_ids: list[str]) -> None:- """Mark test persons as deleted in ClickHouse using batch inserts."""- now = datetime.now()- null_uuid = "00000000-0000-0000-0000-000000000000"-- if person_uuids:- person_values = [(person_uuid, team_id, "{}", 1, 0, 1000, now, 0) for person_uuid in person_uuids]- sync_execute(- "INSERT INTO person (id, team_id, properties, is_deleted, is_identified, version, _timestamp, _offset) VALUES",- person_values,- )- if distinct_ids:- did_values = [(team_id, distinct_id, null_uuid, 1, 1000, now, 0, 0) for distinct_id in distinct_ids]- sync_execute(- "INSERT INTO person_distinct_id2 (team_id, distinct_id, person_id, is_deleted, version, _timestamp, _offset, _partition) VALUES",- did_values,- )---def get_orphaned_person_count(team_id: int) -> int:- """Count orphaned persons in ClickHouse for a team."""- result = sync_execute(- """- SELECT count() FROM person FINAL- WHERE team_id = %(team_id)s- AND is_deleted = 0- AND id NOT IN (- SELECT DISTINCT person_id FROM person_distinct_id2 FINAL- WHERE team_id = %(team_id)s- )- """,- {"team_id": team_id},- )- return result[0][0] if result else 0---# ============================================================================-# Fixtures-# ============================================================================---def test_prefix():- """Generate a unique prefix for test data to avoid collisions."""- return f"test-sync-{uuid.uuid4().hex[:8]}"diff --git a/posthog/temporal/tests/sync_person_distinct_ids/test_activities.py b/posthog/temporal/tests/sync_person_distinct_ids/test_activities.pydeleted file mode 100644index 53125584e00f..000000000000--- a/posthog/temporal/tests/sync_person_distinct_ids/test_activities.py+++ /dev/null@@ -1,504 +0,0 @@-"""Integration tests for sync_person_distinct_ids activities."""--import uuid--import pytest--from asgiref.sync import sync_to_async--from posthog.temporal.sync_person_distinct_ids.activities import (- FindOrphanedPersonsInputs,- FindOrphanedPersonsResult,- LookupPgDistinctIdsInputs,- LookupPgDistinctIdsResult,- MarkChOnlyOrphansDeletedInputs,- MarkChOnlyOrphansDeletedResult,- PersonDistinctIdMapping,- SyncDistinctIdsToChInputs,- SyncDistinctIdsToChResult,- find_orphaned_persons,- lookup_pg_distinct_ids,- mark_ch_only_orphans_deleted,- sync_distinct_ids_to_ch,-)-from posthog.temporal.tests.sync_person_distinct_ids.conftest import (- cleanup_ch_test_data,- get_ch_distinct_id,- get_ch_person,- get_orphaned_person_count,- insert_distinct_id_to_ch,- insert_person_to_ch,-)-from posthog.test.persons import add_distinct_id, create_person--pytestmark = pytest.mark.persons_db_direct---class TestFindOrphanedPersons:- @pytest.fixture(autouse=True)- def setup(self, team, test_prefix, activity_environment):- self.team = team- self.prefix = test_prefix- self.activity_environment = activity_environment- self.created_person_uuids: list[str] = []- self.created_distinct_ids: list[str] = []-- yield-- cleanup_ch_test_data(self.team.id, self.created_person_uuids, self.created_distinct_ids)-- @pytest.mark.asyncio- async def test_finds_orphaned_persons_without_distinct_ids(self):- assert get_orphaned_person_count(self.team.id) == 0-- person_uuid = str(uuid.uuid4())- self.created_person_uuids.append(person_uuid)- insert_person_to_ch(self.team.id, person_uuid, version=0)-- result: FindOrphanedPersonsResult = await self.activity_environment.run(- find_orphaned_persons,- FindOrphanedPersonsInputs(team_id=self.team.id),- )-- assert len(result.orphaned_persons) == 1- assert result.orphaned_persons[0].person_id == person_uuid-- @pytest.mark.asyncio- async def test_does_not_find_persons_with_distinct_ids(self):- assert get_orphaned_person_count(self.team.id) == 0-- person_uuid = str(uuid.uuid4())- distinct_id = f"{self.prefix}-has-did"- self.created_person_uuids.append(person_uuid)- self.created_distinct_ids.append(distinct_id)- insert_person_to_ch(self.team.id, person_uuid, version=0)- insert_distinct_id_to_ch(self.team.id, person_uuid, distinct_id, version=0)-- result: FindOrphanedPersonsResult = await self.activity_environment.run(- find_orphaned_persons,- FindOrphanedPersonsInputs(team_id=self.team.id),- )-- assert len(result.orphaned_persons) == 0-- @pytest.mark.asyncio- async def test_does_not_find_deleted_persons(self):- assert get_orphaned_person_count(self.team.id) == 0-- person_uuid = str(uuid.uuid4())- self.created_person_uuids.append(person_uuid)- insert_person_to_ch(self.team.id, person_uuid, version=0, is_deleted=1)-- result: FindOrphanedPersonsResult = await self.activity_environment.run(- find_orphaned_persons,- FindOrphanedPersonsInputs(team_id=self.team.id),- )-- assert len(result.orphaned_persons) == 0-- @pytest.mark.asyncio- async def test_respects_limit(self):- assert get_orphaned_person_count(self.team.id) == 0-- person_uuids = [str(uuid.uuid4()) for _ in range(5)]- for person_uuid in person_uuids:- self.created_person_uuids.append(person_uuid)- insert_person_to_ch(self.team.id, person_uuid, version=0)-- assert get_orphaned_person_count(self.team.id) == 5-- result: FindOrphanedPersonsResult = await self.activity_environment.run(- find_orphaned_persons,- FindOrphanedPersonsInputs(team_id=self.team.id, limit=2),- )-- assert len(result.orphaned_persons) == 2---class TestLookupPgDistinctIds:- @pytest.fixture(autouse=True)- def setup(self, team, test_prefix, activity_environment):- self.team = team- self.prefix = test_prefix- self.activity_environment = activity_environment- self.created_person_uuids: list[str] = []- self.created_distinct_ids: list[str] = []-- yield-- cleanup_ch_test_data(self.team.id, self.created_person_uuids, self.created_distinct_ids)-- @pytest.mark.asyncio- async def test_finds_distinct_ids_for_fixable_orphans(self):- person_uuid = str(uuid.uuid4())- distinct_id = f"{self.prefix}-fixable"- self.created_person_uuids.append(person_uuid)- self.created_distinct_ids.append(distinct_id)-- @sync_to_async- def create_person_with_did():- person = create_person(team=self.team, uuid=person_uuid)- add_distinct_id(person=person, distinct_id=distinct_id, version=0)-- await create_person_with_did()-- result: LookupPgDistinctIdsResult = await self.activity_environment.run(- lookup_pg_distinct_ids,- LookupPgDistinctIdsInputs(team_id=self.team.id, person_uuids=[person_uuid]),- )-- assert len(result.mappings) == 1- assert result.mappings[0].person_uuid == person_uuid- assert len(result.mappings[0].distinct_id_versions) == 1- assert distinct_id in result.mappings[0].distinct_id_versions- assert len(result.persons_not_found) == 0-- @pytest.mark.asyncio- async def test_returns_persons_not_found_for_ch_only_orphans(self):- person_uuid = str(uuid.uuid4())- self.created_person_uuids.append(person_uuid)-- result: LookupPgDistinctIdsResult = await self.activity_environment.run(- lookup_pg_distinct_ids,- LookupPgDistinctIdsInputs(team_id=self.team.id, person_uuids=[person_uuid]),- )-- assert len(result.mappings) == 0- assert len(result.persons_not_found) == 1- assert person_uuid in result.persons_not_found-- @pytest.mark.asyncio- async def test_categorizes_truly_orphaned_vs_ch_only(self):- truly_orphaned_uuid = str(uuid.uuid4())- ch_only_uuid = str(uuid.uuid4())- self.created_person_uuids.extend([truly_orphaned_uuid, ch_only_uuid])-- @sync_to_async- def _seed():- create_person(team=self.team, uuid=truly_orphaned_uuid)-- await _seed()-- result: LookupPgDistinctIdsResult = await self.activity_environment.run(- lookup_pg_distinct_ids,- LookupPgDistinctIdsInputs(- team_id=self.team.id,- person_uuids=[truly_orphaned_uuid, ch_only_uuid],- categorize_not_found=True,- ),- )-- assert len(result.mappings) == 0- assert len(result.persons_not_found) == 2- assert truly_orphaned_uuid in result.persons_not_found- assert ch_only_uuid in result.persons_not_found- assert len(result.persons_truly_orphaned) == 1- assert truly_orphaned_uuid in result.persons_truly_orphaned- assert len(result.persons_ch_only) == 1- assert ch_only_uuid in result.persons_ch_only-- @pytest.mark.asyncio- async def test_finds_multiple_distinct_ids_for_person(self):- """Each distinct ID should be returned with its own version."""- person_uuid = str(uuid.uuid4())- distinct_ids = [f"{self.prefix}-multi-{i}" for i in range(3)]- self.created_person_uuids.append(person_uuid)- self.created_distinct_ids.extend(distinct_ids)-- @sync_to_async- def create_person_with_dids():- person = create_person(team=self.team, uuid=person_uuid)- for i, distinct_id in enumerate(distinct_ids):- add_distinct_id(person=person, distinct_id=distinct_id, version=i)-- await create_person_with_dids()-- result: LookupPgDistinctIdsResult = await self.activity_environment.run(- lookup_pg_distinct_ids,- LookupPgDistinctIdsInputs(team_id=self.team.id, person_uuids=[person_uuid]),- )-- assert len(result.mappings) == 1- assert len(result.mappings[0].distinct_id_versions) == 3- assert set(result.mappings[0].distinct_id_versions.keys()) == set(distinct_ids)- # Each distinct ID should have its own version, not the max- assert result.mappings[0].distinct_id_versions[distinct_ids[0]] == 0- assert result.mappings[0].distinct_id_versions[distinct_ids[1]] == 1- assert result.mappings[0].distinct_id_versions[distinct_ids[2]] == 2- assert len(result.persons_not_found) == 0---class TestSyncDistinctIdsToCh:- @pytest.fixture(autouse=True)- def setup(self, team, test_prefix, activity_environment):- self.team = team- self.prefix = test_prefix- self.activity_environment = activity_environment- self.created_person_uuids: list[str] = []- self.created_distinct_ids: list[str] = []-- yield-- cleanup_ch_test_data(self.team.id, self.created_person_uuids, self.created_distinct_ids)-- @pytest.mark.asyncio- async def test_dry_run_does_not_sync(self):- person_uuid = str(uuid.uuid4())- distinct_id = f"{self.prefix}-dry-run"- self.created_person_uuids.append(person_uuid)- self.created_distinct_ids.append(distinct_id)- insert_person_to_ch(self.team.id, person_uuid, version=0)-- mapping = PersonDistinctIdMapping(person_uuid=person_uuid, distinct_id_versions={distinct_id: 0})-- result: SyncDistinctIdsToChResult = await self.activity_environment.run(- sync_distinct_ids_to_ch,- SyncDistinctIdsToChInputs(team_id=self.team.id, mappings=[mapping], dry_run=True),- )-- assert result.distinct_ids_synced == 1- assert result.persons_synced == 1- assert get_ch_distinct_id(self.team.id, distinct_id) is None-- @pytest.mark.asyncio- async def test_syncs_distinct_ids_to_ch(self):- person_uuid = str(uuid.uuid4())- distinct_id = f"{self.prefix}-sync"- self.created_person_uuids.append(person_uuid)- self.created_distinct_ids.append(distinct_id)- insert_person_to_ch(self.team.id, person_uuid, version=0)-- mapping = PersonDistinctIdMapping(person_uuid=person_uuid, distinct_id_versions={distinct_id: 0})-- result: SyncDistinctIdsToChResult = await self.activity_environment.run(- sync_distinct_ids_to_ch,- SyncDistinctIdsToChInputs(team_id=self.team.id, mappings=[mapping], dry_run=False),- )-- assert result.distinct_ids_synced == 1- assert result.persons_synced == 1-- @pytest.mark.asyncio- async def test_syncs_multiple_distinct_ids(self):- person_uuid = str(uuid.uuid4())- distinct_ids = [f"{self.prefix}-multi-{i}" for i in range(3)]- self.created_person_uuids.append(person_uuid)- self.created_distinct_ids.extend(distinct_ids)- insert_person_to_ch(self.team.id, person_uuid, version=0)-- mapping = PersonDistinctIdMapping(person_uuid=person_uuid, distinct_id_versions=dict.fromkeys(distinct_ids, 0))-- result: SyncDistinctIdsToChResult = await self.activity_environment.run(- sync_distinct_ids_to_ch,- SyncDistinctIdsToChInputs(team_id=self.team.id, mappings=[mapping], dry_run=False),- )-- assert result.distinct_ids_synced == 3- assert result.persons_synced == 1-- @pytest.mark.asyncio- async def test_syncs_distinct_ids_with_individual_versions(self):- """Each distinct ID should be synced with its own version from PostgreSQL.-- This is important because distinct ID versions are per-DID, not per-person.- They increment during merges when DIDs move between persons. If we use- the wrong version, future merges might be ignored because the new version- after merging could be lower in PG than what we synced to CH.- """- person_uuid = str(uuid.uuid4())- did1 = f"{self.prefix}-version-0"- did2 = f"{self.prefix}-version-5"- self.created_person_uuids.append(person_uuid)- self.created_distinct_ids.extend([did1, did2])- insert_person_to_ch(self.team.id, person_uuid, version=0)-- # Simulate distinct IDs with different versions (e.g., did2 went through more merges)- mapping = PersonDistinctIdMapping(- person_uuid=person_uuid,- distinct_id_versions={did1: 0, did2: 5},- )-- result: SyncDistinctIdsToChResult = await self.activity_environment.run(- sync_distinct_ids_to_ch,- SyncDistinctIdsToChInputs(team_id=self.team.id, mappings=[mapping], dry_run=False),- )-- assert result.distinct_ids_synced == 2- assert result.persons_synced == 1-- # Verify each distinct ID has its correct version in ClickHouse- ch_did1 = get_ch_distinct_id(self.team.id, did1)- ch_did2 = get_ch_distinct_id(self.team.id, did2)-- assert ch_did1 is not None- assert ch_did1["version"] == 0 # did1 should have version 0- assert str(ch_did1["person_id"]) == person_uuid-- assert ch_did2 is not None- assert ch_did2["version"] == 5 # did2 should have version 5- assert str(ch_did2["person_id"]) == person_uuid---class TestMarkChOnlyOrphansDeleted:- @pytest.fixture(autouse=True)- def setup(self, team, test_prefix, activity_environment):- self.team = team- self.prefix = test_prefix- self.activity_environment = activity_environment- self.created_person_uuids: list[str] = []-- yield-- cleanup_ch_test_data(self.team.id, self.created_person_uuids, [])-- @pytest.mark.asyncio- async def test_dry_run_does_not_delete(self):- person_uuid = str(uuid.uuid4())- self.created_person_uuids.append(person_uuid)- insert_person_to_ch(self.team.id, person_uuid, version=0)-- result: MarkChOnlyOrphansDeletedResult = await self.activity_environment.run(- mark_ch_only_orphans_deleted,- MarkChOnlyOrphansDeletedInputs(team_id=self.team.id, person_versions={person_uuid: 0}, dry_run=True),- )-- assert result.persons_marked_deleted == 1- ch_person = get_ch_person(self.team.id, person_uuid)- assert ch_person is not None- assert ch_person["is_deleted"] == 0-- @pytest.mark.asyncio- async def test_marks_persons_as_deleted(self):- person_uuid = str(uuid.uuid4())- self.created_person_uuids.append(person_uuid)- insert_person_to_ch(self.team.id, person_uuid, version=0)-- result: MarkChOnlyOrphansDeletedResult = await self.activity_environment.run(- mark_ch_only_orphans_deleted,- MarkChOnlyOrphansDeletedInputs(team_id=self.team.id, person_versions={person_uuid: 0}, dry_run=False),- )-- assert result.persons_marked_deleted == 1-- @pytest.mark.asyncio- async def test_marks_multiple_persons_as_deleted(self):- person_uuids = [str(uuid.uuid4()) for _ in range(3)]- for person_uuid in person_uuids:- self.created_person_uuids.append(person_uuid)- insert_person_to_ch(self.team.id, person_uuid, version=0)-- person_versions = dict.fromkeys(person_uuids, 0)- result: MarkChOnlyOrphansDeletedResult = await self.activity_environment.run(- mark_ch_only_orphans_deleted,- MarkChOnlyOrphansDeletedInputs(team_id=self.team.id, person_versions=person_versions, dry_run=False),- )-- assert result.persons_marked_deleted == 3-- @pytest.mark.asyncio- async def test_marks_person_with_high_version_as_deleted(self):- """Person with high version should still be marked as deleted.-- The version used for deletion must be higher than the person's current- version, otherwise ClickHouse's ReplacingMergeTree will keep the old- (non-deleted) record.- """- person_uuid = str(uuid.uuid4())- self.created_person_uuids.append(person_uuid)- # Create person with high version (1000)- insert_person_to_ch(self.team.id, person_uuid, version=1000)-- # Verify person exists and is not deleted- ch_person_before = get_ch_person(self.team.id, person_uuid)- assert ch_person_before is not None- assert ch_person_before["is_deleted"] == 0- assert ch_person_before["version"] == 1000-- result: MarkChOnlyOrphansDeletedResult = await self.activity_environment.run(- mark_ch_only_orphans_deleted,- MarkChOnlyOrphansDeletedInputs(team_id=self.team.id, person_versions={person_uuid: 1000}, dry_run=False),- )-- assert result.persons_marked_deleted == 1-- # Verify person is now marked as deleted (using FINAL to get merged result)- ch_person_after = get_ch_person(self.team.id, person_uuid)- assert ch_person_after is not None- assert ch_person_after["is_deleted"] == 1, (- f"Person should be deleted but is_deleted={ch_person_after['is_deleted']}, "- f"version={ch_person_after['version']} (original was 1000)"- )---class TestEndToEndOrphanCategories:- """Test the complete flow of finding and categorizing all orphan types."""-- @pytest.fixture(autouse=True)- def setup(self, team, test_prefix, activity_environment):- self.team = team- self.prefix = test_prefix- self.activity_environment = activity_environment- self.created_person_uuids: list[str] = []- self.created_distinct_ids: list[str] = []-- yield-- cleanup_ch_test_data(self.team.id, self.created_person_uuids, self.created_distinct_ids)-- @pytest.mark.asyncio- async def test_categorizes_all_three_orphan_types(self):- """Test that lookup_pg_distinct_ids correctly categorizes all three orphan types."""- fixable_uuid = str(uuid.uuid4())- fixable_did = f"{self.prefix}-fixable"- truly_orphaned_uuid = str(uuid.uuid4())- ch_only_uuid = str(uuid.uuid4())-- self.created_person_uuids.extend([fixable_uuid, truly_orphaned_uuid, ch_only_uuid])- self.created_distinct_ids.append(fixable_did)-- # Create PG data with sync_to_async- @sync_to_async- def create_pg_data():- # Fixable: Person in PG with DID- person = create_person(team=self.team, uuid=fixable_uuid)- add_distinct_id(person=person, distinct_id=fixable_did, version=0)- # Truly orphaned: Person in PG, no DID- create_person(team=self.team, uuid=truly_orphaned_uuid)- # CH-only: No PG data-- await create_pg_data()-- # Lookup all three UUIDs in PG with categorization- # (simulating what would happen after find_orphaned_persons)- lookup_result: LookupPgDistinctIdsResult = await self.activity_environment.run(- lookup_pg_distinct_ids,- LookupPgDistinctIdsInputs(- team_id=self.team.id,- person_uuids=[fixable_uuid, truly_orphaned_uuid, ch_only_uuid],- categorize_not_found=True,- ),- )-- # Verify fixable- assert len(lookup_result.mappings) == 1- mapping_uuids = [m.person_uuid for m in lookup_result.mappings]- assert fixable_uuid in mapping_uuids- assert truly_orphaned_uuid not in mapping_uuids- assert ch_only_uuid not in mapping_uuids-- # Verify truly orphaned- assert len(lookup_result.persons_truly_orphaned) == 1- assert truly_orphaned_uuid in lookup_result.persons_truly_orphaned- assert fixable_uuid not in lookup_result.persons_truly_orphaned- assert ch_only_uuid not in lookup_result.persons_truly_orphaned-- # Verify CH-only- assert len(lookup_result.persons_ch_only) == 1- assert ch_only_uuid in lookup_result.persons_ch_only- assert fixable_uuid not in lookup_result.persons_ch_only- assert truly_orphaned_uuid not in lookup_result.persons_ch_onlydiff --git a/posthog/temporal/tests/sync_person_distinct_ids/test_workflow.py b/posthog/temporal/tests/sync_person_distinct_ids/test_workflow.pydeleted file mode 100644index 8885c037c3a9..000000000000--- a/posthog/temporal/tests/sync_person_distinct_ids/test_workflow.py+++ /dev/null@@ -1,297 +0,0 @@-"""Integration tests for SyncPersonDistinctIdsWorkflow with real database operations."""--import uuid--import pytest--import temporalio.worker-from asgiref.sync import sync_to_async-from temporalio.testing import WorkflowEnvironment-from temporalio.worker import Worker--from posthog.persons_db import persons_db_connection-from posthog.persons_seed import insert_seed_distinct_id, insert_seed_person-from posthog.temporal.sync_person_distinct_ids.activities import (- find_orphaned_persons,- lookup_pg_distinct_ids,- mark_ch_only_orphans_deleted,- sync_distinct_ids_to_ch,-)-from posthog.temporal.sync_person_distinct_ids.workflow import (- SyncPersonDistinctIdsWorkflow,- SyncPersonDistinctIdsWorkflowInputs,-)-from posthog.temporal.tests.sync_person_distinct_ids.conftest import (- cleanup_ch_test_data,- get_ch_person,- get_orphaned_person_count,- insert_person_to_ch,- insert_persons_to_ch_batch,-)--pytestmark = pytest.mark.persons_db_direct--[email protected]_db(transaction=True)-class TestSyncPersonDistinctIdsWorkflow:- """Test the full workflow with real activities and database operations."""-- FIXABLE_COUNT = 40- TRULY_ORPHANED_COUNT = 30- CH_ONLY_COUNT = 30- BATCH_SIZE = 30 # Small batch size to ensure multiple batches (4 batches for 100 items)-- @pytest.fixture(autouse=True)- def setup(self, team, test_prefix):- self.team = team- self.prefix = test_prefix- self.created_person_uuids: list[str] = []- self.created_distinct_ids: list[str] = []- self.fixable_uuids: list[str] = []- self.truly_orphaned_uuids: list[str] = []- self.ch_only_uuids: list[str] = []-- yield-- cleanup_ch_test_data(self.team.id, self.created_person_uuids, self.created_distinct_ids)-- async def _create_test_data(self):- """Create 100 orphaned persons across all three categories."""- assert get_orphaned_person_count(self.team.id) == 0-- # Generate all UUIDs first- for i in range(self.FIXABLE_COUNT):- person_uuid = str(uuid.uuid4())- distinct_id = f"{self.prefix}-fixable-{i}"- self.fixable_uuids.append(person_uuid)- self.created_person_uuids.append(person_uuid)- self.created_distinct_ids.append(distinct_id)-- for _ in range(self.TRULY_ORPHANED_COUNT):- person_uuid = str(uuid.uuid4())- self.truly_orphaned_uuids.append(person_uuid)- self.created_person_uuids.append(person_uuid)-- for _ in range(self.CH_ONLY_COUNT):- person_uuid = str(uuid.uuid4())- self.ch_only_uuids.append(person_uuid)- self.created_person_uuids.append(person_uuid)-- # Batch insert all persons to ClickHouse- insert_persons_to_ch_batch(self.team.id, self.created_person_uuids, version=0)-- # Create PG data for fixable and truly orphaned- # Persons-DB rows only (no ClickHouse): the fixable persons are orphans precisely because- # their distinct id lives in PG but not CH, so use the low-level inserts rather than the- # create_person/add_distinct_id helpers (which also mirror into ClickHouse).- @sync_to_async- def create_pg_data():- with persons_db_connection(writer=True, autocommit=True) as conn:- for i, person_uuid in enumerate(self.fixable_uuids):- person_id = insert_seed_person(conn, team_id=self.team.id, properties={}, uuid=person_uuid)- insert_seed_distinct_id(- conn, team_id=self.team.id, person_id=person_id, distinct_id=f"{self.prefix}-fixable-{i}"- )- for person_uuid in self.truly_orphaned_uuids:- insert_seed_person(conn, team_id=self.team.id, properties={}, uuid=person_uuid)-- await create_pg_data()-- total_orphans = self.FIXABLE_COUNT + self.TRULY_ORPHANED_COUNT + self.CH_ONLY_COUNT- assert get_orphaned_person_count(self.team.id) == total_orphans-- @pytest.mark.asyncio- async def test_workflow_dry_run(self):- """Test workflow dry run mode - reports counts but makes no changes."""- await self._create_test_data()-- total_orphans = self.FIXABLE_COUNT + self.TRULY_ORPHANED_COUNT + self.CH_ONLY_COUNT-- task_queue_name = str(uuid.uuid4())- async with await WorkflowEnvironment.start_time_skipping() as env:- async with Worker(- env.client,- task_queue=task_queue_name,- workflows=[SyncPersonDistinctIdsWorkflow],- activities=[- find_orphaned_persons,- lookup_pg_distinct_ids,- sync_distinct_ids_to_ch,- mark_ch_only_orphans_deleted,- ],- workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),- ):- result = await env.client.execute_workflow(- SyncPersonDistinctIdsWorkflow.run,- SyncPersonDistinctIdsWorkflowInputs(- team_id=self.team.id,- batch_size=self.BATCH_SIZE,- dry_run=True,- categorize_orphans=True,- ),- id=str(uuid.uuid4()),- task_queue=task_queue_name,- )-- # Verify workflow result- assert result.team_id == self.team.id- assert result.dry_run is True- assert result.total_orphaned_persons == total_orphans- assert result.persons_with_pg_distinct_ids == self.FIXABLE_COUNT- assert result.distinct_ids_synced == self.FIXABLE_COUNT- assert result.persons_truly_orphaned == self.TRULY_ORPHANED_COUNT- assert result.persons_ch_only == self.CH_ONLY_COUNT- assert result.persons_marked_deleted == 0 # dry_run + delete not enabled-- # Verify no changes were made to the database- assert get_orphaned_person_count(self.team.id) == total_orphans-- @pytest.mark.asyncio- async def test_workflow_sync_only(self):- """Test workflow sync-only mode - syncs fixable orphans, doesn't delete CH-only."""- await self._create_test_data()-- task_queue_name = str(uuid.uuid4())- async with await WorkflowEnvironment.start_time_skipping() as env:- async with Worker(- env.client,- task_queue=task_queue_name,- workflows=[SyncPersonDistinctIdsWorkflow],- activities=[- find_orphaned_persons,- lookup_pg_distinct_ids,- sync_distinct_ids_to_ch,- mark_ch_only_orphans_deleted,- ],- workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),- ):- result = await env.client.execute_workflow(- SyncPersonDistinctIdsWorkflow.run,- SyncPersonDistinctIdsWorkflowInputs(- team_id=self.team.id,- batch_size=self.BATCH_SIZE,- dry_run=False,- delete_ch_only_orphans=False,- categorize_orphans=True,- ),- id=str(uuid.uuid4()),- task_queue=task_queue_name,- )-- # Verify workflow result- assert result.dry_run is False- assert result.persons_with_pg_distinct_ids == self.FIXABLE_COUNT- assert result.distinct_ids_synced == self.FIXABLE_COUNT- assert result.persons_marked_deleted == 0-- # Verify fixable orphans are resolved, truly orphaned + CH-only remain- remaining_orphans = self.TRULY_ORPHANED_COUNT + self.CH_ONLY_COUNT- assert get_orphaned_person_count(self.team.id) == remaining_orphans-- @pytest.mark.asyncio- async def test_workflow_sync_and_delete(self):- """Test workflow sync + delete mode - syncs fixable, deletes CH-only."""- await self._create_test_data()-- task_queue_name = str(uuid.uuid4())- async with await WorkflowEnvironment.start_time_skipping() as env:- async with Worker(- env.client,- task_queue=task_queue_name,- workflows=[SyncPersonDistinctIdsWorkflow],- activities=[- find_orphaned_persons,- lookup_pg_distinct_ids,- sync_distinct_ids_to_ch,- mark_ch_only_orphans_deleted,- ],- workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),- ):- result = await env.client.execute_workflow(- SyncPersonDistinctIdsWorkflow.run,- SyncPersonDistinctIdsWorkflowInputs(- team_id=self.team.id,- batch_size=self.BATCH_SIZE,- dry_run=False,- delete_ch_only_orphans=True,- categorize_orphans=True,- ),- id=str(uuid.uuid4()),- task_queue=task_queue_name,- )-- # Verify workflow result- assert result.dry_run is False- assert result.persons_with_pg_distinct_ids == self.FIXABLE_COUNT- assert result.distinct_ids_synced == self.FIXABLE_COUNT- assert result.persons_ch_only == self.CH_ONLY_COUNT- assert result.persons_marked_deleted == self.CH_ONLY_COUNT-- # Verify only truly orphaned remain (fixable synced, CH-only deleted)- assert get_orphaned_person_count(self.team.id) == self.TRULY_ORPHANED_COUNT-- @pytest.mark.asyncio- async def test_workflow_deletes_with_correct_versions(self):- """Test that workflow correctly increments versions when marking persons as deleted.-- This is important because ClickHouse's ReplacingMergeTree uses the version- column to determine which record to keep. If we use a version lower than- the current one, the deletion will be ignored.- """- # Create 3 CH-only orphans with different versions- versions = [1, 1234, 123456789]- person_uuids = []-- for version in versions:- person_uuid = str(uuid.uuid4())- person_uuids.append(person_uuid)- self.created_person_uuids.append(person_uuid)- insert_person_to_ch(self.team.id, person_uuid, version=version)-- # Verify all persons exist and are not deleted- for i, person_uuid in enumerate(person_uuids):- ch_person = get_ch_person(self.team.id, person_uuid)- assert ch_person is not None- assert ch_person["is_deleted"] == 0- assert ch_person["version"] == versions[i]-- task_queue_name = str(uuid.uuid4())- async with await WorkflowEnvironment.start_time_skipping() as env:- async with Worker(- env.client,- task_queue=task_queue_name,- workflows=[SyncPersonDistinctIdsWorkflow],- activities=[- find_orphaned_persons,- lookup_pg_distinct_ids,- sync_distinct_ids_to_ch,- mark_ch_only_orphans_deleted,- ],- workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),- ):- result = await env.client.execute_workflow(- SyncPersonDistinctIdsWorkflow.run,- SyncPersonDistinctIdsWorkflowInputs(- team_id=self.team.id,- person_ids=person_uuids, # Specify exact persons to process- dry_run=False,- delete_ch_only_orphans=True,- categorize_orphans=True,- ),- id=str(uuid.uuid4()),- task_queue=task_queue_name,- )-- # Verify workflow result- assert result.dry_run is False- assert result.total_orphaned_persons == 3- assert result.persons_marked_deleted == 3-- # Verify each person is deleted with version+1- for i, person_uuid in enumerate(person_uuids):- ch_person = get_ch_person(self.team.id, person_uuid)- assert ch_person is not None, f"Person {i} should exist"- assert ch_person["is_deleted"] == 1, f"Person {i} should be deleted"- assert ch_person["version"] == versions[i] + 1, (- f"Person {i} should have version {versions[i] + 1}, got {ch_person['version']}"- )diff --git a/posthog/test/AGENTS.md b/posthog/test/AGENTS.mdindex e0beb3fc820c..df9b20397c36 100644--- a/posthog/test/AGENTS.md+++ b/posthog/test/AGENTS.md@@ -71,8 +71,8 @@ sole source of truth. In tests, a `FakePersonHogClient` stands in for the real sDB is not used at all — the router blocks ORM access to persons-DB models while the fake is active.The helpers seed the fake (and ClickHouse for persons) so code under test reads consistent data.-Tests that exercise the persons DB _layer itself_ (the temporal `sync_person_distinct_ids` / `backfill_*`-activities, the dagster persons-maintenance jobs, and `test_person_schema`) are excluded from the fake+Tests that exercise the persons DB _layer itself_ (the temporal `backfill_*` activities, the dagster+persons-maintenance jobs, and `test_person_schema`) are excluded from the fakein the root `conftest.py` and keep direct persons-DB access.## Other test utilities that create personsdiff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex a5b434cf0af4..70d2da97a5df 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -37,7 +37,6 @@1 posthog/hogql_queries/utils/aggregations.py1 posthog/kafka_client/client.py1 posthog/management/commands/audit_encrypted_field_keys.py-1 posthog/management/commands/backfill_distinct_id_overrides.py1 posthog/management/commands/backfill_raw_sessions_table.py1 posthog/management/commands/create_channel_definitions_file.py1 posthog/models/file_system/file_system_representation.py@@ -1327,7 +1326,6 @@1 products/web_analytics/backend/test/test_digest_notification_workflows.py1 products/web_analytics/backend/test/test_weekly_digest_workflows.py10 posthog/temporal/ai_observability/trace_summarization/models.py-10 posthog/temporal/sync_person_distinct_ids/activities.py10 products/signals/backend/temporal/grouping.py10 products/signals/backend/temporal/summary.py10 products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -1376,7 +1374,6 @@2 posthog/temporal/proxy_service/cloudflare.py2 posthog/temporal/proxy_service/delete.py2 posthog/temporal/salesforce_enrichment/workflow.py-2 posthog/temporal/sync_person_distinct_ids/workflow.py2 posthog/temporal/tests/common/test_error_tracking.py2 posthog/temporal/tests/common/test_posthog_client_team_id.py2 posthog/temporal/tests/test_slo_interceptor.py