: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): add the person divergence repair (#111675)
Eli Reismanafefe6a50697
diff --git a/posthog/management/commands/person_divergence.py b/posthog/management/commands/person_divergence.pyindex 86542d79d909..1dd2aecdbfe3 100644--- a/posthog/management/commands/person_divergence.py+++ b/posthog/management/commands/person_divergence.py@@ -1,13 +1,15 @@-"""Scan for persons whose ClickHouse rows disagree with the persons database.+"""Scan for and repair persons whose ClickHouse rows disagree with the persons database.Usage:python manage.py person_divergence scan hidden --output hidden.csvpython manage.py person_divergence scan swept --output swept.csvpython manage.py person_divergence scan stale --window-days 60 --output stale.csv+ python manage.py person_divergence repair --input hidden.csv --output actions.csv+ python manage.py person_divergence repair --input hidden.csv --output actions.csv --apply-Scans only read. While legacy (version 100 or above) tombstones remain in ClickHouse, run the hidden-scan right before every ClickHouse deletion sweep, because the sweep deletes the rows of every person-it finds, and run the swept scan soon after the sweep.+While legacy (version 100 or above) tombstones remain in ClickHouse, run the hidden scan and repair+what it finds right before every ClickHouse deletion sweep, which deletes every row of those persons.+Run the swept scan soon after the sweep."""import csv@@ -17,6 +19,7 @@ import dataclassesfrom collections.abc import Callablefrom pathlib import Pathfrom typing import Any, TextIO+from uuid import UUIDfrom django.core.management.base import BaseCommand, CommandError, CommandParser@@ -26,7 +29,10 @@ from posthog.models.person.divergence import (STALE_TEAM_STEP,SWEPT_TEAM_STEP,DivergentPerson,+ PersonRef,+ RepairAction,ScanSummary,+ repair_persons,scan_hidden_persons,scan_stale_persons,scan_swept_persons,@@ -54,7 +60,10 @@ _DIVERGENT_SCANS: dict[str, tuple[Callable[..., ScanSummary], int, str]] = {class Command(BaseCommand):- help = "Scan for persons whose ClickHouse rows disagree with the persons database. Scans are read-only."+ help = (+ "Scan for persons whose ClickHouse rows disagree with the persons database, and repair them. "+ "Scans are read-only. A repair is a dry run unless --apply is passed."+ )def add_arguments(self, parser: CommandParser) -> None:actions = parser.add_subparsers(dest="action", required=True, metavar="action")@@ -79,6 +88,34 @@ class Command(BaseCommand):help="Only persons written in the last N days (default: %(default)s).",)+ repair_help = (+ "DRY RUN unless --apply is passed. Republish the Postgres state of the persons in --input "+ "to ClickHouse where ClickHouse disagrees."+ )+ repair = actions.add_parser("repair", help=repair_help, description=repair_help)+ repair.add_argument(+ "--input", type=Path, required=True, help="A CSV with team_id and person_uuid columns, e.g. a scan output."+ )+ self._add_output(repair)+ repair.add_argument("--team-id", type=int, default=None, help="Only repair persons of this team.")+ repair.add_argument(+ "--apply",+ action="store_true",+ help="Write to Postgres and ClickHouse. Without it the repair only reports what it would do.",+ )+ repair.add_argument(+ "--include-stale",+ action="store_true",+ help="Also repair persons a scan classified stale. Their repair replaces the ClickHouse properties "+ "with the Postgres ones for good, so never use it on a team waiting for a restore from ClickHouse.",+ )+ repair.add_argument(+ "--max-writes-per-second",+ type=_positive_float,+ default=50.0,+ help="Divergent persons repaired per second, each one a Postgres write (default: %(default)s).",+ )+@staticmethoddef _add_output(parser: CommandParser) -> None:parser.add_argument("--output", type=Path, required=True, help="CSV to create. Must not exist.")@@ -95,7 +132,10 @@ class Command(BaseCommand):def handle(self, *args: Any, **options: Any) -> None:with tags_context(product=Product.INTERNAL, feature=Feature.MANAGEMENT_COMMAND):- self._scan(options)+ if options["action"] == "repair":+ self._repair(options)+ else:+ self._scan(options)def _log(self, message: str) -> None:self.stdout.write(f"{time.strftime('%H:%M:%S')} {message}")@@ -123,6 +163,29 @@ class Command(BaseCommand):f"skipped teams {summary.skipped_team_ids}")+ def _repair(self, options: dict[str, Any]) -> None:+ targets = _read_targets(options["input"], options["team_id"])+ apply = options["apply"]+ self._log(f"repair {'APPLY' if apply else 'DRY RUN'}: {len(targets)} persons from {options['input']}")+ with _open_output(options["output"]) as handle:+ summary = repair_persons(+ targets,+ apply=apply,+ include_stale=options["include_stale"],+ max_writes_per_second=options["max_writes_per_second"],+ on_action=_csv_sink(handle, RepairAction),+ log=self._log,+ )+ self._log(+ f"repair {'APPLY' if apply else 'DRY RUN'}: {summary.persons} persons, "+ f"person outcomes {summary.person_outcomes}, "+ f"undelivered messages {summary.undelivered}"+ )+ if not apply:+ self._log("Dry run: nothing was written. Pass --apply to write.")+ if summary.undelivered:+ raise CommandError(f"{summary.undelivered} ClickHouse messages were not delivered; rerun the same input")+def _positive_int(value: str) -> int:number = int(value)@@ -131,6 +194,13 @@ def _positive_int(value: str) -> int:return number+def _positive_float(value: str) -> float:+ number = float(value)+ if not number > 0:+ raise argparse.ArgumentTypeError(f"{value} must be above 0")+ return number++def _open_output(path: Path) -> TextIO:try:return path.open("x", newline="")@@ -144,7 +214,25 @@ def _csv_sink(handle: TextIO, row_type: type[Any]) -> Callable[[Any], None]:def write(row: Any) -> None:writer.writerow(dataclasses.asdict(row))- # Flush each row so a scan that dies part way keeps everything it reported.+ # Flush each row so a scan or repair that dies part way keeps everything it reported.handle.flush()return write+++def _read_targets(path: Path, team_id: int | None) -> list[PersonRef]:+ with path.open(newline="") as handle:+ reader = csv.DictReader(handle)+ missing = {"team_id", "person_uuid"} - set(reader.fieldnames or [])+ if missing:+ raise CommandError(f"{path} has no {', '.join(sorted(missing))} column")+ targets: list[PersonRef] = []+ for line, row in enumerate(reader, start=2):+ try:+ target = PersonRef(team_id=int(row["team_id"]), person_uuid=str(UUID(row["person_uuid"])))+ # A short row leaves its missing cells as None, which raises TypeError instead of ValueError.+ except (TypeError, ValueError) as exc:+ raise CommandError(f"{path}:{line}: {exc}") from exc+ if team_id is None or target.team_id == team_id:+ targets.append(target)+ return targetsdiff --git a/posthog/management/commands/test/test_person_divergence.py b/posthog/management/commands/test/test_person_divergence.pyindex 48085571c26a..cf15c175bc9e 100644--- a/posthog/management/commands/test/test_person_divergence.py+++ b/posthog/management/commands/test/test_person_divergence.py@@ -1,12 +1,57 @@+import csvimport tempfile+from io import StringIOfrom pathlib import Path+from posthog.test.base import BaseTest, ClickhouseTestMixin+from django.core.management import call_commandfrom django.core.management.base import CommandErrorfrom django.test import SimpleTestCasefrom parameterized import parameterized+from posthog.clickhouse.client import sync_execute+from posthog.models.person.util import create_person as create_person_in_ch+from posthog.models.signals import mute_selected_signals+from posthog.test.persons import create_person+++class TestPersonDivergenceCommand(ClickhouseTestMixin, BaseTest):+ def _ch_winner(self, person_uuid: str) -> tuple[int, int]:+ [[deleted, version]] = sync_execute(+ "SELECT argMax(is_deleted, version), max(version) FROM person WHERE team_id = %(team_id)s AND id = %(person_uuid)s",+ {"team_id": self.team.pk, "person_uuid": person_uuid},+ )+ return int(deleted), int(version)++ def _run(self, *args: str) -> list[dict[str, str]]:+ call_command("person_divergence", *args, stdout=StringIO())+ output = Path(args[args.index("--output") + 1])+ with output.open(newline="") as handle:+ return list(csv.DictReader(handle))++ def test_repair_reads_a_scan_csv_and_writes_only_with_apply(self) -> None:+ with mute_selected_signals():+ person = create_person(team=self.team, version=3)+ person_uuid = str(person.uuid)+ create_person_in_ch(team_id=self.team.pk, uuid=person_uuid, version=103, is_deleted=True)++ with tempfile.TemporaryDirectory() as tmp:+ team_range = ["--min-team-id", str(self.team.pk), "--max-team-id", str(self.team.pk + 1)]+ hidden = self._run("scan", "hidden", "--output", f"{tmp}/hidden.csv", *team_range)+ dry_run = self._run("repair", "--input", f"{tmp}/hidden.csv", "--output", f"{tmp}/dry.csv")+ dry_run_winner = self._ch_winner(person_uuid)+ applied = self._run("repair", "--input", f"{tmp}/hidden.csv", "--output", f"{tmp}/apply.csv", "--apply")+ with self.assertRaises(CommandError):+ self._run("repair", "--input", f"{tmp}/hidden.csv", "--output", f"{tmp}/apply.csv")++ assert [(row["person_uuid"], row["kind"]) for row in hidden] == [(person_uuid, "hidden")]+ assert [(row["outcome"], row["target_version"]) for row in dry_run] == [("would_repair", "104")]+ assert dry_run_winner == (1, 103)+ assert [row["outcome"] for row in applied] == ["repaired"]+ assert self._ch_winner(person_uuid) == (0, 104)+class TestPersonDivergenceArguments(SimpleTestCase):@parameterized.expand(@@ -29,3 +74,31 @@ class TestPersonDivergenceArguments(SimpleTestCase):with self.assertRaisesMessage(CommandError, message):call_command("person_divergence", "scan", *scan_args, "--output", str(output))assert not output.exists()++ @parameterized.expand([("zero", "0"), ("negative", "-1")])+ def test_repair_rejects_a_write_rate_that_is_not_above_zero(self, _name: str, rate: str) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ scan = Path(tmp) / "hidden.csv"+ scan.write_text("team_id,person_uuid\n")+ output = Path(tmp) / "dry.csv"+ with self.assertRaisesMessage(CommandError, f"{rate} must be above 0"):+ call_command(+ "person_divergence",+ "repair",+ "--input",+ str(scan),+ "--output",+ str(output),+ "--max-writes-per-second",+ rate,+ )+ assert not output.exists()++ def test_repair_names_the_line_of_a_short_row(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ scan = Path(tmp) / "hidden.csv"+ scan.write_text("team_id,person_uuid\n1,0190f8e1-1234-7abc-89de-f0123456789a\n2\n")+ output = Path(tmp) / "dry.csv"+ with self.assertRaisesMessage(CommandError, f"{scan}:3:"):+ call_command("person_divergence", "repair", "--input", str(scan), "--output", str(output))+ assert not output.exists()diff --git a/posthog/models/person/divergence.py b/posthog/models/person/divergence.pyindex 098e5cec8abe..2fe1a6025561 100644--- a/posthog/models/person/divergence.py+++ b/posthog/models/person/divergence.py@@ -1,24 +1,55 @@-"""Find persons whose ClickHouse rows disagree with the persons database.+"""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.+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+holds a version at or above the Postgres one, the repair first raises the Postgres version above+it, so the published row wins and the next ingestion update still outranks it."""from __future__ import annotations-from collections import defaultdict-from collections.abc import Callable-from typing import Any, Literal+import time+from collections import Counter, defaultdict+from collections.abc import Callable, Sequence+from dataclasses import field+from functools import partial+from typing import Any, Literal, TypeVarfrom uuid import UUID+import grpc+from posthog.clickhouse.client import sync_executefrom posthog.clickhouse.workload import Workloadfrom posthog.dataclasses import frozen+from posthog.errors import CH_TRANSIENT_ERRORSfrom posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut-from posthog.models.person.util import _batched_get_persons_by_uuids-from posthog.personhog_client.client import personhog_call-from posthog.personhog_client.proto import ReadOptions--PersonDivergenceKind = Literal["hidden", "swept", "stale"]+from posthog.kafka_client.client import ClickhouseProducer, ProduceResult+from posthog.kafka_client.routing import flush_all_producers+from posthog.kafka_client.topics import KAFKA_PERSON+from posthog.models.person import Person+from posthog.models.person.sql import INSERT_PERSON_SQL+from posthog.models.person.util import (+ _batched_get_persons_by_uuids,+ _person_row,+ get_person_tombstones,+ get_persons_by_uuids,+)+from posthog.models.team import Team+from posthog.personhog_client.client import personhog_call, require_personhog_client+from posthog.personhog_client.interceptor import is_transient_rpc_error+from posthog.personhog_client.proto import ReadOptions, SetPersonVersionFloorRequest++PersonDivergenceKind = Literal["hidden", "swept", "stale", "behind", "absent"]+RepairOutcome = Literal[+ "would_repair",+ "repaired",+ "skipped_not_divergent",+ "skipped_not_live",+ "skipped_team_gone",+ "skipped_tombstoned",+ "skipped_reread_lagging",+ "skipped_stale",+]# The legacy delete path wrote ClickHouse tombstones at version + 100, so those rows sit at 100 or above.LEGACY_TOMBSTONE_MIN_VERSION = 100@@ -34,10 +65,26 @@ _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}# 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+# 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)+_TRANSIENT_RPC_CODES = frozenset(+ {grpc.StatusCode.INTERNAL, grpc.StatusCode.UNAVAILABLE, grpc.StatusCode.DEADLINE_EXCEEDED}+)+_FLUSH_TIMEOUT_SECONDS = 5 * 60+# Confirmed produce results are dropped this often, so a long repair does not hold one per published row.+_DELIVERY_PRUNE_EVERY = 1_000++_T = TypeVar("_T")++_sleep = time.sleep+@frozenclass DivergentPerson:@@ -55,7 +102,35 @@ class ScanSummary:skipped_team_ids: list[int]-# ── ClickHouse and personhog access ──────────────────────────────────+@frozen+class PersonRef:+ team_id: int+ person_uuid: str++ def __post_init__(self) -> None:+ # Lookups key on the canonical form that ClickHouse toString(id) and the persons reads return.+ if str(UUID(self.person_uuid)) != self.person_uuid:+ raise ValueError(f"person_uuid must be a canonical lowercase UUID: {self.person_uuid!r}")+++@frozen+class RepairAction:+ team_id: int+ person_uuid: str+ kind: PersonDivergenceKind | None+ pg_version: int | None+ ch_max_version: int | None+ target_version: int | None+ outcome: RepairOutcome+++@frozen+class RepairSummary:+ applied: bool+ persons: int+ person_outcomes: dict[RepairOutcome, int]+ # Published rows that Kafka did not confirm: the delivery failed, or it was still queued at the deadline.+ undelivered: intdef _ch(sql: str, args: dict[str, Any], settings: dict[str, int]) -> list[Any]:@@ -72,6 +147,12 @@ def _live_person_versions(team_id: int, person_uuids: list[str], operation: str)return {str(UUID(p.uuid)): int(p.version) for p in persons}+def _tombstoned_uuids(team_id: int, person_uuids: list[str]) -> set[str]:+ if not person_uuids:+ return set()+ return {str(t.uuid) for t in get_person_tombstones(team_id, [UUID(u) for u in person_uuids])}++def _resolve_max_team_id(max_team_id: int | None) -> int:if max_team_id is not None:return max_team_id@@ -79,7 +160,8 @@ def _resolve_max_team_id(max_team_id: int | None) -> int:return int(highest or 0) + 1-# ── Scans over team ranges ───────────────────────────────────────────+def _chunks(items: Sequence[_T], size: int) -> list[Sequence[_T]]:+ return [items[i : i + size] for i in range(0, len(items), size)]def _scan_team_ranges(@@ -291,3 +373,368 @@ def scan_stale_persons(on_found=on_found,log=log,)+++# ── Repair ───────────────────────────────────────────────────────────+++@frozen+class _ChPersonState:+ visible_rows: int+ visible_max_version: int+ visible_winner_deleted: bool+ # Includes lightweight-deleted rows, so a republish lands above every row the sweep masked.+ max_version: int+++@frozen+class _PersonPlan:+ team_id: int+ person_uuid: str+ person: Person | None+ kind: PersonDivergenceKind | None+ ch_max_version: int | None+ target_version: int | None+++_PERSON_STATE_SQL = """+SELECT+ toString(id),+ countIf(_row_exists),+ maxIf(version, _row_exists),+ argMaxIf(is_deleted, version, _row_exists),+ max(version)+FROM person+WHERE team_id = %(team_id)s AND id IN %(person_uuids)s+GROUP BY 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+ # never landed leaves ClickHouse below Postgres, and a rerun must still finish it.+ if state is None:+ return "absent"+ if state.visible_rows == 0:+ return "swept"+ if state.visible_winner_deleted:+ return "hidden"+ if state.visible_max_version > pg_version:+ return "stale"+ if state.visible_max_version < pg_version:+ return "behind"+ 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.+ return pg_version if ch_max_version is None else max(pg_version, ch_max_version + 1)+++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)+ return {+ person_uuid: _ChPersonState(+ visible_rows=int(visible_rows),+ visible_max_version=int(visible_max_version),+ visible_winner_deleted=bool(visible_winner_deleted),+ max_version=int(max_version),+ )+ for person_uuid, visible_rows, visible_max_version, visible_winner_deleted, max_version in rows+ }+++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 {}++ plans: list[_PersonPlan] = []+ for person_uuid in person_uuids:+ person = live.get(person_uuid)+ if person is None:+ plans.append(+ _PersonPlan(+ team_id=team_id,+ person_uuid=person_uuid,+ person=None,+ kind=None,+ ch_max_version=None,+ target_version=None,+ )+ )+ continue+ pg_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+ plans.append(+ _PersonPlan(+ team_id=team_id,+ person_uuid=person_uuid,+ person=person,+ kind=_person_kind(pg_version, state),+ ch_max_version=ch_max_version,+ target_version=_target_version(pg_version, ch_max_version),+ )+ )+ return plans+++def _raise_person_version_floor(team_id: int, person_id: int, min_version: int) -> None:+ personhog_call(+ "person_divergence_set_person_version_floor",+ lambda: require_personhog_client().set_person_version_floor(+ SetPersonVersionFloorRequest(team_id=team_id, person_id=person_id, min_version=min_version)+ ),+ )+++def _person_action(plan: _PersonPlan, outcome: RepairOutcome) -> RepairAction:+ return RepairAction(+ team_id=plan.team_id,+ person_uuid=plan.person_uuid,+ 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,+ target_version=plan.target_version if plan.kind is not None else None,+ outcome=outcome,+ )+++def _publish_person(team_id: int, person: Person) -> ProduceResult:+ row = _person_row(+ team_id=team_id,+ uuid=str(person.uuid),+ version=int(person.version or 0),+ properties=person.properties,+ is_identified=person.is_identified,+ is_deleted=False,+ created_at=person.created_at,+ last_seen_at=person.last_seen_at,+ )+ # _person_row fills a missing last_seen_at with the current hour, but ingestion publishes null for it.+ if person.last_seen_at is None:+ row["last_seen_at"] = None+ return ClickhouseProducer().produce(topic=KAFKA_PERSON, sql=INSERT_PERSON_SQL, data=row)+++def _reread_person(team_id: int, person_uuid: str, target_version: int | None) -> Person | None:+ """Read the person from the replica again while it shows a version below ``target_version``."""+ found = get_persons_by_uuids(team_id, [person_uuid], distinct_id_limit=0)+ reread = found[0] if found else None+ for delay in _REREAD_BACKOFF_SECONDS:+ if reread is None or target_version is None or int(reread.version or 0) >= target_version:+ break+ _sleep(delay)+ found = get_persons_by_uuids(team_id, [person_uuid], distinct_id_limit=0)+ reread = found[0] if found else None+ return reread+++def _is_transient(exc: BaseException) -> bool:+ return isinstance(exc, (*CH_TRANSIENT_ERRORS, ClickHouseQueryTimeOut)) or is_transient_rpc_error(+ exc, codes=_TRANSIENT_RPC_CODES+ )+++def _retry_transient(fn: Callable[[], _T], *, what: str, log: Callable[[str], None]) -> _T:+ """Run ``fn`` again after a transient ClickHouse or personhog error, then re-raise once the retries run out.++ Repeating a step is safe because every repair write is idempotent: a version raise never lowers a+ version, and ClickHouse keeps one row per version.+ """+ for delay in _TRANSIENT_RETRY_BACKOFF_SECONDS:+ try:+ return fn()+ except Exception as exc:+ if not _is_transient(exc):+ raise+ log(f"{what}: {type(exc).__name__}, retrying in {delay:g} s")+ _sleep(delay)+ return fn()+++def _execute_plan(+ plan: _PersonPlan,+ *,+ apply: bool,+ include_stale: bool,+ before_write: Callable[[], None],+ published: Callable[[ProduceResult], None],+) -> list[RepairAction]:+ person = plan.person+ 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")]++ if not apply:+ person_outcome: RepairOutcome = "would_repair" if plan.kind is not None else "skipped_not_divergent"+ return [+ _person_action(plan, person_outcome),+ ]++ pg_version = int(person.version or 0)+ if plan.kind is not None and plan.target_version is not None and plan.target_version > pg_version:+ before_write()+ _raise_person_version_floor(plan.team_id, person.pk, plan.target_version)++ # 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 = None+ if 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"+ return [+ _person_action(plan, person_outcome),+ ]++ if plan.kind is None:+ person_outcome = "skipped_not_divergent"+ elif reread is None:+ person_outcome = "skipped_not_live"+ elif plan.target_version is None or int(reread.version or 0) < plan.target_version:+ # The replica has not caught up with the raise, so its properties may predate the raised version.+ person_outcome = "skipped_reread_lagging"+ else:+ published(_publish_person(plan.team_id, reread))+ person_outcome = "repaired"++ return [_person_action(plan, person_outcome)]+++@frozen(frozen=False)+class _WritePacer:+ """Space writes at least 1 / max_per_second apart, so idle time never buys a later burst."""++ max_per_second: float | None+ next_write_at: float = 0.0++ def before_write(self) -> None:+ if self.max_per_second is None:+ return+ now = time.monotonic()+ if now < self.next_write_at:+ time.sleep(self.next_write_at - now)+ now = self.next_write_at+ self.next_write_at = now + 1 / self.max_per_second+++@frozen(frozen=False)+class _Deliveries:+ """Kafka produce results of the published rows, so a failed delivery counts as undelivered."""++ pending: list[ProduceResult] = field(default_factory=list)+ failed: int = 0++ def track(self, result: ProduceResult) -> None:+ self.pending.append(result)+ if len(self.pending) >= _DELIVERY_PRUNE_EVERY:+ self._prune()++ def undelivered(self, timeout: float) -> int:+ flush_all_producers(timeout)+ self._prune()+ return self.failed + len(self.pending)++ def _prune(self) -> None:+ waiting: list[ProduceResult] = []+ for result in self.pending:+ if not result.done():+ waiting.append(result)+ continue+ try:+ result.get(timeout=0)+ except Exception:+ self.failed += 1+ self.pending = waiting+++def repair_persons(+ targets: Sequence[PersonRef],+ *,+ apply: bool,+ include_stale: bool = False,+ max_writes_per_second: float | None = None,+ on_action: Callable[[RepairAction], None],+ log: Callable[[str], None],+) -> RepairSummary:+ """Republish the Postgres state of each target person 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 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.+ """+ if max_writes_per_second is not None and max_writes_per_second <= 0:+ raise ValueError("max_writes_per_second must be above 0")+ by_team: dict[int, list[str]] = defaultdict(list)+ for target in dict.fromkeys(targets):+ by_team[target.team_id].append(target.person_uuid)++ person_outcomes: Counter[RepairOutcome] = Counter()+ processed = 0+ undelivered = 0+ pacer = _WritePacer(max_per_second=max_writes_per_second)+ deliveries = _Deliveries()+ existing_teams = set(Team.objects.filter(id__in=list(by_team)).values_list("id", flat=True))+ try:+ for team_id, person_uuids in sorted(by_team.items()):+ if team_id not in existing_teams:+ # A deleted team's ClickHouse rows go with the team, so a repair would only republish what the deletion removed.+ for person_uuid in person_uuids:+ action = RepairAction(+ team_id=team_id,+ person_uuid=person_uuid,+ kind=None,+ pg_version=None,+ ch_max_version=None,+ target_version=None,+ outcome="skipped_team_gone",+ )+ person_outcomes[action.outcome] += 1+ on_action(action)+ processed += 1+ log(f"team {team_id}: no longer exists, {len(person_uuids)} persons skipped")+ continue+ for chunk in _chunks(person_uuids, _REPAIR_CHUNK_SIZE):+ plans = _retry_transient(+ partial(_plan_chunk, team_id, chunk), what=f"team {team_id}: planning", log=log+ )+ for plan in plans:+ # Only the attempt that succeeds returns actions, so a retried person is counted once.+ actions = _retry_transient(+ partial(+ _execute_plan,+ plan,+ apply=apply,+ include_stale=include_stale,+ before_write=pacer.before_write,+ published=deliveries.track,+ ),+ what=f"team {team_id} person {plan.person_uuid}",+ log=log,+ )+ for action in actions:+ person_outcomes[action.outcome] += 1+ on_action(action)+ processed += 1+ log(f"team {team_id}: {len(person_uuids)} persons, {processed} processed in total")+ finally:+ if apply:+ undelivered = deliveries.undelivered(_FLUSH_TIMEOUT_SECONDS)+ if undelivered:+ log(f"{undelivered} ClickHouse messages were not delivered; rerun the repair for the same input")+ return RepairSummary(+ applied=apply,+ persons=processed,+ person_outcomes=dict(person_outcomes),+ undelivered=undelivered,+ )diff --git a/posthog/models/person/test/test_divergence.py b/posthog/models/person/test/test_divergence.pyindex 0054241debc4..65a7edfc9a9a 100644--- a/posthog/models/person/test/test_divergence.py+++ b/posthog/models/person/test/test_divergence.py@@ -4,18 +4,30 @@ from typing import Anyfrom uuid import UUID, uuid4from posthog.test.base import BaseTest, ClickhouseTestMixin-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom django.test import SimpleTestCasefrom django.utils.timezone import now+import grpc+from confluent_kafka import KafkaErrorfrom parameterized import parameterized+from personhog.types.v1 import person_pb2from posthog.clickhouse.client import sync_executefrom posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut+from posthog.kafka_client.client import ClickhouseProducer, ProduceResult+from posthog.kafka_client.topics import KAFKA_PERSONfrom posthog.models.person import Personfrom posthog.models.person.divergence import (DivergentPerson,+ PersonDivergenceKind,+ PersonRef,+ RepairAction,+ RepairOutcome,+ RepairSummary,+ _WritePacer,+ repair_persons,scan_hidden_persons,scan_stale_persons,scan_swept_persons,@@ -25,6 +37,8 @@ from posthog.models.person.util import (tombstone_persons_in_postgres,)from posthog.models.signals import mute_selected_signals+from posthog.models.team import Team+from posthog.personhog_client.fake_client import get_active_fakefrom posthog.test.persons import add_distinct_id, create_personPG_PROPERTIES = {"email": "[email protected]"}@@ -35,6 +49,12 @@ _PERSON_COLUMNS = ()+def _rpc_error(code: grpc.StatusCode) -> grpc.RpcError:+ error = grpc.RpcError()+ error.code = MagicMock(return_value=code)+ return error++def _utc_naive(hours_ago: float) -> datetime:return (now() - timedelta(hours=hours_ago)).astimezone(UTC).replace(tzinfo=None)@@ -103,7 +123,64 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):sync_execute(f"DELETE FROM {staging} WHERE 1", settings={"lightweight_deletes_sync": 2})sync_execute(f"ALTER TABLE person ATTACH PARTITION tuple() FROM {staging}")- # ── Scans ────────────────────────────────────────────────────────+ def _ch_person(self, person_uuid: UUID | str) -> tuple[int, int, dict[str, Any]]:+ [[deleted, version, properties]] = sync_execute(+ """+ SELECT argMax(is_deleted, version), max(version), argMax(properties, version)+ FROM person WHERE team_id = %(team_id)s AND id = %(person_uuid)s+ """,+ {"team_id": self.team.pk, "person_uuid": str(person_uuid)},+ )+ return int(deleted), int(version), json.loads(properties)++ def _pg_version(self, person: Person) -> int:+ stored = get_active_fake().stored_person(self.team.pk, str(person.uuid))+ assert stored is not None+ return stored.version++ 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(+ """+ SELECT last_seen_at FROM person WHERE team_id = %(team_id)s AND id = %(person_uuid)s+ ORDER BY version DESC LIMIT 1+ """,+ {"team_id": self.team.pk, "person_uuid": str(person_uuid)},+ )+ return last_seen_at++ def _repair(+ self, *person_uuids: UUID | str, apply: bool = True, include_stale: bool = False+ ) -> tuple[RepairSummary, list[RepairAction]]:+ actions: list[RepairAction] = []+ summary = repair_persons(+ [PersonRef(team_id=self.team.pk, person_uuid=str(u)) for u in person_uuids],+ apply=apply,+ include_stale=include_stale,+ on_action=actions.append,+ log=lambda _: None,+ )+ return summary, actions++ def _action(+ self,+ person_uuid: UUID | str,+ outcome: RepairOutcome,+ *,+ kind: PersonDivergenceKind | None = None,+ pg_version: int | None = None,+ ch_max_version: int | None = None,+ target_version: int | None = None,+ ) -> RepairAction:+ return RepairAction(+ team_id=self.team.pk,+ person_uuid=str(person_uuid),+ kind=kind,+ pg_version=pg_version,+ ch_max_version=ch_max_version,+ target_version=target_version,+ outcome=outcome,+ )def _team_scan_range(self) -> dict[str, int]:return {"min_team_id": self.team.pk, "max_team_id": self.team.pk + 1}@@ -179,6 +256,343 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):]assert (summary.candidates, summary.divergent) == (2, 1)+ # ── Repair ───────────────────────────────────────────────────────++ def _divergent_person(self, case: str) -> Person:+ if case == "hidden":+ person = self._pg_person(version=3)+ self._ch_person_row(person.uuid, 3)+ self._ch_person_row(person.uuid, 103, deleted=True)+ elif case == "hidden_after_an_undelivered_publish":+ person = self._pg_person(version=104)+ self._ch_person_row(person.uuid, 103, deleted=True)+ elif case == "stale":+ person = self._pg_person(version=5)+ self._ch_person_row(person.uuid, 10)+ self._ch_person_row(person.uuid, 5)+ elif case == "swept":+ person = self._pg_person(version=3)+ self._swept_rows({person.uuid: [(103, True, 2), (4, False, 1)]})+ elif case == "behind":+ person = self._pg_person(version=7)+ self._ch_person_row(person.uuid, 5)+ else:+ person = self._pg_person(version=3)+ return person++ @parameterized.expand(+ [+ ("hidden", "hidden", 3, 103, 104),+ ("hidden_after_an_undelivered_publish", "hidden", 104, 103, 104),+ ("stale", "stale", 5, 10, 11),+ ("swept", "swept", 3, 103, 104),+ ("behind", "behind", 7, 5, 7),+ ("absent", "absent", 3, None, 3),+ ]+ )+ def test_republishes_a_divergent_person_live_one_version_above_clickhouse(+ self, case: str, kind: PersonDivergenceKind, pg_version: int, ch_max_version: int | None, target_version: int+ ) -> None:+ person = self._divergent_person(case)++ summary, actions = self._repair(person.uuid, include_stale=True)++ assert actions == [+ self._action(+ person.uuid,+ "repaired",+ kind=kind,+ pg_version=pg_version,+ ch_max_version=ch_max_version,+ target_version=target_version,+ )+ ]+ assert (summary.persons, summary.undelivered) == (1, 0)+ assert self._pg_version(person) == target_version+ assert self._ch_person(person.uuid) == (0, target_version, PG_PROPERTIES)+ # Postgres has no last_seen_at for this person, and ingestion publishes that as null.+ 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)+ self._ch_person_row(person.uuid, 3)+ self._ch_person_row(person.uuid, 103, 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),+ ]+ assert summary.applied is apply+ if apply:+ assert self._pg_version(person) == 104+ assert self._ch_person(person.uuid) == (0, 104, PG_PROPERTIES)+ else:+ get_active_fake().assert_not_called("set_person_version_floor")+ assert self._pg_version(person) == 3+ assert self._ch_person(person.uuid) == (1, 103, CH_PROPERTIES)++ @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)+ self._ch_person_row(person.uuid, 103, deleted=True)+ other = self._pg_person(version=3)+ self._ch_person_row(other.uuid, 103, deleted=True)++ with patch("posthog.models.person.divergence.time") as clock:+ clock.monotonic.return_value = 0.0+ repair_persons(+ [PersonRef(team_id=self.team.pk, person_uuid=str(p.uuid)) for p in (person, other)],+ apply=apply,+ max_writes_per_second=1,+ on_action=lambda _: None,+ log=lambda _: None,+ )++ assert [c.args[0] for c in clock.sleep.call_args_list] == sleeps++ def test_publishes_the_properties_postgres_holds_after_the_raise(self) -> None:+ person = self._divergent_person("hidden")+ fake = get_active_fake()+ raise_floor = fake.set_person_version_floor+ updated = {"email": "[email protected]"}++ def ingestion_update_then_raise(+ request: person_pb2.SetPersonVersionFloorRequest, timeout: float | None = None+ ) -> person_pb2.SetPersonVersionFloorResponse:+ stored = fake.stored_person(self.team.pk, str(person.uuid))+ assert stored is not None+ stored.properties = json.dumps(updated).encode()+ stored.version += 1+ return raise_floor(request, timeout)++ with patch.object(fake, "set_person_version_floor", side_effect=ingestion_update_then_raise):+ self._repair(person.uuid)++ assert self._ch_person(person.uuid) == (0, 104, updated)++ def test_a_failed_kafka_delivery_counts_as_undelivered(self) -> None:+ person = self._divergent_person("hidden")+ failed = ProduceResult(topic=KAFKA_PERSON)+ failed.set_result(KafkaError(-192, "Local: Message timed out"), None)++ with patch.object(ClickhouseProducer, "produce", return_value=failed):+ summary, actions = self._repair(person.uuid)++ assert [a.outcome for a in actions] == ["repaired"]+ assert summary.undelivered == 1++ @parameterized.expand(+ [+ ("replica_catches_up_on_the_third_reread", 3, "repaired", [0.025, 0.05]),+ ("replica_never_catches_up", None, "skipped_reread_lagging", [0.025, 0.05, 0.1, 0.15, 0.175]),+ ]+ )+ def test_rereads_until_the_replica_shows_the_raise(+ self, _name: str, caught_up_on_reread: int | None, outcome: RepairOutcome, sleeps: list[float]+ ) -> None:+ person = self._divergent_person("hidden")+ fake = get_active_fake()+ read = fake.get_persons_by_uuids+ raised_to: list[int] = []+ rereads = 0++ def primary_only_raise(+ request: person_pb2.SetPersonVersionFloorRequest, timeout: float | None = None+ ) -> person_pb2.SetPersonVersionFloorResponse:+ raised_to.append(request.min_version)+ return person_pb2.SetPersonVersionFloorResponse(updated=True)++ def lagging_replica(request: person_pb2.GetPersonsByUuidsRequest) -> person_pb2.PersonsResponse:+ nonlocal rereads+ if raised_to:+ rereads += 1+ if rereads == caught_up_on_reread:+ stored = fake.stored_person(self.team.pk, str(person.uuid))+ assert stored is not None+ stored.version = raised_to[0]+ return read(request)++ with (+ patch.object(fake, "set_person_version_floor", side_effect=primary_only_raise),+ patch.object(fake, "get_persons_by_uuids", side_effect=lagging_replica),+ patch("posthog.models.person.divergence._sleep") as sleep,+ ):+ _, actions = self._repair(person.uuid)++ assert [a.outcome for a in actions] == [outcome]+ assert [c.args[0] for c in sleep.call_args_list] == sleeps+ if outcome == "repaired":+ assert self._ch_person(person.uuid) == (0, 104, PG_PROPERTIES)+ else:+ assert self._ch_person(person.uuid) == (1, 103, CH_PROPERTIES)++ @parameterized.expand(+ [+ ("clickhouse_timeout_while_planning", "planning", ClickHouseQueryTimeOut()),+ ("personhog_internal_error_on_the_raise", "raise", grpc.StatusCode.INTERNAL),+ ("personhog_unavailable_on_the_raise", "raise", grpc.StatusCode.UNAVAILABLE),+ ]+ )+ def test_retries_a_transient_error_and_counts_the_person_once(+ self, _name: str, step: str, error: Exception | grpc.StatusCode+ ) -> None:+ person = self._divergent_person("hidden")+ failure = _rpc_error(error) if isinstance(error, grpc.StatusCode) else error++ with self._failing_once(step, failure), patch("posthog.models.person.divergence._sleep") as sleep:+ summary, actions = self._repair(person.uuid)++ assert [a.outcome for a in actions] == ["repaired"]+ assert summary.person_outcomes == {"repaired": 1}+ assert [c.args[0] for c in sleep.call_args_list] == [1.0]+ assert self._ch_person(person.uuid) == (0, 104, PG_PROPERTIES)++ @parameterized.expand(+ [+ ("non_transient_error_is_not_retried", ValueError("bad request"), 1, []),+ ("transient_error_on_every_attempt_stops_after_three", _rpc_error(grpc.StatusCode.INTERNAL), 3, [1.0, 2.0]),+ ]+ )+ def test_stops_the_run_on_an_error_that_does_not_clear(+ self, _name: str, failure: Exception, attempts: int, sleeps: list[float]+ ) -> None:+ person = self._divergent_person("hidden")+ fake = get_active_fake()++ with (+ patch.object(fake, "set_person_version_floor", side_effect=failure) as raise_floor,+ patch("posthog.models.person.divergence._sleep") as sleep,+ ):+ with self.assertRaises(type(failure)):+ self._repair(person.uuid)++ assert raise_floor.call_count == attempts+ assert [c.args[0] for c in sleep.call_args_list] == sleeps++ def _failing_once(self, step: str, failure: Exception) -> Any:+ fake = get_active_fake()+ if step == "planning":+ query = sync_execute+ failed: list[bool] = []++ def ch_fails_once(*args: Any, **kwargs: Any) -> Any:+ if not failed:+ failed.append(True)+ raise failure+ return query(*args, **kwargs)++ return patch("posthog.models.person.divergence.sync_execute", side_effect=ch_fails_once)+ raise_floor = fake.set_person_version_floor+ calls: list[bool] = []++ def raise_fails_once(+ request: person_pb2.SetPersonVersionFloorRequest, timeout: float | None = None+ ) -> person_pb2.SetPersonVersionFloorResponse:+ if not calls:+ calls.append(True)+ raise failure+ return raise_floor(request, timeout)++ return patch.object(fake, "set_person_version_floor", side_effect=raise_fails_once)++ def _skipped_person(self, case: str) -> UUID:+ if case == "in_sync":+ person = self._pg_person(version=3)+ self._ch_person_row(person.uuid, 3)+ return person.uuid+ if case == "tombstoned_in_postgres":+ person = self._pg_person(version=3)+ tombstone_persons_in_postgres(self.team.pk, [person.uuid])+ self._ch_person_row(person.uuid, 103, deleted=True)+ return person.uuid+ if case == "stale_without_include_stale":+ return self._divergent_person("stale").uuid+ absent = uuid4()+ self._ch_person_row(absent, 103, deleted=True)+ return absent++ @parameterized.expand(+ [+ ("in_sync", ["skipped_not_divergent"]),+ ("tombstoned_in_postgres", ["skipped_not_live"]),+ ("absent_from_postgres", ["skipped_not_live"]),+ ("stale_without_include_stale", ["skipped_stale"]),+ ]+ )+ def test_leaves_a_person_alone_unless_it_is_live_in_postgres_and_divergent(+ self, case: str, outcomes: list[str]+ ) -> None:+ person_uuid = self._skipped_person(case)+ before = self._ch_person(person_uuid)++ _, actions = self._repair(person_uuid)++ assert [a.outcome for a in actions] == outcomes+ get_active_fake().assert_not_called("set_person_version_floor")+ assert self._ch_person(person_uuid) == before++ def test_skips_every_person_of_a_team_that_no_longer_exists(self) -> None:+ missing_team_id = self.team.pk + 1_000_000+ assert not Team.objects.filter(pk=missing_team_id).exists()+ person_uuid = str(uuid4())+ get_active_fake().add_person(team_id=missing_team_id, person_id=987654, uuid=person_uuid, version=3)+ self._ch_person_row(person_uuid, 3, team_id=missing_team_id)+ self._ch_person_row(person_uuid, 103, deleted=True, team_id=missing_team_id)+ actions: list[RepairAction] = []++ summary = repair_persons(+ [PersonRef(team_id=missing_team_id, person_uuid=person_uuid)],+ apply=True,+ on_action=actions.append,+ log=lambda _: None,+ )++ assert [a.outcome for a in actions] == ["skipped_team_gone"]+ assert summary.person_outcomes == {"skipped_team_gone": 1}+ get_active_fake().assert_not_called("set_person_version_floor")+ 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)+ self._ch_person_row(person.uuid, 103, deleted=True)+ fake = get_active_fake()+ replica_view = person_pb2.Person()+ stored = fake.stored_person(self.team.pk, str(person.uuid))+ assert stored is not None+ replica_view.CopyFrom(stored)+ tombstone_persons_in_postgres(self.team.pk, [person.uuid])++ with patch.object(+ fake, "get_persons_by_uuids", return_value=person_pb2.PersonsResponse(persons=[replica_view])+ ):+ _, actions = self._repair(person.uuid)++ assert [a.outcome for a in actions] == ["skipped_tombstoned"]+ assert self._ch_person(person.uuid)[:2] == (1, 103)+++class TestWritePacer(SimpleTestCase):+ def test_idle_time_before_the_writes_buys_no_burst(self) -> None:+ clock = [0.0]+ sleeps: list[float] = []++ def sleep(seconds: float) -> None:+ sleeps.append(seconds)+ clock[0] += seconds++ with patch("posthog.models.person.divergence.time") as time_module:+ time_module.monotonic.side_effect = lambda: clock[0]+ time_module.sleep.side_effect = sleep+ pacer = _WritePacer(max_per_second=2)+ clock[0] = 10.0+ for _ in range(3):+ pacer.before_write()++ assert sleeps == [0.5, 0.5]+class TestScanTeamRanges(SimpleTestCase):@parameterized.expand([("out_of_memory", ClickHouseQueryMemoryLimitExceeded), ("timeout", ClickHouseQueryTimeOut)])