: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 sample and team divergence scans (#111664)
Eli Reisman3c1ccb61d428
diff --git a/posthog/management/commands/person_divergence.py b/posthog/management/commands/person_divergence.pyindex c1815cb9c804..c2a9174d9e0a 100644--- a/posthog/management/commands/person_divergence.py+++ b/posthog/management/commands/person_divergence.py@@ -4,6 +4,8 @@ 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 scan sample --modulus 20000 --residue 7 --cutoff 2025-12-01 --output sample.csv+ python manage.py person_divergence scan team --team-id 2 --before 2026-08-01T00:00:00 --output team.csvpython manage.py person_divergence repair --input hidden.csv --output actions.csvpython manage.py person_divergence repair --input hidden.csv --output actions.csv --apply@@ -17,6 +19,7 @@ import timeimport argparseimport dataclassesfrom collections.abc import Callable+from datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any, TextIOfrom uuid import UUID@@ -26,14 +29,19 @@ from django.core.management.base import BaseCommand, CommandError, CommandParserfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.models.person.divergence import (HIDDEN_TEAM_STEP,+ SAMPLE_TEAM_STEP,STALE_TEAM_STEP,SWEPT_TEAM_STEP,DivergentPerson,PersonRef,RepairAction,+ SampledPerson,ScanSummary,+ TeamCheck,+ check_team,repair_persons,scan_hidden_persons,+ scan_sample,scan_stale_persons,scan_swept_persons,)@@ -59,6 +67,11 @@ _DIVERGENT_SCANS: dict[str, tuple[Callable[..., ScanSummary], int, str]] = {}+def _parse_utc(value: str) -> datetime:+ parsed = datetime.fromisoformat(value)+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)++class Command(BaseCommand):help = ("Scan for persons whose ClickHouse rows disagree with the persons database, and repair them. "@@ -88,6 +101,55 @@ class Command(BaseCommand):help="Only persons written in the last N days (default: %(default)s).",)+ sample = scans.add_parser(+ "sample", help="Classify a uniform sample of live ClickHouse persons against Postgres."+ )+ self._add_output(sample)+ self._add_team_range(sample)+ sample.add_argument(+ "--modulus",+ type=_positive_int,+ required=True,+ help="Sample the persons where cityHash64(id) %% MODULUS = RESIDUE.",+ )+ sample.add_argument("--residue", type=int, required=True, help="See --modulus.")+ sample.add_argument(+ "--team-step",+ type=_positive_int,+ default=SAMPLE_TEAM_STEP,+ help="Team ids per ClickHouse query (default: %(default)s).",+ )+ sample.add_argument(+ "--written-within-days",+ type=_positive_int,+ default=None,+ help="Only persons whose winner was written in the last N days.",+ )+ sample.add_argument(+ "--cutoff",+ type=_parse_utc,+ default=None,+ help="Split each class by whether the winner was written before this ISO date or datetime (UTC if no zone).",+ )++ team = scans.add_parser(+ "team", help="Per team, count how many old live ClickHouse persons and mappings Postgres still holds."+ )+ self._add_output(team)+ team.add_argument("--team-id", type=int, action="append", required=True, help="Team to check. Repeatable.")+ team.add_argument(+ "--sample-size",+ type=_positive_int,+ default=200,+ help="Persons and mappings per team (default: %(default)s).",+ )+ team.add_argument(+ "--before",+ type=_parse_utc,+ required=True,+ help="Only rows last written before this ISO datetime (UTC if no zone).",+ )+repair_help = ("DRY RUN unless --apply is passed. Republish the Postgres state of the persons in --input, ""and their distinct ids, to ClickHouse where ClickHouse disagrees."@@ -143,9 +205,13 @@ class Command(BaseCommand):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"]:+ # An empty team range scans nothing and would read as a clean fleet. The team scan takes no range.+ max_team_id = options.get("max_team_id")+ if max_team_id is not None and max_team_id <= options["min_team_id"]:raise CommandError("--max-team-id must be above --min-team-id")+ # A residue outside the modulus samples nothing and would read as a clean fleet.+ if name == "sample" and not 0 <= options["residue"] < options["modulus"]:+ raise CommandError(f"--residue must be between 0 and {options['modulus'] - 1}")with _open_output(options["output"]) as handle:if name in _DIVERGENT_SCANS:scan_fn, _, _ = _DIVERGENT_SCANS[name]@@ -162,6 +228,37 @@ class Command(BaseCommand):f"{name} scan: {summary.candidates} ClickHouse candidates, {summary.divergent} divergent, "f"skipped teams {summary.skipped_team_ids}")+ elif name == "sample":+ sample_summary = scan_sample(+ modulus=options["modulus"],+ residue=options["residue"],+ written_within_days=options["written_within_days"],+ cutoff=options["cutoff"],+ min_team_id=options["min_team_id"],+ max_team_id=options["max_team_id"],+ team_step=options["team_step"],+ on_sampled=_csv_sink(handle, SampledPerson),+ log=self._log,+ )+ counts = ", ".join(+ f"{bucket.classification}/{bucket.era}={count}"+ for bucket, count in sorted(+ sample_summary.counts.items(), key=lambda item: (item[0].classification, item[0].era)+ )+ )+ self._log(+ f"sample scan: {sample_summary.sampled} persons: {counts}, "+ f"skipped teams {sample_summary.skipped_team_ids}"+ )+ else:+ write = _csv_sink(handle, TeamCheck)+ for team_id in options["team_id"]:+ result = check_team(team_id=team_id, sample_size=options["sample_size"], before=options["before"])+ write(result)+ self._log(+ f"team {team_id}: persons live in Postgres {result.persons_live_in_postgres}/{result.persons_sampled}, "+ f"mappings live in Postgres {result.distinct_ids_live_in_postgres}/{result.distinct_ids_sampled}"+ )def _repair(self, options: dict[str, Any]) -> None:targets = _read_targets(options["input"], options["team_id"])diff --git a/posthog/management/commands/test/test_person_divergence.py b/posthog/management/commands/test/test_person_divergence.pyindex cf15c175bc9e..651544665c17 100644--- a/posthog/management/commands/test/test_person_divergence.py+++ b/posthog/management/commands/test/test_person_divergence.py@@ -52,6 +52,14 @@ class TestPersonDivergenceCommand(ClickhouseTestMixin, BaseTest):assert [row["outcome"] for row in applied] == ["repaired"]assert self._ch_winner(person_uuid) == (0, 104)+ def test_team_scan_writes_one_row_per_team(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ rows = self._run(+ "scan", "team", "--team-id", str(self.team.pk), "--before", "2100-01-01", "--output", f"{tmp}/team.csv"+ )++ assert [row["team_id"] for row in rows] == [str(self.team.pk)]+class TestPersonDivergenceArguments(SimpleTestCase):@parameterized.expand(@@ -64,6 +72,19 @@ class TestPersonDivergenceArguments(SimpleTestCase):["hidden", "--min-team-id", "5", "--max-team-id", "5"],"--max-team-id must be above --min-team-id",),+ ("modulus_zero", ["sample", "--modulus", "0", "--residue", "0"], "0 must be 1 or more"),+ ("residue_at_modulus", ["sample", "--modulus", "4", "--residue", "4"], "--residue must be between 0 and 3"),+ ("residue_negative", ["sample", "--modulus", "4", "--residue", "-1"], "--residue must be between 0 and 3"),+ (+ "written_within_zero",+ ["sample", "--modulus", "4", "--residue", "0", "--written-within-days", "0"],+ "0 must be 1 or more",+ ),+ (+ "sample_size_zero",+ ["team", "--team-id", "1", "--before", "2026-01-01", "--sample-size", "0"],+ "0 must be 1 or more",+ ),])def test_scan_rejects_arguments_that_would_check_nothing(diff --git a/posthog/models/person/divergence.py b/posthog/models/person/divergence.pyindex 365d76b0ebf4..26fb3abb3131 100644--- a/posthog/models/person/divergence.py+++ b/posthog/models/person/divergence.py@@ -12,6 +12,7 @@ import timefrom collections import Counter, defaultdictfrom collections.abc import Callable, Sequencefrom dataclasses import field+from datetime import datetimefrom functools import partialfrom typing import Any, Literal, TypeVarfrom uuid import UUID@@ -30,6 +31,7 @@ from 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_distinct_ids,_batched_get_persons_by_uuids,_person_row,create_person_distinct_id,@@ -49,6 +51,8 @@ from posthog.personhog_client.proto import (PersonDivergenceKind = Literal["hidden", "swept", "stale", "behind", "absent"]MappingDivergenceKind = Literal["hidden", "other_person", "stale", "absent"]+SampleClassification = Literal["equal", "pg_below_ch", "pg_above_ch", "team_gone", "pg_tombstone", "pg_absent"]+SampleEra = Literal["before_cutoff", "since_cutoff", "any"]RepairOutcome = Literal["would_repair","repaired",@@ -69,6 +73,7 @@ LEGACY_TOMBSTONE_MIN_VERSION = 100HIDDEN_TEAM_STEP = 10_000SWEPT_TEAM_STEP = 10_000STALE_TEAM_STEP = 5_000+SAMPLE_TEAM_STEP = 10_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}@@ -77,6 +82,8 @@ _STALE_SETTINGS = {"max_memory_usage": 48_000_000_000,"max_bytes_before_external_group_by": 20_000_000_000,}+_SAMPLE_SETTINGS = {"max_execution_time": 3600, "max_memory_usage": 32_000_000_000}+_TEAM_CHECK_SETTINGS = {"max_execution_time": 900, "max_memory_usage": 32_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}@@ -119,6 +126,38 @@ class ScanSummary:skipped_team_ids: list[int]+@frozen+class SampledPerson:+ team_id: int+ person_uuid: str+ classification: SampleClassification+ era: SampleEra+ ch_max_version: int+ pg_version: int | None+++@frozen+class SampleBucket:+ classification: SampleClassification+ era: SampleEra+++@frozen+class SampleSummary:+ sampled: int+ counts: dict[SampleBucket, int]+ skipped_team_ids: list[int]+++@frozen+class TeamCheck:+ team_id: int+ persons_sampled: int+ persons_live_in_postgres: int+ distinct_ids_sampled: int+ distinct_ids_live_in_postgres: int++@frozenclass PersonRef:team_id: int@@ -400,7 +439,179 @@ def scan_stale_persons()-# ── Repair ───────────────────────────────────────────────────────────+_SAMPLE_SQL = """+SELECT team_id, toString(id), max(version) AS max_version, toUnixTimestamp(argMax(_timestamp, version)) AS written_at+FROM person+WHERE cityHash64(id) %% %(modulus)s = %(residue)s AND team_id >= %(min_team_id)s AND team_id < %(max_team_id)s+GROUP BY team_id, id+HAVING argMax(is_deleted, version) = 0+ AND (%(written_within_days)s = 0 OR argMax(_timestamp, version) >= now() - toIntervalDay(%(written_within_days)s))+"""+++def _classify_sampled(+ pg_version: int | None, ch_max_version: int, *, team_exists: bool, tombstoned: bool+) -> SampleClassification:+ if not team_exists:+ return "team_gone"+ if pg_version is None:+ return "pg_tombstone" if tombstoned else "pg_absent"+ if pg_version == ch_max_version:+ return "equal"+ return "pg_below_ch" if pg_version < ch_max_version else "pg_above_ch"+++def scan_sample(+ *,+ modulus: int,+ residue: int,+ written_within_days: int | None = None,+ cutoff: datetime | None = None,+ min_team_id: int = 0,+ max_team_id: int | None = None,+ team_step: int = SAMPLE_TEAM_STEP,+ on_sampled: Callable[[SampledPerson], None],+ log: Callable[[str], None],+) -> SampleSummary:+ """Classify a uniform sample of live ClickHouse persons against Postgres."""+ if not 0 <= residue < modulus:+ raise ValueError("residue must be in [0, modulus)")+ cutoff_ts = cutoff.timestamp() if cutoff is not None else None+ counts: Counter[SampleBucket] = Counter()+ sampled_count = 0++ def query(lo: int, hi: int) -> list[Any]:+ return _ch(+ _SAMPLE_SQL,+ {+ "modulus": modulus,+ "residue": residue,+ "written_within_days": written_within_days or 0,+ "min_team_id": lo,+ "max_team_id": hi,+ },+ _SAMPLE_SETTINGS,+ )++ def on_rows(rows: list[Any]) -> None:+ nonlocal sampled_count+ if not rows:+ return+ sampled_count += len(rows)+ by_team: dict[int, dict[str, tuple[int, SampleEra]]] = defaultdict(dict)+ for team_id, person_uuid, ch_max_version, written_at in rows:+ era: SampleEra = (+ "any" if cutoff_ts is None else "before_cutoff" if written_at < cutoff_ts else "since_cutoff"+ )+ by_team[int(team_id)][person_uuid] = (int(ch_max_version), era)++ existing_teams = set(Team.objects.filter(id__in=list(by_team)).values_list("id", flat=True))+ for team_id, sampled in sorted(by_team.items()):+ team_exists = team_id in existing_teams+ # A deleted team's persons can outlive it in Postgres, so they are team_gone whatever their version.+ pg_versions = (+ _live_person_versions(team_id, list(sampled), "person_divergence_sample") if team_exists else {}+ )+ missing = [u for u in sampled if u not in pg_versions]+ tombstoned = _tombstoned_uuids(team_id, missing) if team_exists else set()+ for person_uuid, (ch_max_version, era) in sampled.items():+ pg_version = pg_versions.get(person_uuid)+ classification = _classify_sampled(+ pg_version, ch_max_version, team_exists=team_exists, tombstoned=person_uuid in tombstoned+ )+ counts[SampleBucket(classification=classification, era=era)] += 1+ on_sampled(+ SampledPerson(+ team_id=team_id,+ person_uuid=person_uuid,+ classification=classification,+ era=era,+ ch_max_version=ch_max_version,+ pg_version=pg_version,+ )+ )++ skipped = _scan_team_ranges(+ query,+ 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,+ )+ log(f"sampled {sampled_count} live ClickHouse persons")+ return SampleSummary(sampled=sampled_count, counts=dict(counts), skipped_team_ids=skipped)+++# The hash pre-filter keeps about this many times the sample, so the sample stays full size and uniform.+_TEAM_CHECK_OVERSAMPLE = 10++_TEAM_PERSON_ROWS_SQL = "SELECT count() FROM person WHERE team_id = %(team_id)s"+_TEAM_MAPPING_ROWS_SQL = "SELECT count() FROM person_distinct_id2 WHERE team_id = %(team_id)s"++_TEAM_PERSONS_SQL = """+SELECT toString(id)+FROM person+WHERE team_id = %(team_id)s AND cityHash64(id) %% %(modulus)s = 0+GROUP BY id+HAVING argMax(is_deleted, version) = 0 AND max(_timestamp) < fromUnixTimestamp(%(before)s)+ORDER BY cityHash64(id)+LIMIT %(limit)s+"""++_TEAM_MAPPINGS_SQL = """+SELECT distinct_id+FROM person_distinct_id2+WHERE team_id = %(team_id)s AND cityHash64(distinct_id) %% %(modulus)s = 0+GROUP BY distinct_id+HAVING argMax(is_deleted, version) = 0 AND max(_timestamp) < fromUnixTimestamp(%(before)s)+ORDER BY cityHash64(distinct_id)+LIMIT %(limit)s+"""+++def _team_check_modulus(rows: int, sample_size: int) -> int:+ return max(1, rows // max(1, sample_size * _TEAM_CHECK_OVERSAMPLE))+++def _team_check_args(rows_sql: str, *, team_id: int, sample_size: int, before: datetime) -> dict[str, int]:+ [[rows]] = _ch(rows_sql, {"team_id": team_id}, _TEAM_CHECK_SETTINGS)+ return {+ "team_id": team_id,+ "before": int(before.timestamp()),+ "limit": sample_size,+ "modulus": _team_check_modulus(int(rows), sample_size),+ }+++def check_team(*, team_id: int, sample_size: int, before: datetime) -> TeamCheck:+ """Count how many of a team's old live ClickHouse persons and mappings Postgres still holds live."""+ person_args = _team_check_args(_TEAM_PERSON_ROWS_SQL, team_id=team_id, sample_size=sample_size, before=before)+ mapping_args = _team_check_args(_TEAM_MAPPING_ROWS_SQL, team_id=team_id, sample_size=sample_size, before=before)+ person_uuids = [row[0] for row in _ch(_TEAM_PERSONS_SQL, person_args, _TEAM_CHECK_SETTINGS)]+ distinct_ids = [row[0] for row in _ch(_TEAM_MAPPINGS_SQL, mapping_args, _TEAM_CHECK_SETTINGS)]+ live_persons = _live_person_versions(team_id, person_uuids, "person_divergence_team_check") if person_uuids else {}+ live_mappings = (+ personhog_call(+ "person_divergence_team_check",+ lambda: _batched_get_persons_by_distinct_ids(+ team_id,+ distinct_ids,+ "person_divergence_team_check",+ deduplicate_by_person=False,+ read_options=_VERSION_ONLY_READ_OPTIONS,+ ),+ )+ if distinct_ids+ else []+ )+ return TeamCheck(+ team_id=team_id,+ persons_sampled=len(person_uuids),+ persons_live_in_postgres=len(live_persons),+ distinct_ids_sampled=len(distinct_ids),+ distinct_ids_live_in_postgres=len({r.distinct_id for r in live_mappings}),+ )@frozendiff --git a/posthog/models/person/test/test_divergence.py b/posthog/models/person/test/test_divergence.pyindex 85d09505891c..07e59498cc5e 100644--- a/posthog/models/person/test/test_divergence.py+++ b/posthog/models/person/test/test_divergence.py@@ -18,6 +18,7 @@ from posthog.clickhouse.client import sync_executefrom posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOutfrom posthog.kafka_client.client import ClickhouseProducer, ProduceResultfrom posthog.kafka_client.topics import KAFKA_PERSON+from posthog.models import Teamfrom posthog.models.person import Personfrom posthog.models.person.divergence import (DivergentPerson,@@ -27,9 +28,17 @@ from posthog.models.person.divergence import (RepairAction,RepairOutcome,RepairSummary,+ SampleBucket,+ SampledPerson,+ SampleSummary,+ ScanSummary,+ TeamCheck,+ _team_check_modulus,_WritePacer,+ check_team,repair_persons,scan_hidden_persons,+ scan_sample,scan_stale_persons,scan_swept_persons,)@@ -39,7 +48,6 @@ from posthog.models.person.util import (tombstone_persons_in_postgres,)from posthog.models.signals import mute_selected_signals-from posthog.models.team import Teamfrom posthog.personhog_client.fake_client import get_active_fakefrom posthog.personhog_client.proto import CONSISTENCY_LEVEL_STRONGfrom posthog.test.persons import add_distinct_id, create_person@@ -323,7 +331,86 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):]assert (summary.candidates, summary.divergent) == (2, 1)- # ── Repair ───────────────────────────────────────────────────────+ def test_sample_classifies_live_clickhouse_persons_against_postgres(self) -> None:+ gone_team = Team.objects.create(organization=self.organization, name="deleted team")+ gone_team_id = gone_team.pk+ gone_team.delete()+ equal = self._pg_person(version=3)+ self._ch_person_row(equal.uuid, 3, hours_ago=48)+ below = self._pg_person(version=3)+ self._ch_person_row(below.uuid, 5)+ above = self._pg_person(version=6)+ self._ch_person_row(above.uuid, 5)+ tombstoned = self._pg_person(version=3)+ tombstone_persons_in_postgres(self.team.pk, [tombstoned.uuid])+ self._ch_person_row(tombstoned.uuid, 3)+ absent = uuid4()+ self._ch_person_row(absent, 3)+ team_gone = uuid4()+ self._ch_person_row(team_gone, 1, team_id=gone_team_id)+ # Postgres can still hold a deleted team's persons until the team purge reaches them.+ team_gone_in_postgres = uuid4()+ self._ch_person_row(team_gone_in_postgres, 1, team_id=gone_team_id)+ get_active_fake().add_person(team_id=gone_team_id, person_id=987655, uuid=str(team_gone_in_postgres), version=1)+ deleted_winner = self._pg_person(version=3)+ self._ch_person_row(deleted_winner.uuid, 4, deleted=True)+ written_long_ago = self._pg_person(version=3)+ self._ch_person_row(written_long_ago.uuid, 3, hours_ago=24 * 10)++ sampled: list[SampledPerson] = []+ summary = scan_sample(+ modulus=1,+ residue=0,+ written_within_days=5,+ cutoff=now() - timedelta(days=1),+ min_team_id=self.team.pk,+ max_team_id=gone_team_id + 1,+ team_step=1,+ on_sampled=sampled.append,+ log=lambda _: None,+ )++ assert {s.person_uuid: (s.classification, s.era, s.pg_version) for s in sampled} == {+ str(equal.uuid): ("equal", "before_cutoff", 3),+ str(below.uuid): ("pg_below_ch", "since_cutoff", 3),+ str(above.uuid): ("pg_above_ch", "since_cutoff", 6),+ str(tombstoned.uuid): ("pg_tombstone", "since_cutoff", None),+ str(absent): ("pg_absent", "since_cutoff", None),+ str(team_gone): ("team_gone", "since_cutoff", None),+ str(team_gone_in_postgres): ("team_gone", "since_cutoff", None),+ }+ assert summary.sampled == 7+ assert summary.skipped_team_ids == []+ assert all(+ call.request.team_id != gone_team_id+ for call in get_active_fake().calls+ if call.method == "get_persons_by_uuids"+ )+ assert summary.counts[SampleBucket(classification="equal", era="before_cutoff")] == 1++ def test_team_check_counts_old_live_clickhouse_rows_that_postgres_still_holds(self) -> None:+ kept = self._pg_person(version=1, distinct_ids={"kept": 0})+ self._ch_person_row(kept.uuid, 1, hours_ago=48)+ self._ch_mapping_row("kept", kept.uuid, 0, hours_ago=48)+ lost = uuid4()+ self._ch_person_row(lost, 1, hours_ago=48)+ self._ch_mapping_row("lost", lost, 0, hours_ago=48)+ recent = self._pg_person(version=1, distinct_ids={"recent": 0})+ self._ch_person_row(recent.uuid, 1)+ self._ch_mapping_row("recent", recent.uuid, 0)+ deleted = uuid4()+ self._ch_person_row(deleted, 1, deleted=True, hours_ago=48)+ self._ch_mapping_row("deleted", deleted, 1, deleted=True, hours_ago=48)++ result = check_team(team_id=self.team.pk, sample_size=10, before=now() - timedelta(days=1))++ assert result == TeamCheck(+ team_id=self.team.pk,+ persons_sampled=2,+ persons_live_in_postgres=1,+ distinct_ids_sampled=2,+ distinct_ids_live_in_postgres=1,+ )def _divergent_person(self, case: str) -> Person:if case == "hidden":@@ -819,6 +906,19 @@ class TestPersonDivergence(ClickhouseTestMixin, BaseTest):assert self._ch_mapping("gone") == (str(person.uuid), 1, 100)+class TestTeamCheckModulus(SimpleTestCase):+ @parameterized.expand(+ [+ ("empty_team", 0, 200, 1),+ ("small_team_reads_everything", 3_999, 200, 1),+ ("filter_keeps_ten_times_the_sample", 4_000, 200, 2),+ ("largest_teams", 50_000_000, 200, 25_000),+ ]+ )+ def test_modulus_keeps_ten_times_the_sample(self, _name: str, rows: int, sample_size: int, expected: int) -> None:+ assert _team_check_modulus(rows, sample_size) == expected++class TestWritePacer(SimpleTestCase):def test_idle_time_before_the_writes_buys_no_burst(self) -> None:clock = [0.0]@@ -840,9 +940,18 @@ class TestWritePacer(SimpleTestCase):class TestScanTeamRanges(SimpleTestCase):- @parameterized.expand([("out_of_memory", ClickHouseQueryMemoryLimitExceeded), ("timeout", ClickHouseQueryTimeOut)])+ @parameterized.expand(+ [+ (f"{scan}_{name}", scan, error)+ for scan in ("stale", "sample")+ for name, error in (+ ("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]+ self, _name: str, scan: str, error: type[Exception]) -> None:scanned: list[int] = []@@ -854,9 +963,25 @@ class TestScanTeamRanges(SimpleTestCase):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- )+ if scan == "stale":+ summary: ScanSummary | SampleSummary = scan_stale_persons(+ window_days=60,+ min_team_id=0,+ max_team_id=16,+ team_step=8,+ on_found=lambda _: None,+ log=lambda _: None,+ )+ else:+ summary = scan_sample(+ modulus=1,+ residue=0,+ min_team_id=0,+ max_team_id=16,+ team_step=8,+ on_sampled=lambda _: None,+ log=lambda _: None,+ )assert summary.skipped_team_ids == [7]assert sorted(scanned) == [team for team in range(16) if team != 7]