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.

feat(cohorts): reconcile_dispatch CLI and parity harness (#72730)

Matheus Batista24d04015d075
diff --git a/products/cohorts/backend/management/commands/compare_cohort_membership.py b/products/cohorts/backend/management/commands/compare_cohort_membership.py
index abaf33abec0d..f31b503d31bb 100644
--- a/products/cohorts/backend/management/commands/compare_cohort_membership.py
+++ b/products/cohorts/backend/management/commands/compare_cohort_membership.py
@@ -24,9 +24,15 @@ from django.core.management.base import BaseCommand, CommandError, CommandParser
from products.cohorts.backend.parity.classifier import ClassifierConfig, CohortComparison, classify_cohort, summarize
from products.cohorts.backend.parity.eligibility import EMITTING_CLASSES, screen_team
-from products.cohorts.backend.parity.fold import fold_membership_changes
+from products.cohorts.backend.parity.fold import fold_membership_changes, 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.report import format_notes, format_summary, format_table, to_json
+from products.cohorts.backend.parity.report import (
+ format_notes,
+ format_reconcile_notes,
+ format_summary,
+ format_table,
+ to_json,
+)
from products.cohorts.backend.parity.snapshots import load_old_membership, load_realtime_cohorts, make_activity_probe
SHADOW_TOPIC_RETENTION_DAYS = 7
@@ -172,8 +178,10 @@ class Command(BaseCommand):
log(
f"drained {drain_stats.consumed} messages from {drain_stats.partitions_read}/{drain_stats.partitions} "
f"partitions; folded {fold_stats.folded} for team {team_id} across {len(fold_stats.cohorts_seen)} cohorts "
- f"(dropped: {fold_stats.dropped_wrong_team} wrong-team, {fold_stats.dropped_before_since} pre-since, "
- f"{fold_stats.dropped_malformed} malformed, {drain_stats.undecodable} undecodable)"
+ 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_malformed} malformed, {drain_stats.undecodable} undecodable; "
+ f"by origin: {dict(sorted(fold_stats.folded_by_origin.items()))})"
)
warnings, infos = _collect_warnings(drain_stats, fold_stats.cohorts_seen - set(screened), since, now)
@@ -189,6 +197,7 @@ class Command(BaseCommand):
classify=not options["no_classify"],
activity_probe=make_activity_probe(team_id),
)
+ completeness_by_cohort = reconcile_completeness_by_cohort(fold_stats)
rows: list[CohortComparison] = []
for cid in sorted(selected_ids):
s = screened[cid]
@@ -201,6 +210,7 @@ class Command(BaseCommand):
new_state=new_state.get(cid, {}),
last_realtime_calculation_at=last_calc[cid],
config=classifier_config,
+ notes=format_reconcile_notes(completeness_by_cohort.get(cid, ())),
)
)
diff --git a/products/cohorts/backend/parity/classifier.py b/products/cohorts/backend/parity/classifier.py
index b5d232e7ae5c..4d6b655848ff 100644
--- a/products/cohorts/backend/parity/classifier.py
+++ b/products/cohorts/backend/parity/classifier.py
@@ -5,8 +5,8 @@ emitted a decision for since the store wipe (fold.py:observed). Within O both pi
have weighed in, so the diff is sound; each rule explains (removes) part of it and the
remainder is the gated residual:
-- R-EXCLUDE: persons in `old - O` are excluded from the diff entirely (the new pipeline
- never evaluated them — flip-only emission means a never-member emits nothing).
+- R-EXCLUDE: persons in `old - O` are excluded from the diff entirely because the new
+ pipeline has not emitted a decision for them.
- R-FRESH: `only_new` entries whose flip is newer than the old side's last recompute —
the old pipeline simply hasn't caught up yet (expected, not over-inclusion).
- R-STALE: the mirror on `only_old` — the new pipeline already flipped a person to
@@ -115,6 +115,7 @@ def classify_cohort(
new_state: dict[str, MembershipRecord],
last_realtime_calculation_at: Optional[datetime],
config: ClassifierConfig,
+ notes: Sequence[str] = (),
) -> CohortComparison:
if not screened.emits:
return CohortComparison(
@@ -122,7 +123,10 @@ def classify_cohort(
name=name,
eligibility=screened.eligibility,
verdict=VERDICT_SKIP,
- notes=("not emit-eligible: " + ", ".join(screened.drop_reasons or (screened.eligibility,)),),
+ notes=(
+ *notes,
+ "not emit-eligible: " + ", ".join(screened.drop_reasons or (screened.eligibility,)),
+ ),
)
obs = observed(new_state)
@@ -133,7 +137,7 @@ def classify_cohort(
unobserved = old_members - obs # excluded from the diff (R-EXCLUDE)
union_size = len(both) + len(only_old) + len(only_new)
raw_pct = _pct(len(only_old) + len(only_new), union_size)
- notes: list[str] = []
+ comparison_notes = list(notes)
fresh = 0
stale = 0
@@ -144,7 +148,7 @@ def classify_cohort(
fresh = len(only_new)
# stale stays 0: a never-recomputed old side has no entered rows to be stale.
if fresh:
- notes.append("old side never recomputed this cohort; all only_new counted fresh")
+ comparison_notes.append("old side never recomputed this cohort; all only_new counted fresh")
else:
fresh = sum(1 for p in only_new if new_state[p].last_updated > last_realtime_calculation_at)
stale = sum(1 for p in only_old if new_state[p].last_updated > last_realtime_calculation_at)
@@ -160,11 +164,11 @@ def classify_cohort(
sample_suspect = sum(1 for p in sample if p in active)
suspect_missing = round(sample_suspect / len(sample) * len(unobserved))
if len(sample) < len(unobserved):
- notes.append(f"suspect_missing extrapolated from sample {len(sample)}/{len(unobserved)}")
+ comparison_notes.append(f"suspect_missing extrapolated from sample {len(sample)}/{len(unobserved)}")
if window == 0:
- notes.append("minute/hour window: probe cutoff is now, suspect≈0 by construction")
+ comparison_notes.append("minute/hour window: probe cutoff is now, suspect≈0 by construction")
elif unobserved and config.warmup_sample <= 0:
- notes.append("suspect check skipped (--warmup-sample 0); unobserved population unprobed")
+ comparison_notes.append("suspect check skipped (--warmup-sample 0); unobserved population unprobed")
residual_old = max(len(only_old) - stale, 0)
residual_new = max(len(only_new) - fresh, 0)
@@ -205,7 +209,7 @@ def classify_cohort(
dormant=dormant,
suspect_pct=suspect_pct,
verdict=verdict,
- notes=tuple(notes),
+ notes=tuple(comparison_notes),
)
diff --git a/products/cohorts/backend/parity/fold.py b/products/cohorts/backend/parity/fold.py
index 5cc53cf5c500..6c908b4441c9 100644
--- a/products/cohorts/backend/parity/fold.py
+++ b/products/cohorts/backend/parity/fold.py
@@ -12,12 +12,34 @@ from collections.abc import Iterable
from dataclasses import dataclass, field
from datetime import UTC, datetime
from typing import Any, Optional
+from uuid import UUID
+
+RECONCILE_COMPLETE_TYPE = "reconcile_complete"
+RECONCILE_PARTITION_COUNT = 64
+LIVE_ORIGIN = "live"
@dataclass(frozen=True)
class MembershipRecord:
status: str # "entered" | "left"
last_updated: datetime
+ origin: Optional[str] = None
+ run_id: Optional[str] = None
+
+
+@dataclass(frozen=True)
+class ReconcileRunCompleteness:
+ run_id: str
+ cohort_id: int
+ partitions_seen: int
+
+ @property
+ def expected_partitions(self) -> int:
+ return RECONCILE_PARTITION_COUNT
+
+ @property
+ def complete(self) -> bool:
+ return self.partitions_seen == RECONCILE_PARTITION_COUNT
@dataclass
@@ -28,6 +50,12 @@ class FoldStats:
dropped_before_since: int = 0
dropped_malformed: 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
+ # partition, so it undercounts. This keeps folded + drops + markers == total (markers land in
+ # neither the folded nor the dropped buckets).
+ reconcile_markers_recorded: int = 0
+ folded_by_origin: dict[str, int] = field(default_factory=dict)
def parse_last_updated(raw: Any) -> Optional[datetime]:
@@ -45,6 +73,47 @@ def parse_last_updated(raw: Any) -> Optional[datetime]:
return None
+def _parse_marker_run_id(raw: Any) -> Optional[str]:
+ if not isinstance(raw, str):
+ return None
+ try:
+ return str(UUID(raw))
+ except ValueError:
+ return None
+
+
+def _optional_string(raw: Any) -> Optional[str]:
+ return raw if isinstance(raw, str) and raw else None
+
+
+def _record_marker(
+ message: dict[str, Any],
+ cohort_id: Any,
+ last_updated: Optional[datetime],
+ since: datetime,
+ stats: FoldStats,
+) -> None:
+ run_id = _parse_marker_run_id(message.get("run_id"))
+ partition = message.get("partition")
+ if (
+ run_id is None
+ or not isinstance(cohort_id, int)
+ or isinstance(cohort_id, bool)
+ or not isinstance(partition, int)
+ or isinstance(partition, bool)
+ or not 0 <= partition < RECONCILE_PARTITION_COUNT
+ or last_updated is None
+ ):
+ stats.dropped_malformed += 1
+ return
+ if last_updated < since:
+ stats.dropped_before_since += 1
+ return
+ stats.reconcile_markers.setdefault((run_id, cohort_id), set()).add(partition)
+ stats.reconcile_markers_recorded += 1
+ stats.cohorts_seen.add(cohort_id)
+
+
def fold_membership_changes(
messages: Iterable[dict[str, Any]],
*,
@@ -57,13 +126,22 @@ def fold_membership_changes(
state: dict[int, dict[str, MembershipRecord]] = {}
for message in messages:
stats.total += 1
- if message.get("team_id") != team_id:
+ message_team_id = message.get("team_id")
+ if not isinstance(message_team_id, int) or isinstance(message_team_id, bool):
+ stats.dropped_malformed += 1
+ continue
+ if message_team_id != team_id:
stats.dropped_wrong_team += 1
continue
cohort_id = message.get("cohort_id")
+ 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)
+ continue
+
person_id = message.get("person_id")
status = message.get("status")
- last_updated = parse_last_updated(message.get("last_updated"))
if (
not isinstance(cohort_id, int)
or isinstance(cohort_id, bool)
@@ -84,13 +162,32 @@ def fold_membership_changes(
# its boundary (here and both readers in snapshots.py) or the sets stop matching.
key = person_id.lower()
prior = bucket.get(key)
+ origin = _optional_string(message.get("origin"))
+ run_id = _optional_string(message.get("run_id"))
if prior is None or last_updated >= prior.last_updated:
- bucket[key] = MembershipRecord(status=status, last_updated=last_updated)
+ bucket[key] = MembershipRecord(status=status, last_updated=last_updated, origin=origin, run_id=run_id)
stats.cohorts_seen.add(cohort_id)
stats.folded += 1
+ origin_key = origin or LIVE_ORIGIN
+ stats.folded_by_origin[origin_key] = stats.folded_by_origin.get(origin_key, 0) + 1
return state, stats
+def reconcile_completeness_by_cohort(stats: FoldStats) -> dict[int, tuple[ReconcileRunCompleteness, ...]]:
+ """Group deterministic per-run marker completeness by cohort in a single sorted pass."""
+ by_cohort: dict[int, list[ReconcileRunCompleteness]] = {}
+ for (run_id, cohort_id), partitions in sorted(stats.reconcile_markers.items()):
+ by_cohort.setdefault(cohort_id, []).append(
+ ReconcileRunCompleteness(run_id=run_id, cohort_id=cohort_id, partitions_seen=len(partitions))
+ )
+ return {cohort_id: tuple(runs) for cohort_id, runs in by_cohort.items()}
+
+
+def reconcile_completeness(stats: FoldStats, cohort_id: int) -> tuple[ReconcileRunCompleteness, ...]:
+ """Return deterministic per-run marker completeness for one cohort."""
+ return reconcile_completeness_by_cohort(stats).get(cohort_id, ())
+
+
def members(state: dict[str, MembershipRecord]) -> set[str]:
"""The currently-entered persons of one cohort's folded state."""
return {person_id for person_id, record in state.items() if record.status == "entered"}
@@ -99,8 +196,8 @@ def members(state: dict[str, MembershipRecord]) -> set[str]:
def observed(state: dict[str, MembershipRecord]) -> set[str]:
"""Every person the new pipeline emitted a decision for in this cohort.
- Emission is flip-only (see the Rust processor's stage1/transition + stage2/evaluator),
- so a first emission is always `entered`: the presence of a key means both pipelines
- have weighed in on that person, which is the universe the membership diff is bounded to.
+ Live and seed processing can be flip-only, while reconcile snapshots emit every current
+ decision. In either case, the presence of a key means the new pipeline has weighed in on
+ that person, which is the universe the membership diff is bounded to.
"""
return set(state.keys())
diff --git a/products/cohorts/backend/parity/report.py b/products/cohorts/backend/parity/report.py
index bf9660957440..020ada401f51 100644
--- a/products/cohorts/backend/parity/report.py
+++ b/products/cohorts/backend/parity/report.py
@@ -14,6 +14,7 @@ from products.cohorts.backend.parity.classifier import (
AggregateSummary,
CohortComparison,
)
+from products.cohorts.backend.parity.fold import ReconcileRunCompleteness
_VERDICT_ORDER = {VERDICT_FAIL: 0, VERDICT_WARMUP: 1, VERDICT_PASS: 2, VERDICT_SKIP: 3}
@@ -49,6 +50,18 @@ def format_notes(rows: Sequence[CohortComparison]) -> str:
return "\n".join(lines)
+def format_reconcile_notes(completeness: Sequence[ReconcileRunCompleteness]) -> tuple[str, ...]:
+ notes: list[str] = []
+ for run in sorted(completeness, key=lambda item: (item.run_id, item.cohort_id)):
+ partition_summary = (
+ f"{run.partitions_seen}/{run.expected_partitions}"
+ if run.complete
+ else f"partial {run.partitions_seen}/{run.expected_partitions}"
+ )
+ notes.append(f"reconcile run {run.run_id}: {partition_summary}")
+ return tuple(notes)
+
+
def format_summary(summary: AggregateSummary) -> str:
lines = [
f"verdicts: {summary.passed} PASS, {summary.failed} FAIL, {summary.warming_up} WARMUP, {summary.skipped} SKIP",
diff --git a/products/cohorts/backend/parity/test/test_classifier.py b/products/cohorts/backend/parity/test/test_classifier.py
index 14e4737f97b7..e83292edb54c 100644
--- a/products/cohorts/backend/parity/test/test_classifier.py
+++ b/products/cohorts/backend/parity/test/test_classifier.py
@@ -1,4 +1,5 @@
import math
+from dataclasses import replace
from datetime import UTC, datetime, timedelta
from django.test import SimpleTestCase
@@ -49,9 +50,33 @@ class TestClassifier(SimpleTestCase):
new_state={},
last_realtime_calculation_at=LAST_CALC,
config=_config(),
+ notes=("reconcile run r: partial 1/64",),
)
self.assertEqual(row.verdict, VERDICT_SKIP)
self.assertFalse(row.gated)
+ self.assertEqual(row.notes[0], "reconcile run r: partial 1/64")
+
+ def test_reconcile_note_does_not_change_classification_fields(self) -> None:
+ baseline = classify_cohort(
+ screened=_screened(),
+ name="x",
+ old_members={"a"},
+ new_state=_entered(["a"], at=NOW),
+ last_realtime_calculation_at=LAST_CALC,
+ config=_config(),
+ )
+ with_reconcile_note = classify_cohort(
+ screened=_screened(),
+ name="x",
+ old_members={"a"},
+ new_state=_entered(["a"], at=NOW),
+ last_realtime_calculation_at=LAST_CALC,
+ config=_config(),
+ notes=("reconcile run r: 64/64",),
+ )
+
+ self.assertEqual(replace(with_reconcile_note, notes=()), baseline)
+ self.assertEqual(with_reconcile_note.notes, ("reconcile run r: 64/64",))
def test_fresh_rule_explains_new_entries_after_last_recompute(self) -> None:
new_state = _entered(["a", "b"], at=NOW - timedelta(minutes=45)) | _entered(
diff --git a/products/cohorts/backend/parity/test/test_fold.py b/products/cohorts/backend/parity/test/test_fold.py
index 39856ac8d322..0937437f50fc 100644
--- a/products/cohorts/backend/parity/test/test_fold.py
+++ b/products/cohorts/backend/parity/test/test_fold.py
@@ -4,9 +4,18 @@ from django.test import SimpleTestCase
from parameterized import parameterized
-from products.cohorts.backend.parity.fold import fold_membership_changes, members, observed, parse_last_updated
+from products.cohorts.backend.parity.fold import (
+ LIVE_ORIGIN,
+ fold_membership_changes,
+ members,
+ observed,
+ parse_last_updated,
+ reconcile_completeness,
+)
SINCE = datetime(2026, 7, 7, 19, 0, tzinfo=UTC)
+RUN_1 = "00000000-0000-0000-0000-000000000001"
+RUN_2 = "00000000-0000-0000-0000-000000000002"
def _msg(status: str, ts: str, *, cohort_id: int | None = 10, person_id: str = "P1", team_id: int = 2) -> dict:
@@ -19,6 +28,30 @@ def _msg(status: str, ts: str, *, cohort_id: int | None = 10, person_id: str = "
}
+def _marker(
+ partition: int,
+ *,
+ run_id: str = RUN_1,
+ cohort_id: int = 10,
+ team_id: int = 2,
+ ts: str = "2026-07-07 19:05:00.000001",
+) -> dict:
+ return {
+ "type": "reconcile_complete",
+ "team_id": team_id,
+ "cohort_id": cohort_id,
+ "partition": partition,
+ "run_id": run_id,
+ "last_updated": ts,
+ }
+
+
+def _marker_without(field: str) -> dict:
+ marker = _marker(1)
+ del marker[field]
+ return marker
+
+
class TestFold(SimpleTestCase):
def test_last_message_wins_per_pair(self) -> None:
state, stats = fold_membership_changes(
@@ -86,6 +119,90 @@ class TestFold(SimpleTestCase):
self.assertEqual(members(state[10]), {"p2"})
self.assertEqual(stats.dropped_wrong_team, 1)
+ def test_reconcile_marker_is_recorded_before_membership_validation(self) -> None:
+ state, stats = fold_membership_changes(
+ [
+ _marker(7),
+ _msg("entered", "2026-07-07 19:06:00.000001") | {"origin": "reconcile", "run_id": RUN_1},
+ ],
+ team_id=2,
+ since=SINCE,
+ )
+
+ self.assertEqual(stats.reconcile_markers, {(RUN_1, 10): {7}})
+ self.assertEqual(stats.dropped_malformed, 0)
+ self.assertEqual(stats.cohorts_seen, {10})
+ self.assertEqual(state[10]["p1"].origin, "reconcile")
+ self.assertEqual(state[10]["p1"].run_id, RUN_1)
+
+ def test_membership_provenance_follows_lww_and_counts_every_folded_origin(self) -> None:
+ state, stats = fold_membership_changes(
+ [
+ _msg("entered", "2026-07-07 19:01:00.000001", person_id="P1"),
+ _msg("entered", "2026-07-07 19:02:00.000001", person_id="P2") | {"origin": "seed", "run_id": RUN_1},
+ _msg("left", "2026-07-07 19:03:00.000001", person_id="P1") | {"origin": "reconcile", "run_id": RUN_2},
+ ],
+ team_id=2,
+ since=SINCE,
+ )
+
+ self.assertEqual(stats.folded_by_origin, {LIVE_ORIGIN: 1, "seed": 1, "reconcile": 1})
+ self.assertEqual(
+ (state[10]["p1"].status, state[10]["p1"].origin, state[10]["p1"].run_id), ("left", "reconcile", RUN_2)
+ )
+ self.assertEqual((state[10]["p2"].origin, state[10]["p2"].run_id), ("seed", RUN_1))
+
+ def test_reconcile_completeness_is_per_run_and_counts_distinct_partitions(self) -> None:
+ messages = [*(_marker(partition, run_id=RUN_2) for partition in range(64))]
+ messages.extend(_marker(partition, run_id=RUN_1) for partition in range(41))
+ messages.append(_marker(0, run_id=RUN_1))
+ # A second cohort shares RUN_1 and covers exactly the partitions cohort 10 is missing
+ # (41..64); its markers must stay under their own cohort so RUN_1 does not read as a
+ # false 64/64 for cohort 10.
+ messages.extend(_marker(partition, run_id=RUN_1, cohort_id=20) for partition in range(41, 64))
+
+ _state, stats = fold_membership_changes(messages, team_id=2, since=SINCE)
+
+ completeness = reconcile_completeness(stats, cohort_id=10)
+ self.assertEqual(
+ [(run.run_id, run.partitions_seen, run.complete) for run in completeness],
+ [(RUN_1, 41, False), (RUN_2, 64, True)],
+ )
+ self.assertEqual(
+ [(run.run_id, run.partitions_seen, run.complete) for run in reconcile_completeness(stats, cohort_id=20)],
+ [(RUN_1, 23, False)],
+ )
+ # Counts every accepted marker message, including the RUN_1 partition-0 duplicate — 129,
+ # not the 128 distinct partitions the completeness sets hold. Keeps the summary's
+ # folded + drops + markers == total accounting exact.
+ self.assertEqual(stats.reconcile_markers_recorded, 129)
+
+ @parameterized.expand(
+ [
+ ("bad_run_id", _marker(1, run_id="not-a-uuid"), 2, 1, 0),
+ ("missing_run_id", _marker_without("run_id"), 2, 1, 0),
+ ("out_of_range_partition", _marker(64), 2, 1, 0),
+ ("missing_partition", _marker_without("partition"), 2, 1, 0),
+ ("missing_timestamp", _marker_without("last_updated"), 2, 1, 0),
+ ("float_team_id", _marker(1) | {"team_id": 2.0}, 2, 1, 0),
+ ("boolean_team_id", _marker(1, team_id=True), 1, 1, 0),
+ ("before_since", _marker(1, ts="2026-07-07 18:59:59.999999"), 2, 0, 1),
+ ]
+ )
+ def test_invalid_or_stale_markers_cannot_certify_reconcile(
+ self,
+ _name: str,
+ marker: dict,
+ team_id: int,
+ expected_malformed: int,
+ expected_before_since: int,
+ ) -> None:
+ _state, stats = fold_membership_changes([marker], team_id=team_id, since=SINCE)
+
+ self.assertEqual(stats.reconcile_markers, {})
+ self.assertEqual(stats.dropped_malformed, expected_malformed)
+ self.assertEqual(stats.dropped_before_since, expected_before_since)
+
@parameterized.expand(
[
("rust_microseconds", "2026-07-07 19:01:00.123456"),
diff --git a/products/cohorts/backend/parity/test/test_report.py b/products/cohorts/backend/parity/test/test_report.py
index 7546d46019eb..43e6ff4f8729 100644
--- a/products/cohorts/backend/parity/test/test_report.py
+++ b/products/cohorts/backend/parity/test/test_report.py
@@ -8,12 +8,23 @@ from products.cohorts.backend.parity.classifier import (
AggregateSummary,
CohortComparison,
)
-from products.cohorts.backend.parity.report import to_json
+from products.cohorts.backend.parity.fold import ReconcileRunCompleteness
+from products.cohorts.backend.parity.report import format_notes, format_reconcile_notes, to_json
-def _row(cohort_id: int, verdict: str, residual_pct: float = 0.0) -> CohortComparison:
+def _row(
+ cohort_id: int,
+ verdict: str,
+ residual_pct: float = 0.0,
+ notes: tuple[str, ...] = (),
+) -> CohortComparison:
return CohortComparison(
- cohort_id=cohort_id, name=f"c{cohort_id}", eligibility="single_leaf", verdict=verdict, residual_pct=residual_pct
+ cohort_id=cohort_id,
+ name=f"c{cohort_id}",
+ eligibility="single_leaf",
+ verdict=verdict,
+ residual_pct=residual_pct,
+ notes=notes,
)
@@ -32,3 +43,20 @@ class TestReport(SimpleTestCase):
[(5, VERDICT_FAIL), (3, VERDICT_FAIL), (4, VERDICT_WARMUP), (2, VERDICT_PASS), (1, VERDICT_SKIP)],
)
self.assertEqual(document["meta"], {"team_id": 2})
+
+ def test_reconcile_completeness_is_rendered_as_complete_or_partial_notes(self) -> None:
+ notes = format_reconcile_notes(
+ [
+ ReconcileRunCompleteness(run_id="run-b", cohort_id=10, partitions_seen=41),
+ ReconcileRunCompleteness(run_id="run-a", cohort_id=10, partitions_seen=64),
+ ]
+ )
+
+ self.assertEqual(notes, ("reconcile run run-a: 64/64", "reconcile run run-b: partial 41/64"))
+ row = _row(10, VERDICT_PASS, notes=notes)
+ self.assertEqual(
+ format_notes([row]),
+ " cohort 10: reconcile run run-a: 64/64\n cohort 10: reconcile run run-b: partial 41/64",
+ )
+ document = to_json([row], AggregateSummary(), {"team_id": 2})
+ self.assertEqual(document["cohorts"][0]["notes"], notes)
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 046a4f0785b7..d7d3c2d78154 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2239,6 +2239,7 @@ dependencies = [
"axum 0.7.9",
"chrono",
"chrono-tz",
+ "clap",
"clickhouse",
"cohort-core",
"common-alloc",
diff --git a/rust/affected-services/tests/integration.rs b/rust/affected-services/tests/integration.rs
index a2008bc69963..a8a757b13cfb 100644
--- a/rust/affected-services/tests/integration.rs
+++ b/rust/affected-services/tests/integration.rs
@@ -113,6 +113,7 @@ fn every_deployable_binary_has_an_image_entry() {
"hermes",
"personhog-stateright", // model-checker explorer CLI, not a service
"personhog-test-harness", // e2e load/correctness harness CLI, not a service
+ "reconcile_dispatch", // operator-invoked cohort reconcile dispatcher CLI, not a service
]
.into();
diff --git a/rust/cohort-seeder/Cargo.toml b/rust/cohort-seeder/Cargo.toml
index 2b05f081f7e7..aecddb9e0d4e 100644
--- a/rust/cohort-seeder/Cargo.toml
+++ b/rust/cohort-seeder/Cargo.toml
@@ -9,11 +9,16 @@ workspace = true
[features]
pg-test-support = []
+[[bin]]
+name = "reconcile_dispatch"
+path = "src/bin/reconcile_dispatch.rs"
+
[dependencies]
anyhow = { workspace = true }
axum = { workspace = true }
chrono = { workspace = true }
chrono-tz = { workspace = true }
+clap = { workspace = true }
clickhouse = { workspace = true }
cohort-core = { path = "../cohort-core" }
common-alloc = { path = "../common/alloc" }
diff --git a/rust/cohort-seeder/src/app/mod.rs b/rust/cohort-seeder/src/app/mod.rs
index f9ada2484a27..a4ee86e084ce 100644
--- a/rust/cohort-seeder/src/app/mod.rs
+++ b/rust/cohort-seeder/src/app/mod.rs
@@ -5,6 +5,7 @@ mod deliver;
mod execute;
mod orchestrator;
mod prepare;
+pub mod reconcile_dispatch;
pub mod settings;
pub use orchestrator::{SeederOrchestrator, ORCHESTRATOR_LIVENESS_DEADLINE};
diff --git a/rust/cohort-seeder/src/app/reconcile_dispatch.rs b/rust/cohort-seeder/src/app/reconcile_dispatch.rs
new file mode 100644
index 000000000000..d0a7f4ba370f
--- /dev/null
+++ b/rust/cohort-seeder/src/app/reconcile_dispatch.rs
@@ -0,0 +1,636 @@
+//! Manual reconcile dispatch orchestration. Database validation and partition-layout verification
+//! finish before the first control tile is enqueued; all enqueued deliveries are drained before an
+//! error is returned.
+
+use std::collections::{BTreeMap, VecDeque};
+use std::future::Future;
+use std::num::NonZeroUsize;
+use std::pin::Pin;
+use std::time::Duration;
+
+use cohort_core::partitioner::COHORT_PARTITION_COUNT;
+use rdkafka::error::KafkaError;
+use sqlx::PgPool;
+
+use crate::domain::{ReconcileTile, RunId};
+use crate::kafka::producer::{
+ EnqueueError, PartitionCountError, SeedPartition, SeedPartitionCountError, SeedTileProducer,
+};
+use crate::store::chunks::{ChunkStoreError, PgChunkStore};
+use crate::store::runs::{load_reconcile_run, ReconcileRun, ReconcileRunError, RunStatus};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CompletionRequirement {
+ Complete,
+ AllowIncomplete,
+}
+
+/// Operator attestation that this run's data tiles were seeded or replayed after membership-register
+/// writers were deployed.
+///
+/// The database does not persist a writer-version boundary, so pre-register runs cannot prove that
+/// their Stage 2 scan domain is complete. Requiring this capability at the dispatch boundary keeps
+/// that residual explicit instead of emitting a false completion certificate.
+#[must_use]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct RegisterBackfillConfirmation(());
+
+impl RegisterBackfillConfirmation {
+ pub const fn confirmed_by_operator() -> Self {
+ Self(())
+ }
+}
+
+/// A run capability minted only after its status, active participations, hashes, and chunk ledger
+/// satisfy the operator's completion requirement.
+#[derive(Debug)]
+pub struct PreparedReconcileDispatch {
+ run: ReconcileRun,
+ total_chunks: u64,
+ remaining_chunks: u64,
+}
+
+impl PreparedReconcileDispatch {
+ pub const fn run_id(&self) -> RunId {
+ self.run.run_id()
+ }
+
+ pub fn cohort_count(&self) -> usize {
+ self.run.cohort_count()
+ }
+
+ pub const fn total_chunks(&self) -> u64 {
+ self.total_chunks
+ }
+
+ pub const fn remaining_chunks(&self) -> u64 {
+ self.remaining_chunks
+ }
+}
+
+pub async fn prepare_reconcile_dispatch(
+ pool: &PgPool,
+ run_id: RunId,
+ completion: CompletionRequirement,
+ _register_backfill: RegisterBackfillConfirmation,
+) -> Result<PreparedReconcileDispatch, PrepareReconcileDispatchError> {
+ let run = load_reconcile_run(pool, run_id).await?;
+ let progress = PgChunkStore::new(pool.clone())
+ .chunk_progress(run_id)
+ .await?;
+ validate_completion(
+ run_id,
+ run.status(),
+ progress.total(),
+ progress.remaining(),
+ completion,
+ )?;
+ Ok(PreparedReconcileDispatch {
+ run,
+ total_chunks: progress.total(),
+ remaining_chunks: progress.remaining(),
+ })
+}
+
+fn validate_completion(
+ run_id: RunId,
+ status: RunStatus,
+ total_chunks: u64,
+ remaining_chunks: u64,
+ completion: CompletionRequirement,
+) -> Result<(), PrepareReconcileDispatchError> {
+ if completion == CompletionRequirement::Complete {
+ if remaining_chunks != 0 {
+ return Err(PrepareReconcileDispatchError::Incomplete {
+ run_id,
+ remaining_chunks,
+ });
+ }
+ if total_chunks == 0 && status == RunStatus::Seeding {
+ return Err(PrepareReconcileDispatchError::EmptyChunkLedger(run_id));
+ }
+ }
+ Ok(())
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum PrepareReconcileDispatchError {
+ #[error(transparent)]
+ Run(#[from] ReconcileRunError),
+ #[error("reading the run's chunk ledger")]
+ Chunks(#[from] ChunkStoreError),
+ #[error("run {run_id:?} still has {remaining_chunks} unconfirmed chunks")]
+ Incomplete {
+ run_id: RunId,
+ remaining_chunks: u64,
+ },
+ #[error(
+ "seeding run {0:?} has no chunk rows, so dispatch cannot prove planning has completed; use --allow-incomplete to override"
+ )]
+ EmptyChunkLedger(RunId),
+}
+
+/// Highest acknowledged reconcile-control offset for every seed partition. A team-wide run may
+/// enqueue several cohorts to one partition, so the maximum is the run's useful partition HWM.
+#[derive(Debug, Clone, PartialEq, Eq, Default)]
+pub struct ReconcileDispatchReceipt {
+ offsets: BTreeMap<SeedPartition, i64>,
+}
+
+impl ReconcileDispatchReceipt {
+ pub fn offsets(&self) -> impl ExactSizeIterator<Item = (SeedPartition, i64)> + '_ {
+ self.offsets
+ .iter()
+ .map(|(partition, offset)| (*partition, *offset))
+ }
+
+ fn observe(&mut self, partition: SeedPartition, offset: i64) {
+ self.offsets
+ .entry(partition)
+ .and_modify(|current| *current = (*current).max(offset))
+ .or_insert(offset);
+ }
+}
+
+pub async fn execute_reconcile_dispatch(
+ prepared: PreparedReconcileDispatch,
+ producer: &SeedTileProducer,
+ max_inflight: NonZeroUsize,
+ metadata_timeout: Duration,
+) -> Result<ReconcileDispatchReceipt, ReconcileDispatchError> {
+ let partitions = SeedPartition::all(COHORT_PARTITION_COUNT)?.collect::<Vec<_>>();
+ let verify_producer = producer.clone();
+ tokio::task::spawn_blocking(move || {
+ verify_producer.verify_partition_count(COHORT_PARTITION_COUNT, metadata_timeout)
+ })
+ .await
+ .map_err(ReconcileDispatchError::PartitionVerificationTask)??;
+
+ let tiles = prepared.run.tiles().collect::<Vec<_>>();
+ produce_reconcile_tiles(tiles, producer, &partitions, max_inflight).await
+}
+
+type ReconcileDelivery =
+ Pin<Box<dyn Future<Output = Result<(i32, i64), KafkaError>> + Send + 'static>>;
+
+trait ReconcileProducer {
+ fn enqueue(
+ &self,
+ tile: &ReconcileTile,
+ partition: SeedPartition,
+ ) -> Result<ReconcileDelivery, EnqueueError>;
+}
+
+impl ReconcileProducer for SeedTileProducer {
+ fn enqueue(
+ &self,
+ tile: &ReconcileTile,
+ partition: SeedPartition,
+ ) -> Result<ReconcileDelivery, EnqueueError> {
+ let delivery = SeedTileProducer::enqueue_reconcile(self, tile, partition)?;
+ Ok(Box::pin(async move {
+ match delivery.await {
+ Ok(Ok(coordinates)) => Ok(coordinates),
+ Ok(Err((error, _))) => Err(error),
+ Err(_) => Err(KafkaError::Canceled),
+ }
+ }))
+ }
+}
+
+async fn produce_reconcile_tiles<P: ReconcileProducer>(
+ tiles: impl IntoIterator<Item = ReconcileTile>,
+ producer: &P,
+ partitions: &[SeedPartition],
+ max_inflight: NonZeroUsize,
+) -> Result<ReconcileDispatchReceipt, ReconcileDispatchError> {
+ let mut pending = VecDeque::new();
+ let mut receipt = ReconcileDispatchReceipt::default();
+ let mut failures = DeliveryFailures::default();
+ let mut enqueue_error = None;
+
+ 'tiles: for tile in tiles {
+ for partition in partitions.iter().copied() {
+ loop {
+ match producer.enqueue(&tile, partition) {
+ Ok(delivery) => {
+ pending.push_back(PendingDelivery {
+ partition,
+ delivery,
+ });
+ break;
+ }
+ Err(EnqueueError::QueueFull) if !pending.is_empty() => {
+ observe_next(&mut pending, &mut receipt, &mut failures).await;
+ }
+ Err(error) => {
+ enqueue_error = Some(error);
+ break 'tiles;
+ }
+ }
+ }
+
+ if pending.len() >= max_inflight.get() {
+ observe_next(&mut pending, &mut receipt, &mut failures).await;
+ }
+ }
+ }
+
+ while !pending.is_empty() {
+ observe_next(&mut pending, &mut receipt, &mut failures).await;
+ }
+
+ if let Some(error) = enqueue_error {
+ return Err(ReconcileDispatchError::Enqueue(error));
+ }
+ if let Some(error) = failures.into_error() {
+ return Err(ReconcileDispatchError::Delivery(error));
+ }
+ Ok(receipt)
+}
+
+struct PendingDelivery {
+ partition: SeedPartition,
+ delivery: ReconcileDelivery,
+}
+
+async fn observe_next(
+ pending: &mut VecDeque<PendingDelivery>,
+ receipt: &mut ReconcileDispatchReceipt,
+ failures: &mut DeliveryFailures,
+) {
+ let pending = pending
+ .pop_front()
+ .expect("observe_next is only called for a non-empty delivery queue");
+ let expected_partition = i32::from(pending.partition.as_u16());
+ match pending.delivery.await {
+ Ok((actual_partition, offset)) if actual_partition == expected_partition && offset >= 0 => {
+ receipt.observe(pending.partition, offset);
+ }
+ Ok((actual_partition, _)) if actual_partition != expected_partition => {
+ failures.record(ReconcileDeliveryFailure::UnexpectedPartition {
+ expected: pending.partition,
+ actual: actual_partition,
+ });
+ }
+ Ok((_, offset)) => {
+ failures.record(ReconcileDeliveryFailure::NegativeOffset {
+ partition: pending.partition,
+ offset,
+ });
+ }
+ Err(error) => failures.record(ReconcileDeliveryFailure::Kafka(error)),
+ }
+}
+
+#[derive(Debug, Default)]
+struct DeliveryFailures {
+ count: usize,
+ first: Option<ReconcileDeliveryFailure>,
+}
+
+impl DeliveryFailures {
+ fn record(&mut self, failure: ReconcileDeliveryFailure) {
+ self.count += 1;
+ if self.first.is_none() {
+ self.first = Some(failure);
+ }
+ }
+
+ fn into_error(self) -> Option<ReconcileDeliveryFailures> {
+ self.first.map(|first| ReconcileDeliveryFailures {
+ count: self.count,
+ first,
+ })
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum ReconcileDispatchError {
+ #[error(transparent)]
+ InvalidPartitionCount(#[from] SeedPartitionCountError),
+ #[error("joining the seed-topic partition verification task")]
+ PartitionVerificationTask(#[source] tokio::task::JoinError),
+ #[error("verifying the seed-topic partition count")]
+ TopicPartitionCount(#[from] PartitionCountError),
+ #[error("enqueuing a reconcile control tile")]
+ Enqueue(#[source] EnqueueError),
+ #[error(transparent)]
+ Delivery(#[from] ReconcileDeliveryFailures),
+}
+
+#[derive(Debug, thiserror::Error)]
+#[error("{count} reconcile control tile deliveries failed; first failure: {first}")]
+pub struct ReconcileDeliveryFailures {
+ count: usize,
+ #[source]
+ first: ReconcileDeliveryFailure,
+}
+
+#[derive(Debug, thiserror::Error)]
+enum ReconcileDeliveryFailure {
+ #[error("Kafka rejected the delivery: {0}")]
+ Kafka(#[source] KafkaError),
+ #[error("partition {expected} was acknowledged as partition {actual}")]
+ UnexpectedPartition {
+ expected: SeedPartition,
+ actual: i32,
+ },
+ #[error("partition {partition} was acknowledged with invalid offset {offset}")]
+ NegativeOffset {
+ partition: SeedPartition,
+ offset: i64,
+ },
+}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::{HashMap, HashSet};
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ use std::sync::{Arc, Mutex};
+
+ use cohort_core::filters::{CohortId, TeamId};
+ use uuid::Uuid;
+
+ use super::*;
+
+ #[test]
+ fn completion_requirement_fails_closed_for_unplanned_seeding_runs() {
+ let run_id = RunId(Uuid::nil());
+ assert!(validate_completion(
+ run_id,
+ RunStatus::Seeding,
+ 3,
+ 0,
+ CompletionRequirement::Complete,
+ )
+ .is_ok());
+ assert!(validate_completion(
+ run_id,
+ RunStatus::Reconciling,
+ 0,
+ 0,
+ CompletionRequirement::Complete,
+ )
+ .is_ok());
+ assert!(validate_completion(
+ run_id,
+ RunStatus::Seeding,
+ 0,
+ 0,
+ CompletionRequirement::AllowIncomplete,
+ )
+ .is_ok());
+ assert!(matches!(
+ validate_completion(
+ run_id,
+ RunStatus::Seeding,
+ 3,
+ 2,
+ CompletionRequirement::Complete,
+ ),
+ Err(PrepareReconcileDispatchError::Incomplete {
+ remaining_chunks: 2,
+ ..
+ })
+ ));
+ assert!(matches!(
+ validate_completion(
+ run_id,
+ RunStatus::Seeding,
+ 0,
+ 0,
+ CompletionRequirement::Complete,
+ ),
+ Err(PrepareReconcileDispatchError::EmptyChunkLedger(id)) if id == run_id
+ ));
+ }
+
+ #[tokio::test]
+ async fn dispatch_covers_every_cohort_partition_and_reports_bounded_hwm() {
+ let partitions = SeedPartition::all(64).unwrap().collect::<Vec<_>>();
+ let producer = FakeProducer::new([]);
+ let receipt = produce_reconcile_tiles(
+ [tile(41), tile(42)],
+ &producer,
+ &partitions,
+ NonZeroUsize::new(5).unwrap(),
+ )
+ .await
+ .unwrap();
+
+ let calls = producer.calls();
+ assert_eq!(calls.len(), 128);
+ assert_eq!(
+ calls
+ .iter()
+ .map(|call| (call.cohort_id, call.partition))
+ .collect::<HashSet<_>>()
+ .len(),
+ 128,
+ );
+ assert_eq!(producer.deliveries.resolved.load(Ordering::SeqCst), 128);
+ assert_eq!(producer.deliveries.current.load(Ordering::SeqCst), 0);
+ assert_eq!(producer.deliveries.maximum.load(Ordering::SeqCst), 5);
+
+ assert_eq!(
+ receipt
+ .offsets()
+ .map(|(partition, offset)| (partition.as_u16(), offset))
+ .collect::<Vec<_>>(),
+ (0_u16..64)
+ .map(|partition| (partition, i64::from(partition) + 1_000))
+ .collect::<Vec<_>>(),
+ );
+ }
+
+ #[tokio::test]
+ async fn queue_full_drains_one_delivery_then_retries_the_same_target() {
+ let partitions = SeedPartition::all(2).unwrap().collect::<Vec<_>>();
+ let producer = FakeProducer::new([
+ ScriptedOutcome::Ack,
+ ScriptedOutcome::QueueFull,
+ ScriptedOutcome::Ack,
+ ]);
+
+ let receipt = produce_reconcile_tiles(
+ [tile(41)],
+ &producer,
+ &partitions,
+ NonZeroUsize::new(10).unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(producer.calls().len(), 3);
+ assert_eq!(producer.deliveries.resolved.load(Ordering::SeqCst), 2);
+ assert_eq!(receipt.offsets().len(), 2);
+ }
+
+ #[tokio::test]
+ async fn nack_and_fatal_enqueue_drain_every_already_enqueued_delivery() {
+ let partitions = SeedPartition::all(3).unwrap().collect::<Vec<_>>();
+ let nack = FakeProducer::new([
+ ScriptedOutcome::Nack,
+ ScriptedOutcome::Ack,
+ ScriptedOutcome::Ack,
+ ]);
+ let nack_error = produce_reconcile_tiles(
+ [tile(41)],
+ &nack,
+ &partitions,
+ NonZeroUsize::new(3).unwrap(),
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(
+ nack_error,
+ ReconcileDispatchError::Delivery(ReconcileDeliveryFailures { count: 1, .. })
+ ));
+ assert_eq!(nack.deliveries.resolved.load(Ordering::SeqCst), 3);
+
+ let fatal = FakeProducer::new([ScriptedOutcome::Ack, ScriptedOutcome::Fatal]);
+ let fatal_error = produce_reconcile_tiles(
+ [tile(41)],
+ &fatal,
+ &partitions,
+ NonZeroUsize::new(3).unwrap(),
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(fatal_error, ReconcileDispatchError::Enqueue(_)));
+ assert_eq!(fatal.calls().len(), 2);
+ assert_eq!(fatal.deliveries.resolved.load(Ordering::SeqCst), 1);
+ }
+
+ #[tokio::test]
+ async fn invalid_delivery_coordinates_fail_the_dispatch() {
+ let partition = SeedPartition::all(1).unwrap().collect::<Vec<_>>();
+ for outcome in [
+ ScriptedOutcome::UnexpectedPartition,
+ ScriptedOutcome::NegativeOffset,
+ ] {
+ let producer = FakeProducer::new([outcome]);
+ assert!(matches!(
+ produce_reconcile_tiles([tile(41)], &producer, &partition, NonZeroUsize::MIN,)
+ .await,
+ Err(ReconcileDispatchError::Delivery(
+ ReconcileDeliveryFailures { count: 1, .. }
+ ))
+ ));
+ assert_eq!(producer.deliveries.resolved.load(Ordering::SeqCst), 1);
+ }
+ }
+
+ fn tile(cohort_id: i32) -> ReconcileTile {
+ ReconcileTile::new(
+ TeamId(2),
+ CohortId(cohort_id),
+ crate::domain::BehavioralShapeHash::parse("behavioral-shape").unwrap(),
+ RunId(Uuid::nil()),
+ )
+ }
+
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+ enum ScriptedOutcome {
+ Ack,
+ QueueFull,
+ Fatal,
+ Nack,
+ UnexpectedPartition,
+ NegativeOffset,
+ }
+
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+ struct RecordedEnqueue {
+ cohort_id: CohortId,
+ partition: SeedPartition,
+ }
+
+ #[derive(Debug, Default)]
+ struct DeliveryStats {
+ current: AtomicUsize,
+ maximum: AtomicUsize,
+ resolved: AtomicUsize,
+ }
+
+ #[derive(Debug, Default)]
+ struct FakeState {
+ scripts: VecDeque<ScriptedOutcome>,
+ calls: Vec<RecordedEnqueue>,
+ next_offsets: HashMap<SeedPartition, i64>,
+ }
+
+ #[derive(Debug)]
+ struct FakeProducer {
+ state: Mutex<FakeState>,
+ deliveries: Arc<DeliveryStats>,
+ }
+
+ impl FakeProducer {
+ fn new(scripts: impl IntoIterator<Item = ScriptedOutcome>) -> Self {
+ Self {
+ state: Mutex::new(FakeState {
+ scripts: scripts.into_iter().collect(),
+ ..FakeState::default()
+ }),
+ deliveries: Arc::new(DeliveryStats::default()),
+ }
+ }
+
+ fn calls(&self) -> Vec<RecordedEnqueue> {
+ self.state.lock().unwrap().calls.clone()
+ }
+
+ fn delivery(&self, result: Result<(i32, i64), KafkaError>) -> ReconcileDelivery {
+ let deliveries = Arc::clone(&self.deliveries);
+ let current = deliveries.current.fetch_add(1, Ordering::SeqCst) + 1;
+ deliveries.maximum.fetch_max(current, Ordering::SeqCst);
+ Box::pin(async move {
+ deliveries.current.fetch_sub(1, Ordering::SeqCst);
+ deliveries.resolved.fetch_add(1, Ordering::SeqCst);
+ result
+ })
+ }
+ }
+
+ impl ReconcileProducer for FakeProducer {
+ fn enqueue(
+ &self,
+ tile: &ReconcileTile,
+ partition: SeedPartition,
+ ) -> Result<ReconcileDelivery, EnqueueError> {
+ let mut state = self.state.lock().unwrap();
+ state.calls.push(RecordedEnqueue {
+ cohort_id: tile.cohort_id(),
+ partition,
+ });
+ let outcome = state.scripts.pop_front().unwrap_or(ScriptedOutcome::Ack);
+ match outcome {
+ ScriptedOutcome::QueueFull => return Err(EnqueueError::QueueFull),
+ ScriptedOutcome::Fatal => {
+ return Err(EnqueueError::Fatal(KafkaError::Canceled));
+ }
+ _ => {}
+ }
+
+ let next_offset = state
+ .next_offsets
+ .entry(partition)
+ .or_insert_with(|| i64::from(partition.as_u16()));
+ let offset = *next_offset;
+ *next_offset += 1_000;
+ drop(state);
+
+ let expected_partition = i32::from(partition.as_u16());
+ let result = match outcome {
+ ScriptedOutcome::Ack => Ok((expected_partition, offset)),
+ ScriptedOutcome::Nack => Err(KafkaError::Canceled),
+ ScriptedOutcome::UnexpectedPartition => Ok((expected_partition + 1, offset)),
+ ScriptedOutcome::NegativeOffset => Ok((expected_partition, -1)),
+ ScriptedOutcome::QueueFull | ScriptedOutcome::Fatal => unreachable!(),
+ };
+ Ok(self.delivery(result))
+ }
+ }
+}
diff --git a/rust/cohort-seeder/src/bin/reconcile_dispatch.rs b/rust/cohort-seeder/src/bin/reconcile_dispatch.rs
new file mode 100644
index 000000000000..7b547013c255
--- /dev/null
+++ b/rust/cohort-seeder/src/bin/reconcile_dispatch.rs
@@ -0,0 +1,152 @@
+//! Operator-invoked reconcile control-tile dispatcher.
+
+use std::num::NonZeroUsize;
+use std::time::Duration;
+
+use anyhow::{Context, Result};
+use clap::Parser;
+use cohort_core::partitioner::COHORT_PARTITION_COUNT;
+use cohort_seeder::app::reconcile_dispatch::{
+ execute_reconcile_dispatch, prepare_reconcile_dispatch, CompletionRequirement,
+ RegisterBackfillConfirmation,
+};
+use cohort_seeder::config::Config;
+use cohort_seeder::domain::RunId;
+use cohort_seeder::kafka::producer::SeedTileProducer;
+use common_database::get_pool_with_config;
+use envconfig::Envconfig;
+use uuid::Uuid;
+
+common_alloc::used!();
+
+const PARTITION_VERIFY_TIMEOUT: Duration = Duration::from_secs(10);
+
+#[derive(Debug, Parser)]
+#[command(
+ name = "reconcile_dispatch",
+ about = "Dispatch partition-targeted reconcile snapshots for one behavioral cohort backfill run"
+)]
+struct Args {
+ /// Behavioral cohort backfill run UUID.
+ run_id: Uuid,
+
+ /// Dispatch while the run still has unconfirmed data chunks. Intended for development only.
+ #[arg(long)]
+ allow_incomplete: bool,
+
+ /// Confirm that this run's data tiles were seeded or replayed after membership-register writers
+ /// were deployed. Required because older runs cannot provide a complete reconcile scan domain.
+ #[arg(long, required = true)]
+ confirm_register_backfilled: bool,
+}
+
+fn main() -> Result<()> {
+ let args = Args::parse();
+ let config = Config::init_from_env().context("loading cohort-seeder configuration")?;
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .context("building tokio runtime")?;
+ runtime.block_on(async_main(args, config))
+}
+
+async fn async_main(args: Args, config: Config) -> Result<()> {
+ validate_partition_count(config.cohort_partition_count)?;
+ let run_id = RunId(args.run_id);
+ let pool = get_pool_with_config(&config.database_url, config.pool_config())
+ .context("creating cohort-seeder PostgreSQL pool")?;
+ let completion = if args.allow_incomplete {
+ CompletionRequirement::AllowIncomplete
+ } else {
+ CompletionRequirement::Complete
+ };
+ let register_backfill = args
+ .confirm_register_backfilled
+ .then_some(RegisterBackfillConfirmation::confirmed_by_operator())
+ .expect("clap requires --confirm-register-backfilled");
+ let prepared = prepare_reconcile_dispatch(&pool, run_id, completion, register_backfill)
+ .await
+ .context("validating reconcile dispatch")?;
+ if prepared.remaining_chunks() != 0 {
+ eprintln!(
+ "Warning: dispatching run {} with {} unconfirmed chunks because --allow-incomplete was set.",
+ prepared.run_id().0,
+ prepared.remaining_chunks(),
+ );
+ } else if args.allow_incomplete && prepared.total_chunks() == 0 {
+ eprintln!(
+ "Warning: dispatching run {} with an empty chunk ledger because --allow-incomplete was set.",
+ prepared.run_id().0,
+ );
+ }
+ eprintln!(
+ "Dispatching {} active cohorts across {} seed partitions for run {}.",
+ prepared.cohort_count(),
+ COHORT_PARTITION_COUNT,
+ prepared.run_id().0,
+ );
+
+ let producer = SeedTileProducer::new(
+ &config.build_kafka_config(),
+ config.seed_events_topic.clone(),
+ )
+ .await
+ .context("creating seed tile producer")?;
+ let max_inflight = NonZeroUsize::new(config.seeder_max_inflight_tiles)
+ .context("SEEDER_MAX_INFLIGHT_TILES must be greater than zero")?;
+ let receipt =
+ execute_reconcile_dispatch(prepared, &producer, max_inflight, PARTITION_VERIFY_TIMEOUT)
+ .await
+ .context("dispatching reconcile control tiles")?;
+
+ for (partition, offset) in receipt.offsets() {
+ println!("partition {}: {}", partition.as_u16(), offset);
+ }
+ Ok(())
+}
+
+fn validate_partition_count(configured: u32) -> Result<()> {
+ anyhow::ensure!(
+ configured == COHORT_PARTITION_COUNT,
+ "COHORT_PARTITION_COUNT must be {COHORT_PARTITION_COUNT} for reconcile dispatch, got {}",
+ configured,
+ );
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const RUN_ID: &str = "0190f909-a2c1-7000-8000-000000000001";
+
+ #[test]
+ fn cli_requires_register_backfill_confirmation() {
+ let args = Args::try_parse_from([
+ "reconcile_dispatch",
+ RUN_ID,
+ "--allow-incomplete",
+ "--confirm-register-backfilled",
+ ])
+ .unwrap();
+ assert_eq!(args.run_id, Uuid::parse_str(RUN_ID).unwrap());
+ assert!(args.allow_incomplete);
+ assert!(args.confirm_register_backfilled);
+
+ assert!(Args::try_parse_from(["reconcile_dispatch"]).is_err());
+ assert!(Args::try_parse_from(["reconcile_dispatch", RUN_ID]).is_err());
+ assert!(Args::try_parse_from([
+ "reconcile_dispatch",
+ RUN_ID,
+ RUN_ID,
+ "--confirm-register-backfilled",
+ ])
+ .is_err());
+ }
+
+ #[test]
+ fn cli_rejects_a_noncontract_partition_count() {
+ assert!(validate_partition_count(COHORT_PARTITION_COUNT).is_ok());
+ assert!(validate_partition_count(8).is_err());
+ }
+}
diff --git a/rust/cohort-seeder/src/domain/mod.rs b/rust/cohort-seeder/src/domain/mod.rs
index 9e4ff9ab4e0b..3215f1d9d9b5 100644
--- a/rust/cohort-seeder/src/domain/mod.rs
+++ b/rust/cohort-seeder/src/domain/mod.rs
@@ -22,7 +22,9 @@ pub use chunk::{
ClaimKind, ClaimedChunk, EnqueuedChunk, HaltReason, Halted, ProduceHwms, ProducedChunk,
ScannedChunk, UnknownChunkStatus,
};
-pub use cohort_core::seed::SeedTile;
+pub use cohort_core::seed::{
+ BehavioralShapeHash, BehavioralShapeHashError, ReconcileTile, SeedTile,
+};
pub use condition::{EventNameSet, Lookback, PinnedCondition};
pub use ids::{
Band, ChunkId, ClaimEpoch, ConditionHash, ConditionHashError, DayIdx, RunId, SChunkMs,
diff --git a/rust/cohort-seeder/src/kafka/producer.rs b/rust/cohort-seeder/src/kafka/producer.rs
index b79ea0b73bf9..a4f112e15d5d 100644
--- a/rust/cohort-seeder/src/kafka/producer.rs
+++ b/rust/cohort-seeder/src/kafka/producer.rs
@@ -4,6 +4,7 @@
//! (pacing, in-flight bound, mark-produced, delivery acks) lives above, in the orchestrator, so this
//! module carries no PostgreSQL dependency.
+use std::fmt;
use std::time::Duration;
use common_kafka::config::KafkaConfig;
@@ -12,7 +13,79 @@ use common_liveness::SyncLivenessReporter;
use rdkafka::error::{KafkaError, RDKafkaErrorCode};
use rdkafka::producer::{DeliveryFuture, FutureProducer, FutureRecord, Producer};
-use crate::domain::SeedTile;
+use crate::domain::{ReconcileTile, SeedTile};
+
+const MAX_SEED_PARTITION_COUNT: u32 = 65_536;
+
+/// A seed-topic partition proven to fit both Kafka's signed partition field and this service's
+/// compact partition representation. Values can only be minted by [`SeedPartition::all`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct SeedPartition(u16);
+
+impl SeedPartition {
+ pub fn all(count: u32) -> Result<SeedPartitions, SeedPartitionCountError> {
+ if count == 0 {
+ return Err(SeedPartitionCountError::Zero);
+ }
+ if count > MAX_SEED_PARTITION_COUNT {
+ return Err(SeedPartitionCountError::TooLarge(count));
+ }
+ Ok(SeedPartitions { next: 0, count })
+ }
+
+ pub const fn as_u16(self) -> u16 {
+ self.0
+ }
+
+ const fn as_i32(self) -> i32 {
+ self.0 as i32
+ }
+}
+
+impl fmt::Display for SeedPartition {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ self.0.fmt(formatter)
+ }
+}
+
+/// The exact sequence `0..count` returned after [`SeedPartition::all`] proves every index fits.
+#[derive(Debug, Clone)]
+pub struct SeedPartitions {
+ next: u32,
+ count: u32,
+}
+
+impl Iterator for SeedPartitions {
+ type Item = SeedPartition;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if self.next == self.count {
+ return None;
+ }
+ let partition = u16::try_from(self.next)
+ .expect("partition count validation proves every partition index fits u16");
+ self.next += 1;
+ Some(SeedPartition(partition))
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ let remaining = usize::try_from(self.count - self.next)
+ .expect("a u32 partition count fits usize on supported targets");
+ (remaining, Some(remaining))
+ }
+}
+
+impl ExactSizeIterator for SeedPartitions {}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+pub enum SeedPartitionCountError {
+ #[error("seed partition count must be greater than zero")]
+ Zero,
+ #[error(
+ "seed partition count {0} exceeds the largest u16-indexed partition set ({MAX_SEED_PARTITION_COUNT})"
+ )]
+ TooLarge(u32),
+}
#[derive(Debug, thiserror::Error)]
pub enum EnqueueError {
@@ -92,6 +165,22 @@ impl SeedTileProducer {
.map_err(|(error, _)| error.into())
}
+ pub fn enqueue_reconcile(
+ &self,
+ tile: &ReconcileTile,
+ partition: SeedPartition,
+ ) -> Result<DeliveryFuture, EnqueueError> {
+ let payload = serde_json::to_vec(tile).expect("ReconcileTile serialization cannot fail");
+ let key = reconcile_partition_key(tile);
+ let record = FutureRecord::to(&self.topic)
+ .partition(partition.as_i32())
+ .key(&key)
+ .payload(&payload);
+ self.producer
+ .send_result(record)
+ .map_err(|(error, _)| error.into())
+ }
+
pub fn flush(&self, timeout: Duration) -> Result<(), KafkaError> {
self.producer.flush(timeout)
}
@@ -130,10 +219,63 @@ impl SyncLivenessReporter for AlwaysHealthy {
fn report_unhealthy(&self) {}
}
+fn reconcile_partition_key(tile: &ReconcileTile) -> String {
+ format!(
+ "{}:{}:{}",
+ tile.team_id().0,
+ tile.cohort_id().0,
+ tile.run_id().0
+ )
+}
+
#[cfg(test)]
mod tests {
+ use cohort_core::filters::{CohortId, TeamId};
+ use uuid::Uuid;
+
use super::*;
+ #[test]
+ fn seed_partitions_cover_exactly_the_valid_partition_domain() {
+ let partitions = SeedPartition::all(64).unwrap().collect::<Vec<_>>();
+ assert_eq!(partitions.len(), 64);
+ assert_eq!(partitions.first().unwrap().as_u16(), 0);
+ assert_eq!(partitions.last().unwrap().as_u16(), 63);
+
+ assert_eq!(
+ SeedPartition::all(MAX_SEED_PARTITION_COUNT)
+ .unwrap()
+ .last()
+ .unwrap()
+ .as_u16(),
+ u16::MAX,
+ );
+ assert!(matches!(
+ SeedPartition::all(0),
+ Err(SeedPartitionCountError::Zero)
+ ));
+ assert!(matches!(
+ SeedPartition::all(MAX_SEED_PARTITION_COUNT + 1),
+ Err(SeedPartitionCountError::TooLarge(count))
+ if count == MAX_SEED_PARTITION_COUNT + 1
+ ));
+ }
+
+ #[test]
+ fn reconcile_key_identifies_the_run_and_cohort() {
+ let tile = ReconcileTile::new(
+ TeamId(2),
+ CohortId(42),
+ crate::domain::BehavioralShapeHash::parse("shape").unwrap(),
+ crate::domain::RunId(Uuid::nil()),
+ );
+
+ assert_eq!(
+ reconcile_partition_key(&tile),
+ "2:42:00000000-0000-0000-0000-000000000000"
+ );
+ }
+
#[test]
fn enqueue_error_splits_queue_full_from_fatal() {
assert!(matches!(
diff --git a/rust/cohort-seeder/src/store/chunks.rs b/rust/cohort-seeder/src/store/chunks.rs
index f77dde9c20bd..e35e62b45903 100644
--- a/rust/cohort-seeder/src/store/chunks.rs
+++ b/rust/cohort-seeder/src/store/chunks.rs
@@ -284,6 +284,32 @@ impl PgChunkStore {
u64::try_from(count).map_err(|_| ChunkStoreError::InvalidRemainingCount(count))
}
+ pub async fn chunk_progress(&self, run_id: RunId) -> Result<ChunkProgress, ChunkStoreError> {
+ let row = sqlx::query_as::<_, ChunkProgressRow>(
+ r#"
+ SELECT count(*)::bigint AS total,
+ count(*) FILTER (WHERE status <> $2)::bigint AS remaining
+ FROM cohort_backfill_chunks
+ WHERE run_id = $1
+ "#,
+ )
+ .bind(run_id)
+ .bind(ChunkStatus::Confirmed.as_str())
+ .fetch_one(&self.pool)
+ .await?;
+ let total = u64::try_from(row.total)
+ .map_err(|_| ChunkStoreError::InvalidChunkProgress(row.total, row.remaining))?;
+ let remaining = u64::try_from(row.remaining)
+ .map_err(|_| ChunkStoreError::InvalidChunkProgress(row.total, row.remaining))?;
+ if remaining > total {
+ return Err(ChunkStoreError::InvalidChunkProgress(
+ row.total,
+ row.remaining,
+ ));
+ }
+ Ok(ChunkProgress { total, remaining })
+ }
+
pub(crate) async fn heartbeat(
&self,
lease: ChunkLease,
@@ -439,6 +465,24 @@ pub enum ChunkStoreError {
InvalidInsertedCount(i64),
#[error("chunk counter returned invalid remaining count {0}")]
InvalidRemainingCount(i64),
+ #[error("chunk counter returned invalid progress total={0}, remaining={1}")]
+ InvalidChunkProgress(i64, i64),
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct ChunkProgress {
+ total: u64,
+ remaining: u64,
+}
+
+impl ChunkProgress {
+ pub const fn total(self) -> u64 {
+ self.total
+ }
+
+ pub const fn remaining(self) -> u64 {
+ self.remaining
+ }
}
#[derive(Debug, FromRow)]
@@ -460,6 +504,12 @@ struct PlanRow {
inserted: i64,
}
+#[derive(Debug, FromRow)]
+struct ChunkProgressRow {
+ total: i64,
+ remaining: i64,
+}
+
fn fenced(
updated: Option<ChunkId>,
lease: ChunkLease,
diff --git a/rust/cohort-seeder/src/store/runs.rs b/rust/cohort-seeder/src/store/runs.rs
index bdf84253b864..0148123c6acf 100644
--- a/rust/cohort-seeder/src/store/runs.rs
+++ b/rust/cohort-seeder/src/store/runs.rs
@@ -11,8 +11,9 @@ use sqlx::types::Json;
use sqlx::{FromRow, PgPool};
use crate::domain::{
- PinnedError, PinnedParticipation, PinnedParticipationState, PinnedRun, PinnedRunSnapshot,
- RunId, TriggerKind, UtcMillis, ValidatedPinnedRun,
+ BehavioralShapeHash, BehavioralShapeHashError, PinnedError, PinnedParticipation,
+ PinnedParticipationState, PinnedRun, PinnedRunSnapshot, ReconcileTile, RunId, TriggerKind,
+ UtcMillis, ValidatedPinnedRun,
};
use super::{RenderedError, PERSISTED_ERROR_LIMIT};
@@ -52,6 +53,13 @@ const READ_RUN: &str = concat!(
"\n WHERE id = $1 AND backfill_kind = 'behavioral'\n"
);
+const READ_ACTIVE_RECONCILE_PARTICIPATIONS: &str = r#"
+ SELECT team_id, cohort_id, behavioral_filters_shape_hash
+ FROM cohort_backfill_run_cohorts
+ WHERE run_id = $1 AND superseded_at IS NULL
+ ORDER BY cohort_id
+"#;
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunWarningNote {
ConditionsDropped,
@@ -180,9 +188,9 @@ impl SeedableRun {
}
pub async fn load_pinned(&self, pool: &PgPool) -> Result<ValidatedPinnedRun, RunError> {
- let rows = sqlx::query_as::<_, ParticipationRow>(
+ let rows = sqlx::query_as::<_, PinnedParticipationRow>(
r#"
- SELECT team_id, cohort_id, filters_shape_hash, pinned_filters, superseded_at
+ SELECT team_id, cohort_id, pinned_filters, superseded_at
FROM cohort_backfill_run_cohorts
WHERE run_id = $1
ORDER BY cohort_id
@@ -225,6 +233,75 @@ impl SeedableRun {
}
}
+/// A behavioral run proven safe to expand into reconcile control tiles. Construction validates
+/// the run state, tenant boundary, active participation set, and every persisted behavioral hash.
+#[derive(Debug, Clone)]
+pub struct ReconcileRun {
+ run_id: RunId,
+ status: RunStatus,
+ team_id: TeamId,
+ participations: Vec<ReconcileParticipation>,
+}
+
+impl ReconcileRun {
+ pub const fn run_id(&self) -> RunId {
+ self.run_id
+ }
+
+ pub const fn status(&self) -> RunStatus {
+ self.status
+ }
+
+ pub fn cohort_count(&self) -> usize {
+ self.participations.len()
+ }
+
+ pub fn tiles(&self) -> impl ExactSizeIterator<Item = ReconcileTile> + '_ {
+ self.participations.iter().map(|participation| {
+ ReconcileTile::new(
+ self.team_id,
+ participation.cohort_id,
+ participation.behavioral_filters_shape_hash.clone(),
+ self.run_id,
+ )
+ })
+ }
+}
+
+#[derive(Debug, Clone)]
+struct ReconcileParticipation {
+ cohort_id: CohortId,
+ behavioral_filters_shape_hash: BehavioralShapeHash,
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum ReconcileRunError {
+ #[error(transparent)]
+ Run(#[from] RunError),
+ #[error(
+ "run {run_id:?} has status {status:?}; reconcile dispatch requires seeding or reconciling"
+ )]
+ Status { run_id: RunId, status: RunStatus },
+ #[error("run {0:?} has no active cohort participations to reconcile")]
+ NoActiveParticipations(RunId),
+ #[error("run {run_id:?} cohort {cohort_id:?} has an invalid behavioral shape hash")]
+ InvalidBehavioralShapeHash {
+ run_id: RunId,
+ cohort_id: CohortId,
+ #[source]
+ source: BehavioralShapeHashError,
+ },
+ #[error(
+ "run {run_id:?} team {expected_team_id} has cohort {cohort_id:?} stored under team {actual_team_id}"
+ )]
+ CrossTeamParticipation {
+ run_id: RunId,
+ cohort_id: CohortId,
+ expected_team_id: i32,
+ actual_team_id: i32,
+ },
+}
+
#[derive(Debug, Clone)]
pub enum BoundaryOutcome {
Established(SeedableRun),
@@ -361,18 +438,20 @@ mod tests {
}
#[derive(Debug, FromRow)]
-struct ParticipationRow {
+struct PinnedParticipationRow {
team_id: i32,
cohort_id: i32,
- /// B5 CAS-readiness / reconcile seam: the filters shape hash read from
- /// `cohort_backfill_run_cohorts` for a future reconcile slice. Populated by Q1 (whose SQL stays
- /// frozen) but not yet read, so the attr suppresses the dead-field lint until that slice lands.
- #[allow(dead_code)]
- filters_shape_hash: String,
pinned_filters: Json<Value>,
superseded_at: Option<DateTime<Utc>>,
}
+#[derive(Debug, FromRow)]
+struct ReconcileParticipationRow {
+ team_id: i32,
+ cohort_id: i32,
+ behavioral_filters_shape_hash: String,
+}
+
#[derive(Debug, FromRow)]
struct BoundaryRow {
boundary_at: DateTime<Utc>,
@@ -400,6 +479,60 @@ pub async fn discover_runs(
rows.into_iter().map(DiscoveredRun::try_from).collect()
}
+pub async fn load_reconcile_run(
+ pool: &PgPool,
+ run_id: RunId,
+) -> Result<ReconcileRun, ReconcileRunError> {
+ let run = read_run(pool, run_id).await?;
+ if !matches!(run.status, RunStatus::Seeding | RunStatus::Reconciling) {
+ return Err(ReconcileRunError::Status {
+ run_id,
+ status: run.status,
+ });
+ }
+
+ let rows = sqlx::query_as::<_, ReconcileParticipationRow>(READ_ACTIVE_RECONCILE_PARTICIPATIONS)
+ .bind(run_id)
+ .fetch_all(pool)
+ .await
+ .map_err(RunError::from)?;
+ if rows.is_empty() {
+ return Err(ReconcileRunError::NoActiveParticipations(run_id));
+ }
+
+ let mut participations = Vec::with_capacity(rows.len());
+ for row in rows {
+ let cohort_id = CohortId(row.cohort_id);
+ if row.team_id != run.team_id.0 {
+ return Err(ReconcileRunError::CrossTeamParticipation {
+ run_id,
+ cohort_id,
+ expected_team_id: run.team_id.0,
+ actual_team_id: row.team_id,
+ });
+ }
+ let behavioral_filters_shape_hash =
+ BehavioralShapeHash::parse(&row.behavioral_filters_shape_hash).map_err(|source| {
+ ReconcileRunError::InvalidBehavioralShapeHash {
+ run_id,
+ cohort_id,
+ source,
+ }
+ })?;
+ participations.push(ReconcileParticipation {
+ cohort_id,
+ behavioral_filters_shape_hash,
+ });
+ }
+
+ Ok(ReconcileRun {
+ run_id,
+ status: run.status,
+ team_id: run.team_id,
+ participations,
+ })
+}
+
pub async fn establish_boundary(
pool: &PgPool,
run: DiscoveredRun,
diff --git a/rust/cohort-seeder/tests/fixtures/cohort_backfill_0004.sql b/rust/cohort-seeder/tests/fixtures/cohort_backfill_0004.sql
index 0a3befa1fc5f..afe3e3f5110f 100644
--- a/rust/cohort-seeder/tests/fixtures/cohort_backfill_0004.sql
+++ b/rust/cohort-seeder/tests/fixtures/cohort_backfill_0004.sql
@@ -62,6 +62,7 @@ CREATE INDEX cohort_bfc_run_status_day_idx ON cohort_backfill_chunks(run_id, sta
CREATE TABLE cohort_backfill_run_cohorts (
id uuid PRIMARY KEY,
filters_shape_hash varchar(64) NOT NULL,
+ behavioral_filters_shape_hash varchar(64) NOT NULL DEFAULT '',
pinned_filters jsonb NOT NULL,
stamped_at timestamptz,
superseded_at timestamptz,
diff --git a/rust/cohort-seeder/tests/pg_chunks.rs b/rust/cohort-seeder/tests/pg_chunks.rs
index b3c75ad4f861..ed677d16e374 100644
--- a/rust/cohort-seeder/tests/pg_chunks.rs
+++ b/rust/cohort-seeder/tests/pg_chunks.rs
@@ -11,13 +11,17 @@ use std::num::NonZeroU16;
use std::time::Duration;
use anyhow::{bail, ensure, Context, Result};
-use cohort_core::filters::CohortId;
+use cohort_core::filters::{CohortId, TeamId};
+use cohort_seeder::app::reconcile_dispatch::{
+ prepare_reconcile_dispatch, CompletionRequirement, PrepareReconcileDispatchError,
+ RegisterBackfillConfirmation,
+};
use cohort_seeder::domain::{ClaimEpoch, PinnedWarning, ProduceHwms};
use cohort_seeder::store::chunks::{ChunkStoreError, PgChunkStore, PlanOutcome};
use cohort_seeder::store::lease::LeaseFailure;
use cohort_seeder::store::runs::{
- discover_runs, establish_boundary, fail_run, record_run_warning, BoundaryOutcome, RunError,
- RunStatus, RunWarningNote,
+ discover_runs, establish_boundary, fail_run, load_reconcile_run, record_run_warning,
+ BoundaryOutcome, ReconcileRunError, RunError, RunStatus, RunWarningNote,
};
use cohort_seeder::store::{Claimant, LeaseDuration, MaxAttempts, RenderedError};
use cohort_seeder::test_support;
@@ -299,6 +303,158 @@ async fn load_pinned_drops_superseded_and_rejects_cross_team_and_dr() -> Result<
.await
}
+/// Manual dispatch reads only active participations, carries the behavioral-only shape hash onto
+/// the control tile, and refuses stale run states or malformed tenant/hash data before Kafka.
+#[tokio::test]
+async fn reconcile_run_load_is_fail_closed_and_behavioral_hash_scoped() -> Result<()> {
+ with_db(|pool| async move {
+ let run_id = insert_run(
+ &pool,
+ 20,
+ "team_enablement",
+ "seeding",
+ true,
+ empty_pinned(),
+ )
+ .await?;
+ insert_participation(
+ &pool,
+ run_id,
+ 20,
+ 201,
+ false,
+ behavioral_filter(ACTIVE_HASH, "active-event"),
+ )
+ .await?;
+ insert_participation(
+ &pool,
+ run_id,
+ 20,
+ 202,
+ true,
+ behavioral_filter(SUPERSEDED_HASH, "superseded-event"),
+ )
+ .await?;
+
+ let register_backfill = RegisterBackfillConfirmation::confirmed_by_operator();
+ ensure!(matches!(
+ prepare_reconcile_dispatch(
+ &pool,
+ run_id,
+ CompletionRequirement::Complete,
+ register_backfill,
+ )
+ .await,
+ Err(PrepareReconcileDispatchError::EmptyChunkLedger(id)) if id == run_id
+ ));
+ let overridden = prepare_reconcile_dispatch(
+ &pool,
+ run_id,
+ CompletionRequirement::AllowIncomplete,
+ register_backfill,
+ )
+ .await?;
+ ensure!(overridden.total_chunks() == 0);
+ ensure!(overridden.remaining_chunks() == 0);
+
+ let reconcile = load_reconcile_run(&pool, run_id).await?;
+ ensure!(reconcile.run_id() == run_id);
+ ensure!(reconcile.status() == RunStatus::Seeding);
+ ensure!(reconcile.cohort_count() == 1);
+ let tile = reconcile
+ .tiles()
+ .next()
+ .context("missing active cohort tile")?;
+ ensure!(tile.team_id() == TeamId(20));
+ ensure!(tile.cohort_id() == CohortId(201));
+ ensure!(tile.filters_hash().as_str() == "behavioral-shape");
+ ensure!(tile.run_id() == run_id);
+
+ sqlx::query("UPDATE cohort_backfill_runs SET status = 'reconciling' WHERE id = $1")
+ .bind(run_id)
+ .execute(&pool)
+ .await?;
+ ensure!(load_reconcile_run(&pool, run_id).await?.status() == RunStatus::Reconciling);
+ ensure!(prepare_reconcile_dispatch(
+ &pool,
+ run_id,
+ CompletionRequirement::Complete,
+ register_backfill,
+ )
+ .await
+ .is_ok());
+
+ sqlx::query(
+ "UPDATE cohort_backfill_run_cohorts SET behavioral_filters_shape_hash = '' \
+ WHERE run_id = $1 AND cohort_id = 201",
+ )
+ .bind(run_id)
+ .execute(&pool)
+ .await?;
+ ensure!(matches!(
+ load_reconcile_run(&pool, run_id).await,
+ Err(ReconcileRunError::InvalidBehavioralShapeHash { cohort_id, .. })
+ if cohort_id == CohortId(201)
+ ));
+
+ sqlx::query(
+ "UPDATE cohort_backfill_run_cohorts \
+ SET behavioral_filters_shape_hash = 'behavioral-shape', team_id = 999 \
+ WHERE run_id = $1 AND cohort_id = 201",
+ )
+ .bind(run_id)
+ .execute(&pool)
+ .await?;
+ ensure!(matches!(
+ load_reconcile_run(&pool, run_id).await,
+ Err(ReconcileRunError::CrossTeamParticipation {
+ expected_team_id: 20,
+ actual_team_id: 999,
+ ..
+ })
+ ));
+
+ sqlx::query(
+ "UPDATE cohort_backfill_run_cohorts SET superseded_at = now() WHERE run_id = $1",
+ )
+ .bind(run_id)
+ .execute(&pool)
+ .await?;
+ ensure!(matches!(
+ load_reconcile_run(&pool, run_id).await,
+ Err(ReconcileRunError::NoActiveParticipations(id)) if id == run_id
+ ));
+
+ let completed_run = insert_run(
+ &pool,
+ 21,
+ "team_enablement",
+ "completed",
+ true,
+ empty_pinned(),
+ )
+ .await?;
+ insert_participation(
+ &pool,
+ completed_run,
+ 21,
+ 211,
+ false,
+ behavioral_filter(ACTIVE_HASH, "active-event"),
+ )
+ .await?;
+ ensure!(matches!(
+ load_reconcile_run(&pool, completed_run).await,
+ Err(ReconcileRunError::Status {
+ status: RunStatus::Completed,
+ ..
+ })
+ ));
+ Ok(())
+ })
+ .await
+}
+
/// Planning a seeding run's days is idempotent (re-planning inserts nothing), stamps the run's team
/// onto every chunk, and reports `RunNotSeeding` for a run that is not seeding.
#[tokio::test]
@@ -310,6 +466,9 @@ async fn planning_is_idempotent_scopes_team_and_gates_on_seeding() -> Result<()>
ensure!(planned_count(store.plan_chunks(seeding_run, [100, 101], ONE_BAND).await?)? == 2);
ensure!(planned_count(store.plan_chunks(seeding_run, [100, 101], ONE_BAND).await?)? == 0);
+ let progress = store.chunk_progress(seeding_run).await?;
+ ensure!(progress.total() == 2);
+ ensure!(progress.remaining() == 2);
let chunk_teams_match: bool = sqlx::query_scalar(
"SELECT bool_and(team_id = 2) FROM cohort_backfill_chunks WHERE run_id = $1",
)
diff --git a/rust/cohort-seeder/tests/support/mod.rs b/rust/cohort-seeder/tests/support/mod.rs
index ce847ef8a7cc..880b12c851cf 100644
--- a/rust/cohort-seeder/tests/support/mod.rs
+++ b/rust/cohort-seeder/tests/support/mod.rs
@@ -145,8 +145,10 @@ pub async fn insert_participation(
sqlx::query(
r#"
INSERT INTO cohort_backfill_run_cohorts
- (id, run_id, team_id, cohort_id, filters_shape_hash, pinned_filters, superseded_at)
- VALUES ($1, $2, $3, $4, 'shape', $5, CASE WHEN $6 THEN now() ELSE NULL END)
+ (id, run_id, team_id, cohort_id, filters_shape_hash,
+ behavioral_filters_shape_hash, pinned_filters, superseded_at)
+ VALUES ($1, $2, $3, $4, 'full-shape', 'behavioral-shape', $5,
+ CASE WHEN $6 THEN now() ELSE NULL END)
"#,
)
.bind(Uuid::now_v7())