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.

fix(cohorts): bound parity testing harness (#69816)

Matheus Batistac9238001eed4
diff --git a/products/cohorts/backend/management/commands/compare_cohort_membership.py b/products/cohorts/backend/management/commands/compare_cohort_membership.py
index 65a1b448cd45..abaf33abec0d 100644
--- a/products/cohorts/backend/management/commands/compare_cohort_membership.py
+++ b/products/cohorts/backend/management/commands/compare_cohort_membership.py
@@ -1,9 +1,12 @@
"""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.
+(cohort, person) vs the argMax of ClickHouse cohort_membership. The diff is bounded to
+the observed universe O = persons the new pipeline decided on since the store wipe;
+never-computed persons (old - O) are excluded from the gate and instead feed a separate
+missed-emission probe. Divergences are classified (R-EXCLUDE / R-FRESH / R-STALE /
+suspect-missing / dormant) so expected skew is separated from real bugs. Exits non-zero
+if any eligible cohort FAILs the residual gate or the (sound-window) suspect-missing gate.
Run from a toolbox/web pod (needs KAFKA_INGESTION_HOSTS + the offline ClickHouse host):
@@ -30,7 +33,9 @@ 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",
+ "the diff is bounded to persons the new pipeline decided on (O); old-only persons outside O are excluded and only probed for missed emissions",
+ "suspect_missing gates FAIL only where the store provably covers the window (window <= pipeline age, or property-only cohorts); on longer windows unobserved actives are unresolvable until warmup (no snapshot resolves pre-since qualifiers) and report as WARMUP",
+ "minute/hour-window cohorts get suspect≈0 by construction — the probe cutoff collapses to now",
"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",
)
@@ -99,9 +104,13 @@ class Command(BaseCommand):
"--warmup-sample",
type=int,
default=5000,
- help="Persons sampled per cohort for the R-WARMUP event check; 0 skips it (cohort-level warmup only)",
+ help="Persons sampled per cohort for the missed-emission (suspect) probe over old - O; 0 skips it",
+ )
+ parser.add_argument(
+ "--no-classify",
+ action="store_true",
+ help="O-bounded raw diff only, no R-FRESH/R-STALE rules or suspect probe",
)
- 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")
@@ -224,4 +233,6 @@ class Command(BaseCommand):
self.stdout.write(f" {caveat}")
if summary.failed:
- raise CommandError(f"{summary.failed} eligible cohort(s) FAIL the {options['threshold']}% residual gate")
+ raise CommandError(
+ f"{summary.failed} eligible cohort(s) FAIL the {options['threshold']}% parity gate (residual or suspect-missing)"
+ )
diff --git a/products/cohorts/backend/parity/classifier.py b/products/cohorts/backend/parity/classifier.py
index c9cb270ef48b..b5d232e7ae5c 100644
--- a/products/cohorts/backend/parity/classifier.py
+++ b/products/cohorts/backend/parity/classifier.py
@@ -1,12 +1,31 @@
-"""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.
+"""Per-cohort divergence classification: O-bounded diff + missed-emission signal.
+
+The membership diff is bounded to the observed universe O = persons the new pipeline
+emitted a decision for since the store wipe (fold.py:observed). Within O both pipelines
+have weighed in, so the diff is sound; each rule explains (removes) part of it and the
+remainder is the gated residual:
+
+- R-EXCLUDE: persons in `old - O` are excluded from the diff entirely (the new pipeline
+ never evaluated them — flip-only emission means a never-member emits nothing).
+- R-FRESH: `only_new` entries whose flip is newer than the old side's last recompute —
+ the old pipeline simply hasn't caught up yet (expected, not over-inclusion).
+- R-STALE: the mirror on `only_old` — the new pipeline already flipped a person to
+ `left` but the old side hasn't recomputed past that eviction, so it still says entered.
+
+R-EXCLUDE hides real under-inclusion bugs (a processor that emits nothing would pass an
+O-bounded gate), so a separate *missed-emission* signal probes `old - O` for recent
+activity: `suspect_missing` persons (active since the discovery cutoff yet undecided by
+the new pipeline) gate FAIL where the store provably covers the window, and are reported
+(WARMUP, not gated) where the window predates the pipeline. The inactive remainder is
+`dormant` (expected).
+
+Pure — the sampled event-activity probe is injected as a callable so tests need no
+ClickHouse.
"""
from __future__ import annotations
+import math
import heapq
from collections.abc import Callable, Sequence
from dataclasses import dataclass, field
@@ -14,16 +33,16 @@ 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
+from products.cohorts.backend.parity.fold import MembershipRecord, members, observed
VERDICT_PASS = "PASS"
VERDICT_FAIL = "FAIL"
VERDICT_SKIP = "SKIP"
-VERDICT_WARMUP = "WARMUP" # reported, not gated: window exceeds pipeline age
+VERDICT_WARMUP = "WARMUP" # reported, not gated: unobserved actives on a window > 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.
+# Persons (a sample of them) that had any event at/after the cutoff — the missed-emission
+# probe over `old - O`: a person with no post-cutoff event was never (re)evaluated by the
+# stream processor, so their absence on the new side is expected (dormant), not a bug.
ActivityProbe = Callable[[Sequence[str], datetime], set[str]]
@@ -32,17 +51,22 @@ class CohortComparison:
cohort_id: int
name: str
eligibility: str
- old_count: int = 0
- new_count: int = 0
+ old_count: int = 0 # full converged old snapshot (superset of the observed universe)
+ observed: int = 0 # |O| — persons the new pipeline decided on
+ new_count: int = 0 # entered set within O
both: int = 0
- only_old: int = 0
+ only_old: int = 0 # (old ∩ O) - new_members
only_new: int = 0
- raw_diff_pct: float = 0.0
+ raw_diff_pct: float = 0.0 # over the observed union
fresh: int = 0
- warmup: int = 0
+ stale: int = 0
residual_old: int = 0
residual_new: int = 0
residual_pct: float = 0.0
+ unobserved: int = 0 # old - O, excluded from the diff, split by the probe below
+ suspect_missing: int = 0 # unobserved but recently active — likely under-inclusion
+ dormant: int = 0 # unobserved and inactive — expected
+ suspect_pct: float = 0.0
verdict: str = VERDICT_SKIP
notes: tuple[str, ...] = ()
@@ -57,7 +81,7 @@ class ClassifierConfig:
now: datetime
threshold_pct: float = 0.5
warmup_sample: int = 5000
- classify: bool = True # False → raw diff only (--no-classify)
+ classify: bool = True # False → O-bounded raw diff only (--no-classify)
activity_probe: Optional[ActivityProbe] = None
@property
@@ -69,6 +93,20 @@ def _pct(part: int, whole: int) -> float:
return part / whole * 100.0 if whole else 0.0
+def _probe_cutoff(window: Optional[float], since: datetime, now: datetime) -> datetime:
+ """`since` if no window, else `max(since, now - window)`.
+
+ A window reaching at/before `since` (including inf and huge finite windows that would
+ overflow `timedelta`) clamps to `since` — the earliest a qualifying event can be.
+ """
+ if window is None:
+ return since
+ pipeline_age_days = (now - since).total_seconds() / 86_400
+ if math.isinf(window) or window >= pipeline_age_days:
+ return since
+ return now - timedelta(days=window)
+
+
def classify_cohort(
*,
screened: ScreenedCohort,
@@ -87,72 +125,85 @@ def classify_cohort(
notes=("not emit-eligible: " + ", ".join(screened.drop_reasons or (screened.eligibility,)),),
)
+ obs = observed(new_state)
new_members = members(new_state)
both = old_members & new_members
- only_old = old_members - new_members
+ only_old = (old_members & obs) - new_members # both weighed in; new landed `left`
only_new = new_members - old_members
+ unobserved = old_members - obs # excluded from the diff (R-EXCLUDE)
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
+ stale = 0
+ suspect_missing = 0
if config.classify:
- # R-FRESH: new-side entries the old pipeline hasn't recomputed past yet.
+ # R-FRESH / R-STALE: entries whose flip is newer than the old side's last recompute.
if last_realtime_calculation_at is None:
fresh = len(only_new)
+ # stale stays 0: a never-recomputed old side has no entered rows to be stale.
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)
+ stale = sum(1 for p in only_old 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)
+ if unobserved and config.warmup_sample > 0 and config.activity_probe is not None:
+ # Missed-emission probe: `old - O` persons active since the discovery cutoff were
+ # evaluable by the stream but never emitted — likely under-inclusion. Sampled,
+ # extrapolated. The inactive remainder is dormant (expected R-EXCLUDE skew).
+ cutoff = _probe_cutoff(window, config.since, config.now)
+ sample = heapq.nsmallest(config.warmup_sample, unobserved)
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)
+ sample_suspect = sum(1 for p in sample if p in active)
+ suspect_missing = round(sample_suspect / len(sample) * len(unobserved))
+ if len(sample) < len(unobserved):
+ notes.append(f"suspect_missing extrapolated from sample {len(sample)}/{len(unobserved)}")
+ if window == 0:
+ notes.append("minute/hour window: probe cutoff is now, suspect≈0 by construction")
+ elif unobserved and config.warmup_sample <= 0:
+ notes.append("suspect check skipped (--warmup-sample 0); unobserved population unprobed")
+
+ residual_old = max(len(only_old) - stale, 0)
residual_new = max(len(only_new) - fresh, 0)
residual_pct = _pct(residual_old + residual_new, union_size)
+ dormant = max(len(unobserved) - suspect_missing, 0)
+ # Silent-miss share of the whole membership (full union, not O-bounded).
+ suspect_pct = _pct(suspect_missing, len(old_members) + len(only_new))
- # 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:
+ # The store provably covers the behavioral window (or there is none), so an unobserved
+ # active is a real miss, not a pre-`since` qualifier the snapshot cannot resolve.
+ sound = screened.max_window_days is None or screened.max_window_days <= config.pipeline_age_days
+
+ if residual_pct > config.threshold_pct:
verdict = VERDICT_FAIL
+ elif suspect_pct > config.threshold_pct:
+ verdict = VERDICT_FAIL if sound else VERDICT_WARMUP
+ else:
+ verdict = VERDICT_PASS
return CohortComparison(
cohort_id=screened.cohort_id,
name=name,
eligibility=screened.eligibility,
old_count=len(old_members),
+ observed=len(obs),
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,
+ stale=stale,
residual_old=residual_old,
residual_new=residual_new,
residual_pct=residual_pct,
+ unobserved=len(unobserved),
+ suspect_missing=suspect_missing,
+ dormant=dormant,
+ suspect_pct=suspect_pct,
verdict=verdict,
notes=tuple(notes),
)
@@ -165,7 +216,9 @@ class AggregateSummary:
skipped: int = 0
warming_up: int = 0
fresh_total: int = 0
- warmup_total: int = 0
+ stale_total: int = 0
+ suspect_total: int = 0
+ dormant_total: int = 0
residual_total: int = 0
raw_diff_total: int = 0
pipeline_age_days: float = 0.0
@@ -184,7 +237,9 @@ def summarize(rows: Sequence[CohortComparison], *, config: ClassifierConfig) ->
else:
summary.skipped += 1
summary.fresh_total += row.fresh
- summary.warmup_total += row.warmup
+ summary.stale_total += row.stale
+ summary.suspect_total += row.suspect_missing
+ summary.dormant_total += row.dormant
summary.residual_total += row.residual_old + row.residual_new
- summary.raw_diff_total += row.only_old + row.only_new
+ summary.raw_diff_total += row.only_old + row.only_new + row.unobserved
return summary
diff --git a/products/cohorts/backend/parity/eligibility.py b/products/cohorts/backend/parity/eligibility.py
index a20428979957..39af9e119355 100644
--- a/products/cohorts/backend/parity/eligibility.py
+++ b/products/cohorts/backend/parity/eligibility.py
@@ -2,7 +2,8 @@
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).
+excluded_*), plus the max behavioral window in days (used by the classifier's soundness
+check and missed-emission probe cutoff).
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
@@ -114,7 +115,7 @@ def _is_absolute_datetime(raw: str) -> bool:
# 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").
+# window length in days for the soundness check (fractional for "seconds", inf for "explicit").
@dataclass(frozen=True)
class _Window:
kind: str
diff --git a/products/cohorts/backend/parity/fold.py b/products/cohorts/backend/parity/fold.py
index 27e31abca62a..5cc53cf5c500 100644
--- a/products/cohorts/backend/parity/fold.py
+++ b/products/cohorts/backend/parity/fold.py
@@ -94,3 +94,13 @@ def fold_membership_changes(
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"}
+
+
+def observed(state: dict[str, MembershipRecord]) -> set[str]:
+ """Every person the new pipeline emitted a decision for in this cohort.
+
+ Emission is flip-only (see the Rust processor's stage1/transition + stage2/evaluator),
+ so a first emission is always `entered`: the presence of a key means both pipelines
+ have weighed in on that person, which is the universe the membership diff is bounded to.
+ """
+ return set(state.keys())
diff --git a/products/cohorts/backend/parity/report.py b/products/cohorts/backend/parity/report.py
index 3c65689c6f42..bf9660957440 100644
--- a/products/cohorts/backend/parity/report.py
+++ b/products/cohorts/backend/parity/report.py
@@ -24,8 +24,9 @@ def _sorted_rows(rows: Sequence[CohortComparison]) -> list[CohortComparison]:
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}"
+ f"{'cohort':<32} {'class':<24} {'old':>9} {'obs':>9} {'new':>9} {'both':>9} "
+ f"{'only_old':>9} {'only_new':>9} {'fresh':>7} {'stale':>7} {'resid%':>7} "
+ f"{'unobs':>9} {'suspect':>8} {'verdict':>7}"
)
lines = [header, "-" * len(header)]
for r in _sorted_rows(rows):
@@ -33,9 +34,9 @@ def format_table(rows: Sequence[CohortComparison]) -> str:
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}"
+ f"{label:<32} {r.eligibility:<24} {r.old_count:>9} {r.observed:>9} {r.new_count:>9} {r.both:>9} "
+ f"{r.only_old:>9} {r.only_new:>9} {r.fresh:>7} {r.stale:>7} {r.residual_pct:>6.2f}% "
+ f"{r.unobserved:>9} {r.suspect_missing:>8} {r.verdict:>7}"
)
return "\n".join(lines)
@@ -51,8 +52,8 @@ def format_notes(rows: Sequence[CohortComparison]) -> str:
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"skew explained: fresh={summary.fresh_total} stale={summary.stale_total} dormant={summary.dormant_total} "
+ f"(of {summary.raw_diff_total} raw diff); suspect_missing={summary.suspect_total}",
f"pipeline age: {summary.pipeline_age_days:.1f}d since --since",
]
for warning in summary.warnings:
diff --git a/products/cohorts/backend/parity/snapshots.py b/products/cohorts/backend/parity/snapshots.py
index 262739542b8f..1977a1625cb0 100644
--- a/products/cohorts/backend/parity/snapshots.py
+++ b/products/cohorts/backend/parity/snapshots.py
@@ -67,7 +67,11 @@ def load_realtime_cohorts(team_id: int) -> QuerySet[Cohort]:
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)."""
+ """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.
+ """
tag_queries(product=ProductKey.COHORTS, feature=Feature.COHORT)
members: set[str] = set()
cursor: str | None = None
@@ -90,7 +94,7 @@ def load_old_membership(team_id: int, cohort_id: int, *, page_size: int = 500_00
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`."""
+ """Missed-emission 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)
diff --git a/products/cohorts/backend/parity/test/test_classifier.py b/products/cohorts/backend/parity/test/test_classifier.py
index 44ce2e8febfe..14e4737f97b7 100644
--- a/products/cohorts/backend/parity/test/test_classifier.py
+++ b/products/cohorts/backend/parity/test/test_classifier.py
@@ -1,7 +1,10 @@
+import math
from datetime import UTC, datetime, timedelta
from django.test import SimpleTestCase
+from parameterized import parameterized
+
from products.cohorts.backend.parity.classifier import (
VERDICT_FAIL,
VERDICT_PASS,
@@ -27,6 +30,10 @@ def _entered(persons: list[str], *, at: datetime) -> dict[str, MembershipRecord]
return {p: MembershipRecord(status="entered", last_updated=at) for p in persons}
+def _state(records: dict[str, tuple[str, datetime]]) -> dict[str, MembershipRecord]:
+ return {p: MembershipRecord(status=status, last_updated=at) for p, (status, at) in records.items()}
+
+
def _config(**overrides) -> ClassifierConfig:
defaults: dict = {"since": SINCE, "now": NOW, "threshold_pct": 0.5, "warmup_sample": 5000}
defaults.update(overrides)
@@ -75,101 +82,123 @@ class TestClassifier(SimpleTestCase):
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()
-
+ def test_old_only_person_outside_O_is_excluded_and_dormant(self) -> None:
+ # Old says entered, new never decided (person absent from O): the person leaves the
+ # diff (only_old excludes them) and, being inactive, is dormant — no FAIL.
row = classify_cohort(
- screened=_screened(window=30),
+ screened=_screened(window=None),
name="x",
old_members={"a", "b", "c"},
new_state={},
last_realtime_calculation_at=LAST_CALC,
- config=_config(activity_probe=probe),
+ config=_config(activity_probe=lambda persons, cutoff: set()),
)
- 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)
+ self.assertEqual((row.observed, row.only_old), (0, 0))
+ self.assertEqual((row.unobserved, row.dormant, row.suspect_missing), (3, 3, 0))
+ self.assertEqual(row.verdict, VERDICT_PASS)
- def test_warming_cohort_still_gates_on_unexplained_only_new(self) -> None:
- stale_over_inclusion = classify_cohort(
- screened=_screened(window=30),
+ @parameterized.expand(
+ [
+ # flip newer than the old side's last recompute → R-STALE explains it → PASS
+ ("flip_after_last_calc", NOW, 1, 0, VERDICT_PASS),
+ # flip older → old has recomputed past it, so it is a genuine residual → FAIL
+ ("flip_before_last_calc", LAST_CALC - timedelta(minutes=5), 0, 1, VERDICT_FAIL),
+ ]
+ )
+ def test_r_stale_mirror(
+ self, _name: str, flip_at: datetime, expected_stale: int, expected_residual_old: int, expected_verdict: str
+ ) -> None:
+ # Person p is in O (new flipped it to `left`) but old still says entered.
+ row = classify_cohort(
+ screened=_screened(),
name="x",
- old_members={"a"},
- new_state=_entered(["a"], at=NOW) | _entered(["b"], at=LAST_CALC - timedelta(minutes=5)),
+ old_members={"p", "a"},
+ new_state=_state({"p": ("left", flip_at), "a": ("entered", NOW)}),
last_realtime_calculation_at=LAST_CALC,
config=_config(),
)
- self.assertEqual(stale_over_inclusion.residual_new, 1)
- self.assertEqual(stale_over_inclusion.verdict, VERDICT_FAIL)
+ self.assertEqual(row.only_old, 1)
+ self.assertEqual(row.stale, expected_stale)
+ self.assertEqual(row.residual_old, expected_residual_old)
+ self.assertEqual(row.verdict, expected_verdict)
- fresh_only = classify_cohort(
+ def test_active_unobserved_on_sound_cohort_is_suspect_and_fails(self) -> None:
+ # Dead-processor case: empty O, populated old, all recently active. The O-bounded
+ # residual is 0, but the missed-emission probe gates FAIL on a sound cohort.
+ row = classify_cohort(
+ screened=_screened(window=None),
+ name="x",
+ old_members={"a", "b", "c"},
+ new_state={},
+ last_realtime_calculation_at=LAST_CALC,
+ config=_config(activity_probe=lambda persons, cutoff: set(persons)),
+ )
+ self.assertEqual((row.observed, row.residual_old, row.residual_new), (0, 0, 0))
+ self.assertEqual((row.suspect_missing, row.dormant), (3, 0))
+ self.assertEqual(row.verdict, VERDICT_FAIL)
+
+ def test_active_unobserved_on_long_window_cohort_is_warmup_not_gated(self) -> None:
+ # Same active-unobserved population, but the behavioral window exceeds pipeline age:
+ # the miss is unresolvable from a snapshot (pre-since qualifier), so WARMUP not FAIL.
+ row = classify_cohort(
screened=_screened(window=30),
name="x",
- old_members={"a"},
- new_state=_entered(["a"], at=NOW) | _entered(["b"], at=NOW),
+ old_members={"a", "b", "c"},
+ new_state={},
last_realtime_calculation_at=LAST_CALC,
- config=_config(),
+ config=_config(activity_probe=lambda persons, cutoff: set(persons)),
)
- self.assertEqual(fresh_only.residual_new, 0)
- self.assertEqual(fresh_only.verdict, VERDICT_WARMUP)
+ self.assertEqual(row.suspect_missing, 3)
+ self.assertEqual(row.verdict, VERDICT_WARMUP)
+ self.assertFalse(row.gated)
- def test_person_level_warmup_explains_inactive_only_old(self) -> None:
- seen_cutoffs: list[datetime] = []
+ def test_warmup_sample_zero_skips_suspect_probe(self) -> None:
+ probe_calls: list[list[str]] = []
def probe(persons, cutoff):
- seen_cutoffs.append(cutoff)
- return {"active"}
+ probe_calls.append(list(persons))
+ return set(persons)
row = classify_cohort(
screened=_screened(window=None),
name="x",
- old_members={"active", "dormant1", "dormant2"},
+ old_members={"a", "b"},
new_state={},
last_realtime_calculation_at=LAST_CALC,
- config=_config(activity_probe=probe),
+ config=_config(warmup_sample=0, 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)
+ self.assertEqual(probe_calls, [])
+ self.assertEqual((row.suspect_missing, row.dormant), (0, 2))
+ self.assertEqual(row.verdict, VERDICT_PASS)
+ self.assertTrue(any("suspect check skipped" in note for note in row.notes))
- def test_behavioral_window_narrows_the_warmup_cutoff(self) -> None:
+ @parameterized.expand(
+ [
+ ("no_window", None, SINCE),
+ ("sub_day_window", 0.25, NOW - timedelta(days=0.25)),
+ ("window_ge_pipeline_age", 30.0, SINCE),
+ ("inf_window", math.inf, SINCE), # would overflow timedelta without the guard
+ ("zero_window", 0.0, NOW), # minute/hour cohorts → cutoff collapses to now
+ ]
+ )
+ def test_probe_cutoff_formula(self, _name: str, window: float | None, expected_cutoff: datetime) -> None:
seen_cutoffs: list[datetime] = []
def probe(persons, cutoff):
seen_cutoffs.append(cutoff)
- return set(persons)
+ return set()
classify_cohort(
- screened=_screened(window=0.25),
+ screened=_screened(window=window),
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)])
+ self.assertEqual(seen_cutoffs, [expected_cutoff])
- 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:
+ def test_suspect_missing_extrapolates_from_sample(self) -> None:
row = classify_cohort(
screened=_screened(window=None),
name="x",
@@ -178,59 +207,56 @@ class TestClassifier(SimpleTestCase):
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)
+ self.assertEqual((row.suspect_missing, row.dormant), (2, 2))
+ self.assertIn("suspect_missing extrapolated from sample 2/4", row.notes)
+ self.assertEqual(row.verdict, VERDICT_FAIL)
- def test_residual_gate_threshold(self) -> None:
+ @parameterized.expand(
+ [
+ ("loose_threshold_passes", 5.0, VERDICT_PASS),
+ ("strict_threshold_fails", 1.0, VERDICT_FAIL),
+ ]
+ )
+ def test_residual_gate_honors_threshold(self, _name: str, threshold: float, expected_verdict: str) -> None:
+ # 97 agreeing + 2 residual (new flipped `left` before last_calc) → residual_pct ~2.02%.
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,
+ new_state = _entered([f"p{i}" for i in range(97)], at=NOW - timedelta(hours=2)) | _state(
+ {"p97": ("left", NOW - timedelta(hours=2)), "p98": ("left", NOW - timedelta(hours=2))}
)
- self.assertEqual(row.residual_new, 0)
- self.assertEqual(row.fresh, 1)
- self.assertEqual(row.verdict, VERDICT_PASS)
-
- stale = classify_cohort(
+ row = 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,
+ new_state=new_state,
+ last_realtime_calculation_at=NOW - timedelta(minutes=1),
+ config=_config(threshold_pct=threshold),
)
- self.assertGreater(stale.residual_pct, 1.0)
- self.assertEqual(stale.verdict, VERDICT_FAIL)
+ self.assertEqual((row.residual_old, row.unobserved), (2, 0))
+ self.assertGreater(row.residual_pct, 1.0)
+ self.assertLess(row.residual_pct, 5.0)
+ self.assertEqual(row.verdict, expected_verdict)
- def test_no_classify_gates_on_raw_diff(self) -> None:
+ def test_no_classify_gates_on_o_bounded_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),
+ config=_config(classify=False, activity_probe=lambda p, c: set(p)),
)
- self.assertEqual(row.fresh, 0)
- self.assertEqual(row.warmup, 0)
+ self.assertEqual((row.fresh, row.stale, row.suspect_missing), (0, 0, 0))
+ self.assertEqual((row.unobserved, row.dormant), (1, 1)) # "a" is outside O, excluded
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()
+ config = _config(activity_probe=lambda persons, cutoff: set(persons))
rows = [
classify_cohort(
screened=_screened(window=30),
- name="warm",
- old_members={"a"},
+ name="warmup",
+ old_members={"a", "b"},
new_state={},
last_realtime_calculation_at=LAST_CALC,
config=config,
@@ -254,5 +280,5 @@ class TestClassifier(SimpleTestCase):
]
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)
+ self.assertEqual((summary.suspect_total, summary.dormant_total, summary.stale_total), (2, 0, 0))
+ self.assertEqual(summary.raw_diff_total, 2)
diff --git a/products/cohorts/backend/parity/test/test_fold.py b/products/cohorts/backend/parity/test/test_fold.py
index b6558a9f93e4..39856ac8d322 100644
--- a/products/cohorts/backend/parity/test/test_fold.py
+++ b/products/cohorts/backend/parity/test/test_fold.py
@@ -4,7 +4,7 @@ from django.test import SimpleTestCase
from parameterized import parameterized
-from products.cohorts.backend.parity.fold import fold_membership_changes, members, parse_last_updated
+from products.cohorts.backend.parity.fold import fold_membership_changes, members, observed, parse_last_updated
SINCE = datetime(2026, 7, 7, 19, 0, tzinfo=UTC)
@@ -36,6 +36,21 @@ class TestFold(SimpleTestCase):
self.assertEqual(stats.folded, 5)
self.assertEqual(stats.cohorts_seen, {10})
+ def test_observed_counts_both_entered_and_left(self) -> None:
+ # The O-bounded diff hinges on `observed` returning every decided person, so a
+ # person whose final state is `left` must still count as observed (unlike members).
+ state, _stats = fold_membership_changes(
+ [
+ _msg("entered", "2026-07-07 19:01:00.000001", person_id="P1"),
+ _msg("left", "2026-07-07 19:02:00.000001", person_id="P1"),
+ _msg("entered", "2026-07-07 19:01:00.000001", person_id="P2"),
+ ],
+ team_id=2,
+ since=SINCE,
+ )
+ self.assertEqual(observed(state[10]), {"p1", "p2"})
+ self.assertEqual(members(state[10]), {"p2"})
+
def test_out_of_order_older_record_does_not_shadow_newer(self) -> None:
state, _stats = fold_membership_changes(
[