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): select the key-table scheduler with config (#96169)

José Sequeira2d42aa09cc98
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 1fbec690b9e3..60155d6801ef 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -6240,6 +6240,7 @@ dependencies = [
"rand 0.8.5",
"rdkafka",
"reqwest 0.12.28",
+ "rstest",
"rustls 0.23.37",
"serde",
"serde_json",
diff --git a/rust/ingestion-consumer/Cargo.toml b/rust/ingestion-consumer/Cargo.toml
index 4c6895c1f109..5364e6633e4d 100644
--- a/rust/ingestion-consumer/Cargo.toml
+++ b/rust/ingestion-consumer/Cargo.toml
@@ -38,4 +38,5 @@ tracing = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter", "json"] }
[dev-dependencies]
+rstest = "0.26"
uuid = { workspace = true }
diff --git a/rust/ingestion-consumer/docs/driver-model-plan.md b/rust/ingestion-consumer/docs/driver-model-plan.md
index 4fb80fc5f140..7b714a864bcf 100644
--- a/rust/ingestion-consumer/docs/driver-model-plan.md
+++ b/rust/ingestion-consumer/docs/driver-model-plan.md
@@ -326,7 +326,7 @@ Exit criterion: zero key-order sentinel violations, `ingestion_consumer_transpor
**Metrics:**
-- Add, emitted when selected: `ingestion_consumer_key_table_keys`, `ingestion_consumer_key_table_queued_messages`, `ingestion_consumer_key_table_queued_bytes`, `ingestion_consumer_key_table_outstanding_keys`, `ingestion_consumer_key_table_parked_keys` (gauges), and `ingestion_consumer_parked_retries_total` (counter). Queued bytes needs an alert before the switch: every key with an outstanding request buffers all later arrivals in full, and key cardinality is customer-controlled.
+- Add, emitted when selected: `ingestion_consumer_key_table_keys`, `ingestion_consumer_key_table_queued_messages`, `ingestion_consumer_key_table_queued_bytes`, `ingestion_consumer_key_table_outstanding_keys`, `ingestion_consumer_key_table_parked_keys` (gauges), `ingestion_consumer_parked_retries_total` (counter), and `ingestion_consumer_key_table_queue_wait_seconds` (histogram, by send kind): the head-of-line wait, the latency cost the one-request-per-key rule accepts. Queued bytes needs an alert before the switch: every key with an outstanding request buffers all later arrivals in full, and key cardinality is customer-controlled.
### 10. Switch to the key-table scheduler (switchover)
@@ -350,7 +350,7 @@ Exit criterion: zero key-order sentinel violations, `ingestion_consumer_transpor
- Replace the flush driver rather than retarget it: `run_flush_driver` is per-batch (ticket loop, `has_unfinished_flush`, per-batch stall deadline), and parked keys have no batch identity. The key table needs a global periodic `Deadline::ParkedRetry` pump plus a global stall watchdog, so a wedged key table restarts loudly instead of growing lag silently.
- Modify `apply_completion` in the consumer: credit each offset to the in-flight poll that contains it, instead of crediting the whole completion to the poll that contains its first offset. A merged run's completion spans polls in steady state; under first-offset crediting the first poll over-counts and the later poll never completes, and its wait loop reports healthy every second while stuck.
- Bound runs by epoch in the key table: stamp the assignment epoch on messages at enqueue, and stop `take_run` at an epoch boundary, so a run never mixes epochs and its completion carries one valid stamp. A cross-epoch completion has no correct stamp and one side is discarded as stale.
-- Purge on rebalance: drop the key table's queued messages for revoked partitions (a routing key maps to one partition). The new partition owner replays them; sending the stale queue too duplicates delivery.
+- Purge on rebalance: drop the key table's queued messages for revoked topic-partitions, and remember revocations for outstanding sends so a later failure cannot requeue their revoked messages. Clear that revocation state at settlement; kept partitions and newly reassigned work remain retryable. The new partition owner replays revoked work; sending it from the old owner too duplicates delivery.
### 11. Delete the old scheduler (cleanup)
diff --git a/rust/ingestion-consumer/src/batcher.rs b/rust/ingestion-consumer/src/batcher.rs
index 6d1a53714601..47b35cea6b94 100644
--- a/rust/ingestion-consumer/src/batcher.rs
+++ b/rust/ingestion-consumer/src/batcher.rs
@@ -15,6 +15,7 @@
//! the failure decision stays in the consumer loop.
use std::collections::HashMap;
+use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -25,9 +26,10 @@ use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tracing::{error, info};
-use crate::dispatcher::{Dispatcher, KeyOffset, SubBatch};
+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;
@@ -54,6 +56,9 @@ struct PendingSubBatch {
/// The accumulator groups this sub-batch carries, kept aside so the
/// resolved send can be broken back into per-group completions.
groups: Vec<CompletionGroup>,
+ /// The runs' epoch when the scheduler stamped one; completions then use
+ /// it instead of the awaiting batch's epoch.
+ assignment_epoch: Option<u64>,
pending: PendingWorkerStreamSend,
}
@@ -77,6 +82,7 @@ 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>,
}
@@ -124,6 +130,7 @@ fn send_group_completions(
pub struct Batcher {
inner: Arc<BatcherInner>,
flush_queue: mpsc::UnboundedSender<FlushTicket>,
+ parked_retry_pump: Option<JoinHandle<()>>,
}
impl Batcher {
@@ -132,6 +139,7 @@ impl Batcher {
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();
@@ -140,10 +148,19 @@ 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,
@@ -151,7 +168,11 @@ impl Batcher {
deferred_flush_timeout,
));
(
- Self { inner, flush_queue },
+ Self {
+ inner,
+ flush_queue,
+ parked_retry_pump,
+ },
BatcherOutputs {
completions: completions_rx,
errors: errors_rx,
@@ -165,6 +186,11 @@ impl Batcher {
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.
@@ -184,12 +210,12 @@ impl Batcher {
self.inner.dispatcher.register_batch(&batch_id);
let assign_start = Instant::now();
let groups = accumulator.into_groups();
- let pending = self
- .inner
- .dispatcher
- .assign_and_send(&batch_id, groups, |sub_batch| {
- begin_send(&self.inner.transport, &batch_id, sub_batch, false)
- });
+ let Submission { pending, retained } = self.inner.dispatcher.assign_and_send(
+ &batch_id,
+ assignment_epoch,
+ groups,
+ |sub_batch| begin_send(&self.inner.transport, &batch_id, sub_batch, false),
+ );
// Assignment serializes on the consumer loop (it does not overlap
// batch collection) — watch this stays a small fraction of the batch
// collection interval.
@@ -200,6 +226,7 @@ impl Batcher {
Arc::clone(&self.inner),
batch_id.clone(),
pending,
+ retained,
assignment_epoch,
));
let _ = self.flush_queue.send(FlushTicket {
@@ -211,6 +238,14 @@ 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.
@@ -218,10 +253,12 @@ async fn run_scatter(
inner: Arc<BatcherInner>,
batch_id: String,
pending: Vec<PendingSubBatch>,
+ retained: bool,
assignment_epoch: u64,
) {
- // Nothing to send and no deferred groups means no usable workers.
- if pending.is_empty() && !inner.dispatcher.batch_has_flush_activity(&batch_id) {
+ // Use the submission's synchronous assignment outcome. Mutable scheduler
+ // state may have changed by the time this spawned task runs.
+ if pending.is_empty() && !retained {
counter!("ingestion_consumer_no_healthy_workers_total").increment(1);
inner.report_error("No healthy workers available to route batch".to_string());
return;
@@ -256,61 +293,13 @@ async fn scatter(
) -> anyhow::Result<u32> {
let mut handles = Vec::with_capacity(pending.len());
for sub_batch in pending {
- let inner = Arc::clone(inner);
- let PendingSubBatch {
- worker,
- routing_keys,
- key_offsets,
- message_count,
- groups,
- pending,
- } = sub_batch;
- let bid = batch_id.to_string();
-
- handles.push(tokio::spawn(async move {
- match pending.wait().await {
- Ok(accepted) => {
- // Advance ACK high-water marks before the settle, which
- // may evict the keys' sentinel state.
- inner.dispatcher.on_sub_batch_acked(&key_offsets);
- inner.dispatcher.settle(
- &worker,
- message_count,
- &routing_keys,
- from_flush,
- None,
- );
- inner.dispatcher.record_send_outcome(&worker, false);
- send_group_completions(&inner.completions, groups, assignment_epoch, accepted);
- accepted
- }
- Err(send_err) => {
- // One settlement call requeues the failed messages and
- // releases the keys together, so a newer send cannot
- // overtake them.
- // Backpressure (a busy worker) is transient, not a fault:
- // re-route the work but do not count it against the
- // worker's health, so passive health tracks real faults.
- let SendError {
- error,
- messages,
- fence_guard,
- } = send_err;
- let is_fault = !error.is_backpressure();
- inner.dispatcher.settle(
- &worker,
- message_count,
- &routing_keys,
- from_flush,
- Some((bid, messages)),
- );
- // Stashed: let the worker stream stop fencing new arrivals.
- drop(fence_guard);
- inner.dispatcher.record_send_outcome(&worker, is_fault);
- 0
- }
- }
- }));
+ handles.push(tokio::spawn(await_settled(
+ Arc::clone(inner),
+ batch_id.to_string(),
+ sub_batch,
+ from_flush,
+ assignment_epoch,
+ )));
}
let mut accepted = 0u32;
@@ -320,6 +309,186 @@ async fn scatter(
Ok(accepted)
}
+/// Await one in-flight send, settle it in one seam call, and spawn an
+/// awaiter for every follow-up send the settlement dispatched (the key
+/// table releases a key's next run at settlement). Every begin_send gets
+/// exactly one awaiter, so every dispatch settles exactly once.
+async fn await_settled(
+ inner: Arc<BatcherInner>,
+ batch_id: String,
+ sub_batch: PendingSubBatch,
+ from_flush: bool,
+ batch_epoch: u64,
+) -> u32 {
+ let PendingSubBatch {
+ worker,
+ routing_keys,
+ key_offsets,
+ message_count,
+ groups,
+ assignment_epoch: run_epoch,
+ pending,
+ } = sub_batch;
+
+ 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);
+ let followups = settle_and_send(
+ &inner,
+ &worker,
+ message_count,
+ &routing_keys,
+ from_flush,
+ None,
+ );
+ inner.dispatcher.record_send_outcome(&worker, false);
+ send_group_completions(
+ &inner.completions,
+ groups,
+ run_epoch.unwrap_or(batch_epoch),
+ accepted,
+ );
+ spawn_followups(&inner, followups, batch_epoch);
+ accepted
+ }
+ Err(send_err) => {
+ // One settlement call requeues the failed messages and
+ // releases the keys together, so a newer send cannot
+ // overtake them.
+ // Backpressure (a busy worker) is transient, not a fault:
+ // re-route the work but do not count it against the
+ // worker's health, so passive health tracks real faults.
+ let SendError {
+ error,
+ messages,
+ fence_guard,
+ } = send_err;
+ let is_fault = !error.is_backpressure();
+ let followups = settle_and_send(
+ &inner,
+ &worker,
+ message_count,
+ &routing_keys,
+ from_flush,
+ Some((batch_id, messages)),
+ );
+ // Stashed: let the worker stream stop fencing new arrivals.
+ drop(fence_guard);
+ inner.dispatcher.record_send_outcome(&worker, is_fault);
+ spawn_followups(&inner, followups, batch_epoch);
+ 0
+ }
+ }
+}
+
+/// Settle one send and begin the settlement's follow-up sends under the
+/// dispatcher lock. Follow-up sends belong to no poll, so they go on the
+/// wire under a fresh batch id, minted for correlation and logs.
+fn settle_and_send(
+ inner: &Arc<BatcherInner>,
+ worker: &WorkerId,
+ message_count: usize,
+ routing_keys: &[String],
+ from_flush: bool,
+ failed: Option<(String, Vec<SerializedKafkaMessage>)>,
+) -> (String, Vec<PendingSubBatch>) {
+ let settle_id = make_batch_id();
+ let followups = inner.dispatcher.settle_and_send(
+ worker,
+ message_count,
+ routing_keys,
+ from_flush,
+ failed,
+ |sub_batch| begin_send(&inner.transport, &settle_id, sub_batch, false),
+ );
+ (settle_id, followups)
+}
+
+/// Spawn one detached awaiter per follow-up send. Follow-ups are never
+/// flush sends, and their completions are stamped from their run's epoch.
+fn spawn_followups(
+ inner: &Arc<BatcherInner>,
+ (settle_id, followups): (String, Vec<PendingSubBatch>),
+ batch_epoch: u64,
+) {
+ for sub_batch in followups {
+ drop(tokio::spawn(await_settled(
+ Arc::clone(inner),
+ settle_id.clone(),
+ sub_batch,
+ false,
+ batch_epoch,
+ )));
+ }
+}
+
+/// 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
@@ -416,6 +585,7 @@ fn begin_send(
messages,
routing_keys,
key_offsets,
+ assignment_epoch,
} = sub_batch;
let groups = completion_groups(&messages);
let message_count = messages.len();
@@ -426,6 +596,7 @@ fn begin_send(
key_offsets,
message_count,
groups,
+ assignment_epoch,
pending,
}
}
diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rs
index 9b125369722c..f9be686f71bf 100644
--- a/rust/ingestion-consumer/src/config.rs
+++ b/rust/ingestion-consumer/src/config.rs
@@ -5,6 +5,7 @@ use tracing::info;
use crate::discovery::DiscoveryMode;
use crate::routing::RoutingStrategy;
+use crate::scheduler::SchedulerKind;
use common_kafka_consumer::config::ConsumerConfigBuilder;
/// Configuration for the ingestion consumer.
@@ -163,6 +164,13 @@ pub struct Config {
#[envconfig(default = "60000")]
pub consumer_deferred_flush_timeout_ms: u64,
+ /// How often the key-table scheduler retries its parked keys
+ /// (milliseconds). Matches the flush driver's retry cadence, so the
+ /// scheduler switch does not regress recovery latency. Only read under
+ /// `INGESTION_SCHEDULER=key_table`.
+ #[envconfig(from = "INGESTION_PARKED_RETRY_INTERVAL_MS", default = "200")]
+ pub parked_retry_interval_ms: u64,
+
/// Maximum Kafka batches to process concurrently. Matches the Node.js
/// CONSUMER_MAX_BACKGROUND_TASKS setting used by the Kafka consumer wrapper.
#[envconfig(from = "CONSUMER_MAX_BACKGROUND_TASKS", default = "1")]
@@ -273,6 +281,12 @@ pub struct Config {
#[envconfig(from = "INGESTION_ROUTING_STRATEGY", default = "binpack")]
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.
+ #[envconfig(from = "INGESTION_SCHEDULER", default = "pin_stash")]
+ pub scheduler: SchedulerKind,
+
/// Minimum aperture width for `INGESTION_ROUTING_STRATEGY=aperture`: how
/// many workers this dispatcher's ring slice spans. The effective width
/// is floored at `ceil(pool / dispatchers)` so the fleet's slices always
diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rs
index cdfe4b7d463e..4b84d56e9506 100644
--- a/rust/ingestion-consumer/src/consumer.rs
+++ b/rust/ingestion-consumer/src/consumer.rs
@@ -1,5 +1,5 @@
use std::collections::{HashMap, VecDeque};
-use std::sync::Arc;
+use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use common_kafka_consumer::{
@@ -25,6 +25,7 @@ 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::types::{Accumulator, SerializedKafkaMessage};
/// Batch-wide statistics gathered while collecting, used to emit parity
@@ -72,6 +73,11 @@ struct PartitionDeliveries {
latest_kafka_ts: i64,
/// Max ingestion lag (ms) — for `ingestion_lag_ms`.
max_lag_ms: Option<i64>,
+ /// Messages the poll delivered, covered, and accepted from this
+ /// partition, so a revoked partition can leave the poll exactly.
+ delivered: u32,
+ covered: u32,
+ accepted: u32,
}
impl PartitionDeliveries {
@@ -83,6 +89,9 @@ impl PartitionDeliveries {
charges: vec![(Offset(delivery.offset), delivery.charge)],
latest_kafka_ts: delivery.kafka_ts,
max_lag_ms: delivery.lag_ms,
+ delivered: 1,
+ covered: 0,
+ accepted: 0,
}
}
@@ -99,6 +108,7 @@ impl PartitionDeliveries {
delivery: &Delivery,
) {
self.span.extend(delivery.offset);
+ self.delivered += 1;
self.latest_kafka_ts = self.latest_kafka_ts.max(delivery.kafka_ts);
if let Some(lag_ms) = delivery.lag_ms {
self.max_lag_ms = Some(self.max_lag_ms.map_or(lag_ms, |max| max.max(lag_ms)));
@@ -157,41 +167,101 @@ impl InFlightPoll {
fn is_complete(&self) -> bool {
self.covered >= self.message_count
}
+}
- fn contains(&self, partition: Partition, offset: i64) -> bool {
- self.partitions.iter().any(|(topic_partition, deliveries)| {
- topic_partition.partition == partition.0
- && deliveries.span.first <= offset
- && offset <= deliveries.span.last
- })
+/// A partition revocation stamped with the ledger generation started by the
+/// revoke. Poll slices from earlier generations are stale; slices collected
+/// after a later reassignment must survive a delayed notification.
+#[derive(Clone, Debug)]
+struct RevokedPartition {
+ topic_partition: TopicPartition,
+ generation: u64,
+}
+
+/// 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
+/// ledger charges at commit, so the frontier never crosses a hole.
+fn strip_revoked_partitions(
+ in_flight_polls: &mut VecDeque<InFlightPoll>,
+ revoked: &[RevokedPartition],
+) -> u64 {
+ let mut stripped: u64 = 0;
+ for poll in in_flight_polls.iter_mut() {
+ let mut removed_delivered = 0u32;
+ let mut removed_covered = 0u32;
+ let mut removed_accepted = 0u32;
+ poll.partitions.retain(|topic_partition, deliveries| {
+ if revoked.iter().any(|revoked| {
+ revoked.topic_partition == *topic_partition
+ && deliveries.generation < revoked.generation
+ }) {
+ removed_delivered += deliveries.delivered;
+ removed_covered += deliveries.covered;
+ removed_accepted += deliveries.accepted;
+ false
+ } else {
+ true
+ }
+ });
+ if removed_delivered > 0 {
+ stripped += u64::from(removed_delivered);
+ poll.message_count = poll.message_count.saturating_sub(removed_delivered);
+ poll.covered = poll.covered.saturating_sub(removed_covered);
+ poll.accepted = poll.accepted.saturating_sub(removed_accepted);
+ }
}
+ in_flight_polls.retain(|poll| poll.message_count > 0);
+ stripped
}
-/// Credit a completion to the poll it belongs to: the one collected under the
-/// same assignment epoch whose offset span holds the completion's offsets.
+/// Credit each of a completion's offsets to the poll that contains it: the
+/// one collected under the same assignment epoch whose span holds the offset.
/// Within one epoch, poll spans are disjoint per partition, so at most one
-/// poll matches. A completion that matches no in-flight poll (its partition
-/// was revoked and reassigned while the group was out, or its poll is gone)
-/// is discarded and counted.
+/// poll matches per offset. A key-table run merges messages from several
+/// polls into one send, so one completion can span polls; crediting per
+/// offset keeps every poll's count exact. Acceptance credits the leading
+/// offsets, so a worker that under-reports shorts the tail poll's accepted
+/// check, matching [`send_group_completions`]'s split across groups. An
+/// offset that matches no poll (its partition was revoked and reassigned
+/// while the group was out, or its poll is gone) is discarded; a completion
+/// with any discarded offset counts as stale once.
+///
+/// [`send_group_completions`]: crate::batcher
fn apply_completion(in_flight: &mut VecDeque<InFlightPoll>, completion: GroupCompletion) {
- let Some(first) = completion.offsets.first().map(|offset| offset.0) else {
- return;
- };
- let Some(poll) = in_flight.iter_mut().find(|poll| {
- poll.assignment_epoch == completion.assignment_epoch
- && poll.contains(completion.partition, first)
- }) else {
+ let mut accepted = completion.accepted;
+ let mut unmatched: u64 = 0;
+ 'offsets: for offset in &completion.offsets {
+ let is_accepted = accepted > 0;
+ accepted = accepted.saturating_sub(1);
+ for poll in in_flight
+ .iter_mut()
+ .filter(|poll| poll.assignment_epoch == completion.assignment_epoch)
+ {
+ for (topic_partition, deliveries) in poll.partitions.iter_mut() {
+ if topic_partition.partition == completion.partition.0
+ && deliveries.span.first <= offset.0
+ && offset.0 <= deliveries.span.last
+ {
+ poll.covered += 1;
+ poll.accepted += u32::from(is_accepted);
+ deliveries.covered += 1;
+ deliveries.accepted += u32::from(is_accepted);
+ continue 'offsets;
+ }
+ }
+ }
+ unmatched += 1;
+ }
+ if unmatched > 0 {
counter!("ingestion_consumer_stale_group_completions_total").increment(1);
warn!(
partition = %completion.partition,
- offset = first,
+ unmatched,
epoch = completion.assignment_epoch,
- "Discarding group completion that matches no in-flight poll"
+ "Discarding completion offsets that match no in-flight poll"
);
- return;
- };
- poll.covered += completion.offsets.len() as u32;
- poll.accepted += completion.accepted;
+ }
}
/// Options for constructing an [`IngestionConsumer`] from pre-built parts.
@@ -210,6 +280,9 @@ pub struct IngestionConsumerOptions {
/// 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>>,
}
@@ -241,6 +314,9 @@ pub struct IngestionConsumer {
/// from. Shared with the consumer's [`SentinelContext`], which forgets
/// partitions on rebalance.
topic_offset_ledger: Arc<TopicOffsetLedger>,
+ /// Partitions revoked since the loop last looked, fed by the rebalance
+ /// callback. Only populated under the key-table scheduler.
+ revoked_partitions: Arc<Mutex<Vec<RevokedPartition>>>,
}
impl IngestionConsumer {
@@ -260,17 +336,42 @@ 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,
+ }
+ }));
+ }
+ }));
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,
topic_offset_ledger,
+ revoked_partitions,
consumer,
batcher,
outputs: Some(outputs),
@@ -323,6 +424,27 @@ impl IngestionConsumer {
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,
+ }
+ }));
+ }
+ }));
let consumer: StreamConsumer<SentinelContext> =
client_config.create_with_context(context)?;
consumer.subscribe(&[&config.ingestion_consumer_consume_topic])?;
@@ -342,6 +464,7 @@ impl IngestionConsumer {
consumer,
debug_recorder,
topic_offset_ledger,
+ revoked_partitions,
batcher,
outputs: Some(outputs),
transport,
@@ -403,6 +526,7 @@ impl IngestionConsumer {
let mut accepting_new_batches = true;
while accepting_new_batches || !in_flight_polls.is_empty() {
+ self.drop_revoked_polls(&mut in_flight_polls);
// Consumer-level concurrency: how many Kafka batches are being
// processed in parallel, bounded by `max_in_flight_batches`.
gauge!("ingestion_consumer_in_flight_batches").set(in_flight_polls.len() as f64);
@@ -523,16 +647,18 @@ impl IngestionConsumer {
completions: &mut mpsc::UnboundedReceiver<GroupCompletion>,
errors: &mut mpsc::UnboundedReceiver<String>,
) -> Result<(), Failure> {
- if in_flight_polls.front().is_none() {
- return Ok(());
- }
-
let mut heartbeat = tokio::time::interval(Duration::from_secs(1));
- while !in_flight_polls
- .front()
- .expect("front is present")
- .is_complete()
- {
+ loop {
+ // A rebalance can drop the front poll (its partitions were
+ // revoked and its purged messages will never complete), so
+ // re-resolve it every pass instead of waiting on it forever.
+ self.drop_revoked_polls(in_flight_polls);
+ let Some(front) = in_flight_polls.front() else {
+ return Ok(());
+ };
+ if front.is_complete() {
+ break;
+ }
tokio::select! {
completion = completions.recv() => match completion {
Some(completion) => apply_completion(in_flight_polls, completion),
@@ -578,6 +704,26 @@ impl IngestionConsumer {
Ok(())
}
+ /// Drop in-flight polls holding a revoked partition. The key table
+ /// purges those partitions' queued messages, so such a poll can never be
+ /// covered; its offsets stay uncommitted and replay under the new
+ /// assignment, and its late completions are discarded as stale.
+ fn drop_revoked_polls(&self, in_flight_polls: &mut VecDeque<InFlightPoll>) {
+ let revoked: Vec<RevokedPartition> =
+ std::mem::take(&mut *self.revoked_partitions.lock().unwrap());
+ if revoked.is_empty() {
+ return;
+ }
+ let stripped = strip_revoked_partitions(in_flight_polls, &revoked);
+ if stripped > 0 {
+ counter!("ingestion_consumer_polls_dropped_on_revoke_total").increment(stripped);
+ info!(
+ stripped,
+ "Removed revoked partitions' messages from in-flight polls"
+ );
+ }
+ }
+
fn fail_batch_processing(&self, err: anyhow::Error) {
error!(error = %err, "Batch processing failed");
counter!("ingestion_consumer_batch_errors_total").increment(1);
@@ -1024,6 +1170,9 @@ mod tests {
charges: Vec::new(),
latest_kafka_ts: 0,
max_lag_ms: None,
+ delivered: count,
+ covered: 0,
+ accepted: 0,
},
);
InFlightPoll {
@@ -1061,6 +1210,211 @@ mod tests {
assert!(in_flight[1].is_complete());
}
+ #[test]
+ fn apply_completion_spanning_two_polls_credits_each() {
+ // A key-table run merges messages from consecutive polls into one
+ // send, so its completion spans both spans.
+ let mut in_flight = VecDeque::from([poll(1, 0, 0, 3, 4), poll(1, 0, 4, 7, 4)]);
+
+ apply_completion(&mut in_flight, completion(1, 0, &[2, 3, 4, 5], 4));
+
+ assert_eq!(in_flight[0].covered, 2);
+ assert_eq!(in_flight[0].accepted, 2);
+ assert_eq!(in_flight[1].covered, 2);
+ assert_eq!(in_flight[1].accepted, 2);
+ }
+
+ #[test]
+ fn apply_completion_under_report_shorts_the_tail_poll() {
+ let mut in_flight = VecDeque::from([poll(1, 0, 0, 3, 4), poll(1, 0, 4, 7, 4)]);
+
+ apply_completion(&mut in_flight, completion(1, 0, &[2, 3, 4, 5], 3));
+
+ assert_eq!(in_flight[0].accepted, 2, "leading offsets are accepted");
+ assert_eq!(
+ in_flight[1].accepted, 1,
+ "the tail poll fails its accepted check"
+ );
+ assert_eq!(in_flight[1].covered, 2);
+ }
+
+ #[test]
+ fn strip_revoked_partitions_keeps_the_other_partitions_slices() {
+ // A cooperative rebalance revokes one partition of a two-partition
+ // poll. The kept partition's slice must stay accounted, or its
+ // ledger charges never settle and its commits freeze at the hole.
+ let mut two = poll(1, 0, 0, 1, 4);
+ two.partitions.insert(
+ TopicPartition::new("test", 1),
+ PartitionDeliveries {
+ span: OffsetSpan {
+ first: 10,
+ last: 11,
+ },
+ generation: 0,
+ generations_version_seen: 0,
+ charges: Vec::new(),
+ latest_kafka_ts: 0,
+ max_lag_ms: None,
+ delivered: 2,
+ covered: 0,
+ accepted: 0,
+ },
+ );
+ two.partitions
+ .get_mut(&TopicPartition::new("test", 0))
+ .unwrap()
+ .delivered = 2;
+ let mut in_flight = VecDeque::from([two]);
+ // Partition 1 already had one message covered before the revoke.
+ apply_completion(&mut in_flight, completion(1, 1, &[10], 1));
+
+ let stripped = strip_revoked_partitions(
+ &mut in_flight,
+ &[RevokedPartition {
+ topic_partition: TopicPartition::new("test", 1),
+ generation: 1,
+ }],
+ );
+
+ assert_eq!(stripped, 2);
+ assert_eq!(in_flight[0].message_count, 2);
+ assert_eq!(in_flight[0].covered, 0, "the revoked slice's credit goes");
+ assert!(!in_flight[0].is_complete());
+
+ // The kept partition completes the poll; a late completion for the
+ // revoked partition is discarded, not credited.
+ apply_completion(&mut in_flight, completion(1, 1, &[11], 1));
+ assert_eq!(in_flight[0].covered, 0);
+ apply_completion(&mut in_flight, completion(1, 0, &[0, 1], 2));
+ assert!(in_flight[0].is_complete());
+ assert_eq!(in_flight[0].accepted, 2);
+ }
+
+ #[test]
+ fn strip_revoked_partitions_removes_an_emptied_poll() {
+ let mut in_flight = VecDeque::from([poll(1, 0, 0, 3, 4), poll(1, 2, 0, 3, 4)]);
+
+ let stripped = strip_revoked_partitions(
+ &mut in_flight,
+ &[RevokedPartition {
+ topic_partition: TopicPartition::new("test", 0),
+ generation: 1,
+ }],
+ );
+
+ assert_eq!(stripped, 4);
+ assert_eq!(in_flight.len(), 1);
+ assert_eq!(in_flight[0].message_count, 4);
+ }
+
+ #[test]
+ fn historical_revoke_keeps_a_reassigned_poll_and_its_ledger_slice() {
+ let topic_partition = TopicPartition::new("test", 0);
+ let ledger = TopicOffsetLedger::new();
+ let delivery = Delivery {
+ offset: 10,
+ charge: Charge {
+ events: 1,
+ bytes: 1,
+ },
+ kafka_ts: 0,
+ lag_ms: None,
+ };
+
+ // This collection saw offset 10 immediately before a revoke, then
+ // saw its replay after the partition was assigned again. Only the
+ // current generation is charged, while the poll still covers both
+ // deliveries that the batcher will complete.
+ let mut reassigned_deliveries = PartitionDeliveries::new(
+ ledger.generation(&topic_partition),
+ ledger.generations_version(),
+ &delivery,
+ );
+ ledger.forget_partitions([("test", 0)]);
+ ledger.forget_partitions([("test", 0)]);
+ reassigned_deliveries.record(
+ ledger.generations_version(),
+ || ledger.generation(&topic_partition),
+ &delivery,
+ );
+ assert_eq!(reassigned_deliveries.generation, 2);
+ assert_eq!(reassigned_deliveries.delivered, 2);
+ assert_eq!(reassigned_deliveries.charges.len(), 1);
+ ledger
+ .charge(
+ &topic_partition,
+ reassigned_deliveries.generation,
+ reassigned_deliveries.charges.iter().copied(),
+ )
+ .unwrap();
+
+ // The queued revoke notification belongs to generation 0. It must
+ // remove genuine old in-flight work, but not this poll collected and
+ // charged under the later reassignment.
+ let old_poll = poll(0, 0, 1, 1, 1);
+ let reassigned_poll = InFlightPoll {
+ poll_id: "reassigned".to_string(),
+ assignment_epoch: 1,
+ partitions: HashMap::from([(topic_partition.clone(), reassigned_deliveries)]),
+ message_count: 2,
+ covered: 0,
+ accepted: 0,
+ dispatched_at: Instant::now(),
+ };
+ let mut in_flight = VecDeque::from([old_poll, reassigned_poll]);
+
+ let stripped = strip_revoked_partitions(
+ &mut in_flight,
+ &[RevokedPartition {
+ topic_partition: topic_partition.clone(),
+ generation: 1,
+ }],
+ );
+
+ assert_eq!(stripped, 1, "only the old assignment is stripped");
+ assert_eq!(in_flight.len(), 1);
+ assert_eq!(in_flight[0].poll_id, "reassigned");
+
+ apply_completion(&mut in_flight, completion(1, 0, &[10, 10], 2));
+ assert!(in_flight[0].is_complete());
+ let reassigned = in_flight.pop_front().unwrap();
+ let retained = reassigned.partitions.get(&topic_partition).unwrap();
+ ledger
+ .settle(
+ &topic_partition,
+ retained.generation,
+ retained.charges.iter().map(|(offset, _)| *offset),
+ )
+ .unwrap();
+ assert_eq!(
+ ledger
+ .take_frontier(&topic_partition)
+ .map(|taken| taken.offset),
+ Some(Offset(11))
+ );
+
+ // With the retained replay slice settled, the next accepted offset
+ // advances normally instead of remaining stuck behind offset 10.
+ ledger
+ .charge(
+ &topic_partition,
+ retained.generation,
+ [(Offset(11), delivery.charge)],
+ )
+ .unwrap();
+ ledger
+ .settle(&topic_partition, retained.generation, [Offset(11)])
+ .unwrap();
+ assert_eq!(
+ ledger
+ .take_frontier(&topic_partition)
+ .map(|taken| taken.offset),
+ Some(Offset(12))
+ );
+ assert_eq!(ledger.held(&topic_partition).offsets, 0);
+ }
+
#[test]
fn apply_completion_requires_a_matching_epoch() {
// The same offsets exist in two polls when a partition was revoked,
@@ -1104,6 +1458,9 @@ mod tests {
.collect(),
latest_kafka_ts: 0,
max_lag_ms: None,
+ delivered: (last - first + 1) as u32,
+ covered: 0,
+ accepted: 0,
};
ledger
.charge(
diff --git a/rust/ingestion-consumer/src/dispatcher.rs b/rust/ingestion-consumer/src/dispatcher.rs
index f6c8d7dad84d..4e6c4231569e 100644
--- a/rust/ingestion-consumer/src/dispatcher.rs
+++ b/rust/ingestion-consumer/src/dispatcher.rs
@@ -9,11 +9,12 @@ use crate::aperture;
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, Settlement,
- SettlementOutcome, WorkerHealth, WorkerSnapshot,
+ Deadline, Dispatch, KeyRun, PinStashScheduler, Scheduler, SchedulerEffects, SchedulerKind,
+ Settlement, SettlementOutcome, WorkerHealth, WorkerSnapshot,
};
use crate::types::{Accumulator, Group, SerializedKafkaMessage};
use crate::worker_registry::{WorkerId, WorkerRegistry};
@@ -41,6 +42,9 @@ pub struct SubBatch {
/// Per-key max offsets. Pass back to `Dispatcher::on_sub_batch_acked` on
/// a successful ACK (only) so the order sentinel tracks ACK progress.
pub key_offsets: Vec<KeyOffset>,
+ /// The runs' epoch, for stamping completions; `None` from the pin-stash
+ /// scheduler, whose completions are stamped by the awaiting batch.
+ pub assignment_epoch: Option<u64>,
}
struct WorkerSubBatchBuilder {
@@ -61,7 +65,9 @@ impl WorkerSubBatchBuilder {
#[derive(Default)]
struct WorkerAssignments {
- by_worker: HashMap<WorkerId, WorkerSubBatchBuilder>,
+ /// Keyed by worker and epoch, so a sub-batch never mixes runs from two
+ /// epochs and its completions carry one stamp.
+ by_worker: HashMap<(WorkerId, Option<u64>), WorkerSubBatchBuilder>,
}
impl WorkerAssignments {
@@ -74,11 +80,12 @@ impl WorkerAssignments {
worker,
routing_key,
messages,
+ assignment_epoch,
..
} = dispatch;
let builder = self
.by_worker
- .entry(worker)
+ .entry((worker, assignment_epoch))
.or_insert_with(|| WorkerSubBatchBuilder {
messages: Vec::new(),
routing_keys: Vec::new(),
@@ -107,7 +114,7 @@ impl WorkerAssignments {
self.by_worker
.iter()
.filter(|(_, builder)| !builder.is_empty())
- .map(|(worker, builder)| SubBatchInfo {
+ .map(|((worker, _), builder)| SubBatchInfo {
worker: worker.to_string(),
messages: builder.message_count(),
routing_keys: builder.routing_keys.len(),
@@ -119,28 +126,168 @@ impl WorkerAssignments {
self.by_worker
.iter()
.filter(|(_, builder)| !builder.is_empty())
- .map(|(worker, builder)| (worker.clone(), builder.message_count()))
+ .map(|((worker, _), builder)| (worker.clone(), builder.message_count()))
}
fn into_sub_batches(self) -> Vec<SubBatch> {
self.by_worker
.into_iter()
.filter(|(_, builder)| !builder.is_empty())
- .map(|(worker, builder)| SubBatch {
+ .map(|((worker, assignment_epoch), builder)| SubBatch {
worker,
messages: builder.messages,
routing_keys: builder.routing_keys,
key_offsets: builder.key_offsets,
+ assignment_epoch,
})
.collect()
}
}
+/// The immediate result of assigning one submission while the scheduler lock
+/// is held. `retained` describes this submission, not mutable table state that
+/// a later task might observe after a purge or settlement.
+pub struct Submission<T> {
+ pub pending: Vec<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: PinStashScheduler,
+ scheduler: SchedulerImpl,
/// 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
@@ -163,6 +310,8 @@ 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.
@@ -183,7 +332,16 @@ impl Dispatcher {
/// Construct a dispatcher with an explicit routing strategy.
pub fn with_strategy(registry: Arc<WorkerRegistry>, strategy: RoutingStrategy) -> Self {
- Self::from_router(registry, strategy, Router::new(strategy))
+ 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))
}
/// Test-only constructor with a seeded RNG so P2C selection is deterministic.
@@ -193,21 +351,28 @@ impl Dispatcher {
strategy: RoutingStrategy,
seed: u64,
) -> Self {
- Self::from_router(registry, strategy, Router::with_seed(strategy, seed))
+ Self::from_router(
+ registry,
+ strategy,
+ SchedulerKind::default(),
+ Router::with_seed(strategy, seed),
+ )
}
fn from_router(
registry: Arc<WorkerRegistry>,
strategy: RoutingStrategy,
+ kind: SchedulerKind,
router: Router,
) -> Self {
Self {
inner: Mutex::new(DispatcherInner {
- scheduler: PinStashScheduler::new(router),
+ scheduler: SchedulerImpl::new(kind, router),
in_flight: WorkerLoad::new(),
}),
registry,
strategy,
+ scheduler_kind: kind,
key_sentinel: Arc::new(KeyOrderSentinel::new()),
aperture: None,
debug_recorder: None,
@@ -319,10 +484,11 @@ impl Dispatcher {
/// Assign a batch of messages to workers. Demuxes the messages into
/// groups first, as the collect path does for a poll, then assigns them
- /// like [`Dispatcher::assign_and_send`].
+ /// like [`Dispatcher::assign_and_send`]. Test-only entry point; the
+ /// epoch is fixed at 0.
pub fn assign(&self, batch_id: &str, messages: Vec<SerializedKafkaMessage>) -> Vec<SubBatch> {
let mut inner = self.inner.lock().unwrap();
- self.assign_groups(&mut inner, batch_id, demux(messages))
+ self.assign_groups(&mut inner, batch_id, 0, demux(messages))
}
/// Assign a poll's groups to workers, then hand each sub-batch to `send`
@@ -340,20 +506,31 @@ impl Dispatcher {
pub fn assign_and_send<T>(
&self,
batch_id: &str,
+ assignment_epoch: u64,
groups: Vec<Group>,
send: impl FnMut(SubBatch) -> T,
- ) -> Vec<T> {
+ ) -> Submission<T> {
+ let has_groups = !groups.is_empty();
let mut inner = self.inner.lock().unwrap();
- self.assign_groups(&mut inner, batch_id, groups)
+ let pending = self
+ .assign_groups(&mut inner, batch_id, assignment_epoch, groups)
.into_iter()
.map(send)
- .collect()
+ .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,
+ };
+ Submission { pending, retained }
}
fn assign_groups(
&self,
inner: &mut DispatcherInner,
batch_id: &str,
+ assignment_epoch: u64,
groups: Vec<Group>,
) -> Vec<SubBatch> {
let GroupedMessages {
@@ -374,7 +551,9 @@ impl Dispatcher {
dispatches,
deferred,
..
- } = inner.scheduler.on_groups(&snapshot, batch_id, runs);
+ } = inner
+ .scheduler
+ .on_groups(&snapshot, batch_id, assignment_epoch, runs);
let assignments = self.note_and_assemble(dispatches);
// Add each worker's message volume to its outstanding load.
@@ -483,6 +662,15 @@ 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.
@@ -545,6 +733,63 @@ 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");
+ for key in &effects.evicted_keys {
+ self.key_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
@@ -590,6 +835,34 @@ impl Dispatcher {
from_flush: bool,
failed: Option<(String, Vec<SerializedKafkaMessage>)>,
) {
+ let unsent = self.settle_and_send(
+ worker,
+ message_count,
+ routing_keys,
+ from_flush,
+ failed,
+ |sub_batch| sub_batch,
+ );
+ debug_assert!(
+ unsent.is_empty(),
+ "settle dropped dispatches; use settle_and_send"
+ );
+ }
+
+ /// Like [`Dispatcher::settle`], and additionally hands the settlement's
+ /// dispatches to `send` under the lock — the key table releases a key's
+ /// next run at settlement, and sending under the lock keeps a key's runs
+ /// entering its worker's stream in dispatch order. The caller must await
+ /// every returned send and settle it exactly once.
+ pub fn settle_and_send<T>(
+ &self,
+ worker: &WorkerId,
+ message_count: usize,
+ routing_keys: &[String],
+ from_flush: bool,
+ failed: Option<(String, Vec<SerializedKafkaMessage>)>,
+ send: impl FnMut(SubBatch) -> T,
+ ) -> Vec<T> {
let mut inner = self.inner.lock().unwrap();
let now_zero = match inner.in_flight.get_mut(worker) {
@@ -628,23 +901,53 @@ impl Dispatcher {
},
);
- if !effects.evicted_keys.is_empty() {
- for key in &effects.evicted_keys {
+ let SchedulerEffects {
+ dispatches,
+ deferred,
+ evicted_keys,
+ } = effects;
+
+ if !evicted_keys.is_empty() {
+ for key in &evicted_keys {
self.key_sentinel.evict(key);
}
counter!(
"ingestion_consumer_dispatcher_pin_evictions_total",
"reason" => "resolved",
)
- .increment(effects.evicted_keys.len() as u64);
+ .increment(evicted_keys.len() as u64);
}
+
+ let sent: Vec<T> = if dispatches.is_empty() {
+ Vec::new()
+ } else {
+ 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_sub_batches_assigned_total",
+ "worker" => worker.clone(),
+ )
+ .increment(1);
+ counter!(
+ "ingestion_consumer_dispatcher_messages_routed_total",
+ "worker" => worker.clone(),
+ )
+ .increment(message_count as u64);
+ }
+ assignments
+ .into_sub_batches()
+ .into_iter()
+ .map(send)
+ .collect()
+ };
drop(inner);
- if effects.deferred.send_failed > 0 {
+ if deferred.send_failed > 0 {
record_if(&self.debug_recorder, || DebugEventKind::Deferred {
batch_id: failed_batch_id.unwrap_or_default(),
reason: "send_failed",
- groups: effects.deferred.send_failed,
+ groups: deferred.send_failed,
});
}
record_if(&self.debug_recorder, || DebugEventKind::SubBatchResolved {
@@ -653,6 +956,7 @@ impl Dispatcher {
routing_keys: routing_keys.len(),
cleared_deferral: from_flush,
});
+ sent
}
/// Call when a worker ACKed a sub-batch (success path only, **before**
@@ -901,12 +1205,14 @@ mod tests {
routing_key: "tok:user-1".to_string(),
messages: make_msgs(&["tok:user-1"]),
kind: SendKind::Fresh,
+ assignment_epoch: None,
});
assignments.add_dispatch(Dispatch {
worker: wid(1),
routing_key: "tok:user-2".to_string(),
messages: make_msgs(&["tok:user-2"]),
kind: SendKind::Fresh,
+ assignment_epoch: None,
});
assert_eq!(
@@ -935,6 +1241,7 @@ mod tests {
routing_key: "tok:user-1".to_string(),
messages: vec![make_msg_at("tok:user-1", 100)],
kind: SendKind::Fresh,
+ assignment_epoch: None,
});
let sub_batches = assignments.into_sub_batches();
assert_eq!(sub_batches[0].key_offsets.len(), 1);
@@ -948,6 +1255,7 @@ mod tests {
routing_key: ":7:42".to_string(),
messages: vec![make_unkeyed_msg()],
kind: SendKind::Fresh,
+ assignment_epoch: None,
});
assert!(assignments.into_sub_batches()[0].key_offsets.is_empty());
}
@@ -1040,7 +1348,7 @@ mod tests {
.lock()
.unwrap()
.scheduler
- .pins
+ .pins()
.contains_key("t:user-1"));
dispatcher.on_sub_batch_resolved(
@@ -1056,7 +1364,7 @@ mod tests {
.lock()
.unwrap()
.scheduler
- .pins
+ .pins()
.contains_key("t:user-1"));
}
@@ -1071,7 +1379,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
);
@@ -1085,8 +1393,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);
}
}
@@ -1397,13 +1705,19 @@ 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.insert(
- "t:pinned".to_string(),
- Pin {
- worker: wid(0),
- ref_count: 1,
- },
- );
+ dispatcher
+ .inner
+ .lock()
+ .unwrap()
+ .scheduler
+ .pins_mut()
+ .insert(
+ "t:pinned".to_string(),
+ Pin {
+ worker: wid(0),
+ ref_count: 1,
+ },
+ );
let sub_batches = dispatcher.assign("b", make_msgs(&["t:pinned"]));
@@ -1493,6 +1807,38 @@ 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
@@ -1861,8 +2207,11 @@ mod tests {
let racing = Arc::clone(&dispatcher);
let mut race = None;
- let sent =
- dispatcher.assign_and_send("batch-2", demux(make_msgs(&["t:user-1"])), |sub_batch| {
+ let sent = dispatcher.assign_and_send(
+ "batch-2",
+ 0,
+ demux(make_msgs(&["t:user-1"])),
+ |sub_batch| {
// Admitted behind batch-1's live pin. batch-1's send now fails
// and tries to stash its messages before this group is enqueued.
let dispatcher = Arc::clone(&racing);
@@ -1876,8 +2225,13 @@ mod tests {
);
race = Some(handle);
sub_batch
- });
- assert_eq!(sent.len(), 1, "batch-2 was admitted and handed to send");
+ },
+ );
+ assert_eq!(
+ sent.pending.len(),
+ 1,
+ "batch-2 was admitted and handed to send"
+ );
race.take().expect("send ran").join().expect("defer_failed");
// The stash landed after the enqueue, so newer work for the key now
diff --git a/rust/ingestion-consumer/src/key_table.rs b/rust/ingestion-consumer/src/key_table.rs
index 4d3b46f4ef4a..5a477788e022 100644
--- a/rust/ingestion-consumer/src/key_table.rs
+++ b/rust/ingestion-consumer/src/key_table.rs
@@ -17,9 +17,10 @@
//! Not selected by any production caller yet; the scheduler switch is the
//! next change.
-use std::collections::{HashMap, VecDeque};
+use std::collections::{HashMap, HashSet, VecDeque};
+use std::time::{Duration, Instant};
-use metrics::{counter, gauge};
+use metrics::{counter, gauge, histogram};
use crate::order_sentinel::SendKind;
use crate::routing::{Router, WorkerLoad};
@@ -30,6 +31,17 @@ use crate::scheduler::{
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()
@@ -37,13 +49,36 @@ fn payload_bytes(messages: &[SerializedKafkaMessage]) -> usize {
.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<SerializedKafkaMessage>,
+ 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,
@@ -58,6 +93,8 @@ impl KeyState {
Self {
queue: VecDeque::new(),
outstanding: false,
+ outstanding_epoch: 0,
+ revoked_while_outstanding: Vec::new(),
parked: false,
redelivering: false,
}
@@ -114,50 +151,93 @@ impl KeyTable {
}
/// Append messages to the key's queue, creating the key when new.
- fn enqueue_back(&mut self, key: &str, messages: Vec<SerializedKafkaMessage>) {
+ 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);
+ .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.
- fn requeue_front(&mut self, key: &str, messages: Vec<SerializedKafkaMessage>) {
- self.queued_messages += messages.len();
- self.queued_bytes += payload_bytes(&messages);
+ /// 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(message);
+ state.queue.push_front(QueuedMessage {
+ epoch,
+ enqueued_at,
+ message,
+ });
}
}
- /// Drain the key's queue into one run and mark the key outstanding.
+ /// 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<Vec<SerializedKafkaMessage>> {
+ 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 run: Vec<SerializedKafkaMessage> = state.queue.drain(..).collect();
+ 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 >= run.len());
- self.queued_messages = self.queued_messages.saturating_sub(run.len());
- self.queued_bytes = self.queued_bytes.saturating_sub(payload_bytes(&run));
- Some(run)
+ 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
@@ -202,6 +282,7 @@ impl KeyTable {
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
}
@@ -209,6 +290,62 @@ impl KeyTable {
}
}
+ /// 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.as_str(), 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 {
@@ -262,15 +399,17 @@ impl KeyTableScheduler {
effects.deferred.unroutable += 1;
return;
};
- let Some(messages) = self.table.take_run(key) else {
+ let Some(run) = self.table.take_run(key) else {
return;
};
- bump_load(working_load, &worker, messages.len());
+ record_queue_wait(&run, kind);
+ bump_load(working_load, &worker, run.messages.len());
effects.dispatches.push(Dispatch {
worker,
routing_key: key.to_string(),
- messages,
+ messages: run.messages,
kind,
+ assignment_epoch: Some(run.epoch),
});
}
@@ -294,6 +433,7 @@ impl Scheduler for KeyTableScheduler {
&mut self,
snapshot: &WorkerSnapshot,
_batch_id: &str,
+ assignment_epoch: u64,
groups: Vec<KeyRun>,
) -> SchedulerEffects {
let mut effects = SchedulerEffects::with_dispatch_capacity(groups.len());
@@ -301,7 +441,8 @@ impl Scheduler for KeyTableScheduler {
let mut touched: Vec<String> = Vec::with_capacity(groups.len());
for group in groups {
- self.table.enqueue_back(&group.routing_key, group.messages);
+ 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) {
@@ -425,22 +566,35 @@ impl Scheduler for KeyTableScheduler {
} else {
SendKind::Fresh
};
- let Some(messages) = self.table.take_run(&key) else {
+ let Some(run) = self.table.take_run(&key) else {
continue;
};
- bump_load(&mut load, &worker, messages.len());
+ 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,
+ 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)]
@@ -544,7 +698,7 @@ mod tests {
fn test_fresh_key_dispatches_its_whole_run_and_goes_outstanding() {
let mut sched = scheduler();
- let effects = sched.on_groups(&snapshot(&[A], &[]), "b1", vec![run("t:a", &[1, 2])]);
+ 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));
@@ -558,9 +712,9 @@ mod tests {
#[test]
fn test_arrival_behind_an_outstanding_request_only_enqueues() {
let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b1", vec![run("t:a", &[1])]);
+ let _ = sched.on_groups(&snapshot(&[A], &[]), "b1", 0, vec![run("t:a", &[1])]);
- let effects = sched.on_groups(&snapshot(&[A], &[]), "b2", vec![run("t:a", &[2])]);
+ let effects = sched.on_groups(&snapshot(&[A], &[]), "b2", 0, vec![run("t:a", &[2])]);
assert!(
effects.dispatches.is_empty(),
@@ -581,6 +735,7 @@ mod tests {
let effects = sched.on_groups(
&snapshot(&[A, B], &[]),
"b1",
+ 0,
vec![run("t:a", &[1, 2, 3]), run("t:b", &[1, 2, 3])],
);
@@ -595,6 +750,7 @@ mod tests {
let effects = sched.on_groups(
&snapshot(&[A, B], &[]),
"b1",
+ 0,
vec![run("t:small", &[1]), run("t:big", &[1, 2, 3, 4, 5])],
);
@@ -611,6 +767,7 @@ mod tests {
let effects = sched.on_groups(
&snapshot(&[A], &[]),
"b1",
+ 0,
vec![run("t:a", &[1]), run("t:a", &[2])],
);
@@ -627,6 +784,7 @@ mod tests {
let effects = sched.on_groups(
&snapshot_narrowed(&[A, B], &[A], &[]),
"b1",
+ 0,
vec![run("t:a", &[1])],
);
@@ -639,7 +797,7 @@ mod tests {
fn test_unroutable_arrival_parks_the_key() {
let mut sched = scheduler();
- let effects = sched.on_groups(&snapshot(&[], &[]), "b1", vec![run("t:a", &[1, 2])]);
+ 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);
@@ -651,11 +809,11 @@ mod tests {
#[test]
fn test_arrival_behind_a_parked_key_waits_for_the_deadline() {
let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[], &[]), "b1", vec![run("t:a", &[1])]);
+ 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", vec![run("t:a", &[2])]);
+ 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);
@@ -667,8 +825,8 @@ mod tests {
#[test]
fn test_settlement_dispatches_the_next_queued_run() {
let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b1", vec![run("t:a", &[1])]);
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b2", vec![run("t:a", &[2, 3])]);
+ 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"]));
@@ -683,7 +841,7 @@ mod tests {
#[test]
fn test_settlement_with_an_empty_queue_evicts_the_key() {
let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b1", vec![run("t:a", &[1])]);
+ let _ = sched.on_groups(&snapshot(&[A], &[]), "b1", 0, vec![run("t:a", &[1])]);
let effects = sched.on_settled(&snapshot(&[A], &[]), delivered(A, &["t:a"]));
@@ -696,8 +854,8 @@ mod tests {
#[test]
fn test_settlement_parks_the_next_run_when_no_worker_is_routable() {
let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b1", vec![run("t:a", &[1])]);
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b2", vec![run("t:a", &[2])]);
+ 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"]));
@@ -724,9 +882,9 @@ mod tests {
#[test]
fn test_failed_settlement_requeues_at_the_front_and_parks() {
let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[A, B], &[]), "b1", vec![run("t:a", &[1, 2])]);
+ 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", vec![run("t:a", &[3])]);
+ let _ = sched.on_groups(&snapshot(&[A, B], &[]), "b2", 0, vec![run("t:a", &[3])]);
let effects = sched.on_settled(
&snapshot(&[A, B], &[]),
@@ -752,8 +910,8 @@ mod tests {
#[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", vec![run("t:a", &[1, 2])]);
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b2", vec![run("t:a", &[3])]);
+ 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);
@@ -788,10 +946,10 @@ mod tests {
#[test]
fn test_new_arrivals_queue_behind_a_failure_awaiting_retry() {
let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[A], &[]), "b1", vec![run("t:a", &[1])]);
+ 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", vec![run("t:a", &[2])]);
+ let effects = sched.on_groups(&snapshot(&[A], &[]), "b2", 0, vec![run("t:a", &[2])]);
assert!(
effects.dispatches.is_empty(),
@@ -802,6 +960,24 @@ mod tests {
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();
@@ -837,7 +1013,7 @@ mod tests {
#[test]
fn test_batch_deadline_is_a_noop_for_the_key_table() {
let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[], &[]), "b1", vec![run("t:a", &[1])]);
+ let _ = sched.on_groups(&snapshot(&[], &[]), "b1", 0, vec![run("t:a", &[1])]);
let effects = sched.on_deadline(&snapshot(&[A], &[]), Deadline::Batch("b1"));
@@ -851,6 +1027,7 @@ mod tests {
let _ = sched.on_groups(
&snapshot(&[], &[]),
"b1",
+ 0,
vec![run("t:a", &[1]), run("t:b", &[1])],
);
assert_eq!(sched.table().parked_keys(), 2);
@@ -872,7 +1049,7 @@ mod tests {
#[test]
fn test_parked_retry_keeps_keys_parked_when_no_worker_is_healthy() {
let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[], &[]), "b1", vec![run("t:a", &[1])]);
+ let _ = sched.on_groups(&snapshot(&[], &[]), "b1", 0, vec![run("t:a", &[1])]);
let effects = sched.on_deadline(&snapshot(&[], &[]), Deadline::ParkedRetry);
@@ -880,7 +1057,7 @@ mod tests {
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", vec![run("t:a", &[2])]);
+ 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]);
@@ -889,7 +1066,7 @@ mod tests {
#[test]
fn test_parked_retry_routes_over_the_whole_healthy_pool() {
let mut sched = scheduler();
- let _ = sched.on_groups(&snapshot(&[], &[]), "b1", vec![run("t:a", &[1])]);
+ 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.
@@ -899,6 +1076,123 @@ mod tests {
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".to_string();
+ 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]
@@ -914,15 +1208,15 @@ mod tests {
};
// Arrive, dispatch, fail, queue more, retry, settle, queue drains.
- let effects = sched.on_groups(&snapshot(&[A], &[]), "b1", vec![run("t:a", &[1, 2])]);
+ 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", vec![run("t:a", &[3])]);
+ 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", vec![run("t:a", &[4])]);
+ 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);
@@ -945,11 +1239,13 @@ mod tests {
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])],
);
diff --git a/rust/ingestion-consumer/src/main.rs b/rust/ingestion-consumer/src/main.rs
index cd143bc149cc..510183e08011 100644
--- a/rust/ingestion-consumer/src/main.rs
+++ b/rust/ingestion-consumer/src/main.rs
@@ -141,7 +141,14 @@ async fn async_main(config: Config) -> Result<()> {
204_800.0,
],
)
- .expect("consumer_batch_size_kb buckets");
+ .expect("consumer_batch_size_kb buckets")
+ .set_buckets_for_metric(
+ Matcher::Full("ingestion_consumer_key_table_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");
// Global default labels (match the Node.js `initializePrometheusLabels`
// defaults): every metric carries ingestion_pipeline / ingestion_lane so
@@ -220,7 +227,11 @@ async fn async_main(config: Config) -> Result<()> {
None
};
- let mut dispatcher = Dispatcher::with_strategy(Arc::clone(&registry), config.routing_strategy);
+ let mut dispatcher = Dispatcher::with_scheduler(
+ Arc::clone(&registry),
+ config.routing_strategy,
+ config.scheduler,
+ );
if let Some(recorder) = &debug_recorder {
dispatcher.set_debug_recorder(Arc::clone(recorder));
}
@@ -496,6 +507,7 @@ async fn async_main(config: Config) -> Result<()> {
Arc::clone(&transport),
consumer_handle.clone(),
Duration::from_millis(config.consumer_deferred_flush_timeout_ms),
+ Duration::from_millis(config.parked_retry_interval_ms),
);
let consumer = IngestionConsumer::new(
diff --git a/rust/ingestion-consumer/src/order_sentinel.rs b/rust/ingestion-consumer/src/order_sentinel.rs
index dc6b1dec8c86..d6bc52016bd6 100644
--- a/rust/ingestion-consumer/src/order_sentinel.rs
+++ b/rust/ingestion-consumer/src/order_sentinel.rs
@@ -24,7 +24,7 @@
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
-use std::sync::{Arc, Mutex};
+use std::sync::{Arc, Mutex, OnceLock};
use metrics::{counter, gauge};
use rdkafka::consumer::{BaseConsumer, ConsumerContext, Rebalance};
@@ -328,8 +328,13 @@ pub struct SentinelContext {
/// rebalances. Distinct from the offset ledger's generations, which move
/// per partition and stamp offset accounting rather than stream order.
assignment_epoch: Option<AssignmentEpoch>,
+ /// Called with the revoked `(topic, partition)` pairs, so the scheduler
+ /// can drop their queued messages before the new owner replays them.
+ revoke_hook: OnceLock<RevokeHook>,
}
+type RevokeHook = Box<dyn Fn(&[(String, i32)]) + Send + Sync>;
+
impl SentinelContext {
pub fn new(
commit_sentinel: Arc<CommitSentinel>,
@@ -341,9 +346,16 @@ impl SentinelContext {
key_sentinel,
topic_offset_ledger,
assignment_epoch: None,
+ revoke_hook: OnceLock::new(),
}
}
+ /// Wire the revocation hook; a second call is ignored. Settable after
+ /// construction because the rdkafka consumer only hands out `&self`.
+ pub fn set_revoke_hook(&self, hook: RevokeHook) {
+ let _ = self.revoke_hook.set(hook);
+ }
+
/// Wire the process-wide assignment epoch. Call before the context is
/// handed to the Kafka consumer.
pub fn set_assignment_epoch(&mut self, epoch: AssignmentEpoch) {
@@ -419,6 +431,17 @@ impl ConsumerContext for SentinelContext {
// 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.
+ if let Some(hook) = self.revoke_hook.get() {
+ let partitions: Vec<(String, i32)> = tpl
+ .elements()
+ .iter()
+ .map(|e| (e.topic().to_string(), e.partition()))
+ .collect();
+ hook(&partitions);
+ }
}
Rebalance::Assign(_) => {}
Rebalance::Error(err) => {
diff --git a/rust/ingestion-consumer/src/scheduler.rs b/rust/ingestion-consumer/src/scheduler.rs
index cee616c1cacd..4537c33e47db 100644
--- a/rust/ingestion-consumer/src/scheduler.rs
+++ b/rust/ingestion-consumer/src/scheduler.rs
@@ -17,6 +17,7 @@
//! this same interface.
use std::collections::HashMap;
+use std::str::FromStr;
use metrics::{counter, gauge};
@@ -87,6 +88,9 @@ pub struct Dispatch {
/// Fresh assignment or a retry of deferred work; the key-order sentinel
/// notes the send under this kind.
pub kind: SendKind,
+ /// The run's epoch, for stamping its completions. `None` from the
+ /// pin-stash scheduler, whose caller stamps from the flush ticket.
+ pub assignment_epoch: Option<u64>,
}
/// One resolved send arriving at the seam.
@@ -173,6 +177,29 @@ impl SchedulerEffects {
}
}
+/// Which scheduler implementation the dispatcher runs. Selected by config;
+/// the switch back is the rollback.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub enum SchedulerKind {
+ #[default]
+ PinStash,
+ KeyTable,
+}
+
+impl FromStr for SchedulerKind {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s.trim().to_lowercase().as_str() {
+ "pin_stash" | "pin-stash" | "pinstash" => Ok(SchedulerKind::PinStash),
+ "key_table" | "key-table" | "keytable" => Ok(SchedulerKind::KeyTable),
+ other => Err(format!(
+ "unknown scheduler '{other}' (expected 'pin_stash' or 'key_table')"
+ )),
+ }
+ }
+}
+
/// The decision core: which runs may go to a worker now, and where.
///
/// The caller owes the seam two things: it sends every dispatch an effects
@@ -181,12 +208,13 @@ impl SchedulerEffects {
/// release path for an outstanding key, so a dropped dispatch or a lost
/// settlement wedges that key permanently.
pub trait Scheduler {
- /// One poll's key runs arrived, in batch order. A key may repeat; its
- /// runs merge in queue order.
+ /// One poll's key runs arrived, in batch order, collected under
+ /// `assignment_epoch`. A key may repeat; its runs merge in queue order.
fn on_groups(
&mut self,
snapshot: &WorkerSnapshot,
batch_id: &str,
+ assignment_epoch: u64,
groups: Vec<KeyRun>,
) -> SchedulerEffects;
@@ -200,6 +228,12 @@ pub trait Scheduler {
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()
+ }
}
/// Sticky pin for one routing key. Tracks which worker owns the key and how
@@ -306,6 +340,7 @@ impl Scheduler for PinStashScheduler {
&mut self,
snapshot: &WorkerSnapshot,
batch_id: &str,
+ _assignment_epoch: u64,
groups: Vec<KeyRun>,
) -> SchedulerEffects {
let mut effects = SchedulerEffects::with_dispatch_capacity(groups.len());
@@ -329,6 +364,7 @@ impl Scheduler for PinStashScheduler {
routing_key: group.routing_key,
messages: group.messages,
kind: SendKind::Fresh,
+ assignment_epoch: None,
});
}
Some(_) => {
@@ -409,6 +445,7 @@ impl Scheduler for PinStashScheduler {
routing_key: group.routing_key,
messages: group.messages,
kind: SendKind::Fresh,
+ assignment_epoch: None,
});
}
@@ -551,6 +588,7 @@ impl Scheduler for PinStashScheduler {
routing_key: group.routing_key,
messages: group.messages,
kind: SendKind::Resend,
+ assignment_epoch: None,
});
}
@@ -728,7 +766,7 @@ mod tests {
let mut sched = scheduler();
sched.register_batch("b1");
- let effects = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", vec![run("t:a", 2)]);
+ let effects = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", 0, vec![run("t:a", 2)]);
assert_eq!(effects.dispatches.len(), 1);
assert_eq!(effects.dispatches[0].worker, wid(A));
@@ -742,13 +780,14 @@ mod tests {
fn test_pinned_key_sticks_to_its_worker_despite_load() {
let mut sched = scheduler();
sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", vec![run("t:a", 1)]);
+ let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
// B is now available and far less loaded — the pin still wins.
sched.register_batch("b2");
let effects = sched.on_groups(
&snapshot(&[A, B], &[], &[(A, 10_000)]),
"b2",
+ 0,
vec![run("t:a", 1)],
);
@@ -766,6 +805,7 @@ mod tests {
let effects = sched.on_groups(
&snapshot(&[A, B], &[], &[]),
"b1",
+ 0,
vec![run("t:a", 3), run("t:b", 3)],
);
@@ -781,6 +821,7 @@ mod tests {
let effects = sched.on_groups(
&snapshot(&[A, B], &[], &[]),
"b1",
+ 0,
vec![run("t:small", 1), run("t:big", 5)],
);
@@ -795,7 +836,7 @@ mod tests {
let mut sched = scheduler();
sched.register_batch("b1");
- let effects = sched.on_groups(&snapshot(&[], &[], &[]), "b1", vec![run("t:a", 2)]);
+ let effects = sched.on_groups(&snapshot(&[], &[], &[]), "b1", 0, vec![run("t:a", 2)]);
assert!(effects.dispatches.is_empty());
assert_eq!(effects.deferred.unroutable, 1);
@@ -810,7 +851,7 @@ mod tests {
fn test_pinned_key_defers_when_worker_draining() {
let mut sched = scheduler();
sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[A, B], &[], &[]), "b1", vec![run("t:a", 1)]);
+ let _ = sched.on_groups(&snapshot(&[A, B], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
let pinned = sched.pins.get("t:a").unwrap().worker.clone();
let pinned_str = pinned.to_string();
@@ -819,6 +860,7 @@ mod tests {
let effects = sched.on_groups(
&snapshot(&[survivor], &[&pinned_str], &[]),
"b2",
+ 0,
vec![run("t:a", 1)],
);
@@ -831,12 +873,12 @@ mod tests {
fn test_pinned_key_defers_when_worker_absent_from_snapshot() {
let mut sched = scheduler();
sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", vec![run("t:a", 1)]);
+ let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
// A is gone from the health map entirely (removed from the registry):
// absent must count as dead, not as healthy.
sched.register_batch("b2");
- let effects = sched.on_groups(&snapshot(&[B], &[], &[]), "b2", vec![run("t:a", 1)]);
+ let effects = sched.on_groups(&snapshot(&[B], &[], &[]), "b2", 0, vec![run("t:a", 1)]);
assert!(effects.dispatches.is_empty());
assert_eq!(effects.deferred.drain, 1);
@@ -846,14 +888,14 @@ mod tests {
fn test_deferring_key_keeps_deferring_even_when_worker_recovers() {
let mut sched = scheduler();
sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", vec![run("t:a", 1)]);
+ let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
sched.register_batch("b2");
- let _ = sched.on_groups(&snapshot(&[B], &[A], &[]), "b2", vec![run("t:a", 1)]);
+ let _ = sched.on_groups(&snapshot(&[B], &[A], &[]), "b2", 0, vec![run("t:a", 1)]);
// A is healthy again, but b2's deferred group hasn't flushed — newer
// messages must queue behind it, and count as cascade, not drain.
sched.register_batch("b3");
- let effects = sched.on_groups(&snapshot(&[A, B], &[], &[]), "b3", vec![run("t:a", 1)]);
+ let effects = sched.on_groups(&snapshot(&[A, B], &[], &[]), "b3", 0, vec![run("t:a", 1)]);
assert!(effects.dispatches.is_empty());
assert_eq!(effects.deferred.queued_behind_deferral, 1);
@@ -865,11 +907,11 @@ mod tests {
let mut sched = scheduler();
sched.register_batch("b1");
// Unroutable: stashed with no pin.
- let _ = sched.on_groups(&snapshot(&[], &[], &[]), "b1", vec![run("t:a", 1)]);
+ let _ = sched.on_groups(&snapshot(&[], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
// A worker appears, but the stashed group must go first.
sched.register_batch("b2");
- let effects = sched.on_groups(&snapshot(&[A], &[], &[]), "b2", vec![run("t:a", 1)]);
+ let effects = sched.on_groups(&snapshot(&[A], &[], &[]), "b2", 0, vec![run("t:a", 1)]);
assert!(effects.dispatches.is_empty());
assert_eq!(effects.deferred.queued_behind_deferral, 1);
@@ -881,7 +923,7 @@ mod tests {
fn test_settlement_evicts_idle_pin() {
let mut sched = scheduler();
sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", vec![run("t:a", 1)]);
+ let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
let effects = sched.on_settled(&snapshot(&[A], &[], &[]), delivered(A, &["t:a"], false));
@@ -893,9 +935,9 @@ mod tests {
fn test_settlement_keeps_pin_while_key_still_defers() {
let mut sched = scheduler();
sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", vec![run("t:a", 1)]);
+ let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
sched.register_batch("b2");
- let _ = sched.on_groups(&snapshot(&[B], &[A], &[]), "b2", vec![run("t:a", 1)]);
+ let _ = sched.on_groups(&snapshot(&[B], &[A], &[]), "b2", 0, vec![run("t:a", 1)]);
// b1's send lands, dropping the ref-count to zero — but b2's deferred
// group is still stashed, so the pin must survive for it.
@@ -909,9 +951,9 @@ mod tests {
fn test_stale_settlement_does_not_touch_repointed_pin() {
let mut sched = scheduler();
sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", vec![run("t:a", 1)]);
+ let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
sched.register_batch("b2");
- let _ = sched.on_groups(&snapshot(&[B], &[A], &[]), "b2", vec![run("t:a", 1)]);
+ let _ = sched.on_groups(&snapshot(&[B], &[A], &[]), "b2", 0, vec![run("t:a", 1)]);
// The deferred flush re-points the pin to B while b1's send is still
// unresolved on A.
@@ -930,7 +972,7 @@ mod tests {
fn test_failed_settlement_restashes_before_releasing_the_key() {
let mut sched = scheduler();
sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[A, B], &[], &[]), "b1", vec![run("t:a", 2)]);
+ let _ = sched.on_groups(&snapshot(&[A, B], &[], &[]), "b1", 0, vec![run("t:a", 2)]);
let effects = sched.on_settled(
&snapshot(&[A, B], &[], &[]),
@@ -946,7 +988,7 @@ mod tests {
// Newer messages queue behind the replay instead of overtaking it.
sched.register_batch("b2");
- let effects = sched.on_groups(&snapshot(&[A, B], &[], &[]), "b2", vec![run("t:a", 1)]);
+ let effects = sched.on_groups(&snapshot(&[A, B], &[], &[]), "b2", 0, vec![run("t:a", 1)]);
assert!(effects.dispatches.is_empty());
assert_eq!(effects.deferred.queued_behind_deferral, 1);
}
@@ -955,7 +997,7 @@ mod tests {
fn test_failed_flush_keeps_key_deferring() {
let mut sched = scheduler();
sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[], &[], &[]), "b1", vec![run("t:a", 1)]);
+ let _ = sched.on_groups(&snapshot(&[], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
let effects = sched.on_deadline(&snapshot(&[A], &[], &[]), Deadline::Batch("b1"));
assert_eq!(effects.dispatches.len(), 1);
@@ -967,7 +1009,7 @@ mod tests {
);
sched.register_batch("b2");
- let effects = sched.on_groups(&snapshot(&[A], &[], &[]), "b2", vec![run("t:a", 1)]);
+ let effects = sched.on_groups(&snapshot(&[A], &[], &[]), "b2", 0, vec![run("t:a", 1)]);
assert!(effects.dispatches.is_empty());
assert_eq!(effects.deferred.queued_behind_deferral, 1);
}
@@ -989,7 +1031,7 @@ mod tests {
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", vec![run("t:a", 1)]);
+ 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.
@@ -1003,7 +1045,7 @@ mod tests {
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", vec![run("t:a", 1)]);
+ let _ = sched.on_groups(&snapshot(&[], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
let effects = sched.on_deadline(&snapshot(&[], &[], &[]), Deadline::Batch("b1"));
@@ -1016,9 +1058,9 @@ mod tests {
fn test_flushed_key_keeps_deferring_until_the_flush_settles() {
let mut sched = scheduler();
sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", vec![run("t:a", 1)]);
+ let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
sched.register_batch("b2");
- let _ = sched.on_groups(&snapshot(&[B], &[A], &[]), "b2", vec![run("t:a", 1)]);
+ 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"));
@@ -1033,7 +1075,7 @@ mod tests {
// The flushed send is in flight but not ACKed — newer messages must
// not honor the fresh pin and race it.
sched.register_batch("b3");
- let effects = sched.on_groups(&snapshot(&[B], &[A], &[]), "b3", vec![run("t:a", 1)]);
+ let effects = sched.on_groups(&snapshot(&[B], &[A], &[]), "b3", 0, vec![run("t:a", 1)]);
assert!(effects.dispatches.is_empty());
assert_eq!(effects.deferred.queued_behind_deferral, 1);
diff --git a/rust/ingestion-consumer/tests/dispatcher_integration_test.rs b/rust/ingestion-consumer/tests/dispatcher_integration_test.rs
index 182a87b6ed61..70fc20844ae0 100644
--- a/rust/ingestion-consumer/tests/dispatcher_integration_test.rs
+++ b/rust/ingestion-consumer/tests/dispatcher_integration_test.rs
@@ -3,6 +3,9 @@ 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;
use axum::routing::get;
@@ -10,8 +13,12 @@ use axum::Router;
use tokio::net::TcpListener;
use tokio_util::sync::CancellationToken;
+use ingestion_consumer::batcher::Batcher;
use ingestion_consumer::dispatcher::Dispatcher;
-use ingestion_consumer::types::SerializedKafkaMessage;
+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};
// ---- FakeWorker ----
@@ -467,3 +474,85 @@ async fn test_draining_worker_defers_then_flushes_to_survivor() {
token.cancel();
}
+
+#[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(
+ 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),
+ transport,
+ handle,
+ Duration::from_secs(10),
+ Duration::from_millis(20),
+ );
+
+ 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)]);
+
+ match tokio::time::timeout(Duration::from_millis(100), outputs.errors.recv()).await {
+ Err(_) => {}
+ Ok(Some(error)) => panic!("revoked work must not report a routing failure: {error}"),
+ Ok(None) => panic!("batcher error channel closed unexpectedly"),
+ }
+}
+
+#[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(
+ 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,
+ transport,
+ handle,
+ Duration::from_secs(10),
+ Duration::from_millis(20),
+ );
+
+ drop(batcher);
+
+ let completion = tokio::time::timeout(Duration::from_millis(100), outputs.completions.recv())
+ .await
+ .expect("dropping the batcher must not leave an idle retry task retaining its senders");
+ assert!(
+ completion.is_none(),
+ "an idle dropped batcher cannot produce a completion"
+ );
+ assert!(
+ outputs.errors.recv().await.is_none(),
+ "all output senders close with the dropped batcher"
+ );
+}
diff --git a/rust/ingestion-consumer/tests/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rs
index 4efa045648b2..fcc8492096d3 100644
--- a/rust/ingestion-consumer/tests/e2e_integration_test.rs
+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs
@@ -20,6 +20,7 @@ use rdkafka::message::{Header, OwnedHeaders};
use rdkafka::producer::{FutureProducer, FutureRecord};
use rdkafka::util::Timeout;
use rdkafka::TopicPartitionList;
+use rstest::rstest;
use tokio::net::TcpListener;
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
@@ -30,6 +31,8 @@ use ingestion_consumer::discovery::reconcile_membership;
use ingestion_consumer::dispatcher::Dispatcher;
use ingestion_consumer::grpc_transport::{GrpcPort, GrpcTransport};
use ingestion_consumer::order_sentinel::SentinelContext;
+use ingestion_consumer::routing::RoutingStrategy;
+use ingestion_consumer::scheduler::SchedulerKind;
use ingestion_consumer::types::SerializedKafkaMessage;
use ingestion_consumer::worker_registry::{
WorkerId, WorkerRegistry, WorkerRegistryConfig, WorkerState,
@@ -420,6 +423,7 @@ impl WorkerIngestService for FakeWorkerGrpc {
// ── Test harness ───────────────────────────────────────────────────────────
struct Harness {
+ scheduler: SchedulerKind,
pub workers: Vec<FakeWorker>,
pub registry: Arc<WorkerRegistry>,
pub dispatcher: Arc<Dispatcher>,
@@ -515,6 +519,7 @@ fn spawn_reaper(
impl Harness {
async fn start(
+ kind: SchedulerKind,
topic: &str,
partitions: i32,
worker_count: usize,
@@ -523,6 +528,7 @@ impl Harness {
registry_config: WorkerRegistryConfig,
) -> Self {
Self::start_inner(
+ kind,
topic,
partitions,
worker_count,
@@ -536,6 +542,7 @@ impl Harness {
}
async fn start_with_liveness(
+ kind: SchedulerKind,
topic: &str,
worker_count: usize,
deferred_flush_timeout: Duration,
@@ -543,6 +550,7 @@ impl Harness {
stall_threshold: u32,
) -> Self {
Self::start_inner(
+ kind,
topic,
1,
worker_count,
@@ -560,8 +568,9 @@ impl Harness {
/// Like `start`, but bounds batch collection by payload bytes as well as
/// count (`CONSUMER_BATCH_SIZE_KB`). Single worker and partition, so each
/// sub-batch is one whole Kafka batch.
- async fn start_byte_capped(topic: &str, batch_size_bytes: usize) -> Self {
+ async fn start_byte_capped(kind: SchedulerKind, topic: &str, batch_size_bytes: usize) -> Self {
Self::start_inner(
+ kind,
topic,
1,
1,
@@ -576,6 +585,7 @@ impl Harness {
#[allow(clippy::too_many_arguments)]
async fn start_inner(
+ kind: SchedulerKind,
topic: &str,
partitions: i32,
worker_count: usize,
@@ -598,7 +608,11 @@ impl Harness {
let probe_token = CancellationToken::new();
Arc::clone(&registry).start_probing(probe_token.clone());
- let dispatcher = Arc::new(Dispatcher::new(Arc::clone(&registry)));
+ let dispatcher = Arc::new(Dispatcher::with_scheduler(
+ 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());
@@ -634,6 +648,7 @@ impl Harness {
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,
@@ -645,6 +660,7 @@ impl Harness {
tokio::time::sleep(Duration::from_millis(300)).await;
Self {
+ scheduler: kind,
workers,
registry: registry_for_test,
dispatcher: dispatcher_for_test,
@@ -677,7 +693,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::new(Arc::clone(&registry)));
+ let dispatcher = Arc::new(Dispatcher::with_scheduler(
+ Arc::clone(&registry),
+ RoutingStrategy::default(),
+ self.scheduler,
+ ));
let transport = Arc::new(test_transport());
spawn_reaper(
Arc::clone(&registry),
@@ -708,6 +728,7 @@ impl Harness {
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,
@@ -829,10 +850,14 @@ fn sole_arrived_worker(harness: &Harness) -> usize {
/// the responsibility of the concurrent-batches layer: when concurrent_batches>1,
/// the Dispatcher's ref-counted pins keep the assignment alive across overlapping
/// in-flight batches. That invariant is tested in the concurrent-batches suite.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn messages_per_distinct_id_arrive_in_order() {
+async fn messages_per_distinct_id_arrive_in_order(#[case] kind: SchedulerKind) {
let topic = format!("e2e-ordering-{}", Uuid::new_v4());
let harness = Harness::start(
+ kind,
&topic,
3,
2,
@@ -878,10 +903,13 @@ async fn messages_per_distinct_id_arrive_in_order() {
/// (the second crosses it). The count cap alone cannot express that, which is
/// the regression: a lane whose events are large gets the memory of a full
/// count batch no matter how the count is tuned.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn byte_bound_caps_batches_below_the_count_bound() {
+async fn byte_bound_caps_batches_below_the_count_bound(#[case] kind: SchedulerKind) {
let topic = format!("e2e-bytecap-{}", Uuid::new_v4());
- let harness = Harness::start_byte_capped(&topic, 4096).await;
+ let harness = Harness::start_byte_capped(kind, &topic, 4096).await;
let producer = make_producer();
let payload = vec![b'x'; 2048];
@@ -921,10 +949,13 @@ async fn byte_bound_caps_batches_below_the_count_bound() {
/// always admitted. Checking after would let one oversized payload produce an
/// empty batch and wedge its partition — the message can never be skipped, and
/// no smaller batch can ever contain it.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn message_larger_than_byte_bound_is_still_delivered() {
+async fn message_larger_than_byte_bound_is_still_delivered(#[case] kind: SchedulerKind) {
let topic = format!("e2e-bytecap-oversize-{}", Uuid::new_v4());
- let harness = Harness::start_byte_capped(&topic, 4096).await;
+ let harness = Harness::start_byte_capped(kind, &topic, 4096).await;
let producer = make_producer();
produce_raw(
@@ -950,10 +981,14 @@ async fn message_larger_than_byte_bound_is_still_delivered() {
/// When a worker becomes unhealthy, its sticky pins are dropped and subsequent
/// messages for the same key are rerouted to a healthy worker.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn failing_worker_triggers_rerouting() {
+async fn failing_worker_triggers_rerouting(#[case] kind: SchedulerKind) {
let topic = format!("e2e-failover-{}", Uuid::new_v4());
let harness = Harness::start(
+ kind,
&topic,
2,
2,
@@ -1009,10 +1044,14 @@ async fn failing_worker_triggers_rerouting() {
/// A worker whose sends fail (5xx through every retry) is a fault for passive
/// health, not backpressure: the failed sends must degrade it even though the
/// readiness probe keeps passing.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn failed_sends_degrade_passive_health() {
+async fn failed_sends_degrade_passive_health(#[case] kind: SchedulerKind) {
let topic = format!("e2e-passive-fault-{}", Uuid::new_v4());
let harness = Harness::start(
+ kind,
&topic,
1,
1,
@@ -1043,10 +1082,14 @@ async fn failed_sends_degrade_passive_health() {
/// subsequent messages for the same distinct_id reroute in order to a surviving
/// worker. The drainer stays alive throughout (it is not failed), so the probe
/// must not declare it dead.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn draining_worker_takes_no_new_work_and_reroutes_in_order() {
+async fn draining_worker_takes_no_new_work_and_reroutes_in_order(#[case] kind: SchedulerKind) {
let topic = format!("e2e-drain-{}", Uuid::new_v4());
let harness = Harness::start(
+ kind,
&topic,
2,
2,
@@ -1173,10 +1216,14 @@ fn worker_msg(distinct_id: &str, seq: usize) -> SerializedKafkaMessage {
/// A send that fails mid-flight is deferred and replayed, in order, to the
/// surviving worker — no loss, no duplication, no reordering.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn send_failure_mid_flight_replays_to_survivor_in_order() {
+async fn send_failure_mid_flight_replays_to_survivor_in_order(#[case] kind: SchedulerKind) {
let topic = format!("e2e-replay-single-{}", Uuid::new_v4());
let harness = Harness::start(
+ kind,
&topic,
1,
2,
@@ -1229,10 +1276,14 @@ async fn send_failure_mid_flight_replays_to_survivor_in_order() {
/// In a batch split across two workers, only the failed sub-batch is deferred
/// and replayed; the successful one is not re-sent. Everything ends up on the
/// survivor, in order, with the failed worker having recorded nothing.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn partial_send_failure_replays_only_the_failed_subbatch() {
+async fn partial_send_failure_replays_only_the_failed_subbatch(#[case] kind: SchedulerKind) {
let topic = format!("e2e-replay-partial-{}", Uuid::new_v4());
let harness = Harness::start(
+ kind,
&topic,
2,
2,
@@ -1293,13 +1344,22 @@ async fn partial_send_failure_replays_only_the_failed_subbatch() {
/// worker returns, then drains in order. Waiting for a worker, and waiting on
/// a slow one once found, both outlast the liveness deadline here: neither is
/// a stall, so the lifecycle monitor must not shut the consumer down.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn deferred_flush_retries_until_a_worker_recovers() {
+async fn deferred_flush_retries_until_a_worker_recovers(#[case] kind: SchedulerKind) {
let topic = format!("e2e-replay-wait-{}", Uuid::new_v4());
let liveness_deadline = Duration::from_millis(1500);
- let harness =
- Harness::start_with_liveness(&topic, 2, Duration::from_secs(60), liveness_deadline, 2)
- .await;
+ let harness = Harness::start_with_liveness(
+ kind,
+ &topic,
+ 2,
+ Duration::from_secs(60),
+ liveness_deadline,
+ 2,
+ )
+ .await;
let producer = make_producer();
// Take worker 1 out of the pool so the batch routes to worker 0.
@@ -1338,16 +1398,16 @@ async fn deferred_flush_retries_until_a_worker_recovers() {
wait_until(
Duration::from_secs(10),
"the failed send to be deferred",
- || harness.dispatcher.stashed_messages() > 0,
+ || harness.dispatcher.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.stashed_messages();
+ let held = harness.dispatcher.held_messages();
tokio::time::sleep(liveness_deadline * 4).await;
assert_eq!(
- harness.dispatcher.stashed_messages(),
+ harness.dispatcher.held_messages(),
held,
"deferred work must be held steady while no worker is available"
);
@@ -1392,13 +1452,18 @@ async fn deferred_flush_retries_until_a_worker_recovers() {
/// With no worker ever coming back, the batch must still fail: the flush
/// loop's own `deferred_flush_timeout` ends it, not a liveness stall, so the
/// exit lands at the flush timeout rather than at the (shorter) stall window.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn no_worker_exit_comes_from_the_flush_timeout_not_a_liveness_stall() {
+async fn no_worker_exit_comes_from_the_flush_timeout_not_a_liveness_stall(
+ #[case] kind: SchedulerKind,
+) {
let topic = format!("e2e-flush-timeout-liveness-{}", Uuid::new_v4());
let flush_timeout = Duration::from_secs(4);
let liveness_deadline = Duration::from_millis(1500);
let mut harness =
- Harness::start_with_liveness(&topic, 2, flush_timeout, liveness_deadline, 2).await;
+ Harness::start_with_liveness(kind, &topic, 2, flush_timeout, liveness_deadline, 2).await;
let producer = make_producer();
harness.workers[1].healthy.store(false, Ordering::SeqCst);
@@ -1423,7 +1488,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.stashed_messages() > 0,
+ || harness.dispatcher.held_messages() > 0,
)
.await;
let deferred_at = tokio::time::Instant::now();
@@ -1450,13 +1515,16 @@ async fn no_worker_exit_comes_from_the_flush_timeout_not_a_liveness_stall() {
/// liveness deadline and the flush timeout: every landing resets the flush
/// deadline, and the wait in between keeps the heartbeat going. Two keys land
/// in two flush rounds, the first only after the original deadline has passed.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn slow_deferred_drain_with_progress_outlasts_the_flush_timeout() {
+async fn slow_deferred_drain_with_progress_outlasts_the_flush_timeout(#[case] kind: SchedulerKind) {
let topic = format!("e2e-slow-drain-{}", Uuid::new_v4());
let flush_timeout = Duration::from_secs(3);
let liveness_deadline = Duration::from_millis(1500);
let harness =
- Harness::start_with_liveness(&topic, 3, flush_timeout, liveness_deadline, 2).await;
+ Harness::start_with_liveness(kind, &topic, 3, flush_timeout, liveness_deadline, 2).await;
let producer = make_producer();
// Workers 1 and 2 out, so both keys route to worker 0 together.
@@ -1510,7 +1578,7 @@ async fn slow_deferred_drain_with_progress_outlasts_the_flush_timeout() {
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.stashed_messages() > 0
+ harness.workers[2].arrived_count() == 1 && harness.dispatcher.held_messages() > 0
})
.await;
let guard2 = harness.workers[2].block().await;
@@ -1571,10 +1639,14 @@ async fn slow_deferred_drain_with_progress_outlasts_the_flush_timeout() {
/// A failed multi-key sub-batch replays every key, each in its own Kafka order,
/// once a worker is available.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn multi_key_send_failure_replays_every_key_in_order() {
+async fn multi_key_send_failure_replays_every_key_in_order(#[case] kind: SchedulerKind) {
let topic = format!("e2e-replay-multikey-{}", Uuid::new_v4());
let harness = Harness::start(
+ kind,
&topic,
3,
2,
@@ -1636,10 +1708,14 @@ async fn multi_key_send_failure_replays_every_key_in_order() {
/// A replay whose target also fails is re-deferred and retried until it lands —
/// cascading failures during flush never lose or reorder the deferred work.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn flush_target_failure_re_defers_then_replays_in_order() {
+async fn flush_target_failure_re_defers_then_replays_in_order(#[case] kind: SchedulerKind) {
let topic = format!("e2e-replay-cascade-{}", Uuid::new_v4());
let harness = Harness::start(
+ kind,
&topic,
1,
2,
@@ -1698,7 +1774,7 @@ async fn flush_target_failure_re_defers_then_replays_in_order() {
wait_until(
Duration::from_secs(10),
"re-deferred work to be held after the replay target also fails",
- || harness.dispatcher.stashed_messages() > 0,
+ || harness.dispatcher.held_messages() > 0,
)
.await;
@@ -1807,10 +1883,14 @@ async fn drain_defer_flush_delivers_to_survivor_over_stream() {
/// deploy overlap — must not fail the batch: fresh keys that can't route
/// anywhere are held and delivered once a worker returns, instead of being
/// dropped (which fails the batch and restarts the process).
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn full_pool_drain_holds_fresh_keys_until_a_worker_returns() {
+async fn full_pool_drain_holds_fresh_keys_until_a_worker_returns(#[case] kind: SchedulerKind) {
let topic = format!("e2e-full-drain-{}", Uuid::new_v4());
let harness = Harness::start(
+ kind,
&topic,
1,
2,
@@ -1857,14 +1937,26 @@ async fn full_pool_drain_holds_fresh_keys_until_a_worker_returns() {
/// while its request is still live. The reap must not break the in-flight
/// resolve, and the key's deferred messages must re-route to a survivor in
/// order once the held batch completes.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn forced_reap_at_drain_timeout_reroutes_deferred_work() {
+async fn forced_reap_at_drain_timeout_reroutes_deferred_work(#[case] kind: SchedulerKind) {
let topic = format!("e2e-forced-reap-{}", Uuid::new_v4());
let registry_config = WorkerRegistryConfig {
drain_timeout: Duration::from_millis(400),
..fast_registry_config()
};
- let harness = Harness::start(&topic, 1, 2, 2, Duration::from_secs(60), registry_config).await;
+ let harness = Harness::start(
+ kind,
+ &topic,
+ 1,
+ 2,
+ 2,
+ Duration::from_secs(60),
+ registry_config,
+ )
+ .await;
let producer = make_producer();
let mut guards: Vec<Option<tokio::sync::OwnedMutexGuard<()>>> = Vec::new();
@@ -1892,7 +1984,7 @@ async fn forced_reap_at_drain_timeout_reroutes_deferred_work() {
produce(&producer, &topic, 0, "tok", "user-1", seq).await;
}
wait_until(Duration::from_secs(10), "batch 2 to defer", || {
- harness.dispatcher.stashed_messages() > 0
+ harness.dispatcher.held_messages() > 0
})
.await;
@@ -1934,10 +2026,14 @@ async fn forced_reap_at_drain_timeout_reroutes_deferred_work() {
/// committed must not lose anything: the restarted consumer resumes from the
/// last commit and redelivers. Duplicates are allowed (at-least-once); loss is
/// not.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn consumer_crash_before_commit_redelivers_without_loss() {
+async fn consumer_crash_before_commit_redelivers_without_loss(#[case] kind: SchedulerKind) {
let topic = format!("e2e-restart-{}", Uuid::new_v4());
let mut harness = Harness::start(
+ kind,
&topic,
1,
2,
@@ -1991,10 +2087,14 @@ async fn consumer_crash_before_commit_redelivers_without_loss() {
/// The broker-committed offset is the ledger frontier — one past everything
/// the workers accepted — and a restart resumes from it with no loss and no
/// redelivery.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn the_committed_offset_is_the_ledger_frontier() {
+async fn the_committed_offset_is_the_ledger_frontier(#[case] kind: SchedulerKind) {
let topic = format!("e2e-ledger-commit-{}", Uuid::new_v4());
let mut harness = Harness::start(
+ kind,
&topic,
1,
1,
@@ -2044,10 +2144,14 @@ async fn the_committed_offset_is_the_ledger_frontier() {
/// from a failed send, so the consumer replays the batch: duplicates are the
/// accepted cost of at-least-once, loss never is, and the replay lands behind
/// the original delivery.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn lost_ack_after_processing_replays_without_loss() {
+async fn lost_ack_after_processing_replays_without_loss(#[case] kind: SchedulerKind) {
let topic = format!("e2e-lost-ack-{}", Uuid::new_v4());
let harness = Harness::start(
+ kind,
&topic,
1,
2,
@@ -2099,10 +2203,14 @@ async fn lost_ack_after_processing_replays_without_loss() {
/// committed, redelivered after restart) rather than spinning forever. Until a
/// DLQ path exists, a poison batch crash-loops the process by design; this
/// pins the "safe" half of that trade-off.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn poison_batch_fails_safely_without_committing() {
+async fn poison_batch_fails_safely_without_committing(#[case] kind: SchedulerKind) {
let topic = format!("e2e-poison-{}", Uuid::new_v4());
let mut harness = Harness::start(
+ kind,
&topic,
1,
2,
@@ -2138,10 +2246,14 @@ async fn poison_batch_fails_safely_without_committing() {
/// sent violates the transport contract. The consumer must treat the batch as
/// incomplete and fail it — never commit offsets over an under-acknowledged
/// batch, which would silently lose the unaccounted messages.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn partial_acceptance_fails_the_batch_without_commit() {
+async fn partial_acceptance_fails_the_batch_without_commit(#[case] kind: SchedulerKind) {
let topic = format!("e2e-partial-accept-{}", Uuid::new_v4());
let mut harness = Harness::start(
+ kind,
&topic,
1,
2,
@@ -2178,10 +2290,14 @@ async fn partial_acceptance_fails_the_batch_without_commit() {
/// A drainer that crashes mid-drain (its in-flight send fails instead of
/// finishing) must not wedge the drain: both its failed in-flight batch and
/// the work deferred behind it replay to the survivor, in order.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn drainer_crash_mid_drain_replays_to_survivor_in_order() {
+async fn drainer_crash_mid_drain_replays_to_survivor_in_order(#[case] kind: SchedulerKind) {
let topic = format!("e2e-drain-crash-{}", Uuid::new_v4());
let harness = Harness::start(
+ kind,
&topic,
1,
2,
@@ -2216,7 +2332,7 @@ async fn drainer_crash_mid_drain_replays_to_survivor_in_order() {
produce(&producer, &topic, 0, "tok", "user-1", seq).await;
}
wait_until(Duration::from_secs(10), "batch 2 to defer", || {
- harness.dispatcher.stashed_messages() > 0
+ harness.dispatcher.held_messages() > 0
})
.await;
@@ -2244,10 +2360,14 @@ async fn drainer_crash_mid_drain_replays_to_survivor_in_order() {
/// The whole pool failing at once with multiple keys in flight, at
/// max_in_flight > 1: everything is stashed while nothing is routable, then
/// drains to the first recovered worker with per-key order intact.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn full_pool_send_failure_with_multiple_keys_recovers_in_order() {
+async fn full_pool_send_failure_with_multiple_keys_recovers_in_order(#[case] kind: SchedulerKind) {
let topic = format!("e2e-pool-loss-{}", Uuid::new_v4());
let harness = Harness::start(
+ kind,
&topic,
2,
2,
@@ -2284,7 +2404,7 @@ async fn full_pool_send_failure_with_multiple_keys_recovers_in_order() {
wait_until(
Duration::from_secs(10),
"all failed work to be stashed",
- || harness.dispatcher.stashed_messages() == 8,
+ || harness.dispatcher.held_messages() == 8,
)
.await;
@@ -2311,10 +2431,14 @@ async fn full_pool_send_failure_with_multiple_keys_recovers_in_order() {
/// Messages without token/distinct_id headers route under synthetic
/// per-message keys; a send failure must replay them exactly once, like any
/// other message.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn headerless_messages_survive_send_failure_replay() {
+async fn headerless_messages_survive_send_failure_replay(#[case] kind: SchedulerKind) {
let topic = format!("e2e-headerless-{}", Uuid::new_v4());
let harness = Harness::start(
+ kind,
&topic,
1,
2,
@@ -2384,10 +2508,14 @@ async fn headerless_messages_survive_send_failure_replay() {
/// A non-UTF-8 payload cannot round-trip the string wire format — its body is
/// nulled in transit today (a known content-loss gap) — but the event itself
/// must still route via its headers and reach a worker, not be dropped.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn non_utf8_payload_is_delivered_not_lost() {
+async fn non_utf8_payload_is_delivered_not_lost(#[case] kind: SchedulerKind) {
let topic = format!("e2e-non-utf8-{}", Uuid::new_v4());
let harness = Harness::start(
+ kind,
&topic,
1,
1,
@@ -2433,10 +2561,14 @@ async fn non_utf8_payload_is_delivered_not_lost() {
/// A full fleet replacement, reconciled exactly as EndpointSlice discovery
/// does: the desired set flips to brand-new workers, the old ones drain and
/// are reaped, and traffic keeps flowing — exactly once, in per-key order.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn fleet_redeploy_migrates_work_to_new_workers_without_loss() {
+async fn fleet_redeploy_migrates_work_to_new_workers_without_loss(#[case] kind: SchedulerKind) {
let topic = format!("e2e-redeploy-{}", Uuid::new_v4());
let mut harness = Harness::start(
+ kind,
&topic,
2,
2,
@@ -2507,10 +2639,14 @@ async fn fleet_redeploy_migrates_work_to_new_workers_without_loss() {
/// the first while it holds an uncommitted in-flight batch. Redelivery of that
/// batch on the new owner may duplicate (at-least-once) — but nothing may be
/// lost across the handover.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn second_consumer_joining_the_group_preserves_all_messages() {
+async fn second_consumer_joining_the_group_preserves_all_messages(#[case] kind: SchedulerKind) {
let topic = format!("e2e-two-consumers-{}", Uuid::new_v4());
let harness = Harness::start(
+ kind,
&topic,
2,
2,
@@ -2542,7 +2678,11 @@ async fn second_consumer_joining_the_group_preserves_all_messages() {
let registry2 = Arc::new(WorkerRegistry::new(&worker_urls, fast_registry_config()));
let probe2 = CancellationToken::new();
Arc::clone(&registry2).start_probing(probe2.clone());
- let dispatcher2 = Arc::new(Dispatcher::new(Arc::clone(&registry2)));
+ let dispatcher2 = Arc::new(Dispatcher::with_scheduler(
+ 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());
@@ -2559,6 +2699,7 @@ async fn second_consumer_joining_the_group_preserves_all_messages() {
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,
@@ -2604,12 +2745,16 @@ async fn second_consumer_joining_the_group_preserves_all_messages() {
/// partition then starts another generation. A ledger bug here would
/// surface as ledger errors or a wedged loop, so continued delivery after
/// both handovers is the health signal.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn partition_lost_and_regained_keeps_the_consumer_alive() {
+async fn partition_lost_and_regained_keeps_the_consumer_alive(#[case] kind: SchedulerKind) {
let topic = format!("e2e-regain-{}", Uuid::new_v4());
// Room for many in-flight batches, so the first consumer keeps polling
// while its batches are held and the rebalance can land underneath them.
let harness = Harness::start(
+ kind,
&topic,
2,
2,
@@ -2647,7 +2792,11 @@ async fn partition_lost_and_regained_keeps_the_consumer_alive() {
let registry2 = Arc::new(WorkerRegistry::new(&worker_urls, fast_registry_config()));
let probe2 = CancellationToken::new();
Arc::clone(&registry2).start_probing(probe2.clone());
- let dispatcher2 = Arc::new(Dispatcher::new(Arc::clone(&registry2)));
+ let dispatcher2 = Arc::new(Dispatcher::with_scheduler(
+ Arc::clone(&registry2),
+ RoutingStrategy::default(),
+ kind,
+ ));
let transport2 = Arc::new(test_transport());
let mut manager2 = Manager::builder("e2e-regain-c2")
.with_trap_signals(false)
@@ -2666,6 +2815,7 @@ async fn partition_lost_and_regained_keeps_the_consumer_alive() {
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,
@@ -2750,8 +2900,11 @@ async fn partition_lost_and_regained_keeps_the_consumer_alive() {
/// the same `group.instance.id`, so the broker fences the first. The fenced
/// instance's client is permanently dead — the consumer must exit (so the pod
/// restarts) rather than keep polling it while reporting healthy.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn fenced_static_member_exits_on_fatal_error() {
+async fn fenced_static_member_exits_on_fatal_error(#[case] kind: SchedulerKind) {
let topic = format!("e2e-fenced-{}", Uuid::new_v4());
create_topic(&topic, 1).await;
@@ -2760,7 +2913,11 @@ async fn fenced_static_member_exits_on_fatal_error() {
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::new(Arc::clone(&registry)));
+ let dispatcher = Arc::new(Dispatcher::with_scheduler(
+ Arc::clone(&registry),
+ RoutingStrategy::default(),
+ kind,
+ ));
let transport = Arc::new(test_transport());
let mut manager = Manager::builder("e2e-fenced")
.with_trap_signals(false)
@@ -2779,6 +2936,7 @@ async fn fenced_static_member_exits_on_fatal_error() {
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,
@@ -2893,7 +3051,12 @@ fn spawn_churn(
})
}
-async fn run_churn_suite(churn: Churn, max_in_flight: usize, strict_order: bool) {
+async fn run_churn_suite(
+ kind: SchedulerKind,
+ churn: Churn,
+ max_in_flight: usize,
+ strict_order: bool,
+) {
let topic = format!("e2e-churn-{churn:?}-mif{max_in_flight}-{}", Uuid::new_v4());
let dids = 8usize;
let per_did = 60usize;
@@ -2901,6 +3064,7 @@ async fn run_churn_suite(churn: Churn, max_in_flight: usize, strict_order: bool)
let partitions = 4i32;
let harness = Harness::start(
+ kind,
&topic,
partitions,
4,
@@ -2972,7 +3136,7 @@ async fn run_churn_suite(churn: Churn, max_in_flight: usize, strict_order: bool)
Duration::from_secs(10),
"dispatcher pins/in-flight/stash to drain to zero after churn",
|| {
- harness.dispatcher.stashed_messages() == 0
+ harness.dispatcher.held_messages() == 0
&& harness.dispatcher.pin_count() == 0
&& harness.dispatcher.total_in_flight() == 0
},
@@ -2982,35 +3146,53 @@ async fn run_churn_suite(churn: Churn, max_in_flight: usize, strict_order: bool)
harness.stop().await;
}
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn churn_drain_preserves_order_at_max_in_flight_2() {
- run_churn_suite(Churn::Drain, 2, true).await;
+async fn churn_drain_preserves_order_at_max_in_flight_2(#[case] kind: SchedulerKind) {
+ run_churn_suite(kind, Churn::Drain, 2, true).await;
}
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn churn_drain_preserves_order_at_max_in_flight_3() {
- run_churn_suite(Churn::Drain, 3, true).await;
+async fn churn_drain_preserves_order_at_max_in_flight_3(#[case] kind: SchedulerKind) {
+ run_churn_suite(kind, Churn::Drain, 3, true).await;
}
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn churn_send_failures_are_exactly_once_at_max_in_flight_3() {
- run_churn_suite(Churn::Fail, 3, false).await;
+async fn churn_send_failures_are_exactly_once_at_max_in_flight_3(#[case] kind: SchedulerKind) {
+ run_churn_suite(kind, Churn::Fail, 3, false).await;
}
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn churn_mixed_drain_and_failures_are_exactly_once_at_max_in_flight_3() {
- run_churn_suite(Churn::Mixed, 3, false).await;
+async fn churn_mixed_drain_and_failures_are_exactly_once_at_max_in_flight_3(
+ #[case] kind: SchedulerKind,
+) {
+ run_churn_suite(kind, Churn::Mixed, 3, false).await;
}
/// A flapping worker — ready (in the pool) but failing every send — must not pin
/// a batch's offsets forever. The flush loop enforces its deadline on the
/// re-defer path too, so the consumer fails the batch within the configured
/// flush timeout instead of spinning. Runs at max_in_flight > 1.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn flapping_worker_does_not_pin_batch_past_flush_timeout() {
+async fn flapping_worker_does_not_pin_batch_past_flush_timeout(#[case] kind: SchedulerKind) {
let topic = format!("e2e-flap-{}", Uuid::new_v4());
// Short flush timeout so the bound is observable quickly; concurrency > 1.
let mut harness = Harness::start(
+ kind,
&topic,
1,
2,
@@ -3068,10 +3250,14 @@ async fn flapping_worker_does_not_pin_batch_past_flush_timeout() {
/// A worker that nacks fences its worker stream: the fenced messages fail back into
/// the deferral path with nothing lost, and once the worker leaves the pool
/// the keys re-route to the survivor in order.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn nacking_worker_fences_worker_stream_and_reroutes_in_order() {
+async fn nacking_worker_fences_worker_stream_and_reroutes_in_order(#[case] kind: SchedulerKind) {
let topic = format!("e2e-fence-{}", Uuid::new_v4());
let harness = Harness::start(
+ kind,
&topic,
2,
2,
@@ -3126,10 +3312,14 @@ async fn nacking_worker_fences_worker_stream_and_reroutes_in_order() {
/// and wedge the consumer. Two waves prove commits keep flowing: with
/// max_in_flight = 1, the second wave can only deliver after the first wave's
/// polls completed.
+#[rstest]
+#[case::pin_stash(SchedulerKind::PinStash)]
+#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn same_key_across_partitions_completes_and_commits() {
+async fn same_key_across_partitions_completes_and_commits(#[case] kind: SchedulerKind) {
let topic = format!("e2e-cross-partition-key-{}", Uuid::new_v4());
let harness = Harness::start(
+ kind,
&topic,
2,
1,
diff --git a/rust/ingestion-consumer/tests/grpc_transport_test.rs b/rust/ingestion-consumer/tests/grpc_transport_test.rs
index 1ed9f1780639..bb1c3acd090b 100644
--- a/rust/ingestion-consumer/tests/grpc_transport_test.rs
+++ b/rust/ingestion-consumer/tests/grpc_transport_test.rs
@@ -7,12 +7,19 @@
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_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::SerializedKafkaMessage;
+use ingestion_consumer::types::{Accumulator, SerializedKafkaMessage};
+use ingestion_consumer::worker_registry::{WorkerRegistry, WorkerRegistryConfig};
use ingestion_worker_proto::ingestion::worker::v1::worker_ingest_server::{
WorkerIngest, WorkerIngestServer,
};
@@ -20,7 +27,8 @@ use ingestion_worker_proto::ingestion::worker::v1::{
ingest_stream_request, ingest_stream_response, IngestStreamRequest, IngestStreamResponse,
StreamReady, SubBatch, SubBatchAck, SubBatchStatus,
};
-use tokio::sync::{mpsc, Mutex};
+use lifecycle::{ComponentOptions, Manager};
+use tokio::sync::{mpsc, oneshot, Mutex};
use tokio_stream::wrappers::UnboundedReceiverStream;
use tokio_stream::StreamExt;
use tonic::{Request, Response, Status, Streaming};
@@ -740,3 +748,317 @@ async fn a_busy_status_fences_as_retriable_with_messages() {
assert!(err.error.is_retriable(), "busy is retriable backpressure");
assert!(matches!(err.error, TransportError::WorkerStreamBusy(_)));
}
+
+enum ControlledReply {
+ Busy,
+ Ok,
+}
+
+struct BusyAttempt {
+ worker: usize,
+ reply: oneshot::Sender<ControlledReply>,
+}
+
+struct ControlledBusyWorker {
+ worker: usize,
+ attempts: mpsc::UnboundedSender<BusyAttempt>,
+}
+
+#[tonic::async_trait]
+impl WorkerIngest for ControlledBusyWorker {
+ type IngestStreamStream = UnboundedReceiverStream<Result<IngestStreamResponse, Status>>;
+
+ async fn ingest_stream(
+ &self,
+ request: Request<Streaming<IngestStreamRequest>>,
+ ) -> Result<Response<Self::IngestStreamStream>, Status> {
+ let mut inbound = request.into_inner();
+ let attempts = self.attempts.clone();
+ let worker = self.worker;
+ let (tx, rx) = mpsc::unbounded_channel();
+ tokio::spawn(async move {
+ let _ = tx.send(Ok(IngestStreamResponse {
+ msg: Some(ingest_stream_response::Msg::Ready(StreamReady {})),
+ }));
+ while let Some(Ok(frame)) = inbound.next().await {
+ let Some(ingest_stream_request::Msg::SubBatch(sub_batch)) = frame.msg else {
+ continue;
+ };
+ let (reply, wait_for_reply) = oneshot::channel();
+ let Some(reply) = async {
+ attempts.send(BusyAttempt { worker, reply }).ok()?;
+ wait_for_reply.await.ok()
+ }
+ .await
+ else {
+ return;
+ };
+ let (status, accepted, error) = match reply {
+ ControlledReply::Busy => {
+ (SubBatchStatus::Busy as i32, 0, "at capacity".to_string())
+ }
+ ControlledReply::Ok => (
+ SubBatchStatus::Ok as i32,
+ sub_batch.messages.len() as u32,
+ String::new(),
+ ),
+ };
+ let _ = tx.send(Ok(IngestStreamResponse {
+ msg: Some(ingest_stream_response::Msg::Ack(SubBatchAck {
+ seq: sub_batch.seq,
+ status,
+ accepted,
+ error,
+ })),
+ }));
+ }
+ });
+ Ok(Response::new(UnboundedReceiverStream::new(rx)))
+ }
+}
+
+async fn start_controlled_busy_worker(
+ worker: usize,
+ attempts: mpsc::UnboundedSender<BusyAttempt>,
+) -> SocketAddr {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ tonic::transport::Server::builder()
+ .add_service(
+ WorkerIngestServer::new(ControlledBusyWorker { worker, attempts })
+ .accept_compressed(tonic::codec::CompressionEncoding::Gzip)
+ .send_compressed(tonic::codec::CompressionEncoding::Gzip),
+ )
+ .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener))
+ .await
+ .unwrap();
+ });
+ addr
+}
+
+fn registry_config() -> WorkerRegistryConfig {
+ WorkerRegistryConfig {
+ probe_interval: Duration::from_secs(60),
+ dead_declaration: Duration::from_secs(60),
+ passive_window: Duration::from_secs(60),
+ passive_error_threshold: 1.0,
+ passive_min_samples: usize::MAX,
+ degraded_hold: Duration::ZERO,
+ min_state_duration: Duration::ZERO,
+ probe_failure_threshold: u32::MAX,
+ drain_timeout: Duration::from_secs(60),
+ }
+}
+
+#[tokio::test]
+async fn key_table_watchdog_bounds_overlapping_busy_retries() {
+ let (attempts_tx, mut attempts_rx) = mpsc::unbounded_channel();
+ let first_addr = start_controlled_busy_worker(0, attempts_tx.clone()).await;
+ let second_addr = start_controlled_busy_worker(1, attempts_tx).await;
+ let worker_urls = vec![
+ format!("http://{first_addr}"),
+ format!("http://{second_addr}"),
+ ];
+ let registry = Arc::new(WorkerRegistry::new(&worker_urls, registry_config()));
+ let dispatcher = Arc::new(Dispatcher::with_scheduler(
+ 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,
+ transport,
+ handle,
+ Duration::from_millis(100),
+ Duration::from_millis(20),
+ );
+
+ let mut accumulator = Accumulator::default();
+ accumulator.push(Partition(0), msg("a", 1).into());
+ accumulator.push(Partition(0), msg("b", 2).into());
+ batcher.submit(accumulator);
+
+ let first = tokio::time::timeout(Duration::from_secs(1), attempts_rx.recv())
+ .await
+ .expect("first key reaches a worker")
+ .expect("attempt channel stays open");
+ let second = tokio::time::timeout(Duration::from_secs(1), attempts_rx.recv())
+ .await
+ .expect("second key reaches a worker")
+ .expect("attempt channel stays open");
+ assert_ne!(
+ first.worker, second.worker,
+ "the two keys must occupy different workers"
+ );
+
+ // Always leave one request outstanding while rejecting the other. If a
+ // retry does not arrive, release the held request after a bounded delay:
+ // the watchdog may wait for a slow in-flight attempt to settle, but must
+ // then diagnose the scheduler-wide lack of acceptance.
+ let busy_replies = Arc::new(AtomicUsize::new(0));
+ let replies = Arc::clone(&busy_replies);
+ let final_attempt_released = Arc::new(AtomicBool::new(false));
+ let released = Arc::clone(&final_attempt_released);
+ let controller = tokio::spawn(async move {
+ let mut reject = first;
+ let mut held = second;
+ loop {
+ let _ = reject.reply.send(ControlledReply::Busy);
+ replies.fetch_add(1, Ordering::Relaxed);
+ match tokio::time::timeout(Duration::from_millis(750), attempts_rx.recv()).await {
+ Ok(Some(next)) => {
+ reject = held;
+ held = next;
+ }
+ _ => {
+ let _ = held.reply.send(ControlledReply::Busy);
+ replies.fetch_add(1, Ordering::Relaxed);
+ released.store(true, Ordering::Relaxed);
+ return;
+ }
+ }
+ }
+ });
+ let error = tokio::time::timeout(Duration::from_secs(3), outputs.errors.recv())
+ .await
+ .expect("watchdog must bound retries that make no acceptance progress")
+ .expect("batcher error channel stays open");
+ assert_eq!(
+ error,
+ "key-table work made no progress within the stall timeout"
+ );
+ assert!(
+ final_attempt_released.load(Ordering::Relaxed),
+ "an in-flight attempt may settle after the deadline before the watchdog fails"
+ );
+ assert!(
+ busy_replies.load(Ordering::Relaxed) >= 2,
+ "the reproduction must overlap busy retry rounds"
+ );
+ controller.await.unwrap();
+}
+
+#[tokio::test]
+async fn key_table_parked_retry_drains_after_shutdown_signal() {
+ 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(
+ 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,
+ transport,
+ handle,
+ Duration::from_millis(500),
+ Duration::from_millis(20),
+ );
+
+ let mut accumulator = Accumulator::default();
+ accumulator.push(Partition(0), msg("a", 1).into());
+ batcher.submit(accumulator);
+
+ let first = tokio::time::timeout(Duration::from_secs(1), attempts_rx.recv())
+ .await
+ .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("attempt channel stays open");
+ assert!(retry.reply.send(ControlledReply::Ok).is_ok());
+
+ let completion = tokio::time::timeout(Duration::from_secs(1), outputs.completions.recv())
+ .await
+ .expect("successful retry completes")
+ .expect("completion channel stays open");
+ assert_eq!(completion.accepted, 1);
+ tokio::time::sleep(Duration::from_millis(550)).await;
+ assert!(
+ outputs.errors.try_recv().is_err(),
+ "accepted retry resets the watchdog and idle work stays healthy"
+ );
+}
+
+#[tokio::test]
+async fn key_table_watchdog_allows_in_flight_success_after_the_deadline() {
+ 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(
+ 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,
+ transport,
+ handle,
+ Duration::from_millis(100),
+ Duration::from_millis(20),
+ );
+
+ let mut accumulator = Accumulator::default();
+ accumulator.push(Partition(0), msg("a", 1).into());
+ batcher.submit(accumulator);
+
+ let attempt = tokio::time::timeout(Duration::from_secs(1), attempts_rx.recv())
+ .await
+ .expect("send reaches the worker")
+ .expect("attempt channel stays open");
+ tokio::time::sleep(Duration::from_millis(150)).await;
+ assert!(
+ outputs.errors.try_recv().is_err(),
+ "the watchdog must wait for an in-flight send after its deadline"
+ );
+ assert!(attempt.reply.send(ControlledReply::Ok).is_ok());
+ let completion = tokio::time::timeout(Duration::from_secs(1), outputs.completions.recv())
+ .await
+ .expect("late successful send completes")
+ .expect("completion channel stays open");
+ assert_eq!(completion.accepted, 1);
+
+ tokio::time::sleep(Duration::from_millis(150)).await;
+ assert!(
+ outputs.errors.try_recv().is_err(),
+ "late acceptance resets the watchdog and idle work stays healthy"
+ );
+}