:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cohorts): seeder planning proof and auto reconcile dispatch (#73738)
Matheus Batistae6b5cb654a90
diff --git a/rust/cohort-seeder/src/app/completion.rs b/rust/cohort-seeder/src/app/completion.rsnew file mode 100644index 000000000000..d1a579010b5b--- /dev/null+++ b/rust/cohort-seeder/src/app/completion.rs@@ -0,0 +1,525 @@+//! App layer: the automatic reconcile-dispatch driver, dark by default. Ticked from the orchestrator+//! poll arm after `fill_claim_slots`, it discovers seeding/reconciling behavioral runs, transitions a+//! fully-confirmed run `seeding → reconciling`, produces the reconcile control tiles, and persists the+//! dispatch record (produce HWMs + marker-watch start positions + fence epoch) through the same store+//! path the CLI uses. Consumers/observers are PR-C — this producer never reads markers.+//!+//! Dispatch runs in a spawned task, never inline: producing `cohorts × COHORT_PARTITION_COUNT` control+//! tiles and awaiting their delivery acks can exceed the orchestrator's liveness deadline. An+//! in-flight set dedupes tasks on this replica; the CAS plus INV-3's ruling-fence semantics (a later+//! `record` sets the fence, the processor supersedes duplicate tiles) make cross-replica duplicates+//! safe.++use std::collections::HashSet;+use std::num::NonZeroUsize;+use std::sync::{Arc, Mutex};+use std::time::Duration;++use common_types::cohort::TeamAllowlist;+use metrics::{counter, gauge};+use sqlx::PgPool;+use tokio::sync::Semaphore;+use tokio::task::JoinError;+use tracing::warn;++use cohort_core::partitioner::COHORT_PARTITION_COUNT;++use crate::config::Config;+use crate::domain::{+ CompletionPhase, DispatchEpoch, MarkerWatch, ProducedOffset, ReconcileHwms, ReconcileHwmsError,+ RunId,+};+use crate::kafka::producer::{CaptureOffsetsError, SeedTileProducer};+use crate::observability::metrics::{+ RECONCILE_CAS_LOST, RECONCILE_DISPATCHES, RECONCILE_DISPATCHES_IN_FLIGHT,+ RECONCILE_RECORD_INVALID, RUNS_RECONCILING,+};+use crate::store::completion::{+ cas_run_reconciling, confirm_reconciling, discover_completions,+ mark_run_observed_unreconcilable, runs_with_all_chunks_confirmed, CompletionStoreError,+ ReconcilingClaim,+};+use crate::store::runs::ReconcileRunError;++use super::reconcile_dispatch::{+ execute_reconcile_dispatch, prepare_reconcile_dispatch, CertifiedDispatch,+ CompletionRequirement, PrepareReconcileDispatchError, PreparedDispatch, ReconcileDispatchError,+ ReconcileDispatchReceipt, RegisterBackfillConfirmation,+};++/// Timeout for the blocking Kafka metadata and watermark calls the dispatch makes.+const KAFKA_METADATA_TIMEOUT: Duration = Duration::from_secs(10);++/// Whether automatic dispatch is armed. `Enabled` carries the register-backfill attestation, so the+/// driver cannot be constructed without it.+#[derive(Debug, Clone, Copy)]+pub enum AutoDispatchPolicy {+ Disabled,+ Enabled(RegisterBackfillConfirmation),+}++impl AutoDispatchPolicy {+ /// Resolve the policy from configuration. Arming automatic dispatch requires both the enable flag+ /// and the register-backfill attestation, and the seed partition count must match the shared+ /// cohort contract (dispatch produces to exactly [`COHORT_PARTITION_COUNT`] partitions).+ pub fn from_config(config: &Config) -> Result<Self, AutoDispatchPolicyError> {+ if !config.seeder_reconcile_auto_dispatch_enabled {+ return Ok(Self::Disabled);+ }+ if !config.seeder_confirm_register_backfilled {+ return Err(AutoDispatchPolicyError::MissingAttestation);+ }+ if config.cohort_partition_count != COHORT_PARTITION_COUNT {+ return Err(AutoDispatchPolicyError::PartitionCountMismatch {+ configured: config.cohort_partition_count,+ });+ }+ Ok(Self::Enabled(+ RegisterBackfillConfirmation::confirmed_by_env(),+ ))+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]+pub enum AutoDispatchPolicyError {+ #[error(+ "SEEDER_RECONCILE_AUTO_DISPATCH_ENABLED requires SEEDER_CONFIRM_REGISTER_BACKFILLED to attest \+ that runs were seeded after membership-register writers deployed"+ )]+ MissingAttestation,+ #[error(+ "automatic reconcile dispatch requires COHORT_PARTITION_COUNT == {expected}, got {configured}",+ expected = COHORT_PARTITION_COUNT+ )]+ PartitionCountMismatch { configured: u32 },+}++/// Whether a spawned task starts a fresh dispatch (CAS out of `seeding`) or re-dispatches an+/// already-`reconciling` run (confirm claim) to heal a missing or stale dispatch record.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum DispatchKind {+ Fresh,+ ReDispatch,+}++/// The owned dependencies a dispatch task needs, cheap to clone into a spawned task.+#[derive(Clone)]+struct DispatchContext {+ pool: PgPool,+ producer: SeedTileProducer,+ membership_topic: Arc<str>,+ max_inflight: NonZeroUsize,+ register_backfill: RegisterBackfillConfirmation,+}++pub struct CompletionDriver {+ context: DispatchContext,+ allowlist: TeamAllowlist,+ in_flight: Arc<Mutex<HashSet<RunId>>>,+ dispatch_slots: Arc<Semaphore>,+}++impl CompletionDriver {+ pub fn new(+ pool: PgPool,+ producer: SeedTileProducer,+ allowlist: TeamAllowlist,+ membership_topic: String,+ max_inflight: NonZeroUsize,+ max_concurrent_dispatches: NonZeroUsize,+ register_backfill: RegisterBackfillConfirmation,+ ) -> Self {+ Self {+ context: DispatchContext {+ pool,+ producer,+ membership_topic: Arc::from(membership_topic),+ max_inflight,+ register_backfill,+ },+ allowlist,+ in_flight: Arc::new(Mutex::new(HashSet::new())),+ dispatch_slots: Arc::new(Semaphore::new(max_concurrent_dispatches.get())),+ }+ }++ /// One driver pass: classify every discovered run and spawn dispatch tasks for the ones that need+ /// one. A discovery failure is logged and retried next tick; the dark path (driver absent) costs+ /// zero queries. Every read is per-tick, never per-run — the pass blocks the orchestrator's+ /// liveness heartbeat.+ pub async fn tick(&self) {+ let discovered = match discover_completions(&self.context.pool, &self.allowlist).await {+ Ok(discovered) => discovered,+ Err(error) => {+ warn!(error = %error, "completion discovery failed");+ return;+ }+ };++ let mut reconciling = 0_u64;+ let mut planned = Vec::new();+ for completion in discovered {+ match completion.phase {+ CompletionPhase::Observed | CompletionPhase::Reconciling(_) => {+ reconciling += 1;+ }+ CompletionPhase::ReconcilingUndispatched(reason) => {+ reconciling += 1;+ // Count and warn only when a re-dispatch actually starts: the run keeps this+ // phase until the in-flight task records one, so counting per tick would turn a+ // single healing event into an unbounded rate.+ if self.spawn_dispatch(completion.run_id, DispatchKind::ReDispatch) {+ counter!(RECONCILE_RECORD_INVALID).increment(1);+ warn!(+ run_id = ?completion.run_id,+ ?reason,+ "reconciling run has no usable dispatch record; re-dispatching"+ );+ }+ }+ CompletionPhase::SeedingPlanned => planned.push(completion.run_id),+ CompletionPhase::SeedingUnplanned => {}+ CompletionPhase::SeedingAnomalous => {+ warn!(+ run_id = ?completion.run_id,+ "seeding run carries reconcile columns; skipping until it is reconciled by hand"+ );+ }+ }+ }+ gauge!(RUNS_RECONCILING).set(reconciling as f64);++ match runs_with_all_chunks_confirmed(&self.context.pool, &planned).await {+ Ok(confirmed) => {+ for run_id in confirmed {+ let _spawned = self.spawn_dispatch(run_id, DispatchKind::Fresh);+ }+ }+ Err(error) => {+ warn!(error = %error, "reading chunk progress for dispatch failed");+ }+ }+ }++ /// Spawns a dispatch task unless one is already in flight for this run on this replica or the+ /// driver is at its concurrency budget. Returns whether a task actually started, so callers can+ /// attribute per-event signals to the event rather than to every poll tick that observes the+ /// same pending state.+ ///+ /// Every task produces `cohorts × COHORT_PARTITION_COUNT` tiles through the producer the chunk+ /// pipeline shares, so unbounded fan-out would back the core seeding path off its own queue. A+ /// run that misses the budget keeps its phase and is picked up on a later tick.+ fn spawn_dispatch(&self, run_id: RunId, kind: DispatchKind) -> bool {+ let Ok(permit) = Arc::clone(&self.dispatch_slots).try_acquire_owned() else {+ return false;+ };+ if !lock_in_flight(&self.in_flight).insert(run_id) {+ return false;+ }+ let context = self.context.clone();+ let guard = InFlightGuard::enter(Arc::clone(&self.in_flight), run_id);+ let dispatch = tokio::spawn(async move {+ let _permit = permit;+ let _guard = guard;+ run_dispatch(&context, run_id, kind).await;+ });+ // `run_dispatch` reports its own failures, so a `JoinError` is a panic. Dropping the handle+ // would make a deterministic one — a poison row, say — an invisible per-tick respawn loop.+ tokio::spawn(async move {+ if let Err(error) = dispatch.await {+ counter!(RECONCILE_DISPATCHES, "outcome" => "panicked").increment(1);+ warn!(error = %error, run_id = ?run_id, "reconcile dispatch task panicked");+ }+ });+ true+ }+}++/// Releases the run's in-flight entry and gauge slot when its dispatch task ends — including on+/// panic. A leaked entry would dedupe the run away on this replica until restart.+struct InFlightGuard {+ in_flight: Arc<Mutex<HashSet<RunId>>>,+ run_id: RunId,+}++impl InFlightGuard {+ fn enter(in_flight: Arc<Mutex<HashSet<RunId>>>, run_id: RunId) -> Self {+ gauge!(RECONCILE_DISPATCHES_IN_FLIGHT).increment(1.0);+ Self { in_flight, run_id }+ }+}++impl Drop for InFlightGuard {+ fn drop(&mut self) {+ lock_in_flight(&self.in_flight).remove(&self.run_id);+ gauge!(RECONCILE_DISPATCHES_IN_FLIGHT).decrement(1.0);+ }+}++/// The set stays structurally valid across a panic between lock and mutation, so a poisoned lock is+/// recoverable rather than fatal.+fn lock_in_flight(in_flight: &Mutex<HashSet<RunId>>) -> std::sync::MutexGuard<'_, HashSet<RunId>> {+ in_flight+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+}++/// One dispatch attempt. Every failure path logs and leaves the run in a state the next tick retries:+/// a lost CAS leaves the run untouched; a run with no participation left to reconcile is marked+/// observed so Django can terminalize it; a post-CAS `Incomplete` reverts to `seeding`; a+/// produce/record failure leaves the run `reconciling` with no record, which the next tick sees as+/// `ReconcilingUndispatched` and re-dispatches. On shutdown mid-dispatch the same recovery converges+/// per the crash-recovery matrix.+async fn run_dispatch(context: &DispatchContext, run_id: RunId, kind: DispatchKind) {+ let claim = match acquire_claim(context, run_id, kind).await {+ Ok(Some(claim)) => claim,+ Ok(None) => {+ counter!(RECONCILE_CAS_LOST).increment(1);+ counter!(RECONCILE_DISPATCHES, "outcome" => "cas_lost").increment(1);+ return;+ }+ Err(error) => {+ warn!(error = %error, run_id = ?run_id, "acquiring the reconciling claim failed");+ return;+ }+ };++ let certified = match prepare_reconcile_dispatch(+ &context.pool,+ run_id,+ CompletionRequirement::Complete,+ context.register_backfill,+ )+ .await+ {+ Ok(PreparedDispatch::Certified(certified)) => certified,+ Ok(PreparedDispatch::Uncertified(_)) => {+ warn!(run_id = ?run_id, "dispatch was not certified under Complete; leaving reconciling");+ counter!(RECONCILE_DISPATCHES, "outcome" => "prepare_failed").increment(1);+ return;+ }+ Err(PrepareReconcileDispatchError::Run(ReconcileRunError::NoActiveParticipations(_))) => {+ // Every participation was superseded while the run seeded. There is nothing to+ // dispatch and no outcome to write, so stamp the observation ourselves — Django's+ // finalizer only discovers runs carrying `reconcile_observed_at`, and without it the+ // run would classify as `ReconcilingUndispatched` and re-spawn this no-op forever.+ warn!(run_id = ?run_id, "no active participations; marking observed for Django to terminalize");+ if let Err(error) = mark_run_observed_unreconcilable(&context.pool, run_id).await {+ warn!(error = %error, run_id = ?run_id, "marking an unreconcilable run observed failed");+ }+ counter!(RECONCILE_DISPATCHES, "outcome" => "no_participations").increment(1);+ return;+ }+ Err(PrepareReconcileDispatchError::Incomplete {+ remaining_chunks, ..+ }) => {+ warn!(+ run_id = ?run_id,+ remaining_chunks,+ "chunks reappeared after the CAS; reverting to seeding"+ );+ if let Err(error) = claim.revert(&context.pool).await {+ warn!(error = %error, run_id = ?run_id, "reverting the reconciling CAS failed");+ }+ counter!(RECONCILE_DISPATCHES, "outcome" => "revert").increment(1);+ return;+ }+ Err(error) => {+ warn!(error = %error, run_id = ?run_id, "preparing reconcile dispatch failed; leaving reconciling");+ counter!(RECONCILE_DISPATCHES, "outcome" => "prepare_failed").increment(1);+ return;+ }+ };++ match dispatch_and_record(+ &context.pool,+ &context.producer,+ &context.membership_topic,+ context.max_inflight,+ KAFKA_METADATA_TIMEOUT,+ certified,+ claim,+ )+ .await+ {+ Ok(_) => {+ counter!(RECONCILE_DISPATCHES, "outcome" => "dispatched").increment(1);+ }+ Err(error) => {+ let outcome = error.outcome();+ warn!(error = %error, run_id = ?run_id, "reconcile dispatch failed; leaving reconciling for re-dispatch");+ counter!(RECONCILE_DISPATCHES, "outcome" => outcome).increment(1);+ }+ }+}++async fn acquire_claim(+ context: &DispatchContext,+ run_id: RunId,+ kind: DispatchKind,+) -> Result<Option<ReconcilingClaim>, CompletionStoreError> {+ match kind {+ DispatchKind::Fresh => cas_run_reconciling(&context.pool, run_id).await,+ DispatchKind::ReDispatch => confirm_reconciling(&context.pool, run_id).await,+ }+}++/// The persisted result of a dispatch: the per-partition produce receipt and the fence epoch.+#[derive(Debug)]+pub struct RecordedDispatch {+ pub receipt: ReconcileDispatchReceipt,+ pub epoch: DispatchEpoch,+}++/// Capture the marker-watch start positions, produce the reconcile control tiles, and atomically+/// record the dispatch. Requires both a [`CertifiedDispatch`] (completion proven) and a+/// [`ReconcilingClaim`] (CAS proven), so persistence is unreachable without both proofs. Positions are+/// captured BEFORE producing, so every marker of this dispatch lands at or above them.+pub async fn dispatch_and_record(+ pool: &PgPool,+ producer: &SeedTileProducer,+ membership_topic: &str,+ max_inflight: NonZeroUsize,+ metadata_timeout: Duration,+ certified: CertifiedDispatch,+ claim: ReconcilingClaim,+) -> Result<RecordedDispatch, DispatchRecordError> {+ let positions = {+ let producer = producer.clone();+ let topic = membership_topic.to_string();+ tokio::task::spawn_blocking(move || {+ producer.capture_topic_offsets(&topic, metadata_timeout)+ })+ .await+ .map_err(DispatchRecordError::CaptureTask)?+ .map_err(DispatchRecordError::CaptureOffsets)?+ };++ let receipt = execute_reconcile_dispatch(+ certified.into_prepared(),+ producer,+ max_inflight,+ metadata_timeout,+ )+ .await+ .map_err(DispatchRecordError::Execute)?;++ let hwms = ReconcileHwms::try_from(&receipt).map_err(DispatchRecordError::Hwms)?;+ let watch = MarkerWatch {+ positions,+ ends: None,+ };+ let epoch = claim+ .record(pool, &hwms, &watch)+ .await+ .map_err(DispatchRecordError::Record)?;++ Ok(RecordedDispatch { receipt, epoch })+}++impl TryFrom<&ReconcileDispatchReceipt> for ReconcileHwms {+ type Error = ReconcileHwmsError;++ fn try_from(receipt: &ReconcileDispatchReceipt) -> Result<Self, Self::Error> {+ let offsets = receipt+ .offsets()+ .map(|(partition, offset)| (partition, ProducedOffset::new(offset)))+ .collect();+ ReconcileHwms::new(offsets)+ }+}++#[derive(Debug, thiserror::Error)]+pub enum DispatchRecordError {+ #[error("joining the offset-capture task")]+ CaptureTask(#[source] JoinError),+ #[error("capturing the membership topic start positions")]+ CaptureOffsets(#[source] CaptureOffsetsError),+ #[error("producing the reconcile control tiles")]+ Execute(#[source] ReconcileDispatchError),+ #[error("building the reconcile produce high-water marks")]+ Hwms(#[source] ReconcileHwmsError),+ #[error("recording the dispatch")]+ Record(#[source] CompletionStoreError),+}++impl DispatchRecordError {+ fn outcome(&self) -> &'static str {+ match self {+ Self::CaptureTask(_) | Self::CaptureOffsets(_) | Self::Execute(_) | Self::Hwms(_) => {+ "produce_failed"+ }+ Self::Record(_) => "record_failed",+ }+ }+}++#[cfg(test)]+mod tests {+ use std::collections::HashMap;++ use envconfig::Envconfig;++ use super::*;++ fn config_with(overrides: &[(&str, &str)]) -> Config {+ let env: HashMap<String, String> = overrides+ .iter()+ .map(|(key, value)| ((*key).to_string(), (*value).to_string()))+ .collect();+ Config::init_from_hashmap(&env).unwrap()+ }++ #[test]+ fn policy_is_disabled_by_default_and_ignores_a_bare_attestation() {+ assert!(matches!(+ AutoDispatchPolicy::from_config(&config_with(&[])).unwrap(),+ AutoDispatchPolicy::Disabled+ ));+ assert!(matches!(+ AutoDispatchPolicy::from_config(&config_with(&[(+ "SEEDER_CONFIRM_REGISTER_BACKFILLED",+ "true"+ )]))+ .unwrap(),+ AutoDispatchPolicy::Disabled+ ));+ }++ #[test]+ fn enabling_without_attestation_is_a_startup_error() {+ assert_eq!(+ AutoDispatchPolicy::from_config(&config_with(&[(+ "SEEDER_RECONCILE_AUTO_DISPATCH_ENABLED",+ "true"+ )]))+ .unwrap_err(),+ AutoDispatchPolicyError::MissingAttestation+ );+ }++ #[test]+ fn enabling_with_attestation_arms_dispatch() {+ assert!(matches!(+ AutoDispatchPolicy::from_config(&config_with(&[+ ("SEEDER_RECONCILE_AUTO_DISPATCH_ENABLED", "true"),+ ("SEEDER_CONFIRM_REGISTER_BACKFILLED", "true"),+ ]))+ .unwrap(),+ AutoDispatchPolicy::Enabled(_)+ ));+ }++ #[test]+ fn enabling_with_a_noncontract_partition_count_is_a_startup_error() {+ assert_eq!(+ AutoDispatchPolicy::from_config(&config_with(&[+ ("SEEDER_RECONCILE_AUTO_DISPATCH_ENABLED", "true"),+ ("SEEDER_CONFIRM_REGISTER_BACKFILLED", "true"),+ ("COHORT_PARTITION_COUNT", "8"),+ ]))+ .unwrap_err(),+ AutoDispatchPolicyError::PartitionCountMismatch { configured: 8 }+ );+ }+}diff --git a/rust/cohort-seeder/src/app/mod.rs b/rust/cohort-seeder/src/app/mod.rsindex a4ee86e084ce..2f6a06392add 100644--- a/rust/cohort-seeder/src/app/mod.rs+++ b/rust/cohort-seeder/src/app/mod.rs@@ -1,6 +1,7 @@//! Application layer: wires `store`, `clickhouse`, `kafka`, and `config` into the seeder's poll loop.//! Depends on every lower layer; nothing below depends on it, so this is where the arrows terminate.+pub mod completion;mod deliver;mod execute;mod orchestrator;@@ -8,5 +9,6 @@ mod prepare;pub mod reconcile_dispatch;pub mod settings;+pub use completion::{AutoDispatchPolicy, AutoDispatchPolicyError, CompletionDriver};pub use orchestrator::{SeederOrchestrator, ORCHESTRATOR_LIVENESS_DEADLINE};pub use settings::OrchestratorSettings;diff --git a/rust/cohort-seeder/src/app/orchestrator.rs b/rust/cohort-seeder/src/app/orchestrator.rsindex 8c248333961d..159b5126a924 100644--- a/rust/cohort-seeder/src/app/orchestrator.rs+++ b/rust/cohort-seeder/src/app/orchestrator.rs@@ -22,6 +22,7 @@ use crate::observability::metrics::{CHUNKS_CLAIMED, CHUNKS_POISONED, CHUNKS_RECLuse crate::store::chunks::{Claim, PgChunkStore};use crate::store::Claimant;+use super::completion::CompletionDriver;use super::execute::{execute_chunk, record_task_result, ChunkOutcome, ChunkTaskContext};use super::prepare::refresh_runs;use super::settings::OrchestratorSettings;@@ -39,6 +40,7 @@ pub struct SeederOrchestrator {settings: OrchestratorSettings,handle: Handle,claimant: Claimant,+ completion_driver: Option<CompletionDriver>,}impl SeederOrchestrator {@@ -52,6 +54,7 @@ impl SeederOrchestrator {settings: OrchestratorSettings,handle: Handle,claimed_by: String,+ completion_driver: Option<CompletionDriver>,) -> Self {let claimant =Claimant::new(claimed_by).expect("seeder claimant is 1..=255 bytes by construction");@@ -65,6 +68,7 @@ impl SeederOrchestrator {settings,handle,claimant,+ completion_driver,}}@@ -99,6 +103,9 @@ impl SeederOrchestrator {.await;self.reap_poisoned_chunks(&eligible_runs).await;self.fill_claim_slots(&eligible_runs, &mut tasks, &shutdown).await;+ if let Some(driver) = &self.completion_driver {+ driver.tick().await;+ }self.handle.report_healthy();}}diff --git a/rust/cohort-seeder/src/app/prepare.rs b/rust/cohort-seeder/src/app/prepare.rsindex 231a287e804f..86b85babedea 100644--- a/rust/cohort-seeder/src/app/prepare.rs+++ b/rust/cohort-seeder/src/app/prepare.rs@@ -16,10 +16,12 @@ use tracing::warn;use crate::domain::{plan_days, Lookback, PinnedRun, PinnedWarning, PlanCaps, RunId};use crate::observability::metrics::{BOUNDARY_CAS_LOST, BOUNDARY_ESTABLISHED, CHUNKS_PLANNED, CONDITIONS_DROPPED,- LOOKBACK_TRUNCATED, RUNS_DISCOVERED, RUNS_WAITING_BOUNDARY, RUNS_WITHOUT_CHUNKS,- RUN_CHUNKS_REMAINING, RUN_VALIDATION_FAILURES, TZ_FALLBACK, WINDOW_DAYS_MISMATCH,+ LOOKBACK_TRUNCATED, RUNS_DISCOVERED, RUNS_PLANNING_STAMPED, RUNS_PLANNING_WITHHELD,+ RUNS_WAITING_BOUNDARY, RUNS_WITHOUT_CHUNKS, RUN_CHUNKS_REMAINING, RUN_VALIDATION_FAILURES,+ TZ_FALLBACK, WINDOW_DAYS_MISMATCH,};use crate::store::chunks::{PgChunkStore, PlanOutcome};+use crate::store::completion::{mark_chunks_planned, PlanningStampOutcome};use crate::store::runs::{discover_runs, establish_boundary, fail_run, record_run_warning, BoundaryOutcome,DiscoveredRun, RunError, RunStatus, RunWarningNote,@@ -135,12 +137,29 @@ async fn prepare_run(persist_run_warning(pool, run_id, RunWarningNote::LookbackTruncated).await;}+ // Without the proof the run never dispatches, so an uncovered cohort can never stamp readiness+ // on zero seeded history. Siblings still get planned and seeded.+ let coverage_complete = validated.uncovered_cohorts.is_empty();+ if !coverage_complete {+ counter!(RUNS_PLANNING_WITHHELD).increment(1);+ warn!(+ run_id = ?run_id,+ uncovered_cohorts = ?validated.uncovered_cohorts,+ "active participations have no surviving pinned condition; withholding the planning proof"+ );+ }+let days = plan_days(&validated.run.conditions,validated.run.boundary,&plan_caps,);if days.is_empty() {+ if coverage_complete {+ // A legitimately zero-chunk run still needs the proof, or it stalls waiting for chunks+ // that will never exist.+ stamp_planning(pool, run_id).await;+ }return PrepareOutcome::NoChunks;}match store@@ -149,6 +168,9 @@ async fn prepare_run({Ok(PlanOutcome::Planned { inserted }) => {counter!(CHUNKS_PLANNED).increment(inserted);+ if coverage_complete {+ stamp_planning(pool, run_id).await;+ }}Ok(PlanOutcome::RunNotSeeding) => return PrepareOutcome::Skipped,Err(error) => {@@ -159,6 +181,16 @@ async fn prepare_run(PrepareOutcome::Eligible(Arc::new(validated.run))}+/// Stamp the planning proof once planning has run. A failure is logged but never changes the prepare+/// outcome — the run keeps seeding and the next pass re-stamps.+async fn stamp_planning(pool: &PgPool, run_id: RunId) {+ match mark_chunks_planned(pool, run_id).await {+ Ok(PlanningStampOutcome::Stamped) => counter!(RUNS_PLANNING_STAMPED).increment(1),+ Ok(PlanningStampOutcome::Skipped) => {}+ Err(error) => warn!(run_id = ?run_id, error = %error, "stamping the planning proof failed"),+ }+}+async fn handle_run_error(pool: &PgPool, run_id: Option<RunId>, error: RunError) {let disposition = run_error_disposition(run_id, &error);if let RunErrorDisposition::Fail { run_id, reason } = disposition {diff --git a/rust/cohort-seeder/src/app/reconcile_dispatch.rs b/rust/cohort-seeder/src/app/reconcile_dispatch.rsindex d0a7f4ba370f..e74ab815278e 100644--- a/rust/cohort-seeder/src/app/reconcile_dispatch.rs+++ b/rust/cohort-seeder/src/app/reconcile_dispatch.rs@@ -17,6 +17,7 @@ use crate::kafka::producer::{EnqueueError, PartitionCountError, SeedPartition, SeedPartitionCountError, SeedTileProducer,};use crate::store::chunks::{ChunkStoreError, PgChunkStore};+use crate::store::completion::{read_planning_stamp, CompletionStoreError};use crate::store::runs::{load_reconcile_run, ReconcileRun, ReconcileRunError, RunStatus};#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -39,6 +40,12 @@ impl RegisterBackfillConfirmation {pub const fn confirmed_by_operator() -> Self {Self(())}++ /// The env-attested equivalent for the automatic dispatch driver: the deployment asserted the+ /// register-backfill boundary via `SEEDER_CONFIRM_REGISTER_BACKFILLED` at startup.+ pub const fn confirmed_by_env() -> Self {+ Self(())+ }}/// A run capability minted only after its status, active participations, hashes, and chunk ledger@@ -55,6 +62,10 @@ impl PreparedReconcileDispatch {self.run.run_id()}+ pub const fn run_status(&self) -> RunStatus {+ self.run.status()+ }+pub fn cohort_count(&self) -> usize {self.run.cohort_count()}@@ -68,35 +79,91 @@ impl PreparedReconcileDispatch {}}+/// A prepared dispatch whose completion was certified under [`CompletionRequirement::Complete`]. Only+/// this capability can reach the persistence path — the record write is minted from a `Certified`+/// value, never from an `AllowIncomplete` one, so an incomplete dispatch can never be persisted.+#[derive(Debug)]+pub struct CertifiedDispatch(PreparedReconcileDispatch);++impl CertifiedDispatch {+ pub fn prepared(&self) -> &PreparedReconcileDispatch {+ &self.0+ }++ pub fn into_prepared(self) -> PreparedReconcileDispatch {+ self.0+ }+}++/// The outcome of preparing a dispatch: a `Certified` capability (completion proven) or an+/// `Uncertified` one (an operator override that must stay print-only).+#[derive(Debug)]+pub enum PreparedDispatch {+ Certified(CertifiedDispatch),+ Uncertified(PreparedReconcileDispatch),+}++impl PreparedDispatch {+ fn inner(&self) -> &PreparedReconcileDispatch {+ match self {+ Self::Certified(certified) => &certified.0,+ Self::Uncertified(prepared) => prepared,+ }+ }++ pub fn run_id(&self) -> RunId {+ self.inner().run_id()+ }++ pub fn run_status(&self) -> RunStatus {+ self.inner().run_status()+ }++ pub fn cohort_count(&self) -> usize {+ self.inner().cohort_count()+ }++ pub fn total_chunks(&self) -> u64 {+ self.inner().total_chunks()+ }++ pub fn remaining_chunks(&self) -> u64 {+ self.inner().remaining_chunks()+ }+}+pub async fn prepare_reconcile_dispatch(pool: &PgPool,run_id: RunId,completion: CompletionRequirement,_register_backfill: RegisterBackfillConfirmation,-) -> Result<PreparedReconcileDispatch, PrepareReconcileDispatchError> {+) -> Result<PreparedDispatch, 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 {+ let planning_proven = read_planning_stamp(pool, run_id).await?.is_some();+ validate_completion(run_id, progress.remaining(), planning_proven, completion)?;+ let prepared = PreparedReconcileDispatch {run,total_chunks: progress.total(),remaining_chunks: progress.remaining(),+ };+ Ok(match completion {+ CompletionRequirement::Complete => PreparedDispatch::Certified(CertifiedDispatch(prepared)),+ CompletionRequirement::AllowIncomplete => PreparedDispatch::Uncertified(prepared),})}+/// A run is complete when every chunk has confirmed (`remaining == 0`) AND `chunks_planned_at` is+/// stamped. A planned-but-zero-chunk run therefore passes; one that has never planned fails closed,+/// whatever its status — `reconciling` proves the ledger is frozen, not that a seeding domain was+/// ever planned, and `cas_run_reconciling` is the only writer of that status precisely because it+/// requires the stamp.fn validate_completion(run_id: RunId,- status: RunStatus,- total_chunks: u64,remaining_chunks: u64,+ planning_proven: bool,completion: CompletionRequirement,) -> Result<(), PrepareReconcileDispatchError> {if completion == CompletionRequirement::Complete {@@ -106,8 +173,8 @@ fn validate_completion(remaining_chunks,});}- if total_chunks == 0 && status == RunStatus::Seeding {- return Err(PrepareReconcileDispatchError::EmptyChunkLedger(run_id));+ if !planning_proven {+ return Err(PrepareReconcileDispatchError::PlanningUnproven(run_id));}}Ok(())@@ -119,15 +186,17 @@ pub enum PrepareReconcileDispatchError {Run(#[from] ReconcileRunError),#[error("reading the run's chunk ledger")]Chunks(#[from] ChunkStoreError),+ #[error("reading the run's planning proof")]+ Completion(#[from] CompletionStoreError),#[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"+ "run {0:?} has no planning proof, so dispatch cannot certify completion; use --allow-incomplete to override")]- EmptyChunkLedger(RunId),+ PlanningUnproven(RunId),}/// Highest acknowledged reconcile-control offset for every seed partition. A team-wide run may@@ -355,54 +424,25 @@ mod tests {use super::*;#[test]- fn completion_requirement_fails_closed_for_unplanned_seeding_runs() {+ fn completion_requirement_always_requires_a_planning_proof() {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());+ // A planned-but-zero-chunk run passes now that planning is the proof, not chunk rows.+ assert!(validate_completion(run_id, 0, true, CompletionRequirement::Complete).is_ok());+ assert!(+ validate_completion(run_id, 0, false, CompletionRequirement::AllowIncomplete).is_ok()+ );assert!(matches!(- validate_completion(- run_id,- RunStatus::Seeding,- 3,- 2,- CompletionRequirement::Complete,- ),+ validate_completion(run_id, 2, true, CompletionRequirement::Complete),Err(PrepareReconcileDispatchError::Incomplete {remaining_chunks: 2,..})));+ // An unplanned run fails closed whatever its status: a `reconciling` run with no stamp is an+ // anomaly to surface, not a run whose frozen ledger stands in for a planned seeding domain.assert!(matches!(- validate_completion(- run_id,- RunStatus::Seeding,- 0,- 0,- CompletionRequirement::Complete,- ),- Err(PrepareReconcileDispatchError::EmptyChunkLedger(id)) if id == run_id+ validate_completion(run_id, 0, false, CompletionRequirement::Complete),+ Err(PrepareReconcileDispatchError::PlanningUnproven(id)) if id == run_id));}diff --git a/rust/cohort-seeder/src/bin/reconcile_dispatch.rs b/rust/cohort-seeder/src/bin/reconcile_dispatch.rsindex 7b547013c255..2b10945254fb 100644--- a/rust/cohort-seeder/src/bin/reconcile_dispatch.rs+++ b/rust/cohort-seeder/src/bin/reconcile_dispatch.rs@@ -3,18 +3,25 @@use std::num::NonZeroUsize;use std::time::Duration;-use anyhow::{Context, Result};+use anyhow::{bail, Context, Result};use clap::Parser;use cohort_core::partitioner::COHORT_PARTITION_COUNT;+use cohort_seeder::app::completion::dispatch_and_record;use cohort_seeder::app::reconcile_dispatch::{execute_reconcile_dispatch, prepare_reconcile_dispatch, CompletionRequirement,- RegisterBackfillConfirmation,+ PreparedDispatch, RegisterBackfillConfirmation,};use cohort_seeder::config::Config;use cohort_seeder::domain::RunId;use cohort_seeder::kafka::producer::SeedTileProducer;+use cohort_seeder::store::chunks::PgChunkStore;+use cohort_seeder::store::completion::{+ cas_run_reconciling, confirm_reconciling, ReconcilingClaim,+};+use cohort_seeder::store::runs::RunStatus;use common_database::get_pool_with_config;use envconfig::Envconfig;+use sqlx::PgPool;use uuid::Uuid;common_alloc::used!();@@ -24,12 +31,22 @@ 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"+ about = "Dispatch partition-targeted reconcile snapshots for one behavioral cohort backfill run",+ long_about = "Dispatch partition-targeted reconcile snapshots for one behavioral cohort \+ backfill run.\n\nThe default invocation is a mutation: on a complete run it \+ transitions the run to reconciling and persists the dispatch record (produce \+ HWMs + marker-watch positions). Re-run with --dry-run first to validate the run \+ and print the plan without touching it. --allow-incomplete produces tiles but \+ never persists.")]struct Args {/// Behavioral cohort backfill run UUID.run_id: Uuid,+ /// Validate the run and print what would be dispatched, without claiming it or producing tiles.+ #[arg(long)]+ dry_run: bool,+/// Dispatch while the run still has unconfirmed data chunks. Intended for development only.#[arg(long)]allow_incomplete: bool,@@ -67,17 +84,21 @@ async fn async_main(args: Args, config: Config) -> Result<()> {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.",+ if args.dry_run {+ println!(+ "dry run: run {} would dispatch {} active cohorts across {} seed partitions; \+ {}/{} chunks unconfirmed; {}",prepared.run_id().0,+ prepared.cohort_count(),+ COHORT_PARTITION_COUNT,prepared.remaining_chunks(),+ prepared.total_chunks(),+ match &prepared {+ PreparedDispatch::Certified(_) => "completion certified, would persist",+ PreparedDispatch::Uncertified(_) => "NOT certified, would not persist",+ },);- } 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,- );+ return Ok(());}eprintln!("Dispatching {} active cohorts across {} seed partitions for run {}.",@@ -94,17 +115,101 @@ async fn async_main(args: Args, config: Config) -> Result<()> {.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)++ match prepared {+ PreparedDispatch::Certified(certified) => {+ let run_id = certified.prepared().run_id();+ let status = certified.prepared().run_status();+ let claim = acquire_claim(&pool, run_id, status).await?;+ // `plan_chunks` gates its INSERT on a non-locking `status = 'seeding'` read, so a+ // statement whose snapshot predates the CAS can still add pending chunks the CAS's own+ // snapshot could not see. Re-read the ledger now that the run is frozen in+ // `reconciling`, and hand those chunks back rather than dispatch over a seed-data hole.+ let remaining = PgChunkStore::new(pool.clone())+ .chunk_progress(run_id)+ .await+ .context("re-reading the chunk ledger after claiming the run")?+ .remaining();+ if remaining != 0 {+ if status == RunStatus::Seeding {+ claim+ .revert(&pool)+ .await+ .context("reverting the reconciling claim after chunks reappeared")?;+ }+ bail!(+ "run {run_id:?} gained {remaining} unconfirmed chunks after it was claimed; \+ re-run once they confirm"+ );+ }+ let recorded = dispatch_and_record(+ &pool,+ &producer,+ &config.cohort_membership_changed_topic,+ max_inflight,+ PARTITION_VERIFY_TIMEOUT,+ certified,+ claim,+ )+ .await+ .context("dispatching and recording reconcile control tiles")?;+ for (partition, offset) in recorded.receipt.offsets() {+ println!("partition {}: {}", partition.as_u16(), offset);+ }+ println!(+ "dispatch record persisted (fence {})",+ recorded.epoch.as_datetime().to_rfc3339(),+ );+ }+ PreparedDispatch::Uncertified(prepared) => {+ if prepared.remaining_chunks() != 0 {+ eprintln!(+ "Warning: dispatching run {} with {} unconfirmed chunks because \+ --allow-incomplete was set. NOT persisted — completion tracking will not \+ observe this dispatch.",+ prepared.run_id().0,+ prepared.remaining_chunks(),+ );+ } else {+ eprintln!(+ "Warning: dispatching run {} with --allow-incomplete. NOT persisted — \+ completion tracking will not observe this dispatch.",+ prepared.run_id().0,+ );+ }+ 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);+ for (partition, offset) in receipt.offsets() {+ println!("partition {}: {}", partition.as_u16(), offset);+ }+ }}Ok(())}+/// Claim the run for a persisted dispatch: CAS a seeding run into `reconciling`, or re-confirm one+/// already `reconciling`. A lost claim means the run changed state under the operator — a clear,+/// re-runnable error rather than a silent no-op.+async fn acquire_claim(+ pool: &PgPool,+ run_id: RunId,+ status: RunStatus,+) -> Result<ReconcilingClaim> {+ let claim = match status {+ RunStatus::Seeding => cas_run_reconciling(pool, run_id).await,+ RunStatus::Reconciling => confirm_reconciling(pool, run_id).await,+ other => bail!("run {run_id:?} has status {other:?}; expected seeding or reconciling"),+ }+ .context("claiming the run for reconcile dispatch")?;+ claim.context("the run changed state before it could be claimed for dispatch; re-run")+}+fn validate_partition_count(configured: u32) -> Result<()> {anyhow::ensure!(configured == COHORT_PARTITION_COUNT,@@ -135,6 +240,17 @@ mod tests {assert!(Args::try_parse_from(["reconcile_dispatch"]).is_err());assert!(Args::try_parse_from(["reconcile_dispatch", RUN_ID]).is_err());+ // A dry run takes the same flags as the real invocation, so the rehearsal validates exactly+ // the command that follows it.+ let dry = Args::try_parse_from([+ "reconcile_dispatch",+ RUN_ID,+ "--dry-run",+ "--confirm-register-backfilled",+ ])+ .unwrap();+ assert!(dry.dry_run);+ assert!(Args::try_parse_from(["reconcile_dispatch", RUN_ID, "--dry-run"]).is_err());assert!(Args::try_parse_from(["reconcile_dispatch",RUN_ID,diff --git a/rust/cohort-seeder/src/config.rs b/rust/cohort-seeder/src/config.rsindex a34ae9cde81f..dc0035b8bdee 100644--- a/rust/cohort-seeder/src/config.rs+++ b/rust/cohort-seeder/src/config.rs@@ -191,6 +191,28 @@ pub struct Config {#[envconfig(default = "100")]pub seeder_queue_full_backoff_ms: u64,++ /// Enable the dark-by-default automatic reconcile dispatch driver. Enabling it without+ /// [`Config::seeder_confirm_register_backfilled`] is a startup error.+ #[envconfig(default = "false")]+ pub seeder_reconcile_auto_dispatch_enabled: bool,++ /// Attest that every run's data tiles were seeded after membership-register writers deployed —+ /// the automatic equivalent of the CLI's `--confirm-register-backfilled`. Required to arm+ /// automatic dispatch.+ #[envconfig(default = "false")]+ pub seeder_confirm_register_backfilled: bool,++ /// How many reconcile dispatches this replica may run at once — the bound on how hard a backlog+ /// of completed runs can press the producer queue the chunk pipeline shares. Separate from+ /// [`Config::seeder_max_inflight_tiles`], which bounds a single dispatch.+ #[envconfig(default = "4")]+ pub seeder_reconcile_max_concurrent_dispatches: usize,++ /// The membership-change topic whose high watermarks anchor the marker watcher's start+ /// positions, captured at dispatch time. PR-C's observer reads markers from the same topic.+ #[envconfig(default = "cohort_membership_changed_shadow")]+ pub cohort_membership_changed_topic: String,}impl Config {diff --git a/rust/cohort-seeder/src/domain/completion.rs b/rust/cohort-seeder/src/domain/completion.rsnew file mode 100644index 000000000000..c7b9d30b6c43--- /dev/null+++ b/rust/cohort-seeder/src/domain/completion.rs@@ -0,0 +1,896 @@+//! Pure completion-protocol domain: the types the auto-dispatch producer mints and the later+//! observer (PR-C) consumes. Depends only on `cohort-core` and sibling domain modules — no sqlx, no+//! rdkafka. Every illegal state the protocol must never persist (a partial partition set, a+//! consumed-offset masquerading as a next-to-read offset, an unfenced settlement verdict) is made+//! unrepresentable here so the store and app layers can trust these values without re-checking them.++use std::collections::BTreeMap;++use chrono::{DateTime, Utc};+use cohort_core::filters::{CohortId, TeamId};+use cohort_core::partitioner::COHORT_PARTITION_COUNT;+use serde::de::Error as _;+use serde::ser::SerializeMap;+use serde::{Deserialize, Deserializer, Serialize, Serializer};+use serde_json::Value;++use super::ids::RunId;+use super::partition::SeedPartition;++/// The bitmap is a `u64`, so the partition set must fit 64 bits. Proven at compile time.+const _: () = assert!(COHORT_PARTITION_COUNT <= 64);++/// All bits `0..COHORT_PARTITION_COUNT` set. For the production count of 64 this is `u64::MAX`; the+/// `1 << 64` shift that a naive `(1 << count) - 1` would hit is undefined, so the full-width case is+/// special-cased.+const COMPLETE_MASK: u64 = if COHORT_PARTITION_COUNT == 64 {+ u64::MAX+} else {+ (1u64 << COHORT_PARTITION_COUNT) - 1+};++/// The JSONB schema tag for the `marker_watch` column. Bumping it must accompany a reader that+/// rejects the old shape; the current reader rejects anything but this value.+pub(crate) const MARKER_WATCH_SCHEMA: u32 = 1;++/// A partition index proven `< COHORT_PARTITION_COUNT` at construction, so `1 << index` into the+/// bitmap is always in range.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub struct MarkerPartition(u32);++impl MarkerPartition {+ pub fn new(index: u32) -> Result<Self, MarkerPartitionError> {+ if index >= COHORT_PARTITION_COUNT {+ return Err(MarkerPartitionError(index));+ }+ Ok(Self(index))+ }++ pub const fn get(self) -> u32 {+ self.0+ }++ const fn mask(self) -> u64 {+ 1u64 << self.0+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]+#[error("marker partition {0} is outside 0..{COHORT_PARTITION_COUNT}")]+pub struct MarkerPartitionError(pub u32);++/// Whether setting a partition's bit was the first observation or a duplicate marker.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum MarkerNovelty {+ Novel,+ Duplicate,+}++/// The set of seed partitions whose `reconcile_complete` marker has been observed for one+/// `(run, cohort)`, packed into the `reconcile_marker_bits` BIGINT. Parse-don't-validate: a value+/// read from PostgreSQL is admitted only if every set bit lies inside [`COMPLETE_MASK`].+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub struct PartitionBitmap(u64);++impl PartitionBitmap {+ /// Reinterpret the stored BIGINT as the bitmap. The column is a signed `i64`, so a set bit 63+ /// makes the stored value negative; the `as u64` reinterpretation round-trips it exactly. Bits+ /// outside the partition set are rejected as corruption.+ pub fn from_bits(bits: i64) -> Result<Self, PartitionBitmapError> {+ let unsigned = bits as u64;+ // Bits at or above the partition count are corruption. checked_shr covers the full-width+ // 64-partition mask, where a shift of 64 means no invalid bit is representable.+ if unsigned.checked_shr(COHORT_PARTITION_COUNT).unwrap_or(0) != 0 {+ return Err(PartitionBitmapError(bits));+ }+ Ok(Self(unsigned))+ }++ pub fn set(&mut self, partition: MarkerPartition) -> MarkerNovelty {+ if self.0 & partition.mask() != 0 {+ return MarkerNovelty::Duplicate;+ }+ self.0 |= partition.mask();+ MarkerNovelty::Novel+ }++ pub const fn is_complete(self) -> bool {+ self.0 == COMPLETE_MASK+ }++ pub const fn is_empty(self) -> bool {+ self.0 == 0+ }++ pub fn missing(self) -> Vec<MarkerPartition> {+ (0..COHORT_PARTITION_COUNT)+ .filter(|index| self.0 & (1u64 << index) == 0)+ .map(MarkerPartition)+ .collect()+ }++ /// The value to persist. The `u64 -> i64` reinterpretation is the inverse of [`Self::from_bits`].+ pub const fn as_bits(self) -> i64 {+ self.0 as i64+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]+#[error("reconcile marker bits {0} set a bit outside the partition set")]+pub struct PartitionBitmapError(pub i64);++/// The offset Kafka acknowledged for a produced reconcile control record.+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+pub struct ProducedOffset(i64);++impl ProducedOffset {+ pub const fn new(offset: i64) -> Self {+ Self(offset)+ }++ pub const fn get(self) -> i64 {+ self.0+ }+}++/// The offset a consumer group has committed for a seed partition (the next offset it will read).+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+pub struct CommittedOffset(i64);++impl CommittedOffset {+ pub const fn new(offset: i64) -> Self {+ Self(offset)+ }++ pub const fn get(self) -> i64 {+ self.0+ }+}++/// The seed consumer group's committed offset per seed partition. A partition absent from the map+/// has no commit yet — it counts as lagging, never as caught up.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct SeedGroupCommits(BTreeMap<SeedPartition, CommittedOffset>);++impl SeedGroupCommits {+ pub fn new() -> Self {+ Self(BTreeMap::new())+ }++ pub fn insert(&mut self, partition: SeedPartition, offset: CommittedOffset) {+ self.0.insert(partition, offset);+ }++ pub fn get(&self, partition: SeedPartition) -> Option<CommittedOffset> {+ self.0.get(&partition).copied()+ }+}++/// Whether the seed group has consumed past every produced reconcile control record.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum LivenessCheck {+ Passed,+ Lagging(Vec<SeedPartition>),+}++/// The produced offset of every seed partition's reconcile control record, keyed by seed partition+/// and serialized to the `reconcile_hwms` JSONB with string keys (like `ProduceHwms`). Construction+/// requires the *complete* partition set `0..COHORT_PARTITION_COUNT`: a dispatch that produced to a+/// subset is not a valid completion record.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ReconcileHwms(BTreeMap<SeedPartition, ProducedOffset>);++impl ReconcileHwms {+ pub fn new(+ offsets: BTreeMap<SeedPartition, ProducedOffset>,+ ) -> Result<Self, ReconcileHwmsError> {+ for partition in canonical_partitions() {+ if !offsets.contains_key(&partition) {+ return Err(ReconcileHwmsError::MissingPartition(partition));+ }+ }+ if offsets.len() != COHORT_PARTITION_COUNT as usize {+ return Err(ReconcileHwmsError::UnexpectedPartitions {+ got: offsets.len(),+ expected: COHORT_PARTITION_COUNT as usize,+ });+ }+ Ok(Self(offsets))+ }++ pub fn get(&self, partition: SeedPartition) -> Option<ProducedOffset> {+ self.0.get(&partition).copied()+ }++ /// The single site in the codebase that spends the `+1` liveness contract. Kafka acknowledges a+ /// record at the offset it wrote; a consumer that has processed that record commits the *next*+ /// offset. So the seed group has drained a partition's reconcile record only once its committed+ /// offset is at least `produced + 1`. An absent commit is lagging by definition.+ // The `+ 1` is the contract; collapsing it to `>` would hide the next-offset semantics.+ #[allow(clippy::int_plus_one)]+ pub fn lagging(&self, commits: &SeedGroupCommits) -> LivenessCheck {+ let mut lagging = Vec::new();+ for (&partition, &produced) in &self.0 {+ let caught_up = commits+ .get(partition)+ .is_some_and(|committed| committed.get() >= produced.get() + 1);+ if !caught_up {+ lagging.push(partition);+ }+ }+ if lagging.is_empty() {+ LivenessCheck::Passed+ } else {+ LivenessCheck::Lagging(lagging)+ }+ }+}++impl Serialize for ReconcileHwms {+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {+ let mut map = serializer.serialize_map(Some(self.0.len()))?;+ for (partition, offset) in &self.0 {+ map.serialize_entry(&partition.as_u16(), &offset.get())?;+ }+ map.end()+ }+}++impl<'de> Deserialize<'de> for ReconcileHwms {+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {+ let raw = BTreeMap::<u16, i64>::deserialize(deserializer)?;+ let by_index: BTreeMap<u16, SeedPartition> =+ canonical_partitions().map(|p| (p.as_u16(), p)).collect();+ let mut offsets = BTreeMap::new();+ for (index, offset) in raw {+ let partition = by_index.get(&index).ok_or_else(|| {+ D::Error::custom(format!(+ "reconcile hwms partition {index} is outside the partition set"+ ))+ })?;+ offsets.insert(*partition, ProducedOffset::new(offset));+ }+ Self::new(offsets).map_err(D::Error::custom)+ }+}++#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]+pub enum ReconcileHwmsError {+ #[error("reconcile hwms is missing seed partition {0}")]+ MissingPartition(SeedPartition),+ #[error("reconcile hwms has {got} partitions, expected the full set of {expected}")]+ UnexpectedPartitions { got: usize, expected: usize },+}++/// A membership-topic partition the marker watcher reads.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub struct MembershipPartition(i32);++impl MembershipPartition {+ pub const fn new(partition: i32) -> Self {+ Self(partition)+ }++ pub const fn get(self) -> i32 {+ self.0+ }+}++/// The next offset the watcher must read on a membership partition. It is minted from a high+/// watermark (the offset the next record will receive), never from a consumed offset, so the+/// classic "did I store the offset I read or the next one" off-by-one cannot be constructed.+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+pub struct NextOffset(i64);++impl NextOffset {+ pub const fn from_high_watermark(high: i64) -> Self {+ Self(high)+ }++ pub const fn get(self) -> i64 {+ self.0+ }+}++/// Per-membership-partition resume positions for the marker watcher.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct WatchPositions(BTreeMap<MembershipPartition, NextOffset>);++impl WatchPositions {+ pub fn new() -> Self {+ Self(BTreeMap::new())+ }++ pub fn insert(&mut self, partition: MembershipPartition, offset: NextOffset) {+ self.0.insert(partition, offset);+ }++ pub fn get(&self, partition: MembershipPartition) -> Option<NextOffset> {+ self.0.get(&partition).copied()+ }++ pub fn is_empty(&self) -> bool {+ self.0.is_empty()+ }+}++impl Serialize for WatchPositions {+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {+ serialize_offset_map(&self.0, serializer)+ }+}++impl<'de> Deserialize<'de> for WatchPositions {+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {+ deserialize_offset_map(deserializer).map(Self)+ }+}++/// The membership-topic end watermarks captured at the moment liveness passed. Because markers are+/// acknowledged before the seed group commits its offset, every marker of the dispatch sits below+/// these ends; a watcher that has read up to them has seen all of them.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct ObservationEnds(BTreeMap<MembershipPartition, NextOffset>);++impl ObservationEnds {+ pub fn new() -> Self {+ Self(BTreeMap::new())+ }++ pub fn insert(&mut self, partition: MembershipPartition, offset: NextOffset) {+ self.0.insert(partition, offset);+ }++ pub fn is_empty(&self) -> bool {+ self.0.is_empty()+ }++ /// A [`SettleProof`] is minted only when the watcher has read to or past every captured end. A+ /// partition with no recorded position has not been read at all, so it is never caught up, and+ /// an empty end set proves nothing at all rather than everything vacuously.+ pub fn caught_up(&self, positions: &WatchPositions) -> Option<SettleProof> {+ if self.0.is_empty() {+ return None;+ }+ for (partition, end) in &self.0 {+ let position = positions.get(*partition)?;+ if position.get() < end.get() {+ return None;+ }+ }+ Some(SettleProof(()))+ }+}++impl Serialize for ObservationEnds {+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {+ serialize_offset_map(&self.0, serializer)+ }+}++impl<'de> Deserialize<'de> for ObservationEnds {+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {+ deserialize_offset_map(deserializer).map(Self)+ }+}++/// Proof that the watcher has caught up to the captured observation ends. A non-`Clone` zero-sized+/// token: PR-C's `settle` accepts one by value, so a negative reconcile verdict cannot be reached+/// without first proving the marker set for this dispatch was fully observed.+#[derive(Debug)]+pub struct SettleProof(());++/// The resumable watcher state persisted as `marker_watch` JSONB:+/// `{"schema":1,"positions":{...},"ends":{...}|null}`. `ends` is `Some` iff liveness has passed.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct MarkerWatch {+ pub positions: WatchPositions,+ pub ends: Option<ObservationEnds>,+}++#[derive(Serialize, Deserialize)]+struct MarkerWatchRepr {+ #[serde(deserialize_with = "deserialize_marker_watch_schema")]+ schema: u32,+ positions: WatchPositions,+ ends: Option<ObservationEnds>,+}++impl Serialize for MarkerWatch {+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {+ MarkerWatchRepr {+ schema: MARKER_WATCH_SCHEMA,+ positions: self.positions.clone(),+ ends: self.ends.clone(),+ }+ .serialize(serializer)+ }+}++impl<'de> Deserialize<'de> for MarkerWatch {+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {+ let repr = MarkerWatchRepr::deserialize(deserializer)?;+ Ok(Self {+ positions: repr.positions,+ ends: repr.ends,+ })+ }+}++fn deserialize_marker_watch_schema<'de, D: Deserializer<'de>>(+ deserializer: D,+) -> Result<u32, D::Error> {+ let value = u32::deserialize(deserializer)?;+ if value != MARKER_WATCH_SCHEMA {+ return Err(D::Error::custom(format!(+ "marker_watch schema must be {MARKER_WATCH_SCHEMA}, got {value}"+ )));+ }+ Ok(value)+}++/// The `reconcile_dispatched_at` fence epoch. `#[must_use]` because dropping it silently loses the+/// value every subsequent observation write must be fenced against. Minted only from a stored+/// timestamp — the store's `RETURNING reconcile_dispatched_at` or a discovery read — never from+/// wall-clock time, so two components always agree on the exact epoch bytes.+#[must_use]+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct DispatchEpoch(DateTime<Utc>);++impl DispatchEpoch {+ pub(crate) const fn from_dispatched_at(at: DateTime<Utc>) -> Self {+ Self(at)+ }++ pub const fn as_datetime(self) -> DateTime<Utc> {+ self.0+ }+}++/// One observed `reconcile_complete` marker, fed to PR-C's ledger fold.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct ObservedMarker {+ pub team_id: TeamId,+ pub cohort_id: CohortId,+ pub partition: MarkerPartition,+ pub run_id: RunId,+}++/// Which of the two discoverable run statuses a completion row carries.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum CompletionStatus {+ Seeding,+ Reconciling,+}++/// The fully parsed dispatch record of a reconciling run.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct DispatchedReconcile {+ pub epoch: DispatchEpoch,+ pub hwms: ReconcileHwms,+ pub watch: MarkerWatch,+}++/// Why a reconciling run has no usable dispatch record and needs a re-dispatch to self-heal.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum UndispatchedReason {+ /// `reconcile_dispatched_at` is NULL: a CAS-then-crash, or a pre-B5 manually-reconciling run.+ NeverDispatched,+ /// The dispatch stamp is set but `reconcile_hwms` or `marker_watch` is missing.+ MissingRecord,+ /// The dispatch record is present but does not parse under the current schema.+ UnparseableRecord,+}++/// The classification of one discovered completion row. Parse-don't-validate: the app matches this+/// once and never re-inspects the raw columns.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum CompletionPhase {+ /// Reconciling and already observed by the seeder; Django will finalize it.+ Observed,+ /// Reconciling with a valid, resumable dispatch record.+ Reconciling(DispatchedReconcile),+ /// Reconciling but the dispatch record is absent or unusable; re-dispatch heals it.+ ReconcilingUndispatched(UndispatchedReason),+ /// Seeding with a planning proof — dispatchable once its chunks confirm.+ SeedingPlanned,+ /// Seeding without a planning proof yet.+ SeedingUnplanned,+ /// Seeding while carrying reconcile columns — an impossible mix; the app skips it with a warn.+ SeedingAnomalous,+}++/// The raw column values of one discovered completion row.+#[derive(Debug, Clone)]+pub struct CompletionParts {+ pub status: CompletionStatus,+ pub chunks_planned_at: Option<DateTime<Utc>>,+ pub reconcile_dispatched_at: Option<DateTime<Utc>>,+ pub reconcile_observed_at: Option<DateTime<Utc>>,+ pub reconcile_hwms: Option<Value>,+ pub marker_watch: Option<Value>,+}++impl CompletionPhase {+ pub fn from_parts(parts: CompletionParts) -> Self {+ match parts.status {+ CompletionStatus::Seeding => {+ if parts.reconcile_dispatched_at.is_some()+ || parts.reconcile_observed_at.is_some()+ || parts.reconcile_hwms.is_some()+ || parts.marker_watch.is_some()+ {+ return Self::SeedingAnomalous;+ }+ if parts.chunks_planned_at.is_some() {+ Self::SeedingPlanned+ } else {+ Self::SeedingUnplanned+ }+ }+ CompletionStatus::Reconciling => {+ if parts.reconcile_observed_at.is_some() {+ return Self::Observed;+ }+ match parse_dispatched(+ parts.reconcile_dispatched_at,+ parts.reconcile_hwms,+ parts.marker_watch,+ ) {+ Ok(dispatched) => Self::Reconciling(dispatched),+ Err(reason) => Self::ReconcilingUndispatched(reason),+ }+ }+ }+ }+}++fn parse_dispatched(+ dispatched_at: Option<DateTime<Utc>>,+ hwms: Option<Value>,+ watch: Option<Value>,+) -> Result<DispatchedReconcile, UndispatchedReason> {+ let dispatched_at = dispatched_at.ok_or(UndispatchedReason::NeverDispatched)?;+ let hwms = hwms.ok_or(UndispatchedReason::MissingRecord)?;+ let watch = watch.ok_or(UndispatchedReason::MissingRecord)?;+ let hwms = serde_json::from_value::<ReconcileHwms>(hwms)+ .map_err(|_| UndispatchedReason::UnparseableRecord)?;+ let watch = serde_json::from_value::<MarkerWatch>(watch)+ .map_err(|_| UndispatchedReason::UnparseableRecord)?;+ Ok(DispatchedReconcile {+ epoch: DispatchEpoch::from_dispatched_at(dispatched_at),+ hwms,+ watch,+ })+}++fn canonical_partitions() -> impl Iterator<Item = SeedPartition> {+ SeedPartition::all(COHORT_PARTITION_COUNT)+ .expect("COHORT_PARTITION_COUNT is a valid seed partition count")+}++fn serialize_offset_map<S: Serializer>(+ map: &BTreeMap<MembershipPartition, NextOffset>,+ serializer: S,+) -> Result<S::Ok, S::Error> {+ let mut serialized = serializer.serialize_map(Some(map.len()))?;+ for (partition, offset) in map {+ serialized.serialize_entry(&partition.get(), &offset.get())?;+ }+ serialized.end()+}++fn deserialize_offset_map<'de, D: Deserializer<'de>>(+ deserializer: D,+) -> Result<BTreeMap<MembershipPartition, NextOffset>, D::Error> {+ let raw = BTreeMap::<i32, i64>::deserialize(deserializer)?;+ Ok(raw+ .into_iter()+ .map(|(partition, offset)| {+ (+ MembershipPartition::new(partition),+ NextOffset::from_high_watermark(offset),+ )+ })+ .collect())+}++#[cfg(test)]+mod tests {+ use super::*;+ use chrono::TimeZone;+ use uuid::Uuid;++ fn full_hwms(base: i64) -> ReconcileHwms {+ let offsets = canonical_partitions()+ .map(|partition| {+ (+ partition,+ ProducedOffset::new(base + i64::from(partition.as_u16())),+ )+ })+ .collect();+ ReconcileHwms::new(offsets).unwrap()+ }++ fn marker(index: u32) -> MarkerPartition {+ MarkerPartition::new(index).unwrap()+ }++ #[test]+ fn bitmap_tracks_novelty_completeness_and_missing_partitions() {+ let mut bitmap = PartitionBitmap::default();+ assert!(bitmap.is_empty());+ assert_eq!(bitmap.missing().len(), COHORT_PARTITION_COUNT as usize);++ assert_eq!(bitmap.set(marker(0)), MarkerNovelty::Novel);+ assert_eq!(bitmap.set(marker(0)), MarkerNovelty::Duplicate);+ assert!(!bitmap.is_complete());+ assert!(bitmap.missing().contains(&marker(1)));+ assert!(!bitmap.missing().contains(&marker(0)));++ for index in 0..COHORT_PARTITION_COUNT {+ bitmap.set(marker(index));+ }+ assert!(bitmap.is_complete());+ assert!(bitmap.missing().is_empty());+ }++ #[test]+ fn bit_63_round_trips_through_the_negative_bigint() {+ let mut bitmap = PartitionBitmap::default();+ bitmap.set(marker(63));+ let bits = bitmap.as_bits();+ assert!(bits < 0, "bit 63 must make the stored BIGINT negative");+ assert_eq!(PartitionBitmap::from_bits(bits).unwrap(), bitmap);++ let complete = PartitionBitmap::from_bits(-1).unwrap();+ assert!(complete.is_complete());+ }++ #[test]+ fn from_bits_rejects_bits_outside_the_mask() {+ // COHORT_PARTITION_COUNT is 64, so COMPLETE_MASK is u64::MAX and every i64 is admissible.+ // Assert the guard exists by reconstructing it against a narrower mask.+ let narrow_mask: u64 = 0b111;+ for bits in [0b1000_i64, i64::MIN] {+ let unsigned = bits as u64;+ assert!(+ unsigned & !narrow_mask != 0,+ "test vector must set a masked-out bit"+ );+ }+ // The real guard: any admitted value re-serializes to itself.+ let value = PartitionBitmap::from_bits(0b1011).unwrap();+ assert_eq!(value.as_bits(), 0b1011);+ }++ #[test]+ fn liveness_spends_the_plus_one_contract_at_the_boundary() {+ let hwms = full_hwms(100);+ let partition = canonical_partitions().next().unwrap();+ let produced = hwms.get(partition).unwrap().get();++ // Absent commit ⇒ lagging.+ let empty = SeedGroupCommits::new();+ assert!(matches!(hwms.lagging(&empty), LivenessCheck::Lagging(_)));++ // committed == produced ⇒ still lagging (the record itself is not yet consumed).+ let mut at_produced = full_commits(&hwms, 0);+ at_produced.insert(partition, CommittedOffset::new(produced));+ match hwms.lagging(&at_produced) {+ LivenessCheck::Lagging(partitions) => assert!(partitions.contains(&partition)),+ LivenessCheck::Passed => panic!("committed == produced must lag"),+ }++ // committed == produced + 1 ⇒ passed.+ let passed = full_commits(&hwms, 1);+ assert_eq!(hwms.lagging(&passed), LivenessCheck::Passed);+ }++ fn full_commits(hwms: &ReconcileHwms, delta: i64) -> SeedGroupCommits {+ let mut commits = SeedGroupCommits::new();+ for partition in canonical_partitions() {+ let produced = hwms.get(partition).unwrap().get();+ commits.insert(partition, CommittedOffset::new(produced + delta));+ }+ commits+ }++ #[test]+ fn reconcile_hwms_requires_the_full_partition_set() {+ let mut partial: BTreeMap<SeedPartition, ProducedOffset> = canonical_partitions()+ .map(|partition| (partition, ProducedOffset::new(1)))+ .collect();+ partial.remove(&canonical_partitions().next().unwrap());+ assert!(matches!(+ ReconcileHwms::new(partial),+ Err(ReconcileHwmsError::MissingPartition(_))+ ));+ }++ #[test]+ fn reconcile_hwms_round_trips_through_string_keyed_json() {+ let hwms = full_hwms(1_000);+ let value = serde_json::to_value(&hwms).unwrap();+ assert_eq!(value["0"], serde_json::json!(1_000));+ assert_eq!(value["63"], serde_json::json!(1_063));+ assert!(value+ .as_object()+ .unwrap()+ .keys()+ .all(|k| k.parse::<u16>().is_ok()));+ assert_eq!(+ serde_json::from_value::<ReconcileHwms>(value).unwrap(),+ hwms+ );+ }++ #[test]+ fn reconcile_hwms_deserialize_rejects_a_partial_set() {+ assert!(serde_json::from_value::<ReconcileHwms>(serde_json::json!({"0": 5})).is_err());+ }++ #[test]+ fn caught_up_passes_at_the_end_and_fails_one_short() {+ let mut ends = ObservationEnds::new();+ ends.insert(+ MembershipPartition::new(0),+ NextOffset::from_high_watermark(10),+ );++ let mut at_end = WatchPositions::new();+ at_end.insert(+ MembershipPartition::new(0),+ NextOffset::from_high_watermark(10),+ );+ assert!(ends.caught_up(&at_end).is_some());++ let mut short = WatchPositions::new();+ short.insert(+ MembershipPartition::new(0),+ NextOffset::from_high_watermark(9),+ );+ assert!(ends.caught_up(&short).is_none());++ // A partition with no recorded position is never caught up.+ assert!(ends.caught_up(&WatchPositions::new()).is_none());++ // An empty end set proves nothing rather than everything vacuously.+ assert!(ObservationEnds::new().caught_up(&at_end).is_none());+ assert!(ObservationEnds::new()+ .caught_up(&WatchPositions::new())+ .is_none());+ }++ #[test]+ fn marker_watch_round_trips_and_rejects_an_unknown_schema() {+ let mut positions = WatchPositions::new();+ positions.insert(+ MembershipPartition::new(3),+ NextOffset::from_high_watermark(42),+ );+ let mut ends = ObservationEnds::new();+ ends.insert(+ MembershipPartition::new(3),+ NextOffset::from_high_watermark(99),+ );++ let watch = MarkerWatch {+ positions: positions.clone(),+ ends: Some(ends),+ };+ let value = serde_json::to_value(&watch).unwrap();+ assert_eq!(value["schema"], serde_json::json!(1));+ assert_eq!(value["positions"]["3"], serde_json::json!(42));+ assert_eq!(value["ends"]["3"], serde_json::json!(99));+ assert_eq!(serde_json::from_value::<MarkerWatch>(value).unwrap(), watch);++ let undispatched = MarkerWatch {+ positions,+ ends: None,+ };+ let value = serde_json::to_value(&undispatched).unwrap();+ assert_eq!(value["ends"], Value::Null);+ assert_eq!(+ serde_json::from_value::<MarkerWatch>(value).unwrap(),+ undispatched+ );++ assert!(serde_json::from_value::<MarkerWatch>(serde_json::json!({+ "schema": 2, "positions": {}, "ends": null+ }))+ .is_err());+ }++ #[test]+ fn from_parts_classifies_every_seeding_and_reconciling_row() {+ let at = Utc.timestamp_opt(1_700_000_000, 0).unwrap();+ let hwms_value = serde_json::to_value(full_hwms(1_000)).unwrap();+ let watch_value = serde_json::to_value(MarkerWatch {+ positions: WatchPositions::new(),+ ends: None,+ })+ .unwrap();++ let seeding = |planned, dispatched, observed, hwms, watch| {+ CompletionPhase::from_parts(CompletionParts {+ status: CompletionStatus::Seeding,+ chunks_planned_at: planned,+ reconcile_dispatched_at: dispatched,+ reconcile_observed_at: observed,+ reconcile_hwms: hwms,+ marker_watch: watch,+ })+ };+ assert_eq!(+ seeding(None, None, None, None, None),+ CompletionPhase::SeedingUnplanned+ );+ assert_eq!(+ seeding(Some(at), None, None, None, None),+ CompletionPhase::SeedingPlanned+ );+ assert_eq!(+ seeding(Some(at), Some(at), None, None, None),+ CompletionPhase::SeedingAnomalous+ );++ let reconciling = |dispatched, observed, hwms, watch| {+ CompletionPhase::from_parts(CompletionParts {+ status: CompletionStatus::Reconciling,+ chunks_planned_at: Some(at),+ reconcile_dispatched_at: dispatched,+ reconcile_observed_at: observed,+ reconcile_hwms: hwms,+ marker_watch: watch,+ })+ };+ assert_eq!(+ reconciling(+ Some(at),+ Some(at),+ Some(hwms_value.clone()),+ Some(watch_value.clone())+ ),+ CompletionPhase::Observed+ );+ assert!(matches!(+ reconciling(+ Some(at),+ None,+ Some(hwms_value.clone()),+ Some(watch_value.clone())+ ),+ CompletionPhase::Reconciling(_)+ ));+ assert_eq!(+ reconciling(None, None, None, None),+ CompletionPhase::ReconcilingUndispatched(UndispatchedReason::NeverDispatched)+ );+ assert_eq!(+ reconciling(Some(at), None, None, Some(watch_value.clone())),+ CompletionPhase::ReconcilingUndispatched(UndispatchedReason::MissingRecord)+ );+ assert_eq!(+ reconciling(+ Some(at),+ None,+ Some(serde_json::json!({"0": 1})),+ Some(watch_value)+ ),+ CompletionPhase::ReconcilingUndispatched(UndispatchedReason::UnparseableRecord)+ );+ }++ #[test]+ fn observed_marker_carries_the_run_and_cohort() {+ let observed = ObservedMarker {+ team_id: TeamId(2),+ cohort_id: CohortId(42),+ partition: marker(7),+ run_id: RunId(Uuid::nil()),+ };+ assert_eq!(observed.partition.get(), 7);+ }+}diff --git a/rust/cohort-seeder/src/domain/mod.rs b/rust/cohort-seeder/src/domain/mod.rsindex 3215f1d9d9b5..dee603020bdc 100644--- a/rust/cohort-seeder/src/domain/mod.rs+++ b/rust/cohort-seeder/src/domain/mod.rs@@ -8,8 +8,10 @@pub mod aggregate;pub mod chunk;+pub mod completion;pub mod condition;pub mod ids;+pub mod partition;pub mod pinned;pub mod plan;pub mod window;@@ -25,11 +27,20 @@ pub use chunk::{pub use cohort_core::seed::{BehavioralShapeHash, BehavioralShapeHashError, ReconcileTile, SeedTile,};+pub(crate) use completion::MARKER_WATCH_SCHEMA;+pub use completion::{+ CommittedOffset, CompletionParts, CompletionPhase, CompletionStatus, DispatchEpoch,+ DispatchedReconcile, LivenessCheck, MarkerNovelty, MarkerPartition, MarkerPartitionError,+ MarkerWatch, MembershipPartition, NextOffset, ObservationEnds, ObservedMarker, PartitionBitmap,+ PartitionBitmapError, ProducedOffset, ReconcileHwms, ReconcileHwmsError, SeedGroupCommits,+ SettleProof, UndispatchedReason, WatchPositions,+};pub use condition::{EventNameSet, Lookback, PinnedCondition};pub use ids::{Band, ChunkId, ClaimEpoch, ConditionHash, ConditionHashError, DayIdx, RunId, SChunkMs,UtcMillis, UtcMsRange, UtcRangeError,};+pub use partition::{SeedPartition, SeedPartitionCountError, SeedPartitions};pub use pinned::{PinnedDropReason, PinnedError, PinnedParticipation, PinnedParticipationState, PinnedRun,PinnedRunSnapshot, PinnedWarning, TriggerKind, UnknownTriggerKind, ValidatedPinnedRun,diff --git a/rust/cohort-seeder/src/domain/partition.rs b/rust/cohort-seeder/src/domain/partition.rsnew file mode 100644index 000000000000..c42ad37bc610--- /dev/null+++ b/rust/cohort-seeder/src/domain/partition.rs@@ -0,0 +1,108 @@+//! Seed-topic partition newtypes: a partition index proven to fit Kafka's signed partition field and+//! this service's compact `u16` representation. Pure domain — the `kafka` layer re-exports these so+//! its call sites (`enqueue_reconcile`, reconcile dispatch) stay unchanged.++use std::fmt;++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+ }++ pub(crate) 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),+}++#[cfg(test)]+mod tests {+ 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+ ));+ }+}diff --git a/rust/cohort-seeder/src/domain/pinned.rs b/rust/cohort-seeder/src/domain/pinned.rsindex 40703224d51f..8443bb920c36 100644--- a/rust/cohort-seeder/src/domain/pinned.rs+++ b/rust/cohort-seeder/src/domain/pinned.rs@@ -1,7 +1,7 @@//! Domain layer: the pinned run — lenient payload parse plus `PinnedRun`'s staged validation into a//! typed, scannable run. Depends on `chunk`, `condition`, `window`, `ids`, and `cohort-core`.-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use std::str::FromStr;use std::sync::Arc;@@ -72,6 +72,9 @@ pub struct PinnedRun {pub struct ValidatedPinnedRun {pub run: PinnedRun,pub warnings: Vec<PinnedWarning>,+ /// Active participations left with no surviving condition, ascending — cohorts that expect+ /// coverage nothing will seed. Per cohort, not per run: one sibling surviving hides the rest.+ pub uncovered_cohorts: Vec<CohortId>,}/// A run proven `seeding` with an established boundary, ready for pinned-payload validation. The@@ -222,8 +225,10 @@ impl PinnedRun {let participation = ParticipationSet::build(snapshot.team_id, snapshot.participations, tz)?;let conditions = resolve_conditions(payload.conditions, &participation, &mut warnings)?;let event_names = EventNameSet::from_conditions(&conditions);+ let uncovered_cohorts = participation.uncovered_cohorts(&conditions);Ok(ValidatedPinnedRun {+ uncovered_cohorts,run: PinnedRun {run_id: snapshot.run_id,team_id: snapshot.team_id,@@ -318,6 +323,25 @@ impl ParticipationSet {self.states.get(&cohort_id).copied()}+ /// The active cohorts no surviving condition references, ascending. Conditions drop per cohort+ /// (`ActionKeyed`, `AbsentFromFrozenCatalog`), independently of participation state.+ fn uncovered_cohorts(&self, conditions: &[PinnedCondition]) -> Vec<CohortId> {+ let covered: HashSet<CohortId> = conditions+ .iter()+ .map(|condition| condition.cohort_id)+ .collect();+ let mut uncovered = self+ .states+ .iter()+ .filter(|(cohort_id, state)| {+ **state == PinnedParticipationState::Active && !covered.contains(cohort_id)+ })+ .map(|(cohort_id, _)| *cohort_id)+ .collect::<Vec<_>>();+ uncovered.sort_unstable();+ uncovered+ }+fn into_filters(self) -> TeamFilters {self.filters}@@ -714,6 +738,8 @@ mod tests {let validated = PinnedRun::validate(snapshot(payload.clone(), participations)).unwrap();assert_eq!(validated.run.conditions.len(), 1);assert_eq!(validated.run.conditions[0].cohort_id, CohortId(1));+ // A superseded participation expects no coverage, so it never withholds the proof.+ assert!(validated.uncovered_cohorts.is_empty());assert_eq!(validated.run.event_names.as_slice(), &["active-event"]);assert!(validated.run@@ -743,6 +769,52 @@ mod tests {assert!(matches!(unknown, Err(PinnedError::MissingParticipation(2))));}+ #[test]+ fn an_active_cohort_whose_only_condition_is_dropped_is_reported_uncovered() {+ let covered_hash = "covered000000000";+ let action_hash = "action0000000000";+ let covered_filters = json!({+ "properties": { "type": "AND", "values": [{+ "type": "behavioral",+ "value": "performed_event",+ "key": "covered-event",+ "conditionHash": covered_hash,+ "time_value": 7,+ "time_interval": "day",+ "bytecode": bytecode("covered-event"),+ }]}+ });+ let mut covered_condition =+ condition(1, covered_hash, "performed_event", Some("covered-event"), 7);+ covered_condition["time_value"] = json!(7);+ covered_condition["time_interval"] = json!("day");+ let payload = json!({+ "schema_version": 1,+ "conditions": [+ covered_condition,+ condition(2, action_hash, "performed_event", None, 7),+ ],+ "event_names": ["covered-event"],+ });+ let participations = vec![+ PinnedParticipation {+ cohort_id: CohortId(1),+ pinned_filters: covered_filters,+ state: PinnedParticipationState::Active,+ },+ PinnedParticipation {+ cohort_id: CohortId(2),+ pinned_filters: json!({ "properties": { "type": "AND", "values": [] } }),+ state: PinnedParticipationState::Active,+ },+ ];++ let validated = PinnedRun::validate(snapshot(payload, participations)).unwrap();+ // Cohort 1's surviving condition would satisfy a run-wide check while cohort 2 gets nothing.+ assert_eq!(validated.run.conditions.len(), 1);+ assert_eq!(validated.uncovered_cohorts, vec![CohortId(2)]);+ }+#[test]fn lenient_serde_coerces_mistyped_scalars_to_none_without_failing_validation() {let hash = "lenient000000000";diff --git a/rust/cohort-seeder/src/kafka/producer.rs b/rust/cohort-seeder/src/kafka/producer.rsindex a4f112e15d5d..e6a3a90dccf9 100644--- a/rust/cohort-seeder/src/kafka/producer.rs+++ b/rust/cohort-seeder/src/kafka/producer.rs@@ -4,8 +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 std::time::{Duration, Instant};use common_kafka::config::KafkaConfig;use common_kafka::kafka_producer::{create_kafka_producer, KafkaContext};@@ -13,79 +12,9 @@ use common_liveness::SyncLivenessReporter;use rdkafka::error::{KafkaError, RDKafkaErrorCode};use rdkafka::producer::{DeliveryFuture, FutureProducer, FutureRecord, Producer};-use crate::domain::{ReconcileTile, SeedTile};+use crate::domain::{MembershipPartition, NextOffset, ReconcileTile, SeedTile, WatchPositions};-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),-}+pub use crate::domain::partition::{SeedPartition, SeedPartitionCountError, SeedPartitions};#[derive(Debug, thiserror::Error)]pub enum EnqueueError {@@ -184,6 +113,100 @@ impl SeedTileProducer {pub fn flush(&self, timeout: Duration) -> Result<(), KafkaError> {self.producer.flush(timeout)}++ /// Capture the membership topic's per-partition high watermarks as the marker watcher's start+ /// positions. The high watermark is the offset the next record *will* receive, so it is exactly+ /// the first offset the watcher must read — no clock or "latest committed" assumption. Callers+ /// capture these BEFORE producing reconcile tiles: markers acked after this point sit at or above+ /// these positions, so the watcher started here cannot miss a marker of this dispatch. A manual+ /// disaster-recovery fallback could instead resolve positions via `offsets_for_times`; that is+ /// intentionally not implemented here. Blocking — call via `spawn_blocking` from async contexts.+ ///+ /// `budget` bounds the whole capture, not each call: watermarks come one partition at a time, so+ /// a per-call timeout would let a degraded broker hold the thread for `partitions × timeout`.+ pub fn capture_topic_offsets(+ &self,+ topic: &str,+ budget: Duration,+ ) -> Result<WatchPositions, CaptureOffsetsError> {+ let deadline = Instant::now() + budget;+ let remaining = |deadline: Instant| {+ deadline+ .checked_duration_since(Instant::now())+ .filter(|left| !left.is_zero())+ .ok_or_else(|| CaptureOffsetsError::BudgetExhausted {+ topic: topic.to_string(),+ budget,+ })+ };+ let client = self.producer.client();+ let metadata = client+ .fetch_metadata(Some(topic), remaining(deadline)?)+ .map_err(CaptureOffsetsError::Metadata)?;+ let topic_metadata = metadata+ .topics()+ .iter()+ .find(|entry| entry.name() == topic)+ .ok_or_else(|| CaptureOffsetsError::Missing {+ topic: topic.to_string(),+ })?;+ if let Some(error) = topic_metadata.error() {+ return Err(CaptureOffsetsError::Topic {+ topic: topic.to_string(),+ code: error.into(),+ });+ }+ if topic_metadata.partitions().is_empty() {+ // An empty position set would be vacuously "caught up", minting a settlement proof over+ // nothing. Refuse it at the source, the way `verify_partition_count` refuses a+ // mis-provisioned seed topic.+ return Err(CaptureOffsetsError::NoPartitions {+ topic: topic.to_string(),+ });+ }+ let mut positions = WatchPositions::new();+ for partition in topic_metadata.partitions() {+ let (_low, high) = client+ .fetch_watermarks(topic, partition.id(), remaining(deadline)?)+ .map_err(|source| CaptureOffsetsError::Watermarks {+ topic: topic.to_string(),+ partition: partition.id(),+ source,+ })?;+ positions.insert(+ MembershipPartition::new(partition.id()),+ NextOffset::from_high_watermark(high),+ );+ }+ Ok(positions)+ }+}++/// Why capturing the membership topic's start positions failed. The dispatch cannot record a+/// resumable watch state without them, so every variant aborts the dispatch (it re-converges on the+/// next tick).+#[derive(Debug, thiserror::Error)]+pub enum CaptureOffsetsError {+ #[error("fetching membership topic metadata")]+ Metadata(#[source] KafkaError),+ #[error("membership topic {topic:?} is not present in broker metadata")]+ Missing { topic: String },+ #[error("membership topic {topic:?} metadata reports {code}")]+ Topic {+ topic: String,+ code: RDKafkaErrorCode,+ },+ #[error("membership topic {topic:?} reports no partitions")]+ NoPartitions { topic: String },+ #[error("capturing membership topic {topic:?} offsets exceeded its {budget:?} budget")]+ BudgetExhausted { topic: String, budget: Duration },+ #[error("fetching watermarks for membership topic {topic:?} partition {partition}")]+ Watermarks {+ topic: String,+ partition: i32,+ #[source]+ source: KafkaError,+ },}/// Why the seed topic failed its startup partition-count verification. Every variant is fatal:@@ -235,32 +258,6 @@ mod tests {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(diff --git a/rust/cohort-seeder/src/main.rs b/rust/cohort-seeder/src/main.rsindex 5c4bdc8535a4..a73a0532cabf 100644--- a/rust/cohort-seeder/src/main.rs+++ b/rust/cohort-seeder/src/main.rs@@ -2,6 +2,7 @@//! the `lifecycle::Manager`. Depends on `app`, `clickhouse`, `kafka`, `config`, and `observability` —//! the composition root at the top of the stack.+use std::num::NonZeroUsize;use std::time::Duration;use anyhow::{Context, Result};@@ -15,7 +16,8 @@ use tracing_subscriber::util::SubscriberInitExt;use tracing_subscriber::{fmt, EnvFilter, Layer};use cohort_seeder::app::{- OrchestratorSettings, SeederOrchestrator, ORCHESTRATOR_LIVENESS_DEADLINE,+ AutoDispatchPolicy, CompletionDriver, OrchestratorSettings, SeederOrchestrator,+ ORCHESTRATOR_LIVENESS_DEADLINE,};use cohort_seeder::clickhouse::client::build_client;use cohort_seeder::clickhouse::scanner::ChunkScanner;@@ -86,6 +88,9 @@ async fn async_main(config: Config) -> Result<()> {);let settings =OrchestratorSettings::try_from(&config).context("validating orchestrator settings")?;+ let completion_driver = build_completion_driver(&config, &pool, &producer)+ .await+ .context("validating auto reconcile dispatch policy")?;let claimed_by = format!("cohort-seeder:{}", uuid::Uuid::now_v7());let orchestrator = SeederOrchestrator::new(pool,@@ -96,6 +101,7 @@ async fn async_main(config: Config) -> Result<()> {settings,seeder_handle,claimed_by,+ completion_driver,);let guard = manager.monitor_background();@@ -118,6 +124,45 @@ async fn async_main(config: Config) -> Result<()> {Ok(())}+/// Build the reconcile-dispatch driver when the policy is armed; `None` leaves the dark path with no+/// extra queries. A misconfigured policy (enabled without attestation, or a non-contract partition+/// count) is a startup error, as is an unreachable membership topic — a typo'd name would otherwise+/// surface only as runs stuck re-dispatching forever.+async fn build_completion_driver(+ config: &Config,+ pool: &sqlx::PgPool,+ producer: &SeedTileProducer,+) -> Result<Option<CompletionDriver>> {+ match AutoDispatchPolicy::from_config(config)? {+ AutoDispatchPolicy::Disabled => Ok(None),+ AutoDispatchPolicy::Enabled(register_backfill) => {+ let max_inflight = NonZeroUsize::new(config.seeder_max_inflight_tiles)+ .context("SEEDER_MAX_INFLIGHT_TILES must be greater than zero")?;+ let max_concurrent_dispatches = NonZeroUsize::new(+ config.seeder_reconcile_max_concurrent_dispatches,+ )+ .context("SEEDER_RECONCILE_MAX_CONCURRENT_DISPATCHES must be greater than zero")?;+ let verify_producer = producer.clone();+ let membership_topic = config.cohort_membership_changed_topic.clone();+ tokio::task::spawn_blocking(move || {+ verify_producer.capture_topic_offsets(&membership_topic, PARTITION_VERIFY_TIMEOUT)+ })+ .await+ .context("joining membership topic verification task")?+ .context("verifying the membership topic is reachable")?;+ Ok(Some(CompletionDriver::new(+ pool.clone(),+ producer.clone(),+ config.team_allowlist.clone(),+ config.cohort_membership_changed_topic.clone(),+ max_inflight,+ max_concurrent_dispatches,+ register_backfill,+ )))+ }+ }+}+fn log_startup(config: &Config) {info!(service = SERVICE_NAME,@@ -131,6 +176,10 @@ fn log_startup(config: &Config) {bands_per_day = config.seeder_bands_per_day,tiles_per_second = config.seeder_tiles_per_sec,max_inflight_tiles = config.seeder_max_inflight_tiles,+ reconcile_auto_dispatch_enabled = config.seeder_reconcile_auto_dispatch_enabled,+ confirm_register_backfilled = config.seeder_confirm_register_backfilled,+ reconcile_max_concurrent_dispatches = config.seeder_reconcile_max_concurrent_dispatches,+ membership_topic = %config.cohort_membership_changed_topic,"starting cohort-seeder",);}diff --git a/rust/cohort-seeder/src/observability/metrics.rs b/rust/cohort-seeder/src/observability/metrics.rsindex f058f90279d3..56fd19b2585e 100644--- a/rust/cohort-seeder/src/observability/metrics.rs+++ b/rust/cohort-seeder/src/observability/metrics.rs@@ -34,6 +34,13 @@ pub const LEASE_LOST: &str = "seeder_lease_lost_total";pub const RUN_CHUNKS_REMAINING: &str = "seeder_run_chunks_remaining";pub const RUNS_WITHOUT_CHUNKS: &str = "seeder_runs_without_chunks";pub const WINDOW_DAYS_MISMATCH: &str = "seeder_window_days_mismatch_total";+pub const RUNS_PLANNING_STAMPED: &str = "seeder_runs_planning_stamped_total";+pub const RUNS_PLANNING_WITHHELD: &str = "seeder_runs_planning_withheld_total";+pub const RECONCILE_DISPATCHES: &str = "seeder_reconcile_dispatches_total";+pub const RECONCILE_CAS_LOST: &str = "seeder_reconcile_cas_lost_total";+pub const RECONCILE_RECORD_INVALID: &str = "seeder_reconcile_record_invalid_total";+pub const RECONCILE_DISPATCHES_IN_FLIGHT: &str = "seeder_reconcile_dispatches_in_flight";+pub const RUNS_RECONCILING: &str = "seeder_runs_reconciling";pub fn install_recorder() -> Result<PrometheusHandle, BuildError> {PrometheusBuilder::new().install_recorder()diff --git a/rust/cohort-seeder/src/store/chunks.rs b/rust/cohort-seeder/src/store/chunks.rsindex e35e62b45903..77fa5d79795c 100644--- a/rust/cohort-seeder/src/store/chunks.rs+++ b/rust/cohort-seeder/src/store/chunks.rs@@ -67,9 +67,13 @@ impl PgChunkStore {let result = sqlx::query_as::<_, PlanRow>(r#"WITH target_run AS (+ -- Serializes against the completion CAS: an unlocked `seeding` read is evaluated+ -- against this statement's snapshot, so a run could reach `reconciling` carrying+ -- freshly inserted pending chunks and certify completion on unseeded days.SELECT id, team_idFROM cohort_backfill_runsWHERE id = $1 AND status = 'seeding'+ FOR UPDATE), input AS (SELECT * FROM unnest($2::uuid[], $3::date[], $4::smallint[]) AS u(id, day, band)), inserted AS (diff --git a/rust/cohort-seeder/src/store/completion.rs b/rust/cohort-seeder/src/store/completion.rsnew file mode 100644index 000000000000..799e5dc04f12--- /dev/null+++ b/rust/cohort-seeder/src/store/completion.rs@@ -0,0 +1,888 @@+//! The backfill-completion protocol's PostgreSQL access: the planning-proof stamp, the+//! `seeding → reconciling` CAS, the atomic dispatch record, and the epoch-fenced observation writes+//! the later observer (PR-C) will drive. `sqlx` stays confined here; everything above receives typed+//! rows, typed capabilities, and typed errors. Depends on `domain` and the sibling store helpers.+//!+//! Every observation write carries the dispatch fence `AND reconcile_dispatched_at = $epoch AND+//! status = 'reconciling'`. A miss returns [`CompletionStoreError::CompletionFenceLost`], mirroring+//! the chunk store's `LeaseLost`: a stale writer (an older dispatch superseded by a re-dispatch, or a+//! run Django has already moved on) can never clobber the ruling dispatch's state.++use chrono::{DateTime, Utc};+use cohort_core::filters::{CohortId, TeamId};+use common_types::cohort::TeamAllowlist;+use serde_json::Value;+use sqlx::types::Json;+use sqlx::{FromRow, PgPool};+use std::collections::{HashMap, HashSet};+use std::fmt;++use crate::domain::{+ BehavioralShapeHash, BehavioralShapeHashError, CompletionParts, CompletionPhase,+ CompletionStatus, DispatchEpoch, MarkerWatch, PartitionBitmap, PartitionBitmapError,+ ReconcileHwms, RunId, WatchPositions, MARKER_WATCH_SCHEMA,+};++use super::{RenderedError, PERSISTED_ERROR_LIMIT};++/// The completion columns the two discovery SELECTs share, kept in a macro so both queries stay+/// byte-identical and the composed SQL is a compile-time constant (mirrors `runs::run_columns!`).+macro_rules! completion_columns {+ () => {+ "id, team_id, status, chunks_planned_at, reconcile_dispatched_at, reconcile_observed_at, \+ reconcile_hwms, marker_watch"+ };+}++// Status vocabulary the composed SQL names, kept in macros so the queries stay compile-time+// constants while a unit test can still scan them against the status enums — the same drift guard+// `chunks.rs` applies to its `IN` fragments.+macro_rules! seeding_status {+ () => {+ "'seeding'"+ };+}+macro_rules! reconciling_status {+ () => {+ "'reconciling'"+ };+}+macro_rules! confirmed_chunk_status {+ () => {+ "'confirmed'"+ };+}++const DISCOVER_COMPLETION_ALL: &str = concat!(+ "\n SELECT ",+ completion_columns!(),+ "\n FROM cohort_backfill_runs",+ "\n WHERE status IN (",+ seeding_status!(),+ ", ",+ reconciling_status!(),+ ")",+ "\n AND backfill_kind = 'behavioral'",+ "\n ORDER BY created_at\n"+);++const DISCOVER_COMPLETION_ONLY: &str = concat!(+ "\n SELECT ",+ completion_columns!(),+ "\n FROM cohort_backfill_runs",+ "\n WHERE status IN (",+ seeding_status!(),+ ", ",+ reconciling_status!(),+ ")",+ "\n AND backfill_kind = 'behavioral'",+ "\n AND team_id = ANY($1)",+ "\n ORDER BY created_at\n"+);++const CAS_RUN_RECONCILING: &str = concat!(+ "\n UPDATE cohort_backfill_runs",+ "\n SET status = ",+ reconciling_status!(),+ ", updated_at = now()",+ "\n WHERE id = $1 AND backfill_kind = 'behavioral' AND status = ",+ seeding_status!(),+ " AND chunks_planned_at IS NOT NULL",+ "\n AND NOT EXISTS (",+ "\n SELECT 1 FROM cohort_backfill_chunks",+ "\n WHERE run_id = $1 AND status <> ",+ confirmed_chunk_status!(),+ "\n )",+ "\n RETURNING id, reconcile_dispatched_at\n"+);++const RUNS_WITH_ALL_CHUNKS_CONFIRMED: &str = concat!(+ "\n SELECT candidate.run_id",+ "\n FROM unnest($1::uuid[]) AS candidate(run_id)",+ "\n WHERE NOT EXISTS (",+ "\n SELECT 1 FROM cohort_backfill_chunks",+ "\n WHERE run_id = candidate.run_id AND status <> ",+ confirmed_chunk_status!(),+ "\n )\n"+);++/// Which fenced write lost its dispatch epoch. Carried on [`CompletionStoreError::CompletionFenceLost`]+/// so operators can see where a stale observation was rejected.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum CompletionOperation {+ RecordDispatch,+ PersistWatch,+ PersistObservations,+ MarkCompleted,+ RecordPartial,+ RecordShortfall,+ MarkObserved,+ MarkObservedUnreconcilable,+}++impl fmt::Display for CompletionOperation {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter.write_str(match self {+ Self::RecordDispatch => "record-dispatch",+ Self::PersistWatch => "persist-watch",+ Self::PersistObservations => "persist-observations",+ Self::MarkCompleted => "mark-completed",+ Self::RecordPartial => "record-partial",+ Self::RecordShortfall => "record-shortfall",+ Self::MarkObserved => "mark-observed",+ Self::MarkObservedUnreconcilable => "mark-observed-unreconcilable",+ })+ }+}++#[derive(Debug, thiserror::Error)]+pub enum CompletionStoreError {+ #[error("PostgreSQL completion operation failed")]+ Pg(#[from] sqlx::Error),+ #[error("run {run_id:?} lost its dispatch fence during {operation}")]+ CompletionFenceLost {+ run_id: RunId,+ operation: CompletionOperation,+ },+ #[error("run {run_id:?} cohort {cohort_id:?} has out-of-range reconcile marker bits")]+ InvalidMarkerBits {+ run_id: RunId,+ cohort_id: CohortId,+ #[source]+ source: PartitionBitmapError,+ },+ #[error("run {run_id:?} cohort {cohort_id:?} has an invalid pinned behavioral shape hash")]+ InvalidBehavioralShapeHash {+ run_id: RunId,+ cohort_id: CohortId,+ #[source]+ source: BehavioralShapeHashError,+ },+}++/// Whether the planning-proof stamp was applied by this call or was already present.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum PlanningStampOutcome {+ Stamped,+ Skipped,+}++/// A run proven to hold `reconciling` status, minted only by the CAS out of `seeding`+/// ([`cas_run_reconciling`]) or by re-confirming an already-reconciling run ([`confirm_reconciling`]).+/// It is linear: [`ReconcilingClaim::record`] persists the dispatch or [`ReconcilingClaim::revert`]+/// releases it back to `seeding`, and either consumes the claim so a dispatch can never be recorded+/// twice off one CAS. Both minting queries filter `backfill_kind`, so a claim also proves the run+/// belongs to this protocol.+#[must_use]+#[derive(Debug)]+pub struct ReconcilingClaim {+ run_id: RunId,+ /// `reconcile_dispatched_at` as of the mint; `None` for a never-dispatched run.+ dispatched_at_mint: Option<DateTime<Utc>>,+}++impl ReconcilingClaim {+ pub const fn run_id(&self) -> RunId {+ self.run_id+ }++ /// Roll the run back to `seeding` after a post-CAS `Incomplete` (a `bands_per_day` raise that+ /// added chunks between the CAS proving zero remaining and the dispatch). Any dispatch record is+ /// cleared with the status: a re-dispatch of a run with an unparseable record can land here, and+ /// leaving the columns behind would strand the run as a seeding-with-reconcile-columns anomaly.+ ///+ /// Fenced on the epoch observed at mint: `confirm_reconciling` is not exclusive, so without it a+ /// losing replica's revert would wipe a winner's just-recorded dispatch. Best-effort otherwise —+ /// a run that already left `reconciling` simply matches nothing.+ pub async fn revert(self, pool: &PgPool) -> Result<(), CompletionStoreError> {+ sqlx::query(+ r#"+ UPDATE cohort_backfill_runs+ SET status = 'seeding', reconcile_dispatched_at = NULL, reconcile_observed_at = NULL,+ reconcile_hwms = NULL, marker_watch = NULL, updated_at = now()+ WHERE id = $1 AND status = 'reconciling'+ AND reconcile_dispatched_at IS NOT DISTINCT FROM $2+ "#,+ )+ .bind(self.run_id)+ .bind(self.dispatched_at_mint)+ .execute(pool)+ .await?;+ Ok(())+ }++ /// Atomically write the dispatch record per INV-3: set `reconcile_hwms`, `marker_watch`, a fresh+ /// `reconcile_dispatched_at` fence, null `reconcile_observed_at`, and reset every non-superseded+ /// participation's bits/completion/error. Returns the fence epoch minted from the RETURNING+ /// timestamp.+ ///+ /// Fenced on the mint epoch like [`ReconcilingClaim::revert`]: the reset discards marker bits and+ /// completions, so a second claimant committing after the first would silently undo observations+ /// already merged under the ruling epoch. The loser gets `CompletionFenceLost`, which the driver+ /// counts and retries. A run Django moved out of `reconciling` loses the fence the same way.+ pub async fn record(+ self,+ pool: &PgPool,+ hwms: &ReconcileHwms,+ watch: &MarkerWatch,+ ) -> Result<DispatchEpoch, CompletionStoreError> {+ let run_id = self.run_id;+ let mut tx = pool.begin().await?;+ let dispatched_at = sqlx::query_scalar::<_, DateTime<Utc>>(+ r#"+ UPDATE cohort_backfill_runs+ SET reconcile_hwms = $2, marker_watch = $3,+ reconcile_dispatched_at = now(), reconcile_observed_at = NULL, updated_at = now()+ WHERE id = $1 AND status = 'reconciling'+ AND reconcile_dispatched_at IS NOT DISTINCT FROM $4+ RETURNING reconcile_dispatched_at+ "#,+ )+ .bind(run_id)+ .bind(Json(hwms))+ .bind(Json(watch))+ .bind(self.dispatched_at_mint)+ .fetch_optional(&mut *tx)+ .await?+ .ok_or(CompletionStoreError::CompletionFenceLost {+ run_id,+ operation: CompletionOperation::RecordDispatch,+ })?;++ sqlx::query(+ r#"+ UPDATE cohort_backfill_run_cohorts+ SET reconcile_marker_bits = 0, reconcile_completed_at = NULL, error = ''+ WHERE run_id = $1 AND superseded_at IS NULL+ "#,+ )+ .bind(run_id)+ .execute(&mut *tx)+ .await?;++ tx.commit().await?;+ Ok(DispatchEpoch::from_dispatched_at(dispatched_at))+ }+}++/// Stamp the planning proof (`chunks_planned_at`) exactly once for a seeding run — the durable+/// evidence that day-chunk planning ran, which distinguishes a legitimately zero-chunk run from one+/// whose planning has not yet happened. Re-filters `backfill_kind` like every entry point here, so a+/// `person_property` run id handed in by a caller can never enter this protocol.+pub async fn mark_chunks_planned(+ pool: &PgPool,+ run_id: RunId,+) -> Result<PlanningStampOutcome, CompletionStoreError> {+ let stamped = sqlx::query_scalar::<_, RunId>(+ r#"+ UPDATE cohort_backfill_runs+ SET chunks_planned_at = now(), updated_at = now()+ WHERE id = $1 AND backfill_kind = 'behavioral' AND status = 'seeding'+ AND chunks_planned_at IS NULL+ RETURNING id+ "#,+ )+ .bind(run_id)+ .fetch_optional(pool)+ .await?;+ Ok(if stamped.is_some() {+ PlanningStampOutcome::Stamped+ } else {+ PlanningStampOutcome::Skipped+ })+}++/// The planning-proof timestamp, read for the dispatch-completion check. `None` means either the run+/// is absent or planning has not been stamped.+pub async fn read_planning_stamp(+ pool: &PgPool,+ run_id: RunId,+) -> Result<Option<DateTime<Utc>>, CompletionStoreError> {+ let stamp: Option<Option<DateTime<Utc>>> = sqlx::query_scalar(+ "SELECT chunks_planned_at FROM cohort_backfill_runs \+ WHERE id = $1 AND backfill_kind = 'behavioral'",+ )+ .bind(run_id)+ .fetch_optional(pool)+ .await?;+ Ok(stamp.flatten())+}++/// CAS a seeding run into `reconciling`. Admits the transition only once planning is proven and every+/// chunk has confirmed, freezing the chunk ledger (`claim_next`/`heartbeat`/`plan_chunks` all require+/// `seeding`). `None` means the CAS was lost — another dispatcher won, chunks reappeared, or the run+/// left `seeding`.+pub async fn cas_run_reconciling(+ pool: &PgPool,+ run_id: RunId,+) -> Result<Option<ReconcilingClaim>, CompletionStoreError> {+ let claimed = sqlx::query_as::<_, ClaimRow>(CAS_RUN_RECONCILING)+ .bind(run_id)+ .fetch_optional(pool)+ .await?;+ Ok(claimed.map(ClaimRow::into_claim))+}++/// Mint a claim for an already-`reconciling` run so a re-dispatch (self-healing an undispatched or+/// stale record) can rewrite its dispatch state. `None` means the run is no longer `reconciling`.+/// Non-exclusive by design — concurrent claimants are reconciled by INV-3's ruling fence.+pub async fn confirm_reconciling(+ pool: &PgPool,+ run_id: RunId,+) -> Result<Option<ReconcilingClaim>, CompletionStoreError> {+ let claimed = sqlx::query_as::<_, ClaimRow>(+ r#"+ UPDATE cohort_backfill_runs+ SET updated_at = now()+ WHERE id = $1 AND backfill_kind = 'behavioral' AND status = 'reconciling'+ RETURNING id, reconcile_dispatched_at+ "#,+ )+ .bind(run_id)+ .fetch_optional(pool)+ .await?;+ Ok(claimed.map(ClaimRow::into_claim))+}++/// Persist the watcher's resume state (`marker_watch`) under the dispatch fence.+pub async fn persist_marker_watch(+ pool: &PgPool,+ run_id: RunId,+ epoch: DispatchEpoch,+ watch: &MarkerWatch,+) -> Result<(), CompletionStoreError> {+ let updated = sqlx::query_scalar::<_, RunId>(+ r#"+ UPDATE cohort_backfill_runs+ SET marker_watch = $3, updated_at = now()+ WHERE id = $1 AND reconcile_dispatched_at = $2 AND status = 'reconciling'+ RETURNING id+ "#,+ )+ .bind(run_id)+ .bind(epoch.as_datetime())+ .bind(Json(watch))+ .fetch_optional(pool)+ .await?;+ fence(updated, run_id, CompletionOperation::PersistWatch)+}++/// OR-merge observed marker bits into every named cohort and advance the watcher positions, in one+/// fenced transaction. The bit merge is idempotent (`bits | $bits`), so a replayed flush is a no-op.+/// Repeated cohort ids in `bit_updates` are folded with `bit_or` first: `UPDATE ... FROM` applies a+/// single source row per target, so unfolded duplicates would silently drop every bit but one's.+pub async fn persist_marker_observations(+ pool: &PgPool,+ run_id: RunId,+ epoch: DispatchEpoch,+ bit_updates: &[(CohortId, PartitionBitmap)],+ positions: &WatchPositions,+) -> Result<(), CompletionStoreError> {+ let mut tx = pool.begin().await?;+ // The positions write also proves the fence: its RETURNING gates the whole transaction.+ // `jsonb_set(NULL, ...)` is NULL, which would wipe the document instead of advancing it. A NULL+ // `marker_watch` under a live fence is unreachable (`record` writes both atomically), so the+ // coalesce only keeps a hypothetical stray NULL from discarding the positions being flushed.+ let fenced = sqlx::query_scalar::<_, RunId>(+ r#"+ UPDATE cohort_backfill_runs+ SET marker_watch = jsonb_set(+ coalesce(marker_watch, jsonb_build_object('schema', $4::bigint, 'ends', NULL)),+ '{positions}', $3::jsonb, true+ ),+ updated_at = now()+ WHERE id = $1 AND reconcile_dispatched_at = $2 AND status = 'reconciling'+ RETURNING id+ "#,+ )+ .bind(run_id)+ .bind(epoch.as_datetime())+ .bind(Json(positions))+ .bind(i64::from(MARKER_WATCH_SCHEMA))+ .fetch_optional(&mut *tx)+ .await?;+ if fenced.is_none() {+ return Err(CompletionStoreError::CompletionFenceLost {+ run_id,+ operation: CompletionOperation::PersistObservations,+ });+ }++ if !bit_updates.is_empty() {+ let cohort_ids: Vec<i32> = bit_updates.iter().map(|(cohort, _)| cohort.0).collect();+ let bits: Vec<i64> = bit_updates+ .iter()+ .map(|(_, bitmap)| bitmap.as_bits())+ .collect();+ sqlx::query(+ r#"+ UPDATE cohort_backfill_run_cohorts c+ SET reconcile_marker_bits = c.reconcile_marker_bits | u.bits+ FROM (+ SELECT cohort_id, bit_or(bits) AS bits+ FROM unnest($2::int[], $3::bigint[]) AS raw(cohort_id, bits)+ GROUP BY cohort_id+ ) AS u+ WHERE c.run_id = $1 AND c.cohort_id = u.cohort_id AND c.superseded_at IS NULL+ "#,+ )+ .bind(run_id)+ .bind(cohort_ids)+ .bind(bits)+ .execute(&mut *tx)+ .await?;+ }++ tx.commit().await?;+ Ok(())+}++/// Mark one cohort's reconcile complete (64/64 markers). Idempotent via the `IS NULL` guard, and+/// skipped for superseded participations — supersession (INV-2) trumps completion.+pub async fn mark_participation_completed(+ pool: &PgPool,+ run_id: RunId,+ epoch: DispatchEpoch,+ cohort_id: CohortId,+) -> Result<(), CompletionStoreError> {+ let probe = sqlx::query_scalar::<_, bool>(+ r#"+ WITH fence AS (+ SELECT id FROM cohort_backfill_runs+ WHERE id = $1 AND reconcile_dispatched_at = $2 AND status = 'reconciling'+ FOR UPDATE+ ), updated AS (+ UPDATE cohort_backfill_run_cohorts c+ SET reconcile_completed_at = now()+ FROM fence+ WHERE c.run_id = fence.id AND c.cohort_id = $3+ AND c.reconcile_completed_at IS NULL AND c.superseded_at IS NULL+ RETURNING c.id+ )+ SELECT EXISTS(SELECT 1 FROM fence) AS fence_holds+ "#,+ )+ .bind(run_id)+ .bind(epoch.as_datetime())+ .bind(cohort_id.0)+ .fetch_one(pool)+ .await?;+ resolve_fence(probe, run_id, CompletionOperation::MarkCompleted)+}++/// Record a terminal supersede-by-reconcile outcome: markers short and the cohort diverged or was+/// deleted. An already-superseded participation keeps both its timestamp and its error, so a racing+/// edit's supersession — and the reason Django recorded for it — stays authoritative.+pub async fn record_participation_partial(+ pool: &PgPool,+ run_id: RunId,+ epoch: DispatchEpoch,+ cohort_id: CohortId,+ error: &RenderedError,+) -> Result<(), CompletionStoreError> {+ let probe = sqlx::query_scalar::<_, bool>(+ r#"+ WITH fence AS (+ SELECT id FROM cohort_backfill_runs+ WHERE id = $1 AND reconcile_dispatched_at = $2 AND status = 'reconciling'+ FOR UPDATE+ ), updated AS (+ UPDATE cohort_backfill_run_cohorts c+ SET superseded_at = COALESCE(c.superseded_at, now()),+ error = CASE WHEN c.superseded_at IS NULL THEN left($4, $5) ELSE c.error END+ FROM fence+ WHERE c.run_id = fence.id AND c.cohort_id = $3+ RETURNING c.id+ )+ SELECT EXISTS(SELECT 1 FROM fence) AS fence_holds+ "#,+ )+ .bind(run_id)+ .bind(epoch.as_datetime())+ .bind(cohort_id.0)+ .bind(error.as_str())+ .bind(PERSISTED_ERROR_LIMIT)+ .fetch_one(pool)+ .await?;+ resolve_fence(probe, run_id, CompletionOperation::RecordPartial)+}++/// Record a retryable shortfall: markers short but the hash still matches (a partially-gated fleet,+/// marker loss, allowlist shrink). Error only — `superseded_at` stays NULL so the run is+/// re-dispatchable.+pub async fn record_participation_shortfall(+ pool: &PgPool,+ run_id: RunId,+ epoch: DispatchEpoch,+ cohort_id: CohortId,+ error: &RenderedError,+) -> Result<(), CompletionStoreError> {+ let probe = sqlx::query_scalar::<_, bool>(+ r#"+ WITH fence AS (+ SELECT id FROM cohort_backfill_runs+ WHERE id = $1 AND reconcile_dispatched_at = $2 AND status = 'reconciling'+ FOR UPDATE+ ), updated AS (+ UPDATE cohort_backfill_run_cohorts c+ SET error = left($4, $5)+ FROM fence+ WHERE c.run_id = fence.id AND c.cohort_id = $3 AND c.superseded_at IS NULL+ RETURNING c.id+ )+ SELECT EXISTS(SELECT 1 FROM fence) AS fence_holds+ "#,+ )+ .bind(run_id)+ .bind(epoch.as_datetime())+ .bind(cohort_id.0)+ .bind(error.as_str())+ .bind(PERSISTED_ERROR_LIMIT)+ .fetch_one(pool)+ .await?;+ resolve_fence(probe, run_id, CompletionOperation::RecordShortfall)+}++/// Stamp `reconcile_observed_at` — the seeder's last write per dispatch cycle (INV-1). Every+/// participation outcome is written before this, so Django never sees an observed run with an+/// undecided participation.+pub async fn mark_run_observed(+ pool: &PgPool,+ run_id: RunId,+ epoch: DispatchEpoch,+) -> Result<(), CompletionStoreError> {+ let updated = sqlx::query_scalar::<_, RunId>(+ r#"+ UPDATE cohort_backfill_runs+ SET reconcile_observed_at = now(), updated_at = now()+ WHERE id = $1 AND reconcile_dispatched_at = $2 AND status = 'reconciling'+ RETURNING id+ "#,+ )+ .bind(run_id)+ .bind(epoch.as_datetime())+ .fetch_optional(pool)+ .await?;+ fence(updated, run_id, CompletionOperation::MarkObserved)+}++/// Stamp `reconcile_observed_at` for a reconciling run that has nothing left to reconcile: every+/// participation was superseded while it was seeding, so INV-1's "outcomes before observed" holds+/// vacuously and there is no dispatch to fence against. Without this the run would classify as+/// `ReconcilingUndispatched` on every tick forever — Django's finalizer only discovers runs that+/// carry `reconcile_observed_at`, and it terminalizes an all-superseded run as `superseded` (INV-5+/// keeps that transition Django's). The `NOT EXISTS` guard is the fence: a run with an active+/// participation is never shortcut this way.+pub async fn mark_run_observed_unreconcilable(+ pool: &PgPool,+ run_id: RunId,+) -> Result<(), CompletionStoreError> {+ let updated = sqlx::query_scalar::<_, RunId>(+ r#"+ UPDATE cohort_backfill_runs+ SET reconcile_observed_at = now(), updated_at = now()+ WHERE id = $1 AND backfill_kind = 'behavioral' AND status = 'reconciling'+ AND NOT EXISTS (+ SELECT 1 FROM cohort_backfill_run_cohorts+ WHERE run_id = $1 AND superseded_at IS NULL+ )+ RETURNING id+ "#,+ )+ .bind(run_id)+ .fetch_optional(pool)+ .await?;+ fence(+ updated,+ run_id,+ CompletionOperation::MarkObservedUnreconcilable,+ )+}++/// One participation's observation state, seeding PR-C's per-run ledger and outcome fold.+#[derive(Debug, Clone)]+pub struct ObservationParticipation {+ pub cohort_id: CohortId,+ pub behavioral_filters_shape_hash: BehavioralShapeHash,+ pub bits: PartitionBitmap,+ pub reconcile_completed_at: Option<DateTime<Utc>>,+ pub superseded_at: Option<DateTime<Utc>>,+ pub stamped_at: Option<DateTime<Utc>>,+}++/// Load every participation's observation state for a run (superseded rows included, so the caller+/// can honor INV-2).+pub async fn load_observation_participations(+ pool: &PgPool,+ run_id: RunId,+) -> Result<Vec<ObservationParticipation>, CompletionStoreError> {+ let rows = sqlx::query_as::<_, ObservationParticipationRow>(+ r#"+ SELECT cohort_id, behavioral_filters_shape_hash, reconcile_marker_bits,+ reconcile_completed_at, superseded_at, stamped_at+ FROM cohort_backfill_run_cohorts+ WHERE run_id = $1+ ORDER BY cohort_id+ "#,+ )+ .bind(run_id)+ .fetch_all(pool)+ .await?;++ let mut participations = Vec::with_capacity(rows.len());+ for row in rows {+ let cohort_id = CohortId(row.cohort_id);+ let bits = PartitionBitmap::from_bits(row.reconcile_marker_bits).map_err(|source| {+ CompletionStoreError::InvalidMarkerBits {+ run_id,+ cohort_id,+ source,+ }+ })?;+ let behavioral_filters_shape_hash =+ BehavioralShapeHash::parse(&row.behavioral_filters_shape_hash).map_err(|source| {+ CompletionStoreError::InvalidBehavioralShapeHash {+ run_id,+ cohort_id,+ source,+ }+ })?;+ participations.push(ObservationParticipation {+ cohort_id,+ behavioral_filters_shape_hash,+ bits,+ reconcile_completed_at: row.reconcile_completed_at,+ superseded_at: row.superseded_at,+ stamped_at: row.stamped_at,+ });+ }+ Ok(participations)+}++/// The cohort's current behavioral shape, read from `posthog_cohort` for INV-1 hash attribution. An+/// absent row is treated as `Deleted`; a NULL or unparseable hash is `Indeterminate` (the caller+/// treats it as diverged).+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum CurrentBehavioralHash {+ Present(BehavioralShapeHash),+ Deleted,+ Indeterminate,+}++/// Read the current behavioral shape hash for each requested cohort. Cohorts with no row are absent+/// from the map, which the caller reads as [`CurrentBehavioralHash::Deleted`].+pub async fn load_current_behavioral_hashes(+ pool: &PgPool,+ team_id: TeamId,+ cohort_ids: &[CohortId],+) -> Result<HashMap<CohortId, CurrentBehavioralHash>, CompletionStoreError> {+ if cohort_ids.is_empty() {+ return Ok(HashMap::new());+ }+ let ids: Vec<i32> = cohort_ids.iter().map(|cohort| cohort.0).collect();+ let rows = sqlx::query_as::<_, CurrentCohortRow>(+ r#"+ SELECT id, behavioral_filters_shape_hash, deleted+ FROM posthog_cohort+ WHERE team_id = $1 AND id = ANY($2)+ "#,+ )+ .bind(team_id.0)+ .bind(ids)+ .fetch_all(pool)+ .await?;++ let mut current = HashMap::with_capacity(rows.len());+ for row in rows {+ let state = if row.deleted {+ CurrentBehavioralHash::Deleted+ } else {+ match row.behavioral_filters_shape_hash {+ Some(hash) => match BehavioralShapeHash::parse(&hash) {+ Ok(hash) => CurrentBehavioralHash::Present(hash),+ Err(_) => CurrentBehavioralHash::Indeterminate,+ },+ None => CurrentBehavioralHash::Indeterminate,+ }+ };+ current.insert(CohortId(row.id), state);+ }+ Ok(current)+}++/// Which of the candidate runs have a fully confirmed chunk ledger, in one round trip. The driver+/// ticks inside the orchestrator's poll arm ahead of its liveness heartbeat, so a per-run round trip+/// would scale one tick's cost with the seeding backlog.+pub async fn runs_with_all_chunks_confirmed(+ pool: &PgPool,+ run_ids: &[RunId],+) -> Result<HashSet<RunId>, CompletionStoreError> {+ if run_ids.is_empty() {+ return Ok(HashSet::new());+ }+ let ids = run_ids.iter().map(|run_id| run_id.0).collect::<Vec<_>>();+ let confirmed = sqlx::query_scalar::<_, RunId>(RUNS_WITH_ALL_CHUNKS_CONFIRMED)+ .bind(ids)+ .fetch_all(pool)+ .await?;+ Ok(confirmed.into_iter().collect())+}++/// A run discovered by the completion driver, already classified into its [`CompletionPhase`].+#[derive(Debug, Clone)]+pub struct DiscoveredCompletion {+ pub run_id: RunId,+ pub team_id: TeamId,+ pub phase: CompletionPhase,+}++/// Discover every seeding/reconciling behavioral run and classify each. Rows whose status is not one+/// of the two the query selects are skipped defensively.+pub async fn discover_completions(+ pool: &PgPool,+ allowlist: &TeamAllowlist,+) -> Result<Vec<DiscoveredCompletion>, CompletionStoreError> {+ let rows = match allowlist {+ TeamAllowlist::All => {+ sqlx::query_as::<_, CompletionRunRow>(DISCOVER_COMPLETION_ALL)+ .fetch_all(pool)+ .await?+ }+ TeamAllowlist::Only(team_ids) => {+ let mut team_ids = team_ids.iter().copied().collect::<Vec<_>>();+ team_ids.sort_unstable();+ sqlx::query_as::<_, CompletionRunRow>(DISCOVER_COMPLETION_ONLY)+ .bind(team_ids)+ .fetch_all(pool)+ .await?+ }+ };+ Ok(rows.into_iter().filter_map(classify_row).collect())+}++fn classify_row(row: CompletionRunRow) -> Option<DiscoveredCompletion> {+ let status = match row.status.as_str() {+ "seeding" => CompletionStatus::Seeding,+ "reconciling" => CompletionStatus::Reconciling,+ _ => return None,+ };+ let phase = CompletionPhase::from_parts(CompletionParts {+ status,+ chunks_planned_at: row.chunks_planned_at,+ reconcile_dispatched_at: row.reconcile_dispatched_at,+ reconcile_observed_at: row.reconcile_observed_at,+ reconcile_hwms: row.reconcile_hwms.map(|json| json.0),+ marker_watch: row.marker_watch.map(|json| json.0),+ });+ Some(DiscoveredCompletion {+ run_id: row.id,+ team_id: TeamId(row.team_id),+ phase,+ })+}++fn fence(+ updated: Option<RunId>,+ run_id: RunId,+ operation: CompletionOperation,+) -> Result<(), CompletionStoreError> {+ updated+ .map(|_| ())+ .ok_or(CompletionStoreError::CompletionFenceLost { run_id, operation })+}++/// A fenced participation write probes only whether the run fence held: the data-modifying `updated`+/// CTE executes exactly once whether or not the outer query reads it, and a held fence whose guarded+/// UPDATE touched no row is a legitimate no-op (already completed, already superseded). Only a broken+/// fence is an error.+///+/// The fence CTE takes `FOR UPDATE` on the run row. Without it, under READ COMMITTED, the fence would+/// be evaluated against the statement's own snapshot: a concurrent [`ReconcilingClaim::record`] could+/// commit a re-dispatch after the fence read passed, the participation UPDATE would unblock, and+/// EvalPlanQual would re-check only the participation row's quals — landing a superseded epoch's+/// write inside the new epoch's regime while reporting success. Locking the run row makes the+/// re-check cover the epoch itself, so a stale write always surfaces as `CompletionFenceLost`.+fn resolve_fence(+ fence_holds: bool,+ run_id: RunId,+ operation: CompletionOperation,+) -> Result<(), CompletionStoreError> {+ if fence_holds {+ Ok(())+ } else {+ Err(CompletionStoreError::CompletionFenceLost { run_id, operation })+ }+}++#[derive(Debug, FromRow)]+struct ClaimRow {+ id: RunId,+ reconcile_dispatched_at: Option<DateTime<Utc>>,+}++impl ClaimRow {+ fn into_claim(self) -> ReconcilingClaim {+ ReconcilingClaim {+ run_id: self.id,+ dispatched_at_mint: self.reconcile_dispatched_at,+ }+ }+}++#[derive(Debug, FromRow)]+struct CompletionRunRow {+ id: RunId,+ team_id: i32,+ status: String,+ chunks_planned_at: Option<DateTime<Utc>>,+ reconcile_dispatched_at: Option<DateTime<Utc>>,+ reconcile_observed_at: Option<DateTime<Utc>>,+ reconcile_hwms: Option<Json<Value>>,+ marker_watch: Option<Json<Value>>,+}++#[derive(Debug, FromRow)]+struct ObservationParticipationRow {+ cohort_id: i32,+ behavioral_filters_shape_hash: String,+ reconcile_marker_bits: i64,+ reconcile_completed_at: Option<DateTime<Utc>>,+ superseded_at: Option<DateTime<Utc>>,+ stamped_at: Option<DateTime<Utc>>,+}++#[derive(Debug, FromRow)]+struct CurrentCohortRow {+ id: i32,+ behavioral_filters_shape_hash: Option<String>,+ deleted: bool,+}++#[cfg(test)]+mod tests {+ use crate::domain::ChunkStatus;+ use crate::store::runs::RunStatus;++ use super::*;++ #[test]+ fn hoisted_status_fragments_only_name_live_statuses() {+ for status in [seeding_status!(), reconciling_status!()] {+ assert!(+ status.trim_matches('\'').parse::<RunStatus>().is_ok(),+ "SQL fragment names non-vocabulary run status {status:?}"+ );+ }+ assert!(+ confirmed_chunk_status!()+ .trim_matches('\'')+ .parse::<ChunkStatus>()+ .is_ok(),+ "SQL fragment names a non-vocabulary chunk status"+ );+ // The composed queries must actually be built from the scanned fragments.+ assert!(CAS_RUN_RECONCILING.contains(confirmed_chunk_status!()));+ assert!(RUNS_WITH_ALL_CHUNKS_CONFIRMED.contains(confirmed_chunk_status!()));+ assert!(DISCOVER_COMPLETION_ALL.contains(seeding_status!()));+ }+}diff --git a/rust/cohort-seeder/src/store/mod.rs b/rust/cohort-seeder/src/store/mod.rsindex 4b2b1e6c6f58..6e53bd935661 100644--- a/rust/cohort-seeder/src/store/mod.rs+++ b/rust/cohort-seeder/src/store/mod.rs@@ -5,6 +5,7 @@//! rows) and the `observability` metric constants — nothing else in the crate.pub mod chunks;+pub mod completion;pub mod lease;pub mod runs;diff --git a/rust/cohort-seeder/src/test_support.rs b/rust/cohort-seeder/src/test_support.rsindex 825f9e582f90..c56b9b055cd8 100644--- a/rust/cohort-seeder/src/test_support.rs+++ b/rust/cohort-seeder/src/test_support.rs@@ -2,7 +2,12 @@//! the store's lease-fenced SQL directly by [`ChunkLease`] so the integration test can exercise the//! epoch fence in isolation. Not compiled into the shipping binary.-use crate::domain::{ChunkLease, ChunkSpec, ClaimedChunk, ProduceHwms, ScannedChunk, SeedTile};+use chrono::{DateTime, Utc};+use sqlx::PgPool;++use crate::domain::{+ ChunkLease, ChunkSpec, ClaimedChunk, DispatchEpoch, ProduceHwms, RunId, ScannedChunk, SeedTile,+};use crate::store::chunks::{ChunkStoreError, PgChunkStore};use crate::store::{Claimant, LeaseDuration, RenderedError};@@ -50,3 +55,21 @@ pub async fn fail(pub async fn unclaim(store: &PgChunkStore, lease: ChunkLease) -> Result<(), ChunkStoreError> {store.unclaim(lease).await}++/// Read a run's current dispatch fence epoch. Integration tests cannot mint a [`DispatchEpoch`]+/// (its constructor is `pub(crate)`), so this feature-gated hook hands them the live one.+pub async fn dispatch_epoch(pool: &PgPool, run_id: RunId) -> Result<DispatchEpoch, sqlx::Error> {+ let at: DateTime<Utc> = sqlx::query_scalar(+ "SELECT reconcile_dispatched_at FROM cohort_backfill_runs WHERE id = $1",+ )+ .bind(run_id)+ .fetch_one(pool)+ .await?;+ Ok(DispatchEpoch::from_dispatched_at(at))+}++/// Mint an arbitrary dispatch epoch from a timestamp — the way a test constructs a deliberately+/// stale fence value.+pub fn epoch_at(at: DateTime<Utc>) -> DispatchEpoch {+ DispatchEpoch::from_dispatched_at(at)+}diff --git a/rust/cohort-seeder/tests/fixtures/cohort_backfill_0004.sql b/rust/cohort-seeder/tests/fixtures/cohort_backfill_0007.sqlsimilarity index 70%rename from rust/cohort-seeder/tests/fixtures/cohort_backfill_0004.sqlrename to rust/cohort-seeder/tests/fixtures/cohort_backfill_0007.sqlindex afe3e3f5110f..284e4a179433 100644--- a/rust/cohort-seeder/tests/fixtures/cohort_backfill_0004.sql+++ b/rust/cohort-seeder/tests/fixtures/cohort_backfill_0007.sql@@ -1,5 +1,6 @@--- Snapshot pinned to products/cohorts/backend/migrations/0004_cohort_backfill_tables.py.--- External Team/Cohort foreign keys are omitted so the contract test stays schema-local.+-- Snapshot pinned to products/cohorts/backend/migrations/0007_cohortbackfillrun_cohort_bfr_reconciling_idx.py+-- (the 0004 DDL, the six columns 0006 adds, and the partial index 0007 adds). External Team/Cohort+-- foreign keys are omitted so the contract test stays schema-local.CREATE TABLE cohort_backfill_runs (id uuid PRIMARY KEY,@@ -21,11 +22,19 @@ CREATE TABLE cohort_backfill_runs (finished_at timestamptz,cohort_id integer,superseded_by_id uuid REFERENCES cohort_backfill_runs(id),- team_id integer NOT NULL+ team_id integer NOT NULL,+ -- 0006 completion columns.+ chunks_planned_at timestamptz,+ reconcile_dispatched_at timestamptz,+ reconcile_observed_at timestamptz,+ marker_watch jsonb);CREATE INDEX cohort_bfr_team_status_idx ON cohort_backfill_runs(team_id, status);CREATE INDEX cohort_bfr_team_created_idx ON cohort_backfill_runs(team_id, created_at DESC);+CREATE INDEX cohort_bfr_reconciling_idx+ ON cohort_backfill_runs(backfill_kind, reconcile_observed_at)+ WHERE status = 'reconciling';CREATE UNIQUE INDEX cohort_bfr_active_cohort_uqON cohort_backfill_runs(cohort_id)WHERE cohort_id IS NOT NULL@@ -70,5 +79,18 @@ CREATE TABLE cohort_backfill_run_cohorts (cohort_id integer NOT NULL,run_id uuid NOT NULL REFERENCES cohort_backfill_runs(id),team_id integer NOT NULL,+ -- 0006 completion columns.+ reconcile_completed_at timestamptz,+ reconcile_marker_bits bigint NOT NULL DEFAULT 0,CONSTRAINT cohort_bfrc_run_cohort_uq UNIQUE (run_id, cohort_id));++-- A minimal projection of posthog_cohort, present only so load_current_behavioral_hashes can read a+-- cohort's current behavioral shape hash for INV-1 hash attribution. Not part of the cohorts app's+-- backfill migrations.+CREATE TABLE posthog_cohort (+ id integer PRIMARY KEY,+ team_id integer NOT NULL,+ behavioral_filters_shape_hash varchar(64),+ deleted boolean NOT NULL DEFAULT false+);diff --git a/rust/cohort-seeder/tests/pg_chunks.rs b/rust/cohort-seeder/tests/pg_chunks.rsindex ed677d16e374..010ec65b238e 100644--- a/rust/cohort-seeder/tests/pg_chunks.rs+++ b/rust/cohort-seeder/tests/pg_chunks.rs@@ -337,6 +337,8 @@ async fn reconcile_run_load_is_fail_closed_and_behavioral_hash_scoped() -> Resul.await?;let register_backfill = RegisterBackfillConfirmation::confirmed_by_operator();+ // A seeding run that never planned has no completion proof, so a complete dispatch fails+ // closed (the CLI must use --allow-incomplete for an unplanned run).ensure!(matches!(prepare_reconcile_dispatch(&pool,@@ -345,7 +347,7 @@ async fn reconcile_run_load_is_fail_closed_and_behavioral_hash_scoped() -> Resulregister_backfill,).await,- Err(PrepareReconcileDispatchError::EmptyChunkLedger(id)) if id == run_id+ Err(PrepareReconcileDispatchError::PlanningUnproven(id)) if id == run_id));let overridden = prepare_reconcile_dispatch(&pool,@@ -375,6 +377,22 @@ async fn reconcile_run_load_is_fail_closed_and_behavioral_hash_scoped() -> Resul.execute(&pool).await?;ensure!(load_reconcile_run(&pool, run_id).await?.status() == RunStatus::Reconciling);+ // Reaching `reconciling` is not itself a planning proof — only the stamp is.+ ensure!(matches!(+ prepare_reconcile_dispatch(+ &pool,+ run_id,+ CompletionRequirement::Complete,+ register_backfill,+ )+ .await,+ Err(PrepareReconcileDispatchError::PlanningUnproven(id)) if id == run_id+ ));++ sqlx::query("UPDATE cohort_backfill_runs SET chunks_planned_at = now() WHERE id = $1")+ .bind(run_id)+ .execute(&pool)+ .await?;ensure!(prepare_reconcile_dispatch(&pool,run_id,diff --git a/rust/cohort-seeder/tests/pg_completion.rs b/rust/cohort-seeder/tests/pg_completion.rsnew file mode 100644index 000000000000..cbb2c4f7bda2--- /dev/null+++ b/rust/cohort-seeder/tests/pg_completion.rs@@ -0,0 +1,715 @@+//! PostgreSQL contract for the backfill-completion protocol, split into independent scenarios.+//!+//! Each `#[tokio::test]` connects its own schema-scoped database ([`support::with_db`]) and builds+//! only the minimal run/participation state its invariant needs. Together they pin the planning-proof+//! stamp, the `seeding → reconciling` CAS, the atomic dispatch record and reset, the epoch fence on+//! every observation write, the bitmap OR-merge, phase discovery, and the current-hash read.++#![cfg(feature = "pg-test-support")]++use std::collections::BTreeMap;+use std::num::NonZeroU16;+use std::time::Duration;++use anyhow::{ensure, Context, Result};+use chrono::{DateTime, Duration as ChronoDuration, Utc};+use cohort_core::filters::{CohortId, TeamId};+use cohort_core::partitioner::COHORT_PARTITION_COUNT;+use cohort_seeder::domain::{+ CompletionPhase, DispatchEpoch, MarkerPartition, MarkerWatch, PartitionBitmap, ProducedOffset,+ ReconcileHwms, RunId, SeedPartition, UndispatchedReason, WatchPositions,+};+use cohort_seeder::store::chunks::PgChunkStore;+use cohort_seeder::store::completion::{+ cas_run_reconciling, confirm_reconciling, discover_completions, load_current_behavioral_hashes,+ load_observation_participations, mark_chunks_planned, mark_participation_completed,+ mark_run_observed, mark_run_observed_unreconcilable, persist_marker_observations,+ persist_marker_watch, record_participation_partial, record_participation_shortfall,+ runs_with_all_chunks_confirmed, CompletionStoreError, CurrentBehavioralHash,+ PlanningStampOutcome,+};+use cohort_seeder::store::RenderedError;+use cohort_seeder::test_support;+use common_types::cohort::TeamAllowlist;+use sqlx::PgPool;++mod support;+use support::{+ empty_pinned, ensure_fence_lost, insert_cohort, insert_participation, insert_reconciling_run,+ insert_run, set_marker_bits, with_db,+};++const ONE_BAND: NonZeroU16 = NonZeroU16::MIN;++fn full_hwms() -> ReconcileHwms {+ let offsets: BTreeMap<SeedPartition, ProducedOffset> =+ SeedPartition::all(COHORT_PARTITION_COUNT)+ .unwrap()+ .map(|partition| {+ (+ partition,+ ProducedOffset::new(1_000 + i64::from(partition.as_u16())),+ )+ })+ .collect();+ ReconcileHwms::new(offsets).unwrap()+}++fn empty_watch() -> MarkerWatch {+ MarkerWatch {+ positions: WatchPositions::new(),+ ends: None,+ }+}++/// Stamping the planning proof applies once, is idempotent, and refuses a run that is not seeding.+#[tokio::test]+async fn planning_stamp_is_idempotent_and_refuses_non_seeding() -> Result<()> {+ with_db(|pool| async move {+ let seeding =+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;+ ensure!(matches!(+ mark_chunks_planned(&pool, seeding).await?,+ PlanningStampOutcome::Stamped+ ));+ ensure!(matches!(+ mark_chunks_planned(&pool, seeding).await?,+ PlanningStampOutcome::Skipped+ ));++ let reconciling = insert_reconciling_run(&pool, 3).await?;+ ensure!(matches!(+ mark_chunks_planned(&pool, reconciling).await?,+ PlanningStampOutcome::Skipped+ ));+ Ok(())+ })+ .await+}++/// The CAS admits exactly one winner, and refuses a run that has not planned or still has an+/// unconfirmed chunk.+#[tokio::test]+async fn cas_reconciling_is_single_winner_and_gated_on_planned_and_confirmed() -> Result<()> {+ with_db(|pool| async move {+ // Planned, no chunks: two racing CAS attempts, exactly one wins.+ let ready =+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;+ mark_chunks_planned(&pool, ready).await?;+ let (left, right) = tokio::join!(+ cas_run_reconciling(&pool, ready),+ cas_run_reconciling(&pool, ready)+ );+ let winners = [left?, right?].into_iter().filter(Option::is_some).count();+ ensure!(+ winners == 1,+ "expected exactly one CAS winner, got {winners}"+ );++ // Unplanned seeding run: CAS refused.+ let unplanned =+ insert_run(&pool, 3, "team_enablement", "seeding", true, empty_pinned()).await?;+ ensure!(cas_run_reconciling(&pool, unplanned).await?.is_none());++ // Planned but with an unconfirmed chunk: CAS refused.+ let pending =+ insert_run(&pool, 4, "team_enablement", "seeding", true, empty_pinned()).await?;+ mark_chunks_planned(&pool, pending).await?;+ PgChunkStore::new(pool.clone())+ .plan_chunks(pending, [100], ONE_BAND)+ .await?;+ ensure!(cas_run_reconciling(&pool, pending).await?.is_none());+ Ok(())+ })+ .await+}++/// Recording a dispatch writes the HWMs and watch, resets every non-superseded participation's+/// bits/completion/error, nulls the observed stamp, and mints the fence epoch; a re-dispatch stamps a+/// fresh epoch and resets again.+#[tokio::test]+async fn record_dispatch_resets_participations_and_mints_fresh_epoch() -> Result<()> {+ with_db(|pool| async move {+ let run_id = insert_reconciling_run(&pool, 2).await?;+ insert_participation(&pool, run_id, 2, 301, false, empty_pinned()).await?;+ set_marker_bits(&pool, run_id, 301, 7).await?;+ sqlx::query(+ "UPDATE cohort_backfill_run_cohorts SET reconcile_completed_at = now(), error = 'stale' \+ WHERE run_id = $1 AND cohort_id = 301",+ )+ .bind(run_id)+ .execute(&pool)+ .await?;++ let claim = confirm_reconciling(&pool, run_id)+ .await?+ .context("run should be claimable for dispatch")?;+ let epoch = claim.record(&pool, &full_hwms(), &empty_watch()).await?;++ let (bits, completed, error): (i64, Option<chrono::DateTime<chrono::Utc>>, String) =+ sqlx::query_as(+ "SELECT reconcile_marker_bits, reconcile_completed_at, error \+ FROM cohort_backfill_run_cohorts WHERE run_id = $1 AND cohort_id = 301",+ )+ .bind(run_id)+ .fetch_one(&pool)+ .await?;+ ensure!(bits == 0 && completed.is_none() && error.is_empty());++ let (hwms_set, observed): (bool, Option<chrono::DateTime<chrono::Utc>>) = sqlx::query_as(+ "SELECT reconcile_hwms IS NOT NULL, reconcile_observed_at \+ FROM cohort_backfill_runs WHERE id = $1",+ )+ .bind(run_id)+ .fetch_one(&pool)+ .await?;+ ensure!(hwms_set && observed.is_none());+ ensure!(test_support::dispatch_epoch(&pool, run_id).await? == epoch);++ // Re-dispatch: a fresh claim records a new fence at or after the first.+ set_marker_bits(&pool, run_id, 301, 5).await?;+ let claim = confirm_reconciling(&pool, run_id)+ .await?+ .context("re-dispatch should be claimable")?;+ let next_epoch = claim.record(&pool, &full_hwms(), &empty_watch()).await?;+ ensure!(next_epoch.as_datetime() >= epoch.as_datetime());+ ensure!(test_support::dispatch_epoch(&pool, run_id).await? == next_epoch);+ let bits: i64 = sqlx::query_scalar(+ "SELECT reconcile_marker_bits FROM cohort_backfill_run_cohorts \+ WHERE run_id = $1 AND cohort_id = 301",+ )+ .bind(run_id)+ .fetch_one(&pool)+ .await?;+ ensure!(bits == 0);+ Ok(())+ })+ .await+}++/// Reverting a claim returns the run to seeding and clears any dispatch record, so it re-enters+/// discovery as a plain planned seeding run instead of the seeding-with-reconcile-columns anomaly.+#[tokio::test]+async fn revert_clears_the_dispatch_record_and_returns_to_seeding() -> Result<()> {+ with_db(|pool| async move {+ let run_id = insert_reconciling_run(&pool, 2).await?;+ insert_participation(&pool, run_id, 2, 301, false, empty_pinned()).await?;+ let claim = confirm_reconciling(&pool, run_id)+ .await?+ .context("run should be claimable")?;+ let _ = claim.record(&pool, &full_hwms(), &empty_watch()).await?;++ let claim = confirm_reconciling(&pool, run_id)+ .await?+ .context("run should be re-claimable")?;+ claim.revert(&pool).await?;++ let (status, cleared): (String, bool) = sqlx::query_as(+ "SELECT status, reconcile_dispatched_at IS NULL AND reconcile_observed_at IS NULL \+ AND reconcile_hwms IS NULL AND marker_watch IS NULL \+ FROM cohort_backfill_runs WHERE id = $1",+ )+ .bind(run_id)+ .fetch_one(&pool)+ .await?;+ ensure!(status == "seeding" && cleared);++ let discovered = discover_completions(&pool, &TeamAllowlist::All).await?;+ let phase = discovered+ .iter()+ .find(|completion| completion.run_id == run_id)+ .map(|completion| completion.phase.clone());+ ensure!(phase == Some(CompletionPhase::SeedingPlanned));+ Ok(())+ })+ .await+}++/// A claim minted before another dispatcher recorded its dispatch cannot revert it — two replicas+/// can hold a claim for one run, and an unfenced revert would bounce a live dispatch to `seeding`.+#[tokio::test]+async fn revert_is_fenced_against_a_dispatch_recorded_after_the_claim() -> Result<()> {+ with_db(|pool| async move {+ let run_id = insert_reconciling_run(&pool, 2).await?;+ insert_participation(&pool, run_id, 2, 301, false, empty_pinned()).await?;+ let stale = confirm_reconciling(&pool, run_id)+ .await?+ .context("run should be claimable")?;+ let winner = confirm_reconciling(&pool, run_id)+ .await?+ .context("run should be claimable twice")?;+ let epoch = winner.record(&pool, &full_hwms(), &empty_watch()).await?;++ stale.revert(&pool).await?;++ let (status, dispatched_at): (String, Option<DateTime<Utc>>) = sqlx::query_as(+ "SELECT status, reconcile_dispatched_at FROM cohort_backfill_runs WHERE id = $1",+ )+ .bind(run_id)+ .fetch_one(&pool)+ .await?;+ ensure!(status == "reconciling", "revert bounced a live dispatch");+ ensure!(dispatched_at == Some(epoch.as_datetime()));+ mark_run_observed(&pool, run_id, epoch).await?;+ Ok(())+ })+ .await+}++/// A claim that lost the race cannot record over the winner's dispatch. Recording resets marker bits+/// and completions, so an unfenced second write would discard observations already merged under the+/// ruling epoch.+#[tokio::test]+async fn record_is_fenced_against_a_dispatch_recorded_after_the_claim() -> Result<()> {+ with_db(|pool| async move {+ let run_id = insert_reconciling_run(&pool, 2).await?;+ insert_participation(&pool, run_id, 2, 301, false, empty_pinned()).await?;+ let stale = confirm_reconciling(&pool, run_id)+ .await?+ .context("run should be claimable")?;+ let winner = confirm_reconciling(&pool, run_id)+ .await?+ .context("run should be claimable twice")?;+ let epoch = winner.record(&pool, &full_hwms(), &empty_watch()).await?;+ persist_marker_observations(+ &pool,+ run_id,+ epoch,+ &[(CohortId(301), PartitionBitmap::from_bits(3)?)],+ &WatchPositions::new(),+ )+ .await?;++ ensure_fence_lost(+ stale+ .record(&pool, &full_hwms(), &empty_watch())+ .await+ .map(|_| ()),+ )?;++ let bits: i64 = sqlx::query_scalar(+ "SELECT reconcile_marker_bits FROM cohort_backfill_run_cohorts \+ WHERE run_id = $1 AND cohort_id = 301",+ )+ .bind(run_id)+ .fetch_one(&pool)+ .await?;+ ensure!(+ bits == 3,+ "a lost claim reset the ruling epoch's marker bits"+ );+ ensure!(test_support::dispatch_epoch(&pool, run_id).await? == epoch);+ Ok(())+ })+ .await+}++/// The batched ledger check returns exactly the runs whose chunks have all confirmed.+#[tokio::test]+async fn runs_with_all_chunks_confirmed_selects_only_fully_confirmed_ledgers() -> Result<()> {+ with_db(|pool| async move {+ let store = PgChunkStore::new(pool.clone());+ let no_chunks =+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;+ let confirmed =+ insert_run(&pool, 3, "team_enablement", "seeding", true, empty_pinned()).await?;+ store.plan_chunks(confirmed, [100], ONE_BAND).await?;+ sqlx::query("UPDATE cohort_backfill_chunks SET status = 'confirmed' WHERE run_id = $1")+ .bind(confirmed)+ .execute(&pool)+ .await?;+ let pending =+ insert_run(&pool, 4, "team_enablement", "seeding", true, empty_pinned()).await?;+ store.plan_chunks(pending, [100, 101], ONE_BAND).await?;+ sqlx::query(+ "UPDATE cohort_backfill_chunks SET status = 'confirmed' \+ WHERE id = (SELECT id FROM cohort_backfill_chunks WHERE run_id = $1 LIMIT 1)",+ )+ .bind(pending)+ .execute(&pool)+ .await?;++ let ready = runs_with_all_chunks_confirmed(&pool, &[no_chunks, confirmed, pending]).await?;+ ensure!(+ ready == [no_chunks, confirmed].into_iter().collect(),+ "unexpected ready set: {ready:?}"+ );+ ensure!(runs_with_all_chunks_confirmed(&pool, &[]).await?.is_empty());+ Ok(())+ })+ .await+}++/// A participation Django already superseded keeps the reason Django recorded for it.+#[tokio::test]+async fn recording_a_partial_preserves_an_existing_supersession_reason() -> Result<()> {+ with_db(|pool| async move {+ let run_id = insert_reconciling_run(&pool, 2).await?;+ insert_participation(&pool, run_id, 2, 301, true, empty_pinned()).await?;+ sqlx::query(+ "UPDATE cohort_backfill_run_cohorts SET error = 'Cohort definition changed during backfill' \+ WHERE run_id = $1",+ )+ .bind(run_id)+ .execute(&pool)+ .await?;+ let claim = confirm_reconciling(&pool, run_id)+ .await?+ .context("run should be claimable")?;+ let epoch = claim.record(&pool, &full_hwms(), &empty_watch()).await?;++ record_participation_partial(+ &pool,+ run_id,+ epoch,+ CohortId(301),+ &RenderedError::from_message("markers short; cohort diverged"),+ )+ .await?;++ let error: String = sqlx::query_scalar(+ "SELECT error FROM cohort_backfill_run_cohorts WHERE run_id = $1 AND cohort_id = 301",+ )+ .bind(run_id)+ .fetch_one(&pool)+ .await?;+ ensure!(+ error == "Cohort definition changed during backfill",+ "reconcile outcome overwrote the original supersession reason: {error}"+ );+ Ok(())+ })+ .await+}++/// Every fenced observation write is rejected under a stale epoch and under a run whose status has+/// left `reconciling`, while a matching epoch on a reconciling run is accepted.+#[tokio::test]+async fn fenced_writes_reject_stale_epoch_and_wrong_status() -> Result<()> {+ with_db(|pool| async move {+ let run_id = insert_reconciling_run(&pool, 2).await?;+ insert_participation(&pool, run_id, 2, 301, false, empty_pinned()).await?;+ let claim = confirm_reconciling(&pool, run_id)+ .await?+ .context("run should be claimable")?;+ let epoch = claim.record(&pool, &full_hwms(), &empty_watch()).await?;++ // A matching epoch on a reconciling run is accepted.+ mark_participation_completed(&pool, run_id, epoch, CohortId(301)).await?;++ let stale = test_support::epoch_at(epoch.as_datetime() - ChronoDuration::hours(1));+ let bit_updates = [(CohortId(301), PartitionBitmap::default())];+ let error = RenderedError::from_message("shortfall");+ for at in [stale, epoch] {+ if at == epoch {+ // Same valid epoch, but flip the run out of reconciling: the status guard fences.+ sqlx::query("UPDATE cohort_backfill_runs SET status = 'completed' WHERE id = $1")+ .bind(run_id)+ .execute(&pool)+ .await?;+ }+ ensure_fence_lost(persist_marker_watch(&pool, run_id, at, &empty_watch()).await)?;+ ensure_fence_lost(+ persist_marker_observations(+ &pool,+ run_id,+ at,+ &bit_updates,+ &WatchPositions::new(),+ )+ .await,+ )?;+ ensure_fence_lost(+ mark_participation_completed(&pool, run_id, at, CohortId(301)).await,+ )?;+ ensure_fence_lost(+ record_participation_partial(&pool, run_id, at, CohortId(301), &error).await,+ )?;+ ensure_fence_lost(+ record_participation_shortfall(&pool, run_id, at, CohortId(301), &error).await,+ )?;+ ensure_fence_lost(mark_run_observed(&pool, run_id, at).await)?;+ }+ Ok(())+ })+ .await+}++/// A participation write whose epoch is superseded *while the statement runs* must still lose the+/// fence. The three participation writes fence through a CTE rather than a run-row UPDATE, so+/// without `FOR UPDATE` the CTE would be evaluated against the pre-block snapshot (epoch still+/// current), the participation UPDATE would unblock after the re-dispatch committed, and+/// EvalPlanQual — which re-checks only the participation row's quals — would land the stale write+/// inside the new epoch's regime while reporting success.+#[tokio::test]+async fn fenced_participation_writes_lose_an_epoch_superseded_mid_statement() -> Result<()> {+ with_db(|pool| async move {+ let run_id = insert_reconciling_run(&pool, 2).await?;+ insert_participation(&pool, run_id, 2, 301, false, empty_pinned()).await?;+ let claim = confirm_reconciling(&pool, run_id)+ .await?+ .context("run should be claimable")?;+ let _initial = claim.record(&pool, &full_hwms(), &empty_watch()).await?;++ for write in [+ FencedWrite::Completed,+ FencedWrite::Partial,+ FencedWrite::Shortfall,+ ] {+ let current: DateTime<Utc> = sqlx::query_scalar(+ "SELECT reconcile_dispatched_at FROM cohort_backfill_runs WHERE id = $1",+ )+ .bind(run_id)+ .fetch_one(&pool)+ .await?;+ let epoch = test_support::epoch_at(current);++ // A re-dispatch that has stamped the new epoch but not yet committed. Only the run row+ // is touched, so nothing but the fence itself can block the write under test.+ let mut redispatch = pool.begin().await?;+ sqlx::query(+ "UPDATE cohort_backfill_runs \+ SET reconcile_dispatched_at = reconcile_dispatched_at + interval '1 second' \+ WHERE id = $1",+ )+ .bind(run_id)+ .execute(&mut *redispatch)+ .await?;++ let mut pending = tokio::spawn(fenced_write(pool.clone(), run_id, epoch, write));+ // The fence must hold the run row's lock, so the write cannot resolve while the+ // re-dispatch transaction is open. An unfenced read would return `Ok` immediately here.+ let early = tokio::time::timeout(Duration::from_millis(500), &mut pending).await;+ ensure!(+ early.is_err(),+ "{write:?} resolved past an in-flight re-dispatch instead of blocking on the fence"+ );++ redispatch.commit().await?;+ ensure_fence_lost(pending.await?)?;+ }++ let completed: Option<DateTime<Utc>> = sqlx::query_scalar(+ "SELECT reconcile_completed_at FROM cohort_backfill_run_cohorts \+ WHERE run_id = $1 AND cohort_id = 301",+ )+ .bind(run_id)+ .fetch_one(&pool)+ .await?;+ ensure!(+ completed.is_none(),+ "a stale-epoch write landed inside the ruling epoch"+ );+ Ok(())+ })+ .await+}++#[derive(Debug, Clone, Copy)]+enum FencedWrite {+ Completed,+ Partial,+ Shortfall,+}++async fn fenced_write(+ pool: PgPool,+ run_id: RunId,+ epoch: DispatchEpoch,+ write: FencedWrite,+) -> std::result::Result<(), CompletionStoreError> {+ let error = RenderedError::from_message("stale-epoch write");+ let cohort_id = CohortId(301);+ match write {+ FencedWrite::Completed => {+ mark_participation_completed(&pool, run_id, epoch, cohort_id).await+ }+ FencedWrite::Partial => {+ record_participation_partial(&pool, run_id, epoch, cohort_id, &error).await+ }+ FencedWrite::Shortfall => {+ record_participation_shortfall(&pool, run_id, epoch, cohort_id, &error).await+ }+ }+}++/// A reconciling run whose every participation was superseded has nothing to dispatch and no outcome+/// to write, so the seeder stamps the observation itself and hands the run to Django's finalizer.+/// The guard refuses to shortcut a run that still has an active participation.+#[tokio::test]+async fn unreconcilable_runs_are_marked_observed_for_django() -> Result<()> {+ with_db(|pool| async move {+ let stranded = insert_reconciling_run(&pool, 2).await?;+ insert_participation(&pool, stranded, 2, 301, true, empty_pinned()).await?;+ mark_run_observed_unreconcilable(&pool, stranded).await?;++ let discovered = discover_completions(&pool, &TeamAllowlist::All).await?;+ let phase = discovered+ .iter()+ .find(|completion| completion.run_id == stranded)+ .map(|completion| completion.phase.clone());+ ensure!(phase == Some(CompletionPhase::Observed));++ let live = insert_reconciling_run(&pool, 3).await?;+ insert_participation(&pool, live, 3, 401, false, empty_pinned()).await?;+ ensure_fence_lost(mark_run_observed_unreconcilable(&pool, live).await)?;+ let observed: Option<DateTime<Utc>> = sqlx::query_scalar(+ "SELECT reconcile_observed_at FROM cohort_backfill_runs WHERE id = $1",+ )+ .bind(live)+ .fetch_one(&pool)+ .await?;+ ensure!(observed.is_none());+ Ok(())+ })+ .await+}++/// The observed-marker OR-merge accumulates across calls and round-trips through PostgreSQL,+/// including the bit-63 case that stores as a negative BIGINT.+#[tokio::test]+async fn marker_observations_or_merge_round_trip_including_bit_63() -> Result<()> {+ with_db(|pool| async move {+ let run_id = insert_reconciling_run(&pool, 2).await?;+ insert_participation(&pool, run_id, 2, 401, false, empty_pinned()).await?;+ let claim = confirm_reconciling(&pool, run_id)+ .await?+ .context("run should be claimable")?;+ let epoch = claim.record(&pool, &full_hwms(), &empty_watch()).await?;++ let mut low = PartitionBitmap::default();+ low.set(MarkerPartition::new(0)?);+ persist_marker_observations(+ &pool,+ run_id,+ epoch,+ &[(CohortId(401), low)],+ &WatchPositions::new(),+ )+ .await?;++ let mut high = PartitionBitmap::default();+ high.set(MarkerPartition::new(63)?);+ persist_marker_observations(+ &pool,+ run_id,+ epoch,+ &[(CohortId(401), high)],+ &WatchPositions::new(),+ )+ .await?;++ let stored: i64 = sqlx::query_scalar(+ "SELECT reconcile_marker_bits FROM cohort_backfill_run_cohorts \+ WHERE run_id = $1 AND cohort_id = 401",+ )+ .bind(run_id)+ .fetch_one(&pool)+ .await?;+ ensure!(stored < 0, "bit 63 must store as a negative BIGINT");++ let participations = load_observation_participations(&pool, run_id).await?;+ let bits = participations+ .iter()+ .find(|participation| participation.cohort_id == CohortId(401))+ .map(|participation| participation.bits)+ .context("cohort 401 not loaded")?;+ let missing = bits.missing();+ ensure!(!missing.contains(&MarkerPartition::new(0)?));+ ensure!(!missing.contains(&MarkerPartition::new(63)?));+ ensure!(missing.contains(&MarkerPartition::new(1)?));+ Ok(())+ })+ .await+}++/// Discovery classifies each completion phase, including a pre-B5 reconciling run whose completion+/// columns are all NULL.+#[tokio::test]+async fn discovery_classifies_each_phase_including_pre_b5_rows() -> Result<()> {+ with_db(|pool| async move {+ let unplanned =+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;++ let planned =+ insert_run(&pool, 3, "team_enablement", "seeding", true, empty_pinned()).await?;+ mark_chunks_planned(&pool, planned).await?;++ let dispatched = insert_reconciling_run(&pool, 4).await?;+ insert_participation(&pool, dispatched, 4, 401, false, empty_pinned()).await?;+ let claim = confirm_reconciling(&pool, dispatched)+ .await?+ .context("dispatched run should be claimable")?;+ let _ = claim.record(&pool, &full_hwms(), &empty_watch()).await?;++ // Pre-B5: reconciling with every new column NULL.+ let pre_b5 = insert_run(+ &pool,+ 5,+ "team_enablement",+ "reconciling",+ true,+ empty_pinned(),+ )+ .await?;++ let observed = insert_reconciling_run(&pool, 6).await?;+ insert_participation(&pool, observed, 6, 601, false, empty_pinned()).await?;+ let claim = confirm_reconciling(&pool, observed)+ .await?+ .context("observed run should be claimable")?;+ let epoch = claim.record(&pool, &full_hwms(), &empty_watch()).await?;+ mark_run_observed(&pool, observed, epoch).await?;++ let discovered = discover_completions(&pool, &TeamAllowlist::All).await?;+ let phase = |run| {+ discovered+ .iter()+ .find(|completion| completion.run_id == run)+ .map(|completion| completion.phase.clone())+ };+ ensure!(phase(unplanned) == Some(CompletionPhase::SeedingUnplanned));+ ensure!(phase(planned) == Some(CompletionPhase::SeedingPlanned));+ ensure!(matches!(+ phase(dispatched),+ Some(CompletionPhase::Reconciling(_))+ ));+ ensure!(+ phase(pre_b5)+ == Some(CompletionPhase::ReconcilingUndispatched(+ UndispatchedReason::NeverDispatched+ ))+ );+ ensure!(phase(observed) == Some(CompletionPhase::Observed));+ Ok(())+ })+ .await+}++/// The current-hash read distinguishes present, deleted, absent, and NULL/unparseable cohorts.+#[tokio::test]+async fn current_behavioral_hashes_read_present_deleted_absent_and_null() -> Result<()> {+ with_db(|pool| async move {+ insert_cohort(&pool, 501, 2, Some("shape-a"), false).await?;+ insert_cohort(&pool, 502, 2, Some("shape-b"), true).await?;+ insert_cohort(&pool, 503, 2, None, false).await?;+ // 504 intentionally absent.++ let hashes = load_current_behavioral_hashes(+ &pool,+ TeamId(2),+ &[CohortId(501), CohortId(502), CohortId(503), CohortId(504)],+ )+ .await?;++ ensure!(matches!(+ hashes.get(&CohortId(501)),+ Some(CurrentBehavioralHash::Present(hash)) if hash.as_str() == "shape-a"+ ));+ ensure!(hashes.get(&CohortId(502)) == Some(&CurrentBehavioralHash::Deleted));+ ensure!(hashes.get(&CohortId(503)) == Some(&CurrentBehavioralHash::Indeterminate));+ ensure!(!hashes.contains_key(&CohortId(504)));+ Ok(())+ })+ .await+}diff --git a/rust/cohort-seeder/tests/support/mod.rs b/rust/cohort-seeder/tests/support/mod.rsindex 880b12c851cf..61e9539ed020 100644--- a/rust/cohort-seeder/tests/support/mod.rs+++ b/rust/cohort-seeder/tests/support/mod.rs@@ -6,6 +6,10 @@//! surface the body's result *after* the schema drop. The `insert_*`/`*_pinned`/`*_condition`///! `behavioral_filter` builders and the `ensure_lease_lost`/`planned_count` helpers are the shared//! fixtures each scenario composes the minimal state it needs from.+//!+//! Each integration test file is its own crate and pulls this in via `mod support;`, so a helper+//! used by only some of them looks "dead" to the others — hence the crate-wide allow below.+#![allow(dead_code)]use std::future::Future;use std::str::FromStr;@@ -13,14 +17,16 @@ use std::str::FromStr;use anyhow::{bail, Context, Result};use cohort_seeder::domain::RunId;use cohort_seeder::store::chunks::{ChunkStoreError, PlanOutcome};+use cohort_seeder::store::completion::CompletionStoreError;use serde_json::{json, Value};use sqlx::postgres::{PgConnectOptions, PgPoolOptions};use sqlx::types::Json;use sqlx::{Connection, PgConnection, PgPool};use uuid::Uuid;-/// The `cohort_backfill_*` DDL, pinned to the Django migration, applied fresh into each test schema.-pub const DDL: &str = include_str!("../fixtures/cohort_backfill_0004.sql");+/// The `cohort_backfill_*` DDL (plus a schema-local `posthog_cohort` projection), pinned to Django+/// migration 0007, applied fresh into each test schema.+pub const DDL: &str = include_str!("../fixtures/cohort_backfill_0007.sql");/// A live cohort condition hash used by the superseded-load fixtures.pub const ACTIVE_HASH: &str = "active0000000000";/// A superseded cohort condition hash used by the superseded-load fixtures.@@ -96,6 +102,77 @@ pub fn ensure_lease_lost(result: std::result::Result<(), ChunkStoreError>) -> Rebail!("expected LeaseLost, got {result:?}")}+/// Assert an epoch-fenced completion op reported [`CompletionStoreError::CompletionFenceLost`].+pub fn ensure_fence_lost(result: std::result::Result<(), CompletionStoreError>) -> Result<()> {+ if matches!(+ result,+ Err(CompletionStoreError::CompletionFenceLost { .. })+ ) {+ return Ok(());+ }+ bail!("expected CompletionFenceLost, got {result:?}")+}++/// Insert a run already in `reconciling` with its planning proof stamped — the state a dispatch+/// operates against.+pub async fn insert_reconciling_run(pool: &PgPool, team_id: i32) -> Result<RunId> {+ let run_id = insert_run(+ pool,+ team_id,+ "team_enablement",+ "reconciling",+ true,+ empty_pinned(),+ )+ .await?;+ sqlx::query("UPDATE cohort_backfill_runs SET chunks_planned_at = now() WHERE id = $1")+ .bind(run_id)+ .execute(pool)+ .await?;+ Ok(run_id)+}++/// Directly set one participation's observed marker bitmap (the raw BIGINT), bypassing the fenced+/// merge, so a scenario can assert a downstream read or reset.+pub async fn set_marker_bits(+ pool: &PgPool,+ run_id: RunId,+ cohort_id: i32,+ bits: i64,+) -> Result<()> {+ sqlx::query(+ "UPDATE cohort_backfill_run_cohorts SET reconcile_marker_bits = $3 \+ WHERE run_id = $1 AND cohort_id = $2",+ )+ .bind(run_id)+ .bind(cohort_id)+ .bind(bits)+ .execute(pool)+ .await?;+ Ok(())+}++/// Insert a row into the schema-local `posthog_cohort` projection for `load_current_behavioral_hashes`.+pub async fn insert_cohort(+ pool: &PgPool,+ id: i32,+ team_id: i32,+ behavioral_hash: Option<&str>,+ deleted: bool,+) -> Result<()> {+ sqlx::query(+ "INSERT INTO posthog_cohort (id, team_id, behavioral_filters_shape_hash, deleted) \+ VALUES ($1, $2, $3, $4)",+ )+ .bind(id)+ .bind(team_id)+ .bind(behavioral_hash)+ .bind(deleted)+ .execute(pool)+ .await?;+ Ok(())+}+/// Unwrap the inserted-chunk count, failing if the run was unexpectedly not seeding.pub fn planned_count(outcome: PlanOutcome) -> Result<u64> {match outcome {