: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): encapsulate the worker batcher (#93162)
José Sequeira013d099c7237
diff --git a/rust/common/kafka-consumer/src/assignment_epoch.rs b/rust/common/kafka-consumer/src/assignment_epoch.rsnew file mode 100644index 000000000000..6befd08b937e--- /dev/null+++ b/rust/common/kafka-consumer/src/assignment_epoch.rs@@ -0,0 +1,56 @@+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::Arc;++/// The consumer's assignment generation: bumped once per partition-assign+/// rebalance event, and read wherever work must be tied to the assignment it+/// was created under. A reader that stamps work at creation can later tell+/// whether the work predates the current assignment.+///+/// The owning consumer's rebalance callback is the single bump site; every+/// other holder only reads. Clones share one counter, so every component+/// holds the same generation.+#[derive(Clone, Debug)]+pub struct AssignmentEpoch {+ counter: Arc<AtomicU64>,+}++impl AssignmentEpoch {+ pub fn new() -> Self {+ Self {+ counter: Arc::new(AtomicU64::new(1)),+ }+ }++ /// Record one more assignment. Called from the rebalance callback.+ pub fn bump(&self) {+ self.counter.fetch_add(1, Ordering::Relaxed);+ }++ /// The current epoch, for stamping work as it is created.+ pub fn current(&self) -> u64 {+ self.counter.load(Ordering::Relaxed)+ }+}++impl Default for AssignmentEpoch {+ fn default() -> Self {+ Self::new()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn clones_share_the_counter() {+ let epoch = AssignmentEpoch::new();+ let clone = epoch.clone();+ assert_eq!(epoch.current(), 1);++ clone.bump();++ assert_eq!(epoch.current(), 2);+ assert_eq!(clone.current(), 2);+ }+}diff --git a/rust/common/kafka-consumer/src/lib.rs b/rust/common/kafka-consumer/src/lib.rsindex dd79297194ad..56ad1099c44f 100644--- a/rust/common/kafka-consumer/src/lib.rs+++ b/rust/common/kafka-consumer/src/lib.rs@@ -1,6 +1,7 @@//! Kafka consumption primitives shared by stateful services.pub mod accumulator;+pub mod assignment_epoch;pub mod charge;pub mod config;pub mod partition_offset_ledger;@@ -8,8 +9,9 @@ pub mod topic_offset_ledger;pub mod types;pub use accumulator::{Accumulator, Group, GroupMessage, PolledMessage};+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 types::{Offset, Partition};+pub use types::{GroupCompletion, Offset, Partition};diff --git a/rust/common/kafka-consumer/src/types.rs b/rust/common/kafka-consumer/src/types.rsindex f05863943598..a656efe5756e 100644--- a/rust/common/kafka-consumer/src/types.rs+++ b/rust/common/kafka-consumer/src/types.rs@@ -12,6 +12,23 @@ impl fmt::Display for Partition {}}+/// One group's completion: the group's messages were delivered downstream and+/// the consumer may account them toward its poll and, later, its commit. No+/// batch identity and no message bodies cross this boundary; the consumer+/// correlates by partition and offset.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct GroupCompletion {+ pub partition: Partition,+ /// The assignment epoch under which the group's poll was collected. A+ /// completion for a partition that was revoked and reassigned in between+ /// carries an older epoch than any poll of the new incarnation.+ pub assignment_epoch: u64,+ /// The offsets of the group's messages, in group order.+ pub offsets: Vec<Offset>,+ /// How many of the group's messages the worker accepted.+ pub accepted: u32,+}+/// A Kafka message offset.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]pub struct Offset(pub i64);diff --git a/rust/ingestion-consumer/docs/driver-model-plan.md b/rust/ingestion-consumer/docs/driver-model-plan.mdindex 4d7f14a9214b..5429d1def52c 100644--- a/rust/ingestion-consumer/docs/driver-model-plan.md+++ b/rust/ingestion-consumer/docs/driver-model-plan.md@@ -263,22 +263,24 @@ Exit criterion: zero key-order sentinel violations, `ingestion_consumer_transpor- `GrpcTransport`, `Router`, and `WorkerRegistry` keep their construction and ownership in `main.rs`. The batcher takes shared handles. Readiness gating, discovery reconciliation, the reaper, and the debug endpoints do not change.- The facade replicates today's behavior exactly, including the oldest-first flush pacing. This is code motion — moving code without changing it — not redesign.- The consumer loop keeps: poll collection, commits, the sentinels, and the admission cap. It tracks each poll's offset spans and completes the poll when completions cover them, so completion and commit behavior do not change.-- The no-progress watchdog survives the move: a poll that gains no completions for the stall window fails the process and replays, exactly as the deferred-flush timeout does today. Every later cycle keeps this bail until cycle 10 adds the per-partition stall deadline.-- The consumer discards a completion whose epoch is not the partition's current epoch, and counts it. The epoch already exists on master. Carrying it on the completion from this change closes the window a partition-ownership check leaves open: a partition revoked and reassigned while a group is out gets a new ledger, and the old incarnation's completion must not land in it.+- The no-progress watchdog moves with the flush: the stall deadline lives in the batcher's flush driver, and only there. The clock suspends while a send is in flight and resets when messages land, exactly as today — a consumer-side completions-only timer cannot see the difference between a wedged flush and a slow send, and would fail drains that today survive. The batcher reports a stall (and the other fatal orchestration failures: shutdown while deferred work is unroutable, a batch with no usable workers) on an error channel beside the completions; the consumer fails the process on the first message, keeping the failure decision in the loop. Every later cycle keeps this bail until cycle 10 adds the per-partition stall deadline.+- Each completion carries the assignment epoch read once at submit, and `submit` returns it. The consumer correlates a completion to a poll by epoch plus partition and offset — within one epoch, poll spans are disjoint per partition — and discards and counts a completion that matches no in-flight poll. The epoch already exists on master. Carrying it on the completion from this change closes the window a partition-ownership check leaves open: a partition revoked, reassigned, and replayed while a group is out has two polls holding the same offsets, and the old incarnation's completion must not land in the new poll (nor, later, in its new ledger).- Changes 8 and 9 extract the scheduler seam inside this boundary.**Interfaces:**- Submit the `Accumulator` from change 6 as one poll's groups, in poll order.-- Add `Batcher` in `batcher.rs`: `submit(Accumulator)` in, a channel of `GroupCompletion` out. It owns `Dispatcher` and the send tasks, and holds shared handles to `GrpcTransport`, `Router`, and `WorkerRegistry`. It creates batch ids internally.-- Add `GroupCompletion`: partition, assignment epoch, offsets, accepted count. No batch id and no messages: the batcher keeps the bodies for retry, and the ledger needs only the offsets.-- Modify `IngestionConsumer`: drop `scatter` and `flush_deferred` — they move into the batcher. Keep collect, commit, and the admission cap. Correlate completions to polls by partition and offset.+- Add `Batcher` in `batcher.rs`: `submit(Accumulator)` in (returning the stamped assignment epoch), a channel of `GroupCompletion` plus an error channel out. It owns `Dispatcher` and the send tasks, and holds shared handles to `GrpcTransport`, `Router`, and `WorkerRegistry`, plus a lifecycle handle and the deferred-flush timeout for its flush driver. It creates batch ids internally.+- Add `GroupCompletion` in the crate's `types.rs`: partition, assignment epoch, offsets, accepted count. No batch id and no messages: the batcher keeps the bodies for retry, and the ledger needs only the offsets.+- Add `AssignmentEpoch` to the crate: the named home of the assignment generation. `main.rs` creates it, the rebalance context bumps it, and the transport and the batcher read it — one counter, one bump site, two readers.+- Modify `IngestionConsumer`: drop `scatter` and `flush_deferred` — they move into the batcher. Keep collect, commit, and the admission cap. Correlate completions to polls by epoch, partition, and offset.- Modify `main.rs`: construct one `Batcher` from the existing transport, registry, and router. The consumer no longer sees the dispatcher.-- Internalize `Dispatcher`'s resolve methods (`on_sub_batch_*`, `defer_failed`): only the batcher calls them.+- Internalize `Dispatcher`'s resolve methods (`on_sub_batch_*`, `defer_failed`): only the batcher calls them in production code. The methods stay public because the e2e suite drives them directly, and that suite must pass unedited.**Metrics:**-- Add `ingestion_consumer_group_completions_total` (counter) and its accepted-message sum. Cross-check: the sum tracks `ingestion_consumer_messages_processed_total`.+- Add `ingestion_consumer_group_completions_total` (counter) and its accepted-message sum, `ingestion_consumer_group_completion_accepted_messages_total`. Cross-check: the sum tracks `ingestion_consumer_messages_processed_total`.+- Add `ingestion_consumer_stale_group_completions_total` (counter): completions discarded because no in-flight poll matched.### 8. Extract the scheduler seam (prepare)diff --git a/rust/ingestion-consumer/src/batcher.rs b/rust/ingestion-consumer/src/batcher.rsnew file mode 100644index 000000000000..330e528f5538--- /dev/null+++ b/rust/ingestion-consumer/src/batcher.rs@@ -0,0 +1,555 @@+//! The worker batcher: the dispatch orchestration behind one boundary.+//!+//! The consumer loop submits one [`Accumulator`] per poll, in poll order, and+//! receives one [`GroupCompletion`] per group back. Everything in between is+//! an implementation detail of this module: assignment, the scatter over the+//! worker streams with its send resolution, and the serialized oldest-first+//! deferred flush. No batch identity crosses the boundary: the batcher+//! creates an internal batch id per accumulator for the dispatcher and the+//! wire request, and the consumer correlates completions by partition and+//! offset.+//!+//! Fatal orchestration failures (a wedged deferred flush, shutdown while+//! deferred work is unroutable, a batch with no usable workers) are reported+//! on an error channel; the consumer turns them into a process failure, so+//! the failure decision stays in the consumer loop.++use std::collections::HashMap;+use std::sync::Arc;+use std::time::{Duration, Instant};++use common_kafka_consumer::{AssignmentEpoch, GroupCompletion, Offset, Partition};+use lifecycle::Handle;+use metrics::{counter, histogram};+use tokio::sync::mpsc;+use tokio::task::JoinHandle;+use tracing::{error, info};++use crate::dispatcher::{Dispatcher, KeyOffset, SubBatch};+use crate::grpc_transport::{GrpcTransport, PendingWorkerStreamSend};+use crate::order_sentinel::KeyOrderSentinel;+use crate::transport::SendError;+use crate::types::Accumulator;+use crate::types::SerializedKafkaMessage;+use crate::worker_registry::WorkerId;++/// The batcher's output channels, held by the consumer loop.+pub struct BatcherOutputs {+ /// One event per group: its partition, assignment epoch, offsets, and+ /// accepted count.+ pub completions: mpsc::UnboundedReceiver<GroupCompletion>,+ /// Fatal orchestration failures. The consumer fails the process on the+ /// first message.+ pub errors: mpsc::UnboundedReceiver<String>,+}++/// A slice of a batch whose send order is already established on its worker's+/// stream (`GrpcTransport::begin_send`), plus the metadata the resolve+/// protocol and the completion events need.+struct PendingSubBatch {+ worker: WorkerId,+ routing_keys: Vec<String>,+ key_offsets: Vec<KeyOffset>,+ message_count: usize,+ /// The accumulator groups this sub-batch carries, kept aside so the+ /// resolved send can be broken back into per-group completions.+ groups: Vec<CompletionGroup>,+ pending: PendingWorkerStreamSend,+}++/// One accumulator group's share of a sub-batch: its partition and offsets.+struct CompletionGroup {+ partition: Partition,+ offsets: Vec<Offset>,+}++/// One submitted batch in the flush driver's queue: the driver awaits the+/// batch's scatter, then flushes its deferred groups, oldest batch first.+struct FlushTicket {+ batch_id: String,+ assignment_epoch: u64,+ scatter: JoinHandle<()>,+}++struct BatcherInner {+ dispatcher: Arc<Dispatcher>,+ transport: Arc<GrpcTransport>,+ /// Stamped on each submitted batch's completions; bumped on partition+ /// assignment by the consumer's rebalance context.+ assignment_epoch: AssignmentEpoch,+ completions: mpsc::UnboundedSender<GroupCompletion>,+ errors: mpsc::UnboundedSender<String>,+}++impl BatcherInner {+ fn report_error(&self, message: String) {+ error!(error = %message, "Batcher failure");+ if self.errors.send(message).is_err() {+ error!("Batcher error channel closed; consumer is gone");+ }+ }+}++/// Emit one completion per group of a successfully resolved send. A send is+/// all-or-nothing, so `accepted` normally equals the sub-batch size and each+/// group completes with its own length; a worker that under-reports shorts+/// the tail groups, so the poll fails its accepted check and the process+/// exits and replays.+fn send_group_completions(+ completions: &mpsc::UnboundedSender<GroupCompletion>,+ groups: Vec<CompletionGroup>,+ assignment_epoch: u64,+ accepted: u32,+) {+ let mut remaining = accepted;+ for group in groups {+ let group_accepted = remaining.min(group.offsets.len() as u32);+ remaining -= group_accepted;+ counter!("ingestion_consumer_group_completions_total").increment(1);+ counter!("ingestion_consumer_group_completion_accepted_messages_total")+ .increment(group_accepted as u64);+ let _ = completions.send(GroupCompletion {+ partition: group.partition,+ assignment_epoch,+ offsets: group.offsets,+ accepted: group_accepted,+ });+ }+}++/// Owns the dispatch orchestration: the dispatcher, the scatter tasks, and+/// the deferred-flush driver. Holds shared handles to the transport; the+/// transport, router, and registry keep their construction and ownership in+/// `main.rs`.+pub struct Batcher {+ inner: Arc<BatcherInner>,+ flush_queue: mpsc::UnboundedSender<FlushTicket>,+}++impl Batcher {+ pub fn new(+ dispatcher: Arc<Dispatcher>,+ transport: Arc<GrpcTransport>,+ handle: Handle,+ deferred_flush_timeout: Duration,+ ) -> (Self, BatcherOutputs) {+ let (completions_tx, completions_rx) = mpsc::unbounded_channel();+ let (errors_tx, errors_rx) = mpsc::unbounded_channel();+ let assignment_epoch = transport.assignment_epoch();+ let inner = Arc::new(BatcherInner {+ dispatcher,+ transport,+ assignment_epoch,+ completions: completions_tx,+ errors: errors_tx,+ });+ let (flush_queue, flush_rx) = mpsc::unbounded_channel();+ tokio::spawn(run_flush_driver(+ Arc::clone(&inner),+ flush_rx,+ handle,+ deferred_flush_timeout,+ ));+ (+ Self { inner, flush_queue },+ BatcherOutputs {+ completions: completions_rx,+ errors: errors_rx,+ },+ )+ }++ /// The dispatcher's per-key order sentinel, shared with the consumer's+ /// rdkafka context so rebalances can reset its baselines.+ pub fn key_order_sentinel(&self) -> Arc<KeyOrderSentinel> {+ self.inner.dispatcher.key_order_sentinel()+ }++ /// Submit one poll's demuxed groups. Call on the consumer loop, in poll+ /// order. Returns the assignment epoch stamped on the poll's completions,+ /// so the consumer can correlate them without a second epoch read.+ ///+ /// Registration and assignment both happen here, synchronously, so both+ /// happen in true batch order. Registration first, so the stash learns+ /// batch order before failed-send deferrals (which land in gather order)+ /// can reach it. Assignment too: on spawned tasks, batch N+1's assign+ /// could beat batch N's to the pin table and send a key's newer messages+ /// first — per-key send order must be fixed exactly once, in Kafka order,+ /// at assignment. Send order is also established here, under the+ /// dispatcher's lock: `begin_send` is synchronous, so a key's sub-batches+ /// enter its worker's stream in assignment order.+ pub fn submit(&self, accumulator: Accumulator) -> u64 {+ let assignment_epoch = self.inner.assignment_epoch.current();+ let batch_id = make_batch_id();+ self.inner.dispatcher.register_batch(&batch_id);+ let assign_start = Instant::now();+ let groups = accumulator.into_groups();+ let pending = self+ .inner+ .dispatcher+ .assign_and_send(&batch_id, groups, |sub_batch| {+ begin_send(&self.inner.transport, &batch_id, sub_batch, false)+ });+ // Assignment serializes on the consumer loop (it does not overlap+ // batch collection) — watch this stays a small fraction of the batch+ // collection interval.+ histogram!("ingestion_consumer_assign_duration_seconds")+ .record(assign_start.elapsed().as_secs_f64());++ let scatter = tokio::spawn(run_scatter(+ Arc::clone(&self.inner),+ batch_id.clone(),+ pending,+ assignment_epoch,+ ));+ let _ = self.flush_queue.send(FlushTicket {+ batch_id,+ assignment_epoch,+ scatter,+ });+ assignment_epoch+ }+}++/// Await a batch's pre-ordered sub-batch sends and feed passive health+/// signals. Reports a batch that had no usable workers, and records the+/// scatter duration on success.+async fn run_scatter(+ inner: Arc<BatcherInner>,+ batch_id: String,+ pending: Vec<PendingSubBatch>,+ assignment_epoch: u64,+) {+ // Nothing to send and no deferred groups means no usable workers.+ if pending.is_empty() && !inner.dispatcher.batch_has_flush_activity(&batch_id) {+ counter!("ingestion_consumer_no_healthy_workers_total").increment(1);+ inner.report_error("No healthy workers available to route batch".to_string());+ return;+ }+ let start = Instant::now();+ match scatter(&inner, &batch_id, pending, false, assignment_epoch).await {+ Ok(_) => {+ histogram!("ingestion_consumer_batch_processing_duration_seconds")+ .record(start.elapsed().as_secs_f64());+ info!(batch_id = %batch_id, "Kafka batch processing completed");+ }+ Err(err) => inner.report_error(format!("awaiting sub-batches failed: {err:#}")),+ }+}++/// Await sub-batch sends in parallel and resolve each in the dispatcher.+/// On a send failure (the worker died mid-send, or its worker stream was fenced),+/// the failed messages are deferred — before the resolve, so the pin+/// isn't evicted — to be replayed in order. A successful send emits one+/// completion per group it carried. Returns the number of messages accepted.+///+/// `from_flush` is true when awaiting sub-batches produced by the flush driver:+/// the resolve then clears one deferral per key, so a key stays deferring from+/// when it was first held until its flushed messages actually land (preventing+/// a newer batch from racing them).+async fn scatter(+ inner: &Arc<BatcherInner>,+ batch_id: &str,+ pending: Vec<PendingSubBatch>,+ from_flush: bool,+ assignment_epoch: u64,+) -> anyhow::Result<u32> {+ let mut handles = Vec::with_capacity(pending.len());+ for sub_batch in pending {+ let inner = Arc::clone(inner);+ let PendingSubBatch {+ worker,+ routing_keys,+ key_offsets,+ message_count,+ groups,+ pending,+ } = sub_batch;+ let bid = batch_id.to_string();++ handles.push(tokio::spawn(async move {+ match pending.wait().await {+ Ok(accepted) => {+ // Advance ACK high-water marks before the resolve, which+ // may evict the keys' sentinel state.+ inner.dispatcher.on_sub_batch_acked(&key_offsets);+ inner.dispatcher.on_sub_batch_resolved(+ &worker,+ message_count,+ &routing_keys,+ from_flush,+ false,+ );+ inner.dispatcher.record_send_outcome(&worker, false);+ send_group_completions(&inner.completions, groups, assignment_epoch, accepted);+ accepted+ }+ Err(send_err) => {+ // Re-defer the failed messages first, so the ref-count drop+ // in `on_sub_batch_resolved` doesn't evict the pin while the+ // key still has work to replay. On the flush path this pairs+ // with the `clears_deferral` decrement in the resolve, so the+ // outstanding count nets to unchanged (never dipping to zero)+ // and the key keeps deferring across the retry.+ // Backpressure (a busy worker) is transient, not a fault:+ // re-route the work but do not count it against the+ // worker's health, so passive health tracks real faults.+ let SendError {+ error,+ messages,+ fence_guard,+ } = send_err;+ let is_fault = !error.is_backpressure();+ inner.dispatcher.defer_failed(&bid, messages);+ // Stashed: let the worker stream stop fencing new arrivals.+ drop(fence_guard);+ inner.dispatcher.on_sub_batch_resolved(+ &worker,+ message_count,+ &routing_keys,+ from_flush,+ true,+ );+ inner.dispatcher.record_send_outcome(&worker, is_fault);+ 0+ }+ }+ }));+ }++ let mut accepted = 0u32;+ for handle in handles {+ accepted += handle.await?;+ }+ Ok(accepted)+}++/// Flush each batch's deferred groups (keys whose worker was draining/dead)+/// in submit order, re-routing them to healthy workers. Serialized, oldest+/// batch first, after that batch's own scatter has resolved, which preserves+/// per-key order across batches. Retries with backoff while a flush can't+/// route (no healthy worker yet).+///+/// The stall deadline bounds **stalls, not total time**: it resets whenever+/// any of the batch's messages are accepted, so a large backlog draining+/// slowly under saturation keeps going, and the batcher only reports failure+/// — exiting the process and replaying — when flushing is truly wedged:+/// nothing landed for a full timeout (nothing routable, or a flapping worker+/// re-deferring every send). Failing the whole process for a mere slow drain+/// amplified today's saturation: each restart replayed all its partitions+/// into an already overloaded pool.+async fn run_flush_driver(+ inner: Arc<BatcherInner>,+ mut tickets: mpsc::UnboundedReceiver<FlushTicket>,+ handle: Handle,+ deferred_flush_timeout: Duration,+) {+ while let Some(ticket) = tickets.recv().await {+ if let Err(err) = ticket.scatter.await {+ inner.report_error(format!("batch processing task failed: {err:#}"));+ return;+ }+ if inner.dispatcher.has_unfinished_flush(&ticket.batch_id) {+ let mut stall_deadline = Instant::now() + deferred_flush_timeout;+ while inner.dispatcher.has_unfinished_flush(&ticket.batch_id) {+ if Instant::now() >= stall_deadline {+ inner.report_error(+ "deferred messages made no progress within the flush timeout".to_string(),+ );+ return;+ }+ // Serialized on this driver, oldest batch first, so+ // begin_send order preserves the flush's key order.+ let pending = inner+ .dispatcher+ .flush_deferred_and_send(&ticket.batch_id, |sub_batch| {+ begin_send(&inner.transport, &ticket.batch_id, sub_batch, true)+ });+ if pending.is_empty() {+ // Nothing is routable right now (no healthy worker), so wait.+ tokio::select! {+ _ = handle.shutdown_recv() => {+ inner.report_error(+ "shutdown while flushing deferred messages".to_string(),+ );+ return;+ }+ _ = tokio::time::sleep(Duration::from_millis(200)) => {+ handle.report_healthy();+ }+ }+ } else {+ match scatter(+ &inner,+ &ticket.batch_id,+ pending,+ true,+ ticket.assignment_epoch,+ )+ .await+ {+ Ok(accepted) if accepted > 0 => {+ stall_deadline = Instant::now() + deferred_flush_timeout;+ }+ Ok(_) => {}+ Err(err) => {+ inner.report_error(format!(+ "awaiting flushed sub-batches failed: {err:#}"+ ));+ return;+ }+ }+ }+ }+ }+ inner.dispatcher.release_batch(&ticket.batch_id);+ }+}++/// Establish a sub-batch's send order. Synchronous and non-blocking on+/// purpose: called under the dispatcher's lock, where send order is decided,+/// so a key's sub-batches enter its worker's stream in exactly that order.+fn begin_send(+ transport: &GrpcTransport,+ batch_id: &str,+ sub_batch: SubBatch,+ replay: bool,+) -> PendingSubBatch {+ let SubBatch {+ worker,+ messages,+ routing_keys,+ key_offsets,+ } = sub_batch;+ let groups = completion_groups(&messages);+ let message_count = messages.len();+ let pending = transport.begin_send(&worker, batch_id, messages, replay);+ PendingSubBatch {+ worker,+ routing_keys,+ key_offsets,+ message_count,+ groups,+ pending,+ }+}++/// Reconstruct the accumulator's groups from a sub-batch's messages: one+/// group per partition and key, a keyless message on its own. The dispatcher+/// may merge one key's groups from two partitions into one sub-batch (the pin+/// table is partition-blind); a completion names one partition, so the merge+/// splits back here.+fn completion_groups(messages: &[SerializedKafkaMessage]) -> Vec<CompletionGroup> {+ let mut groups: Vec<CompletionGroup> = Vec::new();+ let mut index_by_key: HashMap<(Partition, &str), usize> = HashMap::new();+ for message in messages {+ let partition = Partition(message.partition);+ let offset = Offset(message.offset);+ match message.key.as_deref() {+ None => groups.push(CompletionGroup {+ partition,+ offsets: vec![offset],+ }),+ Some(key) => match index_by_key.get(&(partition, key)) {+ Some(&index) => groups[index].offsets.push(offset),+ None => {+ index_by_key.insert((partition, key), groups.len());+ groups.push(CompletionGroup {+ partition,+ offsets: vec![offset],+ });+ }+ },+ }+ }+ groups+}++pub(crate) fn make_batch_id() -> String {+ let ts = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_millis();+ let rand: u32 = rand::random();+ format!("{ts:x}-{rand:08x}")+}++#[cfg(test)]+mod tests {+ use super::*;++ fn message(partition: i32, offset: i64, key: Option<&str>) -> SerializedKafkaMessage {+ SerializedKafkaMessage {+ topic: "test".to_string(),+ partition,+ offset,+ timestamp: 0,+ key: key.map(|k| k.to_string()),+ value: None,+ headers: HashMap::new(),+ }+ }++ fn shapes(groups: &[CompletionGroup]) -> Vec<(i32, Vec<i64>)> {+ groups+ .iter()+ .map(|g| (g.partition.0, g.offsets.iter().map(|o| o.0).collect()))+ .collect()+ }++ #[test]+ fn completion_groups_split_per_partition_and_key() {+ // The dispatcher merges one key across partitions into one sub-batch;+ // the completion groups must split it back per partition.+ let groups = completion_groups(&[+ message(0, 1, Some("a")),+ message(0, 2, Some("b")),+ message(3, 9, Some("a")),+ message(0, 4, Some("a")),+ ]);+ assert_eq!(+ shapes(&groups),+ vec![(0, vec![1, 4]), (0, vec![2]), (3, vec![9])]+ );+ }++ #[test]+ fn completion_groups_keep_keyless_messages_alone() {+ let groups = completion_groups(&[+ message(7, 42, None),+ message(7, 43, None),+ message(7, 44, Some("a")),+ ]);+ assert_eq!(+ shapes(&groups),+ vec![(7, vec![42]), (7, vec![43]), (7, vec![44])]+ );+ }++ #[tokio::test]+ async fn send_group_completions_apportions_an_under_reported_accepted_count() {+ let (completions_tx, mut completions_rx) = mpsc::unbounded_channel();++ let groups = vec![+ CompletionGroup {+ partition: Partition(0),+ offsets: vec![Offset(1), Offset(2)],+ },+ CompletionGroup {+ partition: Partition(0),+ offsets: vec![Offset(3), Offset(4)],+ },+ ];+ send_group_completions(&completions_tx, groups, 5, 3);++ let first = completions_rx.recv().await.expect("first completion");+ assert_eq!(first.assignment_epoch, 5);+ assert_eq!(first.offsets, vec![Offset(1), Offset(2)]);+ assert_eq!(first.accepted, 2);+ // The worker under-reported by one, so the tail group is shorted and+ // the consumer's accepted check fails the poll.+ let second = completions_rx.recv().await.expect("second completion");+ assert_eq!(second.offsets, vec![Offset(3), Offset(4)]);+ assert_eq!(second.accepted, 1);+ }+}diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rsindex e992e6597972..ab42461ac4f6 100644--- a/rust/ingestion-consumer/src/consumer.rs+++ b/rust/ingestion-consumer/src/consumer.rs@@ -1,28 +1,29 @@use std::collections::{HashMap, VecDeque};-use std::future::Future;use std::sync::Arc;use std::time::{Duration, Instant};-use common_kafka_consumer::{Charge, Offset, Partition, TopicOffsetLedger, TopicPartition};+use common_kafka_consumer::{+ Charge, GroupCompletion, 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::TopicPartitionList;+use tokio::sync::mpsc;use tokio::task::JoinHandle;use tracing::{error, info, warn};+use crate::batcher::{make_batch_id, Batcher, BatcherOutputs};use crate::config::Config;use crate::debug_recorder::{record_if, DebugEventKind, DebugRecorder, PartitionOffset};use crate::discovery::DiscoveryMode;-use crate::dispatcher::{Dispatcher, KeyOffset, SubBatch};-use crate::grpc_transport::{GrpcTransport, PendingWorkerStreamSend};+use crate::dispatcher::Dispatcher;+use crate::grpc_transport::GrpcTransport;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;+use crate::types::{Accumulator, SerializedKafkaMessage};/// Batch-wide statistics gathered while collecting, used to emit parity/// metrics. Per-partition facts live on [`PartitionDeliveries`].@@ -116,35 +117,69 @@ impl PartitionDeliveries {/// Output of `collect_batch`.struct CollectedBatch {/// The poll's messages, demuxed per partition and routing key.- groups: Vec<Group>,+ accumulator: Accumulator,partitions: HashMap<TopicPartition, PartitionDeliveries>,stats: BatchStats,}-struct ProcessedBatch {+/// One submitted poll, awaiting its group completions. The consumer+/// correlates completions to it by assignment epoch, partition, and offset;+/// the poll commits only once completions cover every message.+struct InFlightPoll {+ /// Consumer-side id for logs and debug events only; the batcher's+ /// internal batch id never crosses the boundary.+ poll_id: String,+ /// The epoch the batcher stamped on this poll's completions.+ assignment_epoch: u64,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,- /// Total messages in the batch; the batch commits only once `total_accepted`- /// reaches it (i.e. all deferred groups have been flushed and ACKed).- batch_size: u32,- elapsed: Duration,+ message_count: u32,+ /// Messages covered by completions so far, accepted or not.+ covered: u32,+ /// Worker-accepted messages so far. The poll commits only when this+ /// reaches `message_count`.+ accepted: u32,+ dispatched_at: Instant,}-struct InFlightBatch {- batch_id: String,- handle: JoinHandle<anyhow::Result<ProcessedBatch>>,+impl InFlightPoll {+ fn is_complete(&self) -> bool {+ self.covered >= self.message_count+ }++ fn contains(&self, partition: Partition, offset: i64) -> bool {+ self.partitions.iter().any(|(topic_partition, deliveries)| {+ topic_partition.partition == partition.0+ && deliveries.span.first <= offset+ && offset <= deliveries.span.last+ })+ }}-/// A sub-batch whose send order is already established on its worker's stream-/// (`GrpcTransport::begin_send`), plus the metadata the resolve protocol needs.-struct PendingSubBatch {- worker: WorkerId,- routing_keys: Vec<String>,- key_offsets: Vec<KeyOffset>,- message_count: usize,- pending: PendingWorkerStreamSend,+/// Credit a completion to the poll it belongs to: the one collected under the+/// same assignment epoch whose offset span holds the completion's offsets.+/// Within one epoch, poll spans are disjoint per partition, so at most one+/// poll matches. A completion that matches no in-flight poll (its partition+/// was revoked and reassigned while the group was out, or its poll is gone)+/// is discarded and counted.+fn apply_completion(in_flight: &mut VecDeque<InFlightPoll>, completion: GroupCompletion) {+ let Some(first) = completion.offsets.first().map(|offset| offset.0) else {+ return;+ };+ let Some(poll) = in_flight.iter_mut().find(|poll| {+ poll.assignment_epoch == completion.assignment_epoch+ && poll.contains(completion.partition, first)+ }) else {+ counter!("ingestion_consumer_stale_group_completions_total").increment(1);+ warn!(+ partition = %completion.partition,+ offset = first,+ epoch = completion.assignment_epoch,+ "Discarding group completion that matches no in-flight poll"+ );+ return;+ };+ poll.covered += completion.offsets.len() as u32;+ poll.accepted += completion.accepted;}/// Options for constructing an [`IngestionConsumer`] from pre-built parts.@@ -157,28 +192,30 @@ pub struct IngestionConsumerOptions {pub batch_timeout: Duration,pub max_in_flight_batches: usize,pub group_id: String,- /// No-progress bound on flushing a batch's deferred groups: the deadline- /// resets whenever any of the batch's messages land, and the batch fails- /// only after a full window with zero progress. `new` takes it from+ /// No-progress bound on flushing a batch's deferred groups, enforced by+ /// the batcher's flush driver: the deadline resets whenever any of the+ /// batch's messages land, and the batch fails only after a full window+ /// with zero progress. Production takes it from/// `CONSUMER_DEFERRED_FLUSH_TIMEOUT_MS` (default 60s).pub deferred_flush_timeout: Duration,/// Debug event recorder; `None` unless `DEBUG_API_ENABLED`.pub debug_recorder: Option<Arc<DebugRecorder>>,}-/// The main consumer loop: reads from Kafka, routes messages by Kafka key-/// via the health-aware Dispatcher, dispatches sub-batches to workers over-/// ordered gRPC streams, and commits offsets only after all workers ACK.+/// The main consumer loop: reads from Kafka, demuxes each poll into groups,+/// submits them to the [`Batcher`] (which routes, dispatches, and flushes),+/// and commits offsets once the batcher's completions cover a poll.pub struct IngestionConsumer {consumer: Arc<StreamConsumer<SentinelContext>>,- dispatcher: Arc<Dispatcher>,+ batcher: Batcher,+ /// Taken once by `process`.+ outputs: Option<BatcherOutputs>,transport: Arc<GrpcTransport>,worker_urls: Vec<String>,batch_size: usize,batch_size_bytes: usize,batch_timeout: Duration,max_in_flight_batches: usize,- deferred_flush_timeout: Duration,handle: Handle,group_id: String,/// Validates commit contiguity/monotonicity per partition. Shared with the@@ -191,7 +228,9 @@ pub struct IngestionConsumer {impl IngestionConsumer {/// Constructs a consumer from pre-built parts. Useful in integration tests- /// where the Kafka consumer is created and subscribed externally.+ /// where the Kafka consumer is created and subscribed externally. Builds+ /// the batcher from the dispatcher and transport; `new` instead takes one+ /// built in `main`.pub fn from_parts(consumer: StreamConsumer<SentinelContext>,dispatcher: Arc<Dispatcher>,@@ -206,27 +245,34 @@ impl IngestionConsumer {// 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();+ let (batcher, outputs) = Batcher::new(+ dispatcher,+ Arc::clone(&transport),+ handle.clone(),+ options.deferred_flush_timeout,+ );Self {commit_sentinel,debug_recorder: options.debug_recorder,+ ledger_shadow: LedgerShadow::new(topic_offset_ledger),consumer: Arc::new(consumer),- dispatcher,+ batcher,+ outputs: Some(outputs),transport,worker_urls,batch_size: options.batch_size,batch_size_bytes: options.batch_size_bytes,batch_timeout: options.batch_timeout,max_in_flight_batches: options.max_in_flight_batches.max(1),- deferred_flush_timeout: options.deferred_flush_timeout,handle,group_id: options.group_id,- ledger_shadow: LedgerShadow::new(topic_offset_ledger),}}pub fn new(config: &Config,- dispatcher: Arc<Dispatcher>,+ batcher: Batcher,+ outputs: BatcherOutputs,transport: Arc<GrpcTransport>,handle: Handle,debug_recorder: Option<Arc<DebugRecorder>>,@@ -252,7 +298,7 @@ impl IngestionConsumer {);let commit_sentinel = Arc::new(CommitSentinel::new());commit_sentinel.set_enabled(config.consumer_order_sentinel_enabled);- let key_sentinel = dispatcher.key_order_sentinel();+ 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.@@ -282,26 +328,28 @@ impl IngestionConsumer {consumer: Arc::new(consumer),commit_sentinel,debug_recorder,- dispatcher,+ ledger_shadow: LedgerShadow::new(topic_offset_ledger),+ batcher,+ outputs: Some(outputs),transport,worker_urls,batch_size: config.consumer_batch_size,batch_size_bytes: config.consumer_batch_size_kb.saturating_mul(1024),batch_timeout: Duration::from_millis(config.consumer_batch_timeout_ms),max_in_flight_batches: config.consumer_max_background_tasks.max(1),- deferred_flush_timeout: Duration::from_millis(- config.consumer_deferred_flush_timeout_ms,- ),handle,group_id: config.ingestion_consumer_group_id.clone(),- ledger_shadow: LedgerShadow::new(topic_offset_ledger),})}/// Run the consumer loop until shutdown is signalled via the lifecycle handle./// Waits for all workers to be ready before starting to consume from Kafka.- pub async fn process(self) {+ pub async fn process(mut self) {let _guard = self.handle.process_scope();+ let BatcherOutputs {+ mut completions,+ mut errors,+ } = self.outputs.take().expect("process is called once");info!("Waiting for workers to be ready");if let Err(err) = self@@ -331,19 +379,19 @@ impl IngestionConsumer {self.handle.clone(),)));- let mut in_flight_batches = VecDeque::new();+ let mut in_flight_polls: VecDeque<InFlightPoll> = VecDeque::new();let mut accepting_new_batches = true;- while accepting_new_batches || !in_flight_batches.is_empty() {+ while accepting_new_batches || !in_flight_polls.is_empty() {// Consumer-level concurrency: how many Kafka batches are being// processed in parallel, bounded by `max_in_flight_batches`.- gauge!("ingestion_consumer_in_flight_batches").set(in_flight_batches.len() as f64);+ gauge!("ingestion_consumer_in_flight_batches").set(in_flight_polls.len() as f64);- if accepting_new_batches && in_flight_batches.len() < self.max_in_flight_batches {+ if accepting_new_batches && in_flight_polls.len() < self.max_in_flight_batches {tokio::select! {_ = self.handle.shutdown_recv() => {info!(- in_flight = in_flight_batches.len(),+ in_flight = in_flight_polls.len(),"Shutdown signal received, draining in-flight batches");accepting_new_batches = false;@@ -357,16 +405,16 @@ impl IngestionConsumer {}};- if collected.groups.is_empty() {+ if collected.accumulator.message_count() == 0 {self.handle.report_healthy();- if in_flight_batches.is_empty() {+ if in_flight_polls.is_empty() {continue;}} else {- in_flight_batches.push_back(self.spawn_batch_processing(collected));+ in_flight_polls.push_back(self.submit_poll(collected));self.handle.report_healthy();- if in_flight_batches.len() < self.max_in_flight_batches {+ if in_flight_polls.len() < self.max_in_flight_batches {continue;}}@@ -374,7 +422,10 @@ impl IngestionConsumer {}}- if let Err(err) = self.complete_oldest_batch(&mut in_flight_batches).await {+ if let Err(err) = self+ .complete_oldest_poll(&mut in_flight_polls, &mut completions, &mut errors)+ .await+ {self.fail_batch_processing(err);return;}@@ -383,193 +434,107 @@ impl IngestionConsumer {info!("Consumer loop stopped");}- fn spawn_batch_processing(&self, mut collected: CollectedBatch) -> InFlightBatch {- let batch_size: usize = collected.groups.iter().map(Group::len).sum();- let batch_id = make_batch_id();- // Register AND assign here, on the consumer loop, so both happen in- // true batch order. Registration first, so the stash learns batch- // order before failed-send deferrals (which land in gather order) can- // reach it. Assignment too: on spawned tasks, batch N+1's assign could- // beat batch N's to the pin table and send a key's newer messages- // first — per-key send order must be fixed exactly once, in Kafka- // order, at assignment.- self.dispatcher.register_batch(&batch_id);+ /// Submit one collected poll to the batcher and track it as in flight.+ fn submit_poll(&self, collected: CollectedBatch) -> InFlightPoll {+ let CollectedBatch {+ accumulator,+ partitions,+ stats,+ } = collected;+ let message_count = accumulator.message_count();+ let poll_id = make_batch_id();record_if(&self.debug_recorder, || DebugEventKind::BatchDispatched {- batch_id: batch_id.clone(),- messages: batch_size,- partitions: debug_partition_offsets(&collected.partitions),- });- let assign_start = Instant::now();- let groups = std::mem::take(&mut collected.groups);- // Send order is established here too, still on the consumer loop and- // under the dispatcher's lock: `begin_send` is synchronous, so a key's- // sub-batches enter its worker's stream in assignment order — spawned- // tasks racing to send would scramble it.- let pending = self- .dispatcher- .assign_and_send(&batch_id, groups, |sub_batch| {- Self::begin_send(&self.transport, &batch_id, sub_batch, false)- });- // Assignment serializes on the consumer loop (it no longer overlaps- // batch collection) — watch this stays a small fraction of the batch- // collection interval.- histogram!("ingestion_consumer_assign_duration_seconds")- .record(assign_start.elapsed().as_secs_f64());-- let task_batch_id = batch_id.clone();- let dispatcher = Arc::clone(&self.dispatcher);- let group_id = self.group_id.clone();- let max_batch_size = self.batch_size;- let max_batch_bytes = self.batch_size_bytes;-- let handle = tokio::spawn(async move {- Self::process_collected_batch(- collected,- pending,- batch_size,- task_batch_id,- dispatcher,- group_id,- max_batch_size,- max_batch_bytes,- )- .await+ batch_id: poll_id.clone(),+ messages: message_count,+ partitions: debug_partition_offsets(&partitions),});+ emit_poll_stats(+ &stats,+ &partitions,+ message_count,+ &self.group_id,+ self.batch_size,+ self.batch_size_bytes,+ );++ let assignment_epoch = self.batcher.submit(accumulator);info!(- batch_id = %batch_id,- messages = batch_size,+ batch_id = %poll_id,+ messages = message_count,"Kafka batch dispatched");- InFlightBatch { batch_id, handle }+ InFlightPoll {+ poll_id,+ assignment_epoch,+ partitions,+ message_count: message_count as u32,+ covered: 0,+ accepted: 0,+ dispatched_at: Instant::now(),+ }}- async fn complete_oldest_batch(+ /// Wait for completions to cover the oldest in-flight poll, then commit+ /// it. Commits only the oldest poll: later completed polls stay+ /// uncommitted behind any earlier one, preserving at-least-once delivery+ /// across worker or pipeline failures. Completions for newer polls are+ /// still credited while waiting.+ async fn complete_oldest_poll(&self,- in_flight_batches: &mut VecDeque<InFlightBatch>,+ in_flight_polls: &mut VecDeque<InFlightPoll>,+ completions: &mut mpsc::UnboundedReceiver<GroupCompletion>,+ errors: &mut mpsc::UnboundedReceiver<String>,) -> anyhow::Result<()> {- let Some(batch) = in_flight_batches.pop_front() else {+ if in_flight_polls.front().is_none() {return Ok(());- };-- let batch_id = batch.batch_id.clone();- let mut processed = self.await_processed_batch(batch).await?;+ }- // Flush this batch's deferred groups (keys whose worker was draining/dead)- // in order, re-routing them to healthy workers. Doing it here — serialized,- // oldest batch first — preserves per-key order across batches. The- // batch isn't committable until all its messages are accepted.- self.flush_deferred(&batch_id, &mut processed).await?;+ let mut heartbeat = tokio::time::interval(Duration::from_secs(1));+ while !in_flight_polls+ .front()+ .expect("front is present")+ .is_complete()+ {+ tokio::select! {+ completion = completions.recv() => match completion {+ Some(completion) => apply_completion(in_flight_polls, completion),+ None => anyhow::bail!("batcher completion channel closed"),+ },+ failure = errors.recv() => match failure {+ Some(message) => anyhow::bail!(message),+ None => anyhow::bail!("batcher error channel closed"),+ },+ _ = heartbeat.tick() => self.handle.report_healthy(),+ }+ }- if processed.total_accepted < processed.batch_size {+ let poll = in_flight_polls.pop_front().expect("front is present");+ if poll.accepted < poll.message_count {anyhow::bail!("accepted {}/{} messages — not committing offsets",- processed.total_accepted,- processed.batch_size+ poll.accepted,+ poll.message_count);}- // 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.partitions)?;- self.dispatcher.release_batch(&batch_id);- emit_latest_processed_timestamp_metrics(&processed.partitions, &self.group_id);+ self.commit_offsets(&poll.partitions)?;+ emit_latest_processed_timestamp_metrics(&poll.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.partitions),+ batch_id: poll.poll_id.clone(),+ accepted: poll.accepted,+ duration_ms: poll.dispatched_at.elapsed().as_millis() as u64,+ partitions: debug_partition_offsets(&poll.partitions),});- histogram!("ingestion_consumer_batch_processing_duration_seconds")- .record(processed.elapsed.as_secs_f64());- counter!("ingestion_consumer_messages_processed_total")- .increment(processed.total_accepted as u64);+ counter!("ingestion_consumer_messages_processed_total").increment(poll.accepted as u64);counter!("ingestion_consumer_batches_processed_total").increment(1);self.handle.report_healthy();Ok(())}- async fn await_processed_batch(&self, batch: InFlightBatch) -> anyhow::Result<ProcessedBatch> {- let batch_id = batch.batch_id;- let processed = self.heartbeat_while(batch.handle).await??;- info!(batch_id = %batch_id, "Kafka batch processing completed");- Ok(processed)- }-- async fn heartbeat_while<F: Future>(&self, fut: F) -> F::Output {- tokio::pin!(fut);- let mut heartbeat = tokio::time::interval(Duration::from_secs(1));-- loop {- tokio::select! {- output = &mut fut => return output,- _ = heartbeat.tick() => self.handle.report_healthy(),- }- }- }-- /// Flush a completed batch's deferred groups (keys whose worker was- /// draining/dead), re-routing them to healthy workers and accumulating the- /// accepted count. Retries with backoff while a flush can't route (no healthy- /// worker yet). Called serialized, oldest-first, so a key's deferred- /// messages flush in Kafka order.- ///- /// `deferred_flush_timeout` bounds **stalls, not total time**: the deadline- /// resets whenever any of the batch's messages are accepted, so a large- /// backlog draining slowly under saturation keeps- /// going, and the batch only fails — exiting the process and replaying —- /// when flushing is truly wedged: nothing landed for a full timeout- /// (nothing routable, or a flapping worker re-deferring every send).- /// Failing the whole process for a mere slow drain amplified today's- /// saturation: each restart replayed all its partitions into an already- /// overloaded pool.- async fn flush_deferred(- &self,- batch_id: &str,- processed: &mut ProcessedBatch,- ) -> anyhow::Result<()> {- if self.dispatcher.has_unfinished_flush(batch_id) {- let mut stall_deadline = Instant::now() + self.deferred_flush_timeout;- while self.dispatcher.has_unfinished_flush(batch_id) {- if Instant::now() >= stall_deadline {- anyhow::bail!("deferred messages made no progress within the flush timeout");- }- let mut accepted_this_round = 0u32;- // Serialized on the consumer loop, oldest batch first, so- // begin_send order preserves the flush's key order.- let pending = self- .dispatcher- .flush_deferred_and_send(batch_id, |sub_batch| {- Self::begin_send(&self.transport, batch_id, sub_batch, true)- });- if pending.is_empty() {- // Nothing is routable right now (no healthy worker), so wait.- tokio::select! {- _ = self.handle.shutdown_recv() => {- anyhow::bail!("shutdown while flushing deferred messages");- }- _ = tokio::time::sleep(Duration::from_millis(200)) => {- self.handle.report_healthy();- }- }- } else {- accepted_this_round += self- .heartbeat_while(Self::scatter(&self.dispatcher, batch_id, pending, true))- .await?;- }- processed.total_accepted += accepted_this_round;- if accepted_this_round > 0 {- stall_deadline = Instant::now() + self.deferred_flush_timeout;- }- }- }- Ok(())- }-fn fail_batch_processing(&self, err: anyhow::Error) {error!(error = %err, "Batch processing failed");counter!("ingestion_consumer_batch_errors_total").increment(1);@@ -581,200 +546,6 @@ impl IngestionConsumer {.signal_failure(format!("Batch processing failed: {err:#}"));}- /// Establish a sub-batch's send order. Synchronous and non-blocking on- /// purpose: called under the dispatcher's lock on the consumer loop, where- /// send order is decided, so a key's sub-batches enter its worker's stream- /// in exactly that order.- fn begin_send(- transport: &GrpcTransport,- batch_id: &str,- sub_batch: SubBatch,- replay: bool,- ) -> PendingSubBatch {- let SubBatch {- worker,- messages,- routing_keys,- key_offsets,- } = sub_batch;- let message_count = messages.len();- let pending = transport.begin_send(&worker, batch_id, messages, replay);- PendingSubBatch {- worker,- routing_keys,- key_offsets,- message_count,- pending,- }- }-- /// Await a batch's pre-ordered sub-batch sends, gather results, and feed- /// passive health signals. Assignment and send ordering already happened- /// on the consumer loop (see `spawn_batch_processing`); offset commits- /// happen later, in Kafka batch order, in `complete_oldest_batch`.- #[allow(clippy::too_many_arguments)]- async fn process_collected_batch(- collected: CollectedBatch,- pending: Vec<PendingSubBatch>,- batch_size: usize,- batch_id: String,- dispatcher: Arc<Dispatcher>,- group_id: String,- max_batch_size: usize,- max_batch_bytes: usize,- ) -> anyhow::Result<ProcessedBatch> {- let start = Instant::now();-- counter!("ingestion_consumer_messages_received_total").increment(batch_size as u64);- gauge!("ingestion_consumer_batch_size").set(batch_size as f64);-- // Batch fill ratio (batch size / configured max) — matches Node.js- // `consumer_batch_utilization`. A useful scaling signal: sustained high- // utilization means batches are saturating and the consumer is demand-bound.- if max_batch_size > 0 {- gauge!("consumer_batch_utilization", "groupId" => group_id.clone())- .set(batch_size as f64 / max_batch_size as f64);- }-- // The same ratio against the byte bound. Reported separately because the- // two disagree on lanes whose events are large: a count utilization can- // sit far below 1.0 while batches are in fact full, simply because the- // byte bound (or the prefetch queue behind it) ends collection first.- // Reading only the count ratio there invites raising a cap that cannot- // be reached. Absent when the byte bound is disabled.- if max_batch_bytes > 0 {- gauge!("consumer_batch_utilization_bytes", "groupId" => group_id.clone())- .set(collected.stats.total_bytes as f64 / max_batch_bytes as f64);- }-- // Batch size distribution — matches Node.js `consumer_batch_size` histogram.- histogram!("consumer_batch_size").record(batch_size as f64);- 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, partition) in &collected.partitions {- let Some(max_lag) = partition.max_lag_ms else {- continue;- };- gauge!(- "ingestion_lag_ms",- "topic" => topic_partition.topic.clone(),- "partition" => topic_partition.partition.to_string(),- "groupId" => group_id.clone()- )- .set(max_lag as f64);- }-- // Per-message lag histogram — matches Node.js `ingestion_lag_ms_histogram`.- for (partition, lag_ms) in &collected.stats.message_lags_ms {- histogram!(- "ingestion_lag_ms_histogram",- "groupId" => group_id.clone(),- "partition" => partition.to_string()- )- .record(*lag_ms as f64);- }-- // Nothing to send and no deferred groups means no usable workers.- if pending.is_empty() && !dispatcher.batch_has_flush_activity(&batch_id) {- counter!("ingestion_consumer_no_healthy_workers_total").increment(1);- anyhow::bail!("No healthy workers available to route batch");- }-- let total_accepted = Self::scatter(&dispatcher, &batch_id, pending, false).await?;-- Ok(ProcessedBatch {- partitions: collected.partitions,- total_accepted,- batch_size: batch_size as u32,- elapsed: start.elapsed(),- })- }-- /// Await sub-batch sends in parallel and resolve each in the dispatcher.- /// On a send failure (the worker died mid-send, or its worker stream was fenced),- /// the failed messages are deferred — before the resolve, so the pin- /// isn't evicted — to be replayed in order. Returns the number of- /// messages accepted.- ///- /// `from_flush` is true when awaiting sub-batches produced by `flush_deferred`:- /// the resolve then clears one deferral per key, so a key stays deferring from- /// when it was first held until its flushed messages actually land (preventing- /// a newer batch from racing them).- async fn scatter(- dispatcher: &Arc<Dispatcher>,- batch_id: &str,- pending: Vec<PendingSubBatch>,- from_flush: bool,- ) -> anyhow::Result<u32> {- let mut handles = Vec::with_capacity(pending.len());- for sub_batch in pending {- let dispatcher = Arc::clone(dispatcher);- let PendingSubBatch {- worker,- routing_keys,- key_offsets,- message_count,- pending,- } = sub_batch;- let bid = batch_id.to_string();-- handles.push(tokio::spawn(async move {- match pending.wait().await {- Ok(accepted) => {- // Advance ACK high-water marks before the resolve, which- // may evict the keys' sentinel state.- dispatcher.on_sub_batch_acked(&key_offsets);- dispatcher.on_sub_batch_resolved(- &worker,- message_count,- &routing_keys,- from_flush,- false,- );- dispatcher.record_send_outcome(&worker, false);- accepted- }- Err(send_err) => {- // Re-defer the failed messages first, so the ref-count drop- // in `on_sub_batch_resolved` doesn't evict the pin while the- // key still has work to replay. On the flush path this pairs- // with the `clears_deferral` decrement in the resolve, so the- // outstanding count nets to unchanged (never dipping to zero)- // and the key keeps deferring across the retry.- // Backpressure (a busy worker) is transient, not a fault:- // re-route the work but do not count it against the- // worker's health, so passive health tracks real faults.- let SendError {- error,- messages,- fence_guard,- } = send_err;- let is_fault = !error.is_backpressure();- dispatcher.defer_failed(&bid, messages);- // Stashed: let the worker stream stop fencing new arrivals.- drop(fence_guard);- dispatcher.on_sub_batch_resolved(- &worker,- message_count,- &routing_keys,- from_flush,- true,- );- dispatcher.record_send_outcome(&worker, is_fault);- 0- }- }- }));- }-- let mut accepted = 0u32;- for handle in handles {- accepted += handle.await?;- }- Ok(accepted)- }-/// Collect messages from Kafka until the first of `batch_size` messages,/// `batch_size_bytes` of payload (when enabled), or `batch_timeout`.///@@ -914,7 +685,7 @@ impl IngestionConsumer {}Ok(CollectedBatch {- groups: accumulator.into_groups(),+ accumulator,partitions,stats,})@@ -966,6 +737,68 @@ impl IngestionConsumer {}}+/// Emit the per-poll parity metrics (received counts, batch sizes,+/// utilization, and lag) right after collection, before the poll is+/// submitted.+fn emit_poll_stats(+ stats: &BatchStats,+ partitions: &HashMap<TopicPartition, PartitionDeliveries>,+ batch_size: usize,+ group_id: &str,+ max_batch_size: usize,+ max_batch_bytes: usize,+) {+ counter!("ingestion_consumer_messages_received_total").increment(batch_size as u64);+ gauge!("ingestion_consumer_batch_size").set(batch_size as f64);++ // Batch fill ratio (batch size / configured max) — matches Node.js+ // `consumer_batch_utilization`. A useful scaling signal: sustained high+ // utilization means batches are saturating and the consumer is demand-bound.+ if max_batch_size > 0 {+ gauge!("consumer_batch_utilization", "groupId" => group_id.to_string())+ .set(batch_size as f64 / max_batch_size as f64);+ }++ // The same ratio against the byte bound. Reported separately because the+ // two disagree on lanes whose events are large: a count utilization can+ // sit far below 1.0 while batches are in fact full, simply because the+ // byte bound (or the prefetch queue behind it) ends collection first.+ // Reading only the count ratio there invites raising a cap that cannot+ // be reached. Absent when the byte bound is disabled.+ if max_batch_bytes > 0 {+ gauge!("consumer_batch_utilization_bytes", "groupId" => group_id.to_string())+ .set(stats.total_bytes as f64 / max_batch_bytes as f64);+ }++ // Batch size distribution — matches Node.js `consumer_batch_size` histogram.+ histogram!("consumer_batch_size").record(batch_size as f64);+ histogram!("consumer_batch_size_kb").record(stats.total_bytes as f64 / 1024.0);++ // Per-partition ingestion lag gauge — matches Node.js `ingestion_lag_ms`.+ for (topic_partition, partition) in partitions {+ let Some(max_lag) = partition.max_lag_ms else {+ continue;+ };+ gauge!(+ "ingestion_lag_ms",+ "topic" => topic_partition.topic.clone(),+ "partition" => topic_partition.partition.to_string(),+ "groupId" => group_id.to_string()+ )+ .set(max_lag as f64);+ }++ // Per-message lag histogram — matches Node.js `ingestion_lag_ms_histogram`.+ for (partition, lag_ms) in &stats.message_lags_ms {+ histogram!(+ "ingestion_lag_ms_histogram",+ "groupId" => group_id.to_string(),+ "partition" => partition.to_string()+ )+ .record(*lag_ms as f64);+ }+}+/// Per-partition max offset + observed lag for the debug UI's batch events.fn debug_partition_offsets(partitions: &HashMap<TopicPartition, PartitionDeliveries>,@@ -1069,15 +902,6 @@ fn message_charge(message: &impl Message) -> Charge {}}-fn make_batch_id() -> String {- let ts = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default()- .as_millis();- let rand: u32 = rand::random();- format!("{ts:x}-{rand:08x}")-}-fn current_time_ms() -> i64 {std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)@@ -1113,119 +937,78 @@ fn emit_latest_processed_timestamp_metrics(#[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,+ use common_kafka_consumer::Offset as MessageOffset;++ fn poll(epoch: u64, partition: i32, first: i64, last: i64, count: u32) -> InFlightPoll {+ let mut partitions = HashMap::new();+ partitions.insert(+ TopicPartition::new("test", partition),+ PartitionDeliveries {+ span: OffsetSpan { first, last },+ generation: 0,+ generations_version_seen: 0,+ charges: Vec::new(),+ latest_kafka_ts: 0,+ max_lag_ms: None,},- kafka_ts: offset,- lag_ms: Some(offset),+ );+ InFlightPoll {+ poll_id: format!("poll-{epoch}-{partition}-{first}"),+ assignment_epoch: epoch,+ partitions,+ message_count: count,+ covered: 0,+ accepted: 0,+ dispatched_at: Instant::now(),}}- fn charged_offsets(deliveries: &PartitionDeliveries) -> Vec<i64> {- deliveries- .charges- .iter()- .map(|(offset, _)| offset.0)- .collect()+ fn completion(epoch: u64, partition: i32, offsets: &[i64], accepted: u32) -> GroupCompletion {+ GroupCompletion {+ partition: Partition(partition),+ assignment_epoch: epoch,+ offsets: offsets.iter().map(|o| MessageOffset(*o)).collect(),+ accepted,+ }}#[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),- );+ fn apply_completion_credits_the_poll_holding_the_offsets() {+ let mut in_flight = VecDeque::from([poll(1, 0, 0, 3, 4), poll(1, 0, 4, 7, 4)]);- // 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 });- }+ apply_completion(&mut in_flight, completion(1, 0, &[4, 6], 2));- #[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!(in_flight[0].covered, 0);+ assert_eq!(in_flight[1].covered, 2);+ assert_eq!(in_flight[1].accepted, 2);+ assert!(!in_flight[1].is_complete());- assert_eq!(charged_offsets(&deliveries), vec![10, 11]);- assert_eq!(deliveries.generation, 3);+ apply_completion(&mut in_flight, completion(1, 0, &[5, 7], 2));+ assert!(in_flight[1].is_complete());}#[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));- }+ fn apply_completion_requires_a_matching_epoch() {+ // The same offsets exist in two polls when a partition was revoked,+ // reassigned, and replayed. The epoch keeps each incarnation's+ // completions in its own poll.+ let mut in_flight = VecDeque::from([poll(1, 0, 0, 3, 4), poll(2, 0, 0, 3, 4)]);- #[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),- );+ apply_completion(&mut in_flight, completion(2, 0, &[0, 1, 2, 3], 4));- let charge = message_charge(&message);- assert_eq!(charge.events, 1);- assert_eq!(charge.bytes, 10 + 3 + (2 + 3) + 1);+ assert_eq!(in_flight[0].covered, 0);+ assert_eq!(in_flight[1].covered, 4);}#[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,- );+ fn apply_completion_discards_a_completion_matching_no_poll() {+ let mut in_flight = VecDeque::from([poll(1, 0, 0, 3, 4)]);++ // Wrong partition, then wrong epoch: neither may be credited.+ apply_completion(&mut in_flight, completion(1, 2, &[1], 1));+ apply_completion(&mut in_flight, completion(9, 0, &[1], 1));- let charge = message_charge(&message);- assert_eq!(charge.events, 1);- assert_eq!(charge.bytes, 0);+ assert_eq!(in_flight[0].covered, 0);+ assert_eq!(in_flight[0].accepted, 0);}}diff --git a/rust/ingestion-consumer/src/grpc_transport.rs b/rust/ingestion-consumer/src/grpc_transport.rsindex 8f396c242560..d3c4be0b147c 100644--- a/rust/ingestion-consumer/src/grpc_transport.rs+++ b/rust/ingestion-consumer/src/grpc_transport.rs@@ -35,10 +35,10 @@//! resolve.use std::collections::VecDeque;-use std::sync::atomic::{AtomicU64, Ordering};use std::sync::Arc;use std::time::Duration;+use common_kafka_consumer::AssignmentEpoch;use dashmap::DashMap;use ingestion_worker_proto::ingestion::worker::v1::worker_ingest_client::WorkerIngestClient;use ingestion_worker_proto::ingestion::worker::v1::{@@ -161,7 +161,7 @@ pub struct GrpcTransport {ack_timeout: Duration,/// Bumped on Kafka partition assignment; stamped on every sub-batch so/// the worker sentinel rebaselines across rebalances.- assignment_epoch: Arc<AtomicU64>,+ assignment_epoch: AssignmentEpoch,/// Readiness probing stays HTTP: workers always serve `/_ready`.probe_client: reqwest::Client,/// Cap on one frame's estimated size. A sub-batch over it is sent as@@ -180,7 +180,9 @@ impl GrpcTransport {max_unacked,ack_timeout,max_body_bytes: DEFAULT_MAX_BODY_BYTES,- assignment_epoch: Arc::new(AtomicU64::new(1)),+ // A fresh epoch for standalone construction; production wiring+ // injects the shared one via `set_assignment_epoch`.+ assignment_epoch: AssignmentEpoch::new(),probe_client: reqwest::Client::builder().timeout(readiness::PROBE_TIMEOUT).build()@@ -188,9 +190,16 @@ impl GrpcTransport {}}- /// Shared epoch counter; the consumer's rebalance context bumps it.- pub fn assignment_epoch(&self) -> Arc<AtomicU64> {- Arc::clone(&self.assignment_epoch)+ /// Share the process-wide assignment epoch. Call before the transport is+ /// shared, so every stamped sub-batch carries the same generation the+ /// rebalance context bumps.+ pub fn set_assignment_epoch(&mut self, epoch: AssignmentEpoch) {+ self.assignment_epoch = epoch;+ }++ /// The assignment epoch this transport stamps on sub-batches.+ pub fn assignment_epoch(&self) -> AssignmentEpoch {+ self.assignment_epoch.clone()}/// Override the per-frame size cap. Call before the transport is shared.@@ -268,7 +277,7 @@ impl GrpcTransport {consumer_id: self.consumer_id.clone(),max_unacked: self.max_unacked,ack_timeout: self.ack_timeout,- assignment_epoch: Arc::clone(&self.assignment_epoch),+ assignment_epoch: self.assignment_epoch.clone(),};tokio::spawn(async move { runner.run(rx).await });WorkerStream { tx }@@ -328,7 +337,7 @@ struct WorkerStreamRunner {consumer_id: String,max_unacked: usize,ack_timeout: Duration,- assignment_epoch: Arc<AtomicU64>,+ assignment_epoch: AssignmentEpoch,}impl WorkerStreamRunner {@@ -533,7 +542,7 @@ impl WorkerStreamRunner {batch_id: item.batch_id.clone(),messages: item.messages.iter().map(to_proto_message).collect(),replay: item.replay,- assignment_epoch: self.assignment_epoch.load(Ordering::Relaxed),+ assignment_epoch: self.assignment_epoch.current(),})),};// tonic gzips the frame after this point, so only the raw size is observable here.diff --git a/rust/ingestion-consumer/src/lib.rs b/rust/ingestion-consumer/src/lib.rsindex 2ce932bf0fcd..c531b51ccede 100644--- a/rust/ingestion-consumer/src/lib.rs+++ b/rust/ingestion-consumer/src/lib.rs@@ -1,4 +1,5 @@pub mod aperture;+pub mod batcher;pub mod config;pub mod consumer;pub mod debug_recorder;diff --git a/rust/ingestion-consumer/src/main.rs b/rust/ingestion-consumer/src/main.rsindex 32b0f384ddaa..cd143bc149cc 100644--- a/rust/ingestion-consumer/src/main.rs+++ b/rust/ingestion-consumer/src/main.rs@@ -5,6 +5,7 @@ use anyhow::{Context, Result};use axum::response::IntoResponse;use axum::routing::get;use axum::Router;+use common_kafka_consumer::AssignmentEpoch;use envconfig::Envconfig;use futures::future::ready;use futures::StreamExt;@@ -18,6 +19,7 @@ use tracing_subscriber::layer::SubscriberExt;use tracing_subscriber::util::SubscriberInitExt;use tracing_subscriber::{EnvFilter, Layer};+use ingestion_consumer::batcher::Batcher;use ingestion_consumer::config::Config;use ingestion_consumer::consumer::IngestionConsumer;use ingestion_consumer::debug_recorder::{DebugLoad, DebugRecorder, DebugState, WorkerStatus};@@ -239,12 +241,19 @@ async fn async_main(config: Config) -> Result<()> {} else {GrpcPort::Fixed(config.ingestion_worker_grpc_port)};+ // The process-wide assignment epoch: bumped by the consumer's rebalance+ // context, stamped by the transport on wire sub-batches and by the+ // batcher on group completions. Created here so one counter serves all+ // three.+ let assignment_epoch = AssignmentEpoch::new();+let mut transport = GrpcTransport::new(grpc_port,config.ingestion_worker_concurrent_batches,Duration::from_millis(config.ingestion_worker_stream_ack_timeout_ms),);transport.set_max_body_bytes(config.transport_max_body_bytes);+ transport.set_assignment_epoch(assignment_epoch);let transport = Arc::new(transport);// Select the worker discovery provider and start it (static applies the@@ -480,9 +489,19 @@ async fn async_main(config: Config) -> Result<()> {}}+ // The batcher owns the dispatch orchestration; the consumer loop only+ // submits polls to it and reads group completions back.+ let (batcher, batcher_outputs) = Batcher::new(+ Arc::clone(&dispatcher),+ Arc::clone(&transport),+ consumer_handle.clone(),+ Duration::from_millis(config.consumer_deferred_flush_timeout_ms),+ );+let consumer = IngestionConsumer::new(&config,- Arc::clone(&dispatcher),+ batcher,+ batcher_outputs,transport,consumer_handle,debug_recorder,diff --git a/rust/ingestion-consumer/src/order_sentinel.rs b/rust/ingestion-consumer/src/order_sentinel.rsindex 38c82ed8c16d..b7f7a2b8d4f3 100644--- a/rust/ingestion-consumer/src/order_sentinel.rs+++ b/rust/ingestion-consumer/src/order_sentinel.rs@@ -41,7 +41,7 @@//! The sentinels are pure observers: they never influence routing or commits.use std::collections::HashMap;-use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex};use std::time::{SystemTime, UNIX_EPOCH};@@ -52,7 +52,7 @@ use tracing::{info, warn};use crate::ledger_shadow::set_held_gauges;use crate::types::SerializedKafkaMessage;-use common_kafka_consumer::{Held, TopicOffsetLedger, TopicPartition};+use common_kafka_consumer::{AssignmentEpoch, Held, TopicOffsetLedger, TopicPartition};/// The first and last Kafka offsets a batch holds for one topic-partition.#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -578,7 +578,7 @@ pub struct SentinelContext {/// 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>>,+ assignment_epoch: Option<AssignmentEpoch>,}impl SentinelContext {@@ -595,9 +595,9 @@ impl SentinelContext {}}- /// Wire the gRPC transport's assignment-epoch counter. Call before the- /// context is handed to the Kafka consumer.- pub fn set_assignment_epoch(&mut self, epoch: Arc<AtomicU64>) {+ /// Wire the process-wide assignment epoch. Call before the context is+ /// handed to the Kafka consumer.+ pub fn set_assignment_epoch(&mut self, epoch: AssignmentEpoch) {self.assignment_epoch = Some(epoch);}@@ -672,7 +672,7 @@ impl ConsumerContext for SentinelContext {// 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);+ epoch.bump();}}}diff --git a/rust/ingestion-consumer/tests/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rsindex 3685cc74099c..589782518fcf 100644--- a/rust/ingestion-consumer/tests/e2e_integration_test.rs+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs@@ -3049,3 +3049,75 @@ async fn nacking_worker_fences_worker_stream_and_reroutes_in_order() {harness.stop().await;}++/// One routing key arriving on two partitions: a partition-count change+/// leaves a key's backlog on its old partition while new messages land on the+/// new one. The dispatcher merges such a key into one sub-batch (the pin+/// table is partition-blind), so the batcher must split the completion back+/// per partition — mis-attributed coverage would leave the poll uncommitted+/// and wedge the consumer. Two waves prove commits keep flowing: with+/// max_in_flight = 1, the second wave can only deliver after the first wave's+/// polls completed.+#[tokio::test]+async fn same_key_across_partitions_completes_and_commits() {+ let topic = format!("e2e-cross-partition-key-{}", Uuid::new_v4());+ let harness = Harness::start(+ &topic,+ 2,+ 1,+ 1,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;+ let producer = make_producer();++ for seq in 0..3usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ }+ for seq in 3..6usize {+ produce(&producer, &topic, 1, "tok", "user-1", seq).await;+ }+ harness.wait_for(6, Duration::from_secs(15)).await;++ for seq in 6..9usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ }+ for seq in 9..12usize {+ produce(&producer, &topic, 1, "tok", "user-1", seq).await;+ }+ harness.wait_for(12, Duration::from_secs(15)).await;++ // Everything delivered exactly once; cross-partition interleaving is+ // free, but each partition's own sequence must arrive in order.+ let seqs = harness.workers[0].seqs_for("user-1");+ let mut sorted = seqs.clone();+ sorted.sort_unstable();+ assert_eq!(+ sorted,+ (0..12).collect::<Vec<_>>(),+ "every message must land exactly once; got {seqs:?}"+ );+ let partition_0: Vec<usize> = seqs+ .iter()+ .copied()+ .filter(|s| *s < 3 || (6..9).contains(s))+ .collect();+ let partition_1: Vec<usize> = seqs+ .iter()+ .copied()+ .filter(|s| (3..6).contains(s) || *s >= 9)+ .collect();+ assert_eq!(+ partition_0,+ vec![0, 1, 2, 6, 7, 8],+ "partition 0 must keep offset order"+ );+ assert_eq!(+ partition_1,+ vec![3, 4, 5, 9, 10, 11],+ "partition 1 must keep offset order"+ );++ harness.stop().await;+}