: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): eager per-key deferred flush to break the stash cascade (#72493)
José Sequeiracb59437ecf43
diff --git a/nodejs/tests/service-e2e/rust-ingestion-consumer.test.ts b/nodejs/tests/service-e2e/rust-ingestion-consumer.test.tsindex ef12ecdf84bf..a4867217016d 100644--- a/nodejs/tests/service-e2e/rust-ingestion-consumer.test.ts+++ b/nodejs/tests/service-e2e/rust-ingestion-consumer.test.ts@@ -405,7 +405,7 @@ describe('Rust ingestion consumer with Node ingestion API workers', () => {const exit = await rustConsumer.waitForExit(60_000)expect(exit.exitCode).not.toBe(0)- expect(exit.output).toContain('deferred messages could not be flushed within timeout')+ expect(exit.output).toContain('deferred messages made no progress within the flush timeout')await waitForTopicMessageCount(KAFKA_EVENTS_JSON, 0)} finally {await producer.disconnect()diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rsindex b3fb456fb3e8..8999d98fa4ae 100644--- a/rust/ingestion-consumer/src/config.rs+++ b/rust/ingestion-consumer/src/config.rs@@ -121,10 +121,12 @@ pub struct Config {#[envconfig(default = "500")]pub consumer_batch_timeout_ms: u64,- /// Upper bound on retrying a batch's deferred messages (held because no- /// worker was routable) before failing the batch (milliseconds). Bounds how- /// long a full worker outage holds offsets before the process exits and- /// restarts.+ /// No-progress bound on flushing a batch's deferred messages+ /// (milliseconds): the deadline resets whenever any of the batch's+ /// messages are accepted, so a slow drain keeps going and the batch only+ /// fails (exiting the process) after a full window with nothing landed —+ /// e.g. no worker routable at all. Bounds how long a genuine wedge holds+ /// offsets before the process exits and restarts.#[envconfig(default = "60000")]pub consumer_deferred_flush_timeout_ms: u64,@@ -133,6 +135,14 @@ pub struct Config {#[envconfig(from = "CONSUMER_MAX_BACKGROUND_TASKS", default = "1")]pub consumer_max_background_tasks: usize,+ /// Release a deferring key's next stashed group as soon as the send+ /// blocking it resolves, instead of waiting for the owning batch to become+ /// the oldest completed one. Breaks the deferral cascade where a hot key+ /// re-stashes on every arriving batch faster than completion-paced flushes+ /// drain it. The completion-time flush remains as backstop either way.+ #[envconfig(from = "DISPATCHER_EAGER_DEFERRED_FLUSH", default = "false")]+ pub dispatcher_eager_deferred_flush: bool,+// ---- Debug API ----/// Serve the real-time debug API (`/debug/load`, `/debug/state`,/// `/debug/events` SSE) on the health server, recording structured eventsdiff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rsindex f4d6d5b1c693..1407bfc4ba09 100644--- a/rust/ingestion-consumer/src/consumer.rs+++ b/rust/ingestion-consumer/src/consumer.rs@@ -8,13 +8,14 @@ use metrics::{counter, gauge, histogram};use rdkafka::consumer::{CommitMode, Consumer, StreamConsumer};use rdkafka::message::{Headers, Message};use rdkafka::{Offset, TopicPartitionList};+use tokio::sync::mpsc;use tokio::task::JoinHandle;use tracing::{error, info, warn};use crate::config::Config;use crate::debug_recorder::{record_if, DebugEventKind, DebugRecorder, PartitionOffset};use crate::discovery::DiscoveryMode;-use crate::dispatcher::{Dispatcher, SubBatch};+use crate::dispatcher::{Dispatcher, EagerFlush, SubBatch};use crate::order_sentinel::{CommitSentinel, OffsetSpan, SentinelContext};use crate::transport::HttpTransport;use crate::types::SerializedKafkaMessage;@@ -73,12 +74,16 @@ 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. `new` takes it from+ /// No-progress bound on flushing a batch's deferred groups: the deadline+ /// resets whenever any of the batch's messages land, and the batch fails+ /// only after a full window with zero progress. `new` takes it from/// `CONSUMER_DEFERRED_FLUSH_TIMEOUT_MS` (default 60s).pub deferred_flush_timeout: Duration,/// Debug event recorder; `None` unless `DEBUG_API_ENABLED`.pub debug_recorder: Option<Arc<DebugRecorder>>,+ /// Release a deferring key's next stashed group as soon as the send+ /// blocking it resolves (see `DISPATCHER_EAGER_DEFERRED_FLUSH`).+ pub eager_deferred_flush: bool,}/// The main consumer loop: reads from Kafka, routes messages by distinct_id@@ -100,6 +105,8 @@ pub struct IngestionConsumer {commit_sentinel: Arc<CommitSentinel>,/// Debug event recorder; `None` unless `DEBUG_API_ENABLED`.debug_recorder: Option<Arc<DebugRecorder>>,+ /// Whether to enable eager deferred flushing on the dispatcher.+ eager_deferred_flush: bool,}impl IngestionConsumer {@@ -129,6 +136,7 @@ impl IngestionConsumer {deferred_flush_timeout: options.deferred_flush_timeout,handle,group_id: options.group_id,+ eager_deferred_flush: options.eager_deferred_flush,}}@@ -183,6 +191,7 @@ impl IngestionConsumer {),handle,group_id: config.ingestion_consumer_group_id.clone(),+ eager_deferred_flush: config.dispatcher_eager_deferred_flush,})}@@ -209,6 +218,20 @@ impl IngestionConsumer {workers: self.worker_urls.clone(),});+ // Eager deferred flush: the dispatcher routes a deferring key's next+ // stashed group the moment its blocking send resolves and hands it to+ // this task to send. Aborted on drop; anything in flight at teardown+ // replays from uncommitted offsets.+ let _eager_flush_task = self.eager_deferred_flush.then(|| {+ let (tx, rx) = mpsc::unbounded_channel();+ self.dispatcher.set_eager_flush_sender(tx);+ AbortOnDrop(tokio::spawn(Self::run_eager_flush_loop(+ Arc::clone(&self.dispatcher),+ Arc::clone(&self.transport),+ rx,+ )))+ });+// Verify async commits actually land: librdkafka drops the result of// manual async commits (see the note on SentinelContext), so poll the// broker's committed offsets instead. Aborted on drop so a consumer@@ -274,6 +297,10 @@ impl IngestionConsumer {fn spawn_batch_processing(&self, collected: CollectedBatch) -> InFlightBatch {let batch_size = collected.messages.len();let batch_id = make_batch_id();+ // Register here, on the consumer loop, so the stash learns batch order+ // before the spawned tasks race: assignment and failed-send deferrals+ // can reach the stash out of batch order.+ self.dispatcher.register_batch(&batch_id);record_if(&self.debug_recorder, || DebugEventKind::BatchDispatched {batch_id: batch_id.clone(),messages: batch_size,@@ -335,6 +362,7 @@ impl IngestionConsumer {// uncommitted behind any earlier failed batch, preserving at-least-once// delivery across worker or pipeline failures.self.commit_offsets(&processed.offsets)?;+ self.dispatcher.release_batch(&batch_id);emit_latest_processed_timestamp_metrics(&processed.stats, &self.group_id);record_if(&self.debug_recorder, || DebugEventKind::BatchCommitted {batch_id: batch_id.clone(),@@ -375,48 +403,141 @@ 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.+ /// worker yet). Called serialized, oldest-first, so a key's deferred+ /// messages flush in Kafka order.+ ///+ /// `deferred_flush_timeout` bounds **stalls, not total time**: the deadline+ /// resets whenever any of the batch's messages are accepted (scatter or+ /// eager path), so a large backlog draining slowly under saturation keeps+ /// going, and the batch only fails — exiting the process and replaying —+ /// when flushing is truly wedged: nothing landed for a full timeout+ /// (nothing routable, or a flapping worker re-deferring every send).+ /// Failing the whole process for a mere slow drain amplified today's+ /// saturation: each restart replayed all its partitions into an already+ /// overloaded pool.+ ///+ /// With eager flushing enabled, some (or all) of the batch's deferred+ /// groups may instead be in flight on the eager path — the loop also waits+ /// those out, crediting their acceptances (and counting them as progress)+ /// as they land.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");+ if self.dispatcher.has_unfinished_flush(batch_id) {+ let mut stall_deadline = Instant::now() + self.deferred_flush_timeout;+ while self.dispatcher.has_unfinished_flush(batch_id) {+ if Instant::now() >= stall_deadline {+ anyhow::bail!("deferred messages made no progress within the flush timeout");+ }+ let mut accepted_this_round = 0u32;+ let sub_batches = self.dispatcher.flush_deferred(batch_id);+ if sub_batches.is_empty() {+ // Nothing routable right now (no healthy worker), or the+ // remaining work is in flight on the eager path — wait.+ tokio::select! {+ _ = self.handle.shutdown_recv() => {+ anyhow::bail!("shutdown while flushing deferred messages");+ }+ _ = tokio::time::sleep(Duration::from_millis(200)) => {}}- _ = tokio::time::sleep(Duration::from_millis(200)) => {}+ } else {+ accepted_this_round += Self::scatter(+ &self.dispatcher,+ &self.transport,+ batch_id,+ sub_batches,+ true,+ )+ .await?;+ }+ // Eager-path acceptances count as progress too — a batch whose+ // remaining groups are all draining through eager chains must+ // not time out while they are landing.+ accepted_this_round += self.dispatcher.take_eager_accepted(batch_id);+ processed.total_accepted += accepted_this_round;+ if accepted_this_round > 0 {+ stall_deadline = Instant::now() + self.deferred_flush_timeout;}- continue;}- processed.total_accepted += Self::scatter(- &self.dispatcher,- &self.transport,- batch_id,- sub_batches,- true,- )- .await?;}+ // Credit messages the eager path accepted on this batch's behalf —+ // even when nothing was deferred by completion time: a fast eager+ // chain may have drained the batch's groups before this ran.+ processed.total_accepted += self.dispatcher.take_eager_accepted(batch_id);Ok(())}+ /// Receive eagerly-released deferred groups from the dispatcher and send+ /// each on its own task. A send's resolution may release the key's next+ /// group, which arrives back on this channel — the chain advances at ACK+ /// speed instead of batch-completion speed.+ async fn run_eager_flush_loop(+ dispatcher: Arc<Dispatcher>,+ transport: Arc<HttpTransport>,+ mut rx: mpsc::UnboundedReceiver<EagerFlush>,+ ) {+ while let Some(flush) = rx.recv().await {+ let dispatcher = Arc::clone(&dispatcher);+ let transport = Arc::clone(&transport);+ tokio::spawn(async move {+ Self::send_eager_flush(dispatcher, transport, flush).await;+ });+ }+ }++ /// Send one eagerly-released sub-batch, mirroring `scatter`'s resolve+ /// protocol, and settle it in the owning batch's ledger. On failure the+ /// messages re-stash under the owning batch (before the resolve, so the+ /// pin survives) and the completion-time backstop retries them.+ async fn send_eager_flush(+ dispatcher: Arc<Dispatcher>,+ transport: Arc<HttpTransport>,+ flush: EagerFlush,+ ) {+ let EagerFlush {+ batch_id,+ sub_batch,+ } = flush;+ let worker = sub_batch.worker.clone();+ let routing_keys = sub_batch.routing_keys.clone();+ let key_offsets = sub_batch.key_offsets.clone();+ let message_count = sub_batch.messages.len();++ match transport+ .send_batch(&worker, &batch_id, sub_batch.messages, true)+ .await+ {+ Ok(accepted) => {+ dispatcher.on_sub_batch_acked(&key_offsets);+ // Credit before the resolve: the resolve may hand the batch's+ // completion the all-clear, which must already see this+ // acceptance in the ledger.+ dispatcher.eager_flush_accepted(&batch_id, accepted);+ dispatcher.on_sub_batch_resolved(+ &worker,+ message_count,+ &routing_keys,+ true,+ false,+ );+ dispatcher.record_send_outcome(&worker, false);+ }+ Err(send_err) => {+ // Re-stash before the resolve. The eager release popped the+ // group without decrementing its key's outstanding count, so+ // across defer_failed (+1) and the clears_deferral resolve+ // (-1) the count nets to unchanged and never dips to zero —+ // newer batches keep deferring behind the re-stashed group.+ dispatcher.defer_failed(&batch_id, send_err.messages);+ dispatcher.eager_flush_failed(&batch_id);+ dispatcher.on_sub_batch_resolved(&worker, message_count, &routing_keys, true, true);+ dispatcher.record_send_outcome(&worker, true);+ }+ }+ }+fn fail_batch_processing(&self, err: anyhow::Error) {error!(error = %err, "Batch processing failed");counter!("ingestion_consumer_batch_errors_total").increment(1);@@ -483,8 +604,9 @@ impl IngestionConsumer {// draining/dead (held in the dispatcher's stash, flushed at completion).let sub_batches = dispatcher.assign(&batch_id, collected.messages);- // Nothing to send and nothing deferred to wait for → no usable workers.- if sub_batches.is_empty() && !dispatcher.has_deferred(&batch_id) {+ // Nothing to send and no flush-path activity (deferred, in-flight+ // eager, or already eagerly accepted) → no usable workers.+ if sub_batches.is_empty() && !dispatcher.batch_has_flush_activity(&batch_id) {counter!("ingestion_consumer_no_healthy_workers_total").increment(1);anyhow::bail!("No healthy workers available to route batch");}@@ -541,6 +663,7 @@ impl IngestionConsumer {message_count,&routing_keys,from_flush,+ false,);dispatcher.record_send_outcome(&worker, false);accepted@@ -558,6 +681,7 @@ impl IngestionConsumer {message_count,&routing_keys,from_flush,+ true,);dispatcher.record_send_outcome(&worker, true);0diff --git a/rust/ingestion-consumer/src/debug_recorder.rs b/rust/ingestion-consumer/src/debug_recorder.rsindex a620139cb4c4..8d984790486d 100644--- a/rust/ingestion-consumer/src/debug_recorder.rs+++ b/rust/ingestion-consumer/src/debug_recorder.rs@@ -69,7 +69,8 @@ pub enum DebugEventKind {distinct_ids: usize,cleared_deferral: bool,},- /// Messages were stashed rather than sent (`reason`: drain/unroutable/send_failed).+ /// Messages were stashed rather than sent+ /// (`reason`: drain/queued_behind_deferral/unroutable/send_failed).Deferred {batch_id: String,reason: &'static str,diff --git a/rust/ingestion-consumer/src/dispatcher.rs b/rust/ingestion-consumer/src/dispatcher.rsindex 417309dc5aff..0f1d126eb7f7 100644--- a/rust/ingestion-consumer/src/dispatcher.rs+++ b/rust/ingestion-consumer/src/dispatcher.rs@@ -3,6 +3,7 @@ use std::sync::{Arc, Mutex};use k8s_awareness::PeerTracker;use metrics::{counter, gauge, histogram};+use tokio::sync::mpsc::UnboundedSender;use crate::aperture;use crate::debug_recorder::{@@ -59,6 +60,13 @@ struct PinTable {/// Messages deferred because their key's worker is draining/dead, keyed by/// batch, plus per-key outstanding counts. Flushed by `flush_deferred`.stash: Stash,+ /// Batch id → in-flight eager flush sends. A batch is not committable+ /// while it has pending eager sends: their acceptance isn't credited yet,+ /// and a failure would re-stash under the batch.+ eager_pending: HashMap<String, u32>,+ /// Batch id → messages accepted via eager flushes, credited to the batch's+ /// total at completion (`take_eager_accepted`).+ eager_accepted: HashMap<String, u32>,}impl PinTable {@@ -67,10 +75,21 @@ impl PinTable {pins: HashMap::new(),in_flight: WorkerLoad::new(),stash: Stash::new(),+ eager_pending: HashMap::new(),+ eager_accepted: HashMap::new(),}}}+/// A deferred group released eagerly when the send blocking its key resolved.+/// Sent over the eager-flush channel to the consumer, which sends it and+/// credits the acceptance to the owning batch.+pub struct EagerFlush {+ /// The batch that produced (and still owns) the deferred messages.+ pub batch_id: String,+ pub sub_batch: SubBatch,+}+struct MessageGroup {routing_key: String,messages: Vec<SerializedKafkaMessage>,@@ -193,6 +212,9 @@ pub struct Dispatcher {aperture: Option<(Arc<PeerTracker>, usize)>,/// Debug event recorder; `None` unless `DEBUG_API_ENABLED`.debug_recorder: Option<Arc<DebugRecorder>>,+ /// Channel to the consumer's eager-flush send task. `None` disables eager+ /// release (the completion-time flush then does all the draining).+ eager_flush_tx: Mutex<Option<UnboundedSender<EagerFlush>>>,}impl Dispatcher {@@ -210,6 +232,7 @@ impl Dispatcher {key_sentinel: Arc::new(KeyOrderSentinel::new()),aperture: None,debug_recorder: None,+ eager_flush_tx: Mutex::new(None),}}@@ -227,6 +250,7 @@ impl Dispatcher {key_sentinel: Arc::new(KeyOrderSentinel::new()),aperture: None,debug_recorder: None,+ eager_flush_tx: Mutex::new(None),}}@@ -249,6 +273,14 @@ impl Dispatcher {self.debug_recorder = Some(recorder);}+ /// Enable eager deferred flushing: when the send blocking a deferring key+ /// resolves, the key's next stashed group is routed immediately and handed+ /// to `tx` for the consumer to send, instead of waiting for the owning+ /// batch's completion-time flush.+ pub fn set_eager_flush_sender(&self, tx: UnboundedSender<EagerFlush>) {+ *self.eager_flush_tx.lock().unwrap() = Some(tx);+ }+/// Point-in-time load/pin/stash snapshot for the debug UI.pub fn debug_load(&self) -> DispatcherLoad {let table = self.pin_table.lock().unwrap();@@ -333,7 +365,8 @@ impl Dispatcher {.collect();let mut unpinned_groups: Vec<MessageGroup> = Vec::new();- let mut deferred_count = 0u64;+ let mut drain_deferred_count = 0u64;+ let mut cascade_deferred_count = 0u64;let mut unroutable_deferred_count = 0u64;for group in key_groups {@@ -356,6 +389,15 @@ impl Dispatcher {// 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.+ // A key that is already deferring counts as cascade+ // (queued behind its own deferred work) regardless of the+ // pinned worker's state, so the seed (drain) and the+ // amplification (cascade) are measured separately.+ if table.stash.is_deferring(&group.routing_key) {+ cascade_deferred_count += 1;+ } else {+ drain_deferred_count += 1;+ }table.stash.defer(batch_id,DeferredGroup {@@ -363,7 +405,6 @@ impl Dispatcher {messages: group.messages,},);- deferred_count += 1;}None if table.stash.is_deferring(&group.routing_key) => {// No pin, but the key already has stashed groups (it was@@ -376,7 +417,7 @@ impl Dispatcher {messages: group.messages,},);- deferred_count += 1;+ cascade_deferred_count += 1;}None => unpinned_groups.push(group),}@@ -461,12 +502,19 @@ impl Dispatcher {.increment(message_count as u64);}- if deferred_count > 0 {+ if drain_deferred_count > 0 {counter!("ingestion_consumer_dispatcher_deferred_groups_total","reason" => "drain",)- .increment(deferred_count);+ .increment(drain_deferred_count);+ }+ if cascade_deferred_count > 0 {+ counter!(+ "ingestion_consumer_dispatcher_deferred_groups_total",+ "reason" => "queued_behind_deferral",+ )+ .increment(cascade_deferred_count);}if unroutable_deferred_count > 0 {counter!(@@ -478,11 +526,18 @@ impl Dispatcher {gauge!("ingestion_consumer_dispatcher_pins_total").set(table.pins.len() as f64);record_stash_gauges(&table.stash);- if deferred_count > 0 {+ if drain_deferred_count > 0 {record_if(&self.debug_recorder, || DebugEventKind::Deferred {batch_id: batch_id.to_string(),reason: "drain",- groups: deferred_count,+ groups: drain_deferred_count,+ });+ }+ if cascade_deferred_count > 0 {+ record_if(&self.debug_recorder, || DebugEventKind::Deferred {+ batch_id: batch_id.to_string(),+ reason: "queued_behind_deferral",+ groups: cascade_deferred_count,});}if unroutable_deferred_count > 0 {@@ -496,18 +551,90 @@ impl Dispatcher {batch_id: batch_id.to_string(),distinct_ids,sub_batches: assignments.sub_batch_infos(),- deferred_groups: deferred_count,+ deferred_groups: drain_deferred_count + cascade_deferred_count,unroutable_groups: unroutable_deferred_count,});assignments.into_sub_batches()}+ /// Record a batch's arrival order for the stash. Must be called from the+ /// consumer loop in true batch order, before the batch is processed —+ /// per-batch assignment runs on spawned tasks and failed sends re-defer in+ /// gather order, so no later call site can establish the order reliably.+ pub fn register_batch(&self, batch_id: &str) {+ self.pin_table+ .lock()+ .unwrap()+ .stash+ .register_batch(batch_id);+ }++ /// Forget a fully completed (committed) batch's arrival order and any+ /// leftover ledger state.+ pub fn release_batch(&self, batch_id: &str) {+ let mut table = self.pin_table.lock().unwrap();+ table.stash.release_batch(batch_id);+ table.eager_pending.remove(batch_id);+ table.eager_accepted.remove(batch_id);+ }+/// 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 batch still has unfinished flush work: stashed groups+ /// awaiting a flush, or eager sends in flight. The batch is not+ /// committable until this is false (checked under one lock so a failing+ /// eager send can't slip its re-stash between two separate checks).+ pub fn has_unfinished_flush(&self, batch_id: &str) -> bool {+ let table = self.pin_table.lock().unwrap();+ table.stash.has_batch(batch_id) || table.eager_pending.get(batch_id).is_some_and(|&n| n > 0)+ }++ /// Whether the batch has any flush-path activity at all: stashed groups,+ /// in-flight eager sends, or already-credited eager acceptances. Used to+ /// distinguish "everything was deferred/flushed" from "nothing was+ /// routable" right after assignment.+ pub fn batch_has_flush_activity(&self, batch_id: &str) -> bool {+ let table = self.pin_table.lock().unwrap();+ table.stash.has_batch(batch_id)+ || table.eager_pending.get(batch_id).is_some_and(|&n| n > 0)+ || table.eager_accepted.get(batch_id).is_some_and(|&n| n > 0)+ }++ /// Credit an accepted eager flush to its owning batch and mark the send+ /// finished. Done atomically so the batch can't observe pending == 0+ /// before its acceptance is credited.+ pub fn eager_flush_accepted(&self, batch_id: &str, accepted: u32) {+ let mut table = self.pin_table.lock().unwrap();+ decrement_pending(&mut table.eager_pending, batch_id);+ *table+ .eager_accepted+ .entry(batch_id.to_string())+ .or_insert(0) += accepted;+ }++ /// Mark a failed eager flush finished. The caller must have re-stashed the+ /// messages via `defer_failed` first, so the batch keeps unfinished flush+ /// work and the completion-time backstop retries them.+ pub fn eager_flush_failed(&self, batch_id: &str) {+ let mut table = self.pin_table.lock().unwrap();+ decrement_pending(&mut table.eager_pending, batch_id);+ }++ /// Take (and clear) the batch's eagerly-accepted message count, credited+ /// into the batch's completion total.+ pub fn take_eager_accepted(&self, batch_id: &str) -> u32 {+ self.pin_table+ .lock()+ .unwrap()+ .eager_accepted+ .remove(batch_id)+ .unwrap_or(0)+ }+/// 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@@ -597,13 +724,12 @@ impl Dispatcher {// worker, so a key deferred across several batches re-homes to a// single survivor — preserving per-distinct_id (person-batching)// locality instead of scattering its messages across workers.- // Fall back to load-based selection for a fresh key, or when the- // pinned worker is itself unhealthy (e.g. the drainer we're leaving).- let sticky = table- .pins- .get(&group.routing_key)- .map(|pin| pin.worker.clone())- .filter(|w| healthy.contains(w));+ // Fall back to load-based selection for a fresh key, when the+ // pinned worker is itself unhealthy (e.g. the drainer we're+ // leaving), or when it is far more loaded than the rest of the+ // pool (a saturated worker bounces the flush with 503s until the+ // batch times out — see `sticky_pin_for`).+ let sticky = sticky_pin_for(&table.pins, &group.routing_key, &healthy, &working_load);let worker = match sticky {Some(worker) => worker,None => {@@ -689,12 +815,18 @@ impl Dispatcher {}}+ /// `send_failed` must be true when the resolved send failed (its messages+ /// were re-stashed via `defer_failed`): it suppresses eager release for+ /// the sub-batch's keys, leaving the retry to the completion-time flush+ /// loop's paced backoff — otherwise a flapping worker would re-release the+ /// re-stashed group on every failure in a tight loop.pub fn on_sub_batch_resolved(&self,worker: &WorkerId,message_count: usize,routing_keys: &[String],clears_deferral: bool,+ send_failed: bool,) {let mut table = self.pin_table.lock().unwrap();@@ -714,7 +846,9 @@ impl Dispatcher {}}+ let eager_tx = self.eager_flush_tx.lock().unwrap().clone();let mut evictions = 0usize;+ let mut release_keys: Vec<String> = Vec::new();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.@@ -739,10 +873,22 @@ impl Dispatcher {// its order-sentinel history has nothing left to check.self.key_sentinel.evict(key);evictions += 1;+ } else if pin.ref_count == 0 && !send_failed && eager_tx.is_some() {+ // The key's last in-flight send landed but it still has+ // stashed groups — release the oldest one now instead of+ // waiting for its batch's completion-time flush. This is+ // what breaks the deferral cascade for hot keys.+ release_keys.push(key.clone());}}}+ if let Some(tx) = eager_tx {+ if !release_keys.is_empty() {+ self.release_next_groups(&mut table, &tx, &release_keys);+ }+ }+if evictions > 0 {counter!("ingestion_consumer_dispatcher_pin_evictions_total",@@ -767,6 +913,168 @@ impl Dispatcher {pub fn record_send_outcome(&self, worker: &str, is_error: bool) {self.registry.record_outcome(worker, is_error);}++ /// Eagerly release each key's oldest stashed group: route it (sticky pin+ /// if healthy, load-based otherwise), re-pin, and hand it to the consumer's+ /// eager-send task. Called with the pin table already locked, from the+ /// resolve that dropped the key's in-flight count to zero — so per-key+ /// order holds: there is never more than one in-flight send per key.+ /// A key that can't route right now stays stashed for the completion-time+ /// backstop flush.+ fn release_next_groups(+ &self,+ table: &mut PinTable,+ tx: &UnboundedSender<EagerFlush>,+ keys: &[String],+ ) {+ let healthy = self.registry.healthy_workers();+ if healthy.is_empty() {+ return;+ }+ let mut working_load: WorkerLoad = healthy+ .iter()+ .map(|w| (w.clone(), table.in_flight.get(w).copied().unwrap_or(0)))+ .collect();+ let mut router = self.router.lock().unwrap();++ for key in keys {+ let Some((owning_batch, messages)) = table.stash.pop_next(key) else {+ continue;+ };+ let sticky = sticky_pin_for(&table.pins, key, &healthy, &working_load);+ let worker = match sticky.or_else(|| router.select(&healthy, &working_load)) {+ Some(worker) => worker,+ None => {+ table.stash.put_back(+ &owning_batch,+ DeferredGroup {+ routing_key: key.clone(),+ messages,+ },+ );+ continue;+ }+ };+ let message_count = messages.len();+ bump_load(&mut working_load, &worker, message_count);+ match table.pins.get_mut(key) {+ Some(pin) => {+ pin.worker = worker.clone();+ pin.ref_count += 1;+ }+ None => {+ table.pins.insert(+ key.clone(),+ Pin {+ worker: worker.clone(),+ ref_count: 1,+ },+ );+ }+ }+ self.key_sentinel.note_sent(key, &messages);+ let mut assignments = WorkerAssignments::new();+ assignments.add_group(+ worker.clone(),+ MessageGroup {+ routing_key: key.clone(),+ messages,+ },+ );+ *table.in_flight.entry(worker.clone()).or_insert(0) += message_count;+ *table.eager_pending.entry(owning_batch.clone()).or_insert(0) += 1;+ counter!(+ "ingestion_consumer_dispatcher_deferred_flushed_total",+ "worker" => worker.to_string(),+ )+ .increment(message_count as u64);+ let infos = assignments.sub_batch_infos();+ let sub_batch = assignments+ .into_sub_batches()+ .pop()+ .expect("one group produces one sub-batch");+ if let Err(err) = tx.send(EagerFlush {+ batch_id: owning_batch.clone(),+ sub_batch,+ }) {+ // Receiver gone (shutdown) — roll back so nothing is counted+ // as in flight; the messages replay after restart anyway.+ let EagerFlush {+ batch_id,+ sub_batch,+ } = err.0;+ decrement_pending(&mut table.eager_pending, &batch_id);+ if let Some(load) = table.in_flight.get_mut(&sub_batch.worker) {+ *load = load.saturating_sub(sub_batch.messages.len());+ }+ if let Some(pin) = table.pins.get_mut(key) {+ pin.ref_count = pin.ref_count.saturating_sub(1);+ }+ table.stash.put_back(+ &batch_id,+ DeferredGroup {+ routing_key: key.clone(),+ messages: sub_batch.messages,+ },+ );+ continue;+ }+ record_if(&self.debug_recorder, || DebugEventKind::DeferredFlushed {+ batch_id: owning_batch.clone(),+ sub_batches: infos,+ });+ }+ record_stash_gauges(&table.stash);+ }+}++/// Decrement a batch's pending eager-send count, dropping the entry at zero.+fn decrement_pending(pending: &mut HashMap<String, u32>, batch_id: &str) {+ if let Some(n) = pending.get_mut(batch_id) {+ *n = n.saturating_sub(1);+ if *n == 0 {+ pending.remove(batch_id);+ }+ }+}++/// Cap on how much more loaded a pinned worker may be than the least-loaded+/// healthy worker before a flush abandons stickiness. Beyond+/// `min_load * FACTOR + SLACK` in-flight messages the pin is ignored and the+/// group routes by load: a worker at its concurrency cap keeps 503ing the+/// flush until the batch's deferred-flush timeout kills the process, so+/// locality yields to load once the gap is this large. The slack keeps small+/// absolute gaps sticky — an idle candidate (min 0) must not disqualify a pin+/// holding a few hundred messages.+const STICKY_PIN_LOAD_FACTOR: usize = 2;+const STICKY_PIN_LOAD_SLACK: usize = 500;++/// The key's pinned worker, if the pin may be honored for a flush: it must be+/// healthy and not drastically more loaded than the least-loaded candidate+/// (see `STICKY_PIN_LOAD_FACTOR`). Only consulted at flush/eager-release+/// time, when the key has no send in flight — so declining the pin and+/// routing elsewhere cannot reorder the key.+fn sticky_pin_for(+ pins: &HashMap<String, Pin>,+ routing_key: &str,+ healthy: &[WorkerId],+ working_load: &WorkerLoad,+) -> Option<WorkerId> {+ let worker = pins.get(routing_key).map(|pin| pin.worker.clone())?;+ if !healthy.contains(&worker) {+ return None;+ }+ let pinned_load = working_load.get(&worker).copied().unwrap_or(0);+ let min_load = healthy+ .iter()+ .map(|w| working_load.get(w).copied().unwrap_or(0))+ .min()+ .unwrap_or(0);+ if pinned_load > min_load.saturating_mul(STICKY_PIN_LOAD_FACTOR) + STICKY_PIN_LOAD_SLACK {+ counter!("ingestion_consumer_dispatcher_sticky_pin_overrides_total").increment(1);+ return None;+ }+ Some(worker)}/// Add `count` to a worker's working load for this round, if it is a candidate.@@ -1066,6 +1374,7 @@ mod tests {batch1[0].messages.len(),&batch1[0].routing_keys,false,+ false,);// Both user-1 messages merge into one sub-batch.@@ -1121,7 +1430,13 @@ mod tests {.pins.contains_key("t:user-1"));- dispatcher.on_sub_batch_resolved(&worker, b1[0].messages.len(), &b1[0].routing_keys, false);+ dispatcher.on_sub_batch_resolved(+ &worker,+ b1[0].messages.len(),+ &b1[0].routing_keys,+ false,+ false,+ );assert!(!dispatcher.pin_table@@ -1147,7 +1462,13 @@ mod tests {);// 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, false);+ dispatcher.on_sub_batch_resolved(+ &worker,+ b1[0].messages.len(),+ &b1[0].routing_keys,+ false,+ false,+ );{let table = dispatcher.pin_table.lock().unwrap();assert!(table.pins.contains_key("t:user-1"));@@ -1177,7 +1498,13 @@ mod tests {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, false);+ dispatcher.on_sub_batch_resolved(+ &worker,+ b1[0].messages.len(),+ &b1[0].routing_keys,+ false,+ false,+ );assert_eq!(in_flight_of(&dispatcher, &worker), 0);}@@ -1280,6 +1607,7 @@ mod tests {b1[0].messages.len(),&b1[0].routing_keys,false,+ false,);let b2 = dispatcher.assign("b", make_msgs(&[("t", "user-1")]));@@ -1595,6 +1923,7 @@ mod tests {f1[0].messages.len(),&f1[0].routing_keys,true,+ false,);let f2 = dispatcher.flush_deferred("batch-2");assert_eq!(f2.len(), 1);@@ -1623,6 +1952,274 @@ mod tests {assert!(dispatcher.has_deferred("batch-2"));}+ #[test]+ fn test_deferral_reason_splits_drain_seed_from_cascade() {+ let registry = healthy_registry(2);+ let mut dispatcher = Dispatcher::new(Arc::clone(®istry));+ let recorder = DebugRecorder::new(100, Duration::from_secs(60));+ dispatcher.set_debug_recorder(Arc::clone(&recorder));++ // Pin user-1, then drain its worker.+ let b1 = dispatcher.assign("batch-1", make_msgs(&[("t", "user-1")]));+ registry.start_draining(&b1[0].worker);++ // First deferral: pin points at a drainer, nothing stashed yet — seed.+ assert!(dispatcher+ .assign("batch-2", make_msgs(&[("t", "user-1")]))+ .is_empty());+ // Second deferral: the key is already deferring — cascade, even though+ // the pinned worker is still draining.+ assert!(dispatcher+ .assign("batch-3", make_msgs(&[("t", "user-1")]))+ .is_empty());++ let reasons: Vec<_> = recorder+ .backlog()+ .into_iter()+ .filter_map(|e| match e.kind {+ DebugEventKind::Deferred { reason, groups, .. } => Some((reason, groups)),+ _ => None,+ })+ .collect();+ assert_eq!(+ reasons,+ vec![("drain", 1), ("queued_behind_deferral", 1)],+ "seed defers as drain, subsequent deferrals as queued_behind_deferral"+ );+ }++ /// Resolve a previously received eager flush as accepted, the way+ /// `send_eager_flush` does, and return whatever it released next.+ fn resolve_eager_flush(+ dispatcher: &Dispatcher,+ flush: &EagerFlush,+ rx: &mut tokio::sync::mpsc::UnboundedReceiver<EagerFlush>,+ ) -> Option<EagerFlush> {+ dispatcher.eager_flush_accepted(&flush.batch_id, flush.sub_batch.messages.len() as u32);+ dispatcher.on_sub_batch_resolved(+ &flush.sub_batch.worker,+ flush.sub_batch.messages.len(),+ &flush.sub_batch.routing_keys,+ true,+ false,+ );+ rx.try_recv().ok()+ }++ #[test]+ fn test_eager_release_chains_at_ack_speed_across_uncompleted_batches() {+ // The cascade-breaker: a hot key stashed by several in-flight batches+ // drains group-by-group on each ACK, without any of those batches+ // completing.+ let registry = healthy_registry(2);+ let dispatcher = Dispatcher::new(Arc::clone(®istry));+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();+ dispatcher.set_eager_flush_sender(tx);++ let b1 = dispatcher.assign("batch-1", make_msgs(&[("t", "k")]));+ let pinned = b1[0].worker.clone();+ registry.start_draining(&pinned);+ for batch in ["batch-2", "batch-3", "batch-4"] {+ assert!(dispatcher+ .assign(batch, make_msgs(&[("t", "k")]))+ .is_empty());+ }++ // Resolving the blocking send releases the oldest stashed group+ // immediately — no batch completion involved.+ dispatcher.on_sub_batch_resolved(&pinned, 1, &b1[0].routing_keys, false, false);+ let f2 = rx.try_recv().expect("resolve releases the next group");+ assert_eq!(f2.batch_id, "batch-2");+ assert_ne!(f2.sub_batch.worker, pinned, "routed off the drainer");+ assert!(rx.try_recv().is_err(), "at most one in-flight send per key");+ assert!(!dispatcher.has_deferred("batch-2"));+ assert!(+ dispatcher.has_unfinished_flush("batch-2"),+ "owning batch waits on the pending eager send"+ );++ // Each ACK releases the next batch's group, oldest first.+ let f3 = resolve_eager_flush(&dispatcher, &f2, &mut rx).expect("batch-3 group");+ assert_eq!(f3.batch_id, "batch-3");+ assert_eq!(f3.sub_batch.worker, f2.sub_batch.worker, "stays sticky");+ let f4 = resolve_eager_flush(&dispatcher, &f3, &mut rx).expect("batch-4 group");+ assert_eq!(f4.batch_id, "batch-4");+ assert!(+ resolve_eager_flush(&dispatcher, &f4, &mut rx).is_none(),+ "stash drained"+ );++ // The chain fully cleared the deferral: pin evicted, ledgers credited.+ assert_eq!(dispatcher.pin_count(), 0);+ for batch in ["batch-2", "batch-3", "batch-4"] {+ assert!(!dispatcher.has_unfinished_flush(batch));+ assert_eq!(dispatcher.take_eager_accepted(batch), 1);+ }+ }++ #[test]+ fn test_eager_release_without_healthy_worker_leaves_group_stashed() {+ let registry = healthy_registry(2);+ let dispatcher = Dispatcher::new(Arc::clone(®istry));+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();+ dispatcher.set_eager_flush_sender(tx);++ let b1 = dispatcher.assign("batch-1", make_msgs(&[("t", "k")]));+ let pinned = b1[0].worker.clone();+ registry.start_draining(&pinned);+ assert!(dispatcher+ .assign("batch-2", make_msgs(&[("t", "k")]))+ .is_empty());++ // Drain the survivor too — nothing is routable at resolve time.+ for worker in registry.workers() {+ registry.start_draining(&worker);+ }+ dispatcher.on_sub_batch_resolved(&pinned, 1, &b1[0].routing_keys, false, false);++ assert!(rx.try_recv().is_err(), "nothing released");+ assert!(+ dispatcher.has_deferred("batch-2"),+ "group stays stashed for the completion-time backstop"+ );+ }++ #[test]+ fn test_failed_send_does_not_eagerly_retry() {+ // A failed send re-stashes its messages; the following resolve must+ // not re-release them immediately (that would hot-loop against a+ // flapping worker) — the paced completion-time flush retries instead.+ let registry = healthy_registry(2);+ let dispatcher = Dispatcher::new(Arc::clone(®istry));+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();+ dispatcher.set_eager_flush_sender(tx);++ let b1 = dispatcher.assign("batch-1", make_msgs(&[("t", "k")]));+ let pinned = b1[0].worker.clone();+ registry.start_draining(&pinned);+ assert!(dispatcher+ .assign("batch-2", make_msgs(&[("t", "k")]))+ .is_empty());++ dispatcher.on_sub_batch_resolved(&pinned, 1, &b1[0].routing_keys, false, false);+ let flush = rx.try_recv().expect("group released");++ // The eager send fails, mirroring `send_eager_flush`'s failure path.+ dispatcher.defer_failed(&flush.batch_id, flush.sub_batch.messages);+ dispatcher.eager_flush_failed(&flush.batch_id);+ dispatcher.on_sub_batch_resolved(+ &flush.sub_batch.worker,+ 1,+ &flush.sub_batch.routing_keys,+ true,+ true,+ );++ assert!(rx.try_recv().is_err(), "no immediate eager retry");+ assert!(+ dispatcher.has_unfinished_flush("batch-2"),+ "re-stashed for the backstop, batch not committable"+ );+ let backstop = dispatcher.flush_deferred("batch-2");+ assert_eq!(backstop.len(), 1, "completion-time flush retries the group");+ }++ /// Pin key K, then load its worker far above the other one via unresolved+ /// sends of other keys, and put K's group in the stash via a failed send.+ /// Returns (dispatcher, pinned_worker, other_worker); K's group is stashed+ /// under "b0" with no send in flight, the pinned worker holding 600+ /// unresolved messages.+ fn saturated_sticky_setup() -> (Dispatcher, WorkerId, WorkerId) {+ let registry = healthy_registry(2);+ let dispatcher = Dispatcher::new(Arc::clone(®istry));++ let b0 = dispatcher.assign("b0", make_msgs(&[("t", "k")]));+ let pinned = b0[0].worker.clone();++ // Load the OTHER worker so the next 600-message key lands on the+ // pinned one (bin-packing places on the least-loaded worker).+ let b1 = dispatcher.assign("b1", make_msgs(&vec![("t", "b"); 500]));+ let other = b1[0].worker.clone();+ assert_ne!(other, pinned);+ let b2 = dispatcher.assign("b2", make_msgs(&vec![("t", "d"); 600]));+ assert_eq!(+ b2[0].worker, pinned,+ "600-msg key lands on the pinned worker"+ );++ // K's send fails: its group re-stashes, nothing for K is in flight.+ dispatcher.defer_failed("b0", make_msgs(&[("t", "k")]));+ dispatcher.on_sub_batch_resolved(&pinned, 1, &b0[0].routing_keys, false, true);++ (dispatcher, pinned, other)+ }++ #[test]+ fn test_flush_overrides_sticky_pin_on_saturated_worker() {+ let (dispatcher, _pinned, other) = saturated_sticky_setup();++ // The other worker's send resolves — it is now idle while the pinned+ // worker still holds 600 unresolved messages.+ dispatcher.on_sub_batch_resolved(&other, 500, &["t:b".to_string()], false, false);++ let flushed = dispatcher.flush_deferred("b0");+ assert_eq!(flushed.len(), 1);+ assert_eq!(+ flushed[0].worker, other,+ "flush must abandon the saturated sticky pin for the idle worker"+ );+ }++ #[test]+ fn test_flush_keeps_sticky_pin_when_loads_comparable() {+ let (dispatcher, pinned, _other) = saturated_sticky_setup();++ // Both workers still loaded (600 vs 500) — locality wins.+ let flushed = dispatcher.flush_deferred("b0");+ assert_eq!(flushed.len(), 1);+ assert_eq!(+ flushed[0].worker, pinned,+ "comparable loads keep the sticky pin for person-batching locality"+ );+ }++ #[test]+ fn test_eager_release_overrides_saturated_sticky_pin() {+ let registry = healthy_registry(2);+ let dispatcher = Dispatcher::new(Arc::clone(®istry));+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();+ dispatcher.set_eager_flush_sender(tx);++ let b0 = dispatcher.assign("b0", make_msgs(&[("t", "k")]));+ let pinned = b0[0].worker.clone();+ let b2 = dispatcher.assign("b2", make_msgs(&vec![("t", "d"); 600]));+ let other = b2[0].worker.clone();+ assert_ne!(other, pinned);+ let b3 = dispatcher.assign("b3", make_msgs(&vec![("t", "e"); 700]));+ assert_eq!(+ b3[0].worker, pinned,+ "700-msg key lands on the pinned worker"+ );++ // A second K send is honored onto the pin, fails, and re-stashes; the+ // resolve is marked failed so nothing releases yet.+ let b1 = dispatcher.assign("b1", make_msgs(&[("t", "k")]));+ assert_eq!(b1[0].worker, pinned);+ dispatcher.defer_failed("b1", make_msgs(&[("t", "k")]));+ dispatcher.on_sub_batch_resolved(&pinned, 1, &b1[0].routing_keys, false, true);+ // The other worker drains fully; the pinned one still holds 700.+ dispatcher.on_sub_batch_resolved(&other, 600, &["t:d".to_string()], false, false);++ // K's original send resolves cleanly → eager release fires, and must+ // route off the saturated pin.+ dispatcher.on_sub_batch_resolved(&pinned, 1, &b0[0].routing_keys, false, false);+ let flush = rx.try_recv().expect("eager release fires");+ assert_eq!(+ flush.sub_batch.worker, other,+ "eager release must abandon the saturated sticky pin"+ );+ }+#[tokio::test]async fn test_pinned_key_defers_off_dead_worker() {let registry = healthy_registry(2);@@ -1659,7 +2256,13 @@ mod tests {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);+ dispatcher.on_sub_batch_resolved(+ &pinned,+ b1[0].messages.len(),+ &b1[0].routing_keys,+ false,+ false,+ );// Flushing batch-2 re-routes the deferred group onto the surviving worker.let flushed = dispatcher.flush_deferred("batch-2");@@ -1688,7 +2291,13 @@ mod tests {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);+ dispatcher.on_sub_batch_resolved(+ &pinned,+ b1[0].messages.len(),+ &b1[0].routing_keys,+ false,+ false,+ );let flushed = dispatcher.flush_deferred("batch-2");assert_eq!(flushed.len(), 1);@@ -1728,7 +2337,13 @@ mod tests {// 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);+ dispatcher.on_sub_batch_resolved(+ &pinned,+ b1[0].messages.len(),+ &b1[0].routing_keys,+ false,+ false,+ );assert_eq!(dispatcher.pin_count(),1,@@ -1751,7 +2366,13 @@ mod tests {// 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);+ dispatcher.on_sub_batch_resolved(+ &worker,+ b1[0].messages.len(),+ &b1[0].routing_keys,+ false,+ false,+ );assert!(dispatcher.has_deferred("batch-1"),@@ -1799,7 +2420,13 @@ mod tests {// 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);+ dispatcher.on_sub_batch_resolved(+ &pinned,+ b1[0].messages.len(),+ &b1[0].routing_keys,+ false,+ false,+ );for batch in ["batch-2", "batch-3"] {let flushed = dispatcher.flush_deferred(batch);assert_eq!(flushed.len(), 1);@@ -1808,6 +2435,7 @@ mod tests {flushed[0].messages.len(),&flushed[0].routing_keys,true,+ false,);}assert!(!dispatcher.has_deferred("batch-2") && !dispatcher.has_deferred("batch-3"));@@ -1834,7 +2462,13 @@ mod tests {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);+ dispatcher.on_sub_batch_resolved(+ &pinned,+ b1[0].messages.len(),+ &b1[0].routing_keys,+ false,+ false,+ );let flushed = dispatcher.flush_deferred("batch-2");assert_eq!(flushed.len(), 1);@@ -1851,6 +2485,7 @@ mod tests {flushed[0].messages.len(),&flushed[0].routing_keys,true,+ false,);// 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.@@ -1861,6 +2496,7 @@ mod tests {f3[0].messages.len(),&f3[0].routing_keys,true,+ false,);let b4 = dispatcher.assign("batch-4", make_msgs(&[("t", "user-1")]));assert_eq!(@@ -1890,7 +2526,13 @@ mod tests {);// Drain finishes when batch-1's in-flight resolves.- dispatcher.on_sub_batch_resolved(&pinned, b1[0].messages.len(), &b1[0].routing_keys, false);+ dispatcher.on_sub_batch_resolved(+ &pinned,+ b1[0].messages.len(),+ &b1[0].routing_keys,+ false,+ false,+ );// Flush oldest-first (as complete_oldest_batch does): each batch yields// only its own message, in Kafka offset order.@@ -1925,7 +2567,13 @@ mod tests {.is_empty());// Drain completes when batch-1's in-flight resolves.- dispatcher.on_sub_batch_resolved(&pinned, b1[0].messages.len(), &b1[0].routing_keys, false);+ dispatcher.on_sub_batch_resolved(+ &pinned,+ b1[0].messages.len(),+ &b1[0].routing_keys,+ false,+ false,+ );// Flush oldest-first. batch-2 re-homes user-1 onto a survivor; batch-3 must// land on the SAME survivor. Without the fix, batch-2's flush bumps that@@ -1963,7 +2611,13 @@ mod tests {);// 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);+ dispatcher.on_sub_batch_resolved(+ &worker,+ b[0].messages.len(),+ &b[0].routing_keys,+ false,+ false,+ );assert_eq!(registry.reapable_workers(), vec![worker]);}diff --git a/rust/ingestion-consumer/src/stash.rs b/rust/ingestion-consumer/src/stash.rsindex ff6471de9cdc..4c87a4de2e97 100644--- a/rust/ingestion-consumer/src/stash.rs+++ b/rust/ingestion-consumer/src/stash.rs@@ -7,10 +7,18 @@//! 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);+//! Entries are held in a per-routing-key FIFO ordered by **batch sequence** —+//! the arrival order of the batch that produced them, assigned via+//! [`Stash::register_batch`] on the consumer loop before any deferral for the+//! batch can occur. Batch ids themselves (timestamp + random) are not+//! sortable, and deferrals can arrive out of batch order (`defer_failed` lands+//! in send-gather order), so insertion order can't be trusted; the sequence+//! can.+//!+//! Besides the queues, the stash keeps:+//! - a per-batch live-entry count, 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@@ -21,7 +29,7 @@//! 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 std::collections::{HashMap, VecDeque};use crate::types::SerializedKafkaMessage;@@ -38,10 +46,22 @@ impl DeferredGroup {}}+struct Entry {+ batch_seq: u64,+ batch_id: String,+ messages: Vec<SerializedKafkaMessage>,+}+#[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: deferred entries ordered by batch sequence (oldest first).+ queues: HashMap<String, VecDeque<Entry>>,+ /// Batch id → arrival sequence, assigned by `register_batch` (or lazily on+ /// first deferral for callers that don't register, e.g. tests).+ batch_seqs: HashMap<String, u64>,+ next_seq: u64,+ /// Batch id → number of entries currently stashed for it.+ batch_live: HashMap<String, usize>,/// Per routing key: how many deferred groups are outstanding (not yet routed).outstanding: HashMap<String, u32>,}@@ -51,16 +71,59 @@ impl Stash {Self::default()}+ /// Record `batch_id`'s arrival order. Must be called in true batch order+ /// (i.e. from the consumer loop, before the batch is processed) — the+ /// sequence orders a key's entries across batches, so a later deferral for+ /// an older batch still queues ahead of a newer batch's entries.+ pub fn register_batch(&mut self, batch_id: &str) {+ if !self.batch_seqs.contains_key(batch_id) {+ self.batch_seqs.insert(batch_id.to_string(), self.next_seq);+ self.next_seq += 1;+ }+ }++ /// Forget a completed batch's sequence. Call once the batch is fully done+ /// (committed) — no further deferral for it can occur after that.+ pub fn release_batch(&mut self, batch_id: &str) {+ self.batch_seqs.remove(batch_id);+ }++ fn seq_for(&mut self, batch_id: &str) -> u64 {+ if let Some(&seq) = self.batch_seqs.get(batch_id) {+ return seq;+ }+ let seq = self.next_seq;+ self.next_seq += 1;+ self.batch_seqs.insert(batch_id.to_string(), seq);+ seq+ }++ fn insert_entry(&mut self, routing_key: &str, entry: Entry) {+ *self.batch_live.entry(entry.batch_id.clone()).or_insert(0) += 1;+ let queue = self.queues.entry(routing_key.to_string()).or_default();+ // Ordered by batch_seq, stable for equal seqs; append is the common case.+ let pos = queue+ .iter()+ .rposition(|e| e.batch_seq <= entry.batch_seq)+ .map_or(0, |i| i + 1);+ queue.insert(pos, entry);+ }+/// Defer a group produced by `batch_id`, bumping its key's outstanding count.pub fn defer(&mut self, batch_id: &str, group: DeferredGroup) {+ let batch_seq = self.seq_for(batch_id);*self.outstanding.entry(group.routing_key.clone()).or_insert(0) += 1;- self.by_batch- .entry(batch_id.to_string())- .or_default()- .push(group);+ self.insert_entry(+ &group.routing_key,+ Entry {+ batch_seq,+ batch_id: batch_id.to_string(),+ messages: group.messages,+ },+ );}/// Whether the key currently has any outstanding deferred groups. New@@ -72,7 +135,7 @@ impl Stash {/// 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)+ self.batch_live.get(batch_id).is_some_and(|&n| n > 0)}/// Remove and return a batch's deferred groups so the caller can try to@@ -80,15 +143,56 @@ impl Stash {/// 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()+ let mut taken = Vec::new();+ self.queues.retain(|routing_key, queue| {+ let mut i = 0;+ while i < queue.len() {+ if queue[i].batch_id == batch_id {+ let entry = queue.remove(i).expect("index in bounds");+ taken.push(DeferredGroup {+ routing_key: routing_key.clone(),+ messages: entry.messages,+ });+ } else {+ i += 1;+ }+ }+ !queue.is_empty()+ });+ self.batch_live.remove(batch_id);+ taken+ }++ /// Pop the key's oldest deferred entry for eager release, returning the+ /// owning batch id and the messages. Does not change the outstanding+ /// count — the caller is routing the group now, and [`Stash::completed`]+ /// fires when its send resolves, exactly as with [`Stash::take_batch`].+ pub fn pop_next(&mut self, routing_key: &str) -> Option<(String, Vec<SerializedKafkaMessage>)> {+ let queue = self.queues.get_mut(routing_key)?;+ let entry = queue.pop_front()?;+ if queue.is_empty() {+ self.queues.remove(routing_key);+ }+ match self.batch_live.get_mut(&entry.batch_id) {+ Some(n) if *n > 1 => *n -= 1,+ _ => {+ self.batch_live.remove(&entry.batch_id);+ }+ }+ Some((entry.batch_id, entry.messages))}/// 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);+ let batch_seq = self.seq_for(batch_id);+ self.insert_entry(+ &group.routing_key,+ Entry {+ batch_seq,+ batch_id: batch_id.to_string(),+ messages: group.messages,+ },+ );}/// Mark one deferred group for `routing_key` as routed — decrements the@@ -104,24 +208,24 @@ impl Stash {/// Total deferred groups currently stashed (for metrics/tests).pub fn len(&self) -> usize {- self.by_batch.values().map(Vec::len).sum()+ self.queues.values().map(VecDeque::len).sum()}pub fn is_empty(&self) -> bool {- self.by_batch.is_empty()+ self.queues.is_empty()}/// Number of batches that currently have deferred groups awaiting flush.pub fn batch_count(&self) -> usize {- self.by_batch.len()+ self.batch_live.len()}/// Total deferred messages currently stashed across all batches and groups.pub fn message_count(&self) -> usize {- self.by_batch+ self.queues.values()- .flat_map(|groups| groups.iter())- .map(DeferredGroup::message_count)+ .flat_map(|queue| queue.iter())+ .map(|entry| entry.messages.len()).sum()}}@@ -255,4 +359,45 @@ mod tests {assert_eq!(stash.batch_count(), 1);assert_eq!(stash.message_count(), 3);}++ #[test]+ fn test_late_deferral_for_registered_older_batch_queues_ahead() {+ // batch-1 arrives before batch-2 (registration order), but its+ // deferral lands later (a failed send re-defers after the newer batch+ // already stashed). The older batch's entry must still queue ahead of+ // the newer batch's for the same key.+ let mut stash = Stash::new();+ stash.register_batch("batch-1");+ stash.register_batch("batch-2");++ stash.defer("batch-2", group("t:a", 1));+ stash.defer("batch-1", group("t:a", 2));++ let (batch_id, messages) = stash.pop_next("t:a").unwrap();+ assert_eq!(batch_id, "batch-1", "older batch pops first");+ assert_eq!(messages.len(), 2);+ let (batch_id, _) = stash.pop_next("t:a").unwrap();+ assert_eq!(batch_id, "batch-2");+ assert!(stash.pop_next("t:a").is_none());+ }++ #[test]+ fn test_pop_next_keeps_outstanding_until_completed() {+ let mut stash = Stash::new();+ stash.defer("batch-1", group("t:a", 1));++ let (batch_id, _) = stash.pop_next("t:a").unwrap();+ assert_eq!(batch_id, "batch-1");+ assert!(+ !stash.has_batch("batch-1"),+ "popped entry no longer counts toward its batch"+ );+ assert!(+ stash.is_deferring("t:a"),+ "popping for a flush attempt must not clear the outstanding count"+ );++ stash.completed("t:a");+ assert!(!stash.is_deferring("t:a"));+ }}diff --git a/rust/ingestion-consumer/tests/dispatcher_integration_test.rs b/rust/ingestion-consumer/tests/dispatcher_integration_test.rsindex 878f9e9d2301..2f9e588a8f6e 100644--- a/rust/ingestion-consumer/tests/dispatcher_integration_test.rs+++ b/rust/ingestion-consumer/tests/dispatcher_integration_test.rs@@ -235,7 +235,13 @@ async fn test_pinned_key_rerouted_after_dead_declaration() {// 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);+ dispatcher.on_sub_batch_resolved(+ &pinned_to,+ b1[0].messages.len(),+ &b1[0].routing_keys,+ false,+ 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")]);@@ -368,6 +374,7 @@ async fn test_three_workers_one_dies_and_load_rebalances() {w1_sub.messages.len(),&w1_sub.routing_keys,false,+ false,);// The key that was pinned to w1 must re-route to w0 or w2 on its next assign.@@ -465,7 +472,13 @@ async fn test_draining_worker_defers_then_flushes_to_survivor() {);// Resolve batch-1: the drainer finishes and becomes reapable.- dispatcher.on_sub_batch_resolved(&pinned, b1[0].messages.len(), &b1[0].routing_keys, false);+ dispatcher.on_sub_batch_resolved(+ &pinned,+ b1[0].messages.len(),+ &b1[0].routing_keys,+ false,+ false,+ );assert_eq!(registry.reapable_workers(), vec![pinned.clone()]);// Flushing batch-2 reroutes the deferred key onto the surviving worker.diff --git a/rust/ingestion-consumer/tests/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rsindex 1dc263e637ff..ea50a2cbc50b 100644--- a/rust/ingestion-consumer/tests/e2e_integration_test.rs+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs@@ -488,6 +488,7 @@ impl Harness {group_id: "e2e-test".to_string(),deferred_flush_timeout,debug_recorder: None,+ eager_deferred_flush: false,},handle,);@@ -564,6 +565,7 @@ impl Harness {group_id: "e2e-test".to_string(),deferred_flush_timeout: self.deferred_flush_timeout,debug_recorder: None,+ eager_deferred_flush: false,},handle,);@@ -1294,6 +1296,7 @@ async fn drain_defer_flush_delivers_to_survivor_over_http() {b1[0].messages.len(),&b1[0].routing_keys,false,+ false,);let f2 = dispatcher.flush_deferred("batch-2");assert_eq!(f2.len(), 1);@@ -2037,6 +2040,7 @@ async fn second_consumer_joining_the_group_preserves_all_messages() {group_id: "e2e-test".to_string(),deferred_flush_timeout: Duration::from_secs(60),debug_recorder: None,+ eager_deferred_flush: false,},handle2,);@@ -2113,6 +2117,7 @@ async fn fenced_static_member_exits_on_fatal_error() {group_id: "e2e-test".to_string(),deferred_flush_timeout: Duration::from_secs(60),debug_recorder: None,+ eager_deferred_flush: false,},handle,);diff --git a/rust/ingestion-consumer/tests/transport_integration_test.rs b/rust/ingestion-consumer/tests/transport_integration_test.rsindex a574e38f3090..8c7914b9b9f1 100644--- a/rust/ingestion-consumer/tests/transport_integration_test.rs+++ b/rust/ingestion-consumer/tests/transport_integration_test.rs@@ -479,7 +479,7 @@ async fn dispatcher_and_transport_end_to_end() {.send_batch(&worker, "batch-e2e", sub_batch.messages, false).await.unwrap();- d.on_sub_batch_resolved(&worker, message_count, &routing_keys, false);+ d.on_sub_batch_resolved(&worker, message_count, &routing_keys, false, false);result}));}diff --git a/rust/ingestion-control-plane/src/ui/consumer_debug.html b/rust/ingestion-control-plane/src/ui/consumer_debug.htmlindex 78d2f6e6b29d..683583ae1a96 100644--- a/rust/ingestion-control-plane/src/ui/consumer_debug.html+++ b/rust/ingestion-control-plane/src/ui/consumer_debug.html@@ -564,7 +564,7 @@function buildFlow(b, workers) {const idx = {};workers.forEach((w, i) => (idx[w.worker] = i));- const deferBy = { drain: 0, unroutable: 0, send_failed: 0 };+ const deferBy = { drain: 0, queued_behind_deferral: 0, unroutable: 0, send_failed: 0 };b.deferred.forEach((d) => (deferBy[d.reason] = (deferBy[d.reason] || 0) + d.groups));const hasStash = b.deferred.length > 0;const totalDeferred = b.deferred.reduce((a, d) => a + d.groups, 0);@@ -626,9 +626,9 @@if (hasStash) {let incoming = 0;- const da = deferBy.drain + deferBy.unroutable;+ const da = deferBy.drain + deferBy.queued_behind_deferral + deferBy.unroutable;if (da > 0) {- const lbl = [deferBy.drain ? "drain" : "", deferBy.unroutable ? "unroutable" : ""].filter(Boolean).join("/");+ const lbl = [deferBy.drain ? "drain" : "", deferBy.queued_behind_deferral ? "queued" : "", deferBy.unroutable ? "unroutable" : ""].filter(Boolean).join("/");edges.push({ from: "n-assign", to: "n-stash", label: `deferred (${lbl})`, color: C.warn });incoming++;}