: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(cohorts): add ch population oracle mode to parity harness (#75805)
Matheus Batistacb9ac32cf873
diff --git a/products/cohorts/backend/management/commands/compare_cohort_membership.py b/products/cohorts/backend/management/commands/compare_cohort_membership.pyindex 026139d6b353..e10cdafce4f9 100644--- a/products/cohorts/backend/management/commands/compare_cohort_membership.py+++ b/products/cohorts/backend/management/commands/compare_cohort_membership.py@@ -1,6 +1,6 @@"""Classified parity report: new Rust cohort pipeline vs an oracle.-Two oracle modes select what the folded shadow topic (the new pipeline's converged membership) is+Three oracle modes select what the folded shadow topic (the new pipeline's converged membership) iscompared against:- ``--oracle old-pipeline`` (default): the argMax of ClickHouse ``cohort_membership`` — the legacy@@ -15,16 +15,24 @@ compared against:hard gate; under-count (oracle - fold) is segmented by day-domain so the boundary-day decay gap isseparated from real seed/unseeded misses.+- ``--oracle population``: the population the legacy batch calculation wrote to ClickHouse+ ``cohortpeople`` at the cohort's pinned ``version`` — the set the cohort page shows. The fold is+ bounded to each cohort's ``last_calculation`` and the two sets are diffed directly. No filter is+ read, so no cohort shape is unsupported; equally, nothing is adjudicated. Report-only, always+ exits 0.+Run from a toolbox/web pod (needs KAFKA_INGESTION_HOSTS + the offline ClickHouse host):manage.py compare_cohort_membership --team-id 2 --since "2026-07-07T19:11:00Z"manage.py compare_cohort_membership --team-id 2 --cohort-id 433564 --since "2026-07-24T02:00:00Z" --oracle recompute+ manage.py compare_cohort_membership --team-id 2 --since "2026-07-07T19:11:00Z" --oracle population"""from __future__ import annotationsimport jsonfrom collections import Counter+from collections.abc import Mappingfrom dataclasses import dataclassfrom datetime import UTC, datetime, timedeltafrom typing import Any, Optional@@ -35,8 +43,9 @@ from django.core.management.base import BaseCommand, CommandError, CommandParserfrom posthog.models.team.team import Teamfrom products.cohorts.backend.backfill.pinning import pin_conditions_for_cohorts+from products.cohorts.backend.models.cohort import Cohortfrom products.cohorts.backend.parity.classifier import ClassifierConfig, CohortComparison, classify_cohort, summarize-from products.cohorts.backend.parity.eligibility import EMITTING_CLASSES, screen_team+from products.cohorts.backend.parity.eligibility import EMITTING_CLASSES, ScreenedCohort, screen_teamfrom products.cohorts.backend.parity.fold import fold_membership_changes, members, reconcile_completeness_by_cohortfrom products.cohorts.backend.parity.kafka_io import DEFAULT_SHADOW_TOPIC, DrainStats, consumer_config, drain_topicfrom products.cohorts.backend.parity.oracle import (@@ -47,6 +56,12 @@ from products.cohorts.backend.parity.oracle import (load_run_context,run_with_boundary_exists,)+from products.cohorts.backend.parity.population import (+ PopulationComparison,+ compare_populations,+ skip_population,+ summarize_population,+)from products.cohorts.backend.parity.recompute import (ExtendedLeafCounts,RecomputeComparison,@@ -61,6 +76,8 @@ from products.cohorts.backend.parity.recompute import ()from products.cohorts.backend.parity.report import (format_notes,+ format_population_summary,+ format_population_table,format_recompute_notes,format_recompute_summary,format_recompute_table,@@ -68,9 +85,15 @@ from products.cohorts.backend.parity.report import (format_summary,format_table,to_json,+ to_population_json,to_recompute_json,)-from products.cohorts.backend.parity.snapshots import load_old_membership, load_realtime_cohorts, make_activity_probe+from products.cohorts.backend.parity.snapshots import (+ load_cohort_population,+ load_old_membership,+ load_realtime_cohorts,+ make_activity_probe,+)from products.cohorts.backend.parity.tzdates import resolve_zoneinfo, window_start_utcSHADOW_TOPIC_RETENTION_DAYS = 7@@ -84,7 +107,8 @@ DEFAULT_GRACE_MINUTES = 10# A cohort window wider than this drives an unbounded `events` scan for no diagnostic gain; the Rust# side treats such a window as "never evicts" rather than sliding, so SKIP instead of scanning.DEFAULT_MAX_WINDOW_DAYS = 400-# `load_leaf_members` materializes the whole set in a Python set; past this it OOMs a toolbox pod.+# The oracle reads (leaf recompute, cohortpeople population) materialize whole member sets in+# Python; past this they OOM a toolbox pod.DEFAULT_MAX_ORACLE_MEMBERS = 1_000_000# Grace is also the sweep-lag horizon, so a whole day of it would swallow the boundary day.MAX_GRACE_MINUTES = 24 * 60@@ -113,6 +137,13 @@ RECOMPUTE_CAVEATS = ("override/merge drift (fold ids resolved at processing time vs the oracle's current overrides) can pair a false_member with a missing person; a bounded per-class person-id sample ships in the JSON for triage",)+POPULATION_CAVEATS = (+ "this diffs two independent pipelines and deliberately does not say which side is right",+ "without a complete 64/64 reconcile run in the fold the pipeline emits membership flips only, so only_legacy is an upper bound on real misses rather than a miss count",+ "the fold is bounded to each cohort's last_calculation, but the legacy calculation itself ran over some minutes and read ClickHouse with ingestion lag behind it, so minutes of skew on both sides is expected",+ "a partial drain (poll timeout or --max-messages) understates the fold side",+)+def _collect_warnings(drain_stats: DrainStats,@@ -200,6 +231,34 @@ def _collect_recompute_warnings(return warnings+@dataclass(frozen=True)+class PopulationCohortState:+ cohort_id: int+ last_calculation: datetime+ is_calculating: bool+ has_complete_reconcile: bool+++def _collect_population_warnings(*, now: datetime, states: list[PopulationCohortState]) -> list[str]:+ """Pure: the three ways a compared population row can be misread."""+ warnings: list[str] = []+ retention_floor = now - timedelta(days=SHADOW_TOPIC_RETENTION_DAYS)+ for state in states:+ if not state.has_complete_reconcile:+ warnings.append(+ f"cohort {state.cohort_id}: no complete 64/64 reconcile run folded; the fold carries only persons "+ "the pipeline decided on since --since, so only_legacy is an upper bound on real misses"+ )+ if state.last_calculation < retention_floor:+ warnings.append(+ f"cohort {state.cohort_id}: last_calculation {state.last_calculation.isoformat()} is behind the "+ f"{SHADOW_TOPIC_RETENTION_DAYS}d shadow-topic retention floor; the fold cannot reach back that far"+ )+ if state.is_calculating:+ warnings.append(f"cohort {state.cohort_id}: is_calculating is set; the legacy population is mid-rewrite")+ return warnings++def _parse_iso_utc(raw: str, flag: str) -> datetime:try:parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))@@ -229,21 +288,34 @@ def _within_target_cap(targets: list[str], side: str, notes: list[str]) -> bool:return False-def _reject_flags(options: dict[str, Any], flags: tuple[str, ...], mode: str) -> None:- """Reject flags belonging to the other oracle mode.+# Which oracle mode each mode-specific flag parameterizes. A registry rather than per-mode reject+# lists: with three modes, pairwise lists drift into silently accepting a flag that does nothing.+_MODE_FLAGS = {+ "old-pipeline": ("threshold", "warmup_sample", "no_classify"),+ "recompute": ("at", "run_id", "grace_minutes", "max_window_days", "max_oracle_members"),+ "population": ("with_ids", "max_oracle_members"),+}+_ALL_MODE_FLAGS = tuple(sorted({flag for flags in _MODE_FLAGS.values() for flag in flags}))+++def _reject_flags(options: dict[str, Any], mode: str) -> None:+ """Reject mode-specific flags the active oracle does not own.Every mode-specific flag defaults to ``None`` (or ``False`` for a store_true) precisely so anexplicit value that happens to equal the documented default is still caught."""+ owned = set(_MODE_FLAGS[mode])rejected = [- f"--{flag.replace('_', '-')}" for flag in flags if options[flag] is not None and options[flag] is not False+ f"--{flag.replace('_', '-')}"+ for flag in _ALL_MODE_FLAGS+ if flag not in owned and options[flag] is not None and options[flag] is not False]if rejected:- raise CommandError(f"not valid with --oracle {mode} (parameterizes the other oracle): {', '.join(rejected)}")+ raise CommandError(f"not valid with --oracle {mode} (parameterizes another oracle): {', '.join(rejected)}")class Command(BaseCommand):- help = "Compare new-pipeline (shadow topic) vs an oracle (old pipeline or recompute) cohort membership"+ help = "Compare new-pipeline (shadow topic) vs an oracle (old pipeline, recompute or population) cohort membership"def add_arguments(self, parser: CommandParser) -> None:parser.add_argument("--team-id", type=int, required=True)@@ -256,10 +328,15 @@ class Command(BaseCommand):parser.add_argument("--cohort-id", type=int, default=None, help="Limit to one cohort")parser.add_argument("--oracle",- choices=["old-pipeline", "recompute"],+ choices=sorted(_MODE_FLAGS),default="old-pipeline",help="What to compare the fold against (default old-pipeline, byte-identical to prior behavior)",)+ parser.add_argument(+ "--with-ids",+ action="store_true",+ help="population only: carry the complete only_fold / only_legacy person-id lists in the JSON output",+ )parser.add_argument("--at",type=str,@@ -291,8 +368,8 @@ class Command(BaseCommand):"--max-oracle-members",type=int,default=None,- help=f"recompute only: cohorts whose leaf matches more persons than this SKIP rather than being "- f"materialized in memory (default {DEFAULT_MAX_ORACLE_MEMBERS})",+ help=f"recompute/population only: cohorts whose oracle set (leaf members / cohortpeople population) "+ f"exceeds this SKIP rather than being materialized in memory (default {DEFAULT_MAX_ORACLE_MEMBERS})",)parser.add_argument("--threshold",@@ -328,9 +405,15 @@ class Command(BaseCommand):as_json = options["format"] == "json"# Validate every mode-specific flag up front: the drain below takes minutes, and a flag error# surfacing after it wastes the whole run.+ _reject_flags(options, oracle)explicit_at: Optional[datetime] = Noneteam: Optional[Team] = None- if oracle == "recompute":+ if oracle == "population":+ if options["with_ids"] and not as_json:+ raise CommandError("--with-ids needs --format json; the id lists do not fit a fixed-width table")+ if options["max_oracle_members"] is not None and options["max_oracle_members"] < 1:+ raise CommandError("--max-oracle-members must be positive")+ elif oracle == "recompute":self._validate_recompute_flags(options)if options["at"] is not None:explicit_at = _parse_iso_utc(options["at"], "--at")@@ -348,8 +431,6 @@ class Command(BaseCommand):raise CommandError(f"--run-id {options['run_id']} is not a backfill run of team {team_id} with a boundary")- else:- _reject_flags(options, ("at", "run_id", "grace_minutes", "max_window_days", "max_oracle_members"), oracle)def log(message: str) -> None:# Keep stdout clean for the JSON document.@@ -367,6 +448,19 @@ class Command(BaseCommand):screened = screen_team({c.pk: c.filters for c in cohorts}, cascade_enabled=True)names = {c.pk: c.name or "Untitled" for c in cohorts}last_calc = {c.pk: c.last_realtime_cohort_calculation_at for c in cohorts}+ # Each cohort's legacy population was calculated on its own schedule, so the population+ # oracle's clock is per cohort — one team-wide instant cannot bound a multi-cohort fold.+ selected = set(selected_ids)+ until_by_cohort: Optional[dict[int, datetime]] = None+ pre_drain_versions: dict[int, Optional[int]] = {}+ pre_drain_calculated_at: dict[int, Optional[datetime]] = {}+ if oracle == "population":+ # A never-calculated cohort has no oracle clock, so pin its bound to --since: that+ # empties its fold instead of accumulating state the never_calculated skip row below+ # would only throw away.+ until_by_cohort = {c.pk: c.last_calculation or since for c in cohorts if c.pk in selected}+ pre_drain_versions = {c.pk: c.version for c in cohorts}+ pre_drain_calculated_at = {c.pk: c.last_calculation for c in cohorts}histogram = Counter(s.eligibility for s in screened.values())log(f"eligibility histogram (cross-check against cohort_eligibility_total): {dict(histogram)}")@@ -395,7 +489,9 @@ class Command(BaseCommand):max_messages=options["max_messages"],)# An explicit --at pins the comparison clock, so the fold has to converge to that instant too.- new_state, fold_stats = fold_membership_changes(messages, team_id=team_id, since=since, until=explicit_at)+ new_state, fold_stats = fold_membership_changes(+ messages, team_id=team_id, since=since, until=explicit_at, until_by_cohort=until_by_cohort+ )log(f"drained {drain_stats.consumed} messages from {drain_stats.partitions_read}/{drain_stats.partitions} "f"partitions; folded {fold_stats.folded} for team {team_id} across {len(fold_stats.cohorts_seen)} cohorts "@@ -433,6 +529,23 @@ class Command(BaseCommand):as_json=as_json,log=log,)+ elif oracle == "population":+ self._report_population(+ options=options,+ team_id=team_id,+ since=since,+ now=datetime.now(tz=UTC),+ selected_ids=selected_ids,+ screened=screened,+ names=names,+ pre_drain_versions=pre_drain_versions,+ pre_drain_calculated_at=pre_drain_calculated_at,+ new_state=new_state,+ fold_stats=fold_stats,+ drain_warnings=warnings,+ as_json=as_json,+ log=log,+ )else:self._report_old_pipeline(options=options,@@ -450,7 +563,6 @@ class Command(BaseCommand):)def _validate_recompute_flags(self, options: dict[str, Any]) -> None:- _reject_flags(options, ("threshold", "warmup_sample", "no_classify"), "recompute")grace = options["grace_minutes"]if grace is not None and not 0 <= grace <= MAX_GRACE_MINUTES:# Past a day, grace_start reaches back over the boundary day and buckets seed-day events@@ -543,6 +655,127 @@ class Command(BaseCommand):f"{summary.failed} eligible cohort(s) FAIL the {threshold_pct}% parity gate (residual or suspect-missing)")+ def _report_population(+ self,+ *,+ options: dict[str, Any],+ team_id: int,+ since: datetime,+ now: datetime,+ selected_ids: list[int],+ screened: Mapping[int, ScreenedCohort],+ names: dict[int, str],+ pre_drain_versions: dict[int, Optional[int]],+ pre_drain_calculated_at: dict[int, Optional[datetime]],+ new_state: Any,+ fold_stats: Any,+ drain_warnings: list[str],+ as_json: bool,+ log: Any,+ ) -> None:+ with_ids: bool = options["with_ids"]+ max_members = (+ DEFAULT_MAX_ORACLE_MEMBERS if options["max_oracle_members"] is None else options["max_oracle_members"]+ )+ completeness_by_cohort = reconcile_completeness_by_cohort(fold_stats)+ # Re-read after the drain: the batch calculation is scheduled and the drain takes minutes.+ current = {+ c.pk: c+ for c in Cohort.objects.filter(team_id=team_id, pk__in=selected_ids).only(+ "id", "version", "last_calculation", "is_calculating", "deleted"+ )+ }+ log(f"diffing up to {len(selected_ids)} cohort(s) against their pinned cohortpeople population")++ rows: list[PopulationComparison] = []+ warn_states: list[PopulationCohortState] = []+ for cid in sorted(selected_ids):+ name = names[cid]+ s = screened[cid]+ if not s.emits:+ # The fold side is structurally empty because the processor never emits for this+ # cohort, so a compared row would head the table at 0% and drag the aggregate for a+ # coverage gap the eligibility histogram already reports (and the stderr warning+ # above already called SKIPPED).+ reason = "not emit-eligible: " + ", ".join(s.drop_reasons or (s.eligibility,))+ rows.append(skip_population(cohort_id=cid, name=name, reason=reason))+ continue+ cohort = current.get(cid)+ if cohort is None:+ rows.append(skip_population(cohort_id=cid, name=name, reason="cohort_row_disappeared"))+ continue+ if cohort.deleted:+ # A soft delete enqueues an async DELETE of the cohort's whole cohortpeople range+ # with no version bump, so the guard below cannot catch it and the legacy side may+ # already read back empty.+ rows.append(skip_population(cohort_id=cid, name=name, reason="deleted_during_run"))+ continue+ if cohort.version != pre_drain_versions[cid] or cohort.last_calculation != pre_drain_calculated_at[cid]:+ # Reading cohortpeople at a version that is being collapsed away would silently+ # produce a garbage row, and calculate_people_ch stamps version and last_calculation+ # in separate writes, so either moving alone means the fold's bound no longer+ # matches the population read. Re-running is the fix, so say so instead of comparing.+ rows.append(skip_population(cohort_id=cid, name=name, reason="recalculated_during_run"))+ continue+ if cohort.version is None or cohort.last_calculation is None:+ # Reading nothing would render as a clean 100% row rather than "no oracle".+ rows.append(skip_population(cohort_id=cid, name=name, reason="never_calculated"))+ continue+ if cohort.last_calculation < since:+ # The fold is bounded there, so it is empty by construction and the diff would be a+ # spurious 0%.+ rows.append(skip_population(cohort_id=cid, name=name, reason="last_calculation_before_since"))+ continue++ try:+ legacy_members = load_cohort_population(team_id, cid, cohort.version, limit=max_members)+ except OracleSetTooLarge as err:+ rows.append(skip_population(cohort_id=cid, name=name, reason=f"population_over_{err.limit}"))+ continue+ warn_states.append(+ PopulationCohortState(+ cohort_id=cid,+ last_calculation=cohort.last_calculation,+ is_calculating=cohort.is_calculating,+ has_complete_reconcile=any(run.complete for run in completeness_by_cohort.get(cid, ())),+ )+ )+ rows.append(+ compare_populations(+ cohort_id=cid,+ name=name,+ fold_members=members(new_state.get(cid, {})),+ legacy_members=legacy_members,+ legacy_version=cohort.version,+ calculated_at=cohort.last_calculation,+ with_ids=with_ids,+ )+ )++ summary = summarize_population(rows)+ summary.warnings.extend(drain_warnings)+ summary.warnings.extend(_collect_population_warnings(now=now, states=warn_states))++ if as_json:+ meta = {+ "team_id": team_id,+ "since": since.isoformat(),+ "now": now.isoformat(),+ "oracle": "population",+ "with_ids": with_ids,+ "shadow_topic": options["shadow_topic"],+ "caveats": list(POPULATION_CAVEATS),+ }+ self.stdout.write(json.dumps(to_population_json(rows, summary, meta), indent=2))+ return+ self.stdout.write("")+ self.stdout.write(format_population_table(rows))+ self.stdout.write("")+ self.stdout.write(format_population_summary(summary))+ self.stdout.write("caveats:")+ for caveat in POPULATION_CAVEATS:+ self.stdout.write(f" {caveat}")+def _report_recompute(self,*,diff --git a/products/cohorts/backend/parity/fold.py b/products/cohorts/backend/parity/fold.pyindex 4e380f4ac6c6..8304cda3ebe7 100644--- a/products/cohorts/backend/parity/fold.py+++ b/products/cohorts/backend/parity/fold.py@@ -11,7 +11,7 @@ from __future__ import annotationsfrom collections.abc import Iterable, Mappingfrom dataclasses import dataclass, fieldfrom datetime import UTC, datetime-from typing import Any, Optional+from typing import Any, Optional, TypeGuardfrom uuid import UUIDRECONCILE_COMPLETE_TYPE = "reconcile_complete"@@ -87,6 +87,11 @@ def _optional_string(raw: Any) -> Optional[str]:return raw if isinstance(raw, str) and raw else None+def _is_int(value: Any) -> TypeGuard[int]:+ # bool subclasses int, so a bare isinstance check would accept True as a team/cohort/partition id.+ return isinstance(value, int) and not isinstance(value, bool)++def _record_marker(message: dict[str, Any],cohort_id: Any,@@ -99,10 +104,8 @@ def _record_marker(partition = message.get("partition")if (run_id is None- or not isinstance(cohort_id, int)- or isinstance(cohort_id, bool)- or not isinstance(partition, int)- or isinstance(partition, bool)+ or not _is_int(cohort_id)+ or not _is_int(partition)or not 0 <= partition < RECONCILE_PARTITION_COUNTor last_updated is None):@@ -119,25 +122,37 @@ def _record_marker(stats.cohorts_seen.add(cohort_id)+def _bound_for(+ cohort_id: Any,+ until: Optional[datetime],+ until_by_cohort: Optional[Mapping[int, datetime]],+) -> Optional[datetime]:+ if until_by_cohort is None or not _is_int(cohort_id):+ return until+ return until_by_cohort.get(cohort_id, until)++def fold_membership_changes(messages: Iterable[dict[str, Any]],*,team_id: int,since: datetime,until: Optional[datetime] = None,+ until_by_cohort: Optional[Mapping[int, datetime]] = None,) -> tuple[dict[int, dict[str, MembershipRecord]], FoldStats]:"""Fold messages to {cohort_id: {person_id: final record}}, dropping other teams'messages and anything stamped before `since` (pre-wipe residue).`until` bounds the fold to the converged state at an instant: with a pinned comparison clock thefold must not carry decisions the oracle's window cannot see, or every entry made after that- instant reads as an unexplained over-count."""+ instant reads as an unexplained over-count. `until_by_cohort` overrides that bound per cohort,+ for oracles whose clock is a per-cohort calculation time rather than one team-wide instant."""stats = FoldStats()state: dict[int, dict[str, MembershipRecord]] = {}for message in messages:stats.total += 1message_team_id = message.get("team_id")- if not isinstance(message_team_id, int) or isinstance(message_team_id, bool):+ if not _is_int(message_team_id):stats.dropped_malformed += 1continueif message_team_id != team_id:@@ -145,16 +160,16 @@ def fold_membership_changes(continuecohort_id = message.get("cohort_id")last_updated = parse_last_updated(message.get("last_updated"))+ bound = _bound_for(cohort_id, until, until_by_cohort)if message.get("type") == RECONCILE_COMPLETE_TYPE:- _record_marker(message, cohort_id, last_updated, since, until, stats)+ _record_marker(message, cohort_id, last_updated, since, bound, stats)continueperson_id = message.get("person_id")status = message.get("status")if (- not isinstance(cohort_id, int)- or isinstance(cohort_id, bool)+ not _is_int(cohort_id)or not isinstance(person_id, str)or not person_idor status not in ("entered", "left")@@ -165,7 +180,7 @@ def fold_membership_changes(if last_updated < since:stats.dropped_before_since += 1continue- if until is not None and last_updated > until:+ if bound is not None and last_updated > bound:stats.dropped_after_until += 1continue# Match the old side's argMax(status, last_updated): timestamp order, not arrivaldiff --git a/products/cohorts/backend/parity/oracle.py b/products/cohorts/backend/parity/oracle.pyindex ac0dfa7d1b42..d4b57c5cb4c2 100644--- a/products/cohorts/backend/parity/oracle.py+++ b/products/cohorts/backend/parity/oracle.py@@ -122,11 +122,11 @@ _PERSON_ID_CHUNK = 1000class OracleSetTooLarge(Exception):- """A leaf's member set exceeded the cap, so the oracle refuses to materialize it in memory."""+ """An oracle member set exceeded the cap, so the read refuses to materialize it in memory."""- def __init__(self, event_name: str, limit: int) -> None:- super().__init__(f"leaf {event_name!r} matches more than {limit} persons")- self.event_name = event_name+ def __init__(self, label: str, limit: int) -> None:+ super().__init__(f"{label} matches more than {limit} persons")+ self.label = labelself.limit = limit@@ -157,7 +157,7 @@ def load_leaf_members(team_id: int, leaf: OracleLeaf, *, at: datetime, tz: ZoneIteam_id=team_id,)if len(rows) > limit:- raise OracleSetTooLarge(leaf.event_name, limit)+ raise OracleSetTooLarge(f"leaf {leaf.event_name!r}", limit)return {str(row[0]).lower() for row in rows}diff --git a/products/cohorts/backend/parity/population.py b/products/cohorts/backend/parity/population.pynew file mode 100644index 000000000000..2534f0ef1793--- /dev/null+++ b/products/cohorts/backend/parity/population.py@@ -0,0 +1,112 @@+"""Set diff of the folded shadow membership against the legacy batch cohort population.++The ``--oracle population`` mode compares two sets of person ids and nothing else: the fold's+current members, and the population the legacy batch calculation wrote to ClickHouse+``cohortpeople`` at the cohort's pinned version (the set the cohort page shows). No cohort filter is+read, so no shape can be unsupported and no evaluator is reimplemented — and equally, nothing here+attributes divergence to a side. Report-only: there is no verdict and no gate.++Pure — no Django, no ClickHouse, no Kafka.+"""++from __future__ import annotations++from collections.abc import Sequence+from dataclasses import dataclass, field+from datetime import datetime+from typing import Optional+++@dataclass(frozen=True)+class PopulationComparison:+ cohort_id: int+ name: str+ compared: bool+ skip_reason: str = ""+ fold_count: int = 0+ legacy_count: int = 0+ both: int = 0+ only_fold: int = 0+ only_legacy: int = 0+ # None on skip rows: a skipped cohort has no agreement to report, and a 0.0 in the JSON would+ # read as total disagreement rather than as no data.+ match_pct: Optional[float] = None+ legacy_version: Optional[int] = None+ calculated_at: Optional[str] = None+ only_fold_ids: tuple[str, ...] = ()+ only_legacy_ids: tuple[str, ...] = ()+++def _match_pct(both: int, union: int) -> float:+ # An empty union is total agreement, not a ZeroDivisionError: neither side has anyone.+ return 100.0 if union == 0 else both / union * 100+++def compare_populations(+ *,+ cohort_id: int,+ name: str,+ fold_members: set[str],+ legacy_members: set[str],+ legacy_version: int,+ calculated_at: datetime,+ with_ids: bool,+) -> PopulationComparison:+ both = fold_members & legacy_members+ only_fold = fold_members - legacy_members+ only_legacy = legacy_members - fold_members+ return PopulationComparison(+ cohort_id=cohort_id,+ name=name,+ compared=True,+ fold_count=len(fold_members),+ legacy_count=len(legacy_members),+ both=len(both),+ only_fold=len(only_fold),+ only_legacy=len(only_legacy),+ match_pct=_match_pct(len(both), len(both) + len(only_fold) + len(only_legacy)),+ legacy_version=legacy_version,+ calculated_at=calculated_at.isoformat(),+ # Complete or absent: sampling a divergence list would make it unusable for the lookups+ # (`is this person in the seeder's output?`) the flag exists for.+ only_fold_ids=tuple(sorted(only_fold)) if with_ids else (),+ only_legacy_ids=tuple(sorted(only_legacy)) if with_ids else (),+ )+++def skip_population(*, cohort_id: int, name: str, reason: str) -> PopulationComparison:+ """A cohort with no usable oracle. Counts stay zeroed so a skip cannot render as agreement."""+ return PopulationComparison(cohort_id=cohort_id, name=name, compared=False, skip_reason=reason)+++@dataclass+class PopulationSummary:+ compared: int = 0+ skipped: int = 0+ fold_total: int = 0+ legacy_total: int = 0+ both_total: int = 0+ only_fold_total: int = 0+ only_legacy_total: int = 0+ # None when nothing was compared: an all-skip run must ship null, not a perfect 100.0.+ match_pct: Optional[float] = None+ warnings: list[str] = field(default_factory=list)+++def summarize_population(rows: Sequence[PopulationComparison]) -> PopulationSummary:+ summary = PopulationSummary()+ for row in rows:+ if not row.compared:+ summary.skipped += 1+ continue+ summary.compared += 1+ summary.fold_total += row.fold_count+ summary.legacy_total += row.legacy_count+ summary.both_total += row.both+ summary.only_fold_total += row.only_fold+ summary.only_legacy_total += row.only_legacy+ if summary.compared:+ summary.match_pct = _match_pct(+ summary.both_total, summary.both_total + summary.only_fold_total + summary.only_legacy_total+ )+ return summarydiff --git a/products/cohorts/backend/parity/report.py b/products/cohorts/backend/parity/report.pyindex 9a66207808b4..219e6a46e7be 100644--- a/products/cohorts/backend/parity/report.py+++ b/products/cohorts/backend/parity/report.py@@ -3,7 +3,7 @@from __future__ import annotationsfrom collections.abc import Mapping, Sequence-from dataclasses import asdict+from dataclasses import asdict, fieldsfrom typing import Anyfrom products.cohorts.backend.parity.classifier import (@@ -15,6 +15,7 @@ from products.cohorts.backend.parity.classifier import (CohortComparison,)from products.cohorts.backend.parity.fold import ReconcileRunCompleteness+from products.cohorts.backend.parity.population import PopulationComparison, PopulationSummaryfrom products.cohorts.backend.parity.recompute import RecomputeComparison, RecomputeSummary_VERDICT_ORDER = {VERDICT_FAIL: 0, VERDICT_WARMUP: 1, VERDICT_PASS: 2, VERDICT_SKIP: 3}@@ -167,3 +168,67 @@ def to_recompute_json("summary": asdict(summary),"cohorts": [asdict(r) for r in _sorted_recompute_rows(rows)],}+++def _sorted_population_rows(rows: Sequence[PopulationComparison]) -> list[PopulationComparison]:+ # Worst agreement first, because with no verdict to sort on that is what a report-only mode is+ # read for. Skipped rows have no match_pct and sort last on the compared key alone.+ return sorted(rows, key=lambda r: (not r.compared, r.match_pct if r.match_pct is not None else 0.0, r.cohort_id))+++_POPULATION_LABEL_WIDTH = 32+_POPULATION_MATCH_WIDTH = 7+_POPULATION_HEADER = (+ f"{'cohort':<{_POPULATION_LABEL_WIDTH}} {'fold':>9} {'legacy':>9} {'both':>9} "+ f"{'only_fold':>9} {'only_legacy':>11} {'match%':>{_POPULATION_MATCH_WIDTH}}"+)+# A skipped row spends every count column on the reason, so the line still aligns.+_POPULATION_SKIP_WIDTH = len(_POPULATION_HEADER) - _POPULATION_LABEL_WIDTH - _POPULATION_MATCH_WIDTH - 2+++def format_population_table(rows: Sequence[PopulationComparison]) -> str:+ lines = [_POPULATION_HEADER, "-" * len(_POPULATION_HEADER)]+ for r in _sorted_population_rows(rows):+ label = f"{r.cohort_id} {r.name}"+ if len(label) > _POPULATION_LABEL_WIDTH - 1:+ label = label[: _POPULATION_LABEL_WIDTH - 4] + "..."+ if not r.compared:+ reason = f"SKIP: {r.skip_reason}"[:_POPULATION_SKIP_WIDTH]+ lines.append(+ f"{label:<{_POPULATION_LABEL_WIDTH}} {reason:<{_POPULATION_SKIP_WIDTH}} "+ f"{'-':>{_POPULATION_MATCH_WIDTH}}"+ )+ continue+ match = "-" if r.match_pct is None else f"{r.match_pct:.2f}%"+ lines.append(+ f"{label:<{_POPULATION_LABEL_WIDTH}} {r.fold_count:>9} {r.legacy_count:>9} {r.both:>9} "+ f"{r.only_fold:>9} {r.only_legacy:>11} {match:>{_POPULATION_MATCH_WIDTH}}"+ )+ return "\n".join(lines)+++def format_population_summary(summary: PopulationSummary) -> str:+ # match_pct is None when nothing was compared: no data, not total agreement.+ match = f"{summary.match_pct:.2f}%" if summary.match_pct is not None else "-"+ lines = [+ f"compared: {summary.compared}, skipped: {summary.skipped}",+ f"fold={summary.fold_total} legacy={summary.legacy_total} both={summary.both_total} "+ f"only_fold={summary.only_fold_total} only_legacy={summary.only_legacy_total}; match={match}",+ ]+ for warning in summary.warnings:+ lines.append(f"WARNING: {warning}")+ return "\n".join(lines)+++def to_population_json(+ rows: Sequence[PopulationComparison],+ summary: PopulationSummary,+ meta: Mapping[str, Any],+) -> dict[str, Any]:+ return {+ "meta": dict(meta),+ "summary": asdict(summary),+ # Not asdict: it deep-copies containers, and with --with-ids the id tuples can hold the+ # whole diff; a shallow dict keeps them shared with the rows. No nested dataclasses here.+ "cohorts": [{f.name: getattr(r, f.name) for f in fields(r)} for r in _sorted_population_rows(rows)],+ }diff --git a/products/cohorts/backend/parity/snapshots.py b/products/cohorts/backend/parity/snapshots.pyindex 1977a1625cb0..49f44bac1d65 100644--- a/products/cohorts/backend/parity/snapshots.py+++ b/products/cohorts/backend/parity/snapshots.py@@ -4,6 +4,7 @@ from __future__ import annotationsfrom collections.abc import Callable, Sequencefrom datetime import datetime+from typing import Optionalfrom django.db.models import QuerySet@@ -13,11 +14,15 @@ from posthog.clickhouse.query_tagging import Feature, tag_queriesfrom posthog.schema_enums import ProductKeyfrom products.cohorts.backend.models.cohort import Cohort, CohortType+from products.cohorts.backend.parity.oracle import OracleSetTooLarge++# Both keyset cursors cast explicitly: person_id is a UUID column in both tables, and the cursor+# must compare in the column's own (UUID) order, the same order the ORDER BY paginates in. A bare+# string bind leans on ClickHouse coercing the constant, so the cast keeps the contract visible.+_CURSOR_PREDICATE = " AND person_id > toUUID(%(cursor)s)"# Same argMax convergence the old pipeline itself uses to read cohort_membership-# (realtime_cohort_calculation_workflow.py), keyset-paged on person_id: OFFSET paging-# would re-run the full aggregation per page, and each group's rows share one person_id-# so a cursor never splits a group across pages.+# (realtime_cohort_calculation_workflow.py), keyset-paged on person_id (see _paged_person_ids)._OLD_MEMBERS_SQL_TEMPLATE = """SELECT person_idFROM cohort_membership@@ -28,15 +33,35 @@ ORDER BY person_idLIMIT %(limit)s"""_OLD_MEMBERS_FIRST_PAGE_SQL = _OLD_MEMBERS_SQL_TEMPLATE.format(cursor="")-_OLD_MEMBERS_NEXT_PAGE_SQL = _OLD_MEMBERS_SQL_TEMPLATE.format(cursor=" AND person_id > %(cursor)s")+_OLD_MEMBERS_NEXT_PAGE_SQL = _OLD_MEMBERS_SQL_TEMPLATE.format(cursor=_CURSOR_PREDICATE)++# The legacy batch calculation's population, at the version the cohort page pins+# (in_cohort.py lowers a cohort property to `raw_cohort_people ... AND version = N`).+# `sum(sign) > 0` is the CollapsingMergeTree contract of the table; the calc path never+# tombstones the pinned version, so today it agrees with the UI's DISTINCT form.+_POPULATION_SQL_TEMPLATE = """+SELECT person_id+FROM cohortpeople+WHERE team_id = %(team_id)s AND cohort_id = %(cohort_id)s AND version = %(version)s{cursor}+GROUP BY person_id+HAVING sum(sign) > 0+ORDER BY person_id+LIMIT %(limit)s+"""+_POPULATION_FIRST_PAGE_SQL = _POPULATION_SQL_TEMPLATE.format(cursor="")+_POPULATION_NEXT_PAGE_SQL = _POPULATION_SQL_TEMPLATE.format(cursor=_CURSOR_PREDICATE)-_OLD_MEMBERS_SETTINGS = {+# Distinct from oracle.py's _MEMBER_SET_SETTINGS, which bounds single-shot leaf recomputes with+# query timeouts; these paged reads stream instead, so the ClickHouse side stays bounded and only+# the Python-side set can grow without limit (see _paged_person_ids for where that is capped).+_PAGED_MEMBER_SETTINGS = {# The old pipeline's own guards for this aggregation (EXTERNAL_GROUP_BY_MEMORY_RATIO):# without spill, a large cohort's GROUP BY person_id can OOM the offline pool."max_bytes_ratio_before_external_group_by": 0.5,"distributed_aggregation_memory_efficient": 1,- # person_id is a sort-key suffix under the two equality predicates, so aggregate in- # order and stream: LIMIT stops the scan instead of materializing every group first.+ # Both tables lead their sort key with (team_id, cohort_id), leaving person_id the first sort+ # column the equality filters do not pin, so aggregate in order and stream: LIMIT stops the+ # scan instead of materializing every group first."optimize_aggregation_in_order": 1,}@@ -61,38 +86,95 @@ def load_realtime_cohorts(team_id: int) -> QuerySet[Cohort]:deleted=False,filters__isnull=False,)- .only("id", "name", "filters", "last_realtime_cohort_calculation_at")+ .only(+ "id",+ "name",+ "filters",+ "last_realtime_cohort_calculation_at",+ "version",+ "last_calculation",+ "is_calculating",+ ).order_by("id"))-def load_old_membership(team_id: int, cohort_id: int, *, page_size: int = 500_000) -> set[str]:- """Converged entered-set of one cohort from ClickHouse cohort_membership (offline host).-- The full converged snapshot is read (not IN-filtered to the observed universe) because- the classifier needs `old - O` to compute the missed-emission probe.+def _paged_person_ids(+ *,+ first_page_sql: str,+ next_page_sql: str,+ params: dict[str, object],+ team_id: int,+ page_size: int,+ limit: Optional[int] = None,+ label: str = "",+) -> set[str]:+ """Keyset-paged person-id read: OFFSET would re-run the aggregation per page, and a group's+ rows all share one person_id so a cursor never splits one.++ ``limit`` caps the Python-side set (the query itself spills and streams): a single cohort can+ hold up to the 20M realtime ceiling, which no toolbox pod survives as a set of id strings, so+ past the cap the read raises :class:`OracleSetTooLarge` instead of OOMing a multi-cohort run.+ The check runs inside the page loop so at most ``limit + page_size`` ids are ever resident."""tag_queries(product=ProductKey.COHORTS, feature=Feature.COHORT)- members: set[str] = set()+ ids: set[str] = set()cursor: str | None = Nonewhile True:- params: dict[str, object] = {"team_id": team_id, "cohort_id": cohort_id, "limit": page_size}+ page_params: dict[str, object] = {**params, "limit": page_size}if cursor is not None:- params["cursor"] = cursor+ page_params["cursor"] = cursorrows = sync_execute(- _OLD_MEMBERS_FIRST_PAGE_SQL if cursor is None else _OLD_MEMBERS_NEXT_PAGE_SQL,- params,- settings=_OLD_MEMBERS_SETTINGS,+ first_page_sql if cursor is None else next_page_sql,+ page_params,+ settings=_PAGED_MEMBER_SETTINGS,workload=Workload.OFFLINE,team_id=team_id,)# Lowercased to match the fold's person-id normalization (see fold.py).- members.update(str(row[0]).lower() for row in rows)+ ids.update(str(row[0]).lower() for row in rows)+ if limit is not None and len(ids) > limit:+ raise OracleSetTooLarge(label, limit)if len(rows) < page_size:- return members+ return idscursor = str(rows[-1][0])+def load_old_membership(team_id: int, cohort_id: int, *, page_size: int = 500_000) -> set[str]:+ """Converged entered-set of one cohort from ClickHouse cohort_membership (offline host).++ The full converged snapshot is read (not IN-filtered to the observed universe) because+ the classifier needs `old - O` to compute the missed-emission probe. Uncapped: the legacy+ realtime workflow wrote this table for so few cohorts that the sets stay small in practice.+ """+ return _paged_person_ids(+ first_page_sql=_OLD_MEMBERS_FIRST_PAGE_SQL,+ next_page_sql=_OLD_MEMBERS_NEXT_PAGE_SQL,+ params={"team_id": team_id, "cohort_id": cohort_id},+ team_id=team_id,+ page_size=page_size,+ )+++def load_cohort_population(+ team_id: int, cohort_id: int, version: int, *, limit: int, page_size: int = 500_000+) -> set[str]:+ """The legacy batch calculation's population of one cohort, at its pinned version.++ Raises :class:`OracleSetTooLarge` past ``limit`` so an oversized cohort becomes a skip row+ rather than the end of the whole run.+ """+ return _paged_person_ids(+ first_page_sql=_POPULATION_FIRST_PAGE_SQL,+ next_page_sql=_POPULATION_NEXT_PAGE_SQL,+ params={"team_id": team_id, "cohort_id": cohort_id, "version": version},+ team_id=team_id,+ page_size=page_size,+ limit=limit,+ label=f"cohort {cohort_id} population at version {version}",+ )++def make_activity_probe(team_id: int) -> Callable[[Sequence[str], datetime], set[str]]:"""Missed-emission probe: which of `person_ids` had any event at/after `cutoff`."""diff --git a/products/cohorts/backend/parity/test/test_command_warnings.py b/products/cohorts/backend/parity/test/test_command_warnings.pyindex 1716728d137d..4a87c9f41a76 100644--- a/products/cohorts/backend/parity/test/test_command_warnings.py+++ b/products/cohorts/backend/parity/test/test_command_warnings.py@@ -7,8 +7,13 @@ from django.test import SimpleTestCasefrom parameterized import parameterizedfrom products.cohorts.backend.management.commands.compare_cohort_membership import (+ _ALL_MODE_FLAGS,+ _MODE_FLAGS,DEFAULT_THRESHOLD_PCT,+ Command,+ PopulationCohortState,RecomputeCohortState,+ _collect_population_warnings,_collect_recompute_warnings,_collect_warnings,_reject_flags,@@ -60,27 +65,72 @@ class TestCollectWarnings(SimpleTestCase):self.assertTrue(any("absent from the realtime universe" in w and "[7, 42]" in w for w in warnings))+_UNSET_FLAGS: dict[str, Any] = {+ "threshold": None,+ "warmup_sample": None,+ "no_classify": False,+ "at": None,+ "run_id": None,+ "grace_minutes": None,+ "max_window_days": None,+ "max_oracle_members": None,+ "with_ids": False,+}++class TestRejectFlags(SimpleTestCase):@parameterized.expand([- # Every mode-specific flag defaults to None precisely so a value that happens to equal the- # documented default is still rejected rather than silently ignored by the other oracle.- ("explicit_documented_default", {"threshold": DEFAULT_THRESHOLD_PCT}, True),- ("explicit_zero", {"warmup_sample": 0}, True),- ("store_true_set", {"no_classify": True}, True),- ("unset", {}, False),+ # Every mode-specific flag defaults to None (False for a store_true) precisely so a value+ # that happens to equal the documented default is still rejected rather than silently+ # ignored by another oracle.+ ("recompute_rejects_explicit_documented_default", "recompute", {"threshold": DEFAULT_THRESHOLD_PCT}, True),+ ("recompute_rejects_explicit_zero", "recompute", {"warmup_sample": 0}, True),+ ("recompute_rejects_store_true", "recompute", {"no_classify": True}, True),+ ("recompute_rejects_population_flag", "recompute", {"with_ids": True}, True),+ ("recompute_accepts_own_flag", "recompute", {"grace_minutes": 0}, False),+ ("population_rejects_recompute_flag", "population", {"at": "2026-07-30T00:00:00Z"}, True),+ ("population_rejects_old_pipeline_flag", "population", {"threshold": 1.0}, True),+ ("population_accepts_own_flag", "population", {"with_ids": True}, False),+ # max_oracle_members is owned by two modes; collapsing the registry back to single-owner+ # would make population reject the cap it needs against oversized cohortpeople reads.+ ("population_accepts_shared_max_oracle_members", "population", {"max_oracle_members": 5}, False),+ ("old_pipeline_rejects_population_flag", "old-pipeline", {"with_ids": True}, True),+ ("old_pipeline_accepts_own_flag", "old-pipeline", {"no_classify": True}, False),+ ("nothing_set", "population", {}, False),])- def test_explicit_values_are_rejected_even_when_they_match_the_default(- self, _name: str, overrides: dict, expect_error: bool+ def test_each_mode_rejects_only_the_flags_it_does_not_own(+ self, _name: str, mode: str, overrides: dict, expect_error: bool) -> None:- options: dict[str, Any] = {"threshold": None, "warmup_sample": None, "no_classify": False, **overrides}- flags = ("threshold", "warmup_sample", "no_classify")+ options = {**_UNSET_FLAGS, **overrides}if not expect_error:- _reject_flags(options, flags, "recompute")+ _reject_flags(options, mode)returnwith self.assertRaises(CommandError):- _reject_flags(options, flags, "recompute")+ _reject_flags(options, mode)++ def test_every_mode_only_flag_matches_the_registry(self) -> None:+ # A flag in the registry but missing from the parser fails loudly (KeyError on options), but+ # a parser flag missing from the registry is silently accepted by every other oracle. The+ # "<modes> only:" help prefix is the one place each flag names its owners, so hold it and+ # the registry in sync, in both directions.+ parser = Command().create_parser("manage.py", "compare_cohort_membership")+ prefixed: list[str] = []+ for action in parser._actions:+ owner_part, sep, _rest = (action.help or "").partition(" only:")+ if not sep:+ continue+ prefixed.append(action.dest)+ owners = owner_part.split("/")+ for mode, flags in _MODE_FLAGS.items():+ self.assertEqual(+ action.dest in flags,+ mode in owners,+ f"--{action.dest.replace('_', '-')}: help names {owners} but the registry owners "+ f"are {[m for m, f in _MODE_FLAGS.items() if action.dest in f]}",+ )+ self.assertEqual(sorted(prefixed), list(_ALL_MODE_FLAGS))def _ctx(**overrides: Any) -> RunContext:@@ -126,3 +176,26 @@ class TestCollectRecomputeWarnings(SimpleTestCase):self.assertTrue(any("shape-hash" in w for w in warnings))self.assertTrue(any("3 seed chunk(s) not confirmed" in w for w in warnings))self.assertTrue(any("no complete 64/64 reconcile" in w for w in warnings))+++class TestCollectPopulationWarnings(SimpleTestCase):+ def test_clean_state_yields_no_warnings(self) -> None:+ state = PopulationCohortState(+ cohort_id=1, last_calculation=NOW, is_calculating=False, has_complete_reconcile=True+ )+ self.assertEqual(_collect_population_warnings(now=NOW, states=[state]), [])++ def test_each_way_a_population_row_can_be_misread_is_called_out(self) -> None:+ # Without these the report reads as a like-for-like diff: only_legacy looks like a miss count+ # rather than an upper bound, a fold that cannot reach back looks like a real under-count, and+ # a population being rewritten under the read looks settled.+ state = PopulationCohortState(+ cohort_id=7,+ last_calculation=NOW - timedelta(days=8),+ is_calculating=True,+ has_complete_reconcile=False,+ )+ warnings = _collect_population_warnings(now=NOW, states=[state])+ self.assertTrue(any("no complete 64/64 reconcile" in w and "upper bound" in w for w in warnings))+ self.assertTrue(any("retention floor" in w for w in warnings))+ self.assertTrue(any("is_calculating" in w for w in warnings))diff --git a/products/cohorts/backend/parity/test/test_fold.py b/products/cohorts/backend/parity/test/test_fold.pyindex c3fcba2d912b..63aaf5def21e 100644--- a/products/cohorts/backend/parity/test/test_fold.py+++ b/products/cohorts/backend/parity/test/test_fold.py@@ -124,6 +124,33 @@ class TestFold(SimpleTestCase):self.assertEqual(members(state[10]), {"p1"})self.assertEqual(stats.dropped_after_until, 2)+ def test_until_by_cohort_bounds_each_cohort_on_its_own_clock(self) -> None:+ # Each cohort's legacy population is calculated on its own schedule, so the population oracle+ # bounds per cohort; one cohort's clock leaking onto another silently mis-scopes its fold.+ # Cohorts absent from the map fall back to the global `until`.+ state, stats = fold_membership_changes(+ [+ _msg("entered", "2026-07-07 19:09:00.000001", cohort_id=10, person_id="P1"),+ _msg("entered", "2026-07-07 19:09:00.000001", cohort_id=20, person_id="P2"),+ _msg("entered", "2026-07-07 19:19:00.000001", cohort_id=30, person_id="P3"),+ _marker(0, cohort_id=20, ts="2026-07-07 19:09:00.000001"),+ # Past cohort 10's own bound: a marker recorded here would flip has_complete_reconcile+ # and silence the only_legacy-is-an-upper-bound warning in population mode, where the+ # global until is always None.+ _marker(0, cohort_id=10, ts="2026-07-07 19:09:00.000001"),+ ],+ team_id=2,+ since=SINCE,+ until=datetime(2026, 7, 7, 19, 15, tzinfo=UTC),+ until_by_cohort={10: datetime(2026, 7, 7, 19, 5, tzinfo=UTC)},+ )+ self.assertNotIn(10, state)+ self.assertEqual(members(state[20]), {"p2"})+ self.assertNotIn(30, state)+ self.assertEqual(reconcile_completeness(stats, 20)[0].partitions_seen, 1)+ self.assertEqual(reconcile_completeness(stats, 10), ())+ self.assertEqual(stats.dropped_after_until, 3)+def test_until_bound_drops_later_reconcile_markers(self) -> None:_state, stats = fold_membership_changes([_marker(0, ts="2026-07-07 19:01:00.000001"), _marker(1, ts="2026-07-07 19:09:00.000001")],diff --git a/products/cohorts/backend/parity/test/test_population.py b/products/cohorts/backend/parity/test/test_population.pynew file mode 100644index 000000000000..b8d65efc2423--- /dev/null+++ b/products/cohorts/backend/parity/test/test_population.py@@ -0,0 +1,86 @@+from datetime import UTC, datetime++from django.test import SimpleTestCase++from parameterized import parameterized++from products.cohorts.backend.parity.population import compare_populations, skip_population, summarize_population++CALCULATED_AT = datetime(2026, 7, 30, 12, 0, tzinfo=UTC)+++def _compare(fold: set[str], legacy: set[str], *, cohort_id: int = 10, with_ids: bool = False):+ return compare_populations(+ cohort_id=cohort_id,+ name=f"c{cohort_id}",+ fold_members=fold,+ legacy_members=legacy,+ legacy_version=3,+ calculated_at=CALCULATED_AT,+ with_ids=with_ids,+ )+++class TestPopulation(SimpleTestCase):+ @parameterized.expand(+ [+ ("identical", {"a", "b"}, {"a", "b"}, 2, 0, 0, 100.0),+ # A cohort neither side has anyone in is total agreement, not a ZeroDivisionError.+ ("both_empty", set(), set(), 0, 0, 0, 100.0),+ ("fold_only", {"a", "b"}, set(), 0, 2, 0, 0.0),+ ("legacy_only", set(), {"a"}, 0, 0, 1, 0.0),+ ("partial_overlap", {"a", "b"}, {"b", "c"}, 1, 1, 1, 100 / 3),+ ("fold_superset", {"a", "b"}, {"a"}, 1, 1, 0, 50.0),+ ]+ )+ def test_set_shapes_score_over_the_union(+ self,+ _name: str,+ fold: set[str],+ legacy: set[str],+ both: int,+ only_fold: int,+ only_legacy: int,+ match_pct: float,+ ) -> None:+ row = _compare(fold, legacy)+ self.assertEqual(+ (row.fold_count, row.legacy_count, row.both, row.only_fold, row.only_legacy),+ (len(fold), len(legacy), both, only_fold, only_legacy),+ )+ self.assertAlmostEqual(row.match_pct, match_pct)++ def test_divergent_ids_ship_complete_only_when_asked(self) -> None:+ # The flag exists so an operator can look a person up in the seeder's output; a sampled or+ # truncated list would not answer that, and shipping ids by default would dump the whole diff.+ default = _compare({"b", "a"}, {"a", "c"})+ self.assertEqual((default.only_fold_ids, default.only_legacy_ids), ((), ()))++ with_ids = _compare({"b", "a"}, {"a", "c"}, with_ids=True)+ self.assertEqual(with_ids.only_fold_ids, ("b",))+ self.assertEqual(with_ids.only_legacy_ids, ("c",))++ def test_summary_totals_ignore_skipped_rows_and_weight_by_person(self) -> None:+ # Averaging per-row percentages would let a 2-person cohort outvote a 200-person one, and a+ # skipped cohort counted as agreement would hide the fact that it has no oracle at all.+ rows = [+ _compare({f"p{i}" for i in range(200)}, {f"p{i}" for i in range(100)}, cohort_id=1),+ _compare({"a"}, {"a"}, cohort_id=2),+ skip_population(cohort_id=3, name="c3", reason="never_calculated"),+ ]+ summary = summarize_population(rows)+ self.assertEqual((summary.compared, summary.skipped), (2, 1))+ self.assertEqual((summary.fold_total, summary.legacy_total), (201, 101))+ self.assertEqual((summary.both_total, summary.only_fold_total, summary.only_legacy_total), (101, 100, 0))+ assert summary.match_pct is not None+ self.assertAlmostEqual(summary.match_pct, 101 / 201 * 100)++ def test_all_skipped_run_has_no_match_pct(self) -> None:+ # A single --cohort-id run whose only row skips would otherwise serialize the all-zero totals+ # as a perfect 100.0 next to "compared": 0, and a JSON reader keying on the summary would+ # read "no oracle anywhere" as agreement.+ row = skip_population(cohort_id=3, name="c3", reason="last_calculation_before_since")+ self.assertIsNone(row.match_pct)+ summary = summarize_population([row])+ self.assertEqual((summary.compared, summary.skipped), (0, 1))+ self.assertIsNone(summary.match_pct)diff --git a/products/cohorts/backend/parity/test/test_report.py b/products/cohorts/backend/parity/test/test_report.pyindex bef16ee3753b..83102fe3c8a6 100644--- a/products/cohorts/backend/parity/test/test_report.py+++ b/products/cohorts/backend/parity/test/test_report.py@@ -9,12 +9,15 @@ from products.cohorts.backend.parity.classifier import (CohortComparison,)from products.cohorts.backend.parity.fold import ReconcileRunCompleteness+from products.cohorts.backend.parity.population import PopulationComparison, PopulationSummary, skip_populationfrom products.cohorts.backend.parity.recompute import RecomputeComparison, RecomputeSummaryfrom products.cohorts.backend.parity.report import (format_notes,+ format_population_table,format_recompute_table,format_reconcile_notes,to_json,+ to_population_json,to_recompute_json,)@@ -35,6 +38,16 @@ def _row()+def _population_row(cohort_id: int, *, match_pct: float, fold_count: int = 0) -> PopulationComparison:+ return PopulationComparison(+ cohort_id=cohort_id,+ name=f"c{cohort_id}",+ compared=True,+ match_pct=match_pct,+ fold_count=fold_count,+ )++class TestReport(SimpleTestCase):def test_json_rows_order_failures_first(self) -> None:rows = [@@ -143,3 +156,24 @@ class TestRecomputeReport(SimpleTestCase):lines = format_recompute_table(rows).split("\n")self.assertEqual({len(line) for line in lines}, {len(lines[0])})self.assertIn("SKIP: has_event_property_filters", lines[-1])++ def test_population_table_columns_line_up_across_row_kinds(self) -> None:+ rows = [+ _population_row(1, match_pct=99.5, fold_count=5303),+ skip_population(cohort_id=2, name="x" * 60, reason="never_calculated"),+ ]+ lines = format_population_table(rows).split("\n")+ self.assertEqual({len(line) for line in lines}, {len(lines[0])})+ self.assertIn("SKIP: never_calculated", lines[-1])++ def test_population_rows_order_worst_agreement_first(self) -> None:+ # The report has no verdict to sort on, so a sign flip here would put the healthiest cohorts+ # at the top of a long table and bury the divergent ones an operator is looking for.+ rows = [+ _population_row(1, match_pct=100.0),+ skip_population(cohort_id=2, name="c2", reason="never_calculated"),+ _population_row(3, match_pct=12.0),+ _population_row(4, match_pct=61.5),+ ]+ document = to_population_json(rows, PopulationSummary(), {})+ self.assertEqual([c["cohort_id"] for c in document["cohorts"]], [3, 4, 1, 2])