: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 person divergence scans (#111674)
Eli Reisman0cf8b00118f4
diff --git a/posthog/management/commands/person_divergence.py b/posthog/management/commands/person_divergence.pynew file mode 100644index 000000000000..86542d79d909--- /dev/null+++ b/posthog/management/commands/person_divergence.py@@ -0,0 +1,150 @@+"""Scan for persons whose ClickHouse rows disagree with the persons database.++Usage:+ python manage.py person_divergence scan hidden --output hidden.csv+ python manage.py person_divergence scan swept --output swept.csv+ python manage.py person_divergence scan stale --window-days 60 --output stale.csv++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.+"""++import csv+import time+import argparse+import dataclasses+from collections.abc import Callable+from pathlib import Path+from typing import Any, TextIO++from django.core.management.base import BaseCommand, CommandError, CommandParser++from posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.models.person.divergence import (+ HIDDEN_TEAM_STEP,+ STALE_TEAM_STEP,+ SWEPT_TEAM_STEP,+ DivergentPerson,+ ScanSummary,+ scan_hidden_persons,+ scan_stale_persons,+ scan_swept_persons,+)++_DIVERGENT_SCANS: dict[str, tuple[Callable[..., ScanSummary], int, str]] = {+ "hidden": (+ scan_hidden_persons,+ HIDDEN_TEAM_STEP,+ "Persons live in Postgres whose newest ClickHouse row is a legacy (version 100 or above) tombstone. "+ "Run it right before every ClickHouse deletion sweep: the sweep deletes the rows of every person it finds.",+ ),+ "swept": (+ scan_swept_persons,+ SWEPT_TEAM_STEP,+ "Persons live in Postgres whose ClickHouse rows were all lightweight-deleted after a legacy tombstone. "+ "Run it soon after a sweep: once ClickHouse merges remove those rows, no scan finds the person.",+ ),+ "stale": (+ scan_stale_persons,+ STALE_TEAM_STEP,+ "Persons whose live ClickHouse winner outranks Postgres, found through a late lower-version row.",+ ),+}+++class Command(BaseCommand):+ help = "Scan for persons whose ClickHouse rows disagree with the persons database. Scans are read-only."++ def add_arguments(self, parser: CommandParser) -> None:+ actions = parser.add_subparsers(dest="action", required=True, metavar="action")++ scan = actions.add_parser("scan", help="Read-only. Write what a scan finds to a CSV.")+ scans = scan.add_subparsers(dest="scan", required=True, metavar="scan")+ for name, (_, team_step, description) in _DIVERGENT_SCANS.items():+ divergent = scans.add_parser(name, help=description)+ self._add_output(divergent)+ self._add_team_range(divergent)+ divergent.add_argument(+ "--team-step",+ type=_positive_int,+ default=team_step,+ help="Team ids per ClickHouse query (default: %(default)s).",+ )+ if name == "stale":+ divergent.add_argument(+ "--window-days",+ type=_positive_int,+ default=60,+ help="Only persons written in the last N days (default: %(default)s).",+ )++ @staticmethod+ def _add_output(parser: CommandParser) -> None:+ parser.add_argument("--output", type=Path, required=True, help="CSV to create. Must not exist.")++ @staticmethod+ def _add_team_range(parser: CommandParser) -> None:+ parser.add_argument("--min-team-id", type=int, default=0, help="First team id, inclusive (default: 0).")+ parser.add_argument(+ "--max-team-id",+ type=int,+ default=None,+ help="Last team id, exclusive (default: the highest in ClickHouse).",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ with tags_context(product=Product.INTERNAL, feature=Feature.MANAGEMENT_COMMAND):+ self._scan(options)++ def _log(self, message: str) -> None:+ self.stdout.write(f"{time.strftime('%H:%M:%S')} {message}")+ self.stdout.flush()++ def _scan(self, options: dict[str, Any]) -> None:+ name = options["scan"]+ # An empty team range scans nothing and would read as a clean fleet.+ if options["max_team_id"] is not None and options["max_team_id"] <= options["min_team_id"]:+ raise CommandError("--max-team-id must be above --min-team-id")+ with _open_output(options["output"]) as handle:+ if name in _DIVERGENT_SCANS:+ scan_fn, _, _ = _DIVERGENT_SCANS[name]+ extra = {"window_days": options["window_days"]} if name == "stale" else {}+ summary = scan_fn(+ min_team_id=options["min_team_id"],+ max_team_id=options["max_team_id"],+ team_step=options["team_step"],+ on_found=_csv_sink(handle, DivergentPerson),+ log=self._log,+ **extra,+ )+ self._log(+ f"{name} scan: {summary.candidates} ClickHouse candidates, {summary.divergent} divergent, "+ f"skipped teams {summary.skipped_team_ids}"+ )+++def _positive_int(value: str) -> int:+ number = int(value)+ if number < 1:+ raise argparse.ArgumentTypeError(f"{value} must be 1 or more")+ return number+++def _open_output(path: Path) -> TextIO:+ try:+ return path.open("x", newline="")+ except FileExistsError as exc:+ raise CommandError(f"{path} already exists; choose a new --output") from exc+++def _csv_sink(handle: TextIO, row_type: type[Any]) -> Callable[[Any], None]:+ writer = csv.DictWriter(handle, fieldnames=[field.name for field in dataclasses.fields(row_type)])+ writer.writeheader()++ def write(row: Any) -> None:+ writer.writerow(dataclasses.asdict(row))+ # Flush each row so a scan that dies part way keeps everything it reported.+ handle.flush()++ return writediff --git a/posthog/management/commands/test/test_person_divergence.py b/posthog/management/commands/test/test_person_divergence.pynew file mode 100644index 000000000000..48085571c26a--- /dev/null+++ b/posthog/management/commands/test/test_person_divergence.py@@ -0,0 +1,31 @@+import tempfile+from pathlib import Path++from django.core.management import call_command+from django.core.management.base import CommandError+from django.test import SimpleTestCase++from parameterized import parameterized+++class TestPersonDivergenceArguments(SimpleTestCase):+ @parameterized.expand(+ [+ ("team_step_zero", ["hidden", "--team-step", "0"], "0 must be 1 or more"),+ ("team_step_negative", ["hidden", "--team-step", "-5"], "-5 must be 1 or more"),+ ("window_days_zero", ["stale", "--window-days", "0"], "0 must be 1 or more"),+ (+ "empty_team_range",+ ["hidden", "--min-team-id", "5", "--max-team-id", "5"],+ "--max-team-id must be above --min-team-id",+ ),+ ]+ )+ def test_scan_rejects_arguments_that_would_check_nothing(+ self, _name: str, scan_args: list[str], message: str+ ) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ output = Path(tmp) / "scan.csv"+ with self.assertRaisesMessage(CommandError, message):+ call_command("person_divergence", "scan", *scan_args, "--output", str(output))+ assert not output.exists()diff --git a/posthog/models/person/divergence.py b/posthog/models/person/divergence.pynew file mode 100644index 000000000000..098e5cec8abe--- /dev/null+++ b/posthog/models/person/divergence.py@@ -0,0 +1,293 @@+"""Find persons whose ClickHouse rows disagree with the persons database.++The persons database, read through personhog, is the source of truth. Scans only read.+"""++from __future__ import annotations++from collections import defaultdict+from collections.abc import Callable+from typing import Any, Literal+from uuid import UUID++from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.workload import Workload+from posthog.dataclasses import frozen+from 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"]++# The legacy delete path wrote ClickHouse tombstones at version + 100, so those rows sit at 100 or above.+LEGACY_TOMBSTONE_MIN_VERSION = 100++HIDDEN_TEAM_STEP = 10_000+SWEPT_TEAM_STEP = 10_000+STALE_TEAM_STEP = 5_000++_HIDDEN_SETTINGS = {"max_execution_time": 900, "max_memory_usage": 32_000_000_000}+_SWEPT_SETTINGS = {"apply_deleted_mask": 0, "max_execution_time": 1800, "max_memory_usage": 64_000_000_000}+_STALE_SETTINGS = {+ "max_execution_time": 1800,+ "max_memory_usage": 48_000_000_000,+ "max_bytes_before_external_group_by": 20_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"])+++@frozen+class DivergentPerson:+ team_id: int+ person_uuid: str+ kind: PersonDivergenceKind+ ch_max_version: int+ pg_version: int+++@frozen+class ScanSummary:+ candidates: int+ divergent: int+ skipped_team_ids: list[int]+++# ── ClickHouse and personhog access ──────────────────────────────────+++def _ch(sql: str, args: dict[str, Any], settings: dict[str, int]) -> list[Any]:+ return sync_execute(sql, args, settings=settings, workload=Workload.OFFLINE, readonly=True)+++def _live_person_versions(team_id: int, person_uuids: list[str], operation: str) -> dict[str, int]:+ persons = personhog_call(+ operation,+ lambda: _batched_get_persons_by_uuids(+ team_id, person_uuids, operation, read_options=_VERSION_ONLY_READ_OPTIONS+ ),+ )+ return {str(UUID(p.uuid)): int(p.version) for p in persons}+++def _resolve_max_team_id(max_team_id: int | None) -> int:+ if max_team_id is not None:+ return max_team_id+ [[highest]] = _ch("SELECT max(team_id) FROM person", {}, _HIDDEN_SETTINGS)+ return int(highest or 0) + 1+++# ── Scans over team ranges ───────────────────────────────────────────+++def _scan_team_ranges(+ query: Callable[[int, int], list[Any]],+ *,+ min_team_id: int,+ max_team_id: int,+ team_step: int,+ on_rows: Callable[[list[Any]], None],+ log: Callable[[str], None],+) -> list[int]:+ """Return each team that runs out of memory or time even when scanned alone, so the caller can rerun it with higher limits."""+ skipped: list[int] = []++ def scan(lo: int, hi: int) -> None:+ try:+ rows = query(lo, hi)+ except (ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut) as exc:+ reason = "out of memory" if isinstance(exc, ClickHouseQueryMemoryLimitExceeded) else "timed out"+ if hi - lo == 1:+ log(f"team {lo}: {reason}, skipped")+ skipped.append(lo)+ return+ mid = (lo + hi) // 2+ log(f"teams [{lo}, {hi}): {reason}, bisecting")+ scan(lo, mid)+ scan(mid, hi)+ return+ on_rows(rows)+ log(f"teams [{lo}, {hi}): {len(rows)} ClickHouse candidates")++ for lo in range(min_team_id, max_team_id, team_step):+ scan(lo, min(lo + team_step, max_team_id))+ return skipped+++def _scan_divergent_persons(+ *,+ sql: str,+ settings: dict[str, int],+ extra_args: dict[str, Any],+ kind: PersonDivergenceKind,+ divergent: Callable[[int, int], bool],+ min_team_id: int,+ max_team_id: int | None,+ team_step: int,+ on_found: Callable[[DivergentPerson], None],+ log: Callable[[str], None],+) -> ScanSummary:+ candidates = 0+ found = 0++ def on_rows(rows: list[Any]) -> None:+ nonlocal candidates, found+ by_team: dict[int, dict[str, int]] = defaultdict(dict)+ for team_id, person_uuid, ch_max_version in rows:+ by_team[int(team_id)][person_uuid] = int(ch_max_version)+ for team_id, ch_versions in sorted(by_team.items()):+ candidates += len(ch_versions)+ pg_versions = _live_person_versions(team_id, list(ch_versions), f"person_divergence_scan_{kind}")+ for person_uuid, pg_version in pg_versions.items():+ ch_max_version = ch_versions[person_uuid]+ if not divergent(pg_version, ch_max_version):+ continue+ on_found(+ DivergentPerson(+ team_id=team_id,+ person_uuid=person_uuid,+ kind=kind,+ ch_max_version=ch_max_version,+ pg_version=pg_version,+ )+ )+ found += 1++ skipped = _scan_team_ranges(+ lambda lo, hi: _ch(sql, {"min_team_id": lo, "max_team_id": hi, **extra_args}, settings),+ min_team_id=min_team_id,+ max_team_id=_resolve_max_team_id(max_team_id),+ team_step=team_step,+ on_rows=on_rows,+ log=log,+ )+ return ScanSummary(candidates=candidates, divergent=found, skipped_team_ids=skipped)+++_HIDDEN_SQL = """+SELECT team_id, toString(id), max(version) AS max_version+FROM person+WHERE team_id >= %(min_team_id)s AND team_id < %(max_team_id)s+ AND (team_id, id) IN (+ SELECT team_id, id FROM person+ WHERE team_id >= %(min_team_id)s AND team_id < %(max_team_id)s+ AND is_deleted = 1 AND version >= %(min_tombstone_version)s+ )+GROUP BY team_id, id+HAVING argMax(is_deleted, version) = 1 AND max_version >= %(min_tombstone_version)s+"""+++def scan_hidden_persons(+ *,+ min_team_id: int = 0,+ max_team_id: int | None = None,+ team_step: int = HIDDEN_TEAM_STEP,+ on_found: Callable[[DivergentPerson], None],+ log: Callable[[str], None],+) -> ScanSummary:+ """Persons live in Postgres whose newest ClickHouse row is a legacy (version 100 or above) tombstone.++ Run it, then repair what it finds, right before every ClickHouse deletion sweep while such+ tombstones remain: the sweep deletes every ClickHouse row of these persons.+ """+ return _scan_divergent_persons(+ sql=_HIDDEN_SQL,+ settings=_HIDDEN_SETTINGS,+ extra_args={"min_tombstone_version": LEGACY_TOMBSTONE_MIN_VERSION},+ kind="hidden",+ divergent=lambda _pg_version, _ch_max_version: True,+ min_team_id=min_team_id,+ max_team_id=max_team_id,+ team_step=team_step,+ on_found=on_found,+ log=log,+ )+++# The ClickHouse deletion sweep deletes every row of a person whose highest-version row is a tombstone.+# That includes a live row written after the tombstone at a lower version, so the person stays live in+# Postgres with no visible ClickHouse row.+_SWEPT_SQL = """+SELECT team_id, toString(id), max(version) AS max_version+FROM person+WHERE team_id >= %(min_team_id)s AND team_id < %(max_team_id)s+ AND (team_id, id) IN (+ SELECT team_id, id FROM person+ WHERE team_id >= %(min_team_id)s AND team_id < %(max_team_id)s+ AND NOT _row_exists AND is_deleted = 1 AND version >= %(min_tombstone_version)s+ )+GROUP BY team_id, id+HAVING countIf(_row_exists) = 0+ AND maxIf(_timestamp, is_deleted = 0) > maxIf(_timestamp, is_deleted = 1 AND version >= %(min_tombstone_version)s)+"""+++def scan_swept_persons(+ *,+ min_team_id: int = 0,+ max_team_id: int | None = None,+ team_step: int = SWEPT_TEAM_STEP,+ on_found: Callable[[DivergentPerson], None],+ log: Callable[[str], None],+) -> ScanSummary:+ """Live Postgres persons with every ClickHouse row deleted, including a live row written after a legacy tombstone.++ Run it soon after a ClickHouse deletion sweep: once merges remove the deleted rows, no scan finds the person.+ """+ return _scan_divergent_persons(+ sql=_SWEPT_SQL,+ settings=_SWEPT_SETTINGS,+ extra_args={"min_tombstone_version": LEGACY_TOMBSTONE_MIN_VERSION},+ kind="swept",+ divergent=lambda _pg_version, _ch_max_version: True,+ min_team_id=min_team_id,+ max_team_id=max_team_id,+ team_step=team_step,+ on_found=on_found,+ log=log,+ )+++# A row with a lower version that arrives well after the winning row means Postgres restarted the+# person below ClickHouse, so every later update loses to the old winner.+_STALE_SQL = """+SELECT team_id, toString(id), max(version) AS max_version+FROM person+WHERE team_id >= %(min_team_id)s AND team_id < %(max_team_id)s+ AND (team_id, id) IN (+ SELECT team_id, id FROM person+ WHERE team_id >= %(min_team_id)s AND team_id < %(max_team_id)s+ AND _timestamp > now() - toIntervalDay(%(window_days)s)+ )+GROUP BY team_id, id+HAVING argMax(is_deleted, version) = 0+ AND argMax(version, _timestamp) < max_version+ AND max(_timestamp) > argMax(_timestamp, version) + INTERVAL 1 HOUR+"""+++def scan_stale_persons(+ *,+ window_days: int,+ min_team_id: int = 0,+ max_team_id: int | None = None,+ team_step: int = STALE_TEAM_STEP,+ on_found: Callable[[DivergentPerson], None],+ log: Callable[[str], None],+) -> ScanSummary:+ """Persons whose live ClickHouse winner outranks Postgres, found through a late lower-version row."""+ return _scan_divergent_persons(+ sql=_STALE_SQL,+ settings=_STALE_SETTINGS,+ extra_args={"window_days": window_days},+ kind="stale",+ divergent=lambda pg_version, ch_max_version: pg_version < ch_max_version,+ min_team_id=min_team_id,+ max_team_id=max_team_id,+ team_step=team_step,+ on_found=on_found,+ log=log,+ )diff --git a/posthog/models/person/test/test_divergence.py b/posthog/models/person/test/test_divergence.pynew file mode 100644index 000000000000..0054241debc4--- /dev/null+++ b/posthog/models/person/test/test_divergence.py@@ -0,0 +1,203 @@+import json+from datetime import UTC, datetime, timedelta+from typing import Any+from uuid import UUID, uuid4++from posthog.test.base import BaseTest, ClickhouseTestMixin+from unittest.mock import patch++from django.test import SimpleTestCase+from django.utils.timezone import now++from parameterized import parameterized++from posthog.clickhouse.client import sync_execute+from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut+from posthog.models.person import Person+from posthog.models.person.divergence import (+ DivergentPerson,+ scan_hidden_persons,+ scan_stale_persons,+ scan_swept_persons,+)+from posthog.models.person.util import (+ create_person as create_person_in_ch,+ tombstone_persons_in_postgres,+)+from posthog.models.signals import mute_selected_signals+from posthog.test.persons import add_distinct_id, create_person++PG_PROPERTIES = {"email": "[email protected]"}+CH_PROPERTIES = {"email": "[email protected]"}++_PERSON_COLUMNS = (+ "id, created_at, team_id, properties, is_identified, _timestamp, _offset, is_deleted, version, last_seen_at"+)+++def _utc_naive(hours_ago: float) -> datetime:+ return (now() - timedelta(hours=hours_ago)).astimezone(UTC).replace(tzinfo=None)+++class TestPersonDivergence(ClickhouseTestMixin, BaseTest):+ def _pg_person(self, *, version: int, distinct_ids: dict[str, int] | None = None) -> Person:+ # Muted signals keep create_person out of ClickHouse, so each test writes exactly the rows it describes.+ with mute_selected_signals():+ person = create_person(team=self.team, version=version, properties=PG_PROPERTIES)+ for distinct_id, distinct_id_version in (distinct_ids or {}).items():+ add_distinct_id(person=person, distinct_id=distinct_id, version=distinct_id_version)+ return person++ def _ch_person_row(+ self,+ person_uuid: UUID | str,+ version: int,+ *,+ deleted: bool = False,+ hours_ago: float = 0,+ team_id: int | None = None,+ ) -> None:+ create_person_in_ch(+ team_id=team_id or self.team.pk,+ uuid=str(person_uuid),+ version=version,+ is_deleted=deleted,+ properties=CH_PROPERTIES,+ timestamp=now() - timedelta(hours=hours_ago),+ )++ def _stop_person_merges(self) -> 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")++ def _swept_rows(self, rows_by_person: dict[UUID, list[tuple[int, bool, float]]]) -> 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}"+ 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)")+ self.addCleanup(sync_execute, f"DROP TABLE IF EXISTS {staging} SYNC")+ sync_execute(+ f"INSERT INTO {staging} ({_PERSON_COLUMNS}) VALUES",+ [+ {+ "id": person_uuid,+ "created_at": _utc_naive(24),+ "team_id": self.team.pk,+ "properties": json.dumps(CH_PROPERTIES),+ "is_identified": 0,+ "_timestamp": _utc_naive(hours_ago),+ "_offset": 0,+ "is_deleted": int(deleted),+ "version": version,+ "last_seen_at": _utc_naive(24),+ }+ 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}")++ # ── Scans ────────────────────────────────────────────────────────++ def _team_scan_range(self) -> dict[str, int]:+ return {"min_team_id": self.team.pk, "max_team_id": self.team.pk + 1}++ def test_hidden_scan_reports_only_persons_live_in_postgres_behind_a_legacy_tombstone(self) -> None:+ hidden = self._pg_person(version=3)+ self._ch_person_row(hidden.uuid, 3)+ self._ch_person_row(hidden.uuid, 103, deleted=True)+ tombstoned = self._pg_person(version=3)+ tombstone_persons_in_postgres(self.team.pk, [tombstoned.uuid])+ self._ch_person_row(tombstoned.uuid, 103, deleted=True)+ self._ch_person_row(uuid4(), 103, deleted=True)+ current_tombstone = self._pg_person(version=3)+ self._ch_person_row(current_tombstone.uuid, 4, deleted=True)+ revived = self._pg_person(version=104)+ self._ch_person_row(revived.uuid, 103, deleted=True)+ self._ch_person_row(revived.uuid, 104)++ found: list[DivergentPerson] = []+ summary = scan_hidden_persons(**self._team_scan_range(), on_found=found.append, log=lambda _: None)++ assert found == [+ DivergentPerson(+ team_id=self.team.pk, person_uuid=str(hidden.uuid), kind="hidden", ch_max_version=103, pg_version=3+ )+ ]+ assert (summary.candidates, summary.divergent, summary.skipped_team_ids) == (3, 1, [])++ def test_swept_scan_reports_live_persons_whose_late_live_row_was_swept_with_the_tombstone(self) -> None:+ swept = self._pg_person(version=3)+ live_row_before_the_tombstone = self._pg_person(version=3)+ revived_after_the_sweep = self._pg_person(version=104)+ self._swept_rows(+ {+ swept.uuid: [(3, False, 3), (103, True, 2), (4, False, 1)],+ live_row_before_the_tombstone.uuid: [(3, False, 3), (103, True, 2)],+ revived_after_the_sweep.uuid: [(103, True, 2), (4, False, 1)],+ }+ )+ self._ch_person_row(revived_after_the_sweep.uuid, 104)++ found: list[DivergentPerson] = []+ summary = scan_swept_persons(**self._team_scan_range(), on_found=found.append, log=lambda _: None)++ assert found == [+ DivergentPerson(+ team_id=self.team.pk, person_uuid=str(swept.uuid), kind="swept", ch_max_version=103, pg_version=3+ )+ ]+ assert (summary.candidates, summary.divergent) == (1, 1)++ def test_stale_scan_reports_only_a_live_winner_above_postgres_with_a_late_lower_row(self) -> None:+ self._stop_person_merges()+ stale = self._pg_person(version=5)+ in_sync = self._pg_person(version=10)+ deleted_winner = self._pg_person(version=5)+ quick_retry = self._pg_person(version=5)+ for person in (stale, in_sync, deleted_winner):+ self._ch_person_row(person.uuid, 10, deleted=person is deleted_winner, hours_ago=3)+ self._ch_person_row(person.uuid, 5, hours_ago=1)+ self._ch_person_row(quick_retry.uuid, 10, hours_ago=1.5)+ self._ch_person_row(quick_retry.uuid, 5, hours_ago=1)++ found: list[DivergentPerson] = []+ summary = scan_stale_persons(+ window_days=60, **self._team_scan_range(), on_found=found.append, log=lambda _: None+ )++ assert found == [+ DivergentPerson(+ team_id=self.team.pk, person_uuid=str(stale.uuid), kind="stale", ch_max_version=10, pg_version=5+ )+ ]+ assert (summary.candidates, summary.divergent) == (2, 1)+++class TestScanTeamRanges(SimpleTestCase):+ @parameterized.expand([("out_of_memory", ClickHouseQueryMemoryLimitExceeded), ("timeout", ClickHouseQueryTimeOut)])+ def test_a_team_that_fails_alone_is_skipped_and_every_other_team_is_scanned(+ self, _name: str, error: type[Exception]+ ) -> None:+ scanned: list[int] = []++ def query(_sql: str, args: dict[str, Any], **_kwargs: Any) -> list[Any]:+ teams = range(args["min_team_id"], args["max_team_id"])+ if 7 in teams:+ raise error()+ scanned.extend(teams)+ return []++ with patch("posthog.models.person.divergence.sync_execute", side_effect=query):+ summary = scan_stale_persons(+ window_days=60, min_team_id=0, max_team_id=16, team_step=8, on_found=lambda _: None, log=lambda _: None+ )++ assert summary.skipped_team_ids == [7]+ assert sorted(scanned) == [team for team in range(16) if team != 7]