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): add oracle modes to parity harness (#73634)

Matheus Batista163ba9ab43bd
diff --git a/products/cohorts/backend/management/commands/compare_cohort_membership.py b/products/cohorts/backend/management/commands/compare_cohort_membership.py
index f31b503d31bb..026139d6b353 100644
--- a/products/cohorts/backend/management/commands/compare_cohort_membership.py
+++ b/products/cohorts/backend/management/commands/compare_cohort_membership.py
@@ -1,41 +1,97 @@
-"""Classified parity report: new Rust cohort pipeline vs old Temporal recompute pipeline.
+"""Classified parity report: new Rust cohort pipeline vs an oracle.
-Compares converged membership snapshots — the shadow topic folded to final state per
-(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.
+Two oracle modes select what the folded shadow topic (the new pipeline's converged membership) is
+compared against:
+
+- ``--oracle old-pipeline`` (default): the argMax of ClickHouse ``cohort_membership`` — the legacy
+ Temporal recompute. 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
+ feed a separate missed-emission probe. Divergences are classified (R-FRESH / R-STALE /
+ suspect-missing / dormant) so expected skew is separated from real bugs.
+
+- ``--oracle recompute``: membership recomputed from ``events`` with evaluator semantics (window,
+ count>=1 floor, operator, tree composition), then diffed with backfill-aware segmentation — the
+ productized form of the hand-rolled backfill canary verification. Over-count (fold - oracle) is the
+ hard gate; under-count (oracle - fold) is segmented by day-domain so the boundary-day decay gap is
+ separated from real seed/unseeded misses.
Run from a toolbox/web pod (needs KAFKA_INGESTION_HOSTS + the offline ClickHouse host):
manage.py compare_cohort_membership --team-id 2 --since "2026-07-07T19:11:00Z"
+ manage.py compare_cohort_membership --team-id 2 --cohort-id 433564 --since "2026-07-24T02:00:00Z" --oracle recompute
"""
from __future__ import annotations
import json
from collections import Counter
+from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
-from typing import Any
+from typing import Any, Optional
+from uuid import UUID
from django.core.management.base import BaseCommand, CommandError, CommandParser
+from posthog.models.team.team import Team
+
+from products.cohorts.backend.backfill.pinning import pin_conditions_for_cohorts
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, reconcile_completeness_by_cohort
+from products.cohorts.backend.parity.fold import fold_membership_changes, members, reconcile_completeness_by_cohort
from products.cohorts.backend.parity.kafka_io import DEFAULT_SHADOW_TOPIC, DrainStats, consumer_config, drain_topic
+from products.cohorts.backend.parity.oracle import (
+ OracleSetTooLarge,
+ load_day_counts,
+ load_leaf_match_counts,
+ load_leaf_members,
+ load_run_context,
+ run_with_boundary_exists,
+)
+from products.cohorts.backend.parity.recompute import (
+ ExtendedLeafCounts,
+ RecomputeComparison,
+ RecomputeUnsupported,
+ RunContext,
+ classify_recompute,
+ compute_oracle_members,
+ screen_for_recompute,
+ segmentation_blocker,
+ skip_comparison,
+ summarize_recompute,
+)
from products.cohorts.backend.parity.report import (
format_notes,
+ format_recompute_notes,
+ format_recompute_summary,
+ format_recompute_table,
format_reconcile_notes,
format_summary,
format_table,
to_json,
+ to_recompute_json,
)
from products.cohorts.backend.parity.snapshots import load_old_membership, load_realtime_cohorts, make_activity_probe
+from products.cohorts.backend.parity.tzdates import resolve_zoneinfo, window_start_utc
SHADOW_TOPIC_RETENTION_DAYS = 7
+# A pinned --at well behind the drain is sound (the fold converges to the same instant) but describes
+# a past state: reconcile markers and decisions made since are excluded, so say so.
+RECOMPUTE_STALE_AT_MINUTES = 15
+
+DEFAULT_THRESHOLD_PCT = 0.5
+DEFAULT_WARMUP_SAMPLE = 5000
+DEFAULT_GRACE_MINUTES = 10
+# A cohort window wider than this drives an unbounded `events` scan for no diagnostic gain; the Rust
+# side treats such a window as "never evicts" rather than sliding, so SKIP instead of scanning.
+DEFAULT_MAX_WINDOW_DAYS = 400
+# `load_leaf_members` materializes the whole set in a Python set; past this it OOMs a toolbox pod.
+DEFAULT_MAX_ORACLE_MEMBERS = 1_000_000
+# Grace is also the sweep-lag horizon, so a whole day of it would swallow the boundary day.
+MAX_GRACE_MINUTES = 24 * 60
+# Persons per diff side that the per-person reads will chunk through (1000 ids per query).
+MAX_DIFF_TARGETS = 50_000
+# The eviction split asks whether a false member is still a member one day-slide back.
+EVICTION_LOOKBACK_DAYS = 1
# Deliberate coverage limits, restated with every report so a clean run is not over-read.
COVERAGE_CAVEATS = (
@@ -46,6 +102,17 @@ COVERAGE_CAVEATS = (
"a partial drain (poll timeout or --max-messages) understates the new side and biases toward FAIL",
)
+RECOMPUTE_CAVEATS = (
+ "the oracle reproduces only performed_event / performed_event_multiple leaves with a string event key, no event_filters (property matching is HogVM bytecode, not SQL), and whole-day sliding windows within --max-window-days; everything else SKIPs",
+ "over-count (false_members) is the hard gate; the sweep-lag share — still a member one day-slide back, or entered within --grace-minutes — is reported but not gated",
+ "under-count segmentation needs a single supported leaf, a monotone op (gte/gt), a backfill run, and a grace window opening after that run's boundary; without them the cohort reports SKIP (parity not established), never PASS",
+ "past the per-person read cap the two sides fail differently: over-count keeps scoring every false member hard (FAIL), since over-inclusion is the hard invariant, while under-count drops to unsegmented (SKIP); a cap-driven FAIL is called out in the cohort notes and is not on its own evidence of over-inclusion",
+ "missing_boundary_day is the expected decaying gap; missing_seed_domain, missing_unseeded_day and missing_post_boundary gate FAIL — raise --grace-minutes to absorb known live-path lag",
+ "day boundaries use the current team tz, the only tz the processor uses; a run pinned to a different tz SKIPs rather than mis-attributing seed days",
+ "the oracle counts only events ingested by --at (the seeder's inserted_at cutoff), so a longer ingestion lag reads as neither over- nor under-count",
+ "override/merge drift (fold ids resolved at processing time vs the oracle's current overrides) can pair a false_member with a missing person; a bounded per-class person-id sample ships in the JSON for triage",
+)
+
def _collect_warnings(
drain_stats: DrainStats,
@@ -83,18 +150,100 @@ def _collect_warnings(
return warnings, infos
-def _parse_since(raw: str) -> datetime:
+@dataclass(frozen=True)
+class RecomputeCohortState:
+ cohort_id: int
+ ctx: Optional[RunContext]
+ has_complete_reconcile: bool
+
+
+def _collect_recompute_warnings(
+ *,
+ at: datetime,
+ now: datetime,
+ team_timezone: str,
+ states: list[RecomputeCohortState],
+) -> list[str]:
+ """Pure: recompute-specific operator warnings — stale clock and per-cohort run-context caveats."""
+ warnings: list[str] = []
+ stale = now - at
+ if stale > timedelta(minutes=RECOMPUTE_STALE_AT_MINUTES):
+ warnings.append(
+ f"--at is {int(stale.total_seconds() // 60)}m before now; the fold is bounded to it, so this "
+ "report describes that instant rather than the current pipeline state"
+ )
+ for state in states:
+ if state.ctx is None:
+ warnings.append(
+ f"cohort {state.cohort_id}: no backfill run with a boundary; the missing set is left unsegmented"
+ )
+ continue
+ if state.ctx.run_timezone != team_timezone:
+ warnings.append(
+ f"cohort {state.cohort_id}: run tz {state.ctx.run_timezone} != team tz {team_timezone}; seed-chunk "
+ "days cannot be attributed to the team-tz days the processor bins by, so the cohort is SKIPPED"
+ )
+ if state.ctx.shape_hash_drift:
+ warnings.append(
+ f"cohort {state.cohort_id}: behavioral filters changed since the run was pinned (shape-hash "
+ "drift); the seed domain may be stale"
+ )
+ if state.ctx.non_confirmed_chunks > 0:
+ warnings.append(
+ f"cohort {state.cohort_id}: {state.ctx.non_confirmed_chunks} seed chunk(s) not confirmed; the "
+ "seed domain is partial"
+ )
+ if not state.has_complete_reconcile:
+ warnings.append(
+ f"cohort {state.cohort_id}: no complete 64/64 reconcile run folded; over-counts may be spurious"
+ )
+ return warnings
+
+
+def _parse_iso_utc(raw: str, flag: 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
+ raise CommandError(f"{flag} is not ISO8601: {raw!r}") from err
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=UTC)
return parsed.astimezone(UTC)
+def _parse_since(raw: str) -> datetime:
+ return _parse_iso_utc(raw, "--since")
+
+
+def _within_target_cap(targets: list[str], side: str, notes: list[str]) -> bool:
+ """Whether a diff side is small enough to drive per-person reads (1000 ids per query).
+
+ A blown cap is recorded in the report rather than silently truncated: past it the diagnostic
+ would run tens of thousands of sequential `events` scans on the offline pool.
+ """
+ if len(targets) <= MAX_DIFF_TARGETS:
+ return True
+ notes.append(
+ f"{len(targets)} {side} persons exceed the {MAX_DIFF_TARGETS} per-person read cap; "
+ f"{side} left unexplained (check --since: a wrong value empties the fold)"
+ )
+ return False
+
+
+def _reject_flags(options: dict[str, Any], flags: tuple[str, ...], mode: str) -> None:
+ """Reject flags belonging to the other oracle mode.
+
+ Every mode-specific flag defaults to ``None`` (or ``False`` for a store_true) precisely so an
+ explicit value that happens to equal the documented default is still caught.
+ """
+ rejected = [
+ f"--{flag.replace('_', '-')}" for flag in flags if options[flag] is not None and options[flag] is not False
+ ]
+ if rejected:
+ raise CommandError(f"not valid with --oracle {mode} (parameterizes the other oracle): {', '.join(rejected)}")
+
+
class Command(BaseCommand):
- help = "Compare new-pipeline (shadow topic) vs old-pipeline (ClickHouse) cohort membership for one team"
+ help = "Compare new-pipeline (shadow topic) vs an oracle (old pipeline or recompute) cohort membership"
def add_arguments(self, parser: CommandParser) -> None:
parser.add_argument("--team-id", type=int, required=True)
@@ -105,17 +254,63 @@ class Command(BaseCommand):
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(
+ "--oracle",
+ choices=["old-pipeline", "recompute"],
+ default="old-pipeline",
+ help="What to compare the fold against (default old-pipeline, byte-identical to prior behavior)",
+ )
+ parser.add_argument(
+ "--at",
+ type=str,
+ default=None,
+ help="recompute only: ISO8601 pinned instant for both the oracle window and the fold (default: the "
+ "instant the drain finished); must be after --since",
+ )
+ parser.add_argument(
+ "--run-id",
+ type=str,
+ default=None,
+ help="recompute only: backfill run for segmentation metadata (default: latest run with a boundary)",
+ )
+ parser.add_argument(
+ "--grace-minutes",
+ type=int,
+ default=None,
+ help=f"recompute only: last N minutes treated as lag noise, both for a missing person's qualifying "
+ f"events and for a just-entered false member (default {DEFAULT_GRACE_MINUTES})",
+ )
+ parser.add_argument(
+ "--max-window-days",
+ type=int,
+ default=None,
+ help=f"recompute only: cohorts whose leaf window exceeds this SKIP rather than driving an unbounded "
+ f"events scan (default {DEFAULT_MAX_WINDOW_DAYS})",
+ )
+ parser.add_argument(
+ "--max-oracle-members",
+ type=int,
+ default=None,
+ help=f"recompute only: cohorts whose leaf matches more persons than this SKIP rather than being "
+ f"materialized in memory (default {DEFAULT_MAX_ORACLE_MEMBERS})",
+ )
+ parser.add_argument(
+ "--threshold",
+ type=float,
+ default=None,
+ help=f"old-pipeline only: max residual %% for PASS (default {DEFAULT_THRESHOLD_PCT})",
+ )
parser.add_argument(
"--warmup-sample",
type=int,
- default=5000,
- help="Persons sampled per cohort for the missed-emission (suspect) probe over old - O; 0 skips it",
+ default=None,
+ help=f"old-pipeline only: persons sampled per cohort for the missed-emission probe over old - O; "
+ f"0 skips it (default {DEFAULT_WARMUP_SAMPLE})",
)
parser.add_argument(
"--no-classify",
action="store_true",
- help="O-bounded raw diff only, no R-FRESH/R-STALE rules or suspect probe",
+ help="old-pipeline only: O-bounded raw diff, no R-FRESH/R-STALE rules or suspect probe",
)
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")
@@ -129,14 +324,39 @@ class Command(BaseCommand):
now = datetime.now(tz=UTC)
if since >= now:
raise CommandError("--since is in the future")
+ oracle = options["oracle"]
as_json = options["format"] == "json"
+ # Validate every mode-specific flag up front: the drain below takes minutes, and a flag error
+ # surfacing after it wastes the whole run.
+ explicit_at: Optional[datetime] = None
+ team: Optional[Team] = None
+ if oracle == "recompute":
+ self._validate_recompute_flags(options)
+ if options["at"] is not None:
+ explicit_at = _parse_iso_utc(options["at"], "--at")
+ if explicit_at <= since:
+ raise CommandError("--at must be after --since")
+ if explicit_at > now:
+ # An instant the data never reached would pin a report the run cannot describe,
+ # and would silence the staleness warning by making the skew negative.
+ raise CommandError("--at is in the future")
+ # The recompute oracle needs the team tz and a resolvable run; both are cheap to check.
+ team = Team.objects.filter(id=team_id).first()
+ if team is None:
+ raise CommandError(f"team {team_id} does not exist")
+ if options["run_id"] is not None and not run_with_boundary_exists(team_id, options["run_id"]):
+ raise CommandError(
+ f"--run-id {options['run_id']} is not a backfill run of team {team_id} with a boundary"
+ )
+ else:
+ _reject_flags(options, ("at", "run_id", "grace_minutes", "max_window_days", "max_oracle_members"), oracle)
def log(message: str) -> None:
# Keep stdout clean for the JSON document.
(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.
+ # 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}:
@@ -174,12 +394,14 @@ class Command(BaseCommand):
stats=drain_stats,
max_messages=options["max_messages"],
)
- new_state, fold_stats = fold_membership_changes(messages, team_id=team_id, since=since)
+ # An explicit --at pins the comparison clock, so the fold has to converge to that instant too.
+ new_state, fold_stats = fold_membership_changes(messages, team_id=team_id, since=since, until=explicit_at)
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"({fold_stats.reconcile_markers_recorded} reconcile markers; "
f"dropped: {fold_stats.dropped_wrong_team} wrong-team, {fold_stats.dropped_before_since} pre-since, "
+ f"{fold_stats.dropped_after_until} post-at, "
f"{fold_stats.dropped_malformed} malformed, {drain_stats.undecodable} undecodable; "
f"by origin: {dict(sorted(fold_stats.folded_by_origin.items()))})"
)
@@ -188,12 +410,86 @@ class Command(BaseCommand):
for info in infos:
self.stderr.write(info)
- # 3. Old snapshot + classification per eligible cohort.
+ # 3. Oracle-specific classification + report.
+ if oracle == "recompute":
+ # Stamped after the drain, not before it: the fold reflects every offset up to here, so an
+ # oracle window closing earlier would score cohort entries made during the drain as hard
+ # over-counts. --grace-minutes absorbs the remaining tail.
+ assert team is not None # resolved above, before the drain
+ self._report_recompute(
+ options=options,
+ team_id=team_id,
+ team=team,
+ since=since,
+ now=datetime.now(tz=UTC),
+ explicit_at=explicit_at,
+ cohorts=cohorts,
+ selected_ids=selected_ids,
+ screened=screened,
+ names=names,
+ new_state=new_state,
+ fold_stats=fold_stats,
+ drain_warnings=warnings,
+ as_json=as_json,
+ log=log,
+ )
+ else:
+ self._report_old_pipeline(
+ options=options,
+ team_id=team_id,
+ since=since,
+ now=now,
+ selected_ids=selected_ids,
+ screened=screened,
+ names=names,
+ last_calc=last_calc,
+ new_state=new_state,
+ fold_stats=fold_stats,
+ drain_warnings=warnings,
+ as_json=as_json,
+ )
+
+ def _validate_recompute_flags(self, options: dict[str, Any]) -> None:
+ _reject_flags(options, ("threshold", "warmup_sample", "no_classify"), "recompute")
+ grace = options["grace_minutes"]
+ if grace is not None and not 0 <= grace <= MAX_GRACE_MINUTES:
+ # Past a day, grace_start reaches back over the boundary day and buckets seed-day events
+ # as lag noise, collapsing the whole missing set into an ungated class.
+ raise CommandError(f"--grace-minutes must be between 0 and {MAX_GRACE_MINUTES}")
+ for flag in ("max_window_days", "max_oracle_members"):
+ if options[flag] is not None and options[flag] < 1:
+ raise CommandError(f"--{flag.replace('_', '-')} must be positive")
+ if options["run_id"] is not None:
+ try:
+ UUID(options["run_id"])
+ except ValueError as err:
+ # CohortBackfillRun is a UUID model; an unparseable id would otherwise surface as a
+ # raw Django ValidationError traceback after the drain.
+ raise CommandError(f"--run-id is not a UUID: {options['run_id']!r}") from err
+
+ def _report_old_pipeline(
+ self,
+ *,
+ options: dict[str, Any],
+ team_id: int,
+ since: datetime,
+ now: datetime,
+ selected_ids: list[int],
+ screened: Any,
+ names: dict[int, str],
+ last_calc: dict[int, Any],
+ new_state: Any,
+ fold_stats: Any,
+ drain_warnings: list[str],
+ as_json: bool,
+ ) -> None:
+ threshold_pct = DEFAULT_THRESHOLD_PCT if options["threshold"] is None else options["threshold"]
+ warmup_sample = DEFAULT_WARMUP_SAMPLE if options["warmup_sample"] is None else options["warmup_sample"]
classifier_config = ClassifierConfig(
since=since,
now=now,
- threshold_pct=options["threshold"],
- warmup_sample=options["warmup_sample"],
+ threshold_pct=threshold_pct,
+ warmup_sample=warmup_sample,
classify=not options["no_classify"],
activity_probe=make_activity_probe(team_id),
)
@@ -215,17 +511,17 @@ class Command(BaseCommand):
)
summary = summarize(rows, config=classifier_config)
- summary.warnings.extend(warnings)
+ summary.warnings.extend(drain_warnings)
- # 4. Report.
if as_json:
+ # No "oracle" key here: the default path stays byte-identical to the pre-flag output.
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"],
+ "threshold_pct": threshold_pct,
+ "warmup_sample": warmup_sample,
"classify": not options["no_classify"],
"caveats": list(COVERAGE_CAVEATS),
}
@@ -244,5 +540,202 @@ class Command(BaseCommand):
if summary.failed:
raise CommandError(
- f"{summary.failed} eligible cohort(s) FAIL the {options['threshold']}% parity gate (residual or suspect-missing)"
+ f"{summary.failed} eligible cohort(s) FAIL the {threshold_pct}% parity gate (residual or suspect-missing)"
+ )
+
+ def _report_recompute(
+ self,
+ *,
+ options: dict[str, Any],
+ team_id: int,
+ team: Team,
+ since: datetime,
+ now: datetime,
+ explicit_at: Optional[datetime],
+ cohorts: list[Any],
+ selected_ids: list[int],
+ screened: Any,
+ names: dict[int, str],
+ new_state: Any,
+ fold_stats: Any,
+ drain_warnings: list[str],
+ as_json: bool,
+ log: Any,
+ ) -> None:
+ at = now if explicit_at is None else explicit_at
+ grace_minutes = DEFAULT_GRACE_MINUTES if options["grace_minutes"] is None else options["grace_minutes"]
+ grace = timedelta(minutes=grace_minutes)
+ max_window_days = DEFAULT_MAX_WINDOW_DAYS if options["max_window_days"] is None else options["max_window_days"]
+ max_members = (
+ DEFAULT_MAX_ORACLE_MEMBERS if options["max_oracle_members"] is None else options["max_oracle_members"]
+ )
+ run_id: Optional[str] = options["run_id"]
+
+ team_tz = resolve_zoneinfo(team.timezone)
+ cohort_by_id = {c.pk: c for c in cohorts}
+ completeness_by_cohort = reconcile_completeness_by_cohort(fold_stats)
+ log(f"recompute oracle at {at.isoformat()} (team tz {team.timezone}); grace {grace_minutes}m")
+
+ rows: list[RecomputeComparison] = []
+ warn_states: list[RecomputeCohortState] = []
+ for cid in sorted(selected_ids):
+ s = screened[cid]
+ name = names[cid]
+ reconcile_runs = completeness_by_cohort.get(cid, ())
+ if not s.emits:
+ reason = "not emit-eligible: " + ", ".join(s.drop_reasons or (s.eligibility,))
+ rows.append(skip_comparison(cohort_id=cid, name=name, reason=reason, reconcile_runs=reconcile_runs))
+ continue
+
+ cohort = cohort_by_id[cid]
+ pinned_payload, _event_names = pin_conditions_for_cohorts([cohort])
+ screen = screen_for_recompute(
+ cid, cohort.filters, pinned_payload["conditions"], max_window_days=max_window_days
+ )
+ if isinstance(screen, RecomputeUnsupported):
+ rows.append(
+ skip_comparison(cohort_id=cid, name=name, reason=screen.reason, reconcile_runs=reconcile_runs)
+ )
+ continue
+
+ ctx = load_run_context(team_id, cid, run_id)
+ if run_id is not None and ctx is None:
+ # The run itself was validated before the drain, so this cohort simply is not part of
+ # it. Skipping keeps the rest of the report while refusing to claim a parity that the
+ # requested run cannot segment.
+ rows.append(
+ skip_comparison(
+ cohort_id=cid, name=name, reason="not_in_requested_run", reconcile_runs=reconcile_runs
+ )
+ )
+ continue
+ warn_states.append(
+ RecomputeCohortState(
+ cohort_id=cid,
+ ctx=ctx,
+ has_complete_reconcile=any(run.complete for run in reconcile_runs),
+ )
+ )
+ if ctx is not None and ctx.run_timezone != team.timezone:
+ # The processor only ever bins days in the team tz, so seed-chunk days pinned to
+ # another tz cannot be attributed without shifting a day either way.
+ rows.append(
+ skip_comparison(
+ cohort_id=cid, name=name, reason="run_tz_differs_from_team_tz", reconcile_runs=reconcile_runs
+ )
+ )
+ continue
+
+ try:
+ leaf_members = {
+ key: load_leaf_members(team_id, leaf, at=at, tz=team_tz, limit=max_members)
+ for key, leaf in screen.leaves.items()
+ }
+ except OracleSetTooLarge as err:
+ rows.append(
+ skip_comparison(
+ cohort_id=cid, name=name, reason=f"oracle_set_over_{err.limit}", reconcile_runs=reconcile_runs
+ )
+ )
+ continue
+ oracle_members = compute_oracle_members(screen, leaf_members)
+ fold_records = new_state.get(cid, {})
+ fold_members = members(fold_records)
+
+ cohort_notes: list[str] = []
+ false_targets = sorted(fold_members - oracle_members)
+ missing_targets = sorted(oracle_members - fold_members)
+
+ # Over-count split: per-leaf counts over each window slid back one day, for the false set.
+ extended_leaf_counts: ExtendedLeafCounts = {}
+ if false_targets and _within_target_cap(false_targets, "over-count", cohort_notes):
+ extended_leaf_counts = {
+ key: load_leaf_match_counts(
+ team_id,
+ leaf,
+ person_ids=false_targets,
+ at=at,
+ tz=team_tz,
+ extra_days=EVICTION_LOOKBACK_DAYS,
+ )
+ for key, leaf in screen.leaves.items()
+ }
+
+ # Under-count segmentation: per-day counts for the missing set of a single monotone leaf.
+ # `segmentation_blocker` owns whether the shape is segmentable at all; this only decides
+ # whether the query is worth issuing, and reports back if the cap stopped it.
+ day_counts: dict[str, list[Any]] = {}
+ day_counts_loaded = True
+ if missing_targets and segmentation_blocker(screen, ctx, at=at, grace=grace) is None:
+ assert ctx is not None # segmentation_blocker rejects a missing run context
+ if not _within_target_cap(missing_targets, "under-count", cohort_notes):
+ day_counts_loaded = False
+ else:
+ leaf = screen.sole_leaf
+ day_counts = load_day_counts(
+ team_id,
+ event_name=leaf.event_name,
+ person_ids=missing_targets,
+ scan_start=window_start_utc(at, leaf.window_days, team_tz),
+ at=at,
+ grace_start=at - grace,
+ boundary_at=ctx.boundary_at,
+ team_tz=team.timezone,
+ )
+
+ rows.append(
+ classify_recompute(
+ spec=screen,
+ name=name,
+ fold_records=fold_records,
+ oracle_members=oracle_members,
+ day_counts=day_counts,
+ extended_leaf_counts=extended_leaf_counts,
+ ctx=ctx,
+ at=at,
+ grace=grace,
+ team_tz=team_tz,
+ day_counts_loaded=day_counts_loaded,
+ reconcile_runs=reconcile_runs,
+ extra_notes=cohort_notes,
+ )
+ )
+
+ summary = summarize_recompute(rows)
+ summary.warnings.extend(drain_warnings)
+ summary.warnings.extend(
+ _collect_recompute_warnings(at=at, now=now, team_timezone=team.timezone, states=warn_states)
+ )
+
+ if as_json:
+ meta = {
+ "team_id": team_id,
+ "since": since.isoformat(),
+ "at": at.isoformat(),
+ "now": now.isoformat(),
+ "oracle": "recompute",
+ "grace_minutes": grace_minutes,
+ "run_id": run_id,
+ "max_window_days": max_window_days,
+ "max_oracle_members": max_members,
+ "shadow_topic": options["shadow_topic"],
+ "caveats": list(RECOMPUTE_CAVEATS),
+ }
+ self.stdout.write(json.dumps(to_recompute_json(rows, summary, meta), indent=2))
+ else:
+ self.stdout.write("")
+ self.stdout.write(format_recompute_table(rows))
+ notes = format_recompute_notes(rows)
+ if notes:
+ self.stdout.write("\nnotes:\n" + notes)
+ self.stdout.write("")
+ self.stdout.write(format_recompute_summary(summary))
+ self.stdout.write("caveats:")
+ for caveat in RECOMPUTE_CAVEATS:
+ self.stdout.write(f" {caveat}")
+
+ if summary.failed:
+ raise CommandError(
+ f"{summary.failed} cohort(s) FAIL the recompute parity gate "
+ "(hard over-count, or a seed/unseeded/post-boundary miss)"
)
diff --git a/products/cohorts/backend/models/leaf_shape.py b/products/cohorts/backend/models/leaf_shape.py
index d312bf626947..be1c57065870 100644
--- a/products/cohorts/backend/models/leaf_shape.py
+++ b/products/cohorts/backend/models/leaf_shape.py
@@ -1,11 +1,31 @@
import json
import hashlib
from collections.abc import Iterator
+from typing import NamedTuple
_I32_MIN = -(2**31)
_I32_MAX = 2**31 - 1
+class BehavioralLeafKey(NamedTuple):
+ """The behavioral-leaf fields Stage 1 hashes into a `LeafStateKey`.
+
+ `conditionHash` alone is not a leaf identity: it digests only the event matcher, so two leaves
+ that differ in window, operator, or value share it (`rust/cohort-core/src/leaf_state/key.rs`).
+ Anything that has to tell one leaf's state from another's — the processor's state keying, the
+ shape hash below, the recompute oracle's per-leaf member sets — must key on this whole tuple.
+ """
+
+ condition_hash: object
+ value: str
+ time_value: int
+ time_interval: str
+ explicit_datetime: str
+ explicit_datetime_to: str
+ operator: str
+ operator_value: int
+
+
def walk_filter_leaves(node: object) -> Iterator[dict]:
if not isinstance(node, dict):
return
@@ -24,6 +44,35 @@ def _effective_string(value: object) -> str:
return value if isinstance(value, str) else ""
+def behavioral_leaf_key(
+ *,
+ condition_hash: object,
+ value: object,
+ time_value: object,
+ time_interval: object,
+ explicit_datetime: object,
+ explicit_datetime_to: object,
+ operator: object,
+ operator_value: object,
+) -> BehavioralLeafKey:
+ """Normalize one behavioral leaf's raw filter fields into its `BehavioralLeafKey`.
+
+ Coercion mirrors the Rust deserializer the processor keys state with: non-string reads as absent
+ (`opt_string`) and non-`i32` reads as absent (`as_i64` into `i32`). `condition_hash` passes
+ through unchanged — it is already a 16-byte digest and callers validate it.
+ """
+ return BehavioralLeafKey(
+ condition_hash=condition_hash,
+ value=_effective_string(value),
+ time_value=_effective_i32(time_value),
+ time_interval=_effective_string(time_interval),
+ explicit_datetime=_effective_string(explicit_datetime),
+ explicit_datetime_to=_effective_string(explicit_datetime_to),
+ operator=_effective_string(operator),
+ operator_value=_effective_i32(operator_value),
+ )
+
+
def _hash_keys(keys: list[list[object]]) -> str:
if not keys:
return ""
@@ -47,14 +96,16 @@ def _extract_leaf_shape_keys(filters: dict | None, *, behavioral_only: bool) ->
keys.append(
[
"behavioral",
- condition_hash,
- _effective_string(leaf.get("value")),
- _effective_i32(leaf.get("time_value")),
- _effective_string(leaf.get("time_interval")),
- _effective_string(leaf.get("explicit_datetime")),
- _effective_string(leaf.get("explicit_datetime_to")),
- _effective_string(leaf.get("operator")),
- _effective_i32(leaf.get("operator_value")),
+ *behavioral_leaf_key(
+ condition_hash=condition_hash,
+ value=leaf.get("value"),
+ time_value=leaf.get("time_value"),
+ time_interval=leaf.get("time_interval"),
+ explicit_datetime=leaf.get("explicit_datetime"),
+ explicit_datetime_to=leaf.get("explicit_datetime_to"),
+ operator=leaf.get("operator"),
+ operator_value=leaf.get("operator_value"),
+ ),
]
)
elif leaf_type == "cohort" and not behavioral_only:
@@ -67,8 +118,7 @@ def extract_leaf_shape_hash(filters: dict | None) -> str:
This is not the Rust key itself. It is a stable SHA-256 over the full leaf set, while
`LeafStateKey::for_behavioral` uses a 16-byte digest of one leaf. Keep these fields in lockstep:
- behavioral conditionHash, value, time_value, time_interval, explicit_datetime,
- explicit_datetime_to, operator, operator_value; person conditionHash; cohort value and negation.
+ behavioral leaves via `BehavioralLeafKey`; person conditionHash; cohort value and negation.
"""
return _hash_keys(_extract_leaf_shape_keys(filters, behavioral_only=False))
diff --git a/products/cohorts/backend/parity/eligibility.py b/products/cohorts/backend/parity/eligibility.py
index 39af9e119355..db176dd4f76b 100644
--- a/products/cohorts/backend/parity/eligibility.py
+++ b/products/cohorts/backend/parity/eligibility.py
@@ -198,16 +198,45 @@ def _interval_window(node: Mapping[str, Any]) -> Optional[_Window]:
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.
+def resolve_behavioral_window(node: Mapping[str, Any]) -> Optional[_Window]:
+ """The eviction window a behavioral leaf resolves to (``kind`` = days / seconds / explicit),
+ or ``None`` when it has no representable window (leaf drops).
+
+ Public entry point to the private window-resolution the eligibility screen uses, so the
+ recompute oracle (``recompute.py``) shares one window-semantics source. Mirror of
+ ``rust/cohort-core/src/leaf_state/select.rs`` ``eviction_window``: an ``explicit_datetime``(_to)
+ pair takes precedence over ``time_value``/``time_interval``. Non-string bounds 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)
+ return _explicit_window(explicit_from, explicit_to)
+ return _interval_window(node)
+
+
+def explain_unsupported_window(node: Mapping[str, Any]) -> str:
+ """Why :func:`resolve_behavioral_window` returned ``None`` for this leaf.
+
+ Recompute needs the specific shape ``resolve_behavioral_window`` collapses to ``None`` so it can
+ SKIP with a precise reason. Mirror of the ``None`` branches of ``select.rs``
+ ``explicit_eviction_window`` — an unparseable present bound vs a relative range it cannot model —
+ plus the missing-interval case. The grammar stays centralized in :func:`_classify_bound`.
+ """
+ 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 None and explicit_to is None:
+ return "missing_window"
+ from_kind = _classify_bound(explicit_from)[0] if explicit_from is not None else None
+ to_kind = _classify_bound(explicit_to)[0] if explicit_to is not None else None
+ if from_kind == "unparseable" or to_kind == "unparseable":
+ return "unparseable_explicit_bound"
+ return "relative_range_unsupported"
+
+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)."""
+ window = resolve_behavioral_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.
diff --git a/products/cohorts/backend/parity/fold.py b/products/cohorts/backend/parity/fold.py
index 6c908b4441c9..4e380f4ac6c6 100644
--- a/products/cohorts/backend/parity/fold.py
+++ b/products/cohorts/backend/parity/fold.py
@@ -8,7 +8,7 @@ keeps replays and clock regressions from shadowing a newer record.
from __future__ import annotations
-from collections.abc import Iterable
+from collections.abc import Iterable, Mapping
from dataclasses import dataclass, field
from datetime import UTC, datetime
from typing import Any, Optional
@@ -49,6 +49,7 @@ class FoldStats:
dropped_wrong_team: int = 0
dropped_before_since: int = 0
dropped_malformed: int = 0
+ dropped_after_until: int = 0
cohorts_seen: set[int] = field(default_factory=set)
reconcile_markers: dict[tuple[str, int], set[int]] = field(default_factory=dict)
# Count of accepted marker messages, incl. duplicates — the reconcile_markers set dedups by
@@ -91,6 +92,7 @@ def _record_marker(
cohort_id: Any,
last_updated: Optional[datetime],
since: datetime,
+ until: Optional[datetime],
stats: FoldStats,
) -> None:
run_id = _parse_marker_run_id(message.get("run_id"))
@@ -109,6 +111,9 @@ def _record_marker(
if last_updated < since:
stats.dropped_before_since += 1
return
+ if until is not None and last_updated > until:
+ stats.dropped_after_until += 1
+ return
stats.reconcile_markers.setdefault((run_id, cohort_id), set()).add(partition)
stats.reconcile_markers_recorded += 1
stats.cohorts_seen.add(cohort_id)
@@ -119,9 +124,14 @@ def fold_membership_changes(
*,
team_id: int,
since: datetime,
+ until: Optional[datetime] = None,
) -> tuple[dict[int, dict[str, MembershipRecord]], FoldStats]:
"""Fold messages to {cohort_id: {person_id: final record}}, dropping other teams'
- messages and anything stamped before `since` (pre-wipe residue)."""
+ messages and anything stamped before `since` (pre-wipe residue).
+
+ `until` bounds the fold to the converged state at an instant: with a pinned comparison clock the
+ fold must not carry decisions the oracle's window cannot see, or every entry made after that
+ instant reads as an unexplained over-count."""
stats = FoldStats()
state: dict[int, dict[str, MembershipRecord]] = {}
for message in messages:
@@ -137,7 +147,7 @@ def fold_membership_changes(
last_updated = parse_last_updated(message.get("last_updated"))
if message.get("type") == RECONCILE_COMPLETE_TYPE:
- _record_marker(message, cohort_id, last_updated, since, stats)
+ _record_marker(message, cohort_id, last_updated, since, until, stats)
continue
person_id = message.get("person_id")
@@ -155,6 +165,9 @@ def fold_membership_changes(
if last_updated < since:
stats.dropped_before_since += 1
continue
+ if until is not None and last_updated > until:
+ stats.dropped_after_until += 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, {})
@@ -188,12 +201,12 @@ def reconcile_completeness(stats: FoldStats, cohort_id: int) -> tuple[ReconcileR
return reconcile_completeness_by_cohort(stats).get(cohort_id, ())
-def members(state: dict[str, MembershipRecord]) -> set[str]:
+def members(state: Mapping[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]:
+def observed(state: Mapping[str, MembershipRecord]) -> set[str]:
"""Every person the new pipeline emitted a decision for in this cohort.
Live and seed processing can be flip-only, while reconcile snapshots emit every current
diff --git a/products/cohorts/backend/parity/oracle.py b/products/cohorts/backend/parity/oracle.py
new file mode 100644
index 000000000000..ac0dfa7d1b42
--- /dev/null
+++ b/products/cohorts/backend/parity/oracle.py
@@ -0,0 +1,308 @@
+"""Recompute-oracle reads: ClickHouse member-set / segmentation queries + the Django run context.
+
+Mixed IO (ClickHouse + ORM), precedented by :mod:`.snapshots`. The pure classification of what these
+return lives in :mod:`.recompute`; this module only fetches.
+
+Person resolution mirrors the seeder's overrides join (``rust/cohort-seeder/src/clickhouse/sql.rs``):
+``if(notEmpty(ov.distinct_id), ov.person_id, e.person_id)`` with ``argMax(person_id, version) …
+HAVING argMax(is_deleted, version) = 0`` from ``person_distinct_id_overrides``. Every read also
+carries the seeder's ingestion cutoff — ``coalesce(e.inserted_at, e._timestamp) <= at`` — so the
+oracle only counts events the pipeline could already have consumed by ``at``. Without it, ingestion
+lag reads as an under-count the day-domain segmentation would blame on the seeder, and re-running at
+a fixed ``--at`` would keep growing the oracle set.
+
+All tz-date arithmetic is Python-side (:mod:`.tzdates`); SQL only ever compares ``e.timestamp``
+against UTC datetime params or converts the ``e.timestamp`` *column* via
+``toDate(<column>, %(team_tz)s)`` — never ``toDate(<param>, tz)``. Person ids are lowercased at the
+boundary to match the fold's normalization (see ``fold.py``).
+"""
+
+from __future__ import annotations
+
+from collections import defaultdict
+from collections.abc import Sequence
+from datetime import date, datetime
+from typing import Optional
+from zoneinfo import ZoneInfo
+
+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.backfill import (
+ CohortBackfillChunk,
+ CohortBackfillChunkStatus,
+ CohortBackfillRun,
+ CohortBackfillRunCohort,
+)
+from products.cohorts.backend.models.cohort import Cohort
+from products.cohorts.backend.models.util import COHORT_QUERY_TIMEOUT_SECONDS
+from products.cohorts.backend.parity.recompute import DayMatch, OracleLeaf, RunContext
+from products.cohorts.backend.parity.tzdates import day_of_instant, resolve_zoneinfo, window_start_utc
+
+# Never interpolated from user text — the op is one of these fixed comparators, chosen by key.
+_OP_SQL = {"gte": ">=", "lte": "<=", "gt": ">", "lt": "<", "eq": "="}
+
+# The seeder's overrides join, shared by all three reads.
+_OVERRIDES_JOIN = """
+ LEFT JOIN (
+ SELECT distinct_id, argMax(person_id, version) AS person_id
+ FROM person_distinct_id_overrides
+ WHERE team_id = %(team_id)s
+ GROUP BY distinct_id
+ HAVING argMax(is_deleted, version) = 0
+ ) AS ov ON e.distinct_id = ov.distinct_id
+"""
+
+_RESOLVED_PERSON = "toString(if(notEmpty(ov.distinct_id), ov.person_id, e.person_id))"
+
+_MEMBER_SET_SQL = """
+SELECT resolved_person_id, count() AS match_count
+FROM (
+ SELECT {resolved_person} AS resolved_person_id
+ FROM events AS e{overrides_join}
+ WHERE e.team_id = %(team_id)s
+ AND e.event = %(event_name)s
+ AND e.timestamp >= %(window_start)s
+ AND e.timestamp <= %(at)s
+ AND coalesce(e.inserted_at, e._timestamp) <= %(at)s
+)
+GROUP BY resolved_person_id
+HAVING match_count >= 1 AND match_count {op} %(op_value)s
+LIMIT %(limit)s
+"""
+
+_LEAF_COUNTS_SQL = """
+SELECT {resolved_person} AS resolved_person_id, count() AS matches
+FROM events AS e{overrides_join}
+WHERE e.team_id = %(team_id)s
+ AND e.event = %(event_name)s
+ AND e.timestamp >= %(window_start)s
+ AND e.timestamp <= %(at)s
+ AND coalesce(e.inserted_at, e._timestamp) <= %(at)s
+ AND {resolved_person} IN %(person_ids)s
+GROUP BY resolved_person_id
+"""
+
+_SEGMENTATION_SQL = """
+SELECT {resolved_person} AS resolved_person_id,
+ toDate(e.timestamp, %(team_tz)s) AS day,
+ multiIf(e.timestamp >= %(grace_start)s, 'grace',
+ e.timestamp >= %(boundary_at)s, 'post_boundary',
+ 'pre_boundary') AS bucket,
+ count() AS matches
+FROM events AS e{overrides_join}
+WHERE e.team_id = %(team_id)s
+ AND e.event = %(event_name)s
+ AND e.timestamp >= %(scan_start)s
+ AND e.timestamp <= %(at)s
+ AND coalesce(e.inserted_at, e._timestamp) <= %(at)s
+ AND {resolved_person} IN %(person_ids)s
+GROUP BY resolved_person_id, day, bucket
+"""
+
+# Every read is a large cohort scan, so bound wall-clock the way the product's own cohort
+# calculation queries do: a clear timeout an operator can retry with a narrower leaf beats a hang
+# holding an offline-pool connection.
+_TIMEOUT_SETTINGS = {
+ "max_execution_time": COHORT_QUERY_TIMEOUT_SECONDS,
+ "send_timeout": COHORT_QUERY_TIMEOUT_SECONDS,
+ "receive_timeout": COHORT_QUERY_TIMEOUT_SECONDS,
+}
+
+# The GROUP BY resolved_person_id can be large for a broad event; spill like the old-membership read.
+_MEMBER_SET_SETTINGS = {
+ **_TIMEOUT_SETTINGS,
+ "max_bytes_ratio_before_external_group_by": 0.5,
+ "distributed_aggregation_memory_efficient": 1,
+}
+
+_PERSON_ID_CHUNK = 1000
+
+
+class OracleSetTooLarge(Exception):
+ """A leaf's member set exceeded the cap, so the oracle refuses to materialize it in memory."""
+
+ def __init__(self, event_name: str, limit: int) -> None:
+ super().__init__(f"leaf {event_name!r} matches more than {limit} persons")
+ self.event_name = event_name
+ self.limit = limit
+
+
+def _render(sql: str, **extra: str) -> str:
+ return sql.format(overrides_join=_OVERRIDES_JOIN, resolved_person=_RESOLVED_PERSON, **extra)
+
+
+def load_leaf_members(team_id: int, leaf: OracleLeaf, *, at: datetime, tz: ZoneInfo, limit: int) -> set[str]:
+ """Persons matching one leaf's ``count >= 1 AND op(count)`` predicate over its whole-day window.
+
+ The whole set is materialized in memory, so it is capped: a broad event over a long window can
+ match tens of millions of persons, which the driver would buffer and the Python set would not
+ survive. Exceeding ``limit`` raises :class:`OracleSetTooLarge` rather than silently truncating.
+ """
+ tag_queries(product=ProductKey.COHORTS, feature=Feature.COHORT)
+ rows = sync_execute(
+ _render(_MEMBER_SET_SQL, op=_OP_SQL[leaf.op]),
+ {
+ "team_id": team_id,
+ "event_name": leaf.event_name,
+ "window_start": window_start_utc(at, leaf.window_days, tz),
+ "at": at,
+ "op_value": leaf.op_value,
+ "limit": limit + 1,
+ },
+ settings=_MEMBER_SET_SETTINGS,
+ workload=Workload.OFFLINE,
+ team_id=team_id,
+ )
+ if len(rows) > limit:
+ raise OracleSetTooLarge(leaf.event_name, limit)
+ return {str(row[0]).lower() for row in rows}
+
+
+def load_leaf_match_counts(
+ team_id: int,
+ leaf: OracleLeaf,
+ *,
+ person_ids: Sequence[str],
+ at: datetime,
+ tz: ZoneInfo,
+ extra_days: int,
+) -> dict[str, int]:
+ """Per-person match counts for one leaf over its window slid back ``extra_days``.
+
+ Feeds the over-count eviction split: a person still satisfying every leaf's predicate under the
+ just-slid-out window is due for eviction but not yet swept, not over-included.
+ """
+ if not person_ids:
+ return {}
+ tag_queries(product=ProductKey.COHORTS, feature=Feature.COHORT)
+ sql = _render(_LEAF_COUNTS_SQL)
+ window_start = window_start_utc(at, leaf.window_days + extra_days, tz)
+ counts: dict[str, int] = {}
+ for chunk in _chunks(person_ids):
+ rows = sync_execute(
+ sql,
+ {
+ "team_id": team_id,
+ "event_name": leaf.event_name,
+ "window_start": window_start,
+ "at": at,
+ "person_ids": chunk,
+ },
+ settings=_TIMEOUT_SETTINGS,
+ workload=Workload.OFFLINE,
+ team_id=team_id,
+ )
+ for person_id, matches in rows:
+ counts[str(person_id).lower()] = int(matches)
+ return counts
+
+
+def load_day_counts(
+ team_id: int,
+ *,
+ event_name: str,
+ person_ids: Sequence[str],
+ scan_start: datetime,
+ at: datetime,
+ grace_start: datetime,
+ boundary_at: datetime,
+ team_tz: str,
+) -> dict[str, list[DayMatch]]:
+ """Per-(person, day, boundary-bucket) match counts over the missing set.
+
+ ``day`` is bucketed in the team tz — the only tz the processor ever uses for day boundaries
+ (``event_path.rs`` reads ``filters.timezone``), so the day set the oracle window covers and the
+ days attributed to seed chunks are the same days.
+ """
+ if not person_ids:
+ return {}
+ tag_queries(product=ProductKey.COHORTS, feature=Feature.COHORT)
+ sql = _render(_SEGMENTATION_SQL)
+ counts: dict[str, list[DayMatch]] = defaultdict(list)
+ for chunk in _chunks(person_ids):
+ rows = sync_execute(
+ sql,
+ {
+ "team_id": team_id,
+ "event_name": event_name,
+ "team_tz": team_tz,
+ "grace_start": grace_start,
+ "boundary_at": boundary_at,
+ "scan_start": scan_start,
+ "at": at,
+ "person_ids": chunk,
+ },
+ settings=_TIMEOUT_SETTINGS,
+ workload=Workload.OFFLINE,
+ team_id=team_id,
+ )
+ for person_id, day, bucket, matches in rows:
+ counts[str(person_id).lower()].append(DayMatch(day=day, bucket=str(bucket), matches=int(matches)))
+ return dict(counts)
+
+
+def _chunks(person_ids: Sequence[str]) -> list[list[str]]:
+ ids = list(person_ids)
+ return [ids[start : start + _PERSON_ID_CHUNK] for start in range(0, len(ids), _PERSON_ID_CHUNK)]
+
+
+def run_with_boundary_exists(team_id: int, run_id: str) -> bool:
+ """Whether the team has a usable backfill run under this id, regardless of which cohorts it
+ covers. Lets a mistyped ``--run-id`` fail before the drain; per-cohort participation is
+ :func:`load_run_context`'s business."""
+ return CohortBackfillRun.objects.for_team(team_id).filter(id=run_id, boundary_at__isnull=False).exists()
+
+
+def load_run_context(team_id: int, cohort_id: int, run_id: Optional[str] = None) -> Optional[RunContext]:
+ """The backfill run the missing set is segmented against.
+
+ B5 is absent, so real runs stay ``seeding`` forever — deliberately no status filter. Accepts the
+ latest run the cohort participates in (or the explicit ``run_id``) with a set ``boundary_at``.
+ Returns ``None`` when there is no such run, including when an explicit ``run_id`` simply does not
+ cover this cohort — the caller decides whether that is a skip or an error.
+ """
+ runs = (
+ CohortBackfillRun.objects.for_team(team_id)
+ .filter(run_cohorts__cohort_id=cohort_id, boundary_at__isnull=False)
+ .order_by("-created_at")
+ .distinct()
+ )
+ run = runs.filter(id=run_id).first() if run_id else runs.first()
+ if run is None or run.boundary_at is None:
+ return None
+
+ # run_cohorts / chunks are fail-closed reverse relations, so query them through for_team rather
+ # than the run's default (team-scoped) manager, which raises outside a request/team context.
+ participation = CohortBackfillRunCohort.objects.for_team(team_id).filter(run_id=run.id, cohort_id=cohort_id).first()
+ participation_hash = participation.behavioral_filters_shape_hash if participation else ""
+ current_hash = (
+ Cohort.objects.filter(id=cohort_id, team_id=team_id)
+ .values_list("behavioral_filters_shape_hash", flat=True)
+ .first()
+ ) or ""
+
+ # A day is a confirmed seed domain only when all of its band chunks are CONFIRMED — a partially
+ # seeded day must not let a missing person be blamed on the seeder (a false FAIL).
+ chunks = CohortBackfillChunk.objects.for_team(team_id).filter(run_id=run.id)
+ day_statuses: dict[date, set[str]] = defaultdict(set)
+ for day, status in chunks.values_list("day", "status"):
+ day_statuses[day].add(status)
+ confirmed_days = frozenset(
+ day for day, statuses in day_statuses.items() if statuses == {CohortBackfillChunkStatus.CONFIRMED}
+ )
+ non_confirmed = chunks.exclude(status=CohortBackfillChunkStatus.CONFIRMED).count()
+
+ run_tz = resolve_zoneinfo(run.timezone)
+ return RunContext(
+ run_id=str(run.id),
+ status=run.status,
+ boundary_at=run.boundary_at,
+ run_timezone=run.timezone,
+ boundary_day=day_of_instant(run.boundary_at, run_tz),
+ confirmed_days=confirmed_days,
+ non_confirmed_chunks=non_confirmed,
+ shape_hash_drift=participation_hash != current_hash,
+ )
diff --git a/products/cohorts/backend/parity/recompute.py b/products/cohorts/backend/parity/recompute.py
new file mode 100644
index 000000000000..c6ba87c559c5
--- /dev/null
+++ b/products/cohorts/backend/parity/recompute.py
@@ -0,0 +1,741 @@
+"""Recompute-oracle support screen, tree composition, and backfill-aware classification.
+
+The ``--oracle recompute`` mode compares the folded shadow topic (``members(fold)``) against a
+membership set recomputed from ``events`` with evaluator semantics (the "oracle"), instead of the
+old-pipeline ``cohort_membership`` table the R-FRESH/R-STALE classifier uses. This module holds the
+pure logic: which cohorts the oracle can reproduce, how leaf member-sets fold into a tree, and how
+the fold-vs-oracle diff is segmented by backfill day-domain.
+
+Oracle semantics are pinned to the Rust reference so the recompute matches what the processor emits:
+
+- Leaf identity = the full ``BehavioralLeafKey`` tuple, not ``conditionHash``: the hash digests only
+ the event matcher, so leaves differing in window or operator share it
+ (``rust/cohort-core/src/leaf_state/key.rs``).
+- Window = INCLUSIVE ``[at_day - N .. at_day]`` in team tz = ``N + 1`` day-buckets
+ (``rust/cohort-core/src/bucket_tz.rs``, via :mod:`.tzdates`).
+- Membership floor = ``count >= 1 AND op(count)`` — zero-event persons are never members, even under
+ ``lte``/``lt``/``eq 0`` (``rust/cohort-stream-processor/src/stage1/predicate.rs``).
+- Operator mapping mirrors ``select.rs`` ``PredicateOp::from_leaf`` (``gte``/``lte``/``gt``/``lt`` else
+ ``eq``; ``operator_value`` clamped ``>= 0``); ``performed_event`` ≡ ``Gte(1)``.
+- Tree composition = AND/OR fold with per-leaf ``bit ^ negated``, absent leaf = ``false``
+ (``rust/cohort-stream-processor/src/stage2/evaluator.rs``).
+
+MVP scope: ``performed_event`` / ``performed_event_multiple`` leaves with a string event key, no
+``event_filters`` (property matching is HogVM bytecode, not reproducible in SQL), and whole-day
+sliding windows within ``max_window_days``. Anything else SKIPs with a specific reason. Tree
+composition over supported leaves is in scope (cheap set algebra); the under-count segmentation
+additionally needs a single leaf, a monotone operator, and a run boundary the grace window does not
+reach back over (see :func:`segmentation_blocker`).
+
+Pure — no ClickHouse, no Kafka, no Django. The ClickHouse member-set / segmentation reads and the
+Django run-context load live in :mod:`.oracle`.
+"""
+
+from __future__ import annotations
+
+import operator
+from collections import defaultdict
+from collections.abc import Callable, Mapping, Sequence
+from dataclasses import dataclass, field
+from datetime import date, datetime, timedelta
+from typing import Any, Optional, Union
+from zoneinfo import ZoneInfo
+
+from products.cohorts.backend.models.leaf_shape import BehavioralLeafKey, behavioral_leaf_key
+from products.cohorts.backend.parity.classifier import VERDICT_FAIL, VERDICT_PASS, VERDICT_SKIP
+from products.cohorts.backend.parity.eligibility import explain_unsupported_window, resolve_behavioral_window
+from products.cohorts.backend.parity.fold import MembershipRecord, ReconcileRunCompleteness, members
+from products.cohorts.backend.parity.tzdates import window_dates
+
+_I32_MIN = -(2**31)
+_I32_MAX = 2**31 - 1
+
+# op string -> Python comparator, for the ``count >= 1 AND op(count)`` membership predicate.
+_OP_EVAL: dict[str, Callable[[int, int], bool]] = {
+ "gte": operator.ge,
+ "lte": operator.le,
+ "gt": operator.gt,
+ "lt": operator.lt,
+ "eq": operator.eq,
+}
+# Monotone ops (membership only grows with event count) — the only ones whose missing set can be
+# segmented by day-domain. lte/lt/eq stay unsegmented (adding a day can flip membership either way).
+_MONOTONE_OPS = frozenset({"gte", "gt"})
+
+# Boundary buckets the segmentation query stamps per event (the remaining case is "pre_boundary").
+_POST_BOUNDARY = "post_boundary"
+_GRACE = "grace"
+
+# Person ids carried per class in the JSON so an operator can triage a gating class or override/merge
+# drift without re-deriving the diff. Bounded — the report is a summary, not a dump.
+SAMPLE_LIMIT = 20
+
+
+# ---------------------------------------------------------------------------
+# Spec: the recompute-supported shape of one cohort.
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class OracleLeaf:
+ """A recompute-reproducible behavioral leaf: one member-set ClickHouse query per leaf key."""
+
+ key: BehavioralLeafKey
+ event_name: str
+ op: str # gte | lte | gt | lt | eq (whitelist keys, never user text)
+ op_value: int # clamped >= 0
+ window_days: int # whole-day sliding window N (inclusive [at_day - N .. at_day])
+
+ @property
+ def monotone(self) -> bool:
+ return self.op in _MONOTONE_OPS
+
+
+@dataclass(frozen=True)
+class _TreeLeaf:
+ key: BehavioralLeafKey
+ negated: bool
+
+
+@dataclass(frozen=True)
+class _TreeGroup:
+ op: str # AND | OR
+ children: tuple[_TreeNode, ...]
+
+
+_TreeNode = Union[_TreeGroup, _TreeLeaf]
+
+
+@dataclass(frozen=True)
+class RecomputeSpec:
+ cohort_id: int
+ root: _TreeNode
+ leaves: Mapping[BehavioralLeafKey, OracleLeaf] # deduped by leaf key
+ single_leaf: bool # exactly one distinct leaf → the missing set is segmentable per day-domain
+
+ @property
+ def sole_leaf(self) -> OracleLeaf:
+ if not self.single_leaf:
+ raise ValueError("sole_leaf is only defined for a single-leaf spec")
+ return next(iter(self.leaves.values()))
+
+
+@dataclass(frozen=True)
+class RecomputeUnsupported:
+ reason: str
+
+
+# ---------------------------------------------------------------------------
+# Support screen.
+# ---------------------------------------------------------------------------
+
+
+def _clamp_op_value(raw: Any) -> int:
+ """``operator_value`` -> clamped ``u32``, mirroring select.rs ``operator_value.unwrap_or(0).max(0)``.
+
+ Non-i32 JSON (bool, float, numeric string, out-of-range) reads as absent (serde ``as_i64`` into
+ ``i32``) and clamps to 0.
+ """
+ if isinstance(raw, bool) or not isinstance(raw, int):
+ return 0
+ if not (_I32_MIN <= raw <= _I32_MAX):
+ return 0
+ return max(raw, 0)
+
+
+def _resolve_op(value: str, raw_operator: Any, raw_operator_value: Any) -> tuple[str, int]:
+ """(op, op_value) for a leaf. ``performed_event`` ≡ ``Gte(1)``; multiple maps its comparator."""
+ if value == "performed_event":
+ return "gte", 1
+ op = raw_operator if raw_operator in ("gte", "lte", "gt", "lt") else "eq"
+ return op, _clamp_op_value(raw_operator_value)
+
+
+def _leaf_key(source: Mapping[str, Any], *, condition_hash: str) -> BehavioralLeafKey:
+ """Build the leaf key from a raw filter node or a pinned condition row (same field names bar the
+ condition hash, which each side spells differently)."""
+ return behavioral_leaf_key(
+ condition_hash=condition_hash,
+ value=source.get("value"),
+ time_value=source.get("time_value"),
+ time_interval=source.get("time_interval"),
+ explicit_datetime=source.get("explicit_datetime"),
+ explicit_datetime_to=source.get("explicit_datetime_to"),
+ operator=source.get("operator"),
+ operator_value=source.get("operator_value"),
+ )
+
+
+class _ScreenCtx:
+ def __init__(self, pinned_by_key: Mapping[BehavioralLeafKey, Mapping[str, Any]], max_window_days: int) -> None:
+ self.pinned = pinned_by_key
+ self.max_window_days = max_window_days
+ self.leaves: dict[BehavioralLeafKey, OracleLeaf] = {}
+ self.unsupported: Optional[str] = None
+
+ def fail(self, reason: str) -> None:
+ # Keep the first reason encountered (deterministic, left-to-right tree order).
+ if self.unsupported is None:
+ self.unsupported = reason
+
+
+def _parse_behavioral_leaf(node: Mapping[str, Any], ctx: _ScreenCtx) -> Optional[_TreeLeaf]:
+ condition_hash = node.get("conditionHash")
+ if not isinstance(condition_hash, str) or not condition_hash:
+ ctx.fail("parse_error")
+ return None
+ key = _leaf_key(node, condition_hash=condition_hash)
+ pinned = ctx.pinned.get(key)
+ if pinned is None:
+ ctx.fail("parse_error")
+ return None
+ # Property matching is HogVM bytecode; the SQL member-set query cannot reproduce it.
+ if node.get("event_filters"):
+ ctx.fail("has_event_property_filters")
+ return None
+ if pinned.get("is_action"):
+ ctx.fail("action_leaf")
+ return None
+ value = pinned.get("value")
+ if value not in ("performed_event", "performed_event_multiple"):
+ ctx.fail("sequence_or_lifecycle_value")
+ return None
+ event_name = pinned.get("event_name")
+ if not isinstance(event_name, str) or not event_name:
+ ctx.fail("action_leaf")
+ return None
+ window = resolve_behavioral_window(pinned)
+ if window is None:
+ ctx.fail(explain_unsupported_window(pinned))
+ return None
+ if value == "performed_event_multiple":
+ # select.rs: `effective_window_days == 0` (sub-day, or any explicit shape but a relative
+ # lower bound) is HourlyDeferred — no realtime state at all, so the oracle must not
+ # over-count a whole calendar day for it.
+ if window.kind != "days" or window.days < 1:
+ ctx.fail("hourly_deferred")
+ return None
+ elif window.kind == "seconds":
+ ctx.fail("sub_day_window")
+ return None
+ elif window.kind == "explicit":
+ ctx.fail("absolute_explicit_range")
+ return None
+ window_days = int(window.days)
+ # Rust treats an astronomical window as "never evicts"; the oracle would have to scan `events`
+ # over it, so screen instead of driving an unbounded read.
+ if window_days > ctx.max_window_days:
+ ctx.fail("window_exceeds_max_days")
+ return None
+ op, op_value = _resolve_op(value, pinned.get("operator"), pinned.get("operator_value"))
+ ctx.leaves[key] = OracleLeaf(
+ key=key,
+ event_name=event_name,
+ op=op,
+ op_value=op_value,
+ window_days=window_days,
+ )
+ return _TreeLeaf(key=key, negated=node.get("negation") is True)
+
+
+def _parse_node(node: Any, ctx: _ScreenCtx) -> Optional[_TreeNode]:
+ if ctx.unsupported is not None:
+ return None
+ if not isinstance(node, Mapping):
+ ctx.fail("parse_error")
+ return None
+ node_type = node.get("type")
+ if node_type in ("AND", "OR") and isinstance(node.get("values"), list):
+ children = tuple(c for c in (_parse_node(child, ctx) for child in node["values"]) if c is not None)
+ return _TreeGroup(op=node_type, children=children)
+ if node_type == "behavioral":
+ return _parse_behavioral_leaf(node, ctx)
+ if node_type == "person":
+ ctx.fail("person_property_leaf")
+ return None
+ if node_type == "cohort":
+ ctx.fail("cohort_ref_leaf")
+ return None
+ ctx.fail("parse_error")
+ return None
+
+
+def screen_for_recompute(
+ cohort_id: int,
+ filters: Any,
+ pinned_conditions: Sequence[Mapping[str, Any]],
+ *,
+ max_window_days: int,
+) -> Union[RecomputeSpec, RecomputeUnsupported]:
+ """Decide whether the oracle can reproduce this cohort, and build its :class:`RecomputeSpec`.
+
+ ``filters`` is the current ``Cohort.filters`` (the fold reflects current definitions, so the
+ oracle must too — never the run's frozen ``pinned``). ``pinned_conditions`` is
+ ``pin_conditions_for_cohorts([cohort])`` output, joined on the full :class:`BehavioralLeafKey`
+ for the seeder-parity event-name / action resolution; the raw tree walk supplies structure,
+ negation, and ``event_filters`` presence. Assumes the cohort already passed the emit-eligibility
+ screen (so the tree is non-top-level-negated and ref-free at the group level).
+ """
+ if not isinstance(filters, Mapping) or "properties" not in filters:
+ return RecomputeUnsupported("parse_error")
+ pinned_by_key = {
+ _leaf_key(c, condition_hash=c["condition_hash"]): c for c in pinned_conditions if c.get("condition_hash")
+ }
+ ctx = _ScreenCtx(pinned_by_key, max_window_days)
+ root = _parse_node(filters["properties"], ctx)
+ if ctx.unsupported is not None:
+ return RecomputeUnsupported(ctx.unsupported)
+ if root is None or not ctx.leaves:
+ return RecomputeUnsupported("parse_error")
+ return RecomputeSpec(
+ cohort_id=cohort_id,
+ root=root,
+ leaves=dict(ctx.leaves),
+ single_leaf=len(ctx.leaves) == 1,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Tree evaluation and oracle member-set composition.
+# ---------------------------------------------------------------------------
+
+
+def evaluate_tree(node: _TreeNode, leaf_bits: Mapping[BehavioralLeafKey, bool]) -> bool:
+ """Fold the tree to one membership bit. Mirror of evaluator.rs ``evaluate_tree``: absent leaf =
+ ``false``, then ``bit ^ negated``; empty AND = ``true``, empty OR = ``false``."""
+ if isinstance(node, _TreeGroup):
+ if node.op == "AND":
+ return all(evaluate_tree(child, leaf_bits) for child in node.children)
+ return any(evaluate_tree(child, leaf_bits) for child in node.children)
+ return leaf_bits.get(node.key, False) ^ node.negated
+
+
+def compute_oracle_members(
+ spec: RecomputeSpec,
+ leaf_members: Mapping[BehavioralLeafKey, set[str]],
+) -> set[str]:
+ """The oracle's member set: compose per-leaf member sets through the tree.
+
+ A member must satisfy ``>= 1`` positive leaf (the all-absent evaluation is ``false`` for
+ emit-eligible non-negated trees — evaluator.rs ``all_absent_invariant``), so the candidate
+ universe is the union of the leaf member-sets; anyone outside it composes to ``false``.
+ """
+ if not leaf_members:
+ return set()
+ universe: set[str] = set().union(*leaf_members.values())
+ result: set[str] = set()
+ for person in universe:
+ bits = {key: (person in ids) for key, ids in leaf_members.items()}
+ if evaluate_tree(spec.root, bits):
+ result.add(person)
+ return result
+
+
+# ---------------------------------------------------------------------------
+# Backfill run context + per-day segmentation input.
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class RunContext:
+ """The backfill run the missing set is segmented against (loaded by :mod:`.oracle`)."""
+
+ run_id: str
+ status: str
+ boundary_at: datetime
+ run_timezone: str
+ boundary_day: date # day_of_instant(boundary_at, run tz)
+ confirmed_days: frozenset[date] # days whose seed chunks are all CONFIRMED (fully seeded)
+ non_confirmed_chunks: int
+ shape_hash_drift: bool # run's pinned behavioral shape hash != current cohort's
+
+
+@dataclass(frozen=True)
+class DayMatch:
+ """One (person, team-tz day, boundary-bucket) match count from the segmentation query."""
+
+ day: date
+ bucket: str # pre_boundary | post_boundary | grace
+ matches: int
+
+
+# person_id -> their per-(day, bucket) match counts, over the missing set.
+PersonDayCounts = Mapping[str, Sequence[DayMatch]]
+# leaf key -> {person_id: match count over the leaf's window slid back one day}, over the false set.
+ExtendedLeafCounts = Mapping[BehavioralLeafKey, Mapping[str, int]]
+
+
+# ---------------------------------------------------------------------------
+# Classification / segmentation / expiry.
+# ---------------------------------------------------------------------------
+
+
+def _member(count: int, op: str, op_value: int) -> bool:
+ """The parity floor: zero matches is never a member, even under lte/lt/eq 0 (predicate.rs)."""
+ return count >= 1 and _OP_EVAL[op](count, op_value)
+
+
+def _min_count(op: str, op_value: int) -> int:
+ """Smallest window count that satisfies a monotone op's membership floor."""
+ if op == "gte":
+ return max(1, op_value)
+ if op == "gt":
+ return max(1, op_value + 1)
+ raise ValueError(f"non-monotone op {op!r} has no membership threshold")
+
+
+def _sample(ids: Sequence[str]) -> tuple[str, ...]:
+ return tuple(sorted(ids)[:SAMPLE_LIMIT])
+
+
+@dataclass(frozen=True)
+class RecomputeComparison:
+ cohort_id: int
+ name: str
+ supported: bool
+ verdict: str
+ skip_reason: str = ""
+ fold_count: int = 0
+ oracle_count: int = 0
+ both: int = 0
+ false_members: int = 0 # members(fold) - oracle (over-count; hard invariant)
+ false_hard: int = 0 # false_members not explained by sweep lag
+ eviction_pending: int = 0 # sweep lag: still a member one day back, or entered within grace
+ missing: int = 0 # oracle - members(fold) (under-count)
+ missing_grace: int = 0
+ missing_seed_domain: int = 0 # qualified by confirmed seed days alone — gates FAIL
+ missing_boundary_day: int = 0 # needs boundary-day pre-boundary events — the decaying gap
+ missing_unseeded_day: int = 0 # needs a pre-boundary window day with no confirmed chunk — FAIL
+ missing_post_boundary: int = 0 # needs post-boundary events the live path owns — gates FAIL
+ missing_unsegmented: int = 0 # shape or grace window admits no segmentation — not adjudicated
+ missing_unattributed: int = 0 # in the member set but absent from the day read — reads disagree
+ expires_by_day: Mapping[str, int] = field(default_factory=dict) # boundary-class decay prediction
+ samples: Mapping[str, tuple[str, ...]] = field(default_factory=dict) # bounded person ids per class
+ run_id: Optional[str] = None
+ run_status: Optional[str] = None
+ boundary_at: Optional[str] = None
+ boundary_day: Optional[str] = None
+ run_timezone: Optional[str] = None
+ chunk_days_confirmed: int = 0
+ shape_hash_drift: bool = False
+ reconcile_runs: tuple[ReconcileRunCompleteness, ...] = ()
+ notes: tuple[str, ...] = ()
+
+
+def skip_comparison(
+ *,
+ cohort_id: int,
+ name: str,
+ reason: str,
+ reconcile_runs: Sequence[ReconcileRunCompleteness] = (),
+ notes: Sequence[str] = (),
+) -> RecomputeComparison:
+ return RecomputeComparison(
+ cohort_id=cohort_id,
+ name=name,
+ supported=False,
+ verdict=VERDICT_SKIP,
+ skip_reason=reason,
+ reconcile_runs=tuple(reconcile_runs),
+ notes=(*notes, f"unsupported by recompute oracle: {reason}"),
+ )
+
+
+def _person_day_totals(matches: Sequence[DayMatch]) -> dict[tuple[date, str], int]:
+ totals: dict[tuple[date, str], int] = defaultdict(int)
+ for match in matches:
+ totals[(match.day, match.bucket)] += match.matches
+ return totals
+
+
+def _domain_counts(
+ matches: Sequence[DayMatch],
+ *,
+ window: frozenset[date],
+ ctx: RunContext,
+) -> tuple[int, int, int, int, int]:
+ """(grace, seed, boundary, unseeded, post) in-window match counts for one person.
+
+ ``seed`` / ``boundary`` / ``unseeded`` partition the pre-boundary window days: boundary-day first
+ (the seed/live handoff day, even if a chunk exists for it), then confirmed-seed days, then the
+ rest (window days with no confirmed chunk). The scan and the window share one tz and one range,
+ so the out-of-window skip is defensive only — a dropped in-window match would understate the
+ total and misfile the person as lag noise.
+ """
+ grace = seed = boundary = unseeded = post = 0
+ for (day, bucket), count in _person_day_totals(matches).items():
+ if day not in window:
+ continue
+ if bucket == _GRACE:
+ grace += count
+ elif bucket == _POST_BOUNDARY:
+ post += count
+ elif day == ctx.boundary_day:
+ boundary += count
+ elif day in ctx.confirmed_days:
+ seed += count
+ else:
+ unseeded += count
+ return grace, seed, boundary, unseeded, post
+
+
+def _classify_missing_person(
+ matches: Sequence[DayMatch],
+ *,
+ window: frozenset[date],
+ ctx: RunContext,
+ min_count: int,
+) -> str:
+ """Assign a missing (oracle - fold) person to a day-domain class. A person with no in-window
+ matches at all is unattributed; otherwise precedence runs grace ≻ seed ≻ boundary ≻ unseeded ≻
+ post: the highest-precedence domain whose cumulative count crosses the membership threshold. The
+ classes are exhaustive — the final fall-through implies ``post > 0``, since the three preceding
+ sums were all below the threshold the total clears."""
+ grace, seed, boundary, unseeded, post = _domain_counts(matches, window=window, ctx=ctx)
+ if grace + seed + boundary + unseeded + post == 0:
+ # The member-set read put this person in the oracle, so the day read over the same event and
+ # window has to find their matches. Zero means the two reads disagree — override/merge drift
+ # between them, or a dropped chunk — which is not the ingestion lag `grace` stands for.
+ return "missing_unattributed"
+ if seed + boundary + unseeded + post < min_count:
+ return "missing_grace" # crossing depends on the last grace-minutes — lag noise
+ if seed >= min_count:
+ return "missing_seed_domain" # confirmed seed days alone qualify — unexpected, gates FAIL
+ if seed + boundary >= min_count:
+ return "missing_boundary_day" # needs boundary-day pre-boundary events — decaying gap
+ if seed + boundary + unseeded >= min_count:
+ return "missing_unseeded_day" # needs an unseeded pre-boundary window day — gates FAIL
+ return "missing_post_boundary" # needs post-boundary events the live path owns — gates FAIL
+
+
+def _expiry_date(
+ matches: Sequence[DayMatch], *, window: frozenset[date], window_days: int, min_count: int
+) -> Optional[date]:
+ """The smallest future date at which this person's window count drops below ``min_count`` absent
+ new events: the day the oldest still-needed match ages out, ``+ window_days + 1``. ``None`` when
+ no in-window match explains the membership, which leaves nothing to age out."""
+ per_day: dict[date, int] = defaultdict(int)
+ for match in matches:
+ if match.day in window:
+ per_day[match.day] += match.matches
+ if not per_day:
+ return None
+ accumulated = 0
+ critical_day = min(per_day)
+ for day in sorted(per_day, reverse=True): # newest first
+ accumulated += per_day[day]
+ if accumulated >= min_count:
+ critical_day = day
+ break
+ return critical_day + timedelta(days=window_days + 1)
+
+
+def segmentation_blocker(
+ spec: RecomputeSpec,
+ ctx: Optional[RunContext],
+ *,
+ at: datetime,
+ grace: timedelta,
+) -> Optional[str]:
+ """Why the missing set cannot be segmented by day-domain, or ``None`` when it can.
+
+ One formula, shared by the caller deciding whether the per-day read is worth issuing and by
+ :func:`classify_recompute` deciding whether the counts can be trusted. Re-deriving it on either
+ side drifts, and the two failure directions are both silent: a caller that reads when this says
+ no wastes a scan, one that skips when this says yes scores the diff against evidence it never
+ gathered.
+ """
+ if not spec.single_leaf:
+ return "multi-leaf cohort: day-domain segmentation unavailable"
+ leaf = spec.sole_leaf
+ if not leaf.monotone:
+ return f"non-monotone op {leaf.op!r}: missing set left unsegmented (membership parity only)"
+ if ctx is None:
+ return "no backfill run with a boundary; missing set left unsegmented"
+ grace_start = at - grace
+ if grace_start < ctx.boundary_at:
+ # The segmentation query stamps `grace` ahead of both boundary buckets, so a grace window
+ # reaching back over the boundary would bucket real seed-day matches as lag noise and let a
+ # seeder drop report PASS.
+ return (
+ f"grace window opens {grace_start.isoformat()}, before the run boundary "
+ f"{ctx.boundary_at.isoformat()}: pre-boundary matches would read as lag noise, so the "
+ "missing set is left unsegmented (lower --grace-minutes)"
+ )
+ return None
+
+
+def classify_recompute(
+ *,
+ spec: RecomputeSpec,
+ name: str,
+ fold_records: Mapping[str, MembershipRecord],
+ oracle_members: set[str],
+ day_counts: PersonDayCounts,
+ extended_leaf_counts: ExtendedLeafCounts,
+ ctx: Optional[RunContext],
+ at: datetime,
+ grace: timedelta,
+ team_tz: ZoneInfo,
+ day_counts_loaded: bool = True,
+ reconcile_runs: Sequence[ReconcileRunCompleteness] = (),
+ extra_notes: Sequence[str] = (),
+) -> RecomputeComparison:
+ fold_members = members(fold_records)
+ both = fold_members & oracle_members
+ false_set = fold_members - oracle_members
+ missing_set = oracle_members - fold_members
+ notes = list(extra_notes)
+
+ counts = {
+ "missing_grace": 0,
+ "missing_seed_domain": 0,
+ "missing_boundary_day": 0,
+ "missing_unseeded_day": 0,
+ "missing_post_boundary": 0,
+ "missing_unsegmented": 0,
+ "missing_unattributed": 0,
+ }
+ per_class: dict[str, list[str]] = defaultdict(list)
+ expires_by_day: dict[str, int] = defaultdict(int)
+
+ # Over-count split. A false member is sweep lag, not over-inclusion, when either
+ # (a) the tree still evaluates true once every leaf window is slid back one day — the person is
+ # due for eviction but the tz-midnight sweep has not caught up; or
+ # (b) they entered within the grace window — the processor enters on the event and only leaves
+ # on a sweep tick, so a just-ingested historical event legitimately shows as a member
+ # (`event_path.rs` sets has_match on any match; only the sweep clears it).
+ entered_after = at - grace
+ eviction_pending: set[str] = set()
+ for person in false_set:
+ if fold_records[person].last_updated >= entered_after:
+ eviction_pending.add(person)
+ continue
+ if not extended_leaf_counts:
+ continue # slid-back counts were not loaded (the caller says why); score the person hard
+ extended_bits = {
+ key: _member(extended_leaf_counts.get(key, {}).get(person, 0), leaf.op, leaf.op_value)
+ for key, leaf in spec.leaves.items()
+ }
+ if evaluate_tree(spec.root, extended_bits):
+ eviction_pending.add(person)
+
+ # Under-count segmentation. The caller only reports whether it managed to load the per-person day
+ # counts; whether the shape admits segmentation at all is `segmentation_blocker`'s call.
+ blocker = segmentation_blocker(spec, ctx, at=at, grace=grace)
+ if blocker is None and day_counts_loaded:
+ assert ctx is not None # segmentation_blocker rejects a missing run context
+ leaf = spec.sole_leaf
+ window = frozenset(window_dates(at, leaf.window_days, team_tz))
+ min_count = _min_count(leaf.op, leaf.op_value)
+ for person in missing_set:
+ matches = day_counts.get(person, ())
+ bucket = _classify_missing_person(matches, window=window, ctx=ctx, min_count=min_count)
+ counts[bucket] += 1
+ per_class[bucket].append(person)
+ if bucket == "missing_boundary_day":
+ day = _expiry_date(matches, window=window, window_days=leaf.window_days, min_count=min_count)
+ if day is not None:
+ expires_by_day[day.isoformat()] += 1
+ else:
+ counts["missing_unsegmented"] = len(missing_set)
+ per_class["missing_unsegmented"] = list(missing_set)
+ # A segmentable shape can only land here because the caller failed to load the counts, and it
+ # already recorded why in extra_notes.
+ if blocker is not None:
+ notes.append(blocker)
+
+ if counts["missing_unsegmented"]:
+ notes.append(f"{counts['missing_unsegmented']} missing person(s) unadjudicated; parity not established")
+ if counts["missing_unattributed"]:
+ notes.append(
+ f"{counts['missing_unattributed']} missing person(s) are in the oracle member set but have no "
+ "in-window day counts; the two oracle reads disagree (override drift between them?), so they are "
+ "not adjudicated"
+ )
+
+ false_hard_set = false_set - eviction_pending
+ gated_missing = counts["missing_seed_domain"] + counts["missing_unseeded_day"] + counts["missing_post_boundary"]
+ if false_hard_set or gated_missing:
+ verdict = VERDICT_FAIL
+ elif counts["missing_unsegmented"] or counts["missing_unattributed"]:
+ # Not a PASS: the over-count side is clean but part of the under-count was never adjudicated.
+ verdict = VERDICT_SKIP
+ else:
+ verdict = VERDICT_PASS
+
+ samples = {
+ "false_hard": _sample(list(false_hard_set)),
+ "eviction_pending": _sample(list(eviction_pending)),
+ **{cls: _sample(ids) for cls, ids in per_class.items()},
+ }
+
+ return RecomputeComparison(
+ cohort_id=spec.cohort_id,
+ name=name,
+ supported=True,
+ verdict=verdict,
+ fold_count=len(fold_members),
+ oracle_count=len(oracle_members),
+ both=len(both),
+ false_members=len(false_set),
+ false_hard=len(false_hard_set),
+ eviction_pending=len(eviction_pending),
+ missing=len(missing_set),
+ missing_grace=counts["missing_grace"],
+ missing_seed_domain=counts["missing_seed_domain"],
+ missing_boundary_day=counts["missing_boundary_day"],
+ missing_unseeded_day=counts["missing_unseeded_day"],
+ missing_post_boundary=counts["missing_post_boundary"],
+ missing_unsegmented=counts["missing_unsegmented"],
+ missing_unattributed=counts["missing_unattributed"],
+ expires_by_day=dict(sorted(expires_by_day.items())),
+ samples={cls: ids for cls, ids in sorted(samples.items()) if ids},
+ run_id=ctx.run_id if ctx else None,
+ run_status=ctx.status if ctx else None,
+ boundary_at=ctx.boundary_at.isoformat() if ctx else None,
+ boundary_day=ctx.boundary_day.isoformat() if ctx else None,
+ run_timezone=ctx.run_timezone if ctx else None,
+ chunk_days_confirmed=len(ctx.confirmed_days) if ctx else 0,
+ shape_hash_drift=ctx.shape_hash_drift if ctx else False,
+ reconcile_runs=tuple(reconcile_runs),
+ notes=tuple(notes),
+ )
+
+
+@dataclass
+class RecomputeSummary:
+ passed: int = 0
+ failed: int = 0
+ skipped: int = 0
+ false_hard_total: int = 0
+ eviction_pending_total: int = 0
+ missing_total: int = 0
+ seed_domain_total: int = 0
+ unseeded_total: int = 0
+ boundary_total: int = 0
+ post_boundary_total: int = 0
+ unsegmented_total: int = 0
+ unattributed_total: int = 0
+ warnings: list[str] = field(default_factory=list)
+
+
+def summarize_recompute(rows: Sequence[RecomputeComparison]) -> RecomputeSummary:
+ summary = RecomputeSummary()
+ for row in rows:
+ if row.verdict == VERDICT_PASS:
+ summary.passed += 1
+ elif row.verdict == VERDICT_FAIL:
+ summary.failed += 1
+ else:
+ summary.skipped += 1
+ summary.false_hard_total += row.false_hard
+ summary.eviction_pending_total += row.eviction_pending
+ summary.missing_total += row.missing
+ summary.seed_domain_total += row.missing_seed_domain
+ summary.unseeded_total += row.missing_unseeded_day
+ summary.boundary_total += row.missing_boundary_day
+ summary.post_boundary_total += row.missing_post_boundary
+ summary.unsegmented_total += row.missing_unsegmented
+ summary.unattributed_total += row.missing_unattributed
+ return summary
diff --git a/products/cohorts/backend/parity/report.py b/products/cohorts/backend/parity/report.py
index 020ada401f51..9a66207808b4 100644
--- a/products/cohorts/backend/parity/report.py
+++ b/products/cohorts/backend/parity/report.py
@@ -15,8 +15,10 @@ from products.cohorts.backend.parity.classifier import (
CohortComparison,
)
from products.cohorts.backend.parity.fold import ReconcileRunCompleteness
+from products.cohorts.backend.parity.recompute import RecomputeComparison, RecomputeSummary
_VERDICT_ORDER = {VERDICT_FAIL: 0, VERDICT_WARMUP: 1, VERDICT_PASS: 2, VERDICT_SKIP: 3}
+_RECOMPUTE_VERDICT_ORDER = {VERDICT_FAIL: 0, VERDICT_PASS: 1, VERDICT_SKIP: 2}
def _sorted_rows(rows: Sequence[CohortComparison]) -> list[CohortComparison]:
@@ -84,3 +86,84 @@ def to_json(
"summary": asdict(summary),
"cohorts": [asdict(r) for r in _sorted_rows(rows)],
}
+
+
+def _sorted_recompute_rows(rows: Sequence[RecomputeComparison]) -> list[RecomputeComparison]:
+ return sorted(rows, key=lambda r: (_RECOMPUTE_VERDICT_ORDER.get(r.verdict, 9), -r.false_hard, r.cohort_id))
+
+
+_RECOMPUTE_LABEL_WIDTH = 32
+_RECOMPUTE_VERDICT_WIDTH = 7
+_RECOMPUTE_HEADER = (
+ f"{'cohort':<{_RECOMPUTE_LABEL_WIDTH}} {'fold':>8} {'oracle':>8} {'both':>8} {'false':>7} {'hard':>6} "
+ f"{'evict':>6} {'miss':>7} {'grace':>6} {'seed':>6} {'bdry':>6} {'unseed':>6} {'post':>6} "
+ f"{'verdict':>{_RECOMPUTE_VERDICT_WIDTH}}"
+)
+# A screen-skipped row spends every numeric column on the reason, so the line still aligns.
+_RECOMPUTE_SKIP_WIDTH = len(_RECOMPUTE_HEADER) - _RECOMPUTE_LABEL_WIDTH - _RECOMPUTE_VERDICT_WIDTH - 2
+
+
+def format_recompute_table(rows: Sequence[RecomputeComparison]) -> str:
+ lines = [_RECOMPUTE_HEADER, "-" * len(_RECOMPUTE_HEADER)]
+ for r in _sorted_recompute_rows(rows):
+ label = f"{r.cohort_id} {r.name}"
+ if len(label) > _RECOMPUTE_LABEL_WIDTH - 1:
+ label = label[: _RECOMPUTE_LABEL_WIDTH - 4] + "..."
+ if not r.supported:
+ reason = f"SKIP: {r.skip_reason}"[:_RECOMPUTE_SKIP_WIDTH]
+ lines.append(
+ f"{label:<{_RECOMPUTE_LABEL_WIDTH}} {reason:<{_RECOMPUTE_SKIP_WIDTH}} "
+ f"{r.verdict:>{_RECOMPUTE_VERDICT_WIDTH}}"
+ )
+ continue
+ lines.append(
+ f"{label:<{_RECOMPUTE_LABEL_WIDTH}} {r.fold_count:>8} {r.oracle_count:>8} {r.both:>8} "
+ f"{r.false_members:>7} {r.false_hard:>6} {r.eviction_pending:>6} {r.missing:>7} {r.missing_grace:>6} "
+ f"{r.missing_seed_domain:>6} {r.missing_boundary_day:>6} {r.missing_unseeded_day:>6} "
+ f"{r.missing_post_boundary:>6} {r.verdict:>{_RECOMPUTE_VERDICT_WIDTH}}"
+ )
+ return "\n".join(lines)
+
+
+def format_recompute_notes(rows: Sequence[RecomputeComparison]) -> str:
+ lines = []
+ for r in _sorted_recompute_rows(rows):
+ for run in sorted(r.reconcile_runs, key=lambda item: item.run_id):
+ state = (
+ f"{run.partitions_seen}/{run.expected_partitions}"
+ if run.complete
+ else (f"partial {run.partitions_seen}/{run.expected_partitions}")
+ )
+ lines.append(f" cohort {r.cohort_id}: reconcile run {run.run_id}: {state}")
+ for note in r.notes:
+ lines.append(f" cohort {r.cohort_id}: {note}")
+ if r.expires_by_day:
+ summary = ", ".join(f"{day}: {count}" for day, count in r.expires_by_day.items())
+ lines.append(f" cohort {r.cohort_id}: boundary-day gap expires — {summary}")
+ return "\n".join(lines)
+
+
+def format_recompute_summary(summary: RecomputeSummary) -> str:
+ lines = [
+ f"verdicts: {summary.passed} PASS, {summary.failed} FAIL, {summary.skipped} SKIP",
+ f"over-count: false_hard={summary.false_hard_total} (eviction_pending={summary.eviction_pending_total}); "
+ f"under-count: missing={summary.missing_total} (seed_domain={summary.seed_domain_total}, "
+ f"unseeded={summary.unseeded_total}, post_boundary={summary.post_boundary_total}, "
+ f"boundary={summary.boundary_total}, unsegmented={summary.unsegmented_total}, "
+ f"unattributed={summary.unattributed_total})",
+ ]
+ for warning in summary.warnings:
+ lines.append(f"WARNING: {warning}")
+ return "\n".join(lines)
+
+
+def to_recompute_json(
+ rows: Sequence[RecomputeComparison],
+ summary: RecomputeSummary,
+ meta: Mapping[str, Any],
+) -> dict[str, Any]:
+ return {
+ "meta": dict(meta),
+ "summary": asdict(summary),
+ "cohorts": [asdict(r) for r in _sorted_recompute_rows(rows)],
+ }
diff --git a/products/cohorts/backend/parity/test/test_command_warnings.py b/products/cohorts/backend/parity/test/test_command_warnings.py
index eaaf2555dc40..1716728d137d 100644
--- a/products/cohorts/backend/parity/test/test_command_warnings.py
+++ b/products/cohorts/backend/parity/test/test_command_warnings.py
@@ -1,9 +1,20 @@
-from datetime import UTC, datetime, timedelta
+from datetime import UTC, date, datetime, timedelta
+from typing import Any
+from django.core.management.base import CommandError
from django.test import SimpleTestCase
-from products.cohorts.backend.management.commands.compare_cohort_membership import _collect_warnings
+from parameterized import parameterized
+
+from products.cohorts.backend.management.commands.compare_cohort_membership import (
+ DEFAULT_THRESHOLD_PCT,
+ RecomputeCohortState,
+ _collect_recompute_warnings,
+ _collect_warnings,
+ _reject_flags,
+)
from products.cohorts.backend.parity.kafka_io import DrainStats
+from products.cohorts.backend.parity.recompute import RunContext
NOW = datetime(2026, 7, 8, 12, 0, tzinfo=UTC)
SINCE = NOW - timedelta(days=1)
@@ -47,3 +58,71 @@ class TestCollectWarnings(SimpleTestCase):
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))
+
+
+class TestRejectFlags(SimpleTestCase):
+ @parameterized.expand(
+ [
+ # Every mode-specific flag defaults to None precisely so a value that happens to equal the
+ # documented default is still rejected rather than silently ignored by the other oracle.
+ ("explicit_documented_default", {"threshold": DEFAULT_THRESHOLD_PCT}, True),
+ ("explicit_zero", {"warmup_sample": 0}, True),
+ ("store_true_set", {"no_classify": True}, True),
+ ("unset", {}, False),
+ ]
+ )
+ def test_explicit_values_are_rejected_even_when_they_match_the_default(
+ self, _name: str, overrides: dict, expect_error: bool
+ ) -> None:
+ options: dict[str, Any] = {"threshold": None, "warmup_sample": None, "no_classify": False, **overrides}
+ flags = ("threshold", "warmup_sample", "no_classify")
+ if not expect_error:
+ _reject_flags(options, flags, "recompute")
+ return
+ with self.assertRaises(CommandError):
+ _reject_flags(options, flags, "recompute")
+
+
+def _ctx(**overrides: Any) -> RunContext:
+ defaults: dict[str, Any] = {
+ "run_id": "r",
+ "status": "seeding",
+ "boundary_at": NOW - timedelta(hours=6),
+ "run_timezone": "US/Pacific",
+ "boundary_day": date(2026, 7, 8),
+ "confirmed_days": frozenset(),
+ "non_confirmed_chunks": 0,
+ "shape_hash_drift": False,
+ }
+ defaults.update(overrides)
+ return RunContext(**defaults)
+
+
+class TestCollectRecomputeWarnings(SimpleTestCase):
+ def test_clean_state_yields_no_warnings(self) -> None:
+ state = RecomputeCohortState(cohort_id=1, ctx=_ctx(run_timezone="US/Pacific"), has_complete_reconcile=True)
+ warnings = _collect_recompute_warnings(at=NOW, now=NOW, team_timezone="US/Pacific", states=[state])
+ self.assertEqual(warnings, [])
+
+ def test_stale_at_warns(self) -> None:
+ warnings = _collect_recompute_warnings(
+ at=NOW - timedelta(minutes=30), now=NOW, team_timezone="US/Pacific", states=[]
+ )
+ self.assertTrue(any("before now" in w for w in warnings))
+
+ def test_missing_run_context_warns(self) -> None:
+ state = RecomputeCohortState(cohort_id=5, ctx=None, has_complete_reconcile=True)
+ warnings = _collect_recompute_warnings(at=NOW, now=NOW, team_timezone="US/Pacific", states=[state])
+ self.assertTrue(any("no backfill run" in w and "cohort 5" in w for w in warnings))
+
+ def test_per_cohort_context_warnings(self) -> None:
+ state = RecomputeCohortState(
+ cohort_id=9,
+ ctx=_ctx(run_timezone="UTC", shape_hash_drift=True, non_confirmed_chunks=3),
+ has_complete_reconcile=False,
+ )
+ warnings = _collect_recompute_warnings(at=NOW, now=NOW, team_timezone="US/Pacific", states=[state])
+ self.assertTrue(any("run tz UTC != team tz US/Pacific" in w and "SKIPPED" in w for w in warnings))
+ self.assertTrue(any("shape-hash" in w for w in warnings))
+ self.assertTrue(any("3 seed chunk(s) not confirmed" in w for w in warnings))
+ self.assertTrue(any("no complete 64/64 reconcile" in w for w in warnings))
diff --git a/products/cohorts/backend/parity/test/test_fold.py b/products/cohorts/backend/parity/test/test_fold.py
index 0937437f50fc..c3fcba2d912b 100644
--- a/products/cohorts/backend/parity/test/test_fold.py
+++ b/products/cohorts/backend/parity/test/test_fold.py
@@ -107,6 +107,33 @@ class TestFold(SimpleTestCase):
self.assertEqual(members(state[10]), {"p2"})
self.assertEqual(stats.dropped_before_since, 1)
+ def test_until_bound_converges_the_fold_to_the_pinned_instant(self) -> None:
+ # A pinned comparison clock must see the state as of that instant: an entry stamped after it
+ # is invisible to the oracle's window and would otherwise read as an unexplained over-count,
+ # and a later `left` must not retroactively remove a person who was a member at the instant.
+ state, stats = fold_membership_changes(
+ [
+ _msg("entered", "2026-07-07 19:01:00.000001", person_id="P1"),
+ _msg("left", "2026-07-07 19:09:00.000001", person_id="P1"),
+ _msg("entered", "2026-07-07 19:09:00.000001", person_id="P2"),
+ ],
+ team_id=2,
+ since=SINCE,
+ until=datetime(2026, 7, 7, 19, 5, tzinfo=UTC),
+ )
+ self.assertEqual(members(state[10]), {"p1"})
+ self.assertEqual(stats.dropped_after_until, 2)
+
+ def test_until_bound_drops_later_reconcile_markers(self) -> None:
+ _state, stats = fold_membership_changes(
+ [_marker(0, ts="2026-07-07 19:01:00.000001"), _marker(1, ts="2026-07-07 19:09:00.000001")],
+ team_id=2,
+ since=SINCE,
+ until=datetime(2026, 7, 7, 19, 5, tzinfo=UTC),
+ )
+ self.assertEqual(reconcile_completeness(stats, 10)[0].partitions_seen, 1)
+ self.assertEqual(stats.dropped_after_until, 1)
+
def test_wrong_team_messages_are_dropped(self) -> None:
state, stats = fold_membership_changes(
[
diff --git a/products/cohorts/backend/parity/test/test_oracle_run_context.py b/products/cohorts/backend/parity/test/test_oracle_run_context.py
new file mode 100644
index 000000000000..331730127eb7
--- /dev/null
+++ b/products/cohorts/backend/parity/test/test_oracle_run_context.py
@@ -0,0 +1,132 @@
+from datetime import UTC, date, datetime
+
+from posthog.test.base import BaseTest
+
+from django.test import override_settings
+
+from products.cohorts.backend.models.backfill import (
+ CohortBackfillChunk,
+ CohortBackfillChunkStatus,
+ CohortBackfillKind,
+ CohortBackfillRun,
+ CohortBackfillRunCohort,
+ CohortBackfillRunStatus,
+ CohortBackfillScope,
+ CohortBackfillTrigger,
+)
+from products.cohorts.backend.models.cohort import Cohort, CohortType
+from products.cohorts.backend.parity.oracle import load_run_context
+
+_CONFIRMED = CohortBackfillChunkStatus.CONFIRMED
+_PENDING = CohortBackfillChunkStatus.PENDING
+
+
+# Allowlist "none" so creating a realtime cohort does not auto-enqueue a backfill run that would
+# collide with the runs each test builds by hand.
+@override_settings(REALTIME_COHORT_TEAM_ALLOWLIST="none")
+class TestLoadRunContext(BaseTest):
+ def _cohort(self) -> Cohort:
+ cohort = Cohort.objects.create(
+ team=self.team,
+ name="c",
+ cohort_type=CohortType.REALTIME,
+ filters={
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "behavioral",
+ "key": "$pageview",
+ "event_type": "events",
+ "value": "performed_event",
+ "conditionHash": "hash",
+ "time_value": 7,
+ "time_interval": "day",
+ "bytecode": ["_H", 1],
+ }
+ ],
+ }
+ },
+ )
+ cohort.refresh_from_db()
+ return cohort
+
+ def _run(self, *, boundary_at: datetime | None, timezone: str = "UTC") -> CohortBackfillRun:
+ return CohortBackfillRun.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ backfill_kind=CohortBackfillKind.BEHAVIORAL,
+ trigger_kind=CohortBackfillTrigger.TEAM_ENABLEMENT,
+ scope=CohortBackfillScope.TEAM,
+ status=CohortBackfillRunStatus.SEEDING,
+ timezone=timezone,
+ boundary_at=boundary_at,
+ pinned={},
+ preconditions={},
+ )
+
+ def _participation(self, run: CohortBackfillRun, cohort: Cohort, behavioral_hash: str) -> None:
+ CohortBackfillRunCohort.objects.for_team(self.team.id).create(
+ run=run,
+ team_id=self.team.id,
+ cohort=cohort,
+ filters_shape_hash="shape",
+ behavioral_filters_shape_hash=behavioral_hash,
+ pinned_filters=cohort.filters,
+ )
+
+ def _chunk(self, run: CohortBackfillRun, day: date, band: int, status: str) -> None:
+ CohortBackfillChunk.objects.for_team(self.team.id).create(
+ run=run, team_id=self.team.id, day=day, band=band, status=status
+ )
+
+ def test_loads_seeding_run_and_confirms_only_fully_seeded_days(self) -> None:
+ # A run stuck in `seeding` (B5 absent) must still load — no status filter — and a day counts as
+ # a confirmed seed domain only when every band chunk is CONFIRMED. Accessing run_cohorts/chunks
+ # through the fail-closed reverse relation would raise TeamScopeError here, so a clean load also
+ # guards that regression.
+ cohort = self._cohort()
+ run = self._run(boundary_at=datetime(2026, 7, 21, 20, 40, tzinfo=UTC))
+ self._participation(run, cohort, cohort.behavioral_filters_shape_hash or "")
+ self._chunk(run, date(2026, 7, 19), 0, _CONFIRMED)
+ self._chunk(run, date(2026, 7, 19), 1, _CONFIRMED)
+ self._chunk(run, date(2026, 7, 20), 0, _CONFIRMED)
+ self._chunk(run, date(2026, 7, 20), 1, _PENDING) # day 20 only partially seeded
+
+ ctx = load_run_context(self.team.id, cohort.id, None)
+
+ assert ctx is not None
+ self.assertEqual(ctx.run_id, str(run.id))
+ self.assertEqual(ctx.status, CohortBackfillRunStatus.SEEDING)
+ self.assertEqual(ctx.boundary_day, date(2026, 7, 21))
+ self.assertEqual(ctx.confirmed_days, frozenset({date(2026, 7, 19)}))
+ self.assertEqual(ctx.non_confirmed_chunks, 1)
+ self.assertFalse(ctx.shape_hash_drift)
+
+ def test_boundary_day_uses_run_timezone(self) -> None:
+ # 2026-07-21T02:00Z is 2026-07-20 19:00 in US/Pacific, so the boundary calendar day is the 20th.
+ cohort = self._cohort()
+ run = self._run(boundary_at=datetime(2026, 7, 21, 2, 0, tzinfo=UTC), timezone="US/Pacific")
+ self._participation(run, cohort, cohort.behavioral_filters_shape_hash or "")
+
+ ctx = load_run_context(self.team.id, cohort.id, None)
+
+ assert ctx is not None
+ self.assertEqual(ctx.run_timezone, "US/Pacific")
+ self.assertEqual(ctx.boundary_day, date(2026, 7, 20))
+
+ def test_shape_hash_drift_when_pinned_hash_differs_from_current(self) -> None:
+ cohort = self._cohort()
+ run = self._run(boundary_at=datetime(2026, 7, 21, 20, 40, tzinfo=UTC))
+ self._participation(run, cohort, "stale-hash-from-before-an-edit")
+
+ ctx = load_run_context(self.team.id, cohort.id, None)
+
+ assert ctx is not None
+ self.assertTrue(ctx.shape_hash_drift)
+
+ def test_returns_none_when_no_run_has_a_boundary(self) -> None:
+ cohort = self._cohort()
+ run = self._run(boundary_at=None) # awaiting boundary
+ self._participation(run, cohort, "")
+
+ self.assertIsNone(load_run_context(self.team.id, cohort.id, None))
diff --git a/products/cohorts/backend/parity/test/test_recompute.py b/products/cohorts/backend/parity/test/test_recompute.py
new file mode 100644
index 000000000000..346f9d53dba4
--- /dev/null
+++ b/products/cohorts/backend/parity/test/test_recompute.py
@@ -0,0 +1,488 @@
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from zoneinfo import ZoneInfo
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.cohorts.backend.models.leaf_shape import BehavioralLeafKey
+from products.cohorts.backend.parity.fold import MembershipRecord
+from products.cohorts.backend.parity.recompute import (
+ _OP_EVAL,
+ DayMatch,
+ OracleLeaf,
+ RecomputeSpec,
+ RecomputeUnsupported,
+ RunContext,
+ _member,
+ _TreeGroup,
+ _TreeLeaf,
+ classify_recompute,
+ compute_oracle_members,
+ evaluate_tree,
+ screen_for_recompute,
+)
+
+PACIFIC = ZoneInfo("US/Pacific")
+AT = datetime(2026, 7, 24, 18, 0, tzinfo=UTC) # 2026-07-24 11:00 in US/Pacific
+GRACE = timedelta(minutes=10)
+HASH = "aaaaaaaaaaaaaaaa"
+HASH2 = "bbbbbbbbbbbbbbbb"
+
+
+def _key(condition_hash: str = HASH, **overrides: Any) -> BehavioralLeafKey:
+ fields: dict[str, Any] = {
+ "condition_hash": condition_hash,
+ "value": "performed_event",
+ "time_value": 7,
+ "time_interval": "day",
+ "explicit_datetime": "",
+ "explicit_datetime_to": "",
+ "operator": "",
+ "operator_value": 0,
+ }
+ fields.update(overrides)
+ return BehavioralLeafKey(**fields)
+
+
+KEY = _key()
+KEY2 = _key(HASH2)
+
+
+def _behavioral(
+ condition_hash: str = HASH,
+ value: str = "performed_event",
+ key: Any = "$pageview",
+ time_value: Any = 7,
+ time_interval: Any = "day",
+ operator: Optional[str] = None,
+ operator_value: Any = None,
+ explicit_datetime: Optional[str] = None,
+ explicit_datetime_to: Optional[str] = None,
+ event_type: str = "events",
+ event_filters: Any = None,
+ negation: bool = False,
+) -> dict:
+ node: dict = {
+ "type": "behavioral",
+ "value": value,
+ "key": key,
+ "conditionHash": condition_hash,
+ "bytecode": ["_H", 1],
+ "time_value": time_value,
+ "time_interval": time_interval,
+ "event_type": event_type,
+ }
+ if operator is not None:
+ node["operator"] = operator
+ if operator_value is not None:
+ node["operator_value"] = operator_value
+ if explicit_datetime is not None:
+ node["explicit_datetime"] = explicit_datetime
+ if explicit_datetime_to is not None:
+ node["explicit_datetime_to"] = explicit_datetime_to
+ if event_filters is not None:
+ node["event_filters"] = event_filters
+ if negation:
+ node["negation"] = True
+ return node
+
+
+def _pinned(node: dict) -> dict:
+ """Mirror of pin_conditions_for_cohorts leaf resolution (event-name / action)."""
+ key = node.get("key")
+ is_action = node.get("event_type") == "actions" or isinstance(key, int)
+ event_name = key if isinstance(key, str) and not is_action else None
+ return {
+ "condition_hash": node.get("conditionHash"),
+ "value": node.get("value"),
+ "time_value": node.get("time_value"),
+ "time_interval": node.get("time_interval"),
+ "explicit_datetime": node.get("explicit_datetime"),
+ "explicit_datetime_to": node.get("explicit_datetime_to"),
+ "operator": node.get("operator"),
+ "operator_value": node.get("operator_value"),
+ "event_name": event_name,
+ "is_action": is_action,
+ }
+
+
+def _filters(*leaves: dict, op: str = "AND") -> dict:
+ return {"properties": {"type": op, "values": list(leaves)}}
+
+
+def _screen(*leaves: dict, op: str = "AND", max_window_days: int = 400):
+ return screen_for_recompute(
+ 1, _filters(*leaves, op=op), [_pinned(leaf) for leaf in leaves], max_window_days=max_window_days
+ )
+
+
+class TestSupportScreen(SimpleTestCase):
+ def test_canary_single_performed_event_is_supported(self) -> None:
+ result = _screen(_behavioral())
+ assert isinstance(result, RecomputeSpec)
+ self.assertTrue(result.single_leaf)
+ leaf = result.sole_leaf
+ self.assertEqual((leaf.event_name, leaf.op, leaf.op_value, leaf.window_days), ("$pageview", "gte", 1, 7))
+
+ @parameterized.expand(
+ [
+ (
+ "event_property_filters",
+ _behavioral(event_filters=[{"key": "x", "value": "y"}]),
+ "has_event_property_filters",
+ ),
+ ("action_by_event_type", _behavioral(event_type="actions"), "action_leaf"),
+ ("action_by_int_key", _behavioral(key=42), "action_leaf"),
+ ("sub_day_hour_window", _behavioral(time_interval="hour", time_value=5), "sub_day_window"),
+ ("sequence_value", _behavioral(value="performed_event_sequence"), "sequence_or_lifecycle_value"),
+ (
+ "absolute_explicit_range",
+ _behavioral(explicit_datetime="2026-01-01", explicit_datetime_to="2026-02-01"),
+ "absolute_explicit_range",
+ ),
+ (
+ "two_sided_relative_range",
+ _behavioral(explicit_datetime="-30d", explicit_datetime_to="-7d"),
+ "relative_range_unsupported",
+ ),
+ (
+ "unparseable_explicit_bound",
+ _behavioral(explicit_datetime="not-a-date"),
+ "unparseable_explicit_bound",
+ ),
+ ("missing_interval", _behavioral(time_interval=None), "missing_window"),
+ # select.rs maps every zero-effective-window `performed_event_multiple` to HourlyDeferred,
+ # whether the window is sub-day or an explicit shape it cannot slide.
+ (
+ "multiple_zero_day_window",
+ _behavioral(value="performed_event_multiple", time_value=0),
+ "hourly_deferred",
+ ),
+ (
+ "multiple_absolute_explicit_range",
+ _behavioral(
+ value="performed_event_multiple", explicit_datetime="2026-01-01", explicit_datetime_to="2026-02-01"
+ ),
+ "hourly_deferred",
+ ),
+ ("window_over_cap", _behavioral(time_value=10, time_interval="year"), "window_exceeds_max_days"),
+ ]
+ )
+ def test_unsupported_leaf_reasons(self, _name: str, leaf: dict, reason: str) -> None:
+ result = _screen(leaf)
+ self.assertEqual(result, RecomputeUnsupported(reason))
+
+ @parameterized.expand(
+ [
+ (
+ "person_leaf",
+ {"type": "person", "key": "email", "value": "[email protected]", "conditionHash": HASH},
+ "person_property_leaf",
+ ),
+ ("cohort_ref", {"type": "cohort", "key": "id", "value": 7}, "cohort_ref_leaf"),
+ ]
+ )
+ def test_non_behavioral_leaves_are_unsupported(self, _name: str, leaf: dict, reason: str) -> None:
+ # Person/cohort-ref leaves have no pinned behavioral condition; the raw tree walk still classifies them.
+ result = screen_for_recompute(1, _filters(leaf), [], max_window_days=400)
+ self.assertEqual(result, RecomputeUnsupported(reason))
+
+ def test_relative_lower_only_explicit_equals_time_value_interval(self) -> None:
+ # "-7d" and time_value:7/day must resolve to the same window — the same oracle query.
+ explicit = _screen(_behavioral(time_value=None, time_interval=None, explicit_datetime="-7d"))
+ interval = _screen(_behavioral(time_value=7, time_interval="day"))
+ assert isinstance(explicit, RecomputeSpec) and isinstance(interval, RecomputeSpec)
+ self.assertEqual(explicit.sole_leaf.window_days, 7)
+ self.assertEqual(explicit.sole_leaf.window_days, interval.sole_leaf.window_days)
+
+ def test_multiple_operator_defaults_to_eq_and_clamps_negative_value(self) -> None:
+ # performed_event_multiple with no operator -> eq; a negative operator_value clamps to 0.
+ result = _screen(_behavioral(value="performed_event_multiple", operator=None, operator_value=-5))
+ assert isinstance(result, RecomputeSpec)
+ self.assertEqual((result.sole_leaf.op, result.sole_leaf.op_value), ("eq", 0))
+
+ def test_multiple_maps_gte_operator_and_value(self) -> None:
+ result = _screen(_behavioral(value="performed_event_multiple", operator="gte", operator_value=3))
+ assert isinstance(result, RecomputeSpec)
+ self.assertEqual((result.sole_leaf.op, result.sole_leaf.op_value), ("gte", 3))
+
+ def test_identical_leaves_dedupe_to_one_leaf(self) -> None:
+ leaf = _behavioral()
+ result = screen_for_recompute(1, _filters(leaf, leaf), [_pinned(leaf)], max_window_days=400)
+ assert isinstance(result, RecomputeSpec)
+ self.assertEqual(len(result.leaves), 1)
+ self.assertTrue(result.single_leaf)
+
+ def test_same_condition_hash_different_window_stays_two_leaves(self) -> None:
+ # conditionHash digests only the event matcher, so "did $pageview in 30d AND NOT did $pageview
+ # in 1d" — a routine churn shape — shares one hash across two leaves. Collapsing them would
+ # evaluate `bit AND NOT bit`, i.e. an empty oracle set and a FAIL on every fold member.
+ wide = _behavioral(time_value=30)
+ narrow = _behavioral(time_value=1, negation=True)
+ result = screen_for_recompute(1, _filters(wide, narrow), [_pinned(wide), _pinned(narrow)], max_window_days=400)
+ assert isinstance(result, RecomputeSpec)
+ self.assertEqual(sorted(leaf.window_days for leaf in result.leaves.values()), [1, 30])
+ self.assertFalse(result.single_leaf)
+ members = compute_oracle_members(
+ result,
+ {_key(time_value=30): {"stale", "active"}, _key(time_value=1): {"active"}},
+ )
+ self.assertEqual(members, {"stale"})
+
+
+class TestMembershipFloor(SimpleTestCase):
+ @parameterized.expand(
+ [
+ # count 0 is never a member, even under lte/lt/eq 0 (the count >= 1 floor).
+ ("lte5_over0", 0, "lte", 5, False),
+ ("lt5_over0", 0, "lt", 5, False),
+ ("eq0_over0", 0, "eq", 0, False),
+ ("gte1_over0", 0, "gte", 1, False),
+ # count 1 satisfies lte/eq 1 but never eq 0.
+ ("lte5_over1", 1, "lte", 5, True),
+ ("eq1_over1", 1, "eq", 1, True),
+ ("eq0_over1", 1, "eq", 0, False),
+ ]
+ )
+ def test_member_floor(self, _name: str, count: int, op: str, op_value: int, expected: bool) -> None:
+ self.assertEqual(_member(count, op, op_value), expected)
+
+
+class TestTreeEvaluation(SimpleTestCase):
+ def test_and_neg_b_truth_table(self) -> None:
+ tree = _TreeGroup(op="AND", children=(_TreeLeaf(KEY, False), _TreeLeaf(KEY2, True)))
+ cases = [((True, True), False), ((True, False), True), ((False, True), False), ((False, False), False)]
+ for (a, b), expected in cases:
+ self.assertEqual(evaluate_tree(tree, {KEY: a, KEY2: b}), expected, f"A={a} ¬B={b}")
+
+ def test_absent_leaf_reads_false_then_negation(self) -> None:
+ # A positive leaf absent from the bit map reads false; a negated absent leaf reads true.
+ self.assertFalse(evaluate_tree(_TreeLeaf(KEY, False), {}))
+ self.assertTrue(evaluate_tree(_TreeLeaf(KEY, True), {}))
+
+ def test_empty_group_identities(self) -> None:
+ self.assertTrue(evaluate_tree(_TreeGroup(op="AND", children=()), {}))
+ self.assertFalse(evaluate_tree(_TreeGroup(op="OR", children=()), {}))
+
+ def test_compute_oracle_members_and_minus_b(self) -> None:
+ spec = RecomputeSpec(
+ cohort_id=1,
+ root=_TreeGroup(op="AND", children=(_TreeLeaf(KEY, False), _TreeLeaf(KEY2, True))),
+ leaves={
+ KEY: OracleLeaf(KEY, "$pageview", "gte", 1, 7),
+ KEY2: OracleLeaf(KEY2, "purchase", "gte", 1, 7),
+ },
+ single_leaf=False,
+ )
+ # A minus B: {a1, a2} minus {a2, b1} = {a1}. b1 (only in B) composes to false and is excluded.
+ members = compute_oracle_members(spec, {KEY: {"a1", "a2"}, KEY2: {"a2", "b1"}})
+ self.assertEqual(members, {"a1"})
+
+ def test_compute_oracle_members_single_leaf_is_the_set(self) -> None:
+ spec = RecomputeSpec(
+ cohort_id=1,
+ root=_TreeLeaf(KEY, False),
+ leaves={KEY: OracleLeaf(KEY, "$pageview", "gte", 1, 7)},
+ single_leaf=True,
+ )
+ self.assertEqual(compute_oracle_members(spec, {KEY: {"a", "b"}}), {"a", "b"})
+
+
+def _spec(op: str = "gte", op_value: int = 1, window_days: int = 7, single_leaf: bool = True) -> RecomputeSpec:
+ leaves = {KEY: OracleLeaf(KEY, "$pageview", op, op_value, window_days)}
+ if not single_leaf:
+ leaves[KEY2] = OracleLeaf(KEY2, "purchase", op, op_value, window_days)
+ return RecomputeSpec(cohort_id=1, root=_TreeLeaf(KEY, False), leaves=leaves, single_leaf=single_leaf)
+
+
+def _ctx(**overrides: Any) -> RunContext:
+ defaults: dict[str, Any] = {
+ "run_id": "run-1",
+ "status": "seeding",
+ "boundary_at": datetime(2026, 7, 20, 19, 0, tzinfo=UTC), # 2026-07-20 12:00 in US/Pacific
+ "run_timezone": "US/Pacific",
+ "boundary_day": date(2026, 7, 20),
+ "confirmed_days": frozenset({date(2026, 7, 17), date(2026, 7, 18)}),
+ "non_confirmed_chunks": 0,
+ "shape_hash_drift": False,
+ }
+ defaults.update(overrides)
+ return RunContext(**defaults)
+
+
+def _dm(day: date, bucket: str, matches: int = 1) -> DayMatch:
+ return DayMatch(day=day, bucket=bucket, matches=matches)
+
+
+def _fold(*person_ids: str, entered_at: datetime = datetime(2026, 7, 1, tzinfo=UTC)) -> dict[str, MembershipRecord]:
+ return {pid: MembershipRecord(status="entered", last_updated=entered_at) for pid in person_ids}
+
+
+def _classify(**overrides: Any):
+ defaults: dict[str, Any] = {
+ "spec": _spec(),
+ "name": "c",
+ "fold_records": {},
+ "oracle_members": set(),
+ "day_counts": {},
+ "extended_leaf_counts": {},
+ "ctx": _ctx(),
+ "at": AT,
+ "grace": GRACE,
+ "team_tz": PACIFIC,
+ }
+ defaults.update(overrides)
+ return classify_recompute(**defaults)
+
+
+class TestMissingSegmentation(SimpleTestCase):
+ @parameterized.expand(
+ [
+ # 2026-07-24 is at_day; grace bucket there depends only on last grace-minutes.
+ ("grace", [_dm(date(2026, 7, 24), "grace")], "missing_grace", "PASS"),
+ # 2026-07-18 is a confirmed seed day -> should have been seeded (gates FAIL).
+ ("seed_domain", [_dm(date(2026, 7, 18), "pre_boundary")], "missing_seed_domain", "FAIL"),
+ # 2026-07-20 is the boundary day, pre-boundary -> the decaying gap.
+ ("boundary_day", [_dm(date(2026, 7, 20), "pre_boundary")], "missing_boundary_day", "PASS"),
+ # 2026-07-19 is a pre-boundary window day with no confirmed chunk (gates FAIL).
+ ("unseeded_day", [_dm(date(2026, 7, 19), "pre_boundary")], "missing_unseeded_day", "FAIL"),
+ # 2026-07-21 is post-boundary: only the live path could have entered them, so a drop there
+ # is exactly what this gate exists to catch — grace is the lever for known live lag.
+ ("post_boundary", [_dm(date(2026, 7, 21), "post_boundary")], "missing_post_boundary", "FAIL"),
+ # No day counts at all for a person the member-set read returned: the two oracle reads
+ # disagree (override drift, a dropped chunk), which is not the lag noise `grace` means.
+ ("unattributed", [], "missing_unattributed", "SKIP"),
+ ]
+ )
+ def test_missing_person_precedence(
+ self, name: str, matches: list[DayMatch], expected_field: str, verdict: str
+ ) -> None:
+ row = _classify(oracle_members={"p"}, day_counts={"p": matches})
+ self.assertEqual(getattr(row, expected_field), 1, name)
+ self.assertEqual(row.missing, 1)
+ self.assertEqual(row.verdict, verdict, name)
+ self.assertEqual(row.samples[expected_field], ("p",))
+
+ def test_seed_domain_precedence_over_boundary(self) -> None:
+ # A person qualifying via both a confirmed seed day and the boundary day is a seed-domain miss:
+ # the seeder already covered them, so it gates FAIL rather than being written off as the gap.
+ row = _classify(
+ oracle_members={"p"},
+ day_counts={"p": [_dm(date(2026, 7, 18), "pre_boundary"), _dm(date(2026, 7, 20), "pre_boundary")]},
+ )
+ self.assertEqual(row.missing_seed_domain, 1)
+ self.assertEqual(row.verdict, "FAIL")
+
+
+class TestEvictionAndUnsegmented(SimpleTestCase):
+ def test_eviction_pending_splits_false_members(self) -> None:
+ # "evict" still satisfies the predicate once the window slides back a day (the tz-midnight
+ # sweep has not caught up); "hard" does not, so it is real over-inclusion.
+ row = _classify(
+ fold_records=_fold("evict", "hard"),
+ extended_leaf_counts={KEY: {"evict": 1, "hard": 0}},
+ )
+ self.assertEqual(row.false_members, 2)
+ self.assertEqual(row.eviction_pending, 1)
+ self.assertEqual(row.false_hard, 1)
+ self.assertEqual(row.verdict, "FAIL") # the one hard over-count gates FAIL
+ self.assertEqual(row.samples["false_hard"], ("hard",))
+
+ def test_just_entered_false_member_is_sweep_lag_not_over_inclusion(self) -> None:
+ # A late-ingested historical event enters the person now and only a sweep tick can clear them,
+ # so a fold record younger than the grace window is lag, however old the matching event is.
+ row = _classify(fold_records=_fold("fresh", entered_at=AT - timedelta(minutes=1)))
+ self.assertEqual((row.eviction_pending, row.false_hard), (1, 0))
+ self.assertEqual(row.verdict, "PASS")
+
+ def test_multi_leaf_over_count_uses_the_tree_for_the_eviction_split(self) -> None:
+ # Every leaf slides back a day and the tree is re-evaluated, so a multi-leaf cohort near
+ # team-tz midnight is not gated on sweep lag the way a single-leaf one isn't.
+ spec = RecomputeSpec(
+ cohort_id=1,
+ root=_TreeGroup(op="AND", children=(_TreeLeaf(KEY, False), _TreeLeaf(KEY2, False))),
+ leaves={KEY: OracleLeaf(KEY, "$pageview", "gte", 1, 7), KEY2: OracleLeaf(KEY2, "purchase", "gte", 1, 7)},
+ single_leaf=False,
+ )
+ row = _classify(
+ spec=spec,
+ fold_records=_fold("both", "one"),
+ extended_leaf_counts={KEY: {"both": 1, "one": 1}, KEY2: {"both": 1, "one": 0}},
+ )
+ self.assertEqual((row.eviction_pending, row.false_hard), (1, 1))
+ self.assertEqual(row.samples["false_hard"], ("one",))
+
+ @parameterized.expand(
+ [
+ ("non_monotone_op", {"spec": _spec(op="lte", op_value=2)}, "non-monotone"),
+ ("multi_leaf", {"spec": _spec(single_leaf=False)}, "multi-leaf"),
+ ("no_run_context", {"ctx": None}, "no backfill run"),
+ # The segmentation query stamps `grace` ahead of both boundary buckets, so a grace window
+ # opening before the boundary would file a real seed-domain miss as lag noise and PASS.
+ ("grace_reaches_over_the_boundary", {"grace": timedelta(days=4)}, "before the run boundary"),
+ ]
+ )
+ def test_unadjudicated_missing_is_skip_not_pass(self, _name: str, overrides: dict, note: str) -> None:
+ # Reporting PASS here would certify a parity the command never established.
+ row = _classify(oracle_members={"p"}, day_counts={"p": [_dm(date(2026, 7, 18), "pre_boundary")]}, **overrides)
+ self.assertEqual(row.missing_unsegmented, 1)
+ self.assertEqual(row.missing_seed_domain, 0)
+ self.assertEqual(row.verdict, "SKIP")
+ self.assertTrue(any(note in n for n in row.notes), row.notes)
+
+ def test_unloaded_day_counts_keep_the_caller_reason(self) -> None:
+ # The shape is segmentable, so the only explanation is the caller's; emitting a structural
+ # reason here would misattribute a read-cap downgrade to the cohort's definition.
+ row = _classify(
+ oracle_members={"p"},
+ day_counts_loaded=False,
+ extra_notes=["exceeds the per-person read cap"],
+ )
+ self.assertEqual(row.missing_unsegmented, 1)
+ self.assertEqual(row.notes[0], "exceeds the per-person read cap")
+ self.assertFalse(any("multi-leaf" in n or "non-monotone" in n or "no backfill run" in n for n in row.notes))
+
+ def test_hard_over_count_outranks_unadjudicated_missing(self) -> None:
+ row = _classify(spec=_spec(single_leaf=False), fold_records=_fold("x"), oracle_members={"p"})
+ self.assertEqual(row.verdict, "FAIL")
+
+
+class TestExpiryCurve(SimpleTestCase):
+ def test_expiry_is_driven_by_the_oldest_still_needed_match(self) -> None:
+ # threshold 2 across a confirmed seed day and the boundary day: dropping the newer match alone
+ # still leaves the person short, so the *older* match's age-out date is when they fall out.
+ row = _classify(
+ spec=_spec(op="gte", op_value=2, window_days=7),
+ oracle_members={"p"},
+ day_counts={
+ "p": [_dm(date(2026, 7, 18), "pre_boundary"), _dm(date(2026, 7, 20), "pre_boundary")],
+ },
+ )
+ self.assertEqual(row.missing_boundary_day, 1)
+ self.assertEqual(row.expires_by_day, {"2026-07-26": 1}) # 2026-07-18 + 7 + 1
+
+ def test_expiry_counts_group_by_date(self) -> None:
+ row = _classify(
+ spec=_spec(window_days=7),
+ oracle_members={"p1", "p2"},
+ day_counts={
+ "p1": [_dm(date(2026, 7, 20), "pre_boundary")],
+ "p2": [_dm(date(2026, 7, 20), "pre_boundary")],
+ },
+ )
+ self.assertEqual(row.expires_by_day, {"2026-07-28": 2}) # 2026-07-20 + 7 + 1
+
+
+class TestOpWhitelistParity(SimpleTestCase):
+ def test_eval_and_sql_whitelists_agree(self) -> None:
+ # A drift where an op gains a Python comparator but no SQL rendering (or vice versa) would let a
+ # supported leaf reach a KeyError at query time; keep the two op tables in lockstep.
+ from products.cohorts.backend.parity.oracle import _MEMBER_SET_SQL, _OP_SQL, _render
+
+ self.assertEqual(set(_OP_EVAL), set(_OP_SQL))
+ for comparator in _OP_SQL.values():
+ rendered = _render(_MEMBER_SET_SQL, op=comparator)
+ self.assertIn(f"match_count {comparator} %(op_value)s", rendered)
+ self.assertNotIn("{op}", rendered)
diff --git a/products/cohorts/backend/parity/test/test_report.py b/products/cohorts/backend/parity/test/test_report.py
index 43e6ff4f8729..bef16ee3753b 100644
--- a/products/cohorts/backend/parity/test/test_report.py
+++ b/products/cohorts/backend/parity/test/test_report.py
@@ -9,7 +9,14 @@ from products.cohorts.backend.parity.classifier import (
CohortComparison,
)
from products.cohorts.backend.parity.fold import ReconcileRunCompleteness
-from products.cohorts.backend.parity.report import format_notes, format_reconcile_notes, to_json
+from products.cohorts.backend.parity.recompute import RecomputeComparison, RecomputeSummary
+from products.cohorts.backend.parity.report import (
+ format_notes,
+ format_recompute_table,
+ format_reconcile_notes,
+ to_json,
+ to_recompute_json,
+)
def _row(
@@ -60,3 +67,79 @@ class TestReport(SimpleTestCase):
)
document = to_json([row], AggregateSummary(), {"team_id": 2})
self.assertEqual(document["cohorts"][0]["notes"], notes)
+
+
+class TestRecomputeReport(SimpleTestCase):
+ def test_recompute_json_carries_every_decay_watch_field(self) -> None:
+ row = RecomputeComparison(
+ cohort_id=433564,
+ name="canary",
+ supported=True,
+ verdict=VERDICT_PASS,
+ fold_count=5303,
+ oracle_count=5933,
+ both=5303,
+ missing=630,
+ missing_boundary_day=630,
+ expires_by_day={"2026-07-31": 630},
+ samples={"missing_boundary_day": ("0199-aaaa", "0199-bbbb")},
+ run_id="run-1",
+ run_status="seeding",
+ boundary_at="2026-07-24T02:23:00+00:00",
+ boundary_day="2026-07-23",
+ run_timezone="US/Pacific",
+ chunk_days_confirmed=21,
+ shape_hash_drift=False,
+ reconcile_runs=(ReconcileRunCompleteness(run_id="run-1", cohort_id=433564, partitions_seen=64),),
+ )
+ meta = {"oracle": "recompute", "at": "2026-07-24T18:00:00+00:00", "grace_minutes": 10, "run_id": "run-1"}
+ document = to_recompute_json([row], RecomputeSummary(passed=1), meta)
+
+ self.assertEqual({"oracle", "at", "grace_minutes", "run_id"}, set(document["meta"]))
+ cohort = document["cohorts"][0]
+ # The decay-watch contract: every field a daily watch needs must survive serialization.
+ for field in (
+ "run_id",
+ "run_status",
+ "boundary_at",
+ "boundary_day",
+ "run_timezone",
+ "chunk_days_confirmed",
+ "shape_hash_drift",
+ "reconcile_runs",
+ "expires_by_day",
+ "false_hard",
+ "eviction_pending",
+ "missing_boundary_day",
+ ):
+ self.assertIn(field, cohort)
+ self.assertEqual(cohort["expires_by_day"], {"2026-07-31": 630})
+ self.assertEqual(cohort["reconcile_runs"][0]["partitions_seen"], 64)
+ # The caveats promise person ids for triage, so they have to survive serialization.
+ self.assertEqual(cohort["samples"], {"missing_boundary_day": ("0199-aaaa", "0199-bbbb")})
+
+ def test_recompute_json_orders_failures_first(self) -> None:
+ rows = [
+ RecomputeComparison(cohort_id=1, name="a", supported=True, verdict=VERDICT_PASS),
+ RecomputeComparison(cohort_id=2, name="b", supported=False, verdict=VERDICT_SKIP),
+ RecomputeComparison(cohort_id=3, name="c", supported=True, verdict=VERDICT_FAIL, false_hard=2),
+ ]
+ document = to_recompute_json(rows, RecomputeSummary(), {})
+ self.assertEqual([c["cohort_id"] for c in document["cohorts"]], [3, 1, 2])
+
+ def test_recompute_table_columns_line_up_across_row_kinds(self) -> None:
+ # A screen-skipped row spends the numeric columns on its reason; sizing that field by hand
+ # drifts from the header the moment a column is added or renamed.
+ rows = [
+ RecomputeComparison(cohort_id=1, name="numeric", supported=True, verdict=VERDICT_PASS, fold_count=5303),
+ RecomputeComparison(
+ cohort_id=2,
+ name="x" * 60,
+ supported=False,
+ verdict=VERDICT_SKIP,
+ skip_reason="has_event_property_filters",
+ ),
+ ]
+ lines = format_recompute_table(rows).split("\n")
+ self.assertEqual({len(line) for line in lines}, {len(lines[0])})
+ self.assertIn("SKIP: has_event_property_filters", lines[-1])
diff --git a/products/cohorts/backend/parity/test/test_tzdates.py b/products/cohorts/backend/parity/test/test_tzdates.py
new file mode 100644
index 000000000000..5b3d50e8e917
--- /dev/null
+++ b/products/cohorts/backend/parity/test/test_tzdates.py
@@ -0,0 +1,122 @@
+from datetime import UTC, date, datetime
+from zoneinfo import ZoneInfo
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.cohorts.backend.parity.tzdates import (
+ EPOCH_DAY,
+ day_of_instant,
+ start_of_day_utc,
+ window_dates,
+ window_start_utc,
+)
+
+PACIFIC = ZoneInfo("US/Pacific")
+
+
+class TestTzDates(SimpleTestCase):
+ @parameterized.expand(
+ [
+ # An evening UTC instant is still the previous calendar day in US/Pacific.
+ ("evening_utc_is_previous_pacific_day", datetime(2026, 7, 24, 2, 0, tzinfo=UTC), date(2026, 7, 23)),
+ ("midday_utc_same_pacific_day", datetime(2026, 7, 24, 18, 0, tzinfo=UTC), date(2026, 7, 24)),
+ ]
+ )
+ def test_day_of_instant(self, _name: str, instant: datetime, expected: date) -> None:
+ self.assertEqual(day_of_instant(instant, PACIFIC), expected)
+
+ def test_day_of_instant_rejects_naive(self) -> None:
+ with self.assertRaises(ValueError):
+ day_of_instant(datetime(2026, 7, 24, 2, 0), PACIFIC)
+
+ @parameterized.expand(
+ [
+ # Standard time (PST, -8): midnight is 08:00 UTC.
+ ("pst_midnight", date(2026, 1, 15), datetime(2026, 1, 15, 8, 0, tzinfo=UTC)),
+ # Daylight time (PDT, -7): midnight is 07:00 UTC.
+ ("pdt_midnight", date(2026, 7, 15), datetime(2026, 7, 15, 7, 0, tzinfo=UTC)),
+ # Spring-forward day (transition at 02:00): midnight predates the gap, still PST.
+ ("spring_forward_midnight_pst", date(2026, 3, 8), datetime(2026, 3, 8, 8, 0, tzinfo=UTC)),
+ # Fall-back day (transition at 02:00): midnight predates the overlap, still PDT.
+ ("fall_back_midnight_pdt", date(2026, 11, 1), datetime(2026, 11, 1, 7, 0, tzinfo=UTC)),
+ ]
+ )
+ def test_start_of_day_utc_pacific(self, _name: str, day: date, expected: datetime) -> None:
+ self.assertEqual(start_of_day_utc(day, PACIFIC), expected)
+
+ def test_start_of_day_utc_spring_forward_gap_midnight_lands_post_gap(self) -> None:
+ # Sao Paulo sprang forward at midnight 2017-10-15 (00:00 -> 01:00), so local midnight does
+ # not exist. Rust's bucket_tz resolves it to the post-gap instant (01:00 local); fold=0 must
+ # match exactly rather than fall on the pre-gap side.
+ sao_paulo = ZoneInfo("America/Sao_Paulo")
+ start = start_of_day_utc(date(2017, 10, 15), sao_paulo)
+ self.assertEqual(start, datetime(2017, 10, 15, 3, 0, tzinfo=UTC))
+ self.assertEqual(start.astimezone(sao_paulo).hour, 1)
+
+ def test_start_of_day_utc_skipped_civil_day_projects_to_following_midnight(self) -> None:
+ # Apia skipped all of 2011-12-30; its midnight and the following day's midnight are the same
+ # instant, matching bucket_tz's fully-skipped-civil-day golden.
+ apia = ZoneInfo("Pacific/Apia")
+ self.assertEqual(start_of_day_utc(date(2011, 12, 30), apia), datetime(2011, 12, 30, 10, 0, tzinfo=UTC))
+ self.assertEqual(start_of_day_utc(date(2011, 12, 31), apia), datetime(2011, 12, 30, 10, 0, tzinfo=UTC))
+
+ def test_start_of_day_utc_fall_back_ambiguous_midnight_is_earliest(self) -> None:
+ # Lord Howe falls back through 02:00->01:30, but some zones overlap midnight. Use a zone that
+ # falls back at 00:00 to exercise the ambiguous branch: America/Havana fell back 2018-11-04
+ # (01:00 -> 00:00), so 00:00 occurs twice; fold=0 must pick the earliest (pre-transition) UTC.
+ havana = ZoneInfo("America/Havana")
+ start = start_of_day_utc(date(2018, 11, 4), havana)
+ # 00:00 CDT (-4) is the earliest instant = 04:00 UTC (vs the later 00:00 CST (-5) = 05:00 UTC).
+ self.assertEqual(start, datetime(2018, 11, 4, 4, 0, tzinfo=UTC))
+
+ @parameterized.expand(
+ [
+ # N-day window over inclusive [at_day - N .. at_day] = N + 1 dates. This is the off-by-one
+ # the plan flags as the highest-risk regression: a window of N must yield N + 1 buckets.
+ ("zero_day_window_is_one_bucket", 0, [date(2026, 7, 24)]),
+ (
+ "seven_day_window_is_eight_buckets",
+ 7,
+ [
+ date(2026, 7, 17),
+ date(2026, 7, 18),
+ date(2026, 7, 19),
+ date(2026, 7, 20),
+ date(2026, 7, 21),
+ date(2026, 7, 22),
+ date(2026, 7, 23),
+ date(2026, 7, 24),
+ ],
+ ),
+ ]
+ )
+ def test_window_dates_inclusive_n_plus_one(self, _name: str, window_days: int, expected: list[date]) -> None:
+ # 18:00 UTC on 2026-07-24 is still 2026-07-24 in US/Pacific (11:00 PDT).
+ at = datetime(2026, 7, 24, 18, 0, tzinfo=UTC)
+ dates = window_dates(at, window_days, PACIFIC)
+ self.assertEqual(dates, expected)
+ self.assertEqual(len(dates), window_days + 1)
+
+ @parameterized.expand(
+ [
+ # `time_value: 10000, time_interval: "year"` resolves to 3_650_000 days; i32::MAX is the
+ # ceiling the filter grammar allows. Both overflow `date` arithmetic, and an uncaught
+ # OverflowError would kill a whole team-wide report after the drain.
+ ("ten_thousand_years", 3_650_000),
+ ("i32_max", 2**31 - 1),
+ ]
+ )
+ def test_astronomical_window_saturates_instead_of_overflowing(self, _name: str, window_days: int) -> None:
+ at = datetime(2026, 7, 24, 18, 0, tzinfo=UTC)
+ self.assertEqual(window_start_utc(at, window_days, PACIFIC), start_of_day_utc(EPOCH_DAY, PACIFIC))
+ self.assertEqual(window_dates(at, window_days, PACIFIC)[0], EPOCH_DAY)
+
+ def test_window_start_utc_is_midnight_of_at_day_minus_n(self) -> None:
+ at = datetime(2026, 7, 24, 18, 0, tzinfo=UTC) # 2026-07-24 in US/Pacific
+ # at_day - 7 = 2026-07-17; PDT midnight = 07:00 UTC.
+ self.assertEqual(window_start_utc(at, 7, PACIFIC), datetime(2026, 7, 17, 7, 0, tzinfo=UTC))
+ # The start must equal start_of_day_utc of the first window date.
+ first_window_day = window_dates(at, 7, PACIFIC)[0]
+ self.assertEqual(window_start_utc(at, 7, PACIFIC), start_of_day_utc(first_window_day, PACIFIC))
diff --git a/products/cohorts/backend/parity/tzdates.py b/products/cohorts/backend/parity/tzdates.py
new file mode 100644
index 000000000000..4389691049ad
--- /dev/null
+++ b/products/cohorts/backend/parity/tzdates.py
@@ -0,0 +1,98 @@
+"""Team-timezone calendar-day math for the recompute oracle.
+
+Python mirror of ``rust/cohort-core/src/bucket_tz.rs``. Every tz-date computation the oracle
+needs routes through here so the window semantics have one source of truth and the
+``toDate(param, tz)`` footgun below can never be reintroduced piecemeal.
+
+Window boundary (the parity-critical decision): the pipeline's predicate is
+``event_day >= now_day - N`` (``relative_date_parse("-Nd") == now - N days``), so "last N days"
+is the **inclusive** set ``[at_day - N .. at_day]`` = ``N + 1`` day-buckets. :func:`window_dates`
+returns those ``N + 1`` dates and :func:`window_start_utc` returns tz-midnight of ``at_day - N``.
+
+DST (matches ``bucket_tz.rs``): instant -> day is always unambiguous, so :func:`day_of_instant`
+is DST-exact. Day -> instant (:func:`start_of_day_utc`) can be ambiguous (fall-back) or
+nonexistent (spring-forward gap); ``fold=0`` picks the **earliest** instant on a fall-back overlap
+(= Python ``ZoneInfo`` fold=0) and lands on the **post-gap** instant for a skipped local midnight —
+byte-for-byte the same UTC instant Rust's ``start_of_day_ms_in_tz`` returns.
+
+The ``toDate(param, tz)`` footgun (cost hours in the 2026-07-24 canary): NEVER pass a Python-side
+datetime through ClickHouse ``toDate(<datetime>, tz)`` — that re-interprets an already-UTC instant
+in ``tz`` and shifts it a day. All tz-date arithmetic happens here in Python via ``ZoneInfo``; SQL
+receives only UTC datetime params compared against ``e.timestamp``, or the tz *name* as a string
+param inside ``toDate(<column>, %(tz)s)`` (converting a column is safe; converting a param is not).
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, date, datetime, timedelta
+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
+
+
+def resolve_zoneinfo(name: str) -> ZoneInfo:
+ """Parse an IANA tz name, falling back to UTC for an unrecognized one (matches the Rust loader's
+ ``resolve_tz_or_utc``)."""
+ try:
+ return ZoneInfo(name)
+ except (ZoneInfoNotFoundError, ValueError):
+ return ZoneInfo("UTC")
+
+
+def day_of_instant(instant: datetime, tz: ZoneInfo) -> date:
+ """The team-tz calendar date of an aware instant. DST-exact (instant -> day is unambiguous)."""
+ if instant.tzinfo is None:
+ raise ValueError("day_of_instant requires an aware datetime")
+ return instant.astimezone(tz).date()
+
+
+def start_of_day_utc(day: date, tz: ZoneInfo) -> datetime:
+ """tz-midnight of ``day`` as an aware UTC instant.
+
+ ``fold=0`` matches Rust: earliest instant on a fall-back overlap, the post-gap instant on a
+ spring-forward gap (a skipped civil day resolves to the following midnight, exactly as
+ ``bucket_tz.rs``).
+ """
+ local_midnight = datetime(day.year, day.month, day.day, 0, 0, 0, tzinfo=tz, fold=0)
+ return local_midnight.astimezone(UTC)
+
+
+# Saturation floor for an astronomical window: the earliest day a ClickHouse `DateTime64` event
+# timestamp can hold, so the saturated bound still renders as a query parameter.
+EPOCH_DAY = date(1970, 1, 1)
+
+
+def window_start_day(at_day: date, window_days: int) -> date:
+ """``at_day - N``, **saturating** at :data:`EPOCH_DAY` for an astronomical window.
+
+ Mirrors ``bucket_tz.rs`` ``window_start_for_now``, which saturates to ``DayIdx::MIN`` rather than
+ wrapping: an essentially infinite window covers everything and never evicts. Python would raise
+ ``OverflowError`` instead. Defense in depth only — callers screen oversized windows before they
+ drive a scan (see ``recompute.screen_for_recompute``).
+ """
+ if window_days < 0:
+ raise ValueError("window_days must be non-negative")
+ try:
+ start = at_day - timedelta(days=window_days)
+ except OverflowError:
+ return EPOCH_DAY
+ return max(start, EPOCH_DAY)
+
+
+def window_dates(at: datetime, window_days: int, tz: ZoneInfo) -> list[date]:
+ """The inclusive ``[at_day - N .. at_day]`` set = ``N + 1`` team-tz dates, ascending.
+
+ ``window_days`` is the leaf's whole-day sliding window ``N``; the returned list has ``N + 1``
+ entries (the ``+ 1`` is the off-by-one the pipeline's inclusive lower bound demands), unless
+ :func:`window_start_day` saturates the start at :data:`EPOCH_DAY`.
+ """
+ at_day = day_of_instant(at, tz)
+ start = window_start_day(at_day, window_days)
+ return [start + timedelta(days=offset) for offset in range((at_day - start).days + 1)]
+
+
+def window_start_utc(at: datetime, window_days: int, tz: ZoneInfo) -> datetime:
+ """UTC instant of tz-midnight of ``at_day - N`` — the inclusive window's lower bound.
+
+ Paired with an ``e.timestamp <= at`` upper bound, ``e.timestamp >= window_start_utc(...)``
+ selects exactly the whole-day window set without per-event day-bucketing.
+ """
+ return start_of_day_utc(window_start_day(day_of_instant(at, tz), window_days), tz)