:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(ingestion-consumer): extract the commit path behind a pacer seam (#95934)
Paweł Ledwoń7ad246b5913b
diff --git a/rust/common/kafka-consumer/src/partition_offset_ledger.rs b/rust/common/kafka-consumer/src/partition_offset_ledger.rsindex 1ad947d6eba0..e54ca6d1015a 100644--- a/rust/common/kafka-consumer/src/partition_offset_ledger.rs+++ b/rust/common/kafka-consumer/src/partition_offset_ledger.rs@@ -68,10 +68,12 @@ impl fmt::Display for LedgerError {impl std::error::Error for LedgerError {}-/// A consumed contiguous prefix: its commit-ready frontier, the charge it-/// covers, and how many of its offsets Kafka never delivered.+/// A consumed contiguous prefix: the window base it started from, its+/// commit-ready frontier, the charge it covers, and how many of its offsets+/// Kafka never delivered.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct TakenFrontier {+ pub first: Offset,pub offset: Offset,pub charge: Charge,pub gap_offset_count: usize,@@ -230,6 +232,7 @@ impl PartitionOffsetLedger {pub fn take_frontier(&mut self) -> Option<TakenFrontier> {let frontier_offset = self.frontier()?;+ let window_base = self.base_offset.expect("a frontier implies a window base");let mut charge = Charge::ZERO;let mut gap_offset_count = 0;for slot in self.slots.drain(..self.completed_prefix_len) {@@ -242,6 +245,7 @@ impl PartitionOffsetLedger {self.base_offset = Some(frontier_offset);self.completed_prefix_len = 0;Some(TakenFrontier {+ first: window_base,offset: frontier_offset,charge,gap_offset_count,@@ -447,10 +451,16 @@ mod tests {let mut ledger = PartitionOffsetLedger::new(1);ledger.charge([charge(0), charge(1)]).unwrap();ledger.complete([Offset(0), Offset(1)]).unwrap();- ledger.take_frontier().unwrap();+ let first_take = ledger.take_frontier().unwrap();+ assert_eq!(first_take.first, Offset(0));ledger.charge([charge(2)]).unwrap();ledger.complete([Offset(2)]).unwrap();assert_eq!(ledger.frontier(), Some(Offset(3)));- assert_eq!(ledger.take_frontier().unwrap().charge.events, 1);+ let second_take = ledger.take_frontier().unwrap();+ assert_eq!(second_take.charge.events, 1);+ assert_eq!(+ second_take.first, first_take.offset,+ "each take starts where the last one ended"+ );}}diff --git a/rust/common/kafka-consumer/src/topic_offset_ledger.rs b/rust/common/kafka-consumer/src/topic_offset_ledger.rsindex b1df53ec2f25..2bf76769bfe5 100644--- a/rust/common/kafka-consumer/src/topic_offset_ledger.rs+++ b/rust/common/kafka-consumer/src/topic_offset_ledger.rs@@ -5,7 +5,7 @@ use std::sync::{Arc, Mutex};use metrics::{counter, gauge};use crate::charge::Charge;-use crate::partition_offset_ledger::{Held, LedgerError, PartitionOffsetLedger};+use crate::partition_offset_ledger::{Held, LedgerError, PartitionOffsetLedger, TakenFrontier};use crate::types::Offset;/// Offsets a partition holds uncommitted.@@ -194,11 +194,12 @@ impl TopicOffsetLedger {result}- /// Drain the completed prefix and return the frontier it reached; `None`- /// when the partition has no ledger or nothing has completed at the front- /// of its window. The drained offsets leave the window, so the gauges- /// follow them down.- pub fn take_frontier(&self, topic_partition: &TopicPartition) -> Option<Offset> {+ /// Drain the completed prefix and return the span it covers: the window+ /// base it started from and the frontier it reached. `None` when the+ /// partition has no ledger or nothing has completed at the front of its+ /// window. The drained offsets leave the window, so the gauges follow+ /// them down.+ pub fn take_frontier(&self, topic_partition: &TopicPartition) -> Option<TakenFrontier> {let (taken, held) = {let mut partitions = self.partitions.lock().unwrap();let ledger = partitions.get_mut(topic_partition)?;@@ -207,7 +208,7 @@ impl TopicOffsetLedger {};publish_held(topic_partition, held);count_gap_offsets(topic_partition, taken.gap_offset_count);- Some(taken.offset)+ Some(taken)}/// What the partition's window still holds; nothing without a ledger.@@ -336,7 +337,10 @@ mod tests {.expect("live ledger settles");assert_eq!(frontier, Some(Offset(12)));- assert_eq!(ledger.take_frontier(&p0), Some(Offset(12)));+ assert_eq!(+ ledger.take_frontier(&p0).map(|taken| taken.offset),+ Some(Offset(12))+ );assert_eq!(ledger.held(&p0).offsets, 0);}@@ -389,7 +393,7 @@ mod tests {.settle(&p0, 0, [Offset(11)]).expect("live ledger settles");assert_eq!(frontier, None);- assert_eq!(ledger.take_frontier(&p0), None);+ assert!(ledger.take_frontier(&p0).is_none());assert_eq!(ledger.held(&p0).offsets, 2);// The late completion arrives with the next batch and the held@@ -398,7 +402,10 @@ mod tests {.settle(&p0, 0, [Offset(10)]).expect("live ledger settles");assert_eq!(frontier, Some(Offset(12)));- assert_eq!(ledger.take_frontier(&p0), Some(Offset(12)));+ assert_eq!(+ ledger.take_frontier(&p0).map(|taken| taken.offset),+ Some(Offset(12))+ );assert_eq!(ledger.held(&p0).offsets, 0);}@@ -692,6 +699,6 @@ mod tests {);assert_eq!(ledger.held(&p0).offsets, 0);assert_eq!(ledger.generation(&p0), 1);- assert_eq!(ledger.take_frontier(&p0), None);+ assert!(ledger.take_frontier(&p0).is_none());}}diff --git a/rust/ingestion-consumer/README.md b/rust/ingestion-consumer/README.mdindex 7ceb1f809af8..7b3ef3bb4a50 100644--- a/rust/ingestion-consumer/README.md+++ b/rust/ingestion-consumer/README.md@@ -33,6 +33,10 @@ The consumer holds the per-partition offset ledger from `common/kafka-consumer`,Every delivered message is charged to its partition's ledger during collection, and a committed batch completes its offsets there; the commit is then each partition's frontier, one past its longest completed prefix.A partition that settles without a frontier is not committed and stays on its last commit.A batch with no frontier on any partition is not committed at all; `ingestion_consumer_commits_skipped_total{reason}` counts those, where `rejected` means the ledger dropped every slice (expected around a rebalance) and `no_frontier` means an earlier batch is still incomplete at the front of every window the batch settled.+Each frontier the consumer takes goes to the commit sentinel (`commit_sentinel.rs`), which checks it and passes it to the commit pacer (`commit_pacer.rs`); after settling a poll the consumer asks the pacer what is due and commits it in one call.+The pacer is immediate for now, so every poll commits its frontiers as it completes; an interval pacer that coalesces per partition comes with per-partition commits (see the driver-model plan, cycle 8).+The commit pacer holds no I/O: the consumer commits what it is given, and the commit monitor (`commit_monitor.rs`) reports the broker's committed offsets to the sentinel.+A partition that leaves the assignment drops its pending frontier with its ledger, so a later commit cannot commit under another owner.The ledger emits its own metrics, so any consumer built on the crate reports the same series.`kafka_consumer_ledger_uncommitted_offsets{topic,partition}` gauges each partition's window depth; `kafka_consumer_ledger_uncommitted_events` and `kafka_consumer_ledger_uncommitted_bytes` gauge the charge those offsets carry, where bytes is the payload plus key plus headers of each message.`kafka_consumer_ledger_stale_slices_total{stage}` counts charges and settlements dropped because their partition was reassigned while they were in flight; a few around a rebalance are expected.diff --git a/rust/ingestion-consumer/docs/driver-model-plan.md b/rust/ingestion-consumer/docs/driver-model-plan.mdindex f9333103c2f7..4fb80fc5f140 100644--- a/rust/ingestion-consumer/docs/driver-model-plan.md+++ b/rust/ingestion-consumer/docs/driver-model-plan.md@@ -581,11 +581,13 @@ Exit criterion at the canary: zero sentinel violations, and a stalled partition- Keep `max_in_flight_batches` as the bound on outstanding work. A poll's slot frees when all its groups are accepted.- Behavior change: commit timing decouples across partitions and polls. Replay exposure stays inside the admission cap.- Rollback is the switch back to `poll`.+- Commit pacing is the seam for this cycle. The consumer already hands every taken frontier to a commit pacer (`commit_pacer.rs`) and commits what the pacer hands back. Today's pacer is `ImmediateCommitPacer`: everything handed over is due on the next take, so commits stay per poll. Per-partition commits at `group` granularity would commit on every group completion, which is too many commits, so this cycle adds an `IntervalCommitPacer` that keeps the latest frontier per partition and hands them out at most once per `CONSUMER_COMMIT_INTERVAL_MS`. The loop then asks the pacer on a tick, not only after a poll settles, and the tick must not sit in a `select!` next to `collect_batch`, because a dropped collection loses messages before they reach the ledger; the interval bounds the commit delay only if the collection loop itself asks the pacer, otherwise the bound is the interval plus the batch timeout. The commit sentinel must record a partition's attempted offset when the pacer hands it out, not when the frontier is handed over, or `ingestion_consumer_commit_confirmation_lag` reports pending frontiers as commits that never landed. On revoke the pacer forgets the partition; the drain in change 27 commits what the pacer still holds at shutdown. Select between the two pacers with a `CommitPacer` trait or an enum once the second one exists, not before. The sentinel's contiguity check compares the span a poll delivered against the previous commit, which catches a skip in what Kafka delivered; at `group` granularity a take no longer maps to one poll's slice, so that check retires here, after an alert on `kafka_consumer_ledger_gaps_total` stands in for it. Checking the take's own window base against the previous take is not a replacement: the ledger sets the base to the frontier it hands out, so that comparison holds by construction.**Interfaces:**-- Modify `Config`: add the completion granularity.+- Modify `Config`: add the completion granularity and `CONSUMER_COMMIT_INTERVAL_MS`.- Modify `IngestionConsumer::process`: at `group` granularity, select over `GroupCompletion` events. The per-poll path stays for rollback.+- Add `IntervalCommitPacer` next to `ImmediateCommitPacer`, and the seam that selects one.### 22. Delete the per-poll completion path (cleanup)diff --git a/rust/ingestion-consumer/src/commit_monitor.rs b/rust/ingestion-consumer/src/commit_monitor.rsnew file mode 100644index 000000000000..535a5afe6dee--- /dev/null+++ b/rust/ingestion-consumer/src/commit_monitor.rs@@ -0,0 +1,95 @@+//! Confirms that async commits land. librdkafka never reports the result of+//! a manual async commit (see the note on+//! [`crate::order_sentinel::SentinelContext`]), so a task fetches the group's+//! broker-committed offsets on an interval and reports them to the commit+//! sentinel.++use std::sync::Arc;+use std::time::Duration;++use lifecycle::Handle;+use metrics::counter;+use rdkafka::consumer::{Consumer, StreamConsumer};+use tokio::task::JoinHandle;+use tracing::warn;++use crate::commit_sentinel::CommitSentinel;+use crate::order_sentinel::SentinelContext;++/// How often the monitor fetches the group's broker-committed offsets.+const COMMIT_MONITOR_INTERVAL: Duration = Duration::from_secs(30);++/// Aborts the wrapped task when dropped, covering every `process()` exit path.+pub struct AbortOnDrop(JoinHandle<()>);++impl Drop for AbortOnDrop {+ fn drop(&mut self) {+ self.0.abort();+ }+}++/// Run the monitor until shutdown. Aborted when the guard drops, so a+/// consumer torn down mid-test doesn't keep the rdkafka client alive.+pub fn spawn_commit_monitor(+ consumer: Arc<StreamConsumer<SentinelContext>>,+ sentinel: Arc<CommitSentinel>,+ handle: Handle,+) -> AbortOnDrop {+ AbortOnDrop(tokio::spawn(run_commit_monitor(consumer, sentinel, handle)))+}++/// Periodically fetch the broker's committed offsets for the current+/// assignment (an OffsetFetch round trip) and feed them to the commit+/// sentinel, which compares them against attempted commits and stamps the+/// last-successful-commit gauge on progress.+async fn run_commit_monitor(+ consumer: Arc<StreamConsumer<SentinelContext>>,+ sentinel: Arc<CommitSentinel>,+ handle: Handle,+) {+ loop {+ tokio::select! {+ _ = handle.shutdown_recv() => return,+ _ = tokio::time::sleep(COMMIT_MONITOR_INTERVAL) => {}+ }++ let fetch_consumer = Arc::clone(&consumer);+ // assignment() and committed_offsets() block on librdkafka.+ let fetched = tokio::task::spawn_blocking(move || {+ let assignment = fetch_consumer.assignment()?;+ if assignment.count() == 0 {+ return Ok(None);+ }+ fetch_consumer+ .committed_offsets(assignment, Duration::from_secs(5))+ .map(Some)+ })+ .await;++ match fetched {+ Ok(Ok(Some(committed))) => {+ let observed: Vec<(String, i32, i64)> = committed+ .elements()+ .iter()+ .filter_map(|e| match e.offset() {+ rdkafka::Offset::Offset(offset) => {+ Some((e.topic().to_string(), e.partition(), offset))+ }+ // Invalid = no offset stored for the partition yet.+ _ => None,+ })+ .collect();+ sentinel.observe_broker_committed(observed);+ }+ Ok(Ok(None)) => {} // no assignment yet (e.g. before first rebalance)+ Ok(Err(err)) => {+ counter!("ingestion_consumer_commit_monitor_errors_total").increment(1);+ warn!(error = %err, "Commit monitor failed to fetch committed offsets");+ }+ Err(err) => {+ counter!("ingestion_consumer_commit_monitor_errors_total").increment(1);+ warn!(error = %err, "Commit monitor task join error");+ }+ }+ }+}diff --git a/rust/ingestion-consumer/src/commit_pacer.rs b/rust/ingestion-consumer/src/commit_pacer.rsnew file mode 100644index 000000000000..2eff31ba8a64--- /dev/null+++ b/rust/ingestion-consumer/src/commit_pacer.rs@@ -0,0 +1,121 @@+//! Commit pacing for the ingestion consumer. The consumer hands over each+//! partition's frontier as it takes it from the ledger, then asks the pacer+//! what is due and commits that in one call. The pacer holds no I/O.+//!+//! This pacer is immediate: every frontier handed over is due on the next+//! take, so the consumer commits once per poll. Coalescing frontiers on an+//! interval is a later pacer; see the driver-model plan, cycle 8.++use std::collections::HashMap;+use std::sync::Mutex;++use common_kafka_consumer::{Offset, TakenFrontier, TopicPartition};++/// Hands out every frontier handed to it on the next take. The commit+/// sentinel wraps it to check what passes through.+#[derive(Default)]+pub struct ImmediateCommitPacer {+ /// The next-to-read offset each partition is ready to commit. Frontiers+ /// only move forward, so the latest one covers every earlier one.+ pending: Mutex<HashMap<TopicPartition, Offset>>,+}++impl ImmediateCommitPacer {+ pub fn new() -> Self {+ Self::default()+ }++ /// Replace the partition's pending offset; frontiers only move forward.+ pub fn advance_frontier(&self, topic_partition: &TopicPartition, taken: TakenFrontier) {+ self.pending+ .lock()+ .unwrap()+ .insert(topic_partition.clone(), taken.offset);+ }++ /// Partitions leaving the assignment: drop whatever is held for them. A+ /// commit issued for a partition another member now owns could move the+ /// group's offset back behind that member's progress, so the frontier+ /// goes with the partition.+ pub fn forget_partitions(&self, topic_partitions: &[TopicPartition]) {+ let mut pending = self.pending.lock().unwrap();+ for topic_partition in topic_partitions {+ pending.remove(topic_partition);+ }+ }++ /// The offsets due for commit: everything pending, or `None` with+ /// nothing pending.+ pub fn take_due(&self) -> Option<HashMap<TopicPartition, Offset>> {+ let mut pending = self.pending.lock().unwrap();+ if pending.is_empty() {+ return None;+ }+ Some(std::mem::take(&mut pending))+ }+}++#[cfg(test)]+pub(crate) mod test_support {+ use common_kafka_consumer::Charge;++ use super::*;++ pub(crate) fn tp(partition: i32) -> TopicPartition {+ TopicPartition::new("events", partition)+ }++ /// A take that started at window base `first` and reached `offset`.+ pub(crate) fn taken(first: i64, offset: i64) -> TakenFrontier {+ TakenFrontier {+ first: Offset(first),+ offset: Offset(offset),+ charge: Charge::ZERO,+ gap_offset_count: 0,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::test_support::*;+ use super::*;++ #[test]+ fn a_pending_frontier_is_due_on_the_next_take() {+ let pacer = ImmediateCommitPacer::new();+ pacer.advance_frontier(&tp(0), taken(0, 10));++ let offsets = pacer.take_due().expect("due");+ assert_eq!(offsets, HashMap::from([(tp(0), Offset(10))]));+ assert!(pacer.take_due().is_none(), "a take leaves nothing behind");+ }++ #[test]+ fn the_latest_frontier_per_partition_is_what_goes_out() {+ let pacer = ImmediateCommitPacer::new();+ pacer.advance_frontier(&tp(0), taken(0, 10));+ pacer.advance_frontier(&tp(1), taken(0, 20));+ pacer.advance_frontier(&tp(0), taken(10, 12));++ let offsets = pacer.take_due().expect("due");+ assert_eq!(+ offsets,+ HashMap::from([(tp(0), Offset(12)), (tp(1), Offset(20))])+ );+ }++ #[test]+ fn a_forgotten_partition_is_not_committed() {+ let pacer = ImmediateCommitPacer::new();+ pacer.advance_frontier(&tp(0), taken(0, 10));+ pacer.advance_frontier(&tp(1), taken(0, 20));++ pacer.forget_partitions(&[tp(0)]);++ assert_eq!(+ pacer.take_due().expect("due"),+ HashMap::from([(tp(1), Offset(20))])+ );+ }+}diff --git a/rust/ingestion-consumer/src/commit_sentinel.rs b/rust/ingestion-consumer/src/commit_sentinel.rsnew file mode 100644index 000000000000..437d84e587b6--- /dev/null+++ b/rust/ingestion-consumer/src/commit_sentinel.rs@@ -0,0 +1,454 @@+//! The commit sentinel: an always-on observer that turns the consumer's+//! commit guarantee into alertable metrics.+//!+//! **Commit order**: for every topic-partition, offsets must be committed+//! contiguously and monotonically — each span's first offset must equal the+//! previously committed offset (no skips), and the committed offset must+//! never move backwards (no out-of-order commits). Violations increment+//! `ingestion_consumer_commit_violations_total{kind}` and log the offending+//! offsets. `ingestion_consumer_commits_checked_total` is the denominator: the+//! guarantee holds while it grows and the violation counter stays flat.+//!+//! **Commit confirmation**: librdkafka never reports the result of a manual+//! async commit (see the note on [`crate::order_sentinel::SentinelContext`]),+//! so the commit monitor fetches the group's broker-committed offsets and+//! feeds [`CommitSentinel::observe_broker_committed`], which emits+//! `ingestion_consumer_broker_committed_offset` and+//! `ingestion_consumer_commit_confirmation_lag` gauges and stamps+//! `ingestion_consumer_last_successful_commit_timestamp_seconds` on progress.+//!+//! Rebalances reset the baselines, where Kafka legitimately re-deals+//! partitions and the invariant must re-baseline instead of firing false+//! positives.+//!+//! The sentinel wraps the [`ImmediateCommitPacer`] the consumer hands its+//! frontiers to: every frontier passes through it on the way in, and every+//! take passes through it on the way out. It is a pure observer: it never+//! changes what is committed.++use std::collections::HashMap;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex};+use std::time::{SystemTime, UNIX_EPOCH};++use common_kafka_consumer::{Offset, TakenFrontier, TopicPartition};+use metrics::{counter, gauge};+use tracing::warn;++use crate::commit_pacer::ImmediateCommitPacer;+use crate::order_sentinel::OffsetSpan;++/// How a commit violated the contiguous-monotonic invariant.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum CommitViolationKind {+ /// The batch starts past the previously committed offset — the offsets in+ /// between were never part of a committed batch (skipped messages).+ Gap,+ /// The whole batch lies at or behind the committed offset — the commit+ /// moves the partition backwards.+ OutOfOrder,+ /// The batch partially re-covers already-committed offsets.+ Overlap,+}++impl CommitViolationKind {+ fn as_str(&self) -> &'static str {+ match self {+ CommitViolationKind::Gap => "gap",+ CommitViolationKind::OutOfOrder => "out_of_order",+ CommitViolationKind::Overlap => "overlap",+ }+ }+}++/// One detected commit-order violation, returned for tests and logged.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct CommitViolation {+ pub kind: CommitViolationKind,+ pub topic: String,+ pub partition: i32,+ /// The partition's committed offset (Kafka "next to read") before this batch.+ pub prev_committed: i64,+ pub span: OffsetSpan,+}++/// Per-partition commit tracking: what this process asked Kafka to commit+/// (attempted) and what the broker has confirmed as the group's committed+/// offset (observed by the commit monitor via OffsetFetch).+#[derive(Default, Clone, Copy)]+struct PartitionCommits {+ /// The offset value last submitted for commit (Kafka "next to read").+ attempted: Option<i64>,+ /// The broker-confirmed committed offset from the last monitor poll.+ confirmed: Option<i64>,+}++/// Tracks the last committed offset per topic-partition and checks each new+/// commit for contiguity and monotonicity. The first commit after a partition+/// is (re)assigned establishes a baseline and is never a violation — earlier+/// offsets may have been committed by another consumer in the group.+///+/// Caveat: legitimate offset gaps exist on topics with transactional producers+/// (control records consume offsets). The ingestion topics are produced by+/// capture without transactions, so a gap here is a real skip.+pub struct CommitSentinel {+ partitions: Mutex<HashMap<(String, i32), PartitionCommits>>,+ /// Kill switch (`CONSUMER_ORDER_SENTINEL_ENABLED`). When off, checks+ /// no-op and no state accumulates.+ enabled: AtomicBool,+ /// The pacer being observed.+ inner: ImmediateCommitPacer,+}++impl CommitSentinel {+ pub fn new(inner: ImmediateCommitPacer) -> Self {+ Self {+ partitions: Mutex::new(HashMap::new()),+ enabled: AtomicBool::new(true),+ inner,+ }+ }++ pub fn set_enabled(&self, enabled: bool) {+ self.enabled.store(enabled, Ordering::Relaxed);+ }++ /// Check the span the poll delivered for the partition against the+ /// previous commit as the frontier is handed over, so a violation is+ /// attributed to the poll that caused it, then pass the frontier on.+ /// Returns the violations for tests.+ pub fn advance_frontier(+ &self,+ topic_partition: &TopicPartition,+ delivered: OffsetSpan,+ taken: TakenFrontier,+ ) -> Vec<CommitViolation> {+ let violations = self.check_commit([(topic_partition, &delivered)]);+ self.inner.advance_frontier(topic_partition, taken);+ violations+ }++ /// Partitions leaving the assignment: drop their baselines, and whatever+ /// the pacer holds for them.+ pub fn forget_partitions(&self, topic_partitions: &[TopicPartition]) {+ self.forget_baselines(topic_partitions);+ self.inner.forget_partitions(topic_partitions);+ }++ pub fn take_due(&self) -> Option<HashMap<TopicPartition, Offset>> {+ self.inner.take_due()+ }++ /// Check a batch's offset spans against the previous commit per partition,+ /// then advance the tracked committed offset to `span.last + 1`. Emits+ /// metrics and logs; returns the violations for tests.+ pub fn check_commit<'a>(+ &self,+ spans: impl IntoIterator<Item = (&'a TopicPartition, &'a OffsetSpan)>,+ ) -> Vec<CommitViolation> {+ if !self.enabled.load(Ordering::Relaxed) {+ return Vec::new();+ }+ let mut partitions = self.partitions.lock().unwrap();+ let mut violations = Vec::new();++ for (topic_partition, span) in spans {+ counter!("ingestion_consumer_commits_checked_total").increment(1);++ let topic = &topic_partition.topic;+ let partition = &topic_partition.partition;+ let state = partitions.entry((topic.clone(), *partition)).or_default();+ if let Some(prev) = state.attempted {+ let kind = if span.first == prev {+ None+ } else if span.first > prev {+ Some(CommitViolationKind::Gap)+ } else if span.last < prev {+ Some(CommitViolationKind::OutOfOrder)+ } else {+ Some(CommitViolationKind::Overlap)+ };++ if let Some(kind) = kind {+ counter!(+ "ingestion_consumer_commit_violations_total",+ "kind" => kind.as_str(),+ )+ .increment(1);+ warn!(+ kind = kind.as_str(),+ topic = %topic,+ partition = *partition,+ prev_committed = prev,+ batch_first = span.first,+ batch_last = span.last,+ "Commit order violation"+ );+ violations.push(CommitViolation {+ kind,+ topic: topic.clone(),+ partition: *partition,+ prev_committed: prev,+ span: *span,+ });+ }+ }++ state.attempted = Some(span.last + 1);+ gauge!(+ "ingestion_consumer_committed_offset",+ "topic" => topic.clone(),+ "partition" => partition.to_string(),+ )+ .set((span.last + 1) as f64);+ }++ violations+ }++ /// Feed broker-confirmed committed offsets (from an OffsetFetch of the+ /// group's assigned partitions) and compare against what this process+ /// attempted. Emits per-partition gauges:+ ///+ /// - `ingestion_consumer_broker_committed_offset` — the group's committed+ /// offset as the broker reports it;+ /// - `ingestion_consumer_commit_confirmation_lag` — attempted minus+ /// confirmed. Transiently positive while async commits are in flight;+ /// persistently positive means commits are being submitted but not+ /// landing (e.g. a stuck coordinator).+ ///+ /// Returns true when commits verifiably progressed since the last+ /// observation — the broker offset advanced, or everything attempted is+ /// confirmed — so the caller can stamp the last-successful-commit gauge.+ pub fn observe_broker_committed(+ &self,+ observed: impl IntoIterator<Item = (String, i32, i64)>,+ ) -> bool {+ if !self.enabled.load(Ordering::Relaxed) {+ return false;+ }+ let mut partitions = self.partitions.lock().unwrap();+ let mut advanced = false;++ for (topic, partition, committed) in observed {+ gauge!(+ "ingestion_consumer_broker_committed_offset",+ "topic" => topic.clone(),+ "partition" => partition.to_string(),+ )+ .set(committed as f64);++ let state = partitions.entry((topic.clone(), partition)).or_default();+ if let Some(attempted) = state.attempted {+ gauge!(+ "ingestion_consumer_commit_confirmation_lag",+ "topic" => topic.clone(),+ "partition" => partition.to_string(),+ )+ .set((attempted - committed).max(0) as f64);+ }+ // Only an increase over a *previous* observation counts as+ // progress — the first poll baselines (the broker may be reporting+ // a prior incarnation's commits, which say nothing about ours).+ if state.confirmed.is_some_and(|prev| committed > prev) {+ advanced = true;+ }+ state.confirmed = Some(committed);+ }++ let all_confirmed = {+ let attempted_any = partitions.values().any(|s| s.attempted.is_some());+ attempted_any+ && partitions.values().all(|s| match s.attempted {+ Some(attempted) => s.confirmed.is_some_and(|c| c >= attempted),+ None => true,+ })+ };++ let progressed = advanced || all_confirmed;+ if progressed {+ gauge!("ingestion_consumer_last_successful_commit_timestamp_seconds").set(+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default()+ .as_secs_f64(),+ );+ }+ progressed+ }++ /// Drop the baselines for departing partitions so the next commit after a+ /// re-assignment baselines instead of reporting a false gap/overlap+ /// (another group member may have committed in between).+ fn forget_baselines(&self, topic_partitions: &[TopicPartition]) {+ let mut partitions = self.partitions.lock().unwrap();+ for topic_partition in topic_partitions {+ let (topic, partition) = (&topic_partition.topic, topic_partition.partition);+ let forgotten = partitions.remove(&(topic.clone(), partition));+ if forgotten.is_some_and(|state| state.attempted.is_some()) {+ let topic: Arc<str> = Arc::from(topic.as_str());+ let partition: Arc<str> = Arc::from(partition.to_string());+ gauge!(+ "ingestion_consumer_commit_confirmation_lag",+ "topic" => topic,+ "partition" => partition,+ )+ .set(0.0);+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use crate::commit_pacer::test_support::{taken, tp};++ use super::*;++ fn sentinel() -> CommitSentinel {+ CommitSentinel::new(ImmediateCommitPacer::new())+ }++ #[test]+ fn a_delivered_span_is_checked_as_the_frontier_is_handed_over() {+ let sentinel = sentinel();+ let span = |first, last| OffsetSpan { first, last };+ // The first poll baselines. The second delivered 10..=14 and the+ // frontier reached 15, so it starts where the last commit left off.+ assert!(sentinel+ .advance_frontier(&tp(0), span(0, 9), taken(0, 10))+ .is_empty());+ assert!(sentinel+ .advance_frontier(&tp(0), span(10, 14), taken(10, 15))+ .is_empty());++ // A poll that delivered past the last commit skipped offsets, even+ // though the ledger walked the gap and its take chains.+ let violations = sentinel.advance_frontier(&tp(0), span(17, 19), taken(15, 20));+ assert_eq!(violations.len(), 1);+ assert_eq!(violations[0].kind, CommitViolationKind::Gap);+ assert_eq!(violations[0].prev_committed, 15);+ }++ fn spans(entries: &[(&str, i32, i64, i64)]) -> HashMap<TopicPartition, OffsetSpan> {+ entries+ .iter()+ .map(|(topic, partition, first, last)| {+ (+ TopicPartition::new(*topic, *partition),+ OffsetSpan {+ first: *first,+ last: *last,+ },+ )+ })+ .collect()+ }++ // ---- CommitSentinel ----++ #[test]+ fn contiguous_commits_pass() {+ let sentinel = sentinel();+ assert!(+ sentinel.check_commit(&spans(&[("t", 0, 0, 99)])).is_empty(),+ "first commit baselines"+ );+ assert!(+ sentinel+ .check_commit(&spans(&[("t", 0, 100, 149)]))+ .is_empty(),+ "next batch starts exactly at the committed offset"+ );+ }++ #[test]+ fn commit_gap_is_detected() {+ let sentinel = sentinel();+ sentinel.check_commit(&spans(&[("t", 0, 0, 99)]));+ // Offsets 100..=104 were never committed — the batch skipped them.+ let violations = sentinel.check_commit(&spans(&[("t", 0, 105, 150)]));+ assert_eq!(violations.len(), 1);+ assert_eq!(violations[0].kind, CommitViolationKind::Gap);+ assert_eq!(violations[0].prev_committed, 100);+ }++ #[test]+ fn commit_regression_is_out_of_order() {+ let sentinel = sentinel();+ sentinel.check_commit(&spans(&[("t", 0, 0, 99)]));+ let violations = sentinel.check_commit(&spans(&[("t", 0, 10, 50)]));+ assert_eq!(violations.len(), 1);+ assert_eq!(violations[0].kind, CommitViolationKind::OutOfOrder);+ }++ #[test]+ fn partial_recommit_is_overlap() {+ let sentinel = sentinel();+ sentinel.check_commit(&spans(&[("t", 0, 0, 99)]));+ let violations = sentinel.check_commit(&spans(&[("t", 0, 90, 150)]));+ assert_eq!(violations.len(), 1);+ assert_eq!(violations[0].kind, CommitViolationKind::Overlap);+ }++ #[test]+ fn partitions_are_tracked_independently() {+ let sentinel = sentinel();+ sentinel.check_commit(&spans(&[("t", 0, 0, 99), ("t", 1, 0, 9)]));+ // Partition 0 continues cleanly; partition 1 skips 10..=19.+ let violations = sentinel.check_commit(&spans(&[("t", 0, 100, 120), ("t", 1, 20, 30)]));+ assert_eq!(violations.len(), 1);+ assert_eq!(violations[0].partition, 1);+ assert_eq!(violations[0].kind, CommitViolationKind::Gap);+ }++ #[test]+ fn broker_observation_baselines_then_tracks_progress() {+ let sentinel = sentinel();+ sentinel.check_commit(&spans(&[("t", 0, 0, 99)])); // attempted next = 100+ // First poll baselines: a stale broker offset (previous incarnation)+ // is not evidence that OUR commits landed.+ assert!(!sentinel.observe_broker_committed([("t".to_string(), 0, 40)]));+ // Broker offset advancing across polls = commits are landing.+ assert!(sentinel.observe_broker_committed([("t".to_string(), 0, 80)]));+ // No advance and still behind the attempted offset = no progress.+ assert!(!sentinel.observe_broker_committed([("t".to_string(), 0, 80)]));+ // Catching up to everything attempted also counts as progress.+ assert!(sentinel.observe_broker_committed([("t".to_string(), 0, 100)]));+ // Fully confirmed and idle: repeated identical polls stay "progressed"+ // via the all-confirmed arm, keeping the liveness gauge fresh.+ assert!(sentinel.observe_broker_committed([("t".to_string(), 0, 100)]));+ }++ #[test]+ fn broker_observation_requires_every_attempted_partition_confirmed() {+ let sentinel = sentinel();+ sentinel.check_commit(&spans(&[("t", 0, 0, 99), ("t", 1, 0, 9)]));+ sentinel.observe_broker_committed([("t".to_string(), 0, 100), ("t".to_string(), 1, 5)]);+ // Partition 0 fully confirmed but partition 1 stuck below attempted and+ // not advancing: not progress.+ assert!(!sentinel+ .observe_broker_committed([("t".to_string(), 0, 100), ("t".to_string(), 1, 5)]));+ }++ #[test]+ fn forgotten_partition_rebaselines_without_violation() {+ let sentinel = sentinel();+ sentinel.check_commit(&spans(&[("t", 0, 0, 99)]));+ sentinel.forget_partitions(&[TopicPartition::new("t", 0)]);+ // After revoke + re-assign another consumer may have committed past us;+ // a non-contiguous first commit must baseline, not fire.+ assert!(sentinel+ .check_commit(&spans(&[("t", 0, 500, 599)]))+ .is_empty());+ }++ #[test]+ fn a_disabled_sentinel_checks_nothing() {+ let commit = sentinel();+ commit.set_enabled(false);+ commit.check_commit(&spans(&[("t", 0, 0, 99)]));+ // A blatant regression passes: the kill switch disarms the check.+ assert!(commit.check_commit(&spans(&[("t", 0, 10, 50)])).is_empty());+ }+}diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rsindex 88a26d1ec758..cdfe4b7d463e 100644--- a/rust/ingestion-consumer/src/consumer.rs+++ b/rust/ingestion-consumer/src/consumer.rs@@ -12,17 +12,19 @@ use rdkafka::consumer::{CommitMode, Consumer, StreamConsumer};use rdkafka::message::{Headers, Message};use rdkafka::TopicPartitionList;use tokio::sync::mpsc;-use tokio::task::JoinHandle;use tracing::{error, info, warn};use crate::batcher::{make_batch_id, Batcher, BatcherOutputs};+use crate::commit_monitor::spawn_commit_monitor;+use crate::commit_pacer::ImmediateCommitPacer;+use crate::commit_sentinel::{CommitSentinel, CommitViolation};use crate::config::Config;use crate::debug_recorder::{record_if, DebugEventKind, DebugRecorder, PartitionOffset};use crate::discovery::DiscoveryMode;use crate::dispatcher::Dispatcher;use crate::grpc_transport::GrpcTransport;use crate::ledger_rejection::{warn_rejection, RejectedSlice};-use crate::order_sentinel::{CommitSentinel, OffsetSpan, SentinelContext};+use crate::order_sentinel::{OffsetSpan, SentinelContext};use crate::types::{Accumulator, SerializedKafkaMessage};/// Batch-wide statistics gathered while collecting, used to emit parity@@ -114,6 +116,16 @@ impl PartitionDeliveries {}}+/// Why the consumer loop stops. The two are reported on separate channels+/// so a dashboard can tell a pipeline failure from a client that can no+/// longer commit.+enum Failure {+ /// A poll could not be collected, dispatched, or completed.+ Batch(anyhow::Error),+ /// An offset commit could not be submitted to the Kafka client.+ Commit(anyhow::Error),+}+/// Output of `collect_batch`.struct CollectedBatch {/// The poll's messages, demuxed per partition and routing key.@@ -218,8 +230,10 @@ pub struct IngestionConsumer {max_in_flight_batches: usize,handle: Handle,group_id: String,- /// Validates commit contiguity/monotonicity per partition. Shared with the- /// consumer's [`SentinelContext`], which resets baselines on rebalance.+ /// Where settled frontiers go: the sentinel checks each one and passes+ /// it to the pacer, which says when to commit. Shared with the+ /// consumer's [`SentinelContext`], which tells it which partitions leave+ /// the assignment.commit_sentinel: Arc<CommitSentinel>,/// Debug event recorder; `None` unless `DEBUG_API_ENABLED`.debug_recorder: Option<Arc<DebugRecorder>>,@@ -242,10 +256,11 @@ impl IngestionConsumer {options: IngestionConsumerOptions,handle: Handle,) -> Self {- // Share the context's commit sentinel and ledger so rebalance- // callbacks reset the same baselines the commit path checks against.- let commit_sentinel = consumer.context().commit_sentinel();+ // Share the context's ledger and sentinel so rebalance callbacks+ // forget partitions on the same ones the commit path uses.let topic_offset_ledger = consumer.context().topic_offset_ledger();+ let commit_sentinel = consumer.context().commit_sentinel();+ let consumer = Arc::new(consumer);let (batcher, outputs) = Batcher::new(dispatcher,Arc::clone(&transport),@@ -256,7 +271,7 @@ impl IngestionConsumer {commit_sentinel,debug_recorder: options.debug_recorder,topic_offset_ledger,- consumer: Arc::new(consumer),+ consumer,batcher,outputs: Some(outputs),transport,@@ -297,7 +312,7 @@ impl IngestionConsumer {config.consumer_batch_size,config.consumer_batch_size_kb,);- let commit_sentinel = Arc::new(CommitSentinel::new());+ let commit_sentinel = Arc::new(CommitSentinel::new(ImmediateCommitPacer::new()));commit_sentinel.set_enabled(config.consumer_order_sentinel_enabled);let key_sentinel = batcher.key_order_sentinel();key_sentinel.set_enabled(config.consumer_order_sentinel_enabled);@@ -311,6 +326,7 @@ impl IngestionConsumer {let consumer: StreamConsumer<SentinelContext> =client_config.create_with_context(context)?;consumer.subscribe(&[&config.ingestion_consumer_consume_topic])?;+ let consumer = Arc::new(consumer);info!(topic = %config.ingestion_consumer_consume_topic,@@ -322,8 +338,8 @@ impl IngestionConsumer {);Ok(Self {- consumer: Arc::new(consumer),commit_sentinel,+ consumer,debug_recorder,topic_offset_ledger,batcher,@@ -344,8 +360,8 @@ impl IngestionConsumer {pub async fn process(mut self) {let _guard = self.handle.process_scope();let BatcherOutputs {- mut completions,- mut errors,+ completions,+ errors,} = self.outputs.take().expect("process is called once");info!("Waiting for workers to be ready");@@ -366,16 +382,23 @@ impl IngestionConsumer {workers: self.worker_urls.clone(),});- // Verify async commits actually land: librdkafka drops the result of- // manual async commits (see the note on SentinelContext), so poll the- // broker's committed offsets instead. Aborted on drop so a consumer- // torn down mid-test doesn't keep the rdkafka client alive.- let _commit_monitor = AbortOnDrop(tokio::spawn(run_commit_monitor(+ let _commit_monitor = spawn_commit_monitor(Arc::clone(&self.consumer),Arc::clone(&self.commit_sentinel),self.handle.clone(),- )));+ );++ self.run(completions, errors).await;+ info!("Consumer loop stopped");+ }+ /// Poll, dispatch, and complete until shutdown drains the in-flight polls+ /// or the loop fails.+ async fn run(+ &self,+ mut completions: mpsc::UnboundedReceiver<GroupCompletion>,+ mut errors: mpsc::UnboundedReceiver<String>,+ ) {let mut in_flight_polls: VecDeque<InFlightPoll> = VecDeque::new();let mut accepting_new_batches = true;@@ -419,16 +442,32 @@ impl IngestionConsumer {}}- if let Err(err) = self+ if let Err(failure) = self.complete_oldest_poll(&mut in_flight_polls, &mut completions, &mut errors).await{- self.fail_batch_processing(err);+ match failure {+ Failure::Batch(err) => self.fail_batch_processing(err),+ Failure::Commit(err) => self.fail_commit(err),+ }return;}}+ }- info!("Consumer loop stopped");+ /// Submit each partition's next-to-read offset to Kafka, asynchronously.+ fn commit_offsets(&self, offsets: &HashMap<TopicPartition, Offset>) -> anyhow::Result<()> {+ let mut tpl = TopicPartitionList::new();+ for (topic_partition, next_to_read) in offsets {+ tpl.add_partition_offset(+ &topic_partition.topic,+ topic_partition.partition,+ rdkafka::Offset::Offset(next_to_read.0),+ )?;+ }+ self.consumer.commit(&tpl, CommitMode::Async)?;+ counter!("ingestion_consumer_offset_commits_total").increment(1);+ Ok(())}/// Submit one collected poll to the batcher and track it as in flight.@@ -483,7 +522,7 @@ impl IngestionConsumer {in_flight_polls: &mut VecDeque<InFlightPoll>,completions: &mut mpsc::UnboundedReceiver<GroupCompletion>,errors: &mut mpsc::UnboundedReceiver<String>,- ) -> anyhow::Result<()> {+ ) -> Result<(), Failure> {if in_flight_polls.front().is_none() {return Ok(());}@@ -497,11 +536,15 @@ impl IngestionConsumer {tokio::select! {completion = completions.recv() => match completion {Some(completion) => apply_completion(in_flight_polls, completion),- None => anyhow::bail!("batcher completion channel closed"),+ None => return Err(Failure::Batch(anyhow::anyhow!(+ "batcher completion channel closed"+ ))),},failure = errors.recv() => match failure {- Some(message) => anyhow::bail!(message),- None => anyhow::bail!("batcher error channel closed"),+ Some(message) => return Err(Failure::Batch(anyhow::anyhow!(message))),+ None => return Err(Failure::Batch(anyhow::anyhow!(+ "batcher error channel closed"+ ))),},_ = heartbeat.tick() => self.handle.report_healthy(),}@@ -509,14 +552,17 @@ impl IngestionConsumer {let poll = in_flight_polls.pop_front().expect("front is present");if poll.accepted < poll.message_count {- anyhow::bail!(+ return Err(Failure::Batch(anyhow::anyhow!("accepted {}/{} messages — not committing offsets",poll.accepted,poll.message_count- );+ )));}- self.commit_offsets(&poll.partitions)?;+ self.settle_poll(&poll.partitions);+ if let Some(offsets) = self.commit_sentinel.take_due() {+ self.commit_offsets(&offsets).map_err(Failure::Commit)?;+ }emit_latest_processed_timestamp_metrics(&poll.partitions, &self.group_id);record_if(&self.debug_recorder, || DebugEventKind::BatchCommitted {batch_id: poll.poll_id.clone(),@@ -543,6 +589,20 @@ impl IngestionConsumer {.signal_failure(format!("Batch processing failed: {err:#}"));}+ /// The Kafka client refused a commit. The commit is asynchronous, so this+ /// is a client that cannot commit at all, not a broker verdict. Consuming+ /// on would freeze the committed position while reporting healthy, so the+ /// process exits and restarts.+ fn fail_commit(&self, err: anyhow::Error) {+ error!(error = %err, "Offset commit failed");+ counter!("ingestion_consumer_commit_errors_total").increment(1);+ record_if(&self.debug_recorder, || DebugEventKind::CommitFailed {+ error: format!("{err:#}"),+ });+ self.handle+ .signal_failure(format!("Offset commit failed: {err:#}"));+ }+/// Collect messages from Kafka until the first of `batch_size` messages,/// `batch_size_bytes` of payload (when enabled), or `batch_timeout`.///@@ -701,45 +761,26 @@ impl IngestionConsumer {})}- /// Settle the batch against the ledger and commit each partition's- /// frontier. A partition without a frontier is not committed and stays on- /// its last committed offset.- fn commit_offsets(- &self,- partitions: &HashMap<TopicPartition, PartitionDeliveries>,- ) -> anyhow::Result<()> {+ /// Settle the poll against the ledger and hand each partition's frontier+ /// over for commit. A partition without a frontier stays on its last+ /// commit.+ fn settle_poll(&self, partitions: &HashMap<TopicPartition, PartitionDeliveries>) {if partitions.is_empty() {// Unreachable while batches require messages to be spawned; counted// so "no empty commits" is a measurable guarantee, not an assumption.counter!("ingestion_consumer_commit_violations_total", "kind" => "empty").increment(1);- warn!("Commit requested with no offsets");- return Ok(());+ warn!("Poll settled with no partitions");+ return;}- let mut settled = Vec::with_capacity(partitions.len());- let mut frontier_spans = Vec::with_capacity(partitions.len());- for (topic_partition, partition) in partitions {- // A rejected slice is not committed, and the commit sentinel- // keeps its baseline. A stale slice belongs to an assignment the- // revoke callback already forgot on the sentinel, so the- // partition's next commit rebaselines. A violation reset the- // ledger and dropped what it held, so the partition's next commit- // can pass work still in flight; the sentinel reports that as the- // gap it is.- let Ok(frontier) = self.settle(topic_partition, partition) else {- continue;- };- settled.push(topic_partition);- if let Some(span) = frontier_span(&partition.span, frontier) {- frontier_spans.push((topic_partition, span));- }- }+ let settlement =+ settle_partitions(&self.topic_offset_ledger, &self.commit_sentinel, partitions);- if frontier_spans.is_empty() {+ if settlement.advanced == 0 {// `rejected`: the ledger dropped every slice, expected around a// rebalance. `no_frontier`: a slice landed, but an earlier batch// is still incomplete at the front of every window it settled.- let reason = if settled.is_empty() {+ let reason = if settlement.settled == 0 {"rejected"} else {"no_frontier"@@ -749,75 +790,87 @@ impl IngestionConsumer {reason,"No ledger frontier available for completed offsets; skipping commit");- return Ok(());}+ }+}- self.submit_commit(- frontier_spans- .iter()- .map(|(topic_partition, span)| (*topic_partition, span)),- )?;- for topic_partition in settled {- self.topic_offset_ledger.take_frontier(topic_partition);- }- Ok(())+/// How a poll settled: how many partitions the ledger accepted, how many of+/// those reached a frontier that was handed over for commit, and what the+/// sentinel found on the way. The sentinel has already counted and logged+/// the violations; they are returned for tests.+struct PollSettlement {+ settled: usize,+ advanced: usize,+ violations: Vec<CommitViolation>,+}++/// Settle each partition's slice against the ledger and hand every frontier+/// reached to the sentinel, with the span the poll delivered for it.+fn settle_partitions(+ ledger: &TopicOffsetLedger,+ sentinel: &CommitSentinel,+ partitions: &HashMap<TopicPartition, PartitionDeliveries>,+) -> PollSettlement {+ let mut settlement = PollSettlement {+ settled: 0,+ advanced: 0,+ violations: Vec::new(),+ };+ for (topic_partition, partition) in partitions {+ // A rejected slice is not committed, and the commit sentinel+ // keeps its baseline. A stale slice belongs to an assignment the+ // revoke callback already forgot on the sentinel, so the+ // partition's next commit rebaselines. A violation reset the+ // ledger and dropped what it held, so the partition's next commit+ // can pass work still in flight; the sentinel reports that as the+ // gap it is.+ let Ok(frontier) = settle(ledger, topic_partition, partition) else {+ continue;+ };+ settlement.settled += 1;+ let Some(span) = frontier_span(&partition.span, frontier) else {+ continue;+ };+ let Some(taken) = ledger.take_frontier(topic_partition) else {+ continue;+ };+ settlement+ .violations+ .extend(sentinel.advance_frontier(topic_partition, span, taken));+ settlement.advanced += 1;}+ settlement+}- /// Settle one partition's slice of a batch against the ledger and report- /// the frontier it reached. `Err` when the ledger rejected the slice,- /// which it has already counted and this logs.- fn settle(- &self,- topic_partition: &TopicPartition,- partition: &PartitionDeliveries,- ) -> Result<Option<Offset>, Rejection> {- self.topic_offset_ledger- .settle(+/// Settle one partition's slice of a batch against the ledger and report+/// the frontier it reached. `Err` when the ledger rejected the slice,+/// which it has already counted and this logs.+fn settle(+ ledger: &TopicOffsetLedger,+ topic_partition: &TopicPartition,+ partition: &PartitionDeliveries,+) -> Result<Option<Offset>, Rejection> {+ ledger+ .settle(+ topic_partition,+ partition.generation,+ partition.charges.iter().map(|(offset, _)| *offset),+ )+ .inspect_err(|rejection| {+ warn_rejection(+ "settle",topic_partition,- partition.generation,- partition.charges.iter().map(|(offset, _)| *offset),+ *rejection,+ RejectedSlice::settled(&partition.span),)- .inspect_err(|rejection| {- warn_rejection(- "settle",- topic_partition,- *rejection,- RejectedSlice::settled(&partition.span),- )- })- }-- /// Validate and submit one commit to Kafka.- fn submit_commit<'a>(- &self,- spans: impl IntoIterator<Item = (&'a TopicPartition, &'a OffsetSpan)>,- ) -> anyhow::Result<()> {- let spans: Vec<_> = spans.into_iter().collect();- // Validate contiguity/monotonicity per partition before committing, so- // a violation is attributed to the batch that caused it.- self.commit_sentinel.check_commit(spans.iter().copied());-- let mut tpl = TopicPartitionList::new();- for (topic_partition, span) in &spans {- // Commit offset + 1 (Kafka convention: committed offset = next to read)- tpl.add_partition_offset(- &topic_partition.topic,- topic_partition.partition,- rdkafka::Offset::Offset(span.last + 1),- )?;- }-- self.consumer.commit(&tpl, CommitMode::Async)?;- counter!("ingestion_consumer_offset_commits_total").increment(1);-- Ok(())- }+ })}-/// Map a settled frontier back to the span the commit path submits: the-/// frontier is next-to-read and the span is last-processed, so the commit-/// adds the 1 back and submits the frontier verbatim. `None` for a partition-/// that settled without a frontier; it stays on its last commit.+/// Map a settled frontier back to the span the sentinel checks: the+/// frontier is next-to-read and the span is last-processed, so the span+/// starts at the poll's first delivered offset and ends one before the+/// frontier. `None` for a partition that settled without a frontier; it+/// stays on its last commit.fn frontier_span(span: &OffsetSpan, frontier: Option<Offset>) -> Option<OffsetSpan> {frontier.map(|frontier| OffsetSpan {first: span.first,@@ -902,74 +955,6 @@ fn debug_partition_offsets(.collect()}-/// Aborts the wrapped task when dropped, covering every `process()` exit path.-struct AbortOnDrop(JoinHandle<()>);--impl Drop for AbortOnDrop {- fn drop(&mut self) {- self.0.abort();- }-}--/// How often the commit monitor fetches the group's broker-committed offsets.-const COMMIT_MONITOR_INTERVAL: Duration = Duration::from_secs(30);--/// Periodically fetch the broker's committed offsets for the current-/// assignment (an OffsetFetch round trip) and feed them to the commit-/// sentinel, which compares them against attempted commits and stamps the-/// last-successful-commit gauge on progress.-async fn run_commit_monitor(- consumer: Arc<StreamConsumer<SentinelContext>>,- sentinel: Arc<CommitSentinel>,- handle: Handle,-) {- loop {- tokio::select! {- _ = handle.shutdown_recv() => return,- _ = tokio::time::sleep(COMMIT_MONITOR_INTERVAL) => {}- }-- let fetch_consumer = Arc::clone(&consumer);- // assignment() and committed_offsets() block on librdkafka.- let fetched = tokio::task::spawn_blocking(move || {- let assignment = fetch_consumer.assignment()?;- if assignment.count() == 0 {- return Ok(None);- }- fetch_consumer- .committed_offsets(assignment, Duration::from_secs(5))- .map(Some)- })- .await;-- match fetched {- Ok(Ok(Some(committed))) => {- let observed: Vec<(String, i32, i64)> = committed- .elements()- .iter()- .filter_map(|e| match e.offset() {- rdkafka::Offset::Offset(offset) => {- Some((e.topic().to_string(), e.partition(), offset))- }- // Invalid = no offset stored for the partition yet.- _ => None,- })- .collect();- sentinel.observe_broker_committed(observed);- }- Ok(Ok(None)) => {} // no assignment yet (e.g. before first rebalance)- Ok(Err(err)) => {- counter!("ingestion_consumer_commit_monitor_errors_total").increment(1);- warn!(error = %err, "Commit monitor failed to fetch committed offsets");- }- Err(err) => {- counter!("ingestion_consumer_commit_monitor_errors_total").increment(1);- warn!(error = %err, "Commit monitor task join error");- }- }- }-}-/// One delivered message's cost against the ledger: one event, and the bytes/// the process holds for the message. The byte count is a memory bound, so it/// is the payload plus the key plus every header key and value, not only the@@ -1025,6 +1010,7 @@ fn emit_latest_processed_timestamp_metrics(#[cfg(test)]mod tests {use super::*;+ use crate::commit_sentinel::CommitViolationKind;use common_kafka_consumer::Offset as MessageOffset;fn poll(epoch: u64, partition: i32, first: i64, last: i64, count: u32) -> InFlightPoll {@@ -1100,6 +1086,109 @@ mod tests {assert_eq!(in_flight[0].accepted, 0);}+ /// A poll's slice of one partition, charged to the ledger under the+ /// partition's current generation.+ fn charged(+ ledger: &TopicOffsetLedger,+ topic_partition: &TopicPartition,+ first: i64,+ last: i64,+ ) -> PartitionDeliveries {+ let generation = ledger.generation(topic_partition);+ let partition = PartitionDeliveries {+ span: OffsetSpan { first, last },+ generation,+ generations_version_seen: 0,+ charges: (first..=last)+ .map(|offset| (MessageOffset(offset), Charge::ZERO))+ .collect(),+ latest_kafka_ts: 0,+ max_lag_ms: None,+ };+ ledger+ .charge(+ topic_partition,+ generation,+ partition.charges.iter().copied(),+ )+ .expect("charge");+ partition+ }++ #[test]+ fn a_settled_poll_hands_its_frontier_to_the_pacer() {+ let ledger = TopicOffsetLedger::new();+ let sentinel = CommitSentinel::new(ImmediateCommitPacer::new());+ let tp = TopicPartition::new("test", 0);+ let partitions = HashMap::from([(tp.clone(), charged(&ledger, &tp, 10, 11))]);++ let settlement = settle_partitions(&ledger, &sentinel, &partitions);++ assert_eq!((settlement.settled, settlement.advanced), (1, 1));+ assert_eq!(+ sentinel.take_due(),+ Some(HashMap::from([(tp, MessageOffset(12))]))+ );+ }++ #[test]+ fn a_gap_in_what_kafka_delivered_fires_the_sentinel_and_still_commits() {+ let ledger = TopicOffsetLedger::new();+ let sentinel = CommitSentinel::new(ImmediateCommitPacer::new());+ let tp = TopicPartition::new("test", 0);+ let first = HashMap::from([(tp.clone(), charged(&ledger, &tp, 10, 11))]);+ assert!(settle_partitions(&ledger, &sentinel, &first)+ .violations+ .is_empty());+ assert_eq!(+ sentinel.take_due(),+ Some(HashMap::from([(tp.clone(), MessageOffset(12))]))+ );++ // Offsets 12 and 13 never arrived. The ledger walks the gap, so its+ // take chains from 12; the sentinel must see what was delivered.+ let second = HashMap::from([(tp.clone(), charged(&ledger, &tp, 14, 15))]);+ let settlement = settle_partitions(&ledger, &sentinel, &second);++ assert_eq!(settlement.violations.len(), 1);+ assert_eq!(settlement.violations[0].kind, CommitViolationKind::Gap);+ assert_eq!(settlement.violations[0].prev_committed, 12);+ assert_eq!(settlement.violations[0].span.first, 14);+ assert_eq!(+ sentinel.take_due(),+ Some(HashMap::from([(tp, MessageOffset(16))]))+ );+ }++ #[test]+ fn a_rejected_slice_hands_nothing_to_the_pacer() {+ let ledger = TopicOffsetLedger::new();+ let sentinel = CommitSentinel::new(ImmediateCommitPacer::new());+ let tp = TopicPartition::new("test", 0);+ let partitions = HashMap::from([(tp.clone(), charged(&ledger, &tp, 10, 11))]);+ // The partition left and came back while the poll was in flight.+ ledger.forget_partitions([("test", 0)]);++ let settlement = settle_partitions(&ledger, &sentinel, &partitions);++ assert_eq!((settlement.settled, settlement.advanced), (0, 0));+ assert!(sentinel.take_due().is_none());+ }++ #[test]+ fn a_poll_behind_an_incomplete_one_hands_nothing_to_the_pacer() {+ let ledger = TopicOffsetLedger::new();+ let sentinel = CommitSentinel::new(ImmediateCommitPacer::new());+ let tp = TopicPartition::new("test", 0);+ let _older = charged(&ledger, &tp, 10, 11);+ let newer = HashMap::from([(tp.clone(), charged(&ledger, &tp, 12, 13))]);++ let settlement = settle_partitions(&ledger, &sentinel, &newer);++ assert_eq!((settlement.settled, settlement.advanced), (1, 0));+ assert!(sentinel.take_due().is_none());+ }+#[test]fn frontier_span_submits_the_frontier_verbatim() {let span = OffsetSpan {@@ -1107,14 +1196,14 @@ mod tests {last: 11,};assert_eq!(- frontier_span(&span, Some(Offset(12))),+ frontier_span(&span, Some(MessageOffset(12))),Some(OffsetSpan {first: 10,last: 11}));assert_eq!(- frontier_span(&span, Some(Offset(11))),+ frontier_span(&span, Some(MessageOffset(11))),Some(OffsetSpan {first: 10,last: 10diff --git a/rust/ingestion-consumer/src/debug_recorder.rs b/rust/ingestion-consumer/src/debug_recorder.rsindex 32b4d99ab764..01cd23ceb4cf 100644--- a/rust/ingestion-consumer/src/debug_recorder.rs+++ b/rust/ingestion-consumer/src/debug_recorder.rs@@ -93,6 +93,9 @@ pub enum DebugEventKind {batch_id: Option<String>,error: String,},+ /// An offset commit was refused by the Kafka client; the process will+ /// exit and restart.+ CommitFailed { error: String },/// A worker moved between health states.WorkerStateChanged {worker: String,diff --git a/rust/ingestion-consumer/src/lib.rs b/rust/ingestion-consumer/src/lib.rsindex 8c20c680207f..8e7bd59eeee5 100644--- a/rust/ingestion-consumer/src/lib.rs+++ b/rust/ingestion-consumer/src/lib.rs@@ -1,5 +1,8 @@pub mod aperture;pub mod batcher;+pub mod commit_monitor;+pub mod commit_pacer;+pub mod commit_sentinel;pub mod config;pub mod consumer;pub mod debug_recorder;diff --git a/rust/ingestion-consumer/src/order_sentinel.rs b/rust/ingestion-consumer/src/order_sentinel.rsindex a95e10680a5d..dc6b1dec8c86 100644--- a/rust/ingestion-consumer/src/order_sentinel.rs+++ b/rust/ingestion-consumer/src/order_sentinel.rs@@ -1,14 +1,5 @@-//! Always-on ordering sentinels: cheap invariant checkers that turn the-//! consumer's two core guarantees into alertable metrics.-//!-//! **Commit order** ([`CommitSentinel`]): for every topic-partition, offsets-//! must be committed contiguously and monotonically — each batch's first-//! offset must equal the previously committed offset (no skips), and the-//! committed offset must never move backwards (no out-of-order commits).-//! Checked at commit time in the consumer loop; violations increment-//! `ingestion_consumer_commit_violations_total{kind}` and log the offending-//! offsets. `ingestion_consumer_commits_checked_total` is the denominator: the-//! guarantee holds while it grows and the violation counter stays flat.+//! The per-key send-order sentinel and the consumer's rdkafka context. The+//! commit sentinel lives in [`crate::commit_sentinel`].//!//! **Per-key send order** ([`KeyOrderSentinel`]): for every routing key//! (the Kafka message key), messages must be handed to workers in Kafka offset@@ -25,31 +16,23 @@//! and offsets from different partitions are not comparable. Skipped messages//! are counted in `ingestion_consumer_key_sentinel_unkeyed_total`.//!-//! **Commit confirmation**: "commits are actually made" cannot be observed via-//! `ConsumerContext::commit_callback` — librdkafka drops the result of manual-//! async commits (see the note on [`SentinelContext`]). Instead the consumer's-//! commit monitor periodically fetches the group's broker-committed offsets and-//! feeds [`CommitSentinel::observe_broker_committed`], which emits-//! `ingestion_consumer_broker_committed_offset` and-//! `ingestion_consumer_commit_confirmation_lag` gauges and stamps-//! `ingestion_consumer_last_successful_commit_timestamp_seconds` on progress.-//!//! [`SentinelContext`] is the consumer's rdkafka context: it resets sentinel//! baselines on rebalances, where Kafka legitimately re-deals partitions and-//! both invariants must re-baseline instead of firing false positives.+//! the invariants must re-baseline instead of firing false positives.//!-//! The sentinels are pure observers: they never influence routing or commits.+//! The sentinel is a pure observer: it never influences routing.use std::collections::HashMap;use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex};-use std::time::{SystemTime, UNIX_EPOCH};use metrics::{counter, gauge};use rdkafka::consumer::{BaseConsumer, ConsumerContext, Rebalance};use rdkafka::{ClientContext, Statistics, TopicPartitionList};use tracing::{info, warn};+use crate::commit_pacer::ImmediateCommitPacer;+use crate::commit_sentinel::CommitSentinel;use crate::types::SerializedKafkaMessage;use common_kafka_consumer::{AssignmentEpoch, TopicOffsetLedger, TopicPartition};@@ -75,250 +58,6 @@ impl OffsetSpan {}}-/// How a commit violated the contiguous-monotonic invariant.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum CommitViolationKind {- /// The batch starts past the previously committed offset — the offsets in- /// between were never part of a committed batch (skipped messages).- Gap,- /// The whole batch lies at or behind the committed offset — the commit- /// moves the partition backwards.- OutOfOrder,- /// The batch partially re-covers already-committed offsets.- Overlap,-}--impl CommitViolationKind {- fn as_str(&self) -> &'static str {- match self {- CommitViolationKind::Gap => "gap",- CommitViolationKind::OutOfOrder => "out_of_order",- CommitViolationKind::Overlap => "overlap",- }- }-}--/// One detected commit-order violation, returned for tests and logged.-#[derive(Clone, Debug, PartialEq, Eq)]-pub struct CommitViolation {- pub kind: CommitViolationKind,- pub topic: String,- pub partition: i32,- /// The partition's committed offset (Kafka "next to read") before this batch.- pub prev_committed: i64,- pub span: OffsetSpan,-}--/// Per-partition commit tracking: what this process asked Kafka to commit-/// (attempted) and what the broker has confirmed as the group's committed-/// offset (observed by the commit monitor via OffsetFetch).-#[derive(Default, Clone, Copy)]-struct PartitionCommits {- /// The offset value last submitted for commit (Kafka "next to read").- attempted: Option<i64>,- /// The broker-confirmed committed offset from the last monitor poll.- confirmed: Option<i64>,-}--/// Tracks the last committed offset per topic-partition and checks each new-/// commit for contiguity and monotonicity. The first commit after a partition-/// is (re)assigned establishes a baseline and is never a violation — earlier-/// offsets may have been committed by another consumer in the group.-///-/// Caveat: legitimate offset gaps exist on topics with transactional producers-/// (control records consume offsets). The ingestion topics are produced by-/// capture without transactions, so a gap here is a real skip.-///-/// Because commits use `CommitMode::Async` and librdkafka silently drops the-/// result of manual async commits (no conf-level `offset_commit_cb` is ever-/// registered by rust-rdkafka, so `ConsumerContext::commit_callback` never-/// fires for them), commit *success* is verified out of band: the consumer's-/// commit monitor periodically fetches the group's broker-committed offsets-/// and feeds them to [`CommitSentinel::observe_broker_committed`].-pub struct CommitSentinel {- partitions: Mutex<HashMap<(String, i32), PartitionCommits>>,- /// Kill switch (`CONSUMER_ORDER_SENTINEL_ENABLED`). When off, checks- /// no-op and no state accumulates.- enabled: AtomicBool,-}--impl Default for CommitSentinel {- fn default() -> Self {- Self {- partitions: Mutex::new(HashMap::new()),- enabled: AtomicBool::new(true),- }- }-}--impl CommitSentinel {- pub fn new() -> Self {- Self::default()- }-- pub fn set_enabled(&self, enabled: bool) {- self.enabled.store(enabled, Ordering::Relaxed);- }-- /// Check a batch's offset spans against the previous commit per partition,- /// then advance the tracked committed offset to `span.last + 1`. Emits- /// metrics and logs; returns the violations for tests.- pub fn check_commit<'a>(- &self,- spans: impl IntoIterator<Item = (&'a TopicPartition, &'a OffsetSpan)>,- ) -> Vec<CommitViolation> {- if !self.enabled.load(Ordering::Relaxed) {- return Vec::new();- }- let mut partitions = self.partitions.lock().unwrap();- let mut violations = Vec::new();-- for (topic_partition, span) in spans {- counter!("ingestion_consumer_commits_checked_total").increment(1);-- let topic = &topic_partition.topic;- let partition = &topic_partition.partition;- let state = partitions.entry((topic.clone(), *partition)).or_default();- if let Some(prev) = state.attempted {- let kind = if span.first == prev {- None- } else if span.first > prev {- Some(CommitViolationKind::Gap)- } else if span.last < prev {- Some(CommitViolationKind::OutOfOrder)- } else {- Some(CommitViolationKind::Overlap)- };-- if let Some(kind) = kind {- counter!(- "ingestion_consumer_commit_violations_total",- "kind" => kind.as_str(),- )- .increment(1);- warn!(- kind = kind.as_str(),- topic = %topic,- partition = *partition,- prev_committed = prev,- batch_first = span.first,- batch_last = span.last,- "Commit order violation"- );- violations.push(CommitViolation {- kind,- topic: topic.clone(),- partition: *partition,- prev_committed: prev,- span: *span,- });- }- }-- state.attempted = Some(span.last + 1);- gauge!(- "ingestion_consumer_committed_offset",- "topic" => topic.clone(),- "partition" => partition.to_string(),- )- .set((span.last + 1) as f64);- }-- violations- }-- /// Feed broker-confirmed committed offsets (from an OffsetFetch of the- /// group's assigned partitions) and compare against what this process- /// attempted. Emits per-partition gauges:- ///- /// - `ingestion_consumer_broker_committed_offset` — the group's committed- /// offset as the broker reports it;- /// - `ingestion_consumer_commit_confirmation_lag` — attempted minus- /// confirmed. Transiently positive while async commits are in flight;- /// persistently positive means commits are being submitted but not- /// landing (e.g. a stuck coordinator).- ///- /// Returns true when commits verifiably progressed since the last- /// observation — the broker offset advanced, or everything attempted is- /// confirmed — so the caller can stamp the last-successful-commit gauge.- pub fn observe_broker_committed(- &self,- observed: impl IntoIterator<Item = (String, i32, i64)>,- ) -> bool {- if !self.enabled.load(Ordering::Relaxed) {- return false;- }- let mut partitions = self.partitions.lock().unwrap();- let mut advanced = false;-- for (topic, partition, committed) in observed {- gauge!(- "ingestion_consumer_broker_committed_offset",- "topic" => topic.clone(),- "partition" => partition.to_string(),- )- .set(committed as f64);-- let state = partitions.entry((topic.clone(), partition)).or_default();- if let Some(attempted) = state.attempted {- gauge!(- "ingestion_consumer_commit_confirmation_lag",- "topic" => topic.clone(),- "partition" => partition.to_string(),- )- .set((attempted - committed).max(0) as f64);- }- // Only an increase over a *previous* observation counts as- // progress — the first poll baselines (the broker may be reporting- // a prior incarnation's commits, which say nothing about ours).- if state.confirmed.is_some_and(|prev| committed > prev) {- advanced = true;- }- state.confirmed = Some(committed);- }-- let all_confirmed = {- let attempted_any = partitions.values().any(|s| s.attempted.is_some());- attempted_any- && partitions.values().all(|s| match s.attempted {- Some(attempted) => s.confirmed.is_some_and(|c| c >= attempted),- None => true,- })- };-- let progressed = advanced || all_confirmed;- if progressed {- gauge!("ingestion_consumer_last_successful_commit_timestamp_seconds").set(- SystemTime::now()- .duration_since(UNIX_EPOCH)- .unwrap_or_default()- .as_secs_f64(),- );- }- progressed- }-- /// Drop the baselines for revoked partitions so the next commit after a- /// re-assignment baselines instead of reporting a false gap/overlap- /// (another group member may have committed in between).- pub fn forget_partitions<'a>(&self, revoked: impl IntoIterator<Item = (&'a str, i32)>) {- let mut partitions = self.partitions.lock().unwrap();- for (topic, partition) in revoked {- let forgotten = partitions.remove(&(topic.to_string(), partition));- if forgotten.is_some_and(|state| state.attempted.is_some()) {- let topic: Arc<str> = Arc::from(topic);- let partition: Arc<str> = Arc::from(partition.to_string());- gauge!(- "ingestion_consumer_commit_confirmation_lag",- "topic" => topic,- "partition" => partition,- )- .set(0.0);- }- }- }-}-/// How a send violated the per-key order invariant.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum KeyOrderViolationKind {@@ -577,6 +316,8 @@ impl KeyOrderSentinel {/// restart-time redelivery), resets sentinel baselines around rebalances, and/// exports librdkafka's internal statistics (see [`crate::kafka_stats`]).pub struct SentinelContext {+ /// Where the consumer's frontiers go. Held here so the rebalance+ /// callbacks tell it which partitions leave the assignment.commit_sentinel: Arc<CommitSentinel>,key_sentinel: Arc<KeyOrderSentinel>,/// The offset ledger the commit path settles against. Owned here so the@@ -609,11 +350,12 @@ impl SentinelContext {self.assignment_epoch = Some(epoch);}- /// A context with its own free-standing sentinels and ledger, for tests- /// and tools that build the Kafka consumer separately from the dispatcher.+ /// A context with its own free-standing sentinels, ledger, and commit+ /// pacer, for tests and tools that build the Kafka consumer separately+ /// from the dispatcher.pub fn detached() -> Self {Self::new(- Arc::new(CommitSentinel::new()),+ Arc::new(CommitSentinel::new(ImmediateCommitPacer::new())),Arc::new(KeyOrderSentinel::new()),Arc::new(TopicOffsetLedger::new()),)@@ -628,10 +370,16 @@ impl SentinelContext {}/// Start a new ledger generation for every partition in `tpl`, dropping- /// its window.+ /// its window and any frontier it had ready to commit.fn forget_ledger_partitions(&self, tpl: &TopicPartitionList) {+ let elements = tpl.elements();self.topic_offset_ledger- .forget_partitions(tpl.elements().iter().map(|e| (e.topic(), e.partition())));+ .forget_partitions(elements.iter().map(|e| (e.topic(), e.partition())));+ let topic_partitions: Vec<TopicPartition> = elements+ .iter()+ .map(|e| TopicPartition::new(e.topic(), e.partition()))+ .collect();+ self.commit_sentinel.forget_partitions(&topic_partitions);}}@@ -666,8 +414,6 @@ impl ConsumerContext for SentinelContext {topic_partitions = ?partition_names(tpl),"Rebalance: partitions revoked");- self.commit_sentinel- .forget_partitions(tpl.elements().iter().map(|e| (e.topic(), e.partition())));self.forget_ledger_partitions(tpl);// Revoked partitions may be replayed by another consumer (or by// us after re-assignment) from the last commit — every per-key@@ -714,21 +460,6 @@ impl ConsumerContext for SentinelContext {mod tests {use super::*;- fn spans(entries: &[(&str, i32, i64, i64)]) -> HashMap<TopicPartition, OffsetSpan> {- entries- .iter()- .map(|(topic, partition, first, last)| {- (- TopicPartition::new(*topic, *partition),- OffsetSpan {- first: *first,- last: *last,- },- )- })- .collect()- }-fn msg_at(partition: i32, offset: i64) -> SerializedKafkaMessage {SerializedKafkaMessage {topic: "test".to_string(),@@ -748,104 +479,6 @@ mod tests {}}- // ---- CommitSentinel ------ #[test]- fn contiguous_commits_pass() {- let sentinel = CommitSentinel::new();- assert!(- sentinel.check_commit(&spans(&[("t", 0, 0, 99)])).is_empty(),- "first commit baselines"- );- assert!(- sentinel- .check_commit(&spans(&[("t", 0, 100, 149)]))- .is_empty(),- "next batch starts exactly at the committed offset"- );- }-- #[test]- fn commit_gap_is_detected() {- let sentinel = CommitSentinel::new();- sentinel.check_commit(&spans(&[("t", 0, 0, 99)]));- // Offsets 100..=104 were never committed — the batch skipped them.- let violations = sentinel.check_commit(&spans(&[("t", 0, 105, 150)]));- assert_eq!(violations.len(), 1);- assert_eq!(violations[0].kind, CommitViolationKind::Gap);- assert_eq!(violations[0].prev_committed, 100);- }-- #[test]- fn commit_regression_is_out_of_order() {- let sentinel = CommitSentinel::new();- sentinel.check_commit(&spans(&[("t", 0, 0, 99)]));- let violations = sentinel.check_commit(&spans(&[("t", 0, 10, 50)]));- assert_eq!(violations.len(), 1);- assert_eq!(violations[0].kind, CommitViolationKind::OutOfOrder);- }-- #[test]- fn partial_recommit_is_overlap() {- let sentinel = CommitSentinel::new();- sentinel.check_commit(&spans(&[("t", 0, 0, 99)]));- let violations = sentinel.check_commit(&spans(&[("t", 0, 90, 150)]));- assert_eq!(violations.len(), 1);- assert_eq!(violations[0].kind, CommitViolationKind::Overlap);- }-- #[test]- fn partitions_are_tracked_independently() {- let sentinel = CommitSentinel::new();- sentinel.check_commit(&spans(&[("t", 0, 0, 99), ("t", 1, 0, 9)]));- // Partition 0 continues cleanly; partition 1 skips 10..=19.- let violations = sentinel.check_commit(&spans(&[("t", 0, 100, 120), ("t", 1, 20, 30)]));- assert_eq!(violations.len(), 1);- assert_eq!(violations[0].partition, 1);- assert_eq!(violations[0].kind, CommitViolationKind::Gap);- }-- #[test]- fn broker_observation_baselines_then_tracks_progress() {- let sentinel = CommitSentinel::new();- sentinel.check_commit(&spans(&[("t", 0, 0, 99)])); // attempted next = 100- // First poll baselines: a stale broker offset (previous incarnation)- // is not evidence that OUR commits landed.- assert!(!sentinel.observe_broker_committed([("t".to_string(), 0, 40)]));- // Broker offset advancing across polls = commits are landing.- assert!(sentinel.observe_broker_committed([("t".to_string(), 0, 80)]));- // No advance and still behind the attempted offset = no progress.- assert!(!sentinel.observe_broker_committed([("t".to_string(), 0, 80)]));- // Catching up to everything attempted also counts as progress.- assert!(sentinel.observe_broker_committed([("t".to_string(), 0, 100)]));- // Fully confirmed and idle: repeated identical polls stay "progressed"- // via the all-confirmed arm, keeping the liveness gauge fresh.- assert!(sentinel.observe_broker_committed([("t".to_string(), 0, 100)]));- }-- #[test]- fn broker_observation_requires_every_attempted_partition_confirmed() {- let sentinel = CommitSentinel::new();- sentinel.check_commit(&spans(&[("t", 0, 0, 99), ("t", 1, 0, 9)]));- sentinel.observe_broker_committed([("t".to_string(), 0, 100), ("t".to_string(), 1, 5)]);- // Partition 0 fully confirmed but partition 1 stuck below attempted and- // not advancing: not progress.- assert!(!sentinel- .observe_broker_committed([("t".to_string(), 0, 100), ("t".to_string(), 1, 5)]));- }-- #[test]- fn forgotten_partition_rebaselines_without_violation() {- let sentinel = CommitSentinel::new();- sentinel.check_commit(&spans(&[("t", 0, 0, 99)]));- sentinel.forget_partitions([("t", 0)]);- // After revoke + re-assign another consumer may have committed past us;- // a non-contiguous first commit must baseline, not fire.- assert!(sentinel- .check_commit(&spans(&[("t", 0, 500, 599)]))- .is_empty());- }-// ---- KeyOrderSentinel ----#[test]@@ -965,13 +598,7 @@ mod tests {}#[test]- fn disabled_sentinels_check_nothing_and_hold_no_state() {- let commit = CommitSentinel::new();- commit.set_enabled(false);- commit.check_commit(&spans(&[("t", 0, 0, 99)]));- // A blatant regression passes: the kill switch disarms the check.- assert!(commit.check_commit(&spans(&[("t", 0, 10, 50)])).is_empty());-+ fn a_disabled_key_sentinel_checks_nothing_and_holds_no_state() {let keys = KeyOrderSentinel::new();keys.set_enabled(false);keys.note_sent("t:a", &[msg_at(0, 5)], SendKind::Fresh);