Skip to content

: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.

chore(cohorts): parity testing harness (#69448)

Matheus Batista7ee28d76b222
diff --git a/products/cohorts/backend/management/commands/compare_cohort_membership.py b/products/cohorts/backend/management/commands/compare_cohort_membership.py
new file mode 100644
index 000000000000..65a1b448cd45
--- /dev/null
+++ b/products/cohorts/backend/management/commands/compare_cohort_membership.py
@@ -0,0 +1,227 @@
+"""Classified parity report: new Rust cohort pipeline vs old Temporal recompute pipeline.
+
+Compares converged membership snapshots — the shadow topic folded to final state per
+(cohort, person) vs the argMax of ClickHouse cohort_membership — and classifies the
+divergences (R-EXCLUDE / R-FRESH / R-WARMUP / residual) so expected skew is separated
+from real bugs. Exits non-zero if any eligible cohort FAILs the residual gate.
+
+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"
+"""
+
+from __future__ import annotations
+
+import json
+from collections import Counter
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+
+from 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.fold import fold_membership_changes
+from products.cohorts.backend.parity.kafka_io import DEFAULT_SHADOW_TOPIC, DrainStats, consumer_config, drain_topic
+from products.cohorts.backend.parity.report import format_notes, format_summary, format_table, to_json
+from products.cohorts.backend.parity.snapshots import load_old_membership, load_realtime_cohorts, make_activity_probe
+
+SHADOW_TOPIC_RETENTION_DAYS = 7
+
+# Deliberate coverage limits, restated with every report so a clean run is not over-read.
+COVERAGE_CAVEATS = (
+ "WARMUP cohorts attribute all only_old to warmup (window predates the pipeline); they gate only on unexplained only_new",
+ "cohorts the old pipeline never recomputed count all only_new as fresh (residual_new is 0 there)",
+ "a partial drain (poll timeout or --max-messages) understates the new side and biases toward FAIL",
+)
+
+
+def _collect_warnings(
+ drain_stats: DrainStats,
+ unknown_cohorts: set[int],
+ since: datetime,
+ now: datetime,
+) -> tuple[list[str], list[str]]:
+ """Pure: derive operator (warnings, info lines) from drain results and the clock."""
+ warnings: list[str] = []
+ infos: list[str] = []
+ if drain_stats.earliest_retained is not None:
+ message = f"earliest retained shadow message: {drain_stats.earliest_retained.isoformat()}"
+ if drain_stats.maybe_clipped_partitions:
+ warnings.append(
+ message + f" — retention already clipped partitions {sorted(drain_stats.maybe_clipped_partitions)} "
+ "past --since; the fold may be incomplete"
+ )
+ else:
+ infos.append(message)
+ if not drain_stats.reached_end:
+ warnings.append(
+ "drain stopped before the high-watermark snapshot (poll timeout or --max-messages); fold is partial"
+ )
+ retention_deadline = since + timedelta(days=SHADOW_TOPIC_RETENTION_DAYS)
+ if now > retention_deadline - timedelta(days=1):
+ warnings.append(
+ f"fold-from-topic completeness expires ~{retention_deadline.date()} ({SHADOW_TOPIC_RETENTION_DAYS}d "
+ "topic retention) — ship the shadow materializer before then"
+ )
+ if unknown_cohorts:
+ warnings.append(
+ f"shadow topic contains {len(unknown_cohorts)} cohort id(s) absent from the realtime universe "
+ f"(deleted/retyped since?): {sorted(unknown_cohorts)[:20]}"
+ )
+ return warnings, infos
+
+
+def _parse_since(raw: str) -> datetime:
+ try:
+ parsed = datetime.fromisoformat(raw.replace("Z", "+00:00"))
+ except ValueError as err:
+ raise CommandError(f"--since is not ISO8601: {raw!r}") from err
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=UTC)
+ return parsed.astimezone(UTC)
+
+
+class Command(BaseCommand):
+ help = "Compare new-pipeline (shadow topic) vs old-pipeline (ClickHouse) cohort membership for one team"
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--team-id", type=int, required=True)
+ parser.add_argument(
+ "--since",
+ type=str,
+ required=True,
+ help="ISO8601 cutoff; must be the processor store-wipe time. Wrong values poison the fold and the warmup clock.",
+ )
+ parser.add_argument("--cohort-id", type=int, default=None, help="Limit to one cohort")
+ parser.add_argument("--threshold", type=float, default=0.5, help="Max residual %% of union for PASS")
+ parser.add_argument(
+ "--warmup-sample",
+ type=int,
+ default=5000,
+ help="Persons sampled per cohort for the R-WARMUP event check; 0 skips it (cohort-level warmup only)",
+ )
+ parser.add_argument("--no-classify", action="store_true", help="Raw snapshot diff only, no R-* rules")
+ parser.add_argument("--shadow-topic", type=str, default=DEFAULT_SHADOW_TOPIC)
+ parser.add_argument("--new-kafka-hosts", type=str, default=None, help="Override shadow-topic bootstrap servers")
+ parser.add_argument("--security-protocol", type=str, default=None, help="Override Kafka security protocol")
+ parser.add_argument("--format", choices=["table", "json"], default="table")
+ parser.add_argument("--max-messages", type=int, default=None, help="Cap on shadow messages drained")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ team_id: int = options["team_id"]
+ since = _parse_since(options["since"])
+ now = datetime.now(tz=UTC)
+ if since >= now:
+ raise CommandError("--since is in the future")
+ as_json = options["format"] == "json"
+
+ def log(message: str) -> None:
+ # Keep stdout clean for the JSON document.
+ (self.stderr if as_json else self.stdout).write(message)
+
+ # 1. Universe + eligibility screen (same rows the Rust loader reads). The screen
+ # always covers the whole team so cohort refs resolve, even with --cohort-id.
+ cohorts = list(load_realtime_cohorts(team_id))
+ if options["cohort_id"] is not None:
+ if options["cohort_id"] not in {c.pk for c in cohorts}:
+ raise CommandError(f"cohort {options['cohort_id']} is not a realtime cohort of team {team_id}")
+ selected_ids = [options["cohort_id"]]
+ else:
+ selected_ids = [c.pk for c in cohorts]
+ 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}
+
+ histogram = Counter(s.eligibility for s in screened.values())
+ log(f"eligibility histogram (cross-check against cohort_eligibility_total): {dict(histogram)}")
+ excluded = {cid: screened[cid] for cid in selected_ids if screened[cid].eligibility not in EMITTING_CLASSES}
+ for cid, s in sorted(excluded.items()):
+ self.stderr.write(
+ self.style.WARNING(
+ f"cohort {cid} screened {s.eligibility} (drops: {', '.join(s.drop_reasons) or '-'}) — "
+ "SKIPPED. If cohort_eligibility_total shows no excluded_* classes, the screen mis-classified "
+ "it; time to build the processor /debug/catalog endpoint."
+ )
+ )
+
+ # 2. New snapshot: bounded drain of the shadow topic, folded while consuming.
+ config = consumer_config(
+ hosts_override=options["new_kafka_hosts"],
+ security_protocol_override=options["security_protocol"],
+ )
+ log(f"draining {options['shadow_topic']} from {since.isoformat()} via {config['bootstrap.servers']}")
+ drain_stats = DrainStats()
+ messages = drain_topic(
+ options["shadow_topic"],
+ config=config,
+ since=since,
+ stats=drain_stats,
+ max_messages=options["max_messages"],
+ )
+ new_state, fold_stats = fold_membership_changes(messages, team_id=team_id, since=since)
+ 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 "
+ f"(dropped: {fold_stats.dropped_wrong_team} wrong-team, {fold_stats.dropped_before_since} pre-since, "
+ f"{fold_stats.dropped_malformed} malformed, {drain_stats.undecodable} undecodable)"
+ )
+
+ warnings, infos = _collect_warnings(drain_stats, fold_stats.cohorts_seen - set(screened), since, now)
+ for info in infos:
+ self.stderr.write(info)
+
+ # 3. Old snapshot + classification per eligible cohort.
+ classifier_config = ClassifierConfig(
+ since=since,
+ now=now,
+ threshold_pct=options["threshold"],
+ warmup_sample=options["warmup_sample"],
+ classify=not options["no_classify"],
+ activity_probe=make_activity_probe(team_id),
+ )
+ rows: list[CohortComparison] = []
+ for cid in sorted(selected_ids):
+ s = screened[cid]
+ old_members = load_old_membership(team_id, cid) if s.emits else set()
+ rows.append(
+ classify_cohort(
+ screened=s,
+ name=names[cid],
+ old_members=old_members,
+ new_state=new_state.get(cid, {}),
+ last_realtime_calculation_at=last_calc[cid],
+ config=classifier_config,
+ )
+ )
+
+ summary = summarize(rows, config=classifier_config)
+ summary.warnings.extend(warnings)
+
+ # 4. Report.
+ if as_json:
+ meta = {
+ "team_id": team_id,
+ "since": since.isoformat(),
+ "now": now.isoformat(),
+ "shadow_topic": options["shadow_topic"],
+ "threshold_pct": options["threshold"],
+ "warmup_sample": options["warmup_sample"],
+ "classify": not options["no_classify"],
+ "caveats": list(COVERAGE_CAVEATS),
+ }
+ self.stdout.write(json.dumps(to_json(rows, summary, meta), indent=2))
+ else:
+ self.stdout.write("")
+ self.stdout.write(format_table(rows))
+ notes = format_notes(rows)
+ if notes:
+ self.stdout.write("\nnotes:\n" + notes)
+ self.stdout.write("")
+ self.stdout.write(format_summary(summary))
+ self.stdout.write("caveats:")
+ for caveat in COVERAGE_CAVEATS:
+ self.stdout.write(f" {caveat}")
+
+ if summary.failed:
+ raise CommandError(f"{summary.failed} eligible cohort(s) FAIL the {options['threshold']}% residual gate")
diff --git a/products/cohorts/backend/parity/classifier.py b/products/cohorts/backend/parity/classifier.py
new file mode 100644
index 000000000000..c9cb270ef48b
--- /dev/null
+++ b/products/cohorts/backend/parity/classifier.py
@@ -0,0 +1,190 @@
+"""Per-cohort divergence classification: R-EXCLUDE / R-FRESH / R-WARMUP / residual gate.
+
+Pure — the sampled event-activity check is injected as a callable so tests need no
+ClickHouse. Rules apply in order; each explains (removes) part of the raw diff, and
+whatever remains is the gated residual.
+"""
+
+from __future__ import annotations
+
+import heapq
+from collections.abc import Callable, Sequence
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta
+from typing import Optional
+
+from products.cohorts.backend.parity.eligibility import ScreenedCohort
+from products.cohorts.backend.parity.fold import MembershipRecord, members
+
+VERDICT_PASS = "PASS"
+VERDICT_FAIL = "FAIL"
+VERDICT_SKIP = "SKIP"
+VERDICT_WARMUP = "WARMUP" # reported, not gated: window exceeds pipeline age
+
+# Persons (a sample of them) that had any event at/after the cutoff — the visibility
+# probe for R-WARMUP: a person with no post-cutoff event was never (re)evaluated by the
+# stream processor, so their absence on the new side is expected, not a bug.
+ActivityProbe = Callable[[Sequence[str], datetime], set[str]]
+
+
+@dataclass(frozen=True)
+class CohortComparison:
+ cohort_id: int
+ name: str
+ eligibility: str
+ old_count: int = 0
+ new_count: int = 0
+ both: int = 0
+ only_old: int = 0
+ only_new: int = 0
+ raw_diff_pct: float = 0.0
+ fresh: int = 0
+ warmup: int = 0
+ residual_old: int = 0
+ residual_new: int = 0
+ residual_pct: float = 0.0
+ verdict: str = VERDICT_SKIP
+ notes: tuple[str, ...] = ()
+
+ @property
+ def gated(self) -> bool:
+ return self.verdict in (VERDICT_PASS, VERDICT_FAIL)
+
+
+@dataclass
+class ClassifierConfig:
+ since: datetime
+ now: datetime
+ threshold_pct: float = 0.5
+ warmup_sample: int = 5000
+ classify: bool = True # False → raw diff only (--no-classify)
+ activity_probe: Optional[ActivityProbe] = None
+
+ @property
+ def pipeline_age_days(self) -> float:
+ return max((self.now - self.since).total_seconds() / 86_400, 0.0)
+
+
+def _pct(part: int, whole: int) -> float:
+ return part / whole * 100.0 if whole else 0.0
+
+
+def classify_cohort(
+ *,
+ screened: ScreenedCohort,
+ name: str,
+ old_members: set[str],
+ new_state: dict[str, MembershipRecord],
+ last_realtime_calculation_at: Optional[datetime],
+ config: ClassifierConfig,
+) -> CohortComparison:
+ if not screened.emits:
+ return CohortComparison(
+ cohort_id=screened.cohort_id,
+ name=name,
+ eligibility=screened.eligibility,
+ verdict=VERDICT_SKIP,
+ notes=("not emit-eligible: " + ", ".join(screened.drop_reasons or (screened.eligibility,)),),
+ )
+
+ new_members = members(new_state)
+ both = old_members & new_members
+ only_old = old_members - new_members
+ only_new = new_members - old_members
+ union_size = len(both) + len(only_old) + len(only_new)
+ raw_pct = _pct(len(only_old) + len(only_new), union_size)
+ notes: list[str] = []
+
+ fresh = 0
+ warmup = 0
+ cohort_warmup = False
+ if config.classify:
+ # R-FRESH: new-side entries the old pipeline hasn't recomputed past yet.
+ if last_realtime_calculation_at is None:
+ fresh = len(only_new)
+ if fresh:
+ notes.append("old side never recomputed this cohort; all only_new counted fresh")
+ else:
+ fresh = sum(1 for p in only_new if new_state[p].last_updated > last_realtime_calculation_at)
+
+ # R-WARMUP, cohort-level fast path: the whole behavioral window predates the pipeline.
+ window = screened.max_window_days
+ if window is not None and window > config.pipeline_age_days:
+ cohort_warmup = True
+ warmup = len(only_old)
+ notes.append(f"window {window:g}d > pipeline age {config.pipeline_age_days:.1f}d — whole cohort warming up")
+ elif only_old and config.warmup_sample > 0 and config.activity_probe is not None:
+ # R-WARMUP, person-level: only_old persons invisible to the stream (no event
+ # since the discovery cutoff) are expected skew. Sampled; extrapolated.
+ cutoff = config.since if window is None else max(config.since, config.now - timedelta(days=window))
+ sample = heapq.nsmallest(config.warmup_sample, only_old)
+ active = config.activity_probe(sample, cutoff)
+ sample_warmup = sum(1 for p in sample if p not in active)
+ warmup = round(sample_warmup / len(sample) * len(only_old))
+ if len(sample) < len(only_old):
+ notes.append(f"warmup extrapolated from sample {len(sample)}/{len(only_old)}")
+
+ residual_old = max(len(only_old) - warmup, 0)
+ residual_new = max(len(only_new) - fresh, 0)
+ residual_pct = _pct(residual_old + residual_new, union_size)
+
+ # A warming cohort's only_old is fully attributed to warmup, but its residual (all
+ # only_new there) is unexplained over-inclusion and must still gate — otherwise the
+ # WARMUP verdict masks new-pipeline bugs exactly while parity testing matters most.
+ if cohort_warmup and residual_pct <= config.threshold_pct:
+ verdict = VERDICT_WARMUP
+ elif residual_pct <= config.threshold_pct:
+ verdict = VERDICT_PASS
+ else:
+ verdict = VERDICT_FAIL
+
+ return CohortComparison(
+ cohort_id=screened.cohort_id,
+ name=name,
+ eligibility=screened.eligibility,
+ old_count=len(old_members),
+ new_count=len(new_members),
+ both=len(both),
+ only_old=len(only_old),
+ only_new=len(only_new),
+ raw_diff_pct=raw_pct,
+ fresh=fresh,
+ warmup=warmup,
+ residual_old=residual_old,
+ residual_new=residual_new,
+ residual_pct=residual_pct,
+ verdict=verdict,
+ notes=tuple(notes),
+ )
+
+
+@dataclass
+class AggregateSummary:
+ passed: int = 0
+ failed: int = 0
+ skipped: int = 0
+ warming_up: int = 0
+ fresh_total: int = 0
+ warmup_total: int = 0
+ residual_total: int = 0
+ raw_diff_total: int = 0
+ pipeline_age_days: float = 0.0
+ warnings: list[str] = field(default_factory=list)
+
+
+def summarize(rows: Sequence[CohortComparison], *, config: ClassifierConfig) -> AggregateSummary:
+ summary = AggregateSummary(pipeline_age_days=config.pipeline_age_days)
+ for row in rows:
+ if row.verdict == VERDICT_PASS:
+ summary.passed += 1
+ elif row.verdict == VERDICT_FAIL:
+ summary.failed += 1
+ elif row.verdict == VERDICT_WARMUP:
+ summary.warming_up += 1
+ else:
+ summary.skipped += 1
+ summary.fresh_total += row.fresh
+ summary.warmup_total += row.warmup
+ summary.residual_total += row.residual_old + row.residual_new
+ summary.raw_diff_total += row.only_old + row.only_new
+ return summary
diff --git a/products/cohorts/backend/parity/eligibility.py b/products/cohorts/backend/parity/eligibility.py
new file mode 100644
index 000000000000..a20428979957
--- /dev/null
+++ b/products/cohorts/backend/parity/eligibility.py
@@ -0,0 +1,475 @@
+"""Python mirror of the Rust cohort-stream-processor eligibility screen.
+
+Predicts, per cohort, the `class` label the processor reports in
+`cohort_eligibility_total` (single_leaf / stage2_composable / stage2_composable_ref /
+excluded_*), plus the max behavioral window in days (used by the R-WARMUP rule).
+Mirrors `rust/cohort-stream-processor/src/filters/{leaf_classifier,tree,cohort_graph}.rs`
+and `src/stage1/pick_state.rs` + `src/stage2/eligibility.rs` — including known quirks
+(e.g. a string `time_value` reads as absent), because the screen must predict what the
+processor actually emits, not what it ideally should.
+
+Mirrored at Rust commit 659e670e917; when those files change, re-check this module and
+the golden fixture against the Rust unit tests. This screen is a stopgap: retire it in
+favor of a processor `/debug/catalog` endpoint once one exists (building that endpoint
+is already the plan if `excluded_*` classes ever appear in `cohort_eligibility_total`).
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Mapping
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Any, Optional, Union
+
+SINGLE_LEAF = "single_leaf"
+STAGE2_COMPOSABLE = "stage2_composable"
+STAGE2_COMPOSABLE_REF = "stage2_composable_ref"
+EXCLUDED_NOT_MULTI_LEAF = "excluded_not_multi_leaf"
+EXCLUDED_TOP_LEVEL_NEGATION = "excluded_top_level_negation"
+EXCLUDED_EMPTY_GROUP = "excluded_empty_group"
+EXCLUDED_HAS_COHORT_REF = "excluded_has_cohort_ref"
+EXCLUDED_CYCLE_DETECTED = "excluded_cycle_detected"
+EXCLUDED_UNRESOLVED_REF = "excluded_unresolved_ref"
+EXCLUDED_HAS_DROPPED_LEAF = "excluded_has_dropped_leaf"
+# Not a processor metric class: the Rust loader skips these cohorts entirely.
+PARSE_ERROR = "parse_error"
+
+EMITTING_CLASSES = frozenset({SINGLE_LEAF, STAGE2_COMPOSABLE, STAGE2_COMPOSABLE_REF})
+
+_INTERVAL_DAYS = {"minute": 0, "hour": 0, "day": 1, "week": 7, "month": 30, "year": 365}
+_INTERVAL_SECONDS = {"minute": 60, "hour": 3_600}
+_RELATIVE_UNIT_DAYS = {"d": 1.0, "w": 7.0, "m": 30.0, "y": 365.0, "h": 1 / 24, "M": 1 / 1440}
+_I32_MAX = 2**31 - 1
+
+
+@dataclass(frozen=True)
+class ScreenedCohort:
+ cohort_id: int
+ eligibility: str
+ # Max whole-day window across kept behavioral leaves; inf for absolute explicit
+ # ranges (permanent membership); None when no kept behavioral leaf.
+ max_window_days: Optional[float]
+ drop_reasons: tuple[str, ...] = ()
+
+ @property
+ def emits(self) -> bool:
+ return self.eligibility in EMITTING_CLASSES
+
+
+@dataclass(frozen=True)
+class _Leaf:
+ kind: str # "person" | "behavioral" | "cohort_ref"
+ negated: bool = False
+ window_days: Optional[float] = None
+ ref_id: Optional[int] = None
+
+ @property
+ def state_keyed(self) -> bool:
+ return self.kind != "cohort_ref"
+
+
+@dataclass(frozen=True)
+class _Group:
+ op: str # "AND" | "OR"
+ children: tuple[_Node, ...]
+
+
+_Node = Union[_Group, _Leaf]
+
+
+@dataclass
+class _ParseFlags:
+ state_keyed_leaf_count: int = 0
+ has_cohort_ref: bool = False
+ drop_reasons: list[str] = field(default_factory=list)
+ behavioral_windows: list[float] = field(default_factory=list)
+ positive_ref_targets: set[int] = field(default_factory=set)
+ all_ref_targets: set[int] = field(default_factory=set)
+
+
+def _opt_i32(value: Any) -> Optional[int]:
+ # serde_json as_i64: integers only — bools, floats, and numeric strings read as absent.
+ if isinstance(value, bool) or not isinstance(value, int):
+ return None
+ return value if -(2**31) <= value <= _I32_MAX else None
+
+
+def _is_absolute_datetime(raw: str) -> bool:
+ try:
+ parsed = datetime.fromisoformat(raw)
+ except ValueError:
+ return False
+ if parsed.tzinfo is not None:
+ return True
+ # Naive shapes the Rust parser accepts: bare date, T- or space-separated datetime.
+ for fmt in ("%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M:%S.%f", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f"):
+ try:
+ datetime.strptime(raw, fmt)
+ return True
+ except ValueError:
+ continue
+ return False
+
+
+# A resolved eviction window: kind is "days" (whole-day sliding), "seconds" (sub-day
+# sliding), or "explicit" (absolute calendar range, permanent membership). `days` is the
+# window length in days for R-WARMUP (fractional for "seconds", inf for "explicit").
+@dataclass(frozen=True)
+class _Window:
+ kind: str
+ days: float
+
+
+# Mirror of the Rust Option<Option<EvictionWindow>>: `is_relative=False` means the
+# string is not a relative offset at all; `is_relative=True, window=None` means a
+# recognized relative grammar with no representable window (q/s units → leaf drops).
+@dataclass(frozen=True)
+class _RelativeParse:
+ is_relative: bool
+ window: Optional[_Window] = None
+
+
+_NOT_RELATIVE = _RelativeParse(is_relative=False)
+
+
+def _relative_offset_to_window(raw: str) -> _RelativeParse:
+ """Mirror of pick_state.rs relative_offset_to_window."""
+ if not raw.startswith("-"):
+ return _NOT_RELATIVE
+ rest = raw[1:]
+ split = next((i for i, c in enumerate(rest) if not c.isdigit()), None)
+ if split is None:
+ return _NOT_RELATIVE
+ digits, tail = rest[:split], rest[split:]
+ for suffix in ("Start", "End"):
+ if tail.endswith(suffix):
+ tail = tail[: -len(suffix)]
+ break
+ try:
+ count = int(digits)
+ except ValueError:
+ return _NOT_RELATIVE
+ if count > _I32_MAX:
+ return _NOT_RELATIVE
+ if tail in ("q", "s"):
+ return _RelativeParse(is_relative=True, window=None)
+ unit_days = _RELATIVE_UNIT_DAYS.get(tail)
+ if unit_days is None:
+ return _NOT_RELATIVE
+ if tail in ("h", "M"):
+ return _RelativeParse(is_relative=True, window=_Window("seconds", count * unit_days))
+ return _RelativeParse(is_relative=True, window=_Window("days", float(count * unit_days)))
+
+
+def _classify_bound(raw: str) -> tuple[str, Optional[_Window]]:
+ """One explicit_datetime bound → ("absolute"|"relative"|"unparseable", window)."""
+ if _is_absolute_datetime(raw):
+ return "absolute", None
+ parsed = _relative_offset_to_window(raw)
+ if parsed.is_relative:
+ return "relative", parsed.window
+ return "unparseable", None
+
+
+def _explicit_window(from_raw: Optional[str], to_raw: Optional[str]) -> Optional[_Window]:
+ """Mirror of pick_state.rs explicit_eviction_window; None = leaf drops."""
+ from_kind, from_window = _classify_bound(from_raw) if from_raw is not None else (None, None)
+ to_kind, _ = _classify_bound(to_raw) if to_raw is not None else (None, None)
+ if from_kind == "unparseable" or to_kind == "unparseable":
+ return None
+ if to_kind == "relative":
+ return None
+ if from_kind == "relative" and to_kind == "absolute":
+ return None
+ if from_kind == "relative":
+ return from_window # None for q/s → drop
+ return _Window("explicit", math.inf)
+
+
+def _interval_window(node: Mapping[str, Any]) -> Optional[_Window]:
+ interval = node.get("time_interval")
+ if not isinstance(interval, str) or interval not in _INTERVAL_DAYS:
+ return None
+ time_value = max(_opt_i32(node.get("time_value")) or 0, 0)
+ if _INTERVAL_DAYS[interval] == 0:
+ return _Window("seconds", time_value * _INTERVAL_SECONDS[interval] / 86_400)
+ return _Window("days", float(time_value * _INTERVAL_DAYS[interval]))
+
+
+def _behavioral_window_days(node: Mapping[str, Any], value: str) -> Optional[float]:
+ """The leaf's window in days, or None when the state variant is unsupported (drop)."""
+ # Non-string values read as absent (Rust opt_string), so coerce before the presence check.
+ explicit_from = node.get("explicit_datetime") if isinstance(node.get("explicit_datetime"), str) else None
+ explicit_to = node.get("explicit_datetime_to") if isinstance(node.get("explicit_datetime_to"), str) else None
+ if explicit_from is not None or explicit_to is not None:
+ window = _explicit_window(explicit_from, explicit_to)
+ else:
+ window = _interval_window(node)
+
+ if value == "performed_event":
+ return window.days if window is not None else None
+ # performed_event_multiple: only whole-day sliding windows ≥ 1 day are representable.
+ if window is not None and window.kind == "days" and window.days >= 1:
+ return window.days
+ return None
+
+
+def _valid_condition_hash(value: Any) -> bool:
+ return isinstance(value, str) and len(value.encode("utf-8")) == 16
+
+
+def _classify_leaf(node: Mapping[str, Any]) -> Union[_Leaf, str]:
+ """Mirror of leaf_classifier.rs classify_leaf: a kept/ref _Leaf, or a drop-reason string."""
+ leaf_type = node.get("type")
+ if leaf_type == "behavioral":
+ return _classify_behavioral(node)
+ if leaf_type == "cohort":
+ return _classify_cohort_ref(node)
+ if leaf_type == "person":
+ return _classify_person(node)
+ return "unknown_leaf_type"
+
+
+def _explicit_negation(node: Mapping[str, Any]) -> bool:
+ return node.get("negation") is True
+
+
+def _classify_behavioral(node: Mapping[str, Any]) -> Union[_Leaf, str]:
+ value = node.get("value")
+ if value not in ("performed_event", "performed_event_multiple"):
+ return "unsupported_behavioral_value"
+ key = node.get("key")
+ if isinstance(key, (int, float)) and not isinstance(key, bool):
+ return "behavioral_action_key"
+ if not _valid_condition_hash(node.get("conditionHash")):
+ return "missing_condition_hash"
+ if not isinstance(node.get("bytecode"), list):
+ return "missing_bytecode"
+ if not isinstance(key, str) or not key:
+ return "malformed_leaf"
+ window = _behavioral_window_days(node, value)
+ if window is None:
+ return "unsupported_state_variant"
+ return _Leaf(kind="behavioral", negated=_explicit_negation(node), window_days=window)
+
+
+def _classify_person(node: Mapping[str, Any]) -> Union[_Leaf, str]:
+ if not _valid_condition_hash(node.get("conditionHash")):
+ return "missing_condition_hash"
+ if not isinstance(node.get("bytecode"), list):
+ return "missing_bytecode"
+ return _Leaf(kind="person", negated=_explicit_negation(node))
+
+
+def _classify_cohort_ref(node: Mapping[str, Any]) -> Union[_Leaf, str]:
+ value = node.get("value")
+ ref_id: Optional[int] = _opt_i32(value)
+ if ref_id is None and isinstance(value, str):
+ try:
+ candidate = int(value.strip())
+ except ValueError:
+ candidate = None
+ if candidate is not None and -(2**31) <= candidate <= _I32_MAX:
+ ref_id = candidate
+ if ref_id is None:
+ return "malformed_leaf"
+ negation = _explicit_negation(node) or node.get("operator") == "not_in"
+ return _Leaf(kind="cohort_ref", negated=negation, ref_id=ref_id)
+
+
+def _parse_node(node: Any, flags: _ParseFlags) -> Optional[_Node]:
+ if not isinstance(node, Mapping):
+ flags.drop_reasons.append("unknown_leaf_type")
+ return None
+ if node.get("type") in ("AND", "OR") and isinstance(node.get("values"), list):
+ children = tuple(c for c in (_parse_node(child, flags) for child in node["values"]) if c is not None)
+ return _Group(op=node["type"], children=children)
+ classified = _classify_leaf(node)
+ if isinstance(classified, str):
+ flags.drop_reasons.append(classified)
+ return None
+ if classified.kind == "cohort_ref":
+ flags.has_cohort_ref = True
+ assert classified.ref_id is not None
+ flags.all_ref_targets.add(classified.ref_id)
+ if not classified.negated:
+ flags.positive_ref_targets.add(classified.ref_id)
+ else:
+ flags.state_keyed_leaf_count += 1
+ if classified.window_days is not None:
+ flags.behavioral_windows.append(classified.window_days)
+ return classified
+
+
+def _condition_negation(node: _Node) -> bool:
+ if isinstance(node, _Leaf):
+ return node.negated
+ if node.op == "AND":
+ return bool(node.children) and all(_condition_negation(c) for c in node.children)
+ return any(_condition_negation(c) for c in node.children)
+
+
+def _has_empty_group(node: _Node) -> bool:
+ if isinstance(node, _Leaf):
+ return False
+ return not node.children or any(_has_empty_group(c) for c in node.children)
+
+
+def _tree_leaves(node: _Node) -> list[_Leaf]:
+ if isinstance(node, _Leaf):
+ return [node]
+ return [leaf for child in node.children for leaf in _tree_leaves(child)]
+
+
+@dataclass
+class _Parsed:
+ root: _Node
+ flags: _ParseFlags
+
+
+def _parse_cohort(filters: Any) -> Optional[_Parsed]:
+ if not isinstance(filters, Mapping) or "properties" not in filters:
+ return None
+ flags = _ParseFlags()
+ root = _parse_node(filters["properties"], flags) or _Group(op="AND", children=())
+ return _Parsed(root=root, flags=flags)
+
+
+def _classify_cohort(parsed: _Parsed) -> str:
+ """Mirror of stage2/eligibility.rs classify() — pre-ref-refinement class."""
+ flags = parsed.flags
+ if flags.drop_reasons:
+ return EXCLUDED_HAS_DROPPED_LEAF
+ if _has_empty_group(parsed.root):
+ return EXCLUDED_EMPTY_GROUP
+ if _condition_negation(parsed.root):
+ return EXCLUDED_TOP_LEVEL_NEGATION
+ if flags.has_cohort_ref:
+ return EXCLUDED_HAS_COHORT_REF
+ leaves = _tree_leaves(parsed.root)
+ if len(leaves) == 1 and leaves[0].state_keyed:
+ return SINGLE_LEAF
+ if flags.state_keyed_leaf_count >= 2:
+ return STAGE2_COMPOSABLE
+ return EXCLUDED_NOT_MULTI_LEAF
+
+
+def _find_cycles(edges: Mapping[int, set[int]]) -> set[int]:
+ """Nodes in a ref cycle (SCC of size > 1, or self-loop), over all-ref edges.
+
+ Iterative Tarjan SCC (explicit work stack instead of recursion), matching the Rust
+ side's petgraph tarjan_scc.
+ """
+ in_cycle: set[int] = {n for n, targets in edges.items() if n in targets}
+ index_counter = [0]
+ stack: list[int] = []
+ on_stack: set[int] = set()
+ index: dict[int, int] = {}
+ lowlink: dict[int, int] = {}
+
+ def strongconnect(v: int) -> None:
+ work = [(v, iter(sorted(edges.get(v, ()))))]
+ index[v] = lowlink[v] = index_counter[0]
+ index_counter[0] += 1
+ stack.append(v)
+ on_stack.add(v)
+ while work:
+ node, it = work[-1]
+ advanced = False
+ for w in it:
+ if w not in index:
+ index[w] = lowlink[w] = index_counter[0]
+ index_counter[0] += 1
+ stack.append(w)
+ on_stack.add(w)
+ work.append((w, iter(sorted(edges.get(w, ())))))
+ advanced = True
+ break
+ if w in on_stack:
+ lowlink[node] = min(lowlink[node], index[w])
+ if advanced:
+ continue
+ work.pop()
+ if work:
+ parent = work[-1][0]
+ lowlink[parent] = min(lowlink[parent], lowlink[node])
+ if lowlink[node] == index[node]:
+ scc = []
+ while True:
+ w = stack.pop()
+ on_stack.discard(w)
+ scc.append(w)
+ if w == node:
+ break
+ if len(scc) > 1:
+ in_cycle.update(scc)
+
+ for node in sorted(edges):
+ if node not in index:
+ strongconnect(node)
+ return in_cycle
+
+
+def screen_team(
+ cohort_filters: Mapping[int, Any],
+ *,
+ cascade_enabled: bool = True,
+) -> dict[int, ScreenedCohort]:
+ """Screen every cohort of one team, including cross-cohort ref refinement."""
+ parsed: dict[int, Optional[_Parsed]] = {cid: _parse_cohort(f) for cid, f in cohort_filters.items()}
+ base: dict[int, str] = {}
+ for cid, p in parsed.items():
+ base[cid] = PARSE_ERROR if p is None else _classify_cohort(p)
+
+ edges = {cid: p.flags.all_ref_targets for cid, p in parsed.items() if p is not None and p.flags.all_ref_targets}
+ in_cycle = _find_cycles(edges) if edges else set()
+
+ # Ref refinement (stage2/eligibility.rs refine_ref_bearing), targets-before-referrers
+ # via memo. Iterative with an explicit stack: a long acyclic reference chain must not
+ # hit Python's recursion limit and crash the report.
+ final: dict[int, str] = {}
+ resolvable = {SINGLE_LEAF, STAGE2_COMPOSABLE, STAGE2_COMPOSABLE_REF, EXCLUDED_HAS_COHORT_REF}
+
+ def refine(cid: int) -> str:
+ stack = [cid]
+ while stack:
+ current = stack[-1]
+ if current in final:
+ stack.pop()
+ continue
+ cls = base.get(current)
+ if cls != EXCLUDED_HAS_COHORT_REF:
+ final[current] = cls if cls is not None else PARSE_ERROR
+ stack.pop()
+ continue
+ if current in in_cycle:
+ final[current] = EXCLUDED_CYCLE_DETECTED
+ stack.pop()
+ continue
+ p = parsed[current]
+ assert p is not None
+ targets = sorted(p.flags.positive_ref_targets)
+ # Refine known targets first; revisit `current` once they are all final.
+ # Terminates because every true reference cycle is pre-marked in `in_cycle`.
+ pending = [t for t in targets if t in base and t not in final]
+ if pending:
+ stack.extend(pending)
+ continue
+ if any(t not in base or final[t] not in resolvable for t in targets):
+ final[current] = EXCLUDED_UNRESOLVED_REF
+ else:
+ final[current] = STAGE2_COMPOSABLE_REF if cascade_enabled else EXCLUDED_HAS_COHORT_REF
+ stack.pop()
+ return final[cid]
+
+ result: dict[int, ScreenedCohort] = {}
+ for cid, p in parsed.items():
+ windows = p.flags.behavioral_windows if p is not None else []
+ result[cid] = ScreenedCohort(
+ cohort_id=cid,
+ eligibility=refine(cid),
+ max_window_days=max(windows) if windows else None,
+ drop_reasons=tuple(p.flags.drop_reasons) if p is not None else (),
+ )
+ return result
diff --git a/products/cohorts/backend/parity/fold.py b/products/cohorts/backend/parity/fold.py
new file mode 100644
index 000000000000..27e31abca62a
--- /dev/null
+++ b/products/cohorts/backend/parity/fold.py
@@ -0,0 +1,96 @@
+"""Fold a shadow-topic message stream into converged per-cohort membership state.
+
+Max last_updated per (cohort_id, person_id) wins, matching the argMax convergence of the
+old side's ClickHouse table. In practice that is also arrival order (messages are keyed
+by person_id, so one person's transitions live in one partition), but the timestamp rule
+keeps replays and clock regressions from shadowing a newer record.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from dataclasses import dataclass, field
+from datetime import UTC, datetime
+from typing import Any, Optional
+
+
+@dataclass(frozen=True)
+class MembershipRecord:
+ status: str # "entered" | "left"
+ last_updated: datetime
+
+
+@dataclass
+class FoldStats:
+ total: int = 0
+ folded: int = 0
+ dropped_wrong_team: int = 0
+ dropped_before_since: int = 0
+ dropped_malformed: int = 0
+ cohorts_seen: set[int] = field(default_factory=set)
+
+
+def parse_last_updated(raw: Any) -> Optional[datetime]:
+ """Parse the wire `last_updated` (ClickHouse DateTime64 string, UTC) to an aware datetime.
+
+ Accepts both the Rust `%.6f` and Python `%f` renderings, with or without fraction.
+ """
+ if not isinstance(raw, str):
+ return None
+ for fmt in ("%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S"):
+ try:
+ return datetime.strptime(raw, fmt).replace(tzinfo=UTC)
+ except ValueError:
+ continue
+ return None
+
+
+def fold_membership_changes(
+ messages: Iterable[dict[str, Any]],
+ *,
+ team_id: int,
+ since: datetime,
+) -> 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)."""
+ stats = FoldStats()
+ state: dict[int, dict[str, MembershipRecord]] = {}
+ for message in messages:
+ stats.total += 1
+ if message.get("team_id") != team_id:
+ stats.dropped_wrong_team += 1
+ continue
+ cohort_id = message.get("cohort_id")
+ person_id = message.get("person_id")
+ status = message.get("status")
+ last_updated = parse_last_updated(message.get("last_updated"))
+ if (
+ not isinstance(cohort_id, int)
+ or isinstance(cohort_id, bool)
+ or not isinstance(person_id, str)
+ or not person_id
+ or status not in ("entered", "left")
+ or last_updated is None
+ ):
+ stats.dropped_malformed += 1
+ continue
+ if last_updated < since:
+ stats.dropped_before_since += 1
+ continue
+ # Match the old side's argMax(status, last_updated): timestamp order, not arrival
+ # order, so an out-of-order replay cannot shadow a newer record.
+ bucket = state.setdefault(cohort_id, {})
+ # Person ids compare case-insensitively: every membership source lowercases at
+ # its boundary (here and both readers in snapshots.py) or the sets stop matching.
+ key = person_id.lower()
+ prior = bucket.get(key)
+ if prior is None or last_updated >= prior.last_updated:
+ bucket[key] = MembershipRecord(status=status, last_updated=last_updated)
+ stats.cohorts_seen.add(cohort_id)
+ stats.folded += 1
+ return state, stats
+
+
+def members(state: dict[str, MembershipRecord]) -> set[str]:
+ """The currently-entered persons of one cohort's folded state."""
+ return {person_id for person_id, record in state.items() if record.status == "entered"}
diff --git a/products/cohorts/backend/parity/kafka_io.py b/products/cohorts/backend/parity/kafka_io.py
new file mode 100644
index 000000000000..781324a6bdf2
--- /dev/null
+++ b/products/cohorts/backend/parity/kafka_io.py
@@ -0,0 +1,172 @@
+"""Kafka profile resolution and a bounded shadow-topic drain.
+
+The drain reads each partition from `offsets_for_times(--since)` up to a high-watermark
+snapshot taken at start, so a still-producing topic terminates. Uses a throwaway
+consumer group with commits disabled and explicit `assign()` — a diagnostic tool must
+never join or disturb a real consumer group.
+"""
+
+from __future__ import annotations
+
+import json
+import uuid
+from collections.abc import Iterator
+from dataclasses import dataclass, field
+from datetime import UTC, datetime
+from typing import Any, Optional
+
+from confluent_kafka import OFFSET_END, Consumer, KafkaError, TopicPartition
+
+from posthog.kafka_client.profiles import KafkaClusterProfile
+from posthog.kafka_client.routing import get_profile_settings
+
+DEFAULT_SHADOW_TOPIC = "cohort_membership_changed_shadow"
+
+
+@dataclass
+class DrainStats:
+ partitions: int = 0
+ partitions_read: int = 0
+ consumed: int = 0
+ undecodable: int = 0
+ # Earliest broker timestamp observed among partitions read from their low watermark.
+ earliest_retained: Optional[datetime] = None
+ # Partitions where retention already deleted offsets and the earliest retained
+ # message is newer than --since: the fold cannot be proven complete.
+ maybe_clipped_partitions: list[int] = field(default_factory=list)
+ reached_end: bool = False
+
+
+def consumer_config(
+ *,
+ hosts_override: Optional[str] = None,
+ security_protocol_override: Optional[str] = None,
+) -> dict[str, Any]:
+ """Consumer config for the shadow topic's cluster (Warpstream ingestion).
+
+ The shadow topic is not in the Django routing table, so the INGESTION profile is
+ resolved explicitly; overrides serve local runs against a dev stack.
+ """
+ profile = get_profile_settings(profile=KafkaClusterProfile.INGESTION)
+ hosts = hosts_override or ",".join(profile.hosts)
+ config: dict[str, Any] = {
+ "bootstrap.servers": hosts,
+ "group.id": f"cohort-parity-{uuid.uuid4().hex[:8]}",
+ "enable.auto.commit": False,
+ "auto.offset.reset": "earliest",
+ }
+ security_protocol = security_protocol_override or profile.security_protocol
+ if security_protocol:
+ config["security.protocol"] = security_protocol
+ # Only forward the profile's SASL creds to the profile's own hosts; an explicit host
+ # override is a local/dev target that must not receive the production credential.
+ if security_protocol in ("SASL_PLAINTEXT", "SASL_SSL") and hosts_override is None:
+ config["sasl.mechanism"] = profile.sasl_mechanism
+ config["sasl.username"] = profile.sasl_user
+ config["sasl.password"] = profile.sasl_password
+ return config
+
+
+def _broker_ts(message: Any) -> Optional[datetime]:
+ _ts_type, ts_ms = message.timestamp()
+ if ts_ms is None or ts_ms <= 0:
+ return None
+ return datetime.fromtimestamp(ts_ms / 1000, tz=UTC)
+
+
+def _resolve_start_offsets(
+ consumer: Consumer, topic: str, since: datetime, stats: DrainStats
+) -> tuple[list[TopicPartition], dict[int, int], set[int], dict[int, int]]:
+ """Per-partition drain bounds: (assignment at start offsets, partition → exclusive
+ high-watermark end, partitions starting at their low watermark, partition → low)."""
+ metadata = consumer.list_topics(topic, timeout=15)
+ topic_meta = metadata.topics.get(topic)
+ if topic_meta is None or topic_meta.error is not None:
+ raise RuntimeError(f"topic {topic!r} not found: {topic_meta.error if topic_meta else 'no metadata'}")
+ stats.partitions = len(topic_meta.partitions)
+
+ since_ms = int(since.timestamp() * 1000)
+ lows: dict[int, int] = {}
+ highs: dict[int, int] = {}
+ for partition in topic_meta.partitions:
+ low, high = consumer.get_watermark_offsets(TopicPartition(topic, partition), timeout=15)
+ lows[partition], highs[partition] = low, high
+
+ start_requests = [TopicPartition(topic, p, since_ms) for p in sorted(lows) if highs[p] > lows[p]]
+ starts = consumer.offsets_for_times(start_requests, timeout=15) if start_requests else []
+
+ assignment: list[TopicPartition] = []
+ remaining: dict[int, int] = {}
+ at_low: set[int] = set()
+ for tp in starts:
+ if tp.error is not None:
+ raise RuntimeError(f"offsets_for_times failed for partition {tp.partition}: {tp.error}")
+ if tp.offset < 0 or tp.offset == OFFSET_END or tp.offset >= highs[tp.partition]:
+ continue # no retained message at/after --since in this partition
+ if tp.offset == lows[tp.partition]:
+ at_low.add(tp.partition)
+ remaining[tp.partition] = highs[tp.partition]
+ assignment.append(TopicPartition(topic, tp.partition, tp.offset))
+
+ stats.partitions_read = len(assignment)
+ return assignment, remaining, at_low, lows
+
+
+def drain_topic(
+ topic: str,
+ *,
+ config: dict[str, Any],
+ since: datetime,
+ stats: DrainStats,
+ max_messages: Optional[int] = None,
+ poll_timeout: float = 5.0,
+) -> Iterator[dict[str, Any]]:
+ """Yield JSON-decoded messages from `since` up to the start-time high watermark."""
+ consumer = Consumer(config)
+ try:
+ assignment, remaining, at_low, lows = _resolve_start_offsets(consumer, topic, since, stats)
+ if not assignment:
+ stats.reached_end = True
+ return
+ consumer.assign(assignment)
+
+ first_seen: set[int] = set()
+ while remaining:
+ message = consumer.poll(timeout=poll_timeout)
+ if message is None:
+ return # broker went quiet before the watermark snapshot — stats.reached_end stays False
+ error = message.error()
+ if error is not None:
+ if error.code() == getattr(KafkaError, "_PARTITION_EOF", None):
+ continue
+ raise RuntimeError(str(error))
+
+ partition = message.partition()
+ if partition not in remaining:
+ continue # already past this partition's start-time high watermark
+ if partition in at_low and partition not in first_seen:
+ first_seen.add(partition)
+ ts = _broker_ts(message)
+ if ts is not None:
+ if stats.earliest_retained is None or ts < stats.earliest_retained:
+ stats.earliest_retained = ts
+ if lows[partition] > 0 and ts > since:
+ stats.maybe_clipped_partitions.append(partition)
+
+ value = message.value()
+ if value is not None:
+ try:
+ decoded = json.loads(value.decode("utf-8"))
+ except (ValueError, UnicodeDecodeError):
+ stats.undecodable += 1
+ else:
+ stats.consumed += 1
+ yield decoded
+ if max_messages is not None and stats.consumed >= max_messages:
+ return
+ offset = message.offset()
+ if offset is not None and offset + 1 >= remaining[partition]:
+ del remaining[partition]
+ stats.reached_end = True
+ finally:
+ consumer.close()
diff --git a/products/cohorts/backend/parity/report.py b/products/cohorts/backend/parity/report.py
new file mode 100644
index 000000000000..3c65689c6f42
--- /dev/null
+++ b/products/cohorts/backend/parity/report.py
@@ -0,0 +1,72 @@
+"""Render classified parity rows as a fixed-width table or a JSON document."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping, Sequence
+from dataclasses import asdict
+from typing import Any
+
+from products.cohorts.backend.parity.classifier import (
+ VERDICT_FAIL,
+ VERDICT_PASS,
+ VERDICT_SKIP,
+ VERDICT_WARMUP,
+ AggregateSummary,
+ CohortComparison,
+)
+
+_VERDICT_ORDER = {VERDICT_FAIL: 0, VERDICT_WARMUP: 1, VERDICT_PASS: 2, VERDICT_SKIP: 3}
+
+
+def _sorted_rows(rows: Sequence[CohortComparison]) -> list[CohortComparison]:
+ return sorted(rows, key=lambda r: (_VERDICT_ORDER.get(r.verdict, 9), -r.residual_pct, r.cohort_id))
+
+
+def format_table(rows: Sequence[CohortComparison]) -> str:
+ header = (
+ f"{'cohort':<32} {'class':<24} {'old':>9} {'new':>9} {'both':>9} "
+ f"{'only_old':>9} {'only_new':>9} {'raw%':>7} {'fresh':>8} {'warmup':>8} {'resid%':>7} {'verdict':>7}"
+ )
+ lines = [header, "-" * len(header)]
+ for r in _sorted_rows(rows):
+ label = f"{r.cohort_id} {r.name}"
+ if len(label) > 31:
+ label = label[:28] + "..."
+ lines.append(
+ f"{label:<32} {r.eligibility:<24} {r.old_count:>9} {r.new_count:>9} {r.both:>9} "
+ f"{r.only_old:>9} {r.only_new:>9} {r.raw_diff_pct:>6.2f}% {r.fresh:>8} {r.warmup:>8} "
+ f"{r.residual_pct:>6.2f}% {r.verdict:>7}"
+ )
+ return "\n".join(lines)
+
+
+def format_notes(rows: Sequence[CohortComparison]) -> str:
+ lines = []
+ for r in _sorted_rows(rows):
+ for note in r.notes:
+ lines.append(f" cohort {r.cohort_id}: {note}")
+ return "\n".join(lines)
+
+
+def format_summary(summary: AggregateSummary) -> str:
+ lines = [
+ f"verdicts: {summary.passed} PASS, {summary.failed} FAIL, {summary.warming_up} WARMUP, {summary.skipped} SKIP",
+ f"skew explained: fresh={summary.fresh_total} warmup={summary.warmup_total} "
+ f"residual={summary.residual_total} (of {summary.raw_diff_total} raw diff)",
+ f"pipeline age: {summary.pipeline_age_days:.1f}d since --since",
+ ]
+ for warning in summary.warnings:
+ lines.append(f"WARNING: {warning}")
+ return "\n".join(lines)
+
+
+def to_json(
+ rows: Sequence[CohortComparison],
+ summary: AggregateSummary,
+ meta: Mapping[str, Any],
+) -> dict[str, Any]:
+ return {
+ "meta": dict(meta),
+ "summary": asdict(summary),
+ "cohorts": [asdict(r) for r in _sorted_rows(rows)],
+ }
diff --git a/products/cohorts/backend/parity/snapshots.py b/products/cohorts/backend/parity/snapshots.py
new file mode 100644
index 000000000000..262739542b8f
--- /dev/null
+++ b/products/cohorts/backend/parity/snapshots.py
@@ -0,0 +1,110 @@
+"""Old-pipeline snapshot and warmup-probe reads (ClickHouse) + cohort universe (ORM)."""
+
+from __future__ import annotations
+
+from collections.abc import Callable, Sequence
+from datetime import datetime
+
+from django.db.models import QuerySet
+
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.client.connection import Workload
+from posthog.clickhouse.query_tagging import Feature, tag_queries
+from posthog.schema_enums import ProductKey
+
+from products.cohorts.backend.models.cohort import Cohort, CohortType
+
+# 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.
+_OLD_MEMBERS_SQL_TEMPLATE = """
+SELECT person_id
+FROM cohort_membership
+WHERE team_id = %(team_id)s AND cohort_id = %(cohort_id)s{cursor}
+GROUP BY person_id
+HAVING argMax(status, last_updated) = 'entered'
+ORDER BY person_id
+LIMIT %(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_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.
+ "optimize_aggregation_in_order": 1,
+}
+
+_ACTIVE_PERSONS_SQL = """
+SELECT DISTINCT person_id
+FROM events
+WHERE team_id = %(team_id)s AND timestamp >= %(cutoff)s AND person_id IN %(person_ids)s
+"""
+
+_ACTIVITY_CHUNK = 1000
+
+
+def load_realtime_cohorts(team_id: int) -> QuerySet[Cohort]:
+ """The rows the Rust filter loader reads (loader.rs REALTIME_COHORTS_SQL).
+
+ Narrowed to the fields the parity report consumes.
+ """
+ return (
+ Cohort.objects.filter(
+ team_id=team_id,
+ cohort_type=CohortType.REALTIME,
+ deleted=False,
+ filters__isnull=False,
+ )
+ .only("id", "name", "filters", "last_realtime_cohort_calculation_at")
+ .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)."""
+ tag_queries(product=ProductKey.COHORTS, feature=Feature.COHORT)
+ members: set[str] = set()
+ cursor: str | None = None
+ while True:
+ params: dict[str, object] = {"team_id": team_id, "cohort_id": cohort_id, "limit": page_size}
+ if cursor is not None:
+ params["cursor"] = cursor
+ rows = sync_execute(
+ _OLD_MEMBERS_FIRST_PAGE_SQL if cursor is None else _OLD_MEMBERS_NEXT_PAGE_SQL,
+ params,
+ settings=_OLD_MEMBERS_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)
+ if len(rows) < page_size:
+ return members
+ cursor = str(rows[-1][0])
+
+
+def make_activity_probe(team_id: int) -> Callable[[Sequence[str], datetime], set[str]]:
+ """R-WARMUP probe: which of `person_ids` had any event at/after `cutoff`."""
+
+ def probe(person_ids: Sequence[str], cutoff: datetime) -> set[str]:
+ tag_queries(product=ProductKey.COHORTS, feature=Feature.COHORT)
+ active: set[str] = set()
+ for start in range(0, len(person_ids), _ACTIVITY_CHUNK):
+ chunk = list(person_ids[start : start + _ACTIVITY_CHUNK])
+ rows = sync_execute(
+ _ACTIVE_PERSONS_SQL,
+ {"team_id": team_id, "cutoff": cutoff, "person_ids": chunk},
+ workload=Workload.OFFLINE,
+ team_id=team_id,
+ )
+ # Lowercased to match the fold's person-id normalization (see fold.py).
+ active.update(str(row[0]).lower() for row in rows)
+ return active
+
+ return probe
diff --git a/products/cohorts/backend/parity/test/fixtures/eligibility_golden.json b/products/cohorts/backend/parity/test/fixtures/eligibility_golden.json
new file mode 100644
index 000000000000..5b9f94c2d262
--- /dev/null
+++ b/products/cohorts/backend/parity/test/fixtures/eligibility_golden.json
@@ -0,0 +1,261 @@
+{
+ "_comment": "Golden vectors mirroring the Rust unit tests in leaf_classifier.rs, eligibility.rs, and pick_state.rs. expected_window_days: number of days, 'inf' for absolute explicit ranges, null for no kept behavioral leaf.",
+ "cases": [
+ {
+ "name": "performed_event_daily_window_is_single_leaf",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event", "key": "$pageview", "time_value": 7, "time_interval": "day", "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "single_leaf",
+ "expected_window_days": 7
+ },
+ {
+ "name": "performed_event_multiple_daily_window_is_kept",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event_multiple", "key": "$pageview", "time_value": 7, "time_interval": "day", "operator": "gte", "operator_value": 3, "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "single_leaf",
+ "expected_window_days": 7
+ },
+ {
+ "name": "performed_event_multiple_sub_day_window_is_dropped",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event_multiple", "key": "$pageview", "time_value": 5, "time_interval": "hour", "operator": "gte", "operator_value": 3, "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "performed_event_multiple_365_day_window_is_kept",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event_multiple", "key": "$pageview", "time_value": 365, "time_interval": "day", "operator": "gte", "operator_value": 3, "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "single_leaf",
+ "expected_window_days": 365
+ },
+ {
+ "name": "performed_event_multiple_explicit_relative_lower_7d_is_kept",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event_multiple", "key": "$pageview", "explicit_datetime": "-7d", "operator": "gte", "operator_value": 3, "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "single_leaf",
+ "expected_window_days": 7
+ },
+ {
+ "name": "performed_event_multiple_explicit_relative_lower_1y_is_kept",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event_multiple", "key": "$pageview", "explicit_datetime": "-1y", "operator": "gte", "operator_value": 3, "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "single_leaf",
+ "expected_window_days": 365
+ },
+ {
+ "name": "performed_event_multiple_explicit_sub_day_is_dropped",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event_multiple", "key": "$pageview", "explicit_datetime": "-2h", "operator": "gte", "operator_value": 3, "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "performed_event_multiple_explicit_whole_day_hours_is_dropped",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event_multiple", "key": "$pageview", "explicit_datetime": "-24h", "operator": "gte", "operator_value": 3, "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "performed_event_multiple_explicit_absolute_range_is_dropped",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event_multiple", "key": "$pageview", "explicit_datetime": "2026-01-01", "explicit_datetime_to": "2026-12-31", "operator": "gte", "operator_value": 3, "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "performed_event_without_window_is_dropped",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event", "key": "$pageview", "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "performed_event_sequence_is_dropped",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event_sequence", "key": "$pageview", "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "action_keyed_behavioral_is_dropped",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event", "key": 12345, "time_value": 7, "time_interval": "day", "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "behavioral_without_condition_hash_is_dropped",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event", "key": "$pageview", "time_value": 7, "time_interval": "day", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "short_condition_hash_is_dropped",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event", "key": "$pageview", "time_value": 7, "time_interval": "day", "conditionHash": "tooshort", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "behavioral_without_bytecode_is_dropped",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event", "key": "$pageview", "time_value": 7, "time_interval": "day", "conditionHash": "0123456789abcdef"}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "non_array_bytecode_is_dropped",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event", "key": "$pageview", "time_value": 7, "time_interval": "day", "conditionHash": "0123456789abcdef", "bytecode": "not-an-array"}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "person_leaf_is_single_leaf_without_window",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "person", "key": "email", "value": "[email protected]", "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 1, 2, 11]}]}},
+ "expected": "single_leaf",
+ "expected_window_days": null
+ },
+ {
+ "name": "person_without_condition_hash_is_dropped",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "person", "key": "email", "value": "[email protected]", "bytecode": ["_H", 1, 32, "[email protected]", 32, "email", 32, "properties", 1, 2, 11]}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "person_without_bytecode_is_dropped",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "person", "key": "email", "value": "[email protected]", "conditionHash": "0123456789abcdef"}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "unknown_leaf_type_is_dropped",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "event", "key": "$pageview", "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "performed_event_sub_day_window_is_kept_fractional",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event", "key": "$pageview", "time_value": 12, "time_interval": "hour", "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "single_leaf",
+ "expected_window_days": 0.5
+ },
+ {
+ "name": "performed_event_explicit_absolute_range_is_permanent",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event", "key": "$pageview", "explicit_datetime": "2026-01-01", "explicit_datetime_to": "2026-12-31", "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "single_leaf",
+ "expected_window_days": "inf"
+ },
+ {
+ "name": "performed_event_explicit_relative_upper_is_dropped",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event", "key": "$pageview", "explicit_datetime": "2026-01-01", "explicit_datetime_to": "-7d", "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "performed_event_explicit_unparseable_bound_is_dropped",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event", "key": "$pageview", "explicit_datetime": "not-a-date", "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "performed_event_explicit_quarter_unit_is_dropped",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event", "key": "$pageview", "explicit_datetime": "-2q", "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "performed_event_string_time_value_reads_as_zero_window",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event", "key": "$pageview", "time_value": "30", "time_interval": "day", "conditionHash": "0123456789abcdef", "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11]}]}},
+ "expected": "single_leaf",
+ "expected_window_days": 0
+ },
+ {
+ "name": "two_person_leaves_are_composable",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "person", "key": "email", "value": "[email protected]", "conditionHash": "aaaaaaaaaaaaaaaa", "bytecode": ["_H", 1]}, {"type": "person", "key": "plan", "value": "pro", "conditionHash": "bbbbbbbbbbbbbbbb", "bytecode": ["_H", 1]}]}},
+ "expected": "stage2_composable"
+ },
+ {
+ "name": "behavioral_plus_person_is_composable_with_window",
+ "filters": {"properties": {"type": "OR", "values": [{"type": "behavioral", "value": "performed_event", "key": "$pageview", "time_value": 7, "time_interval": "day", "conditionHash": "aaaaaaaaaaaaaaaa", "bytecode": ["_H", 1]}, {"type": "person", "key": "email", "value": "[email protected]", "conditionHash": "bbbbbbbbbbbbbbbb", "bytecode": ["_H", 1]}]}},
+ "expected": "stage2_composable",
+ "expected_window_days": 7
+ },
+ {
+ "name": "empty_group_is_excluded",
+ "filters": {"properties": {"type": "AND", "values": []}},
+ "expected": "excluded_empty_group"
+ },
+ {
+ "name": "nested_empty_group_is_excluded",
+ "filters": {"properties": {"type": "OR", "values": [{"type": "AND", "values": []}, {"type": "person", "key": "email", "value": "[email protected]", "conditionHash": "aaaaaaaaaaaaaaaa", "bytecode": ["_H", 1]}]}},
+ "expected": "excluded_empty_group"
+ },
+ {
+ "name": "single_negated_person_is_top_level_negation",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "person", "key": "email", "value": "[email protected]", "conditionHash": "aaaaaaaaaaaaaaaa", "bytecode": ["_H", 1], "negation": true}]}},
+ "expected": "excluded_top_level_negation"
+ },
+ {
+ "name": "or_with_any_negated_child_is_top_level_negation",
+ "filters": {"properties": {"type": "OR", "values": [{"type": "person", "key": "email", "value": "[email protected]", "conditionHash": "aaaaaaaaaaaaaaaa", "bytecode": ["_H", 1], "negation": true}, {"type": "person", "key": "plan", "value": "pro", "conditionHash": "bbbbbbbbbbbbbbbb", "bytecode": ["_H", 1]}]}},
+ "expected": "excluded_top_level_negation"
+ },
+ {
+ "name": "and_with_one_negated_child_is_composable",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "person", "key": "email", "value": "[email protected]", "conditionHash": "aaaaaaaaaaaaaaaa", "bytecode": ["_H", 1], "negation": true}, {"type": "person", "key": "plan", "value": "pro", "conditionHash": "bbbbbbbbbbbbbbbb", "bytecode": ["_H", 1]}]}},
+ "expected": "stage2_composable"
+ },
+ {
+ "name": "single_not_in_cohort_ref_is_top_level_negation",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "cohort", "key": "id", "value": 99, "operator": "not_in"}]}},
+ "extra_cohorts": {"99": {"properties": {"type": "AND", "values": [{"type": "person", "key": "email", "value": "[email protected]", "conditionHash": "aaaaaaaaaaaaaaaa", "bytecode": ["_H", 1]}]}}},
+ "expected": "excluded_top_level_negation"
+ },
+ {
+ "name": "resolvable_cohort_ref_promotes_under_cascade",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "cohort", "key": "id", "value": 99}]}},
+ "extra_cohorts": {"99": {"properties": {"type": "AND", "values": [{"type": "person", "key": "email", "value": "[email protected]", "conditionHash": "aaaaaaaaaaaaaaaa", "bytecode": ["_H", 1]}]}}},
+ "expected": "stage2_composable_ref"
+ },
+ {
+ "name": "string_cohort_ref_id_promotes_under_cascade",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "cohort", "key": "id", "value": "99"}]}},
+ "extra_cohorts": {"99": {"properties": {"type": "AND", "values": [{"type": "person", "key": "email", "value": "[email protected]", "conditionHash": "aaaaaaaaaaaaaaaa", "bytecode": ["_H", 1]}]}}},
+ "expected": "stage2_composable_ref"
+ },
+ {
+ "name": "cohort_ref_without_cascade_stays_excluded",
+ "cascade_enabled": false,
+ "filters": {"properties": {"type": "AND", "values": [{"type": "cohort", "key": "id", "value": 99}]}},
+ "extra_cohorts": {"99": {"properties": {"type": "AND", "values": [{"type": "person", "key": "email", "value": "[email protected]", "conditionHash": "aaaaaaaaaaaaaaaa", "bytecode": ["_H", 1]}]}}},
+ "expected": "excluded_has_cohort_ref"
+ },
+ {
+ "name": "self_reference_is_cycle",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "cohort", "key": "id", "value": 1}]}},
+ "expected": "excluded_cycle_detected"
+ },
+ {
+ "name": "two_cohort_cycle_is_cycle",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "cohort", "key": "id", "value": 99}]}},
+ "extra_cohorts": {"99": {"properties": {"type": "AND", "values": [{"type": "cohort", "key": "id", "value": 1}]}}},
+ "expected": "excluded_cycle_detected"
+ },
+ {
+ "name": "absent_ref_target_is_unresolved",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "cohort", "key": "id", "value": 424242}]}},
+ "expected": "excluded_unresolved_ref"
+ },
+ {
+ "name": "structurally_excluded_ref_target_is_unresolved",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "cohort", "key": "id", "value": 99}]}},
+ "extra_cohorts": {"99": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event_sequence", "key": "$pageview", "conditionHash": "aaaaaaaaaaaaaaaa", "bytecode": ["_H", 1]}]}}},
+ "expected": "excluded_unresolved_ref"
+ },
+ {
+ "name": "negated_ref_to_absent_target_does_not_block",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "cohort", "key": "id", "value": 424242, "negation": true}, {"type": "person", "key": "email", "value": "[email protected]", "conditionHash": "aaaaaaaaaaaaaaaa", "bytecode": ["_H", 1]}]}},
+ "expected": "stage2_composable_ref"
+ },
+ {
+ "name": "ref_chain_promotes_through_refined_target",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "cohort", "key": "id", "value": 99}]}},
+ "extra_cohorts": {
+ "99": {"properties": {"type": "AND", "values": [{"type": "cohort", "key": "id", "value": 98}]}},
+ "98": {"properties": {"type": "AND", "values": [{"type": "person", "key": "email", "value": "[email protected]", "conditionHash": "aaaaaaaaaaaaaaaa", "bytecode": ["_H", 1]}]}}
+ },
+ "expected": "stage2_composable_ref"
+ },
+ {
+ "name": "dropped_leaf_takes_precedence_over_negation",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "behavioral", "value": "performed_event_sequence", "key": "$pageview", "conditionHash": "aaaaaaaaaaaaaaaa", "bytecode": ["_H", 1]}, {"type": "person", "key": "email", "value": "[email protected]", "conditionHash": "bbbbbbbbbbbbbbbb", "bytecode": ["_H", 1], "negation": true}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "malformed_cohort_ref_is_dropped",
+ "filters": {"properties": {"type": "AND", "values": [{"type": "cohort", "key": "id"}]}},
+ "expected": "excluded_has_dropped_leaf"
+ },
+ {
+ "name": "missing_properties_is_parse_error",
+ "filters": {"groups": []},
+ "expected": "parse_error"
+ },
+ {
+ "name": "null_filters_is_parse_error",
+ "filters": null,
+ "expected": "parse_error"
+ }
+ ]
+}
diff --git a/products/cohorts/backend/parity/test/test_classifier.py b/products/cohorts/backend/parity/test/test_classifier.py
new file mode 100644
index 000000000000..44ce2e8febfe
--- /dev/null
+++ b/products/cohorts/backend/parity/test/test_classifier.py
@@ -0,0 +1,258 @@
+from datetime import UTC, datetime, timedelta
+
+from django.test import SimpleTestCase
+
+from products.cohorts.backend.parity.classifier import (
+ VERDICT_FAIL,
+ VERDICT_PASS,
+ VERDICT_SKIP,
+ VERDICT_WARMUP,
+ ClassifierConfig,
+ classify_cohort,
+ summarize,
+)
+from products.cohorts.backend.parity.eligibility import EXCLUDED_HAS_DROPPED_LEAF, SINGLE_LEAF, ScreenedCohort
+from products.cohorts.backend.parity.fold import MembershipRecord
+
+NOW = datetime(2026, 7, 8, 12, 0, tzinfo=UTC)
+SINCE = NOW - timedelta(days=1)
+LAST_CALC = NOW - timedelta(minutes=30)
+
+
+def _screened(eligibility: str = SINGLE_LEAF, window: float | None = None) -> ScreenedCohort:
+ return ScreenedCohort(cohort_id=1, eligibility=eligibility, max_window_days=window)
+
+
+def _entered(persons: list[str], *, at: datetime) -> dict[str, MembershipRecord]:
+ return {p: MembershipRecord(status="entered", last_updated=at) for p in persons}
+
+
+def _config(**overrides) -> ClassifierConfig:
+ defaults: dict = {"since": SINCE, "now": NOW, "threshold_pct": 0.5, "warmup_sample": 5000}
+ defaults.update(overrides)
+ return ClassifierConfig(**defaults)
+
+
+class TestClassifier(SimpleTestCase):
+ def test_excluded_cohort_is_skipped_not_gated(self) -> None:
+ row = classify_cohort(
+ screened=_screened(EXCLUDED_HAS_DROPPED_LEAF),
+ name="x",
+ old_members={"a", "b"},
+ new_state={},
+ last_realtime_calculation_at=LAST_CALC,
+ config=_config(),
+ )
+ self.assertEqual(row.verdict, VERDICT_SKIP)
+ self.assertFalse(row.gated)
+
+ def test_fresh_rule_explains_new_entries_after_last_recompute(self) -> None:
+ new_state = _entered(["a", "b"], at=NOW - timedelta(minutes=45)) | _entered(
+ ["c"], at=NOW - timedelta(minutes=5)
+ )
+ row = classify_cohort(
+ screened=_screened(),
+ name="x",
+ old_members={"a", "b"},
+ new_state=new_state,
+ last_realtime_calculation_at=LAST_CALC,
+ config=_config(activity_probe=lambda persons, cutoff: set(persons)),
+ )
+ self.assertEqual(row.only_new, 1)
+ self.assertEqual(row.fresh, 1)
+ self.assertEqual(row.residual_new, 0)
+ self.assertEqual(row.verdict, VERDICT_PASS)
+
+ def test_never_recomputed_cohort_counts_all_only_new_as_fresh(self) -> None:
+ row = classify_cohort(
+ screened=_screened(),
+ name="x",
+ old_members=set(),
+ new_state=_entered(["a", "b"], at=NOW - timedelta(hours=2)),
+ last_realtime_calculation_at=None,
+ config=_config(),
+ )
+ self.assertEqual(row.fresh, 2)
+ self.assertEqual(row.verdict, VERDICT_PASS)
+
+ def test_cohort_level_warmup_when_window_exceeds_pipeline_age(self) -> None:
+ probe_calls: list[list[str]] = []
+
+ def probe(persons, cutoff):
+ probe_calls.append(list(persons))
+ return set()
+
+ row = classify_cohort(
+ screened=_screened(window=30),
+ name="x",
+ old_members={"a", "b", "c"},
+ new_state={},
+ last_realtime_calculation_at=LAST_CALC,
+ config=_config(activity_probe=probe),
+ )
+ self.assertEqual(row.verdict, VERDICT_WARMUP)
+ self.assertEqual(row.warmup, 3)
+ self.assertEqual(row.residual_old, 0)
+ self.assertEqual(probe_calls, [])
+ self.assertFalse(row.gated)
+
+ def test_warming_cohort_still_gates_on_unexplained_only_new(self) -> None:
+ stale_over_inclusion = classify_cohort(
+ screened=_screened(window=30),
+ name="x",
+ old_members={"a"},
+ new_state=_entered(["a"], at=NOW) | _entered(["b"], at=LAST_CALC - timedelta(minutes=5)),
+ last_realtime_calculation_at=LAST_CALC,
+ config=_config(),
+ )
+ self.assertEqual(stale_over_inclusion.residual_new, 1)
+ self.assertEqual(stale_over_inclusion.verdict, VERDICT_FAIL)
+
+ fresh_only = classify_cohort(
+ screened=_screened(window=30),
+ name="x",
+ old_members={"a"},
+ new_state=_entered(["a"], at=NOW) | _entered(["b"], at=NOW),
+ last_realtime_calculation_at=LAST_CALC,
+ config=_config(),
+ )
+ self.assertEqual(fresh_only.residual_new, 0)
+ self.assertEqual(fresh_only.verdict, VERDICT_WARMUP)
+
+ def test_person_level_warmup_explains_inactive_only_old(self) -> None:
+ seen_cutoffs: list[datetime] = []
+
+ def probe(persons, cutoff):
+ seen_cutoffs.append(cutoff)
+ return {"active"}
+
+ row = classify_cohort(
+ screened=_screened(window=None),
+ name="x",
+ old_members={"active", "dormant1", "dormant2"},
+ new_state={},
+ last_realtime_calculation_at=LAST_CALC,
+ config=_config(activity_probe=probe),
+ )
+ self.assertEqual(row.warmup, 2)
+ self.assertEqual(row.residual_old, 1)
+ self.assertEqual(seen_cutoffs, [SINCE])
+ self.assertEqual(row.verdict, VERDICT_FAIL)
+
+ def test_behavioral_window_narrows_the_warmup_cutoff(self) -> None:
+ seen_cutoffs: list[datetime] = []
+
+ def probe(persons, cutoff):
+ seen_cutoffs.append(cutoff)
+ return set(persons)
+
+ classify_cohort(
+ screened=_screened(window=0.25),
+ name="x",
+ old_members={"a"},
+ new_state={},
+ last_realtime_calculation_at=LAST_CALC,
+ config=_config(activity_probe=probe),
+ )
+ self.assertEqual(seen_cutoffs, [NOW - timedelta(days=0.25)])
+
+ def test_warmup_sample_zero_degrades_to_cohort_level_only(self) -> None:
+ row = classify_cohort(
+ screened=_screened(window=None),
+ name="x",
+ old_members={"a", "b"},
+ new_state={},
+ last_realtime_calculation_at=LAST_CALC,
+ config=_config(warmup_sample=0, activity_probe=lambda p, c: set()),
+ )
+ self.assertEqual(row.warmup, 0)
+ self.assertEqual(row.residual_old, 2)
+ self.assertEqual(row.verdict, VERDICT_FAIL)
+
+ def test_warmup_extrapolates_from_sample(self) -> None:
+ row = classify_cohort(
+ screened=_screened(window=None),
+ name="x",
+ old_members={"a", "b", "c", "d"},
+ new_state={},
+ last_realtime_calculation_at=LAST_CALC,
+ config=_config(warmup_sample=2, activity_probe=lambda persons, cutoff: {"a"}),
+ )
+ self.assertEqual(row.warmup, 2)
+ self.assertEqual(row.residual_old, 2)
+ self.assertIn("warmup extrapolated from sample 2/4", row.notes)
+
+ def test_residual_gate_threshold(self) -> None:
+ old_members = {f"p{i}" for i in range(99)}
+ last_calc = NOW - timedelta(minutes=1)
+ config = _config(threshold_pct=1.0, activity_probe=lambda p, c: set(p))
+
+ row = classify_cohort(
+ screened=_screened(),
+ name="x",
+ old_members=old_members,
+ new_state=_entered([f"p{i}" for i in range(99)], at=NOW - timedelta(hours=2)) | _entered(["q"], at=NOW),
+ last_realtime_calculation_at=last_calc,
+ config=config,
+ )
+ self.assertEqual(row.residual_new, 0)
+ self.assertEqual(row.fresh, 1)
+ self.assertEqual(row.verdict, VERDICT_PASS)
+
+ stale = classify_cohort(
+ screened=_screened(),
+ name="x",
+ old_members=old_members,
+ new_state=_entered([f"p{i}" for i in range(97)], at=NOW - timedelta(hours=2)),
+ last_realtime_calculation_at=last_calc,
+ config=config,
+ )
+ self.assertGreater(stale.residual_pct, 1.0)
+ self.assertEqual(stale.verdict, VERDICT_FAIL)
+
+ def test_no_classify_gates_on_raw_diff(self) -> None:
+ row = classify_cohort(
+ screened=_screened(window=30),
+ name="x",
+ old_members={"a"},
+ new_state=_entered(["b"], at=NOW),
+ last_realtime_calculation_at=None,
+ config=_config(classify=False),
+ )
+ self.assertEqual(row.fresh, 0)
+ self.assertEqual(row.warmup, 0)
+ self.assertEqual(row.residual_pct, row.raw_diff_pct)
+ self.assertEqual(row.verdict, VERDICT_FAIL)
+
+ def test_summarize_counts_verdicts_and_buckets(self) -> None:
+ config = _config()
+ rows = [
+ classify_cohort(
+ screened=_screened(window=30),
+ name="warm",
+ old_members={"a"},
+ new_state={},
+ last_realtime_calculation_at=LAST_CALC,
+ config=config,
+ ),
+ classify_cohort(
+ screened=_screened(EXCLUDED_HAS_DROPPED_LEAF),
+ name="skip",
+ old_members=set(),
+ new_state={},
+ last_realtime_calculation_at=LAST_CALC,
+ config=config,
+ ),
+ classify_cohort(
+ screened=_screened(),
+ name="pass",
+ old_members={"a"},
+ new_state=_entered(["a"], at=NOW),
+ last_realtime_calculation_at=LAST_CALC,
+ config=config,
+ ),
+ ]
+ summary = summarize(rows, config=config)
+ self.assertEqual((summary.passed, summary.failed, summary.warming_up, summary.skipped), (1, 0, 1, 1))
+ self.assertEqual(summary.warmup_total, 1)
+ self.assertEqual(summary.raw_diff_total, 1)
diff --git a/products/cohorts/backend/parity/test/test_command_warnings.py b/products/cohorts/backend/parity/test/test_command_warnings.py
new file mode 100644
index 000000000000..eaaf2555dc40
--- /dev/null
+++ b/products/cohorts/backend/parity/test/test_command_warnings.py
@@ -0,0 +1,49 @@
+from datetime import UTC, datetime, timedelta
+
+from django.test import SimpleTestCase
+
+from products.cohorts.backend.management.commands.compare_cohort_membership import _collect_warnings
+from products.cohorts.backend.parity.kafka_io import DrainStats
+
+NOW = datetime(2026, 7, 8, 12, 0, tzinfo=UTC)
+SINCE = NOW - timedelta(days=1)
+
+
+def _complete_drain(**overrides) -> DrainStats:
+ stats = DrainStats(partitions=4, partitions_read=4, consumed=10, reached_end=True)
+ for key, value in overrides.items():
+ setattr(stats, key, value)
+ return stats
+
+
+class TestCollectWarnings(SimpleTestCase):
+ def test_clean_complete_drain_yields_no_warnings(self) -> None:
+ warnings, infos = _collect_warnings(_complete_drain(earliest_retained=SINCE), set(), SINCE, NOW)
+ self.assertEqual(warnings, [])
+ self.assertEqual(len(infos), 1)
+ self.assertIn("earliest retained", infos[0])
+
+ def test_clipped_partitions_warn_instead_of_info(self) -> None:
+ stats = _complete_drain(earliest_retained=NOW - timedelta(hours=1), maybe_clipped_partitions=[3, 1])
+ warnings, infos = _collect_warnings(stats, set(), SINCE, NOW)
+ self.assertEqual(infos, [])
+ self.assertEqual(len(warnings), 1)
+ self.assertIn("[1, 3]", warnings[0])
+ self.assertIn("incomplete", warnings[0])
+
+ def test_partial_drain_warns(self) -> None:
+ warnings, _infos = _collect_warnings(_complete_drain(reached_end=False), set(), SINCE, NOW)
+ self.assertTrue(any("fold is partial" in w for w in warnings))
+
+ def test_retention_deadline_warns_within_a_day(self) -> None:
+ old_since = NOW - timedelta(days=6, hours=1)
+ warnings, _infos = _collect_warnings(_complete_drain(), set(), old_since, NOW)
+ self.assertTrue(any("completeness expires" in w for w in warnings))
+
+ fresh_since = NOW - timedelta(days=1)
+ warnings, _infos = _collect_warnings(_complete_drain(), set(), fresh_since, NOW)
+ self.assertFalse(any("completeness expires" in w for w in warnings))
+
+ def test_unknown_cohorts_warn(self) -> None:
+ warnings, _infos = _collect_warnings(_complete_drain(), {42, 7}, SINCE, NOW)
+ self.assertTrue(any("absent from the realtime universe" in w and "[7, 42]" in w for w in warnings))
diff --git a/products/cohorts/backend/parity/test/test_eligibility.py b/products/cohorts/backend/parity/test/test_eligibility.py
new file mode 100644
index 000000000000..2b07a5cbf73d
--- /dev/null
+++ b/products/cohorts/backend/parity/test/test_eligibility.py
@@ -0,0 +1,55 @@
+import json
+import math
+from pathlib import Path
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.cohorts.backend.parity.eligibility import screen_team
+
+_FIXTURE = Path(__file__).parent / "fixtures" / "eligibility_golden.json"
+_CASES = json.loads(_FIXTURE.read_text())["cases"]
+
+
+class TestEligibilityGoldenVectors(SimpleTestCase):
+ def test_long_acyclic_ref_chain_does_not_hit_recursion_limit(self) -> None:
+ chain_length = 2000 # comfortably past Python's default recursion limit
+ cohorts: dict[int, dict] = {
+ cid: {"properties": {"type": "AND", "values": [{"type": "cohort", "key": "id", "value": cid + 1}]}}
+ for cid in range(1, chain_length)
+ }
+ cohorts[chain_length] = {
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "person",
+ "key": "email",
+ "value": "[email protected]",
+ "conditionHash": "aaaaaaaaaaaaaaaa",
+ "bytecode": ["_H", 1],
+ }
+ ],
+ }
+ }
+ screened = screen_team(cohorts, cascade_enabled=True)
+ self.assertEqual(screened[1].eligibility, "stage2_composable_ref")
+ self.assertEqual(screened[chain_length].eligibility, "single_leaf")
+
+ @parameterized.expand([(case["name"], case) for case in _CASES])
+ def test_golden_vector(self, _name: str, case: dict) -> None:
+ cohorts = {1: case["filters"]}
+ for cid, filters in case.get("extra_cohorts", {}).items():
+ cohorts[int(cid)] = filters
+ screened = screen_team(cohorts, cascade_enabled=case.get("cascade_enabled", True))
+
+ self.assertEqual(screened[1].eligibility, case["expected"])
+ if "expected_window_days" in case:
+ expected = case["expected_window_days"]
+ if expected == "inf":
+ self.assertEqual(screened[1].max_window_days, math.inf)
+ elif expected is None:
+ self.assertIsNone(screened[1].max_window_days)
+ else:
+ self.assertEqual(screened[1].max_window_days, expected)
diff --git a/products/cohorts/backend/parity/test/test_fold.py b/products/cohorts/backend/parity/test/test_fold.py
new file mode 100644
index 000000000000..b6558a9f93e4
--- /dev/null
+++ b/products/cohorts/backend/parity/test/test_fold.py
@@ -0,0 +1,103 @@
+from datetime import UTC, datetime
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.cohorts.backend.parity.fold import fold_membership_changes, members, parse_last_updated
+
+SINCE = datetime(2026, 7, 7, 19, 0, tzinfo=UTC)
+
+
+def _msg(status: str, ts: str, *, cohort_id: int | None = 10, person_id: str = "P1", team_id: int = 2) -> dict:
+ return {
+ "team_id": team_id,
+ "cohort_id": cohort_id,
+ "person_id": person_id,
+ "last_updated": ts,
+ "status": status,
+ }
+
+
+class TestFold(SimpleTestCase):
+ def test_last_message_wins_per_pair(self) -> None:
+ state, stats = fold_membership_changes(
+ [
+ _msg("entered", "2026-07-07 19:01:00.000001"),
+ _msg("left", "2026-07-07 19:02:00.000001"),
+ _msg("entered", "2026-07-07 19:03:00.000001"),
+ _msg("entered", "2026-07-07 19:01:00.000001", person_id="P2"),
+ _msg("left", "2026-07-07 19:02:00.000001", person_id="P2"),
+ ],
+ team_id=2,
+ since=SINCE,
+ )
+ self.assertEqual(members(state[10]), {"p1"})
+ self.assertEqual(stats.folded, 5)
+ self.assertEqual(stats.cohorts_seen, {10})
+
+ def test_out_of_order_older_record_does_not_shadow_newer(self) -> None:
+ state, _stats = fold_membership_changes(
+ [
+ _msg("entered", "2026-07-07 19:03:00.000001"),
+ _msg("left", "2026-07-07 19:02:00.000001"),
+ ],
+ team_id=2,
+ since=SINCE,
+ )
+ self.assertEqual(members(state[10]), {"p1"})
+
+ def test_since_cutoff_drops_pre_wipe_messages(self) -> None:
+ state, stats = fold_membership_changes(
+ [
+ _msg("entered", "2026-07-07 18:59:59.999999"),
+ _msg("entered", "2026-07-07 19:00:00.000000", person_id="P2"),
+ ],
+ team_id=2,
+ since=SINCE,
+ )
+ self.assertEqual(members(state[10]), {"p2"})
+ self.assertEqual(stats.dropped_before_since, 1)
+
+ def test_wrong_team_messages_are_dropped(self) -> None:
+ state, stats = fold_membership_changes(
+ [
+ _msg("entered", "2026-07-07 19:01:00.000001", team_id=99999),
+ _msg("entered", "2026-07-07 19:01:00.000001", person_id="P2"),
+ ],
+ team_id=2,
+ since=SINCE,
+ )
+ self.assertEqual(members(state[10]), {"p2"})
+ self.assertEqual(stats.dropped_wrong_team, 1)
+
+ @parameterized.expand(
+ [
+ ("rust_microseconds", "2026-07-07 19:01:00.123456"),
+ ("python_microseconds", "2026-07-07 19:01:00.000042"),
+ ("short_fraction", "2026-07-07 19:01:00.5"),
+ ("no_fraction", "2026-07-07 19:01:00"),
+ ]
+ )
+ def test_last_updated_renderings_parse_as_utc(self, _name: str, raw: str) -> None:
+ parsed = parse_last_updated(raw)
+ assert parsed is not None
+ self.assertEqual(parsed.tzinfo, UTC)
+ self.assertEqual(parsed.replace(microsecond=0), datetime(2026, 7, 7, 19, 1, 0, tzinfo=UTC))
+
+ @parameterized.expand(
+ [
+ (
+ "missing_person",
+ {"team_id": 2, "cohort_id": 10, "status": "entered", "last_updated": "2026-07-07 19:01:00"},
+ ),
+ ("bad_status", _msg("member", "2026-07-07 19:01:00.000001")),
+ ("bad_timestamp", _msg("entered", "07/07/2026")),
+ ("non_int_cohort", _msg("entered", "2026-07-07 19:01:00.000001", cohort_id=None)),
+ ]
+ )
+ def test_malformed_rows_are_skipped_and_counted(self, _name: str, message: dict) -> None:
+ state, stats = fold_membership_changes([message], team_id=2, since=SINCE)
+ self.assertEqual(state, {})
+ self.assertEqual(stats.dropped_malformed, 1)
+ self.assertEqual(stats.folded, 0)
diff --git a/products/cohorts/backend/parity/test/test_kafka_io.py b/products/cohorts/backend/parity/test/test_kafka_io.py
new file mode 100644
index 000000000000..80d17d1e399f
--- /dev/null
+++ b/products/cohorts/backend/parity/test/test_kafka_io.py
@@ -0,0 +1,132 @@
+from datetime import UTC, datetime
+
+from unittest import mock
+
+from django.test import SimpleTestCase
+
+from confluent_kafka import TopicPartition
+
+from products.cohorts.backend.parity.kafka_io import DrainStats, drain_topic
+
+SINCE = datetime(2026, 7, 7, 19, 0, tzinfo=UTC)
+TOPIC = "shadow-test"
+
+
+class _FakeMessage:
+ def __init__(self, partition: int, offset: int, ts: datetime, payload: bytes = b'{"n": 1}'):
+ self._partition = partition
+ self._offset = offset
+ self._ts_ms = int(ts.timestamp() * 1000)
+ self._payload = payload
+
+ def error(self):
+ return None
+
+ def partition(self) -> int:
+ return self._partition
+
+ def offset(self) -> int:
+ return self._offset
+
+ def timestamp(self) -> tuple[int, int]:
+ return (1, self._ts_ms)
+
+ def value(self) -> bytes:
+ return self._payload
+
+
+class _FakeConsumer:
+ def __init__(self, *, watermarks: dict[int, tuple[int, int]], starts: dict[int, int], polls: list[_FakeMessage]):
+ self._watermarks = watermarks
+ self._starts = starts
+ self._polls = list(polls)
+ self.assigned: list[TopicPartition] = []
+ self.closed = False
+
+ def list_topics(self, topic: str, timeout: float):
+ topic_meta = mock.Mock(error=None, partitions=dict.fromkeys(self._watermarks))
+ return mock.Mock(topics={topic: topic_meta})
+
+ def get_watermark_offsets(self, tp: TopicPartition, timeout: float) -> tuple[int, int]:
+ return self._watermarks[tp.partition]
+
+ def offsets_for_times(self, tps: list[TopicPartition], timeout: float) -> list[TopicPartition]:
+ return [TopicPartition(tp.topic, tp.partition, self._starts[tp.partition]) for tp in tps]
+
+ def assign(self, assignment: list[TopicPartition]) -> None:
+ self.assigned = assignment
+
+ def poll(self, timeout: float):
+ return self._polls.pop(0) if self._polls else None
+
+ def close(self) -> None:
+ self.closed = True
+
+
+def _drain(consumer: _FakeConsumer, stats: DrainStats) -> list[dict]:
+ with mock.patch("products.cohorts.backend.parity.kafka_io.Consumer", return_value=consumer):
+ return list(drain_topic(TOPIC, config={}, since=SINCE, stats=stats))
+
+
+class TestDrainTopic(SimpleTestCase):
+ def test_fast_partition_stops_at_its_high_watermark_snapshot(self) -> None:
+ ts = datetime(2026, 7, 7, 20, 0, tzinfo=UTC)
+ consumer = _FakeConsumer(
+ watermarks={0: (0, 1), 1: (0, 2)},
+ starts={0: 0, 1: 0},
+ polls=[
+ _FakeMessage(0, 0, ts, b'{"p": "0-0"}'),
+ # Produced after the snapshot on the already-finished partition 0: a
+ # still-producing topic keeps returning these while partition 1 drains.
+ _FakeMessage(0, 1, ts, b'{"p": "0-1-post-snapshot"}'),
+ _FakeMessage(1, 0, ts, b'{"p": "1-0"}'),
+ _FakeMessage(1, 1, ts, b'{"p": "1-1"}'),
+ ],
+ )
+ stats = DrainStats()
+ drained = _drain(consumer, stats)
+ self.assertEqual([m["p"] for m in drained], ["0-0", "1-0", "1-1"])
+ self.assertEqual(stats.consumed, 3)
+ self.assertTrue(stats.reached_end)
+ self.assertTrue(consumer.closed)
+
+ def test_clipped_partition_sets_warning_stats(self) -> None:
+ first_retained_ts = datetime(2026, 7, 7, 21, 0, tzinfo=UTC)
+ consumer = _FakeConsumer(
+ # low > 0: retention already deleted offsets, and the drain starts at low.
+ watermarks={0: (5, 7)},
+ starts={0: 5},
+ polls=[_FakeMessage(0, 5, first_retained_ts), _FakeMessage(0, 6, first_retained_ts)],
+ )
+ stats = DrainStats()
+ drained = _drain(consumer, stats)
+ self.assertEqual(len(drained), 2)
+ self.assertEqual(stats.earliest_retained, first_retained_ts)
+ self.assertEqual(stats.maybe_clipped_partitions, [0])
+ self.assertTrue(stats.reached_end)
+
+ def test_empty_and_post_since_partitions_are_skipped(self) -> None:
+ consumer = _FakeConsumer(
+ # Partition 0 is empty; partition 1 has data but nothing at/after --since
+ # (offsets_for_times returns -1).
+ watermarks={0: (0, 0), 1: (0, 3)},
+ starts={1: -1},
+ polls=[],
+ )
+ stats = DrainStats()
+ drained = _drain(consumer, stats)
+ self.assertEqual(drained, [])
+ self.assertEqual(stats.partitions, 2)
+ self.assertEqual(stats.partitions_read, 0)
+ self.assertTrue(stats.reached_end)
+
+ def test_poll_timeout_leaves_reached_end_unset(self) -> None:
+ consumer = _FakeConsumer(
+ watermarks={0: (0, 2)},
+ starts={0: 0},
+ polls=[_FakeMessage(0, 0, datetime(2026, 7, 7, 20, 0, tzinfo=UTC))],
+ )
+ stats = DrainStats()
+ drained = _drain(consumer, stats)
+ self.assertEqual(len(drained), 1)
+ self.assertFalse(stats.reached_end)
diff --git a/products/cohorts/backend/parity/test/test_report.py b/products/cohorts/backend/parity/test/test_report.py
new file mode 100644
index 000000000000..7546d46019eb
--- /dev/null
+++ b/products/cohorts/backend/parity/test/test_report.py
@@ -0,0 +1,34 @@
+from django.test import SimpleTestCase
+
+from products.cohorts.backend.parity.classifier import (
+ VERDICT_FAIL,
+ VERDICT_PASS,
+ VERDICT_SKIP,
+ VERDICT_WARMUP,
+ AggregateSummary,
+ CohortComparison,
+)
+from products.cohorts.backend.parity.report import to_json
+
+
+def _row(cohort_id: int, verdict: str, residual_pct: float = 0.0) -> CohortComparison:
+ return CohortComparison(
+ cohort_id=cohort_id, name=f"c{cohort_id}", eligibility="single_leaf", verdict=verdict, residual_pct=residual_pct
+ )
+
+
+class TestReport(SimpleTestCase):
+ def test_json_rows_order_failures_first(self) -> None:
+ rows = [
+ _row(1, VERDICT_SKIP),
+ _row(2, VERDICT_PASS),
+ _row(3, VERDICT_FAIL, residual_pct=1.0),
+ _row(4, VERDICT_WARMUP),
+ _row(5, VERDICT_FAIL, residual_pct=9.0),
+ ]
+ document = to_json(rows, AggregateSummary(), {"team_id": 2})
+ self.assertEqual(
+ [(r["cohort_id"], r["verdict"]) for r in document["cohorts"]],
+ [(5, VERDICT_FAIL), (3, VERDICT_FAIL), (4, VERDICT_WARMUP), (2, VERDICT_PASS), (1, VERDICT_SKIP)],
+ )
+ self.assertEqual(document["meta"], {"team_id": 2})