:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ingestion-consumer): graceful worker drain with ordered replay (#65145)
José Sequeiraa0e3e24441dd
diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rsindex c88fe890400e..2cd27621cdb8 100644--- a/rust/ingestion-consumer/src/config.rs+++ b/rust/ingestion-consumer/src/config.rs@@ -165,6 +165,14 @@ pub struct Config {#[envconfig(from = "WORKER_PORT", default = "9001")]pub worker_port: u16,+ /// When a worker leaves the pool (e.g. a draining pod during a deploy), it is+ /// marked draining rather than removed: no new work is routed to it, but its+ /// in-flight batches are allowed to finish and ACK. It is fully removed once+ /// its in-flight count reaches zero, or after this timeout as a safety net+ /// (milliseconds) — sized above the worst-case batch processing time.+ #[envconfig(from = "WORKER_DRAIN_TIMEOUT_MS", default = "30000")]+ pub worker_drain_timeout_ms: u64,+/// How unpinned routing keys are assigned to workers: `binpack` (default,/// least-loaded — accurate for the co-located sidecar) or `p2c`/// (power-of-two-choices — herd-resistant for a shared worker pool).diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rsindex 9277894e4b9b..ab39e89eb940 100644--- a/rust/ingestion-consumer/src/consumer.rs+++ b/rust/ingestion-consumer/src/consumer.rs@@ -13,10 +13,14 @@ use tracing::{error, info, warn};use crate::config::Config;use crate::discovery::DiscoveryMode;-use crate::dispatcher::Dispatcher;+use crate::dispatcher::{Dispatcher, SubBatch};use crate::transport::HttpTransport;use crate::types::SerializedKafkaMessage;+/// Max time `complete_oldest_batch` will keep retrying to flush a batch's+/// deferred groups (waiting for a healthy worker) before failing the batch.+const DEFERRED_FLUSH_TIMEOUT: Duration = Duration::from_secs(60);+/// Statistics gathered while collecting a batch, used to emit parity metrics.struct BatchStats {/// Max Kafka message timestamp (ms) per (topic, partition) — for `latest_processed_timestamp_ms`.@@ -50,7 +54,12 @@ struct CollectedBatch {struct ProcessedBatch {offsets: HashMap<(String, i32), i64>,stats: BatchStats,+ /// Messages accepted so far. Deferred groups (keys whose worker was+ /// draining/dead) are flushed in `complete_oldest_batch`, which adds to this.total_accepted: u32,+ /// Total messages in the batch; the batch commits only once `total_accepted`+ /// reaches it (i.e. all deferred groups have been flushed and ACKed).+ batch_size: u32,elapsed: Duration,}@@ -66,6 +75,10 @@ pub struct IngestionConsumerOptions {pub batch_timeout: Duration,pub max_in_flight_batches: usize,pub group_id: String,+ /// Upper bound on how long `complete_oldest_batch` retries flushing a batch's+ /// deferred groups before failing the batch. Defaults to+ /// [`DEFERRED_FLUSH_TIMEOUT`] in `new`.+ pub deferred_flush_timeout: Duration,}/// The main consumer loop: reads from Kafka, routes messages by distinct_id@@ -79,6 +92,7 @@ pub struct IngestionConsumer {batch_size: usize,batch_timeout: Duration,max_in_flight_batches: usize,+ deferred_flush_timeout: Duration,handle: Handle,group_id: String,}@@ -102,6 +116,7 @@ impl IngestionConsumer {batch_size: options.batch_size,batch_timeout: options.batch_timeout,max_in_flight_batches: options.max_in_flight_batches.max(1),+ deferred_flush_timeout: options.deferred_flush_timeout,handle,group_id: options.group_id,}@@ -144,6 +159,7 @@ impl IngestionConsumer {batch_size: config.consumer_batch_size,batch_timeout: Duration::from_millis(config.consumer_batch_timeout_ms),max_in_flight_batches: config.consumer_max_background_tasks.max(1),+ deferred_flush_timeout: DEFERRED_FLUSH_TIMEOUT,handle,group_id: config.ingestion_consumer_group_id.clone(),})@@ -250,7 +266,22 @@ impl IngestionConsumer {return Ok(());};- let processed = self.await_processed_batch(batch).await?;+ let batch_id = batch.batch_id.clone();+ let mut processed = self.await_processed_batch(batch).await?;++ // Flush this batch's deferred groups (keys whose worker was draining/dead)+ // in order, re-routing them to healthy workers. Doing it here — serialized,+ // oldest batch first — preserves per-distinct_id order across batches. The+ // batch isn't committable until all its messages are accepted.+ self.flush_deferred(&batch_id, &mut processed).await?;++ if processed.total_accepted < processed.batch_size {+ anyhow::bail!(+ "accepted {}/{} messages — not committing offsets",+ processed.total_accepted,+ processed.batch_size+ );+ }// Commit only the oldest completed batch. Later successful batches stay// uncommitted behind any earlier failed batch, preserving at-least-once@@ -287,6 +318,51 @@ impl IngestionConsumer {}}+ /// Flush a completed batch's deferred groups (keys whose worker was+ /// draining/dead), re-routing them to healthy workers and accumulating the+ /// accepted count. Retries with backoff while a flush can't route (no healthy+ /// worker yet), bounded by `DEFERRED_FLUSH_TIMEOUT`. Called serialized,+ /// oldest-first, so a key's deferred messages flush in Kafka order.+ async fn flush_deferred(+ &self,+ batch_id: &str,+ processed: &mut ProcessedBatch,+ ) -> anyhow::Result<()> {+ if !self.dispatcher.has_deferred(batch_id) {+ return Ok(());+ }+ let deadline = Instant::now() + self.deferred_flush_timeout;+ while self.dispatcher.has_deferred(batch_id) {+ // Bound the whole loop, not just the no-healthy-worker branch: a+ // flapping worker (visible in `healthy_workers` but failing sends)+ // re-defers on every scatter and would otherwise spin here forever,+ // pinning this batch's offsets indefinitely.+ if Instant::now() >= deadline {+ anyhow::bail!("deferred messages could not be flushed within timeout");+ }+ let sub_batches = self.dispatcher.flush_deferred(batch_id);+ if sub_batches.is_empty() {+ // Nothing routable right now (no healthy worker) — wait and retry.+ tokio::select! {+ _ = self.handle.shutdown_recv() => {+ anyhow::bail!("shutdown while flushing deferred messages");+ }+ _ = tokio::time::sleep(Duration::from_millis(200)) => {}+ }+ continue;+ }+ processed.total_accepted += Self::scatter(+ &self.dispatcher,+ &self.transport,+ batch_id,+ sub_batches,+ true,+ )+ .await?;+ }+ Ok(())+ }+fn fail_batch_processing(&self, err: anyhow::Error) {error!(error = %err, "Batch processing failed");counter!("ingestion_consumer_batch_errors_total").increment(1);@@ -336,56 +412,94 @@ impl IngestionConsumer {}// Health-aware assignment: groups by routing key, honors stickiness,- // skips unhealthy/dead workers.- let sub_batches = dispatcher.assign(collected.messages);+ // skips unhealthy/dead workers, and defers keys whose worker is+ // draining/dead (held in the dispatcher's stash, flushed at completion).+ let sub_batches = dispatcher.assign(&batch_id, collected.messages);- if sub_batches.is_empty() {+ // Nothing to send and nothing deferred to wait for → no usable workers.+ if sub_batches.is_empty() && !dispatcher.has_deferred(&batch_id) {counter!("ingestion_consumer_no_healthy_workers_total").increment(1);anyhow::bail!("No healthy workers available to route batch");}- // Scatter: send sub-batches to workers in parallel.+ let total_accepted =+ Self::scatter(&dispatcher, &transport, &batch_id, sub_batches, false).await?;++ Ok(ProcessedBatch {+ offsets: collected.offsets,+ stats: collected.stats,+ total_accepted,+ batch_size: batch_size as u32,+ elapsed: start.elapsed(),+ })+ }++ /// Send sub-batches to workers in parallel and resolve each in the+ /// dispatcher. On a send failure (the worker died mid-send), the failed+ /// messages are deferred — before the resolve, so the pin isn't evicted —+ /// to be replayed in order. Returns the number of messages accepted.+ ///+ /// `from_flush` is true when sending sub-batches produced by `flush_deferred`:+ /// the resolve then clears one deferral per key, so a key stays deferring from+ /// when it was first held until its flushed messages actually land (preventing+ /// a newer batch from racing them).+ async fn scatter(+ dispatcher: &Arc<Dispatcher>,+ transport: &Arc<HttpTransport>,+ batch_id: &str,+ sub_batches: Vec<SubBatch>,+ from_flush: bool,+ ) -> anyhow::Result<u32> {let mut handles = Vec::with_capacity(sub_batches.len());for sub_batch in sub_batches {- let transport = Arc::clone(&transport);- let dispatcher = Arc::clone(&dispatcher);+ let transport = Arc::clone(transport);+ let dispatcher = Arc::clone(dispatcher);let worker = sub_batch.worker.clone();- let bid = batch_id.clone();+ let bid = batch_id.to_string();let routing_keys = sub_batch.routing_keys.clone();let message_count = sub_batch.messages.len();handles.push(tokio::spawn(async move {- let result = transport+ match transport.send_batch(&worker, &bid, sub_batch.messages)- .await;- let is_error = result.is_err();-- dispatcher.on_sub_batch_resolved(&worker, message_count, &routing_keys);- dispatcher.record_send_outcome(&worker, is_error);-- result+ .await+ {+ Ok(accepted) => {+ dispatcher.on_sub_batch_resolved(+ &worker,+ message_count,+ &routing_keys,+ from_flush,+ );+ dispatcher.record_send_outcome(&worker, false);+ accepted+ }+ Err(send_err) => {+ // Re-defer the failed messages first, so the ref-count drop+ // in `on_sub_batch_resolved` doesn't evict the pin while the+ // key still has work to replay. On the flush path this pairs+ // with the `clears_deferral` decrement in the resolve, so the+ // outstanding count nets to unchanged (never dipping to zero)+ // and the key keeps deferring across the retry.+ dispatcher.defer_failed(&bid, send_err.messages);+ dispatcher.on_sub_batch_resolved(+ &worker,+ message_count,+ &routing_keys,+ from_flush,+ );+ dispatcher.record_send_outcome(&worker, true);+ 0+ }+ }}));}- // Gather: wait for all workers to ACK.- let mut total_accepted = 0u32;+ let mut accepted = 0u32;for handle in handles {- let result = handle.await??;- total_accepted += result;- }-- if total_accepted < batch_size as u32 {- anyhow::bail!(- "Workers accepted {total_accepted}/{batch_size} messages — not committing offsets"- );+ accepted += handle.await?;}-- Ok(ProcessedBatch {- offsets: collected.offsets,- stats: collected.stats,- total_accepted,- elapsed: start.elapsed(),- })+ Ok(accepted)}/// Collect messages from Kafka up to batch_size or batch_timeout.diff --git a/rust/ingestion-consumer/src/discovery.rs b/rust/ingestion-consumer/src/discovery.rsindex 73f8e36e924b..8d3a7900bac1 100644--- a/rust/ingestion-consumer/src/discovery.rs+++ b/rust/ingestion-consumer/src/discovery.rs@@ -11,7 +11,9 @@//! reconciles the registry directly instead of feeding a Tower balancer.//!//! Routing stays client-side in the dispatcher; discovery only supplies the-//! member list (and prunes per-worker transport state on removal).+//! member list. A departed worker is marked *draining* (it keeps finishing+//! in-flight work) rather than removed outright; the reaper in `main` removes it+//! from the registry and transport once it has drained or timed out.use std::collections::{HashMap, HashSet};use std::net::{IpAddr, SocketAddr};@@ -29,7 +31,6 @@ use tokio::task::JoinHandle;use tokio_util::sync::CancellationToken;use tracing::{info, warn};-use crate::transport::HttpTransport;use crate::worker_registry::{WorkerId, WorkerRegistry};/// Pause before re-listing after the watcher stream closes, so a persistently@@ -69,26 +70,27 @@ pub trait WorkerDiscovery: Send {fn start(self: Box<Self>,registry: Arc<WorkerRegistry>,- transport: Arc<HttpTransport>,cancel: CancellationToken,) -> Option<JoinHandle<()>>;}-/// Reconcile the registry and transport to a desired worker set: add workers-/// that are new, drop workers that are gone (and prune their transport state).-fn reconcile_membership(- registry: &WorkerRegistry,- transport: &HttpTransport,- desired: &HashSet<WorkerId>,-) {+/// Reconcile the registry to a desired worker set: add workers that are new and+/// re-admit any that rejoined, and mark departed workers as draining (they keep+/// finishing in-flight work; the reaper removes them once drained or timed out).+fn reconcile_membership(registry: &WorkerRegistry, desired: &HashSet<WorkerId>) {let current: HashSet<WorkerId> = registry.workers().into_iter().collect();for worker in desired.difference(¤t) {registry.add_worker(worker.clone());}+ // Re-admit any desired worker that was draining (rejoined the pool).+ for worker in desired.intersection(¤t) {+ if registry.is_draining(worker) {+ registry.add_worker(worker.clone());+ }+ }for worker in current.difference(desired) {- registry.remove_worker(worker);- transport.remove_worker(worker);+ registry.start_draining(worker);}gauge!("ingestion_consumer_discovery_workers").set(desired.len() as f64);@@ -145,7 +147,6 @@ impl WorkerDiscovery for StaticDiscovery {fn start(self: Box<Self>,registry: Arc<WorkerRegistry>,- transport: Arc<HttpTransport>,_cancel: CancellationToken,) -> Option<JoinHandle<()>> {let desired: HashSet<WorkerId> = self@@ -153,7 +154,7 @@ impl WorkerDiscovery for StaticDiscovery {.iter().map(|u| WorkerId::from(u.as_str())).collect();- reconcile_membership(®istry, &transport, &desired);+ reconcile_membership(®istry, &desired);None}}@@ -177,12 +178,7 @@ impl EndpointSliceDiscovery {}}- async fn run(- self,- registry: Arc<WorkerRegistry>,- transport: Arc<HttpTransport>,- cancel: CancellationToken,- ) {+ async fn run(self, registry: Arc<WorkerRegistry>, cancel: CancellationToken) {let api: Api<EndpointSlice> = Api::namespaced(self.client.clone(), &self.namespace);let label_selector = format!("kubernetes.io/service-name={}", self.service_name);@@ -216,7 +212,7 @@ impl EndpointSliceDiscovery {match item {Some(Ok(event)) => {if let Some(desired) = Self::apply_event(event, &mut slices, self.port) {- reconcile_membership(®istry, &transport, &desired);+ reconcile_membership(®istry, &desired);}}Some(Err(e)) => {@@ -284,13 +280,12 @@ impl WorkerDiscovery for EndpointSliceDiscovery {fn start(self: Box<Self>,registry: Arc<WorkerRegistry>,- transport: Arc<HttpTransport>,cancel: CancellationToken,) -> Option<JoinHandle<()>> {let this = *self;- Some(tokio::spawn(async move {- this.run(registry, transport, cancel).await- }))+ Some(tokio::spawn(+ async move { this.run(registry, cancel).await },+ ))}}@@ -459,53 +454,73 @@ mod tests {degraded_hold: Duration::from_millis(50),min_state_duration: Duration::ZERO,probe_failure_threshold: 2,+ drain_timeout: Duration::from_secs(5),},)}- fn test_transport() -> HttpTransport {- HttpTransport::new(Duration::from_secs(1), 0, None, &[], 1)+ fn sorted_routable(registry: &WorkerRegistry) -> Vec<String> {+ let mut got: Vec<String> = registry+ .healthy_workers()+ .iter()+ .map(|w| w.to_string())+ .collect();+ got.sort();+ got}#[test]- fn test_reconcile_adds_and_removes_workers() {+ fn test_reconcile_adds_workers_and_drains_departures() {let registry = test_registry();- let transport = test_transport();reconcile_membership(®istry,- &transport,&HashSet::from([worker("10.0.0.1", 9001), worker("10.0.0.2", 9001)]),);- let mut got: Vec<String> = registry.workers().iter().map(|w| w.to_string()).collect();- got.sort();- assert_eq!(got, vec!["http://10.0.0.1:9001", "http://10.0.0.2:9001"]);+ assert_eq!(+ sorted_routable(®istry),+ vec!["http://10.0.0.1:9001", "http://10.0.0.2:9001"]+ );- // Reconcile to a new set: .1 drops, .3 joins, .2 stays.+ // Reconcile to a new set: .1 departs (→ draining, still present but not+ // routable), .3 joins, .2 stays.reconcile_membership(®istry,- &transport,&HashSet::from([worker("10.0.0.2", 9001), worker("10.0.0.3", 9001)]),);- let mut got: Vec<String> = registry.workers().iter().map(|w| w.to_string()).collect();- got.sort();- assert_eq!(got, vec!["http://10.0.0.2:9001", "http://10.0.0.3:9001"]);+ assert_eq!(+ sorted_routable(®istry),+ vec!["http://10.0.0.2:9001", "http://10.0.0.3:9001"],+ "departed worker must no longer be routable"+ );+ assert!(+ registry.is_draining("http://10.0.0.1:9001"),+ "departed worker must be draining, not hard-removed"+ );+ }++ #[test]+ fn test_reconcile_readmits_a_rejoined_draining_worker() {+ let registry = test_registry();+ reconcile_membership(®istry, &HashSet::from([worker("10.0.0.1", 9001)]));+ // .1 departs → draining.+ reconcile_membership(®istry, &HashSet::new());+ assert!(registry.is_draining("http://10.0.0.1:9001"));+ // .1 rejoins → draining cleared, routable again.+ reconcile_membership(®istry, &HashSet::from([worker("10.0.0.1", 9001)]));+ assert!(!registry.is_draining("http://10.0.0.1:9001"));+ assert_eq!(sorted_routable(®istry), vec!["http://10.0.0.1:9001"]);}#[test]fn test_static_discovery_populates_registry() {let registry = Arc::new(test_registry());- let transport = Arc::new(test_transport());let discovery = Box::new(StaticDiscovery::new(vec!["http://w:1".to_string(),"http://w:2".to_string(),]));- let handle = discovery.start(- Arc::clone(®istry),- Arc::clone(&transport),- CancellationToken::new(),- );+ let handle = discovery.start(Arc::clone(®istry), CancellationToken::new());assert!(handle.is_none(), "static discovery spawns no task");assert_eq!(registry.worker_count(), 2);diff --git a/rust/ingestion-consumer/src/dispatcher.rs b/rust/ingestion-consumer/src/dispatcher.rsindex 528a28e9d452..2c92d6ba1de5 100644--- a/rust/ingestion-consumer/src/dispatcher.rs+++ b/rust/ingestion-consumer/src/dispatcher.rs@@ -4,6 +4,7 @@ use std::sync::{Arc, Mutex};use metrics::{counter, gauge, histogram};use crate::routing::{Router, RoutingStrategy, WorkerLoad};+use crate::stash::{DeferredGroup, Stash};use crate::types::SerializedKafkaMessage;use crate::worker_registry::{WorkerId, WorkerRegistry};@@ -19,8 +20,8 @@ pub struct SubBatch {}/// Sticky pin for one routing key. Tracks which worker owns the key and how-/// many in-flight batches currently reference it. The pin is evicted when-/// ref_count reaches 0.+/// many in-flight batches reference it. The pin is evicted when ref_count+/// reaches 0 and the key has no deferred groups outstanding (see [`Stash`]).struct Pin {worker: WorkerId,ref_count: u32,@@ -35,6 +36,9 @@ struct PinTable {/// lightly-loaded workers — load is balanced by message volume rather than/// by sub-batch count. A worker with no outstanding messages has no entry.in_flight: WorkerLoad,+ /// Messages deferred because their key's worker is draining/dead, keyed by+ /// batch, plus per-key outstanding counts. Flushed by `flush_deferred`.+ stash: Stash,}impl PinTable {@@ -42,15 +46,9 @@ impl PinTable {Self {pins: HashMap::new(),in_flight: WorkerLoad::new(),+ stash: Stash::new(),}}-- /// Drop all pins targeting dead workers. Returns the count of evictions.- fn drop_dead_pins(&mut self, registry: &WorkerRegistry) -> usize {- let before = self.pins.len();- self.pins.retain(|_, pin| !registry.is_dead(&pin.worker));- before - self.pins.len()- }}struct MessageGroup {@@ -168,26 +166,18 @@ impl Dispatcher {/// Assign a batch of messages to workers.///- /// Steps:- /// 1. Drop pins for workers that are now dead.- /// 2. Group messages by routing key.- /// 3. Honor existing pins for live workers; collect unassigned groups.- /// 4. Route unassigned groups onto healthy/degraded workers via the- /// configured strategy (bin-packing or P2C).- /// 5. Add routed messages to in-flight load and bump pin ref-counts.- /// 6. Return one `SubBatch` per worker.+ /// Groups messages by routing key, then per group:+ /// - honor an existing pin to a worker still taking work;+ /// - **defer** (stash under `batch_id`) a key pinned to a draining/dead+ /// worker, or one that already has deferred groups pending, so newer+ /// messages can't race ahead of the key's earlier ones;+ /// - otherwise route fresh via the configured strategy.///- /// Returns an empty vec if all workers are dead/unhealthy.- pub fn assign(&self, messages: Vec<SerializedKafkaMessage>) -> Vec<SubBatch> {+ /// Returns one `SubBatch` per worker to send now. Deferred groups stay in+ /// the stash and are flushed later via [`Dispatcher::flush_deferred`].+ pub fn assign(&self, batch_id: &str, messages: Vec<SerializedKafkaMessage>) -> Vec<SubBatch> {let mut table = self.pin_table.lock().unwrap();- // Drop stale pins for dead workers before routing this batch.- let evictions = table.drop_dead_pins(&self.registry);- if evictions > 0 {- counter!("ingestion_consumer_dispatcher_pin_evictions_total", "reason" => "dead_worker")- .increment(evictions as u64);- }-let GroupedMessages {groups: key_groups,missing_header_count,@@ -212,22 +202,36 @@ impl Dispatcher {.collect();let mut unpinned_groups: Vec<MessageGroup> = Vec::new();+ let mut deferred_count = 0u64;for group in key_groups {- match table.pins.get_mut(&group.routing_key) {- Some(pin) if !self.registry.is_dead(&pin.worker) => {- // Existing live pin — honor it.- pin.ref_count += 1;- let worker = pin.worker.clone();+ let pinned_worker = table.pins.get(&group.routing_key).map(|p| p.worker.clone());+ match pinned_worker {+ Some(worker)+ if !table.stash.is_deferring(&group.routing_key)+ && !self.registry.is_dead(&worker)+ && !self.registry.is_draining(&worker) =>+ {+ // Live pin on a worker still taking work, nothing deferred+ // ahead of it — honor it.+ table.pins.get_mut(&group.routing_key).unwrap().ref_count += 1;bump_load(&mut working_load, &worker, group.messages.len());assignments.add_group(worker, group);}- _ => {- // No pin or pinned to a dead worker — drop stale entry and- // queue for routing by the configured strategy.- table.pins.remove(&group.routing_key);- unpinned_groups.push(group);+ Some(_) => {+ // Pinned to a draining/dead worker, or the key already has+ // deferred groups pending — defer so newer messages can't+ // race ahead of the key's earlier in-flight/deferred ones.+ table.stash.defer(+ batch_id,+ DeferredGroup {+ routing_key: group.routing_key,+ messages: group.messages,+ },+ );+ deferred_count += 1;}+ None => unpinned_groups.push(group),}}@@ -275,7 +279,137 @@ impl Dispatcher {.increment(message_count as u64);}+ if deferred_count > 0 {+ counter!(+ "ingestion_consumer_dispatcher_deferred_groups_total",+ "reason" => "drain",+ )+ .increment(deferred_count);+ }gauge!("ingestion_consumer_dispatcher_pins_total").set(table.pins.len() as f64);+ record_stash_gauges(&table.stash);++ assignments.into_sub_batches()+ }++ /// Whether `batch_id` still has deferred groups awaiting flush.+ pub fn has_deferred(&self, batch_id: &str) -> bool {+ self.pin_table.lock().unwrap().stash.has_batch(batch_id)+ }++ /// Whether the worker has any in-flight (sent, unresolved) messages. The+ /// reaper uses this to promptly complete a drain for a worker that was idle+ /// when it left the pool — its in-flight never resolves, so the registry's+ /// `complete_drain` (which fires from `on_sub_batch_resolved`) never would.+ pub fn has_in_flight(&self, worker: &WorkerId) -> bool {+ self.pin_table+ .lock()+ .unwrap()+ .in_flight+ .get(worker)+ .is_some_and(|&n| n > 0)+ }++ /// Total messages currently held in the stash across all batches. Exposed+ /// for observability and for tests to synchronize on deferral.+ pub fn stashed_messages(&self) -> usize {+ self.pin_table.lock().unwrap().stash.message_count()+ }++ /// Defer messages whose send failed (the worker died mid-send) so they can be+ /// replayed in order. Must be called **before** `on_sub_batch_resolved` for+ /// the failed sub-batch, so the ref-count drop doesn't evict the pin while+ /// the key still has work to replay.+ pub fn defer_failed(&self, batch_id: &str, messages: Vec<SerializedKafkaMessage>) {+ let mut table = self.pin_table.lock().unwrap();+ let GroupedMessages { groups, .. } = group_messages_by_routing_key(messages);+ let deferred_count = groups.len() as u64;+ for group in groups {+ table.stash.defer(+ batch_id,+ DeferredGroup {+ routing_key: group.routing_key,+ messages: group.messages,+ },+ );+ }+ if deferred_count > 0 {+ counter!(+ "ingestion_consumer_dispatcher_deferred_groups_total",+ "reason" => "send_failed",+ )+ .increment(deferred_count);+ }+ record_stash_gauges(&table.stash);+ }++ /// Flush a batch's deferred groups: route each to a healthy worker now that+ /// the key's earlier in-flight has resolved, re-pinning it. Returns the+ /// sub-batches to send. Groups that can't route yet (no healthy worker) stay+ /// stashed — call again after a backoff. Cross-key order is preserved because+ /// the consumer flushes batches oldest-first.+ pub fn flush_deferred(&self, batch_id: &str) -> Vec<SubBatch> {+ let mut table = self.pin_table.lock().unwrap();+ let groups = table.stash.take_batch(batch_id);+ if groups.is_empty() {+ return Vec::new();+ }++ let healthy = self.registry.healthy_workers();+ let mut working_load: WorkerLoad = healthy+ .iter()+ .map(|w| (w.clone(), table.in_flight.get(w).copied().unwrap_or(0)))+ .collect();+ let mut assignments = WorkerAssignments::new();++ let mut router = self.router.lock().unwrap();+ for group in groups {+ let Some(worker) = router.select(&healthy, &working_load) else {+ // No healthy worker yet — keep it stashed for a later flush.+ table.stash.put_back(batch_id, group);+ continue;+ };+ bump_load(&mut working_load, &worker, group.messages.len());+ // Re-pin the key to the new worker. The deferral is NOT cleared here:+ // the flushed messages are now in flight but not yet ACKed, so the key+ // must keep deferring until that send resolves (see the `clears_deferral`+ // path in `on_sub_batch_resolved`). Otherwise a newer batch could honor+ // this fresh pin and race the not-yet-landed flushed messages.+ match table.pins.get_mut(&group.routing_key) {+ Some(pin) => {+ pin.worker = worker.clone();+ pin.ref_count += 1;+ }+ None => {+ table.pins.insert(+ group.routing_key.clone(),+ Pin {+ worker: worker.clone(),+ ref_count: 1,+ },+ );+ }+ }+ assignments.add_group(+ worker,+ MessageGroup {+ routing_key: group.routing_key,+ messages: group.messages,+ },+ );+ }+ drop(router);++ for (worker, message_count) in assignments.routed_counts() {+ *table.in_flight.entry(worker.clone()).or_insert(0) += message_count;+ counter!(+ "ingestion_consumer_dispatcher_deferred_flushed_total",+ "worker" => worker.to_string(),+ )+ .increment(message_count as u64);+ }+ gauge!("ingestion_consumer_dispatcher_pins_total").set(table.pins.len() as f64);+ record_stash_gauges(&table.stash);assignments.into_sub_batches()}@@ -284,11 +418,18 @@ impl Dispatcher {/// message count from the worker's outstanding load and decrements the/// ref-count for each key. Evicts zero-count pins so the key is re-assigned/// on its next arrival. `message_count` must match the sub-batch's length.+ ///+ /// `clears_deferral` must be true only when resolving a **flushed** sub-batch+ /// (one produced by `flush_deferred`): it decrements the key's outstanding+ /// deferral count, so the key keeps deferring newer messages from the moment+ /// it was first deferred until its flushed messages have actually landed —+ /// closing the window where a newer batch could race them.pub fn on_sub_batch_resolved(&self,worker: &WorkerId,message_count: usize,routing_keys: &[String],+ clears_deferral: bool,) {let mut table = self.pin_table.lock().unwrap();@@ -301,20 +442,33 @@ impl Dispatcher {};if now_zero {table.in_flight.remove(worker);+ // A draining worker with no in-flight left has finished its work —+ // mark it reapable so it's removed promptly rather than at the timeout.+ if self.registry.is_draining(worker) {+ self.registry.complete_drain(worker);+ }}let mut evictions = 0usize;for key in routing_keys {+ // For a flushed sub-batch, the key's flushed chunk has now landed —+ // clear one outstanding deferral before checking whether it can evict.+ if clears_deferral {+ table.stash.completed(key);+ }+ // Don't evict a pin while the key still has deferred groups awaiting+ // flush — new messages must keep deferring behind them to preserve+ // per-distinct_id order.+ let still_deferring = table.stash.is_deferring(key);if let Some(pin) = table.pins.get_mut(key) {- // Skip stale resolves: after a worker dies, `drop_dead_pins` evicts the- // old pin and `assign` may create a new one for a different worker using- // the same key. A DLQ resolve from the original dead sub-batch would- // otherwise corrupt the new pin's ref_count.+ // Skip stale resolves: a key's pin may have been re-pointed to a+ // different worker (e.g. by a deferred flush). A resolve from the+ // original sub-batch must not touch the new pin's ref_count.if pin.worker != *worker {continue;}pin.ref_count = pin.ref_count.saturating_sub(1);- if pin.ref_count == 0 {+ if pin.ref_count == 0 && !still_deferring {table.pins.remove(key);evictions += 1;}@@ -348,6 +502,14 @@ fn bump_load(working_load: &mut WorkerLoad, worker: &WorkerId, count: usize) {}}+/// Publish point-in-time stash depth so a drain's backlog is observable and can+/// be alerted on if it fails to drain to zero. Call after every mutation.+fn record_stash_gauges(stash: &Stash) {+ gauge!("ingestion_consumer_dispatcher_stashed_batches").set(stash.batch_count() as f64);+ gauge!("ingestion_consumer_dispatcher_stashed_groups").set(stash.len() as f64);+ gauge!("ingestion_consumer_dispatcher_stashed_messages").set(stash.message_count() as f64);+}+struct GroupedMessages {groups: Vec<MessageGroup>,missing_header_count: u64,@@ -427,6 +589,13 @@ mod tests {specs.iter().map(|(t, d)| make_msg(t, d)).collect()}+ fn make_msg_at(token: &str, distinct_id: &str, offset: i64) -> SerializedKafkaMessage {+ SerializedKafkaMessage {+ offset,+ ..make_msg(token, distinct_id)+ }+ }+fn make_msg_with_headers(headers: HashMap<String, String>) -> SerializedKafkaMessage {SerializedKafkaMessage {topic: "test".to_string(),@@ -452,6 +621,7 @@ mod tests {degraded_hold: Duration::from_millis(50),min_state_duration: Duration::ZERO,probe_failure_threshold: 2,+ drain_timeout: Duration::from_secs(5),};Arc::new(WorkerRegistry::new(&urls, config))}@@ -467,6 +637,10 @@ mod tests {.unwrap_or(0)}+ fn pin_count(dispatcher: &Dispatcher) -> usize {+ dispatcher.pin_table.lock().unwrap().pins.len()+ }+// ---- routing key ----#[test]@@ -552,7 +726,7 @@ mod tests {let registry = healthy_registry(1);let dispatcher = Dispatcher::new(registry);- let sub_batches = dispatcher.assign(make_msgs(&[("t", "a"), ("t", "b"), ("t", "c")]));+ let sub_batches = dispatcher.assign("b", make_msgs(&[("t", "a"), ("t", "b"), ("t", "c")]));assert_eq!(sub_batches.len(), 1);assert_eq!(sub_batches[0].worker, wid(0));@@ -563,7 +737,7 @@ mod tests {fn test_empty_batch_returns_no_sub_batches() {let registry = healthy_registry(2);let dispatcher = Dispatcher::new(registry);- assert!(dispatcher.assign(vec![]).is_empty());+ assert!(dispatcher.assign("b", vec![]).is_empty());}#[test]@@ -571,17 +745,18 @@ mod tests {let registry = healthy_registry(3);let dispatcher = Dispatcher::new(registry);- let batch1 = dispatcher.assign(make_msgs(&[("t", "user-1")]));+ let batch1 = dispatcher.assign("b", make_msgs(&[("t", "user-1")]));assert_eq!(batch1.len(), 1);let worker = batch1[0].worker.clone();dispatcher.on_sub_batch_resolved(&worker,batch1[0].messages.len(),&batch1[0].routing_keys,+ false,);// Both user-1 messages merge into one sub-batch.- let batch2 = dispatcher.assign(make_msgs(&[("t", "user-1"), ("t", "user-1")]));+ let batch2 = dispatcher.assign("b", make_msgs(&[("t", "user-1"), ("t", "user-1")]));assert_eq!(batch2.len(), 1);}@@ -593,13 +768,13 @@ mod tests {let dispatcher = Dispatcher::new(registry);// First batch pins "t:user-1" to some worker.- let b1 = dispatcher.assign(make_msgs(&[("t", "user-1")]));+ let b1 = dispatcher.assign("b", make_msgs(&[("t", "user-1")]));let pinned_worker = b1[0].worker.clone();// Do NOT resolve b1 — pin stays alive with ref_count=1.// Second batch: same key must hit the same worker.- let b2 = dispatcher.assign(make_msgs(&[("t", "user-1")]));+ let b2 = dispatcher.assign("b", make_msgs(&[("t", "user-1")]));assert_eq!(b2.len(), 1);assert_eq!(b2[0].worker, pinned_worker);}@@ -610,7 +785,7 @@ mod tests {let dispatcher = Dispatcher::new(registry);// With 2 workers, bin-packing should spread 2 fresh keys across them.- let sub_batches = dispatcher.assign(make_msgs(&[("t", "user-1"), ("t", "user-2")]));+ let sub_batches = dispatcher.assign("b", make_msgs(&[("t", "user-1"), ("t", "user-2")]));let total_msgs: usize = sub_batches.iter().map(|b| b.messages.len()).sum();assert_eq!(total_msgs, 2);@@ -623,7 +798,7 @@ mod tests {let registry = healthy_registry(2);let dispatcher = Dispatcher::new(registry);- let b1 = dispatcher.assign(make_msgs(&[("t", "user-1")]));+ let b1 = dispatcher.assign("b", make_msgs(&[("t", "user-1")]));let worker = b1[0].worker.clone();assert!(dispatcher@@ -633,7 +808,7 @@ mod tests {.pins.contains_key("t:user-1"));- dispatcher.on_sub_batch_resolved(&worker, b1[0].messages.len(), &b1[0].routing_keys);+ dispatcher.on_sub_batch_resolved(&worker, b1[0].messages.len(), &b1[0].routing_keys, false);assert!(!dispatcher.pin_table@@ -648,18 +823,18 @@ mod tests {let registry = healthy_registry(2);let dispatcher = Dispatcher::new(registry);- let b1 = dispatcher.assign(make_msgs(&[("t", "user-1")]));+ let b1 = dispatcher.assign("b", make_msgs(&[("t", "user-1")]));let worker = b1[0].worker.clone();// Second batch, same key, pin not yet resolved: ref_count should be 2.- dispatcher.assign(make_msgs(&[("t", "user-1")]));+ dispatcher.assign("b", make_msgs(&[("t", "user-1")]));assert_eq!(dispatcher.pin_table.lock().unwrap().pins["t:user-1"].ref_count,2);// Resolve first sub-batch: ref_count drops to 1, pin stays.- dispatcher.on_sub_batch_resolved(&worker, b1[0].messages.len(), &b1[0].routing_keys);+ dispatcher.on_sub_batch_resolved(&worker, b1[0].messages.len(), &b1[0].routing_keys, false);{let table = dispatcher.pin_table.lock().unwrap();assert!(table.pins.contains_key("t:user-1"));@@ -675,7 +850,7 @@ mod tests {let dispatcher = Dispatcher::new(registry);// Two messages for one key → one sub-batch carrying two messages.- let b1 = dispatcher.assign(make_msgs(&[("t", "user-1"), ("t", "user-1")]));+ let b1 = dispatcher.assign("b", make_msgs(&[("t", "user-1"), ("t", "user-1")]));let worker = b1[0].worker.clone();assert_eq!(in_flight_of(&dispatcher, &worker), 2);@@ -686,10 +861,10 @@ mod tests {let registry = healthy_registry(2);let dispatcher = Dispatcher::new(registry);- let b1 = dispatcher.assign(make_msgs(&[("t", "user-1"), ("t", "user-1")]));+ let b1 = dispatcher.assign("b", make_msgs(&[("t", "user-1"), ("t", "user-1")]));let worker = b1[0].worker.clone();- dispatcher.on_sub_batch_resolved(&worker, b1[0].messages.len(), &b1[0].routing_keys);+ dispatcher.on_sub_batch_resolved(&worker, b1[0].messages.len(), &b1[0].routing_keys, false);assert_eq!(in_flight_of(&dispatcher, &worker), 0);}@@ -702,7 +877,7 @@ mod tests {let registry = healthy_registry(1);let dispatcher = Dispatcher::new(registry);- dispatcher.assign(make_msgs(&[("t", "a"), ("t", "b"), ("t", "c")]));+ dispatcher.assign("b", make_msgs(&[("t", "a"), ("t", "b"), ("t", "c")]));assert_eq!(in_flight_of(&dispatcher, &wid(0)), 3);}@@ -723,7 +898,7 @@ mod tests {.insert(wid(0), 3);// A fresh key should go to worker 1 (load = 0).- let b = dispatcher.assign(make_msgs(&[("t", "fresh")]));+ let b = dispatcher.assign("b", make_msgs(&[("t", "fresh")]));assert_eq!(b.len(), 1);assert_eq!(b[0].worker, wid(1));}@@ -742,7 +917,7 @@ mod tests {specs.push(("t", d));}- let sub_batches = dispatcher.assign(make_msgs(&specs));+ let sub_batches = dispatcher.assign("b", make_msgs(&specs));assert_eq!(sub_batches.len(), 2, "both workers must carry messages");let load0 = in_flight_of(&dispatcher, &wid(0));@@ -769,7 +944,7 @@ mod tests {let dispatcher = Dispatcher::new(Arc::clone(®istry));// Pin "user-1" to whichever worker gets it first.- let b1 = dispatcher.assign(make_msgs(&[("t", "user-1")]));+ let b1 = dispatcher.assign("b", make_msgs(&[("t", "user-1")]));let original_worker = b1[0].worker.clone();let other_worker = if original_worker == wid(0) {wid(1)@@ -784,8 +959,17 @@ mod tests {tokio::time::sleep(Duration::from_millis(40)).await;assert!(registry.is_dead(&original_worker));- // Next batch: pin must be dropped and key rerouted to the live worker.- let b2 = dispatcher.assign(make_msgs(&[("t", "user-1")]));+ // Resolve b1 so the dead worker has no in-flight (the max_in_flight=1+ // ordering: the previous batch completes before the next assigns). The+ // zero-ref pin is evicted, so the key re-routes to the live worker.+ dispatcher.on_sub_batch_resolved(+ &original_worker,+ b1[0].messages.len(),+ &b1[0].routing_keys,+ false,+ );++ let b2 = dispatcher.assign("b", make_msgs(&[("t", "user-1")]));assert_eq!(b2.len(), 1);assert_eq!(b2[0].worker, other_worker);}@@ -803,7 +987,7 @@ mod tests {}// Both workers are Unhealthy — the dispatcher should not route to them.- let b = dispatcher.assign(make_msgs(&[("t", "user-1")]));+ let b = dispatcher.assign("b", make_msgs(&[("t", "user-1")]));assert!(b.is_empty());}@@ -817,7 +1001,7 @@ mod tests {fn test_p2c_single_worker_all_messages_go_there() {let dispatcher = p2c_dispatcher(1, 1);- let sub_batches = dispatcher.assign(make_msgs(&[("t", "a"), ("t", "b"), ("t", "c")]));+ let sub_batches = dispatcher.assign("b", make_msgs(&[("t", "a"), ("t", "b"), ("t", "c")]));assert_eq!(sub_batches.len(), 1);assert_eq!(sub_batches[0].worker, wid(0));@@ -829,11 +1013,11 @@ mod tests {let dispatcher = p2c_dispatcher(3, 7);// First batch pins "t:user-1"; do NOT resolve so the pin stays alive.- let b1 = dispatcher.assign(make_msgs(&[("t", "user-1")]));+ let b1 = dispatcher.assign("b", make_msgs(&[("t", "user-1")]));let pinned_worker = b1[0].worker.clone();// Second batch with the same key must hit the same worker, bypassing P2C.- let b2 = dispatcher.assign(make_msgs(&[("t", "user-1")]));+ let b2 = dispatcher.assign("b", make_msgs(&[("t", "user-1")]));assert_eq!(b2.len(), 1);assert_eq!(b2[0].worker, pinned_worker);}@@ -844,7 +1028,7 @@ mod tests {// key steers the second to the other worker — one message each.let dispatcher = p2c_dispatcher(2, 3);- let sub_batches = dispatcher.assign(make_msgs(&[("t", "user-1"), ("t", "user-2")]));+ let sub_batches = dispatcher.assign("b", make_msgs(&[("t", "user-1"), ("t", "user-2")]));assert_eq!(sub_batches.len(), 2, "both workers must carry a message");let total: usize = sub_batches.iter().map(|b| b.messages.len()).sum();@@ -863,7 +1047,7 @@ mod tests {.in_flight.insert(wid(0), 5);- let b = dispatcher.assign(make_msgs(&[("t", "fresh")]));+ let b = dispatcher.assign("b", make_msgs(&[("t", "fresh")]));assert_eq!(b.len(), 1);assert_eq!(b[0].worker, wid(1));}@@ -880,7 +1064,337 @@ mod tests {}}- let b = dispatcher.assign(make_msgs(&[("t", "user-1")]));+ let b = dispatcher.assign("b", make_msgs(&[("t", "user-1")]));assert!(b.is_empty());}++ // ---- graceful drain ----++ #[test]+ fn test_draining_worker_gets_no_new_keys() {+ let registry = healthy_registry(2);+ let dispatcher = Dispatcher::new(Arc::clone(®istry));+ registry.start_draining(&worker_url(0));++ let msgs: Vec<_> = (0..10).map(|i| make_msg("t", &format!("u{i}"))).collect();+ let sub_batches = dispatcher.assign("b", msgs);++ assert!(+ sub_batches.iter().all(|b| b.worker != wid(0)),+ "no new keys may route to a draining worker"+ );+ }++ #[test]+ fn test_pinned_key_defers_off_draining_worker() {+ let registry = healthy_registry(2);+ let dispatcher = Dispatcher::new(Arc::clone(®istry));++ // Pin "user-1"; do NOT resolve, so the pin stays live on its worker.+ let b1 = dispatcher.assign("batch-1", make_msgs(&[("t", "user-1")]));+ let pinned = b1[0].worker.clone();++ registry.start_draining(&pinned);++ // The live pin points at a draining worker — new messages for the key are+ // deferred (held), not sent and not rerouted, so they can't pass the+ // earlier in-flight message still being processed on that worker.+ let b2 = dispatcher.assign("batch-2", make_msgs(&[("t", "user-1")]));+ assert!(+ b2.is_empty(),+ "messages for a draining-pinned key must be deferred, not routed"+ );+ assert!(dispatcher.has_deferred("batch-2"));+ }++ #[tokio::test]+ async fn test_pinned_key_defers_off_dead_worker() {+ let registry = healthy_registry(2);+ let dispatcher = Dispatcher::new(Arc::clone(®istry));++ let b1 = dispatcher.assign("batch-1", make_msgs(&[("t", "user-1")]));+ let pinned = b1[0].worker.clone();++ // Kill the pinned worker via passive signal, leaving b1 in-flight.+ for _ in 0..5 {+ registry.record_outcome(&pinned, true);+ }+ tokio::time::sleep(Duration::from_millis(40)).await;+ assert!(registry.is_dead(&pinned));++ let b2 = dispatcher.assign("batch-2", make_msgs(&[("t", "user-1")]));+ assert!(+ b2.is_empty(),+ "messages for a dead-pinned key with in-flight must be deferred"+ );+ assert!(dispatcher.has_deferred("batch-2"));+ }++ #[test]+ fn test_flush_deferred_routes_to_healthy_worker_and_repins() {+ let registry = healthy_registry(2);+ let dispatcher = Dispatcher::new(Arc::clone(®istry));++ // Pin user-1, then drain its worker so the next batch defers.+ let b1 = dispatcher.assign("batch-1", make_msgs(&[("t", "user-1")]));+ let pinned = b1[0].worker.clone();+ registry.start_draining(&pinned);+ let b2 = dispatcher.assign("batch-2", make_msgs(&[("t", "user-1")]));+ assert!(b2.is_empty());++ // Resolve batch-1's in-flight so the worker finishes draining.+ dispatcher.on_sub_batch_resolved(&pinned, b1[0].messages.len(), &b1[0].routing_keys, false);++ // Flushing batch-2 re-routes the deferred group onto the surviving worker.+ let flushed = dispatcher.flush_deferred("batch-2");+ assert_eq!(flushed.len(), 1);+ assert_ne!(+ flushed[0].worker, pinned,+ "deferred group routes off drainer"+ );+ assert_eq!(flushed[0].routing_keys, vec!["t:user-1".to_string()]);+ assert!(+ !dispatcher.has_deferred("batch-2"),+ "nothing left after flush"+ );+ }++ #[test]+ fn test_defer_keeps_pin_alive_until_flushed() {+ let registry = healthy_registry(2);+ let dispatcher = Dispatcher::new(Arc::clone(®istry));++ let b1 = dispatcher.assign("batch-1", make_msgs(&[("t", "user-1")]));+ let pinned = b1[0].worker.clone();+ registry.start_draining(&pinned);+ dispatcher.assign("batch-2", make_msgs(&[("t", "user-1")]));++ // Resolving batch-1 drops ref_count to 0, but the deferred batch-2 group+ // must keep the pin from being evicted (so order is preserved on flush).+ dispatcher.on_sub_batch_resolved(&pinned, b1[0].messages.len(), &b1[0].routing_keys, false);+ assert_eq!(+ pin_count(&dispatcher),+ 1,+ "pin retained while deferred pending"+ );++ // After flushing, the pin is repointed and stays (now ref-counted by the+ // flushed sub-batch), but nothing is deferred anymore.+ dispatcher.flush_deferred("batch-2");+ assert!(!dispatcher.has_deferred("batch-2"));+ }++ #[test]+ fn test_defer_failed_holds_messages_for_replay() {+ let registry = healthy_registry(2);+ let dispatcher = Dispatcher::new(Arc::clone(®istry));++ let b1 = dispatcher.assign("batch-1", make_msgs(&[("t", "user-1")]));+ let worker = b1[0].worker.clone();++ // Simulate a send failure: defer the failed messages, then resolve.+ dispatcher.defer_failed("batch-1", make_msgs(&[("t", "user-1")]));+ dispatcher.on_sub_batch_resolved(&worker, b1[0].messages.len(), &b1[0].routing_keys, false);++ assert!(+ dispatcher.has_deferred("batch-1"),+ "failed messages held for replay"+ );+ assert_eq!(+ pin_count(&dispatcher),+ 1,+ "pin kept for the deferred replay"+ );++ let flushed = dispatcher.flush_deferred("batch-1");+ assert_eq!(flushed.len(), 1);+ assert!(!dispatcher.has_deferred("batch-1"));+ }++ #[test]+ fn test_rejoin_during_drain_keeps_deferring_until_flushed() {+ let registry = healthy_registry(2);+ let dispatcher = Dispatcher::new(Arc::clone(®istry));++ // Pin user-1, keep it in-flight, then drain its worker.+ let b1 = dispatcher.assign("batch-1", make_msgs(&[("t", "user-1")]));+ let pinned = b1[0].worker.clone();+ registry.start_draining(&pinned);++ // batch-2 defers behind the draining pin.+ let b2 = dispatcher.assign("batch-2", make_msgs(&[("t", "user-1")]));+ assert!(b2.is_empty());+ assert!(dispatcher.has_deferred("batch-2"));++ // The worker rejoins (EndpointSlice re-adds it) — draining is cleared.+ registry.add_worker(pinned.clone());+ assert!(!registry.is_draining(&pinned));++ // Even so, new messages must keep deferring: the key still has deferred+ // groups outstanding, so honoring the (now-healthy-again) pin would let+ // newer messages jump ahead of the older deferred ones.+ let b3 = dispatcher.assign("batch-3", make_msgs(&[("t", "user-1")]));+ assert!(+ b3.is_empty(),+ "must keep deferring while earlier deferred work is unflushed"+ );+ assert!(dispatcher.has_deferred("batch-3"));++ // Resolve batch-1's in-flight, then flush the deferred batches in order+ // and resolve the flushed sub-batches (which clears the deferral).+ dispatcher.on_sub_batch_resolved(&pinned, b1[0].messages.len(), &b1[0].routing_keys, false);+ for batch in ["batch-2", "batch-3"] {+ let flushed = dispatcher.flush_deferred(batch);+ assert_eq!(flushed.len(), 1);+ dispatcher.on_sub_batch_resolved(+ &flushed[0].worker,+ flushed[0].messages.len(),+ &flushed[0].routing_keys,+ true,+ );+ }+ assert!(!dispatcher.has_deferred("batch-2") && !dispatcher.has_deferred("batch-3"));++ // With the stash drained, a fresh batch honors the pin again.+ let b4 = dispatcher.assign("batch-4", make_msgs(&[("t", "user-1")]));+ assert_eq!(b4.len(), 1, "honors the pin once nothing is deferred");+ }++ #[test]+ fn test_flushed_key_keeps_deferring_until_acked() {+ // The ordering-critical case: after a key is flushed to a survivor, its+ // messages are in flight but not yet ACKed. A newer batch for the same key+ // must keep deferring until that flush lands — otherwise it could be+ // routed onto the fresh pin and race the not-yet-acked flushed messages.+ let registry = healthy_registry(2);+ let dispatcher = Dispatcher::new(Arc::clone(®istry));++ let b1 = dispatcher.assign("batch-1", make_msgs(&[("t", "user-1")]));+ let pinned = b1[0].worker.clone();+ registry.start_draining(&pinned);++ // batch-2 defers; batch-1 resolves; flush batch-2 to the survivor.+ assert!(dispatcher+ .assign("batch-2", make_msgs(&[("t", "user-1")]))+ .is_empty());+ dispatcher.on_sub_batch_resolved(&pinned, b1[0].messages.len(), &b1[0].routing_keys, false);+ let flushed = dispatcher.flush_deferred("batch-2");+ assert_eq!(flushed.len(), 1);++ // Flushed but NOT yet resolved → a newer batch must still defer.+ let b3 = dispatcher.assign("batch-3", make_msgs(&[("t", "user-1")]));+ assert!(+ b3.is_empty(),+ "newer messages must not race the in-flight flushed messages"+ );++ // Once the flush ACKs (clears_deferral), the key is free to be honored.+ dispatcher.on_sub_batch_resolved(+ &flushed[0].worker,+ flushed[0].messages.len(),+ &flushed[0].routing_keys,+ true,+ );+ // batch-3's deferred group is the only thing left; flush it to confirm the+ // key drains fully and a fresh assign then honors the pin.+ let f3 = dispatcher.flush_deferred("batch-3");+ assert_eq!(f3.len(), 1);+ dispatcher.on_sub_batch_resolved(+ &f3[0].worker,+ f3[0].messages.len(),+ &f3[0].routing_keys,+ true,+ );+ let b4 = dispatcher.assign("batch-4", make_msgs(&[("t", "user-1")]));+ assert_eq!(+ b4.len(),+ 1,+ "honors the pin once all flushed work has landed"+ );+ }++ #[test]+ fn test_cross_batch_deferred_flush_preserves_order() {+ let registry = healthy_registry(2);+ let dispatcher = Dispatcher::new(Arc::clone(®istry));++ // batch-1 pins user-1 (offset 0); keep it in-flight, then drain its worker.+ let b1 = dispatcher.assign("batch-1", vec![make_msg_at("t", "user-1", 0)]);+ let pinned = b1[0].worker.clone();+ registry.start_draining(&pinned);++ // The next two batches each carry user-1's next message — both defer,+ // each held under its own batch, behind the draining pin.+ let b2 = dispatcher.assign("batch-2", vec![make_msg_at("t", "user-1", 1)]);+ let b3 = dispatcher.assign("batch-3", vec![make_msg_at("t", "user-1", 2)]);+ assert!(+ b2.is_empty() && b3.is_empty(),+ "both must defer behind the drainer"+ );++ // Drain finishes when batch-1's in-flight resolves.+ dispatcher.on_sub_batch_resolved(&pinned, b1[0].messages.len(), &b1[0].routing_keys, false);++ // Flush oldest-first (as complete_oldest_batch does): each batch yields+ // only its own message, in Kafka offset order.+ let f2 = dispatcher.flush_deferred("batch-2");+ let f3 = dispatcher.flush_deferred("batch-3");+ assert_eq!(offsets(&f2), vec![1], "batch-2 flushes its own message");+ assert_eq!(offsets(&f3), vec![2], "batch-3 flushes its own message");+ assert!(!dispatcher.has_deferred("batch-2") && !dispatcher.has_deferred("batch-3"));+ }++ fn offsets(sub_batches: &[SubBatch]) -> Vec<i64> {+ sub_batches+ .iter()+ .flat_map(|b| b.messages.iter().map(|m| m.offset))+ .collect()+ }++ #[test]+ fn test_resolve_completes_drain_when_in_flight_hits_zero() {+ let registry = healthy_registry(1);+ let dispatcher = Dispatcher::new(Arc::clone(®istry));++ // Send a batch to worker 0, then mark it draining while in-flight.+ let b = dispatcher.assign("b", make_msgs(&[("t", "a")]));+ let worker = b[0].worker.clone();+ registry.start_draining(&worker);+ assert!(+ registry.reapable_workers().is_empty(),+ "not reapable while in-flight remains"+ );++ // Resolving the last in-flight sub-batch should mark it reapable.+ dispatcher.on_sub_batch_resolved(&worker, b[0].messages.len(), &b[0].routing_keys, false);+ assert_eq!(registry.reapable_workers(), vec![worker]);+ }++ #[test]+ fn test_idle_drained_worker_reaped_via_reaper_path() {+ // A worker drained while idle has no in-flight to resolve, so+ // `on_sub_batch_resolved`/`complete_drain` never fire for it. The reaper+ // instead completes the drain when `has_in_flight` is false. This checks+ // the accessors that path relies on.+ let registry = healthy_registry(2);+ let dispatcher = Dispatcher::new(Arc::clone(®istry));++ let idle = wid(0);+ registry.start_draining(&idle);++ // Reaper's condition holds: the worker is draining and has no in-flight.+ assert!(registry.draining_workers().contains(&idle));+ assert!(+ !dispatcher.has_in_flight(&idle),+ "idle worker has no in-flight"+ );+ assert!(+ registry.reapable_workers().is_empty(),+ "not reapable yet — its deadline is the full drain timeout"+ );++ // The reaper completes the drain → immediately reapable, no timeout wait.+ registry.complete_drain(&idle);+ assert_eq!(registry.reapable_workers(), vec![idle]);+ }}diff --git a/rust/ingestion-consumer/src/lib.rs b/rust/ingestion-consumer/src/lib.rsindex d4f3924500ba..962f059960d8 100644--- a/rust/ingestion-consumer/src/lib.rs+++ b/rust/ingestion-consumer/src/lib.rs@@ -4,6 +4,7 @@ pub mod discovery;pub mod dispatcher;pub mod kafka_config;pub mod routing;+pub mod stash;pub mod transport;pub mod types;pub mod worker_registry;diff --git a/rust/ingestion-consumer/src/main.rs b/rust/ingestion-consumer/src/main.rsindex 42b6abf465f6..b91062d9bf41 100644--- a/rust/ingestion-consumer/src/main.rs+++ b/rust/ingestion-consumer/src/main.rs@@ -177,11 +177,37 @@ async fn async_main(config: Config) -> Result<()> {))}};- let _discovery_handle = discovery.start(- Arc::clone(®istry),- Arc::clone(&transport),- discovery_token.clone(),- );+ let _discovery_handle = discovery.start(Arc::clone(®istry), discovery_token.clone());++ // Reap drained workers: once a departed worker has finished its in-flight+ // batches (or hit the drain timeout), remove it from the registry and prune+ // its transport semaphore. No-op in static mode (workers never drain).+ {+ let registry = Arc::clone(®istry);+ let transport = Arc::clone(&transport);+ let dispatcher = Arc::clone(&dispatcher);+ let token = probe_token.clone();+ tokio::spawn(async move {+ loop {+ tokio::select! {+ _ = token.cancelled() => break,+ _ = tokio::time::sleep(Duration::from_secs(1)) => {}+ }+ // A worker that left the pool while idle has no in-flight to+ // resolve, so `on_sub_batch_resolved` never completes its drain.+ // Complete it here so it's reaped now rather than at the timeout.+ for worker in registry.draining_workers() {+ if !dispatcher.has_in_flight(&worker) {+ registry.complete_drain(&worker);+ }+ }+ for worker in registry.reapable_workers() {+ registry.remove_worker(&worker);+ transport.remove_worker(&worker);+ }+ }+ });+ }// For dynamic discovery, wait for the first workers before consuming so the// first batch has somewhere to route.diff --git a/rust/ingestion-consumer/src/stash.rs b/rust/ingestion-consumer/src/stash.rsnew file mode 100644index 000000000000..6a4d43c1fdce--- /dev/null+++ b/rust/ingestion-consumer/src/stash.rs@@ -0,0 +1,243 @@+//! Deferred-message stash for graceful drain / worker loss.+//!+//! When a routing key is pinned to a worker that is draining or dead, new+//! messages for that key can't be sent there (it must finish and exit) and+//! can't be re-routed elsewhere yet (the key's earlier messages are still in+//! flight on that worker — re-routing now would reorder the distinct_id). So+//! they are *stashed* here until the worker's in-flight resolves, then flushed+//! (re-routed) in order.+//!+//! The stash keeps two things:+//! - the deferred groups themselves, keyed by the batch that produced them, so+//! the consumer can flush a batch's deferred work as part of completing that+//! batch (preserving per-batch offset ownership and oldest-first order);+//! - a per-routing-key **outstanding count**, which the dispatcher consults to+//! (a) keep deferring new messages for a key that already has deferred work,+//! so they can't race ahead, and (b) avoid evicting a pin while its key still+//! has deferred work pending.+//!+//! A group contributes 1 to its key's outstanding count from [`Stash::defer`]+//! until [`Stash::completed`] (i.e. until it has actually been routed). Pulling+//! groups out to attempt a flush ([`Stash::take_batch`]) and putting back the+//! ones that couldn't route ([`Stash::put_back`]) do not change the count.++use std::collections::HashMap;++use crate::types::SerializedKafkaMessage;++/// Messages for one routing key, deferred because the key's pinned worker is+/// draining or dead.+pub struct DeferredGroup {+ pub routing_key: String,+ pub messages: Vec<SerializedKafkaMessage>,+}++impl DeferredGroup {+ pub fn message_count(&self) -> usize {+ self.messages.len()+ }+}++#[derive(Default)]+pub struct Stash {+ /// Deferred groups awaiting flush, keyed by the batch id that produced them.+ by_batch: HashMap<String, Vec<DeferredGroup>>,+ /// Per routing key: how many deferred groups are outstanding (not yet routed).+ outstanding: HashMap<String, u32>,+}++impl Stash {+ pub fn new() -> Self {+ Self::default()+ }++ /// Defer a group produced by `batch_id`, bumping its key's outstanding count.+ pub fn defer(&mut self, batch_id: &str, group: DeferredGroup) {+ *self+ .outstanding+ .entry(group.routing_key.clone())+ .or_insert(0) += 1;+ self.by_batch+ .entry(batch_id.to_string())+ .or_default()+ .push(group);+ }++ /// Whether the key currently has any outstanding deferred groups. New+ /// messages for such a key must keep deferring, and its pin must not be+ /// evicted.+ pub fn is_deferring(&self, routing_key: &str) -> bool {+ self.outstanding.get(routing_key).is_some_and(|&n| n > 0)+ }++ /// Whether `batch_id` has any deferred groups still awaiting flush.+ pub fn has_batch(&self, batch_id: &str) -> bool {+ self.by_batch.contains_key(batch_id)+ }++ /// Remove and return a batch's deferred groups so the caller can try to+ /// route them. Routed groups must be acknowledged with [`Stash::completed`];+ /// groups that couldn't route are returned via [`Stash::put_back`]. Neither+ /// this call nor `put_back` changes outstanding counts — only `completed` does.+ pub fn take_batch(&mut self, batch_id: &str) -> Vec<DeferredGroup> {+ self.by_batch.remove(batch_id).unwrap_or_default()+ }++ /// Re-stash a taken group that couldn't be routed yet (no healthy worker).+ pub fn put_back(&mut self, batch_id: &str, group: DeferredGroup) {+ self.by_batch+ .entry(batch_id.to_string())+ .or_default()+ .push(group);+ }++ /// Mark one deferred group for `routing_key` as routed — decrements the+ /// key's outstanding count.+ pub fn completed(&mut self, routing_key: &str) {+ if let Some(n) = self.outstanding.get_mut(routing_key) {+ *n -= 1;+ if *n == 0 {+ self.outstanding.remove(routing_key);+ }+ }+ }++ /// Total deferred groups currently stashed (for metrics/tests).+ pub fn len(&self) -> usize {+ self.by_batch.values().map(Vec::len).sum()+ }++ pub fn is_empty(&self) -> bool {+ self.by_batch.is_empty()+ }++ /// Number of batches that currently have deferred groups awaiting flush.+ pub fn batch_count(&self) -> usize {+ self.by_batch.len()+ }++ /// Total deferred messages currently stashed across all batches and groups.+ pub fn message_count(&self) -> usize {+ self.by_batch+ .values()+ .flat_map(|groups| groups.iter())+ .map(DeferredGroup::message_count)+ .sum()+ }+}++#[cfg(test)]+mod tests {+ use std::collections::HashMap;++ use super::*;+ use crate::types::SerializedKafkaMessage;++ fn msg(distinct_id: &str) -> SerializedKafkaMessage {+ let mut headers = HashMap::new();+ headers.insert("token".to_string(), "t".to_string());+ headers.insert("distinct_id".to_string(), distinct_id.to_string());+ SerializedKafkaMessage {+ topic: "test".to_string(),+ partition: 0,+ offset: 0,+ timestamp: 0,+ key: None,+ value: None,+ headers,+ }+ }++ fn group(key: &str, n: usize) -> DeferredGroup {+ DeferredGroup {+ routing_key: key.to_string(),+ messages: (0..n).map(|_| msg(key)).collect(),+ }+ }++ #[test]+ fn test_defer_marks_key_deferring() {+ let mut stash = Stash::new();+ assert!(!stash.is_deferring("t:a"));++ stash.defer("batch-1", group("t:a", 2));+ assert!(stash.is_deferring("t:a"));+ assert!(stash.has_batch("batch-1"));+ assert_eq!(stash.len(), 1);+ }++ #[test]+ fn test_completed_clears_deferring_only_when_count_hits_zero() {+ let mut stash = Stash::new();+ // Same key deferred by two batches → outstanding count 2.+ stash.defer("batch-1", group("t:a", 1));+ stash.defer("batch-2", group("t:a", 1));+ assert!(stash.is_deferring("t:a"));++ stash.completed("t:a");+ assert!(+ stash.is_deferring("t:a"),+ "still deferring with one outstanding"+ );++ stash.completed("t:a");+ assert!(+ !stash.is_deferring("t:a"),+ "no longer deferring once all routed"+ );+ }++ #[test]+ fn test_take_batch_removes_groups_without_changing_outstanding() {+ let mut stash = Stash::new();+ stash.defer("batch-1", group("t:a", 1));++ let taken = stash.take_batch("batch-1");+ assert_eq!(taken.len(), 1);+ assert!(!stash.has_batch("batch-1"), "batch's groups are removed");+ assert!(+ stash.is_deferring("t:a"),+ "taking to attempt a flush must not clear the outstanding count"+ );+ }++ #[test]+ fn test_put_back_re_stashes_without_double_counting() {+ let mut stash = Stash::new();+ stash.defer("batch-1", group("t:a", 1));+ let mut taken = stash.take_batch("batch-1");++ // Couldn't route — put it back.+ stash.put_back("batch-1", taken.pop().unwrap());+ assert!(stash.has_batch("batch-1"));+ assert!(stash.is_deferring("t:a"));++ // Now it routes: take + completed → count clears.+ let mut taken = stash.take_batch("batch-1");+ stash.completed(&taken.pop().unwrap().routing_key);+ assert!(!stash.is_deferring("t:a"));+ }++ #[test]+ fn test_take_unknown_batch_is_empty() {+ let mut stash = Stash::new();+ assert!(stash.take_batch("nope").is_empty());+ }++ #[test]+ fn test_depth_counts_batches_groups_and_messages() {+ let mut stash = Stash::new();+ stash.defer("batch-1", group("t:a", 2));+ stash.defer("batch-1", group("t:b", 1));+ stash.defer("batch-2", group("t:a", 3));++ assert_eq!(stash.batch_count(), 2);+ assert_eq!(stash.len(), 3, "three groups across two batches");+ assert_eq!(stash.message_count(), 6, "2 + 1 + 3 messages");++ // Taking a batch out to attempt a flush drops it from the depth counts.+ let _ = stash.take_batch("batch-1");+ assert_eq!(stash.batch_count(), 1);+ assert_eq!(stash.message_count(), 3);+ }+}diff --git a/rust/ingestion-consumer/src/transport.rs b/rust/ingestion-consumer/src/transport.rsindex 0302b0889c84..cf28fb74affe 100644--- a/rust/ingestion-consumer/src/transport.rs+++ b/rust/ingestion-consumer/src/transport.rs@@ -170,7 +170,7 @@ impl HttpTransport {worker_url: &str,batch_id: &str,messages: Vec<SerializedKafkaMessage>,- ) -> Result<u32, TransportError> {+ ) -> Result<u32, SendError> {let message_count = messages.len();let request = IngestBatchRequest {batch_id: batch_id.to_string(),@@ -261,7 +261,10 @@ impl HttpTransport {"Failed to send batch to worker");if !err.is_retriable() {- return Err(err);+ return Err(SendError {+ error: err,+ messages: request.messages,+ });}last_err = Some(err);}@@ -278,7 +281,10 @@ impl HttpTransport {);counter!("ingestion_consumer_transport_exhausted_total", "worker" => worker_url.to_string()).increment(1);- Err(err)+ Err(SendError {+ error: err,+ messages: request.messages,+ })}async fn do_send(@@ -311,6 +317,15 @@ impl HttpTransport {}}+/// Failure from [`HttpTransport::send_batch`], carrying back the batch's+/// messages so the caller can defer/replay them (the worker may have died+/// mid-send and the messages were never accepted).+#[derive(Debug)]+pub struct SendError {+ pub error: TransportError,+ pub messages: Vec<SerializedKafkaMessage>,+}+#[derive(Debug, thiserror::Error)]pub enum TransportError {#[error("HTTP request failed: {0}")]diff --git a/rust/ingestion-consumer/src/worker_registry.rs b/rust/ingestion-consumer/src/worker_registry.rsindex a0709f2974f6..406fd6daea4a 100644--- a/rust/ingestion-consumer/src/worker_registry.rs+++ b/rust/ingestion-consumer/src/worker_registry.rs@@ -78,6 +78,12 @@ struct WorkerHealth {/// Rolling window of passive send outcomes: (timestamp, is_error)./// Always appended in chronological order so the head is always the oldest entry.passive_window: VecDeque<(Instant, bool)>,+ /// The worker is draining: it left the pool (e.g. a deploy) but may still be+ /// finishing in-flight batches. It receives no new work and its `/_ready`+ /// probe failures are ignored (readiness is expected to be down), but send+ /// failures still escalate it (a crash mid-drain). It is reaped once+ /// `drain_deadline` passes — set to "now" when its in-flight reaches zero.+ drain_deadline: Option<Instant>,}impl WorkerHealth {@@ -88,9 +94,14 @@ impl WorkerHealth {unhealthy_since: None,consecutive_probe_failures: 0,passive_window: VecDeque::new(),+ drain_deadline: None,}}+ fn is_draining(&self) -> bool {+ self.drain_deadline.is_some()+ }+/// Attempt a state transition. Returns true if the transition happened.////// Transitions to the same state are ignored. Transitions within@@ -186,6 +197,7 @@ pub struct WorkerRegistryConfig {pub degraded_hold: Duration,pub min_state_duration: Duration,pub probe_failure_threshold: u32,+ pub drain_timeout: Duration,}impl From<&Config> for WorkerRegistryConfig {@@ -199,6 +211,7 @@ impl From<&Config> for WorkerRegistryConfig {degraded_hold: Duration::from_millis(c.worker_degraded_hold_ms),min_state_duration: Duration::from_millis(c.worker_min_state_duration_ms),probe_failure_threshold: c.worker_probe_failure_threshold,+ drain_timeout: Duration::from_millis(c.worker_drain_timeout_ms),}}}@@ -260,16 +273,17 @@ impl WorkerRegistry {self.workers.iter().map(|e| e.key().clone()).collect()}- /// Snapshot of worker ids currently eligible for routing (Healthy or- /// Degraded). Returned in arbitrary order.+ /// Snapshot of worker ids currently eligible for routing: Healthy or+ /// Degraded, and not draining. Returned in arbitrary order.pub fn healthy_workers(&self) -> Vec<WorkerId> {self.workers.iter().filter(|e| {- matches!(- e.value().state,- WorkerState::Healthy | WorkerState::Degraded- )+ !e.value().is_draining()+ && matches!(+ e.value().state,+ WorkerState::Healthy | WorkerState::Degraded+ )}).map(|e| e.key().clone()).collect()@@ -293,19 +307,86 @@ impl WorkerRegistry {.unwrap_or(true)}- /// Add a worker to the pool if not already present (starts Healthy).- /// Idempotent — re-adding an existing worker preserves its current health.+ /// Add a worker to the pool. If it is already present and draining (it left+ /// and rejoined, e.g. a flapping EndpointSlice), clear the draining mark so+ /// it routes again; otherwise an existing worker keeps its current health.pub fn add_worker(&self, worker: WorkerId) {- // `entry` makes the check-and-insert atomic — a plain- // `contains_key` + `insert` could let a concurrent caller overwrite a- // fresh `WorkerHealth` and reset health state.- let Entry::Vacant(slot) = self.workers.entry(worker.clone()) else {- return;- };- set_state_gauge(&worker, WorkerState::Healthy);- info!(worker = %worker, "Worker added to pool");- slot.insert(WorkerHealth::new());- counter!("ingestion_consumer_worker_membership_total", "action" => "add").increment(1);+ // `entry` makes the check-and-insert atomic — a plain `contains_key` ++ // `insert` could let a concurrent caller overwrite a fresh `WorkerHealth`+ // and reset health state.+ match self.workers.entry(worker.clone()) {+ Entry::Occupied(mut slot) => {+ // Already present. If it was draining (it left and rejoined, e.g.+ // a flapping EndpointSlice), clear the draining mark so it routes+ // again; otherwise it keeps its current health.+ if slot.get_mut().drain_deadline.take().is_some() {+ info!(worker = %worker, "Draining worker rejoined the pool");+ }+ }+ Entry::Vacant(slot) => {+ set_state_gauge(&worker, WorkerState::Healthy);+ info!(worker = %worker, "Worker added to pool");+ slot.insert(WorkerHealth::new());+ counter!("ingestion_consumer_worker_membership_total", "action" => "add")+ .increment(1);+ }+ }+ }++ /// Mark a worker as draining: it stops receiving new work (excluded from+ /// `healthy_workers`) but is not treated as dead, so its already-sent+ /// in-flight batches finish and ACK normally. Probe failures are ignored+ /// while draining (its readiness is expected to be down), but send failures+ /// still escalate it (a crash mid-drain). The reaper removes it once+ /// `complete_drain` fires (in-flight reached zero) or `drain_timeout` elapses.+ pub fn start_draining(&self, worker: &str) {+ if let Some(mut health) = self.workers.get_mut(worker) {+ if health.is_draining() {+ return;+ }+ health.drain_deadline = Some(Instant::now() + self.config.drain_timeout);+ info!(worker = %worker, "Worker draining (no new work; finishing in-flight)");+ counter!("ingestion_consumer_worker_membership_total", "action" => "drain")+ .increment(1);+ }+ }++ /// Mark a draining worker ready to reap now — called once its in-flight count+ /// reaches zero, so it's removed promptly instead of waiting for the timeout.+ pub fn complete_drain(&self, worker: &str) {+ if let Some(mut health) = self.workers.get_mut(worker) {+ if health.is_draining() {+ health.drain_deadline = Some(Instant::now());+ }+ }+ }++ pub fn is_draining(&self, worker: &str) -> bool {+ self.workers+ .get(worker)+ .map(|h| h.is_draining())+ .unwrap_or(false)+ }++ /// Draining workers whose reap deadline has passed (in-flight drained, or the+ /// timeout elapsed). The caller removes them from the registry and transport.+ pub fn reapable_workers(&self) -> Vec<WorkerId> {+ let now = Instant::now();+ self.workers+ .iter()+ .filter(|e| e.value().drain_deadline.is_some_and(|d| now >= d))+ .map(|e| e.key().clone())+ .collect()+ }++ /// All workers currently draining (regardless of deadline). The reaper uses+ /// this to complete the drain of a worker that left the pool while idle.+ pub fn draining_workers(&self) -> Vec<WorkerId> {+ self.workers+ .iter()+ .filter(|e| e.value().is_draining())+ .map(|e| e.key().clone())+ .collect()}/// Remove a worker from the pool (e.g. it left the EndpointSlice).@@ -389,6 +470,14 @@ impl WorkerRegistry {return;};+ // A draining worker's `/_ready` is expected to be down (it flipped+ // readiness to leave the pool), so ignore probe results — otherwise the+ // probe would march it to dead and evict its in-flight work. A crash+ // mid-drain is still caught by the passive send-failure signal.+ if health.is_draining() {+ return;+ }+if is_success {health.consecutive_probe_failures = 0;@@ -444,6 +533,7 @@ mod tests {degraded_hold: Duration::from_millis(50),min_state_duration: Duration::ZERO,probe_failure_threshold: 2,+ drain_timeout: Duration::from_secs(5),}}@@ -657,6 +747,81 @@ mod tests {assert!(!healthy.iter().any(|w| w.as_ref() == W2));}+ // --- Draining lifecycle ---++ #[test]+ fn test_draining_excludes_from_routing_but_not_dead() {+ let registry = WorkerRegistry::new(&three_workers(), no_cooldown_config());+ registry.start_draining(W2);++ assert!(registry.is_draining(W2));+ assert!(+ !registry.is_dead(W2),+ "a draining worker is alive, not dead"+ );+ assert_eq!(+ registry.state(W2),+ WorkerState::Healthy,+ "draining doesn't change the health state"+ );+ assert!(+ !registry.healthy_workers().iter().any(|w| w.as_ref() == W2),+ "a draining worker is not routable"+ );+ assert_eq!(registry.worker_count(), 3, "still in the pool until reaped");+ }++ #[test]+ fn test_complete_drain_makes_reapable() {+ // Long timeout, so only complete_drain (in-flight reached zero) reaps it.+ let config = WorkerRegistryConfig {+ drain_timeout: Duration::from_secs(3600),+ ..no_cooldown_config()+ };+ let registry = WorkerRegistry::new(&three_workers(), config);+ registry.start_draining(W2);+ assert!(+ registry.reapable_workers().is_empty(),+ "not reapable until drained or timed out"+ );++ registry.complete_drain(W2);+ assert_eq!(registry.reapable_workers(), vec![WorkerId::from(W2)]);+ }++ #[tokio::test]+ async fn test_drain_timeout_makes_reapable() {+ let config = WorkerRegistryConfig {+ drain_timeout: Duration::from_millis(20),+ ..no_cooldown_config()+ };+ let registry = WorkerRegistry::new(&one_worker(), config);+ registry.start_draining(W1);+ assert!(registry.reapable_workers().is_empty());++ tokio::time::sleep(Duration::from_millis(30)).await;+ assert_eq!(registry.reapable_workers(), vec![WorkerId::from(W1)]);+ }++ #[test]+ fn test_add_worker_rejoin_clears_draining() {+ let registry = WorkerRegistry::new(&one_worker(), no_cooldown_config());+ registry.start_draining(W1);+ assert!(registry.is_draining(W1));++ registry.add_worker(WorkerId::from(W1));+ assert!(!registry.is_draining(W1), "rejoining clears draining");+ assert!(registry.healthy_workers().iter().any(|w| w.as_ref() == W1));+ }++ #[test]+ fn test_start_draining_unknown_worker_is_noop() {+ let registry = WorkerRegistry::new(&one_worker(), no_cooldown_config());+ registry.start_draining("http://worker:9999");+ assert!(!registry.is_draining("http://worker:9999"));+ assert!(registry.reapable_workers().is_empty());+ }+// --- Passive window pruning ---#[tokio::test]diff --git a/rust/ingestion-consumer/tests/dispatcher_integration_test.rs b/rust/ingestion-consumer/tests/dispatcher_integration_test.rsindex 808b69000ee0..878f9e9d2301 100644--- a/rust/ingestion-consumer/tests/dispatcher_integration_test.rs+++ b/rust/ingestion-consumer/tests/dispatcher_integration_test.rs@@ -99,6 +99,7 @@ fn fast_config() -> WorkerRegistryConfig {degraded_hold: Duration::from_millis(30),min_state_duration: Duration::ZERO,probe_failure_threshold: 2,+ drain_timeout: Duration::from_secs(5),}}@@ -181,7 +182,7 @@ async fn test_new_keys_skip_unhealthy_worker() {let keys: Vec<_> = (0..10).map(|i| make_msg("t", &format!("user-{i}"))).collect();- let sub_batches = dispatcher.assign(keys);+ let sub_batches = dispatcher.assign("b", keys);assert!(sub_batches.iter().all(|b| b.worker.as_ref() == w0.url),@@ -211,7 +212,7 @@ async fn test_pinned_key_rerouted_after_dead_declaration() {// Pin "t:user-1" to whichever worker gets it first. Hold the sub-batch// open (don't call on_sub_batch_resolved) so the pin stays alive.- let b1 = dispatcher.assign(vec![make_msg("t", "user-1")]);+ let b1 = dispatcher.assign("b", vec![make_msg("t", "user-1")]);assert_eq!(b1.len(), 1);let pinned_to = b1[0].worker.clone();let other = if pinned_to.as_ref() == w0.url {@@ -231,8 +232,13 @@ async fn test_pinned_key_rerouted_after_dead_declaration() {wait_for_state(®istry, &pinned_to, WorkerState::Unhealthy).await;wait_for_dead(®istry, &pinned_to).await;- // Next assign: the stale pin is evicted and the key re-routes to the live worker.- let b2 = dispatcher.assign(vec![make_msg("t", "user-1")]);+ // Resolve b1: with max_in_flight=1 the previous batch completes before the+ // next assigns, so the dead worker has no in-flight and its zero-ref pin is+ // evicted (an unresolved pin would instead defer to preserve order).+ dispatcher.on_sub_batch_resolved(&pinned_to, b1[0].messages.len(), &b1[0].routing_keys, false);++ // Next assign: the evicted pin means the key re-routes to the live worker.+ let b2 = dispatcher.assign("b", vec![make_msg("t", "user-1")]);assert_eq!(b2.len(), 1, "expected exactly one sub-batch");assert_eq!(b2[0].worker.as_ref(),@@ -274,7 +280,7 @@ async fn test_worker_recovery_detected_by_probe() {let keys: Vec<_> = (0..40).map(|i| make_msg("t", &format!("user-{i}"))).collect();- let sub_batches = dispatcher.assign(keys);+ let sub_batches = dispatcher.assign("b", keys);let workers_used: std::collections::HashSet<String> =sub_batches.iter().map(|b| b.worker.to_string()).collect();@@ -305,11 +311,14 @@ async fn test_three_workers_one_dies_and_load_rebalances() {// 3 distinct keys of equal size: bin-packing spreads exactly one key per// worker (provisional load increases by 1 for each pick, breaking all ties).- let first = dispatcher.assign(vec![- make_msg("t", "key-a"),- make_msg("t", "key-b"),- make_msg("t", "key-c"),- ]);+ let first = dispatcher.assign(+ "b",+ vec![+ make_msg("t", "key-a"),+ make_msg("t", "key-b"),+ make_msg("t", "key-c"),+ ],+ );assert_eq!(first.len(),3,@@ -334,11 +343,14 @@ async fn test_three_workers_one_dies_and_load_rebalances() {wait_for_dead(®istry, &w1.url).await;// Fresh keys must only land on w0 or w2.- let fresh = dispatcher.assign(vec![- make_msg("t", "new-1"),- make_msg("t", "new-2"),- make_msg("t", "new-3"),- ]);+ let fresh = dispatcher.assign(+ "b",+ vec![+ make_msg("t", "new-1"),+ make_msg("t", "new-2"),+ make_msg("t", "new-3"),+ ],+ );assert!(fresh.iter().all(|b| b.worker.as_ref() != w1.url),"fresh keys must not route to dead w1; workers used: {:?}",@@ -348,10 +360,19 @@ async fn test_three_workers_one_dies_and_load_rebalances() {.collect::<Vec<_>>());+ // Resolve w1's in-flight sub-batch (max_in_flight=1: the prior batch+ // completes before the next assigns), evicting its now zero-ref pin.+ let w1_sub = first.iter().find(|b| b.worker.as_ref() == w1.url).unwrap();+ dispatcher.on_sub_batch_resolved(+ &w1_sub.worker,+ w1_sub.messages.len(),+ &w1_sub.routing_keys,+ false,+ );+// The key that was pinned to w1 must re-route to w0 or w2 on its next assign.- // The pin was evicted by drop_dead_pins during the fresh-keys assign above.let (_, distinct_id) = w1_key.split_once(':').unwrap();- let rerouted = dispatcher.assign(vec![make_msg("t", distinct_id)]);+ let rerouted = dispatcher.assign("b", vec![make_msg("t", distinct_id)]);assert_eq!(rerouted.len(),1,@@ -386,7 +407,7 @@ async fn test_all_workers_unhealthy_returns_empty() {wait_for_state(®istry, &w0.url, WorkerState::Unhealthy).await;wait_for_state(®istry, &w1.url, WorkerState::Unhealthy).await;- let sub_batches = dispatcher.assign(vec![make_msg("t", "user-1")]);+ let sub_batches = dispatcher.assign("b", vec![make_msg("t", "user-1")]);assert!(sub_batches.is_empty(),"expected empty assignment when all workers are unhealthy"@@ -394,3 +415,64 @@ async fn test_all_workers_unhealthy_returns_empty() {token.cancel();}++/// Graceful drain end-to-end at the dispatcher level: a draining worker keeps+/// its in-flight pin (new messages defer rather than reroute or pile onto it),+/// the liveness probe does not evict it while draining, and once its in-flight+/// resolves it becomes reapable and the deferred key reroutes to a survivor.+#[tokio::test]+async fn test_draining_worker_defers_then_flushes_to_survivor() {+ let w0 = FakeWorker::start().await;+ let w1 = FakeWorker::start().await;++ let urls = vec![w0.url.clone(), w1.url.clone()];+ let registry = Arc::new(WorkerRegistry::new(&urls, fast_config()));+ let dispatcher = Dispatcher::new(Arc::clone(®istry));++ let token = CancellationToken::new();+ Arc::clone(®istry).start_probing(token.clone());++ // Pin user-1 to whichever worker gets it; hold the sub-batch open.+ let b1 = dispatcher.assign("batch-1", vec![make_msg("t", "user-1")]);+ let pinned = b1[0].worker.clone();+ let other = if pinned.as_ref() == w0.url {+ w1.url.clone()+ } else {+ w0.url.clone()+ };++ // Begin draining (as an EndpointSlice removal would).+ registry.start_draining(&pinned);++ // New messages for user-1 defer — not sent to the drainer, not yet rerouted.+ let b2 = dispatcher.assign("batch-2", vec![make_msg("t", "user-1")]);+ assert!(+ b2.is_empty(),+ "must defer while the pinned worker is draining"+ );+ assert!(dispatcher.has_deferred("batch-2"));++ // The drainer is still alive and healthy — the probe must not evict it while+ // it finishes in-flight work (its /_ready still returns 200 here).+ tokio::time::sleep(Duration::from_millis(120)).await;+ assert!(+ !registry.is_dead(&pinned),+ "drainer must not be probed to death"+ );+ assert!(+ registry.reapable_workers().is_empty(),+ "not reapable while in-flight remains"+ );++ // Resolve batch-1: the drainer finishes and becomes reapable.+ dispatcher.on_sub_batch_resolved(&pinned, b1[0].messages.len(), &b1[0].routing_keys, false);+ assert_eq!(registry.reapable_workers(), vec![pinned.clone()]);++ // Flushing batch-2 reroutes the deferred key onto the surviving worker.+ let flushed = dispatcher.flush_deferred("batch-2");+ assert_eq!(flushed.len(), 1);+ assert_eq!(flushed[0].worker.as_ref(), other);+ assert!(!dispatcher.has_deferred("batch-2"));++ token.cancel();+}diff --git a/rust/ingestion-consumer/tests/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rsindex e6d0eadc603c..a6d224ee79f6 100644--- a/rust/ingestion-consumer/tests/e2e_integration_test.rs+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs@@ -3,7 +3,8 @@//! Requires Kafka on localhost:9092 (available via docker-compose).//! Each test creates a uniquely-named topic to avoid cross-test interference.-use std::sync::atomic::{AtomicBool, Ordering};+use std::collections::HashMap;+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::{Arc, Mutex};use std::time::Duration;@@ -25,8 +26,8 @@ use uuid::Uuid;use ingestion_consumer::consumer::{IngestionConsumer, IngestionConsumerOptions};use ingestion_consumer::dispatcher::Dispatcher;use ingestion_consumer::transport::HttpTransport;-use ingestion_consumer::types::{IngestBatchRequest, IngestBatchResponse};-use ingestion_consumer::worker_registry::{WorkerRegistry, WorkerRegistryConfig};+use ingestion_consumer::types::{IngestBatchRequest, IngestBatchResponse, SerializedKafkaMessage};+use ingestion_consumer::worker_registry::{WorkerId, WorkerRegistry, WorkerRegistryConfig};const KAFKA_BROKERS: &str = "localhost:9092";@@ -95,14 +96,45 @@ struct FakeWorker {pub url: String,/// (distinct_id, seq) pairs in arrival order.pub received: Arc<Mutex<Vec<(String, usize)>>>,+ /// Gates /_ready (pool membership). When false the worker leaves the pool.pub healthy: Arc<AtomicBool>,+ /// Gates /ingest only. When false the worker stays ready (in the pool) but+ /// fails every send — a "flapping" worker, used to exercise the flush loop's+ /// re-defer path and its timeout bound.+ pub ingest_ok: Arc<AtomicBool>,+ /// Number of /ingest requests that have reached the handler. Counted before+ /// the gate, so a test can observe a batch is in-flight even while held.+ arrived: Arc<AtomicUsize>,+ /// Held by the handler for the duration of each /ingest request. A test can+ /// acquire it via `block()` to freeze a request in flight (simulating a slow+ /// worker), then drop the guard to let it complete.+ gate: Arc<tokio::sync::Mutex<()>>,_task: tokio::task::JoinHandle<()>,}+/// A receipt-ordered log of `(distinct_id, seq)` shared across all workers in a+/// run. The shared mutex gives every accepted message a slot in a single total+/// order, so a test can reconstruct global delivery order across reroutes and+/// assert per-distinct_id ordering, no loss, and no duplication.+type DeliveryLog = Arc<Mutex<Vec<(String, usize)>>>;+impl FakeWorker {async fn start() -> Self {+ Self::start_inner(None).await+ }++ /// Like `start`, but also appends every accepted message to a shared,+ /// cross-worker delivery log (for the churn/ordering suite).+ async fn start_logged(delivery_log: DeliveryLog) -> Self {+ Self::start_inner(Some(delivery_log)).await+ }++ async fn start_inner(delivery_log: Option<DeliveryLog>) -> Self {let received: Arc<Mutex<Vec<(String, usize)>>> = Arc::new(Mutex::new(Vec::new()));let healthy = Arc::new(AtomicBool::new(true));+ let ingest_ok = Arc::new(AtomicBool::new(true));+ let arrived = Arc::new(AtomicUsize::new(0));+ let gate = Arc::new(tokio::sync::Mutex::new(()));let app = Router::new().route(@@ -126,11 +158,26 @@ impl FakeWorker {post({let recv = Arc::clone(&received);let h = Arc::clone(&healthy);+ let ingest_ok = Arc::clone(&ingest_ok);+ let arrived = Arc::clone(&arrived);+ let gate = Arc::clone(&gate);+ let delivery_log = delivery_log.clone();move |AxumJson(req): AxumJson<IngestBatchRequest>| {let recv = recv.clone();let h = h.clone();+ let ingest_ok = ingest_ok.clone();+ let arrived = arrived.clone();+ let gate = gate.clone();+ let delivery_log = delivery_log.clone();async move {- if !h.load(Ordering::Relaxed) {+ arrived.fetch_add(1, Ordering::SeqCst);+ // Block here while a test holds the gate (slow worker).+ let _hold = gate.lock().await;+ // Health is checked after the gate so a test can flip a+ // held request to a failure before releasing it. A+ // worker that is ready but has ingest_ok=false fails+ // sends while staying in the pool (a flapping worker).+ if !h.load(Ordering::Relaxed) || !ingest_ok.load(Ordering::Relaxed) {return (axum::http::StatusCode::INTERNAL_SERVER_ERROR,AxumJson(IngestBatchResponse {@@ -142,18 +189,29 @@ impl FakeWorker {);}let accepted = req.messages.len() as u32;- let mut g = recv.lock().unwrap();- for msg in &req.messages {- let did =- msg.headers.get("distinct_id").cloned().unwrap_or_default();- let seq = msg- .value- .as_deref()- .and_then(|v| serde_json::from_str::<serde_json::Value>(v).ok())- .and_then(|v| v["seq"].as_u64())- .unwrap_or(0)- as usize;- g.push((did, seq));+ let entries: Vec<(String, usize)> = req+ .messages+ .iter()+ .map(|msg| {+ let did =+ msg.headers.get("distinct_id").cloned().unwrap_or_default();+ let seq = msg+ .value+ .as_deref()+ .and_then(|v| {+ serde_json::from_str::<serde_json::Value>(v).ok()+ })+ .and_then(|v| v["seq"].as_u64())+ .unwrap_or(0)+ as usize;+ (did, seq)+ })+ .collect();+ recv.lock().unwrap().extend(entries.iter().cloned());+ // Record the whole batch as one contiguous slot in the+ // shared total order (it was accepted as a unit).+ if let Some(log) = &delivery_log {+ log.lock().unwrap().extend(entries);}(axum::http::StatusCode::OK,@@ -178,6 +236,9 @@ impl FakeWorker {url,received,healthy,+ ingest_ok,+ arrived,+ gate,_task: task,}}@@ -186,6 +247,17 @@ impl FakeWorker {self.received.lock().unwrap().len()}+ /// /ingest requests that have reached this worker (including any held by the gate).+ fn arrived_count(&self) -> usize {+ self.arrived.load(Ordering::SeqCst)+ }++ /// Freeze this worker's /ingest handling: requests arrive but block until the+ /// returned guard is dropped. Acquire before producing so the batch is caught.+ async fn block(&self) -> tokio::sync::OwnedMutexGuard<()> {+ Arc::clone(&self.gate).lock_owned().await+ }+fn seqs_for(&self, distinct_id: &str) -> Vec<usize> {self.received.lock()@@ -201,8 +273,12 @@ impl FakeWorker {struct Harness {pub workers: Vec<FakeWorker>,+ pub registry: Arc<WorkerRegistry>,+ pub dispatcher: Arc<Dispatcher>,+ /// Cross-worker, receipt-ordered log of every accepted message.+ pub delivery_log: DeliveryLog,pub shutdown: CancellationToken,- _task: tokio::task::JoinHandle<()>,+ task: Option<tokio::task::JoinHandle<()>>,_probe_token: CancellationToken,}@@ -211,13 +287,16 @@ impl Harness {topic: &str,partitions: i32,worker_count: usize,+ max_in_flight: usize,+ deferred_flush_timeout: Duration,registry_config: WorkerRegistryConfig,) -> Self {create_topic(topic, partitions).await;+ let delivery_log: DeliveryLog = Arc::new(Mutex::new(Vec::new()));let mut workers = Vec::new();for _ in 0..worker_count {- workers.push(FakeWorker::start().await);+ workers.push(FakeWorker::start_logged(Arc::clone(&delivery_log)).await);}let worker_urls: Vec<String> = workers.iter().map(|w| w.url.clone()).collect();@@ -226,6 +305,8 @@ impl Harness {Arc::clone(®istry).start_probing(probe_token.clone());let dispatcher = Arc::new(Dispatcher::new(Arc::clone(®istry)));+ let registry_for_test = Arc::clone(®istry);+ let dispatcher_for_test = Arc::clone(&dispatcher);let transport = Arc::new(HttpTransport::new(Duration::from_secs(5),0, // no retries — errors surface immediately for health tracking@@ -259,8 +340,9 @@ impl Harness {IngestionConsumerOptions {batch_size: 50,batch_timeout: Duration::from_millis(100),- max_in_flight_batches: 1,+ max_in_flight_batches: max_in_flight,group_id: "e2e-test".to_string(),+ deferred_flush_timeout,},handle,);@@ -272,12 +354,24 @@ impl Harness {Self {workers,+ registry: registry_for_test,+ dispatcher: dispatcher_for_test,+ delivery_log,shutdown,- _task: task,+ task: Some(task),_probe_token: probe_token,}}+ /// Wait for the consumer's process loop to exit on its own (e.g. after it+ /// fails a batch), up to `timeout`. Returns true if it exited within the bound.+ async fn wait_for_consumer_exit(&mut self, timeout: Duration) -> bool {+ let Some(task) = self.task.take() else {+ return true;+ };+ tokio::time::timeout(timeout, task).await.is_ok()+ }+async fn wait_for(&self, total: usize, timeout: Duration) {let deadline = tokio::time::Instant::now() + timeout;loop {@@ -293,9 +387,11 @@ impl Harness {}}- async fn stop(self) {+ async fn stop(mut self) {self.shutdown.cancel();- let _ = tokio::time::timeout(Duration::from_secs(3), self._task).await;+ if let Some(task) = self.task.take() {+ let _ = tokio::time::timeout(Duration::from_secs(3), task).await;+ }}}@@ -309,9 +405,40 @@ fn fast_registry_config() -> WorkerRegistryConfig {degraded_hold: Duration::from_millis(100),min_state_duration: Duration::ZERO,probe_failure_threshold: 2,+ drain_timeout: Duration::from_secs(5),}}+/// Poll `cond` until it returns true or the timeout elapses (panics on timeout).+async fn wait_until(timeout: Duration, msg: &str, mut cond: impl FnMut() -> bool) {+ let deadline = tokio::time::Instant::now() + timeout;+ while !cond() {+ assert!(+ tokio::time::Instant::now() < deadline,+ "timed out waiting for: {msg}"+ );+ tokio::time::sleep(Duration::from_millis(20)).await;+ }+}++/// Index of the single worker that has received an /ingest request so far.+/// Panics if zero or more than one have — callers rely on a unique pin.+fn sole_arrived_worker(harness: &Harness) -> usize {+ let arrived: Vec<usize> = harness+ .workers+ .iter()+ .enumerate()+ .filter(|(_, w)| w.arrived_count() > 0)+ .map(|(i, _)| i)+ .collect();+ assert_eq!(+ arrived.len(),+ 1,+ "expected exactly one worker to have a batch in flight, got {arrived:?}"+ );+ arrived[0]+}+// ── Tests ──────────────────────────────────────────────────────────────────/// Kafka partition order is preserved per distinct_id on each worker.@@ -328,7 +455,15 @@ fn fast_registry_config() -> WorkerRegistryConfig {#[tokio::test]async fn messages_per_distinct_id_arrive_in_order() {let topic = format!("e2e-ordering-{}", Uuid::new_v4());- let harness = Harness::start(&topic, 3, 2, fast_registry_config()).await;+ let harness = Harness::start(+ &topic,+ 3,+ 2,+ 1,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;let producer = make_producer();for seq in 0..8usize {@@ -363,7 +498,15 @@ async fn messages_per_distinct_id_arrive_in_order() {#[tokio::test]async fn failing_worker_triggers_rerouting() {let topic = format!("e2e-failover-{}", Uuid::new_v4());- let harness = Harness::start(&topic, 2, 2, fast_registry_config()).await;+ let harness = Harness::start(+ &topic,+ 2,+ 2,+ 1,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;let producer = make_producer();@@ -407,3 +550,791 @@ async fn failing_worker_triggers_rerouting() {harness.stop().await;}++/// Graceful drain end-to-end: a worker that begins draining receives no new+/// work, keeps the messages it already has (no reprocessing, no loss), and+/// 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.+#[tokio::test]+async fn draining_worker_takes_no_new_work_and_reroutes_in_order() {+ let topic = format!("e2e-drain-{}", Uuid::new_v4());+ let harness = Harness::start(+ &topic,+ 2,+ 2,+ 1,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;++ let producer = make_producer();++ // Batch 1: 4 messages each for user-1 (partition 0) and user-2 (partition 1).+ for seq in 0..4usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ produce(&producer, &topic, 1, "tok", "user-2", seq).await;+ }+ harness.wait_for(8, Duration::from_secs(10)).await;++ // Identify which worker owns user-1 and begin draining it.+ let drain_idx = if !harness.workers[0].seqs_for("user-1").is_empty() {+ 0+ } else {+ 1+ };+ let live_idx = 1 - drain_idx;+ let drain_url = harness.workers[drain_idx].url.clone();+ harness.registry.start_draining(&drain_url);++ // A draining worker is alive, not failed: its /_ready still returns 200, and+ // the probe skips draining workers — it must never be declared dead.+ tokio::time::sleep(Duration::from_millis(400)).await;+ assert!(+ !harness.registry.is_dead(&drain_url),+ "a draining (but alive) worker must not be probed to death"+ );++ // Batch 2: 4 more messages for user-1. The drainer takes no new work, so+ // these must route to the live worker, in order.+ for seq in 4..8usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ }+ harness.wait_for(12, Duration::from_secs(10)).await;++ // No reprocessing / no loss: each user-1 seq 0..8 is delivered exactly once.+ let mut all_user1: Vec<usize> = harness+ .workers+ .iter()+ .flat_map(|w| w.seqs_for("user-1"))+ .collect();+ all_user1.sort_unstable();+ assert_eq!(+ all_user1,+ (0..8).collect::<Vec<_>>(),+ "user-1 messages were lost or duplicated: {all_user1:?}"+ );++ // The draining worker received no new work after draining began.+ let drained_seqs = harness.workers[drain_idx].seqs_for("user-1");+ assert!(+ drained_seqs.iter().all(|&s| s < 4),+ "draining worker received new work: {drained_seqs:?}"+ );++ // Batch-2 messages all landed on the live worker, in ascending order.+ let live_batch2: Vec<usize> = harness.workers[live_idx]+ .seqs_for("user-1")+ .into_iter()+ .filter(|&s| s >= 4)+ .collect();+ assert_eq!(+ live_batch2,+ vec![4, 5, 6, 7],+ "batch-2 messages misrouted or out of order on the live worker: {live_batch2:?}"+ );++ harness.stop().await;+}++// ── Failure-triggered defer + flush at the consumer level ────────────────────+//+// These drive the consumer's defer→stash→flush loop end-to-end through real+// Kafka. A "blocking" worker holds a batch in flight so a test can flip it to a+// failure before it responds; the failed send then exercises `defer_failed` and+// the `complete_oldest_batch` flush loop. (The drain-triggered defer needs a+// drain signal injected between two overlapping batch assigns, which isn't+// reachable from a black-box test; that path is covered by the dispatcher unit+// and dispatcher_integration tests, which drive `assign`/`flush_deferred`+// directly.)++/// Whether `url` is currently routable (healthy or degraded) per the registry.+fn in_pool(harness: &Harness, url: &str) -> bool {+ harness+ .registry+ .healthy_workers()+ .iter()+ .any(|w| w.as_ref() == url)+}++/// Whether `url` is routable per a bare registry (no Harness).+fn registry_has(registry: &WorkerRegistry, url: &str) -> bool {+ registry.healthy_workers().iter().any(|w| w.as_ref() == url)+}++/// Build a dispatcher-level message for a distinct_id carrying `seq` in its body,+/// so a FakeWorker records it the same way it records produced Kafka records.+fn worker_msg(distinct_id: &str, seq: usize) -> SerializedKafkaMessage {+ let mut headers = HashMap::new();+ headers.insert("token".to_string(), "tok".to_string());+ headers.insert("distinct_id".to_string(), distinct_id.to_string());+ SerializedKafkaMessage {+ topic: "t".to_string(),+ partition: 0,+ offset: seq as i64,+ timestamp: 0,+ key: None,+ value: Some(format!(r#"{{"seq":{seq}}}"#)),+ headers,+ }+}++/// A send that fails mid-flight is deferred and replayed, in order, to the+/// surviving worker — no loss, no duplication, no reordering.+#[tokio::test]+async fn send_failure_mid_flight_replays_to_survivor_in_order() {+ let topic = format!("e2e-replay-single-{}", Uuid::new_v4());+ let harness = Harness::start(+ &topic,+ 1,+ 2,+ 1,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;+ let producer = make_producer();++ // Freeze both workers so whichever gets the batch holds it in flight.+ let mut guards: Vec<Option<tokio::sync::OwnedMutexGuard<()>>> = Vec::new();+ for w in &harness.workers {+ guards.push(Some(w.block().await));+ }++ for seq in 0..4usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ }+ wait_until(Duration::from_secs(10), "batch to reach a worker", || {+ harness.workers.iter().any(|w| w.arrived_count() > 0)+ })+ .await;+ let failed = sole_arrived_worker(&harness);+ let survivor = 1 - failed;++ // Turn the held request into a failure, then release everything.+ harness.workers[failed]+ .healthy+ .store(false, Ordering::SeqCst);+ guards[survivor] = None;+ guards[failed] = None;++ harness.wait_for(4, Duration::from_secs(10)).await;++ assert_eq!(+ harness.workers[failed].count(),+ 0,+ "the failed worker recorded nothing (it only returned errors)"+ );+ assert_eq!(+ harness.workers[survivor].seqs_for("user-1"),+ vec![0, 1, 2, 3],+ "user-1 must replay to the survivor in Kafka order"+ );++ harness.stop().await;+}++/// 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.+#[tokio::test]+async fn partial_send_failure_replays_only_the_failed_subbatch() {+ let topic = format!("e2e-replay-partial-{}", Uuid::new_v4());+ let harness = Harness::start(+ &topic,+ 2,+ 2,+ 1,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;+ let producer = make_producer();++ let mut guards: Vec<Option<tokio::sync::OwnedMutexGuard<()>>> = Vec::new();+ for w in &harness.workers {+ guards.push(Some(w.block().await));+ }++ // Two equal-size keys on two partitions → bin-packed one per worker: one+ // batch, two sub-batches, one per worker.+ for seq in 0..4usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ produce(&producer, &topic, 1, "tok", "user-2", seq).await;+ }+ wait_until(+ Duration::from_secs(10),+ "both workers to receive a sub-batch",+ || harness.workers.iter().all(|w| w.arrived_count() > 0),+ )+ .await;++ // Fail worker 0's sub-batch only. Whatever key it held replays to worker 1,+ // so worker 1 ends with both keys and worker 0 with nothing.+ harness.workers[0].healthy.store(false, Ordering::SeqCst);+ guards[1] = None;+ guards[0] = None;++ harness.wait_for(8, Duration::from_secs(15)).await;++ assert_eq!(+ harness.workers[0].count(),+ 0,+ "failed worker recorded nothing"+ );+ assert_eq!(+ harness.workers[1].seqs_for("user-1"),+ vec![0, 1, 2, 3],+ "user-1 fully on the survivor in order"+ );+ assert_eq!(+ harness.workers[1].seqs_for("user-2"),+ vec![0, 1, 2, 3],+ "user-2 (the originally-successful sub-batch) intact, not duplicated"+ );++ harness.stop().await;+}++/// When a send fails and there is no healthy worker to replay to, the deferred+/// work is held (not lost, not dropped) and the flush loop retries until a+/// worker returns, then drains in order.+#[tokio::test]+async fn deferred_flush_retries_until_a_worker_recovers() {+ let topic = format!("e2e-replay-wait-{}", Uuid::new_v4());+ let harness = Harness::start(+ &topic,+ 1,+ 2,+ 1,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;+ let producer = make_producer();++ // Take worker 1 out of the pool so the batch routes to worker 0.+ harness.workers[1].healthy.store(false, Ordering::SeqCst);+ wait_until(+ Duration::from_secs(10),+ "worker 1 to leave the pool",+ || !in_pool(&harness, &harness.workers[1].url),+ )+ .await;++ let guard0 = harness.workers[0].block().await;+ for seq in 0..4usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ }+ wait_until(Duration::from_secs(10), "batch to reach worker 0", || {+ harness.workers[0].arrived_count() > 0+ })+ .await;++ // Fail worker 0 too: now there is nowhere to replay.+ harness.workers[0].healthy.store(false, Ordering::SeqCst);+ drop(guard0);++ // Wait until worker 0 has also left the pool. The failed send is now+ // deferred with nowhere to go. (At max_in_flight=1 the consumer is parked in+ // the flush loop for the oldest batch and stops consuming, so only that+ // batch's messages are stashed — Kafka polling may have split the produced+ // records across batches; the exact count doesn't matter.)+ wait_until(+ Duration::from_secs(10),+ "worker 0 to leave the pool",+ || !in_pool(&harness, &harness.workers[0].url),+ )+ .await;+ wait_until(+ Duration::from_secs(10),+ "the failed send to be deferred",+ || harness.dispatcher.stashed_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();+ tokio::time::sleep(Duration::from_millis(400)).await;+ assert_eq!(+ harness.dispatcher.stashed_messages(),+ held,+ "deferred work must be held steady while no worker is available"+ );++ // Recover worker 1 → the flush loop drains the stash to it, then the consumer+ // resumes and delivers the rest. All of user-1 lands on worker 1, in order.+ harness.workers[1].healthy.store(true, Ordering::SeqCst);+ harness.wait_for(4, Duration::from_secs(15)).await;++ assert_eq!(+ harness.workers[1].seqs_for("user-1"),+ vec![0, 1, 2, 3],+ "deferred user-1 must flush to the recovered worker in order"+ );+ assert_eq!(+ harness.workers[0].count(),+ 0,+ "failed worker recorded nothing"+ );++ harness.stop().await;+}++/// A failed multi-key sub-batch replays every key, each in its own Kafka order,+/// once a worker is available.+#[tokio::test]+async fn multi_key_send_failure_replays_every_key_in_order() {+ let topic = format!("e2e-replay-multikey-{}", Uuid::new_v4());+ let harness = Harness::start(+ &topic,+ 3,+ 2,+ 1,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;+ let producer = make_producer();++ // Worker 1 out so all three keys land on worker 0 as one sub-batch.+ harness.workers[1].healthy.store(false, Ordering::SeqCst);+ wait_until(+ Duration::from_secs(10),+ "worker 1 to leave the pool",+ || !in_pool(&harness, &harness.workers[1].url),+ )+ .await;++ let guard0 = harness.workers[0].block().await;+ for seq in 0..3usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ produce(&producer, &topic, 1, "tok", "user-2", seq).await;+ produce(&producer, &topic, 2, "tok", "user-3", seq).await;+ }+ wait_until(Duration::from_secs(10), "batch to reach worker 0", || {+ harness.workers[0].arrived_count() > 0+ })+ .await;++ // Fail worker 0 and bring worker 1 back as the replay target.+ harness.workers[0].healthy.store(false, Ordering::SeqCst);+ harness.workers[1].healthy.store(true, Ordering::SeqCst);+ wait_until(+ Duration::from_secs(10),+ "worker 1 to rejoin the pool",+ || in_pool(&harness, &harness.workers[1].url),+ )+ .await;+ drop(guard0);++ harness.wait_for(9, Duration::from_secs(15)).await;++ assert_eq!(+ harness.workers[0].count(),+ 0,+ "failed worker recorded nothing"+ );+ for user in ["user-1", "user-2", "user-3"] {+ assert_eq!(+ harness.workers[1].seqs_for(user),+ vec![0, 1, 2],+ "{user} must replay to the recovered worker in order"+ );+ }++ harness.stop().await;+}++/// 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.+#[tokio::test]+async fn flush_target_failure_re_defers_then_replays_in_order() {+ let topic = format!("e2e-replay-cascade-{}", Uuid::new_v4());+ let harness = Harness::start(+ &topic,+ 1,+ 2,+ 1,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;+ let producer = make_producer();++ let mut guards: Vec<Option<tokio::sync::OwnedMutexGuard<()>>> = Vec::new();+ for w in &harness.workers {+ guards.push(Some(w.block().await));+ }++ for seq in 0..4usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ }+ wait_until(Duration::from_secs(10), "batch to reach a worker", || {+ harness.workers.iter().any(|w| w.arrived_count() > 0)+ })+ .await;+ let first = sole_arrived_worker(&harness);+ let second = 1 - first;++ // Fail the initial send → the batch defers and the flush re-routes to the+ // other worker, whose request we are holding via its gate.+ harness.workers[first]+ .healthy+ .store(false, Ordering::SeqCst);+ guards[first] = None;+ wait_until(+ Duration::from_secs(10),+ "the replay to reach the second worker",+ || harness.workers[second].arrived_count() > 0,+ )+ .await;++ // Fail the replay too → it must be re-deferred, not lost.+ harness.workers[second]+ .healthy+ .store(false, Ordering::SeqCst);+ guards[second] = None;+ wait_until(+ Duration::from_secs(10),+ "both workers to leave the pool",+ || {+ !in_pool(&harness, &harness.workers[first].url)+ && !in_pool(&harness, &harness.workers[second].url)+ },+ )+ .await;+ assert!(+ harness.dispatcher.stashed_messages() > 0,+ "re-deferred work must be held after the replay target also fails"+ );++ // Recover the second worker → the replay finally lands, in order.+ harness.workers[second]+ .healthy+ .store(true, Ordering::SeqCst);+ harness.wait_for(4, Duration::from_secs(15)).await;++ assert_eq!(+ harness.workers[first].count(),+ 0,+ "the worker that only ever failed recorded nothing"+ );+ assert_eq!(+ harness.workers[second].seqs_for("user-1"),+ vec![0, 1, 2, 3],+ "user-1 replays to the recovered worker in order despite the cascade"+ );++ harness.stop().await;+}++/// Drain-triggered defer through the dispatcher + real HTTP transport — the path+/// the consumer drives. The Kafka poll loop can't inject a drain between two+/// overlapping batch assigns deterministically (it assigns available batches+/// back-to-back and parks in `complete_oldest_batch` the moment data dries up),+/// so this models the consumer's exact sequence — assign, drain, assign (defer),+/// resolve, flush — and delivers over real HTTP, asserting the deferred key lands+/// on the survivor in order.+#[tokio::test]+async fn drain_defer_flush_delivers_to_survivor_over_http() {+ let w0 = FakeWorker::start().await;+ let w1 = FakeWorker::start().await;+ let urls = vec![w0.url.clone(), w1.url.clone()];+ let workers = [w0, w1];++ let registry = Arc::new(WorkerRegistry::new(&urls, fast_registry_config()));+ let probe_token = CancellationToken::new();+ Arc::clone(®istry).start_probing(probe_token.clone());+ let dispatcher = Dispatcher::new(Arc::clone(®istry));+ let transport = HttpTransport::new(Duration::from_secs(5), 0, None, &urls, 1);++ // batch-1: user-1 pins to a worker. Send it for real but DON'T resolve, so it+ // is genuinely in flight on that worker.+ let b1 = dispatcher.assign("batch-1", vec![worker_msg("user-1", 0)]);+ assert_eq!(b1.len(), 1);+ let pinned_url = b1[0].worker.to_string();+ let pinned_idx = workers.iter().position(|w| w.url == pinned_url).unwrap();+ let survivor_idx = 1 - pinned_idx;+ transport+ .send_batch(&pinned_url, "batch-1", b1[0].messages.clone())+ .await+ .expect("batch-1 send");++ // Drain the pinned worker. The next batch for the key must defer (its worker+ // is draining and still has in-flight work — rerouting now would reorder it).+ registry.start_draining(&pinned_url);+ let b2 = dispatcher.assign("batch-2", vec![worker_msg("user-1", 1)]);+ assert!(b2.is_empty(), "must defer while the pinned worker drains");+ assert!(dispatcher.has_deferred("batch-2"));++ // Resolve batch-1 (the drainer finishes its in-flight), then flush batch-2:+ // it re-routes to the survivor.+ dispatcher.on_sub_batch_resolved(+ &b1[0].worker,+ b1[0].messages.len(),+ &b1[0].routing_keys,+ false,+ );+ let f2 = dispatcher.flush_deferred("batch-2");+ assert_eq!(f2.len(), 1);+ assert_eq!(+ f2[0].worker.to_string(),+ workers[survivor_idx].url,+ "deferred group flushes to the survivor, not the drainer"+ );+ transport+ .send_batch(f2[0].worker.as_ref(), "batch-2", f2[0].messages.clone())+ .await+ .expect("batch-2 flush send");++ // The drainer kept its in-flight seq 0; the deferred seq 1 landed on the+ // survivor — delivered over real HTTP, in order, with nothing lost.+ assert_eq!(workers[pinned_idx].seqs_for("user-1"), vec![0]);+ assert_eq!(workers[survivor_idx].seqs_for("user-1"), vec![1]);+ assert!(+ registry_has(®istry, &workers[survivor_idx].url),+ "survivor stayed routable throughout"+ );++ probe_token.cancel();+}++// ── max_in_flight > 1 churn / invariant suite ────────────────────────────────+//+// At max_in_flight > 1 the consumer processes batches concurrently, so exact+// scenarios can't be scripted deterministically. These tests instead run a high+// volume across many distinct_ids while aggressively churning the worker pool,+// and assert the correctness INVARIANTS on the cross-worker delivery log:+// - exactly-once: every produced (distinct_id, seq) is delivered once — no+// loss, no duplication;+// - ordering: under graceful drain, each distinct_id's messages are delivered+// in Kafka order despite rerouting (a regression of the deferred-replay+// ordering shows up here as an out-of-order seq).+//+// Drain churn (the graceful-drain feature) preserves order, so it is asserted+// strictly. Send-failure churn falls back to at-least-once replay, which can+// interleave a failed-then-replayed message with a later same-key success on a+// flapping worker; those variants assert exactly-once but not strict order.++#[derive(Clone, Copy, Debug)]+enum Churn {+ Drain,+ Fail,+ Mixed,+}++async fn sleep_or_cancel(token: &CancellationToken, ms: u64) -> bool {+ tokio::select! {+ _ = token.cancelled() => true,+ _ = tokio::time::sleep(Duration::from_millis(ms)) => false,+ }+}++/// Continuously churn the worker pool until cancelled, affecting one worker at a+/// time so the pool always keeps a healthy majority (progress is always+/// possible). Drain = leave/rejoin the pool (EndpointSlice-style); Fail = stay+/// ready but error sends (a crash mid-send). Restores all workers on exit.+fn spawn_churn(+ harness: &Harness,+ churn: Churn,+ token: CancellationToken,+) -> tokio::task::JoinHandle<()> {+ let registry = Arc::clone(&harness.registry);+ let controls: Vec<(String, Arc<AtomicBool>)> = harness+ .workers+ .iter()+ .map(|w| (w.url.clone(), Arc::clone(&w.ingest_ok)))+ .collect();+ tokio::spawn(async move {+ let mut i = 0usize;+ while !token.is_cancelled() {+ let (url, ingest_ok) = &controls[i % controls.len()];+ let drain = match churn {+ Churn::Drain => true,+ Churn::Fail => false,+ Churn::Mixed => i.is_multiple_of(2),+ };+ if drain {+ registry.start_draining(url);+ if sleep_or_cancel(&token, 120).await {+ break;+ }+ registry.add_worker(WorkerId::from(url.as_str()));+ } else {+ ingest_ok.store(false, Ordering::SeqCst);+ if sleep_or_cancel(&token, 120).await {+ break;+ }+ ingest_ok.store(true, Ordering::SeqCst);+ }+ // A gap with everyone healthy so the backlog can drain.+ if sleep_or_cancel(&token, 80).await {+ break;+ }+ i += 1;+ }+ for (url, ingest_ok) in &controls {+ ingest_ok.store(true, Ordering::SeqCst);+ registry.add_worker(WorkerId::from(url.as_str()));+ }+ })+}++async fn run_churn_suite(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;+ let total = dids * per_did;+ let partitions = 4i32;++ let harness = Harness::start(+ &topic,+ partitions,+ 4,+ max_in_flight,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;+ let producer = make_producer();++ let churn_token = CancellationToken::new();+ let churn_handle = spawn_churn(&harness, churn, churn_token.clone());++ // Interleave distinct_ids so each Kafka batch mixes many keys.+ for seq in 0..per_did {+ for d in 0..dids {+ produce(+ &producer,+ &topic,+ (d as i32) % partitions,+ "tok",+ &format!("user-{d}"),+ seq,+ )+ .await;+ }+ }++ harness.wait_for(total, Duration::from_secs(90)).await;++ // Quiesce churn so the final assertions see a settled log.+ churn_token.cancel();+ let _ = churn_handle.await;++ let log = harness.delivery_log.lock().unwrap().clone();+ assert_eq!(+ log.len(),+ total,+ "exactly-once: expected {total} deliveries, got {}",+ log.len()+ );++ let expected: Vec<usize> = (0..per_did).collect();+ for d in 0..dids {+ let did = format!("user-{d}");+ let seqs: Vec<usize> = log+ .iter()+ .filter(|(id, _)| *id == did)+ .map(|(_, s)| *s)+ .collect();+ let mut sorted = seqs.clone();+ sorted.sort_unstable();+ assert_eq!(+ sorted, expected,+ "{did}: messages lost or duplicated under {churn:?} churn: {seqs:?}"+ );+ if strict_order {+ assert_eq!(+ seqs, expected,+ "{did}: messages delivered out of order under {churn:?} churn: {seqs:?}"+ );+ }+ }++ harness.stop().await;+}++#[tokio::test]+async fn churn_drain_preserves_order_at_max_in_flight_2() {+ run_churn_suite(Churn::Drain, 2, true).await;+}++#[tokio::test]+async fn churn_drain_preserves_order_at_max_in_flight_3() {+ run_churn_suite(Churn::Drain, 3, true).await;+}++#[tokio::test]+async fn churn_send_failures_are_exactly_once_at_max_in_flight_3() {+ run_churn_suite(Churn::Fail, 3, false).await;+}++#[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;+}++/// 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.+#[tokio::test]+async fn flapping_worker_does_not_pin_batch_past_flush_timeout() {+ let topic = format!("e2e-flap-{}", Uuid::new_v4());+ // Short flush timeout so the bound is observable quickly; concurrency > 1.+ let mut harness = Harness::start(+ &topic,+ 1,+ 2,+ 2,+ Duration::from_secs(2),+ fast_registry_config(),+ )+ .await;+ let producer = make_producer();++ let mut guards: Vec<Option<tokio::sync::OwnedMutexGuard<()>>> = Vec::new();+ for w in &harness.workers {+ guards.push(Some(w.block().await));+ }++ for seq in 0..4usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ }+ wait_until(Duration::from_secs(10), "batch to reach a worker", || {+ harness.workers.iter().any(|w| w.arrived_count() > 0)+ })+ .await;+ let target = sole_arrived_worker(&harness);+ let other = 1 - target;++ // `target` flaps: stays ready (in the pool) but fails every send. `other` is+ // taken out of the pool so the flush can't escape — the flush loop keeps+ // re-routing to the flapping target and re-deferring on the scatter path.+ harness.workers[target]+ .ingest_ok+ .store(false, Ordering::SeqCst);+ harness.workers[other]+ .healthy+ .store(false, Ordering::SeqCst);+ guards[other] = None;+ guards[target] = None;++ // The consumer must fail the batch within ~the flush timeout, not spin+ // forever on the re-defer path.+ assert!(+ harness+ .wait_for_consumer_exit(Duration::from_secs(20))+ .await,+ "consumer must fail the batch within the flush timeout, not spin forever"+ );+ assert_eq!(+ harness.workers.iter().map(|w| w.count()).sum::<usize>(),+ 0,+ "nothing should be delivered (target only errors; other is down)"+ );+}diff --git a/rust/ingestion-consumer/tests/transport_integration_test.rs b/rust/ingestion-consumer/tests/transport_integration_test.rsindex 05a4277b6f97..a0685b114899 100644--- a/rust/ingestion-consumer/tests/transport_integration_test.rs+++ b/rust/ingestion-consumer/tests/transport_integration_test.rs@@ -276,7 +276,7 @@ async fn transport_retries_on_worker_busy() {let elapsed = start.elapsed();assert!(- matches!(err, TransportError::WorkerBusy(_)),+ matches!(err.error, TransportError::WorkerBusy(_)),"expected WorkerBusy, got {err:?}");// One retry means one busy backoff (base 250ms + jitter), so the call must@@ -449,6 +449,7 @@ async fn dispatcher_and_transport_end_to_end() {degraded_hold: Duration::from_secs(10),min_state_duration: Duration::ZERO,probe_failure_threshold: 2,+ drain_timeout: Duration::from_secs(5),},));let dispatcher = Arc::new(Dispatcher::new(Arc::clone(®istry)));@@ -468,7 +469,7 @@ async fn dispatcher_and_transport_end_to_end() {make_message("tok", "user-3", 3, r#"{"event":"d"}"#),];- let sub_batches = dispatcher.assign(messages);+ let sub_batches = dispatcher.assign("b", messages);// Scatter to workerslet mut handles = Vec::new();@@ -483,7 +484,7 @@ async fn dispatcher_and_transport_end_to_end() {.send_batch(&worker, "batch-e2e", sub_batch.messages).await.unwrap();- d.on_sub_batch_resolved(&worker, message_count, &routing_keys);+ d.on_sub_batch_resolved(&worker, message_count, &routing_keys, false);result}));}