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(ingestion-consumer): shadow offset ledger commits (#91764)

Paweł Ledwoń9000fadc37eb
diff --git a/rust/common/kafka-consumer/src/charge.rs b/rust/common/kafka-consumer/src/charge.rs
index 75bac14262e1..17bb3a17b8b3 100644
--- a/rust/common/kafka-consumer/src/charge.rs
+++ b/rust/common/kafka-consumer/src/charge.rs
@@ -1,5 +1,5 @@
use std::iter::Sum;
-use std::ops::{Add, AddAssign};
+use std::ops::{Add, AddAssign, Sub, SubAssign};
/// A message's cost against later consumer admission budgets.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
@@ -32,6 +32,23 @@ impl AddAssign for Charge {
}
}
+impl Sub for Charge {
+ type Output = Charge;
+
+ fn sub(self, rhs: Charge) -> Self::Output {
+ Charge {
+ events: self.events - rhs.events,
+ bytes: self.bytes - rhs.bytes,
+ }
+ }
+}
+
+impl SubAssign for Charge {
+ fn sub_assign(&mut self, rhs: Charge) {
+ *self = *self - rhs;
+ }
+}
+
impl Sum for Charge {
fn sum<I: Iterator<Item = Charge>>(iter: I) -> Self {
iter.fold(Charge::ZERO, Add::add)
diff --git a/rust/common/kafka-consumer/src/ledger.rs b/rust/common/kafka-consumer/src/ledger.rs
deleted file mode 100644
index 01c6de2039a8..000000000000
--- a/rust/common/kafka-consumer/src/ledger.rs
+++ /dev/null
@@ -1,271 +0,0 @@
-use std::collections::VecDeque;
-
-use crate::charge::Charge;
-use crate::types::Offset;
-
-#[derive(Debug)]
-struct Slot {
- complete: bool,
- charge: Charge,
-}
-
-/// A consumed contiguous prefix: its commit-ready frontier and the charge it
-/// covers.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub struct TakenFrontier {
- pub offset: Offset,
- pub charge: Charge,
-}
-
-/// Per-partition offset accounting: record offsets as they are delivered,
-/// complete them in any order, and read the frontier in Kafka's
-/// committed-offset representation. Observing the frontier never changes it;
-/// a commit point consumes it with `take_frontier`.
-///
-/// Charge every record the poll delivers, including records the caller drops
-/// without processing: an omitted offset is indistinguishable from an offset
-/// Kafka never delivered, and the frontier commits past it as if it held no
-/// message.
-///
-/// A ledger lives for one partition assignment: create it on assign, drop it
-/// on revoke. Kafka replays a partition from its committed offset after a
-/// rebalance, so a ledger kept across assignments sees the replay as
-/// duplicate delivery and panics. Completions from a previous assignment's
-/// in-flight work must be discarded before they reach the new ledger; it
-/// never charged those offsets and panics on them too (see the panic
-/// contracts on `charge` and `complete`).
-#[derive(Debug, Default)]
-pub struct OffsetLedger {
- /// The offset of `slots[0]`; `None` until the first delivery.
- base_offset: Option<Offset>,
- /// Number of completed slots at the front of the window, kept current on
- /// every completion so `frontier` stays O(1).
- prefix: usize,
- /// A dense sliding window over one contiguous offset range: `charge`
- /// appends at the back, `take_frontier` pops the front, and `complete`
- /// indexes by offset minus `base_offset`. Every operation is amortized constant
- /// time per offset.
- slots: VecDeque<Slot>,
-}
-
-impl OffsetLedger {
- pub fn new() -> Self {
- Self::default()
- }
-
- /// Record offsets in delivery order and return their total charge. An
- /// offset gap (transaction control records) never blocks the frontier and
- /// carries no charge.
- ///
- /// # Panics
- ///
- /// When an offset is not above every offset already recorded. Duplicate
- /// or out-of-order delivery is a caller bug, and recording it would
- /// corrupt the commit accounting.
- pub fn charge(&mut self, offsets: impl IntoIterator<Item = (Offset, Charge)>) -> Charge {
- let mut total = Charge::ZERO;
- for (offset, charge) in offsets {
- let base_offset = *self.base_offset.get_or_insert(offset);
- let next_offset = base_offset + self.slots.len();
- assert!(
- offset >= next_offset,
- "offset {offset} delivered below the window's next offset {next_offset}"
- );
- // A gap becomes pre-completed zero-charge filler so the index
- // math stays aligned with offsets.
- for _ in 0..offset - next_offset {
- self.slots.push_back(Slot {
- complete: true,
- charge: Charge::ZERO,
- });
- }
- self.slots.push_back(Slot {
- complete: false,
- charge,
- });
- total += charge;
- }
- total
- }
-
- /// Mark delivered offsets complete in any order.
- ///
- /// # Panics
- ///
- /// When an offset was never charged, was completed before, or was already
- /// consumed by `take_frontier`. Each case means the completion does not
- /// belong to this ledger's window, and marking it would corrupt the
- /// commit accounting.
- pub fn complete(&mut self, offsets: &[Offset]) {
- let base_offset = self.base_offset.expect("completion before any delivery");
- for &offset in offsets {
- let slot_index =
- usize::try_from(offset - base_offset).expect("completion below the window base");
- let slot = self
- .slots
- .get_mut(slot_index)
- .expect("completion for an uncharged offset");
- assert!(!slot.complete, "offset {offset} completed twice");
- slot.complete = true;
- }
- while self
- .slots
- .get(self.prefix)
- .is_some_and(|slot| slot.complete)
- {
- self.prefix += 1;
- }
- }
-
- /// The next offset to read: one past the highest contiguous completed
- /// offset, in Kafka's committed-offset representation, so a commit uses
- /// it verbatim. `None` before the first completion.
- pub fn frontier(&self) -> Option<Offset> {
- let base_offset = self.base_offset?;
- (self.prefix > 0).then(|| base_offset + self.prefix)
- }
-
- /// Take the frontier and the charge of everything below it, forgetting
- /// that span. Kept separate from `complete` so that reading the frontier
- /// has no side effects and only commit points consume it.
- pub fn take_frontier(&mut self) -> Option<TakenFrontier> {
- let frontier_offset = self.frontier()?;
- let charge = self
- .slots
- .drain(..self.prefix)
- .map(|slot| slot.charge)
- .sum();
- self.base_offset = Some(frontier_offset);
- self.prefix = 0;
- Some(TakenFrontier {
- offset: frontier_offset,
- charge,
- })
- }
-
- pub fn len(&self) -> usize {
- self.slots.len()
- }
-
- pub fn is_empty(&self) -> bool {
- self.slots.is_empty()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn charge(offset: i64) -> (Offset, Charge) {
- (
- Offset(offset),
- Charge {
- events: 1,
- bytes: 10,
- },
- )
- }
-
- #[test]
- fn out_of_order_completion_does_not_move_the_frontier() {
- let mut ledger = OffsetLedger::new();
- ledger.charge([charge(0), charge(1), charge(2)]);
- ledger.complete(&[Offset(2)]);
- assert_eq!(ledger.frontier(), None);
- assert_eq!(ledger.take_frontier(), None);
- ledger.complete(&[Offset(0), Offset(1)]);
- assert_eq!(ledger.frontier(), Some(Offset(3)));
- }
-
- #[test]
- fn a_partial_take_keeps_the_remainder_completable() {
- let mut ledger = OffsetLedger::new();
- ledger.charge([charge(0), charge(1), charge(2)]);
- ledger.complete(&[Offset(0)]);
- let taken = ledger.take_frontier().unwrap();
- assert_eq!(taken.offset, Offset(1));
- assert_eq!(taken.charge.events, 1);
- assert_eq!(ledger.len(), 2);
- ledger.complete(&[Offset(1), Offset(2)]);
- assert_eq!(ledger.frontier(), Some(Offset(3)));
- assert_eq!(ledger.take_frontier().unwrap().charge.events, 2);
- }
-
- #[test]
- #[should_panic(expected = "delivered below the window's next offset")]
- fn duplicate_delivery_panics() {
- let mut ledger = OffsetLedger::new();
- ledger.charge([charge(0), charge(1)]);
- ledger.charge([charge(1)]);
- }
-
- #[test]
- #[should_panic(expected = "completed twice")]
- fn double_completion_panics() {
- let mut ledger = OffsetLedger::new();
- ledger.charge([charge(0)]);
- ledger.complete(&[Offset(0)]);
- ledger.complete(&[Offset(0)]);
- }
-
- #[test]
- #[should_panic(expected = "completion for an uncharged offset")]
- fn completing_an_undelivered_offset_panics() {
- let mut ledger = OffsetLedger::new();
- ledger.charge([charge(0)]);
- ledger.complete(&[Offset(5)]);
- }
-
- #[test]
- #[should_panic(expected = "completion below the window base")]
- fn completing_below_the_window_after_a_take_panics() {
- let mut ledger = OffsetLedger::new();
- ledger.charge([charge(0), charge(1)]);
- ledger.complete(&[Offset(0)]);
- ledger.take_frontier().unwrap();
- ledger.complete(&[Offset(0)]);
- }
-
- #[test]
- fn frontier_is_idempotent_and_take_drains_it() {
- let mut ledger = OffsetLedger::new();
- ledger.charge([charge(0), charge(1)]);
- ledger.complete(&[Offset(0), Offset(1)]);
- assert_eq!(ledger.frontier(), Some(Offset(2)));
- assert_eq!(ledger.frontier(), Some(Offset(2)));
- assert_eq!(ledger.take_frontier().unwrap().charge.events, 2);
- assert_eq!(ledger.len(), 0);
- }
-
- #[test]
- fn delivery_gaps_do_not_block_delivered_offsets() {
- let mut ledger = OffsetLedger::new();
- ledger.charge([charge(0), charge(3)]);
- ledger.complete(&[Offset(0), Offset(3)]);
- assert_eq!(ledger.frontier(), Some(Offset(4)));
- }
-
- #[test]
- fn gap_filler_carries_no_charge_and_the_frontier_walks_over_it() {
- let mut ledger = OffsetLedger::new();
- ledger.charge([charge(0), charge(3)]);
- ledger.complete(&[Offset(0)]);
- assert_eq!(ledger.frontier(), Some(Offset(3)));
- ledger.complete(&[Offset(3)]);
- let taken = ledger.take_frontier().unwrap();
- assert_eq!(taken.offset, Offset(4));
- assert_eq!(taken.charge.events, 2);
- }
-
- #[test]
- fn the_window_slides_across_take_frontier() {
- let mut ledger = OffsetLedger::new();
- ledger.charge([charge(0), charge(1)]);
- ledger.complete(&[Offset(0), Offset(1)]);
- ledger.take_frontier().unwrap();
- ledger.charge([charge(2)]);
- ledger.complete(&[Offset(2)]);
- assert_eq!(ledger.frontier(), Some(Offset(3)));
- assert_eq!(ledger.take_frontier().unwrap().charge.events, 1);
- }
-}
diff --git a/rust/common/kafka-consumer/src/lib.rs b/rust/common/kafka-consumer/src/lib.rs
index 08b5aa5752ec..dd79297194ad 100644
--- a/rust/common/kafka-consumer/src/lib.rs
+++ b/rust/common/kafka-consumer/src/lib.rs
@@ -3,11 +3,13 @@
pub mod accumulator;
pub mod charge;
pub mod config;
-pub mod ledger;
+pub mod partition_offset_ledger;
+pub mod topic_offset_ledger;
pub mod types;
pub use accumulator::{Accumulator, Group, GroupMessage, PolledMessage};
pub use charge::Charge;
pub use config::ConsumerConfigBuilder;
-pub use ledger::{OffsetLedger, TakenFrontier};
+pub use partition_offset_ledger::{Held, LedgerError, PartitionOffsetLedger, TakenFrontier};
+pub use topic_offset_ledger::{Rejection, Settlement, TopicOffsetLedger, TopicPartition};
pub use types::{Offset, Partition};
diff --git a/rust/common/kafka-consumer/src/partition_offset_ledger.rs b/rust/common/kafka-consumer/src/partition_offset_ledger.rs
new file mode 100644
index 000000000000..1f91ba650f6d
--- /dev/null
+++ b/rust/common/kafka-consumer/src/partition_offset_ledger.rs
@@ -0,0 +1,426 @@
+use std::collections::VecDeque;
+use std::fmt;
+
+use crate::charge::Charge;
+use crate::types::Offset;
+
+#[derive(Debug)]
+struct Slot {
+ complete: bool,
+ charge: Charge,
+}
+
+/// A charge or completion the ledger's window cannot account for. The ledger
+/// checks each offset as it applies it, so on an error the window holds the
+/// offsets applied before the offending one; the owner discards the ledger
+/// rather than reasoning about that state.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum LedgerError {
+ /// A charge delivered an offset that is not above every offset already
+ /// recorded.
+ OffsetNotAboveWindow { offset: Offset, next: Offset },
+ /// A completion arrived before any delivery was charged.
+ CompletionBeforeDelivery { offset: Offset },
+ /// A completion for an offset `take_frontier` already consumed.
+ CompletionBelowWindow { offset: Offset, base: Offset },
+ /// A completion for an offset the window never charged.
+ CompletionUncharged { offset: Offset },
+ /// A completion for an offset completed before.
+ CompletedTwice { offset: Offset },
+}
+
+impl LedgerError {
+ /// A stable label for metrics.
+ pub fn kind(&self) -> &'static str {
+ match self {
+ LedgerError::OffsetNotAboveWindow { .. } => "offset_not_above_window",
+ LedgerError::CompletionBeforeDelivery { .. } => "completion_before_delivery",
+ LedgerError::CompletionBelowWindow { .. } => "completion_below_window",
+ LedgerError::CompletionUncharged { .. } => "completion_uncharged",
+ LedgerError::CompletedTwice { .. } => "completed_twice",
+ }
+ }
+}
+
+impl fmt::Display for LedgerError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ LedgerError::OffsetNotAboveWindow { offset, next } => {
+ write!(
+ f,
+ "offset {offset} delivered but not above the window's next offset {next}"
+ )
+ }
+ LedgerError::CompletionBeforeDelivery { offset } => {
+ write!(f, "offset {offset} completed before any delivery")
+ }
+ LedgerError::CompletionBelowWindow { offset, base } => {
+ write!(f, "offset {offset} completed below the window base {base}")
+ }
+ LedgerError::CompletionUncharged { offset } => {
+ write!(f, "offset {offset} completed but never charged")
+ }
+ LedgerError::CompletedTwice { offset } => write!(f, "offset {offset} completed twice"),
+ }
+ }
+}
+
+impl std::error::Error for LedgerError {}
+
+/// A consumed contiguous prefix: its commit-ready frontier and the charge it
+/// covers.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct TakenFrontier {
+ pub offset: Offset,
+ pub charge: Charge,
+}
+
+/// What a window holds: the offsets charged and not yet drained by
+/// `take_frontier`, and the charge they carry.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct Held {
+ pub offsets: usize,
+ pub charge: Charge,
+}
+
+/// Per-partition offset accounting: record offsets as they are delivered,
+/// complete them in any order, and read the frontier in Kafka's
+/// committed-offset representation. Observing the frontier never changes it;
+/// a commit point consumes it with `take_frontier`.
+///
+/// Charge every record the poll delivers, including records the caller drops
+/// without processing: an omitted offset is indistinguishable from an offset
+/// Kafka never delivered, and the frontier commits past it as if it held no
+/// message.
+///
+/// A ledger lives for one partition assignment: create it on assign, drop it
+/// on revoke. Kafka redelivers a partition from its committed offset after a
+/// rebalance, so a ledger kept across assignments sees the redelivery as
+/// duplicate delivery and rejects it. Completions from a previous
+/// assignment's in-flight work must be discarded before they reach the new
+/// ledger; it never charged those offsets and rejects them too. Both come
+/// back as a [`LedgerError`]: the ledger never panics, so an owner holding
+/// it under a lock stays usable.
+#[derive(Debug)]
+pub struct PartitionOffsetLedger {
+ /// The partition generation this ledger was founded under. The owner
+ /// compares it with the stamp on incoming work to drop work from an
+ /// earlier assignment.
+ generation: u64,
+ /// The offset of `slots[0]`; `None` until the first delivery.
+ base_offset: Option<Offset>,
+ /// Number of completed slots at the front of the window, kept current on
+ /// every completion so `frontier` stays O(1).
+ completed_prefix_len: usize,
+ /// Charge of every slot in the window, kept current on every charge and
+ /// take so `held` stays O(1).
+ held_charge: Charge,
+ /// A dense sliding window over one contiguous offset range: `charge`
+ /// appends at the back, `take_frontier` pops the front, and `complete`
+ /// indexes by offset minus `base_offset`. Every operation is amortized constant
+ /// time per offset.
+ slots: VecDeque<Slot>,
+}
+
+impl PartitionOffsetLedger {
+ pub fn new(generation: u64) -> Self {
+ Self {
+ generation,
+ base_offset: None,
+ completed_prefix_len: 0,
+ held_charge: Charge::ZERO,
+ slots: VecDeque::new(),
+ }
+ }
+
+ /// The partition generation this ledger was founded under.
+ pub fn generation(&self) -> u64 {
+ self.generation
+ }
+
+ /// Record offsets in delivery order and return their total charge. An
+ /// offset gap (transaction control records) never blocks the frontier and
+ /// carries no charge.
+ ///
+ /// Fails when an offset is not above every offset already recorded.
+ /// Duplicate or out-of-order delivery is a caller bug, and recording it
+ /// would corrupt the commit accounting.
+ pub fn charge(
+ &mut self,
+ offset_charges: impl IntoIterator<Item = (Offset, Charge)>,
+ ) -> Result<Charge, LedgerError> {
+ let mut total = Charge::ZERO;
+ for (offset, charge) in offset_charges {
+ let base_offset = *self.base_offset.get_or_insert(offset);
+ let next_offset = base_offset + self.slots.len();
+ if offset < next_offset {
+ return Err(LedgerError::OffsetNotAboveWindow {
+ offset,
+ next: next_offset,
+ });
+ }
+ // A gap becomes pre-completed zero-charge filler so the index
+ // math stays aligned with offsets.
+ for _ in 0..offset - next_offset {
+ self.slots.push_back(Slot {
+ complete: true,
+ charge: Charge::ZERO,
+ });
+ }
+ self.slots.push_back(Slot {
+ complete: false,
+ charge,
+ });
+ total += charge;
+ self.held_charge += charge;
+ }
+ Ok(total)
+ }
+
+ /// Mark delivered offsets complete in any order.
+ ///
+ /// Fails when an offset was never charged, was completed before, or was
+ /// already consumed by `take_frontier`. Each case means the completion
+ /// does not belong to this ledger's window, and marking it would corrupt
+ /// the commit accounting.
+ pub fn complete(
+ &mut self,
+ offsets: impl IntoIterator<Item = Offset>,
+ ) -> Result<(), LedgerError> {
+ for offset in offsets {
+ let Some(base_offset) = self.base_offset else {
+ return Err(LedgerError::CompletionBeforeDelivery { offset });
+ };
+ let slot_index = usize::try_from(offset - base_offset).map_err(|_| {
+ LedgerError::CompletionBelowWindow {
+ offset,
+ base: base_offset,
+ }
+ })?;
+ let slot = self
+ .slots
+ .get_mut(slot_index)
+ .ok_or(LedgerError::CompletionUncharged { offset })?;
+ if slot.complete {
+ return Err(LedgerError::CompletedTwice { offset });
+ }
+ slot.complete = true;
+ }
+ while self
+ .slots
+ .get(self.completed_prefix_len)
+ .is_some_and(|slot| slot.complete)
+ {
+ self.completed_prefix_len += 1;
+ }
+ Ok(())
+ }
+
+ /// The next offset to read: one past the highest contiguous completed
+ /// offset, in Kafka's committed-offset representation, so a commit uses
+ /// it verbatim. `None` before the first completion.
+ pub fn frontier(&self) -> Option<Offset> {
+ let base_offset = self.base_offset?;
+ (self.completed_prefix_len > 0).then(|| base_offset + self.completed_prefix_len)
+ }
+
+ /// Take the frontier and the charge of everything below it, forgetting
+ /// that span. Kept separate from `complete` so that reading the frontier
+ /// has no side effects and only commit points consume it.
+ pub fn take_frontier(&mut self) -> Option<TakenFrontier> {
+ let frontier_offset = self.frontier()?;
+ let charge = self
+ .slots
+ .drain(..self.completed_prefix_len)
+ .map(|slot| slot.charge)
+ .sum();
+ self.held_charge -= charge;
+ self.base_offset = Some(frontier_offset);
+ self.completed_prefix_len = 0;
+ Some(TakenFrontier {
+ offset: frontier_offset,
+ charge,
+ })
+ }
+
+ /// What the window still holds: offsets charged and not yet drained by
+ /// `take_frontier`, and their charge.
+ pub fn held(&self) -> Held {
+ Held {
+ offsets: self.slots.len(),
+ charge: self.held_charge,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn charge(offset: i64) -> (Offset, Charge) {
+ (
+ Offset(offset),
+ Charge {
+ events: 1,
+ bytes: 10,
+ },
+ )
+ }
+
+ #[test]
+ fn out_of_order_completion_does_not_move_the_frontier() {
+ let mut ledger = PartitionOffsetLedger::new(1);
+ ledger.charge([charge(0), charge(1), charge(2)]).unwrap();
+ ledger.complete([Offset(2)]).unwrap();
+ assert_eq!(ledger.frontier(), None);
+ assert_eq!(ledger.take_frontier(), None);
+ ledger.complete([Offset(0), Offset(1)]).unwrap();
+ assert_eq!(ledger.frontier(), Some(Offset(3)));
+ }
+
+ #[test]
+ fn a_partial_take_keeps_the_remainder_completable() {
+ let mut ledger = PartitionOffsetLedger::new(1);
+ ledger.charge([charge(0), charge(1), charge(2)]).unwrap();
+ ledger.complete([Offset(0)]).unwrap();
+ let taken = ledger.take_frontier().unwrap();
+ assert_eq!(taken.offset, Offset(1));
+ assert_eq!(taken.charge.events, 1);
+ assert_eq!(ledger.held().offsets, 2);
+ ledger.complete([Offset(1), Offset(2)]).unwrap();
+ assert_eq!(ledger.frontier(), Some(Offset(3)));
+ assert_eq!(ledger.take_frontier().unwrap().charge.events, 2);
+ }
+
+ #[test]
+ fn duplicate_delivery_is_rejected() {
+ let mut ledger = PartitionOffsetLedger::new(1);
+ ledger.charge([charge(0), charge(1)]).unwrap();
+ assert_eq!(
+ ledger.charge([charge(1)]),
+ Err(LedgerError::OffsetNotAboveWindow {
+ offset: Offset(1),
+ next: Offset(2),
+ })
+ );
+ }
+
+ #[test]
+ fn completion_before_any_delivery_is_rejected() {
+ let mut ledger = PartitionOffsetLedger::new(1);
+ assert_eq!(
+ ledger.complete([Offset(0)]),
+ Err(LedgerError::CompletionBeforeDelivery { offset: Offset(0) })
+ );
+ }
+
+ #[test]
+ fn double_completion_is_rejected() {
+ let mut ledger = PartitionOffsetLedger::new(1);
+ ledger.charge([charge(0)]).unwrap();
+ ledger.complete([Offset(0)]).unwrap();
+ assert_eq!(
+ ledger.complete([Offset(0)]),
+ Err(LedgerError::CompletedTwice { offset: Offset(0) })
+ );
+ }
+
+ #[test]
+ fn completing_an_undelivered_offset_is_rejected() {
+ let mut ledger = PartitionOffsetLedger::new(1);
+ ledger.charge([charge(0)]).unwrap();
+ assert_eq!(
+ ledger.complete([Offset(5)]),
+ Err(LedgerError::CompletionUncharged { offset: Offset(5) })
+ );
+ }
+
+ #[test]
+ fn completing_below_the_window_after_a_take_is_rejected() {
+ let mut ledger = PartitionOffsetLedger::new(1);
+ ledger.charge([charge(0), charge(1)]).unwrap();
+ ledger.complete([Offset(0)]).unwrap();
+ ledger.take_frontier().unwrap();
+ assert_eq!(
+ ledger.complete([Offset(0)]),
+ Err(LedgerError::CompletionBelowWindow {
+ offset: Offset(0),
+ base: Offset(1),
+ })
+ );
+ }
+
+ #[test]
+ fn frontier_is_idempotent_and_take_drains_it() {
+ let mut ledger = PartitionOffsetLedger::new(1);
+ ledger.charge([charge(0), charge(1)]).unwrap();
+ ledger.complete([Offset(0), Offset(1)]).unwrap();
+ assert_eq!(ledger.frontier(), Some(Offset(2)));
+ assert_eq!(ledger.frontier(), Some(Offset(2)));
+ assert_eq!(ledger.take_frontier().unwrap().charge.events, 2);
+ assert_eq!(ledger.held().offsets, 0);
+ }
+
+ #[test]
+ fn delivery_gaps_do_not_block_delivered_offsets() {
+ let mut ledger = PartitionOffsetLedger::new(1);
+ ledger.charge([charge(0), charge(3)]).unwrap();
+ ledger.complete([Offset(0), Offset(3)]).unwrap();
+ assert_eq!(ledger.frontier(), Some(Offset(4)));
+ }
+
+ #[test]
+ fn gap_filler_carries_no_charge_and_the_frontier_walks_over_it() {
+ let mut ledger = PartitionOffsetLedger::new(1);
+ ledger.charge([charge(0), charge(3)]).unwrap();
+ ledger.complete([Offset(0)]).unwrap();
+ assert_eq!(ledger.frontier(), Some(Offset(3)));
+ ledger.complete([Offset(3)]).unwrap();
+ let taken = ledger.take_frontier().unwrap();
+ assert_eq!(taken.offset, Offset(4));
+ assert_eq!(taken.charge.events, 2);
+ }
+
+ #[test]
+ fn held_charge_follows_charges_and_takes() {
+ let mut ledger = PartitionOffsetLedger::new(1);
+ ledger.charge([charge(0), charge(1), charge(3)]).unwrap();
+ assert_eq!(
+ ledger.held(),
+ Held {
+ offsets: 4,
+ charge: Charge {
+ events: 3,
+ bytes: 30
+ }
+ },
+ "gap filler holds a slot but no charge"
+ );
+
+ // The take drains the completed prefix, gap filler included.
+ ledger.complete([Offset(0), Offset(1)]).unwrap();
+ ledger.take_frontier().unwrap();
+ assert_eq!(
+ ledger.held(),
+ Held {
+ offsets: 1,
+ charge: Charge {
+ events: 1,
+ bytes: 10
+ }
+ }
+ );
+ }
+
+ #[test]
+ fn the_window_slides_across_take_frontier() {
+ let mut ledger = PartitionOffsetLedger::new(1);
+ ledger.charge([charge(0), charge(1)]).unwrap();
+ ledger.complete([Offset(0), Offset(1)]).unwrap();
+ ledger.take_frontier().unwrap();
+ 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);
+ }
+}
diff --git a/rust/common/kafka-consumer/src/topic_offset_ledger.rs b/rust/common/kafka-consumer/src/topic_offset_ledger.rs
new file mode 100644
index 000000000000..e34ab118fccd
--- /dev/null
+++ b/rust/common/kafka-consumer/src/topic_offset_ledger.rs
@@ -0,0 +1,573 @@
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::Mutex;
+
+use crate::charge::Charge;
+use crate::partition_offset_ledger::{Held, LedgerError, PartitionOffsetLedger};
+use crate::types::Offset;
+
+/// A partition of a named topic, the key for everything the ledger tracks.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct TopicPartition {
+ pub topic: String,
+ pub partition: i32,
+}
+
+impl TopicPartition {
+ pub fn new(topic: impl Into<String>, partition: i32) -> Self {
+ Self {
+ topic: topic.into(),
+ partition,
+ }
+ }
+}
+
+/// Why a charge or settlement did not land on its partition's ledger.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Rejection {
+ /// The work predates the partition's current assignment. Kafka
+ /// redelivers its offsets under the current one, so nothing is lost.
+ Stale { stamp: u64, generation: u64 },
+ /// The work violated the ledger's contract. The partition's window is
+ /// unknown after this, so its ledger was reset to a new generation: work
+ /// in flight drops as stale, and the next delivery founds a fresh ledger.
+ Violation(LedgerError),
+}
+
+/// One batch's settled view of its partition ledger: the frontier after its
+/// offsets landed, plus the context a mismatch report needs.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Settlement {
+ /// Next-to-read frontier, `None` while the first offset of the window is
+ /// still incomplete.
+ pub frontier: Option<Offset>,
+ /// What the window still holds after the completion.
+ pub held: Held,
+ pub generation: u64,
+}
+
+/// One [`PartitionOffsetLedger`] per partition, each founded under a
+/// per-partition generation. Forgetting a partition advances its generation and
+/// replaces its ledger in one step, so charges and completions stamped with an
+/// earlier generation are dropped instead of corrupting the new assignment.
+///
+/// Staleness is one rule: work whose stamp is below the partition's current
+/// generation is stale. Generations are independent per partition, so one
+/// partition's reassignment never affects another's in-flight work.
+#[derive(Default)]
+pub struct TopicOffsetLedger {
+ partitions: Mutex<HashMap<TopicPartition, PartitionOffsetLedger>>,
+ /// Version of the per-partition generation map: moves whenever any
+ /// partition's generation does. A caller stamping work outside the lock
+ /// reads this per message and only re-reads the partition's generation
+ /// when it moved.
+ generations_version: AtomicU64,
+}
+
+impl TopicOffsetLedger {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// The partition's current generation, for stamping work as it is
+ /// buffered; 0 for a partition the ledger has never seen.
+ pub fn generation(&self, topic_partition: &TopicPartition) -> u64 {
+ self.partitions
+ .lock()
+ .unwrap()
+ .get(topic_partition)
+ .map(PartitionOffsetLedger::generation)
+ .unwrap_or_default()
+ }
+
+ /// Version of the per-partition generation map. Cheaper than
+ /// `generation` and moves whenever any generation does, so a caller
+ /// compares it per message and consults `generation` only on a change.
+ pub fn generations_version(&self) -> u64 {
+ self.generations_version.load(Ordering::Relaxed)
+ }
+
+ /// Record one slice of delivered offsets on the partition's ledger,
+ /// founding the ledger when the slice is the partition's first delivery.
+ /// Returns what the partition's window holds after the charge, or why
+ /// the slice was rejected.
+ pub fn charge(
+ &self,
+ topic_partition: &TopicPartition,
+ stamp: u64,
+ offset_charges: impl IntoIterator<Item = (Offset, Charge)>,
+ ) -> Result<Held, Rejection> {
+ let mut partitions = self.partitions.lock().unwrap();
+ let ledger = partitions
+ .entry(topic_partition.clone())
+ .or_insert_with(|| PartitionOffsetLedger::new(0));
+ let generation = ledger.generation();
+ if stamp < generation {
+ return Err(Rejection::Stale { stamp, generation });
+ }
+ match ledger.charge(offset_charges) {
+ Ok(_) => Ok(ledger.held()),
+ Err(error) => {
+ *ledger = PartitionOffsetLedger::new(generation + 1);
+ self.generations_version.fetch_add(1, Ordering::Relaxed);
+ Err(Rejection::Violation(error))
+ }
+ }
+ }
+
+ /// Settle one batch's offsets, stamped with the generation they were
+ /// buffered under: mark them complete on the partition's ledger and
+ /// report the frontier that results. The window holds the offsets until
+ /// `take_frontier` drains them.
+ pub fn settle(
+ &self,
+ topic_partition: &TopicPartition,
+ stamp: u64,
+ offsets: impl IntoIterator<Item = Offset>,
+ ) -> Result<Settlement, Rejection> {
+ let mut partitions = self.partitions.lock().unwrap();
+ let Some(ledger) = partitions.get_mut(topic_partition) else {
+ // Nothing was ever charged, so the batch cannot have been either.
+ return Err(Rejection::Stale {
+ stamp,
+ generation: 0,
+ });
+ };
+ let generation = ledger.generation();
+ if stamp < generation {
+ return Err(Rejection::Stale { stamp, generation });
+ }
+ match ledger.complete(offsets) {
+ Ok(()) => Ok(Settlement {
+ frontier: ledger.frontier(),
+ held: ledger.held(),
+ generation,
+ }),
+ Err(error) => {
+ *ledger = PartitionOffsetLedger::new(generation + 1);
+ self.generations_version.fetch_add(1, Ordering::Relaxed);
+ Err(Rejection::Violation(error))
+ }
+ }
+ }
+
+ /// 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.
+ pub fn take_frontier(&self, topic_partition: &TopicPartition) -> Option<Offset> {
+ let mut partitions = self.partitions.lock().unwrap();
+ let ledger = partitions.get_mut(topic_partition)?;
+ ledger.take_frontier().map(|taken| taken.offset)
+ }
+
+ /// What the partition's window still holds; nothing without a ledger.
+ pub fn held(&self, topic_partition: &TopicPartition) -> Held {
+ self.partitions
+ .lock()
+ .unwrap()
+ .get(topic_partition)
+ .map(PartitionOffsetLedger::held)
+ .unwrap_or_default()
+ }
+
+ /// Start a new generation for each partition, dropping its ledger. Called
+ /// when a partition is revoked or assigned: Kafka redelivers it from the
+ /// committed offset, which a kept ledger would reject as duplicate
+ /// delivery, and work still in flight from the old assignment must not
+ /// land on the new one.
+ pub fn forget_partitions<'a>(
+ &self,
+ topic_partitions: impl IntoIterator<Item = (&'a str, i32)>,
+ ) {
+ let mut partitions = self.partitions.lock().unwrap();
+ let mut forgotten = 0;
+ for (topic, partition) in topic_partitions {
+ let key = TopicPartition::new(topic, partition);
+ let generation = partitions
+ .get(&key)
+ .map(PartitionOffsetLedger::generation)
+ .unwrap_or_default();
+ partitions.insert(key, PartitionOffsetLedger::new(generation + 1));
+ forgotten += 1;
+ }
+ self.generations_version
+ .fetch_add(forgotten, Ordering::Relaxed);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn tp(topic: &str, partition: i32) -> TopicPartition {
+ TopicPartition::new(topic, partition)
+ }
+
+ fn charge(ledger: &TopicOffsetLedger, tp: &TopicPartition, stamp: u64, offsets: &[i64]) {
+ ledger
+ .charge(
+ tp,
+ stamp,
+ offsets.iter().map(|&offset| (Offset(offset), Charge::ZERO)),
+ )
+ .unwrap();
+ }
+
+ #[test]
+ fn a_completed_batch_reports_its_frontier_and_drains() {
+ let ledger = TopicOffsetLedger::new();
+ let p0 = tp("events", 0);
+ charge(&ledger, &p0, 0, &[10]);
+ charge(&ledger, &p0, 0, &[11]);
+
+ let settlement = ledger
+ .settle(&p0, 0, [Offset(10), Offset(11)])
+ .expect("live ledger settles");
+ assert_eq!(settlement.frontier, Some(Offset(12)));
+
+ assert_eq!(ledger.take_frontier(&p0), Some(Offset(12)));
+ assert_eq!(ledger.held(&p0).offsets, 0);
+ }
+
+ #[test]
+ fn forgetting_a_partition_drops_its_ledger_and_advances_its_generation() {
+ let ledger = TopicOffsetLedger::new();
+ let p0 = tp("events", 0);
+ charge(&ledger, &p0, 0, &[10]);
+ assert_eq!(ledger.generations_version(), 0);
+
+ ledger.forget_partitions([("events", 0)]);
+
+ assert_eq!(ledger.held(&p0).offsets, 0);
+ assert_eq!(ledger.generation(&p0), 1);
+ assert_eq!(ledger.generations_version(), 1);
+ }
+
+ #[test]
+ fn forgetting_an_unseen_partition_still_opens_a_generation() {
+ // A slice buffered before the revoke carries stamp 0; without a new
+ // generation it would found the new assignment's ledger with stale offsets.
+ let ledger = TopicOffsetLedger::new();
+ let p0 = tp("events", 0);
+ ledger.forget_partitions([("events", 0)]);
+
+ assert_eq!(ledger.generation(&p0), 1);
+ assert_eq!(
+ ledger.charge(&p0, 0, [(Offset(10), Charge::ZERO)]),
+ Err(Rejection::Stale {
+ stamp: 0,
+ generation: 1
+ })
+ );
+ assert_eq!(
+ ledger
+ .charge(&p0, 1, [(Offset(10), Charge::ZERO)])
+ .map(|held| held.offsets),
+ Ok(1)
+ );
+ }
+
+ #[test]
+ fn an_incomplete_prefix_reports_no_frontier_and_holds_offsets() {
+ let ledger = TopicOffsetLedger::new();
+ let p0 = tp("events", 0);
+ charge(&ledger, &p0, 0, &[10]);
+ charge(&ledger, &p0, 0, &[11]);
+
+ let settlement = ledger
+ .settle(&p0, 0, [Offset(11)])
+ .expect("live ledger settles");
+ assert_eq!(settlement.frontier, None);
+ assert_eq!(settlement.held.offsets, 2);
+ assert_eq!(ledger.take_frontier(&p0), None);
+ assert_eq!(ledger.held(&p0).offsets, 2);
+
+ // The late completion arrives with the next batch and the held
+ // offsets drain.
+ let settlement = ledger
+ .settle(&p0, 0, [Offset(10)])
+ .expect("live ledger settles");
+ assert_eq!(settlement.frontier, Some(Offset(12)));
+ assert_eq!(ledger.take_frontier(&p0), Some(Offset(12)));
+ assert_eq!(ledger.held(&p0).offsets, 0);
+ }
+
+ #[test]
+ fn a_batch_spanning_partitions_settles_each_independently() {
+ let ledger = TopicOffsetLedger::new();
+ let p0 = tp("events", 0);
+ let p1 = tp("events", 1);
+ charge(&ledger, &p0, 0, &[10, 11]);
+ charge(&ledger, &p1, 0, &[20, 21]);
+
+ let settled = ledger
+ .settle(&p0, 0, [Offset(10), Offset(11)])
+ .expect("live ledger settles");
+ assert_eq!(settled.frontier, Some(Offset(12)));
+ let held = ledger
+ .settle(&p1, 0, [Offset(21)])
+ .expect("live ledger settles");
+ assert_eq!(held.frontier, None);
+
+ ledger.take_frontier(&p0);
+ ledger.take_frontier(&p1);
+ assert_eq!(ledger.held(&p0).offsets, 0, "the settled partition drains");
+ assert_eq!(
+ ledger.held(&p1).offsets,
+ 2,
+ "the held partition keeps its offsets"
+ );
+ }
+
+ #[test]
+ fn completions_for_a_forgotten_partition_are_stale() {
+ let ledger = TopicOffsetLedger::new();
+ let p0 = tp("events", 0);
+ charge(&ledger, &p0, 0, &[10]);
+ ledger.forget_partitions([("events", 0)]);
+
+ assert_eq!(
+ ledger.settle(&p0, 0, [Offset(10)]),
+ Err(Rejection::Stale {
+ stamp: 0,
+ generation: 1
+ })
+ );
+ }
+
+ #[test]
+ fn completions_for_a_never_charged_partition_are_stale() {
+ let ledger = TopicOffsetLedger::new();
+ assert_eq!(
+ ledger.settle(&tp("events", 0), 0, [Offset(10)]),
+ Err(Rejection::Stale {
+ stamp: 0,
+ generation: 0
+ })
+ );
+ }
+
+ #[test]
+ fn partitions_are_keyed_by_topic_and_partition() {
+ let ledger = TopicOffsetLedger::new();
+ let events = tp("events", 0);
+ let overflow = tp("overflow", 0);
+ charge(&ledger, &events, 0, &[10]);
+ charge(&ledger, &overflow, 0, &[10]);
+
+ ledger
+ .settle(&events, 0, [Offset(10)])
+ .expect("live ledger settles");
+ ledger.take_frontier(&events);
+
+ assert_eq!(ledger.held(&events).offsets, 0);
+ assert_eq!(ledger.held(&overflow).offsets, 1);
+ }
+
+ #[test]
+ fn stale_completions_from_a_previous_assignment_are_dropped() {
+ let ledger = TopicOffsetLedger::new();
+ let p0 = tp("events", 0);
+ charge(&ledger, &p0, 0, &[10]);
+
+ // The partition is revoked and reassigned to this consumer while the
+ // batch is still in flight; the redelivery recharges the same offset.
+ ledger.forget_partitions([("events", 0)]);
+ charge(&ledger, &p0, 1, &[10]);
+
+ assert_eq!(
+ ledger.settle(&p0, 0, [Offset(10)]),
+ Err(Rejection::Stale {
+ stamp: 0,
+ generation: 1
+ })
+ );
+ assert_eq!(
+ ledger.held(&p0).offsets,
+ 1,
+ "the redelivered offset stays uncompleted"
+ );
+
+ // The redelivery's own completion settles the new assignment's ledger.
+ ledger
+ .settle(&p0, 1, [Offset(10)])
+ .expect("current-generation batch settles");
+ ledger.take_frontier(&p0);
+ assert_eq!(ledger.held(&p0).offsets, 0);
+ }
+
+ #[test]
+ fn a_reassignment_affects_only_its_own_partition() {
+ let ledger = TopicOffsetLedger::new();
+ let p0 = tp("events", 0);
+ let p1 = tp("events", 1);
+ charge(&ledger, &p0, 0, &[10]);
+ charge(&ledger, &p1, 0, &[20]);
+
+ // Only partition 0 is revoked and reassigned.
+ ledger.forget_partitions([("events", 0)]);
+ charge(&ledger, &p0, 1, &[10]);
+ assert_eq!(
+ ledger.generation(&p1),
+ 0,
+ "partition 1 keeps its generation"
+ );
+
+ assert_eq!(
+ ledger.settle(&p0, 0, [Offset(10)]),
+ Err(Rejection::Stale {
+ stamp: 0,
+ generation: 1
+ })
+ );
+ ledger
+ .settle(&p1, 0, [Offset(20)])
+ .expect("untouched partition settles");
+ ledger.take_frontier(&p1);
+
+ assert_eq!(
+ ledger.held(&p0).offsets,
+ 1,
+ "the reassigned partition ignores the stale completion"
+ );
+ assert_eq!(
+ ledger.held(&p1).offsets,
+ 0,
+ "the untouched partition completes and drains"
+ );
+ }
+
+ #[test]
+ fn slices_spanning_another_partitions_generation_change_still_charge() {
+ let ledger = TopicOffsetLedger::new();
+ let p1 = tp("events", 1);
+ charge(&ledger, &p1, 0, &[20]);
+
+ // Another partition's reassignment moves the generations version;
+ // this partition's generation and ledger are untouched.
+ ledger.forget_partitions([("events", 0)]);
+ assert_eq!(ledger.generations_version(), 1);
+ charge(&ledger, &p1, 0, &[21]);
+ assert_eq!(ledger.held(&p1).offsets, 2);
+
+ ledger
+ .settle(&p1, 0, [Offset(20), Offset(21)])
+ .expect("surviving ledger settles");
+ ledger.take_frontier(&p1);
+ assert_eq!(ledger.held(&p1).offsets, 0, "no message is lost");
+ }
+
+ #[test]
+ fn a_partition_lost_for_a_generation_returns_under_a_later_one() {
+ let ledger = TopicOffsetLedger::new();
+ let p0 = tp("events", 0);
+ charge(&ledger, &p0, 0, &[10]);
+
+ // The partition leaves for another consumer and returns later; both
+ // callbacks forget it, and the in-flight batch settles in between.
+ ledger.forget_partitions([("events", 0)]);
+ ledger.forget_partitions([("events", 0)]);
+ assert_eq!(ledger.generation(&p0), 2);
+
+ assert_eq!(
+ ledger.settle(&p0, 0, [Offset(10)]),
+ Err(Rejection::Stale {
+ stamp: 0,
+ generation: 2
+ })
+ );
+ assert_eq!(ledger.held(&p0).offsets, 0, "no ledger, nothing lands");
+
+ charge(&ledger, &p0, 2, &[10]);
+ ledger
+ .settle(&p0, 2, [Offset(10)])
+ .expect("the new assignment settles");
+ ledger.take_frontier(&p0);
+ assert_eq!(ledger.held(&p0).offsets, 0);
+ }
+
+ #[test]
+ fn slices_from_every_older_generation_cannot_refound_a_dropped_ledger() {
+ let ledger = TopicOffsetLedger::new();
+ let p0 = tp("events", 0);
+ charge(&ledger, &p0, 0, &[10]);
+ ledger.forget_partitions([("events", 0)]);
+ ledger.forget_partitions([("events", 0)]);
+
+ assert_eq!(
+ ledger.charge(&p0, 0, [(Offset(10), Charge::ZERO)]),
+ Err(Rejection::Stale {
+ stamp: 0,
+ generation: 2
+ })
+ );
+ assert_eq!(
+ ledger.charge(&p0, 1, [(Offset(10), Charge::ZERO)]),
+ Err(Rejection::Stale {
+ stamp: 1,
+ generation: 2
+ })
+ );
+ assert_eq!(ledger.held(&p0).offsets, 0);
+
+ assert_eq!(
+ ledger
+ .charge(&p0, 2, [(Offset(10), Charge::ZERO)])
+ .map(|held| held.offsets),
+ Ok(1)
+ );
+ }
+
+ #[test]
+ fn a_violating_charge_resets_the_partition_to_a_new_generation() {
+ let ledger = TopicOffsetLedger::new();
+ let p0 = tp("events", 0);
+ charge(&ledger, &p0, 0, &[10, 11]);
+
+ // A duplicate delivery under the same generation is a contract
+ // violation, not a rebalance: the ledger cannot trust its window.
+ assert_eq!(
+ ledger.charge(&p0, 0, [(Offset(11), Charge::ZERO)]),
+ Err(Rejection::Violation(LedgerError::OffsetNotAboveWindow {
+ offset: Offset(11),
+ next: Offset(12),
+ }))
+ );
+ assert_eq!(ledger.held(&p0).offsets, 0, "the window is discarded");
+ assert_eq!(ledger.generation(&p0), 1);
+ assert_eq!(ledger.generations_version(), 1);
+
+ // In-flight work from before the reset drops as stale; the next
+ // delivery under the new generation founds a fresh ledger.
+ assert_eq!(
+ ledger.settle(&p0, 0, [Offset(10)]),
+ Err(Rejection::Stale {
+ stamp: 0,
+ generation: 1
+ })
+ );
+ assert_eq!(
+ ledger
+ .charge(&p0, 1, [(Offset(12), Charge::ZERO)])
+ .map(|held| held.offsets),
+ Ok(1)
+ );
+ }
+
+ #[test]
+ fn a_violating_completion_resets_the_partition_to_a_new_generation() {
+ let ledger = TopicOffsetLedger::new();
+ let p0 = tp("events", 0);
+ charge(&ledger, &p0, 0, &[10]);
+
+ assert_eq!(
+ ledger.settle(&p0, 0, [Offset(15)]),
+ Err(Rejection::Violation(LedgerError::CompletionUncharged {
+ offset: Offset(15)
+ }))
+ );
+ assert_eq!(ledger.held(&p0).offsets, 0);
+ assert_eq!(ledger.generation(&p0), 1);
+ assert_eq!(ledger.take_frontier(&p0), None);
+ }
+}
diff --git a/rust/ingestion-consumer/README.md b/rust/ingestion-consumer/README.md
index e9887580c5d0..878b8eb26689 100644
--- a/rust/ingestion-consumer/README.md
+++ b/rust/ingestion-consumer/README.md
@@ -27,6 +27,16 @@ It measures the invariant at its end point: the worker's grouping stage processe
Rebalances reset all baselines (`ingestion_consumer_rebalances_total{event}` counts them), so partition handoffs don't fire false positives.
Null-key messages (e.g. overflow rerouting) are excluded from both checks: the producer deliberately forfeits per-key order for them, and the consumer routes each one individually rather than pinning it, so there is no invariant to check on either side.
+## Shadow offset ledger
+
+`ledger_shadow.rs` runs the per-partition offset ledger from `common/kafka-consumer` next to the current commit path without changing what is committed.
+Every delivered message is charged to its partition's ledger during collection, and a committed batch completes its offsets there; the ledger's frontier is then compared with the offset the batch commits.
+`ingestion_consumer_ledger_mismatch_total{topic,partition,direction}` counts every disagreement, and a warning logs when a partition's disagreement starts and when it ends.
+`ingestion_consumer_ledger_uncommitted_offsets{topic,partition}` gauges each partition's window depth; `ingestion_consumer_ledger_uncommitted_events` and `ingestion_consumer_ledger_uncommitted_bytes` gauge the charge those offsets carry, where bytes is the payload plus key plus headers of each message.
+`ingestion_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.
+`ingestion_consumer_ledger_errors_total{stage,kind}` counts contract violations in the ledger's accounting; it must stay 0. A violation resets that partition's ledger, and the consumer keeps running.
+`CONSUMER_OFFSET_LEDGER_SHADOW_ENABLED` (default `true`) is the kill switch: off, the consumer builds no ledger at all, so nothing is charged, settled, forgotten on rebalance, or reported.
+
## Debug API
Set `DEBUG_API_ENABLED=true` **and** `DEBUG_API_SECRET` to mount a real-time debug API on the health server (default `:3301`), for dev and incident debugging; off by default.
diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rs
index 9b125369722c..8bebe8446db9 100644
--- a/rust/ingestion-consumer/src/config.rs
+++ b/rust/ingestion-consumer/src/config.rs
@@ -196,6 +196,16 @@ pub struct Config {
#[envconfig(from = "CONSUMER_ORDER_SENTINEL_ENABLED", default = "true")]
pub consumer_order_sentinel_enabled: bool,
+ // ---- Offset ledger ----
+ /// Kill switch for the shadow offset ledger. The ledger accounts every
+ /// delivered offset and reports where its frontier disagrees with the
+ /// offset the consumer commits; it never changes what is committed.
+ /// Off, the consumer builds no ledger: nothing is charged, settled,
+ /// forgotten on rebalance, or reported. Disable it only if its
+ /// accounting or metrics are implicated in a problem.
+ #[envconfig(from = "CONSUMER_OFFSET_LEDGER_SHADOW_ENABLED", default = "true")]
+ pub consumer_offset_ledger_shadow_enabled: bool,
+
// ---- Worker transport ----
/// Comma-separated list of worker HTTP URLs. Readiness probes hit these
/// directly; each worker's gRPC stream address is derived from its URL's
diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rs
index 39da25e6b2cf..e992e6597972 100644
--- a/rust/ingestion-consumer/src/consumer.rs
+++ b/rust/ingestion-consumer/src/consumer.rs
@@ -3,13 +3,13 @@ use std::future::Future;
use std::sync::Arc;
use std::time::{Duration, Instant};
-use common_kafka_consumer::Partition;
+use common_kafka_consumer::{Charge, Offset, Partition, TopicOffsetLedger, TopicPartition};
use futures::StreamExt;
use lifecycle::Handle;
use metrics::{counter, gauge, histogram};
use rdkafka::consumer::{CommitMode, Consumer, StreamConsumer};
use rdkafka::message::{Headers, Message};
-use rdkafka::{Offset, TopicPartitionList};
+use rdkafka::TopicPartitionList;
use tokio::task::JoinHandle;
use tracing::{error, info, warn};
@@ -18,17 +18,15 @@ use crate::debug_recorder::{record_if, DebugEventKind, DebugRecorder, PartitionO
use crate::discovery::DiscoveryMode;
use crate::dispatcher::{Dispatcher, KeyOffset, SubBatch};
use crate::grpc_transport::{GrpcTransport, PendingWorkerStreamSend};
+use crate::ledger_shadow::LedgerShadow;
use crate::order_sentinel::{CommitSentinel, OffsetSpan, SentinelContext};
use crate::transport::SendError;
use crate::types::{Accumulator, Group, SerializedKafkaMessage};
use crate::worker_registry::WorkerId;
-/// Statistics gathered while collecting a batch, used to emit parity metrics.
+/// Batch-wide statistics gathered while collecting, used to emit parity
+/// metrics. Per-partition facts live on [`PartitionDeliveries`].
struct BatchStats {
- /// Max Kafka message timestamp (ms) per (topic, partition) — for `latest_processed_timestamp_ms`.
- latest_kafka_ts: HashMap<(String, i32), i64>,
- /// Max ingestion lag (ms) per (topic, partition) — for `ingestion_lag_ms`.
- max_lag_ms: HashMap<(String, i32), i64>,
/// Per-message (partition, lag_ms) pairs — for `ingestion_lag_ms_histogram`.
message_lags_ms: Vec<(i32, i64)>,
/// Total byte size of message payloads — for `consumer_batch_size_kb`.
@@ -38,25 +36,93 @@ struct BatchStats {
impl BatchStats {
fn new() -> Self {
Self {
- latest_kafka_ts: HashMap::new(),
- max_lag_ms: HashMap::new(),
message_lags_ms: Vec::new(),
total_bytes: 0,
}
}
}
+/// One delivered message, as the batch records it against its partition.
+struct Delivery {
+ offset: i64,
+ charge: Charge,
+ /// Kafka message timestamp (ms).
+ kafka_ts: i64,
+ /// Ingestion lag (ms); `None` without a parseable `now` header.
+ lag_ms: Option<i64>,
+}
+
+/// What a batch saw delivered from one partition, folded in one map entry
+/// per message. The span feeds the commit; the stamped charges feed the
+/// shadow ledger.
+struct PartitionDeliveries {
+ /// The offsets the commit path commits, as `last + 1`.
+ span: OffsetSpan,
+ /// Ledger generation the charges are stamped with.
+ generation: u64,
+ /// Ledger generations version seen when the charges were last stamped.
+ /// Comparing it per message is cheaper than reading the generation.
+ generations_version_seen: u64,
+ /// The slice charged to the ledger: offsets delivered under `generation`.
+ charges: Vec<(Offset, Charge)>,
+ /// Max Kafka message timestamp (ms) — for `latest_processed_timestamp_ms`.
+ latest_kafka_ts: i64,
+ /// Max ingestion lag (ms) — for `ingestion_lag_ms`.
+ max_lag_ms: Option<i64>,
+}
+
+impl PartitionDeliveries {
+ fn new(generation: u64, generations_version: u64, delivery: &Delivery) -> Self {
+ Self {
+ span: OffsetSpan::new(delivery.offset),
+ generation,
+ generations_version_seen: generations_version,
+ charges: vec![(Offset(delivery.offset), delivery.charge)],
+ latest_kafka_ts: delivery.kafka_ts,
+ max_lag_ms: delivery.lag_ms,
+ }
+ }
+
+ /// Record one more delivery. `generation` is consulted only when
+ /// `generations_version` moved since the last stamp. A moved generation
+ /// means the partition was revoked and regained inside this batch: the
+ /// offsets buffered so far belong to the old assignment and Kafka
+ /// redelivers them, so the ledger slice restarts. The commit span keeps
+ /// them, as the commit path does today.
+ fn record(
+ &mut self,
+ generations_version: u64,
+ generation: impl FnOnce() -> u64,
+ delivery: &Delivery,
+ ) {
+ self.span.extend(delivery.offset);
+ self.latest_kafka_ts = self.latest_kafka_ts.max(delivery.kafka_ts);
+ if let Some(lag_ms) = delivery.lag_ms {
+ self.max_lag_ms = Some(self.max_lag_ms.map_or(lag_ms, |max| max.max(lag_ms)));
+ }
+ if generations_version != self.generations_version_seen {
+ self.generations_version_seen = generations_version;
+ let generation = generation();
+ if generation != self.generation {
+ self.generation = generation;
+ self.charges.clear();
+ }
+ }
+ self.charges
+ .push((Offset(delivery.offset), delivery.charge));
+ }
+}
+
/// Output of `collect_batch`.
struct CollectedBatch {
/// The poll's messages, demuxed per partition and routing key.
groups: Vec<Group>,
- offsets: HashMap<(String, i32), OffsetSpan>,
+ partitions: HashMap<TopicPartition, PartitionDeliveries>,
stats: BatchStats,
}
struct ProcessedBatch {
- offsets: HashMap<(String, i32), OffsetSpan>,
- stats: BatchStats,
+ partitions: HashMap<TopicPartition, PartitionDeliveries>,
/// Messages accepted so far. Deferred groups (keys whose worker was
/// draining/dead) are flushed in `complete_oldest_batch`, which adds to this.
total_accepted: u32,
@@ -120,6 +186,7 @@ pub struct IngestionConsumer {
commit_sentinel: Arc<CommitSentinel>,
/// Debug event recorder; `None` unless `DEBUG_API_ENABLED`.
debug_recorder: Option<Arc<DebugRecorder>>,
+ ledger_shadow: LedgerShadow,
}
impl IngestionConsumer {
@@ -133,9 +200,12 @@ impl IngestionConsumer {
options: IngestionConsumerOptions,
handle: Handle,
) -> Self {
- // Share the context's commit sentinel so rebalance callbacks reset the
- // same baselines the commit path checks against.
+ // Share the context's commit sentinel and ledger so rebalance
+ // callbacks reset the same baselines the commit path checks against.
+ // The shadow runs whenever the context carries a ledger: `new` reads
+ // the kill switch, and a detached context always carries one.
let commit_sentinel = consumer.context().commit_sentinel();
+ let topic_offset_ledger = consumer.context().topic_offset_ledger();
Self {
commit_sentinel,
debug_recorder: options.debug_recorder,
@@ -150,6 +220,7 @@ impl IngestionConsumer {
deferred_flush_timeout: options.deferred_flush_timeout,
handle,
group_id: options.group_id,
+ ledger_shadow: LedgerShadow::new(topic_offset_ledger),
}
}
@@ -183,7 +254,16 @@ impl IngestionConsumer {
commit_sentinel.set_enabled(config.consumer_order_sentinel_enabled);
let key_sentinel = dispatcher.key_order_sentinel();
key_sentinel.set_enabled(config.consumer_order_sentinel_enabled);
- let mut context = SentinelContext::new(Arc::clone(&commit_sentinel), key_sentinel);
+ // Off, the consumer has no ledger at all: the rebalance callbacks
+ // have nothing to forget and the shadow nothing to charge.
+ let topic_offset_ledger = config
+ .consumer_offset_ledger_shadow_enabled
+ .then(|| Arc::new(TopicOffsetLedger::new()));
+ let mut context = SentinelContext::new(
+ Arc::clone(&commit_sentinel),
+ key_sentinel,
+ topic_offset_ledger.clone(),
+ );
context.set_assignment_epoch(transport.assignment_epoch());
let consumer: StreamConsumer<SentinelContext> =
client_config.create_with_context(context)?;
@@ -214,6 +294,7 @@ impl IngestionConsumer {
),
handle,
group_id: config.ingestion_consumer_group_id.clone(),
+ ledger_shadow: LedgerShadow::new(topic_offset_ledger),
})
}
@@ -316,7 +397,7 @@ impl IngestionConsumer {
record_if(&self.debug_recorder, || DebugEventKind::BatchDispatched {
batch_id: batch_id.clone(),
messages: batch_size,
- partitions: debug_partition_offsets(&collected.offsets, &collected.stats.max_lag_ms),
+ partitions: debug_partition_offsets(&collected.partitions),
});
let assign_start = Instant::now();
let groups = std::mem::take(&mut collected.groups);
@@ -392,14 +473,14 @@ impl IngestionConsumer {
// Commit only the oldest completed batch. Later successful batches stay
// uncommitted behind any earlier failed batch, preserving at-least-once
// delivery across worker or pipeline failures.
- self.commit_offsets(&processed.offsets)?;
+ self.commit_offsets(&processed.partitions)?;
self.dispatcher.release_batch(&batch_id);
- emit_latest_processed_timestamp_metrics(&processed.stats, &self.group_id);
+ emit_latest_processed_timestamp_metrics(&processed.partitions, &self.group_id);
record_if(&self.debug_recorder, || DebugEventKind::BatchCommitted {
batch_id: batch_id.clone(),
accepted: processed.total_accepted,
duration_ms: processed.elapsed.as_millis() as u64,
- partitions: debug_partition_offsets(&processed.offsets, &processed.stats.max_lag_ms),
+ partitions: debug_partition_offsets(&processed.partitions),
});
histogram!("ingestion_consumer_batch_processing_duration_seconds")
@@ -571,14 +652,17 @@ impl IngestionConsumer {
histogram!("consumer_batch_size_kb").record(collected.stats.total_bytes as f64 / 1024.0);
// Per-partition ingestion lag gauge — matches Node.js `ingestion_lag_ms`.
- for ((topic, partition), max_lag) in &collected.stats.max_lag_ms {
+ for (topic_partition, partition) in &collected.partitions {
+ let Some(max_lag) = partition.max_lag_ms else {
+ continue;
+ };
gauge!(
"ingestion_lag_ms",
- "topic" => topic.clone(),
- "partition" => partition.to_string(),
+ "topic" => topic_partition.topic.clone(),
+ "partition" => topic_partition.partition.to_string(),
"groupId" => group_id.clone()
)
- .set(*max_lag as f64);
+ .set(max_lag as f64);
}
// Per-message lag histogram — matches Node.js `ingestion_lag_ms_histogram`.
@@ -600,8 +684,7 @@ impl IngestionConsumer {
let total_accepted = Self::scatter(&dispatcher, &batch_id, pending, false).await?;
Ok(ProcessedBatch {
- offsets: collected.offsets,
- stats: collected.stats,
+ partitions: collected.partitions,
total_accepted,
batch_size: batch_size as u32,
elapsed: start.elapsed(),
@@ -702,7 +785,7 @@ impl IngestionConsumer {
/// at most one message, itself bounded by `fetch.message.max.bytes`.
async fn collect_batch(&self) -> anyhow::Result<CollectedBatch> {
let mut accumulator = Accumulator::default();
- let mut offsets: HashMap<(String, i32), OffsetSpan> = HashMap::new();
+ let mut partitions: HashMap<TopicPartition, PartitionDeliveries> = HashMap::new();
let mut stats = BatchStats::new();
let deadline = Instant::now() + self.batch_timeout;
let batch_start_ms = current_time_ms();
@@ -730,22 +813,7 @@ impl IngestionConsumer {
let topic = borrowed_message.topic().to_string();
let partition = borrowed_message.partition();
let offset = borrowed_message.offset();
-
- offsets
- .entry((topic.clone(), partition))
- .and_modify(|span| span.extend(offset))
- .or_insert_with(|| OffsetSpan::new(offset));
-
let kafka_ts = borrowed_message.timestamp().to_millis().unwrap_or(0);
- stats
- .latest_kafka_ts
- .entry((topic.clone(), partition))
- .and_modify(|t| {
- if kafka_ts > *t {
- *t = kafka_ts;
- }
- })
- .or_insert(kafka_ts);
let payload_bytes = borrowed_message.payload().map(|v| v.len()).unwrap_or(0);
stats.total_bytes += payload_bytes;
@@ -762,20 +830,41 @@ impl IngestionConsumer {
}
}
- if let Some(capture_ms) = headers.get("now").and_then(|v| parse_now_ms(v)) {
- let lag_ms = (batch_start_ms - capture_ms).max(0);
- stats
- .max_lag_ms
- .entry((topic.clone(), partition))
- .and_modify(|l| {
- if lag_ms > *l {
- *l = lag_ms;
- }
- })
- .or_insert(lag_ms);
+ let lag_ms = headers
+ .get("now")
+ .and_then(|v| parse_now_ms(v))
+ .map(|capture_ms| (batch_start_ms - capture_ms).max(0));
+ if let Some(lag_ms) = lag_ms {
stats.message_lags_ms.push((partition, lag_ms));
}
+ let delivery = Delivery {
+ offset,
+ charge: message_charge(&borrowed_message),
+ kafka_ts,
+ lag_ms,
+ };
+ let key = TopicPartition::new(topic.clone(), partition);
+ let generations_version = self.ledger_shadow.generations_version();
+ match partitions.get_mut(&key) {
+ Some(deliveries) => deliveries.record(
+ generations_version,
+ || self.ledger_shadow.generation(&key),
+ &delivery,
+ ),
+ None => {
+ let generation = self.ledger_shadow.generation(&key);
+ partitions.insert(
+ key,
+ PartitionDeliveries::new(
+ generation,
+ generations_version,
+ &delivery,
+ ),
+ );
+ }
+ }
+
let serialized = SerializedKafkaMessage {
topic,
partition,
@@ -817,16 +906,26 @@ impl IngestionConsumer {
}
}
+ // One ledger call per partition keeps the lock and the gauge labels
+ // off the per-message path.
+ for (topic_partition, partition) in &partitions {
+ self.ledger_shadow
+ .charge(topic_partition, partition.generation, &partition.charges);
+ }
+
Ok(CollectedBatch {
groups: accumulator.into_groups(),
- offsets,
+ partitions,
stats,
})
}
/// Commit the max offset for each topic-partition.
- fn commit_offsets(&self, offsets: &HashMap<(String, i32), OffsetSpan>) -> anyhow::Result<()> {
- if offsets.is_empty() {
+ fn commit_offsets(
+ &self,
+ partitions: &HashMap<TopicPartition, PartitionDeliveries>,
+ ) -> anyhow::Result<()> {
+ 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);
@@ -836,15 +935,31 @@ impl IngestionConsumer {
// Validate contiguity/monotonicity per partition before committing, so
// a violation is attributed to the batch that caused it.
- self.commit_sentinel.check_commit(offsets);
+ self.commit_sentinel.check_commit(
+ partitions
+ .iter()
+ .map(|(topic_partition, partition)| (topic_partition, &partition.span)),
+ );
let mut tpl = TopicPartitionList::new();
- for ((topic, partition), span) in offsets {
+ for (topic_partition, partition) in partitions {
// Commit offset + 1 (Kafka convention: committed offset = next to read)
- tpl.add_partition_offset(topic, *partition, rdkafka::Offset::Offset(span.last + 1))?;
+ tpl.add_partition_offset(
+ &topic_partition.topic,
+ topic_partition.partition,
+ rdkafka::Offset::Offset(partition.span.last + 1),
+ )?;
}
self.consumer.commit(&tpl, CommitMode::Async)?;
+ for (topic_partition, partition) in partitions {
+ self.ledger_shadow.settle(
+ topic_partition,
+ partition.generation,
+ partition.charges.iter().map(|(offset, _)| *offset),
+ &partition.span,
+ );
+ }
counter!("ingestion_consumer_offset_commits_total").increment(1);
Ok(())
@@ -853,19 +968,15 @@ impl IngestionConsumer {
/// Per-partition max offset + observed lag for the debug UI's batch events.
fn debug_partition_offsets(
- offsets: &HashMap<(String, i32), OffsetSpan>,
- max_lag_ms: &HashMap<(String, i32), i64>,
+ partitions: &HashMap<TopicPartition, PartitionDeliveries>,
) -> Vec<PartitionOffset> {
- offsets
+ partitions
.iter()
- .map(|((topic, partition), span)| PartitionOffset {
- topic: topic.clone(),
- partition: *partition,
- offset: span.last,
- lag_ms: max_lag_ms
- .get(&(topic.clone(), *partition))
- .copied()
- .unwrap_or(0),
+ .map(|(topic_partition, partition)| PartitionOffset {
+ topic: topic_partition.topic.clone(),
+ partition: topic_partition.partition,
+ offset: partition.span.last,
+ lag_ms: partition.max_lag_ms.unwrap_or(0),
})
.collect()
}
@@ -916,7 +1027,7 @@ async fn run_commit_monitor(
.elements()
.iter()
.filter_map(|e| match e.offset() {
- Offset::Offset(offset) => {
+ rdkafka::Offset::Offset(offset) => {
Some((e.topic().to_string(), e.partition(), offset))
}
// Invalid = no offset stored for the partition yet.
@@ -938,6 +1049,26 @@ async fn run_commit_monitor(
}
}
+/// 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
+/// payload.
+fn message_charge(message: &impl Message) -> Charge {
+ let payload_bytes = message.payload().map(|v| v.len()).unwrap_or(0);
+ let key_bytes = message.key().map(|k| k.len()).unwrap_or(0);
+ let mut header_bytes = 0;
+ if let Some(headers) = message.headers() {
+ for i in 0..headers.count() {
+ let header = headers.get(i);
+ header_bytes += header.key.len() + header.value.map(|v| v.len()).unwrap_or(0);
+ }
+ }
+ Charge {
+ events: 1,
+ bytes: (payload_bytes + key_bytes + header_bytes) as u64,
+ }
+}
+
fn make_batch_id() -> String {
let ts = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -962,16 +1093,139 @@ fn parse_now_ms(value: &str) -> Option<i64> {
.map(|dt| dt.timestamp_millis())
}
-fn emit_latest_processed_timestamp_metrics(stats: &BatchStats, group_id: &str) {
+fn emit_latest_processed_timestamp_metrics(
+ partitions: &HashMap<TopicPartition, PartitionDeliveries>,
+ group_id: &str,
+) {
// Per-partition latest committed timestamp — matches Node.js
// `latest_processed_timestamp_ms`.
- for ((topic, partition), ts_ms) in &stats.latest_kafka_ts {
+ for (topic_partition, partition) in partitions {
gauge!(
"latest_processed_timestamp_ms",
- "topic" => topic.clone(),
- "partition" => partition.to_string(),
+ "topic" => topic_partition.topic.clone(),
+ "partition" => topic_partition.partition.to_string(),
"groupId" => group_id.to_string()
)
- .set(*ts_ms as f64);
+ .set(partition.latest_kafka_ts as f64);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use rdkafka::message::{Header, OwnedHeaders, OwnedMessage};
+ use rdkafka::Timestamp;
+
+ fn delivery(offset: i64) -> Delivery {
+ Delivery {
+ offset,
+ charge: Charge {
+ events: 1,
+ bytes: 1,
+ },
+ kafka_ts: offset,
+ lag_ms: Some(offset),
+ }
+ }
+
+ fn charged_offsets(deliveries: &PartitionDeliveries) -> Vec<i64> {
+ deliveries
+ .charges
+ .iter()
+ .map(|(offset, _)| offset.0)
+ .collect()
+ }
+
+ #[test]
+ fn a_mid_batch_regain_restarts_the_ledger_slice_and_keeps_the_span() {
+ let mut deliveries = PartitionDeliveries::new(3, 7, &delivery(10));
+ deliveries.record(
+ 7,
+ || unreachable!("unchanged version, no generation read"),
+ &delivery(11),
+ );
+
+ // The partition is revoked and regained: Kafka redelivers from the
+ // committed offset 5 under generation 4.
+ deliveries.record(8, || 4, &delivery(5));
+ deliveries.record(
+ 8,
+ || unreachable!("stamped once per version change"),
+ &delivery(6),
+ );
+
+ assert_eq!(charged_offsets(&deliveries), vec![5, 6]);
+ assert_eq!(deliveries.generation, 4);
+ assert_eq!(deliveries.span, OffsetSpan { first: 5, last: 11 });
+ }
+
+ #[test]
+ fn another_partitions_generation_change_keeps_the_slice() {
+ let mut deliveries = PartitionDeliveries::new(3, 7, &delivery(10));
+ deliveries.record(8, || 3, &delivery(11));
+
+ assert_eq!(charged_offsets(&deliveries), vec![10, 11]);
+ assert_eq!(deliveries.generation, 3);
+ }
+
+ #[test]
+ fn a_partition_keeps_its_max_timestamp_and_lag() {
+ let mut deliveries = PartitionDeliveries::new(0, 0, &delivery(10));
+ deliveries.record(
+ 0,
+ || 0,
+ &Delivery {
+ offset: 11,
+ charge: Charge::ZERO,
+ kafka_ts: 5,
+ lag_ms: None,
+ },
+ );
+
+ assert_eq!(deliveries.latest_kafka_ts, 10);
+ assert_eq!(deliveries.max_lag_ms, Some(10));
+ }
+
+ #[test]
+ fn message_charge_counts_payload_key_and_headers() {
+ let headers = OwnedHeaders::new()
+ .insert(Header {
+ key: "ab",
+ value: Some("xyz".as_bytes()),
+ })
+ .insert(Header {
+ key: "c",
+ value: None::<&[u8]>,
+ });
+ let message = OwnedMessage::new(
+ Some(vec![0; 10]),
+ Some(vec![0; 3]),
+ "events".to_string(),
+ Timestamp::NotAvailable,
+ 0,
+ 0,
+ Some(headers),
+ );
+
+ let charge = message_charge(&message);
+ assert_eq!(charge.events, 1);
+ assert_eq!(charge.bytes, 10 + 3 + (2 + 3) + 1);
+ }
+
+ #[test]
+ fn message_charge_of_an_empty_message_is_one_event() {
+ let message = OwnedMessage::new(
+ None,
+ None,
+ "events".to_string(),
+ Timestamp::NotAvailable,
+ 0,
+ 0,
+ None,
+ );
+
+ let charge = message_charge(&message);
+ assert_eq!(charge.events, 1);
+ assert_eq!(charge.bytes, 0);
}
}
diff --git a/rust/ingestion-consumer/src/ledger_shadow.rs b/rust/ingestion-consumer/src/ledger_shadow.rs
new file mode 100644
index 000000000000..3845bf893d9f
--- /dev/null
+++ b/rust/ingestion-consumer/src/ledger_shadow.rs
@@ -0,0 +1,391 @@
+//! Shadow-mode verification of the offset ledger: compares the frontier the
+//! ledger reaches with the commit the consumer calculates today, and carries
+//! the ledger's metric vocabulary.
+
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
+
+use common_kafka_consumer::{
+ Charge, Held, Offset, Rejection, Settlement, TopicOffsetLedger, TopicPartition,
+};
+use metrics::{counter, gauge};
+use tracing::{info, warn};
+
+use crate::order_sentinel::OffsetSpan;
+
+/// Runs the offset ledger next to the current commit path without taking
+/// part in commit choice. Without a ledger every call is a no-op: the kill
+/// switch leaves the consumer with no ledger at all, so nothing is charged,
+/// settled, or forgotten anywhere.
+pub(crate) struct LedgerShadow {
+ ledger: Option<Arc<TopicOffsetLedger>>,
+ /// Partitions whose frontier disagrees with the commit, by the ledger
+ /// generation the disagreement was seen under. A persistent disagreement
+ /// logs when it starts and when it ends, not on every batch.
+ mismatched: Mutex<HashMap<TopicPartition, u64>>,
+}
+
+impl LedgerShadow {
+ pub(crate) fn new(ledger: Option<Arc<TopicOffsetLedger>>) -> Self {
+ Self {
+ ledger,
+ mismatched: Mutex::new(HashMap::new()),
+ }
+ }
+
+ /// See [`TopicOffsetLedger::generations_version`]; constant without a
+ /// ledger.
+ pub(crate) fn generations_version(&self) -> u64 {
+ let Some(ledger) = &self.ledger else {
+ return 0;
+ };
+ ledger.generations_version()
+ }
+
+ /// See [`TopicOffsetLedger::generation`]; 0 without a ledger.
+ pub(crate) fn generation(&self, topic_partition: &TopicPartition) -> u64 {
+ let Some(ledger) = &self.ledger else {
+ return 0;
+ };
+ ledger.generation(topic_partition)
+ }
+
+ /// Charge one batch's slice of a partition to its ledger and publish what
+ /// the partition's window holds.
+ pub(crate) fn charge(
+ &self,
+ topic_partition: &TopicPartition,
+ stamp: u64,
+ charges: &[(Offset, Charge)],
+ ) {
+ let Some(ledger) = &self.ledger else {
+ return;
+ };
+ match ledger.charge(topic_partition, stamp, charges.iter().copied()) {
+ Ok(held) => set_held_gauges(&topic_partition.topic, topic_partition.partition, held),
+ Err(rejection) => count_rejection("charge", topic_partition, rejection),
+ }
+ }
+
+ /// Settle one batch's slice of a partition: complete its offsets, compare
+ /// the frontier with the commit the batch submits, and drain the
+ /// completed prefix.
+ pub(crate) fn settle(
+ &self,
+ topic_partition: &TopicPartition,
+ stamp: u64,
+ offsets: impl IntoIterator<Item = Offset>,
+ span: &OffsetSpan,
+ ) {
+ let Some(ledger) = &self.ledger else {
+ return;
+ };
+ let settlement = match ledger.settle(topic_partition, stamp, offsets) {
+ Ok(settlement) => settlement,
+ Err(rejection) => {
+ count_rejection("settle", topic_partition, rejection);
+ return;
+ }
+ };
+ self.observe(topic_partition, &settlement, span, stamp);
+ ledger.take_frontier(topic_partition);
+ set_held_gauges(
+ &topic_partition.topic,
+ topic_partition.partition,
+ ledger.held(topic_partition),
+ );
+ }
+
+ /// Count every disagreement; log only the batch that starts one and the
+ /// batch that ends it.
+ fn observe(
+ &self,
+ topic_partition: &TopicPartition,
+ settlement: &Settlement,
+ span: &OffsetSpan,
+ stamp: u64,
+ ) {
+ let mut mismatched = self.mismatched.lock().unwrap();
+ let Some(mismatch) = frontier_mismatch(topic_partition, settlement.frontier, span) else {
+ if mismatched.remove(topic_partition).is_some() {
+ info!(
+ topic = %topic_partition.topic,
+ partition = topic_partition.partition,
+ committed = span.last + 1,
+ "Offset ledger frontier agrees with current commit again"
+ );
+ }
+ return;
+ };
+ counter!(
+ "ingestion_consumer_ledger_mismatch_total",
+ "topic" => mismatch.topic_partition.topic.clone(),
+ "partition" => mismatch.topic_partition.partition.to_string(),
+ "direction" => mismatch.direction()
+ )
+ .increment(1);
+ // A new generation is a new assignment, so its first disagreement
+ // logs again.
+ let entered = mismatched.insert(topic_partition.clone(), settlement.generation)
+ != Some(settlement.generation);
+ if entered {
+ warn!(
+ topic = %mismatch.topic_partition.topic,
+ partition = mismatch.topic_partition.partition,
+ committed = mismatch.committed,
+ frontier = ?mismatch.frontier,
+ direction = mismatch.direction(),
+ depth = settlement.held.offsets,
+ batch_generation = stamp,
+ ledger_generation = settlement.generation,
+ "Offset ledger frontier differs from current commit"
+ );
+ }
+ }
+}
+
+/// A mismatch between the current commit calculation and the ledger frontier.
+#[derive(Debug, PartialEq, Eq)]
+struct LedgerMismatch {
+ topic_partition: TopicPartition,
+ committed: i64,
+ frontier: Option<Offset>,
+}
+
+impl LedgerMismatch {
+ /// `"ahead"` when the ledger frontier passed the current commit,
+ /// `"behind"` when it trails it.
+ fn direction(&self) -> &'static str {
+ match self.frontier {
+ Some(frontier) if frontier.0 > self.committed => "ahead",
+ _ => "behind",
+ }
+ }
+}
+
+/// Compare the ledger frontier with the commit the consumer calculates from
+/// the batch's offset span. The frontier is next-to-read and the commit path
+/// submits `span.last + 1`, so the two agree when equal.
+fn frontier_mismatch(
+ topic_partition: &TopicPartition,
+ frontier: Option<Offset>,
+ span: &OffsetSpan,
+) -> Option<LedgerMismatch> {
+ let committed = span.last + 1;
+ if frontier == Some(Offset(committed)) {
+ return None;
+ }
+ Some(LedgerMismatch {
+ topic_partition: topic_partition.clone(),
+ committed,
+ frontier,
+ })
+}
+
+/// Count one charge or settlement the ledger rejected. A stale slice is
+/// expected around a rebalance; a violation is a bug in the accounting.
+fn count_rejection(stage: &'static str, topic_partition: &TopicPartition, rejection: Rejection) {
+ match rejection {
+ Rejection::Stale { .. } => {
+ counter!("ingestion_consumer_ledger_stale_slices_total", "stage" => stage).increment(1);
+ }
+ Rejection::Violation(error) => {
+ counter!(
+ "ingestion_consumer_ledger_errors_total",
+ "stage" => stage,
+ "kind" => error.kind()
+ )
+ .increment(1);
+ warn!(
+ stage,
+ topic = %topic_partition.topic,
+ partition = topic_partition.partition,
+ error = %error,
+ "Offset ledger rejected a slice and reset its partition"
+ );
+ }
+ }
+}
+
+/// Publish what a partition's window holds: its uncommitted offsets and the
+/// events and bytes they carry.
+pub(crate) fn set_held_gauges(topic: &str, partition: i32, held: Held) {
+ let topic: Arc<str> = Arc::from(topic);
+ let partition: Arc<str> = Arc::from(partition.to_string());
+ gauge!(
+ "ingestion_consumer_ledger_uncommitted_offsets",
+ "topic" => topic.clone(),
+ "partition" => partition.clone()
+ )
+ .set(held.offsets as f64);
+ gauge!(
+ "ingestion_consumer_ledger_uncommitted_events",
+ "topic" => topic.clone(),
+ "partition" => partition.clone()
+ )
+ .set(held.charge.events as f64);
+ gauge!(
+ "ingestion_consumer_ledger_uncommitted_bytes",
+ "topic" => topic,
+ "partition" => partition
+ )
+ .set(held.charge.bytes as f64);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn span(first: i64, last: i64) -> OffsetSpan {
+ OffsetSpan { first, last }
+ }
+
+ fn tp(topic: &str, partition: i32) -> TopicPartition {
+ TopicPartition::new(topic, partition)
+ }
+
+ fn shadow() -> (Arc<TopicOffsetLedger>, LedgerShadow) {
+ let ledger = Arc::new(TopicOffsetLedger::new());
+ (Arc::clone(&ledger), LedgerShadow::new(Some(ledger)))
+ }
+
+ fn charges(offsets: &[i64]) -> Vec<(Offset, Charge)> {
+ offsets
+ .iter()
+ .map(|&offset| (Offset(offset), Charge::ZERO))
+ .collect()
+ }
+
+ #[test]
+ fn settle_drains_live_partitions_and_skips_stale_batches() {
+ let (ledger, shadow) = shadow();
+ let reassigned = tp("events", 0);
+ let live = tp("events", 1);
+ shadow.charge(&reassigned, 0, &charges(&[10]));
+ shadow.charge(&live, 0, &charges(&[20]));
+
+ // Partition 0 is revoked and reassigned while the batch is in flight.
+ ledger.forget_partitions([("events", 0)]);
+ shadow.charge(&reassigned, 1, &charges(&[10]));
+
+ shadow.settle(&reassigned, 0, [Offset(10)], &span(10, 10));
+ shadow.settle(&live, 0, [Offset(20)], &span(20, 20));
+
+ assert_eq!(
+ ledger.held(&reassigned).offsets,
+ 1,
+ "the stale batch settles nothing against the new ledger"
+ );
+ assert_eq!(
+ ledger.held(&live).offsets,
+ 0,
+ "the live batch settles and drains"
+ );
+ }
+
+ #[test]
+ fn a_partition_with_an_incomplete_prefix_holds_its_offsets() {
+ let (ledger, shadow) = shadow();
+ let held = tp("events", 0);
+ shadow.charge(&held, 0, &charges(&[10, 11]));
+
+ shadow.settle(&held, 0, [Offset(11)], &span(11, 11));
+
+ assert_eq!(ledger.held(&held).offsets, 2);
+ }
+
+ #[test]
+ fn a_shadow_without_a_ledger_does_nothing() {
+ let shadow = LedgerShadow::new(None);
+ let p0 = tp("events", 0);
+ shadow.charge(&p0, 0, &charges(&[10]));
+ shadow.settle(&p0, 0, [Offset(10)], &span(10, 10));
+
+ assert_eq!(shadow.generations_version(), 0);
+ assert_eq!(shadow.generation(&p0), 0);
+ }
+
+ #[test]
+ fn a_mismatch_is_tracked_from_its_first_batch_until_the_frontier_agrees() {
+ let (_, shadow) = shadow();
+ let p0 = tp("events", 0);
+ shadow.charge(&p0, 0, &charges(&[10, 11]));
+
+ // Only offset 11 completes: the frontier stays behind the commit.
+ shadow.settle(&p0, 0, [Offset(11)], &span(10, 11));
+ assert_eq!(shadow.mismatched.lock().unwrap().get(&p0), Some(&0));
+
+ // Offset 10 completes and the frontier catches up.
+ shadow.settle(&p0, 0, [Offset(10)], &span(10, 11));
+ assert!(shadow.mismatched.lock().unwrap().is_empty());
+ }
+
+ #[test]
+ fn frontier_matching_the_commit_is_not_a_mismatch() {
+ assert!(frontier_mismatch(&tp("events", 0), Some(Offset(12)), &span(11, 11)).is_none());
+ }
+
+ #[test]
+ fn a_trailing_or_absent_frontier_is_behind() {
+ let mismatch = frontier_mismatch(&tp("events", 0), Some(Offset(11)), &span(11, 11))
+ .expect("frontier below the commit");
+ assert_eq!(mismatch.committed, 12);
+ assert_eq!(mismatch.direction(), "behind");
+
+ let mismatch =
+ frontier_mismatch(&tp("events", 0), None, &span(11, 11)).expect("no frontier yet");
+ assert_eq!(mismatch.direction(), "behind");
+ }
+
+ #[test]
+ fn a_frontier_past_the_commit_is_ahead() {
+ let mismatch = frontier_mismatch(&tp("events", 0), Some(Offset(13)), &span(11, 11))
+ .expect("frontier above the commit");
+ assert_eq!(mismatch.direction(), "ahead");
+ }
+
+ #[test]
+ fn a_violating_charge_resets_the_partition_and_the_shadow_carries_on() {
+ let (ledger, shadow) = shadow();
+ let p0 = tp("events", 0);
+ shadow.charge(&p0, 0, &charges(&[10]));
+
+ // The same offset delivered twice under one generation is a contract
+ // violation, not a rebalance: the ledger resets the partition.
+ shadow.charge(&p0, 0, &charges(&[10]));
+ assert_eq!(ledger.held(&p0).offsets, 0, "the window is discarded");
+ assert_eq!(ledger.generation(&p0), 1);
+
+ // The batch in flight from before the reset settles as stale, and the
+ // next delivery under the new generation founds a fresh ledger.
+ shadow.settle(&p0, 0, [Offset(10)], &span(10, 10));
+ shadow.charge(&p0, 1, &charges(&[11]));
+ assert_eq!(ledger.held(&p0).offsets, 1);
+ shadow.settle(&p0, 1, [Offset(11)], &span(11, 11));
+ assert_eq!(
+ ledger.held(&p0).offsets,
+ 0,
+ "the fresh ledger settles and drains"
+ );
+ }
+
+ #[test]
+ fn a_violating_settlement_resets_the_partition_and_the_shadow_carries_on() {
+ let (ledger, shadow) = shadow();
+ let p0 = tp("events", 0);
+ shadow.charge(&p0, 0, &charges(&[10]));
+
+ // Settling an offset the ledger never charged resets the partition.
+ shadow.settle(&p0, 0, [Offset(15)], &span(15, 15));
+ assert_eq!(ledger.held(&p0).offsets, 0, "the window is discarded");
+ assert_eq!(ledger.generation(&p0), 1);
+
+ shadow.charge(&p0, 1, &charges(&[11]));
+ shadow.settle(&p0, 1, [Offset(11)], &span(11, 11));
+ assert_eq!(
+ ledger.held(&p0).offsets,
+ 0,
+ "the fresh ledger settles and drains"
+ );
+ }
+}
diff --git a/rust/ingestion-consumer/src/lib.rs b/rust/ingestion-consumer/src/lib.rs
index 7b934c76f685..2ce932bf0fcd 100644
--- a/rust/ingestion-consumer/src/lib.rs
+++ b/rust/ingestion-consumer/src/lib.rs
@@ -6,6 +6,7 @@ pub mod discovery;
pub mod dispatcher;
pub mod grpc_transport;
pub mod kafka_stats;
+pub mod ledger_shadow;
pub mod order_sentinel;
pub mod readiness;
pub mod routing;
diff --git a/rust/ingestion-consumer/src/order_sentinel.rs b/rust/ingestion-consumer/src/order_sentinel.rs
index 3de71b5a2818..38c82ed8c16d 100644
--- a/rust/ingestion-consumer/src/order_sentinel.rs
+++ b/rust/ingestion-consumer/src/order_sentinel.rs
@@ -47,10 +47,12 @@ use std::time::{SystemTime, UNIX_EPOCH};
use metrics::{counter, gauge};
use rdkafka::consumer::{BaseConsumer, ConsumerContext, Rebalance};
-use rdkafka::{ClientContext, Statistics};
+use rdkafka::{ClientContext, Statistics, TopicPartitionList};
use tracing::{info, warn};
+use crate::ledger_shadow::set_held_gauges;
use crate::types::SerializedKafkaMessage;
+use common_kafka_consumer::{Held, TopicOffsetLedger, TopicPartition};
/// The first and last Kafka offsets a batch holds for one topic-partition.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -162,16 +164,21 @@ impl CommitSentinel {
/// 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(&self, spans: &HashMap<(String, i32), OffsetSpan>) -> Vec<CommitViolation> {
+ 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 {
+ 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 {
@@ -563,17 +570,27 @@ impl KeyOrderSentinel {
pub struct SentinelContext {
commit_sentinel: Arc<CommitSentinel>,
key_sentinel: Arc<KeyOrderSentinel>,
- /// Bumped on every partition assignment; the gRPC transport stamps it on
- /// sub-batches so the worker's feed-order sentinel rebaselines across
- /// rebalances.
+ /// The offset ledger the commit path settles against. Owned here so the
+ /// rebalance callbacks forget partitions on the same ledger. `None` when
+ /// the ledger is switched off: the consumer then has no ledger anywhere.
+ topic_offset_ledger: Option<Arc<TopicOffsetLedger>>,
+ /// Advanced once per assignment callback; the gRPC transport stamps it
+ /// on sub-batches so the worker's feed-order sentinel rebaselines across
+ /// rebalances. Distinct from the offset ledger's generations, which move
+ /// per partition and stamp offset accounting rather than stream order.
assignment_epoch: Option<Arc<AtomicU64>>,
}
impl SentinelContext {
- pub fn new(commit_sentinel: Arc<CommitSentinel>, key_sentinel: Arc<KeyOrderSentinel>) -> Self {
+ pub fn new(
+ commit_sentinel: Arc<CommitSentinel>,
+ key_sentinel: Arc<KeyOrderSentinel>,
+ topic_offset_ledger: Option<Arc<TopicOffsetLedger>>,
+ ) -> Self {
Self {
commit_sentinel,
key_sentinel,
+ topic_offset_ledger,
assignment_epoch: None,
}
}
@@ -584,18 +601,35 @@ impl SentinelContext {
self.assignment_epoch = Some(epoch);
}
- /// A context with its own free-standing sentinels, for tests and tools
- /// that build the Kafka consumer separately from the dispatcher.
+ /// A context with its own free-standing sentinels and ledger, 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(KeyOrderSentinel::new()),
+ Some(Arc::new(TopicOffsetLedger::new())),
)
}
pub fn commit_sentinel(&self) -> Arc<CommitSentinel> {
Arc::clone(&self.commit_sentinel)
}
+
+ pub fn topic_offset_ledger(&self) -> Option<Arc<TopicOffsetLedger>> {
+ self.topic_offset_ledger.clone()
+ }
+
+ /// Start a new ledger generation for every partition in `tpl`, dropping
+ /// its window and zeroing its gauges. Nothing to do without a ledger.
+ fn forget_ledger_partitions(&self, tpl: &TopicPartitionList) {
+ let Some(ledger) = &self.topic_offset_ledger else {
+ return;
+ };
+ ledger.forget_partitions(tpl.elements().iter().map(|e| (e.topic(), e.partition())));
+ for element in tpl.elements() {
+ set_held_gauges(element.topic(), element.partition(), Held::default());
+ }
+ }
}
impl ClientContext for SentinelContext {
@@ -614,6 +648,7 @@ impl ConsumerContext for SentinelContext {
info!(partitions = tpl.count(), "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
// baseline is stale.
@@ -631,6 +666,11 @@ impl ConsumerContext for SentinelContext {
if let Rebalance::Assign(tpl) = rebalance {
counter!("ingestion_consumer_rebalances_total", "event" => "assign").increment(1);
info!(partitions = tpl.count(), "Rebalance: partitions assigned");
+ // An assign list names partitions that start a new assignment, so
+ // any surviving ledger for them is stale. The revoke callback
+ // normally dropped it already; this covers losses with no revoke
+ // callback (an error rebalance, a fenced member).
+ self.forget_ledger_partitions(tpl);
if let Some(epoch) = &self.assignment_epoch {
epoch.fetch_add(1, Ordering::Relaxed);
}
@@ -650,12 +690,12 @@ impl ConsumerContext for SentinelContext {
mod tests {
use super::*;
- fn spans(entries: &[(&str, i32, i64, i64)]) -> HashMap<(String, i32), OffsetSpan> {
+ fn spans(entries: &[(&str, i32, i64, i64)]) -> HashMap<TopicPartition, OffsetSpan> {
entries
.iter()
.map(|(topic, partition, first, last)| {
(
- (topic.to_string(), *partition),
+ TopicPartition::new(*topic, *partition),
OffsetSpan {
first: *first,
last: *last,
diff --git a/rust/ingestion-consumer/tests/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rs
index 4411b88ef4a8..3685cc74099c 100644
--- a/rust/ingestion-consumer/tests/e2e_integration_test.rs
+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs
@@ -23,6 +23,7 @@ use tokio::net::TcpListener;
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
+use common_kafka_consumer::{TopicOffsetLedger, TopicPartition};
use ingestion_consumer::consumer::{IngestionConsumer, IngestionConsumerOptions};
use ingestion_consumer::discovery::reconcile_membership;
use ingestion_consumer::dispatcher::Dispatcher;
@@ -429,18 +430,31 @@ struct Harness {
topic: String,
/// Consumer group id, kept so `restart_consumer` rejoins the same group.
group_id: String,
+ /// The running consumer's offset ledger, for observing its generations.
+ pub ledger: Arc<TopicOffsetLedger>,
max_in_flight: usize,
deferred_flush_timeout: Duration,
}
/// Build a Kafka consumer subscribed to `topic` in `group_id`, configured like
/// the production batch consumer (no auto commit/store, earliest reset). The
-/// short session timeout makes group handovers observable quickly in tests.
-/// `instance_id` opts into static membership (`group.instance.id`).
+/// short session timeout and heartbeat make group handovers observable
+/// quickly in tests. `instance_id` opts into static membership
+/// (`group.instance.id`).
fn make_kafka_consumer(
topic: &str,
group_id: &str,
instance_id: Option<&str>,
+) -> StreamConsumer<SentinelContext> {
+ make_kafka_consumer_with_context(topic, group_id, instance_id, SentinelContext::detached())
+}
+
+/// Like `make_kafka_consumer`, under a context the test keeps a hand on.
+fn make_kafka_consumer_with_context(
+ topic: &str,
+ group_id: &str,
+ instance_id: Option<&str>,
+ context: SentinelContext,
) -> StreamConsumer<SentinelContext> {
let mut config = ClientConfig::new();
config
@@ -450,13 +464,13 @@ fn make_kafka_consumer(
.set("enable.auto.commit", "false")
.set("enable.auto.offset.store", "false")
.set("session.timeout.ms", "6000")
+ .set("heartbeat.interval.ms", "1000")
.set("socket.timeout.ms", "5000");
if let Some(id) = instance_id {
config.set("group.instance.id", id);
}
- let kafka_consumer: StreamConsumer<SentinelContext> = config
- .create_with_context(SentinelContext::detached())
- .expect("kafka consumer");
+ let kafka_consumer: StreamConsumer<SentinelContext> =
+ config.create_with_context(context).expect("kafka consumer");
kafka_consumer.subscribe(&[topic]).expect("subscribe");
kafka_consumer
}
@@ -603,7 +617,11 @@ impl Harness {
let _monitor = manager.monitor_background();
let group_id = format!("e2e-{}", Uuid::new_v4());
- let kafka_consumer = make_kafka_consumer(topic, &group_id, None);
+ let context = SentinelContext::detached();
+ let ledger = context
+ .topic_offset_ledger()
+ .expect("a detached context carries a ledger");
+ let kafka_consumer = make_kafka_consumer_with_context(topic, &group_id, None, context);
let consumer = IngestionConsumer::from_parts(
kafka_consumer,
@@ -637,6 +655,7 @@ impl Harness {
_probe_token: probe_token,
topic: topic.to_string(),
group_id,
+ ledger,
max_in_flight,
deferred_flush_timeout,
}
@@ -674,7 +693,12 @@ impl Harness {
let handle = manager.register("consumer", ComponentOptions::new());
self.shutdown = handle.shutdown_token();
- let kafka_consumer = make_kafka_consumer(&self.topic, &self.group_id, None);
+ let context = SentinelContext::detached();
+ self.ledger = context
+ .topic_offset_ledger()
+ .expect("a detached context carries a ledger");
+ let kafka_consumer =
+ make_kafka_consumer_with_context(&self.topic, &self.group_id, None, context);
let consumer = IngestionConsumer::from_parts(
kafka_consumer,
Arc::clone(&dispatcher),
@@ -2504,6 +2528,156 @@ async fn second_consumer_joining_the_group_preserves_all_messages() {
harness.stop().await;
}
+/// A partition leaves for a second consumer while a batch is in flight, and
+/// returns when that consumer shuts down. The first consumer keeps polling
+/// under the held batch, so the rebalance lands before the batch settles:
+/// its offsets are stamped under generations the revoke replaced, and they
+/// drop as stale instead of landing on the new assignment. The returned
+/// partition then starts another generation. A ledger bug here would
+/// surface as ledger errors or a wedged loop, so continued delivery after
+/// both handovers is the health signal.
+#[tokio::test]
+async fn partition_lost_and_regained_keeps_the_consumer_alive() {
+ let topic = format!("e2e-regain-{}", Uuid::new_v4());
+ // Room for many in-flight batches, so the first consumer keeps polling
+ // while its batches are held and the rebalance can land underneath them.
+ let harness = Harness::start(
+ &topic,
+ 2,
+ 2,
+ 128,
+ Duration::from_secs(60),
+ fast_registry_config(),
+ )
+ .await;
+ let producer = make_producer();
+ let partitions = [
+ TopicPartition::new(topic.clone(), 0),
+ TopicPartition::new(topic.clone(), 1),
+ ];
+
+ // Hold the first batch in flight while the group changes underneath it.
+ let mut guards: Vec<Option<tokio::sync::OwnedMutexGuard<()>>> = Vec::new();
+ for w in &harness.workers {
+ guards.push(Some(w.block().await));
+ }
+ for seq in 0..5usize {
+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;
+ produce(&producer, &topic, 1, "tok", "user-2", seq).await;
+ }
+ wait_until(Duration::from_secs(10), "work to reach a worker", || {
+ harness.workers.iter().any(|w| w.arrived_count() > 0)
+ })
+ .await;
+ let generations_before: Vec<u64> = partitions
+ .iter()
+ .map(|partition| harness.ledger.generation(partition))
+ .collect();
+
+ // A second consumer joins and takes a partition away.
+ let worker_urls: Vec<String> = harness.workers.iter().map(|w| w.url.clone()).collect();
+ let registry2 = Arc::new(WorkerRegistry::new(&worker_urls, fast_registry_config()));
+ let probe2 = CancellationToken::new();
+ Arc::clone(&registry2).start_probing(probe2.clone());
+ let dispatcher2 = Arc::new(Dispatcher::new(Arc::clone(&registry2)));
+ let transport2 = Arc::new(test_transport());
+ let mut manager2 = Manager::builder("e2e-regain-c2")
+ .with_trap_signals(false)
+ .build();
+ let handle2 = manager2.register("consumer", ComponentOptions::new());
+ let shutdown2 = handle2.shutdown_token();
+ let consumer2 = IngestionConsumer::from_parts(
+ make_kafka_consumer(&topic, &harness.group_id, None),
+ dispatcher2,
+ transport2,
+ worker_urls,
+ IngestionConsumerOptions {
+ batch_size: 50,
+ batch_size_bytes: 0,
+ batch_timeout: Duration::from_millis(100),
+ max_in_flight_batches: 1,
+ group_id: "e2e-test".to_string(),
+ deferred_flush_timeout: Duration::from_secs(60),
+ debug_recorder: None,
+ },
+ handle2,
+ );
+ let task2 = tokio::spawn(async move { consumer2.process().await });
+
+ // The first consumer polls only while its polls return messages, and
+ // only a polling consumer takes part in a rebalance: a trickle holds it
+ // in the poll loop until the rebalance has reached its ledger. Every
+ // trickle batch is held like the first one.
+ let rebalanced = || {
+ partitions
+ .iter()
+ .zip(&generations_before)
+ .any(|(partition, before)| harness.ledger.generation(partition) > *before)
+ };
+ let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
+ let mut trickle_seq = 1000usize;
+ while !rebalanced() {
+ assert!(
+ tokio::time::Instant::now() < deadline,
+ "timed out waiting for the rebalance to reach the first consumer's ledger"
+ );
+ produce(&producer, &topic, 0, "tok", "user-1", trickle_seq).await;
+ trickle_seq += 1;
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+
+ // Release the held batch: its offsets are stamped under generations the
+ // rebalance replaced, so they settle as stale.
+ guards.clear();
+ for seq in 5..10usize {
+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;
+ produce(&producer, &topic, 1, "tok", "user-2", seq).await;
+ }
+ wait_until(
+ Duration::from_secs(30),
+ "every message to be delivered across the join",
+ || {
+ ["user-1", "user-2"].iter().all(|user| {
+ let delivered: HashSet<usize> = harness
+ .workers
+ .iter()
+ .flat_map(|w| w.seqs_for(user))
+ .collect();
+ (0..10).all(|s| delivered.contains(&s))
+ })
+ },
+ )
+ .await;
+
+ // The second consumer leaves; its partition returns to the first under a
+ // new generation and must consume as a fresh assignment.
+ shutdown2.cancel();
+ let _ = tokio::time::timeout(Duration::from_secs(5), task2).await;
+ probe2.cancel();
+
+ for seq in 10..15usize {
+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;
+ produce(&producer, &topic, 1, "tok", "user-2", seq).await;
+ }
+ wait_until(
+ Duration::from_secs(30),
+ "the returned partition to consume under its new assignment",
+ || {
+ ["user-1", "user-2"].iter().all(|user| {
+ let delivered: HashSet<usize> = harness
+ .workers
+ .iter()
+ .flat_map(|w| w.seqs_for(user))
+ .collect();
+ (10..15).all(|s| delivered.contains(&s))
+ })
+ },
+ )
+ .await;
+
+ harness.stop().await;
+}
+
/// A same-name pod restart racing its old instance: a second member joins with
/// the same `group.instance.id`, so the broker fences the first. The fenced
/// instance's client is permanently dead — the consumer must exit (so the pod