Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(cohorts): seeder reconcile marker watcher and observation pass (#73739)

Matheus Batista7b3c5f1dd719
diff --git a/products/cohorts/backend/backfill/finalize.py b/products/cohorts/backend/backfill/finalize.py
index 5803b1beaa35..037a0380e633 100644
--- a/products/cohorts/backend/backfill/finalize.py
+++ b/products/cohorts/backend/backfill/finalize.py
@@ -1,12 +1,12 @@
"""Terminalizes behavioral backfill runs the Rust seeder has fully observed.
-B5 stamps only ``last_backfill_events_at``; mixed person+behavioral cohorts stay flag-incompatible
-until B7 stamps the person-properties column (intended fail-closed).
+Only ``last_backfill_events_at`` is stamped; mixed person+behavioral cohorts stay flag-incompatible
+until the person-properties column is stamped too (intended fail-closed).
The seeder writes a definitive per-participation outcome (``reconcile_completed_at`` /
``superseded_at`` / retryable ``error``) before it sets ``run.reconcile_observed_at`` as its last
-write (INV-1). This finalizer trusts those columns — never Kafka — and CASes the run out of
-``reconciling`` once every participation has a terminal outcome (INV-5).
+write. This finalizer trusts those columns — never Kafka — and CASes the run out of
+``reconciling`` once every participation has a terminal outcome.
"""
from dataclasses import dataclass
@@ -93,7 +93,7 @@ def finalize_backfill_runs() -> FinalizerPass:
observed = list(
CohortBackfillRun.objects.unscoped()
.filter(
- # B5 stamps only the events column, so never terminalize a person-properties run (B7).
+ # Only the events column is stamped, so never terminalize a person-properties run.
backfill_kind=CohortBackfillKind.BEHAVIORAL,
status=CohortBackfillRunStatus.RECONCILING,
reconcile_observed_at__isnull=False,
@@ -170,7 +170,7 @@ def _finalize_one_run(run_id: UUID, team_id: int, result: FinalizerPass) -> bool
participations=len(participations),
)
for participation in participations:
- # INV-2: supersede trumps completion, so check it first.
+ # Supersede trumps completion, so check it first.
if participation.superseded_at is not None:
superseded += 1
continue
@@ -191,7 +191,7 @@ def _finalize_one_run(run_id: UUID, team_id: int, result: FinalizerPass) -> bool
continue
# No outcome despite reconcile_observed_at being set. An empty error means the seeder
- # violated INV-1 (observed without an outcome); a non-empty error is a legitimate
+ # observed the run without writing an outcome; a non-empty error is a legitimate
# retryable shortfall that simply holds until re-dispatch.
held += 1
if participation.error == "":
diff --git a/products/cohorts/backend/backfill/readiness.py b/products/cohorts/backend/backfill/readiness.py
index 124aa2fe1b22..3eaecc4208d0 100644
--- a/products/cohorts/backend/backfill/readiness.py
+++ b/products/cohorts/backend/backfill/readiness.py
@@ -49,8 +49,8 @@ def stamp_events_readiness(run: CohortBackfillRun, cohort_id: int) -> bool:
A person-property or cohort-reference edit mid-backfill shifts the full hash without touching
events readiness, so keying on the full hash would wrongly supersede a still-valid events backfill.
- This update intentionally bypasses signals. B5 must explicitly invalidate feature-flag and
- behavioral-cohort caches after a successful stamp.
+ This update intentionally bypasses signals. The caller must explicitly invalidate feature-flag
+ and behavioral-cohort caches after a successful stamp.
Call inside a transaction: the cohort stamp and the participation CAS that ratifies it must
commit or roll back together.
@@ -107,7 +107,7 @@ def stamp_events_readiness(run: CohortBackfillRun, cohort_id: int) -> bool:
error = "Cohort definition changed before readiness was stamped"
# ``superseded_at__isnull`` keeps an earlier supersession's timestamp and message rather than
# clobbering them with this later, less specific diagnosis (the Rust side COALESCEs for the
- # same reason). Either way the participation ends up terminal, which is what INV-2 needs.
+ # same reason). Either way the participation ends up terminal.
CohortBackfillRunCohort.objects.for_team(run.team_id).filter(
id=participation.id, superseded_at__isnull=True
).update(superseded_at=Now(), error=error)
diff --git a/products/cohorts/backend/backfill/test/test_finalize.py b/products/cohorts/backend/backfill/test/test_finalize.py
index e0c5a25ee074..6297765a8879 100644
--- a/products/cohorts/backend/backfill/test/test_finalize.py
+++ b/products/cohorts/backend/backfill/test/test_finalize.py
@@ -97,7 +97,7 @@ class TestBackfillFinalizer(BaseTest):
elif outcome == "shortfall":
rows.update(error="markers short, retryable")
elif outcome == "missing_outcome":
- pass # nothing written despite reconcile_observed_at — INV-1 violation
+ pass # nothing written despite reconcile_observed_at
else:
raise ValueError(outcome)
return cohort, participation
@@ -130,8 +130,8 @@ class TestBackfillFinalizer(BaseTest):
("all_superseded", ["superseded", "superseded"], CohortBackfillRunStatus.SUPERSEDED, []),
("superseded_trumps_completed", ["superseded_and_completed"], CohortBackfillRunStatus.SUPERSEDED, []),
("shortfall_holds", ["shortfall"], CohortBackfillRunStatus.RECONCILING, []),
- # No outcome at all despite reconcile_observed_at: an INV-1 violation must hold the run
- # rather than terminalize it on incomplete information.
+ # No outcome at all despite reconcile_observed_at must hold the run rather than
+ # terminalize it on incomplete information.
("missing_outcome_holds", ["missing_outcome"], CohortBackfillRunStatus.RECONCILING, []),
("mixed_held_still_stamps", ["completed", "shortfall"], CohortBackfillRunStatus.RECONCILING, [0]),
]
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 50dc62dc8793..bb2e603bff49 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2265,6 +2265,7 @@ name = "cohort-seeder"
version = "0.1.0"
dependencies = [
"anyhow",
+ "async-trait",
"axum 0.7.9",
"chrono",
"chrono-tz",
@@ -2277,6 +2278,7 @@ dependencies = [
"common-liveness",
"common-types",
"envconfig",
+ "futures",
"governor",
"hyper-rustls 0.27.7",
"hyper-util",
diff --git a/rust/cohort-core/src/seed/mod.rs b/rust/cohort-core/src/seed/mod.rs
index aeab50b6e0e6..51ca40b7a450 100644
--- a/rust/cohort-core/src/seed/mod.rs
+++ b/rust/cohort-core/src/seed/mod.rs
@@ -16,5 +16,7 @@ pub mod tile;
pub use decode::{decode_seed, DecodedSeed};
pub use ids::{ClaimEpoch, ConditionHash, ConditionHashError, RunId, SChunkMs};
-pub use reconcile::{BehavioralShapeHash, BehavioralShapeHashError, ReconcileTile};
+pub use reconcile::{
+ BehavioralShapeHash, BehavioralShapeHashError, ReconcileCompleteMarker, ReconcileTile,
+};
pub use tile::SeedTile;
diff --git a/rust/cohort-core/src/seed/reconcile.rs b/rust/cohort-core/src/seed/reconcile.rs
index 67e6666cd2b5..2bb599e37857 100644
--- a/rust/cohort-core/src/seed/reconcile.rs
+++ b/rust/cohort-core/src/seed/reconcile.rs
@@ -184,6 +184,93 @@ fn deserialize_schema_version<'de, D: Deserializer<'de>>(deserializer: D) -> Res
Ok(value)
}
+pub(super) const RECONCILE_COMPLETE_KIND: &str = "reconcile_complete";
+
+/// A completion certificate emitted after one partition's reconcile snapshot is durable. Produced by
+/// the stream processor onto the membership topic and folded by the seeder's marker watcher, so it
+/// lives here — the shared seed contract — rather than in either crate. Field order is the wire order;
+/// the golden test below pins the exact bytes both ends depend on.
+///
+/// Deliberately carries no dispatch epoch. A marker is a run-scoped durable fact: that partition's
+/// snapshot drained under this run's pinned filters. If a re-dispatch's watcher folds a late marker
+/// from the previous dispatch, it counts toward the same end state the new drain would reach — a run
+/// is only re-dispatched for a *retryable* shortfall, whose hash still matches (a diverged cohort is
+/// superseded and excluded), so both dispatches drain identical filters. Adding an epoch here would
+/// discard that work and buy nothing.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct ReconcileCompleteMarker {
+ #[serde(rename = "type")]
+ kind: ReconcileCompleteKind,
+ team_id: i32,
+ cohort_id: i32,
+ partition: u16,
+ run_id: RunId,
+ /// ClickHouse `DateTime64(6)` wire format.
+ last_updated: String,
+}
+
+impl ReconcileCompleteMarker {
+ pub fn new(
+ team_id: TeamId,
+ cohort_id: CohortId,
+ partition: u16,
+ run_id: RunId,
+ last_updated: String,
+ ) -> Self {
+ Self {
+ kind: ReconcileCompleteKind,
+ team_id: team_id.0,
+ cohort_id: cohort_id.0,
+ partition,
+ run_id,
+ last_updated,
+ }
+ }
+
+ pub const fn team_id(&self) -> TeamId {
+ TeamId(self.team_id)
+ }
+
+ pub const fn cohort_id(&self) -> CohortId {
+ CohortId(self.cohort_id)
+ }
+
+ pub const fn partition(&self) -> u16 {
+ self.partition
+ }
+
+ pub const fn run_id(&self) -> RunId {
+ self.run_id
+ }
+
+ pub fn last_updated(&self) -> &str {
+ &self.last_updated
+ }
+}
+
+/// A zero-sized discriminant proven to be [`RECONCILE_COMPLETE_KIND`] during deserialization.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+struct ReconcileCompleteKind;
+
+impl Serialize for ReconcileCompleteKind {
+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ serializer.serialize_str(RECONCILE_COMPLETE_KIND)
+ }
+}
+
+impl<'de> Deserialize<'de> for ReconcileCompleteKind {
+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let value = String::deserialize(deserializer)?;
+ if value != RECONCILE_COMPLETE_KIND {
+ return Err(DeError::invalid_value(
+ Unexpected::Str(&value),
+ &"marker type \"reconcile_complete\"",
+ ));
+ }
+ Ok(Self)
+ }
+}
+
#[cfg(test)]
mod tests {
use uuid::Uuid;
@@ -255,6 +342,45 @@ mod tests {
}
}
+ #[test]
+ fn reconcile_complete_marker_has_the_exact_wire_contract() {
+ let marker = ReconcileCompleteMarker::new(
+ TeamId(42),
+ CohortId(91204),
+ 7,
+ RunId(Uuid::nil()),
+ "2026-05-26 12:34:56.789123".to_string(),
+ );
+
+ assert_eq!(
+ serde_json::to_string(&marker).unwrap(),
+ r#"{"type":"reconcile_complete","team_id":42,"cohort_id":91204,"partition":7,"run_id":"00000000-0000-0000-0000-000000000000","last_updated":"2026-05-26 12:34:56.789123"}"#,
+ );
+ assert_eq!(
+ serde_json::from_str::<ReconcileCompleteMarker>(
+ &serde_json::to_string(&marker).unwrap()
+ )
+ .unwrap(),
+ marker
+ );
+ }
+
+ #[test]
+ fn reconcile_complete_marker_rejects_another_message_type() {
+ let marker = ReconcileCompleteMarker::new(
+ TeamId(42),
+ CohortId(91204),
+ 7,
+ RunId(Uuid::nil()),
+ "2026-05-26 12:34:56.789123".to_string(),
+ );
+ let payload = serde_json::to_string(&marker)
+ .unwrap()
+ .replace("reconcile_complete", "seed");
+
+ assert!(serde_json::from_str::<ReconcileCompleteMarker>(&payload).is_err());
+ }
+
#[test]
fn behavioral_shape_hash_matches_the_persisted_output_bounds() {
assert_eq!(BehavioralShapeHash::parse(SHA256).unwrap().as_str(), SHA256,);
diff --git a/rust/cohort-seeder/Cargo.toml b/rust/cohort-seeder/Cargo.toml
index 38166981897f..3945551a0bf8 100644
--- a/rust/cohort-seeder/Cargo.toml
+++ b/rust/cohort-seeder/Cargo.toml
@@ -15,6 +15,7 @@ path = "src/bin/reconcile_dispatch.rs"
[dependencies]
anyhow = { workspace = true }
+async-trait = { workspace = true }
axum = { workspace = true }
chrono = { workspace = true }
chrono-tz = { workspace = true }
@@ -27,6 +28,7 @@ common-kafka = { path = "../common/kafka" }
common-liveness = { path = "../common/liveness" }
common-types = { path = "../common/types" }
envconfig = { workspace = true }
+futures = { workspace = true }
governor = { workspace = true }
hyper-rustls = { workspace = true }
# client-legacy: the `clickhouse` crate's `with_http_client` escape hatch only accepts a
diff --git a/rust/cohort-seeder/src/app/completion.rs b/rust/cohort-seeder/src/app/completion.rs
index d1a579010b5b..4ad6a9acef56 100644
--- a/rust/cohort-seeder/src/app/completion.rs
+++ b/rust/cohort-seeder/src/app/completion.rs
@@ -2,50 +2,65 @@
//! 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.
+//! path the CLI uses. Its second, independently gated half publishes the marker-watch directives and
+//! runs the per-run observation pass; either half alone is a valid configuration.
//!
//! 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.
+//! in-flight set dedupes tasks on this replica; the CAS plus the ruling fence (a later `record` sets
+//! the fence, the processor supersedes duplicate tiles) make cross-replica duplicates safe.
+//!
+//! A tick observes many runs, so the lag gauges are published once here from the worst reading of
+//! the tick: they report fleet-wide and clear themselves once nothing lags. The observation pass's
+//! two broker reads are likewise tick-scoped — see [`TickBrokerSnapshot`].
-use std::collections::HashSet;
+use std::collections::hash_map::Entry;
+use std::collections::{HashMap, HashSet};
use std::num::NonZeroUsize;
use std::sync::{Arc, Mutex};
-use std::time::Duration;
+use std::time::{Duration, Instant};
+use async_trait::async_trait;
+use chrono::{DateTime, Utc};
use common_types::cohort::TeamAllowlist;
-use metrics::{counter, gauge};
+use metrics::{counter, gauge, histogram};
use sqlx::PgPool;
-use tokio::sync::Semaphore;
+use tokio::sync::{watch, Semaphore};
use tokio::task::JoinError;
-use tracing::warn;
+use tracing::{info, warn};
use cohort_core::partitioner::COHORT_PARTITION_COUNT;
use crate::config::Config;
use crate::domain::{
- CompletionPhase, DispatchEpoch, MarkerWatch, ProducedOffset, ReconcileHwms, ReconcileHwmsError,
- RunId,
+ CompletionPhase, DispatchEpoch, DispatchedReconcile, MarkerWatch, ObservationEnds,
+ PartitionBitmap, ProducedOffset, ReconcileHwms, ReconcileHwmsError, RunId, SeedGroupCommits,
};
use crate::kafka::producer::{CaptureOffsetsError, SeedTileProducer};
use crate::observability::metrics::{
RECONCILE_CAS_LOST, RECONCILE_DISPATCHES, RECONCILE_DISPATCHES_IN_FLIGHT,
- RECONCILE_RECORD_INVALID, RUNS_RECONCILING,
+ RECONCILE_LIVENESS_LAGGING_PARTITIONS, RECONCILE_MARKER_WATCH_LAG,
+ RECONCILE_OBSERVATION_PASS_SECONDS, RECONCILE_OBSERVATION_STALLED_AGE_SECONDS,
+ RECONCILE_OBSERVE_ERRORS, RECONCILE_RECORD_INVALID, RECONCILE_RUNS_UNDISPATCHED,
+ RECONCILE_ZERO_MARKER_RUNS, RUNS_OBSERVED, RUNS_RECONCILING,
};
use crate::store::completion::{
cas_run_reconciling, confirm_reconciling, discover_completions,
mark_run_observed_unreconcilable, runs_with_all_chunks_confirmed, CompletionStoreError,
- ReconcilingClaim,
+ DiscoveredCompletion, ObservationParticipation, ReconcilingClaim,
};
use crate::store::runs::ReconcileRunError;
+use super::observe::{
+ observe_run, CommittedOffsetSource, ObservationStore, ObserveError, ObserveStep, ObserveTarget,
+ PgObservationStore, SourceError, TopicOffsetSource,
+};
use super::reconcile_dispatch::{
execute_reconcile_dispatch, prepare_reconcile_dispatch, CertifiedDispatch,
CompletionRequirement, PrepareReconcileDispatchError, PreparedDispatch, ReconcileDispatchError,
ReconcileDispatchReceipt, RegisterBackfillConfirmation,
};
+use super::watch::{WatchDirective, WatchDirectives};
/// Timeout for the blocking Kafka metadata and watermark calls the dispatch makes.
const KAFKA_METADATA_TIMEOUT: Duration = Duration::from_secs(10);
@@ -94,6 +109,38 @@ pub enum AutoDispatchPolicyError {
PartitionCountMismatch { configured: u32 },
}
+/// Whether the reconcile observer (marker watcher + observation pass) is armed. A separate gate from
+/// [`AutoDispatchPolicy`]: observation can run against CLI-dispatched runs without auto-dispatch, and
+/// auto-dispatch can run without the observer (a two-step rollout).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ObservePolicy {
+ Disabled,
+ Enabled,
+}
+
+impl ObservePolicy {
+ pub fn from_config(config: &Config) -> Result<Self, ObservePolicyError> {
+ if !config.seeder_reconcile_observer_enabled {
+ return Ok(Self::Disabled);
+ }
+ if config.cohort_partition_count != COHORT_PARTITION_COUNT {
+ return Err(ObservePolicyError::PartitionCountMismatch {
+ configured: config.cohort_partition_count,
+ });
+ }
+ Ok(Self::Enabled)
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+pub enum ObservePolicyError {
+ #[error(
+ "the reconcile observer 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)]
@@ -102,53 +149,100 @@ enum DispatchKind {
ReDispatch,
}
-/// The owned dependencies a dispatch task needs, cheap to clone into a spawned task.
+/// The dispatch half's dependencies, cheap to clone into a spawned dispatch task.
#[derive(Clone)]
-struct DispatchContext {
+struct DispatchArm {
pool: PgPool,
producer: SeedTileProducer,
membership_topic: Arc<str>,
max_inflight: NonZeroUsize,
+ /// Caps how many dispatch tasks this replica runs at once. 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.
+ dispatch_slots: Arc<Semaphore>,
register_backfill: RegisterBackfillConfirmation,
}
+/// The observation half's dependencies: the store seam, the two broker-read seams, and the channel
+/// the driver republishes the watched-run set on each tick.
+struct ObserveArm {
+ store: Arc<dyn ObservationStore>,
+ committed: Arc<dyn CommittedOffsetSource>,
+ topic_ends: Arc<dyn TopicOffsetSource>,
+ directives: watch::Sender<WatchDirectives>,
+}
+
+/// The completion driver, ticked from the orchestrator poll arm. It carries whichever halves are
+/// armed: `dispatch` transitions confirmed runs into `reconciling` and produces reconcile tiles;
+/// `observe` publishes marker-watch directives and runs the observation pass. Either half alone is a
+/// valid configuration — construction requires at least one, encoded as the driver existing at all.
pub struct CompletionDriver {
- context: DispatchContext,
+ pool: PgPool,
allowlist: TeamAllowlist,
+ dispatch: Option<DispatchArm>,
+ observe: Option<ObserveArm>,
in_flight: Arc<Mutex<HashSet<RunId>>>,
- dispatch_slots: Arc<Semaphore>,
+ /// Runs already reported as carrying an unusable dispatch record, mapped to when this replica
+ /// first saw them in that phase, so the warn and counter fire per broken record rather than per
+ /// poll tick and the stalled gauge ages from the phase. Pruned each tick to the runs still in it.
+ reported_undispatched: Mutex<HashMap<RunId, DateTime<Utc>>>,
}
impl CompletionDriver {
- pub fn new(
- pool: PgPool,
+ /// Base driver with neither half armed. `main` adds the halves the config enables.
+ pub fn new(pool: PgPool, allowlist: TeamAllowlist) -> Self {
+ Self {
+ pool,
+ allowlist,
+ dispatch: None,
+ observe: None,
+ in_flight: Arc::new(Mutex::new(HashSet::new())),
+ reported_undispatched: Mutex::new(HashMap::new()),
+ }
+ }
+
+ /// Arm automatic reconcile dispatch.
+ pub fn with_dispatch(
+ mut self,
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())),
+ self.dispatch = Some(DispatchArm {
+ pool: self.pool.clone(),
+ producer,
+ membership_topic: Arc::from(membership_topic),
+ max_inflight,
dispatch_slots: Arc::new(Semaphore::new(max_concurrent_dispatches.get())),
- }
+ register_backfill,
+ });
+ self
}
- /// 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.
+ /// Arm the reconcile observer, publishing directives on `directives` for the marker-watch task.
+ /// The store seam is built over the driver's own pool.
+ pub fn with_observe(
+ mut self,
+ committed: Arc<dyn CommittedOffsetSource>,
+ topic_ends: Arc<dyn TopicOffsetSource>,
+ directives: watch::Sender<WatchDirectives>,
+ ) -> Self {
+ self.observe = Some(ObserveArm {
+ store: Arc::new(PgObservationStore::new(self.pool.clone())),
+ committed,
+ topic_ends,
+ directives,
+ });
+ self
+ }
+
+ /// One driver pass: classify every discovered run, dispatch the ones that need it (dispatch arm),
+ /// and observe the reconciling ones (observe arm). A discovery failure is logged and retried next
+ /// tick; the dark path (driver absent) costs zero queries.
pub async fn tick(&self) {
- let discovered = match discover_completions(&self.context.pool, &self.allowlist).await {
+ let discovered = match discover_completions(&self.pool, &self.allowlist).await {
Ok(discovered) => discovered,
Err(error) => {
warn!(error = %error, "completion discovery failed");
@@ -156,28 +250,105 @@ impl CompletionDriver {
}
};
+ let now = Utc::now();
let mut reconciling = 0_u64;
+ let mut oldest_stalled: Option<DateTime<Utc>> = None;
+ let mut directives = Vec::new();
+ let mut undispatched = HashSet::new();
+ // Collected across the loop and resolved with one batched chunk-ledger read below, so the
+ // pass never issues a query per planned run.
let mut planned = Vec::new();
+ // Worst lag seen this tick, published once below so the gauges read fleet-wide and clear
+ // themselves when nothing is lagging.
+ let mut liveness_lagging = 0_usize;
+ let mut marker_lag = 0_usize;
+ let mut observation_elapsed = Duration::ZERO;
+ let broker = self.observe.as_ref().map(TickBrokerSnapshot::new);
+
for completion in discovered {
- match completion.phase {
- CompletionPhase::Observed | CompletionPhase::Reconciling(_) => {
+ match &completion.phase {
+ CompletionPhase::Observed => {
reconciling += 1;
}
+ CompletionPhase::Reconciling(dispatched) => {
+ reconciling += 1;
+ // Age from the dispatch, not the run's creation: a run that legitimately spent
+ // days seeding would otherwise read as stalled-by-days the instant it dispatches.
+ track_oldest(&mut oldest_stalled, dispatched.epoch.as_datetime());
+ if let (Some(observe), Some(broker)) = (&self.observe, &broker) {
+ let started = Instant::now();
+ // One read per run per tick, shared by the watch directive and the pass.
+ match observe.store.load_participations(completion.run_id).await {
+ Ok(participations) => {
+ directives.push(build_directive(
+ &completion,
+ dispatched,
+ &participations,
+ ));
+ let outcome = self
+ .observe_reconciling(
+ observe,
+ broker,
+ &completion,
+ dispatched,
+ &participations,
+ )
+ .await;
+ liveness_lagging = liveness_lagging.max(outcome.liveness_lagging);
+ marker_lag = marker_lag.max(outcome.marker_lag);
+ }
+ Err(error) => {
+ warn!(error = %error, run_id = ?completion.run_id, "loading participations for the observation pass failed");
+ }
+ }
+ observation_elapsed += started.elapsed();
+ }
+ }
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) {
+ undispatched.insert(completion.run_id);
+ // A run holds this phase until a re-dispatch records — across a whole
+ // observe-only rollout window, if auto-dispatch is off. Count and warn once per
+ // stretch so the signal measures broken dispatch records rather than how many
+ // ticks have looked at the same one.
+ let (first_sighting, since) = {
+ let mut reported = lock_recoverable(&self.reported_undispatched);
+ match reported.entry(completion.run_id) {
+ Entry::Occupied(entry) => (false, *entry.get()),
+ Entry::Vacant(entry) => (true, *entry.insert(now)),
+ }
+ };
+ // Age from the phase, not the run: days of legitimate seeding would otherwise
+ // read as stalled the instant the dispatch record breaks.
+ track_oldest(&mut oldest_stalled, since);
+ if first_sighting {
counter!(RECONCILE_RECORD_INVALID).increment(1);
+ }
+ // Only the dispatch arm can heal an undispatched run; observe-only leaves it for a
+ // CLI re-dispatch.
+ if self.dispatch.is_some() {
+ if first_sighting {
+ warn!(
+ run_id = ?completion.run_id,
+ ?reason,
+ "reconciling run has no usable dispatch record; re-dispatching"
+ );
+ }
+ self.spawn_dispatch(completion.run_id, DispatchKind::ReDispatch);
+ } else if first_sighting {
warn!(
run_id = ?completion.run_id,
?reason,
- "reconciling run has no usable dispatch record; re-dispatching"
+ "reconciling run has no usable dispatch record; re-dispatch required (auto-dispatch off)"
);
}
}
- CompletionPhase::SeedingPlanned => planned.push(completion.run_id),
+ CompletionPhase::SeedingPlanned => {
+ // Only the dispatch arm consumes these, so observe-only skips the batch read.
+ if self.dispatch.is_some() {
+ planned.push(completion.run_id);
+ }
+ }
CompletionPhase::SeedingUnplanned => {}
CompletionPhase::SeedingAnomalous => {
warn!(
@@ -187,36 +358,131 @@ impl CompletionDriver {
}
}
}
+
+ // Forget runs that have left the phase, so a later relapse counts as a fresh event.
+ lock_recoverable(&self.reported_undispatched)
+ .retain(|run_id, _| undispatched.contains(run_id));
+
gauge!(RUNS_RECONCILING).set(reconciling as f64);
+ // A standing count: the first-sighting counter goes flat while runs stay stranded.
+ gauge!(RECONCILE_RUNS_UNDISPATCHED).set(undispatched.len() as f64);
- match runs_with_all_chunks_confirmed(&self.context.pool, &planned).await {
+ match runs_with_all_chunks_confirmed(&self.pool, &planned).await {
Ok(confirmed) => {
for run_id in confirmed {
- let _spawned = self.spawn_dispatch(run_id, DispatchKind::Fresh);
+ self.spawn_dispatch(run_id, DispatchKind::Fresh);
}
}
Err(error) => {
warn!(error = %error, "reading chunk progress for dispatch failed");
}
}
+
+ if let Some(observe) = &self.observe {
+ // send_replace never fails even if the watch task is gone; a dead task is caught by its own
+ // lifecycle deadline.
+ observe
+ .directives
+ .send_replace(WatchDirectives { runs: directives });
+ gauge!(RECONCILE_LIVENESS_LAGGING_PARTITIONS).set(liveness_lagging as f64);
+ gauge!(RECONCILE_MARKER_WATCH_LAG).set(marker_lag as f64);
+ let stalled_age = oldest_stalled
+ .map(|since| (now - since).num_seconds().max(0) as f64)
+ .unwrap_or(0.0);
+ gauge!(RECONCILE_OBSERVATION_STALLED_AGE_SECONDS).set(stalled_age);
+ // The pass runs inline on the orchestrator's liveness path; this leads the deadline.
+ histogram!(RECONCILE_OBSERVATION_PASS_SECONDS)
+ .record(observation_elapsed.as_secs_f64());
+ }
+ }
+
+ /// Run the observation pass for one reconciling run, returning what the tick's aggregate gauges
+ /// need. Per-run counters are emitted here, where the step is known.
+ async fn observe_reconciling(
+ &self,
+ observe: &ObserveArm,
+ broker: &TickBrokerSnapshot<'_>,
+ completion: &DiscoveredCompletion,
+ dispatched: &DispatchedReconcile,
+ participations: &[ObservationParticipation],
+ ) -> ObserveOutcome {
+ let target = ObserveTarget {
+ run_id: completion.run_id,
+ team_id: completion.team_id,
+ epoch: dispatched.epoch,
+ hwms: dispatched.hwms.clone(),
+ watch: dispatched.watch.clone(),
+ };
+ match observe_run(
+ observe.store.as_ref(),
+ broker,
+ broker,
+ &target,
+ participations,
+ )
+ .await
+ {
+ Ok(ObserveStep::Settled(summary)) => {
+ if summary.completed + summary.partial + summary.shortfall > 0
+ || summary.zero_markers
+ {
+ counter!(RUNS_OBSERVED).increment(1);
+ }
+ if summary.zero_markers {
+ // A counter, not a gauge: a settled run is `Observed` on the next tick, so a
+ // fleet-wide gate-off would be a single-tick blip most scrapes would miss.
+ counter!(RECONCILE_ZERO_MARKER_RUNS).increment(1);
+ }
+ ObserveOutcome::default()
+ }
+ Ok(ObserveStep::ObservedAllComplete) => {
+ counter!(RUNS_OBSERVED).increment(1);
+ ObserveOutcome::default()
+ }
+ Ok(ObserveStep::LivenessLagging(partitions)) => ObserveOutcome {
+ liveness_lagging: partitions,
+ ..ObserveOutcome::default()
+ },
+ Ok(ObserveStep::MarkerLagging(lag)) => ObserveOutcome {
+ marker_lag: lag,
+ ..ObserveOutcome::default()
+ },
+ Ok(ObserveStep::EndsCaptured) => ObserveOutcome::default(),
+ Err(ObserveError::Store(CompletionStoreError::CompletionFenceLost {
+ operation,
+ ..
+ })) => {
+ info!(
+ run_id = ?completion.run_id,
+ %operation,
+ "observation lost the dispatch fence; a re-dispatch superseded this pass"
+ );
+ ObserveOutcome::default()
+ }
+ Err(error) => {
+ // The default outcome reads as healthy on both lag gauges, so a failed pass needs
+ // its own signal to tell "nothing is lagging" from "we could not tell".
+ counter!(RECONCILE_OBSERVE_ERRORS).increment(1);
+ warn!(error = %error, run_id = ?completion.run_id, "observing the reconciling run failed");
+ ObserveOutcome::default()
+ }
+ }
}
- /// 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;
+ /// Spawns a dispatch task unless the dispatch arm is disarmed, one is already in flight for this
+ /// run on this replica, or the arm is at its concurrency budget. 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) {
+ let Some(dispatch) = &self.dispatch else {
+ return;
};
- if !lock_in_flight(&self.in_flight).insert(run_id) {
- return false;
+ let Ok(permit) = Arc::clone(&dispatch.dispatch_slots).try_acquire_owned() else {
+ return;
+ };
+ if !lock_recoverable(&self.in_flight).insert(run_id) {
+ return;
}
- let context = self.context.clone();
+ let context = dispatch.clone();
let guard = InFlightGuard::enter(Arc::clone(&self.in_flight), run_id);
let dispatch = tokio::spawn(async move {
let _permit = permit;
@@ -231,7 +497,87 @@ impl CompletionDriver {
warn!(error = %error, run_id = ?run_id, "reconcile dispatch task panicked");
}
});
- true
+ }
+}
+
+/// What one run's observation pass contributed to the tick's aggregate gauges.
+#[derive(Debug, Clone, Copy, Default)]
+struct ObserveOutcome {
+ liveness_lagging: usize,
+ marker_lag: usize,
+}
+
+/// Memoizes the two broker reads for one tick, failures included. Both ask about the cluster, not
+/// about a run, so every run in a tick shares one answer — and the tick runs inside the orchestrator's
+/// liveness budget, where one call per run against a slow broker costs the reconciling-run count
+/// times the offsets timeout.
+struct TickBrokerSnapshot<'a> {
+ committed_source: &'a dyn CommittedOffsetSource,
+ ends_source: &'a dyn TopicOffsetSource,
+ commits: tokio::sync::Mutex<Option<Result<SeedGroupCommits, SourceError>>>,
+ ends: tokio::sync::Mutex<Option<Result<ObservationEnds, SourceError>>>,
+}
+
+impl<'a> TickBrokerSnapshot<'a> {
+ fn new(observe: &'a ObserveArm) -> Self {
+ Self {
+ committed_source: observe.committed.as_ref(),
+ ends_source: observe.topic_ends.as_ref(),
+ commits: tokio::sync::Mutex::new(None),
+ ends: tokio::sync::Mutex::new(None),
+ }
+ }
+}
+
+#[async_trait]
+impl CommittedOffsetSource for TickBrokerSnapshot<'_> {
+ async fn committed(&self) -> Result<SeedGroupCommits, SourceError> {
+ let mut cached = self.commits.lock().await;
+ if cached.is_none() {
+ *cached = Some(self.committed_source.committed().await);
+ }
+ cached.as_ref().expect("filled above").clone()
+ }
+}
+
+#[async_trait]
+impl TopicOffsetSource for TickBrokerSnapshot<'_> {
+ async fn observation_ends(&self) -> Result<ObservationEnds, SourceError> {
+ let mut cached = self.ends.lock().await;
+ if cached.is_none() {
+ *cached = Some(self.ends_source.observation_ends().await);
+ }
+ cached.as_ref().expect("filled above").clone()
+ }
+}
+
+/// Build a watch directive for one reconciling run from its dispatch record and persisted bits, so
+/// the watcher resumes the fold rather than restarting it.
+fn build_directive(
+ completion: &DiscoveredCompletion,
+ dispatched: &DispatchedReconcile,
+ participations: &[ObservationParticipation],
+) -> WatchDirective {
+ let seeded: Vec<(_, PartitionBitmap)> = participations
+ .iter()
+ .filter(|participation| participation.superseded_at.is_none())
+ .map(|participation| (participation.cohort_id, participation.bits))
+ .collect();
+ WatchDirective {
+ run_id: completion.run_id,
+ team_id: completion.team_id,
+ epoch: dispatched.epoch,
+ start: dispatched.watch.positions.clone(),
+ seeded,
+ }
+}
+
+/// Track the oldest not-yet-observed reconciling run for the stalled-observation pager gauge.
+/// `since` is when the run entered its current phase, never when it was created.
+fn track_oldest(oldest: &mut Option<DateTime<Utc>>, since: DateTime<Utc>) {
+ match oldest {
+ Some(current) if *current <= since => {}
+ _ => *oldest = Some(since),
}
}
@@ -251,15 +597,15 @@ impl InFlightGuard {
impl Drop for InFlightGuard {
fn drop(&mut self) {
- lock_in_flight(&self.in_flight).remove(&self.run_id);
+ lock_recoverable(&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
+/// The driver's run sets stay structurally valid across a panic between lock and mutation, so a
+/// poisoned lock is recoverable rather than fatal.
+fn lock_recoverable<T>(value: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
+ value
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
@@ -270,7 +616,7 @@ fn lock_in_flight(in_flight: &Mutex<HashSet<RunId>>) -> std::sync::MutexGuard<'_
/// 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) {
+async fn run_dispatch(context: &DispatchArm, run_id: RunId, kind: DispatchKind) {
let claim = match acquire_claim(context, run_id, kind).await {
Ok(Some(claim)) => claim,
Ok(None) => {
@@ -354,7 +700,7 @@ async fn run_dispatch(context: &DispatchContext, run_id: RunId, kind: DispatchKi
}
async fn acquire_claim(
- context: &DispatchContext,
+ context: &DispatchArm,
run_id: RunId,
kind: DispatchKind,
) -> Result<Option<ReconcilingClaim>, CompletionStoreError> {
@@ -522,4 +868,29 @@ mod tests {
AutoDispatchPolicyError::PartitionCountMismatch { configured: 8 }
);
}
+
+ #[test]
+ fn observer_policy_is_a_gate_independent_of_auto_dispatch() {
+ assert_eq!(
+ ObservePolicy::from_config(&config_with(&[])).unwrap(),
+ ObservePolicy::Disabled
+ );
+ // The observer arms without the dispatch flags: the two gates are independent.
+ assert_eq!(
+ ObservePolicy::from_config(&config_with(&[(
+ "SEEDER_RECONCILE_OBSERVER_ENABLED",
+ "true"
+ )]))
+ .unwrap(),
+ ObservePolicy::Enabled
+ );
+ assert_eq!(
+ ObservePolicy::from_config(&config_with(&[
+ ("SEEDER_RECONCILE_OBSERVER_ENABLED", "true"),
+ ("COHORT_PARTITION_COUNT", "8"),
+ ]))
+ .unwrap_err(),
+ ObservePolicyError::PartitionCountMismatch { configured: 8 }
+ );
+ }
}
diff --git a/rust/cohort-seeder/src/app/mod.rs b/rust/cohort-seeder/src/app/mod.rs
index 2f6a06392add..d37bbc50d02c 100644
--- a/rust/cohort-seeder/src/app/mod.rs
+++ b/rust/cohort-seeder/src/app/mod.rs
@@ -4,11 +4,18 @@
pub mod completion;
mod deliver;
mod execute;
+pub mod observe;
mod orchestrator;
mod prepare;
pub mod reconcile_dispatch;
pub mod settings;
+pub mod watch;
-pub use completion::{AutoDispatchPolicy, AutoDispatchPolicyError, CompletionDriver};
+pub use completion::{
+ AutoDispatchPolicy, AutoDispatchPolicyError, CompletionDriver, ObservePolicy,
+ ObservePolicyError,
+};
+pub use observe::{KafkaCommittedOffsets, KafkaTopicOffsets};
pub use orchestrator::{SeederOrchestrator, ORCHESTRATOR_LIVENESS_DEADLINE};
pub use settings::OrchestratorSettings;
+pub use watch::{MarkerWatchTask, PgMarkerFlush, WatchDirectives, MARKER_WATCH_LIVENESS_DEADLINE};
diff --git a/rust/cohort-seeder/src/app/observe.rs b/rust/cohort-seeder/src/app/observe.rs
new file mode 100644
index 000000000000..0d28e6ed8749
--- /dev/null
+++ b/rust/cohort-seeder/src/app/observe.rs
@@ -0,0 +1,1032 @@
+//! The driver's observation pass for one reconciling run, plus the app-owned seams the tests fake.
+//!
+//! Outcomes land before observed: every non-superseded participation gets a definitive outcome
+//! write before `reconcile_observed_at` is stamped, which is this pass's last
+//! write. The marker set is the completion *authority* (bitmaps decide complete vs short); the seed
+//! group's committed offsets are *liveness only* (they gate whether we may even capture the membership
+//! end-watermarks that a negative verdict's settlement proof requires). Hash attribution splits a
+//! shortfall into terminal (the cohort diverged or was deleted — supersede) vs retryable (the hash
+//! still matches — a gate-off or lossy fleet, error only). A [`CompletionStoreError::CompletionFenceLost`]
+//! from any write means a re-dispatch superseded this pass; the caller stops observing the run.
+//!
+//! Three seams keep the pass testable without a broker or a database: [`CommittedOffsetSource`] and
+//! [`TopicOffsetSource`] wrap the kafka layer, [`ObservationStore`] wraps the fenced store writes.
+//!
+//! Lag is reported through [`ObserveStep`]; the driver aggregates it across the tick's runs into
+//! one fleet-wide gauge reading.
+
+use std::collections::HashMap;
+use std::time::Duration;
+
+use async_trait::async_trait;
+use cohort_core::filters::{CohortId, TeamId};
+use cohort_core::partitioner::COHORT_PARTITION_COUNT;
+use metrics::counter;
+use sqlx::PgPool;
+use tracing::warn;
+
+use crate::domain::{
+ BehavioralShapeHash, DispatchEpoch, LivenessCheck, MarkerLedger, MarkerWatch, ObservationEnds,
+ PartitionBitmap, ReconcileHwms, RunId, SeedGroupCommits, SettledVerdict,
+};
+use crate::kafka::committed::SeedGroupOffsetReader;
+use crate::kafka::producer::SeedTileProducer;
+use crate::observability::metrics::{
+ RECONCILE_COHORTS_COMPLETED, RECONCILE_COHORTS_PARTIAL, RECONCILE_COHORTS_SHORTFALL,
+};
+use crate::store::completion::{
+ load_current_behavioral_hashes, load_observation_participations, mark_participation_completed,
+ mark_run_observed, persist_observation_ends, record_participation_partial,
+ record_participation_shortfall, CompletionStoreError, CurrentBehavioralHash,
+ ObservationParticipation,
+};
+use crate::store::{render_error_chain, RenderedError};
+
+/// The dispatch record the observer needs, lifted from a `Reconciling(DispatchedReconcile)` phase.
+#[derive(Debug, Clone)]
+pub struct ObserveTarget {
+ pub run_id: RunId,
+ pub team_id: TeamId,
+ pub epoch: DispatchEpoch,
+ pub hwms: ReconcileHwms,
+ pub watch: MarkerWatch,
+}
+
+/// What one observation pass did — the driver's metric/logging surface and the tests' assertion point.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ObserveStep {
+ /// Every active participation was already complete; observed with no liveness call.
+ ObservedAllComplete,
+ /// The seed group has not drained the reconcile records; the run holds for the next tick.
+ LivenessLagging(usize),
+ /// Liveness passed and the membership end-watermarks were captured; observation resumes next tick.
+ EndsCaptured,
+ /// Liveness passed earlier but the marker watcher has not read to the captured ends.
+ MarkerLagging(usize),
+ /// Settled against the marker set and observed.
+ Settled(SettleSummary),
+}
+
+/// The per-cohort outcome tally of a settlement.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub struct SettleSummary {
+ pub completed: usize,
+ /// Terminal supersede-by-reconcile (diverged / deleted).
+ pub partial: usize,
+ /// Retryable shortfall (hash still matches).
+ pub shortfall: usize,
+ /// Not a single marker was observed — a fleet-wide gate-off signal.
+ pub zero_markers: bool,
+}
+
+/// Run the observation pass. Returns the step reached; the caller maps a lost fence to an info log.
+/// `participations` is passed in rather than read here so one tick reads a run's rows once and both
+/// the watch directive and this pass see the same snapshot.
+pub async fn observe_run(
+ store: &dyn ObservationStore,
+ committed: &dyn CommittedOffsetSource,
+ topic_ends: &dyn TopicOffsetSource,
+ target: &ObserveTarget,
+ participations: &[ObservationParticipation],
+) -> Result<ObserveStep, ObserveError> {
+ let active: Vec<&ObservationParticipation> = participations
+ .iter()
+ .filter(|participation| participation.superseded_at.is_none())
+ .collect();
+
+ // 1. Early success: every active participation is already complete. No liveness needed — the
+ // marker authority is already satisfied. (Vacuously true when everything is superseded: the
+ // supersessions are the definitive outcomes, so the run is observable.)
+ if active
+ .iter()
+ .all(|p| p.bits.is_complete() || p.reconcile_completed_at.is_some())
+ {
+ for participation in &active {
+ store
+ .mark_completed(target.run_id, target.epoch, participation.cohort_id)
+ .await?;
+ }
+ store.mark_observed(target.run_id, target.epoch).await?;
+ counter!(RECONCILE_COHORTS_COMPLETED).increment(active.len() as u64);
+ return Ok(ObserveStep::ObservedAllComplete);
+ }
+
+ // 2. Some participation is short — a negative verdict needs both liveness and a settlement proof.
+ let proof = match &target.watch.ends {
+ None => {
+ let commits = committed
+ .committed()
+ .await
+ .map_err(ObserveError::Committed)?;
+ match target.hwms.lagging(&commits) {
+ LivenessCheck::Lagging(partitions) => {
+ return Ok(ObserveStep::LivenessLagging(partitions.len()));
+ }
+ LivenessCheck::Passed => {
+ let ends = topic_ends
+ .observation_ends()
+ .await
+ .map_err(ObserveError::TopicEnds)?;
+ store
+ .persist_ends(target.run_id, target.epoch, &ends)
+ .await?;
+ return Ok(ObserveStep::EndsCaptured);
+ }
+ }
+ }
+ Some(ends) => match ends.caught_up(&target.watch.positions) {
+ None => {
+ return Ok(ObserveStep::MarkerLagging(
+ ends.behind(&target.watch.positions),
+ ))
+ }
+ Some(proof) => proof,
+ },
+ };
+
+ // 3. The proof is in hand: settle against the persisted marker bits.
+ let ledger = MarkerLedger::new(
+ target.run_id,
+ target.team_id,
+ active.iter().map(|p| (p.cohort_id, p.bits)),
+ );
+ let summary = apply_verdict(store, target, &active, ledger.settle(proof)).await?;
+ store.mark_observed(target.run_id, target.epoch).await?;
+ Ok(ObserveStep::Settled(summary))
+}
+
+async fn apply_verdict(
+ store: &dyn ObservationStore,
+ target: &ObserveTarget,
+ active: &[&ObservationParticipation],
+ verdict: SettledVerdict,
+) -> Result<SettleSummary, ObserveError> {
+ match verdict {
+ SettledVerdict::AllComplete => {
+ for participation in active {
+ store
+ .mark_completed(target.run_id, target.epoch, participation.cohort_id)
+ .await?;
+ }
+ counter!(RECONCILE_COHORTS_COMPLETED).increment(active.len() as u64);
+ Ok(SettleSummary {
+ completed: active.len(),
+ ..SettleSummary::default()
+ })
+ }
+ SettledVerdict::Partial {
+ complete,
+ incomplete,
+ } => {
+ for cohort_id in &complete {
+ store
+ .mark_completed(target.run_id, target.epoch, *cohort_id)
+ .await?;
+ }
+ counter!(RECONCILE_COHORTS_COMPLETED).increment(complete.len() as u64);
+ let (partial, shortfall) =
+ attribute_incomplete(store, target, active, &incomplete).await?;
+ Ok(SettleSummary {
+ completed: complete.len(),
+ partial,
+ shortfall,
+ zero_markers: false,
+ })
+ }
+ SettledVerdict::NoMarkers => {
+ warn!(
+ run_id = ?target.run_id,
+ team_id = target.team_id.0,
+ "zero reconcile markers observed for a settled run — the processor reconcile gate is likely off fleet-wide"
+ );
+ let incomplete: Vec<(CohortId, PartitionBitmap)> =
+ active.iter().map(|p| (p.cohort_id, p.bits)).collect();
+ let (partial, shortfall) =
+ attribute_incomplete(store, target, active, &incomplete).await?;
+ Ok(SettleSummary {
+ completed: 0,
+ partial,
+ shortfall,
+ zero_markers: true,
+ })
+ }
+ }
+}
+
+/// Split each short cohort into a terminal supersede (hash diverged / cohort deleted / indeterminate)
+/// or a retryable shortfall (hash still matches the pinned one).
+async fn attribute_incomplete(
+ store: &dyn ObservationStore,
+ target: &ObserveTarget,
+ active: &[&ObservationParticipation],
+ incomplete: &[(CohortId, PartitionBitmap)],
+) -> Result<(usize, usize), ObserveError> {
+ let cohort_ids: Vec<CohortId> = incomplete.iter().map(|(cohort_id, _)| *cohort_id).collect();
+ let current = store
+ .load_current_hashes(target.team_id, &cohort_ids)
+ .await?;
+ let pinned: HashMap<CohortId, &BehavioralShapeHash> = active
+ .iter()
+ .map(|p| (p.cohort_id, &p.behavioral_filters_shape_hash))
+ .collect();
+
+ let mut partial = 0;
+ let mut shortfall = 0;
+ for (cohort_id, bitmap) in incomplete {
+ let missing = render_missing(*bitmap);
+ let hash_matches = match current.get(cohort_id) {
+ Some(CurrentBehavioralHash::Present(current_hash)) => pinned
+ .get(cohort_id)
+ .is_some_and(|pinned_hash| *pinned_hash == current_hash),
+ // Deleted / Indeterminate / absent row all read as diverged: terminal.
+ _ => false,
+ };
+ if hash_matches {
+ let error = RenderedError::from_message(format!("reconcile shortfall: {missing}"));
+ store
+ .record_shortfall(target.run_id, target.epoch, *cohort_id, &error)
+ .await?;
+ shortfall += 1;
+ counter!(RECONCILE_COHORTS_SHORTFALL).increment(1);
+ } else {
+ let error = RenderedError::from_message(format!(
+ "reconcile superseded by a cohort change: {missing}"
+ ));
+ store
+ .record_partial(target.run_id, target.epoch, *cohort_id, &error)
+ .await?;
+ partial += 1;
+ counter!(RECONCILE_COHORTS_PARTIAL).increment(1);
+ }
+ }
+ Ok((partial, shortfall))
+}
+
+fn render_missing(bitmap: PartitionBitmap) -> String {
+ let missing = bitmap.missing();
+ let names: Vec<String> = missing.iter().map(|p| p.get().to_string()).collect();
+ format!(
+ "{}/{COHORT_PARTITION_COUNT} partitions still missing: {}",
+ names.len(),
+ names.join(",")
+ )
+}
+
+/// The seed group's committed offsets — the reconcile liveness signal.
+#[async_trait]
+pub trait CommittedOffsetSource: Send + Sync {
+ async fn committed(&self) -> Result<SeedGroupCommits, SourceError>;
+}
+
+/// The membership topic's current end-watermarks — captured at the liveness pass to bound the marker
+/// set of this dispatch.
+#[async_trait]
+pub trait TopicOffsetSource: Send + Sync {
+ async fn observation_ends(&self) -> Result<ObservationEnds, SourceError>;
+}
+
+/// The observation pass's store surface: the fenced writes plus the two reads it folds over. The
+/// real impl delegates to `store::completion`; `sqlx` stays confined below this seam.
+#[async_trait]
+pub trait ObservationStore: Send + Sync {
+ async fn load_participations(
+ &self,
+ run_id: RunId,
+ ) -> Result<Vec<ObservationParticipation>, CompletionStoreError>;
+ async fn load_current_hashes(
+ &self,
+ team_id: TeamId,
+ cohort_ids: &[CohortId],
+ ) -> Result<HashMap<CohortId, CurrentBehavioralHash>, CompletionStoreError>;
+ async fn persist_ends(
+ &self,
+ run_id: RunId,
+ epoch: DispatchEpoch,
+ ends: &ObservationEnds,
+ ) -> Result<(), CompletionStoreError>;
+ async fn mark_completed(
+ &self,
+ run_id: RunId,
+ epoch: DispatchEpoch,
+ cohort_id: CohortId,
+ ) -> Result<(), CompletionStoreError>;
+ async fn record_partial(
+ &self,
+ run_id: RunId,
+ epoch: DispatchEpoch,
+ cohort_id: CohortId,
+ error: &RenderedError,
+ ) -> Result<(), CompletionStoreError>;
+ async fn record_shortfall(
+ &self,
+ run_id: RunId,
+ epoch: DispatchEpoch,
+ cohort_id: CohortId,
+ error: &RenderedError,
+ ) -> Result<(), CompletionStoreError>;
+ async fn mark_observed(
+ &self,
+ run_id: RunId,
+ epoch: DispatchEpoch,
+ ) -> Result<(), CompletionStoreError>;
+}
+
+/// The real observation store over the seeder's pool.
+pub struct PgObservationStore {
+ pool: PgPool,
+}
+
+impl PgObservationStore {
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+#[async_trait]
+impl ObservationStore for PgObservationStore {
+ async fn load_participations(
+ &self,
+ run_id: RunId,
+ ) -> Result<Vec<ObservationParticipation>, CompletionStoreError> {
+ load_observation_participations(&self.pool, run_id).await
+ }
+
+ async fn load_current_hashes(
+ &self,
+ team_id: TeamId,
+ cohort_ids: &[CohortId],
+ ) -> Result<HashMap<CohortId, CurrentBehavioralHash>, CompletionStoreError> {
+ load_current_behavioral_hashes(&self.pool, team_id, cohort_ids).await
+ }
+
+ async fn persist_ends(
+ &self,
+ run_id: RunId,
+ epoch: DispatchEpoch,
+ ends: &ObservationEnds,
+ ) -> Result<(), CompletionStoreError> {
+ persist_observation_ends(&self.pool, run_id, epoch, ends).await
+ }
+
+ async fn mark_completed(
+ &self,
+ run_id: RunId,
+ epoch: DispatchEpoch,
+ cohort_id: CohortId,
+ ) -> Result<(), CompletionStoreError> {
+ mark_participation_completed(&self.pool, run_id, epoch, cohort_id).await
+ }
+
+ async fn record_partial(
+ &self,
+ run_id: RunId,
+ epoch: DispatchEpoch,
+ cohort_id: CohortId,
+ error: &RenderedError,
+ ) -> Result<(), CompletionStoreError> {
+ record_participation_partial(&self.pool, run_id, epoch, cohort_id, error).await
+ }
+
+ async fn record_shortfall(
+ &self,
+ run_id: RunId,
+ epoch: DispatchEpoch,
+ cohort_id: CohortId,
+ error: &RenderedError,
+ ) -> Result<(), CompletionStoreError> {
+ record_participation_shortfall(&self.pool, run_id, epoch, cohort_id, error).await
+ }
+
+ async fn mark_observed(
+ &self,
+ run_id: RunId,
+ epoch: DispatchEpoch,
+ ) -> Result<(), CompletionStoreError> {
+ mark_run_observed(&self.pool, run_id, epoch).await
+ }
+}
+
+/// An opaque broker-read failure. Broker plumbing lives in the kafka layer, so this carries only the
+/// rendered message across the seam.
+#[derive(Debug, Clone, thiserror::Error)]
+#[error("{0}")]
+pub struct SourceError(String);
+
+impl SourceError {
+ pub fn new(message: impl Into<String>) -> Self {
+ Self(message.into())
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum ObserveError {
+ #[error("reading the seed group's committed offsets")]
+ Committed(#[source] SourceError),
+ #[error("capturing the membership end watermarks")]
+ TopicEnds(#[source] SourceError),
+ #[error(transparent)]
+ Store(#[from] CompletionStoreError),
+}
+
+/// The real committed-offset seam: the seed-group offset reader.
+pub struct KafkaCommittedOffsets(SeedGroupOffsetReader);
+
+impl KafkaCommittedOffsets {
+ pub fn new(reader: SeedGroupOffsetReader) -> Self {
+ Self(reader)
+ }
+}
+
+#[async_trait]
+impl CommittedOffsetSource for KafkaCommittedOffsets {
+ async fn committed(&self) -> Result<SeedGroupCommits, SourceError> {
+ self.0
+ .committed()
+ .await
+ .map_err(|error| SourceError::new(render_error_chain(&error)))
+ }
+}
+
+/// The real topic-offset seam: the seed producer's client fetches the membership topic's watermarks.
+pub struct KafkaTopicOffsets {
+ producer: SeedTileProducer,
+ topic: String,
+ timeout: Duration,
+}
+
+impl KafkaTopicOffsets {
+ pub fn new(producer: SeedTileProducer, topic: String, timeout: Duration) -> Self {
+ Self {
+ producer,
+ topic,
+ timeout,
+ }
+ }
+}
+
+#[async_trait]
+impl TopicOffsetSource for KafkaTopicOffsets {
+ async fn observation_ends(&self) -> Result<ObservationEnds, SourceError> {
+ let producer = self.producer.clone();
+ let topic = self.topic.clone();
+ let timeout = self.timeout;
+ let positions =
+ tokio::task::spawn_blocking(move || producer.capture_topic_offsets(&topic, timeout))
+ .await
+ .map_err(|error| {
+ SourceError::new(format!("join membership watermark task: {error}"))
+ })?
+ .map_err(|error| SourceError::new(render_error_chain(&error)))?;
+ Ok(ObservationEnds::from_positions(&positions))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::collections::BTreeMap;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ use std::sync::Mutex;
+
+ use uuid::Uuid;
+
+ use crate::domain::{
+ CommittedOffset, MarkerPartition, MembershipPartition, NextOffset, ProducedOffset,
+ SeedPartition, WatchPositions,
+ };
+ use crate::store::completion::CompletionOperation;
+
+ fn run_id() -> RunId {
+ RunId(Uuid::from_u128(7))
+ }
+
+ fn epoch() -> DispatchEpoch {
+ use chrono::TimeZone;
+ DispatchEpoch::from_dispatched_at(chrono::Utc.timestamp_opt(1_700_000_000, 0).unwrap())
+ }
+
+ fn hash(value: &str) -> BehavioralShapeHash {
+ BehavioralShapeHash::parse(value).unwrap()
+ }
+
+ fn full_hwms() -> ReconcileHwms {
+ let offsets: BTreeMap<SeedPartition, ProducedOffset> =
+ SeedPartition::all(COHORT_PARTITION_COUNT)
+ .unwrap()
+ .map(|partition| (partition, ProducedOffset::new(100)))
+ .collect();
+ ReconcileHwms::new(offsets).unwrap()
+ }
+
+ fn commits(delta: i64) -> SeedGroupCommits {
+ let mut commits = SeedGroupCommits::new();
+ for partition in SeedPartition::all(COHORT_PARTITION_COUNT).unwrap() {
+ commits.insert(partition, CommittedOffset::new(100 + delta));
+ }
+ commits
+ }
+
+ fn participation(cohort: i32, bits: PartitionBitmap) -> ObservationParticipation {
+ ObservationParticipation {
+ cohort_id: CohortId(cohort),
+ behavioral_filters_shape_hash: hash("pinned"),
+ bits,
+ reconcile_completed_at: None,
+ superseded_at: None,
+ stamped_at: None,
+ }
+ }
+
+ fn complete_bits() -> PartitionBitmap {
+ PartitionBitmap::from_bits(-1).unwrap()
+ }
+
+ fn one_short_bits() -> PartitionBitmap {
+ let mut bitmap = PartitionBitmap::default();
+ for index in 1..COHORT_PARTITION_COUNT {
+ bitmap.set(MarkerPartition::new(index).unwrap());
+ }
+ bitmap
+ }
+
+ fn target(ends: Option<ObservationEnds>) -> ObserveTarget {
+ ObserveTarget {
+ run_id: run_id(),
+ team_id: TeamId(2),
+ epoch: epoch(),
+ hwms: full_hwms(),
+ watch: MarkerWatch {
+ positions: watched_positions(),
+ ends,
+ },
+ }
+ }
+
+ /// Where the watcher has read to. Past [`caught_up_ends`], short of [`pending_ends`].
+ fn watched_positions() -> WatchPositions {
+ let mut positions = WatchPositions::new();
+ positions.insert(
+ MembershipPartition::new(0),
+ NextOffset::from_high_watermark(10),
+ );
+ positions
+ }
+
+ /// Ends the watcher's positions already satisfy, so settlement is reachable.
+ fn caught_up_ends() -> ObservationEnds {
+ let mut ends = ObservationEnds::new();
+ ends.insert(
+ MembershipPartition::new(0),
+ NextOffset::from_high_watermark(10),
+ );
+ ends
+ }
+
+ fn pending_ends() -> ObservationEnds {
+ let mut ends = ObservationEnds::new();
+ ends.insert(
+ MembershipPartition::new(0),
+ NextOffset::from_high_watermark(20),
+ );
+ ends
+ }
+
+ #[derive(Default)]
+ struct FakeCommittedOffsets {
+ commits: Mutex<Option<SeedGroupCommits>>,
+ calls: AtomicUsize,
+ }
+
+ impl FakeCommittedOffsets {
+ fn returning(commits: SeedGroupCommits) -> Self {
+ Self {
+ commits: Mutex::new(Some(commits)),
+ calls: AtomicUsize::new(0),
+ }
+ }
+
+ fn calls(&self) -> usize {
+ self.calls.load(Ordering::SeqCst)
+ }
+ }
+
+ #[async_trait]
+ impl CommittedOffsetSource for FakeCommittedOffsets {
+ async fn committed(&self) -> Result<SeedGroupCommits, SourceError> {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ self.commits
+ .lock()
+ .unwrap()
+ .clone()
+ .ok_or_else(|| SourceError::new("no scripted commits"))
+ }
+ }
+
+ #[derive(Default)]
+ struct FakeTopicOffsets {
+ calls: AtomicUsize,
+ }
+
+ #[async_trait]
+ impl TopicOffsetSource for FakeTopicOffsets {
+ async fn observation_ends(&self) -> Result<ObservationEnds, SourceError> {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ Ok(pending_ends())
+ }
+ }
+
+ #[derive(Debug, Clone, PartialEq, Eq)]
+ enum StoreCall {
+ Completed(CohortId),
+ Partial(CohortId),
+ Shortfall(CohortId),
+ PersistEnds(ObservationEnds),
+ Observed,
+ }
+
+ #[derive(Default)]
+ struct FakeStore {
+ participations: Vec<ObservationParticipation>,
+ current: HashMap<CohortId, CurrentBehavioralHash>,
+ calls: Mutex<Vec<StoreCall>>,
+ fence_lost_on_completed: bool,
+ }
+
+ impl FakeStore {
+ fn calls(&self) -> Vec<StoreCall> {
+ self.calls.lock().unwrap().clone()
+ }
+
+ fn observed(&self) -> bool {
+ self.calls().contains(&StoreCall::Observed)
+ }
+ }
+
+ #[async_trait]
+ impl ObservationStore for FakeStore {
+ async fn load_participations(
+ &self,
+ _run_id: RunId,
+ ) -> Result<Vec<ObservationParticipation>, CompletionStoreError> {
+ Ok(self.participations.clone())
+ }
+
+ async fn load_current_hashes(
+ &self,
+ _team_id: TeamId,
+ cohort_ids: &[CohortId],
+ ) -> Result<HashMap<CohortId, CurrentBehavioralHash>, CompletionStoreError> {
+ Ok(cohort_ids
+ .iter()
+ .filter_map(|cohort_id| {
+ self.current
+ .get(cohort_id)
+ .map(|state| (*cohort_id, state.clone()))
+ })
+ .collect())
+ }
+
+ async fn persist_ends(
+ &self,
+ _run_id: RunId,
+ _epoch: DispatchEpoch,
+ ends: &ObservationEnds,
+ ) -> Result<(), CompletionStoreError> {
+ self.calls
+ .lock()
+ .unwrap()
+ .push(StoreCall::PersistEnds(ends.clone()));
+ Ok(())
+ }
+
+ async fn mark_completed(
+ &self,
+ run_id: RunId,
+ _epoch: DispatchEpoch,
+ cohort_id: CohortId,
+ ) -> Result<(), CompletionStoreError> {
+ if self.fence_lost_on_completed {
+ return Err(CompletionStoreError::CompletionFenceLost {
+ run_id,
+ operation: CompletionOperation::MarkCompleted,
+ });
+ }
+ self.calls
+ .lock()
+ .unwrap()
+ .push(StoreCall::Completed(cohort_id));
+ Ok(())
+ }
+
+ async fn record_partial(
+ &self,
+ _run_id: RunId,
+ _epoch: DispatchEpoch,
+ cohort_id: CohortId,
+ _error: &RenderedError,
+ ) -> Result<(), CompletionStoreError> {
+ self.calls
+ .lock()
+ .unwrap()
+ .push(StoreCall::Partial(cohort_id));
+ Ok(())
+ }
+
+ async fn record_shortfall(
+ &self,
+ _run_id: RunId,
+ _epoch: DispatchEpoch,
+ cohort_id: CohortId,
+ _error: &RenderedError,
+ ) -> Result<(), CompletionStoreError> {
+ self.calls
+ .lock()
+ .unwrap()
+ .push(StoreCall::Shortfall(cohort_id));
+ Ok(())
+ }
+
+ async fn mark_observed(
+ &self,
+ _run_id: RunId,
+ _epoch: DispatchEpoch,
+ ) -> Result<(), CompletionStoreError> {
+ self.calls.lock().unwrap().push(StoreCall::Observed);
+ Ok(())
+ }
+ }
+
+ #[tokio::test]
+ async fn all_complete_early_exits_without_any_liveness_call() {
+ let store = FakeStore {
+ participations: vec![
+ participation(10, complete_bits()),
+ participation(11, complete_bits()),
+ ],
+ ..FakeStore::default()
+ };
+ let committed = FakeCommittedOffsets::default();
+ let ends = FakeTopicOffsets::default();
+
+ let step = observe_run(
+ &store,
+ &committed,
+ &ends,
+ &target(None),
+ &store.participations,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(step, ObserveStep::ObservedAllComplete);
+ assert_eq!(committed.calls(), 0, "no liveness read on the early exit");
+ assert_eq!(ends.calls.load(Ordering::SeqCst), 0);
+ assert_eq!(
+ store.calls(),
+ vec![
+ StoreCall::Completed(CohortId(10)),
+ StoreCall::Completed(CohortId(11)),
+ StoreCall::Observed,
+ ],
+ "outcomes land before observed"
+ );
+ }
+
+ #[tokio::test]
+ async fn lagging_liveness_holds_the_run_without_persisting_ends() {
+ let store = FakeStore {
+ participations: vec![participation(10, PartitionBitmap::default())],
+ ..FakeStore::default()
+ };
+ // committed == produced ⇒ still lagging (the +1 contract).
+ let committed = FakeCommittedOffsets::returning(commits(0));
+ let ends = FakeTopicOffsets::default();
+
+ let step = observe_run(
+ &store,
+ &committed,
+ &ends,
+ &target(None),
+ &store.participations,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ step,
+ ObserveStep::LivenessLagging(COHORT_PARTITION_COUNT as usize)
+ );
+ assert_eq!(
+ ends.calls.load(Ordering::SeqCst),
+ 0,
+ "no ends captured while lagging"
+ );
+ assert!(store.calls().is_empty(), "a held run writes nothing");
+ }
+
+ #[tokio::test]
+ async fn ends_are_captured_once_then_liveness_is_skipped() {
+ let store = FakeStore {
+ participations: vec![participation(10, PartitionBitmap::default())],
+ ..FakeStore::default()
+ };
+ let committed = FakeCommittedOffsets::returning(commits(1));
+ let ends = FakeTopicOffsets::default();
+
+ // First pass: liveness passes, ends are captured and persisted.
+ let step = observe_run(
+ &store,
+ &committed,
+ &ends,
+ &target(None),
+ &store.participations,
+ )
+ .await
+ .unwrap();
+ assert_eq!(step, ObserveStep::EndsCaptured);
+ assert_eq!(committed.calls(), 1);
+ assert_eq!(ends.calls.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ store.calls(),
+ vec![StoreCall::PersistEnds(pending_ends())],
+ "the captured ends are persisted verbatim"
+ );
+
+ // Second pass with ends present but positions behind: liveness is not re-read.
+ let step = observe_run(
+ &store,
+ &committed,
+ &ends,
+ &target(Some(pending_ends())),
+ &store.participations,
+ )
+ .await
+ .unwrap();
+ assert_eq!(step, ObserveStep::MarkerLagging(1));
+ assert_eq!(committed.calls(), 1, "ends present skips the liveness read");
+ assert!(!store.observed());
+ }
+
+ #[tokio::test]
+ async fn zero_markers_settles_to_shortfalls_and_observes() {
+ let store = FakeStore {
+ participations: vec![
+ participation(10, PartitionBitmap::default()),
+ participation(11, PartitionBitmap::default()),
+ ],
+ current: HashMap::from([
+ (CohortId(10), CurrentBehavioralHash::Present(hash("pinned"))),
+ (CohortId(11), CurrentBehavioralHash::Present(hash("pinned"))),
+ ]),
+ ..FakeStore::default()
+ };
+ let committed = FakeCommittedOffsets::default();
+ let ends = FakeTopicOffsets::default();
+
+ let step = observe_run(
+ &store,
+ &committed,
+ &ends,
+ &target(Some(caught_up_ends())),
+ &store.participations,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ step,
+ ObserveStep::Settled(SettleSummary {
+ completed: 0,
+ partial: 0,
+ shortfall: 2,
+ zero_markers: true,
+ })
+ );
+ assert_eq!(
+ store.calls(),
+ vec![
+ StoreCall::Shortfall(CohortId(10)),
+ StoreCall::Shortfall(CohortId(11)),
+ StoreCall::Observed,
+ ],
+ "matching hashes are retryable shortfalls, and observed lands last"
+ );
+ }
+
+ #[tokio::test]
+ async fn hash_attribution_splits_diverged_deleted_indeterminate_and_matching() {
+ let store = FakeStore {
+ participations: vec![
+ participation(10, complete_bits()), // complete
+ participation(11, one_short_bits()), // diverged ⇒ partial
+ participation(12, one_short_bits()), // matching ⇒ shortfall
+ participation(13, one_short_bits()), // deleted ⇒ partial
+ participation(14, one_short_bits()), // indeterminate ⇒ partial
+ participation(15, one_short_bits()), // absent row ⇒ partial
+ ],
+ current: HashMap::from([
+ (
+ CohortId(11),
+ CurrentBehavioralHash::Present(hash("diverged")),
+ ),
+ (CohortId(12), CurrentBehavioralHash::Present(hash("pinned"))),
+ (CohortId(13), CurrentBehavioralHash::Deleted),
+ (CohortId(14), CurrentBehavioralHash::Indeterminate),
+ ]),
+ ..FakeStore::default()
+ };
+ let committed = FakeCommittedOffsets::default();
+ let ends = FakeTopicOffsets::default();
+
+ let step = observe_run(
+ &store,
+ &committed,
+ &ends,
+ &target(Some(caught_up_ends())),
+ &store.participations,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ step,
+ ObserveStep::Settled(SettleSummary {
+ completed: 1,
+ partial: 4,
+ shortfall: 1,
+ zero_markers: false,
+ })
+ );
+ let calls = store.calls();
+ assert_eq!(calls.first(), Some(&StoreCall::Completed(CohortId(10))));
+ assert!(calls.contains(&StoreCall::Partial(CohortId(11))));
+ assert!(calls.contains(&StoreCall::Shortfall(CohortId(12))));
+ assert!(calls.contains(&StoreCall::Partial(CohortId(13))));
+ assert!(calls.contains(&StoreCall::Partial(CohortId(14))));
+ assert!(calls.contains(&StoreCall::Partial(CohortId(15))));
+ assert_eq!(
+ calls.last(),
+ Some(&StoreCall::Observed),
+ "observed lands last"
+ );
+ }
+
+ #[tokio::test]
+ async fn superseded_participations_are_excluded_and_all_superseded_observes() {
+ let mut superseded = participation(10, PartitionBitmap::default());
+ superseded.superseded_at = Some(chrono::Utc::now());
+ let store = FakeStore {
+ participations: vec![superseded],
+ ..FakeStore::default()
+ };
+ let committed = FakeCommittedOffsets::default();
+ let ends = FakeTopicOffsets::default();
+
+ let step = observe_run(
+ &store,
+ &committed,
+ &ends,
+ &target(None),
+ &store.participations,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(step, ObserveStep::ObservedAllComplete);
+ assert_eq!(
+ store.calls(),
+ vec![StoreCall::Observed],
+ "supersessions are already definitive outcomes; only observed is stamped"
+ );
+ }
+
+ #[tokio::test]
+ async fn fence_loss_mid_pass_stops_cleanly_without_observing() {
+ let store = FakeStore {
+ participations: vec![participation(10, complete_bits())],
+ fence_lost_on_completed: true,
+ ..FakeStore::default()
+ };
+ let committed = FakeCommittedOffsets::default();
+ let ends = FakeTopicOffsets::default();
+
+ let error = observe_run(
+ &store,
+ &committed,
+ &ends,
+ &target(None),
+ &store.participations,
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(
+ error,
+ ObserveError::Store(CompletionStoreError::CompletionFenceLost { .. })
+ ));
+ assert!(
+ !store.observed(),
+ "a lost fence never reaches the observed stamp"
+ );
+ }
+}
diff --git a/rust/cohort-seeder/src/app/orchestrator.rs b/rust/cohort-seeder/src/app/orchestrator.rs
index 159b5126a924..39a9253ed47b 100644
--- a/rust/cohort-seeder/src/app/orchestrator.rs
+++ b/rust/cohort-seeder/src/app/orchestrator.rs
@@ -104,6 +104,11 @@ impl SeederOrchestrator {
self.reap_poisoned_chunks(&eligible_runs).await;
self.fill_claim_slots(&eligible_runs, &mut tasks, &shutdown).await;
if let Some(driver) = &self.completion_driver {
+ // Dispatch work is spawned off this tick, but observation runs inline: a few
+ // DB reads per reconciling run, plus at most one OffsetFetch and one
+ // watermark sweep for the whole tick (the driver memoizes both). If the
+ // per-run cost ever stops being negligible, observation must be spawned like
+ // dispatch to stay inside the liveness deadline.
driver.tick().await;
}
self.handle.report_healthy();
diff --git a/rust/cohort-seeder/src/app/watch.rs b/rust/cohort-seeder/src/app/watch.rs
new file mode 100644
index 000000000000..ad074380694f
--- /dev/null
+++ b/rust/cohort-seeder/src/app/watch.rs
@@ -0,0 +1,1129 @@
+//! The single global marker-watch task — the seeder's second lifecycle component.
+//!
+//! One dedicated consumer tails the whole membership topic, folding every observed
+//! `reconcile_complete` marker into the per-run [`MarkerLedger`] it names. Bits and the watcher's
+//! resume positions are flushed through the fenced [`persist_marker_observations`] on a cadence
+//! (every persist interval), a batch cap (every N consumed messages), or immediately when a cohort's
+//! bitmap completes — whichever comes first. The driver publishes the set of runs to watch via a
+//! [`watch`] channel, recomputed each tick from discovery; the task adds ledgers seeded from persisted
+//! bits (so a resumed watcher continues the fold) and drops runs that leave the set. A lost dispatch
+//! fence (a re-dispatch superseded us) or a truncated start offset (retention outran the watch
+//! position) drops the run locally; re-dispatch is the recovery path.
+//!
+//! The broker plumbing lives behind the [`MarkerStream`] and [`MarkerFlush`] seams so the fold/flush
+//! decision logic is tested with fakes — the rdkafka consumer follows proven prior art and gets no
+//! broker integration test.
+
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::time::Duration;
+
+use async_trait::async_trait;
+use cohort_core::filters::{CohortId, TeamId};
+use lifecycle::Handle;
+use metrics::counter;
+use sqlx::PgPool;
+use tokio::sync::watch;
+use tracing::{info, warn};
+
+use crate::domain::{
+ DispatchEpoch, MarkerFold, MarkerLedger, MembershipPartition, NextOffset, PartitionBitmap,
+ RunId, WatchPositions,
+};
+use crate::kafka::markers::{MarkerWatcher, WatchError, WatchItem};
+use crate::observability::metrics::{RECONCILE_MARKERS_OBSERVED, RECONCILE_WATCH_TRUNCATED};
+use crate::store::completion::{persist_marker_observations, CompletionStoreError};
+
+/// One run the driver wants watched: its identity, dispatch fence, watcher start offsets, and the bits
+/// already persisted (so a resumed ledger continues rather than restarts).
+#[derive(Debug, Clone)]
+pub struct WatchDirective {
+ pub run_id: RunId,
+ pub team_id: TeamId,
+ pub epoch: DispatchEpoch,
+ pub start: WatchPositions,
+ pub seeded: Vec<(CohortId, PartitionBitmap)>,
+}
+
+/// The full set of runs to watch, republished each driver tick.
+#[derive(Debug, Clone, Default)]
+pub struct WatchDirectives {
+ pub runs: Vec<WatchDirective>,
+}
+
+/// The membership-topic consumer seam. Real impl: [`MarkerWatcher`].
+#[async_trait]
+pub trait MarkerStream: Send {
+ /// Re-assign the stream to read from `start` on every named partition. The watch state decides
+ /// *when* a seek is needed; the stream just does it.
+ async fn seek(&mut self, start: &WatchPositions) -> Result<(), WatchError>;
+ /// Drop the assignment entirely. Called when the last watched run leaves, so an idle watcher
+ /// stops fetching a high-volume topic nobody is folding.
+ async fn unassign(&mut self) -> Result<(), WatchError>;
+ /// Await the next classified record.
+ async fn recv(&mut self) -> Result<WatchItem, WatchError>;
+}
+
+#[async_trait]
+impl MarkerStream for MarkerWatcher {
+ async fn seek(&mut self, start: &WatchPositions) -> Result<(), WatchError> {
+ self.seek_to(start).await
+ }
+
+ async fn unassign(&mut self) -> Result<(), WatchError> {
+ MarkerWatcher::unassign(self)
+ }
+
+ async fn recv(&mut self) -> Result<WatchItem, WatchError> {
+ MarkerWatcher::next_item(self).await
+ }
+}
+
+/// The fenced-persist seam. Real impl: [`PgMarkerFlush`].
+#[async_trait]
+pub trait MarkerFlush: Send {
+ async fn persist(
+ &self,
+ run_id: RunId,
+ epoch: DispatchEpoch,
+ bits: &[(CohortId, PartitionBitmap)],
+ positions: &WatchPositions,
+ ) -> Result<(), CompletionStoreError>;
+}
+
+/// The real flush: the epoch-fenced OR-merge of bits plus the watcher positions.
+pub struct PgMarkerFlush {
+ pool: PgPool,
+}
+
+impl PgMarkerFlush {
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+#[async_trait]
+impl MarkerFlush for PgMarkerFlush {
+ async fn persist(
+ &self,
+ run_id: RunId,
+ epoch: DispatchEpoch,
+ bits: &[(CohortId, PartitionBitmap)],
+ positions: &WatchPositions,
+ ) -> Result<(), CompletionStoreError> {
+ persist_marker_observations(&self.pool, run_id, epoch, bits, positions).await
+ }
+}
+
+/// One watched run's in-memory fold state. `positions` is this run's fold *coverage*: it starts at
+/// the directive's dispatch-time start (so partitions with no traffic since the dispatch already
+/// read as covered) and max-merges forward as the stream reads. Coverage is tracked per run so a
+/// freshly added run cannot claim offsets the stream read before that run's ledger existed — its
+/// settlement proof rests on this.
+struct RunWatch {
+ epoch: DispatchEpoch,
+ positions: WatchPositions,
+ ledger: MarkerLedger,
+}
+
+impl RunWatch {
+ fn from_directive(directive: &WatchDirective) -> Self {
+ Self {
+ epoch: directive.epoch,
+ positions: directive.start.clone(),
+ ledger: MarkerLedger::new(
+ directive.run_id,
+ directive.team_id,
+ directive.seeded.iter().copied(),
+ ),
+ }
+ }
+}
+
+/// What the stream has read since coverage was last folded into the watched runs. Held once for the
+/// whole task rather than advanced into every run per record: the membership topic is high-volume and
+/// the watched-run set has no upper bound, so per-record work must not scale with it.
+#[derive(Default)]
+struct StreamCoverage(BTreeMap<MembershipPartition, NextOffset>);
+
+impl StreamCoverage {
+ fn advance(&mut self, partition: MembershipPartition, next: NextOffset) {
+ let slot = self.0.entry(partition).or_insert(next);
+ if next > *slot {
+ *slot = next;
+ }
+ }
+
+ /// Raise a run's tracked partitions to what the stream has read. [`WatchPositions::advance`] drops
+ /// partitions the run never captured, which is what keeps a run from claiming one it never read
+ /// from the beginning.
+ fn raise(&self, positions: &mut WatchPositions) {
+ for (&partition, &next) in &self.0 {
+ positions.advance(partition, next);
+ }
+ }
+
+ fn is_empty(&self) -> bool {
+ self.0.is_empty()
+ }
+
+ fn clear(&mut self) {
+ self.0.clear();
+ }
+}
+
+/// The fold/flush state machine, driven by the runner loop but callable directly in tests.
+struct WatchState<S, F> {
+ stream: S,
+ flush: F,
+ persist_max_batch: u64,
+ stream_coverage: StreamCoverage,
+ /// Heartbeat between per-run persists. `None` in tests, which drive the state machine directly.
+ heartbeat: Option<Handle>,
+ runs: HashMap<RunId, RunWatch>,
+ messages_since_flush: u64,
+ positions_advanced: bool,
+ /// A cohort completed since the last flush, which triggers an immediate one. Aggregated on
+ /// ingest because `should_flush` runs per record on a high-volume topic.
+ completion_pending: bool,
+ /// A seek is owed (a run was added or rebuilt, or the last seek failed transiently) but has not
+ /// succeeded yet. Cleared only by a successful seek, so a broker blip is retried on the next
+ /// directive publish instead of silently leaving the stream unassigned.
+ seek_pending: bool,
+ /// Dispatch epochs dropped because retention outran their watch start. PostgreSQL still
+ /// classifies such a run `Reconciling`, so the driver republishes its directive every tick;
+ /// without this the watcher would rebuild, re-seek, re-truncate and re-drop it forever — a
+ /// watermark sweep per tick, and a truncation counter that measures ticks instead of events.
+ /// Recovery is a re-dispatch, which mints a new epoch and is therefore not blocked.
+ truncated: HashMap<RunId, DispatchEpoch>,
+}
+
+impl<S: MarkerStream, F: MarkerFlush> WatchState<S, F> {
+ fn new(stream: S, flush: F, persist_max_batch: u64, heartbeat: Option<Handle>) -> Self {
+ Self {
+ stream,
+ flush,
+ persist_max_batch,
+ stream_coverage: StreamCoverage::default(),
+ heartbeat,
+ runs: HashMap::new(),
+ messages_since_flush: 0,
+ positions_advanced: false,
+ completion_pending: false,
+ seek_pending: false,
+ truncated: HashMap::new(),
+ }
+ }
+
+ /// Fold one record: advance every watched run's coverage and route any marker to its ledger.
+ /// While a seek is owed the stream still reads the pre-seek assignment, so advancing coverage or
+ /// folding would claim reads a rewound run has not made — the owed seek rewinds and these
+ /// records are re-read, so dropping them here loses nothing.
+ fn ingest(&mut self, item: WatchItem) {
+ if self.seek_pending {
+ return;
+ }
+ self.stream_coverage
+ .advance(item.partition, item.next_offset);
+ self.positions_advanced = true;
+ self.messages_since_flush += 1;
+ if let Some(marker) = item.marker {
+ let (fold, completed) = match self.runs.get_mut(&marker.run_id) {
+ Some(run) => (
+ run.ledger.observe(&marker),
+ run.ledger.completed_since_flush(),
+ ),
+ None => (MarkerFold::Unwatched, false),
+ };
+ self.completion_pending |= completed;
+ counter!(RECONCILE_MARKERS_OBSERVED, "fold" => fold.label()).increment(1);
+ }
+ }
+
+ fn should_flush(&self) -> bool {
+ self.messages_since_flush >= self.persist_max_batch || self.completion_pending
+ }
+
+ /// Fold the stream's reads into every watched run and reset. Every reader of `positions` calls
+ /// this first, and it must run before a run joins the set — a run may only ever claim offsets the
+ /// stream read while it was already watched.
+ fn materialize_coverage(&mut self) {
+ if self.stream_coverage.is_empty() {
+ return;
+ }
+ for run in self.runs.values_mut() {
+ self.stream_coverage.raise(&mut run.positions);
+ }
+ self.stream_coverage.clear();
+ }
+
+ /// Reconcile the watched-run set with a fresh directive snapshot, then re-seek if the set changed.
+ /// A run removed from the set (it left `reconciling`) is flushed once and dropped; a run whose
+ /// epoch changed (a re-dispatch) is rebuilt from the fresh directive.
+ ///
+ /// A seek happens only when a run was added or rebuilt (or a previous seek is still owed). An
+ /// added run's start can sit below the stream's current read position — markers there were
+ /// consumed before its ledger existed — so the seek rewinds to the minimum start across all
+ /// watched runs; re-reading is safe because bit folds and position advances are idempotent.
+ /// Steady-state republishes (same runs, same epochs) never re-seek.
+ async fn apply_directives(&mut self, directives: &WatchDirectives) {
+ // Before the set changes, so a run inserted below starts at its dispatch position rather than
+ // inheriting reads the stream made before its ledger existed.
+ self.materialize_coverage();
+ let incoming: HashSet<RunId> = directives.runs.iter().map(|d| d.run_id).collect();
+ let removed: Vec<RunId> = self
+ .runs
+ .keys()
+ .copied()
+ .filter(|run_id| !incoming.contains(run_id))
+ .collect();
+ let removed_any = !removed.is_empty();
+ for run_id in removed {
+ let _ = self.flush_run(run_id).await;
+ self.runs.remove(&run_id);
+ }
+ // A run the driver stopped publishing can be re-added cleanly, so its tombstone goes too.
+ self.truncated.retain(|run_id, _| incoming.contains(run_id));
+
+ for directive in &directives.runs {
+ if self.truncated.get(&directive.run_id) == Some(&directive.epoch) {
+ continue;
+ }
+ let rebuild = self
+ .runs
+ .get(&directive.run_id)
+ .is_none_or(|existing| existing.epoch != directive.epoch);
+ if rebuild {
+ self.truncated.remove(&directive.run_id);
+ self.runs
+ .insert(directive.run_id, RunWatch::from_directive(directive));
+ self.seek_pending = true;
+ }
+ }
+
+ // Losing the last watched run must release the assignment, not just stop folding.
+ if removed_any && self.runs.is_empty() {
+ self.seek_pending = true;
+ }
+
+ if self.seek_pending {
+ self.reassign().await;
+ }
+ }
+
+ /// Owe a seek and try to satisfy it now. A recv error can park a partition — an offset out of
+ /// range under `auto.offset.reset = error` leaves it dark — and nothing else would reassign
+ /// until the watched-run set happens to change.
+ async fn request_seek(&mut self) {
+ self.seek_pending = true;
+ self.reassign().await;
+ }
+
+ /// Seek the stream to the minimum start across all watched runs. A truncated start drops every
+ /// run whose coverage sits below the log's low watermark and retries with the raised floor.
+ async fn reassign(&mut self) {
+ self.materialize_coverage();
+ loop {
+ if self.runs.is_empty() {
+ // Stays owed until it lands, like the seek below: nothing else revisits an
+ // idle-but-still-assigned consumer.
+ match self.stream.unassign().await {
+ Ok(()) => self.seek_pending = false,
+ Err(error) => {
+ warn!(error = %error, "unassigning the idle marker watcher failed; retrying next directive")
+ }
+ }
+ return;
+ }
+ let start = min_start(self.runs.values());
+ if start.is_empty() {
+ self.seek_pending = false;
+ return;
+ }
+ match self.stream.seek(&start).await {
+ Ok(()) => {
+ self.seek_pending = false;
+ return;
+ }
+ Err(WatchError::Truncated {
+ partition,
+ requested,
+ low,
+ }) => {
+ let partition = MembershipPartition::new(partition);
+ // Drop against the log's low watermark, not just the rejected start: every run
+ // below it is equally unreadable, so one pass clears them all instead of one
+ // watermark round-trip per coverage level.
+ let floor = NextOffset::from_high_watermark(low);
+ let dropped: Vec<RunId> = self
+ .runs
+ .iter()
+ .filter(|(_, run)| {
+ run.positions
+ .get(partition)
+ .is_some_and(|coverage| coverage < floor)
+ })
+ .map(|(run_id, _)| *run_id)
+ .collect();
+ if dropped.is_empty() {
+ warn!(
+ partition = partition.get(),
+ requested,
+ low,
+ "marker watch reported truncation but no run sits below the low watermark"
+ );
+ return;
+ }
+ for run_id in dropped {
+ counter!(RECONCILE_WATCH_TRUNCATED).increment(1);
+ warn!(
+ run_id = ?run_id,
+ partition = partition.get(),
+ low,
+ "membership topic truncated past this run's watch start; dropping (re-dispatch to recover)"
+ );
+ if let Some(run) = self.runs.remove(&run_id) {
+ self.truncated.insert(run_id, run.epoch);
+ }
+ }
+ }
+ Err(error) => {
+ warn!(error = %error, "assigning the marker watcher failed; retrying next directive");
+ return;
+ }
+ }
+ }
+ }
+
+ /// Flush every watched run's dirty bits and the current positions, then reset the flush accounting.
+ async fn flush(&mut self) {
+ self.materialize_coverage();
+ let run_ids: Vec<RunId> = self.runs.keys().copied().collect();
+ let mut all_persisted = true;
+ for run_id in run_ids {
+ all_persisted &= self.flush_run(run_id).await;
+ // One round trip per run, all of it before the runner loop's own heartbeat: a large
+ // watched set must slow flushes down, not spend the whole liveness budget.
+ if let Some(handle) = &self.heartbeat {
+ handle.report_healthy();
+ }
+ }
+ self.messages_since_flush = 0;
+ // A failed persist holds both retry flags. For a run whose bits are clean but whose coverage
+ // moved, `positions_advanced` is the only thing `flush_run`'s guard retries on, and an idle
+ // topic never sets it again.
+ self.positions_advanced = !all_persisted;
+ self.completion_pending = self
+ .runs
+ .values()
+ .any(|run| run.ledger.completed_since_flush());
+ }
+
+ /// Persist one run's dirty bits and the watcher positions under its dispatch fence. A lost fence
+ /// drops the run (a re-dispatch superseded it); a transient error keeps the bits dirty for retry.
+ /// Returns whether the run has nothing left owed — `false` only on a transient error, so the
+ /// caller knows to keep the retry flag set.
+ async fn flush_run(&mut self, run_id: RunId) -> bool {
+ let Some(run) = self.runs.get(&run_id) else {
+ return true;
+ };
+ // Nothing to persist if neither the bits nor the positions moved since the last flush.
+ if !run.ledger.has_dirty() && !self.positions_advanced {
+ return true;
+ }
+ let epoch = run.epoch;
+ let dirty = run.ledger.dirty_bitmaps();
+ let positions = run.positions.clone();
+ match self.flush.persist(run_id, epoch, &dirty, &positions).await {
+ Ok(()) => {
+ if let Some(run) = self.runs.get_mut(&run_id) {
+ run.ledger.clear_dirty();
+ }
+ true
+ }
+ Err(CompletionStoreError::CompletionFenceLost { .. }) => {
+ info!(
+ run_id = ?run_id,
+ "marker watch lost the dispatch fence; dropping run (a re-dispatch superseded it)"
+ );
+ self.runs.remove(&run_id);
+ true
+ }
+ Err(error) => {
+ warn!(run_id = ?run_id, error = %error, "persisting marker observations failed; will retry");
+ false
+ }
+ }
+ }
+}
+
+/// The per-partition minimum fold coverage across all watched runs — where the stream must read from
+/// so every run's ledger sees everything it has not yet covered. Using coverage (not the original
+/// dispatch starts) keeps a late-added run's rewind from re-reading ranges established runs already
+/// folded and persisted.
+fn min_start<'a>(runs: impl Iterator<Item = &'a RunWatch>) -> WatchPositions {
+ let mut min = WatchPositions::new();
+ for run in runs {
+ for (partition, next) in run.positions.iter() {
+ match min.get(partition) {
+ Some(current) if current <= next => {}
+ _ => min.insert(partition, next),
+ }
+ }
+ }
+ min
+}
+
+/// The lifecycle-registered runner around a [`WatchState`].
+pub struct MarkerWatchTask<S, F> {
+ state: WatchState<S, F>,
+ directives: watch::Receiver<WatchDirectives>,
+ handle: Handle,
+ persist_interval: Duration,
+}
+
+impl<S: MarkerStream, F: MarkerFlush> MarkerWatchTask<S, F> {
+ pub fn new(
+ stream: S,
+ flush: F,
+ directives: watch::Receiver<WatchDirectives>,
+ handle: Handle,
+ persist_interval: Duration,
+ persist_max_batch: u64,
+ ) -> Self {
+ Self {
+ state: WatchState::new(stream, flush, persist_max_batch, Some(handle.clone())),
+ directives,
+ handle,
+ persist_interval,
+ }
+ }
+
+ /// Drive the fold loop until shutdown, then final-flush. A second lifecycle component: it reports
+ /// liveness on progress and drains on the shutdown token.
+ pub async fn run(mut self) {
+ let _scope = self.handle.process_scope();
+ let shutdown = self.handle.shutdown_token();
+ let mut flush_tick = tokio::time::interval(self.persist_interval);
+ flush_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
+ self.handle.report_healthy();
+
+ let initial = self.directives.borrow_and_update().clone();
+ self.state.apply_directives(&initial).await;
+
+ info!("marker watch task starting");
+ loop {
+ tokio::select! {
+ biased;
+ _ = shutdown.cancelled() => break,
+ changed = self.directives.changed() => {
+ if changed.is_err() {
+ break;
+ }
+ let directives = self.directives.borrow_and_update().clone();
+ self.state.apply_directives(&directives).await;
+ self.handle.report_healthy();
+ }
+ item = self.state.stream.recv() => {
+ match item {
+ Ok(item) => {
+ self.state.ingest(item);
+ if self.state.should_flush() {
+ self.state.flush().await;
+ }
+ self.handle.report_healthy();
+ }
+ Err(error) => {
+ warn!(error = %error, "receiving from the membership topic failed; backing off");
+ self.state.request_seek().await;
+ self.handle.report_healthy();
+ tokio::time::sleep(RECV_BACKOFF).await;
+ }
+ }
+ }
+ _ = flush_tick.tick() => {
+ self.state.flush().await;
+ self.handle.report_healthy();
+ }
+ }
+ }
+
+ self.state.flush().await;
+ info!("marker watch task stopped");
+ }
+}
+
+/// Backoff after a broker recv failure so a hard error does not spin the loop.
+const RECV_BACKOFF: Duration = Duration::from_millis(500);
+
+/// The watch task heartbeats at least once per flush tick (default 5 s), so a minute of silence means
+/// the loop is stuck, not idle.
+pub const MARKER_WATCH_LIVENESS_DEADLINE: Duration = Duration::from_secs(60);
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::collections::VecDeque;
+ use std::sync::Mutex;
+
+ use cohort_core::partitioner::COHORT_PARTITION_COUNT;
+ use uuid::Uuid;
+
+ use crate::domain::{MarkerPartition, ObservedMarker};
+ use crate::store::completion::CompletionOperation;
+
+ fn run(seed: u128) -> RunId {
+ RunId(Uuid::from_u128(seed))
+ }
+
+ fn start_at(partition: i32, offset: i64) -> WatchPositions {
+ let mut positions = WatchPositions::new();
+ positions.insert(
+ MembershipPartition::new(partition),
+ NextOffset::from_high_watermark(offset),
+ );
+ positions
+ }
+
+ fn directive(
+ run_id: RunId,
+ epoch_secs: i64,
+ start: WatchPositions,
+ cohorts: &[i32],
+ ) -> WatchDirective {
+ WatchDirective {
+ run_id,
+ team_id: TeamId(2),
+ epoch: epoch(epoch_secs),
+ start,
+ seeded: cohorts
+ .iter()
+ .map(|&cohort| (CohortId(cohort), PartitionBitmap::default()))
+ .collect(),
+ }
+ }
+
+ fn epoch(secs: i64) -> DispatchEpoch {
+ use chrono::TimeZone;
+ DispatchEpoch::from_dispatched_at(chrono::Utc.timestamp_opt(secs, 0).unwrap())
+ }
+
+ fn marker_item(partition: i32, offset: i64, run_id: RunId, cohort: i32, bit: u32) -> WatchItem {
+ WatchItem {
+ partition: MembershipPartition::new(partition),
+ next_offset: NextOffset::from_high_watermark(offset),
+ marker: Some(ObservedMarker {
+ team_id: TeamId(2),
+ cohort_id: CohortId(cohort),
+ partition: MarkerPartition::new(bit).unwrap(),
+ run_id,
+ }),
+ }
+ }
+
+ #[derive(Default)]
+ struct FakeStream {
+ seek_result: Mutex<Option<WatchError>>,
+ unassign_result: Mutex<Option<WatchError>>,
+ seeks: Vec<WatchPositions>,
+ unassigns: usize,
+ }
+
+ #[async_trait]
+ impl MarkerStream for FakeStream {
+ async fn seek(&mut self, start: &WatchPositions) -> Result<(), WatchError> {
+ match self.seek_result.lock().unwrap().take() {
+ Some(error) => Err(error),
+ None => {
+ self.seeks.push(start.clone());
+ Ok(())
+ }
+ }
+ }
+
+ async fn unassign(&mut self) -> Result<(), WatchError> {
+ self.unassigns += 1;
+ match self.unassign_result.lock().unwrap().take() {
+ Some(error) => Err(error),
+ None => Ok(()),
+ }
+ }
+
+ async fn recv(&mut self) -> Result<WatchItem, WatchError> {
+ std::future::pending().await
+ }
+ }
+
+ #[derive(Clone, Debug, PartialEq, Eq)]
+ struct FlushCall {
+ run_id: RunId,
+ bits: Vec<(CohortId, PartitionBitmap)>,
+ positions: WatchPositions,
+ }
+
+ #[derive(Default)]
+ struct FakeFlush {
+ calls: Mutex<Vec<FlushCall>>,
+ fence_lost: Mutex<VecDeque<RunId>>,
+ transient: Mutex<VecDeque<RunId>>,
+ }
+
+ impl FakeFlush {
+ fn lose_fence(&self, run_id: RunId) {
+ self.fence_lost.lock().unwrap().push_back(run_id);
+ }
+
+ fn fail_once(&self, run_id: RunId) {
+ self.transient.lock().unwrap().push_back(run_id);
+ }
+
+ fn calls(&self) -> Vec<FlushCall> {
+ self.calls.lock().unwrap().clone()
+ }
+ }
+
+ #[async_trait]
+ impl MarkerFlush for FakeFlush {
+ async fn persist(
+ &self,
+ run_id: RunId,
+ _epoch: DispatchEpoch,
+ bits: &[(CohortId, PartitionBitmap)],
+ positions: &WatchPositions,
+ ) -> Result<(), CompletionStoreError> {
+ if self
+ .fence_lost
+ .lock()
+ .unwrap()
+ .front()
+ .is_some_and(|lost| *lost == run_id)
+ {
+ self.fence_lost.lock().unwrap().pop_front();
+ return Err(CompletionStoreError::CompletionFenceLost {
+ run_id,
+ operation: CompletionOperation::PersistObservations,
+ });
+ }
+ if self
+ .transient
+ .lock()
+ .unwrap()
+ .front()
+ .is_some_and(|failing| *failing == run_id)
+ {
+ self.transient.lock().unwrap().pop_front();
+ return Err(CompletionStoreError::Pg(sqlx::Error::PoolClosed));
+ }
+ self.calls.lock().unwrap().push(FlushCall {
+ run_id,
+ bits: bits.to_vec(),
+ positions: positions.clone(),
+ });
+ Ok(())
+ }
+ }
+
+ fn make_state(flush: FakeFlush, max_batch: u64) -> WatchState<FakeStream, FakeFlush> {
+ WatchState::new(FakeStream::default(), flush, max_batch, None)
+ }
+
+ #[tokio::test]
+ async fn batch_cap_and_completion_trigger_flushes() {
+ let run_id = run(1);
+ let mut state = make_state(FakeFlush::default(), 3);
+ state
+ .apply_directives(&WatchDirectives {
+ runs: vec![directive(run_id, 100, start_at(0, 0), &[10])],
+ })
+ .await;
+
+ // Two non-marker rows: below the batch cap, no flush.
+ for offset in 1..=2 {
+ state.ingest(WatchItem {
+ partition: MembershipPartition::new(0),
+ next_offset: NextOffset::from_high_watermark(offset),
+ marker: None,
+ });
+ }
+ assert!(
+ !state.should_flush(),
+ "two of three messages does not flush"
+ );
+
+ // The third crosses the batch cap.
+ state.ingest(marker_item(0, 3, run_id, 10, 0));
+ assert!(state.should_flush(), "the batch cap triggers a flush");
+
+ // Completing a cohort triggers a flush regardless of the batch cap.
+ let mut fresh = make_state(FakeFlush::default(), 10_000);
+ fresh
+ .apply_directives(&WatchDirectives {
+ runs: vec![directive(run_id, 100, start_at(0, 0), &[10])],
+ })
+ .await;
+ for bit in 0..COHORT_PARTITION_COUNT {
+ fresh.ingest(marker_item(0, i64::from(bit) + 1, run_id, 10, bit));
+ }
+ assert!(
+ fresh.should_flush(),
+ "a completed cohort triggers an immediate flush"
+ );
+ }
+
+ #[tokio::test]
+ async fn flush_persists_dirty_bits_then_clears_them() {
+ let run_id = run(1);
+ let flush = FakeFlush::default();
+ let mut state = make_state(flush, 10_000);
+ state
+ .apply_directives(&WatchDirectives {
+ runs: vec![directive(run_id, 100, start_at(0, 0), &[10])],
+ })
+ .await;
+
+ state.ingest(marker_item(0, 1, run_id, 10, 5));
+ state.flush().await;
+ let first = state.flush.calls();
+ assert_eq!(first.len(), 1);
+ assert_eq!(first[0].run_id, run_id);
+ assert_eq!(first[0].bits.len(), 1, "the dirty cohort is persisted");
+
+ // A second flush with no new bits and no advanced positions is a no-op.
+ state.flush().await;
+ assert_eq!(
+ state.flush.calls().len(),
+ 1,
+ "a clean run is not re-flushed"
+ );
+ }
+
+ #[tokio::test]
+ async fn a_failed_persist_is_retried_without_new_traffic() {
+ // Coverage advanced but the bits are already clean, so `positions_advanced` is the only
+ // thing that gets this run flushed again. Clearing it after a failed persist would strand
+ // the run's positions below its captured ends forever on an idle topic.
+ let run_id = run(1);
+ let flush = FakeFlush::default();
+ flush.fail_once(run_id);
+ let mut state = make_state(flush, 10_000);
+ state
+ .apply_directives(&WatchDirectives {
+ runs: vec![directive(run_id, 100, start_at(0, 0), &[10])],
+ })
+ .await;
+
+ state.ingest(WatchItem {
+ partition: MembershipPartition::new(0),
+ next_offset: NextOffset::from_high_watermark(1),
+ marker: None,
+ });
+ state.flush().await;
+ assert!(state.flush.calls().is_empty(), "the persist failed");
+
+ state.flush().await;
+ assert_eq!(
+ state.flush.calls().len(),
+ 1,
+ "the next flush retries without waiting for new traffic"
+ );
+ }
+
+ #[tokio::test]
+ async fn a_run_joining_late_does_not_inherit_earlier_reads() {
+ // Coverage is folded in from one shared stream position, so the fold has to land before a run
+ // joins. A run that inherited reads made before its ledger existed could settle without ever
+ // having seen its own markers.
+ let early = run(1);
+ let late = run(2);
+ let mut state = make_state(FakeFlush::default(), 10_000);
+ state
+ .apply_directives(&WatchDirectives {
+ runs: vec![directive(early, 100, start_at(0, 0), &[10])],
+ })
+ .await;
+
+ for offset in 1..=100 {
+ state.ingest(WatchItem {
+ partition: MembershipPartition::new(0),
+ next_offset: NextOffset::from_high_watermark(offset),
+ marker: None,
+ });
+ }
+
+ state
+ .apply_directives(&WatchDirectives {
+ runs: vec![
+ directive(early, 100, start_at(0, 0), &[10]),
+ directive(late, 100, start_at(0, 50), &[11]),
+ ],
+ })
+ .await;
+ state.flush().await;
+
+ let calls = state.flush.calls();
+ let persisted = |run_id| {
+ calls
+ .iter()
+ .filter(|call| call.run_id == run_id)
+ .next_back()
+ .and_then(|call| call.positions.get(MembershipPartition::new(0)))
+ };
+ assert_eq!(
+ persisted(early),
+ Some(NextOffset::from_high_watermark(100)),
+ "the run watched throughout keeps every read the stream made"
+ );
+ assert_eq!(
+ persisted(late),
+ Some(NextOffset::from_high_watermark(50)),
+ "a run that joined after those reads stays at its dispatch start"
+ );
+ }
+
+ #[tokio::test]
+ async fn lost_fence_drops_the_run() {
+ let run_id = run(1);
+ let flush = FakeFlush::default();
+ flush.lose_fence(run_id);
+ let mut state = make_state(flush, 10_000);
+ state
+ .apply_directives(&WatchDirectives {
+ runs: vec![directive(run_id, 100, start_at(0, 0), &[10])],
+ })
+ .await;
+
+ state.ingest(marker_item(0, 1, run_id, 10, 5));
+ state.flush().await;
+ assert!(
+ !state.runs.contains_key(&run_id),
+ "a lost dispatch fence drops the run locally"
+ );
+ assert!(
+ state.flush.calls().is_empty(),
+ "the lost-fence flush persisted nothing"
+ );
+ }
+
+ #[tokio::test]
+ async fn truncated_start_drops_the_run_and_tombstones_its_epoch() {
+ let early = run(1);
+ let later = run(2);
+ let mut state = make_state(FakeFlush::default(), 10_000);
+ let truncated = || WatchError::Truncated {
+ partition: 0,
+ requested: 5,
+ low: 20,
+ };
+ *state.stream.seek_result.lock().unwrap() = Some(truncated());
+ let published = WatchDirectives {
+ runs: vec![
+ directive(early, 100, start_at(0, 5), &[10]),
+ directive(later, 100, start_at(0, 50), &[11]),
+ ],
+ };
+
+ state.apply_directives(&published).await;
+
+ assert!(
+ !state.runs.contains_key(&early),
+ "the run below the low watermark is dropped"
+ );
+ assert!(
+ state.runs.contains_key(&later),
+ "a run above the low watermark keeps being watched"
+ );
+
+ // The driver republishes the dropped run every tick (PostgreSQL still calls it reconciling).
+ // Re-adding it would re-seek, re-truncate and re-drop it forever.
+ state.stream.seeks.clear();
+ *state.stream.seek_result.lock().unwrap() = Some(truncated());
+ state.apply_directives(&published).await;
+ assert!(!state.runs.contains_key(&early));
+ assert!(
+ state.stream.seeks.is_empty(),
+ "a tombstoned run must not provoke another seek"
+ );
+
+ // A re-dispatch mints a fresh epoch, which is the documented recovery.
+ *state.stream.seek_result.lock().unwrap() = None;
+ state
+ .apply_directives(&WatchDirectives {
+ runs: vec![
+ directive(early, 200, start_at(0, 50), &[10]),
+ directive(later, 100, start_at(0, 50), &[11]),
+ ],
+ })
+ .await;
+ assert!(
+ state.runs.contains_key(&early),
+ "a re-dispatched epoch is watched again"
+ );
+ }
+
+ #[tokio::test]
+ async fn seeks_happen_only_when_a_run_is_added_or_rebuilt() {
+ let run_a = run(1);
+ let run_b = run(2);
+ let mut state = make_state(FakeFlush::default(), 10_000);
+
+ // Adding a run seeks once.
+ let first = WatchDirectives {
+ runs: vec![directive(run_a, 100, start_at(0, 100), &[10])],
+ };
+ state.apply_directives(&first).await;
+ assert_eq!(state.stream.seeks.len(), 1);
+
+ // A steady-state republish of the same set does not re-seek.
+ state.apply_directives(&first).await;
+ assert_eq!(
+ state.stream.seeks.len(),
+ 1,
+ "unchanged set must not re-seek"
+ );
+
+ // Adding a second run re-seeks to the minimum start across runs, so markers consumed before
+ // its ledger existed are re-read.
+ state
+ .apply_directives(&WatchDirectives {
+ runs: vec![
+ directive(run_a, 100, start_at(0, 100), &[10]),
+ directive(run_b, 100, start_at(0, 50), &[11]),
+ ],
+ })
+ .await;
+ assert_eq!(state.stream.seeks.len(), 2);
+ assert_eq!(
+ state.stream.seeks[1].get(MembershipPartition::new(0)),
+ Some(NextOffset::from_high_watermark(50)),
+ "the seek rewinds to the earliest watched start"
+ );
+
+ // Losing the last run releases the assignment instead of leaving the consumer fetching a
+ // high-volume topic for nobody.
+ state.apply_directives(&WatchDirectives::default()).await;
+ assert!(state.runs.is_empty());
+ assert_eq!(state.stream.unassigns, 1);
+ assert_eq!(state.stream.seeks.len(), 2, "an idle watcher does not seek");
+ }
+
+ #[tokio::test]
+ async fn a_failed_unassign_stays_owed_and_retries() {
+ // Nothing re-triggers the release once the set is already empty, so clearing the owed work
+ // on a failed unassign would leak the assignment until a new run is dispatched.
+ let run_id = run(1);
+ let mut state = make_state(FakeFlush::default(), 10_000);
+ state
+ .apply_directives(&WatchDirectives {
+ runs: vec![directive(run_id, 100, start_at(0, 0), &[10])],
+ })
+ .await;
+
+ *state.stream.unassign_result.lock().unwrap() =
+ Some(WatchError::Consumer(rdkafka::error::KafkaError::Canceled));
+ state.apply_directives(&WatchDirectives::default()).await;
+ assert_eq!(state.stream.unassigns, 1);
+ assert!(state.seek_pending, "a failed unassign stays owed");
+
+ // A steady-state republish of the still-empty set retries it.
+ state.apply_directives(&WatchDirectives::default()).await;
+ assert_eq!(state.stream.unassigns, 2);
+ assert!(!state.seek_pending, "the retry cleared the owed release");
+ }
+
+ #[tokio::test]
+ async fn flush_persists_start_coverage_for_idle_partitions() {
+ // The directive's start covers two partitions; traffic arrives on only one. The flush must
+ // still persist the idle partition at its dispatch start, or an idle membership partition
+ // would hold `caught_up` (and every negative-verdict settlement) open forever.
+ let run_id = run(1);
+ let mut start = start_at(0, 10);
+ start.insert(
+ MembershipPartition::new(1),
+ NextOffset::from_high_watermark(7),
+ );
+ let mut state = make_state(FakeFlush::default(), 10_000);
+ state
+ .apply_directives(&WatchDirectives {
+ runs: vec![directive(run_id, 100, start, &[10])],
+ })
+ .await;
+
+ state.ingest(marker_item(0, 11, run_id, 10, 5));
+ state.flush().await;
+
+ let calls = state.flush.calls();
+ assert_eq!(calls.len(), 1);
+ assert_eq!(
+ calls[0].positions.get(MembershipPartition::new(0)),
+ Some(NextOffset::from_high_watermark(11)),
+ "the read partition advances to the ingested record's next offset"
+ );
+ assert_eq!(
+ calls[0].positions.get(MembershipPartition::new(1)),
+ Some(NextOffset::from_high_watermark(7)),
+ "the idle partition stays covered at its dispatch start"
+ );
+ }
+
+ #[tokio::test]
+ async fn records_while_a_seek_is_owed_are_dropped_not_claimed() {
+ // A transient seek failure leaves the stream on its pre-seek assignment. Folding or
+ // advancing coverage from those records would claim reads the rewound run never made.
+ let run_id = run(1);
+ let mut state = make_state(FakeFlush::default(), 10_000);
+ *state.stream.seek_result.lock().unwrap() =
+ Some(WatchError::Consumer(rdkafka::error::KafkaError::Canceled));
+ state
+ .apply_directives(&WatchDirectives {
+ runs: vec![directive(run_id, 100, start_at(0, 10), &[10])],
+ })
+ .await;
+ assert!(state.seek_pending, "the failed seek stays owed");
+
+ state.ingest(marker_item(0, 500, run_id, 10, 5));
+ assert!(
+ !state.runs[&run_id].ledger.has_dirty(),
+ "a record read on the stale assignment is not folded"
+ );
+ assert_eq!(
+ state.runs[&run_id]
+ .positions
+ .get(MembershipPartition::new(0)),
+ Some(NextOffset::from_high_watermark(10)),
+ "coverage stays at the dispatch start until the seek lands"
+ );
+
+ // The next directive publish retries the seek; once it lands, records count again.
+ state
+ .apply_directives(&WatchDirectives {
+ runs: vec![directive(run_id, 100, start_at(0, 10), &[10])],
+ })
+ .await;
+ assert!(!state.seek_pending);
+ state.ingest(marker_item(0, 11, run_id, 10, 5));
+ assert!(state.runs[&run_id].ledger.has_dirty());
+ }
+
+ #[tokio::test]
+ async fn re_dispatch_epoch_change_rebuilds_the_ledger() {
+ let run_id = run(1);
+ let mut state = make_state(FakeFlush::default(), 10_000);
+ state
+ .apply_directives(&WatchDirectives {
+ runs: vec![directive(run_id, 100, start_at(0, 0), &[10])],
+ })
+ .await;
+ state.ingest(marker_item(0, 1, run_id, 10, 5));
+ assert!(state.runs[&run_id].ledger.has_dirty());
+
+ // A fresh epoch (re-dispatch) rebuilds the fold from the fresh directive's seeded bits.
+ state
+ .apply_directives(&WatchDirectives {
+ runs: vec![directive(run_id, 200, start_at(0, 0), &[10])],
+ })
+ .await;
+ assert!(
+ !state.runs[&run_id].ledger.has_dirty(),
+ "a re-dispatch resets the in-memory fold"
+ );
+ }
+}
diff --git a/rust/cohort-seeder/src/config.rs b/rust/cohort-seeder/src/config.rs
index dc0035b8bdee..1c7bc9b9ef3e 100644
--- a/rust/cohort-seeder/src/config.rs
+++ b/rust/cohort-seeder/src/config.rs
@@ -210,9 +210,34 @@ pub struct Config {
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.
+ /// positions, captured at dispatch time. The observer reads markers from the same topic.
#[envconfig(default = "cohort_membership_changed_shadow")]
pub cohort_membership_changed_topic: String,
+
+ /// Enable the dark-by-default reconcile observer: the marker-watch task and the driver's
+ /// observation pass. A separate gate from auto-dispatch — observation can run against
+ /// CLI-dispatched runs without auto-dispatch, and vice versa.
+ #[envconfig(default = "false")]
+ pub seeder_reconcile_observer_enabled: bool,
+
+ /// The seed processor's consumer group id. The observer queries this group's committed offsets on
+ /// the seed topic as the reconcile-liveness signal; it never commits to it.
+ #[envconfig(default = "cohort-stream-seeds")]
+ pub kafka_seed_consumer_group: String,
+
+ /// Timeout for the seed-group OffsetFetch and membership-topic watermark metadata calls the
+ /// observer makes.
+ #[envconfig(default = "10000")]
+ pub seeder_reconcile_offsets_timeout_ms: u64,
+
+ /// Flush the marker watcher's accumulated bits and positions at least this often.
+ #[envconfig(default = "5000")]
+ pub seeder_reconcile_persist_interval_ms: u64,
+
+ /// Flush the marker watcher after this many consumed messages even if the interval has not
+ /// elapsed, bounding how many observations a crash can lose.
+ #[envconfig(default = "5000")]
+ pub seeder_reconcile_persist_max_batch: u64,
}
impl Config {
diff --git a/rust/cohort-seeder/src/domain/completion.rs b/rust/cohort-seeder/src/domain/completion.rs
index c7b9d30b6c43..6f2ee20eeeb0 100644
--- a/rust/cohort-seeder/src/domain/completion.rs
+++ b/rust/cohort-seeder/src/domain/completion.rs
@@ -1,5 +1,5 @@
-//! 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
+//! Pure completion-protocol domain: the types the auto-dispatch producer mints and the observer
+//! 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.
@@ -312,6 +312,29 @@ impl WatchPositions {
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
+
+ pub fn iter(&self) -> impl Iterator<Item = (MembershipPartition, NextOffset)> + '_ {
+ self.0
+ .iter()
+ .map(|(&partition, &offset)| (partition, offset))
+ }
+
+ /// Advance a partition's position to the later of its current and `offset`. The watcher reads a
+ /// single global consumer, so positions must never regress even when a re-assignment re-reads an
+ /// earlier offset; taking the max keeps the persisted resume state monotone.
+ ///
+ /// A partition this position set does not already name is ignored rather than inserted. Such a
+ /// partition appeared after the dispatch captured its start offsets, so the run never read it
+ /// from the beginning; inserting it would claim coverage of everything below `offset`. Leaving
+ /// it absent keeps [`ObservationEnds::caught_up`] fail-closed — the run holds until a
+ /// re-dispatch recaptures a start position for it.
+ pub fn advance(&mut self, partition: MembershipPartition, offset: NextOffset) {
+ if let Some(current) = self.0.get_mut(&partition) {
+ if offset > *current {
+ *current = offset;
+ }
+ }
+ }
}
impl Serialize for WatchPositions {
@@ -341,8 +364,23 @@ impl ObservationEnds {
self.0.insert(partition, offset);
}
- pub fn is_empty(&self) -> bool {
- self.0.is_empty()
+ /// The membership end-watermarks captured at the liveness pass have the same shape as the
+ /// watcher's start positions — both are next-to-read offsets keyed by membership partition.
+ pub fn from_positions(positions: &WatchPositions) -> Self {
+ Self(positions.0.clone())
+ }
+
+ /// How many captured-end partitions the watcher has not yet read to — the reconcile marker-watch
+ /// lag, for the observer's hold gauge. Zero exactly when [`Self::caught_up`] mints a proof.
+ pub fn behind(&self, positions: &WatchPositions) -> usize {
+ self.0
+ .iter()
+ .filter(|(partition, end)| {
+ positions
+ .get(**partition)
+ .is_none_or(|position| position.get() < end.get())
+ })
+ .count()
}
/// A [`SettleProof`] is minted only when the watcher has read to or past every captured end. A
@@ -375,7 +413,7 @@ impl<'de> Deserialize<'de> for ObservationEnds {
}
/// 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
+/// token: `MarkerLedger::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(());
@@ -447,7 +485,7 @@ impl DispatchEpoch {
}
}
-/// One observed `reconcile_complete` marker, fed to PR-C's ledger fold.
+/// One observed `reconcile_complete` marker, fed to the ledger fold.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ObservedMarker {
pub team_id: TeamId,
@@ -474,7 +512,8 @@ pub struct DispatchedReconcile {
/// 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.
+ /// `reconcile_dispatched_at` is NULL: a CAS-then-crash, or a run reconciled by hand before the
+ /// dispatch record existed.
NeverDispatched,
/// The dispatch stamp is set but `reconcile_hwms` or `marker_watch` is missing.
MissingRecord,
@@ -731,6 +770,36 @@ mod tests {
assert!(serde_json::from_value::<ReconcileHwms>(serde_json::json!({"0": 5})).is_err());
}
+ #[test]
+ fn advance_is_monotone_and_ignores_partitions_it_does_not_track() {
+ // Both guards feed `caught_up`. Regressing a position would rewind persisted coverage;
+ // inserting an untracked partition would claim coverage of everything below `offset`.
+ let tracked = MembershipPartition::new(0);
+ let untracked = MembershipPartition::new(1);
+ let mut positions = WatchPositions::new();
+ positions.insert(tracked, NextOffset::from_high_watermark(10));
+
+ positions.advance(tracked, NextOffset::from_high_watermark(20));
+ assert_eq!(
+ positions.get(tracked),
+ Some(NextOffset::from_high_watermark(20))
+ );
+
+ positions.advance(tracked, NextOffset::from_high_watermark(5));
+ assert_eq!(
+ positions.get(tracked),
+ Some(NextOffset::from_high_watermark(20)),
+ "a re-assignment re-reading an earlier offset must not regress coverage"
+ );
+
+ positions.advance(untracked, NextOffset::from_high_watermark(99));
+ assert_eq!(
+ positions.get(untracked),
+ None,
+ "a partition with no captured start is never claimed as covered"
+ );
+ }
+
#[test]
fn caught_up_passes_at_the_end_and_fails_one_short() {
let mut ends = ObservationEnds::new();
diff --git a/rust/cohort-seeder/src/domain/ledger.rs b/rust/cohort-seeder/src/domain/ledger.rs
new file mode 100644
index 000000000000..8fbc8b0d26bd
--- /dev/null
+++ b/rust/cohort-seeder/src/domain/ledger.rs
@@ -0,0 +1,364 @@
+//! Pure per-run fold of observed `reconcile_complete` markers into per-cohort partition bitmaps.
+//!
+//! The marker watcher's dedicated task reads *all* membership partitions and hands each marker
+//! to the ledger of the run it names. Folding is a monotone set-union: a partition's bit, once set,
+//! never clears, so replaying the same marker stream in any order yields the same bitmaps. The final
+//! per-cohort outcome (complete / partial) is reachable only through [`MarkerLedger::settle`], which
+//! consumes a [`SettleProof`] — the capability minted in [`super::completion`] once the watcher has
+//! read past the membership end-watermarks captured at the liveness pass. No proof, no negative
+//! verdict.
+
+use std::collections::BTreeMap;
+
+use cohort_core::filters::{CohortId, TeamId};
+
+use super::completion::{MarkerNovelty, ObservedMarker, PartitionBitmap, SettleProof};
+use super::ids::RunId;
+
+/// How one observed marker was routed. Only [`Novel`](MarkerFold::Novel) mutates a bitmap; the rest
+/// are accounted (via the `fold` metric label) and dropped, never errors — the watcher reads a shared
+/// topic carrying every run's and team's markers.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum MarkerFold {
+ /// A marker for one of this run's cohorts, setting a bit for the first time.
+ Novel,
+ /// A marker for one of this run's cohorts whose bit was already set.
+ Duplicate,
+ /// This run's team, but a different run — folded into another ledger.
+ ForeignRun,
+ /// A different team entirely.
+ ForeignTeam,
+ /// This run, but a cohort it does not track (superseded and excluded by the caller, or garbage).
+ UnknownCohort,
+ /// No ledger names this run. Decided by the watcher before any ledger sees the marker, and the
+ /// dominant outcome since the watcher tails a topic carrying every run's markers.
+ Unwatched,
+}
+
+impl MarkerFold {
+ /// The metric label for `seeder_reconcile_markers_observed_total{fold}`.
+ pub const fn label(self) -> &'static str {
+ match self {
+ Self::Novel => "novel",
+ Self::Duplicate => "duplicate",
+ Self::ForeignRun => "foreign_run",
+ Self::ForeignTeam => "foreign_team",
+ Self::UnknownCohort => "unknown_cohort",
+ Self::Unwatched => "unwatched",
+ }
+ }
+}
+
+/// The settled per-cohort verdict for a run, reachable only with a [`SettleProof`].
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum SettledVerdict {
+ /// Every tracked cohort reached its full partition set.
+ AllComplete,
+ /// A mix: `complete` reached the full set, `incomplete` did not (each with its observed bitmap so
+ /// the caller can name the missing partitions).
+ Partial {
+ complete: Vec<CohortId>,
+ incomplete: Vec<(CohortId, PartitionBitmap)>,
+ },
+ /// Not a single marker was observed for any tracked cohort — the degenerate all-empty case that
+ /// signals a fleet-wide reconcile gate-off.
+ NoMarkers,
+}
+
+/// One tracked cohort's fold state.
+#[derive(Debug, Clone, Copy)]
+struct CohortFold {
+ bitmap: PartitionBitmap,
+ /// A bit was set since the last [`MarkerLedger::clear_dirty`]. Drives incremental flushes.
+ dirty: bool,
+ /// The bitmap reached its full set since the last [`MarkerLedger::clear_dirty`]. Drives the
+ /// flush-on-completion trigger.
+ newly_complete: bool,
+}
+
+/// A run's marker fold: its identity plus the per-cohort bitmaps it accumulates. Seeded from the bits
+/// already persisted so a resumed watcher continues the fold rather than restarting it.
+#[derive(Debug, Clone)]
+pub struct MarkerLedger {
+ run_id: RunId,
+ team_id: TeamId,
+ cohorts: BTreeMap<CohortId, CohortFold>,
+}
+
+impl MarkerLedger {
+ /// Build a ledger for one run over its non-superseded cohorts and their already-persisted bitmaps.
+ /// A cohort absent from `seeded` is not tracked; a marker for it folds as [`MarkerFold::UnknownCohort`].
+ pub fn new(
+ run_id: RunId,
+ team_id: TeamId,
+ seeded: impl IntoIterator<Item = (CohortId, PartitionBitmap)>,
+ ) -> Self {
+ let cohorts = seeded
+ .into_iter()
+ .map(|(cohort_id, bitmap)| {
+ (
+ cohort_id,
+ CohortFold {
+ bitmap,
+ dirty: false,
+ newly_complete: false,
+ },
+ )
+ })
+ .collect();
+ Self {
+ run_id,
+ team_id,
+ cohorts,
+ }
+ }
+
+ pub const fn run_id(&self) -> RunId {
+ self.run_id
+ }
+
+ /// Fold one observed marker. Routing is pure: team, then run, then cohort membership. Only a
+ /// marker naming this run and a tracked cohort touches a bitmap.
+ pub fn observe(&mut self, marker: &ObservedMarker) -> MarkerFold {
+ if marker.team_id != self.team_id {
+ return MarkerFold::ForeignTeam;
+ }
+ if marker.run_id != self.run_id {
+ return MarkerFold::ForeignRun;
+ }
+ let Some(fold) = self.cohorts.get_mut(&marker.cohort_id) else {
+ return MarkerFold::UnknownCohort;
+ };
+ match fold.bitmap.set(marker.partition) {
+ MarkerNovelty::Duplicate => MarkerFold::Duplicate,
+ MarkerNovelty::Novel => {
+ fold.dirty = true;
+ if fold.bitmap.is_complete() {
+ fold.newly_complete = true;
+ }
+ MarkerFold::Novel
+ }
+ }
+ }
+
+ /// Every tracked cohort is complete. Monotone (bits never clear) and usable without a proof: it
+ /// only ever flips from false to true, so it is safe as an early-exit signal. A ledger with no
+ /// tracked cohorts is vacuously complete.
+ pub fn all_complete(&self) -> bool {
+ self.cohorts.values().all(|fold| fold.bitmap.is_complete())
+ }
+
+ /// The cohorts whose bitmap changed since the last [`Self::clear_dirty`], with their current bits.
+ /// Flushed through the idempotent OR-merge persist, so re-flushing the same bits is a no-op.
+ pub fn dirty_bitmaps(&self) -> Vec<(CohortId, PartitionBitmap)> {
+ self.cohorts
+ .iter()
+ .filter(|(_, fold)| fold.dirty)
+ .map(|(cohort_id, fold)| (*cohort_id, fold.bitmap))
+ .collect()
+ }
+
+ pub fn has_dirty(&self) -> bool {
+ self.cohorts.values().any(|fold| fold.dirty)
+ }
+
+ /// A cohort reached its full partition set since the last [`Self::clear_dirty`]. The watcher
+ /// flushes immediately on this so a completed cohort's outcome is durable without waiting a tick.
+ pub fn completed_since_flush(&self) -> bool {
+ self.cohorts.values().any(|fold| fold.newly_complete)
+ }
+
+ /// Clear the incremental-flush flags after a successful persist. Bitmaps are untouched.
+ pub fn clear_dirty(&mut self) {
+ for fold in self.cohorts.values_mut() {
+ fold.dirty = false;
+ fold.newly_complete = false;
+ }
+ }
+
+ /// Settle the run: split tracked cohorts into complete and incomplete. Consumes the ledger and the
+ /// [`SettleProof`], so a caller cannot record a negative outcome without first proving the marker
+ /// set for this dispatch was fully observed.
+ pub fn settle(self, _proof: SettleProof) -> SettledVerdict {
+ let mut complete = Vec::new();
+ let mut incomplete = Vec::new();
+ let mut any_bit = false;
+ for (cohort_id, fold) in self.cohorts {
+ if !fold.bitmap.is_empty() {
+ any_bit = true;
+ }
+ if fold.bitmap.is_complete() {
+ complete.push(cohort_id);
+ } else {
+ incomplete.push((cohort_id, fold.bitmap));
+ }
+ }
+ if incomplete.is_empty() {
+ SettledVerdict::AllComplete
+ } else if !any_bit {
+ SettledVerdict::NoMarkers
+ } else {
+ SettledVerdict::Partial {
+ complete,
+ incomplete,
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use cohort_core::partitioner::COHORT_PARTITION_COUNT;
+ use uuid::Uuid;
+
+ use crate::domain::MarkerPartition;
+
+ fn marker(team: i32, cohort: i32, run: RunId, partition: u32) -> ObservedMarker {
+ ObservedMarker {
+ team_id: TeamId(team),
+ cohort_id: CohortId(cohort),
+ partition: MarkerPartition::new(partition).unwrap(),
+ run_id: run,
+ }
+ }
+
+ fn run(seed: u128) -> RunId {
+ RunId(Uuid::from_u128(seed))
+ }
+
+ fn ledger(cohorts: &[i32]) -> MarkerLedger {
+ MarkerLedger::new(
+ run(1),
+ TeamId(2),
+ cohorts
+ .iter()
+ .map(|&cohort| (CohortId(cohort), PartitionBitmap::default())),
+ )
+ }
+
+ fn complete_cohort(ledger: &mut MarkerLedger, cohort: i32) {
+ for partition in 0..COHORT_PARTITION_COUNT {
+ ledger.observe(&marker(2, cohort, run(1), partition));
+ }
+ }
+
+ #[test]
+ fn observe_routes_every_fold_variant() {
+ let mut ledger = ledger(&[10]);
+ assert_eq!(ledger.observe(&marker(2, 10, run(1), 0)), MarkerFold::Novel);
+ assert_eq!(
+ ledger.observe(&marker(2, 10, run(1), 0)),
+ MarkerFold::Duplicate
+ );
+ assert_eq!(
+ ledger.observe(&marker(2, 10, run(9), 0)),
+ MarkerFold::ForeignRun
+ );
+ assert_eq!(
+ ledger.observe(&marker(7, 10, run(1), 0)),
+ MarkerFold::ForeignTeam
+ );
+ assert_eq!(
+ ledger.observe(&marker(2, 99, run(1), 0)),
+ MarkerFold::UnknownCohort
+ );
+ }
+
+ #[test]
+ fn fold_is_order_independent() {
+ let markers = [
+ marker(2, 10, run(1), 3),
+ marker(2, 11, run(1), 0),
+ marker(2, 10, run(1), 1),
+ marker(2, 10, run(1), 3),
+ marker(2, 11, run(1), 5),
+ ];
+
+ let mut forward = ledger(&[10, 11]);
+ for m in &markers {
+ forward.observe(m);
+ }
+ let mut backward = ledger(&[10, 11]);
+ for m in markers.iter().rev() {
+ backward.observe(m);
+ }
+
+ assert_eq!(forward.dirty_bitmaps(), backward.dirty_bitmaps());
+ }
+
+ #[test]
+ fn all_complete_is_monotone_and_ignores_untracked_state() {
+ let mut both = ledger(&[10, 11]);
+ assert!(!both.all_complete());
+ complete_cohort(&mut both, 10);
+ assert!(!both.all_complete(), "one cohort short is not complete");
+ complete_cohort(&mut both, 11);
+ assert!(both.all_complete());
+
+ // Vacuously complete with nothing to track.
+ assert!(ledger(&[]).all_complete());
+ }
+
+ #[test]
+ fn dirty_and_completion_flags_track_flushes() {
+ let mut ledger = ledger(&[10, 11]);
+ assert!(!ledger.has_dirty());
+
+ ledger.observe(&marker(2, 10, run(1), 0));
+ assert!(ledger.has_dirty());
+ assert!(!ledger.completed_since_flush());
+ assert_eq!(ledger.dirty_bitmaps().len(), 1);
+
+ complete_cohort(&mut ledger, 10);
+ assert!(ledger.completed_since_flush());
+
+ ledger.clear_dirty();
+ assert!(!ledger.has_dirty());
+ assert!(!ledger.completed_since_flush());
+ assert!(
+ ledger.dirty_bitmaps().is_empty(),
+ "cleared flags hide already-persisted bits"
+ );
+ }
+
+ #[test]
+ fn settle_discriminates_all_complete_partial_and_no_markers() {
+ // Reach the proof through the real caught-up path so the ZST stays un-forgeable in tests:
+ // one partition read up to its captured end, minting a fresh proof for each settle.
+ let proof = || {
+ use crate::domain::{MembershipPartition, NextOffset, ObservationEnds, WatchPositions};
+ let partition = MembershipPartition::new(0);
+ let at = NextOffset::from_high_watermark(10);
+ let mut ends = ObservationEnds::new();
+ ends.insert(partition, at);
+ let mut positions = WatchPositions::new();
+ positions.insert(partition, at);
+ ends.caught_up(&positions)
+ .expect("positions at the captured end are caught up")
+ };
+
+ let mut all = ledger(&[10, 11]);
+ complete_cohort(&mut all, 10);
+ complete_cohort(&mut all, 11);
+ assert_eq!(all.settle(proof()), SettledVerdict::AllComplete);
+
+ let mut partial = ledger(&[10, 11]);
+ complete_cohort(&mut partial, 10);
+ partial.observe(&marker(2, 11, run(1), 0));
+ match partial.settle(proof()) {
+ SettledVerdict::Partial {
+ complete,
+ incomplete,
+ } => {
+ assert_eq!(complete, vec![CohortId(10)]);
+ assert_eq!(incomplete.len(), 1);
+ assert_eq!(incomplete[0].0, CohortId(11));
+ }
+ other => panic!("expected partial, got {other:?}"),
+ }
+
+ let empty = ledger(&[10, 11]);
+ assert_eq!(empty.settle(proof()), SettledVerdict::NoMarkers);
+ }
+}
diff --git a/rust/cohort-seeder/src/domain/mod.rs b/rust/cohort-seeder/src/domain/mod.rs
index dee603020bdc..b70b716ae2ed 100644
--- a/rust/cohort-seeder/src/domain/mod.rs
+++ b/rust/cohort-seeder/src/domain/mod.rs
@@ -11,6 +11,7 @@ pub mod chunk;
pub mod completion;
pub mod condition;
pub mod ids;
+pub mod ledger;
pub mod partition;
pub mod pinned;
pub mod plan;
@@ -25,7 +26,7 @@ pub use chunk::{
ScannedChunk, UnknownChunkStatus,
};
pub use cohort_core::seed::{
- BehavioralShapeHash, BehavioralShapeHashError, ReconcileTile, SeedTile,
+ BehavioralShapeHash, BehavioralShapeHashError, ReconcileCompleteMarker, ReconcileTile, SeedTile,
};
pub(crate) use completion::MARKER_WATCH_SCHEMA;
pub use completion::{
@@ -40,6 +41,7 @@ pub use ids::{
Band, ChunkId, ClaimEpoch, ConditionHash, ConditionHashError, DayIdx, RunId, SChunkMs,
UtcMillis, UtcMsRange, UtcRangeError,
};
+pub use ledger::{MarkerFold, MarkerLedger, SettledVerdict};
pub use partition::{SeedPartition, SeedPartitionCountError, SeedPartitions};
pub use pinned::{
PinnedDropReason, PinnedError, PinnedParticipation, PinnedParticipationState, PinnedRun,
diff --git a/rust/cohort-seeder/src/kafka/committed.rs b/rust/cohort-seeder/src/kafka/committed.rs
new file mode 100644
index 000000000000..e0be85079f0a
--- /dev/null
+++ b/rust/cohort-seeder/src/kafka/committed.rs
@@ -0,0 +1,157 @@
+//! Reads the seed consumer group's committed offsets — the *liveness* signal for the completion
+//! protocol. A run's reconcile control records were produced to the seed topic; the processor has
+//! drained them only once the seed group commits past each produced offset. This asks that group,
+//! never our own: the consumer is built with the target group id and both auto-commit and
+//! auto-offset-store disabled, so querying it can never mutate the processor's durable progress. It
+//! never subscribes or consumes. Mirrors `personhog-leader`'s warming offset query exactly.
+
+use std::time::Duration;
+
+use common_kafka::config::KafkaConfig;
+use rdkafka::consumer::{Consumer, StreamConsumer};
+use rdkafka::error::KafkaError;
+use rdkafka::{ClientConfig, Offset, TopicPartitionList};
+
+use crate::domain::{CommittedOffset, SeedGroupCommits, SeedPartition, SeedPartitionCountError};
+
+/// Queries one consumer group's committed offsets for the seed topic's partitions. Cheap to
+/// construct and clone: it holds only configuration, building a short-lived consumer per query.
+#[derive(Clone)]
+pub struct SeedGroupOffsetReader {
+ kafka: KafkaConfig,
+ group_id: String,
+ topic: String,
+ partition_count: u32,
+ timeout: Duration,
+}
+
+impl SeedGroupOffsetReader {
+ pub fn new(
+ kafka: KafkaConfig,
+ group_id: String,
+ topic: String,
+ partition_count: u32,
+ timeout: Duration,
+ ) -> Self {
+ Self {
+ kafka,
+ group_id,
+ topic,
+ partition_count,
+ timeout,
+ }
+ }
+
+ /// Fetch the seed group's committed offset for every seed partition in one OffsetFetch round-trip.
+ /// A partition the group has never committed is absent from the result — the domain reads that as
+ /// "not yet caught up". The synchronous `committed_offsets` RPC runs on the blocking pool so a slow
+ /// broker cannot stall the runtime.
+ pub async fn committed(&self) -> Result<SeedGroupCommits, SeedGroupOffsetError> {
+ let partitions = SeedPartition::all(self.partition_count)?.collect::<Vec<_>>();
+ let kafka = self.kafka.clone();
+ let group_id = self.group_id.clone();
+ let topic = self.topic.clone();
+ let timeout = self.timeout;
+ tokio::task::spawn_blocking(move || {
+ let consumer =
+ make_offset_consumer(&kafka, &group_id).map_err(SeedGroupOffsetError::Consumer)?;
+ let mut tpl = TopicPartitionList::new();
+ for partition in &partitions {
+ tpl.add_partition(&topic, i32::from(partition.as_u16()));
+ }
+ let committed = consumer
+ .committed_offsets(tpl, timeout)
+ .map_err(SeedGroupOffsetError::Fetch)?;
+ Ok(build_commits(&partitions, &committed, &topic))
+ })
+ .await
+ .map_err(SeedGroupOffsetError::Join)?
+ }
+}
+
+/// Keep only the partitions the group has a concrete committed offset for. `Invalid`/`Beginning`/
+/// `End` sentinels and absent partitions mean no real commit, so they stay out of the map — which the
+/// domain reads as lagging.
+fn build_commits(
+ partitions: &[SeedPartition],
+ committed: &TopicPartitionList,
+ topic: &str,
+) -> SeedGroupCommits {
+ let mut commits = SeedGroupCommits::new();
+ for partition in partitions {
+ if let Some(Offset::Offset(offset)) = committed
+ .find_partition(topic, i32::from(partition.as_u16()))
+ .map(|entry| entry.offset())
+ {
+ commits.insert(*partition, CommittedOffset::new(offset));
+ }
+ }
+ commits
+}
+
+/// Build the short-lived query consumer. Auto-commit and auto-offset-store are off so instantiating it
+/// with the writer's (seed processor's) group id cannot clobber that group's durable offsets.
+fn make_offset_consumer(kafka: &KafkaConfig, group_id: &str) -> Result<StreamConsumer, KafkaError> {
+ let mut config = ClientConfig::new();
+ config
+ .set("bootstrap.servers", &kafka.kafka_hosts)
+ .set("group.id", group_id)
+ .set("enable.auto.commit", "false")
+ .set("enable.auto.offset.store", "false")
+ .set("auto.offset.reset", "error");
+ if kafka.kafka_tls {
+ config
+ .set("security.protocol", "ssl")
+ .set("enable.ssl.certificate.verification", "false");
+ }
+ if !kafka.kafka_client_rack.is_empty() {
+ config.set("client.rack", &kafka.kafka_client_rack);
+ }
+ config.create()
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum SeedGroupOffsetError {
+ #[error("invalid seed partition count")]
+ PartitionCount(#[from] SeedPartitionCountError),
+ #[error("creating the seed-group offset query consumer")]
+ Consumer(#[source] KafkaError),
+ #[error("fetching the seed group's committed offsets")]
+ Fetch(#[source] KafkaError),
+ #[error("joining the committed-offset query task")]
+ Join(#[source] tokio::task::JoinError),
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const TOPIC: &str = "cohort_seed_events";
+
+ #[test]
+ fn only_a_concrete_committed_offset_counts_as_progress() {
+ let partitions: Vec<SeedPartition> = SeedPartition::all(4).unwrap().collect();
+ let mut committed = TopicPartitionList::new();
+ committed
+ .add_partition_offset(TOPIC, 0, Offset::Offset(42))
+ .unwrap();
+ committed
+ .add_partition_offset(TOPIC, 1, Offset::Invalid)
+ .unwrap();
+ committed
+ .add_partition_offset(TOPIC, 2, Offset::Beginning)
+ .unwrap();
+ // Partition 3 is absent from the response entirely.
+
+ let commits = build_commits(&partitions, &committed, TOPIC);
+
+ assert_eq!(commits.get(partitions[0]), Some(CommittedOffset::new(42)));
+ for partition in &partitions[1..] {
+ assert_eq!(
+ commits.get(*partition),
+ None,
+ "a sentinel or missing offset must read as lagging, not as caught up"
+ );
+ }
+ }
+}
diff --git a/rust/cohort-seeder/src/kafka/markers.rs b/rust/cohort-seeder/src/kafka/markers.rs
new file mode 100644
index 000000000000..d9947c1c22a6
--- /dev/null
+++ b/rust/cohort-seeder/src/kafka/markers.rs
@@ -0,0 +1,316 @@
+//! Tails the membership-change topic for `reconcile_complete` markers — the completion *authority*.
+//!
+//! An assign-only consumer with a unique throwaway group id: it never subscribes and never commits, so
+//! it participates in no rebalance and leaves no durable offset. It watches every membership partition
+//! from explicit start offsets (the high watermarks captured at dispatch), with `auto.offset.reset=
+//! error` so a start below the log's low watermark surfaces as [`WatchError::Truncated`] instead of
+//! silently jumping. The topic is high-volume and person-keyed; markers are the rare key that contains
+//! `':'` (`"{team}:{cohort}:{run}"`), so that byte probe rejects membership rows before any JSON parse.
+//! Non-marker messages still advance the partition's next-read offset. rdkafka types stay confined
+//! here — the watcher yields typed [`WatchItem`]s.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+use std::time::Duration;
+
+use common_kafka::config::KafkaConfig;
+use futures::stream::{self, StreamExt, TryStreamExt};
+use metrics::counter;
+use rdkafka::consumer::{Consumer, StreamConsumer};
+use rdkafka::error::KafkaError;
+use rdkafka::message::Message;
+use rdkafka::{ClientConfig, Offset, TopicPartitionList};
+
+use crate::domain::{
+ MarkerPartition, MembershipPartition, NextOffset, ObservedMarker, ReconcileCompleteMarker,
+ WatchPositions,
+};
+use crate::observability::metrics::RECONCILE_MARKER_PARSE_FAILURES;
+
+/// In-flight watermark fetches during a seek, matching the group-lag scanner's bound.
+const WATERMARK_CONCURRENCY: usize = 16;
+
+/// One record read from the membership topic: where the watcher now sits on that partition, and the
+/// marker it carried (if any). Non-marker rows carry `marker: None` but still advance `next_offset`.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct WatchItem {
+ pub partition: MembershipPartition,
+ pub next_offset: NextOffset,
+ pub marker: Option<ObservedMarker>,
+}
+
+/// An assign-only consumer over the membership topic. Holds an rdkafka `StreamConsumer` behind an
+/// `Arc` so the (infrequent, blocking) watermark check can run on the blocking pool while `recv` keeps
+/// borrowing it. The app-level `MarkerStream` seam wraps it so the watch task can be tested with a fake.
+pub struct MarkerWatcher {
+ consumer: Arc<StreamConsumer>,
+ topic: String,
+ watermark_timeout: Duration,
+}
+
+impl MarkerWatcher {
+ /// Create the consumer without assigning any partitions. The first [`Self::seek_to`] seeks it to
+ /// the watched runs' start offsets.
+ pub fn new(
+ kafka: &KafkaConfig,
+ topic: String,
+ group_id: &str,
+ watermark_timeout: Duration,
+ ) -> Result<Self, WatchError> {
+ let consumer: Arc<StreamConsumer> = Arc::new(
+ build_config(kafka, group_id)
+ .create()
+ .map_err(WatchError::Consumer)?,
+ );
+ Ok(Self {
+ consumer,
+ topic,
+ watermark_timeout,
+ })
+ }
+
+ /// Re-assign the consumer to read from `start` on every named partition. Unconditional — the app's
+ /// watch state decides *when* a seek is needed (a run was added or re-dispatched); re-reading is
+ /// safe because bit folds and position advances are idempotent. Each start offset is checked
+ /// against the log's low watermark first, so a start below retention surfaces as
+ /// [`WatchError::Truncated`] rather than a silent reset. The blocking watermark calls run on the
+ /// blocking pool.
+ pub async fn seek_to(&mut self, start: &WatchPositions) -> Result<(), WatchError> {
+ let lows = self.low_watermarks(start).await?;
+ let tpl = build_assignment(&self.topic, start, &lows)?;
+ self.consumer.assign(&tpl).map_err(WatchError::Assign)?;
+ // Records queued under the previous assignment can still be sitting in librdkafka's fetch
+ // queue here. They are discarded rather than delivered: `assign` bumps each partition's
+ // fetch version, and the client drops messages tagged with a stale version. The watch state
+ // relies on that — a leaked pre-seek record would advance coverage past markers the rewound
+ // run never read.
+ Ok(())
+ }
+
+ /// Fetch every watched partition's low watermark, one blocking call each, bounded-concurrent
+ /// like `ingestion-control-plane`'s group-lag scan. Each call can block for the full watermark
+ /// timeout, and a seek covers all 64 membership partitions, so serializing them against an
+ /// unresponsive broker overruns the watch task's liveness deadline.
+ async fn low_watermarks(
+ &self,
+ start: &WatchPositions,
+ ) -> Result<HashMap<MembershipPartition, i64>, WatchError> {
+ let partitions: Vec<MembershipPartition> = start.iter().map(|(p, _)| p).collect();
+ stream::iter(partitions)
+ .map(|partition| {
+ let consumer = Arc::clone(&self.consumer);
+ let topic = self.topic.clone();
+ let timeout = self.watermark_timeout;
+ async move {
+ tokio::task::spawn_blocking(move || {
+ consumer
+ .fetch_watermarks(&topic, partition.get(), timeout)
+ .map(|(low, _high)| (partition, low))
+ .map_err(|source| WatchError::Watermarks {
+ partition: partition.get(),
+ source,
+ })
+ })
+ .await
+ .map_err(WatchError::WatermarkJoin)?
+ }
+ })
+ .buffer_unordered(WATERMARK_CONCURRENCY)
+ .try_collect()
+ .await
+ }
+
+ /// Drop every assigned partition. The consumer stays alive and re-assigns on the next
+ /// [`Self::seek_to`].
+ pub fn unassign(&self) -> Result<(), WatchError> {
+ self.consumer
+ .assign(&TopicPartitionList::new())
+ .map_err(WatchError::Assign)
+ }
+
+ /// Await the next record and classify it. A membership row yields `marker: None`; a keyed record
+ /// that fails to parse increments the parse-failure counter and still advances the offset.
+ pub async fn next_item(&self) -> Result<WatchItem, WatchError> {
+ let message = self.consumer.recv().await.map_err(WatchError::Recv)?;
+ let partition = MembershipPartition::new(message.partition());
+ let next_offset = NextOffset::from_high_watermark(message.offset() + 1);
+ let marker = classify_marker(message.key(), message.payload());
+ Ok(WatchItem {
+ partition,
+ next_offset,
+ marker,
+ })
+ }
+}
+
+/// Build the assignment TPL for `start`, rejecting any partition whose start fell out of retention.
+/// `start` iterates in partition order, so the truncation reported is the lowest offending partition
+/// rather than whichever watermark call happened to return first.
+fn build_assignment(
+ topic: &str,
+ start: &WatchPositions,
+ lows: &HashMap<MembershipPartition, i64>,
+) -> Result<TopicPartitionList, WatchError> {
+ let mut tpl = TopicPartitionList::new();
+ for (partition, next) in start.iter() {
+ // `lows` covers these same partitions, so the fallback is unreachable.
+ let low = lows.get(&partition).copied().unwrap_or(0);
+ if next.get() < low {
+ return Err(WatchError::Truncated {
+ partition: partition.get(),
+ requested: next.get(),
+ low,
+ });
+ }
+ tpl.add_partition_offset(topic, partition.get(), Offset::Offset(next.get()))
+ .map_err(WatchError::Assign)?;
+ }
+ Ok(tpl)
+}
+
+/// Cheap discriminator then parse. Markers are keyed `"{team}:{cohort}:{run}"`; membership rows are
+/// keyed by a person UUID (no `':'`), so the byte probe skips the JSON parse for the common case.
+fn classify_marker(key: Option<&[u8]>, payload: Option<&[u8]>) -> Option<ObservedMarker> {
+ let key = key?;
+ if !key.contains(&b':') {
+ return None;
+ }
+ let Some(payload) = payload else {
+ counter!(RECONCILE_MARKER_PARSE_FAILURES).increment(1);
+ return None;
+ };
+ let marker = match serde_json::from_slice::<ReconcileCompleteMarker>(payload) {
+ Ok(marker) => marker,
+ Err(_) => {
+ counter!(RECONCILE_MARKER_PARSE_FAILURES).increment(1);
+ return None;
+ }
+ };
+ match MarkerPartition::new(u32::from(marker.partition())) {
+ Ok(partition) => Some(ObservedMarker {
+ team_id: marker.team_id(),
+ cohort_id: marker.cohort_id(),
+ partition,
+ run_id: marker.run_id(),
+ }),
+ Err(_) => {
+ counter!(RECONCILE_MARKER_PARSE_FAILURES).increment(1);
+ None
+ }
+ }
+}
+
+fn build_config(kafka: &KafkaConfig, group_id: &str) -> ClientConfig {
+ let mut config = ClientConfig::new();
+ config
+ .set("bootstrap.servers", &kafka.kafka_hosts)
+ .set("group.id", group_id)
+ .set("enable.auto.commit", "false")
+ .set("enable.auto.offset.store", "false")
+ // A start position outside the retained log is a real event (retention outran the watcher);
+ // fail loudly rather than silently reset so the run is re-dispatched.
+ .set("auto.offset.reset", "error");
+ if kafka.kafka_tls {
+ config
+ .set("security.protocol", "ssl")
+ .set("enable.ssl.certificate.verification", "false");
+ }
+ if !kafka.kafka_client_rack.is_empty() {
+ config.set("client.rack", &kafka.kafka_client_rack);
+ }
+ config
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum WatchError {
+ #[error("creating the marker-watch consumer")]
+ Consumer(#[source] KafkaError),
+ #[error("fetching watermarks for membership partition {partition}")]
+ Watermarks {
+ partition: i32,
+ #[source]
+ source: KafkaError,
+ },
+ #[error("joining the membership watermark task")]
+ WatermarkJoin(#[source] tokio::task::JoinError),
+ #[error(
+ "membership partition {partition} start offset {requested} is below the log's low watermark \
+ {low}: the topic was truncated past the captured watch position"
+ )]
+ Truncated {
+ partition: i32,
+ requested: i64,
+ low: i64,
+ },
+ #[error("assigning the marker-watch partitions")]
+ Assign(#[source] KafkaError),
+ #[error("receiving from the membership topic")]
+ Recv(#[source] KafkaError),
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use cohort_core::filters::{CohortId, TeamId};
+ use cohort_core::seed::RunId;
+ use uuid::Uuid;
+
+ fn marker_payload(partition: u16) -> Vec<u8> {
+ serde_json::to_vec(&ReconcileCompleteMarker::new(
+ TeamId(2),
+ CohortId(42),
+ partition,
+ RunId(Uuid::nil()),
+ "2026-05-26 12:34:56.789123".to_string(),
+ ))
+ .unwrap()
+ }
+
+ #[test]
+ fn classify_probes_the_key_before_parsing_and_extracts_the_marker() {
+ // Person-keyed membership row: no ':' in the key, so no parse attempt, no marker.
+ assert!(classify_marker(Some(b"01928aaa-bbbb-cccc"), Some(b"{}")).is_none());
+
+ // A marker key with a valid payload.
+ let observed = classify_marker(Some(b"2:42:run"), Some(&marker_payload(7))).unwrap();
+ assert_eq!(observed.team_id, TeamId(2));
+ assert_eq!(observed.cohort_id, CohortId(42));
+ assert_eq!(observed.partition.get(), 7);
+
+ // A key that passes the probe but a payload that is not a marker: dropped, not a marker.
+ assert!(classify_marker(Some(b"2:42:run"), Some(b"{\"not\":\"a marker\"}")).is_none());
+
+ // A marker whose partition is outside the bitmap range is corrupt: dropped.
+ assert!(classify_marker(Some(b"2:42:run"), Some(&marker_payload(64))).is_none());
+ }
+
+ #[test]
+ fn a_start_below_the_low_watermark_is_truncation_and_the_boundary_is_not() {
+ // A start exactly at the low watermark is the normal case right after a retention sweep.
+ // Reporting it as truncated would drop and tombstone every run on the partition.
+ let partition = MembershipPartition::new(0);
+ let lows = HashMap::from([(partition, 20_i64)]);
+ let positions = |offset| {
+ let mut positions = WatchPositions::new();
+ positions.insert(partition, NextOffset::from_high_watermark(offset));
+ positions
+ };
+
+ assert!(matches!(
+ build_assignment(TOPIC, &positions(5), &lows),
+ Err(WatchError::Truncated {
+ partition: 0,
+ requested: 5,
+ low: 20
+ })
+ ));
+
+ let tpl = build_assignment(TOPIC, &positions(20), &lows).unwrap();
+ assert_eq!(
+ tpl.find_partition(TOPIC, 0).map(|entry| entry.offset()),
+ Some(Offset::Offset(20))
+ );
+ }
+
+ const TOPIC: &str = "cohort_membership_changed_shadow";
+}
diff --git a/rust/cohort-seeder/src/kafka/mod.rs b/rust/cohort-seeder/src/kafka/mod.rs
index b85706a2a0e9..653005fc897b 100644
--- a/rust/cohort-seeder/src/kafka/mod.rs
+++ b/rust/cohort-seeder/src/kafka/mod.rs
@@ -1,8 +1,13 @@
-//! Kafka layer: the seed-tile producer client and the produce pacer. Depends only on `domain` (plus
-//! the shared metric-name constants); never on `store`.
+//! Kafka layer: the seed-tile producer client, the produce pacer, and the completion observers — the
+//! seed-group offset reader (liveness) and the membership-topic marker watcher (authority). Depends
+//! only on `domain` (plus the shared metric-name constants); never on `store`.
+pub mod committed;
+pub mod markers;
pub mod pacing;
pub mod producer;
+pub use committed::{SeedGroupOffsetError, SeedGroupOffsetReader};
+pub use markers::{MarkerWatcher, WatchError, WatchItem};
pub use pacing::TilePacer;
pub use producer::{EnqueueError, SeedTileProducer};
diff --git a/rust/cohort-seeder/src/main.rs b/rust/cohort-seeder/src/main.rs
index a73a0532cabf..83f6437d55bb 100644
--- a/rust/cohort-seeder/src/main.rs
+++ b/rust/cohort-seeder/src/main.rs
@@ -3,6 +3,7 @@
//! the composition root at the top of the stack.
use std::num::NonZeroUsize;
+use std::sync::Arc;
use std::time::Duration;
use anyhow::{Context, Result};
@@ -16,12 +17,15 @@ use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{fmt, EnvFilter, Layer};
use cohort_seeder::app::{
- AutoDispatchPolicy, CompletionDriver, OrchestratorSettings, SeederOrchestrator,
- ORCHESTRATOR_LIVENESS_DEADLINE,
+ AutoDispatchPolicy, CompletionDriver, KafkaCommittedOffsets, KafkaTopicOffsets,
+ MarkerWatchTask, ObservePolicy, OrchestratorSettings, PgMarkerFlush, SeederOrchestrator,
+ WatchDirectives, MARKER_WATCH_LIVENESS_DEADLINE, ORCHESTRATOR_LIVENESS_DEADLINE,
};
use cohort_seeder::clickhouse::client::build_client;
use cohort_seeder::clickhouse::scanner::ChunkScanner;
use cohort_seeder::config::Config;
+use cohort_seeder::kafka::committed::SeedGroupOffsetReader;
+use cohort_seeder::kafka::markers::MarkerWatcher;
use cohort_seeder::kafka::pacing::TilePacer;
use cohort_seeder::kafka::producer::SeedTileProducer;
use cohort_seeder::observability;
@@ -44,6 +48,9 @@ async fn async_main(config: Config) -> Result<()> {
init_tracing();
log_startup(&config);
+ let observe_policy =
+ ObservePolicy::from_config(&config).context("validating reconcile observer policy")?;
+
let mut manager = Manager::builder(SERVICE_NAME)
.with_global_shutdown_timeout(Duration::from_secs(30))
.build();
@@ -56,6 +63,20 @@ async fn async_main(config: Config) -> Result<()> {
.with_liveness_deadline(ORCHESTRATOR_LIVENESS_DEADLINE)
.with_stall_threshold(3),
);
+ // The marker-watch task is the binary's second lifecycle component, registered only when the
+ // observer gate is on.
+ let watch_handle = match observe_policy {
+ ObservePolicy::Enabled => Some(
+ manager.register(
+ "marker-watch",
+ ComponentOptions::new()
+ .with_graceful_shutdown(Duration::from_secs(30))
+ .with_liveness_deadline(MARKER_WATCH_LIVENESS_DEADLINE)
+ .with_stall_threshold(3),
+ ),
+ ),
+ ObservePolicy::Disabled => None,
+ };
let readiness = manager.readiness_handler();
let liveness = manager.liveness_handler();
let recorder = config
@@ -88,9 +109,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)
+ let completion = build_completion(&config, &pool, &producer, observe_policy, watch_handle)
.await
- .context("validating auto reconcile dispatch policy")?;
+ .context("validating completion driver policies")?;
let claimed_by = format!("cohort-seeder:{}", uuid::Uuid::now_v7());
let orchestrator = SeederOrchestrator::new(
pool,
@@ -101,11 +122,14 @@ async fn async_main(config: Config) -> Result<()> {
settings,
seeder_handle,
claimed_by,
- completion_driver,
+ completion.driver,
);
let guard = manager.monitor_background();
tokio::spawn(orchestrator.process());
+ if let Some(watch_task) = completion.watch_task {
+ tokio::spawn(watch_task.run());
+ }
let app = observability::health::router(SERVICE_NAME, readiness, liveness, recorder);
let bind = config.bind_address();
@@ -124,43 +148,138 @@ 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(
+/// The wired completion components: the driver ticked from the orchestrator (with whichever halves
+/// the policies armed) and the marker-watch task to spawn when the observer is on.
+struct WiredCompletion {
+ driver: Option<CompletionDriver>,
+ watch_task: Option<MarkerWatchTask<MarkerWatcher, PgMarkerFlush>>,
+}
+
+/// Build the completion driver from the two independent gates. Auto-dispatch arms the dispatch half
+/// (CAS + tile produce + record); the observer arms the observation half (marker-watch directives +
+/// the observation pass) and its dedicated watch task. Either half alone is valid; both off leaves the
+/// dark path with no extra queries. A misconfigured policy (dispatch 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(
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(),
+ observe_policy: ObservePolicy,
+ watch_handle: Option<lifecycle::Handle>,
+) -> Result<WiredCompletion> {
+ let dispatch_policy = AutoDispatchPolicy::from_config(config)
+ .context("validating auto reconcile dispatch policy")?;
+ if matches!(dispatch_policy, AutoDispatchPolicy::Disabled)
+ && observe_policy == ObservePolicy::Disabled
+ {
+ return Ok(WiredCompletion {
+ driver: None,
+ watch_task: None,
+ });
+ }
+
+ // Both halves ride the membership topic — dispatch produces reconcile tiles onto it, the observer
+ // watches it for markers — so prove it is reachable before either arms.
+ 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")?;
+
+ let mut driver = CompletionDriver::new(pool.clone(), config.team_allowlist.clone());
+
+ if let AutoDispatchPolicy::Enabled(register_backfill) = dispatch_policy {
+ 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")?;
+ driver = driver.with_dispatch(
+ producer.clone(),
+ config.cohort_membership_changed_topic.clone(),
+ max_inflight,
+ max_concurrent_dispatches,
+ register_backfill,
+ );
+ }
+
+ let watch_task = match observe_policy {
+ ObservePolicy::Disabled => None,
+ ObservePolicy::Enabled => {
+ let handle = watch_handle
+ .context("the marker-watch component must be registered when the observer is on")?;
+ // A zero interval would panic tokio's interval timer; a zero batch would flush per message.
+ if config.seeder_reconcile_persist_interval_ms == 0 {
+ anyhow::bail!("SEEDER_RECONCILE_PERSIST_INTERVAL_MS must be greater than zero");
+ }
+ if config.seeder_reconcile_persist_max_batch == 0 {
+ anyhow::bail!("SEEDER_RECONCILE_PERSIST_MAX_BATCH must be greater than zero");
+ }
+ // The flush tick is the watch task's only heartbeat while the topic is idle, so too long
+ // an interval gets a healthy-but-idle task killed as stalled.
+ let persist_interval =
+ Duration::from_millis(config.seeder_reconcile_persist_interval_ms);
+ if persist_interval > MARKER_WATCH_LIVENESS_DEADLINE / 2 {
+ anyhow::bail!(
+ "SEEDER_RECONCILE_PERSIST_INTERVAL_MS must be at most half the marker-watch \
+ liveness deadline ({}ms)",
+ MARKER_WATCH_LIVENESS_DEADLINE.as_millis() / 2
+ );
+ }
+ // A zero timeout fails every OffsetFetch and watermark call rather than disabling the
+ // timeout, silently dropping the liveness signal.
+ if config.seeder_reconcile_offsets_timeout_ms == 0 {
+ anyhow::bail!("SEEDER_RECONCILE_OFFSETS_TIMEOUT_MS must be greater than zero");
+ }
+ let offsets_timeout = Duration::from_millis(config.seeder_reconcile_offsets_timeout_ms);
+ let reader = SeedGroupOffsetReader::new(
+ config.build_kafka_config(),
+ config.kafka_seed_consumer_group.clone(),
+ config.seed_events_topic.clone(),
+ config.cohort_partition_count,
+ offsets_timeout,
+ );
+ let topic_ends = KafkaTopicOffsets::new(
producer.clone(),
- config.team_allowlist.clone(),
config.cohort_membership_changed_topic.clone(),
- max_inflight,
- max_concurrent_dispatches,
- register_backfill,
- )))
+ offsets_timeout,
+ );
+ // Unique group id: the watcher never commits or joins a group, but a distinct id keeps it
+ // out of any real group's coordinator state.
+ let watch_group = format!("cohort-seeder-marker-watch-{}", uuid::Uuid::now_v7());
+ let watcher = MarkerWatcher::new(
+ &config.build_kafka_config(),
+ config.cohort_membership_changed_topic.clone(),
+ &watch_group,
+ offsets_timeout,
+ )
+ .context("creating the marker-watch consumer")?;
+ let (directives_tx, directives_rx) =
+ tokio::sync::watch::channel(WatchDirectives::default());
+ driver = driver.with_observe(
+ Arc::new(KafkaCommittedOffsets::new(reader)),
+ Arc::new(topic_ends),
+ directives_tx,
+ );
+ Some(MarkerWatchTask::new(
+ watcher,
+ PgMarkerFlush::new(pool.clone()),
+ directives_rx,
+ handle,
+ persist_interval,
+ config.seeder_reconcile_persist_max_batch,
+ ))
}
- }
+ };
+
+ Ok(WiredCompletion {
+ driver: Some(driver),
+ watch_task,
+ })
}
fn log_startup(config: &Config) {
@@ -180,6 +299,11 @@ fn log_startup(config: &Config) {
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,
+ reconcile_observer_enabled = config.seeder_reconcile_observer_enabled,
+ seed_consumer_group = %config.kafka_seed_consumer_group,
+ reconcile_offsets_timeout_ms = config.seeder_reconcile_offsets_timeout_ms,
+ reconcile_persist_interval_ms = config.seeder_reconcile_persist_interval_ms,
+ reconcile_persist_max_batch = config.seeder_reconcile_persist_max_batch,
"starting cohort-seeder",
);
}
diff --git a/rust/cohort-seeder/src/observability/metrics.rs b/rust/cohort-seeder/src/observability/metrics.rs
index 56fd19b2585e..bf90e9512f74 100644
--- a/rust/cohort-seeder/src/observability/metrics.rs
+++ b/rust/cohort-seeder/src/observability/metrics.rs
@@ -41,6 +41,23 @@ 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";
+// Liveness, marker watcher, and observation.
+pub const RECONCILE_MARKERS_OBSERVED: &str = "seeder_reconcile_markers_observed_total";
+pub const RECONCILE_MARKER_PARSE_FAILURES: &str = "seeder_reconcile_marker_parse_failures_total";
+pub const RECONCILE_MARKER_WATCH_LAG: &str = "seeder_reconcile_marker_watch_lag";
+pub const RECONCILE_LIVENESS_LAGGING_PARTITIONS: &str =
+ "seeder_reconcile_liveness_lagging_partitions";
+pub const RECONCILE_COHORTS_COMPLETED: &str = "seeder_reconcile_cohorts_completed_total";
+pub const RECONCILE_COHORTS_PARTIAL: &str = "seeder_reconcile_cohorts_partial_total";
+pub const RECONCILE_COHORTS_SHORTFALL: &str = "seeder_reconcile_cohorts_shortfall_total";
+pub const RECONCILE_ZERO_MARKER_RUNS: &str = "seeder_reconcile_zero_marker_runs_total";
+pub const RUNS_OBSERVED: &str = "seeder_runs_observed_total";
+pub const RECONCILE_WATCH_TRUNCATED: &str = "seeder_reconcile_watch_truncated_total";
+pub const RECONCILE_OBSERVATION_STALLED_AGE_SECONDS: &str =
+ "seeder_reconcile_observation_stalled_age_seconds";
+pub const RECONCILE_OBSERVATION_PASS_SECONDS: &str = "seeder_reconcile_observation_pass_seconds";
+pub const RECONCILE_OBSERVE_ERRORS: &str = "seeder_reconcile_observe_errors_total";
+pub const RECONCILE_RUNS_UNDISPATCHED: &str = "seeder_reconcile_runs_undispatched";
pub fn install_recorder() -> Result<PrometheusHandle, BuildError> {
PrometheusBuilder::new().install_recorder()
diff --git a/rust/cohort-seeder/src/store/completion.rs b/rust/cohort-seeder/src/store/completion.rs
index 799e5dc04f12..94ef4f0d52b2 100644
--- a/rust/cohort-seeder/src/store/completion.rs
+++ b/rust/cohort-seeder/src/store/completion.rs
@@ -1,6 +1,6 @@
//! 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
+//! the observer drives. `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
@@ -19,8 +19,8 @@ use std::fmt;
use crate::domain::{
BehavioralShapeHash, BehavioralShapeHashError, CompletionParts, CompletionPhase,
- CompletionStatus, DispatchEpoch, MarkerWatch, PartitionBitmap, PartitionBitmapError,
- ReconcileHwms, RunId, WatchPositions, MARKER_WATCH_SCHEMA,
+ CompletionStatus, DispatchEpoch, MarkerWatch, ObservationEnds, PartitionBitmap,
+ PartitionBitmapError, ReconcileHwms, RunId, WatchPositions, MARKER_WATCH_SCHEMA,
};
use super::{RenderedError, PERSISTED_ERROR_LIMIT};
@@ -29,8 +29,8 @@ use super::{RenderedError, PERSISTED_ERROR_LIMIT};
/// 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"
+ "id, team_id, status, chunks_planned_at, reconcile_dispatched_at, \
+ reconcile_observed_at, reconcile_hwms, marker_watch"
};
}
@@ -111,7 +111,7 @@ const RUNS_WITH_ALL_CHUNKS_CONFIRMED: &str = concat!(
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompletionOperation {
RecordDispatch,
- PersistWatch,
+ PersistEnds,
PersistObservations,
MarkCompleted,
RecordPartial,
@@ -124,7 +124,7 @@ 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::PersistEnds => "persist-ends",
Self::PersistObservations => "persist-observations",
Self::MarkCompleted => "mark-completed",
Self::RecordPartial => "record-partial",
@@ -211,7 +211,7 @@ impl ReconcilingClaim {
Ok(())
}
- /// Atomically write the dispatch record per INV-3: set `reconcile_hwms`, `marker_watch`, a fresh
+ /// Atomically write the whole dispatch record: 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.
@@ -325,7 +325,7 @@ pub async fn cas_run_reconciling(
/// 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.
+/// Non-exclusive by design — whichever claimant records last sets the ruling fence.
pub async fn confirm_reconciling(
pool: &PgPool,
run_id: RunId,
@@ -344,27 +344,36 @@ pub async fn confirm_reconciling(
Ok(claimed.map(ClaimRow::into_claim))
}
-/// Persist the watcher's resume state (`marker_watch`) under the dispatch fence.
-pub async fn persist_marker_watch(
+/// Record the captured observation ends under the dispatch fence — the once-per-dispatch write that
+/// arms the settlement proof. It patches only the `ends` key: the observer holds discovery-time
+/// positions, so writing the whole document would race the watch task's position flush and regress
+/// the watcher's coverage (safe in direction, but on an idle topic nothing would ever repair it and
+/// the run could never mint a proof).
+pub async fn persist_observation_ends(
pool: &PgPool,
run_id: RunId,
epoch: DispatchEpoch,
- watch: &MarkerWatch,
+ ends: &ObservationEnds,
) -> Result<(), CompletionStoreError> {
let updated = sqlx::query_scalar::<_, RunId>(
r#"
UPDATE cohort_backfill_runs
- SET marker_watch = $3, updated_at = now()
+ SET marker_watch = jsonb_set(
+ coalesce(marker_watch, jsonb_build_object('schema', $4::bigint, 'positions', '{}'::jsonb)),
+ '{ends}', $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(watch))
+ .bind(Json(ends))
+ .bind(i64::from(MARKER_WATCH_SCHEMA))
.fetch_optional(pool)
.await?;
- fence(updated, run_id, CompletionOperation::PersistWatch)
+ fence(updated, run_id, CompletionOperation::PersistEnds)
}
/// OR-merge observed marker bits into every named cohort and advance the watcher positions, in one
@@ -438,7 +447,7 @@ pub async fn persist_marker_observations(
}
/// 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.
+/// skipped for superseded participations — supersession trumps completion.
pub async fn mark_participation_completed(
pool: &PgPool,
run_id: RunId,
@@ -543,7 +552,7 @@ pub async fn record_participation_shortfall(
resolve_fence(probe, run_id, CompletionOperation::RecordShortfall)
}
-/// Stamp `reconcile_observed_at` — the seeder's last write per dispatch cycle (INV-1). Every
+/// Stamp `reconcile_observed_at` — the seeder's last write per dispatch cycle. Every
/// participation outcome is written before this, so Django never sees an observed run with an
/// undecided participation.
pub async fn mark_run_observed(
@@ -567,11 +576,11 @@ pub async fn mark_run_observed(
}
/// 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
+/// participation was superseded while it was seeding, so "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
+/// carry `reconcile_observed_at`, and terminalizing an all-superseded run as `superseded` is
+/// Django's transition to make. 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,
@@ -599,7 +608,7 @@ pub async fn mark_run_observed_unreconcilable(
)
}
-/// One participation's observation state, seeding PR-C's per-run ledger and outcome fold.
+/// One participation's observation state, seeding the per-run ledger and outcome fold.
#[derive(Debug, Clone)]
pub struct ObservationParticipation {
pub cohort_id: CohortId,
@@ -610,8 +619,8 @@ pub struct ObservationParticipation {
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).
+/// Load every participation's observation state for a run. Superseded rows are included so the
+/// caller can let supersession trump completion.
pub async fn load_observation_participations(
pool: &PgPool,
run_id: RunId,
@@ -659,7 +668,7 @@ pub async fn load_observation_participations(
Ok(participations)
}
-/// The cohort's current behavioral shape, read from `posthog_cohort` for INV-1 hash attribution. An
+/// The cohort's current behavioral shape, read from `posthog_cohort` to attribute a shortfall. 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)]
diff --git a/rust/cohort-seeder/tests/fixtures/cohort_backfill_0007.sql b/rust/cohort-seeder/tests/fixtures/cohort_backfill_0007.sql
index 284e4a179433..d7e0b5404fcd 100644
--- a/rust/cohort-seeder/tests/fixtures/cohort_backfill_0007.sql
+++ b/rust/cohort-seeder/tests/fixtures/cohort_backfill_0007.sql
@@ -86,7 +86,7 @@ CREATE TABLE cohort_backfill_run_cohorts (
);
-- 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
+-- cohort's current behavioral shape hash when attributing a shortfall. Not part of the cohorts app's
-- backfill migrations.
CREATE TABLE posthog_cohort (
id integer PRIMARY KEY,
diff --git a/rust/cohort-seeder/tests/pg_completion.rs b/rust/cohort-seeder/tests/pg_completion.rs
index cbb2c4f7bda2..6f9c27f953e1 100644
--- a/rust/cohort-seeder/tests/pg_completion.rs
+++ b/rust/cohort-seeder/tests/pg_completion.rs
@@ -16,21 +16,23 @@ 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,
+ CompletionPhase, DispatchEpoch, MarkerPartition, MarkerWatch, MembershipPartition, NextOffset,
+ ObservationEnds, 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,
+ persist_observation_ends, 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::types::Json;
use sqlx::PgPool;
mod support;
@@ -55,6 +57,15 @@ fn full_hwms() -> ReconcileHwms {
ReconcileHwms::new(offsets).unwrap()
}
+fn captured_ends() -> ObservationEnds {
+ let mut ends = ObservationEnds::new();
+ ends.insert(
+ MembershipPartition::new(0),
+ NextOffset::from_high_watermark(10),
+ );
+ ends
+}
+
fn empty_watch() -> MarkerWatch {
MarkerWatch {
positions: WatchPositions::new(),
@@ -408,7 +419,7 @@ async fn fenced_writes_reject_stale_epoch_and_wrong_status() -> Result<()> {
.execute(&pool)
.await?;
}
- ensure_fence_lost(persist_marker_watch(&pool, run_id, at, &empty_watch()).await)?;
+ ensure_fence_lost(persist_observation_ends(&pool, run_id, at, &captured_ends()).await)?;
ensure_fence_lost(
persist_marker_observations(
&pool,
@@ -533,6 +544,43 @@ async fn fenced_write(
}
}
+/// Capturing the observation ends patches only the `ends` key. The observer holds discovery-time
+/// positions, so writing the whole document would regress the watcher's flushed coverage — and on a
+/// topic that then goes idle nothing would repair it, leaving the run unable to ever mint a proof.
+#[tokio::test]
+async fn capturing_ends_leaves_the_watcher_positions_alone() -> 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?;
+
+ let mut advanced = WatchPositions::new();
+ advanced.insert(
+ MembershipPartition::new(0),
+ NextOffset::from_high_watermark(42),
+ );
+ persist_marker_observations(&pool, run_id, epoch, &[], &advanced).await?;
+ persist_observation_ends(&pool, run_id, epoch, &captured_ends()).await?;
+
+ let watch: Json<MarkerWatch> =
+ sqlx::query_scalar("SELECT marker_watch FROM cohort_backfill_runs WHERE id = $1")
+ .bind(run_id)
+ .fetch_one(&pool)
+ .await?;
+ ensure!(
+ watch.0.positions.get(MembershipPartition::new(0))
+ == Some(NextOffset::from_high_watermark(42)),
+ "capturing the ends regressed the watcher positions"
+ );
+ ensure!(watch.0.ends == Some(captured_ends()));
+ Ok(())
+ })
+ .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.
@@ -623,10 +671,10 @@ async fn marker_observations_or_merge_round_trip_including_bit_63() -> Result<()
.await
}
-/// Discovery classifies each completion phase, including a pre-B5 reconciling run whose completion
+/// Discovery classifies each completion phase, including a reconciling run whose completion
/// columns are all NULL.
#[tokio::test]
-async fn discovery_classifies_each_phase_including_pre_b5_rows() -> Result<()> {
+async fn discovery_classifies_each_phase_including_undispatched_rows() -> Result<()> {
with_db(|pool| async move {
let unplanned =
insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;
@@ -642,8 +690,8 @@ async fn discovery_classifies_each_phase_including_pre_b5_rows() -> Result<()> {
.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(
+ // A run that predates the completion columns: reconciling with every one of them NULL.
+ let undispatched = insert_run(
&pool,
5,
"team_enablement",
@@ -675,7 +723,7 @@ async fn discovery_classifies_each_phase_including_pre_b5_rows() -> Result<()> {
Some(CompletionPhase::Reconciling(_))
));
ensure!(
- phase(pre_b5)
+ phase(undispatched)
== Some(CompletionPhase::ReconcilingUndispatched(
UndispatchedReason::NeverDispatched
))
diff --git a/rust/cohort-stream-processor/src/producer/mod.rs b/rust/cohort-stream-processor/src/producer/mod.rs
index e2e7a97bb2b9..a4788167289f 100644
--- a/rust/cohort-stream-processor/src/producer/mod.rs
+++ b/rust/cohort-stream-processor/src/producer/mod.rs
@@ -16,14 +16,15 @@ use async_trait::async_trait;
use chrono::Utc;
use common_kafka::kafka_producer::KafkaProduceError;
use metrics::counter;
-use serde::de::{Deserializer, Error as DeError, Unexpected};
-use serde::ser::Serializer;
use serde::{Deserialize, Serialize};
use cohort_core::seed::RunId;
+// Hoisted to the shared seed contract so the seeder's marker watcher and this producer agree on the
+// wire bytes; re-exported here so processor call sites keep their `crate::producer` import path.
+pub use cohort_core::seed::ReconcileCompleteMarker;
use crate::filters::reverse_index::TeamFilters;
-use crate::filters::{CohortId, TeamId};
+use crate::filters::CohortId;
use crate::observability::metrics::OUTPUT_TRANSITIONS_UNMAPPED;
use crate::stage1::transition::{LeafTransition, TransitionKind};
@@ -65,84 +66,6 @@ pub enum ChangeOrigin {
Reconcile,
}
-const RECONCILE_COMPLETE_KIND: &str = "reconcile_complete";
-
-/// A completion certificate emitted after one partition's reconcile snapshot is durable.
-/// Field order is the wire order.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-pub struct ReconcileCompleteMarker {
- #[serde(rename = "type")]
- kind: ReconcileCompleteKind,
- team_id: i32,
- cohort_id: i32,
- partition: u16,
- run_id: RunId,
- /// ClickHouse `DateTime64(6)` wire format.
- last_updated: String,
-}
-
-impl ReconcileCompleteMarker {
- pub fn new(
- team_id: TeamId,
- cohort_id: CohortId,
- partition: u16,
- run_id: RunId,
- last_updated: String,
- ) -> Self {
- Self {
- kind: ReconcileCompleteKind,
- team_id: team_id.0,
- cohort_id: cohort_id.0,
- partition,
- run_id,
- last_updated,
- }
- }
-
- pub const fn team_id(&self) -> TeamId {
- TeamId(self.team_id)
- }
-
- pub const fn cohort_id(&self) -> CohortId {
- CohortId(self.cohort_id)
- }
-
- pub const fn partition(&self) -> u16 {
- self.partition
- }
-
- pub const fn run_id(&self) -> RunId {
- self.run_id
- }
-
- pub fn last_updated(&self) -> &str {
- &self.last_updated
- }
-}
-
-/// A zero-sized discriminant proven to be [`RECONCILE_COMPLETE_KIND`] during deserialization.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-struct ReconcileCompleteKind;
-
-impl Serialize for ReconcileCompleteKind {
- fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
- serializer.serialize_str(RECONCILE_COMPLETE_KIND)
- }
-}
-
-impl<'de> Deserialize<'de> for ReconcileCompleteKind {
- fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
- let value = String::deserialize(deserializer)?;
- if value != RECONCILE_COMPLETE_KIND {
- return Err(DeError::invalid_value(
- Unexpected::Str(&value),
- &"marker type \"reconcile_complete\"",
- ));
- }
- Ok(Self)
- }
-}
-
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MembershipStatus {
@@ -512,32 +435,6 @@ mod tests {
assert_eq!(value, json!("reconcile"));
}
- #[test]
- fn reconcile_complete_marker_has_the_exact_wire_contract() {
- let marker = reconcile_complete_marker(7);
-
- assert_eq!(
- serde_json::to_string(&marker).unwrap(),
- r#"{"type":"reconcile_complete","team_id":42,"cohort_id":91204,"partition":7,"run_id":"00000000-0000-0000-0000-000000000000","last_updated":"2026-05-26 12:34:56.789123"}"#,
- );
- assert_eq!(
- serde_json::from_str::<ReconcileCompleteMarker>(
- &serde_json::to_string(&marker).unwrap()
- )
- .unwrap(),
- marker
- );
- }
-
- #[test]
- fn reconcile_complete_marker_rejects_another_message_type() {
- let payload = serde_json::to_string(&reconcile_complete_marker(7))
- .unwrap()
- .replace("reconcile_complete", "seed");
-
- assert!(serde_json::from_str::<ReconcileCompleteMarker>(&payload).is_err());
- }
-
#[test]
fn live_path_change_stays_byte_identical_and_a_seed_tag_adds_only_the_two_keys() {
let live = CohortMembershipChange {
diff --git a/rust/cohort-stream-processor/src/sweep/reconcile.rs b/rust/cohort-stream-processor/src/sweep/reconcile.rs
index 7cd3e1f1c89b..34f23d6cf872 100644
--- a/rust/cohort-stream-processor/src/sweep/reconcile.rs
+++ b/rust/cohort-stream-processor/src/sweep/reconcile.rs
@@ -33,8 +33,6 @@ impl Sweeper for ReconcileDrainSweeper {
if !self.has_work() {
return;
}
- // B6's live-lag pause belongs here, before fan-out, so admitted jobs keep their deferred
- // offsets while maintenance reads are paused without waking every partition worker.
self.dispatcher.route_reconcile_drain().await;
}
}