Skip to content

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

feat(ingestion-consumer): run the key-table scheduler on a batcher state machine (#112509)

Paweł Ledwońe7bc2e140996
diff --git a/rust/ingestion-consumer/Cargo.toml b/rust/ingestion-consumer/Cargo.toml
index 80493d7b95c5..20230b74e5d7 100644
--- a/rust/ingestion-consumer/Cargo.toml
+++ b/rust/ingestion-consumer/Cargo.toml
@@ -40,4 +40,5 @@ tracing-subscriber = { workspace = true, features = ["env-filter", "json"] }
[dev-dependencies]
rstest = "0.26"
+tokio = { workspace = true, features = ["test-util"] }
uuid = { workspace = true }
diff --git a/rust/ingestion-consumer/README.md b/rust/ingestion-consumer/README.md
index 7b3ef3bb4a50..53c5de1723e0 100644
--- a/rust/ingestion-consumer/README.md
+++ b/rust/ingestion-consumer/README.md
@@ -42,6 +42,33 @@ The ledger emits its own metrics, so any consumer built on the crate reports the
`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.
+## Schedulers
+
+`INGESTION_SCHEDULER` selects how runs are ordered and placed on workers.
+
+- `pin_stash` (default) pins each key to a worker and stashes a batch's groups while a pinned worker drains. It is the fallback.
+- `key_table` runs the batcher state machine in `src/batcher/`.
+
+Under `key_table`:
+
+- One task owns the state machine and applies polls, worker responses, revokes and retry wakeups one at a time.
+- Each key has a FIFO queue, and at most one request per key is in flight, which preserves per-key order.
+- Each claimed key run is a request of its own. A run never mixes assignment epochs or fresh and replayed messages.
+- A request is placed on a worker when it is sent, against the load at that moment. Each worker takes at most `INGESTION_WORKER_CONCURRENT_BATCHES` requests at a time.
+- A failed send returns its messages to the front of their keys' queues. They go out again as replay after the retry delay.
+- A revoke drops the pending messages of the revoked partitions, because the new owner replays them.
+- Pending work with nothing in flight and nothing accepted for `CONSUMER_DEFERRED_FLUSH_TIMEOUT_MS` fails the consumer, which restarts and replays.
+
+| Setting | Default | Effect under `key_table` |
+| --- | --- | --- |
+| `INGESTION_PARKED_RETRY_INTERVAL_MS` | `200` | The delay before a failed send retries, and how often a request with no routable worker tries again. |
+
+Metrics:
+
+- `ingestion_consumer_request_events` and `ingestion_consumer_request_bytes` record each request as sent.
+- `ingestion_consumer_request_queue_wait_seconds{kind=fresh|replay}` records how long a request's oldest message waited.
+- The `ingestion_consumer_batcher_*` gauges report keys, queued messages and bytes, claimed and waiting keys, unplaced work, and in-flight requests.
+
## Debug API
Set `DEBUG_API_ENABLED=true` **and** `DEBUG_API_SECRET` to mount a real-time debug API on the health server (default `:3301`), for dev and incident debugging; off by default.
diff --git a/rust/ingestion-consumer/src/batcher/driver.rs b/rust/ingestion-consumer/src/batcher/driver.rs
new file mode 100644
index 000000000000..598b24b9acfc
--- /dev/null
+++ b/rust/ingestion-consumer/src/batcher/driver.rs
@@ -0,0 +1,749 @@
+//! Runs the batcher state machine on one task and performs its effects.
+
+use std::collections::HashSet;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::Instant;
+
+use common_kafka_consumer::{AssignmentEpoch, GroupCompletion};
+use futures::future::{BoxFuture, FutureExt};
+use futures::stream::{FuturesUnordered, StreamExt};
+use metrics::{counter, histogram};
+use tokio::sync::mpsc;
+use tokio::task::JoinHandle;
+use tracing::error;
+
+use super::in_flight::RequestId;
+use super::key_queues::KeyRun;
+use super::state_machine::{BatcherStateMachine, Effects, FailureCause, SendRequest};
+use super::worker_pool::WorkerPoolSource;
+use super::{make_batch_id, BatcherOutputs};
+use crate::grpc_transport::GrpcTransport;
+use crate::order_sentinel::{KeyOrderSentinel, SendKind, SentinelBatch};
+use crate::transport::SendError;
+use crate::types::{Accumulator, SerializedKafkaMessage};
+use crate::worker_registry::WorkerId;
+
+pub(super) struct StateMachineDriver {
+ inputs: mpsc::UnboundedSender<Input>,
+ assignment_epoch: AssignmentEpoch,
+ key_sentinel: Arc<KeyOrderSentinel>,
+ load: Arc<Load>,
+ task: JoinHandle<()>,
+}
+
+enum Input {
+ Groups {
+ assignment_epoch: u64,
+ runs: Vec<KeyRun>,
+ },
+ PartitionsRevoked(Vec<(String, i32)>),
+ Shutdown,
+}
+
+#[derive(Debug, Default)]
+pub(super) struct Load {
+ pub pending_messages: AtomicUsize,
+ pub in_flight_messages: AtomicUsize,
+ pub busy_workers: Mutex<HashSet<WorkerId>>,
+}
+
+pub(super) struct RevokeSender(mpsc::UnboundedSender<Input>);
+
+pub(super) trait RequestSender: Send + Sync + 'static {
+ fn assignment_epoch(&self) -> AssignmentEpoch;
+
+ fn send(
+ &self,
+ worker: &WorkerId,
+ messages: Vec<SerializedKafkaMessage>,
+ replay: bool,
+ ) -> BoxFuture<'static, Result<u32, SendError>>;
+}
+
+pub(super) trait Workers: Send + 'static {
+ fn candidates(&self) -> Vec<WorkerId>;
+
+ fn record_outcome(&self, worker: &WorkerId, fault: bool);
+
+ /// Completes the worker's drain if it is draining.
+ fn idle(&self, worker: &WorkerId);
+}
+
+impl RequestSender for GrpcTransport {
+ fn assignment_epoch(&self) -> AssignmentEpoch {
+ GrpcTransport::assignment_epoch(self)
+ }
+
+ fn send(
+ &self,
+ worker: &WorkerId,
+ messages: Vec<SerializedKafkaMessage>,
+ replay: bool,
+ ) -> BoxFuture<'static, Result<u32, SendError>> {
+ self.begin_send(worker, &make_batch_id(), messages, replay)
+ .wait()
+ .boxed()
+ }
+}
+
+impl Workers for WorkerPoolSource {
+ fn candidates(&self) -> Vec<WorkerId> {
+ WorkerPoolSource::candidates(self)
+ }
+
+ fn record_outcome(&self, worker: &WorkerId, fault: bool) {
+ self.registry().record_outcome(worker, fault);
+ }
+
+ fn idle(&self, worker: &WorkerId) {
+ let registry = self.registry();
+ if registry.is_draining(worker) {
+ registry.complete_drain(worker);
+ }
+ }
+}
+
+type Response = BoxFuture<'static, (RequestId, Result<u32, SendError>)>;
+
+struct BatcherTask<S, W> {
+ inputs: mpsc::UnboundedReceiver<Input>,
+ responses: FuturesUnordered<Response>,
+ wakeup: Option<Instant>,
+ workers: W,
+ sender: Arc<S>,
+ key_sentinel: Arc<KeyOrderSentinel>,
+ completions: mpsc::UnboundedSender<GroupCompletion>,
+ errors: mpsc::UnboundedSender<String>,
+ load: Arc<Load>,
+}
+
+enum Event {
+ Input(Input),
+ Response(RequestId, Result<u32, SendError>),
+ Wakeup,
+}
+
+impl StateMachineDriver {
+ pub(super) fn new<S: RequestSender, W: Workers>(
+ state: BatcherStateMachine,
+ workers: W,
+ sender: Arc<S>,
+ ) -> (Self, BatcherOutputs) {
+ let (inputs_tx, inputs_rx) = mpsc::unbounded_channel();
+ let (completions_tx, completions_rx) = mpsc::unbounded_channel();
+ let (errors_tx, errors_rx) = mpsc::unbounded_channel();
+ let load = Arc::new(Load::default());
+ let key_sentinel = Arc::new(KeyOrderSentinel::new());
+ let assignment_epoch = sender.assignment_epoch();
+ let task = BatcherTask {
+ inputs: inputs_rx,
+ responses: FuturesUnordered::new(),
+ wakeup: None,
+ workers,
+ sender,
+ key_sentinel: Arc::clone(&key_sentinel),
+ completions: completions_tx,
+ errors: errors_tx,
+ load: Arc::clone(&load),
+ };
+ let task = tokio::spawn(task.run(state));
+ (
+ Self {
+ inputs: inputs_tx,
+ assignment_epoch,
+ key_sentinel,
+ load,
+ task,
+ },
+ BatcherOutputs {
+ completions: completions_rx,
+ errors: errors_rx,
+ },
+ )
+ }
+
+ pub(super) fn key_order_sentinel(&self) -> Arc<KeyOrderSentinel> {
+ Arc::clone(&self.key_sentinel)
+ }
+
+ pub(super) fn load(&self) -> Arc<Load> {
+ Arc::clone(&self.load)
+ }
+
+ pub(super) fn revoke_sender(&self) -> RevokeSender {
+ RevokeSender(self.inputs.clone())
+ }
+
+ pub(super) fn submit(&self, accumulator: Accumulator) -> u64 {
+ let assignment_epoch = self.assignment_epoch.current();
+ let runs = KeyRun::from_groups(accumulator.into_groups());
+ let unkeyed: usize = runs
+ .iter()
+ .filter(|run| run.messages.first().is_some_and(|m| m.key.is_none()))
+ .map(|run| run.messages.len())
+ .sum();
+ if unkeyed > 0 {
+ counter!("ingestion_consumer_dispatcher_unkeyed_messages_total")
+ .increment(unkeyed as u64);
+ }
+ histogram!("ingestion_consumer_routing_keys_per_batch").record(runs.len() as f64);
+ self.send(Input::Groups {
+ assignment_epoch,
+ runs,
+ });
+ assignment_epoch
+ }
+
+ pub(super) fn begin_shutdown(&self) {
+ self.send(Input::Shutdown);
+ }
+
+ fn send(&self, input: Input) {
+ if self.inputs.send(input).is_err() {
+ error!("Batcher task is gone");
+ }
+ }
+}
+
+impl Drop for StateMachineDriver {
+ fn drop(&mut self) {
+ self.task.abort();
+ }
+}
+
+impl RevokeSender {
+ /// Called from the rebalance callback inside the consumer loop's Kafka
+ /// poll, so it queues the revoke rather than waiting for it. The revoke
+ /// lands between the polls submitted before and after the rebalance.
+ pub(super) fn purge_revoked(&self, partitions: &[(String, i32)]) {
+ let _ = self.0.send(Input::PartitionsRevoked(partitions.to_vec()));
+ }
+}
+
+impl<S: RequestSender, W: Workers> BatcherTask<S, W> {
+ async fn run(mut self, mut state: BatcherStateMachine) {
+ loop {
+ let wakeup = self.wakeup;
+ let event = tokio::select! {
+ // Inputs first, so a revoke applies before a response ready at
+ // the same time can send a revoked key.
+ biased;
+ input = self.inputs.recv() => match input {
+ Some(input) => Event::Input(input),
+ None => return,
+ },
+ Some((request, result)) = self.responses.next(), if !self.responses.is_empty() => {
+ Event::Response(request, result)
+ }
+ _ = sleep_until(wakeup), if wakeup.is_some() => Event::Wakeup,
+ };
+ state = self.handle(state, event);
+ }
+ }
+
+ fn handle(&mut self, state: BatcherStateMachine, event: Event) -> BatcherStateMachine {
+ // Read through tokio, so tests on paused time control the clock.
+ let now = tokio::time::Instant::now().into_std();
+ let mut assigned = false;
+ let (state, effects) = match event {
+ Event::Input(Input::Groups {
+ assignment_epoch,
+ runs,
+ }) => {
+ assigned = true;
+ state.on_groups(now, &self.workers.candidates(), assignment_epoch, runs)
+ }
+ Event::Input(Input::PartitionsRevoked(partitions)) => {
+ // Cleared in order with the sends, so no revoked message is
+ // noted as sent after the revoke.
+ self.key_sentinel.clear();
+ state.on_partitions_revoked(now, &partitions)
+ }
+ Event::Input(Input::Shutdown) => state.on_shutdown(now, &self.workers.candidates()),
+ Event::Response(request, Ok(accepted)) => {
+ state.on_request_succeeded(now, &self.workers.candidates(), request, accepted)
+ }
+ Event::Response(request, Err(failure)) => {
+ // Backpressure is transient, not a worker fault.
+ let cause = if failure.error.is_backpressure() {
+ FailureCause::Busy
+ } else {
+ FailureCause::Fault
+ };
+ let requeued = state.on_request_failed(
+ now,
+ &self.workers.candidates(),
+ request,
+ cause,
+ failure.messages,
+ );
+ // The worker stream takes no new send until the failed
+ // messages are requeued. Released before this action's
+ // sends, which can go to the same stream.
+ drop(failure.fence_guard);
+ requeued
+ }
+ Event::Wakeup => state.on_wakeup(now, &self.workers.candidates()),
+ };
+ self.perform(&state, effects);
+ if assigned {
+ histogram!("ingestion_consumer_assign_duration_seconds")
+ .record(now.elapsed().as_secs_f64());
+ }
+ state
+ }
+
+ fn perform(&mut self, state: &BatcherStateMachine, effects: Effects) {
+ let Effects {
+ sends,
+ completions,
+ key_acks,
+ evicted_keys,
+ worker_outcomes,
+ idle_workers,
+ busy_workers,
+ fatal,
+ next_wakeup,
+ } = effects;
+ let key_sentinel = Arc::clone(&self.key_sentinel);
+ let mut sentinel = key_sentinel.batch();
+ for ack in &key_acks {
+ sentinel.note_acked(&ack.routing_key, ack.max_offset);
+ }
+ for key in &evicted_keys {
+ sentinel.evict(key);
+ }
+ for send in sends {
+ self.begin(send, &mut sentinel);
+ }
+ drop(sentinel);
+
+ // A worker can go idle and then busy in one action, never the reverse.
+ if !idle_workers.is_empty() || !busy_workers.is_empty() {
+ let mut busy = self.load.busy_workers.lock().unwrap();
+ for worker in &idle_workers {
+ busy.remove(worker);
+ }
+ busy.extend(busy_workers);
+ }
+
+ for outcome in worker_outcomes {
+ self.workers.record_outcome(&outcome.worker, outcome.fault);
+ }
+ for worker in idle_workers {
+ self.workers.idle(&worker);
+ }
+ for completion in completions {
+ counter!("ingestion_consumer_group_completions_total").increment(1);
+ counter!("ingestion_consumer_group_completion_accepted_messages_total")
+ .increment(completion.accepted as u64);
+ let _ = self.completions.send(completion);
+ }
+ if let Some(reason) = fatal {
+ error!(error = %reason, "Batcher failure");
+ if self.errors.send(reason).is_err() {
+ error!("Batcher error channel closed; consumer is gone");
+ }
+ }
+ self.wakeup = next_wakeup;
+ self.load
+ .pending_messages
+ .store(state.pending_messages(), Ordering::Relaxed);
+ self.load
+ .in_flight_messages
+ .store(state.in_flight_messages(), Ordering::Relaxed);
+ }
+
+ fn begin(&mut self, send: SendRequest, sentinel: &mut SentinelBatch<'_>) {
+ let kind = if send.class.replay {
+ SendKind::Resend
+ } else {
+ SendKind::Fresh
+ };
+ let mut messages = Vec::new();
+ for run in send.runs {
+ sentinel.note_sent(&run.routing_key, &run.messages, kind);
+ messages.extend(run.messages);
+ }
+ let response = self.sender.send(&send.worker, messages, send.class.replay);
+ let request = send.request;
+ self.responses
+ .push(async move { (request, response.await) }.boxed());
+ }
+}
+
+async fn sleep_until(wakeup: Option<Instant>) {
+ match wakeup {
+ Some(at) => tokio::time::sleep_until(tokio::time::Instant::from_std(at)).await,
+ None => std::future::pending().await,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::time::Duration;
+
+ use tokio::sync::oneshot;
+
+ use super::*;
+ use crate::batcher::retry_policy::RetryPolicy;
+ use crate::batcher::test_support::{message, offsets};
+ use crate::batcher::worker_assigner::WorkerAssigner;
+ use crate::routing::{Router, RoutingStrategy};
+ use crate::transport::{FenceGuard, TransportError};
+
+ const FAULT_DELAY: Duration = Duration::from_millis(200);
+ const BUSY_DELAY: Duration = Duration::from_millis(20);
+ const NO_WORKER_DELAY: Duration = Duration::from_millis(100);
+ const STALL: Duration = Duration::from_secs(60);
+
+ struct Sent {
+ worker: WorkerId,
+ offsets: Vec<i64>,
+ replay: bool,
+ fence_released: Option<bool>,
+ reply: oneshot::Sender<Result<u32, SendError>>,
+ }
+
+ struct FakeSender {
+ assignment_epoch: AssignmentEpoch,
+ sent: Mutex<Vec<Sent>>,
+ fence: Mutex<Option<mpsc::UnboundedReceiver<()>>>,
+ }
+
+ impl RequestSender for FakeSender {
+ fn assignment_epoch(&self) -> AssignmentEpoch {
+ self.assignment_epoch.clone()
+ }
+
+ fn send(
+ &self,
+ worker: &WorkerId,
+ messages: Vec<SerializedKafkaMessage>,
+ replay: bool,
+ ) -> BoxFuture<'static, Result<u32, SendError>> {
+ let fence_released = self
+ .fence
+ .lock()
+ .unwrap()
+ .as_mut()
+ .map(|released| released.try_recv().is_ok());
+ let (reply, response) = oneshot::channel();
+ self.sent.lock().unwrap().push(Sent {
+ worker: worker.clone(),
+ offsets: offsets(&messages),
+ replay,
+ fence_released,
+ reply,
+ });
+ async move { response.await.expect("the test replies to every send") }.boxed()
+ }
+ }
+
+ #[derive(Default)]
+ struct WorkersState {
+ candidates: Vec<WorkerId>,
+ outcomes: Vec<(WorkerId, bool)>,
+ idle: Vec<WorkerId>,
+ }
+
+ #[derive(Clone, Default)]
+ struct FakeWorkers(Arc<Mutex<WorkersState>>);
+
+ impl Workers for FakeWorkers {
+ fn candidates(&self) -> Vec<WorkerId> {
+ self.0.lock().unwrap().candidates.clone()
+ }
+
+ fn record_outcome(&self, worker: &WorkerId, fault: bool) {
+ self.0
+ .lock()
+ .unwrap()
+ .outcomes
+ .push((worker.clone(), fault));
+ }
+
+ fn idle(&self, worker: &WorkerId) {
+ self.0.lock().unwrap().idle.push(worker.clone());
+ }
+ }
+
+ struct Harness {
+ driver: StateMachineDriver,
+ outputs: BatcherOutputs,
+ sender: Arc<FakeSender>,
+ workers: FakeWorkers,
+ }
+
+ impl Harness {
+ fn new(workers: &[&str], max_requests_per_worker: usize) -> Self {
+ let assigner = WorkerAssigner::new(
+ Router::new(RoutingStrategy::BinPack),
+ max_requests_per_worker,
+ )
+ .expect("valid request cap");
+ let retry = RetryPolicy::new(FAULT_DELAY, BUSY_DELAY, NO_WORKER_DELAY)
+ .expect("valid retry policy");
+ let state = BatcherStateMachine::new(
+ assigner,
+ retry,
+ STALL,
+ tokio::time::Instant::now().into_std(),
+ )
+ .expect("valid stall timeout");
+ let fake_workers = FakeWorkers::default();
+ fake_workers.set_candidates(workers);
+ let sender = Arc::new(FakeSender {
+ assignment_epoch: AssignmentEpoch::new(),
+ sent: Mutex::new(Vec::new()),
+ fence: Mutex::new(None),
+ });
+ let (driver, outputs) =
+ StateMachineDriver::new(state, fake_workers.clone(), Arc::clone(&sender));
+ Self {
+ driver,
+ outputs,
+ sender,
+ workers: fake_workers,
+ }
+ }
+
+ fn submit(&self, runs: Vec<KeyRun>) {
+ self.driver.send(Input::Groups {
+ assignment_epoch: 0,
+ runs,
+ });
+ }
+
+ fn take_sent(&self) -> Vec<Sent> {
+ std::mem::take(&mut *self.sender.sent.lock().unwrap())
+ }
+
+ fn completed_offsets(&mut self) -> Vec<i64> {
+ let mut completed = Vec::new();
+ while let Ok(completion) = self.outputs.completions.try_recv() {
+ completed.extend(completion.offsets.iter().map(|offset| offset.0));
+ }
+ completed
+ }
+ }
+
+ impl FakeWorkers {
+ fn set_candidates(&self, workers: &[&str]) {
+ self.0.lock().unwrap().candidates =
+ workers.iter().map(|w| WorkerId::from(*w)).collect();
+ }
+
+ fn outcomes(&self) -> Vec<(WorkerId, bool)> {
+ self.0.lock().unwrap().outcomes.clone()
+ }
+
+ fn idle(&self) -> Vec<WorkerId> {
+ self.0.lock().unwrap().idle.clone()
+ }
+ }
+
+ /// Lets the batcher task handle everything queued for it.
+ async fn settle() {
+ for _ in 0..8 {
+ tokio::task::yield_now().await;
+ }
+ }
+
+ fn run(key: &str, offsets: &[i64]) -> KeyRun {
+ KeyRun {
+ routing_key: key.into(),
+ messages: offsets
+ .iter()
+ .map(|&offset| message(key, 0, offset))
+ .collect(),
+ }
+ }
+
+ fn busy(sent: &Sent, fence_guard: Option<FenceGuard>) -> SendError {
+ SendError {
+ error: TransportError::WorkerStreamBusy("test"),
+ messages: sent
+ .offsets
+ .iter()
+ .map(|&offset| message("a", 0, offset))
+ .collect(),
+ fence_guard,
+ }
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn an_accepted_send_completes_its_offsets_and_idles_the_worker() {
+ let mut h = Harness::new(&["w"], 4);
+ h.submit(vec![run("a", &[1, 2])]);
+ settle().await;
+
+ let sent = h.take_sent();
+ assert_eq!(sent.len(), 1);
+ assert_eq!(sent[0].worker, WorkerId::from("w"));
+ assert_eq!(sent[0].offsets, vec![1, 2]);
+ assert!(!sent[0].replay);
+
+ let send = sent.into_iter().next().unwrap();
+ send.reply.send(Ok(2)).unwrap();
+ settle().await;
+ assert_eq!(h.completed_offsets(), vec![1, 2]);
+ assert_eq!(h.workers.outcomes(), vec![(WorkerId::from("w"), false)]);
+ assert_eq!(h.workers.idle(), vec![WorkerId::from("w")]);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn a_busy_send_replays_after_the_busy_delay() {
+ let h = Harness::new(&["w"], 4);
+ h.submit(vec![run("a", &[1])]);
+ settle().await;
+ let send = h.take_sent().pop().unwrap();
+ let failure = busy(&send, None);
+ send.reply.send(Err(failure)).unwrap();
+ settle().await;
+ assert!(h.take_sent().is_empty());
+ assert_eq!(h.workers.outcomes(), vec![(WorkerId::from("w"), false)]);
+
+ tokio::time::advance(BUSY_DELAY - Duration::from_millis(1)).await;
+ settle().await;
+ assert!(h.take_sent().is_empty(), "the retry waits for its delay");
+
+ tokio::time::advance(Duration::from_millis(1)).await;
+ settle().await;
+ let replay = h.take_sent();
+ assert_eq!(replay.len(), 1);
+ assert!(replay[0].replay);
+ assert_eq!(replay[0].offsets, vec![1]);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn a_failed_send_counts_against_the_worker() {
+ let h = Harness::new(&["w"], 4);
+ h.submit(vec![run("a", &[1])]);
+ settle().await;
+ let send = h.take_sent().pop().unwrap();
+ send.reply
+ .send(Err(SendError {
+ error: TransportError::WorkerStreamFailed("test"),
+ messages: vec![message("a", 0, 1)],
+ fence_guard: None,
+ }))
+ .unwrap();
+ settle().await;
+ assert_eq!(h.workers.outcomes(), vec![(WorkerId::from("w"), true)]);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn a_failed_sends_fence_is_released_before_the_next_send_to_its_worker() {
+ let h = Harness::new(&["w"], 1);
+ h.submit(vec![run("a", &[1]), run("b", &[2])]);
+ settle().await;
+ let send = h.take_sent().pop().unwrap();
+ assert_eq!(send.offsets, vec![1], "b waits for the only slot");
+
+ let (release, released) = mpsc::unbounded_channel();
+ *h.sender.fence.lock().unwrap() = Some(released);
+ let failure = busy(&send, Some(FenceGuard::new(release)));
+ send.reply.send(Err(failure)).unwrap();
+ settle().await;
+
+ let next = h.take_sent();
+ assert_eq!(next.len(), 1);
+ assert_eq!(next[0].offsets, vec![2]);
+ assert_eq!(next[0].fence_released, Some(true));
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn a_revoke_queued_with_a_ready_response_applies_first() {
+ let mut h = Harness::new(&["w"], 4);
+ h.submit(vec![run("a", &[1])]);
+ settle().await;
+ h.submit(vec![run("a", &[2])]);
+ settle().await;
+ let send = h.take_sent().pop().unwrap();
+
+ send.reply.send(Ok(1)).unwrap();
+ h.driver
+ .revoke_sender()
+ .purge_revoked(&[("events".to_string(), 0)]);
+ settle().await;
+
+ assert!(
+ h.take_sent().is_empty(),
+ "a's queued message was revoked before the response released a"
+ );
+ assert_eq!(h.completed_offsets(), vec![1]);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn a_revoke_clears_the_order_sentinel() {
+ let h = Harness::new(&["w"], 4);
+ h.submit(vec![run("a", &[1])]);
+ settle().await;
+ let sentinel = h.driver.key_order_sentinel();
+ assert_eq!(sentinel.key_count(), 1);
+
+ h.driver
+ .revoke_sender()
+ .purge_revoked(&[("events".to_string(), 9)]);
+ settle().await;
+ assert_eq!(sentinel.key_count(), 0);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn the_load_tracks_pending_in_flight_and_busy_workers() {
+ let h = Harness::new(&[], 2);
+ let load = h.driver.load();
+ h.submit(vec![run("a", &[1]), run("b", &[2, 3])]);
+ settle().await;
+ assert_eq!(load.pending_messages.load(Ordering::Relaxed), 3);
+ assert!(load.busy_workers.lock().unwrap().is_empty());
+
+ h.workers.set_candidates(&["w"]);
+ tokio::time::advance(NO_WORKER_DELAY).await;
+ settle().await;
+ assert_eq!(load.pending_messages.load(Ordering::Relaxed), 0);
+ assert_eq!(load.in_flight_messages.load(Ordering::Relaxed), 3);
+ assert_eq!(
+ *load.busy_workers.lock().unwrap(),
+ HashSet::from([WorkerId::from("w")])
+ );
+
+ let mut sent = h.take_sent();
+ let accepted = |send: &Sent| send.offsets.len() as u32;
+ let first = sent.remove(0);
+ let count = accepted(&first);
+ first.reply.send(Ok(count)).unwrap();
+ settle().await;
+ assert!(!load.busy_workers.lock().unwrap().is_empty());
+
+ let last = sent.remove(0);
+ let count = accepted(&last);
+ last.reply.send(Ok(count)).unwrap();
+ settle().await;
+ assert!(load.busy_workers.lock().unwrap().is_empty());
+ assert_eq!(load.in_flight_messages.load(Ordering::Relaxed), 0);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn a_state_machine_failure_reaches_the_error_channel() {
+ let mut h = Harness::new(&["w"], 4);
+ h.submit(vec![run("a", &[1, 2])]);
+ settle().await;
+ let send = h.take_sent().pop().unwrap();
+ send.reply.send(Ok(1)).unwrap();
+ settle().await;
+ assert!(h.outputs.errors.try_recv().is_ok());
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn dropping_the_driver_stops_its_task() {
+ let h = Harness::new(&["w"], 4);
+ let sender = Arc::clone(&h.sender);
+ assert_eq!(Arc::strong_count(&sender), 3);
+ drop(h);
+ settle().await;
+ assert_eq!(Arc::strong_count(&sender), 1);
+ }
+}
diff --git a/rust/ingestion-consumer/src/batcher/in_flight.rs b/rust/ingestion-consumer/src/batcher/in_flight.rs
new file mode 100644
index 000000000000..2917f4daeb1f
--- /dev/null
+++ b/rust/ingestion-consumer/src/batcher/in_flight.rs
@@ -0,0 +1,174 @@
+//! Remembers what each in-flight request carried, because a response names
+//! its request only by id.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use super::key_queues::KeyRun;
+use super::request::RequestClass;
+use crate::types::SerializedKafkaMessage;
+use crate::worker_registry::WorkerId;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct RequestId(u64);
+
+#[derive(Debug)]
+pub struct SentMessage {
+ pub partition: i32,
+ pub offset: i64,
+ pub keyed: bool,
+}
+
+impl SentMessage {
+ fn of(message: &SerializedKafkaMessage) -> Self {
+ Self {
+ partition: message.partition,
+ offset: message.offset,
+ keyed: message.key.is_some(),
+ }
+ }
+}
+
+pub struct SentRun {
+ pub routing_key: Arc<str>,
+ pub messages: Vec<SentMessage>,
+}
+
+pub struct InFlightRequest {
+ pub worker: WorkerId,
+ pub class: RequestClass,
+ pub message_count: usize,
+ runs: Vec<SentRun>,
+}
+
+#[derive(Default)]
+pub struct InFlightRequests {
+ next_id: u64,
+ requests: HashMap<RequestId, InFlightRequest, ahash::RandomState>,
+}
+
+impl InFlightRequests {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn len(&self) -> usize {
+ self.requests.len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.requests.is_empty()
+ }
+
+ pub fn register(
+ &mut self,
+ worker: WorkerId,
+ class: RequestClass,
+ runs: &[KeyRun],
+ ) -> RequestId {
+ let id = RequestId(self.next_id);
+ self.next_id += 1;
+ let runs: Vec<SentRun> = runs
+ .iter()
+ .map(|run| SentRun {
+ routing_key: Arc::clone(&run.routing_key),
+ messages: run.messages.iter().map(SentMessage::of).collect(),
+ })
+ .collect();
+ let message_count = runs.iter().map(|run| run.messages.len()).sum();
+ self.requests.insert(
+ id,
+ InFlightRequest {
+ worker,
+ class,
+ message_count,
+ runs,
+ },
+ );
+ id
+ }
+
+ pub fn take(&mut self, id: RequestId) -> Option<InFlightRequest> {
+ self.requests.remove(&id)
+ }
+}
+
+impl InFlightRequest {
+ pub fn accepted(self) -> Vec<SentRun> {
+ self.runs
+ }
+
+ /// The transport hands back every message of a failed request in send
+ /// order, so the runs are cut by length.
+ pub fn hand_back(self, messages: Vec<SerializedKafkaMessage>) -> Result<Vec<KeyRun>, String> {
+ if messages.len() != self.message_count {
+ return Err(format!(
+ "transport handed back {} of {} messages of a failed request",
+ messages.len(),
+ self.message_count
+ ));
+ }
+ let mut messages = messages.into_iter();
+ Ok(self
+ .runs
+ .into_iter()
+ .map(|run| KeyRun {
+ messages: messages.by_ref().take(run.messages.len()).collect(),
+ routing_key: run.routing_key,
+ })
+ .collect())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::batcher::test_support::{message, offsets};
+
+ const FRESH: RequestClass = RequestClass {
+ assignment_epoch: 0,
+ replay: false,
+ };
+
+ fn run(key: &str, offsets: &[i64]) -> KeyRun {
+ KeyRun {
+ routing_key: key.into(),
+ messages: offsets
+ .iter()
+ .map(|&offset| message(key, 0, offset))
+ .collect(),
+ }
+ }
+
+ fn request() -> InFlightRequest {
+ let mut requests = InFlightRequests::new();
+ let id = requests.register(
+ WorkerId::from("w"),
+ FRESH,
+ &[run("a", &[1, 2, 3]), run("b", &[10])],
+ );
+ requests.take(id).expect("registered")
+ }
+
+ #[test]
+ fn a_failed_request_hands_each_key_back_its_run() {
+ let request = request();
+ let handed_back = vec![
+ message("a", 0, 1),
+ message("a", 0, 2),
+ message("a", 0, 3),
+ message("b", 0, 10),
+ ];
+ let runs = request.hand_back(handed_back).expect("every message");
+ let shapes: Vec<_> = runs
+ .iter()
+ .map(|run| (&*run.routing_key, offsets(&run.messages)))
+ .collect();
+ assert_eq!(shapes, vec![("a", vec![1, 2, 3]), ("b", vec![10])]);
+ }
+
+ #[test]
+ fn a_hand_back_missing_messages_is_an_error() {
+ assert!(request().hand_back(vec![message("a", 0, 1)]).is_err());
+ }
+}
diff --git a/rust/ingestion-consumer/src/batcher/key_queues.rs b/rust/ingestion-consumer/src/batcher/key_queues.rs
new file mode 100644
index 000000000000..6d8fc0354864
--- /dev/null
+++ b/rust/ingestion-consumer/src/batcher/key_queues.rs
@@ -0,0 +1,706 @@
+//! Per-key message queues that keep per-key order: a key has at most one run
+//! out, and its later messages wait until that run settles.
+
+use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};
+use std::sync::Arc;
+use std::time::Instant;
+
+use common_kafka_consumer::Offset;
+
+use super::request::RequestClass;
+use crate::types::{Group, SerializedKafkaMessage};
+
+#[derive(Clone, Debug)]
+pub struct KeyRun {
+ pub routing_key: Arc<str>,
+ pub messages: Vec<SerializedKafkaMessage>,
+}
+
+impl KeyRun {
+ /// An unkeyed group gets a synthetic key: it has no per-key order to keep.
+ pub fn from_groups(groups: Vec<Group>) -> Vec<KeyRun> {
+ let mut runs: Vec<KeyRun> = Vec::with_capacity(groups.len());
+ let mut index_by_key: HashMap<Arc<str>, usize> = HashMap::new();
+ for group in groups {
+ let routing_key: Arc<str> = match group.key {
+ Some(key) => key.into(),
+ None => {
+ let first = group.messages.first().map_or(Offset(-1), |m| m.offset);
+ format!(":{}:{}", group.partition, first).into()
+ }
+ };
+ let messages = group.messages.into_iter().map(|m| m.message);
+ match index_by_key.get(&routing_key) {
+ Some(&index) => runs[index].messages.extend(messages),
+ None => {
+ index_by_key.insert(routing_key.clone(), runs.len());
+ runs.push(KeyRun {
+ routing_key,
+ messages: messages.collect(),
+ });
+ }
+ }
+ }
+ runs
+ }
+}
+
+pub(super) fn payload_bytes(messages: &[SerializedKafkaMessage]) -> usize {
+ messages
+ .iter()
+ .map(SerializedKafkaMessage::payload_bytes)
+ .sum()
+}
+
+pub struct ReadyRun {
+ pub class: RequestClass,
+ pub run: KeyRun,
+ pub bytes: usize,
+ pub first_arrival: Instant,
+}
+
+/// Every settle releases a claim the queues handed out, so this is a
+/// bookkeeping bug.
+#[derive(Debug, thiserror::Error, PartialEq, Eq)]
+#[error("settled key {routing_key} without a claim")]
+pub struct UnclaimedSettle {
+ pub routing_key: String,
+}
+
+struct Segment {
+ class: RequestClass,
+ queued_at: Instant,
+ bytes: usize,
+ messages: Vec<SerializedKafkaMessage>,
+}
+
+struct Claim {
+ assignment_epoch: u64,
+ /// Requeued messages of these partitions drop; the new owner replays them.
+ revoked: Vec<(String, i32)>,
+}
+
+#[derive(Default)]
+struct KeyState {
+ queue: VecDeque<Segment>,
+ claim: Option<Claim>,
+ retry_at: Option<Instant>,
+}
+
+impl KeyState {
+ fn is_ready(&self) -> bool {
+ self.claim.is_none() && self.retry_at.is_none() && !self.queue.is_empty()
+ }
+
+ fn is_idle(&self) -> bool {
+ self.claim.is_none() && self.retry_at.is_none() && self.queue.is_empty()
+ }
+}
+
+#[derive(Default)]
+pub struct KeyQueues {
+ /// Seeded per map, because routing keys are customer-chosen.
+ keys: HashMap<Arc<str>, KeyState, ahash::RandomState>,
+ /// Can hold stale keys; `take_ready` skips them.
+ ready: VecDeque<Arc<str>>,
+ waiting: BTreeSet<(Instant, Arc<str>)>,
+ queued_messages: usize,
+ queued_bytes: usize,
+ claimed_keys: usize,
+}
+
+impl KeyQueues {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn key_count(&self) -> usize {
+ self.keys.len()
+ }
+
+ pub fn queued_messages(&self) -> usize {
+ self.queued_messages
+ }
+
+ pub fn queued_bytes(&self) -> usize {
+ self.queued_bytes
+ }
+
+ pub fn claimed_keys(&self) -> usize {
+ self.claimed_keys
+ }
+
+ pub fn waiting_keys(&self) -> usize {
+ self.waiting.len()
+ }
+
+ pub fn next_retry_at(&self) -> Option<Instant> {
+ self.waiting.first().map(|(at, _)| *at)
+ }
+
+ pub fn has_ready(&self) -> bool {
+ self.ready
+ .iter()
+ .any(|key| self.keys.get(key).is_some_and(KeyState::is_ready))
+ }
+
+ pub fn push(
+ &mut self,
+ routing_key: Arc<str>,
+ assignment_epoch: u64,
+ messages: Vec<SerializedKafkaMessage>,
+ now: Instant,
+ ) {
+ if messages.is_empty() {
+ return;
+ }
+ let bytes = payload_bytes(&messages);
+ self.queued_messages += messages.len();
+ self.queued_bytes += bytes;
+ let class = RequestClass {
+ assignment_epoch,
+ replay: false,
+ };
+ let state = match self.keys.get_mut(&*routing_key) {
+ Some(state) => state,
+ None => self.keys.entry(Arc::clone(&routing_key)).or_default(),
+ };
+ let was_ready = state.is_ready();
+ state.queue.push_back(Segment {
+ class,
+ queued_at: now,
+ bytes,
+ messages,
+ });
+ if !was_ready && state.is_ready() {
+ self.ready.push_back(routing_key);
+ }
+ }
+
+ pub fn promote_due(&mut self, now: Instant) {
+ while let Some((at, _)) = self.waiting.first() {
+ if *at > now {
+ break;
+ }
+ let (_, key) = self.waiting.pop_first().expect("checked non-empty");
+ if let Some(state) = self.keys.get_mut(&key) {
+ state.retry_at = None;
+ if state.is_ready() {
+ self.ready.push_back(key);
+ }
+ }
+ }
+ }
+
+ pub fn take_ready(&mut self, now: Instant, limit: usize) -> Vec<ReadyRun> {
+ self.promote_due(now);
+
+ let mut runs = Vec::with_capacity(limit.min(self.ready.len()));
+ while runs.len() < limit {
+ let Some(key) = self.ready.pop_front() else {
+ break;
+ };
+ let Some(state) = self.keys.get_mut(&key) else {
+ continue;
+ };
+ if !state.is_ready() {
+ continue;
+ }
+ let Segment {
+ class,
+ queued_at: first_arrival,
+ mut bytes,
+ mut messages,
+ } = state.queue.pop_front().expect("a ready key has messages");
+ while state
+ .queue
+ .front()
+ .is_some_and(|segment| segment.class == class)
+ {
+ let next = state.queue.pop_front().expect("checked");
+ bytes += next.bytes;
+ messages.extend(next.messages);
+ }
+ debug_assert!(self.queued_messages >= messages.len());
+ self.queued_messages = self.queued_messages.saturating_sub(messages.len());
+ self.queued_bytes = self.queued_bytes.saturating_sub(bytes);
+ state.claim = Some(Claim {
+ assignment_epoch: class.assignment_epoch,
+ revoked: Vec::new(),
+ });
+ self.claimed_keys += 1;
+ runs.push(ReadyRun {
+ class,
+ run: KeyRun {
+ routing_key: key,
+ messages,
+ },
+ bytes,
+ first_arrival,
+ });
+ }
+ runs
+ }
+
+ pub fn settle(
+ &mut self,
+ routing_key: &Arc<str>,
+ mut requeued: Vec<SerializedKafkaMessage>,
+ retry_at: Option<Instant>,
+ now: Instant,
+ ) -> Result<bool, UnclaimedSettle> {
+ let unclaimed = || UnclaimedSettle {
+ routing_key: routing_key.to_string(),
+ };
+ let Some(state) = self.keys.get_mut(&**routing_key) else {
+ return Err(unclaimed());
+ };
+ let Some(claim) = state.claim.take() else {
+ return Err(unclaimed());
+ };
+ self.claimed_keys = self.claimed_keys.saturating_sub(1);
+
+ if !claim.revoked.is_empty() {
+ requeued.retain(|message| {
+ !claim.revoked.iter().any(|(topic, partition)| {
+ topic.as_str() == &*message.topic && *partition == message.partition
+ })
+ });
+ }
+ if !requeued.is_empty() {
+ let bytes = payload_bytes(&requeued);
+ self.queued_messages += requeued.len();
+ self.queued_bytes += bytes;
+ // Ahead of later arrivals and under the run's epoch, so the replay
+ // keeps offset order.
+ state.queue.push_front(Segment {
+ class: RequestClass {
+ assignment_epoch: claim.assignment_epoch,
+ replay: true,
+ },
+ queued_at: now,
+ bytes,
+ messages: requeued,
+ });
+ if let Some(at) = retry_at.filter(|at| *at > now) {
+ state.retry_at = Some(at);
+ self.waiting.insert((at, Arc::clone(routing_key)));
+ }
+ }
+
+ if state.is_idle() {
+ self.keys.remove(&**routing_key);
+ return Ok(true);
+ }
+ if state.is_ready() {
+ self.ready.push_back(Arc::clone(routing_key));
+ }
+ Ok(false)
+ }
+
+ pub fn purge(&mut self, revoked: &[(String, i32)]) -> Vec<Arc<str>> {
+ let revoked_set: HashSet<(&str, i32)> = revoked
+ .iter()
+ .map(|(topic, partition)| (topic.as_str(), *partition))
+ .collect();
+ let mut purged = 0usize;
+ let mut purged_bytes = 0usize;
+ for (key, state) in self.keys.iter_mut() {
+ if let Some(claim) = &mut state.claim {
+ for revocation in revoked {
+ if !claim.revoked.contains(revocation) {
+ claim.revoked.push(revocation.clone());
+ }
+ }
+ }
+ for segment in state.queue.iter_mut() {
+ let before = segment.messages.len();
+ segment.messages.retain(|message| {
+ let keep = !revoked_set.contains(&(&*message.topic, message.partition));
+ if !keep {
+ segment.bytes -= message.payload_bytes();
+ purged_bytes += message.payload_bytes();
+ }
+ keep
+ });
+ purged += before - segment.messages.len();
+ }
+ state.queue.retain(|segment| !segment.messages.is_empty());
+ // The wait was for the requeued messages the revoke just dropped.
+ if !state.queue.iter().any(|segment| segment.class.replay) {
+ if let Some(at) = state.retry_at.take() {
+ self.waiting.remove(&(at, key.clone()));
+ if state.is_ready() {
+ self.ready.push_back(key.clone());
+ }
+ }
+ }
+ }
+ self.queued_messages = self.queued_messages.saturating_sub(purged);
+ self.queued_bytes = self.queued_bytes.saturating_sub(purged_bytes);
+
+ let evicted_keys: Vec<Arc<str>> = self
+ .keys
+ .iter()
+ .filter(|(_, state)| state.is_idle())
+ .map(|(key, _)| key.clone())
+ .collect();
+ for key in &evicted_keys {
+ self.keys.remove(key);
+ }
+ let keys = &self.keys;
+ self.ready
+ .retain(|key| keys.get(key).is_some_and(KeyState::is_ready));
+ evicted_keys
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::time::Duration;
+
+ use common_kafka_consumer::{GroupMessage, Partition};
+
+ use super::*;
+ use crate::batcher::test_support::{message, offsets};
+
+ fn key(routing_key: &str) -> Arc<str> {
+ Arc::from(routing_key)
+ }
+
+ fn claimed(runs: &[ReadyRun]) -> Vec<(&str, Vec<i64>, bool)> {
+ runs.iter()
+ .map(|run| {
+ (
+ &*run.run.routing_key,
+ offsets(&run.run.messages),
+ run.class.replay,
+ )
+ })
+ .collect()
+ }
+
+ #[test]
+ fn arrivals_for_a_claimed_key_wait_for_its_settle() {
+ let now = Instant::now();
+ let mut queues = KeyQueues::new();
+ queues.push(key("a"), 0, vec![message("a", 0, 1)], now);
+ assert_eq!(
+ claimed(&queues.take_ready(now, usize::MAX)),
+ vec![("a", vec![1], false)]
+ );
+
+ queues.push(
+ key("a"),
+ 0,
+ vec![message("a", 0, 2), message("a", 0, 3)],
+ now,
+ );
+ assert!(
+ queues.take_ready(now, usize::MAX).is_empty(),
+ "one run per key is out"
+ );
+
+ assert_eq!(queues.settle(&key("a"), Vec::new(), None, now), Ok(false));
+ assert_eq!(
+ claimed(&queues.take_ready(now, usize::MAX)),
+ vec![("a", vec![2, 3], false)]
+ );
+ assert_eq!(queues.settle(&key("a"), Vec::new(), None, now), Ok(true));
+ assert_eq!(queues.key_count(), 0);
+ }
+
+ #[test]
+ fn keys_past_the_take_limit_stay_unclaimed_and_keep_their_turn() {
+ let now = Instant::now();
+ let mut queues = KeyQueues::new();
+ for routing_key in ["a", "b", "c"] {
+ queues.push(key(routing_key), 0, vec![message(routing_key, 0, 1)], now);
+ }
+
+ assert_eq!(
+ claimed(&queues.take_ready(now, 1)),
+ vec![("a", vec![1], false)]
+ );
+ assert!(queues.take_ready(now, 0).is_empty());
+ assert_eq!(queues.claimed_keys(), 1);
+ assert_eq!(queues.queued_messages(), 2);
+ assert_eq!(
+ claimed(&queues.take_ready(now, usize::MAX)),
+ vec![("b", vec![1], false), ("c", vec![1], false)]
+ );
+ }
+
+ #[test]
+ fn requeued_messages_go_first_as_replay_after_their_retry_time() {
+ let now = Instant::now();
+ let retry_at = now + Duration::from_millis(100);
+ let mut queues = KeyQueues::new();
+ queues.push(
+ key("a"),
+ 0,
+ vec![message("a", 0, 1), message("a", 0, 2)],
+ now,
+ );
+ queues.take_ready(now, usize::MAX);
+ queues.push(key("a"), 0, vec![message("a", 0, 3)], now);
+
+ let requeued = vec![message("a", 0, 2)];
+ assert_eq!(
+ queues.settle(&key("a"), requeued, Some(retry_at), now),
+ Ok(false)
+ );
+ assert!(
+ queues.take_ready(now, usize::MAX).is_empty(),
+ "waits for its retry time"
+ );
+ assert_eq!(queues.next_retry_at(), Some(retry_at));
+
+ assert_eq!(
+ claimed(&queues.take_ready(retry_at, usize::MAX)),
+ vec![("a", vec![2], true)]
+ );
+ queues
+ .settle(&key("a"), Vec::new(), None, retry_at)
+ .expect("claimed");
+ assert_eq!(
+ claimed(&queues.take_ready(retry_at, usize::MAX)),
+ vec![("a", vec![3], false)]
+ );
+ }
+
+ #[test]
+ fn a_run_stops_at_an_epoch_boundary() {
+ let now = Instant::now();
+ let mut queues = KeyQueues::new();
+ queues.push(key("a"), 1, vec![message("a", 0, 1)], now);
+ queues.push(key("a"), 2, vec![message("a", 0, 2)], now);
+
+ let runs = queues.take_ready(now, usize::MAX);
+ assert_eq!(runs.len(), 1);
+ assert_eq!(runs[0].class.assignment_epoch, 1);
+ assert_eq!(offsets(&runs[0].run.messages), vec![1]);
+ }
+
+ #[test]
+ fn a_revoke_drops_queued_messages_and_requeued_messages_of_the_partition() {
+ let now = Instant::now();
+ let mut queues = KeyQueues::new();
+ queues.push(
+ key("a"),
+ 0,
+ vec![message("a", 0, 1), message("a", 1, 7)],
+ now,
+ );
+ queues.take_ready(now, usize::MAX);
+ queues.push(key("a"), 0, vec![message("a", 0, 2)], now);
+ queues.push(key("b"), 0, vec![message("b", 0, 5)], now);
+
+ let evicted = queues.purge(&[("events".to_string(), 0)]);
+ assert_eq!(evicted, vec![Arc::<str>::from("b")]);
+ assert_eq!(queues.queued_messages(), 0);
+
+ let requeued = vec![message("a", 0, 1), message("a", 1, 7)];
+ queues
+ .settle(&key("a"), requeued, None, now)
+ .expect("claimed");
+ assert_eq!(
+ claimed(&queues.take_ready(now, usize::MAX)),
+ vec![("a", vec![7], true)],
+ "only the message of the kept partition returns"
+ );
+ }
+
+ #[test]
+ fn a_revoke_that_drops_the_requeued_messages_ends_their_wait() {
+ let now = Instant::now();
+ let mut queues = KeyQueues::new();
+ queues.push(key("a"), 0, vec![message("a", 0, 1)], now);
+ queues.take_ready(now, usize::MAX);
+ queues.push(key("a"), 0, vec![message("a", 1, 7)], now);
+ let retry_at = now + Duration::from_millis(100);
+ queues
+ .settle(&key("a"), vec![message("a", 0, 1)], Some(retry_at), now)
+ .expect("claimed");
+
+ queues.purge(&[("events".to_string(), 0)]);
+ assert_eq!(queues.next_retry_at(), None);
+ assert_eq!(
+ claimed(&queues.take_ready(now, usize::MAX)),
+ vec![("a", vec![7], false)]
+ );
+ }
+
+ #[test]
+ fn a_settle_without_a_claim_is_an_error() {
+ let now = Instant::now();
+ let mut queues = KeyQueues::new();
+ queues.push(key("a"), 0, vec![message("a", 0, 1)], now);
+ assert!(queues
+ .settle(&key("a"), vec![message("a", 0, 1)], None, now)
+ .is_err());
+ assert_eq!(queues.queued_messages(), 1);
+ }
+
+ #[test]
+ fn a_key_split_over_groups_is_one_run_and_an_unkeyed_group_gets_its_own_key() {
+ let group = |partition: i32, key: Option<&str>, offsets: &[i64]| Group {
+ partition: Partition(partition),
+ key: key.map(str::to_string),
+ messages: offsets
+ .iter()
+ .map(|&offset| GroupMessage {
+ offset: Offset(offset),
+ message: SerializedKafkaMessage {
+ key: key.map(str::to_string),
+ ..message("unused", partition, offset)
+ },
+ })
+ .collect(),
+ };
+ let runs = KeyRun::from_groups(vec![
+ group(0, Some("a"), &[1]),
+ group(1, None, &[5]),
+ group(2, Some("a"), &[7]),
+ ]);
+ let shapes: Vec<_> = runs
+ .iter()
+ .map(|run| (&*run.routing_key, offsets(&run.messages)))
+ .collect();
+ assert_eq!(shapes, vec![("a", vec![1, 7]), (":1:5", vec![5])]);
+ }
+
+ #[test]
+ fn pushes_of_one_class_before_a_claim_leave_as_one_run() {
+ let now = Instant::now();
+ let mut queues = KeyQueues::new();
+ queues.push(key("a"), 0, vec![message("a", 0, 1)], now);
+ queues.push(key("a"), 0, vec![message("a", 0, 2)], now);
+ assert_eq!(
+ claimed(&queues.take_ready(now, usize::MAX)),
+ vec![("a", vec![1, 2], false)]
+ );
+ }
+
+ #[test]
+ fn queued_bytes_follow_messages_through_claim_requeue_and_purge() {
+ let now = Instant::now();
+ let mut queues = KeyQueues::new();
+ queues.push(
+ key("a"),
+ 0,
+ vec![message("a", 0, 1), message("a", 1, 2)],
+ now,
+ );
+ queues.take_ready(now, usize::MAX);
+ assert_eq!(queues.queued_bytes(), 0);
+
+ let requeued = vec![message("a", 0, 1), message("a", 1, 2)];
+ let requeued_bytes = payload_bytes(&requeued);
+ queues
+ .settle(&key("a"), requeued, None, now)
+ .expect("claimed");
+ assert_eq!(queues.queued_bytes(), requeued_bytes);
+
+ queues.purge(&[("events".to_string(), 0)]);
+ assert_eq!(queues.queued_bytes(), message("a", 1, 2).payload_bytes());
+ }
+
+ #[test]
+ fn repeated_failures_keep_one_replay_segment_ahead_of_every_later_arrival() {
+ let now = Instant::now();
+ let mut queues = KeyQueues::new();
+ let failed = || vec![message("a", 0, 1), message("a", 0, 2)];
+ queues.push(key("a"), 0, failed(), now);
+ queues.take_ready(now, usize::MAX);
+ queues.push(key("a"), 0, vec![message("a", 0, 3)], now);
+ queues
+ .settle(&key("a"), failed(), None, now)
+ .expect("claimed");
+ assert_eq!(
+ claimed(&queues.take_ready(now, usize::MAX)),
+ vec![("a", vec![1, 2], true)]
+ );
+
+ queues.push(key("a"), 0, vec![message("a", 0, 4)], now);
+ queues
+ .settle(&key("a"), failed(), None, now)
+ .expect("claimed");
+ assert_eq!(queues.queued_messages(), 4);
+ assert_eq!(
+ claimed(&queues.take_ready(now, usize::MAX)),
+ vec![("a", vec![1, 2], true)]
+ );
+ queues
+ .settle(&key("a"), Vec::new(), None, now)
+ .expect("claimed");
+ assert_eq!(
+ claimed(&queues.take_ready(now, usize::MAX)),
+ vec![("a", vec![3, 4], false)]
+ );
+ assert_eq!(queues.settle(&key("a"), Vec::new(), None, now), Ok(true));
+ assert_eq!(queues.queued_messages(), 0);
+ assert_eq!(queues.queued_bytes(), 0);
+ }
+
+ #[test]
+ fn a_key_evicted_by_a_purge_and_pushed_again_is_claimed_once() {
+ let now = Instant::now();
+ let mut queues = KeyQueues::new();
+ queues.push(key("a"), 0, vec![message("a", 0, 1)], now);
+ queues.push(key("a"), 0, vec![message("a", 0, 2)], now);
+ assert_eq!(
+ queues.purge(&[("events".to_string(), 0)]),
+ vec![Arc::<str>::from("a")]
+ );
+
+ queues.push(key("a"), 0, vec![message("a", 1, 5)], now);
+ assert_eq!(
+ claimed(&queues.take_ready(now, usize::MAX)),
+ vec![("a", vec![5], false)]
+ );
+ assert_eq!(queues.claimed_keys(), 1);
+ assert!(queues.take_ready(now, usize::MAX).is_empty());
+ }
+
+ #[test]
+ fn a_double_purge_does_not_double_count() {
+ let now = Instant::now();
+ let mut queues = KeyQueues::new();
+ queues.push(
+ key("a"),
+ 0,
+ vec![message("a", 0, 1), message("a", 1, 2)],
+ now,
+ );
+ queues.purge(&[("events".to_string(), 0)]);
+ queues.purge(&[("events".to_string(), 0)]);
+ assert_eq!(queues.queued_messages(), 1);
+ assert_eq!(queues.queued_bytes(), message("a", 1, 2).payload_bytes());
+ assert_eq!(
+ claimed(&queues.take_ready(now, usize::MAX)),
+ vec![("a", vec![2], false)]
+ );
+ }
+
+ #[test]
+ fn a_partially_revoked_requeue_keeps_waiting_for_its_retry() {
+ let now = Instant::now();
+ let retry_at = now + Duration::from_millis(100);
+ let mut queues = KeyQueues::new();
+ let spanning = || vec![message("a", 0, 1), message("a", 1, 7)];
+ queues.push(key("a"), 0, spanning(), now);
+ queues.take_ready(now, usize::MAX);
+ queues
+ .settle(&key("a"), spanning(), Some(retry_at), now)
+ .expect("claimed");
+
+ queues.purge(&[("events".to_string(), 0)]);
+ assert_eq!(queues.next_retry_at(), Some(retry_at));
+ assert!(queues.take_ready(now, usize::MAX).is_empty());
+ assert_eq!(
+ claimed(&queues.take_ready(retry_at, usize::MAX)),
+ vec![("a", vec![7], true)]
+ );
+ }
+}
diff --git a/rust/ingestion-consumer/src/batcher.rs b/rust/ingestion-consumer/src/batcher/mod.rs
similarity index 79%
rename from rust/ingestion-consumer/src/batcher.rs
rename to rust/ingestion-consumer/src/batcher/mod.rs
index fff5742498dd..a1761ab91c31 100644
--- a/rust/ingestion-consumer/src/batcher.rs
+++ b/rust/ingestion-consumer/src/batcher/mod.rs
@@ -14,8 +14,19 @@
//! on an error channel; the consumer turns them into a process failure, so
//! the failure decision stays in the consumer loop.
+mod driver;
+pub mod in_flight;
+pub mod key_queues;
+pub mod request;
+pub mod retry_policy;
+pub mod state_machine;
+#[cfg(test)]
+pub(crate) mod test_support;
+pub mod worker_assigner;
+pub mod worker_pool;
+
use std::collections::HashMap;
-use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -26,10 +37,12 @@ use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tracing::{error, info};
+use self::driver::StateMachineDriver;
+use self::state_machine::BatcherStateMachine;
+use self::worker_pool::WorkerPoolSource;
use crate::dispatcher::{Dispatcher, KeyOffset, SubBatch, Submission};
use crate::grpc_transport::{GrpcTransport, PendingWorkerStreamSend};
use crate::order_sentinel::KeyOrderSentinel;
-use crate::scheduler::SchedulerKind;
use crate::transport::SendError;
use crate::types::Accumulator;
use crate::types::SerializedKafkaMessage;
@@ -82,7 +95,6 @@ struct BatcherInner {
/// Stamped on each submitted batch's completions; bumped on partition
/// assignment by the consumer's rebalance context.
assignment_epoch: AssignmentEpoch,
- accepted_messages: AtomicU64,
completions: mpsc::UnboundedSender<GroupCompletion>,
errors: mpsc::UnboundedSender<String>,
}
@@ -123,23 +135,189 @@ fn send_group_completions(
}
}
+/// Submits polls, and receives completions and fatal errors back, through
+/// either the dispatcher or the batcher state machine, as
+/// `INGESTION_SCHEDULER` selects.
+pub struct Batcher {
+ backend: Backend,
+}
+
+enum Backend {
+ Dispatcher(DispatcherBatcher),
+ StateMachine(StateMachineDriver),
+}
+
+impl Batcher {
+ /// Drive the dispatcher's pin-stash scheduler.
+ pub fn new(
+ dispatcher: Arc<Dispatcher>,
+ transport: Arc<GrpcTransport>,
+ handle: Handle,
+ deferred_flush_timeout: Duration,
+ ) -> (Self, BatcherOutputs) {
+ let (inner, outputs) =
+ DispatcherBatcher::new(dispatcher, transport, handle, deferred_flush_timeout);
+ (
+ Self {
+ backend: Backend::Dispatcher(inner),
+ },
+ outputs,
+ )
+ }
+
+ /// Drive the batcher state machine, the `key_table` scheduler.
+ pub fn with_state_machine(
+ state_machine: BatcherStateMachine,
+ pool_source: WorkerPoolSource,
+ transport: Arc<GrpcTransport>,
+ ) -> (Self, BatcherOutputs) {
+ let (driver, outputs) = StateMachineDriver::new(state_machine, pool_source, transport);
+ (
+ Self {
+ backend: Backend::StateMachine(driver),
+ },
+ outputs,
+ )
+ }
+
+ /// The per-key order sentinel, so the consumer can enable it.
+ pub fn key_order_sentinel(&self) -> Arc<KeyOrderSentinel> {
+ match &self.backend {
+ Backend::Dispatcher(inner) => inner.key_order_sentinel(),
+ Backend::StateMachine(driver) => driver.key_order_sentinel(),
+ }
+ }
+
+ /// The batcher's half of the consumer's revocation hook.
+ pub fn revoker(&self) -> Revoker {
+ match &self.backend {
+ Backend::Dispatcher(inner) => {
+ Revoker(RevokeTarget::Dispatcher(inner.key_order_sentinel()))
+ }
+ Backend::StateMachine(driver) => {
+ Revoker(RevokeTarget::StateMachine(driver.revoke_sender()))
+ }
+ }
+ }
+
+ /// Submit one poll's demuxed groups. Call on the consumer loop, in poll
+ /// order. Returns the assignment epoch stamped on the poll's completions.
+ pub fn submit(&self, accumulator: Accumulator) -> u64 {
+ match &self.backend {
+ Backend::Dispatcher(inner) => inner.submit(accumulator),
+ Backend::StateMachine(driver) => driver.submit(accumulator),
+ }
+ }
+
+ /// A read-only view of the batcher's load, for the drain reaper and
+ /// tests.
+ pub fn observer(&self) -> BatcherObserver {
+ match &self.backend {
+ Backend::Dispatcher(inner) => BatcherObserver(ObserverTarget::Dispatcher(Arc::clone(
+ &inner.inner.dispatcher,
+ ))),
+ Backend::StateMachine(driver) => {
+ BatcherObserver(ObserverTarget::StateMachine(driver.load()))
+ }
+ }
+ }
+
+ /// The consumer stopped polling. The state machine takes no new groups
+ /// and stops once nothing is pending or in flight.
+ pub fn begin_shutdown(&self) {
+ if let Backend::StateMachine(driver) = &self.backend {
+ driver.begin_shutdown();
+ }
+ }
+}
+
+/// A read-only view of the batcher's load.
+#[derive(Clone)]
+pub struct BatcherObserver(ObserverTarget);
+
+#[derive(Clone)]
+enum ObserverTarget {
+ Dispatcher(Arc<Dispatcher>),
+ StateMachine(Arc<driver::Load>),
+}
+
+impl BatcherObserver {
+ /// Whether the worker has sent, unresolved work. The reaper completes a
+ /// draining worker's drain only when it has none.
+ pub fn has_in_flight(&self, worker: &WorkerId) -> bool {
+ match &self.0 {
+ ObserverTarget::Dispatcher(dispatcher) => dispatcher.has_in_flight(worker),
+ ObserverTarget::StateMachine(load) => {
+ load.busy_workers.lock().unwrap().contains(worker)
+ }
+ }
+ }
+
+ /// Messages held for a later send: the pin-stash's stash, or the
+ /// state machine's queued, packed and unplaced messages.
+ pub fn held_messages(&self) -> usize {
+ match &self.0 {
+ ObserverTarget::Dispatcher(dispatcher) => dispatcher.stashed_messages(),
+ ObserverTarget::StateMachine(load) => load.pending_messages.load(Ordering::Relaxed),
+ }
+ }
+
+ pub fn total_in_flight(&self) -> usize {
+ match &self.0 {
+ ObserverTarget::Dispatcher(dispatcher) => dispatcher.total_in_flight(),
+ ObserverTarget::StateMachine(load) => load.in_flight_messages.load(Ordering::Relaxed),
+ }
+ }
+
+ /// Live sticky pins; the state machine keeps none.
+ pub fn pin_count(&self) -> usize {
+ match &self.0 {
+ ObserverTarget::Dispatcher(dispatcher) => dispatcher.pin_count(),
+ ObserverTarget::StateMachine(_) => 0,
+ }
+ }
+}
+
+/// Purges revoked partitions from the batcher. Runs on the rebalance
+/// callback.
+pub struct Revoker(RevokeTarget);
+
+enum RevokeTarget {
+ /// The pin-stash scheduler keeps nothing to purge.
+ Dispatcher(Arc<KeyOrderSentinel>),
+ StateMachine(driver::RevokeSender),
+}
+
+impl Revoker {
+ pub fn purge_revoked(&self, partitions: &[(String, i32)]) {
+ match &self.0 {
+ RevokeTarget::Dispatcher(key_sentinel) => key_sentinel.clear(),
+ RevokeTarget::StateMachine(sender) => sender.purge_revoked(partitions),
+ }
+ }
+
+ /// Whether purged messages never complete, so the consumer must drop the
+ /// in-flight polls that hold a revoked partition.
+ pub fn drops_revoked_polls(&self) -> bool {
+ matches!(self.0, RevokeTarget::StateMachine(_))
+ }
+}
+
/// 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 {
+struct DispatcherBatcher {
inner: Arc<BatcherInner>,
flush_queue: mpsc::UnboundedSender<FlushTicket>,
- parked_retry_pump: Option<JoinHandle<()>>,
}
-impl Batcher {
- pub fn new(
+impl DispatcherBatcher {
+ fn new(
dispatcher: Arc<Dispatcher>,
transport: Arc<GrpcTransport>,
handle: Handle,
deferred_flush_timeout: Duration,
- parked_retry_interval: Duration,
) -> (Self, BatcherOutputs) {
let (completions_tx, completions_rx) = mpsc::unbounded_channel();
let (errors_tx, errors_rx) = mpsc::unbounded_channel();
@@ -148,19 +326,10 @@ impl Batcher {
dispatcher,
transport,
assignment_epoch,
- accepted_messages: AtomicU64::new(0),
completions: completions_tx,
errors: errors_tx,
});
let (flush_queue, flush_rx) = mpsc::unbounded_channel();
- let parked_retry_pump = (inner.dispatcher.scheduler_kind() == SchedulerKind::KeyTable)
- .then(|| {
- tokio::spawn(run_parked_retry_pump(
- Arc::clone(&inner),
- parked_retry_interval,
- deferred_flush_timeout,
- ))
- });
tokio::spawn(run_flush_driver(
Arc::clone(&inner),
flush_rx,
@@ -168,11 +337,7 @@ impl Batcher {
deferred_flush_timeout,
));
(
- Self {
- inner,
- flush_queue,
- parked_retry_pump,
- },
+ Self { inner, flush_queue },
BatcherOutputs {
completions: completions_rx,
errors: errors_rx,
@@ -180,17 +345,10 @@ impl Batcher {
)
}
- /// 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> {
+ fn key_order_sentinel(&self) -> Arc<KeyOrderSentinel> {
self.inner.dispatcher.key_order_sentinel()
}
- /// The dispatcher, for the consumer's revocation hook.
- pub fn dispatcher(&self) -> Arc<Dispatcher> {
- Arc::clone(&self.inner.dispatcher)
- }
-
/// 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.
@@ -204,7 +362,7 @@ impl Batcher {
/// 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 {
+ 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);
@@ -238,14 +396,6 @@ impl Batcher {
}
}
-impl Drop for Batcher {
- fn drop(&mut self) {
- if let Some(pump) = self.parked_retry_pump.take() {
- pump.abort();
- }
- }
-}
-
/// 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.
@@ -332,11 +482,6 @@ async fn await_settled(
match pending.wait().await {
Ok(accepted) => {
- if accepted > 0 {
- inner
- .accepted_messages
- .fetch_add(accepted as u64, Ordering::Relaxed);
- }
// Advance ACK high-water marks before the settle, which
// may evict the keys' sentinel state.
inner.dispatcher.on_sub_batch_acked(&key_offsets);
@@ -429,66 +574,6 @@ fn spawn_followups(
}
}
-/// The key table's retry driver: fire the parked-retry deadline on an
-/// interval. Parked keys are the ones no settlement can release, so the
-/// pump is their only retry path. Its stall watchdog matches the flush
-/// driver's: acceptance resets the deadline, and pending work with zero
-/// acceptance for a full window fails the process, so a wedged key table
-/// restarts loudly instead of growing lag silently.
-async fn run_parked_retry_pump(
- inner: Arc<BatcherInner>,
- interval: Duration,
- stall_timeout: Duration,
-) {
- let mut ticker = tokio::time::interval(interval);
- ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
- let mut seen_accepted = 0u64;
- let mut stall_deadline = Instant::now() + stall_timeout;
- loop {
- ticker.tick().await;
-
- // Check the stall before this tick's retries. Acceptance or full
- // idleness resets the clock. Once the deadline expires, stop starting
- // parked retries so overlapping failures must converge to zero
- // outstanding; then report the stall. An already in-flight send may
- // still be healthy but slow, so let it settle: acceptance resets the
- // deadline, while failure leaves queued work with nothing outstanding
- // and trips the watchdog on the next tick.
- let accepted = inner.accepted_messages.load(Ordering::Relaxed);
- let (queued, outstanding) = inner.dispatcher.key_work().unwrap_or((0, 0));
- let now = Instant::now();
- if accepted != seen_accepted || (queued == 0 && outstanding == 0) {
- seen_accepted = accepted;
- stall_deadline = now + stall_timeout;
- } else if now >= stall_deadline {
- if queued > 0 && outstanding == 0 {
- inner.report_error(
- "key-table work made no progress within the stall timeout".to_string(),
- );
- return;
- }
- continue;
- }
-
- // A retried send may replay a failed run, so it goes on the wire
- // with the replay flag, like a deferred flush.
- let settle_id = make_batch_id();
- let pending = inner.dispatcher.parked_retry_and_send(|sub_batch| {
- begin_send(&inner.transport, &settle_id, sub_batch, true)
- });
- let epoch = inner.assignment_epoch.current();
- for sub_batch in pending {
- drop(tokio::spawn(await_settled(
- Arc::clone(&inner),
- settle_id.clone(),
- sub_batch,
- false,
- epoch,
- )));
- }
- }
-}
-
/// 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
diff --git a/rust/ingestion-consumer/src/batcher/request.rs b/rust/ingestion-consumer/src/batcher/request.rs
new file mode 100644
index 000000000000..c1169ef6ff96
--- /dev/null
+++ b/rust/ingestion-consumer/src/batcher/request.rs
@@ -0,0 +1,33 @@
+//! A request on the wire: claimed key runs of one class.
+
+use std::time::Instant;
+
+use super::key_queues::{KeyRun, ReadyRun};
+
+/// Applies to every message of a request, so a request never mixes classes.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub struct RequestClass {
+ pub assignment_epoch: u64,
+ pub replay: bool,
+}
+
+#[derive(Debug)]
+pub struct Request {
+ pub class: RequestClass,
+ pub runs: Vec<KeyRun>,
+ pub message_count: usize,
+ pub bytes: usize,
+ pub oldest_arrival: Instant,
+}
+
+impl Request {
+ pub fn from_run(ready: ReadyRun) -> Self {
+ Self {
+ class: ready.class,
+ message_count: ready.run.messages.len(),
+ bytes: ready.bytes,
+ oldest_arrival: ready.first_arrival,
+ runs: vec![ready.run],
+ }
+ }
+}
diff --git a/rust/ingestion-consumer/src/batcher/retry_policy.rs b/rust/ingestion-consumer/src/batcher/retry_policy.rs
new file mode 100644
index 000000000000..eac45b3a1a47
--- /dev/null
+++ b/rust/ingestion-consumer/src/batcher/retry_policy.rs
@@ -0,0 +1,55 @@
+//! When each kind of retry fires.
+
+use std::time::{Duration, Instant};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum RetryReason {
+ Fault,
+ Busy,
+ /// Nothing signals a worker joining the pool, so placement polls for one.
+ NoWorker,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct RetryPolicy {
+ fault: Duration,
+ busy: Duration,
+ no_worker: Duration,
+}
+
+impl RetryPolicy {
+ pub fn new(fault: Duration, busy: Duration, no_worker: Duration) -> Result<Self, String> {
+ // Zero would wake the state machine on every action.
+ if no_worker.is_zero() {
+ return Err("the no-worker retry delay must be > 0".to_string());
+ }
+ Ok(Self {
+ fault,
+ busy,
+ no_worker,
+ })
+ }
+
+ pub fn uniform(delay: Duration) -> Result<Self, String> {
+ Self::new(delay, delay, delay)
+ }
+
+ pub fn retry_at(&self, now: Instant, reason: RetryReason) -> Instant {
+ let delay = match reason {
+ RetryReason::Fault => self.fault,
+ RetryReason::Busy => self.busy,
+ RetryReason::NoWorker => self.no_worker,
+ };
+ now + delay
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_zero_no_worker_delay_is_rejected() {
+ assert!(RetryPolicy::uniform(Duration::ZERO).is_err());
+ }
+}
diff --git a/rust/ingestion-consumer/src/batcher/state_machine.rs b/rust/ingestion-consumer/src/batcher/state_machine.rs
new file mode 100644
index 000000000000..da760ba6d0b9
--- /dev/null
+++ b/rust/ingestion-consumer/src/batcher/state_machine.rs
@@ -0,0 +1,1148 @@
+//! Decides which key runs go to which worker, and when. The batcher task
+//! feeds it polls, worker responses, retry wakeups, revokes and shutdown,
+//! and performs the [`Effects`] each action returns. The state machine does
+//! no I/O.
+//!
+//! The caller performs one action's effects in this order: order-sentinel
+//! ACKs before evictions, then the sends in the order given, which is each
+//! key's send order. `next_wakeup` replaces the previous wakeup; `None` needs
+//! no timer. `fatal` means the state machine failed and the process must
+//! exit and replay.
+//!
+//! When work is pending, nothing is in flight, and no message was accepted
+//! for `stall_timeout`, the state machine fails, so a wedged batcher restarts
+//! instead of growing lag.
+
+use std::cmp::Reverse;
+use std::collections::HashMap;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use common_kafka_consumer::{GroupCompletion, Offset, Partition};
+use metrics::{gauge, histogram};
+
+use super::in_flight::{InFlightRequest, InFlightRequests, RequestId, SentRun};
+use super::key_queues::{KeyQueues, KeyRun};
+use super::request::{Request, RequestClass};
+use super::retry_policy::{RetryPolicy, RetryReason};
+use super::worker_assigner::WorkerAssigner;
+use crate::types::SerializedKafkaMessage;
+use crate::worker_registry::WorkerId;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum FailureCause {
+ Fault,
+ Busy,
+}
+
+#[derive(Debug)]
+pub struct SendRequest {
+ pub request: RequestId,
+ pub worker: WorkerId,
+ pub class: RequestClass,
+ pub runs: Vec<KeyRun>,
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub struct KeyAck {
+ pub routing_key: Arc<str>,
+ pub max_offset: i64,
+}
+
+#[derive(Debug, PartialEq, Eq)]
+pub struct WorkerOutcome {
+ pub worker: WorkerId,
+ pub fault: bool,
+}
+
+#[derive(Debug, Default)]
+pub struct Effects {
+ pub sends: Vec<SendRequest>,
+ pub completions: Vec<GroupCompletion>,
+ pub key_acks: Vec<KeyAck>,
+ pub evicted_keys: Vec<Arc<str>>,
+ pub worker_outcomes: Vec<WorkerOutcome>,
+ /// A draining worker listed here has finished its work.
+ pub idle_workers: Vec<WorkerId>,
+ pub busy_workers: Vec<WorkerId>,
+ pub fatal: Option<String>,
+ pub next_wakeup: Option<Instant>,
+}
+
+pub enum BatcherStateMachine {
+ Running(ActiveState),
+ Draining(ActiveState),
+ Stopped,
+ Failed,
+}
+
+impl BatcherStateMachine {
+ pub fn new(
+ assigner: WorkerAssigner,
+ retry: RetryPolicy,
+ stall_timeout: Duration,
+ now: Instant,
+ ) -> Result<Self, String> {
+ if stall_timeout.is_zero() {
+ return Err("stall_timeout must be > 0".to_string());
+ }
+ Ok(BatcherStateMachine::Running(ActiveState {
+ keys: KeyQueues::new(),
+ assigner,
+ in_flight: InFlightRequests::new(),
+ retry,
+ stall_timeout,
+ last_progress: now,
+ }))
+ }
+
+ pub fn on_groups(
+ self,
+ now: Instant,
+ workers: &[WorkerId],
+ assignment_epoch: u64,
+ runs: Vec<KeyRun>,
+ ) -> (Self, Effects) {
+ match self {
+ BatcherStateMachine::Running(mut active) => {
+ let result = active.on_groups(now, workers, assignment_epoch, runs);
+ Self::after(active, false, result)
+ }
+ BatcherStateMachine::Draining(_) | BatcherStateMachine::Stopped => {
+ Self::failed("groups submitted after shutdown started".to_string())
+ }
+ BatcherStateMachine::Failed => (BatcherStateMachine::Failed, Effects::default()),
+ }
+ }
+
+ pub fn on_request_succeeded(
+ self,
+ now: Instant,
+ workers: &[WorkerId],
+ request: RequestId,
+ accepted: u32,
+ ) -> (Self, Effects) {
+ self.act(|active| active.on_request_succeeded(now, workers, request, accepted))
+ }
+
+ /// A worker accepts a whole request or none of it. The failed request's
+ /// messages go back to the front of their keys' queues and are sent again
+ /// as replay after the retry delay.
+ pub fn on_request_failed(
+ self,
+ now: Instant,
+ workers: &[WorkerId],
+ request: RequestId,
+ cause: FailureCause,
+ messages: Vec<SerializedKafkaMessage>,
+ ) -> (Self, Effects) {
+ self.act(|active| active.on_request_failed(now, workers, request, cause, messages))
+ }
+
+ pub fn on_wakeup(self, now: Instant, workers: &[WorkerId]) -> (Self, Effects) {
+ self.act(|active| {
+ let mut effects = Effects::default();
+ active.advance(now, workers, &mut effects)?;
+ Ok(effects)
+ })
+ }
+
+ /// The new owner replays the revoked partitions, so their pending
+ /// messages drop. Runs already in flight finish; if they fail, their
+ /// messages of revoked partitions drop too.
+ pub fn on_partitions_revoked(
+ self,
+ now: Instant,
+ partitions: &[(String, i32)],
+ ) -> (Self, Effects) {
+ self.act(|active| active.on_partitions_revoked(now, partitions))
+ }
+
+ /// Takes no new groups from now on, and stops once nothing is pending or
+ /// in flight.
+ pub fn on_shutdown(self, now: Instant, workers: &[WorkerId]) -> (Self, Effects) {
+ match self {
+ BatcherStateMachine::Running(active) | BatcherStateMachine::Draining(active) => {
+ BatcherStateMachine::Draining(active).on_wakeup(now, workers)
+ }
+ other => (other, Effects::default()),
+ }
+ }
+
+ pub fn pending_messages(&self) -> usize {
+ self.active().map_or(0, ActiveState::pending_messages)
+ }
+
+ pub fn in_flight_messages(&self) -> usize {
+ self.active()
+ .map_or(0, |active| active.assigner.in_flight_messages())
+ }
+
+ fn active(&self) -> Option<&ActiveState> {
+ match self {
+ BatcherStateMachine::Running(active) | BatcherStateMachine::Draining(active) => {
+ Some(active)
+ }
+ BatcherStateMachine::Stopped | BatcherStateMachine::Failed => None,
+ }
+ }
+
+ fn act(
+ self,
+ action: impl FnOnce(&mut ActiveState) -> Result<Effects, String>,
+ ) -> (Self, Effects) {
+ match self {
+ BatcherStateMachine::Running(mut active) => {
+ let result = action(&mut active);
+ Self::after(active, false, result)
+ }
+ BatcherStateMachine::Draining(mut active) => {
+ let result = action(&mut active);
+ Self::after(active, true, result)
+ }
+ finished => (finished, Effects::default()),
+ }
+ }
+
+ fn after(
+ active: ActiveState,
+ draining: bool,
+ result: Result<Effects, String>,
+ ) -> (Self, Effects) {
+ match result {
+ Err(reason) => Self::failed(reason),
+ Ok(effects) if draining && active.is_drained() => (
+ BatcherStateMachine::Stopped,
+ Effects {
+ next_wakeup: None,
+ ..effects
+ },
+ ),
+ Ok(effects) if draining => (BatcherStateMachine::Draining(active), effects),
+ Ok(effects) => (BatcherStateMachine::Running(active), effects),
+ }
+ }
+
+ fn failed(reason: String) -> (Self, Effects) {
+ (
+ BatcherStateMachine::Failed,
+ Effects {
+ fatal: Some(reason),
+ ..Effects::default()
+ },
+ )
+ }
+}
+
+pub struct ActiveState {
+ keys: KeyQueues,
+ assigner: WorkerAssigner,
+ in_flight: InFlightRequests,
+ retry: RetryPolicy,
+ stall_timeout: Duration,
+ last_progress: Instant,
+}
+
+impl ActiveState {
+ fn pending_messages(&self) -> usize {
+ self.keys.queued_messages()
+ }
+
+ /// The stall clock starts when work becomes pending, not at the last
+ /// action before a quiet period.
+ fn restart_stall_clock_if_quiet(&mut self, now: Instant) {
+ if self.pending_messages() == 0 && self.in_flight.is_empty() {
+ self.last_progress = now;
+ }
+ }
+
+ fn is_drained(&self) -> bool {
+ self.pending_messages() == 0 && self.in_flight.is_empty()
+ }
+
+ fn on_groups(
+ &mut self,
+ now: Instant,
+ workers: &[WorkerId],
+ assignment_epoch: u64,
+ runs: Vec<KeyRun>,
+ ) -> Result<Effects, String> {
+ self.restart_stall_clock_if_quiet(now);
+ for run in runs {
+ self.keys
+ .push(run.routing_key, assignment_epoch, run.messages, now);
+ }
+ let mut effects = Effects::default();
+ self.advance(now, workers, &mut effects)?;
+ Ok(effects)
+ }
+
+ fn on_request_succeeded(
+ &mut self,
+ now: Instant,
+ workers: &[WorkerId],
+ request: RequestId,
+ accepted: u32,
+ ) -> Result<Effects, String> {
+ let mut effects = Effects::default();
+ let sent = self.take_request(request, &mut effects)?;
+ if accepted as usize != sent.message_count {
+ return Err(format!(
+ "worker accepted {accepted} of {} messages",
+ sent.message_count
+ ));
+ }
+ effects.worker_outcomes.push(WorkerOutcome {
+ worker: sent.worker.clone(),
+ fault: false,
+ });
+ if accepted > 0 {
+ self.last_progress = now;
+ }
+ let assignment_epoch = sent.class.assignment_epoch;
+ let runs = sent.accepted();
+ effects.completions = completions(assignment_epoch, &runs);
+ effects.key_acks = key_acks(&runs);
+ for run in runs {
+ self.settle_key(&run.routing_key, Vec::new(), None, now, &mut effects)?;
+ }
+ self.advance(now, workers, &mut effects)?;
+ Ok(effects)
+ }
+
+ fn on_request_failed(
+ &mut self,
+ now: Instant,
+ workers: &[WorkerId],
+ request: RequestId,
+ cause: FailureCause,
+ messages: Vec<SerializedKafkaMessage>,
+ ) -> Result<Effects, String> {
+ let mut effects = Effects::default();
+ let sent = self.take_request(request, &mut effects)?;
+ effects.worker_outcomes.push(WorkerOutcome {
+ worker: sent.worker.clone(),
+ fault: cause == FailureCause::Fault,
+ });
+ let runs = sent.hand_back(messages)?;
+ let retry_at = self.retry.retry_at(
+ now,
+ match cause {
+ FailureCause::Fault => RetryReason::Fault,
+ FailureCause::Busy => RetryReason::Busy,
+ },
+ );
+ for run in runs {
+ self.settle_key(
+ &run.routing_key,
+ run.messages,
+ Some(retry_at),
+ now,
+ &mut effects,
+ )?;
+ }
+ self.advance(now, workers, &mut effects)?;
+ Ok(effects)
+ }
+
+ fn on_partitions_revoked(
+ &mut self,
+ now: Instant,
+ partitions: &[(String, i32)],
+ ) -> Result<Effects, String> {
+ let mut effects = Effects {
+ evicted_keys: self.keys.purge(partitions),
+ ..Effects::default()
+ };
+ self.finish(now, &mut effects)?;
+ if self.keys.has_ready() {
+ effects.next_wakeup = Some(now);
+ }
+ Ok(effects)
+ }
+
+ fn take_request(
+ &mut self,
+ request: RequestId,
+ effects: &mut Effects,
+ ) -> Result<InFlightRequest, String> {
+ let sent = self
+ .in_flight
+ .take(request)
+ .ok_or_else(|| format!("response for unknown request {request:?}"))?;
+ if self.assigner.release(&sent.worker, sent.message_count) {
+ effects.idle_workers.push(sent.worker.clone());
+ }
+ Ok(sent)
+ }
+
+ fn settle_key(
+ &mut self,
+ routing_key: &Arc<str>,
+ requeued: Vec<SerializedKafkaMessage>,
+ retry_at: Option<Instant>,
+ now: Instant,
+ effects: &mut Effects,
+ ) -> Result<(), String> {
+ let evicted = self
+ .keys
+ .settle(routing_key, requeued, retry_at, now)
+ .map_err(|err| err.to_string())?;
+ if evicted {
+ effects.evicted_keys.push(Arc::clone(routing_key));
+ }
+ Ok(())
+ }
+
+ fn advance(
+ &mut self,
+ now: Instant,
+ workers: &[WorkerId],
+ effects: &mut Effects,
+ ) -> Result<(), String> {
+ self.restart_stall_clock_if_quiet(now);
+ // Past the stall deadline no new request starts, so overlapping
+ // failures drain to nothing in flight and the watchdog can fire.
+ let stalled = self.pending_messages() > 0 && now >= self.last_progress + self.stall_timeout;
+ if !stalled {
+ self.place(now, workers, effects)?;
+ }
+ self.finish(now, effects)
+ }
+
+ fn place(
+ &mut self,
+ now: Instant,
+ workers: &[WorkerId],
+ effects: &mut Effects,
+ ) -> Result<(), String> {
+ let free_slots = self.assigner.free_slots(workers);
+ let mut batch: Vec<Request> = self
+ .keys
+ .take_ready(now, free_slots)
+ .into_iter()
+ .map(Request::from_run)
+ .collect();
+ if self.assigner.prefers_largest_first() {
+ // Bin-packing places the heavy requests first, so they drive
+ // the load distribution.
+ batch.sort_by_key(|request| Reverse(request.message_count));
+ }
+ for request in batch {
+ let worker = self
+ .assigner
+ .assign(workers, request.message_count)
+ .ok_or("no worker took a request within the free slots")?;
+ if self.assigner.requests_on(&worker) == 1 {
+ effects.busy_workers.push(worker.clone());
+ }
+ self.send(now, worker, request, effects);
+ }
+ Ok(())
+ }
+
+ fn send(&mut self, now: Instant, worker: WorkerId, request: Request, effects: &mut Effects) {
+ let kind = if request.class.replay {
+ "replay"
+ } else {
+ "fresh"
+ };
+ histogram!("ingestion_consumer_request_events").record(request.message_count as f64);
+ histogram!("ingestion_consumer_request_bytes").record(request.bytes as f64);
+ histogram!("ingestion_consumer_request_queue_wait_seconds", "kind" => kind).record(
+ now.saturating_duration_since(request.oldest_arrival)
+ .as_secs_f64(),
+ );
+ let id = self
+ .in_flight
+ .register(worker.clone(), request.class, &request.runs);
+ effects.sends.push(SendRequest {
+ request: id,
+ worker,
+ class: request.class,
+ runs: request.runs,
+ });
+ }
+
+ fn finish(&mut self, now: Instant, effects: &mut Effects) -> Result<(), String> {
+ // A stalled action and a revoke skip `take_ready`, so without this a due
+ // retry would set the next wakeup at or before `now`.
+ self.keys.promote_due(now);
+ let pending = self.pending_messages();
+ let in_flight = self.in_flight.len();
+ if pending == 0 && in_flight == 0 {
+ self.last_progress = now;
+ }
+ self.record_gauges();
+ let stall_deadline = self.last_progress + self.stall_timeout;
+ if pending > 0 && in_flight == 0 && now >= stall_deadline {
+ return Err("pending work made no progress within the stall timeout".to_string());
+ }
+ effects.next_wakeup = [
+ self.keys.next_retry_at(),
+ self.keys
+ .has_ready()
+ .then(|| self.retry.retry_at(now, RetryReason::NoWorker)),
+ (pending > 0 && in_flight == 0).then_some(stall_deadline),
+ ]
+ .into_iter()
+ .flatten()
+ .min();
+ Ok(())
+ }
+
+ fn record_gauges(&self) {
+ gauge!("ingestion_consumer_batcher_keys").set(self.keys.key_count() as f64);
+ gauge!("ingestion_consumer_batcher_queued_messages")
+ .set(self.keys.queued_messages() as f64);
+ gauge!("ingestion_consumer_batcher_queued_bytes").set(self.keys.queued_bytes() as f64);
+ gauge!("ingestion_consumer_batcher_claimed_keys").set(self.keys.claimed_keys() as f64);
+ gauge!("ingestion_consumer_batcher_waiting_keys").set(self.keys.waiting_keys() as f64);
+ gauge!("ingestion_consumer_batcher_in_flight_requests").set(self.in_flight.len() as f64);
+ }
+}
+
+fn completions(assignment_epoch: u64, runs: &[SentRun]) -> Vec<GroupCompletion> {
+ let mut by_partition: HashMap<i32, Vec<Offset>> = HashMap::new();
+ for run in runs {
+ for message in &run.messages {
+ by_partition
+ .entry(message.partition)
+ .or_default()
+ .push(Offset(message.offset));
+ }
+ }
+ let mut completions: Vec<GroupCompletion> = by_partition
+ .into_iter()
+ .map(|(partition, offsets)| GroupCompletion {
+ partition: Partition(partition),
+ assignment_epoch,
+ accepted: offsets.len() as u32,
+ offsets,
+ })
+ .collect();
+ completions.sort_by_key(|completion| completion.partition.0);
+ completions
+}
+
+fn key_acks(runs: &[SentRun]) -> Vec<KeyAck> {
+ runs.iter()
+ .filter_map(|run| {
+ let max_offset = run
+ .messages
+ .iter()
+ // An unkeyed message lives on an arbitrary partition under a
+ // synthetic key, so it does not advance an ACK high-water mark.
+ .filter(|message| message.keyed)
+ .map(|message| message.offset)
+ .max()?;
+ Some(KeyAck {
+ routing_key: Arc::clone(&run.routing_key),
+ max_offset,
+ })
+ })
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::VecDeque;
+
+ use super::*;
+ use crate::batcher::test_support::{message, offsets};
+ use crate::routing::{Router, RoutingStrategy};
+
+ const FAULT_DELAY: Duration = Duration::from_millis(200);
+ const BUSY_DELAY: Duration = Duration::from_millis(20);
+ const NO_WORKER_DELAY: Duration = Duration::from_millis(100);
+ const STALL: Duration = Duration::from_secs(60);
+
+ /// Distinct delays, so a wakeup time shows which retry reason applied.
+ fn retry_policy() -> RetryPolicy {
+ RetryPolicy::new(FAULT_DELAY, BUSY_DELAY, NO_WORKER_DELAY).expect("valid retry policy")
+ }
+
+ fn batcher(max_requests_per_worker: usize, now: Instant) -> BatcherStateMachine {
+ let assigner = WorkerAssigner::new(
+ Router::new(RoutingStrategy::BinPack),
+ max_requests_per_worker,
+ )
+ .expect("valid request cap");
+ BatcherStateMachine::new(assigner, retry_policy(), STALL, now).expect("valid stall timeout")
+ }
+
+ fn pool(workers: &[&str]) -> Vec<WorkerId> {
+ workers.iter().map(|w| WorkerId::from(*w)).collect()
+ }
+
+ fn run(key: &str, offsets: &[i64]) -> KeyRun {
+ KeyRun {
+ routing_key: key.into(),
+ messages: offsets
+ .iter()
+ .map(|&offset| message(key, 0, offset))
+ .collect(),
+ }
+ }
+
+ fn shape(send: &SendRequest) -> Vec<(&str, Vec<i64>)> {
+ send.runs
+ .iter()
+ .map(|run| (&*run.routing_key, offsets(&run.messages)))
+ .collect()
+ }
+
+ fn sent_messages(send: &SendRequest) -> Vec<SerializedKafkaMessage> {
+ send.runs
+ .iter()
+ .flat_map(|run| run.messages.iter().cloned())
+ .collect()
+ }
+
+ #[test]
+ fn each_key_run_is_its_own_request_and_its_next_run_waits_for_the_response() {
+ let now = Instant::now();
+ let workers = pool(&["w"]);
+ let batcher = batcher(4, now);
+
+ let (batcher, effects) =
+ batcher.on_groups(now, &workers, 0, vec![run("a", &[1]), run("b", &[2])]);
+ assert_eq!(
+ effects.sends.iter().map(shape).collect::<Vec<_>>(),
+ vec![vec![("a", vec![1])], vec![("b", vec![2])]]
+ );
+ let request = effects.sends[0].request;
+
+ let (batcher, effects) = batcher.on_groups(now, &workers, 0, vec![run("a", &[3])]);
+ assert!(effects.sends.is_empty(), "a's first run is still in flight");
+
+ let (_, effects) = batcher.on_request_succeeded(now, &workers, request, 1);
+ assert_eq!(shape(&effects.sends[0]), vec![("a", vec![3])]);
+ assert_eq!(effects.completions.len(), 1);
+ assert_eq!(effects.completions[0].offsets, vec![Offset(1)]);
+ assert_eq!(
+ effects.key_acks,
+ vec![KeyAck {
+ routing_key: "a".into(),
+ max_offset: 1
+ }]
+ );
+ }
+
+ #[test]
+ fn a_key_arriving_under_a_new_epoch_stays_one_run_out() {
+ let now = Instant::now();
+ let workers = pool(&["w"]);
+ let batcher = batcher(4, now);
+
+ let (batcher, effects) = batcher.on_groups(now, &workers, 1, vec![run("k", &[1])]);
+ assert_eq!(effects.sends[0].class.assignment_epoch, 1);
+ let request = effects.sends[0].request;
+ let (batcher, effects) = batcher.on_groups(now, &workers, 2, vec![run("k", &[2])]);
+ assert!(
+ effects.sends.is_empty(),
+ "the epoch-2 message waits for k's run"
+ );
+
+ let (_, effects) = batcher.on_request_succeeded(now, &workers, request, 1);
+ assert_eq!(effects.sends[0].class.assignment_epoch, 2);
+ assert_eq!(shape(&effects.sends[0]), vec![("k", vec![2])]);
+ }
+
+ #[test]
+ fn a_transport_failure_retries_as_replay_after_the_fault_delay() {
+ let now = Instant::now();
+ let workers = pool(&["w"]);
+ let batcher = batcher(4, now);
+ let (batcher, effects) = batcher.on_groups(now, &workers, 0, vec![run("a", &[1])]);
+ let request = effects.sends[0].request;
+
+ let messages = vec![message("a", 0, 1)];
+ let (batcher, effects) =
+ batcher.on_request_failed(now, &workers, request, FailureCause::Fault, messages);
+ assert_eq!(
+ effects.worker_outcomes,
+ vec![WorkerOutcome {
+ worker: WorkerId::from("w"),
+ fault: true
+ }]
+ );
+ assert!(effects.completions.is_empty());
+ assert!(effects.sends.is_empty());
+ assert_eq!(effects.next_wakeup, Some(now + FAULT_DELAY));
+
+ let (_, effects) = batcher.on_wakeup(now + FAULT_DELAY, &workers);
+ assert!(effects.sends[0].class.replay);
+ assert_eq!(shape(&effects.sends[0]), vec![("a", vec![1])]);
+ }
+
+ #[test]
+ fn a_revoke_after_a_retry_time_passed_asks_for_a_wakeup_now() {
+ let now = Instant::now();
+ let workers = pool(&["w"]);
+ let batcher = batcher(4, now);
+ let (batcher, effects) = batcher.on_groups(now, &workers, 0, vec![run("a", &[1])]);
+ let request = effects.sends[0].request;
+ let (batcher, _) = batcher.on_request_failed(
+ now,
+ &workers,
+ request,
+ FailureCause::Busy,
+ vec![message("a", 0, 1)],
+ );
+
+ let late = now + BUSY_DELAY * 3;
+ let (_, effects) = batcher.on_partitions_revoked(late, &[("events".to_string(), 9)]);
+ assert_eq!(effects.next_wakeup, Some(late));
+ }
+
+ #[test]
+ fn bin_packing_places_the_largest_request_first() {
+ let now = Instant::now();
+ let workers = pool(&["w1", "w2"]);
+ let batcher = batcher(4, now);
+
+ let (_, effects) = batcher.on_groups(
+ now,
+ &workers,
+ 0,
+ vec![run("small", &[1]), run("large", &[2, 3, 4])],
+ );
+ let placed: Vec<_> = effects
+ .sends
+ .iter()
+ .map(|send| (&*send.runs[0].routing_key, send.worker.as_ref()))
+ .collect();
+ assert_eq!(placed, vec![("large", "w1"), ("small", "w2")]);
+ }
+
+ #[test]
+ fn a_request_without_a_worker_waits_and_is_sent_when_one_appears() {
+ let now = Instant::now();
+ let batcher = batcher(4, now);
+
+ let (batcher, effects) = batcher.on_groups(now, &pool(&[]), 0, vec![run("a", &[1])]);
+ assert!(effects.sends.is_empty());
+ assert_eq!(batcher.pending_messages(), 1);
+ assert_eq!(effects.next_wakeup, Some(now + NO_WORKER_DELAY));
+
+ let (_, effects) = batcher.on_wakeup(now + NO_WORKER_DELAY, &pool(&["w"]));
+ assert_eq!(shape(&effects.sends[0]), vec![("a", vec![1])]);
+ }
+
+ #[test]
+ fn the_request_cap_holds_sends_until_a_slot_frees() {
+ let now = Instant::now();
+ let workers = pool(&["w"]);
+ let batcher = batcher(1, now);
+
+ let (batcher, effects) =
+ batcher.on_groups(now, &workers, 0, vec![run("a", &[1]), run("b", &[2])]);
+ assert_eq!(effects.sends.len(), 1);
+ let request = effects.sends[0].request;
+ let (batcher, _) = batcher.on_groups(now, &workers, 0, vec![run("b", &[3])]);
+
+ let (_, effects) = batcher.on_request_succeeded(now, &workers, request, 1);
+ assert_eq!(
+ shape(&effects.sends[0]),
+ vec![("b", vec![2, 3])],
+ "b was never claimed, so its later message joins the run"
+ );
+ // The freed slot is refilled in the same action, so the worker is
+ // reported idle and then busy again.
+ assert_eq!(effects.idle_workers, vec![WorkerId::from("w")]);
+ assert_eq!(effects.busy_workers, vec![WorkerId::from("w")]);
+ }
+
+ #[test]
+ fn a_worker_is_busy_from_its_first_request_until_its_last_settles() {
+ let now = Instant::now();
+ let workers = pool(&["w"]);
+ let batcher = batcher(2, now);
+
+ let (batcher, effects) =
+ batcher.on_groups(now, &workers, 0, vec![run("a", &[1]), run("b", &[2])]);
+ assert_eq!(effects.sends.len(), 2);
+ assert_eq!(effects.busy_workers, vec![WorkerId::from("w")]);
+ let (first, second) = (effects.sends[0].request, effects.sends[1].request);
+
+ let (batcher, effects) = batcher.on_request_succeeded(now, &workers, first, 1);
+ assert!(effects.idle_workers.is_empty());
+
+ let (_, effects) = batcher.on_request_succeeded(now, &workers, second, 1);
+ assert_eq!(effects.idle_workers, vec![WorkerId::from("w")]);
+ }
+
+ #[test]
+ fn a_revoke_drops_pending_messages_and_never_sends_them() {
+ let now = Instant::now();
+ let batcher = batcher(4, now);
+ let (batcher, effects) = batcher.on_groups(now, &pool(&[]), 0, vec![run("a", &[1])]);
+ assert!(effects.sends.is_empty());
+
+ let (batcher, effects) = batcher.on_partitions_revoked(now, &[("events".to_string(), 0)]);
+ assert!(effects.sends.is_empty());
+ assert_eq!(effects.evicted_keys, vec![Arc::<str>::from("a")]);
+ assert_eq!(batcher.pending_messages(), 0);
+
+ let (_, effects) = batcher.on_wakeup(now + STALL / 2, &pool(&["w"]));
+ assert!(effects.sends.is_empty());
+ }
+
+ #[test]
+ fn shutdown_stops_once_drained() {
+ let now = Instant::now();
+ let workers = pool(&["w"]);
+ let batcher = batcher(4, now);
+ let (batcher, effects) = batcher.on_groups(now, &workers, 0, vec![run("a", &[1])]);
+ let request = effects.sends[0].request;
+
+ let (batcher, _) = batcher.on_shutdown(now, &workers);
+ assert!(matches!(batcher, BatcherStateMachine::Draining(_)));
+
+ let (batcher, effects) = batcher.on_request_succeeded(now, &workers, request, 1);
+ assert!(matches!(batcher, BatcherStateMachine::Stopped));
+ assert_eq!(effects.next_wakeup, None);
+ }
+
+ #[test]
+ fn a_second_shutdown_keeps_a_waiting_retrys_wakeup() {
+ let now = Instant::now();
+ let workers = pool(&["w"]);
+ let batcher = batcher(4, now);
+ let (batcher, effects) = batcher.on_groups(now, &workers, 0, vec![run("a", &[1])]);
+ let request = effects.sends[0].request;
+ let (batcher, _) = batcher.on_request_failed(
+ now,
+ &workers,
+ request,
+ FailureCause::Busy,
+ vec![message("a", 0, 1)],
+ );
+ let (batcher, _) = batcher.on_shutdown(now, &workers);
+
+ let (batcher, effects) = batcher.on_shutdown(now, &workers);
+ assert!(matches!(batcher, BatcherStateMachine::Draining(_)));
+ assert_eq!(effects.next_wakeup, Some(now + BUSY_DELAY));
+ }
+
+ #[test]
+ fn a_zero_stall_timeout_is_rejected() {
+ let assigner =
+ WorkerAssigner::new(Router::new(RoutingStrategy::BinPack), 1).expect("valid cap");
+ let created =
+ BatcherStateMachine::new(assigner, retry_policy(), Duration::ZERO, Instant::now());
+ assert!(created.is_err());
+ }
+
+ #[test]
+ fn work_stuck_without_progress_fails_the_state_machine() {
+ let now = Instant::now();
+ let batcher = batcher(4, now);
+ let (batcher, _) = batcher.on_groups(now, &pool(&[]), 0, vec![run("a", &[1])]);
+
+ let (batcher, effects) = batcher.on_wakeup(now + STALL, &pool(&[]));
+ assert!(matches!(batcher, BatcherStateMachine::Failed));
+ assert!(effects.fatal.is_some());
+ assert_eq!(effects.next_wakeup, None);
+ }
+
+ #[test]
+ fn a_passed_stall_deadline_with_a_request_in_flight_never_asks_for_a_past_wakeup() {
+ let now = Instant::now();
+ let workers = pool(&["w"]);
+ let batcher = batcher(1, now);
+ let (batcher, _) =
+ batcher.on_groups(now, &workers, 0, vec![run("a", &[1]), run("b", &[2])]);
+
+ let late = now + STALL * 2;
+ let (batcher, effects) = batcher.on_wakeup(late, &workers);
+ assert!(matches!(batcher, BatcherStateMachine::Running(_)));
+ assert!(effects.next_wakeup.is_some_and(|at| at > late));
+ }
+
+ #[test]
+ fn a_retry_due_past_the_stall_deadline_waits_the_no_worker_delay() {
+ let now = Instant::now();
+ let workers = pool(&["w1", "w2"]);
+ let (batcher, effects) =
+ batcher(1, now).on_groups(now, &workers, 0, vec![run("a", &[1]), run("b", &[2])]);
+ let a = effects
+ .sends
+ .iter()
+ .find(|send| &*send.runs[0].routing_key == "a")
+ .expect("a was sent")
+ .request;
+ let (batcher, _) = batcher.on_request_failed(
+ now + STALL - BUSY_DELAY / 2,
+ &workers,
+ a,
+ FailureCause::Busy,
+ vec![message("a", 0, 1)],
+ );
+
+ let late = now + STALL + BUSY_DELAY;
+ let (batcher, effects) = batcher.on_wakeup(late, &workers);
+ assert!(matches!(batcher, BatcherStateMachine::Running(_)));
+ assert_eq!(effects.next_wakeup, Some(late + NO_WORKER_DELAY));
+ }
+
+ #[test]
+ fn past_the_stall_deadline_no_new_request_starts_until_the_in_flight_one_settles() {
+ let now = Instant::now();
+ let workers = pool(&["w"]);
+ let batcher = batcher(1, now);
+ let (batcher, effects) =
+ batcher.on_groups(now, &workers, 0, vec![run("a", &[1]), run("b", &[2])]);
+ let request = effects.sends[0].request;
+
+ let late = now + STALL;
+ let (batcher, effects) = batcher.on_request_failed(
+ late,
+ &workers,
+ request,
+ FailureCause::Busy,
+ vec![message("a", 0, 1)],
+ );
+ assert!(effects.sends.is_empty(), "b stays unsent past the deadline");
+ assert!(matches!(batcher, BatcherStateMachine::Failed));
+ }
+
+ #[test]
+ fn an_idle_period_does_not_count_toward_a_stall() {
+ let start = Instant::now();
+ let workers = pool(&["w"]);
+ let batcher = batcher(4, start);
+
+ let arrival = start + STALL * 3;
+ let (batcher, effects) = batcher.on_groups(arrival, &workers, 0, vec![run("a", &[1])]);
+ assert!(matches!(batcher, BatcherStateMachine::Running(_)));
+ assert_eq!(shape(&effects.sends[0]), vec![("a", vec![1])]);
+ }
+
+ #[test]
+ fn a_worker_accepting_fewer_messages_than_sent_fails_the_state_machine() {
+ let now = Instant::now();
+ let workers = pool(&["w"]);
+ let batcher = batcher(4, now);
+ let (batcher, effects) = batcher.on_groups(now, &workers, 0, vec![run("a", &[1, 2])]);
+ let request = effects.sends[0].request;
+
+ let (batcher, effects) = batcher.on_request_succeeded(now, &workers, request, 1);
+ assert!(matches!(batcher, BatcherStateMachine::Failed));
+ assert!(effects.fatal.is_some());
+ }
+
+ #[test]
+ fn an_accepted_request_completes_each_partition_and_acks_only_keyed_messages() {
+ let now = Instant::now();
+ let workers = pool(&["w"]);
+ let batcher = batcher(4, now);
+ let keyed = KeyRun {
+ routing_key: "a".into(),
+ messages: vec![message("a", 0, 1), message("a", 1, 2)],
+ };
+ let unkeyed = KeyRun {
+ routing_key: ":2:5".into(),
+ messages: vec![SerializedKafkaMessage {
+ key: None,
+ ..message("unkeyed", 2, 5)
+ }],
+ };
+ let (batcher, effects) = batcher.on_groups(now, &workers, 0, vec![keyed, unkeyed]);
+ let (keyed_request, unkeyed_request) = (effects.sends[0].request, effects.sends[1].request);
+
+ let (batcher, effects) = batcher.on_request_succeeded(now, &workers, keyed_request, 2);
+ let completed: Vec<_> = effects
+ .completions
+ .iter()
+ .map(|completion| (completion.partition.0, completion.offsets.clone()))
+ .collect();
+ assert_eq!(completed, vec![(0, vec![Offset(1)]), (1, vec![Offset(2)])]);
+ assert_eq!(
+ effects.key_acks,
+ vec![KeyAck {
+ routing_key: "a".into(),
+ max_offset: 2
+ }]
+ );
+
+ let (_, effects) = batcher.on_request_succeeded(now, &workers, unkeyed_request, 1);
+ assert_eq!(effects.completions[0].offsets, vec![Offset(5)]);
+ assert!(effects.key_acks.is_empty());
+ }
+
+ #[test]
+ fn a_failed_run_spanning_a_revoked_partition_replays_only_the_kept_partition_in_order() {
+ let now = Instant::now();
+ let workers = pool(&["w"]);
+ let spanning = KeyRun {
+ routing_key: "a".into(),
+ messages: vec![message("a", 0, 1), message("a", 1, 7)],
+ };
+ let (batcher, effects) = batcher(4, now).on_groups(now, &workers, 0, vec![spanning]);
+ let (request, messages) = (effects.sends[0].request, sent_messages(&effects.sends[0]));
+ let later = KeyRun {
+ routing_key: "a".into(),
+ messages: vec![message("a", 1, 8)],
+ };
+ let (batcher, effects) = batcher.on_groups(now, &workers, 0, vec![later]);
+ assert!(effects.sends.is_empty());
+
+ let (batcher, effects) = batcher.on_partitions_revoked(now, &[("events".to_string(), 0)]);
+ assert!(effects.evicted_keys.is_empty(), "a's run is in flight");
+ let (batcher, _) =
+ batcher.on_request_failed(now, &workers, request, FailureCause::Fault, messages);
+
+ let retry_at = now + FAULT_DELAY;
+ let (batcher, effects) = batcher.on_wakeup(retry_at, &workers);
+ assert!(effects.sends[0].class.replay);
+ assert_eq!(shape(&effects.sends[0]), vec![("a", vec![7])]);
+ let replay = effects.sends[0].request;
+
+ let (_, effects) = batcher.on_request_succeeded(retry_at, &workers, replay, 1);
+ assert_eq!(effects.completions[0].offsets, vec![Offset(7)]);
+ assert!(!effects.sends[0].class.replay);
+ assert_eq!(shape(&effects.sends[0]), vec![("a", vec![8])]);
+ }
+
+ #[test]
+ fn a_revoke_then_reassign_drops_the_old_requeue_and_sends_the_new_epoch_run_once() {
+ let now = Instant::now();
+ let workers = pool(&["w"]);
+ let (batcher, effects) =
+ batcher(4, now).on_groups(now, &workers, 1, vec![run("a", &[1, 2])]);
+ let (request, messages) = (effects.sends[0].request, sent_messages(&effects.sends[0]));
+ let (batcher, _) = batcher.on_partitions_revoked(now, &[("events".to_string(), 0)]);
+ // The new owner of the partition replays the uncommitted offsets.
+ let (batcher, effects) = batcher.on_groups(now, &workers, 2, vec![run("a", &[1, 2, 3])]);
+ assert!(effects.sends.is_empty(), "a's epoch-1 run is still out");
+
+ let (batcher, effects) =
+ batcher.on_request_failed(now, &workers, request, FailureCause::Fault, messages);
+ assert_eq!(effects.sends.len(), 1, "the epoch-2 run goes at once");
+ assert_eq!(effects.sends[0].class.assignment_epoch, 2);
+ assert!(!effects.sends[0].class.replay);
+ assert_eq!(shape(&effects.sends[0]), vec![("a", vec![1, 2, 3])]);
+ let request = effects.sends[0].request;
+
+ let (batcher, effects) = batcher.on_request_succeeded(now, &workers, request, 3);
+ assert_eq!(effects.completions.len(), 1);
+ assert_eq!(effects.completions[0].assignment_epoch, 2);
+ assert_eq!(
+ effects.completions[0].offsets,
+ vec![Offset(1), Offset(2), Offset(3)]
+ );
+ assert_eq!(batcher.pending_messages(), 0);
+ assert_eq!(batcher.in_flight_messages(), 0);
+ }
+
+ #[test]
+ fn a_second_response_for_the_same_request_fails_the_state_machine() {
+ let now = Instant::now();
+ let workers = pool(&["w"]);
+ let (batcher, effects) = batcher(4, now).on_groups(now, &workers, 0, vec![run("a", &[1])]);
+ let request = effects.sends[0].request;
+ let (batcher, _) = batcher.on_request_succeeded(now, &workers, request, 1);
+
+ let (batcher, effects) = batcher.on_request_succeeded(now, &workers, request, 1);
+ assert!(matches!(batcher, BatcherStateMachine::Failed));
+ assert!(effects.fatal.is_some());
+ assert!(effects.completions.is_empty());
+ }
+
+ #[test]
+ fn a_failure_handing_back_extra_messages_fails_the_state_machine() {
+ let now = Instant::now();
+ let workers = pool(&["w"]);
+ let (batcher, effects) = batcher(4, now).on_groups(now, &workers, 0, vec![run("a", &[1])]);
+ let request = effects.sends[0].request;
+
+ let (batcher, effects) = batcher.on_request_failed(
+ now,
+ &workers,
+ request,
+ FailureCause::Fault,
+ vec![message("a", 0, 1), message("a", 0, 2)],
+ );
+ assert!(matches!(batcher, BatcherStateMachine::Failed));
+ assert!(effects.fatal.is_some());
+ }
+
+ #[test]
+ fn a_revoke_during_a_replay_wait_leaves_no_wait_behind_for_a_fresh_sibling_partition() {
+ let now = Instant::now();
+ let workers = pool(&["w"]);
+ let (batcher, effects) = batcher(4, now).on_groups(now, &workers, 0, vec![run("a", &[1])]);
+ let (request, messages) = (effects.sends[0].request, sent_messages(&effects.sends[0]));
+ let sibling = KeyRun {
+ routing_key: "a".into(),
+ messages: vec![message("a", 1, 7)],
+ };
+ let (batcher, _) = batcher.on_groups(now, &workers, 0, vec![sibling]);
+ let (batcher, _) =
+ batcher.on_request_failed(now, &workers, request, FailureCause::Fault, messages);
+
+ let (batcher, effects) = batcher.on_partitions_revoked(now, &[("events".to_string(), 0)]);
+ assert_eq!(effects.next_wakeup, Some(now), "a is ready again at once");
+ let (_, effects) = batcher.on_wakeup(now, &workers);
+ assert!(!effects.sends[0].class.replay);
+ assert_eq!(shape(&effects.sends[0]), vec![("a", vec![7])]);
+ }
+
+ #[test]
+ fn the_watchdog_fires_once_overlapping_failures_drain_even_with_waiting_retries() {
+ let now = Instant::now();
+ let workers = pool(&["w"]);
+ let (mut batcher, effects) =
+ batcher(2, now).on_groups(now, &workers, 0, vec![run("a", &[1]), run("b", &[2])]);
+ let mut outstanding: VecDeque<_> = effects
+ .sends
+ .iter()
+ .map(|send| (send.request, sent_messages(send)))
+ .collect();
+
+ let mut at = now;
+ let (failed, fired_at) = loop {
+ at += BUSY_DELAY;
+ assert!(at < now + STALL * 2, "the watchdog never fired");
+ let (request, messages) = outstanding.pop_front().expect("a request in flight");
+ let (next, effects) =
+ batcher.on_request_failed(at, &workers, request, FailureCause::Busy, messages);
+ if effects.fatal.is_some() {
+ break (next, at);
+ }
+ let (next, effects) = next.on_wakeup(at + BUSY_DELAY, &workers);
+ outstanding.extend(
+ effects
+ .sends
+ .iter()
+ .map(|send| (send.request, sent_messages(send))),
+ );
+ batcher = next;
+ };
+ assert!(matches!(failed, BatcherStateMachine::Failed));
+ assert!(fired_at <= now + STALL + BUSY_DELAY * 3);
+ }
+
+ #[test]
+ fn draining_stops_when_an_in_flight_run_of_a_revoked_partition_fails() {
+ let now = Instant::now();
+ let workers = pool(&["w"]);
+ let (batcher, effects) = batcher(4, now).on_groups(now, &workers, 0, vec![run("a", &[1])]);
+ let (request, messages) = (effects.sends[0].request, sent_messages(&effects.sends[0]));
+ let (batcher, _) = batcher.on_shutdown(now, &workers);
+ let (batcher, _) = batcher.on_partitions_revoked(now, &[("events".to_string(), 0)]);
+ assert!(
+ matches!(batcher, BatcherStateMachine::Draining(_)),
+ "a is in flight"
+ );
+
+ let (batcher, effects) =
+ batcher.on_request_failed(now, &workers, request, FailureCause::Fault, messages);
+ assert!(matches!(batcher, BatcherStateMachine::Stopped));
+ assert!(effects.sends.is_empty());
+ assert!(effects.completions.is_empty());
+ assert_eq!(effects.next_wakeup, None);
+ }
+}
diff --git a/rust/ingestion-consumer/src/batcher/test_support.rs b/rust/ingestion-consumer/src/batcher/test_support.rs
new file mode 100644
index 000000000000..be34eba6de51
--- /dev/null
+++ b/rust/ingestion-consumer/src/batcher/test_support.rs
@@ -0,0 +1,19 @@
+use std::collections::HashMap;
+
+use crate::types::SerializedKafkaMessage;
+
+pub fn message(key: &str, partition: i32, offset: i64) -> SerializedKafkaMessage {
+ SerializedKafkaMessage {
+ topic: "events".into(),
+ partition,
+ offset,
+ timestamp: 0,
+ key: Some(key.to_string()),
+ value: Some("{}".to_string()),
+ headers: HashMap::new(),
+ }
+}
+
+pub fn offsets(messages: &[SerializedKafkaMessage]) -> Vec<i64> {
+ messages.iter().map(|m| m.offset).collect()
+}
diff --git a/rust/ingestion-consumer/src/batcher/worker_assigner.rs b/rust/ingestion-consumer/src/batcher/worker_assigner.rs
new file mode 100644
index 000000000000..b78b150a6772
--- /dev/null
+++ b/rust/ingestion-consumer/src/batcher/worker_assigner.rs
@@ -0,0 +1,117 @@
+//! Picks each request's worker when it is sent, against the load in flight.
+
+use std::collections::HashMap;
+
+use crate::routing::{Router, WorkerLoad};
+use crate::worker_registry::WorkerId;
+
+pub struct WorkerAssigner {
+ router: Router,
+ max_requests_per_worker: usize,
+ message_load: WorkerLoad,
+ request_load: HashMap<WorkerId, usize>,
+}
+
+impl WorkerAssigner {
+ pub fn new(router: Router, max_requests_per_worker: usize) -> Result<Self, String> {
+ if max_requests_per_worker == 0 {
+ return Err("max_requests_per_worker must be > 0".to_string());
+ }
+ Ok(Self {
+ router,
+ max_requests_per_worker,
+ message_load: WorkerLoad::new(),
+ request_load: HashMap::new(),
+ })
+ }
+
+ pub fn in_flight_messages(&self) -> usize {
+ self.message_load.values().sum()
+ }
+
+ pub fn prefers_largest_first(&self) -> bool {
+ self.router.prefers_largest_first()
+ }
+
+ pub fn free_slots(&self, pool: &[WorkerId]) -> usize {
+ pool.iter()
+ .map(|worker| self.max_requests_per_worker - self.requests_on(worker))
+ .sum()
+ }
+
+ pub fn assign(&mut self, pool: &[WorkerId], message_count: usize) -> Option<WorkerId> {
+ // A worker at the cap is skipped, so one slow worker cannot hold
+ // every send slot.
+ let open: Vec<WorkerId> = pool
+ .iter()
+ .filter(|worker| self.requests_on(worker) < self.max_requests_per_worker)
+ .cloned()
+ .collect();
+ let worker = self.router.select(&open, &self.message_load)?;
+ *self.message_load.entry(worker.clone()).or_insert(0) += message_count;
+ *self.request_load.entry(worker.clone()).or_insert(0) += 1;
+ Some(worker)
+ }
+
+ /// True when the worker has nothing left in flight.
+ pub fn release(&mut self, worker: &WorkerId, message_count: usize) -> bool {
+ if let Some(load) = self.message_load.get_mut(worker) {
+ *load = load.saturating_sub(message_count);
+ }
+ let idle = match self.request_load.get_mut(worker) {
+ Some(requests) => {
+ *requests = requests.saturating_sub(1);
+ *requests == 0
+ }
+ None => true,
+ };
+ if idle {
+ self.request_load.remove(worker);
+ self.message_load.remove(worker);
+ }
+ idle
+ }
+
+ pub fn requests_on(&self, worker: &WorkerId) -> usize {
+ self.request_load.get(worker).copied().unwrap_or(0)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::routing::RoutingStrategy;
+
+ fn wid(s: &str) -> WorkerId {
+ WorkerId::from(s)
+ }
+
+ #[test]
+ fn a_zero_request_cap_is_rejected() {
+ assert!(WorkerAssigner::new(Router::new(RoutingStrategy::BinPack), 0).is_err());
+ }
+
+ #[test]
+ fn a_worker_at_the_request_cap_is_skipped_until_a_request_settles() {
+ let pool = vec![wid("a"), wid("b")];
+ let mut assigner = WorkerAssigner::new(Router::new(RoutingStrategy::BinPack), 1).unwrap();
+
+ assert_eq!(assigner.assign(&pool, 10), Some(wid("a")));
+ assert_eq!(assigner.assign(&pool, 10), Some(wid("b")));
+ assert_eq!(assigner.assign(&pool, 10), None, "both at the cap");
+ assert_eq!(assigner.free_slots(&pool), 0);
+
+ assert!(assigner.release(&wid("a"), 10));
+ assert_eq!(assigner.assign(&pool, 10), Some(wid("a")));
+ }
+
+ #[test]
+ fn placement_follows_the_in_flight_message_load() {
+ let pool = vec![wid("a"), wid("b")];
+ let mut assigner = WorkerAssigner::new(Router::new(RoutingStrategy::BinPack), 10).unwrap();
+
+ assert_eq!(assigner.assign(&pool, 100), Some(wid("a")));
+ assert_eq!(assigner.assign(&pool, 1), Some(wid("b")));
+ assert_eq!(assigner.assign(&pool, 1), Some(wid("b")), "b is lighter");
+ }
+}
diff --git a/rust/ingestion-consumer/src/batcher/worker_pool.rs b/rust/ingestion-consumer/src/batcher/worker_pool.rs
new file mode 100644
index 000000000000..01b12e4d389e
--- /dev/null
+++ b/rust/ingestion-consumer/src/batcher/worker_pool.rs
@@ -0,0 +1,91 @@
+use std::sync::Arc;
+
+use k8s_awareness::PeerTracker;
+
+use crate::aperture;
+use crate::routing::RoutingStrategy;
+use crate::worker_registry::{WorkerId, WorkerRegistry};
+
+/// The routable workers for one action.
+#[derive(Clone, Debug, Default)]
+pub struct WorkerPool {
+ pub healthy: Vec<WorkerId>,
+ /// Candidates for fresh requests: the aperture ring slice when narrowing
+ /// applies, otherwise the healthy pool.
+ pub candidates: Vec<WorkerId>,
+}
+
+/// Captures a [`WorkerPool`] from the registry and the peer set.
+#[derive(Clone)]
+pub struct WorkerPoolSource {
+ registry: Arc<WorkerRegistry>,
+ strategy: RoutingStrategy,
+ aperture: Option<(Arc<PeerTracker>, usize)>,
+}
+
+impl WorkerPoolSource {
+ pub fn new(registry: Arc<WorkerRegistry>, strategy: RoutingStrategy) -> Self {
+ Self {
+ registry,
+ strategy,
+ aperture: None,
+ }
+ }
+
+ /// Narrow fresh candidates to this consumer's slice of the worker ring,
+ /// `min_aperture` wide. Only consulted under [`RoutingStrategy::Aperture`].
+ pub fn set_aperture(&mut self, tracker: Arc<PeerTracker>, min_aperture: usize) {
+ self.aperture = Some((tracker, min_aperture.max(1)));
+ }
+
+ pub fn registry(&self) -> &Arc<WorkerRegistry> {
+ &self.registry
+ }
+
+ pub fn strategy(&self) -> RoutingStrategy {
+ self.strategy
+ }
+
+ pub fn min_aperture(&self) -> Option<usize> {
+ self.aperture.as_ref().map(|(_, width)| *width)
+ }
+
+ /// The ring slice of `healthy`, or `None` when narrowing does not apply.
+ /// The slice falls back to `None` while the peer set is unknown, at
+ /// startup or with peer awareness disabled.
+ pub fn slice(&self, ring: &[WorkerId], healthy: &[WorkerId]) -> Option<Vec<WorkerId>> {
+ let (tracker, width) = self.active_aperture()?;
+ let peers = tracker.snapshot();
+ aperture::ring_slice(ring, healthy, peers.self_index, peers.peer_count(), *width)
+ }
+
+ pub fn pool(&self) -> WorkerPool {
+ let healthy = self.registry.healthy_workers();
+ let candidates = self.narrow(&healthy).unwrap_or_else(|| healthy.clone());
+ WorkerPool {
+ healthy,
+ candidates,
+ }
+ }
+
+ pub fn candidates(&self) -> Vec<WorkerId> {
+ let healthy = self.registry.healthy_workers();
+ self.narrow(&healthy).unwrap_or(healthy)
+ }
+
+ fn active_aperture(&self) -> Option<&(Arc<PeerTracker>, usize)> {
+ if self.strategy == RoutingStrategy::Aperture {
+ self.aperture.as_ref()
+ } else {
+ None
+ }
+ }
+
+ fn narrow(&self, healthy: &[WorkerId]) -> Option<Vec<WorkerId>> {
+ self.active_aperture()?;
+ let ring = aperture::sorted_ring(self.registry.workers());
+ // The fleet's slices tile the pool, so each consumer's requests
+ // consolidate onto few workers.
+ self.slice(&ring, healthy)
+ }
+}
diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rs
index f9be686f71bf..196253c834a3 100644
--- a/rust/ingestion-consumer/src/config.rs
+++ b/rust/ingestion-consumer/src/config.rs
@@ -1,10 +1,15 @@
+use std::time::{Duration, Instant};
+
use common_continuous_profiling::ContinuousProfilingConfig;
use envconfig::Envconfig;
use rdkafka::ClientConfig;
use tracing::info;
+use crate::batcher::retry_policy::RetryPolicy;
+use crate::batcher::state_machine::BatcherStateMachine;
+use crate::batcher::worker_assigner::WorkerAssigner;
use crate::discovery::DiscoveryMode;
-use crate::routing::RoutingStrategy;
+use crate::routing::{Router, RoutingStrategy};
use crate::scheduler::SchedulerKind;
use common_kafka_consumer::config::ConsumerConfigBuilder;
@@ -164,7 +169,8 @@ pub struct Config {
#[envconfig(default = "60000")]
pub consumer_deferred_flush_timeout_ms: u64,
- /// How often the key-table scheduler retries its parked keys
+ /// How long the key-table scheduler waits before it retries a failed
+ /// send, and how often a request with no routable worker tries again
/// (milliseconds). Matches the flush driver's retry cadence, so the
/// scheduler switch does not regress recovery latency. Only read under
/// `INGESTION_SCHEDULER=key_table`.
@@ -282,8 +288,9 @@ pub struct Config {
pub routing_strategy: RoutingStrategy,
/// Which scheduler orders and places runs: `pin_stash` (default, sticky
- /// pins with a per-batch stash) or `key_table` (at most one in-flight
- /// request per key). The switch back is the rollback.
+ /// pins with a per-batch stash) or `key_table` (the batcher state
+ /// machine: at most one in-flight request per key, with packing). The
+ /// switch back is the rollback.
#[envconfig(from = "INGESTION_SCHEDULER", default = "pin_stash")]
pub scheduler: SchedulerKind,
@@ -403,6 +410,23 @@ impl Config {
format!("{}:{}", self.bind_host, self.bind_port)
}
+ /// The key-table scheduler's state machine. It reuses the stream's
+ /// un-acked cap as its per-worker request cap, the parked-retry interval
+ /// for every retry, and the deferred-flush timeout as its stall timeout.
+ pub fn batcher_state_machine(&self) -> Result<BatcherStateMachine, String> {
+ let assigner = WorkerAssigner::new(
+ Router::new(self.routing_strategy),
+ self.ingestion_worker_concurrent_batches,
+ )?;
+ let retry = RetryPolicy::uniform(Duration::from_millis(self.parked_retry_interval_ms))?;
+ BatcherStateMachine::new(
+ assigner,
+ retry,
+ Duration::from_millis(self.consumer_deferred_flush_timeout_ms),
+ Instant::now(),
+ )
+ }
+
pub fn worker_urls(&self) -> Vec<String> {
self.worker_addresses
.split(',')
diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rs
index c8d116ce2f33..d98448a71572 100644
--- a/rust/ingestion-consumer/src/consumer.rs
+++ b/rust/ingestion-consumer/src/consumer.rs
@@ -14,18 +14,16 @@ use rdkafka::TopicPartitionList;
use tokio::sync::mpsc;
use tracing::{error, info, warn};
-use crate::batcher::{make_batch_id, Batcher, BatcherOutputs};
+use crate::batcher::{make_batch_id, Batcher, BatcherObserver, BatcherOutputs, Revoker};
use crate::commit_monitor::spawn_commit_monitor;
use crate::commit_pacer::ImmediateCommitPacer;
use crate::commit_sentinel::{CommitSentinel, CommitViolation};
use crate::config::Config;
use crate::debug_recorder::{record_if, DebugEventKind, DebugRecorder, PartitionOffset};
use crate::discovery::DiscoveryMode;
-use crate::dispatcher::Dispatcher;
use crate::grpc_transport::GrpcTransport;
use crate::ledger_rejection::{warn_rejection, RejectedSlice};
-use crate::order_sentinel::{OffsetSpan, SentinelContext};
-use crate::scheduler::SchedulerKind;
+use crate::order_sentinel::{OffsetSpan, RevokeHook, SentinelContext};
use crate::types::{Accumulator, SerializedKafkaMessage};
/// Batch-wide statistics gathered while collecting, used to emit parity
@@ -178,6 +176,32 @@ struct RevokedPartition {
generation: u64,
}
+/// The consumer's revocation hook: purge the batcher, and record the revoked
+/// partitions when the batcher's purge means their polls never complete.
+fn revoke_hook(
+ revoker: Revoker,
+ ledger: Arc<TopicOffsetLedger>,
+ revoked_partitions: Arc<Mutex<Vec<RevokedPartition>>>,
+) -> RevokeHook {
+ let records_revocations = revoker.drops_revoked_polls();
+ Box::new(move |partitions| {
+ revoker.purge_revoked(partitions);
+ if records_revocations {
+ revoked_partitions
+ .lock()
+ .unwrap()
+ .extend(partitions.iter().map(|(topic, partition)| {
+ let topic_partition = TopicPartition::new(topic, *partition);
+ let generation = ledger.generation(&topic_partition);
+ RevokedPartition {
+ topic_partition,
+ generation,
+ }
+ }));
+ }
+ })
+}
+
/// Remove revoked partitions from in-flight polls, and remove polls left
/// empty. Only slices from before that partition's revoke generation go: a
/// poll's kept or newly reassigned slices retain their counts and settle their
@@ -274,15 +298,6 @@ 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, 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,
- /// The key-table scheduler's parked-retry cadence. Production takes it
- /// from `INGESTION_PARKED_RETRY_INTERVAL_MS` (default 200ms).
- pub parked_retry_interval: Duration,
/// Debug event recorder; `None` unless `DEBUG_API_ENABLED`.
pub debug_recorder: Option<Arc<DebugRecorder>>,
}
@@ -321,12 +336,11 @@ 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. Builds
- /// the batcher from the dispatcher and transport; `new` instead takes one
- /// built in `main`.
+ /// where the Kafka consumer is created and subscribed externally.
pub fn from_parts(
consumer: StreamConsumer<SentinelContext>,
- dispatcher: Arc<Dispatcher>,
+ batcher: Batcher,
+ outputs: BatcherOutputs,
transport: Arc<GrpcTransport>,
worker_urls: Vec<String>,
options: IngestionConsumerOptions,
@@ -336,37 +350,14 @@ impl IngestionConsumer {
// forget partitions on the same ones the commit path uses.
let topic_offset_ledger = consumer.context().topic_offset_ledger();
let commit_sentinel = consumer.context().commit_sentinel();
- let revoke_ledger = Arc::clone(&topic_offset_ledger);
let revoked_partitions: Arc<Mutex<Vec<RevokedPartition>>> =
Arc::new(Mutex::new(Vec::new()));
- let purge_dispatcher = Arc::clone(&dispatcher);
- let hook_revoked = (dispatcher.scheduler_kind() == SchedulerKind::KeyTable)
- .then(|| Arc::clone(&revoked_partitions));
- consumer
- .context()
- .set_revoke_hook(Box::new(move |partitions| {
- purge_dispatcher.purge_revoked(partitions);
- if let Some(list) = &hook_revoked {
- list.lock()
- .unwrap()
- .extend(partitions.iter().map(|(topic, partition)| {
- let topic_partition = TopicPartition::new(topic, *partition);
- let generation = revoke_ledger.generation(&topic_partition);
- RevokedPartition {
- topic_partition,
- generation,
- }
- }));
- }
- }));
+ consumer.context().set_revoke_hook(revoke_hook(
+ batcher.revoker(),
+ Arc::clone(&topic_offset_ledger),
+ Arc::clone(&revoked_partitions),
+ ));
let consumer = Arc::new(consumer);
- let (batcher, outputs) = Batcher::new(
- dispatcher,
- Arc::clone(&transport),
- handle.clone(),
- options.deferred_flush_timeout,
- options.parked_retry_interval,
- );
Self {
commit_sentinel,
debug_recorder: options.debug_recorder,
@@ -415,36 +406,22 @@ impl IngestionConsumer {
);
let commit_sentinel = Arc::new(CommitSentinel::new(ImmediateCommitPacer::new()));
commit_sentinel.set_enabled(config.consumer_order_sentinel_enabled);
- let key_sentinel = batcher.key_order_sentinel();
- key_sentinel.set_enabled(config.consumer_order_sentinel_enabled);
+ batcher
+ .key_order_sentinel()
+ .set_enabled(config.consumer_order_sentinel_enabled);
let topic_offset_ledger = Arc::new(TopicOffsetLedger::new());
let mut context = SentinelContext::new(
Arc::clone(&commit_sentinel),
- key_sentinel,
Arc::clone(&topic_offset_ledger),
);
context.set_assignment_epoch(transport.assignment_epoch());
- let revoke_ledger = Arc::clone(&topic_offset_ledger);
let revoked_partitions: Arc<Mutex<Vec<RevokedPartition>>> =
Arc::new(Mutex::new(Vec::new()));
- let purge_dispatcher = batcher.dispatcher();
- let hook_revoked = (purge_dispatcher.scheduler_kind() == SchedulerKind::KeyTable)
- .then(|| Arc::clone(&revoked_partitions));
- context.set_revoke_hook(Box::new(move |partitions| {
- purge_dispatcher.purge_revoked(partitions);
- if let Some(list) = &hook_revoked {
- list.lock()
- .unwrap()
- .extend(partitions.iter().map(|(topic, partition)| {
- let topic_partition = TopicPartition::new(topic, *partition);
- let generation = revoke_ledger.generation(&topic_partition);
- RevokedPartition {
- topic_partition,
- generation,
- }
- }));
- }
- }));
+ context.set_revoke_hook(revoke_hook(
+ batcher.revoker(),
+ Arc::clone(&topic_offset_ledger),
+ Arc::clone(&revoked_partitions),
+ ));
let consumer: StreamConsumer<SentinelContext> =
client_config.create_with_context(context)?;
consumer.subscribe(&[&config.ingestion_consumer_consume_topic])?;
@@ -478,6 +455,11 @@ impl IngestionConsumer {
})
}
+ /// A read-only view of the batcher's load.
+ pub fn batcher_observer(&self) -> BatcherObserver {
+ self.batcher.observer()
+ }
+
/// 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(mut self) {
@@ -539,6 +521,7 @@ impl IngestionConsumer {
"Shutdown signal received, draining in-flight batches"
);
accepting_new_batches = false;
+ self.batcher.begin_shutdown();
}
result = self.collect_batch() => {
let collected = match result {
diff --git a/rust/ingestion-consumer/src/dispatcher.rs b/rust/ingestion-consumer/src/dispatcher.rs
index 9b466061db02..799589009ae2 100644
--- a/rust/ingestion-consumer/src/dispatcher.rs
+++ b/rust/ingestion-consumer/src/dispatcher.rs
@@ -6,15 +6,15 @@ use k8s_awareness::PeerTracker;
use metrics::{counter, histogram};
use crate::aperture;
+use crate::batcher::worker_pool::{WorkerPool, WorkerPoolSource};
use crate::debug_recorder::{
record_if, DebugEventKind, DebugRecorder, DispatcherLoad, LoadEntry, RoutingDebug, SubBatchInfo,
};
-use crate::key_table::KeyTableScheduler;
use crate::order_sentinel::KeyOrderSentinel;
use crate::routing::{Router, RoutingStrategy, WorkerLoad};
use crate::scheduler::{
- Deadline, Dispatch, KeyRun, PinStashScheduler, Scheduler, SchedulerEffects, SchedulerKind,
- Settlement, SettlementOutcome, WorkerHealth, WorkerSnapshot,
+ Dispatch, KeyRun, PinStashScheduler, Scheduler, SchedulerEffects, Settlement,
+ SettlementOutcome, WorkerHealth, WorkerSnapshot,
};
use crate::types::{Accumulator, Group, SerializedKafkaMessage};
use crate::worker_registry::{WorkerId, WorkerRegistry};
@@ -152,142 +152,11 @@ pub struct Submission<T> {
pub retained: bool,
}
-/// The selected scheduler. An enum rather than a trait object, so the
-/// pin-stash-only methods below stay off the [`Scheduler`] trait and the
-/// cleanup change deletes one arm.
-enum SchedulerImpl {
- PinStash(PinStashScheduler),
- KeyTable(KeyTableScheduler),
-}
-
-impl SchedulerImpl {
- fn new(kind: SchedulerKind, router: Router) -> Self {
- match kind {
- SchedulerKind::PinStash => SchedulerImpl::PinStash(PinStashScheduler::new(router)),
- SchedulerKind::KeyTable => SchedulerImpl::KeyTable(KeyTableScheduler::new(router)),
- }
- }
-
- // Pin-stash-only bookkeeping. The key table is batch-blind: it registers
- // nothing, defers nothing per batch, and reports its own gauges.
-
- fn register_batch(&mut self, batch_id: &str) {
- if let SchedulerImpl::PinStash(scheduler) = self {
- scheduler.register_batch(batch_id);
- }
- }
-
- fn release_batch(&mut self, batch_id: &str) {
- if let SchedulerImpl::PinStash(scheduler) = self {
- scheduler.release_batch(batch_id);
- }
- }
-
- fn has_batch(&self, batch_id: &str) -> bool {
- match self {
- SchedulerImpl::PinStash(scheduler) => scheduler.has_batch(batch_id),
- SchedulerImpl::KeyTable(_) => false,
- }
- }
-
- fn pin_count(&self) -> usize {
- match self {
- SchedulerImpl::PinStash(scheduler) => scheduler.pin_count(),
- SchedulerImpl::KeyTable(_) => 0,
- }
- }
-
- fn stashed_messages(&self) -> usize {
- match self {
- SchedulerImpl::PinStash(scheduler) => scheduler.stashed_messages(),
- SchedulerImpl::KeyTable(_) => 0,
- }
- }
-
- fn stashed_batches(&self) -> usize {
- match self {
- SchedulerImpl::PinStash(scheduler) => scheduler.stashed_batches(),
- SchedulerImpl::KeyTable(_) => 0,
- }
- }
-
- fn stash_failed(&mut self, batch_id: &str, runs: Vec<KeyRun>) -> u64 {
- match self {
- SchedulerImpl::PinStash(scheduler) => scheduler.stash_failed(batch_id, runs),
- SchedulerImpl::KeyTable(_) => 0,
- }
- }
-
- #[cfg(test)]
- fn pins(&self) -> &HashMap<String, crate::scheduler::Pin> {
- match self {
- SchedulerImpl::PinStash(scheduler) => &scheduler.pins,
- SchedulerImpl::KeyTable(_) => panic!("pins are pin-stash state"),
- }
- }
-
- #[cfg(test)]
- fn pins_mut(&mut self) -> &mut HashMap<String, crate::scheduler::Pin> {
- match self {
- SchedulerImpl::PinStash(scheduler) => &mut scheduler.pins,
- SchedulerImpl::KeyTable(_) => panic!("pins are pin-stash state"),
- }
- }
-}
-
-impl Scheduler for SchedulerImpl {
- fn on_groups(
- &mut self,
- snapshot: &WorkerSnapshot,
- batch_id: &str,
- assignment_epoch: u64,
- groups: Vec<KeyRun>,
- ) -> SchedulerEffects {
- match self {
- SchedulerImpl::PinStash(scheduler) => {
- scheduler.on_groups(snapshot, batch_id, assignment_epoch, groups)
- }
- SchedulerImpl::KeyTable(scheduler) => {
- scheduler.on_groups(snapshot, batch_id, assignment_epoch, groups)
- }
- }
- }
-
- fn on_settled(
- &mut self,
- snapshot: &WorkerSnapshot,
- settlement: Settlement,
- ) -> SchedulerEffects {
- match self {
- SchedulerImpl::PinStash(scheduler) => scheduler.on_settled(snapshot, settlement),
- SchedulerImpl::KeyTable(scheduler) => scheduler.on_settled(snapshot, settlement),
- }
- }
-
- fn on_deadline(
- &mut self,
- snapshot: &WorkerSnapshot,
- deadline: Deadline<'_>,
- ) -> SchedulerEffects {
- match self {
- SchedulerImpl::PinStash(scheduler) => scheduler.on_deadline(snapshot, deadline),
- SchedulerImpl::KeyTable(scheduler) => scheduler.on_deadline(snapshot, deadline),
- }
- }
-
- fn on_partitions_revoked(&mut self, partitions: &[(String, i32)]) -> SchedulerEffects {
- match self {
- SchedulerImpl::PinStash(scheduler) => scheduler.on_partitions_revoked(partitions),
- SchedulerImpl::KeyTable(scheduler) => scheduler.on_partitions_revoked(partitions),
- }
- }
-}
-
/// The scheduler and the load table, behind the dispatcher's single Mutex.
struct DispatcherInner {
/// The decision core. Every ordering and placement decision happens in
/// its seam calls; the dispatcher applies the returned effects.
- scheduler: SchedulerImpl,
+ scheduler: PinStashScheduler,
/// Outstanding (in-flight) message count per worker. Both routing
/// strategies use it as the per-worker load signal so new key-groups land
/// on lightly-loaded workers — load is balanced by message volume rather
@@ -310,16 +179,13 @@ pub struct Dispatcher {
/// The configured routing strategy; the scheduler owns the router itself.
/// Kept here for view construction (aperture narrowing) and debug.
strategy: RoutingStrategy,
- /// The selected scheduler kind, for the batcher's driver choice.
- scheduler_kind: SchedulerKind,
/// Per-key send/ACK order checker. Called under the inner lock (lock
/// order: inner → sentinel; the sentinel never takes the inner lock),
/// so its check order matches the intended per-key send order.
key_sentinel: Arc<KeyOrderSentinel>,
- /// Peer tracker + aperture width for [`RoutingStrategy::Aperture`]: this
- /// dispatcher's ring slice is derived from its agreed peer index. `None`
- /// (or a not-yet-known peer index) falls back to the full healthy pool.
- aperture: Option<(Arc<PeerTracker>, usize)>,
+ /// The healthy pool and, under [`RoutingStrategy::Aperture`], this
+ /// dispatcher's ring slice for fresh keys.
+ pool_source: WorkerPoolSource,
/// Debug event recorder; `None` unless `DEBUG_API_ENABLED`.
debug_recorder: Option<Arc<DebugRecorder>>,
}
@@ -332,16 +198,7 @@ impl Dispatcher {
/// Construct a dispatcher with an explicit routing strategy.
pub fn with_strategy(registry: Arc<WorkerRegistry>, strategy: RoutingStrategy) -> Self {
- Self::with_scheduler(registry, strategy, SchedulerKind::default())
- }
-
- /// Construct a dispatcher with an explicit routing strategy and scheduler.
- pub fn with_scheduler(
- registry: Arc<WorkerRegistry>,
- strategy: RoutingStrategy,
- kind: SchedulerKind,
- ) -> Self {
- Self::from_router(registry, strategy, kind, Router::new(strategy))
+ Self::from_router(registry, strategy, Router::new(strategy))
}
/// Test-only constructor with a seeded RNG so P2C selection is deterministic.
@@ -351,30 +208,23 @@ impl Dispatcher {
strategy: RoutingStrategy,
seed: u64,
) -> Self {
- Self::from_router(
- registry,
- strategy,
- SchedulerKind::default(),
- Router::with_seed(strategy, seed),
- )
+ Self::from_router(registry, strategy, Router::with_seed(strategy, seed))
}
fn from_router(
registry: Arc<WorkerRegistry>,
strategy: RoutingStrategy,
- kind: SchedulerKind,
router: Router,
) -> Self {
Self {
inner: Mutex::new(DispatcherInner {
- scheduler: SchedulerImpl::new(kind, router),
+ scheduler: PinStashScheduler::new(router),
in_flight: WorkerLoad::new(),
}),
+ pool_source: WorkerPoolSource::new(Arc::clone(&registry), strategy),
registry,
strategy,
- scheduler_kind: kind,
key_sentinel: Arc::new(KeyOrderSentinel::new()),
- aperture: None,
debug_recorder: None,
}
}
@@ -390,7 +240,12 @@ impl Dispatcher {
/// Only consulted under [`RoutingStrategy::Aperture`]. Call before the
/// dispatcher is shared.
pub fn set_aperture(&mut self, tracker: Arc<PeerTracker>, min_aperture: usize) {
- self.aperture = Some((tracker, min_aperture.max(1)));
+ self.pool_source.set_aperture(tracker, min_aperture);
+ }
+
+ /// The worker pool source, shared with the batcher state machine.
+ pub fn worker_pool_source(&self) -> WorkerPoolSource {
+ self.pool_source.clone()
}
/// Inject the debug UI recorder. Call before the dispatcher is shared.
@@ -423,19 +278,11 @@ impl Dispatcher {
/// captured in one registry effects — so within one debug response the ring,
/// slice, and worker rows can't disagree under churn.
pub fn debug_routing(&self, workers: Vec<WorkerId>, healthy: &[WorkerId]) -> RoutingDebug {
- let strategy = self.strategy;
let ring = aperture::sorted_ring(workers);
- let slice = if strategy == RoutingStrategy::Aperture {
- self.aperture.as_ref().and_then(|(tracker, width)| {
- let peers = tracker.snapshot();
- aperture::ring_slice(&ring, healthy, peers.self_index, peers.peer_count(), *width)
- })
- } else {
- None
- };
+ let slice = self.pool_source.slice(&ring, healthy);
RoutingDebug {
- strategy: strategy.as_str().to_string(),
- min_aperture: self.aperture.as_ref().map(|(_, width)| *width),
+ strategy: self.strategy.as_str().to_string(),
+ min_aperture: self.pool_source.min_aperture(),
ring: ring.iter().map(|w| w.to_string()).collect(),
slice: slice.map(|s| s.iter().map(|w| w.to_string()).collect()),
}
@@ -446,7 +293,10 @@ impl Dispatcher {
/// health, and the current load table. The scheduler decides over this
/// snapshot instead of querying the registry itself.
fn worker_snapshot(&self, in_flight: &WorkerLoad) -> WorkerSnapshot {
- let healthy = self.registry.healthy_workers();
+ let WorkerPool {
+ healthy,
+ candidates,
+ } = self.pool_source.pool();
let workers = self
.registry
.workers()
@@ -459,26 +309,6 @@ impl Dispatcher {
(worker, health)
})
.collect();
- // Aperture: narrow the candidates to this dispatcher's ring slice, so
- // the fleet's slices tile the pool and each batch consolidates onto
- // few workers. Falls back to the full healthy pool while the peer set
- // is unknown (startup, peer awareness disabled).
- let narrowed = if self.strategy == RoutingStrategy::Aperture {
- self.aperture.as_ref().and_then(|(tracker, width)| {
- let peers = tracker.snapshot();
- let ring = aperture::sorted_ring(self.registry.workers());
- aperture::ring_slice(
- &ring,
- &healthy,
- peers.self_index,
- peers.peer_count(),
- *width,
- )
- })
- } else {
- None
- };
- let candidates = narrowed.unwrap_or_else(|| healthy.clone());
WorkerSnapshot::new(healthy, candidates, in_flight.clone(), workers)
}
@@ -510,19 +340,13 @@ impl Dispatcher {
groups: Vec<Group>,
send: impl FnMut(SubBatch) -> T,
) -> Submission<T> {
- let has_groups = !groups.is_empty();
let mut inner = self.inner.lock().unwrap();
let pending = self
.assign_groups(&mut inner, batch_id, assignment_epoch, groups)
.into_iter()
.map(send)
.collect();
- let retained = match &inner.scheduler {
- SchedulerImpl::PinStash(scheduler) => scheduler.has_batch(batch_id),
- // Every non-empty key-table submission is synchronously enqueued
- // before assignment returns, even when no worker is routable.
- SchedulerImpl::KeyTable(_) => has_groups,
- };
+ let retained = inner.scheduler.has_batch(batch_id);
Submission { pending, retained }
}
@@ -662,15 +486,6 @@ impl Dispatcher {
self.inner.lock().unwrap().scheduler.stashed_messages()
}
- /// Messages the scheduler holds for later, whichever scheduler runs:
- /// the pin-stash's stash, or the key table's queues.
- pub fn held_messages(&self) -> usize {
- match &self.inner.lock().unwrap().scheduler {
- SchedulerImpl::PinStash(scheduler) => scheduler.stashed_messages(),
- SchedulerImpl::KeyTable(scheduler) => scheduler.table().queued_messages(),
- }
- }
-
/// Number of live sticky pins. Exposed so tests can assert the pin table
/// drains back to zero once all in-flight work has resolved — a leak here
/// permanently skews routing.
@@ -733,69 +548,9 @@ impl Dispatcher {
.collect()
}
- /// Fire the parked-retry deadline and hand each sub-batch to `send`
- /// under the lock, like `flush_deferred_and_send`. The key table's pump
- /// calls this on its interval; keys that still cannot route stay parked
- /// for the next call.
- pub fn parked_retry_and_send<T>(&self, send: impl FnMut(SubBatch) -> T) -> Vec<T> {
- let mut inner = self.inner.lock().unwrap();
- let snapshot = self.worker_snapshot(&inner.in_flight);
- let SchedulerEffects { dispatches, .. } = inner
- .scheduler
- .on_deadline(&snapshot, Deadline::ParkedRetry);
- if dispatches.is_empty() {
- return Vec::new();
- }
- let assignments = self.note_and_assemble(dispatches);
- for (worker, message_count) in assignments.routed_counts() {
- *inner.in_flight.entry(worker.clone()).or_insert(0) += message_count;
- counter!(
- "ingestion_consumer_dispatcher_messages_routed_total",
- "worker" => worker.clone(),
- )
- .increment(message_count as u64);
- }
- assignments
- .into_sub_batches()
- .into_iter()
- .map(send)
- .collect()
- }
-
- /// The scheduler selected at construction.
- pub fn scheduler_kind(&self) -> SchedulerKind {
- self.scheduler_kind
- }
-
- /// Drop the scheduler's queued messages for revoked partitions, as
- /// `(topic, partition)`. Called from the consumer's rebalance callback.
- pub fn purge_revoked(&self, partitions: &[(String, i32)]) {
- let mut inner = self.inner.lock().unwrap();
- let effects = inner.scheduler.on_partitions_revoked(partitions);
- debug_assert!(effects.dispatches.is_empty(), "a purge never dispatches");
- let mut sentinel = self.key_sentinel.batch();
- for key in &effects.evicted_keys {
- sentinel.evict(key);
- }
- }
-
- /// The key table's `(queued messages, outstanding keys)`, for the pump's
- /// stall watchdog; `None` under the pin-stash scheduler.
- pub fn key_work(&self) -> Option<(usize, usize)> {
- match &self.inner.lock().unwrap().scheduler {
- SchedulerImpl::PinStash(_) => None,
- SchedulerImpl::KeyTable(scheduler) => Some((
- scheduler.table().queued_messages(),
- scheduler.table().outstanding_keys(),
- )),
- }
- }
-
fn flush_groups(&self, inner: &mut DispatcherInner, batch_id: &str) -> Vec<SubBatch> {
let snapshot = self.worker_snapshot(&inner.in_flight);
- let SchedulerEffects { dispatches, .. } = inner
- .scheduler
- .on_deadline(&snapshot, Deadline::Batch(batch_id));
+ let SchedulerEffects { dispatches, .. } = inner.scheduler.on_deadline(&snapshot, batch_id);
if dispatches.is_empty() {
return Vec::new();
}
@@ -1350,7 +1105,7 @@ mod tests {
.lock()
.unwrap()
.scheduler
- .pins()
+ .pins
.contains_key("t:user-1"));
dispatcher.on_sub_batch_resolved(
@@ -1366,7 +1121,7 @@ mod tests {
.lock()
.unwrap()
.scheduler
- .pins()
+ .pins
.contains_key("t:user-1"));
}
@@ -1381,7 +1136,7 @@ mod tests {
// Second batch, same key, pin not yet resolved: ref_count should be 2.
dispatcher.assign("b", make_msgs(&["t:user-1"]));
assert_eq!(
- dispatcher.inner.lock().unwrap().scheduler.pins()["t:user-1"].ref_count,
+ dispatcher.inner.lock().unwrap().scheduler.pins["t:user-1"].ref_count,
2
);
@@ -1395,8 +1150,8 @@ mod tests {
);
{
let inner = dispatcher.inner.lock().unwrap();
- assert!(inner.scheduler.pins().contains_key("t:user-1"));
- assert_eq!(inner.scheduler.pins()["t:user-1"].ref_count, 1);
+ assert!(inner.scheduler.pins.contains_key("t:user-1"));
+ assert_eq!(inner.scheduler.pins["t:user-1"].ref_count, 1);
}
}
@@ -1707,19 +1462,13 @@ mod tests {
let mut dispatcher =
Dispatcher::with_strategy(healthy_registry(6), RoutingStrategy::Aperture);
dispatcher.set_aperture(peer_tracker("10.0.0.2", &["10.0.0.1", "10.0.0.2"]), 2);
- dispatcher
- .inner
- .lock()
- .unwrap()
- .scheduler
- .pins_mut()
- .insert(
- "t:pinned".to_string(),
- Pin {
- worker: wid(0),
- ref_count: 1,
- },
- );
+ dispatcher.inner.lock().unwrap().scheduler.pins.insert(
+ "t:pinned".to_string(),
+ Pin {
+ worker: wid(0),
+ ref_count: 1,
+ },
+ );
let sub_batches = dispatcher.assign("b", make_msgs(&["t:pinned"]));
@@ -1809,38 +1558,6 @@ mod tests {
assert!(!dispatcher.has_deferred("batch-1"));
}
- #[test]
- fn test_key_table_parked_key_retries_when_a_worker_returns() {
- let registry = healthy_registry(0);
- let dispatcher = Dispatcher::with_scheduler(
- Arc::clone(&registry),
- RoutingStrategy::BinPack,
- SchedulerKind::KeyTable,
- );
-
- let sub_batches = dispatcher.assign("b1", make_msgs(&["t:user-1"]));
- assert!(sub_batches.is_empty(), "nothing routable yet");
- assert_eq!(
- dispatcher.key_work(),
- Some((1, 0)),
- "the key table keeps the parked message"
- );
-
- // Still nothing healthy: the key stays parked for the next tick.
- assert!(dispatcher.parked_retry_and_send(|sub| sub).is_empty());
-
- registry.add_worker(wid(0));
- let retried = dispatcher.parked_retry_and_send(|sub| sub);
- assert_eq!(retried.len(), 1);
- assert_eq!(retried[0].worker, wid(0));
- assert_eq!(retried[0].messages.len(), 1);
- assert_eq!(
- dispatcher.key_work(),
- Some((0, 1)),
- "outstanding until settled"
- );
- }
-
#[test]
fn test_fresh_key_queues_behind_its_own_deferred_groups() {
// batch-1 defers a fresh key because nothing was routable; a worker
diff --git a/rust/ingestion-consumer/src/grpc_transport.rs b/rust/ingestion-consumer/src/grpc_transport.rs
index 737893f53f8e..492881a7143c 100644
--- a/rust/ingestion-consumer/src/grpc_transport.rs
+++ b/rust/ingestion-consumer/src/grpc_transport.rs
@@ -197,6 +197,11 @@ impl GrpcTransport {
self.assignment_epoch = epoch;
}
+ /// The most sub-batches one worker stream keeps un-acked.
+ pub fn max_unacked(&self) -> usize {
+ self.max_unacked
+ }
+
/// The assignment epoch this transport stamps on sub-batches.
pub fn assignment_epoch(&self) -> AssignmentEpoch {
self.assignment_epoch.clone()
diff --git a/rust/ingestion-consumer/src/key_table.rs b/rust/ingestion-consumer/src/key_table.rs
deleted file mode 100644
index 0260191be215..000000000000
--- a/rust/ingestion-consumer/src/key_table.rs
+++ /dev/null
@@ -1,1258 +0,0 @@
-//! The key-table scheduler: at most one request per key is in flight.
-//!
-//! The key table holds one FIFO queue per routing key, an outstanding flag,
-//! and a parked list. A key is runnable when it has queued work and no
-//! outstanding request. Arrival enqueues and dispatches a runnable key's
-//! queued run; a dispatch marks the key outstanding. A delivered settlement
-//! clears the flag and dispatches the key's next run. A failed settlement
-//! returns the run to the front of its queue, then clears the flag — requeue
-//! before release, in one seam call — and parks the key. The parked-retry
-//! deadline ([`Deadline::ParkedRetry`]) covers the keys no settlement can
-//! release: unroutable groups, and keys behind a failed send.
-//!
-//! At most one outstanding request per key preserves per-key order. Nothing
-//! else does, and nothing else must: placement is stateless — the configured
-//! router picks a worker per dispatch, with no pins and no stash.
-//!
-//! Not selected by any production caller yet; the scheduler switch is the
-//! next change.
-
-use std::collections::{HashMap, HashSet, VecDeque};
-use std::time::{Duration, Instant};
-
-use metrics::{counter, gauge, histogram};
-
-use crate::order_sentinel::SendKind;
-use crate::routing::{Router, WorkerLoad};
-use crate::scheduler::{
- bump_load, working_load, Deadline, Dispatch, KeyRun, Scheduler, SchedulerEffects, Settlement,
- SettlementOutcome, WorkerSnapshot,
-};
-use crate::types::SerializedKafkaMessage;
-use crate::worker_registry::WorkerId;
-
-/// Record the run's head-of-line wait: how long its oldest message sat
-/// queued behind the key's outstanding request, park, or epoch boundary.
-fn record_queue_wait(run: &Run, kind: SendKind) {
- let kind = match kind {
- SendKind::Fresh => "fresh",
- SendKind::Resend => "resend",
- };
- histogram!("ingestion_consumer_key_table_queue_wait_seconds", "kind" => kind)
- .record(run.head_wait.as_secs_f64());
-}
-
-fn payload_bytes(messages: &[SerializedKafkaMessage]) -> usize {
- messages
- .iter()
- .map(SerializedKafkaMessage::payload_bytes)
- .sum()
-}
-
-/// One queued message: the epoch it was polled under and its arrival time,
-/// for the queue-wait histogram. A requeued failure restarts the clock, so
-/// a resend's wait measures the pause before the redelivery.
-struct QueuedMessage {
- epoch: u64,
- enqueued_at: Instant,
- message: SerializedKafkaMessage,
-}
-
-/// One drained run: the longest same-epoch prefix of a key's queue.
-struct Run {
- epoch: u64,
- /// Age of the run's oldest message: the head-of-line wait.
- head_wait: Duration,
- messages: Vec<SerializedKafkaMessage>,
-}
-
-/// One key's scheduling state.
-struct KeyState {
- /// Queued messages in arrival order. A failed run returns to the front.
- queue: VecDeque<QueuedMessage>,
- /// A request for this key is in flight. No second dispatch may happen
- /// until it settles.
- outstanding: bool,
- /// The epoch of the outstanding run, so its failed messages requeue
- /// under the epoch they were polled in.
- outstanding_epoch: u64,
- /// Remember revocations until this send settles: its messages live in
- /// the transport, not the queue. New assignments must remain retryable.
- revoked_while_outstanding: Vec<(String, i32)>,
- /// The key waits for the parked-retry deadline. A parked key is never
- /// outstanding: it parks only when nothing of its is in flight.
- parked: bool,
- /// The queue's front messages were sent once and failed. Their next
- /// dispatch is a [`SendKind::Resend`]; a key parked only as unroutable
- /// has never been sent, so its retry stays a strictly checked first send.
- redelivering: bool,
-}
-
-impl KeyState {
- fn new() -> Self {
- Self {
- queue: VecDeque::new(),
- outstanding: false,
- outstanding_epoch: 0,
- revoked_while_outstanding: Vec::new(),
- parked: false,
- redelivering: false,
- }
- }
-}
-
-/// Per-key FIFO queues, outstanding flags, and the parked list.
-#[derive(Default)]
-pub struct KeyTable {
- keys: HashMap<String, KeyState>,
- /// Keys awaiting the parked-retry deadline, in park order, so retries
- /// preserve arrival fairness across keys.
- parked: Vec<String>,
- /// Total queued messages and payload bytes across all keys, kept
- /// incrementally for the gauges. Bytes matter for visibility: every key
- /// with an outstanding request buffers all later arrivals, and key
- /// cardinality is customer-controlled.
- queued_messages: usize,
- queued_bytes: usize,
- outstanding_keys: usize,
-}
-
-impl KeyTable {
- pub fn new() -> Self {
- Self::default()
- }
-
- pub fn key_count(&self) -> usize {
- self.keys.len()
- }
-
- pub fn queued_messages(&self) -> usize {
- self.queued_messages
- }
-
- pub fn queued_bytes(&self) -> usize {
- self.queued_bytes
- }
-
- pub fn outstanding_keys(&self) -> usize {
- self.outstanding_keys
- }
-
- pub fn parked_keys(&self) -> usize {
- self.parked.len()
- }
-
- /// Whether the key may dispatch now: queued work, nothing outstanding,
- /// not waiting for the parked-retry deadline.
- fn is_runnable(&self, key: &str) -> bool {
- self.keys
- .get(key)
- .is_some_and(|state| !state.queue.is_empty() && !state.outstanding && !state.parked)
- }
-
- /// Append messages to the key's queue, creating the key when new.
- fn enqueue_back(&mut self, key: &str, epoch: u64, messages: Vec<SerializedKafkaMessage>) {
- self.queued_messages += messages.len();
- self.queued_bytes += payload_bytes(&messages);
- let enqueued_at = Instant::now();
- self.keys
- .entry(key.to_string())
- .or_insert_with(KeyState::new)
- .queue
- .extend(messages.into_iter().map(|message| QueuedMessage {
- epoch,
- enqueued_at,
- message,
- }));
- }
-
- /// Return a failed run to the front of its queue, ahead of anything that
- /// arrived while the run was in flight, so the redelivery keeps offset order.
- /// The messages keep the outstanding run's epoch, except those revoked
- /// while the send was in flight, which the new owner will replay.
- fn requeue_front(&mut self, key: &str, mut messages: Vec<SerializedKafkaMessage>) {
- let state = self
- .keys
- .entry(key.to_string())
- .or_insert_with(KeyState::new);
- if !state.revoked_while_outstanding.is_empty() {
- messages.retain(|message| {
- !state
- .revoked_while_outstanding
- .iter()
- .any(|(topic, partition)| {
- *topic == *message.topic && *partition == message.partition
- })
- });
- }
- if messages.is_empty() {
- return;
- }
- self.queued_messages += messages.len();
- self.queued_bytes += payload_bytes(&messages);
- state.redelivering = true;
- let epoch = state.outstanding_epoch;
- let enqueued_at = Instant::now();
- for message in messages.into_iter().rev() {
- state.queue.push_front(QueuedMessage {
- epoch,
- enqueued_at,
- message,
- });
- }
- }
-
- /// Drain the queue's longest same-epoch prefix into one run and mark the
- /// key outstanding. A run never mixes epochs, so its completions carry
- /// one valid stamp; later-epoch messages wait for the next settlement.
- /// Returns None, with no state change, when there is nothing to dispatch.
- fn take_run(&mut self, key: &str) -> Option<Run> {
- let state = self.keys.get_mut(key)?;
- debug_assert!(!state.outstanding, "at most one request per key");
- if state.outstanding || state.queue.is_empty() {
- return None;
- }
- let front = state.queue.front().expect("checked non-empty");
- let epoch = front.epoch;
- let head_wait = front.enqueued_at.elapsed();
- let mut messages: Vec<SerializedKafkaMessage> = Vec::new();
- while state
- .queue
- .front()
- .is_some_and(|queued| queued.epoch == epoch)
- {
- messages.push(state.queue.pop_front().expect("front checked").message);
- }
- state.outstanding = true;
- state.outstanding_epoch = epoch;
- state.parked = false;
- state.redelivering = false;
- self.outstanding_keys += 1;
- // Saturate so an accounting bug publishes zero to the gauges instead
- // of a wrapped huge value.
- debug_assert!(self.queued_messages >= messages.len());
- self.queued_messages = self.queued_messages.saturating_sub(messages.len());
- self.queued_bytes = self.queued_bytes.saturating_sub(payload_bytes(&messages));
- Some(Run {
- epoch,
- head_wait,
- messages,
- })
- }
-
- /// Put the key on the parked list, to be retried at the parked-retry
- /// deadline. A no-op when it is already parked or not tracked.
- fn park(&mut self, key: &str) {
- let Some(state) = self.keys.get_mut(key) else {
- return;
- };
- if !state.parked {
- state.parked = true;
- self.parked.push(key.to_string());
- }
- }
-
- /// Take the parked list for one retry pass. Keys that still cannot route
- /// go back via [`KeyTable::repark`]; their `parked` flag stays set so
- /// arrivals keep queueing behind them in the meantime.
- fn take_parked(&mut self) -> Vec<String> {
- std::mem::take(&mut self.parked)
- }
-
- /// Restore a key's parked-list entry after a retry pass could not route
- /// it. Its `parked` flag never dropped, so only the entry returns.
- fn repark(&mut self, key: String) {
- self.parked.push(key);
- }
-
- /// Messages queued for the key.
- fn queued_len(&self, key: &str) -> usize {
- self.keys.get(key).map_or(0, |state| state.queue.len())
- }
-
- /// Whether the key's next dispatch redelivers messages from a failed send.
- fn is_redelivering(&self, key: &str) -> bool {
- self.keys.get(key).is_some_and(|state| state.redelivering)
- }
-
- /// Clear the key's outstanding flag when its request settles. Returns
- /// false for a key this table is not tracking as outstanding — a stale
- /// settlement to ignore.
- fn settle_key(&mut self, key: &str) -> bool {
- match self.keys.get_mut(key) {
- Some(state) if state.outstanding => {
- state.outstanding = false;
- state.revoked_while_outstanding.clear();
- self.outstanding_keys = self.outstanding_keys.saturating_sub(1);
- true
- }
- _ => false,
- }
- }
-
- /// Drop queued messages on revoked partitions and the keys that emptied,
- /// unless still outstanding. Returns the purged message count and the
- /// evicted keys.
- fn purge_partitions(&mut self, revoked: &[(String, i32)]) -> (usize, Vec<String>) {
- let revoked: HashSet<(&str, i32)> = revoked
- .iter()
- .map(|(topic, partition)| (topic.as_str(), *partition))
- .collect();
- let mut purged = 0usize;
- let mut purged_bytes = 0usize;
- for state in self.keys.values_mut() {
- if state.outstanding {
- for &(topic, partition) in &revoked {
- if !state.revoked_while_outstanding.iter().any(
- |(revoked_topic, revoked_partition)| {
- revoked_topic == topic && *revoked_partition == partition
- },
- ) {
- state
- .revoked_while_outstanding
- .push((topic.to_string(), partition));
- }
- }
- }
- let before = state.queue.len();
- state.queue.retain(|queued| {
- let keep = !revoked.contains(&(&*queued.message.topic, queued.message.partition));
- if !keep {
- purged_bytes += queued.message.payload_bytes();
- }
- keep
- });
- purged += before - state.queue.len();
- if state.queue.is_empty() {
- state.parked = false;
- state.redelivering = false;
- }
- }
- self.queued_messages = self.queued_messages.saturating_sub(purged);
- self.queued_bytes = self.queued_bytes.saturating_sub(purged_bytes);
-
- let keys = &mut self.keys;
- self.parked
- .retain(|key| keys.get(key).is_some_and(|state| state.parked));
- let evicted: Vec<String> = keys
- .iter()
- .filter(|(_, state)| state.queue.is_empty() && !state.outstanding && !state.parked)
- .map(|(key, _)| key.clone())
- .collect();
- for key in &evicted {
- keys.remove(key);
- }
- (purged, evicted)
- }
-
- /// Drop the key when nothing is queued, outstanding, or parked, so its
- /// order-sentinel state can go too. Returns true when it was removed.
- fn evict_if_idle(&mut self, key: &str) -> bool {
- let idle = self
- .keys
- .get(key)
- .is_some_and(|state| state.queue.is_empty() && !state.outstanding && !state.parked);
- if idle {
- self.keys.remove(key);
- }
- idle
- }
-}
-
-/// The target scheduler: the key table plus stateless placement via the
-/// configured routing strategy (P2C within the aperture slice, or bin-pack).
-pub struct KeyTableScheduler {
- table: KeyTable,
- router: Router,
-}
-
-impl KeyTableScheduler {
- pub fn new(router: Router) -> Self {
- Self {
- table: KeyTable::new(),
- router,
- }
- }
-
- pub fn table(&self) -> &KeyTable {
- &self.table
- }
-
- /// Route the key's queued run to a worker, or park the key when no worker
- /// is routable. `pool` is the candidate set for this dispatch kind.
- fn dispatch_or_park(
- &mut self,
- pool: &[WorkerId],
- working_load: &mut WorkerLoad,
- key: &str,
- kind: SendKind,
- effects: &mut SchedulerEffects,
- ) {
- let Some(worker) = self.router.select(pool, working_load) else {
- // Counted once, at the park: a repark and arrivals behind an
- // already parked key do not re-count, so the counter tracks
- // newly stranded messages. The queued gauges carry the backlog.
- counter!("ingestion_consumer_dispatcher_unroutable_messages_total")
- .increment(self.table.queued_len(key) as u64);
- self.table.park(key);
- effects.deferred.unroutable += 1;
- return;
- };
- let Some(run) = self.table.take_run(key) else {
- return;
- };
- record_queue_wait(&run, kind);
- bump_load(working_load, &worker, run.messages.len());
- effects.dispatches.push(Dispatch {
- worker,
- routing_key: key.to_string(),
- messages: run.messages,
- kind,
- assignment_epoch: Some(run.epoch),
- });
- }
-
- fn record_gauges(&self) {
- gauge!("ingestion_consumer_key_table_keys").set(self.table.key_count() as f64);
- gauge!("ingestion_consumer_key_table_queued_messages")
- .set(self.table.queued_messages() as f64);
- gauge!("ingestion_consumer_key_table_queued_bytes").set(self.table.queued_bytes() as f64);
- gauge!("ingestion_consumer_key_table_outstanding_keys")
- .set(self.table.outstanding_keys() as f64);
- gauge!("ingestion_consumer_key_table_parked_keys").set(self.table.parked_keys() as f64);
- }
-}
-
-impl Scheduler for KeyTableScheduler {
- /// Enqueue each run, then dispatch every runnable key it touched. A key
- /// that is outstanding or parked just queues the new messages — they go
- /// out behind the earlier ones, when the request settles or the parked
- /// retry fires.
- fn on_groups(
- &mut self,
- snapshot: &WorkerSnapshot,
- _batch_id: &str,
- assignment_epoch: u64,
- groups: Vec<KeyRun>,
- ) -> SchedulerEffects {
- let mut effects = SchedulerEffects::with_dispatch_capacity(groups.len());
- let mut load = working_load(snapshot);
-
- let mut touched: Vec<String> = Vec::with_capacity(groups.len());
- for group in groups {
- self.table
- .enqueue_back(&group.routing_key, assignment_epoch, group.messages);
- // The group queues behind an outstanding request or a parked
- // backlog: the "why is this key not moving" signal.
- if !self.table.is_runnable(&group.routing_key) {
- effects.deferred.queued_behind_deferral += 1;
- }
- touched.push(group.routing_key);
- }
-
- // Bin-packing wants the biggest runs placed first so heavy hitters
- // drive the load distribution; P2C is per-run and order-independent.
- if self.router.prefers_largest_first() {
- touched.sort_by_key(|key| std::cmp::Reverse(self.table.queued_len(key)));
- }
-
- // Fresh work routes within the aperture slice, like an unpinned key
- // in the pin-stash scheduler.
- for key in touched {
- if !self.table.is_runnable(&key) {
- continue;
- }
- self.dispatch_or_park(
- &snapshot.candidates,
- &mut load,
- &key,
- SendKind::Fresh,
- &mut effects,
- );
- }
-
- self.record_gauges();
- effects
- }
-
- /// Clear each settled key. Success dispatches the key's next run, or
- /// evicts an emptied key. Failure requeues the failed runs at the front
- /// of their queues, then clears the flags — requeue before release, so a
- /// newer send can never overtake the failed messages — and parks the keys
- /// for the parked-retry deadline.
- fn on_settled(
- &mut self,
- snapshot: &WorkerSnapshot,
- settlement: Settlement,
- ) -> SchedulerEffects {
- let mut effects = SchedulerEffects::default();
- // Built on the first dispatch: the evict path and the failed arm
- // never read the load.
- let mut load: Option<WorkerLoad> = None;
-
- match settlement.outcome {
- SettlementOutcome::Delivered => {
- for key in &settlement.routing_keys {
- if !self.table.settle_key(key) {
- continue;
- }
- if self.table.is_runnable(key) {
- self.dispatch_or_park(
- &snapshot.candidates,
- load.get_or_insert_with(|| working_load(snapshot)),
- key,
- SendKind::Fresh,
- &mut effects,
- );
- } else if self.table.evict_if_idle(key) {
- effects.evicted_keys.push(key.clone());
- }
- }
- }
- SettlementOutcome::Failed { runs, .. } => {
- effects.deferred.send_failed = runs.len() as u64;
- for run in runs {
- self.table.requeue_front(&run.routing_key, run.messages);
- }
- for key in &settlement.routing_keys {
- if !self.table.settle_key(key) {
- continue;
- }
- // Failed work waits for the parked-retry deadline instead
- // of retrying at once, so a failing worker pool gets a
- // pause before the redelivery.
- if self.table.queued_len(key) > 0 {
- self.table.park(key);
- } else if self.table.evict_if_idle(key) {
- effects.evicted_keys.push(key.clone());
- }
- }
- }
- }
-
- self.record_gauges();
- effects
- }
-
- /// Retry every parked key: dispatch the ones that can route now, keep the
- /// rest parked for the next deadline. The per-batch arm belongs to the
- /// pin-stash scheduler and is a no-op here.
- fn on_deadline(
- &mut self,
- snapshot: &WorkerSnapshot,
- deadline: Deadline<'_>,
- ) -> SchedulerEffects {
- let Deadline::ParkedRetry = deadline else {
- return SchedulerEffects::default();
- };
-
- let parked = self.table.take_parked();
- let mut effects = SchedulerEffects::with_dispatch_capacity(parked.len());
- let mut load = working_load(snapshot);
-
- for key in parked {
- // A retry escapes the aperture slice and routes over the whole
- // healthy pool, like a deferred flush: the slice may be exactly
- // what the key could not route into.
- let Some(worker) = self.router.select(&snapshot.healthy, &load) else {
- self.table.repark(key);
- continue;
- };
- // A key parked only as unroutable has never been sent: its retry
- // is a first send, checked strictly by the order sentinel.
- let kind = if self.table.is_redelivering(&key) {
- SendKind::Resend
- } else {
- SendKind::Fresh
- };
- let Some(run) = self.table.take_run(&key) else {
- continue;
- };
- record_queue_wait(&run, kind);
- bump_load(&mut load, &worker, run.messages.len());
- counter!("ingestion_consumer_parked_retries_total").increment(1);
- effects.dispatches.push(Dispatch {
- worker,
- routing_key: key,
- messages: run.messages,
- kind,
- assignment_epoch: Some(run.epoch),
- });
- }
-
- self.record_gauges();
- effects
- }
-
- fn on_partitions_revoked(&mut self, partitions: &[(String, i32)]) -> SchedulerEffects {
- let mut effects = SchedulerEffects::default();
- let (purged, evicted) = self.table.purge_partitions(partitions);
- if purged > 0 {
- counter!("ingestion_consumer_key_table_purged_messages_total").increment(purged as u64);
- }
- effects.evicted_keys = evicted;
- self.record_gauges();
- effects
- }
-}
-
-#[cfg(test)]
-mod tests {
- use std::collections::HashMap;
-
- use super::*;
- use crate::routing::RoutingStrategy;
- use crate::scheduler::WorkerHealth;
-
- const A: &str = "http://worker:1";
- const B: &str = "http://worker:2";
-
- fn wid(s: &str) -> WorkerId {
- WorkerId::from(s)
- }
-
- fn msg(key: &str, offset: i64) -> SerializedKafkaMessage {
- SerializedKafkaMessage {
- topic: "test".into(),
- partition: 0,
- offset,
- timestamp: 0,
- key: Some(key.to_string()),
- value: None,
- headers: HashMap::new(),
- }
- }
-
- fn run(key: &str, offsets: &[i64]) -> KeyRun {
- KeyRun {
- routing_key: key.to_string(),
- messages: offsets.iter().map(|o| msg(key, *o)).collect(),
- }
- }
-
- /// Snapshot where every listed worker is live, with the given loads and
- /// candidates equal to the healthy pool.
- fn snapshot(live: &[&str], load: &[(&str, usize)]) -> WorkerSnapshot {
- snapshot_narrowed(live, live, load)
- }
-
- /// Snapshot with an aperture-narrowed candidate slice.
- fn snapshot_narrowed(
- live: &[&str],
- candidates: &[&str],
- load: &[(&str, usize)],
- ) -> WorkerSnapshot {
- let healthy: Vec<WorkerId> = live.iter().map(|w| wid(w)).collect();
- let candidates: Vec<WorkerId> = candidates.iter().map(|w| wid(w)).collect();
- let workers: HashMap<WorkerId, WorkerHealth> = live
- .iter()
- .map(|w| {
- (
- wid(w),
- WorkerHealth {
- dead: false,
- draining: false,
- },
- )
- })
- .collect();
- let load: WorkerLoad = load.iter().map(|(w, n)| (wid(w), *n)).collect();
- WorkerSnapshot::new(healthy, candidates, load, workers)
- }
-
- fn scheduler() -> KeyTableScheduler {
- KeyTableScheduler::new(Router::with_seed(RoutingStrategy::BinPack, 0))
- }
-
- fn delivered(worker: &str, keys: &[&str]) -> Settlement {
- Settlement {
- worker: wid(worker),
- message_count: keys.len(),
- routing_keys: keys.iter().map(|k| k.to_string()).collect(),
- from_flush: false,
- outcome: SettlementOutcome::Delivered,
- }
- }
-
- fn failed(worker: &str, runs: Vec<KeyRun>) -> Settlement {
- Settlement {
- worker: wid(worker),
- message_count: runs.iter().map(|r| r.messages.len()).sum(),
- routing_keys: runs.iter().map(|r| r.routing_key.clone()).collect(),
- from_flush: false,
- outcome: SettlementOutcome::Failed {
- batch_id: "b".to_string(),
- runs,
- },
- }
- }
-
- fn offsets_of(dispatch: &Dispatch) -> Vec<i64> {
- dispatch.messages.iter().map(|m| m.offset).collect()
- }
-
- // ---- on_groups: arrival ----
-
- #[test]
- fn test_fresh_key_dispatches_its_whole_run_and_goes_outstanding() {
- let mut sched = scheduler();
-
- let effects = sched.on_groups(&snapshot(&[A], &[]), "b1", 0, vec![run("t:a", &[1, 2])]);
-
- assert_eq!(effects.dispatches.len(), 1);
- assert_eq!(effects.dispatches[0].worker, wid(A));
- assert_eq!(effects.dispatches[0].kind, SendKind::Fresh);
- assert_eq!(offsets_of(&effects.dispatches[0]), vec![1, 2]);
- assert_eq!(effects.deferred.total(), 0);
- assert_eq!(sched.table().outstanding_keys(), 1);
- assert_eq!(sched.table().queued_messages(), 0);
- }
-
- #[test]
- fn test_arrival_behind_an_outstanding_request_only_enqueues() {
- let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b1", 0, vec![run("t:a", &[1])]);
-
- let effects = sched.on_groups(&snapshot(&[A], &[]), "b2", 0, vec![run("t:a", &[2])]);
-
- assert!(
- effects.dispatches.is_empty(),
- "at most one request per key may be in flight"
- );
- assert_eq!(effects.deferred.queued_behind_deferral, 1);
- assert_eq!(sched.table().queued_messages(), 1);
- assert_eq!(sched.table().queued_bytes(), "t:a".len());
- assert_eq!(sched.table().outstanding_keys(), 1);
- }
-
- #[test]
- fn test_intra_batch_placement_accounts_for_earlier_picks() {
- let mut sched = scheduler();
-
- // Two fresh equal-size runs, two idle workers: the first pick must
- // bump the working load so the second run lands on the other worker.
- let effects = sched.on_groups(
- &snapshot(&[A, B], &[]),
- "b1",
- 0,
- vec![run("t:a", &[1, 2, 3]), run("t:b", &[1, 2, 3])],
- );
-
- assert_eq!(effects.dispatches.len(), 2);
- assert_ne!(effects.dispatches[0].worker, effects.dispatches[1].worker);
- }
-
- #[test]
- fn test_binpack_places_largest_run_first() {
- let mut sched = scheduler();
-
- let effects = sched.on_groups(
- &snapshot(&[A, B], &[]),
- "b1",
- 0,
- vec![run("t:small", &[1]), run("t:big", &[1, 2, 3, 4, 5])],
- );
-
- assert_eq!(
- effects.dispatches[0].routing_key, "t:big",
- "heavy hitters drive the load distribution"
- );
- }
-
- #[test]
- fn test_duplicate_key_runs_in_one_call_merge_into_one_dispatch() {
- let mut sched = scheduler();
-
- let effects = sched.on_groups(
- &snapshot(&[A], &[]),
- "b1",
- 0,
- vec![run("t:a", &[1]), run("t:a", &[2])],
- );
-
- assert_eq!(effects.dispatches.len(), 1);
- assert_eq!(offsets_of(&effects.dispatches[0]), vec![1, 2]);
- }
-
- #[test]
- fn test_fresh_work_routes_within_the_aperture_slice() {
- let mut sched = scheduler();
-
- // B is healthy but outside the candidate slice — fresh work must not
- // land there.
- let effects = sched.on_groups(
- &snapshot_narrowed(&[A, B], &[A], &[]),
- "b1",
- 0,
- vec![run("t:a", &[1])],
- );
-
- assert_eq!(effects.dispatches[0].worker, wid(A));
- }
-
- // ---- on_groups: parking ----
-
- #[test]
- fn test_unroutable_arrival_parks_the_key() {
- let mut sched = scheduler();
-
- let effects = sched.on_groups(&snapshot(&[], &[]), "b1", 0, vec![run("t:a", &[1, 2])]);
-
- assert!(effects.dispatches.is_empty());
- assert_eq!(effects.deferred.unroutable, 1);
- assert_eq!(sched.table().parked_keys(), 1);
- assert_eq!(sched.table().queued_messages(), 2);
- assert_eq!(sched.table().outstanding_keys(), 0);
- }
-
- #[test]
- fn test_arrival_behind_a_parked_key_waits_for_the_deadline() {
- let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[], &[]), "b1", 0, vec![run("t:a", &[1])]);
-
- // A worker is back, but the parked messages must go first, and only
- // the parked-retry deadline releases them.
- let effects = sched.on_groups(&snapshot(&[A], &[]), "b2", 0, vec![run("t:a", &[2])]);
-
- assert!(effects.dispatches.is_empty());
- assert_eq!(sched.table().parked_keys(), 1);
- assert_eq!(sched.table().queued_messages(), 2);
- }
-
- // ---- on_settled: delivered ----
-
- #[test]
- fn test_settlement_dispatches_the_next_queued_run() {
- let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b1", 0, vec![run("t:a", &[1])]);
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b2", 0, vec![run("t:a", &[2, 3])]);
-
- let effects = sched.on_settled(&snapshot(&[A], &[]), delivered(A, &["t:a"]));
-
- assert_eq!(effects.dispatches.len(), 1);
- assert_eq!(effects.dispatches[0].kind, SendKind::Fresh);
- assert_eq!(offsets_of(&effects.dispatches[0]), vec![2, 3]);
- assert!(effects.evicted_keys.is_empty(), "the key is busy again");
- assert_eq!(sched.table().outstanding_keys(), 1);
- assert_eq!(sched.table().queued_messages(), 0);
- }
-
- #[test]
- fn test_settlement_with_an_empty_queue_evicts_the_key() {
- let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b1", 0, vec![run("t:a", &[1])]);
-
- let effects = sched.on_settled(&snapshot(&[A], &[]), delivered(A, &["t:a"]));
-
- assert_eq!(effects.evicted_keys, vec!["t:a".to_string()]);
- assert!(effects.dispatches.is_empty());
- assert_eq!(sched.table().key_count(), 0);
- assert_eq!(sched.table().outstanding_keys(), 0);
- }
-
- #[test]
- fn test_settlement_parks_the_next_run_when_no_worker_is_routable() {
- let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b1", 0, vec![run("t:a", &[1])]);
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b2", 0, vec![run("t:a", &[2])]);
-
- // The pool emptied while the send was in flight (deploy overlap).
- let effects = sched.on_settled(&snapshot(&[], &[]), delivered(A, &["t:a"]));
-
- assert!(effects.dispatches.is_empty());
- assert_eq!(effects.deferred.unroutable, 1);
- assert_eq!(sched.table().parked_keys(), 1);
- assert_eq!(sched.table().outstanding_keys(), 0);
- }
-
- #[test]
- fn test_settlement_for_an_unknown_key_is_ignored() {
- let mut sched = scheduler();
-
- let effects = sched.on_settled(&snapshot(&[A], &[]), delivered(A, &["t:ghost"]));
-
- assert!(effects.dispatches.is_empty());
- assert!(effects.evicted_keys.is_empty());
- assert_eq!(sched.table().key_count(), 0);
- }
-
- // ---- on_settled: failed ----
-
- #[test]
- fn test_failed_settlement_requeues_at_the_front_and_parks() {
- let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[A, B], &[]), "b1", 0, vec![run("t:a", &[1, 2])]);
- // Newer messages arrive while the send is in flight.
- let _ = sched.on_groups(&snapshot(&[A, B], &[]), "b2", 0, vec![run("t:a", &[3])]);
-
- let effects = sched.on_settled(
- &snapshot(&[A, B], &[]),
- failed(A, vec![run("t:a", &[1, 2])]),
- );
-
- assert!(
- effects.dispatches.is_empty(),
- "failed work waits for the parked-retry deadline"
- );
- assert_eq!(effects.deferred.send_failed, 1);
- assert!(effects.evicted_keys.is_empty());
- assert_eq!(sched.table().parked_keys(), 1);
- assert_eq!(sched.table().outstanding_keys(), 0);
-
- // The retry redelivers the failed run ahead of the later arrival.
- let effects = sched.on_deadline(&snapshot(&[A, B], &[]), Deadline::ParkedRetry);
- assert_eq!(effects.dispatches.len(), 1);
- assert_eq!(effects.dispatches[0].kind, SendKind::Resend);
- assert_eq!(offsets_of(&effects.dispatches[0]), vec![1, 2, 3]);
- }
-
- #[test]
- fn test_a_run_that_fails_twice_is_resent_again_and_ends_clean() {
- let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b1", 0, vec![run("t:a", &[1, 2])]);
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b2", 0, vec![run("t:a", &[3])]);
- let _ = sched.on_settled(&snapshot(&[A], &[]), failed(A, vec![run("t:a", &[1, 2])]));
- let effects = sched.on_deadline(&snapshot(&[A], &[]), Deadline::ParkedRetry);
- assert_eq!(effects.dispatches[0].kind, SendKind::Resend);
- assert_eq!(offsets_of(&effects.dispatches[0]), vec![1, 2, 3]);
-
- // The resend fails too: requeue, park, wait for the next deadline.
- let effects = sched.on_settled(
- &snapshot(&[A], &[]),
- failed(A, vec![run("t:a", &[1, 2, 3])]),
- );
- assert!(effects.dispatches.is_empty());
- assert_eq!(effects.deferred.send_failed, 1);
- assert_eq!(sched.table().parked_keys(), 1);
- assert_eq!(sched.table().outstanding_keys(), 0);
- assert_eq!(sched.table().queued_messages(), 3);
-
- // The second retry is still a resend, in the same order.
- let effects = sched.on_deadline(&snapshot(&[A], &[]), Deadline::ParkedRetry);
- assert_eq!(effects.dispatches.len(), 1);
- assert_eq!(effects.dispatches[0].kind, SendKind::Resend);
- assert_eq!(offsets_of(&effects.dispatches[0]), vec![1, 2, 3]);
- assert_eq!(sched.table().parked_keys(), 0);
- assert_eq!(sched.table().outstanding_keys(), 1);
-
- // Delivery empties the key and evicts it.
- let effects = sched.on_settled(&snapshot(&[A], &[]), delivered(A, &["t:a"]));
- assert_eq!(effects.evicted_keys, vec!["t:a".to_string()]);
- assert_eq!(sched.table().key_count(), 0);
- assert_eq!(sched.table().outstanding_keys(), 0);
- }
-
- #[test]
- fn test_new_arrivals_queue_behind_a_failure_awaiting_retry() {
- let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b1", 0, vec![run("t:a", &[1])]);
- let _ = sched.on_settled(&snapshot(&[A], &[]), failed(A, vec![run("t:a", &[1])]));
-
- let effects = sched.on_groups(&snapshot(&[A], &[]), "b2", 0, vec![run("t:a", &[2])]);
-
- assert!(
- effects.dispatches.is_empty(),
- "must not overtake the failed run"
- );
- assert_eq!(effects.deferred.queued_behind_deferral, 1);
- let effects = sched.on_deadline(&snapshot(&[A], &[]), Deadline::ParkedRetry);
- assert_eq!(offsets_of(&effects.dispatches[0]), vec![1, 2]);
- }
-
- #[test]
- fn test_a_run_never_mixes_assignment_epochs() {
- let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b1", 5, vec![run("t:a", &[1])]);
- // Arrivals from two epochs queue behind the outstanding request.
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b2", 5, vec![run("t:a", &[2])]);
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b3", 6, vec![run("t:a", &[3])]);
-
- let effects = sched.on_settled(&snapshot(&[A], &[]), delivered(A, &["t:a"]));
- assert_eq!(effects.dispatches.len(), 1);
- assert_eq!(offsets_of(&effects.dispatches[0]), vec![2]);
- assert_eq!(effects.dispatches[0].assignment_epoch, Some(5));
-
- let effects = sched.on_settled(&snapshot(&[A], &[]), delivered(A, &["t:a"]));
- assert_eq!(offsets_of(&effects.dispatches[0]), vec![3]);
- assert_eq!(effects.dispatches[0].assignment_epoch, Some(6));
- }
-
- #[test]
- fn test_failed_settlement_for_an_unknown_key_is_not_parked() {
- let mut sched = scheduler();
-
- // Hand-built: the failed() helper derives routing_keys from runs, so
- // it cannot produce a key with no requeued messages.
- let settlement = Settlement {
- worker: wid(A),
- message_count: 0,
- routing_keys: vec!["t:ghost".to_string()],
- from_flush: false,
- outcome: SettlementOutcome::Failed {
- batch_id: "b".to_string(),
- runs: vec![],
- },
- };
- let effects = sched.on_settled(&snapshot(&[A], &[]), settlement);
-
- assert!(effects.dispatches.is_empty());
- assert_eq!(sched.table().key_count(), 0);
- assert_eq!(sched.table().parked_keys(), 0);
-
- let effects = sched.on_deadline(&snapshot(&[A], &[]), Deadline::ParkedRetry);
- assert!(
- effects.dispatches.is_empty(),
- "a stale key must not become a parked entry"
- );
- assert_eq!(sched.table().outstanding_keys(), 0);
- }
-
- // ---- on_deadline ----
-
- #[test]
- fn test_batch_deadline_is_a_noop_for_the_key_table() {
- let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[], &[]), "b1", 0, vec![run("t:a", &[1])]);
-
- let effects = sched.on_deadline(&snapshot(&[A], &[]), Deadline::Batch("b1"));
-
- assert!(effects.dispatches.is_empty());
- assert_eq!(sched.table().parked_keys(), 1, "still parked");
- }
-
- #[test]
- fn test_parked_retry_dispatches_in_park_order_and_unparks() {
- let mut sched = scheduler();
- let _ = sched.on_groups(
- &snapshot(&[], &[]),
- "b1",
- 0,
- vec![run("t:a", &[1]), run("t:b", &[1])],
- );
- assert_eq!(sched.table().parked_keys(), 2);
-
- let effects = sched.on_deadline(&snapshot(&[A], &[]), Deadline::ParkedRetry);
-
- assert_eq!(effects.dispatches.len(), 2);
- assert_eq!(effects.dispatches[0].routing_key, "t:a");
- assert_eq!(effects.dispatches[1].routing_key, "t:b");
- assert_eq!(
- effects.dispatches[0].kind,
- SendKind::Fresh,
- "an unroutable park was never sent, so its retry is a first send"
- );
- assert_eq!(sched.table().parked_keys(), 0);
- assert_eq!(sched.table().outstanding_keys(), 2);
- }
-
- #[test]
- fn test_parked_retry_keeps_keys_parked_when_no_worker_is_healthy() {
- let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[], &[]), "b1", 0, vec![run("t:a", &[1])]);
-
- let effects = sched.on_deadline(&snapshot(&[], &[]), Deadline::ParkedRetry);
-
- assert!(effects.dispatches.is_empty());
- assert_eq!(sched.table().parked_keys(), 1, "kept for a later deadline");
-
- // Arrivals in the meantime still queue behind the parked work.
- let effects = sched.on_groups(&snapshot(&[], &[]), "b2", 0, vec![run("t:a", &[2])]);
- assert!(effects.dispatches.is_empty());
- let effects = sched.on_deadline(&snapshot(&[A], &[]), Deadline::ParkedRetry);
- assert_eq!(offsets_of(&effects.dispatches[0]), vec![1, 2]);
- }
-
- #[test]
- fn test_parked_retry_routes_over_the_whole_healthy_pool() {
- let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[], &[]), "b1", 0, vec![run("t:a", &[1])]);
-
- // The aperture slice is empty but a worker is healthy: the retry must
- // escape the slice, like a deferred flush.
- let effects = sched.on_deadline(&snapshot_narrowed(&[B], &[], &[]), Deadline::ParkedRetry);
-
- assert_eq!(effects.dispatches.len(), 1);
- assert_eq!(effects.dispatches[0].worker, wid(B));
- }
-
- #[test]
- fn test_revoked_partitions_purge_queued_messages() {
- let mut sched = scheduler();
- // Key a queues behind its outstanding request; key b parks unroutable.
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b1", 0, vec![run("t:a", &[1])]);
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b2", 0, vec![run("t:a", &[2])]);
- let _ = sched.on_groups(&snapshot(&[], &[]), "b3", 0, vec![run("t:b", &[1])]);
-
- // An unrelated partition purges nothing.
- let effects = sched.on_partitions_revoked(&[("test".to_string(), 7)]);
- assert!(effects.evicted_keys.is_empty());
- assert_eq!(sched.table().queued_messages(), 2);
-
- let effects = sched.on_partitions_revoked(&[("test".to_string(), 0)]);
-
- assert_eq!(sched.table().queued_messages(), 0);
- assert_eq!(sched.table().queued_bytes(), 0);
- assert_eq!(sched.table().parked_keys(), 0);
- assert_eq!(
- effects.evicted_keys,
- vec!["t:b".to_string()],
- "the emptied parked key goes; the outstanding key stays"
- );
- assert_eq!(sched.table().outstanding_keys(), 1);
-
- // The outstanding key's settlement finds nothing queued and evicts it.
- let effects = sched.on_settled(&snapshot(&[A], &[]), delivered(A, &["t:a"]));
- assert!(effects.dispatches.is_empty());
- assert_eq!(sched.table().key_count(), 0);
- }
-
- #[test]
- fn test_revoked_outstanding_failure_is_not_retried() {
- let mut sched = scheduler();
- let live = snapshot(&[A], &[]);
- let sent = sched.on_groups(&live, "b1", 5, vec![run("t:a", &[1])]);
- assert_eq!(sent.dispatches.len(), 1);
-
- // No queued messages exist to identify the outstanding run during purge.
- let _ = sched.on_partitions_revoked(&[("test".to_string(), 0)]);
- let settled = sched.on_settled(&live, failed(A, vec![run("t:a", &[1])]));
- assert!(settled.dispatches.is_empty());
-
- let retry = sched.on_deadline(&live, Deadline::ParkedRetry);
- assert!(
- retry.dispatches.is_empty(),
- "a failed send must not resurrect revoked work"
- );
- assert_eq!(sched.table().key_count(), 0);
- assert_eq!(sched.table().queued_messages(), 0);
- assert_eq!(sched.table().queued_bytes(), 0);
- assert_eq!(sched.table().outstanding_keys(), 0);
- assert_eq!(sched.table().parked_keys(), 0);
- }
-
- #[test]
- fn test_revoked_outstanding_failure_preserves_kept_partitions() {
- let mut sched = scheduler();
- let live = snapshot(&[A], &[]);
- let mixed_run = || {
- let mut mixed = run("t:a", &[1, 2, 3, 4]);
- mixed.messages[1].partition = 1;
- mixed.messages[2].topic = "other".into();
- mixed.messages[3].partition = 2;
- mixed
- };
- let sent = sched.on_groups(&live, "b1", 5, vec![mixed_run()]);
- assert_eq!(sent.dispatches.len(), 1);
-
- let _ = sched.on_partitions_revoked(&[("test".to_string(), 0)]);
- let _ = sched.on_partitions_revoked(&[("test".to_string(), 2)]);
- let _ = sched.on_settled(&live, failed(A, vec![mixed_run()]));
-
- let retry = sched.on_deadline(&live, Deadline::ParkedRetry);
- assert_eq!(retry.dispatches.len(), 1);
- assert_eq!(
- offsets_of(&retry.dispatches[0]),
- vec![2, 3],
- "only revoked topic-partitions may be discarded"
- );
- assert_eq!(retry.dispatches[0].assignment_epoch, Some(5));
- let _ = sched.on_settled(&live, delivered(A, &["t:a"]));
- assert_eq!(sched.table().key_count(), 0);
- assert_eq!(sched.table().queued_bytes(), 0);
- }
-
- #[test]
- fn test_revoked_outstanding_failure_preserves_reassigned_work() {
- let mut sched = scheduler();
- let live = snapshot(&[A], &[]);
- let sent = sched.on_groups(&live, "b1", 5, vec![run("t:a", &[1])]);
- assert_eq!(sent.dispatches.len(), 1);
- let _ = sched.on_partitions_revoked(&[("test".to_string(), 0)]);
-
- // The same offset is polled again before the old send settles.
- let queued = sched.on_groups(&live, "b2", 6, vec![run("t:a", &[1, 2])]);
- assert!(queued.dispatches.is_empty());
- let _ = sched.on_settled(&live, failed(A, vec![run("t:a", &[1])]));
-
- let retry = sched.on_deadline(&live, Deadline::ParkedRetry);
- assert_eq!(retry.dispatches.len(), 1);
- assert_eq!(offsets_of(&retry.dispatches[0]), vec![1, 2]);
- assert_eq!(retry.dispatches[0].assignment_epoch, Some(6));
- assert_eq!(retry.dispatches[0].kind, SendKind::Fresh);
-
- // Revocation of the old assignment must not suppress this run's retries.
- let _ = sched.on_settled(&live, failed(A, vec![run("t:a", &[1, 2])]));
- let retry = sched.on_deadline(&live, Deadline::ParkedRetry);
- assert_eq!(retry.dispatches.len(), 1);
- assert_eq!(offsets_of(&retry.dispatches[0]), vec![1, 2]);
- assert_eq!(retry.dispatches[0].assignment_epoch, Some(6));
- assert_eq!(retry.dispatches[0].kind, SendKind::Resend);
- let _ = sched.on_settled(&live, delivered(A, &["t:a"]));
- assert_eq!(sched.table().key_count(), 0);
- assert_eq!(sched.table().queued_bytes(), 0);
- }
-
- // ---- lifecycle ----
-
- #[test]
- fn test_full_lifecycle_preserves_per_key_order_and_ends_clean() {
- let mut sched = scheduler();
- let mut sent: Vec<i64> = Vec::new();
- let mut record = |effects: &SchedulerEffects| {
- for dispatch in &effects.dispatches {
- assert_eq!(dispatch.routing_key, "t:a");
- sent.extend(dispatch.messages.iter().map(|m| m.offset));
- }
- effects.dispatches.len()
- };
-
- // Arrive, dispatch, fail, queue more, retry, settle, queue drains.
- let effects = sched.on_groups(&snapshot(&[A], &[]), "b1", 0, vec![run("t:a", &[1, 2])]);
- assert_eq!(record(&effects), 1);
- let effects = sched.on_groups(&snapshot(&[A], &[]), "b2", 0, vec![run("t:a", &[3])]);
- assert_eq!(record(&effects), 0);
- let effects = sched.on_settled(&snapshot(&[A], &[]), failed(A, vec![run("t:a", &[1, 2])]));
- assert_eq!(record(&effects), 0);
- let effects = sched.on_deadline(&snapshot(&[A], &[]), Deadline::ParkedRetry);
- assert_eq!(record(&effects), 1);
- let effects = sched.on_groups(&snapshot(&[A], &[]), "b3", 0, vec![run("t:a", &[4])]);
- assert_eq!(record(&effects), 0);
- let effects = sched.on_settled(&snapshot(&[A], &[]), delivered(A, &["t:a"]));
- assert_eq!(record(&effects), 1);
- let effects = sched.on_settled(&snapshot(&[A], &[]), delivered(A, &["t:a"]));
- assert_eq!(record(&effects), 0);
-
- // The failed prefix is redelivered once, and every offset goes out in order.
- assert_eq!(sent, vec![1, 2, 1, 2, 3, 4]);
- assert_eq!(effects.evicted_keys, vec!["t:a".to_string()]);
- assert_eq!(sched.table().key_count(), 0);
- assert_eq!(sched.table().queued_messages(), 0);
- assert_eq!(sched.table().queued_bytes(), 0);
- assert_eq!(sched.table().outstanding_keys(), 0);
- assert_eq!(sched.table().parked_keys(), 0);
- }
-
- #[test]
- fn test_keys_progress_independently() {
- let mut sched = scheduler();
- let _ = sched.on_groups(
- &snapshot(&[A, B], &[]),
- "b1",
- 0,
- vec![run("t:a", &[1]), run("t:b", &[1])],
- );
- let _ = sched.on_groups(
- &snapshot(&[A, B], &[]),
- "b2",
- 0,
- vec![run("t:a", &[2]), run("t:b", &[2])],
- );
-
- // Only t:a settles — only t:a's next run may go out.
- let effects = sched.on_settled(&snapshot(&[A, B], &[]), delivered(A, &["t:a"]));
-
- assert_eq!(effects.dispatches.len(), 1);
- assert_eq!(effects.dispatches[0].routing_key, "t:a");
- assert_eq!(sched.table().queued_messages(), 1, "t:b still queued");
- }
-}
diff --git a/rust/ingestion-consumer/src/lib.rs b/rust/ingestion-consumer/src/lib.rs
index 8e7bd59eeee5..b96e5d7c2399 100644
--- a/rust/ingestion-consumer/src/lib.rs
+++ b/rust/ingestion-consumer/src/lib.rs
@@ -10,7 +10,6 @@ pub mod discovery;
pub mod dispatcher;
pub mod grpc_transport;
pub mod kafka_stats;
-pub mod key_table;
pub mod ledger_rejection;
pub mod order_sentinel;
pub mod readiness;
diff --git a/rust/ingestion-consumer/src/main.rs b/rust/ingestion-consumer/src/main.rs
index 510183e08011..f89c7835d8d4 100644
--- a/rust/ingestion-consumer/src/main.rs
+++ b/rust/ingestion-consumer/src/main.rs
@@ -29,6 +29,7 @@ use ingestion_consumer::discovery::{
use ingestion_consumer::dispatcher::Dispatcher;
use ingestion_consumer::grpc_transport::{GrpcPort, GrpcTransport};
use ingestion_consumer::routing::RoutingStrategy;
+use ingestion_consumer::scheduler::SchedulerKind;
use ingestion_consumer::worker_registry::{WorkerId, WorkerRegistry, WorkerRegistryConfig};
common_alloc::used!();
@@ -143,12 +144,32 @@ async fn async_main(config: Config) -> Result<()> {
)
.expect("consumer_batch_size_kb buckets")
.set_buckets_for_metric(
- Matcher::Full("ingestion_consumer_key_table_queue_wait_seconds".into()),
+ Matcher::Full("ingestion_consumer_request_queue_wait_seconds".into()),
&[
0.005, 0.025, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0,
],
)
- .expect("key_table_queue_wait buckets");
+ .expect("request_queue_wait buckets")
+ .set_buckets_for_metric(
+ Matcher::Full("ingestion_consumer_request_events".into()),
+ &[
+ 1.0, 10.0, 50.0, 100.0, 250.0, 500.0, 1_000.0, 2_500.0, 5_000.0,
+ ],
+ )
+ .expect("request_events buckets")
+ .set_buckets_for_metric(
+ Matcher::Full("ingestion_consumer_request_bytes".into()),
+ &[
+ 1_024.0,
+ 16_384.0,
+ 65_536.0,
+ 262_144.0,
+ 1_048_576.0,
+ 4_194_304.0,
+ 16_777_216.0,
+ ],
+ )
+ .expect("request_bytes buckets");
// Global default labels (match the Node.js `initializePrometheusLabels`
// defaults): every metric carries ingestion_pipeline / ingestion_lane so
@@ -227,11 +248,7 @@ async fn async_main(config: Config) -> Result<()> {
None
};
- let mut dispatcher = Dispatcher::with_scheduler(
- Arc::clone(&registry),
- config.routing_strategy,
- config.scheduler,
- );
+ let mut dispatcher = Dispatcher::with_strategy(Arc::clone(&registry), config.routing_strategy);
if let Some(recorder) = &debug_recorder {
dispatcher.set_debug_recorder(Arc::clone(recorder));
}
@@ -288,36 +305,6 @@ async fn async_main(config: Config) -> Result<()> {
};
let _discovery_handle = discovery.start(Arc::clone(&registry), discovery_token.clone());
- // Reap drained workers: once a departed worker has finished its in-flight
- // batches (or hit the drain timeout), remove it from the registry and prune
- // its transport semaphore. No-op in static mode (workers never drain).
- {
- let registry = Arc::clone(&registry);
- let transport = Arc::clone(&transport);
- let dispatcher = Arc::clone(&dispatcher);
- let token = probe_token.clone();
- tokio::spawn(async move {
- loop {
- tokio::select! {
- _ = token.cancelled() => break,
- _ = tokio::time::sleep(Duration::from_secs(1)) => {}
- }
- // A worker that left the pool while idle has no in-flight to
- // resolve, so `on_sub_batch_resolved` never completes its drain.
- // Complete it here so it's reaped now rather than at the timeout.
- for worker in registry.draining_workers() {
- if !dispatcher.has_in_flight(&worker) {
- registry.complete_drain(&worker);
- }
- }
- for worker in registry.reapable_workers() {
- registry.remove_worker(&worker);
- transport.remove_worker(&worker);
- }
- }
- });
- }
-
// Build and serve the health/metrics HTTP server BEFORE gating on worker
// discovery. Otherwise /_readiness and /_liveness stay unbound while we wait
// for the first workers, so kubelet sees "connection refused" instead of a
@@ -502,13 +489,54 @@ 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),
- Duration::from_millis(config.parked_retry_interval_ms),
- );
+ let (batcher, batcher_outputs) = match config.scheduler {
+ SchedulerKind::PinStash => Batcher::new(
+ Arc::clone(&dispatcher),
+ Arc::clone(&transport),
+ consumer_handle.clone(),
+ Duration::from_millis(config.consumer_deferred_flush_timeout_ms),
+ ),
+ SchedulerKind::KeyTable => {
+ let state_machine = config
+ .batcher_state_machine()
+ .map_err(|err| anyhow::anyhow!("invalid key-table configuration: {err}"))?;
+ Batcher::with_state_machine(
+ state_machine,
+ dispatcher.worker_pool_source(),
+ Arc::clone(&transport),
+ )
+ }
+ };
+
+ // Reap drained workers: once a departed worker has finished its in-flight
+ // batches (or hit the drain timeout), remove it from the registry and prune
+ // its transport semaphore. No-op in static mode (workers never drain).
+ {
+ let registry = Arc::clone(&registry);
+ let transport = Arc::clone(&transport);
+ let observer = batcher.observer();
+ let token = probe_token.clone();
+ tokio::spawn(async move {
+ loop {
+ tokio::select! {
+ _ = token.cancelled() => break,
+ _ = tokio::time::sleep(Duration::from_secs(1)) => {}
+ }
+ // A worker that left the pool while idle has no in-flight to
+ // resolve, so `on_sub_batch_resolved` never completes its drain.
+ // Complete it here so it's reaped now rather than at the timeout.
+ for worker in registry.draining_workers() {
+ if !observer.has_in_flight(&worker) {
+ registry.complete_drain(&worker);
+ }
+ }
+ for worker in registry.reapable_workers() {
+ registry.remove_worker(&worker);
+ transport.remove_worker(&worker);
+ }
+ }
+ });
+ }
let consumer = IngestionConsumer::new(
&config,
diff --git a/rust/ingestion-consumer/src/order_sentinel.rs b/rust/ingestion-consumer/src/order_sentinel.rs
index c1efd8b971a3..88143e8af2e8 100644
--- a/rust/ingestion-consumer/src/order_sentinel.rs
+++ b/rust/ingestion-consumer/src/order_sentinel.rs
@@ -122,7 +122,7 @@ struct KeyState {
pub struct KeyOrderSentinel {
/// Keyed by customer-chosen routing keys, so the hasher is seeded per
/// map to resist collision flooding.
- keys: Mutex<HashMap<String, KeyState, ahash::RandomState>>,
+ keys: Mutex<HashMap<Arc<str>, KeyState, ahash::RandomState>>,
/// Kill switch (`CONSUMER_ORDER_SENTINEL_ENABLED`). When off, checks
/// no-op and no state accumulates.
enabled: AtomicBool,
@@ -174,33 +174,71 @@ impl KeyOrderSentinel {
self.keys.lock().unwrap().len()
}
}
+/// A routing key the sentinel looks up as `&str` and stores as `Arc<str>`,
+/// so a caller that already shares its keys stores them without a copy.
+pub trait SentinelKey {
+ fn as_key(&self) -> &str;
+ fn to_shared(&self) -> Arc<str>;
+}
+
+impl SentinelKey for str {
+ fn as_key(&self) -> &str {
+ self
+ }
+
+ fn to_shared(&self) -> Arc<str> {
+ Arc::from(self)
+ }
+}
+
+impl SentinelKey for String {
+ fn as_key(&self) -> &str {
+ self
+ }
+
+ fn to_shared(&self) -> Arc<str> {
+ Arc::from(self.as_str())
+ }
+}
+
+impl SentinelKey for Arc<str> {
+ fn as_key(&self) -> &str {
+ self
+ }
+
+ fn to_shared(&self) -> Arc<str> {
+ Arc::clone(self)
+ }
+}
/// A run of sentinel calls under one lock. Disabled, every call is a no-op.
pub struct SentinelBatch<'a> {
- keys: Option<MutexGuard<'a, HashMap<String, KeyState, ahash::RandomState>>>,
+ keys: Option<MutexGuard<'a, HashMap<Arc<str>, KeyState, ahash::RandomState>>>,
}
impl SentinelBatch<'_> {
/// Record that `messages` for `routing_key` are being handed to a worker.
/// `kind` distinguishes a fresh assignment (offsets must only move
/// forward) from a retry-path resend (repeating un-ACKed offsets is
- /// legal). Call at assignment time, under the dispatcher's pin-table
- /// lock, so the check order matches the intended per-key send order.
- /// Null-key messages are skipped — they carry no per-key order promise
- /// (see module docs). Emits metrics and logs; returns violations for
- /// tests.
+ /// legal). Call in the intended per-key send order. Null-key messages are
+ /// skipped — they carry no per-key order promise (see module docs). Emits
+ /// metrics and logs; returns violations for tests.
pub fn note_sent(
&mut self,
- routing_key: &str,
+ key: &(impl SentinelKey + ?Sized),
messages: &[SerializedKafkaMessage],
kind: SendKind,
) -> Vec<KeyOrderViolation> {
let Some(keys) = self.keys.as_mut() else {
return Vec::new();
};
+ let routing_key = key.as_key();
let mut violations = Vec::new();
let mut first: Option<&SerializedKafkaMessage> = None;
let mut last: Option<&SerializedKafkaMessage> = None;
+ // The watermark tracks one partition; a key run merged across
+ // partitions must not mix another partition's offset into it.
+ let mut last_on_first_partition = None;
let mut unkeyed = 0usize;
for message in messages {
if message.key.is_none() {
@@ -220,23 +258,26 @@ impl SentinelBatch<'_> {
});
}
}
- first.get_or_insert(message);
+ let first = first.get_or_insert(message);
+ if message.partition == first.partition {
+ last_on_first_partition = Some(message.offset);
+ }
last = Some(message);
}
if unkeyed > 0 {
counter!("ingestion_consumer_key_sentinel_unkeyed_total").increment(unkeyed as u64);
}
- let (Some(first), Some(last)) = (first, last) else {
+ let (Some(first), Some(last_sent)) = (first, last_on_first_partition) else {
return violations;
};
match keys.get_mut(routing_key) {
None => {
keys.insert(
- routing_key.to_string(),
+ key.to_shared(),
KeyState {
partition: first.partition,
- last_sent: last.offset,
+ last_sent,
last_acked: None,
},
);
@@ -251,12 +292,12 @@ impl SentinelBatch<'_> {
counter!("ingestion_consumer_key_partition_moves_total").increment(1);
*state = KeyState {
partition: first.partition,
- last_sent: last.offset,
+ last_sent,
last_acked: None,
};
} else if first.offset > state.last_sent {
// Normal forward progress.
- state.last_sent = last.offset;
+ state.last_sent = last_sent;
} else if state.last_acked.is_some_and(|acked| first.offset <= acked) {
violations.push(KeyOrderViolation {
kind: KeyOrderViolationKind::ResendAfterAck,
@@ -264,12 +305,12 @@ impl SentinelBatch<'_> {
partition: first.partition,
offset: first.offset,
});
- state.last_sent = state.last_sent.max(last.offset);
+ state.last_sent = state.last_sent.max(last_sent);
} else if kind == SendKind::Resend {
// Replay of a not-yet-ACKed range: the legal retry path
// (send failure → defer → flush re-routes the same messages).
counter!("ingestion_consumer_key_replays_total").increment(1);
- state.last_sent = state.last_sent.max(last.offset);
+ state.last_sent = state.last_sent.max(last_sent);
} else {
// A fresh send regressed: a newer batch's assignment for
// this key overtook an older batch's. (A rebalance racing
@@ -282,7 +323,7 @@ impl SentinelBatch<'_> {
partition: first.partition,
offset: first.offset,
});
- state.last_sent = state.last_sent.max(last.offset);
+ state.last_sent = state.last_sent.max(last_sent);
}
}
}
@@ -337,13 +378,12 @@ impl Drop for SentinelBatch<'_> {
/// The consumer's rdkafka context: observes async commit results (a
/// fire-and-forget `CommitMode::Async` failure is otherwise invisible until
-/// restart-time redelivery), resets sentinel baselines around rebalances, and
+/// restart-time redelivery), forgets revoked partitions around rebalances, and
/// exports librdkafka's internal statistics (see [`crate::kafka_stats`]).
pub struct SentinelContext {
/// Where the consumer's frontiers go. Held here so the rebalance
/// callbacks tell it which partitions leave the assignment.
commit_sentinel: Arc<CommitSentinel>,
- key_sentinel: Arc<KeyOrderSentinel>,
/// The offset ledger the commit path settles against. Owned here so the
/// rebalance callbacks forget partitions on the same ledger.
topic_offset_ledger: Arc<TopicOffsetLedger>,
@@ -357,17 +397,15 @@ pub struct SentinelContext {
revoke_hook: OnceLock<RevokeHook>,
}
-type RevokeHook = Box<dyn Fn(&[(String, i32)]) + Send + Sync>;
+pub type RevokeHook = Box<dyn Fn(&[(String, i32)]) + Send + Sync>;
impl SentinelContext {
pub fn new(
commit_sentinel: Arc<CommitSentinel>,
- key_sentinel: Arc<KeyOrderSentinel>,
topic_offset_ledger: Arc<TopicOffsetLedger>,
) -> Self {
Self {
commit_sentinel,
- key_sentinel,
topic_offset_ledger,
assignment_epoch: None,
revoke_hook: OnceLock::new(),
@@ -392,7 +430,6 @@ impl SentinelContext {
pub fn detached() -> Self {
Self::new(
Arc::new(CommitSentinel::new(ImmediateCommitPacer::new())),
- Arc::new(KeyOrderSentinel::new()),
Arc::new(TopicOffsetLedger::new()),
)
}
@@ -451,10 +488,6 @@ impl ConsumerContext for SentinelContext {
"Rebalance: partitions revoked"
);
self.forget_ledger_partitions(tpl);
- // Revoked partitions may be replayed by another consumer (or by
- // us after re-assignment) from the last commit — every per-key
- // baseline is stale.
- self.key_sentinel.clear();
// The hook must run after the ledger forget above: it stamps
// each revocation with the bumped generation so only older
// poll slices are stripped.
@@ -723,6 +756,19 @@ mod tests {
.is_empty());
}
+ #[test]
+ fn a_send_spanning_two_partitions_keeps_the_first_partitions_watermark() {
+ let sentinel = KeyOrderSentinel::new();
+ assert!(sentinel
+ .batch()
+ .note_sent("t:a", &[msg_at(1, 5), msg_at(0, 100)], SendKind::Fresh)
+ .is_empty());
+ assert!(sentinel
+ .batch()
+ .note_sent("t:a", &[msg_at(1, 6)], SendKind::Fresh)
+ .is_empty());
+ }
+
#[test]
fn null_key_messages_are_ignored() {
let sentinel = KeyOrderSentinel::new();
diff --git a/rust/ingestion-consumer/src/scheduler.rs b/rust/ingestion-consumer/src/scheduler.rs
index 01b5047dbeca..79815445a237 100644
--- a/rust/ingestion-consumer/src/scheduler.rs
+++ b/rust/ingestion-consumer/src/scheduler.rs
@@ -122,17 +122,6 @@ pub enum SettlementOutcome {
},
}
-/// The retry deadline that fired. Each scheduler paces retries its own way
-/// and answers only its own arm; the other arm is a no-op.
-pub enum Deadline<'a> {
- /// The flush deadline for one batch's deferred work — the pin-stash
- /// pacing, fired oldest batch first.
- Batch(&'a str),
- /// The parked-retry deadline: retry every parked key — the key-table
- /// pacing.
- ParkedRetry,
-}
-
/// Groups deferred by one seam call, by reason. The caller emits the debug
/// events from these; the scheduler emits its own counters.
#[derive(Default)]
@@ -183,6 +172,9 @@ impl SchedulerEffects {
pub enum SchedulerKind {
#[default]
PinStash,
+ /// The batcher state machine: per-key queues with at most one request
+ /// in flight per key, and placement at send. It replaces the
+ /// dispatcher's scheduling.
KeyTable,
}
@@ -222,18 +214,9 @@ pub trait Scheduler {
fn on_settled(&mut self, snapshot: &WorkerSnapshot, settlement: Settlement)
-> SchedulerEffects;
- /// A retry deadline fired.
- fn on_deadline(
- &mut self,
- snapshot: &WorkerSnapshot,
- deadline: Deadline<'_>,
- ) -> SchedulerEffects;
-
- /// Partitions were revoked, as `(topic, partition)`. Queued messages for
- /// them must drop: the new partition owner replays them.
- fn on_partitions_revoked(&mut self, _partitions: &[(String, i32)]) -> SchedulerEffects {
- SchedulerEffects::default()
- }
+ /// The flush deadline for one batch's deferred work fired. Deadlines
+ /// fire oldest batch first.
+ fn on_deadline(&mut self, snapshot: &WorkerSnapshot, batch_id: &str) -> SchedulerEffects;
}
/// Sticky pin for one routing key. Tracks which worker owns the key and how
@@ -516,16 +499,8 @@ impl Scheduler for PinStashScheduler {
/// that the key's earlier in-flight has resolved, re-pinning it. Groups
/// that can't route yet (no healthy worker) stay stashed for the next
/// deadline. Cross-key order is preserved because the caller fires
- /// deadlines oldest batch first. The parked-retry arm belongs to the
- /// key-table scheduler and is a no-op here.
- fn on_deadline(
- &mut self,
- snapshot: &WorkerSnapshot,
- deadline: Deadline<'_>,
- ) -> SchedulerEffects {
- let Deadline::Batch(batch_id) = deadline else {
- return SchedulerEffects::default();
- };
+ /// deadlines oldest batch first.
+ fn on_deadline(&mut self, snapshot: &WorkerSnapshot, batch_id: &str) -> SchedulerEffects {
let groups = self.stash.take_batch(batch_id);
if groups.is_empty() {
return SchedulerEffects::default();
@@ -957,7 +932,7 @@ mod tests {
// The deferred flush re-points the pin to B while b1's send is still
// unresolved on A.
- let effects = sched.on_deadline(&snapshot(&[B], &[A], &[]), Deadline::Batch("b2"));
+ let effects = sched.on_deadline(&snapshot(&[B], &[A], &[]), "b2");
assert_eq!(effects.dispatches[0].worker, wid(B));
let ref_count = sched.pins.get("t:a").unwrap().ref_count;
@@ -998,7 +973,7 @@ mod tests {
let mut sched = scheduler();
sched.register_batch("b1");
let _ = sched.on_groups(&snapshot(&[], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
- let effects = sched.on_deadline(&snapshot(&[A], &[], &[]), Deadline::Batch("b1"));
+ let effects = sched.on_deadline(&snapshot(&[A], &[], &[]), "b1");
assert_eq!(effects.dispatches.len(), 1);
// The flushed send fails: the re-stash and the from_flush decrement
@@ -1020,34 +995,20 @@ mod tests {
fn test_deadline_with_nothing_stashed_is_a_noop() {
let mut sched = scheduler();
- let effects = sched.on_deadline(&snapshot(&[A], &[], &[]), Deadline::Batch("b1"));
+ let effects = sched.on_deadline(&snapshot(&[A], &[], &[]), "b1");
assert!(effects.dispatches.is_empty());
assert_eq!(effects.deferred.total(), 0);
assert!(effects.evicted_keys.is_empty());
}
- #[test]
- fn test_parked_retry_deadline_is_a_noop_for_pin_stash() {
- let mut sched = scheduler();
- sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
-
- // The parked-retry pacing belongs to the key-table scheduler; the
- // pin-stash stash flushes only on its per-batch deadline.
- let effects = sched.on_deadline(&snapshot(&[A], &[], &[]), Deadline::ParkedRetry);
-
- assert!(effects.dispatches.is_empty());
- assert_eq!(sched.stashed_messages(), 1);
- }
-
#[test]
fn test_deadline_keeps_group_stashed_when_no_worker_is_healthy() {
let mut sched = scheduler();
sched.register_batch("b1");
let _ = sched.on_groups(&snapshot(&[], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
- let effects = sched.on_deadline(&snapshot(&[], &[], &[]), Deadline::Batch("b1"));
+ let effects = sched.on_deadline(&snapshot(&[], &[], &[]), "b1");
assert!(effects.dispatches.is_empty());
assert!(sched.has_batch("b1"), "kept for a later deadline");
@@ -1063,7 +1024,7 @@ mod tests {
let _ = sched.on_groups(&snapshot(&[B], &[A], &[]), "b2", 0, vec![run("t:a", 1)]);
let _ = sched.on_settled(&snapshot(&[B], &[A], &[]), delivered(A, &["t:a"], false));
- let effects = sched.on_deadline(&snapshot(&[B], &[A], &[]), Deadline::Batch("b2"));
+ let effects = sched.on_deadline(&snapshot(&[B], &[A], &[]), "b2");
assert_eq!(effects.dispatches.len(), 1);
assert_eq!(effects.dispatches[0].kind, SendKind::Resend);
assert_eq!(
@@ -1083,7 +1044,7 @@ mod tests {
// free to flush and the key's life cycle ends clean.
let effects = sched.on_settled(&snapshot(&[B], &[A], &[]), delivered(B, &["t:a"], true));
assert!(effects.evicted_keys.is_empty(), "b3's group still stashed");
- let effects = sched.on_deadline(&snapshot(&[B], &[A], &[]), Deadline::Batch("b3"));
+ let effects = sched.on_deadline(&snapshot(&[B], &[A], &[]), "b3");
assert_eq!(effects.dispatches.len(), 1);
let effects = sched.on_settled(&snapshot(&[B], &[A], &[]), delivered(B, &["t:a"], true));
assert_eq!(effects.evicted_keys, vec!["t:a".to_string()]);
diff --git a/rust/ingestion-consumer/tests/common/mod.rs b/rust/ingestion-consumer/tests/common/mod.rs
new file mode 100644
index 000000000000..6ceadeb3f433
--- /dev/null
+++ b/rust/ingestion-consumer/tests/common/mod.rs
@@ -0,0 +1,52 @@
+//! Batcher construction shared by the integration suites. Each suite compiles
+//! this module separately and uses part of it.
+#![allow(dead_code)]
+
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use ingestion_consumer::batcher::retry_policy::RetryPolicy;
+use ingestion_consumer::batcher::state_machine::BatcherStateMachine;
+use ingestion_consumer::batcher::worker_assigner::WorkerAssigner;
+use ingestion_consumer::batcher::{Batcher, BatcherOutputs};
+use ingestion_consumer::dispatcher::Dispatcher;
+use ingestion_consumer::grpc_transport::GrpcTransport;
+use ingestion_consumer::routing::Router;
+use ingestion_consumer::scheduler::SchedulerKind;
+use lifecycle::Handle;
+
+/// `stall_timeout` is the deferred-flush timeout for pin-stash and the stall
+/// timeout for the state machine.
+pub fn batcher(
+ kind: SchedulerKind,
+ dispatcher: &Arc<Dispatcher>,
+ transport: Arc<GrpcTransport>,
+ handle: Handle,
+ stall_timeout: Duration,
+ retry_delay: Duration,
+) -> (Batcher, BatcherOutputs) {
+ match kind {
+ SchedulerKind::PinStash => {
+ Batcher::new(Arc::clone(dispatcher), transport, handle, stall_timeout)
+ }
+ SchedulerKind::KeyTable => {
+ key_table_batcher(dispatcher, transport, stall_timeout, retry_delay)
+ }
+ }
+}
+
+pub fn key_table_batcher(
+ dispatcher: &Dispatcher,
+ transport: Arc<GrpcTransport>,
+ stall_timeout: Duration,
+ retry_delay: Duration,
+) -> (Batcher, BatcherOutputs) {
+ let pool_source = dispatcher.worker_pool_source();
+ let assigner =
+ WorkerAssigner::new(Router::new(pool_source.strategy()), transport.max_unacked())
+ .expect("valid request cap");
+ let retry = RetryPolicy::uniform(retry_delay).expect("valid retry delay");
+ let state_machine = BatcherStateMachine::new(assigner, retry, stall_timeout, Instant::now())
+ .expect("valid stall timeout");
+ Batcher::with_state_machine(state_machine, pool_source, transport)
+}
diff --git a/rust/ingestion-consumer/tests/dispatcher_integration_test.rs b/rust/ingestion-consumer/tests/dispatcher_integration_test.rs
index 25cd693b7288..c2de61391c4e 100644
--- a/rust/ingestion-consumer/tests/dispatcher_integration_test.rs
+++ b/rust/ingestion-consumer/tests/dispatcher_integration_test.rs
@@ -1,10 +1,11 @@
+mod common;
+
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use common_kafka_consumer::Partition;
-use lifecycle::{ComponentOptions, Manager};
use axum::extract::State;
use axum::response::IntoResponse;
@@ -13,11 +14,10 @@ use axum::Router;
use tokio::net::TcpListener;
use tokio_util::sync::CancellationToken;
-use ingestion_consumer::batcher::Batcher;
+use common::key_table_batcher;
use ingestion_consumer::dispatcher::Dispatcher;
use ingestion_consumer::grpc_transport::{GrpcPort, GrpcTransport};
use ingestion_consumer::routing::RoutingStrategy;
-use ingestion_consumer::scheduler::SchedulerKind;
use ingestion_consumer::types::{Accumulator, SerializedKafkaMessage};
use ingestion_consumer::worker_registry::{WorkerRegistry, WorkerRegistryConfig, WorkerState};
@@ -478,25 +478,18 @@ async fn test_draining_worker_defers_then_flushes_to_survivor() {
#[tokio::test(flavor = "current_thread")]
async fn purging_a_just_submitted_key_table_batch_is_not_fatal() {
let registry = Arc::new(WorkerRegistry::new(&[], fast_config()));
- let dispatcher = Arc::new(Dispatcher::with_scheduler(
+ let dispatcher = Arc::new(Dispatcher::with_strategy(
registry,
RoutingStrategy::BinPack,
- SchedulerKind::KeyTable,
));
let transport = Arc::new(GrpcTransport::new(
GrpcPort::OffsetFromHttp(0),
1,
Duration::from_secs(30),
));
- let mut manager = Manager::builder("submission-purge-race-test")
- .with_trap_signals(false)
- .build();
- let handle = manager.register("batcher", ComponentOptions::new());
- let _monitor = manager.monitor_background();
- let (batcher, mut outputs) = Batcher::new(
- Arc::clone(&dispatcher),
+ let (batcher, mut outputs) = key_table_batcher(
+ &dispatcher,
transport,
- handle,
Duration::from_secs(10),
Duration::from_millis(20),
);
@@ -504,10 +497,9 @@ async fn purging_a_just_submitted_key_table_batch_is_not_fatal() {
let mut accumulator = Accumulator::default();
accumulator.push(Partition(0), make_msg("a").into());
batcher.submit(accumulator);
- // No await between submit and purge: run_scatter is queued but cannot run
- // until this current-thread task yields. The submission was accepted and
- // retained synchronously, then intentionally discarded by revocation.
- dispatcher.purge_revoked(&[("test".to_string(), 0)]);
+ // No await between submit and purge: the batcher task receives both
+ // before it runs, and discards the submission when it applies the purge.
+ batcher.revoker().purge_revoked(&[("test".to_string(), 0)]);
match tokio::time::timeout(Duration::from_millis(100), outputs.errors.recv()).await {
Err(_) => {}
@@ -519,25 +511,18 @@ async fn purging_a_just_submitted_key_table_batch_is_not_fatal() {
#[tokio::test]
async fn dropping_an_idle_key_table_batcher_closes_its_outputs() {
let registry = Arc::new(WorkerRegistry::new(&[], fast_config()));
- let dispatcher = Arc::new(Dispatcher::with_scheduler(
+ let dispatcher = Arc::new(Dispatcher::with_strategy(
registry,
RoutingStrategy::BinPack,
- SchedulerKind::KeyTable,
));
let transport = Arc::new(GrpcTransport::new(
GrpcPort::OffsetFromHttp(0),
1,
Duration::from_secs(30),
));
- let mut manager = Manager::builder("batcher-drop-test")
- .with_trap_signals(false)
- .build();
- let handle = manager.register("batcher", ComponentOptions::new());
- let _monitor = manager.monitor_background();
- let (batcher, mut outputs) = Batcher::new(
- dispatcher,
+ let (batcher, mut outputs) = key_table_batcher(
+ &dispatcher,
transport,
- handle,
Duration::from_secs(10),
Duration::from_millis(20),
);
diff --git a/rust/ingestion-consumer/tests/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rs
index 6c0f8bbf3300..0e0345d8f33c 100644
--- a/rust/ingestion-consumer/tests/e2e_integration_test.rs
+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs
@@ -3,6 +3,8 @@
//! Requires Kafka on localhost:9092 (available via docker-compose).
//! Each test creates a uniquely-named topic to avoid cross-test interference.
+mod common;
+
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
@@ -26,6 +28,7 @@ use tokio_util::sync::CancellationToken;
use uuid::Uuid;
use common_kafka_consumer::{TopicOffsetLedger, TopicPartition};
+use ingestion_consumer::batcher::BatcherObserver;
use ingestion_consumer::consumer::{IngestionConsumer, IngestionConsumerOptions};
use ingestion_consumer::discovery::reconcile_membership;
use ingestion_consumer::dispatcher::Dispatcher;
@@ -487,7 +490,7 @@ struct Harness {
scheduler: SchedulerKind,
pub workers: Vec<FakeWorker>,
pub registry: Arc<WorkerRegistry>,
- pub dispatcher: Arc<Dispatcher>,
+ pub observer: BatcherObserver,
/// Cross-worker, receipt-ordered log of every accepted message.
pub delivery_log: DeliveryLog,
pub shutdown: CancellationToken,
@@ -556,7 +559,7 @@ fn test_transport() -> GrpcTransport {
fn spawn_reaper(
registry: Arc<WorkerRegistry>,
transport: Arc<GrpcTransport>,
- dispatcher: Arc<Dispatcher>,
+ observer: BatcherObserver,
token: CancellationToken,
) {
tokio::spawn(async move {
@@ -566,7 +569,7 @@ fn spawn_reaper(
_ = tokio::time::sleep(Duration::from_millis(100)) => {}
}
for worker in registry.draining_workers() {
- if !dispatcher.has_in_flight(&worker) {
+ if !observer.has_in_flight(&worker) {
registry.complete_drain(&worker);
}
}
@@ -669,20 +672,12 @@ impl Harness {
let probe_token = CancellationToken::new();
Arc::clone(&registry).start_probing(probe_token.clone());
- let dispatcher = Arc::new(Dispatcher::with_scheduler(
+ let dispatcher = Arc::new(Dispatcher::with_strategy(
Arc::clone(&registry),
RoutingStrategy::default(),
- kind,
));
let registry_for_test = Arc::clone(&registry);
- let dispatcher_for_test = Arc::clone(&dispatcher);
let transport = Arc::new(test_transport());
- spawn_reaper(
- Arc::clone(&registry),
- Arc::clone(&transport),
- Arc::clone(&dispatcher),
- probe_token.clone(),
- );
let mut manager = Manager::builder("e2e-test")
.with_trap_signals(false)
@@ -697,10 +692,19 @@ impl Harness {
let ledger = context.topic_offset_ledger();
let kafka_consumer = make_kafka_consumer_with_context(topic, &group_id, None, context);
+ let (batcher, outputs) = common::batcher(
+ kind,
+ &dispatcher,
+ Arc::clone(&transport),
+ handle.clone(),
+ deferred_flush_timeout,
+ Duration::from_millis(200),
+ );
let consumer = IngestionConsumer::from_parts(
kafka_consumer,
- dispatcher,
- transport,
+ batcher,
+ outputs,
+ Arc::clone(&transport),
worker_urls,
IngestionConsumerOptions {
batch_size: 50,
@@ -708,12 +712,17 @@ impl Harness {
batch_timeout: Duration::from_millis(100),
max_in_flight_batches: max_in_flight,
group_id: "e2e-test".to_string(),
- deferred_flush_timeout,
- parked_retry_interval: Duration::from_millis(200),
debug_recorder: None,
},
handle,
);
+ let observer = consumer.batcher_observer();
+ spawn_reaper(
+ Arc::clone(&registry),
+ transport,
+ observer.clone(),
+ probe_token.clone(),
+ );
let task = tokio::spawn(async move { consumer.process().await });
@@ -724,7 +733,7 @@ impl Harness {
scheduler: kind,
workers,
registry: registry_for_test,
- dispatcher: dispatcher_for_test,
+ observer,
delivery_log,
shutdown,
task: Some(task),
@@ -754,18 +763,11 @@ impl Harness {
let registry = Arc::new(WorkerRegistry::new(&worker_urls, registry_config));
Arc::clone(&registry).start_probing(self._probe_token.clone());
- let dispatcher = Arc::new(Dispatcher::with_scheduler(
+ let dispatcher = Arc::new(Dispatcher::with_strategy(
Arc::clone(&registry),
RoutingStrategy::default(),
- self.scheduler,
));
let transport = Arc::new(test_transport());
- spawn_reaper(
- Arc::clone(&registry),
- Arc::clone(&transport),
- Arc::clone(&dispatcher),
- self._probe_token.clone(),
- );
let mut manager = Manager::builder("e2e-test-restarted")
.with_trap_signals(false)
@@ -777,10 +779,19 @@ impl Harness {
self.ledger = context.topic_offset_ledger();
let kafka_consumer =
make_kafka_consumer_with_context(&self.topic, &self.group_id, None, context);
+ let (batcher, outputs) = common::batcher(
+ self.scheduler,
+ &dispatcher,
+ Arc::clone(&transport),
+ handle.clone(),
+ self.deferred_flush_timeout,
+ Duration::from_millis(200),
+ );
let consumer = IngestionConsumer::from_parts(
kafka_consumer,
- Arc::clone(&dispatcher),
- transport,
+ batcher,
+ outputs,
+ Arc::clone(&transport),
worker_urls,
IngestionConsumerOptions {
batch_size: 50,
@@ -788,15 +799,19 @@ impl Harness {
batch_timeout: Duration::from_millis(100),
max_in_flight_batches: self.max_in_flight,
group_id: "e2e-test".to_string(),
- deferred_flush_timeout: self.deferred_flush_timeout,
- parked_retry_interval: Duration::from_millis(200),
debug_recorder: None,
},
handle,
);
+ self.observer = consumer.batcher_observer();
+ spawn_reaper(
+ Arc::clone(&registry),
+ transport,
+ self.observer.clone(),
+ self._probe_token.clone(),
+ );
self.registry = registry;
- self.dispatcher = dispatcher;
self.task = Some(tokio::spawn(async move { consumer.process().await }));
// Give the restarted consumer time to rejoin the group and start polling.
@@ -1460,16 +1475,16 @@ async fn deferred_flush_retries_until_a_worker_recovers(#[case] kind: SchedulerK
wait_until(
Duration::from_secs(10),
"the failed send to be deferred",
- || harness.dispatcher.held_messages() > 0,
+ || harness.observer.held_messages() > 0,
)
.await;
// The deferred work is held steady — the flush loop is backing off, not
// dropping anything — for as long as no worker is available.
- let held = harness.dispatcher.held_messages();
+ let held = harness.observer.held_messages();
tokio::time::sleep(liveness_deadline * 4).await;
assert_eq!(
- harness.dispatcher.held_messages(),
+ harness.observer.held_messages(),
held,
"deferred work must be held steady while no worker is available"
);
@@ -1550,7 +1565,7 @@ async fn no_worker_exit_comes_from_the_flush_timeout_not_a_liveness_stall(
wait_until(
Duration::from_secs(10),
"the failed send to be deferred",
- || harness.dispatcher.held_messages() > 0,
+ || harness.observer.held_messages() > 0,
)
.await;
let deferred_at = tokio::time::Instant::now();
@@ -1640,7 +1655,7 @@ async fn slow_deferred_drain_with_progress_outlasts_the_flush_timeout(#[case] ki
harness.workers[2].ingest_ok.store(false, Ordering::SeqCst);
drop(guard2);
wait_until(Duration::from_secs(10), "worker 2 to answer", || {
- harness.workers[2].arrived_count() == 1 && harness.dispatcher.held_messages() > 0
+ harness.workers[2].arrived_count() == 1 && harness.observer.held_messages() > 0
})
.await;
let guard2 = harness.workers[2].block().await;
@@ -1836,7 +1851,7 @@ async fn flush_target_failure_re_defers_then_replays_in_order(#[case] kind: Sche
wait_until(
Duration::from_secs(10),
"re-deferred work to be held after the replay target also fails",
- || harness.dispatcher.held_messages() > 0,
+ || harness.observer.held_messages() > 0,
)
.await;
@@ -2046,7 +2061,7 @@ async fn forced_reap_at_drain_timeout_reroutes_deferred_work(#[case] kind: Sched
produce(&producer, &topic, 0, "tok", "user-1", seq).await;
}
wait_until(Duration::from_secs(10), "batch 2 to defer", || {
- harness.dispatcher.held_messages() > 0
+ harness.observer.held_messages() > 0
})
.await;
@@ -2394,7 +2409,7 @@ async fn drainer_crash_mid_drain_replays_to_survivor_in_order(#[case] kind: Sche
produce(&producer, &topic, 0, "tok", "user-1", seq).await;
}
wait_until(Duration::from_secs(10), "batch 2 to defer", || {
- harness.dispatcher.held_messages() > 0
+ harness.observer.held_messages() > 0
})
.await;
@@ -2466,7 +2481,7 @@ async fn full_pool_send_failure_with_multiple_keys_recovers_in_order(#[case] kin
wait_until(
Duration::from_secs(10),
"all failed work to be stashed",
- || harness.dispatcher.held_messages() == 8,
+ || harness.observer.held_messages() == 8,
)
.await;
@@ -2740,18 +2755,26 @@ async fn second_consumer_joining_the_group_preserves_all_messages(#[case] kind:
let registry2 = Arc::new(WorkerRegistry::new(&worker_urls, fast_registry_config()));
let probe2 = CancellationToken::new();
Arc::clone(&registry2).start_probing(probe2.clone());
- let dispatcher2 = Arc::new(Dispatcher::with_scheduler(
+ let dispatcher2 = Arc::new(Dispatcher::with_strategy(
Arc::clone(&registry2),
RoutingStrategy::default(),
- kind,
));
let transport2 = Arc::new(test_transport());
let mut manager2 = Manager::builder("e2e-c2").with_trap_signals(false).build();
let handle2 = manager2.register("consumer", ComponentOptions::new());
let shutdown2 = handle2.shutdown_token();
+ let (batcher, outputs) = common::batcher(
+ kind,
+ &dispatcher2,
+ Arc::clone(&transport2),
+ handle2.clone(),
+ Duration::from_secs(60),
+ Duration::from_millis(200),
+ );
let consumer2 = IngestionConsumer::from_parts(
make_kafka_consumer(&topic, &harness.group_id, None),
- dispatcher2,
+ batcher,
+ outputs,
transport2,
worker_urls,
IngestionConsumerOptions {
@@ -2760,8 +2783,6 @@ async fn second_consumer_joining_the_group_preserves_all_messages(#[case] kind:
batch_timeout: Duration::from_millis(100),
max_in_flight_batches: 1,
group_id: "e2e-test".to_string(),
- deferred_flush_timeout: Duration::from_secs(60),
- parked_retry_interval: Duration::from_millis(200),
debug_recorder: None,
},
handle2,
@@ -2854,10 +2875,9 @@ async fn partition_lost_and_regained_keeps_the_consumer_alive(#[case] kind: Sche
let registry2 = Arc::new(WorkerRegistry::new(&worker_urls, fast_registry_config()));
let probe2 = CancellationToken::new();
Arc::clone(&registry2).start_probing(probe2.clone());
- let dispatcher2 = Arc::new(Dispatcher::with_scheduler(
+ let dispatcher2 = Arc::new(Dispatcher::with_strategy(
Arc::clone(&registry2),
RoutingStrategy::default(),
- kind,
));
let transport2 = Arc::new(test_transport());
let mut manager2 = Manager::builder("e2e-regain-c2")
@@ -2865,9 +2885,18 @@ async fn partition_lost_and_regained_keeps_the_consumer_alive(#[case] kind: Sche
.build();
let handle2 = manager2.register("consumer", ComponentOptions::new());
let shutdown2 = handle2.shutdown_token();
+ let (batcher, outputs) = common::batcher(
+ kind,
+ &dispatcher2,
+ Arc::clone(&transport2),
+ handle2.clone(),
+ Duration::from_secs(60),
+ Duration::from_millis(200),
+ );
let consumer2 = IngestionConsumer::from_parts(
make_kafka_consumer(&topic, &harness.group_id, None),
- dispatcher2,
+ batcher,
+ outputs,
transport2,
worker_urls,
IngestionConsumerOptions {
@@ -2876,8 +2905,6 @@ async fn partition_lost_and_regained_keeps_the_consumer_alive(#[case] kind: Sche
batch_timeout: Duration::from_millis(100),
max_in_flight_batches: 1,
group_id: "e2e-test".to_string(),
- deferred_flush_timeout: Duration::from_secs(60),
- parked_retry_interval: Duration::from_millis(200),
debug_recorder: None,
},
handle2,
@@ -2975,10 +3002,9 @@ async fn fenced_static_member_exits_on_fatal_error(#[case] kind: SchedulerKind)
let registry = Arc::new(WorkerRegistry::new(&urls, fast_registry_config()));
let probe = CancellationToken::new();
Arc::clone(&registry).start_probing(probe.clone());
- let dispatcher = Arc::new(Dispatcher::with_scheduler(
+ let dispatcher = Arc::new(Dispatcher::with_strategy(
Arc::clone(&registry),
RoutingStrategy::default(),
- kind,
));
let transport = Arc::new(test_transport());
let mut manager = Manager::builder("e2e-fenced")
@@ -2986,9 +3012,18 @@ async fn fenced_static_member_exits_on_fatal_error(#[case] kind: SchedulerKind)
.build();
let handle = manager.register("consumer", ComponentOptions::new());
let group = format!("e2e-{}", Uuid::new_v4());
+ let (batcher, outputs) = common::batcher(
+ kind,
+ &dispatcher,
+ Arc::clone(&transport),
+ handle.clone(),
+ Duration::from_secs(60),
+ Duration::from_millis(200),
+ );
let consumer = IngestionConsumer::from_parts(
make_kafka_consumer(&topic, &group, Some("pod-1")),
- dispatcher,
+ batcher,
+ outputs,
transport,
urls,
IngestionConsumerOptions {
@@ -2997,8 +3032,6 @@ async fn fenced_static_member_exits_on_fatal_error(#[case] kind: SchedulerKind)
batch_timeout: Duration::from_millis(100),
max_in_flight_batches: 1,
group_id: "e2e-test".to_string(),
- deferred_flush_timeout: Duration::from_secs(60),
- parked_retry_interval: Duration::from_millis(200),
debug_recorder: None,
},
handle,
@@ -3198,9 +3231,9 @@ async fn run_churn_suite(
Duration::from_secs(10),
"dispatcher pins/in-flight/stash to drain to zero after churn",
|| {
- harness.dispatcher.held_messages() == 0
- && harness.dispatcher.pin_count() == 0
- && harness.dispatcher.total_in_flight() == 0
+ harness.observer.held_messages() == 0
+ && harness.observer.pin_count() == 0
+ && harness.observer.total_in_flight() == 0
},
)
.await;
diff --git a/rust/ingestion-consumer/tests/grpc_transport_test.rs b/rust/ingestion-consumer/tests/grpc_transport_test.rs
index 4e1ec5855917..2cb72f8c06b3 100644
--- a/rust/ingestion-consumer/tests/grpc_transport_test.rs
+++ b/rust/ingestion-consumer/tests/grpc_transport_test.rs
@@ -5,18 +5,19 @@
//! failure fences everything outstanding (in order, with the messages handed
//! back) so the dispatcher's deferral path can replay it.
+mod common;
+
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;
+use common::key_table_batcher;
use common_kafka_consumer::Partition;
-use ingestion_consumer::batcher::Batcher;
use ingestion_consumer::dispatcher::Dispatcher;
use ingestion_consumer::grpc_transport::{GrpcPort, GrpcTransport};
use ingestion_consumer::routing::RoutingStrategy;
-use ingestion_consumer::scheduler::SchedulerKind;
use ingestion_consumer::transport::TransportError;
use ingestion_consumer::types::{Accumulator, SerializedKafkaMessage};
use ingestion_consumer::worker_registry::{WorkerRegistry, WorkerRegistryConfig};
@@ -27,7 +28,6 @@ use ingestion_worker_proto::ingestion::worker::v1::{
ingest_stream_request, ingest_stream_response, IngestStreamRequest, IngestStreamResponse,
StreamReady, SubBatch, SubBatchAck, SubBatchStatus,
};
-use lifecycle::{ComponentOptions, Manager};
use tokio::sync::{mpsc, oneshot, Mutex};
use tokio_stream::wrappers::UnboundedReceiverStream;
use tokio_stream::StreamExt;
@@ -514,6 +514,38 @@ async fn a_failed_chunk_hands_back_the_whole_sub_batch() {
assert!(err.fence_guard.is_some(), "a fenced send carries a guard");
}
+#[tokio::test]
+async fn chunks_acked_out_of_order_then_fenced_hand_back_messages_in_send_order() {
+ let (ack_tx, ack_rx) = mpsc::unbounded_channel();
+ let mock = start_mock(AckMode::Manual, Some(ack_rx)).await;
+ let mut transport = GrpcTransport::new(
+ GrpcPort::Fixed(mock.addr.port()),
+ 3,
+ Duration::from_secs(30),
+ );
+ transport.set_max_body_bytes(200);
+ let url = worker_url(mock.addr);
+
+ let pending = transport.begin_send(
+ &url,
+ "batch-1",
+ vec![msg("d1", 1), msg("d2", 2), msg("d3", 3)],
+ false,
+ );
+ wait_for_received(&mock, 3).await;
+ for seq in [3, 2] {
+ ack_tx.send(ManualAck::Ok { seq, accepted: 1 }).unwrap();
+ }
+ ack_tx.send(ManualAck::Nack(1)).unwrap();
+
+ let err = pending
+ .wait()
+ .await
+ .expect_err("a nacked chunk fails the send");
+ let offsets: Vec<i64> = err.messages.iter().map(|m| m.offset).collect();
+ assert_eq!(offsets, vec![1, 2, 3]);
+}
+
#[tokio::test]
async fn a_nack_fences_everything_outstanding_in_order() {
// Regression: on a failure, every un-acked and queued sub-batch must fail
@@ -861,25 +893,18 @@ async fn key_table_watchdog_bounds_overlapping_busy_retries() {
format!("http://{second_addr}"),
];
let registry = Arc::new(WorkerRegistry::new(&worker_urls, registry_config()));
- let dispatcher = Arc::new(Dispatcher::with_scheduler(
+ let dispatcher = Arc::new(Dispatcher::with_strategy(
registry,
RoutingStrategy::BinPack,
- SchedulerKind::KeyTable,
));
let transport = Arc::new(GrpcTransport::new(
GrpcPort::OffsetFromHttp(0),
1,
Duration::from_secs(30),
));
- let mut manager = Manager::builder("key-table-watchdog-test")
- .with_trap_signals(false)
- .build();
- let handle = manager.register("batcher", ComponentOptions::new());
- let _monitor = manager.monitor_background();
- let (batcher, mut outputs) = Batcher::new(
- dispatcher,
+ let (batcher, mut outputs) = key_table_batcher(
+ &dispatcher,
transport,
- handle,
Duration::from_millis(100),
Duration::from_millis(20),
);
@@ -936,7 +961,7 @@ async fn key_table_watchdog_bounds_overlapping_busy_retries() {
.expect("batcher error channel stays open");
assert_eq!(
error,
- "key-table work made no progress within the stall timeout"
+ "pending work made no progress within the stall timeout"
);
assert!(
final_attempt_released.load(Ordering::Relaxed),
@@ -950,31 +975,23 @@ async fn key_table_watchdog_bounds_overlapping_busy_retries() {
}
#[tokio::test]
-async fn key_table_parked_retry_drains_after_shutdown_signal() {
+async fn key_table_retries_a_busy_send_until_it_completes() {
let (attempts_tx, mut attempts_rx) = mpsc::unbounded_channel();
let addr = start_controlled_busy_worker(0, attempts_tx).await;
let worker_urls = vec![format!("http://{addr}")];
let registry = Arc::new(WorkerRegistry::new(&worker_urls, registry_config()));
- let dispatcher = Arc::new(Dispatcher::with_scheduler(
+ let dispatcher = Arc::new(Dispatcher::with_strategy(
registry,
RoutingStrategy::BinPack,
- SchedulerKind::KeyTable,
));
let transport = Arc::new(GrpcTransport::new(
GrpcPort::OffsetFromHttp(0),
1,
Duration::from_secs(30),
));
- let mut manager = Manager::builder("key-table-retry-recovery-test")
- .with_trap_signals(false)
- .build();
- let handle = manager.register("batcher", ComponentOptions::new());
- let shutdown = handle.shutdown_token();
- let _monitor = manager.monitor_background();
- let (batcher, mut outputs) = Batcher::new(
- dispatcher,
+ let (batcher, mut outputs) = key_table_batcher(
+ &dispatcher,
transport,
- handle,
Duration::from_millis(500),
Duration::from_millis(20),
);
@@ -988,10 +1005,9 @@ async fn key_table_parked_retry_drains_after_shutdown_signal() {
.expect("initial send reaches the worker")
.expect("attempt channel stays open");
assert!(first.reply.send(ControlledReply::Busy).is_ok());
- shutdown.cancel();
let retry = tokio::time::timeout(Duration::from_secs(1), attempts_rx.recv())
.await
- .expect("parked retry reaches the worker")
+ .expect("the retry reaches the worker")
.expect("attempt channel stays open");
assert!(retry.reply.send(ControlledReply::Ok).is_ok());
@@ -1013,25 +1029,18 @@ async fn key_table_watchdog_allows_in_flight_success_after_the_deadline() {
let addr = start_controlled_busy_worker(0, attempts_tx).await;
let worker_urls = vec![format!("http://{addr}")];
let registry = Arc::new(WorkerRegistry::new(&worker_urls, registry_config()));
- let dispatcher = Arc::new(Dispatcher::with_scheduler(
+ let dispatcher = Arc::new(Dispatcher::with_strategy(
registry,
RoutingStrategy::BinPack,
- SchedulerKind::KeyTable,
));
let transport = Arc::new(GrpcTransport::new(
GrpcPort::OffsetFromHttp(0),
1,
Duration::from_secs(30),
));
- let mut manager = Manager::builder("key-table-late-success-test")
- .with_trap_signals(false)
- .build();
- let handle = manager.register("batcher", ComponentOptions::new());
- let _monitor = manager.monitor_background();
- let (batcher, mut outputs) = Batcher::new(
- dispatcher,
+ let (batcher, mut outputs) = key_table_batcher(
+ &dispatcher,
transport,
- handle,
Duration::from_millis(100),
Duration::from_millis(20),
);