:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(ingestion-consumer): delete the old commit computation (#94950)
Paweł Ledwoń8a2e0c1cb993
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 97ffee4dca54..202ecda22e9b 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2921,6 +2921,7 @@ dependencies = [name = "common-kafka-consumer"version = "0.1.0"dependencies = [+ "metrics","rdkafka",]diff --git a/rust/common/kafka-consumer/Cargo.toml b/rust/common/kafka-consumer/Cargo.tomlindex 5e3630c98dcb..c5b3c3f92e98 100644--- a/rust/common/kafka-consumer/Cargo.toml+++ b/rust/common/kafka-consumer/Cargo.toml@@ -8,4 +8,5 @@ publish = falseworkspace = true[dependencies]+metrics = { workspace = true }rdkafka = { workspace = true }diff --git a/rust/common/kafka-consumer/README.md b/rust/common/kafka-consumer/README.mdindex dda9dd55eda2..94ff54845a93 100644--- a/rust/common/kafka-consumer/README.md+++ b/rust/common/kafka-consumer/README.md@@ -8,4 +8,17 @@ Kafka consumption primitives shared by stateful services.- `types`: `Offset` and `Partition`.- `accumulator`: `Group`, one routing key's messages from one poll on one partition, and `Accumulator`, the demux that builds a poll's groups.- `charge`: `Charge`, a message's cost (events and bytes) against consumer admission budgets.-- `ledger`: `OffsetLedger`, offset accounting scoped to one partition assignment: completion in any order, an observable contiguous frontier, and explicit consumption at commit points.+- `partition_offset_ledger`: `PartitionOffsetLedger`, offset accounting scoped to one partition assignment: completion in any order, an observable contiguous frontier, and explicit consumption at commit points.+- `topic_offset_ledger`: `TopicOffsetLedger`, one partition ledger per assigned topic-partition, keyed by generation so work from a previous assignment cannot land on the current one.++## Metrics++`TopicOffsetLedger` publishes these itself, so every consumer built on the crate reports the same series.++| Metric | Labels | Meaning |+| --- | --- | --- |+| `kafka_consumer_ledger_uncommitted_offsets` (gauge) | `topic`, `partition` | Offsets the partition's window holds. |+| `kafka_consumer_ledger_uncommitted_events` (gauge) | `topic`, `partition` | Events those offsets carry. |+| `kafka_consumer_ledger_uncommitted_bytes` (gauge) | `topic`, `partition` | Bytes those offsets carry (payload plus key plus headers). |+| `kafka_consumer_ledger_stale_slices_total` (counter) | `stage` | Charges and settlements dropped because their partition was reassigned while they were in flight; a few around a rebalance are expected. |+| `kafka_consumer_ledger_errors_total` (counter) | `stage`, `kind` | Contract violations in the accounting; must stay 0. A violation resets that partition's ledger and the consumer keeps running. |diff --git a/rust/common/kafka-consumer/src/lib.rs b/rust/common/kafka-consumer/src/lib.rsindex 56ad1099c44f..bee3348d5678 100644--- a/rust/common/kafka-consumer/src/lib.rs+++ b/rust/common/kafka-consumer/src/lib.rs@@ -13,5 +13,5 @@ pub use assignment_epoch::AssignmentEpoch;pub use charge::Charge;pub use config::ConsumerConfigBuilder;pub use partition_offset_ledger::{Held, LedgerError, PartitionOffsetLedger, TakenFrontier};-pub use topic_offset_ledger::{Rejection, Settlement, TopicOffsetLedger, TopicPartition};+pub use topic_offset_ledger::{Rejection, TopicOffsetLedger, TopicPartition};pub use types::{GroupCompletion, Offset, Partition};diff --git a/rust/common/kafka-consumer/src/topic_offset_ledger.rs b/rust/common/kafka-consumer/src/topic_offset_ledger.rsindex 75958d96d1bd..600eb2d52487 100644--- a/rust/common/kafka-consumer/src/topic_offset_ledger.rs+++ b/rust/common/kafka-consumer/src/topic_offset_ledger.rs@@ -1,11 +1,25 @@use std::collections::HashMap;use std::sync::atomic::{AtomicU64, Ordering};-use std::sync::Mutex;+use std::sync::{Arc, Mutex};++use metrics::{counter, gauge};use crate::charge::Charge;use crate::partition_offset_ledger::{Held, LedgerError, PartitionOffsetLedger};use crate::types::Offset;+/// Offsets a partition holds uncommitted.+const UNCOMMITTED_OFFSETS: &str = "kafka_consumer_ledger_uncommitted_offsets";+/// Events those offsets carry.+const UNCOMMITTED_EVENTS: &str = "kafka_consumer_ledger_uncommitted_events";+/// Bytes those offsets carry.+const UNCOMMITTED_BYTES: &str = "kafka_consumer_ledger_uncommitted_bytes";+/// Charges and settlements dropped because their partition was reassigned+/// while they were in flight.+const STALE_SLICES: &str = "kafka_consumer_ledger_stale_slices_total";+/// Contract violations in the ledger's accounting; must stay at zero.+const ERRORS: &str = "kafka_consumer_ledger_errors_total";+/// A partition of a named topic, the key for everything the ledger tracks.#[derive(Debug, Clone, PartialEq, Eq, Hash)]pub struct TopicPartition {@@ -40,18 +54,6 @@ pub enum Rejection {},}-/// 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@@ -60,6 +62,10 @@ pub struct Settlement {/// 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.+///+/// The ledger publishes its own metrics under the `kafka_consumer_ledger_`+/// prefix, so every consumer built on this crate reports the same series and+/// no caller can forget a gauge.#[derive(Default)]pub struct TopicOffsetLedger {partitions: Mutex<HashMap<TopicPartition, PartitionOffsetLedger>>,@@ -96,86 +102,109 @@ impl TopicOffsetLedger {/// 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.+ /// the slice was rejected. Publishes the outcome either way.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) => {- let held = ledger.held();- *ledger = PartitionOffsetLedger::new(generation + 1);- self.generations_version.fetch_add(1, Ordering::Relaxed);- Err(Rejection::Violation {- error,- stamp,- generation,- held,- })+ let result = {+ 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 {+ Err(Rejection::Stale { stamp, generation })+ } else {+ match ledger.charge(offset_charges) {+ Ok(_) => Ok(ledger.held()),+ Err(error) => {+ let held = ledger.held();+ *ledger = PartitionOffsetLedger::new(generation + 1);+ self.generations_version.fetch_add(1, Ordering::Relaxed);+ Err(Rejection::Violation {+ error,+ stamp,+ generation,+ held,+ })+ }+ }}+ };+ // Outside the lock, and on every path, so no caller has to remember.+ match result {+ Ok(held) => publish_held(topic_partition, held),+ Err(rejection) => count_rejection("charge", rejection),}+ result}/// 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.+ /// report the next-to-read frontier that results, `None` while the first+ /// offset of the window is still incomplete. 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) => {- let held = ledger.held();- *ledger = PartitionOffsetLedger::new(generation + 1);- self.generations_version.fetch_add(1, Ordering::Relaxed);- Err(Rejection::Violation {- error,+ ) -> Result<Option<Offset>, Rejection> {+ let result = {+ let mut partitions = self.partitions.lock().unwrap();+ match partitions.get_mut(topic_partition) {+ // Nothing was ever charged, so the batch cannot have been either.+ None => Err(Rejection::Stale {stamp,- generation,- held,- })+ generation: 0,+ }),+ Some(ledger) => {+ let generation = ledger.generation();+ if stamp < generation {+ Err(Rejection::Stale { stamp, generation })+ } else {+ match ledger.complete(offsets) {+ Ok(()) => Ok(ledger.frontier()),+ Err(error) => {+ let held = ledger.held();+ *ledger = PartitionOffsetLedger::new(generation + 1);+ self.generations_version.fetch_add(1, Ordering::Relaxed);+ Err(Rejection::Violation {+ error,+ stamp,+ generation,+ held,+ })+ }+ }+ }+ }}+ };+ // The window only changes depth at a charge or a take, so a+ // settlement reports rejections and leaves the gauges alone.+ if let Err(rejection) = result {+ count_rejection("settle", rejection);}+ result}/// Drain the completed prefix and return the frontier it reached; `None`/// when the partition has no ledger or nothing has completed at the front- /// of its window.+ /// of its window. The drained offsets leave the window, so the gauges+ /// follow them down.pub fn take_frontier(&self, topic_partition: &TopicPartition) -> Option<Offset> {- let mut partitions = self.partitions.lock().unwrap();- let ledger = partitions.get_mut(topic_partition)?;- ledger.take_frontier().map(|taken| taken.offset)+ let (offset, held) = {+ let mut partitions = self.partitions.lock().unwrap();+ let ledger = partitions.get_mut(topic_partition)?;+ let taken = ledger.take_frontier()?;+ (taken.offset, ledger.held())+ };+ publish_held(topic_partition, held);+ Some(offset)}/// What the partition's window still holds; nothing without a ledger.@@ -192,27 +221,79 @@ impl TopicOffsetLedger {/// 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.+ /// land on the new one. The dropped offsets leave the window, so the+ /// partition's gauges go to zero.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;+ let mut forgotten = Vec::new();+ {+ let mut partitions = self.partitions.lock().unwrap();+ 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.clone(), PartitionOffsetLedger::new(generation + 1));+ forgotten.push(key);+ }+ self.generations_version+ .fetch_add(forgotten.len() as u64, Ordering::Relaxed);+ }+ for topic_partition in forgotten {+ publish_held(&topic_partition, Held::default());}- self.generations_version- .fetch_add(forgotten, Ordering::Relaxed);}}+/// Publish what a partition's window holds.+fn publish_held(topic_partition: &TopicPartition, held: Held) {+ let (topic, partition) = labels(topic_partition);+ gauge!(+ UNCOMMITTED_OFFSETS,+ "topic" => topic.clone(),+ "partition" => partition.clone()+ )+ .set(held.offsets as f64);+ gauge!(+ UNCOMMITTED_EVENTS,+ "topic" => topic.clone(),+ "partition" => partition.clone()+ )+ .set(held.charge.events as f64);+ gauge!(+ UNCOMMITTED_BYTES,+ "topic" => topic,+ "partition" => partition+ )+ .set(held.charge.bytes as f64);+}++/// Count one charge or settlement the ledger rejected. A stale slice is+/// expected around a rebalance; a violation is a bug in the accounting. The+/// rejection is returned to the caller, which alone still holds the slice+/// and so is the place to log it.+fn count_rejection(stage: &'static str, rejection: Rejection) {+ match rejection {+ Rejection::Stale { .. } => {+ counter!(STALE_SLICES, "stage" => stage).increment(1);+ }+ Rejection::Violation { error, .. } => {+ counter!(ERRORS, "stage" => stage, "kind" => error.kind()).increment(1);+ }+ }+}++/// One partition's label values, built once per emission.+fn labels(topic_partition: &TopicPartition) -> (Arc<str>, Arc<str>) {+ (+ Arc::from(topic_partition.topic.as_str()),+ Arc::from(topic_partition.partition.to_string()),+ )+}+#[cfg(test)]mod tests {use super::*;@@ -238,10 +319,10 @@ mod tests {charge(&ledger, &p0, 0, &[10]);charge(&ledger, &p0, 0, &[11]);- let settlement = ledger+ let frontier = ledger.settle(&p0, 0, [Offset(10), Offset(11)]).expect("live ledger settles");- assert_eq!(settlement.frontier, Some(Offset(12)));+ assert_eq!(frontier, Some(Offset(12)));assert_eq!(ledger.take_frontier(&p0), Some(Offset(12)));assert_eq!(ledger.held(&p0).offsets, 0);@@ -292,20 +373,19 @@ mod tests {charge(&ledger, &p0, 0, &[10]);charge(&ledger, &p0, 0, &[11]);- let settlement = ledger+ let frontier = ledger.settle(&p0, 0, [Offset(11)]).expect("live ledger settles");- assert_eq!(settlement.frontier, None);- assert_eq!(settlement.held.offsets, 2);+ assert_eq!(frontier, None);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+ let frontier = ledger.settle(&p0, 0, [Offset(10)]).expect("live ledger settles");- assert_eq!(settlement.frontier, Some(Offset(12)));+ assert_eq!(frontier, Some(Offset(12)));assert_eq!(ledger.take_frontier(&p0), Some(Offset(12)));assert_eq!(ledger.held(&p0).offsets, 0);}@@ -321,11 +401,11 @@ mod tests {let settled = ledger.settle(&p0, 0, [Offset(10), Offset(11)]).expect("live ledger settles");- assert_eq!(settled.frontier, Some(Offset(12)));+ assert_eq!(settled, Some(Offset(12)));let held = ledger.settle(&p1, 0, [Offset(21)]).expect("live ledger settles");- assert_eq!(held.frontier, None);+ assert_eq!(held, None);ledger.take_frontier(&p0);ledger.take_frontier(&p1);diff --git a/rust/ingestion-consumer/README.md b/rust/ingestion-consumer/README.mdindex 4c9cf0820622..7ceb1f809af8 100644--- a/rust/ingestion-consumer/README.md+++ b/rust/ingestion-consumer/README.md@@ -27,15 +27,16 @@ It measures the invariant at its end point: the worker's grouping stage processeRebalances 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_MODE` selects the source of offset commits: `off` commits the per-batch max offset and builds no ledger at all, so nothing is charged, settled, forgotten on rebalance, or reported; `shadow` (default) commits the same offset and compares the ledger frontier with it; `commit` commits the ledger frontier after that comparison, and a partition that settles without a frontier stays on its last commit.+## Offset ledger++The consumer holds the per-partition offset ledger from `common/kafka-consumer`, which owns the commit.+Every delivered message is charged to its partition's ledger during collection, and a committed batch completes its offsets there; the commit is then each partition's frontier, one past its longest completed prefix.+A partition that settles without a frontier is not committed and stays on its last commit.+A batch with no frontier on any partition is not committed at all; `ingestion_consumer_commits_skipped_total{reason}` counts those, where `rejected` means the ledger dropped every slice (expected around a rebalance) and `no_frontier` means an earlier batch is still incomplete at the front of every window the batch settled.+The ledger emits its own metrics, so any consumer built on the crate reports the same series.+`kafka_consumer_ledger_uncommitted_offsets{topic,partition}` gauges each partition's window depth; `kafka_consumer_ledger_uncommitted_events` and `kafka_consumer_ledger_uncommitted_bytes` gauge the charge those offsets carry, where bytes is the payload plus key plus headers of each message.+`kafka_consumer_ledger_stale_slices_total{stage}` counts charges and settlements dropped because their partition was reassigned while they were in flight; a few around a rebalance are expected.+`kafka_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; the consumer logs the rejected slice with the batch and ledger generations and the window depth before the reset.## Debug APIdiff --git a/rust/ingestion-consumer/docs/driver-model-plan.md b/rust/ingestion-consumer/docs/driver-model-plan.mdindex d04a546f15cb..136641fccf1d 100644--- a/rust/ingestion-consumer/docs/driver-model-plan.md+++ b/rust/ingestion-consumer/docs/driver-model-plan.md@@ -134,7 +134,7 @@ This cycle has no switchover: the eager flush was never enabled.Outcome: commit contiguity is a property of a data structure, not of completion order.**Verify:** change 3 compares the frontier with every real commit on all lanes.-Exit criterion: `ingestion_consumer_ledger_mismatch_total` stays zero across deploys and rebalances, and `ingestion_consumer_ledger_uncommitted_offsets` returns toward zero when a lane is idle — the ring drains.+Exit criterion: `ingestion_consumer_ledger_mismatch_total` stays zero across deploys and rebalances, and `kafka_consumer_ledger_uncommitted_offsets` returns toward zero when a lane is idle — the ring drains.### 2. Add the common Kafka consumer crate and offset ledger (implement)@@ -144,7 +144,7 @@ Exit criterion: `ingestion_consumer_ledger_mismatch_total` stays zero across dep- Start from the config extraction in [Jose's branch](https://github.com/PostHog/posthog/compare/master...jose-sequeira/kafka-consumer-loop): move the current consumer config builder unchanged into `common-kafka-consumer`, retain its fixture coverage, and make `ingestion-consumer` depend on it.- Copy only the cycle-2 domain primitives from Jose's second commit into the new crate: the offset wrapper and the charge carried by a ledger slot. Adapt its `OffsetLedger` representation to this plan's `complete`, non-mutating `frontier`, and consuming `take_frontier` contract: Jose's current `complete` advances and removes the prefix, so it cannot be copied unchanged into the shadow comparison.-- Do not take `Accumulator`, `Budget`, `PartitionDriver`, `PartitionManager`, or `CommitManager`; those implement later cycles and would make this PR cross several plan boundaries. The ledger module must not depend on `rdkafka`, `ingestion-consumer`, or service-specific metrics. The shared config module may retain its `rdkafka` dependency.+- Do not take `Accumulator`, `Budget`, `PartitionDriver`, `PartitionManager`, or `CommitManager`; those implement later cycles and would make this PR cross several plan boundaries. The ledger module must not depend on `rdkafka`, `ingestion-consumer`, or service-specific metrics; it emits its own metrics under the crate prefix. The shared config module may retain its `rdkafka` dependency.- One ledger per partition. The ledger is a dense ring of delivered offsets.- Each slot records: complete or not, event count, byte count. The counts serve the budget in change 23.@@ -155,7 +155,7 @@ Exit criterion: `ingestion_consumer_ledger_mismatch_total` stays zero across dep- Completions can arrive in any order. The frontier moves only over completed slots.- Kafka can deliver offsets with gaps: transaction markers occupy offsets that consumers never receive, and compaction keeps offsets while removing records. Our ingestion topics have neither today, and the commit sentinel treats a gap as a real skip (see the caveat on `CommitSentinel`).- The ledger still defines contiguity over delivered offsets, not offset arithmetic. A legitimate gap can then never block the frontier.-- The sentinel's gap alert and the ledger's gap handling cannot both stand. Once the frontier owns commits (change 4), a commit that walks over a legitimate gap is correct, and the sentinel would report it as a skip. The ledger therefore counts each gap it walked over (`ingestion_consumer_ledger_gaps_total`), and the sentinel's gap alert retires in change 5. Until then the alert stays, because the ingestion topics have no legitimate gaps today and a gap is still a real skip.+- The sentinel's gap alert and the ledger's gap handling cannot both stand. Once the frontier owns commits (change 4), a commit that walks over a legitimate gap is correct, and the sentinel would report it as a skip. The ledger therefore counts each gap it walked over (`kafka_consumer_ledger_gaps_total`), and the sentinel's gap alert retires in change 5. Until then the alert stays, because the ingestion topics have no legitimate gaps today and a gap is still a real skip.- Add property tests: out-of-order completion, monotonic frontier, `frontier` idempotence, the ring drains after `take_frontier`, offset gaps, ring capacity.**Interfaces:**@@ -188,8 +188,8 @@ Exit criterion: `ingestion_consumer_ledger_mismatch_total` stays zero across dep**Metrics:**- Add `ingestion_consumer_ledger_mismatch_total` (counter): frontier vs committed offset disagreement.-- Add `ingestion_consumer_ledger_uncommitted_offsets` (gauge, per partition): ring depth. It must fall at commit points. A value that only grows is a drain bug (a leak).-- Add `ingestion_consumer_ledger_gaps_total` (counter): offset gaps the ledger walked over. Expected to stay at zero on the ingestion topics; a non-zero value is the signal the sentinel's gap alert gave before change 5 retires it.+- Add `kafka_consumer_ledger_uncommitted_offsets` (gauge, per partition): ring depth. It must fall at commit points. A value that only grows is a drain bug (a leak).+- Add `kafka_consumer_ledger_gaps_total` (counter): offset gaps the ledger walked over. Expected to stay at zero on the ingestion topics; a non-zero value is the signal the sentinel's gap alert gave before change 5 retires it.### 4. Commit from the ledger frontier (switchover)@@ -557,7 +557,7 @@ This is a deliberate structural outcome, not routine cleanup: it is the largestOutcome: commits advance per partition as groups complete. Needs cycles 2 and 3.-**Verify:** the commit sentinel checks every commit, and `ingestion_consumer_ledger_uncommitted_offsets` shows per-partition frontier lag.+**Verify:** the commit sentinel checks every commit, and `kafka_consumer_ledger_uncommitted_offsets` shows per-partition frontier lag.Exit criterion at the canary: zero sentinel violations, and a stalled partition no longer moves the commit rate of other partitions.### 21. Switch completion to group granularity (switchover)@@ -723,7 +723,7 @@ Exit criterion: `ingestion_consumer_drain_duration_seconds` stays inside the deaThe steady-state dashboard after the migration:- Delivery: `ingestion_lag_ms`, the `ingestion_consumer_messages_processed_total` rate, and the two sentinel violation counters, which must stay at zero.-- Commits: `ingestion_consumer_ledger_uncommitted_offsets` per partition (frontier lag, and the ring-leak detector) and the `ingestion_consumer_offset_commits_total` rate.+- Commits: `kafka_consumer_ledger_uncommitted_offsets` per partition (frontier lag, and the ring-leak detector) and the `ingestion_consumer_offset_commits_total` rate.- Scheduling: the key-table gauges and `ingestion_consumer_parked_retries_total`.- Admission: the budget gauges and `ingestion_consumer_budget_paused`.- Requests: the request-size histograms, `ingestion_consumer_transport_duration_seconds`, `ingestion_consumer_governor_permits`, `ingestion_consumer_request_rtt_seconds`, and `ingestion_consumer_request_budget_partials_total`.diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rsindex e5df0e8f9c81..9b125369722c 100644--- a/rust/ingestion-consumer/src/config.rs+++ b/rust/ingestion-consumer/src/config.rs@@ -1,5 +1,3 @@-use std::str::FromStr;-use common_continuous_profiling::ContinuousProfilingConfig;use envconfig::Envconfig;use rdkafka::ClientConfig;@@ -9,35 +7,6 @@ use crate::discovery::DiscoveryMode;use crate::routing::RoutingStrategy;use common_kafka_consumer::config::ConsumerConfigBuilder;-/// Whether the consumer keeps an offset ledger, and whether that ledger-/// observes the commit path or owns it.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]-pub enum LedgerMode {- /// No ledger: commit the per-batch max offset as before. Nothing is- /// charged, settled, forgotten on rebalance, or reported.- Off,- /// Commit the per-batch max offset and compare the ledger frontier to it.- #[default]- Shadow,- /// Commit the ledger frontier after the comparison.- Commit,-}--impl FromStr for LedgerMode {- type Err = String;-- fn from_str(value: &str) -> Result<Self, Self::Err> {- match value.trim().to_lowercase().as_str() {- "off" => Ok(Self::Off),- "shadow" => Ok(Self::Shadow),- "commit" => Ok(Self::Commit),- other => Err(format!(- "unknown consumer offset ledger mode '{other}' (expected 'off', 'shadow' or 'commit')"- )),- }- }-}-/// Configuration for the ingestion consumer.////// Kafka env vars match the Node.js ingestion consumer so this can be a@@ -199,14 +168,6 @@ pub struct Config {#[envconfig(from = "CONSUMER_MAX_BACKGROUND_TASKS", default = "1")]pub consumer_max_background_tasks: usize,- /// The source of offset commits. `off` commits the per-batch max offset- /// and keeps no ledger. `shadow` commits the same offset and compares the- /// ledger frontier with it, reporting disagreements. `commit` commits the- /// ledger frontier after that comparison. Fall back to `off` only if the- /// ledger's accounting or metrics are implicated in a problem.- #[envconfig(from = "CONSUMER_OFFSET_LEDGER_MODE", default = "shadow")]- pub consumer_offset_ledger_mode: LedgerMode,-// ---- Debug API ----/// Serve the real-time debug API (`/debug/load`, `/debug/state`,/// `/debug/events` SSE) on the health server, recording structured events@@ -235,7 +196,6 @@ pub struct Config {#[envconfig(from = "CONSUMER_ORDER_SENTINEL_ENABLED", default = "true")]pub consumer_order_sentinel_enabled: bool,- // ---- Offset ledger ----// ---- 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@@ -504,17 +464,3 @@ impl Config {builder.build()}}--#[cfg(test)]-mod tests {- use super::LedgerMode;- use std::str::FromStr;-- #[test]- fn ledger_mode_parses_known_values() {- assert_eq!(LedgerMode::from_str("off"), Ok(LedgerMode::Off));- assert_eq!(LedgerMode::from_str(" SHADOW "), Ok(LedgerMode::Shadow));- assert_eq!(LedgerMode::from_str("commit"), Ok(LedgerMode::Commit));- assert!(LedgerMode::from_str("on").is_err());- }-}diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rsindex 07b166d85066..88a26d1ec758 100644--- a/rust/ingestion-consumer/src/consumer.rs+++ b/rust/ingestion-consumer/src/consumer.rs@@ -3,7 +3,7 @@ use std::sync::Arc;use std::time::{Duration, Instant};use common_kafka_consumer::{- Charge, GroupCompletion, Offset, Partition, Settlement, TopicOffsetLedger, TopicPartition,+ Charge, GroupCompletion, Offset, Partition, Rejection, TopicOffsetLedger, TopicPartition,};use futures::StreamExt;use lifecycle::Handle;@@ -16,12 +16,12 @@ use tokio::task::JoinHandle;use tracing::{error, info, warn};use crate::batcher::{make_batch_id, Batcher, BatcherOutputs};-use crate::config::{Config, LedgerMode};+use crate::config::Config;use crate::debug_recorder::{record_if, DebugEventKind, DebugRecorder, PartitionOffset};use crate::discovery::DiscoveryMode;use crate::dispatcher::Dispatcher;use crate::grpc_transport::GrpcTransport;-use crate::ledger_shadow::LedgerShadow;+use crate::ledger_rejection::{warn_rejection, RejectedSlice};use crate::order_sentinel::{CommitSentinel, OffsetSpan, SentinelContext};use crate::types::{Accumulator, SerializedKafkaMessage};@@ -54,10 +54,10 @@ struct Delivery {}/// 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.+/// per message. The span bounds what the batch delivered; the stamped+/// charges feed the ledger.struct PartitionDeliveries {- /// The offsets the commit path commits, as `last + 1`.+ /// The offsets the batch delivered, first to last.span: OffsetSpan,/// Ledger generation the charges are stamped with.generation: u64,@@ -88,8 +88,8 @@ impl PartitionDeliveries {/// `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.+ /// redelivers them, so the ledger slice restarts. The span keeps them,+ /// so the commit sentinel still sees the whole delivered range.fn record(&mut self,generations_version: u64,@@ -200,8 +200,6 @@ pub struct IngestionConsumerOptions {pub deferred_flush_timeout: Duration,/// Debug event recorder; `None` unless `DEBUG_API_ENABLED`.pub debug_recorder: Option<Arc<DebugRecorder>>,- /// Whether the offset ledger observes or owns the commit path.- pub ledger_mode: LedgerMode,}/// The main consumer loop: reads from Kafka, demuxes each poll into groups,@@ -225,9 +223,10 @@ pub struct IngestionConsumer {commit_sentinel: Arc<CommitSentinel>,/// Debug event recorder; `None` unless `DEBUG_API_ENABLED`.debug_recorder: Option<Arc<DebugRecorder>>,- ledger_shadow: LedgerShadow,- /// Selects whether commits come from the batch spans or the ledger.- ledger_mode: LedgerMode,+ /// The per-partition offset ledger the commit path reads its frontiers+ /// from. Shared with the consumer's [`SentinelContext`], which forgets+ /// partitions on rebalance.+ topic_offset_ledger: Arc<TopicOffsetLedger>,}impl IngestionConsumer {@@ -245,9 +244,6 @@ impl IngestionConsumer {) -> Self {// 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` builds- // one unless the mode is off, and a detached context always carries- // one.let commit_sentinel = consumer.context().commit_sentinel();let topic_offset_ledger = consumer.context().topic_offset_ledger();let (batcher, outputs) = Batcher::new(@@ -259,8 +255,7 @@ impl IngestionConsumer {Self {commit_sentinel,debug_recorder: options.debug_recorder,- ledger_shadow: LedgerShadow::new(topic_offset_ledger),- ledger_mode: options.ledger_mode,+ topic_offset_ledger,consumer: Arc::new(consumer),batcher,outputs: Some(outputs),@@ -306,14 +301,11 @@ impl IngestionConsumer {commit_sentinel.set_enabled(config.consumer_order_sentinel_enabled);let key_sentinel = batcher.key_order_sentinel();key_sentinel.set_enabled(config.consumer_order_sentinel_enabled);- // 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_mode != LedgerMode::Off)- .then(|| Arc::new(TopicOffsetLedger::new()));+ let topic_offset_ledger = Arc::new(TopicOffsetLedger::new());let mut context = SentinelContext::new(Arc::clone(&commit_sentinel),key_sentinel,- topic_offset_ledger.clone(),+ Arc::clone(&topic_offset_ledger),);context.set_assignment_epoch(transport.assignment_epoch());let consumer: StreamConsumer<SentinelContext> =@@ -333,8 +325,7 @@ impl IngestionConsumer {consumer: Arc::new(consumer),commit_sentinel,debug_recorder,- ledger_shadow: LedgerShadow::new(topic_offset_ledger),- ledger_mode: config.consumer_offset_ledger_mode,+ topic_offset_ledger,batcher,outputs: Some(outputs),transport,@@ -622,15 +613,15 @@ impl IngestionConsumer {lag_ms,};let key = TopicPartition::new(topic.clone(), partition);- let generations_version = self.ledger_shadow.generations_version();+ let generations_version = self.topic_offset_ledger.generations_version();match partitions.get_mut(&key) {Some(deliveries) => deliveries.record(generations_version,- || self.ledger_shadow.generation(&key),+ || self.topic_offset_ledger.generation(&key),&delivery,),None => {- let generation = self.ledger_shadow.generation(&key);+ let generation = self.topic_offset_ledger.generation(&key);partitions.insert(key,PartitionDeliveries::new(@@ -686,8 +677,21 @@ 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);+ // The ledger counts both outcomes and publishes what the window+ // holds; a rejection is logged here, where the slice is still+ // known.+ if let Err(rejection) = self.topic_offset_ledger.charge(+ topic_partition,+ partition.generation,+ partition.charges.iter().copied(),+ ) {+ warn_rejection(+ "charge",+ topic_partition,+ rejection,+ RejectedSlice::charged(&partition.charges),+ );+ }}Ok(CollectedBatch {@@ -697,8 +701,9 @@ impl IngestionConsumer {})}- /// Commit either the existing per-batch max offset or the verified ledger- /// frontier for each topic-partition.+ /// Settle the batch against the ledger and commit each partition's+ /// frontier. A partition without a frontier is not committed and stays on+ /// its last committed offset.fn commit_offsets(&self,partitions: &HashMap<TopicPartition, PartitionDeliveries>,@@ -711,53 +716,39 @@ impl IngestionConsumer {return Ok(());}- match self.ledger_mode {- LedgerMode::Off | LedgerMode::Shadow => self.commit_offset_spans(partitions),- LedgerMode::Commit => self.commit_frontiers(partitions),- }- }-- /// Off and shadow modes: commit the per-batch max offsets unchanged, then- /// settle the ledger against them for comparison only. Off has no ledger,- /// so the settlement is a no-op there.- fn commit_offset_spans(- &self,- partitions: &HashMap<TopicPartition, PartitionDeliveries>,- ) -> anyhow::Result<()> {- self.submit_commit(- partitions- .iter()- .map(|(topic_partition, partition)| (topic_partition, &partition.span)),- )?;- for (topic_partition, partition) in partitions {- if self.settle(topic_partition, partition).is_some() {- self.ledger_shadow.drain(topic_partition);- }- }- Ok(())- }-- /// Commit mode: settle the batch against the ledger and commit each- /// partition's frontier. A partition without a frontier is not committed- /// and stays on its last committed offset.- fn commit_frontiers(- &self,- partitions: &HashMap<TopicPartition, PartitionDeliveries>,- ) -> anyhow::Result<()> {let mut settled = Vec::with_capacity(partitions.len());let mut frontier_spans = Vec::with_capacity(partitions.len());for (topic_partition, partition) in partitions {- let Some(settlement) = self.settle(topic_partition, partition) else {+ // A rejected slice is not committed, and the commit sentinel+ // keeps its baseline. A stale slice belongs to an assignment the+ // revoke callback already forgot on the sentinel, so the+ // partition's next commit rebaselines. A violation reset the+ // ledger and dropped what it held, so the partition's next commit+ // can pass work still in flight; the sentinel reports that as the+ // gap it is.+ let Ok(frontier) = self.settle(topic_partition, partition) else {continue;};settled.push(topic_partition);- if let Some(span) = frontier_span(&partition.span, settlement.frontier) {+ if let Some(span) = frontier_span(&partition.span, frontier) {frontier_spans.push((topic_partition, span));}}if frontier_spans.is_empty() {- warn!("No ledger frontier available for completed offsets; skipping commit");+ // `rejected`: the ledger dropped every slice, expected around a+ // rebalance. `no_frontier`: a slice landed, but an earlier batch+ // is still incomplete at the front of every window it settled.+ let reason = if settled.is_empty() {+ "rejected"+ } else {+ "no_frontier"+ };+ counter!("ingestion_consumer_commits_skipped_total", "reason" => reason).increment(1);+ warn!(+ reason,+ "No ledger frontier available for completed offsets; skipping commit"+ );return Ok(());}@@ -767,23 +758,33 @@ impl IngestionConsumer {.map(|(topic_partition, span)| (*topic_partition, span)),)?;for topic_partition in settled {- self.ledger_shadow.drain(topic_partition);+ self.topic_offset_ledger.take_frontier(topic_partition);}Ok(())}- /// Settle one partition's slice of a batch against the ledger.+ /// Settle one partition's slice of a batch against the ledger and report+ /// the frontier it reached. `Err` when the ledger rejected the slice,+ /// which it has already counted and this logs.fn settle(&self,topic_partition: &TopicPartition,partition: &PartitionDeliveries,- ) -> Option<Settlement> {- self.ledger_shadow.settle(- topic_partition,- partition.generation,- partition.charges.iter().map(|(offset, _)| *offset),- &partition.span,- )+ ) -> Result<Option<Offset>, Rejection> {+ self.topic_offset_ledger+ .settle(+ topic_partition,+ partition.generation,+ partition.charges.iter().map(|(offset, _)| *offset),+ )+ .inspect_err(|rejection| {+ warn_rejection(+ "settle",+ topic_partition,+ *rejection,+ RejectedSlice::settled(&partition.span),+ )+ })}/// Validate and submit one commit to Kafka.diff --git a/rust/ingestion-consumer/src/ledger_rejection.rs b/rust/ingestion-consumer/src/ledger_rejection.rsnew file mode 100644index 000000000000..c00dc3033ccb--- /dev/null+++ b/rust/ingestion-consumer/src/ledger_rejection.rs@@ -0,0 +1,98 @@+//! Attribution for slices the offset ledger rejected. The ledger counts a+//! rejection where it happens; the consumer logs it here, because only the+//! consumer still holds the slice the ledger consumed.++use common_kafka_consumer::{Charge, Offset, Rejection, TopicPartition};+use tracing::warn;++use crate::order_sentinel::OffsetSpan;++#[derive(Debug, Clone, Copy)]+pub(crate) enum RejectedSlice {+ /// Exactly the offsets the charge submitted to the ledger.+ Charged {+ first: Option<i64>,+ last: Option<i64>,+ offsets: usize,+ },+ /// The batch's delivered span for the partition, not the settled slice.+ /// A generation change mid-batch drops the old generation's charges but+ /// leaves the span whole, so the span can cover offsets the settlement+ /// never submitted. The settled offsets are an iterator the happy path+ /// does not collect, so the span is the closest description available.+ /// The error names the offending offset.+ Settled { first: i64, last: i64 },+}++impl RejectedSlice {+ pub(crate) fn charged(charges: &[(Offset, Charge)]) -> Self {+ Self::Charged {+ first: charges.first().map(|(offset, _)| offset.0),+ last: charges.last().map(|(offset, _)| offset.0),+ offsets: charges.len(),+ }+ }++ pub(crate) fn settled(span: &OffsetSpan) -> Self {+ Self::Settled {+ first: span.first,+ last: span.last,+ }+ }+}++/// Log one charge or settlement the ledger rejected. A stale slice is+/// expected around a rebalance and stays quiet; a violation is a bug in the+/// accounting and names the slice. Callers must build `slice` inside their+/// error arm so the happy path pays nothing for it.+pub(crate) fn warn_rejection(+ stage: &'static str,+ topic_partition: &TopicPartition,+ rejection: Rejection,+ slice: RejectedSlice,+) {+ let Rejection::Violation {+ error,+ stamp,+ generation,+ held,+ } = rejection+ else {+ return;+ };+ // A tracing field name is fixed at the call site, so each variant needs+ // its own `warn!`.+ match slice {+ RejectedSlice::Charged {+ first,+ last,+ offsets,+ } => warn!(+ stage,+ topic = %topic_partition.topic,+ partition = topic_partition.partition,+ error = %error,+ kind = error.kind(),+ batch_generation = stamp,+ ledger_generation = generation,+ depth = held.offsets,+ slice_first = ?first,+ slice_last = ?last,+ slice_offsets = offsets,+ "Offset ledger rejected a slice and reset its partition"+ ),+ RejectedSlice::Settled { first, last } => warn!(+ stage,+ topic = %topic_partition.topic,+ partition = topic_partition.partition,+ error = %error,+ kind = error.kind(),+ batch_generation = stamp,+ ledger_generation = generation,+ depth = held.offsets,+ batch_first = first,+ batch_last = last,+ "Offset ledger rejected a slice and reset its partition"+ ),+ }+}diff --git a/rust/ingestion-consumer/src/ledger_shadow.rs b/rust/ingestion-consumer/src/ledger_shadow.rsdeleted file mode 100644index 974fa251949d..000000000000--- a/rust/ingestion-consumer/src/ledger_shadow.rs+++ /dev/null@@ -1,493 +0,0 @@-//! 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 off-/// mode 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,- RejectedSlice::charged(charges),- ),- }- }-- /// Settle one batch's slice of a partition: complete its offsets and- /// compare the frontier with the commit the batch submits. Returns the- /// settlement, or `None` when the ledger rejected the slice. The window- /// holds the offsets until `drain`.- pub(crate) fn settle(- &self,- topic_partition: &TopicPartition,- stamp: u64,- offsets: impl IntoIterator<Item = Offset>,- span: &OffsetSpan,- ) -> Option<Settlement> {- let Some(ledger) = &self.ledger else {- return None;- };- let settlement = match ledger.settle(topic_partition, stamp, offsets) {- Ok(settlement) => settlement,- Err(rejection) => {- count_rejection(- "settle",- topic_partition,- rejection,- RejectedSlice::settled(span),- );- return None;- }- };- self.observe(topic_partition, &settlement, span, stamp);- Some(settlement)- }-- /// Drain a settled partition's completed prefix and publish what its- /// window still holds.- pub(crate) fn drain(&self, topic_partition: &TopicPartition) {- let Some(ledger) = &self.ledger else {- return;- };- 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,- })-}--#[derive(Debug, Clone, Copy)]-enum RejectedSlice {- /// Exactly the offsets the charge submitted to the ledger.- Charged {- first: Option<i64>,- last: Option<i64>,- offsets: usize,- },- /// The batch's delivered span for the partition, not the settled slice.- /// A generation change mid-batch drops the old generation's charges but- /// leaves the span whole, so the span can cover offsets the settlement- /// never submitted. The settled offsets are an iterator the happy path- /// does not collect, so the span is the closest description available.- /// The error names the offending offset.- Settled { first: i64, last: i64 },-}--impl RejectedSlice {- fn charged(charges: &[(Offset, Charge)]) -> Self {- Self::Charged {- first: charges.first().map(|(offset, _)| offset.0),- last: charges.last().map(|(offset, _)| offset.0),- offsets: charges.len(),- }- }-- fn settled(span: &OffsetSpan) -> Self {- Self::Settled {- first: span.first,- last: span.last,- }- }-}--/// Count one charge or settlement the ledger rejected. A stale slice is-/// expected around a rebalance; a violation is a bug in the accounting.-/// Callers must build `slice` inside their error arm so the happy path pays-/// nothing for it.-fn count_rejection(- stage: &'static str,- topic_partition: &TopicPartition,- rejection: Rejection,- slice: RejectedSlice,-) {- match rejection {- Rejection::Stale { .. } => {- counter!("ingestion_consumer_ledger_stale_slices_total", "stage" => stage).increment(1);- }- Rejection::Violation {- error,- stamp,- generation,- held,- } => {- counter!(- "ingestion_consumer_ledger_errors_total",- "stage" => stage,- "kind" => error.kind()- )- .increment(1);- // A tracing field name is fixed at the call site, so each variant- // needs its own `warn!`.- match slice {- RejectedSlice::Charged {- first,- last,- offsets,- } => warn!(- stage,- topic = %topic_partition.topic,- partition = topic_partition.partition,- error = %error,- kind = error.kind(),- batch_generation = stamp,- ledger_generation = generation,- depth = held.offsets,- slice_first = ?first,- slice_last = ?last,- slice_offsets = offsets,- "Offset ledger rejected a slice and reset its partition"- ),- RejectedSlice::Settled { first, last } => warn!(- stage,- topic = %topic_partition.topic,- partition = topic_partition.partition,- error = %error,- kind = error.kind(),- batch_generation = stamp,- ledger_generation = generation,- depth = held.offsets,- batch_first = first,- batch_last = last,- "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]));-- assert!(- shadow- .settle(&reassigned, 0, [Offset(10)], &span(10, 10))- .is_none(),- "the stale batch settles nothing against the new ledger"- );- let settlement = shadow- .settle(&live, 0, [Offset(20)], &span(20, 20))- .expect("the live batch settles");- assert_eq!(settlement.frontier, Some(Offset(21)));- shadow.drain(&live);-- assert_eq!(ledger.held(&reassigned).offsets, 1);- assert_eq!(ledger.held(&live).offsets, 0, "the live batch 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]));-- let settlement = shadow- .settle(&held, 0, [Offset(11)], &span(11, 11))- .expect("the batch settles");- assert_eq!(settlement.frontier, None);- shadow.drain(&held);-- 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]));- assert!(shadow.settle(&p0, 0, [Offset(10)], &span(10, 10)).is_none());- shadow.drain(&p0);-- 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));- shadow.drain(&p0);- 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));- shadow.drain(&p0);- 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.rsindex 446e898afe59..cd69a677f462 100644--- a/rust/ingestion-consumer/src/lib.rs+++ b/rust/ingestion-consumer/src/lib.rs@@ -7,7 +7,7 @@ pub mod discovery;pub mod dispatcher;pub mod grpc_transport;pub mod kafka_stats;-pub mod ledger_shadow;+pub mod ledger_rejection;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.rsindex 8c7ce283cde8..8851166f6fc2 100644--- a/rust/ingestion-consumer/src/order_sentinel.rs+++ b/rust/ingestion-consumer/src/order_sentinel.rs@@ -50,9 +50,8 @@ use rdkafka::consumer::{BaseConsumer, ConsumerContext, Rebalance};use rdkafka::{ClientContext, Statistics, TopicPartitionList};use tracing::{info, warn};-use crate::ledger_shadow::set_held_gauges;use crate::types::SerializedKafkaMessage;-use common_kafka_consumer::{AssignmentEpoch, Held, TopicOffsetLedger, TopicPartition};+use common_kafka_consumer::{AssignmentEpoch, TopicOffsetLedger, TopicPartition};/// The first and last Kafka offsets a batch holds for one topic-partition.#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -571,9 +570,8 @@ pub struct SentinelContext {commit_sentinel: Arc<CommitSentinel>,key_sentinel: Arc<KeyOrderSentinel>,/// 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>>,+ /// rebalance callbacks forget partitions on the same ledger.+ topic_offset_ledger: 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@@ -585,7 +583,7 @@ impl SentinelContext {pub fn new(commit_sentinel: Arc<CommitSentinel>,key_sentinel: Arc<KeyOrderSentinel>,- topic_offset_ledger: Option<Arc<TopicOffsetLedger>>,+ topic_offset_ledger: Arc<TopicOffsetLedger>,) -> Self {Self {commit_sentinel,@@ -607,7 +605,7 @@ impl SentinelContext {Self::new(Arc::new(CommitSentinel::new()),Arc::new(KeyOrderSentinel::new()),- Some(Arc::new(TopicOffsetLedger::new())),+ Arc::new(TopicOffsetLedger::new()),)}@@ -615,20 +613,15 @@ impl SentinelContext {Arc::clone(&self.commit_sentinel)}- pub fn topic_offset_ledger(&self) -> Option<Arc<TopicOffsetLedger>> {- self.topic_offset_ledger.clone()+ pub fn topic_offset_ledger(&self) -> Arc<TopicOffsetLedger> {+ Arc::clone(&self.topic_offset_ledger)}/// Start a new ledger generation for every partition in `tpl`, dropping- /// its window and zeroing its gauges. Nothing to do without a ledger.+ /// its window.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());- }+ self.topic_offset_ledger+ .forget_partitions(tpl.elements().iter().map(|e| (e.topic(), e.partition())));}}diff --git a/rust/ingestion-consumer/tests/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rsindex ee24c87783d2..4efa045648b2 100644--- a/rust/ingestion-consumer/tests/e2e_integration_test.rs+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs@@ -25,7 +25,6 @@ use tokio_util::sync::CancellationToken;use uuid::Uuid;use common_kafka_consumer::{TopicOffsetLedger, TopicPartition};-use ingestion_consumer::config::LedgerMode;use ingestion_consumer::consumer::{IngestionConsumer, IngestionConsumerOptions};use ingestion_consumer::discovery::reconcile_membership;use ingestion_consumer::dispatcher::Dispatcher;@@ -436,7 +435,6 @@ struct Harness {pub ledger: Arc<TopicOffsetLedger>,max_in_flight: usize,deferred_flush_timeout: Duration,- ledger_mode: LedgerMode,}/// Build a Kafka consumer subscribed to `topic` in `group_id`, configured like@@ -533,7 +531,6 @@ impl Harness {registry_config,0,ComponentOptions::new(),- LedgerMode::Shadow,).await}@@ -556,7 +553,6 @@ impl Harness {ComponentOptions::new().with_liveness_deadline(liveness_deadline).with_stall_threshold(stall_threshold),- LedgerMode::Shadow,).await}@@ -574,24 +570,6 @@ impl Harness {fast_registry_config(),batch_size_bytes,ComponentOptions::new(),- LedgerMode::Shadow,- )- .await- }-- /// Single worker and partition, ledger commit mode: the Kafka commit- /// comes from the ledger frontier instead of the batch spans.- async fn start_commit_mode(topic: &str) -> Self {- Self::start_inner(- topic,- 1,- 1,- 1,- Duration::from_secs(60),- fast_registry_config(),- 0,- ComponentOptions::new(),- LedgerMode::Commit,).await}@@ -606,7 +584,6 @@ impl Harness {registry_config: WorkerRegistryConfig,batch_size_bytes: usize,component_options: ComponentOptions,- ledger_mode: LedgerMode,) -> Self {create_topic(topic, partitions).await;@@ -642,9 +619,7 @@ impl Harness {let group_id = format!("e2e-{}", Uuid::new_v4());let context = SentinelContext::detached();- let ledger = context- .topic_offset_ledger()- .expect("a detached context carries a ledger");+ let ledger = context.topic_offset_ledger();let kafka_consumer = make_kafka_consumer_with_context(topic, &group_id, None, context);let consumer = IngestionConsumer::from_parts(@@ -660,7 +635,6 @@ impl Harness {group_id: "e2e-test".to_string(),deferred_flush_timeout,debug_recorder: None,- ledger_mode,},handle,);@@ -683,7 +657,6 @@ impl Harness {ledger,max_in_flight,deferred_flush_timeout,- ledger_mode,}}@@ -720,9 +693,7 @@ impl Harness {self.shutdown = handle.shutdown_token();let context = SentinelContext::detached();- self.ledger = context- .topic_offset_ledger()- .expect("a detached context carries a ledger");+ self.ledger = context.topic_offset_ledger();let kafka_consumer =make_kafka_consumer_with_context(&self.topic, &self.group_id, None, context);let consumer = IngestionConsumer::from_parts(@@ -738,7 +709,6 @@ impl Harness {group_id: "e2e-test".to_string(),deferred_flush_timeout: self.deferred_flush_timeout,debug_recorder: None,- ledger_mode: self.ledger_mode,},handle,);@@ -2018,13 +1988,21 @@ async fn consumer_crash_before_commit_redelivers_without_loss() {harness.stop().await;}-/// Commit mode: the broker-committed offset is the ledger frontier — one past-/// everything the workers accepted — and a restart resumes from it with no-/// loss and no redelivery.+/// The broker-committed offset is the ledger frontier — one past everything+/// the workers accepted — and a restart resumes from it with no loss and no+/// redelivery.#[tokio::test]-async fn commit_mode_commits_the_ledger_frontier() {+async fn the_committed_offset_is_the_ledger_frontier() {let topic = format!("e2e-ledger-commit-{}", Uuid::new_v4());- let mut harness = Harness::start_commit_mode(&topic).await;+ let mut harness = Harness::start(+ &topic,+ 1,+ 1,+ 1,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;let producer = make_producer();for seq in 0..10usize {@@ -2582,7 +2560,6 @@ async fn second_consumer_joining_the_group_preserves_all_messages() {group_id: "e2e-test".to_string(),deferred_flush_timeout: Duration::from_secs(60),debug_recorder: None,- ledger_mode: LedgerMode::Shadow,},handle2,);@@ -2690,7 +2667,6 @@ async fn partition_lost_and_regained_keeps_the_consumer_alive() {group_id: "e2e-test".to_string(),deferred_flush_timeout: Duration::from_secs(60),debug_recorder: None,- ledger_mode: LedgerMode::Shadow,},handle2,);@@ -2804,7 +2780,6 @@ async fn fenced_static_member_exits_on_fatal_error() {group_id: "e2e-test".to_string(),deferred_flush_timeout: Duration::from_secs(60),debug_recorder: None,- ledger_mode: LedgerMode::Shadow,},handle,);