Skip to content

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

chore(ingestion-consumer): remove eager deferred flush (#92402)

Paweł Ledwońb3eb9c8aecc2
diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rs
index fd6e7aee586d..9b125369722c 100644
--- a/rust/ingestion-consumer/src/config.rs
+++ b/rust/ingestion-consumer/src/config.rs
@@ -168,14 +168,6 @@ 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 events
diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rs
index cec689f7843d..4a459b8b20e4 100644
--- a/rust/ingestion-consumer/src/consumer.rs
+++ b/rust/ingestion-consumer/src/consumer.rs
@@ -9,14 +9,13 @@ 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, EagerFlush, KeyOffset, SubBatch};
+use crate::dispatcher::{Dispatcher, KeyOffset, SubBatch};
use crate::grpc_transport::{GrpcTransport, PendingWorkerStreamSend};
use crate::order_sentinel::{CommitSentinel, OffsetSpan, SentinelContext};
use crate::transport::SendError;
@@ -97,9 +96,6 @@ pub struct IngestionConsumerOptions {
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 Kafka key
@@ -122,8 +118,6 @@ 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 {
@@ -154,7 +148,6 @@ impl IngestionConsumer {
deferred_flush_timeout: options.deferred_flush_timeout,
handle,
group_id: options.group_id,
- eager_deferred_flush: options.eager_deferred_flush,
}
}
@@ -219,7 +212,6 @@ impl IngestionConsumer {
),
handle,
group_id: config.ingestion_consumer_group_id.clone(),
- eager_deferred_flush: config.dispatcher_eager_deferred_flush,
})
}
@@ -246,20 +238,6 @@ 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
@@ -458,19 +436,14 @@ impl IngestionConsumer {
/// 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
+ /// resets whenever any of the batch's messages are accepted, so a large
+ /// backlog draining slowly under saturation keeps
/// going, and the batch only fails — exiting the process and replaying —
/// when flushing is truly wedged: nothing landed for a full timeout
/// (nothing routable, or a flapping worker re-deferring every send).
/// Failing the whole process for a mere slow drain amplified today's
/// saturation: each restart replayed all its partitions into an already
/// overloaded pool.
- ///
- /// 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,
@@ -491,8 +464,7 @@ impl IngestionConsumer {
Self::begin_send(&self.transport, batch_id, sub_batch, true)
});
if pending.is_empty() {
- // Nothing routable right now (no healthy worker), or the
- // remaining work is in flight on the eager path — wait.
+ // Nothing is routable right now (no healthy worker), so wait.
tokio::select! {
_ = self.handle.shutdown_recv() => {
anyhow::bail!("shutdown while flushing deferred messages");
@@ -506,105 +478,15 @@ impl IngestionConsumer {
.heartbeat_while(Self::scatter(&self.dispatcher, batch_id, pending, 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;
}
}
}
- // 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. `begin_send` runs here, in
- /// channel-receive order, before the awaiting task spawns.
- async fn run_eager_flush_loop(
- dispatcher: Arc<Dispatcher>,
- transport: Arc<GrpcTransport>,
- mut rx: mpsc::UnboundedReceiver<EagerFlush>,
- ) {
- while let Some(flush) = rx.recv().await {
- let EagerFlush {
- batch_id,
- sub_batch,
- } = flush;
- let pending = Self::begin_send(&transport, &batch_id, sub_batch, true);
- let dispatcher = Arc::clone(&dispatcher);
- tokio::spawn(async move {
- Self::send_eager_flush(dispatcher, batch_id, pending).await;
- });
- }
- }
-
- /// Await one eagerly-released sub-batch send, 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>,
- batch_id: String,
- pending: PendingSubBatch,
- ) {
- let PendingSubBatch {
- worker,
- routing_keys,
- key_offsets,
- message_count,
- pending,
- } = pending;
-
- match pending.wait().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.
- // A busy worker is backpressure, not a fault: re-route the work
- // but keep it off the worker's health, so passive health tracks
- // real faults.
- let SendError {
- error,
- messages,
- fence_guard,
- } = send_err;
- let is_fault = !error.is_backpressure();
- dispatcher.defer_failed(&batch_id, messages);
- // Stashed: let the worker stream stop fencing new arrivals.
- drop(fence_guard);
- dispatcher.eager_flush_failed(&batch_id);
- dispatcher.on_sub_batch_resolved(&worker, message_count, &routing_keys, true, true);
- dispatcher.record_send_outcome(&worker, is_fault);
- }
- }
- }
-
fn fail_batch_processing(&self, err: anyhow::Error) {
error!(error = %err, "Batch processing failed");
counter!("ingestion_consumer_batch_errors_total").increment(1);
@@ -617,9 +499,9 @@ impl IngestionConsumer {
}
/// Establish a sub-batch's send order. Synchronous and non-blocking on
- /// purpose: called where send order is decided (under the dispatcher's
- /// lock on the consumer loop, and in the eager flush loop), so a key's
- /// sub-batches enter its worker's stream in exactly that order.
+ /// purpose: called under the dispatcher's lock on the consumer loop, where
+ /// send order is decided, so a key's sub-batches enter its worker's stream
+ /// in exactly that order.
fn begin_send(
transport: &GrpcTransport,
batch_id: &str,
@@ -707,8 +589,7 @@ impl IngestionConsumer {
.record(*lag_ms as f64);
}
- // Nothing to send and no flush-path activity (deferred, in-flight
- // eager, or already eagerly accepted) → no usable workers.
+ // Nothing to send and no deferred groups means no usable workers.
if pending.is_empty() && !dispatcher.batch_has_flush_activity(&batch_id) {
counter!("ingestion_consumer_no_healthy_workers_total").increment(1);
anyhow::bail!("No healthy workers available to route batch");
diff --git a/rust/ingestion-consumer/src/dispatcher.rs b/rust/ingestion-consumer/src/dispatcher.rs
index 2801d16f3296..ced8b26f38c3 100644
--- a/rust/ingestion-consumer/src/dispatcher.rs
+++ b/rust/ingestion-consumer/src/dispatcher.rs
@@ -3,7 +3,6 @@ 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::{
@@ -60,13 +59,6 @@ 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 {
@@ -75,21 +67,10 @@ 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>,
@@ -213,9 +194,6 @@ 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 {
@@ -233,7 +211,6 @@ impl Dispatcher {
key_sentinel: Arc::new(KeyOrderSentinel::new()),
aperture: None,
debug_recorder: None,
- eager_flush_tx: Mutex::new(None),
}
}
@@ -251,7 +228,6 @@ impl Dispatcher {
key_sentinel: Arc::new(KeyOrderSentinel::new()),
aperture: None,
debug_recorder: None,
- eager_flush_tx: Mutex::new(None),
}
}
@@ -274,14 +250,6 @@ 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();
@@ -604,10 +572,7 @@ impl Dispatcher {
/// 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);
+ self.pin_table.lock().unwrap().stash.release_batch(batch_id);
}
/// Whether `batch_id` still has deferred groups awaiting flush.
@@ -615,55 +580,16 @@ impl Dispatcher {
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).
+ /// Whether the batch still has deferred groups awaiting a flush.
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)
+ self.pin_table.lock().unwrap().stash.has_batch(batch_id)
}
- /// 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.
+ /// Whether the batch has any deferred groups. 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)
+ self.pin_table.lock().unwrap().stash.has_batch(batch_id)
}
/// Whether the worker has any in-flight (sent, unresolved) messages. The
@@ -864,18 +790,13 @@ 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,
+ _send_failed: bool,
) {
let mut table = self.pin_table.lock().unwrap();
@@ -895,9 +816,7 @@ 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.
@@ -922,22 +841,10 @@ 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",
@@ -962,130 +869,6 @@ 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, SendKind::Resend);
- 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
@@ -1101,9 +884,9 @@ 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.
+/// (see `STICKY_PIN_LOAD_FACTOR`). Only consulted at flush 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,
@@ -2004,136 +1787,6 @@ mod tests {
);
}
- /// 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(&registry));
- 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(&registry));
- 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(&registry));
- 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
@@ -2193,43 +1846,6 @@ mod tests {
);
}
- #[test]
- fn test_eager_release_overrides_saturated_sticky_pin() {
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
- 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);
diff --git a/rust/ingestion-consumer/src/order_sentinel.rs b/rust/ingestion-consumer/src/order_sentinel.rs
index efa039f11dfa..3de71b5a2818 100644
--- a/rust/ingestion-consumer/src/order_sentinel.rs
+++ b/rust/ingestion-consumer/src/order_sentinel.rs
@@ -333,9 +333,9 @@ pub enum SendKind {
/// single partition, so their offsets must only move forward; a regression
/// is a [`KeyOrderViolationKind::SendBelowLastSent`] violation.
Fresh,
- /// A retry path (deferred flush or eager release) that re-routes messages
- /// whose earlier send failed — repeating un-ACKed offsets is expected
- /// at-least-once behavior, not a violation.
+ /// A deferred-flush retry that re-routes messages whose earlier send
+ /// failed — repeating un-ACKed offsets is expected at-least-once behavior,
+ /// not a violation.
Resend,
}
diff --git a/rust/ingestion-consumer/src/stash.rs b/rust/ingestion-consumer/src/stash.rs
index 61072401a881..7d331fa881a2 100644
--- a/rust/ingestion-consumer/src/stash.rs
+++ b/rust/ingestion-consumer/src/stash.rs
@@ -163,25 +163,6 @@ impl Stash {
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) {
let batch_seq = self.seq_for(batch_id);
@@ -356,45 +337,4 @@ 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/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rs
index bfed88659f5c..4411b88ef4a8 100644
--- a/rust/ingestion-consumer/tests/e2e_integration_test.rs
+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs
@@ -618,7 +618,6 @@ impl Harness {
group_id: "e2e-test".to_string(),
deferred_flush_timeout,
debug_recorder: None,
- eager_deferred_flush: false,
},
handle,
);
@@ -689,7 +688,6 @@ impl Harness {
group_id: "e2e-test".to_string(),
deferred_flush_timeout: self.deferred_flush_timeout,
debug_recorder: None,
- eager_deferred_flush: false,
},
handle,
);
@@ -2470,7 +2468,6 @@ 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,
);
@@ -2541,7 +2538,6 @@ 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,
);