:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(persons): repair divergent distinct ids (#111676)
Eli Reisman9ef74fac832f
diff --git a/posthog/management/commands/person_divergence.py b/posthog/management/commands/person_divergence.pyindex 1dd2aecdbfe3..c1815cb9c804 100644--- a/posthog/management/commands/person_divergence.py+++ b/posthog/management/commands/person_divergence.py@@ -89,8 +89,8 @@ class Command(BaseCommand):)repair_help = (- "DRY RUN unless --apply is passed. Republish the Postgres state of the persons in --input "- "to ClickHouse where ClickHouse disagrees."+ "DRY RUN unless --apply is passed. Republish the Postgres state of the persons in --input, "+ "and their distinct ids, to ClickHouse where ClickHouse disagrees.")repair = actions.add_parser("repair", help=repair_help, description=repair_help)repair.add_argument(@@ -113,7 +113,7 @@ class Command(BaseCommand):"--max-writes-per-second",type=_positive_float,default=50.0,- help="Divergent persons repaired per second, each one a Postgres write (default: %(default)s).",+ help="Divergent persons and distinct ids repaired per second, each one a Postgres write (default: %(default)s).",)@staticmethod@@ -178,7 +178,7 @@ class Command(BaseCommand):)self._log(f"repair {'APPLY' if apply else 'DRY RUN'}: {summary.persons} persons, "- f"person outcomes {summary.person_outcomes}, "+ f"person outcomes {summary.person_outcomes}, mapping outcomes {summary.mapping_outcomes}, "f"undelivered messages {summary.undelivered}")if not apply:diff --git a/posthog/models/person/divergence.py b/posthog/models/person/divergence.pyindex 2fe1a6025561..365d76b0ebf4 100644--- a/posthog/models/person/divergence.py+++ b/posthog/models/person/divergence.py@@ -1,7 +1,7 @@"""Find and repair persons whose ClickHouse rows disagree with the persons database.The persons database, read through personhog, is the source of truth. Scans only read. A repair-republishes the Postgres state of a person to ClickHouse. When ClickHouse+republishes the Postgres state of a person and its distinct ids to ClickHouse. When ClickHouseholds a version at or above the Postgres one, the repair first raises the Postgres version aboveit, so the published row wins and the next ingestion update still outranks it."""@@ -29,17 +29,26 @@ from posthog.kafka_client.topics import KAFKA_PERSONfrom posthog.models.person import Personfrom posthog.models.person.sql import INSERT_PERSON_SQLfrom posthog.models.person.util import (+ _batched_get_distinct_ids_for_persons,_batched_get_persons_by_uuids,_person_row,+ create_person_distinct_id,get_person_tombstones,get_persons_by_uuids,)from posthog.models.team import Teamfrom posthog.personhog_client.client import personhog_call, require_personhog_clientfrom posthog.personhog_client.interceptor import is_transient_rpc_error-from posthog.personhog_client.proto import ReadOptions, SetPersonVersionFloorRequest+from posthog.personhog_client.proto import (+ CONSISTENCY_LEVEL_STRONG,+ GetDistinctIdsForPersonsRequest,+ ReadOptions,+ SetPersonDistinctIdVersionFloorRequest,+ SetPersonVersionFloorRequest,+)PersonDivergenceKind = Literal["hidden", "swept", "stale", "behind", "absent"]+MappingDivergenceKind = Literal["hidden", "other_person", "stale", "absent"]RepairOutcome = Literal["would_repair","repaired",@@ -47,8 +56,11 @@ RepairOutcome = Literal["skipped_not_live","skipped_team_gone","skipped_tombstoned",+ "skipped_owner_changed",+ "skipped_mapping_gone","skipped_reread_lagging","skipped_stale",+ "skipped_too_many_distinct_ids",]# The legacy delete path wrote ClickHouse tombstones at version + 100, so those rows sit at 100 or above.@@ -65,12 +77,17 @@ _STALE_SETTINGS = {"max_memory_usage": 48_000_000_000,"max_bytes_before_external_group_by": 20_000_000_000,}-_REPAIR_PERSON_READ_SETTINGS = {"apply_deleted_mask": 0, "max_execution_time": 60, "max_memory_usage": 4_000_000_000}+# Repair reads see lightweight-deleted rows, so a republish lands above every row a sweep masked.+_REPAIR_READ_SETTINGS = {"apply_deleted_mask": 0, "max_execution_time": 60, "max_memory_usage": 4_000_000_000}# A scan reads only these fields, which keeps person properties out of the RPC payloads._VERSION_ONLY_READ_OPTIONS = ReadOptions(field_mask=["id", "uuid", "team_id", "version"])_REPAIR_CHUNK_SIZE = 100+_MAPPING_QUERY_CHUNK_SIZE = 1_000+# A person with more distinct ids keeps its person repair, and its mappings are reported for a separate plan:+# one read of every mapping can exceed the gRPC message limit, and their paced writes would run for hours.+_MAX_REPAIR_DISTINCT_IDS_PER_PERSON = 1_000# The waits between re-reads give the replica about 0.5 s to show a raise, far above its usual lag of a few milliseconds._REREAD_BACKOFF_SECONDS = (0.025, 0.05, 0.1, 0.15, 0.175)_TRANSIENT_RETRY_BACKOFF_SECONDS = (1.0, 2.0)@@ -115,9 +132,16 @@ class PersonRef:@frozenclass RepairAction:+ """One person row (``distinct_id`` is None) or one of its mappings, with what the repair did to it.++ A person with too many distinct ids to repair gets one extra row with no ``distinct_id`` and the+ outcome ``skipped_too_many_distinct_ids``, which stands for all of its mappings.+ """+team_id: intperson_uuid: str- kind: PersonDivergenceKind | None+ distinct_id: str | None+ kind: PersonDivergenceKind | MappingDivergenceKind | Nonepg_version: int | Nonech_max_version: int | Nonetarget_version: int | None@@ -129,6 +153,7 @@ class RepairSummary:applied: boolpersons: intperson_outcomes: dict[RepairOutcome, int]+ mapping_outcomes: dict[RepairOutcome, int]# Published rows that Kafka did not confirm: the delivery failed, or it was still queued at the deadline.undelivered: int@@ -387,6 +412,24 @@ class _ChPersonState:max_version: int+@frozen+class _ChMappingState:+ visible_rows: int+ visible_max_version: int+ visible_winner_deleted: bool+ visible_winner_person_uuid: str+ max_version: int+++@frozen+class _MappingPlan:+ distinct_id: str+ kind: MappingDivergenceKind | None+ pg_version: int+ ch_max_version: int | None+ target_version: int++@frozenclass _PersonPlan:team_id: int@@ -395,6 +438,8 @@ class _PersonPlan:kind: PersonDivergenceKind | Nonech_max_version: int | Nonetarget_version: int | None+ mappings: list[_MappingPlan]+ too_many_distinct_ids: bool = False_PERSON_STATE_SQL = """@@ -409,6 +454,19 @@ WHERE team_id = %(team_id)s AND id IN %(person_uuids)sGROUP BY id"""+_MAPPING_STATE_SQL = """+SELECT+ distinct_id,+ countIf(_row_exists),+ maxIf(version, _row_exists),+ argMaxIf(is_deleted, version, _row_exists),+ toString(argMaxIf(person_id, version, _row_exists)),+ max(version)+FROM person_distinct_id2+WHERE team_id = %(team_id)s AND distinct_id IN %(distinct_ids)s+GROUP BY distinct_id+"""+def _person_kind(pg_version: int, state: _ChPersonState | None) -> PersonDivergenceKind | None:# Any winner that differs from Postgres counts, whatever the versions: a raise whose publish@@ -426,6 +484,19 @@ def _person_kind(pg_version: int, state: _ChPersonState | None) -> PersonDivergereturn None+def _mapping_kind(person_uuid: str, pg_version: int, state: _ChMappingState | None) -> MappingDivergenceKind | None:+ if state is None or state.visible_rows == 0:+ return "absent"+ if state.visible_winner_deleted:+ return "hidden"+ if state.visible_winner_person_uuid != person_uuid:+ return "other_person"+ # The owner matches, but a later move of this mapping would be written below the ClickHouse winner and lost.+ if state.visible_max_version > pg_version:+ return "stale"+ return None++def _target_version(pg_version: int, ch_max_version: int | None) -> int:# One above ClickHouse, not 100 above: a later Postgres write or tombstone takes the next version# and must outrank this row.@@ -433,7 +504,7 @@ def _target_version(pg_version: int, ch_max_version: int | None) -> int:def _ch_person_states(team_id: int, person_uuids: list[str]) -> dict[str, _ChPersonState]:- rows = _ch(_PERSON_STATE_SQL, {"team_id": team_id, "person_uuids": person_uuids}, _REPAIR_PERSON_READ_SETTINGS)+ rows = _ch(_PERSON_STATE_SQL, {"team_id": team_id, "person_uuids": person_uuids}, _REPAIR_READ_SETTINGS)return {person_uuid: _ChPersonState(visible_rows=int(visible_rows),@@ -445,9 +516,48 @@ def _ch_person_states(team_id: int, person_uuids: list[str]) -> dict[str, _ChPer}+def _ch_mapping_states(team_id: int, distinct_ids: list[str]) -> dict[str, _ChMappingState]:+ states: dict[str, _ChMappingState] = {}+ for chunk in _chunks(distinct_ids, _MAPPING_QUERY_CHUNK_SIZE):+ rows = _ch(_MAPPING_STATE_SQL, {"team_id": team_id, "distinct_ids": list(chunk)}, _REPAIR_READ_SETTINGS)+ for (+ distinct_id,+ visible_rows,+ visible_max_version,+ visible_winner_deleted,+ visible_winner_person_uuid,+ max_version,+ ) in rows:+ states[distinct_id] = _ChMappingState(+ visible_rows=int(visible_rows),+ visible_max_version=int(visible_max_version),+ visible_winner_deleted=bool(visible_winner_deleted),+ visible_winner_person_uuid=visible_winner_person_uuid,+ max_version=int(max_version),+ )+ return states++def _plan_chunk(team_id: int, person_uuids: Sequence[str]) -> list[_PersonPlan]:live = {str(p.uuid): p for p in get_persons_by_uuids(team_id, list(person_uuids), distinct_id_limit=0)}person_states = _ch_person_states(team_id, list(live)) if live else {}+ distinct_ids_by_person = (+ personhog_call(+ "person_divergence_repair_distinct_ids",+ lambda: _batched_get_distinct_ids_for_persons(+ team_id, [p.pk for p in live.values()], limit_per_person=_MAX_REPAIR_DISTINCT_IDS_PER_PERSON + 1+ ),+ )+ if live+ else {}+ )+ all_distinct_ids = [+ d.id+ for dids in distinct_ids_by_person.values()+ if len(dids) <= _MAX_REPAIR_DISTINCT_IDS_PER_PERSON+ for d in dids+ ]+ mapping_states = _ch_mapping_states(team_id, all_distinct_ids) if all_distinct_ids else {}plans: list[_PersonPlan] = []for person_uuid in person_uuids:@@ -461,12 +571,28 @@ def _plan_chunk(team_id: int, person_uuids: Sequence[str]) -> list[_PersonPlan]:kind=None,ch_max_version=None,target_version=None,+ mappings=[],))continuepg_version = int(person.version or 0)state = person_states.get(person_uuid)ch_max_version = state.max_version if state is not None else None+ person_distinct_ids = distinct_ids_by_person.get(person.pk, [])+ too_many_distinct_ids = len(person_distinct_ids) > _MAX_REPAIR_DISTINCT_IDS_PER_PERSON+ mappings = []+ for mapping in [] if too_many_distinct_ids else person_distinct_ids:+ mapping_state = mapping_states.get(mapping.id)+ mapping_ch_max = mapping_state.max_version if mapping_state is not None else None+ mappings.append(+ _MappingPlan(+ distinct_id=mapping.id,+ kind=_mapping_kind(person_uuid, mapping.version, mapping_state),+ pg_version=mapping.version,+ ch_max_version=mapping_ch_max,+ target_version=_target_version(mapping.version, mapping_ch_max),+ )+ )plans.append(_PersonPlan(team_id=team_id,@@ -475,6 +601,8 @@ def _plan_chunk(team_id: int, person_uuids: Sequence[str]) -> list[_PersonPlan]:kind=_person_kind(pg_version, state),ch_max_version=ch_max_version,target_version=_target_version(pg_version, ch_max_version),+ mappings=mappings,+ too_many_distinct_ids=too_many_distinct_ids,))return plans@@ -489,10 +617,39 @@ def _raise_person_version_floor(team_id: int, person_id: int, min_version: int))+def _raise_mapping_version_floor(team_id: int, distinct_id: str, min_version: int) -> str | None:+ """Raise the mapping's version on the primary and return the uuid of the person it maps to there."""+ response = personhog_call(+ "person_divergence_set_person_distinct_id_version_floor",+ lambda: require_personhog_client().set_person_distinct_id_version_floor(+ SetPersonDistinctIdVersionFloorRequest(team_id=team_id, distinct_id=distinct_id, min_version=min_version)+ ),+ )+ if not response.HasField("person"):+ return None+ return str(UUID(response.person.uuid))+++def _primary_mapping_versions(team_id: int, person_id: int) -> dict[str, int]:+ response = personhog_call(+ "person_divergence_confirm_mapping_versions",+ lambda: require_personhog_client().get_distinct_ids_for_persons(+ GetDistinctIdsForPersonsRequest(+ team_id=team_id,+ person_ids=[person_id],+ read_options=ReadOptions(consistency=CONSISTENCY_LEVEL_STRONG),+ limit_per_person=_MAX_REPAIR_DISTINCT_IDS_PER_PERSON + 1,+ )+ ),+ )+ return {d.distinct_id: int(d.version or 0) for pd in response.person_distinct_ids for d in pd.distinct_ids}++def _person_action(plan: _PersonPlan, outcome: RepairOutcome) -> RepairAction:return RepairAction(team_id=plan.team_id,person_uuid=plan.person_uuid,+ distinct_id=None,kind=plan.kind,pg_version=int(plan.person.version or 0) if plan.person is not None else None,ch_max_version=plan.ch_max_version,@@ -501,6 +658,32 @@ def _person_action(plan: _PersonPlan, outcome: RepairOutcome) -> RepairAction:)+def _too_many_distinct_ids_action(plan: _PersonPlan) -> RepairAction:+ return RepairAction(+ team_id=plan.team_id,+ person_uuid=plan.person_uuid,+ distinct_id=None,+ kind=None,+ pg_version=None,+ ch_max_version=None,+ target_version=None,+ outcome="skipped_too_many_distinct_ids",+ )+++def _mapping_action(plan: _PersonPlan, mapping: _MappingPlan, outcome: RepairOutcome) -> RepairAction:+ return RepairAction(+ team_id=plan.team_id,+ person_uuid=plan.person_uuid,+ distinct_id=mapping.distinct_id,+ kind=mapping.kind,+ pg_version=mapping.pg_version,+ ch_max_version=mapping.ch_max_version,+ target_version=mapping.target_version if mapping.kind is not None else None,+ outcome=outcome,+ )++def _publish_person(team_id: int, person: Person) -> ProduceResult:row = _person_row(team_id=team_id,@@ -566,12 +749,25 @@ def _execute_plan(if person is None:return [_person_action(plan, "skipped_not_live")]if plan.kind == "stale" and not include_stale:- return [_person_action(plan, "skipped_stale")]+ return [+ _person_action(plan, "skipped_stale"),+ *(+ _mapping_action(plan, m, "skipped_not_divergent" if m.kind is None else "skipped_stale")+ for m in plan.mappings+ ),+ *([_too_many_distinct_ids_action(plan)] if plan.too_many_distinct_ids else []),+ ]+ divergent_mappings = [m for m in plan.mappings if m.kind is not None]+ mapping_actions = [_mapping_action(plan, m, "skipped_not_divergent") for m in plan.mappings if m.kind is None]+ if plan.too_many_distinct_ids:+ mapping_actions.append(_too_many_distinct_ids_action(plan))if not apply:person_outcome: RepairOutcome = "would_repair" if plan.kind is not None else "skipped_not_divergent"return [_person_action(plan, person_outcome),+ *mapping_actions,+ *(_mapping_action(plan, m, "would_repair") for m in divergent_mappings),]pg_version = int(person.version or 0)@@ -579,16 +775,31 @@ def _execute_plan(before_write()_raise_person_version_floor(plan.team_id, person.pk, plan.target_version)+ # SetPersonDistinctIdVersionFloor runs on the primary, so its reply is the owner check: the replica list+ # that produced this mapping can lag a merge that moved it to another person.+ owned: list[_MappingPlan] = []+ for mapping in divergent_mappings:+ before_write()+ owner = _raise_mapping_version_floor(plan.team_id, mapping.distinct_id, mapping.target_version)+ if owner is None:+ mapping_actions.append(_mapping_action(plan, mapping, "skipped_mapping_gone"))+ elif owner != plan.person_uuid:+ mapping_actions.append(_mapping_action(plan, mapping, "skipped_owner_changed"))+ else:+ owned.append(mapping)+# Re-read after the raise so the published properties are the ones Postgres holds at the# published version, including any ingestion update that landed after the first read.reread: Person | None = Noneif plan.kind is not None:reread = _reread_person(plan.team_id, plan.person_uuid, plan.target_version)- if plan.kind is not None and _tombstoned_uuids(plan.team_id, [plan.person_uuid]):- person_outcome = "skipped_tombstoned"+ if (plan.kind is not None or owned) and _tombstoned_uuids(plan.team_id, [plan.person_uuid]):+ person_outcome = "skipped_tombstoned" if plan.kind is not None else "skipped_not_divergent"return [_person_action(plan, person_outcome),+ *mapping_actions,+ *(_mapping_action(plan, m, "skipped_tombstoned") for m in owned),]if plan.kind is None:@@ -602,7 +813,29 @@ def _execute_plan(published(_publish_person(plan.team_id, reread))person_outcome = "repaired"- return [_person_action(plan, person_outcome)]+ # The SetPersonDistinctIdVersionFloor reply does not say whether it wrote, and a personhog-replica build+ # without NULL-version handling leaves a NULL version unchanged, so publish only the mappings whose+ # version on the primary reached the target.+ stored_versions = _primary_mapping_versions(plan.team_id, person.pk) if owned else {}+ for mapping in owned:+ stored_version = stored_versions.get(mapping.distinct_id)+ if stored_version is None:+ # The primary no longer lists the mapping under this person: it moved or was tombstoned after the raise.+ mapping_actions.append(_mapping_action(plan, mapping, "skipped_mapping_gone"))+ elif stored_version < mapping.target_version:+ mapping_actions.append(_mapping_action(plan, mapping, "skipped_reread_lagging"))+ else:+ published(+ create_person_distinct_id(+ team_id=plan.team_id,+ distinct_id=mapping.distinct_id,+ person_id=plan.person_uuid,+ version=stored_version,+ is_deleted=False,+ )+ )+ mapping_actions.append(_mapping_action(plan, mapping, "repaired"))+ return [_person_action(plan, person_outcome), *mapping_actions]@frozen(frozen=False)@@ -661,17 +894,14 @@ def repair_persons(on_action: Callable[[RepairAction], None],log: Callable[[str], None],) -> RepairSummary:- """Republish the Postgres state of each target person where ClickHouse disagrees.+ """Republish the Postgres state of each target person and its mappings where ClickHouse disagrees.- Without ``apply`` nothing is written and every planned action is reported as ``would_repair``.- A person that is in sync with Postgres is left untouched. A rerun is safe: every write is- guarded by a version floor, and a person whose earlier publish never landed is still divergent.- ``max_writes_per_second`` paces every version-floor write on the persons primary, one per- divergent person.+ A rerun is safe: each Postgres write only raises a version, and a person whose publish never landed+ still counts as divergent. ``max_writes_per_second`` paces each Postgres write, one per divergent+ person or distinct id.- A stale person is skipped unless ``include_stale`` is set, because its repair replaces the- ClickHouse properties with the Postgres ones for good, and a team waiting for a restore from- its ClickHouse rows needs the ClickHouse ones.+ ``include_stale`` also repairs stale persons and their mappings. That replaces their ClickHouse properties+ with the Postgres ones for good, so never use it on a team waiting for a restore from ClickHouse."""if max_writes_per_second is not None and max_writes_per_second <= 0:raise ValueError("max_writes_per_second must be above 0")@@ -680,6 +910,7 @@ def repair_persons(by_team[target.team_id].append(target.person_uuid)person_outcomes: Counter[RepairOutcome] = Counter()+ mapping_outcomes: Counter[RepairOutcome] = Counter()processed = 0undelivered = 0pacer = _WritePacer(max_per_second=max_writes_per_second)@@ -693,6 +924,7 @@ def repair_persons(action = RepairAction(team_id=team_id,person_uuid=person_uuid,+ distinct_id=None,kind=None,pg_version=None,ch_max_version=None,@@ -723,7 +955,8 @@ def repair_persons(log=log,)for action in actions:- person_outcomes[action.outcome] += 1+ is_person_row = action.distinct_id is None and action.outcome != "skipped_too_many_distinct_ids"+ (person_outcomes if is_person_row else mapping_outcomes)[action.outcome] += 1on_action(action)processed += 1log(f"team {team_id}: {len(person_uuids)} persons, {processed} processed in total")@@ -736,5 +969,6 @@ def repair_persons(applied=apply,persons=processed,person_outcomes=dict(person_outcomes),+ mapping_outcomes=dict(mapping_outcomes),undelivered=undelivered,)diff --git a/posthog/models/person/test/test_divergence.py b/posthog/models/person/test/test_divergence.pyindex 65a7edfc9a9a..85d09505891c 100644--- a/posthog/models/person/test/test_divergence.py+++ b/posthog/models/person/test/test_divergence.py@@ -21,6 +21,7 @@ from posthog.kafka_client.topics import KAFKA_PERSONfrom posthog.models.person import Personfrom posthog.models.person.divergence import (DivergentPerson,+ MappingDivergenceKind,PersonDivergenceKind,PersonRef,RepairAction,@@ -32,6 +33,7 @@ from posthog.models.person.divergence import (scan_stale_persons,scan_swept_persons,)+from posthog.models.person.sql import BULK_INSERT_PERSON_DISTINCT_ID2from posthog.models.person.util import (create_person as create_person_in_ch,tombstone_persons_in_postgres,@@ -39,6 +41,7 @@ from posthog.models.person.util import (from posthog.models.signals import mute_selected_signalsfrom posthog.models.team import Teamfrom posthog.personhog_client.fake_client import get_active_fake+from posthog.personhog_client.proto import CONSISTENCY_LEVEL_STRONGfrom posthog.test.persons import add_distinct_id, create_personPG_PROPERTIES = {"email": "[email protected]"}@@ -86,21 +89,51 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):timestamp=now() - timedelta(hours=hours_ago),)- def _stop_person_merges(self) -> None:+ def _ch_mapping_row(+ self, distinct_id: str, person_uuid: UUID | str, version: int, *, deleted: bool = False, hours_ago: float = 0+ ) -> None:+ sync_execute(+ BULK_INSERT_PERSON_DISTINCT_ID2,+ [+ {+ "distinct_id": distinct_id,+ "person_id": str(person_uuid),+ "team_id": self.team.pk,+ "is_deleted": int(deleted),+ "version": version,+ "_timestamp": _utc_naive(hours_ago),+ "_offset": 0,+ "_partition": 0,+ }+ ],+ flush=False,+ )++ def _stop_merges(self, table: str) -> None:# A background merge collapses the older rows that the stale and swept shapes are made of.- sync_execute("SYSTEM STOP MERGES person")- self.addCleanup(sync_execute, "SYSTEM START MERGES person")+ sync_execute(f"SYSTEM STOP MERGES {table}")+ self.addCleanup(sync_execute, f"SYSTEM START MERGES {table}")- def _swept_rows(self, rows_by_person: dict[UUID, list[tuple[int, bool, float]]]) -> None:+ def _stop_person_merges(self) -> None:+ self._stop_merges("person")++ def _attach_swept_part(self, table: str, sort_key: str, columns: str, rows: list[dict[str, Any]]) -> None:# Stopped merges also block lightweight deletes, which run as mutations, so the rows are deleted- # in a one-part side table whose part is then attached to person.- self._stop_person_merges()- staging = f"person_divergence_swept_{self.team.pk}"+ # in a one-part side table whose part is then attached to the target table.+ self._stop_merges(table)+ staging = f"person_divergence_swept_{table}_{self.team.pk}"sync_execute(f"DROP TABLE IF EXISTS {staging} SYNC")- sync_execute(f"CREATE TABLE {staging} AS person ENGINE = ReplacingMergeTree(version) ORDER BY (team_id, id)")+ sync_execute(f"CREATE TABLE {staging} AS {table} ENGINE = ReplacingMergeTree(version) ORDER BY {sort_key}")self.addCleanup(sync_execute, f"DROP TABLE IF EXISTS {staging} SYNC")- sync_execute(- f"INSERT INTO {staging} ({_PERSON_COLUMNS}) VALUES",+ sync_execute(f"INSERT INTO {staging} ({columns}) VALUES", rows, settings={"optimize_on_insert": 0}, flush=False)+ sync_execute(f"DELETE FROM {staging} WHERE 1", settings={"lightweight_deletes_sync": 2})+ sync_execute(f"ALTER TABLE {table} ATTACH PARTITION tuple() FROM {staging}")++ def _swept_rows(self, rows_by_person: dict[UUID, list[tuple[int, bool, float]]]) -> None:+ self._attach_swept_part(+ "person",+ "(team_id, id)",+ _PERSON_COLUMNS,[{"id": person_uuid,@@ -117,11 +150,27 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):for person_uuid, rows in rows_by_person.items()for version, deleted, hours_ago in rows],- settings={"optimize_on_insert": 0},- flush=False,)- sync_execute(f"DELETE FROM {staging} WHERE 1", settings={"lightweight_deletes_sync": 2})- sync_execute(f"ALTER TABLE person ATTACH PARTITION tuple() FROM {staging}")++ def _swept_mapping_rows(self, distinct_id: str, person_uuid: UUID, rows: list[tuple[int, bool, float]]) -> None:+ self._attach_swept_part(+ "person_distinct_id2",+ "(team_id, distinct_id)",+ "distinct_id, person_id, team_id, is_deleted, version, _timestamp, _offset, _partition",+ [+ {+ "distinct_id": distinct_id,+ "person_id": str(person_uuid),+ "team_id": self.team.pk,+ "is_deleted": int(deleted),+ "version": version,+ "_timestamp": _utc_naive(hours_ago),+ "_offset": 0,+ "_partition": 0,+ }+ for version, deleted, hours_ago in rows+ ],+ )def _ch_person(self, person_uuid: UUID | str) -> tuple[int, int, dict[str, Any]]:[[deleted, version, properties]] = sync_execute(@@ -133,11 +182,27 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):)return int(deleted), int(version), json.loads(properties)+ def _ch_mapping(self, distinct_id: str) -> tuple[str, int, int]:+ [[person_uuid, deleted, version]] = sync_execute(+ """+ SELECT toString(argMax(person_id, version)), argMax(is_deleted, version), max(version)+ FROM person_distinct_id2 WHERE team_id = %(team_id)s AND distinct_id = %(distinct_id)s+ """,+ {"team_id": self.team.pk, "distinct_id": distinct_id},+ )+ return person_uuid, int(deleted), int(version)+def _pg_version(self, person: Person) -> int:stored = get_active_fake().stored_person(self.team.pk, str(person.uuid))assert stored is not Nonereturn stored.version+ def _pg_mapping_versions(self, person: Person) -> dict[str, int]:+ response = get_active_fake().get_distinct_ids_for_persons(+ person_pb2.GetDistinctIdsForPersonsRequest(team_id=self.team.pk, person_ids=[person.pk])+ )+ return {d.distinct_id: d.version for pd in response.person_distinct_ids for d in pd.distinct_ids}+def _ch_last_seen_at(self, person_uuid: UUID | str) -> datetime | None:# argMax skips NULL values, so read the newest row itself.[[last_seen_at]] = sync_execute(@@ -167,7 +232,8 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):person_uuid: UUID | str,outcome: RepairOutcome,*,- kind: PersonDivergenceKind | None = None,+ distinct_id: str | None = None,+ kind: PersonDivergenceKind | MappingDivergenceKind | None = None,pg_version: int | None = None,ch_max_version: int | None = None,target_version: int | None = None,@@ -175,6 +241,7 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):return RepairAction(team_id=self.team.pk,person_uuid=str(person_uuid),+ distinct_id=distinct_id,kind=kind,pg_version=pg_version,ch_max_version=ch_max_version,@@ -314,37 +381,50 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):assert self._ch_last_seen_at(person.uuid) is None@parameterized.expand([("dry_run", False), ("apply", True)])- def test_repairs_a_hidden_person_only_when_applied(self, _name: str, apply: bool) -> None:- person = self._pg_person(version=3)+ def test_repairs_a_hidden_person_and_its_hidden_mapping_only_when_applied(self, _name: str, apply: bool) -> None:+ person = self._pg_person(version=3, distinct_ids={"hidden-did": 0})self._ch_person_row(person.uuid, 3)self._ch_person_row(person.uuid, 103, deleted=True)+ self._ch_mapping_row("hidden-did", person.uuid, 0)+ self._ch_mapping_row("hidden-did", person.uuid, 100, deleted=True)summary, actions = self._repair(person.uuid, apply=apply)outcome: RepairOutcome = "repaired" if apply else "would_repair"assert actions == [self._action(person.uuid, outcome, kind="hidden", pg_version=3, ch_max_version=103, target_version=104),+ self._action(+ person.uuid,+ outcome,+ distinct_id="hidden-did",+ kind="hidden",+ pg_version=0,+ ch_max_version=100,+ target_version=101,+ ),]assert summary.applied is applyif apply:- assert self._pg_version(person) == 104+ assert (self._pg_version(person), self._pg_mapping_versions(person)) == (104, {"hidden-did": 101})assert self._ch_person(person.uuid) == (0, 104, PG_PROPERTIES)+ assert self._ch_mapping("hidden-did") == (str(person.uuid), 0, 101)else:get_active_fake().assert_not_called("set_person_version_floor")- assert self._pg_version(person) == 3+ get_active_fake().assert_not_called("set_person_distinct_id_version_floor")+ assert (self._pg_version(person), self._pg_mapping_versions(person)) == (3, {"hidden-did": 0})assert self._ch_person(person.uuid) == (1, 103, CH_PROPERTIES)+ assert self._ch_mapping("hidden-did") == (str(person.uuid), 1, 100)@parameterized.expand([("dry_run", False, []), ("apply", True, [1.0])])def test_throttles_on_each_divergent_row_written(self, _name: str, apply: bool, sleeps: list[float]) -> None:- person = self._pg_person(version=3)+ person = self._pg_person(version=3, distinct_ids={"throttled-did": 0})self._ch_person_row(person.uuid, 103, deleted=True)- other = self._pg_person(version=3)- self._ch_person_row(other.uuid, 103, deleted=True)+ self._ch_mapping_row("throttled-did", person.uuid, 100, deleted=True)with patch("posthog.models.person.divergence.time") as clock:clock.monotonic.return_value = 0.0repair_persons(- [PersonRef(team_id=self.team.pk, person_uuid=str(p.uuid)) for p in (person, other)],+ [PersonRef(team_id=self.team.pk, person_uuid=str(person.uuid))],apply=apply,max_writes_per_second=1,on_action=lambda _: None,@@ -500,8 +580,9 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):def _skipped_person(self, case: str) -> UUID:if case == "in_sync":- person = self._pg_person(version=3)+ person = self._pg_person(version=3, distinct_ids={"steady": 2})self._ch_person_row(person.uuid, 3)+ self._ch_mapping_row("steady", person.uuid, 1)return person.uuidif case == "tombstoned_in_postgres":person = self._pg_person(version=3)@@ -509,17 +590,21 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):self._ch_person_row(person.uuid, 103, deleted=True)return person.uuidif case == "stale_without_include_stale":- return self._divergent_person("stale").uuid+ person = self._pg_person(version=5, distinct_ids={"stale-did": 2})+ self._ch_person_row(person.uuid, 10)+ self._ch_person_row(person.uuid, 5)+ self._ch_mapping_row("stale-did", person.uuid, 100, deleted=True)+ return person.uuidabsent = uuid4()self._ch_person_row(absent, 103, deleted=True)return absent@parameterized.expand([- ("in_sync", ["skipped_not_divergent"]),+ ("in_sync", ["skipped_not_divergent", "skipped_not_divergent"]),("tombstoned_in_postgres", ["skipped_not_live"]),("absent_from_postgres", ["skipped_not_live"]),- ("stale_without_include_stale", ["skipped_stale"]),+ ("stale_without_include_stale", ["skipped_stale", "skipped_stale"]),])def test_leaves_a_person_alone_unless_it_is_live_in_postgres_and_divergent(@@ -532,6 +617,7 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):assert [a.outcome for a in actions] == outcomesget_active_fake().assert_not_called("set_person_version_floor")+ get_active_fake().assert_not_called("set_person_distinct_id_version_floor")assert self._ch_person(person_uuid) == beforedef test_skips_every_person_of_a_team_that_no_longer_exists(self) -> None:@@ -556,8 +642,9 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):get_active_fake().assert_not_called("get_persons_by_uuids")def test_skips_a_person_the_primary_tombstoned_while_the_replica_still_shows_it_live(self) -> None:- person = self._pg_person(version=3)+ person = self._pg_person(version=3, distinct_ids={"lagging-did": 0})self._ch_person_row(person.uuid, 103, deleted=True)+ self._ch_mapping_row("lagging-did", person.uuid, 100, deleted=True)fake = get_active_fake()replica_view = person_pb2.Person()stored = fake.stored_person(self.team.pk, str(person.uuid))@@ -570,8 +657,166 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):):_, actions = self._repair(person.uuid)- assert [a.outcome for a in actions] == ["skipped_tombstoned"]+ assert [(a.distinct_id, a.outcome) for a in actions] == [+ (None, "skipped_tombstoned"),+ ("lagging-did", "skipped_tombstoned"),+ ]assert self._ch_person(person.uuid)[:2] == (1, 103)+ assert self._ch_mapping("lagging-did") == (str(person.uuid), 1, 100)++ @parameterized.expand(+ [+ ("winner_deleted", "self", True, 100, "hidden", 101),+ ("winner_is_another_person", "other", False, 7, "other_person", 8),+ ("winner_is_another_person_below_postgres", "other", False, 1, "other_person", 2),+ ("winner_above_postgres", "self", False, 7, "stale", 8),+ ("absent_from_clickhouse", None, False, None, "absent", 2),+ ("swept_from_clickhouse", "swept", True, 100, "absent", 101),+ ]+ )+ def test_republishes_a_divergent_mapping_for_its_postgres_owner(+ self,+ _name: str,+ ch_owner: str | None,+ ch_deleted: bool,+ ch_version: int | None,+ kind: MappingDivergenceKind,+ target_version: int,+ ) -> None:+ person = self._pg_person(version=3, distinct_ids={"divergent": 2, "steady": 0})+ self._ch_person_row(person.uuid, 3)+ self._ch_mapping_row("steady", person.uuid, 0)+ if ch_owner == "swept":+ self._swept_mapping_rows("divergent", person.uuid, [(1, False, 2), (100, True, 1)])+ elif ch_owner is not None and ch_version is not None:+ owner = person.uuid if ch_owner == "self" else uuid4()+ self._ch_mapping_row("divergent", owner, ch_version, deleted=ch_deleted)++ _, actions = self._repair(person.uuid)++ assert actions == [+ self._action(person.uuid, "skipped_not_divergent", pg_version=3, ch_max_version=3),+ self._action(person.uuid, "skipped_not_divergent", distinct_id="steady", pg_version=0, ch_max_version=0),+ self._action(+ person.uuid,+ "repaired",+ distinct_id="divergent",+ kind=kind,+ pg_version=2,+ ch_max_version=ch_version,+ target_version=target_version,+ ),+ ]+ floors = get_active_fake().assert_called("set_person_distinct_id_version_floor", times=1)+ assert floors[0].request.distinct_id == "divergent"+ get_active_fake().assert_not_called("set_person_version_floor")+ assert self._pg_mapping_versions(person)["divergent"] == target_version+ assert self._ch_mapping("divergent") == (str(person.uuid), 0, target_version)++ @parameterized.expand(+ [+ # A personhog-replica build without NULL-version handling leaves the stored version unchanged.+ ("floor_not_applied", None, "skipped_reread_lagging", 2, (1, 100)),+ # A concurrent write took the mapping past the target, so the publish carries the stored version.+ ("stored_past_the_target", 5, "repaired", 106, (0, 106)),+ ]+ )+ def test_publishes_a_mapping_only_at_the_version_the_primary_holds(+ self,+ _name: str,+ extra_versions: int | None,+ outcome: RepairOutcome,+ stored_version: int,+ ch_deleted_and_version: tuple[int, int],+ ) -> None:+ person = self._pg_person(version=3, distinct_ids={"divergent": 2})+ self._ch_person_row(person.uuid, 3)+ self._ch_mapping_row("divergent", person.uuid, 100, deleted=True)+ fake = get_active_fake()+ raise_floor = fake.set_person_distinct_id_version_floor++ def raise_floor_differently(+ request: person_pb2.SetPersonDistinctIdVersionFloorRequest, timeout: float | None = None+ ) -> person_pb2.SetPersonDistinctIdVersionFloorResponse:+ min_version = 0 if extra_versions is None else request.min_version + extra_versions+ return raise_floor(+ person_pb2.SetPersonDistinctIdVersionFloorRequest(+ team_id=request.team_id, distinct_id=request.distinct_id, min_version=min_version+ ),+ timeout,+ )++ with patch.object(fake, "set_person_distinct_id_version_floor", side_effect=raise_floor_differently):+ _, actions = self._repair(person.uuid)++ assert [(a.distinct_id, a.outcome, a.target_version) for a in actions] == [+ (None, "skipped_not_divergent", None),+ ("divergent", outcome, 101),+ ]+ assert self._pg_mapping_versions(person)["divergent"] == stored_version+ assert self._ch_mapping("divergent") == (str(person.uuid), *ch_deleted_and_version)++ def test_repairs_the_person_but_reports_its_mappings_when_it_has_too_many_distinct_ids(self) -> None:+ person = self._pg_person(version=3, distinct_ids={"a": 0, "b": 0, "c": 0})+ self._ch_person_row(person.uuid, 103, deleted=True)+ self._ch_mapping_row("a", person.uuid, 100, deleted=True)++ with patch("posthog.models.person.divergence._MAX_REPAIR_DISTINCT_IDS_PER_PERSON", 2):+ summary, actions = self._repair(person.uuid)++ assert actions == [+ self._action(person.uuid, "repaired", kind="hidden", pg_version=3, ch_max_version=103, target_version=104),+ self._action(person.uuid, "skipped_too_many_distinct_ids"),+ ]+ assert (summary.person_outcomes, summary.mapping_outcomes) == (+ {"repaired": 1},+ {"skipped_too_many_distinct_ids": 1},+ )+ reads = get_active_fake().assert_called("get_distinct_ids_for_persons", times=1)+ assert reads[0].request.limit_per_person == 3+ get_active_fake().assert_not_called("set_person_distinct_id_version_floor")+ assert self._ch_person(person.uuid) == (0, 104, PG_PROPERTIES)+ assert self._ch_mapping("a") == (str(person.uuid), 1, 100)++ def test_leaves_a_mapping_unpublished_once_the_primary_moved_it_to_another_person(self) -> None:+ person = self._pg_person(version=3, distinct_ids={"moved": 0})+ self._ch_person_row(person.uuid, 3)+ self._ch_mapping_row("moved", person.uuid, 100, deleted=True)+ new_owner = self._pg_person(version=1)+ # The primary maps the id to new_owner while the replica list read for person still carries it.+ with mute_selected_signals():+ add_distinct_id(person=new_owner, distinct_id="moved")++ _, actions = self._repair(person.uuid)++ assert [(a.distinct_id, a.outcome) for a in actions] == [+ (None, "skipped_not_divergent"),+ ("moved", "skipped_owner_changed"),+ ]+ assert self._ch_mapping("moved") == (str(person.uuid), 1, 100)++ def test_leaves_a_mapping_unpublished_once_the_primary_no_longer_lists_it_after_the_raise(self) -> None:+ person = self._pg_person(version=3, distinct_ids={"gone": 0})+ self._ch_person_row(person.uuid, 3)+ self._ch_mapping_row("gone", person.uuid, 100, deleted=True)+ fake = get_active_fake()+ list_distinct_ids = fake.get_distinct_ids_for_persons++ def primary_lost_the_mapping(+ request: person_pb2.GetDistinctIdsForPersonsRequest,+ ) -> person_pb2.GetDistinctIdsForPersonsResponse:+ if request.read_options.consistency == CONSISTENCY_LEVEL_STRONG:+ return person_pb2.GetDistinctIdsForPersonsResponse()+ return list_distinct_ids(request)++ with patch.object(fake, "get_distinct_ids_for_persons", side_effect=primary_lost_the_mapping):+ _, actions = self._repair(person.uuid)++ assert [(a.distinct_id, a.outcome) for a in actions] == [+ (None, "skipped_not_divergent"),+ ("gone", "skipped_mapping_gone"),+ ]+ assert self._ch_mapping("gone") == (str(person.uuid), 1, 100)class TestWritePacer(SimpleTestCase):