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 the pin-stash scheduler (#118347)

José Sequeira67530f18dfe5
diff --git a/nodejs/tests/service-e2e/rust-ingestion-consumer.serial.test.ts b/nodejs/tests/service-e2e/rust-ingestion-consumer.serial.test.ts
index ea193006cdd6..430189a2df76 100644
--- a/nodejs/tests/service-e2e/rust-ingestion-consumer.serial.test.ts
+++ b/nodejs/tests/service-e2e/rust-ingestion-consumer.serial.test.ts
@@ -136,11 +136,11 @@ describe('Rust ingestion consumer with Node ingestion API workers', () => {
expectedMinCommits: 2,
})
const initialWorker0Routed = getPrometheusSample(metricsAfterInitialBatch, {
- name: 'ingestion_consumer_dispatcher_messages_routed_total',
+ name: 'ingestion_consumer_batcher_messages_sent_total',
labels: { worker: workers[0].url },
})
const initialWorker1Routed = getPrometheusSample(metricsAfterInitialBatch, {
- name: 'ingestion_consumer_dispatcher_messages_routed_total',
+ name: 'ingestion_consumer_batcher_messages_sent_total',
labels: { worker: workers[1].url },
})
expect(initialWorker0Routed).toBeGreaterThan(0)
@@ -217,11 +217,11 @@ describe('Rust ingestion consumer with Node ingestion API workers', () => {
const metricsAfterHealthyBatch = await fetchMetrics(rustConsumer, rustMetricsPort)
const worker0RoutedAfterHealthyBatch = getPrometheusSample(metricsAfterHealthyBatch, {
- name: 'ingestion_consumer_dispatcher_messages_routed_total',
+ name: 'ingestion_consumer_batcher_messages_sent_total',
labels: { worker: workers[0].url },
})
const worker1RoutedAfterHealthyBatch = getPrometheusSample(metricsAfterHealthyBatch, {
- name: 'ingestion_consumer_dispatcher_messages_routed_total',
+ name: 'ingestion_consumer_batcher_messages_sent_total',
labels: { worker: workers[1].url },
})
expect(worker0RoutedAfterHealthyBatch).toBeGreaterThan(0)
@@ -246,13 +246,13 @@ describe('Rust ingestion consumer with Node ingestion API workers', () => {
const metrics = await fetchMetrics(rustConsumer, rustMetricsPort)
expect(
getPrometheusSample(metrics, {
- name: 'ingestion_consumer_dispatcher_messages_routed_total',
+ name: 'ingestion_consumer_batcher_messages_sent_total',
labels: { worker: workers[0].url },
})
).toBe(worker0RoutedAfterHealthyBatch)
expect(
getPrometheusSample(metrics, {
- name: 'ingestion_consumer_dispatcher_messages_routed_total',
+ name: 'ingestion_consumer_batcher_messages_sent_total',
labels: { worker: workers[1].url },
})
).toBeGreaterThanOrEqual(worker1RoutedAfterHealthyBatch + failoverEvents.length)
@@ -266,7 +266,7 @@ describe('Rust ingestion consumer with Node ingestion API workers', () => {
const metricsBeforeRecovery = await fetchMetrics(rustConsumer, rustMetricsPort)
const worker0RoutedBeforeRecovery = getPrometheusSample(metricsBeforeRecovery, {
- name: 'ingestion_consumer_dispatcher_messages_routed_total',
+ name: 'ingestion_consumer_batcher_messages_sent_total',
labels: { worker: workers[0].url },
})
@@ -290,7 +290,7 @@ describe('Rust ingestion consumer with Node ingestion API workers', () => {
const metrics = await fetchMetrics(rustConsumer, rustMetricsPort)
expect(
getPrometheusSample(metrics, {
- name: 'ingestion_consumer_dispatcher_messages_routed_total',
+ name: 'ingestion_consumer_batcher_messages_sent_total',
labels: { worker: workers[0].url },
})
).toBeGreaterThan(worker0RoutedBeforeRecovery)
@@ -314,7 +314,7 @@ describe('Rust ingestion consumer with Node ingestion API workers', () => {
test('Rust consumer holds the batch then exits when all Node ingestion API workers stay down', async () => {
// During a full worker outage the consumer must hold the batch (nothing
- // dropped, nothing committed) and retry for the configured deferred-flush
+ // dropped, nothing committed) and retry for the configured stall
// timeout, then exit non-zero so the pod restarts and Kafka redelivers.
// A short timeout keeps the bounded-exit contract observable quickly.
const { workers, rustConsumer, rustMetricsPort } = await startRustNodeStack(services, {
@@ -343,7 +343,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 made no progress within the flush timeout')
+ expect(exit.output).toContain('pending work made no progress within the stall timeout')
await waitForTopicMessageCount(KAFKA_EVENTS_JSON, 0)
} finally {
await producer.disconnect()
@@ -523,6 +523,9 @@ function startRustIngestionConsumer(
CONSUMER_BATCH_TIMEOUT_MS: '1000',
CONSUMER_MAX_BACKGROUND_TASKS: '1',
INGESTION_WORKER_CONCURRENT_BATCHES: '1',
+ // A request packs every ready key up to the target, so a poll would
+ // go to one worker whole; a small target spreads it over both.
+ INGESTION_PACK_TARGET_EVENTS: '4',
WORKER_ADDRESSES: workers.join(','),
INGESTION_WORKER_GRPC_PORT_OFFSET: GRPC_PORT_OFFSET.toString(),
WORKER_PROBE_INTERVAL_MS: '250',
@@ -978,7 +981,7 @@ async function waitForRoutedMetrics(
(sum, worker) =>
sum +
getPrometheusSample(lastMetrics, {
- name: 'ingestion_consumer_dispatcher_messages_routed_total',
+ name: 'ingestion_consumer_batcher_messages_sent_total',
labels: { worker },
}),
0
@@ -986,9 +989,7 @@ async function waitForRoutedMetrics(
expect(totalRouted).toBeGreaterThanOrEqual(expectedMessages)
for (const worker of expectedWorkers) {
- expect(lastMetrics).toContain(
- `ingestion_consumer_dispatcher_sub_batches_assigned_total{worker="${worker}"}`
- )
+ expect(lastMetrics).toContain(`ingestion_consumer_batcher_requests_sent_total{worker="${worker}"}`)
}
expect(getOffsetCommitCount(lastMetrics)).toBeGreaterThanOrEqual(expectedMinCommits)
}, 30_000)
diff --git a/rust/ingestion-consumer/README.md b/rust/ingestion-consumer/README.md
index b168fe3ff2c8..5396cd923050 100644
--- a/rust/ingestion-consumer/README.md
+++ b/rust/ingestion-consumer/README.md
@@ -1,8 +1,8 @@
# ingestion-consumer
-Rust Kafka consumer that routes analytics events to Node.js ingestion workers over ordered gRPC streams with sticky per-key assignment.
-It reads batches from Kafka, groups messages by Kafka message key, pins each key to a worker (preserving per-key ordering; unkeyed messages can go to any worker), sends each worker's sub-batches on its `WorkerIngest` stream, and commits offsets only after every message in the batch is accepted.
-Worker health combines active `/_ready` probes with passive send outcomes; workers that leave the pool drain gracefully — in-flight work finishes, new work for their keys defers and re-routes to survivors in order.
+Rust Kafka consumer that routes analytics events to Node.js ingestion workers over ordered gRPC streams, with at most one request per key in flight.
+It reads batches from Kafka, groups messages by Kafka message key, packs each key's messages into requests (preserving per-key ordering; unkeyed messages can go to any worker), sends each request on its worker's `WorkerIngest` stream, and commits offsets only after every message in the batch is accepted.
+Worker health combines active `/_ready` probes with passive send outcomes; workers that leave the pool drain gracefully: in-flight work finishes, and new work for their keys waits and goes to survivors in order.
## Ordering sentinels
@@ -26,7 +26,7 @@ The worker-side check lives in `nodejs/src/ingestion/api/feed-order-sentinel.ts`
It measures the invariant at its end point: the worker groups each key's messages by distinct id and processes each group in feed order, so "fed in offset order per key" is "processed in order per distinct id".
A partial ack keeps that, because the worker leaves only the last messages of a distinct id unfinished and the consumer resends them in order.
Rebalances reset all baselines (`ingestion_consumer_rebalances_total{event}` counts them), so partition handoffs don't fire false positives.
-Null-key messages (e.g. overflow rerouting) are excluded from both checks: the producer deliberately forfeits per-key order for them, and the consumer routes each one individually rather than pinning it, so there is no invariant to check on either side.
+Null-key messages (e.g. overflow rerouting) are excluded from both checks: the producer deliberately forfeits per-key order for them, and the consumer routes each one on its own, so there is no invariant to check on either side.
## Offset ledger
@@ -43,14 +43,9 @@ The ledger emits its own metrics, so any consumer built on the crate reports the
`kafka_consumer_ledger_stale_slices_total{stage}` counts charges and settlements dropped because their partition was reassigned while they were in flight; a few around a rebalance are expected.
`kafka_consumer_ledger_errors_total{stage,kind}` counts contract violations in the ledger's accounting; it must stay 0. A violation resets that partition's ledger and the consumer keeps running; the consumer logs the rejected slice with the batch and ledger generations and the window depth before the reset.
-## Schedulers
+## Batcher
-`INGESTION_SCHEDULER` selects how runs are ordered and placed on workers.
-
-- `pin_stash` (default) pins each key to a worker and stashes a batch's groups while a pinned worker drains. It is the fallback.
-- `key_table` runs the batcher state machine in `src/batcher/`.
-
-Under `key_table`:
+The batcher state machine in `src/batcher/` orders runs and places them on workers.
- One task owns the state machine and applies polls, worker responses, revokes and retry wakeups one at a time.
- Each key has a FIFO queue, and at most one request per key is in flight, which preserves per-key order.
@@ -62,19 +57,20 @@ Under `key_table`:
- A revoke drops the pending messages of the revoked partitions, because the new owner replays them.
- Pending work with nothing in flight and nothing accepted for `CONSUMER_DEFERRED_FLUSH_TIMEOUT_MS` fails the consumer, which restarts and replays.
-| Setting | Default | Effect under `key_table` |
+| Setting | Default | Effect |
| --- | --- | --- |
| `INGESTION_PACK_TARGET_EVENTS` | `500` | Send a request to a free slot once this many events are ready. Unless a run cap is set, it also caps one key's run. `0` disables the event target and the cap, and needs a byte target. |
| `INGESTION_PACK_TARGET_BYTES` | `0` | Send a request to a free slot once this many key-plus-value bytes are ready. Unless a run cap is set, it also caps one key's run. `0` disables the byte target and the cap, and needs an event target. |
| `INGESTION_RUN_CAP_EVENTS` | `0` | The most events one key's run holds, which is the most of its backlog a key sends per round trip. With both run caps at `0`, the pack targets cap runs. When either is set, the run caps replace them, and a `0` cap leaves that dimension uncapped. |
| `INGESTION_RUN_CAP_BYTES` | `0` | One key's run stops growing once it holds this many key-plus-value bytes. Works with `INGESTION_RUN_CAP_EVENTS`. |
| `INGESTION_PACK_LATENCY_BUDGET_MS` | `0` | Once a slot is free, wait this long for ready events below the target to reach it. `0` waits for nothing: each free slot gets what is ready, packed up to the target. Replays never wait, because they already waited out a retry delay or a worker's time budget. |
-| `INGESTION_REQUEST_SOFT_BUDGET_MS` | `0` | How long a worker may spend on one request before it stops starting work and acks what finished as partial. The rest goes out again at once. `0` sends no budget. A request split into several frames goes without one. Startup fails if it is below `100` or above `2147483647`, if it is set under `pin_stash`, if it times `INGESTION_WORKER_CONCURRENT_BATCHES` reaches `INGESTION_WORKER_STREAM_ACK_TIMEOUT_MS`, or if it plus `INGESTION_PACK_LATENCY_BUDGET_MS` reaches `CONSUMER_DEFERRED_FLUSH_TIMEOUT_MS`. |
+| `INGESTION_REQUEST_SOFT_BUDGET_MS` | `0` | How long a worker may spend on one request before it stops starting work and acks what finished as partial. The rest goes out again at once. `0` sends no budget. A request split into several frames goes without one. Startup fails if it is below `100` or above `2147483647`, if it times `INGESTION_WORKER_CONCURRENT_BATCHES` reaches `INGESTION_WORKER_STREAM_ACK_TIMEOUT_MS`, or if it plus `INGESTION_PACK_LATENCY_BUDGET_MS` reaches `CONSUMER_DEFERRED_FLUSH_TIMEOUT_MS`. |
| `INGESTION_REQUEST_BUDGET_ATTEMPTS` | `3` | How many budgeted attempts may leave a key's messages unfinished, since the key last finished a run, before it resends without a budget. At least 1, or startup fails. Only read when `INGESTION_REQUEST_SOFT_BUDGET_MS` is set. |
| `INGESTION_PARKED_RETRY_INTERVAL_MS` | `200` | The delay before a failed send retries, and how often a request with no routable worker tries again. |
Metrics:
+- `ingestion_consumer_batcher_requests_sent_total{worker}` and `ingestion_consumer_batcher_messages_sent_total{worker}` count what each worker was sent, replays included.
- `ingestion_consumer_request_events` and `ingestion_consumer_request_bytes` record each request as sent. They show whether requests reach the pack target.
- `ingestion_consumer_request_queue_wait_seconds{kind=fresh|replay}` records how long a request's oldest message waited, including the pack budget.
- `ingestion_consumer_batcher_packed_requests_total{reason=target|deadline|replay|shutdown}` counts why the packer built each request: at the target, at the budget deadline, as a replay, or at shutdown.
@@ -88,9 +84,9 @@ Set `DEBUG_API_ENABLED=true` **and** `DEBUG_API_SECRET` to mount a real-time deb
Every request must present the secret as `X-Debug-Api-Secret`; enabling without a secret fails closed (nothing is mounted).
The secret is dedicated to this control-plane→consumer hop — deliberately not `INTERNAL_API_SECRET` (see `.agents/security.md`).
The ingestion control plane UI consumes these endpoints to render the consumer's live state.
-`debug_recorder.rs` keeps a bounded in-memory buffer of structured lifecycle events — batch dispatch/assignment/commit, deferrals and flushes, worker health and membership — recorded at the same points that emit metrics, and it never influences routing.
+`debug_recorder.rs` keeps a bounded in-memory buffer of structured lifecycle events (batch dispatch, commit and failure, worker health and membership), recorded at the same points that emit metrics, and it never influences routing.
-- `/debug/load` — cheap JSON snapshot (worker health + dispatcher in-flight/pins/stash), safe to poll fast.
+- `/debug/load` — cheap JSON snapshot (worker health + the batcher's in-flight and pending counts), safe to poll fast.
- `/debug/state` — the same plus the retained event backlog.
- `/debug/events` — SSE stream: backlog replay, then live events (concurrent subscribers capped at 8; 429 beyond).
@@ -116,14 +112,14 @@ Remaining: alert rules on the new metrics.
### 3. DLQ for poison messages
-A message a worker permanently rejects (a nack on every delivery) has no dead-letter path: after the flush timeout the batch fails and the process crash-loops on redelivery.
+A message a worker permanently rejects (a nack on every delivery) has no dead-letter path: after the stall timeout (`CONSUMER_DEFERRED_FLUSH_TIMEOUT_MS`) the consumer fails and the process crash-loops on redelivery.
`poison_batch_fails_safely_without_committing` pins the safe half of the trade-off (never commit past unaccepted messages).
Needs a design pass: DLQ topic, retry budget before giving up, the per-key ordering caveat (DLQ-ing one message then delivering later ones for the same person), and replay ownership.
Non-UTF-8 payloads — currently nulled in `collect_batch` with no metric — should route to the same DLQ as malformed input; a bytes-preserving wire format is not worth it while the producer (capture) guarantees UTF-8 JSON.
### 4. Revoke-aware partition handoff
-Sticky pins and the deferral stash are per-process.
+The batcher's key queues are per-process.
During a consumer-group rebalance another instance can start a partition from the last commit while this instance still has uncommitted in-flight work — duplicates and possible cross-pod interleaving per key (`second_consumer_joining_the_group_preserves_all_messages` asserts no loss only, deliberately).
Fix: on partition revoke (cooperative-sticky callback, via the same `ConsumerContext` as item 2), finish and commit in-flight batches for the revoked partitions before acknowledging the revoke.
diff --git a/rust/ingestion-consumer/src/aperture.rs b/rust/ingestion-consumer/src/aperture.rs
index ce651e0d91c6..1162ea48746c 100644
--- a/rust/ingestion-consumer/src/aperture.rs
+++ b/rust/ingestion-consumer/src/aperture.rs
@@ -1,11 +1,11 @@
//! Deterministic aperture: ring-slice candidate selection.
//!
-//! Every dispatcher sorts the full worker set into the same ring, takes the
-//! slice starting at `peer_index * ring_len / peer_count`, and routes its
-//! unpinned groups only within that slice (via the configured selection
+//! Every consumer sorts the full worker set into the same ring, takes the
+//! slice starting at `peer_index * ring_len / peer_count`, and places its
+//! requests only within that slice (via the configured selection
//! strategy). Because peers agree on both the ring order (same EndpointSlices,
//! same sort) and their own indices ([`k8s_awareness::PeerTracker`]), the
-//! slices tile the ring without any coordination — each dispatcher talks to
+//! slices tile the ring without any coordination, so each consumer talks to
//! a handful of workers instead of the whole pool, which is what keeps
//! sub-batches consolidated. Modeled on Finagle's deterministic aperture.
//!
@@ -111,8 +111,7 @@ mod tests {
#[test]
fn test_width_floored_so_slices_cover_an_oversized_ring() {
// 2 peers x configured width 3 over 8 workers: unfloored slices would
- // be spaced 4 apart and leave positions 3 and 7 with zero unpinned
- // traffic. The ceil(8/2)=4 floor widens each slice just enough that
+ // be spaced 4 apart and leave positions 3 and 7 with no traffic. The ceil(8/2)=4 floor widens each slice just enough that
// the union covers the whole ring.
let ring = ring(8);
let mut seen = HashSet::new();
diff --git a/rust/ingestion-consumer/src/batcher/driver.rs b/rust/ingestion-consumer/src/batcher/driver.rs
index 09d929d58657..3fb98ad88d9a 100644
--- a/rust/ingestion-consumer/src/batcher/driver.rs
+++ b/rust/ingestion-consumer/src/batcher/driver.rs
@@ -379,6 +379,16 @@ impl<S: RequestSender, W: Workers> BatcherTask<S, W> {
sentinel.note_sent(&run.routing_key, &run.messages, kind);
messages.extend(run.messages);
}
+ counter!(
+ "ingestion_consumer_batcher_requests_sent_total",
+ "worker" => send.worker.clone()
+ )
+ .increment(1);
+ counter!(
+ "ingestion_consumer_batcher_messages_sent_total",
+ "worker" => send.worker.clone()
+ )
+ .increment(messages.len() as u64);
let options = SendOptions {
replay: send.class.replay,
soft_budget: send.soft_budget,
diff --git a/rust/ingestion-consumer/src/batcher/mod.rs b/rust/ingestion-consumer/src/batcher/mod.rs
index c0b7a68cbbe9..ec8771eb143e 100644
--- a/rust/ingestion-consumer/src/batcher/mod.rs
+++ b/rust/ingestion-consumer/src/batcher/mod.rs
@@ -2,15 +2,14 @@
//!
//! The consumer loop submits one [`Accumulator`] per poll, in poll order, and
//! receives one [`GroupCompletion`] per group back. Everything in between is
-//! an implementation detail of this module: assignment, the scatter over the
-//! worker streams with its send resolution, and the serialized oldest-first
-//! deferred flush. No batch identity crosses the boundary: the batcher
-//! creates an internal batch id per accumulator for the dispatcher and the
-//! wire request, and the consumer correlates completions by partition and
-//! offset.
+//! an implementation detail of this module: the state machine queues each
+//! key's messages, packs ready keys into requests for free worker slots,
+//! places each request on a worker as it is sent, and retries failures; one
+//! task drives it and performs its effects. No batch identity crosses the
+//! boundary: the consumer correlates completions by partition and offset.
//!
-//! Fatal orchestration failures (a wedged deferred flush, shutdown while
-//! deferred work is unroutable, a batch with no usable workers) are reported
+//! Fatal orchestration failures (pending work that makes no progress for the
+//! stall timeout, a worker that accepts more than it was sent) are reported
//! on an error channel; the consumer turns them into a process failure, so
//! the failure decision stays in the consumer loop.
@@ -26,27 +25,18 @@ pub(crate) mod test_support;
pub mod worker_assigner;
pub mod worker_pool;
-use std::collections::HashMap;
use std::sync::atomic::Ordering;
use std::sync::Arc;
-use std::time::{Duration, Instant};
-use common_kafka_consumer::{AssignmentEpoch, GroupCompletion, Offset, Partition};
-use lifecycle::Handle;
-use metrics::{counter, histogram};
+use common_kafka_consumer::GroupCompletion;
use tokio::sync::mpsc;
-use tokio::task::JoinHandle;
-use tracing::{error, info};
use self::driver::StateMachineDriver;
use self::state_machine::BatcherStateMachine;
use self::worker_pool::WorkerPoolSource;
-use crate::dispatcher::{Dispatcher, KeyOffset, SubBatch, Submission};
-use crate::grpc_transport::{GrpcTransport, PendingWorkerStreamSend};
+use crate::grpc_transport::GrpcTransport;
use crate::order_sentinel::KeyOrderSentinel;
-use crate::transport::{SendError, SendOutcome};
use crate::types::Accumulator;
-use crate::types::SerializedKafkaMessage;
use crate::worker_registry::WorkerId;
/// The batcher's output channels, held by the consumer loop.
@@ -59,671 +49,83 @@ pub struct BatcherOutputs {
pub errors: mpsc::UnboundedReceiver<String>,
}
-/// A slice of a batch whose send order is already established on its worker's
-/// stream (`GrpcTransport::begin_send`), plus the metadata the resolve
-/// protocol and the completion events need.
-struct PendingSubBatch {
- worker: WorkerId,
- routing_keys: Vec<String>,
- key_offsets: Vec<KeyOffset>,
- message_count: usize,
- /// The accumulator groups this sub-batch carries, kept aside so the
- /// resolved send can be broken back into per-group completions.
- groups: Vec<CompletionGroup>,
- /// The runs' epoch when the scheduler stamped one; completions then use
- /// it instead of the awaiting batch's epoch.
- assignment_epoch: Option<u64>,
- pending: PendingWorkerStreamSend,
-}
-
-/// One accumulator group's share of a sub-batch: its partition and offsets.
-struct CompletionGroup {
- partition: Partition,
- offsets: Vec<Offset>,
-}
-
-/// One submitted batch in the flush driver's queue: the driver awaits the
-/// batch's scatter, then flushes its deferred groups, oldest batch first.
-struct FlushTicket {
- batch_id: String,
- assignment_epoch: u64,
- scatter: JoinHandle<()>,
-}
-
-struct BatcherInner {
- dispatcher: Arc<Dispatcher>,
- transport: Arc<GrpcTransport>,
- /// Stamped on each submitted batch's completions; bumped on partition
- /// assignment by the consumer's rebalance context.
- assignment_epoch: AssignmentEpoch,
- completions: mpsc::UnboundedSender<GroupCompletion>,
- errors: mpsc::UnboundedSender<String>,
-}
-
-impl BatcherInner {
- fn report_error(&self, message: String) {
- error!(error = %message, "Batcher failure");
- if self.errors.send(message).is_err() {
- error!("Batcher error channel closed; consumer is gone");
- }
- }
-}
-
-/// Emit one completion per group of a successfully resolved send. A send is
-/// all-or-nothing, so `accepted` normally equals the sub-batch size and each
-/// group completes with its own length; a worker that under-reports shorts
-/// the tail groups, so the poll fails its accepted check and the process
-/// exits and replays.
-fn send_group_completions(
- completions: &mpsc::UnboundedSender<GroupCompletion>,
- groups: Vec<CompletionGroup>,
- assignment_epoch: u64,
- accepted: u32,
-) {
- let mut remaining = accepted;
- for group in groups {
- let group_accepted = remaining.min(group.offsets.len() as u32);
- remaining -= group_accepted;
- counter!("ingestion_consumer_group_completions_total").increment(1);
- counter!("ingestion_consumer_group_completion_accepted_messages_total")
- .increment(group_accepted as u64);
- let _ = completions.send(GroupCompletion {
- partition: group.partition,
- assignment_epoch,
- offsets: group.offsets,
- accepted: group_accepted,
- });
- }
-}
-
-/// Submits polls, and receives completions and fatal errors back, through
-/// either the dispatcher or the batcher state machine, as
-/// `INGESTION_SCHEDULER` selects.
+/// Submits polls to the batcher state machine, and receives completions and
+/// fatal errors back.
pub struct Batcher {
- backend: Backend,
-}
-
-enum Backend {
- Dispatcher(DispatcherBatcher),
- StateMachine(StateMachineDriver),
+ driver: StateMachineDriver,
}
impl Batcher {
- /// Drive the dispatcher's pin-stash scheduler.
pub fn new(
- dispatcher: Arc<Dispatcher>,
- transport: Arc<GrpcTransport>,
- handle: Handle,
- deferred_flush_timeout: Duration,
- ) -> (Self, BatcherOutputs) {
- let (inner, outputs) =
- DispatcherBatcher::new(dispatcher, transport, handle, deferred_flush_timeout);
- (
- Self {
- backend: Backend::Dispatcher(inner),
- },
- outputs,
- )
- }
-
- /// Drive the batcher state machine, the `key_table` scheduler.
- pub fn with_state_machine(
state_machine: BatcherStateMachine,
pool_source: WorkerPoolSource,
transport: Arc<GrpcTransport>,
) -> (Self, BatcherOutputs) {
let (driver, outputs) = StateMachineDriver::new(state_machine, pool_source, transport);
- (
- Self {
- backend: Backend::StateMachine(driver),
- },
- outputs,
- )
+ (Self { driver }, outputs)
}
/// The per-key order sentinel, so the consumer can enable it.
pub fn key_order_sentinel(&self) -> Arc<KeyOrderSentinel> {
- match &self.backend {
- Backend::Dispatcher(inner) => inner.key_order_sentinel(),
- Backend::StateMachine(driver) => driver.key_order_sentinel(),
- }
+ self.driver.key_order_sentinel()
}
/// The batcher's half of the consumer's revocation hook.
pub fn revoker(&self) -> Revoker {
- match &self.backend {
- Backend::Dispatcher(inner) => {
- Revoker(RevokeTarget::Dispatcher(inner.key_order_sentinel()))
- }
- Backend::StateMachine(driver) => {
- Revoker(RevokeTarget::StateMachine(driver.revoke_sender()))
- }
- }
+ Revoker(self.driver.revoke_sender())
}
/// Submit one poll's demuxed groups. Call on the consumer loop, in poll
/// order. Returns the assignment epoch stamped on the poll's completions.
pub fn submit(&self, accumulator: Accumulator) -> u64 {
- match &self.backend {
- Backend::Dispatcher(inner) => inner.submit(accumulator),
- Backend::StateMachine(driver) => driver.submit(accumulator),
- }
+ self.driver.submit(accumulator)
}
- /// A read-only view of the batcher's load, for the drain reaper and
- /// tests.
+ /// A read-only view of the batcher's load, for the drain reaper, the
+ /// debug API and tests.
pub fn observer(&self) -> BatcherObserver {
- match &self.backend {
- Backend::Dispatcher(inner) => BatcherObserver(ObserverTarget::Dispatcher(Arc::clone(
- &inner.inner.dispatcher,
- ))),
- Backend::StateMachine(driver) => {
- BatcherObserver(ObserverTarget::StateMachine(driver.load()))
- }
- }
+ BatcherObserver(self.driver.load())
}
/// The consumer stopped polling. The state machine takes no new groups
/// and stops once nothing is pending or in flight.
pub fn begin_shutdown(&self) {
- if let Backend::StateMachine(driver) = &self.backend {
- driver.begin_shutdown();
- }
+ self.driver.begin_shutdown();
}
}
/// A read-only view of the batcher's load.
#[derive(Clone)]
-pub struct BatcherObserver(ObserverTarget);
-
-#[derive(Clone)]
-enum ObserverTarget {
- Dispatcher(Arc<Dispatcher>),
- StateMachine(Arc<driver::Load>),
-}
+pub struct BatcherObserver(Arc<driver::Load>);
impl BatcherObserver {
/// Whether the worker has sent, unresolved work. The reaper completes a
/// draining worker's drain only when it has none.
pub fn has_in_flight(&self, worker: &WorkerId) -> bool {
- match &self.0 {
- ObserverTarget::Dispatcher(dispatcher) => dispatcher.has_in_flight(worker),
- ObserverTarget::StateMachine(load) => {
- load.busy_workers.lock().unwrap().contains(worker)
- }
- }
+ self.0.busy_workers.lock().unwrap().contains(worker)
}
- /// Messages held for a later send: the pin-stash's stash, or the
- /// state machine's queued, packed and unplaced messages.
- pub fn held_messages(&self) -> usize {
- match &self.0 {
- ObserverTarget::Dispatcher(dispatcher) => dispatcher.stashed_messages(),
- ObserverTarget::StateMachine(load) => load.pending_messages.load(Ordering::Relaxed),
- }
+ /// Messages held for a later send: queued, packed and unplaced.
+ pub fn pending_messages(&self) -> usize {
+ self.0.pending_messages.load(Ordering::Relaxed)
}
pub fn total_in_flight(&self) -> usize {
- match &self.0 {
- ObserverTarget::Dispatcher(dispatcher) => dispatcher.total_in_flight(),
- ObserverTarget::StateMachine(load) => load.in_flight_messages.load(Ordering::Relaxed),
- }
- }
-
- /// Live sticky pins; the state machine keeps none.
- pub fn pin_count(&self) -> usize {
- match &self.0 {
- ObserverTarget::Dispatcher(dispatcher) => dispatcher.pin_count(),
- ObserverTarget::StateMachine(_) => 0,
- }
+ self.0.in_flight_messages.load(Ordering::Relaxed)
}
}
/// Purges revoked partitions from the batcher. Runs on the rebalance
-/// callback.
-pub struct Revoker(RevokeTarget);
-
-enum RevokeTarget {
- /// The pin-stash scheduler keeps nothing to purge.
- Dispatcher(Arc<KeyOrderSentinel>),
- StateMachine(driver::RevokeSender),
-}
+/// callback. Purged messages never complete, so the consumer drops the
+/// in-flight polls that hold a revoked partition.
+pub struct Revoker(driver::RevokeSender);
impl Revoker {
pub fn purge_revoked(&self, partitions: &[(String, i32)]) {
- match &self.0 {
- RevokeTarget::Dispatcher(key_sentinel) => key_sentinel.clear(),
- RevokeTarget::StateMachine(sender) => sender.purge_revoked(partitions),
- }
- }
-
- /// Whether purged messages never complete, so the consumer must drop the
- /// in-flight polls that hold a revoked partition.
- pub fn drops_revoked_polls(&self) -> bool {
- matches!(self.0, RevokeTarget::StateMachine(_))
- }
-}
-
-/// Owns the dispatch orchestration: the dispatcher, the scatter tasks, and
-/// the deferred-flush driver. Holds shared handles to the transport; the
-/// transport, router, and registry keep their construction and ownership in
-/// `main.rs`.
-struct DispatcherBatcher {
- inner: Arc<BatcherInner>,
- flush_queue: mpsc::UnboundedSender<FlushTicket>,
-}
-
-impl DispatcherBatcher {
- fn new(
- dispatcher: Arc<Dispatcher>,
- transport: Arc<GrpcTransport>,
- handle: Handle,
- deferred_flush_timeout: Duration,
- ) -> (Self, BatcherOutputs) {
- let (completions_tx, completions_rx) = mpsc::unbounded_channel();
- let (errors_tx, errors_rx) = mpsc::unbounded_channel();
- let assignment_epoch = transport.assignment_epoch();
- let inner = Arc::new(BatcherInner {
- dispatcher,
- transport,
- assignment_epoch,
- completions: completions_tx,
- errors: errors_tx,
- });
- let (flush_queue, flush_rx) = mpsc::unbounded_channel();
- tokio::spawn(run_flush_driver(
- Arc::clone(&inner),
- flush_rx,
- handle,
- deferred_flush_timeout,
- ));
- (
- Self { inner, flush_queue },
- BatcherOutputs {
- completions: completions_rx,
- errors: errors_rx,
- },
- )
- }
-
- fn key_order_sentinel(&self) -> Arc<KeyOrderSentinel> {
- self.inner.dispatcher.key_order_sentinel()
- }
-
- /// Submit one poll's demuxed groups. Call on the consumer loop, in poll
- /// order. Returns the assignment epoch stamped on the poll's completions,
- /// so the consumer can correlate them without a second epoch read.
- ///
- /// Registration and assignment both happen here, synchronously, so both
- /// happen in true batch order. Registration first, so the stash learns
- /// batch order before failed-send deferrals (which land in gather order)
- /// can reach it. Assignment too: on spawned tasks, batch N+1's assign
- /// could beat batch N's to the pin table and send a key's newer messages
- /// first — per-key send order must be fixed exactly once, in Kafka order,
- /// at assignment. Send order is also established here, under the
- /// dispatcher's lock: `begin_send` is synchronous, so a key's sub-batches
- /// enter its worker's stream in assignment order.
- fn submit(&self, accumulator: Accumulator) -> u64 {
- let assignment_epoch = self.inner.assignment_epoch.current();
- let batch_id = make_batch_id();
- self.inner.dispatcher.register_batch(&batch_id);
- let assign_start = Instant::now();
- let groups = accumulator.into_groups();
- let Submission { pending, retained } = self.inner.dispatcher.assign_and_send(
- &batch_id,
- assignment_epoch,
- groups,
- |sub_batch| begin_send(&self.inner.transport, &batch_id, sub_batch, false),
- );
- // Assignment serializes on the consumer loop (it does not overlap
- // batch collection) — watch this stays a small fraction of the batch
- // collection interval.
- histogram!("ingestion_consumer_assign_duration_seconds")
- .record(assign_start.elapsed().as_secs_f64());
-
- let scatter = tokio::spawn(run_scatter(
- Arc::clone(&self.inner),
- batch_id.clone(),
- pending,
- retained,
- assignment_epoch,
- ));
- let _ = self.flush_queue.send(FlushTicket {
- batch_id,
- assignment_epoch,
- scatter,
- });
- assignment_epoch
+ self.0.purge_revoked(partitions);
}
}
-/// Await a batch's pre-ordered sub-batch sends and feed passive health
-/// signals. Reports a batch that had no usable workers, and records the
-/// scatter duration on success.
-async fn run_scatter(
- inner: Arc<BatcherInner>,
- batch_id: String,
- pending: Vec<PendingSubBatch>,
- retained: bool,
- assignment_epoch: u64,
-) {
- // Use the submission's synchronous assignment outcome. Mutable scheduler
- // state may have changed by the time this spawned task runs.
- if pending.is_empty() && !retained {
- counter!("ingestion_consumer_no_healthy_workers_total").increment(1);
- inner.report_error("No healthy workers available to route batch".to_string());
- return;
- }
- let start = Instant::now();
- match scatter(&inner, &batch_id, pending, false, assignment_epoch).await {
- Ok(_) => {
- histogram!("ingestion_consumer_batch_processing_duration_seconds")
- .record(start.elapsed().as_secs_f64());
- info!(batch_id = %batch_id, "Kafka batch processing completed");
- }
- Err(err) => inner.report_error(format!("awaiting sub-batches failed: {err:#}")),
- }
-}
-
-/// Await sub-batch sends in parallel and resolve each in the dispatcher.
-/// On a send failure (the worker died mid-send, or its worker stream was fenced),
-/// the failed messages are deferred — before the resolve, so the pin
-/// isn't evicted — to be replayed in order. A successful send emits one
-/// completion per group it carried. Returns the number of messages accepted.
-///
-/// `from_flush` is true when awaiting sub-batches produced by the flush driver:
-/// the resolve then clears one deferral per key, so a key stays deferring from
-/// when it was first held until its flushed messages actually land (preventing
-/// a newer batch from racing them).
-async fn scatter(
- inner: &Arc<BatcherInner>,
- batch_id: &str,
- pending: Vec<PendingSubBatch>,
- from_flush: bool,
- assignment_epoch: u64,
-) -> anyhow::Result<u32> {
- let mut handles = Vec::with_capacity(pending.len());
- for sub_batch in pending {
- handles.push(tokio::spawn(await_settled(
- Arc::clone(inner),
- batch_id.to_string(),
- sub_batch,
- from_flush,
- assignment_epoch,
- )));
- }
-
- let mut accepted = 0u32;
- for handle in handles {
- accepted += handle.await?;
- }
- Ok(accepted)
-}
-
-/// Await one in-flight send, settle it in one seam call, and spawn an
-/// awaiter for every follow-up send the settlement dispatched (the key
-/// table releases a key's next run at settlement). Every begin_send gets
-/// exactly one awaiter, so every dispatch settles exactly once.
-async fn await_settled(
- inner: Arc<BatcherInner>,
- batch_id: String,
- sub_batch: PendingSubBatch,
- from_flush: bool,
- batch_epoch: u64,
-) -> u32 {
- let PendingSubBatch {
- worker,
- routing_keys,
- key_offsets,
- message_count,
- groups,
- assignment_epoch: run_epoch,
- pending,
- } = sub_batch;
-
- match pending.wait().await {
- // The dispatcher sends no budget, and the transport refuses a partial
- // ack for an unbudgeted sub-batch.
- Ok(SendOutcome::Partial { .. }) => {
- inner.report_error("partial ack for a pin_stash send".to_string());
- 0
- }
- Ok(SendOutcome::Accepted(accepted)) => {
- // Advance ACK high-water marks before the settle, which
- // may evict the keys' sentinel state.
- inner.dispatcher.on_sub_batch_acked(&key_offsets);
- let followups = settle_and_send(
- &inner,
- &worker,
- message_count,
- &routing_keys,
- from_flush,
- None,
- );
- inner.dispatcher.record_send_outcome(&worker, false);
- send_group_completions(
- &inner.completions,
- groups,
- run_epoch.unwrap_or(batch_epoch),
- accepted,
- );
- spawn_followups(&inner, followups, batch_epoch);
- accepted
- }
- Err(send_err) => {
- // One settlement call requeues the failed messages and
- // releases the keys together, so a newer send cannot
- // overtake them.
- // Backpressure (a busy worker) is transient, not a fault:
- // re-route the work but do not count it against the
- // worker's health, so passive health tracks real faults.
- let SendError {
- error,
- messages,
- fence_guard,
- } = send_err;
- let is_fault = !error.is_backpressure();
- let followups = settle_and_send(
- &inner,
- &worker,
- message_count,
- &routing_keys,
- from_flush,
- Some((batch_id, messages)),
- );
- // Stashed: let the worker stream stop fencing new arrivals.
- drop(fence_guard);
- inner.dispatcher.record_send_outcome(&worker, is_fault);
- spawn_followups(&inner, followups, batch_epoch);
- 0
- }
- }
-}
-
-/// Settle one send and begin the settlement's follow-up sends under the
-/// dispatcher lock. Follow-up sends belong to no poll, so they go on the
-/// wire under a fresh batch id, minted for correlation and logs.
-fn settle_and_send(
- inner: &Arc<BatcherInner>,
- worker: &WorkerId,
- message_count: usize,
- routing_keys: &[String],
- from_flush: bool,
- failed: Option<(String, Vec<SerializedKafkaMessage>)>,
-) -> (String, Vec<PendingSubBatch>) {
- let settle_id = make_batch_id();
- let followups = inner.dispatcher.settle_and_send(
- worker,
- message_count,
- routing_keys,
- from_flush,
- failed,
- |sub_batch| begin_send(&inner.transport, &settle_id, sub_batch, false),
- );
- (settle_id, followups)
-}
-
-/// Spawn one detached awaiter per follow-up send. Follow-ups are never
-/// flush sends, and their completions are stamped from their run's epoch.
-fn spawn_followups(
- inner: &Arc<BatcherInner>,
- (settle_id, followups): (String, Vec<PendingSubBatch>),
- batch_epoch: u64,
-) {
- for sub_batch in followups {
- drop(tokio::spawn(await_settled(
- Arc::clone(inner),
- settle_id.clone(),
- sub_batch,
- false,
- batch_epoch,
- )));
- }
-}
-
-/// Flush each batch's deferred groups (keys whose worker was draining/dead)
-/// in submit order, re-routing them to healthy workers. Serialized, oldest
-/// batch first, after that batch's own scatter has resolved, which preserves
-/// per-key order across batches. Retries with backoff while a flush can't
-/// route (no healthy worker yet).
-///
-/// The stall deadline bounds **stalls, not total time**: it resets whenever
-/// any of the batch's messages are accepted, so a large backlog draining
-/// slowly under saturation keeps going, and the batcher only reports failure
-/// — 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.
-async fn run_flush_driver(
- inner: Arc<BatcherInner>,
- mut tickets: mpsc::UnboundedReceiver<FlushTicket>,
- handle: Handle,
- deferred_flush_timeout: Duration,
-) {
- while let Some(ticket) = tickets.recv().await {
- if let Err(err) = ticket.scatter.await {
- inner.report_error(format!("batch processing task failed: {err:#}"));
- return;
- }
- if inner.dispatcher.has_unfinished_flush(&ticket.batch_id) {
- let mut stall_deadline = Instant::now() + deferred_flush_timeout;
- while inner.dispatcher.has_unfinished_flush(&ticket.batch_id) {
- if Instant::now() >= stall_deadline {
- inner.report_error(
- "deferred messages made no progress within the flush timeout".to_string(),
- );
- return;
- }
- // Serialized on this driver, oldest batch first, so
- // begin_send order preserves the flush's key order.
- let pending = inner
- .dispatcher
- .flush_deferred_and_send(&ticket.batch_id, |sub_batch| {
- begin_send(&inner.transport, &ticket.batch_id, sub_batch, true)
- });
- if pending.is_empty() {
- // Nothing is routable right now (no healthy worker), so wait.
- tokio::select! {
- _ = handle.shutdown_recv() => {
- inner.report_error(
- "shutdown while flushing deferred messages".to_string(),
- );
- return;
- }
- _ = tokio::time::sleep(Duration::from_millis(200)) => {
- handle.report_healthy();
- }
- }
- } else {
- match scatter(
- &inner,
- &ticket.batch_id,
- pending,
- true,
- ticket.assignment_epoch,
- )
- .await
- {
- Ok(accepted) if accepted > 0 => {
- stall_deadline = Instant::now() + deferred_flush_timeout;
- }
- Ok(_) => {}
- Err(err) => {
- inner.report_error(format!(
- "awaiting flushed sub-batches failed: {err:#}"
- ));
- return;
- }
- }
- }
- }
- }
- inner.dispatcher.release_batch(&ticket.batch_id);
- }
-}
-
-/// Establish a sub-batch's send order. Synchronous and non-blocking on
-/// purpose: called under the dispatcher's lock, 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,
- sub_batch: SubBatch,
- replay: bool,
-) -> PendingSubBatch {
- let SubBatch {
- worker,
- messages,
- routing_keys,
- key_offsets,
- assignment_epoch,
- } = sub_batch;
- let groups = completion_groups(&messages);
- let message_count = messages.len();
- let pending = transport.begin_send(&worker, batch_id, messages, replay);
- PendingSubBatch {
- worker,
- routing_keys,
- key_offsets,
- message_count,
- groups,
- assignment_epoch,
- pending,
- }
-}
-
-/// Reconstruct the accumulator's groups from a sub-batch's messages: one
-/// group per partition and key, a keyless message on its own. The dispatcher
-/// may merge one key's groups from two partitions into one sub-batch (the pin
-/// table is partition-blind); a completion names one partition, so the merge
-/// splits back here.
-fn completion_groups(messages: &[SerializedKafkaMessage]) -> Vec<CompletionGroup> {
- let mut groups: Vec<CompletionGroup> = Vec::new();
- let mut index_by_key: HashMap<(Partition, &str), usize> = HashMap::new();
- for message in messages {
- let partition = Partition(message.partition);
- let offset = Offset(message.offset);
- match message.key.as_deref() {
- None => groups.push(CompletionGroup {
- partition,
- offsets: vec![offset],
- }),
- Some(key) => match index_by_key.get(&(partition, key)) {
- Some(&index) => groups[index].offsets.push(offset),
- None => {
- index_by_key.insert((partition, key), groups.len());
- groups.push(CompletionGroup {
- partition,
- offsets: vec![offset],
- });
- }
- },
- }
- }
- groups
-}
-
pub(crate) fn make_batch_id() -> String {
let ts = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -732,83 +134,3 @@ pub(crate) fn make_batch_id() -> String {
let rand: u32 = rand::random();
format!("{ts:x}-{rand:08x}")
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn message(partition: i32, offset: i64, key: Option<&str>) -> SerializedKafkaMessage {
- SerializedKafkaMessage {
- topic: "test".into(),
- partition,
- offset,
- timestamp: 0,
- key: key.map(|k| k.to_string()),
- value: None,
- headers: HashMap::new(),
- }
- }
-
- fn shapes(groups: &[CompletionGroup]) -> Vec<(i32, Vec<i64>)> {
- groups
- .iter()
- .map(|g| (g.partition.0, g.offsets.iter().map(|o| o.0).collect()))
- .collect()
- }
-
- #[test]
- fn completion_groups_split_per_partition_and_key() {
- // The dispatcher merges one key across partitions into one sub-batch;
- // the completion groups must split it back per partition.
- let groups = completion_groups(&[
- message(0, 1, Some("a")),
- message(0, 2, Some("b")),
- message(3, 9, Some("a")),
- message(0, 4, Some("a")),
- ]);
- assert_eq!(
- shapes(&groups),
- vec![(0, vec![1, 4]), (0, vec![2]), (3, vec![9])]
- );
- }
-
- #[test]
- fn completion_groups_keep_keyless_messages_alone() {
- let groups = completion_groups(&[
- message(7, 42, None),
- message(7, 43, None),
- message(7, 44, Some("a")),
- ]);
- assert_eq!(
- shapes(&groups),
- vec![(7, vec![42]), (7, vec![43]), (7, vec![44])]
- );
- }
-
- #[tokio::test]
- async fn send_group_completions_apportions_an_under_reported_accepted_count() {
- let (completions_tx, mut completions_rx) = mpsc::unbounded_channel();
-
- let groups = vec![
- CompletionGroup {
- partition: Partition(0),
- offsets: vec![Offset(1), Offset(2)],
- },
- CompletionGroup {
- partition: Partition(0),
- offsets: vec![Offset(3), Offset(4)],
- },
- ];
- send_group_completions(&completions_tx, groups, 5, 3);
-
- let first = completions_rx.recv().await.expect("first completion");
- assert_eq!(first.assignment_epoch, 5);
- assert_eq!(first.offsets, vec![Offset(1), Offset(2)]);
- assert_eq!(first.accepted, 2);
- // The worker under-reported by one, so the tail group is shorted and
- // the consumer's accepted check fails the poll.
- let second = completions_rx.recv().await.expect("second completion");
- assert_eq!(second.offsets, vec![Offset(3), Offset(4)]);
- assert_eq!(second.accepted, 1);
- }
-}
diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rs
index c993b084872b..c39b88a5b2db 100644
--- a/rust/ingestion-consumer/src/config.rs
+++ b/rust/ingestion-consumer/src/config.rs
@@ -13,7 +13,6 @@ use crate::batcher::state_machine::{BatcherStateMachine, RequestBudget};
use crate::batcher::worker_assigner::WorkerAssigner;
use crate::discovery::DiscoveryMode;
use crate::routing::{Router, RoutingStrategy};
-use crate::scheduler::SchedulerKind;
use common_kafka_consumer::config::ConsumerConfigBuilder;
/// Configuration for the ingestion consumer.
@@ -163,36 +162,31 @@ pub struct Config {
#[envconfig(default = "500")]
pub consumer_batch_timeout_ms: u64,
- /// 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.
+ /// No-progress bound on the batcher's pending work (milliseconds): the
+ /// deadline resets whenever a worker accepts a request, so a slow drain
+ /// keeps going and the consumer only fails (exiting the process) after a
+ /// full window with pending work and nothing landed, for example with 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,
- /// How long the key-table scheduler waits before it retries a failed
- /// send, and how often a request with no routable worker tries again
- /// (milliseconds). Matches the flush driver's retry cadence, so the
- /// scheduler switch does not regress recovery latency. Only read under
- /// `INGESTION_SCHEDULER=key_table`.
+ /// How long the batcher waits before it retries a failed send, and how
+ /// often a request with no routable worker tries again (milliseconds).
#[envconfig(from = "INGESTION_PARKED_RETRY_INTERVAL_MS", default = "200")]
pub parked_retry_interval_ms: u64,
- /// Target request size in events for the key-table packer: once this many
- /// events are ready, a free worker slot gets a request at once. Unless a
- /// run cap is set, one key's run never holds more, so a key's backlog
- /// leaves in consecutive requests. `0` disables the event target and the
- /// cap, and needs a byte target. Only read under
- /// `INGESTION_SCHEDULER=key_table`.
+ /// Target request size in events for the packer: once this many events
+ /// are ready, a free worker slot gets a request at once. Unless a run cap
+ /// is set, one key's run never holds more, so a key's backlog leaves in
+ /// consecutive requests. `0` disables the event target and the cap, and
+ /// needs a byte target.
#[envconfig(from = "INGESTION_PACK_TARGET_EVENTS", default = "500")]
pub pack_target_events: usize,
- /// Target request size in key-plus-value bytes for the key-table packer.
- /// Unless a run cap is set, one key's run never holds more. `0` (default)
- /// disables the byte target and the cap, and needs an event target. Only
- /// read under `INGESTION_SCHEDULER=key_table`.
+ /// Target request size in key-plus-value bytes for the packer. Unless a
+ /// run cap is set, one key's run never holds more. `0` (default) disables
+ /// the byte target and the cap, and needs an event target.
#[envconfig(from = "INGESTION_PACK_TARGET_BYTES", default = "0")]
pub pack_target_bytes: usize,
@@ -205,19 +199,17 @@ pub struct Config {
pub run_cap_bytes: usize,
/// How long ready events below the target wait for more, counted from
- /// when a worker slot is free for them, before the key-table packer sends
- /// them short of the target (milliseconds). `0` (default) waits for
- /// nothing: each free slot gets what is ready, packed up to the target.
- /// At most half of `CONSUMER_DEFERRED_FLUSH_TIMEOUT_MS`. Only read under
- /// `INGESTION_SCHEDULER=key_table`.
+ /// when a worker slot is free for them, before the packer sends them
+ /// short of the target (milliseconds). `0` (default) waits for nothing:
+ /// each free slot gets what is ready, packed up to the target. At most
+ /// half of `CONSUMER_DEFERRED_FLUSH_TIMEOUT_MS`.
#[envconfig(from = "INGESTION_PACK_LATENCY_BUDGET_MS", default = "0")]
pub pack_latency_budget_ms: u64,
- /// How long a worker may spend on one key-table request before it stops
- /// starting work and acks what finished as partial (milliseconds). `0`
- /// (default) sends no budget, otherwise at least 100. Needs
- /// `INGESTION_SCHEDULER=key_table`. See `request_budget` for the bounds
- /// against the ack and stall timeouts.
+ /// How long a worker may spend on one request before it stops starting
+ /// work and acks what finished as partial (milliseconds). `0` (default)
+ /// sends no budget, otherwise at least 100. See `request_budget` for the
+ /// bounds against the ack and stall timeouts.
#[envconfig(from = "INGESTION_REQUEST_SOFT_BUDGET_MS", default = "0")]
pub request_soft_budget_ms: u64,
@@ -331,19 +323,12 @@ pub struct Config {
#[envconfig(from = "WORKER_DRAIN_TIMEOUT_MS", default = "30000")]
pub worker_drain_timeout_ms: u64,
- /// How unpinned routing keys are assigned to workers: `p2c` (default,
+ /// How requests are placed on workers: `p2c` (default,
/// power-of-two-choices — herd-resistant for a shared worker pool) or
/// `aperture` (P2C within this consumer's slice of the worker ring).
#[envconfig(from = "INGESTION_ROUTING_STRATEGY", default = "p2c")]
pub routing_strategy: RoutingStrategy,
- /// Which scheduler orders and places runs: `pin_stash` (default, sticky
- /// pins with a per-batch stash) or `key_table` (the batcher state
- /// machine: at most one in-flight request per key, with packing). The
- /// switch back is the rollback.
- #[envconfig(from = "INGESTION_SCHEDULER", default = "pin_stash")]
- pub scheduler: SchedulerKind,
-
/// Minimum aperture width for `INGESTION_ROUTING_STRATEGY=aperture`: how
/// many workers this dispatcher's ring slice spans. The effective width
/// is floored at `ceil(pool / dispatchers)` so the fleet's slices always
@@ -372,8 +357,8 @@ pub struct Config {
#[envconfig(default = "5000")]
pub worker_probe_interval_ms: u64,
- /// Time a worker must spend in Unhealthy before it is declared dead and
- /// sticky pins are dropped (milliseconds).
+ /// Time a worker must spend in Unhealthy before it is declared dead
+ /// (milliseconds).
#[envconfig(default = "15000")]
pub worker_dead_declaration_ms: u64,
@@ -460,9 +445,9 @@ impl Config {
format!("{}:{}", self.bind_host, self.bind_port)
}
- /// The key-table scheduler's state machine. It reuses the stream's
- /// un-acked cap as its per-worker request cap, the parked-retry interval
- /// for every retry, and the deferred-flush timeout as its stall timeout.
+ /// The batcher state machine. It reuses the stream's un-acked cap as its
+ /// per-worker request cap, the parked-retry interval for every retry, and
+ /// the deferred-flush timeout as its stall timeout.
pub fn batcher_state_machine(&self) -> Result<BatcherStateMachine, String> {
let mut packer = Packer::new(PackTargets {
events: NonZeroUsize::new(self.pack_target_events),
@@ -498,13 +483,6 @@ impl Config {
if budget_ms == 0 {
return Ok(None);
}
- // pin_stash keeps several requests per key in flight, so a partial
- // ack's resend could overtake a newer request for the same key.
- if self.scheduler != SchedulerKind::KeyTable {
- return Err(
- "INGESTION_REQUEST_SOFT_BUDGET_MS needs INGESTION_SCHEDULER=key_table".to_string(),
- );
- }
// Below this the worker's fixed work per frame outlasts the budget, so
// nearly every request comes back partial with nothing finished.
if budget_ms < Self::MIN_REQUEST_SOFT_BUDGET_MS {
@@ -645,21 +623,14 @@ mod tests {
#[rstest]
#[case::unset(&[], None)]
- #[case::under_key_table(
- &[("INGESTION_SCHEDULER", "key_table"), ("INGESTION_REQUEST_SOFT_BUDGET_MS", "250")],
- Some((250, 3))
- )]
- #[case::at_the_floor(
- &[("INGESTION_SCHEDULER", "key_table"), ("INGESTION_REQUEST_SOFT_BUDGET_MS", "100")],
- Some((100, 3))
- )]
+ #[case::set(&[("INGESTION_REQUEST_SOFT_BUDGET_MS", "250")], Some((250, 3)))]
+ #[case::at_the_floor(&[("INGESTION_REQUEST_SOFT_BUDGET_MS", "100")], Some((100, 3)))]
#[case::just_below_the_ack_and_stall_timeouts(
- &[("INGESTION_SCHEDULER", "key_table"), ("INGESTION_REQUEST_SOFT_BUDGET_MS", "59999")],
+ &[("INGESTION_REQUEST_SOFT_BUDGET_MS", "59999")],
Some((59999, 3))
)]
#[case::just_below_the_stall_timeout_with_the_pack_latency(
&[
- ("INGESTION_SCHEDULER", "key_table"),
("INGESTION_REQUEST_SOFT_BUDGET_MS", "49999"),
("INGESTION_PACK_LATENCY_BUDGET_MS", "10000"),
],
@@ -677,33 +648,22 @@ mod tests {
}
#[rstest]
- #[case::under_pin_stash(&[
- ("INGESTION_SCHEDULER", "pin_stash"),
- ("INGESTION_REQUEST_SOFT_BUDGET_MS", "250"),
- ])]
- #[case::below_the_floor(&[
- ("INGESTION_SCHEDULER", "key_table"),
- ("INGESTION_REQUEST_SOFT_BUDGET_MS", "99"),
- ])]
+ #[case::below_the_floor(&[("INGESTION_REQUEST_SOFT_BUDGET_MS", "99")])]
#[case::longer_than_the_worker_honors(&[
- ("INGESTION_SCHEDULER", "key_table"),
("INGESTION_REQUEST_SOFT_BUDGET_MS", "2147483648"),
("INGESTION_WORKER_STREAM_ACK_TIMEOUT_MS", "4294967296"),
("CONSUMER_DEFERRED_FLUSH_TIMEOUT_MS", "4294967296"),
])]
#[case::at_the_ack_timeout_across_every_frame_in_flight(&[
- ("INGESTION_SCHEDULER", "key_table"),
("INGESTION_REQUEST_SOFT_BUDGET_MS", "15000"),
("INGESTION_WORKER_CONCURRENT_BATCHES", "4"),
])]
#[case::at_the_stall_timeout_with_the_pack_latency(&[
- ("INGESTION_SCHEDULER", "key_table"),
("INGESTION_REQUEST_SOFT_BUDGET_MS", "50000"),
("INGESTION_PACK_LATENCY_BUDGET_MS", "10000"),
("INGESTION_WORKER_STREAM_ACK_TIMEOUT_MS", "120000"),
])]
#[case::with_no_budgeted_attempt(&[
- ("INGESTION_SCHEDULER", "key_table"),
("INGESTION_REQUEST_SOFT_BUDGET_MS", "250"),
("INGESTION_REQUEST_BUDGET_ATTEMPTS", "0"),
])]
diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rs
index d400cd1d6b6f..9016d2e08c73 100644
--- a/rust/ingestion-consumer/src/consumer.rs
+++ b/rust/ingestion-consumer/src/consumer.rs
@@ -204,28 +204,25 @@ struct RevokedPartition {
}
/// The consumer's revocation hook: purge the batcher, and record the revoked
-/// partitions when the batcher's purge means their polls never complete.
+/// partitions, because the purge means their polls never complete.
fn revoke_hook(
revoker: Revoker,
ledger: Arc<TopicOffsetLedger>,
revoked_partitions: Arc<Mutex<Vec<RevokedPartition>>>,
) -> RevokeHook {
- let records_revocations = revoker.drops_revoked_polls();
Box::new(move |partitions| {
revoker.purge_revoked(partitions);
- if records_revocations {
- revoked_partitions
- .lock()
- .unwrap()
- .extend(partitions.iter().map(|(topic, partition)| {
- let topic_partition = TopicPartition::new(topic, *partition);
- let generation = ledger.generation(&topic_partition);
- RevokedPartition {
- topic_partition,
- generation,
- }
- }));
- }
+ revoked_partitions
+ .lock()
+ .unwrap()
+ .extend(partitions.iter().map(|(topic, partition)| {
+ let topic_partition = TopicPartition::new(topic, *partition);
+ let generation = ledger.generation(&topic_partition);
+ RevokedPartition {
+ topic_partition,
+ generation,
+ }
+ }));
})
}
@@ -381,7 +378,7 @@ pub struct IngestionConsumer {
/// partitions on rebalance.
topic_offset_ledger: Arc<TopicOffsetLedger>,
/// Partitions revoked since the loop last looked, fed by the rebalance
- /// callback. Only populated under the key-table scheduler.
+ /// callback.
revoked_partitions: Arc<Mutex<Vec<RevokedPartition>>>,
}
diff --git a/rust/ingestion-consumer/src/debug_recorder.rs b/rust/ingestion-consumer/src/debug_recorder.rs
index f0751cdcb5d8..aa1280d40870 100644
--- a/rust/ingestion-consumer/src/debug_recorder.rs
+++ b/rust/ingestion-consumer/src/debug_recorder.rs
@@ -2,12 +2,12 @@
//! ingestion control plane UI).
//!
//! When `DEBUG_API_ENABLED` is set, an `Arc<DebugRecorder>` is injected into
-//! the dispatcher, consumer, transport, and worker registry. Each records a
-//! structured [`DebugEvent`] at the same points it already emits metrics —
-//! batch assignment, sub-batch resolution, deferral/flush, retries, worker
-//! health transitions. The recorder keeps a bounded rolling window of recent
-//! events (for a client connecting mid-stream to see history) and broadcasts
-//! every new event to live subscribers (the SSE feed at `/debug/events`).
+//! the consumer and the worker registry. Each records a structured
+//! [`DebugEvent`] at the same points it already emits metrics: batch
+//! dispatch, commit and failure, worker health transitions and membership.
+//! The recorder keeps a bounded rolling window of recent events (for a client
+//! connecting mid-stream to see history) and broadcasts every new event to
+//! live subscribers (the SSE feed at `/debug/events`).
//!
//! It is a pure observer: it never influences routing. When the feature is off,
//! the recorder is `None` everywhere and nothing is constructed or recorded.
@@ -20,14 +20,6 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH};
use serde::Serialize;
use tokio::sync::broadcast;
-/// One worker's slice of an assigned (or flushed) batch.
-#[derive(Clone, Serialize)]
-pub struct SubBatchInfo {
- pub worker: String,
- pub messages: usize,
- pub routing_keys: usize,
-}
-
/// A topic-partition and the batch's max offset there, with observed lag.
#[derive(Clone, Serialize)]
pub struct PartitionOffset {
@@ -54,33 +46,6 @@ pub enum DebugEventKind {
messages: usize,
partitions: Vec<PartitionOffset>,
},
- /// The dispatcher grouped a batch by Kafka key and assigned sub-batches.
- BatchAssigned {
- batch_id: String,
- routing_keys: usize,
- sub_batches: Vec<SubBatchInfo>,
- deferred_groups: u64,
- unroutable_groups: u64,
- },
- /// A sub-batch resolved (ACK), releasing the worker's outstanding load.
- SubBatchResolved {
- worker: String,
- messages: usize,
- routing_keys: usize,
- cleared_deferral: bool,
- },
- /// Messages were stashed rather than sent
- /// (`reason`: drain/queued_behind_deferral/unroutable/send_failed).
- Deferred {
- batch_id: String,
- reason: &'static str,
- groups: u64,
- },
- /// Previously-deferred groups were re-routed to healthy workers.
- DeferredFlushed {
- batch_id: String,
- sub_batches: Vec<SubBatchInfo>,
- },
/// A batch's offsets were committed to Kafka.
BatchCommitted {
batch_id: String,
@@ -133,26 +98,18 @@ pub struct WorkerHealthSnapshot {
pub passive_samples: usize,
}
-/// Per-worker outstanding in-flight load.
-#[derive(Serialize)]
-pub struct LoadEntry {
- pub worker: String,
- pub in_flight: usize,
-}
-
-/// The dispatcher's current load/pin/stash accounting.
+/// The batcher's current load accounting.
#[derive(Serialize)]
-pub struct DispatcherLoad {
- pub per_worker: Vec<LoadEntry>,
+pub struct BatcherLoad {
+ /// Messages sent and not yet resolved.
pub total_in_flight: usize,
- pub pin_count: usize,
- pub stashed_messages: usize,
- pub stashed_batches: usize,
+ /// Messages held for a later send: queued, packed and unplaced.
+ pub pending_messages: usize,
}
-/// The dispatcher's routing configuration and, under aperture, its current
-/// ring slice — computed by the same code the assignment path uses, so what
-/// this reports is what the next batch would route with.
+/// The consumer's routing configuration and, under aperture, its current
+/// ring slice, computed by the same code the placement path uses, so what
+/// this reports is what the next request would route with.
#[derive(Serialize)]
pub struct RoutingDebug {
/// Configured strategy (`p2c`, `aperture`).
@@ -161,13 +118,14 @@ pub struct RoutingDebug {
pub min_aperture: Option<usize>,
/// The canonical sorted worker ring shared by all peers.
pub ring: Vec<String>,
- /// This dispatcher's current slice candidates for unpinned keys; `None`
+ /// This consumer's current slice candidates for fresh requests; `None`
/// when routing uses the full healthy pool (non-aperture strategy, or
/// aperture falling back while the peer set is unknown).
pub slice: Option<Vec<String>>,
}
-/// Merged worker row: registry health plus the dispatcher's in-flight count.
+/// Merged worker row: registry health plus whether the batcher has a request
+/// in flight on the worker.
#[derive(Serialize)]
pub struct WorkerStatus {
pub url: String,
@@ -176,7 +134,7 @@ pub struct WorkerStatus {
pub consecutive_probe_failures: u32,
pub passive_error_rate: f64,
pub passive_samples: usize,
- pub in_flight_messages: usize,
+ pub busy: bool,
}
/// The full snapshot returned by `/debug/state` (workers + load + event backlog).
@@ -184,7 +142,7 @@ pub struct WorkerStatus {
pub struct DebugState {
pub group_id: String,
pub workers: Vec<WorkerStatus>,
- pub dispatcher: DispatcherLoad,
+ pub batcher: BatcherLoad,
/// This pod's index among its ready peers; `None` while not yet ready or
/// when peer awareness is disabled.
pub peer_index: Option<usize>,
@@ -194,13 +152,13 @@ pub struct DebugState {
pub events: Vec<DebugEvent>,
}
-/// Lightweight snapshot returned by `/debug/load` — workers + dispatcher load
+/// Lightweight snapshot returned by `/debug/load`: workers and batcher load
/// only, no event backlog, so the UI can poll it at a high rate cheaply.
#[derive(Serialize)]
pub struct DebugLoad {
pub group_id: String,
pub workers: Vec<WorkerStatus>,
- pub dispatcher: DispatcherLoad,
+ pub batcher: BatcherLoad,
/// See [`DebugState::peer_index`].
pub peer_index: Option<usize>,
/// See [`DebugState::peer_count`].
diff --git a/rust/ingestion-consumer/src/discovery.rs b/rust/ingestion-consumer/src/discovery.rs
index 9a29c25c473b..7dd3dd161982 100644
--- a/rust/ingestion-consumer/src/discovery.rs
+++ b/rust/ingestion-consumer/src/discovery.rs
@@ -9,7 +9,7 @@
//! membership watch ([`k8s_awareness::watch_service_members`]) and keeps the
//! registry in sync as worker pods join/leave (the separately-deployed pool).
//!
-//! Routing stays client-side in the dispatcher; discovery only supplies the
+//! Routing stays client-side in the batcher; discovery only supplies the
//! member list. A departed worker is marked *draining* (it keeps finishing
//! in-flight work) rather than removed outright; the reaper in `main` removes it
//! from the registry and transport once it has drained or timed out.
diff --git a/rust/ingestion-consumer/src/dispatcher.rs b/rust/ingestion-consumer/src/dispatcher.rs
deleted file mode 100644
index 5628894a2f12..000000000000
--- a/rust/ingestion-consumer/src/dispatcher.rs
+++ /dev/null
@@ -1,2208 +0,0 @@
-use std::collections::HashMap;
-use std::sync::{Arc, Mutex};
-
-use common_kafka_consumer::{Offset, Partition};
-use k8s_awareness::PeerTracker;
-use metrics::{counter, histogram};
-
-use crate::aperture;
-use crate::batcher::worker_pool::{WorkerPool, WorkerPoolSource};
-use crate::debug_recorder::{
- record_if, DebugEventKind, DebugRecorder, DispatcherLoad, LoadEntry, RoutingDebug, SubBatchInfo,
-};
-use crate::order_sentinel::KeyOrderSentinel;
-use crate::routing::{Router, RoutingStrategy, WorkerLoad};
-use crate::scheduler::{
- Dispatch, KeyRun, PinStashScheduler, Scheduler, SchedulerEffects, Settlement,
- SettlementOutcome, WorkerHealth, WorkerSnapshot,
-};
-use crate::types::{Accumulator, Group, SerializedKafkaMessage};
-use crate::worker_registry::{WorkerId, WorkerRegistry};
-
-/// The max offset a sub-batch carries for one routing key, over keyed
-/// messages only (null-key offsets live on arbitrary partitions and carry no
-/// per-key order promise). Passed back via
-/// [`Dispatcher::on_sub_batch_acked`] when the worker ACKs, so the
-/// [`KeyOrderSentinel`] can advance the key's ACK high-water mark.
-#[derive(Clone)]
-pub struct KeyOffset {
- pub routing_key: String,
- pub max_offset: i64,
-}
-
-/// A slice of a batch assigned to one worker, carrying the messages and the
-/// routing keys they belong to. Routing keys are needed to decrement pin
-/// ref-counts when the sub-batch resolves.
-pub struct SubBatch {
- pub worker: WorkerId,
- pub messages: Vec<SerializedKafkaMessage>,
- /// Unique routing keys contained in this sub-batch. Pass back to
- /// `Dispatcher::settle` on ACK or DLQ.
- pub routing_keys: Vec<String>,
- /// Per-key max offsets. Pass back to `Dispatcher::on_sub_batch_acked` on
- /// a successful ACK (only) so the order sentinel tracks ACK progress.
- pub key_offsets: Vec<KeyOffset>,
- /// The runs' epoch, for stamping completions; `None` from the pin-stash
- /// scheduler, whose completions are stamped by the awaiting batch.
- pub assignment_epoch: Option<u64>,
-}
-
-struct WorkerSubBatchBuilder {
- messages: Vec<SerializedKafkaMessage>,
- routing_keys: Vec<String>,
- key_offsets: Vec<KeyOffset>,
-}
-
-impl WorkerSubBatchBuilder {
- fn is_empty(&self) -> bool {
- self.messages.is_empty()
- }
-
- fn message_count(&self) -> usize {
- self.messages.len()
- }
-}
-
-#[derive(Default)]
-struct WorkerAssignments {
- /// Keyed by worker and epoch, so a sub-batch never mixes runs from two
- /// epochs and its completions carry one stamp.
- by_worker: HashMap<(WorkerId, Option<u64>), WorkerSubBatchBuilder>,
-}
-
-impl WorkerAssignments {
- fn new() -> Self {
- Self::default()
- }
-
- fn add_dispatch(&mut self, dispatch: Dispatch) {
- let Dispatch {
- worker,
- routing_key,
- messages,
- assignment_epoch,
- ..
- } = dispatch;
- let builder = self
- .by_worker
- .entry((worker, assignment_epoch))
- .or_insert_with(|| WorkerSubBatchBuilder {
- messages: Vec::new(),
- routing_keys: Vec::new(),
- key_offsets: Vec::new(),
- });
-
- // Only keyed messages participate in the key-order sentinel: an
- // unkeyed message lives on an arbitrary partition and is grouped under
- // a synthetic key, so it has no ACK watermark to advance.
- if let Some(max_offset) = messages
- .iter()
- .filter(|m| m.key.is_some())
- .map(|m| m.offset)
- .max()
- {
- builder.key_offsets.push(KeyOffset {
- routing_key: routing_key.clone(),
- max_offset,
- });
- }
- builder.messages.extend(messages);
- builder.routing_keys.push(routing_key);
- }
-
- fn sub_batch_infos(&self) -> Vec<SubBatchInfo> {
- self.by_worker
- .iter()
- .filter(|(_, builder)| !builder.is_empty())
- .map(|((worker, _), builder)| SubBatchInfo {
- worker: worker.to_string(),
- messages: builder.message_count(),
- routing_keys: builder.routing_keys.len(),
- })
- .collect()
- }
-
- fn routed_counts(&self) -> impl Iterator<Item = (WorkerId, usize)> + '_ {
- self.by_worker
- .iter()
- .filter(|(_, builder)| !builder.is_empty())
- .map(|((worker, _), builder)| (worker.clone(), builder.message_count()))
- }
-
- fn into_sub_batches(self) -> Vec<SubBatch> {
- self.by_worker
- .into_iter()
- .filter(|(_, builder)| !builder.is_empty())
- .map(|((worker, assignment_epoch), builder)| SubBatch {
- worker,
- messages: builder.messages,
- routing_keys: builder.routing_keys,
- key_offsets: builder.key_offsets,
- assignment_epoch,
- })
- .collect()
- }
-}
-
-/// The immediate result of assigning one submission while the scheduler lock
-/// is held. `retained` describes this submission, not mutable table state that
-/// a later task might observe after a purge or settlement.
-pub struct Submission<T> {
- pub pending: Vec<T>,
- pub retained: bool,
-}
-
-/// The scheduler and the load table, behind the dispatcher's single Mutex.
-struct DispatcherInner {
- /// The decision core. Every ordering and placement decision happens in
- /// its seam calls; the dispatcher applies the returned effects.
- scheduler: PinStashScheduler,
- /// Outstanding (in-flight) message count per worker. Both routing
- /// strategies use it as the per-worker load signal so new key-groups land
- /// on lightly-loaded workers — load is balanced by message volume rather
- /// than by sub-batch count. A worker with no outstanding messages has no
- /// entry.
- in_flight: WorkerLoad,
-}
-
-/// Routes batches to workers: the plumbing around the [`Scheduler`] seam.
-///
-/// The dispatcher owns the lock, the in-flight load table, the metrics and
-/// debug events, the sentinel calls, and the sub-batch assembly. Every
-/// ordering and placement decision — honor a pin, defer behind the stash,
-/// route fresh, re-pin on flush, evict on settle — lives in the scheduler
-/// behind the seam. The dispatcher captures a [`WorkerSnapshot`] snapshot before
-/// each seam call and applies the returned [`SchedulerEffects`].
-pub struct Dispatcher {
- inner: Mutex<DispatcherInner>,
- registry: Arc<WorkerRegistry>,
- /// The configured routing strategy; the scheduler owns the router itself.
- /// Kept here for view construction (aperture narrowing) and debug.
- strategy: RoutingStrategy,
- /// Per-key send/ACK order checker. Called under the inner lock (lock
- /// order: inner → sentinel; the sentinel never takes the inner lock),
- /// so its check order matches the intended per-key send order.
- key_sentinel: Arc<KeyOrderSentinel>,
- /// The healthy pool and, under [`RoutingStrategy::Aperture`], this
- /// dispatcher's ring slice for fresh keys.
- pool_source: WorkerPoolSource,
- /// Debug event recorder; `None` unless `DEBUG_API_ENABLED`.
- debug_recorder: Option<Arc<DebugRecorder>>,
-}
-
-impl Dispatcher {
- /// Construct a dispatcher with the default routing strategy.
- pub fn new(registry: Arc<WorkerRegistry>) -> Self {
- Self::with_strategy(registry, RoutingStrategy::default())
- }
-
- /// Construct a dispatcher with an explicit routing strategy.
- pub fn with_strategy(registry: Arc<WorkerRegistry>, strategy: RoutingStrategy) -> Self {
- Self::from_router(registry, strategy, Router::new(strategy))
- }
-
- /// Test-only constructor with a seeded RNG so P2C selection is deterministic.
- #[cfg(test)]
- fn with_strategy_seeded(
- registry: Arc<WorkerRegistry>,
- strategy: RoutingStrategy,
- seed: u64,
- ) -> Self {
- Self::from_router(registry, strategy, Router::with_seed(strategy, seed))
- }
-
- fn from_router(
- registry: Arc<WorkerRegistry>,
- strategy: RoutingStrategy,
- router: Router,
- ) -> Self {
- Self {
- inner: Mutex::new(DispatcherInner {
- scheduler: PinStashScheduler::new(router),
- in_flight: WorkerLoad::new(),
- }),
- pool_source: WorkerPoolSource::new(Arc::clone(&registry), strategy),
- registry,
- strategy,
- key_sentinel: Arc::new(KeyOrderSentinel::new()),
- debug_recorder: None,
- }
- }
-
- /// The per-key order sentinel, shared with the consumer's rdkafka context
- /// so rebalances can reset its baselines.
- pub fn key_order_sentinel(&self) -> Arc<KeyOrderSentinel> {
- Arc::clone(&self.key_sentinel)
- }
-
- /// Enable deterministic-aperture candidate narrowing: unpinned keys route
- /// within this dispatcher's slice of the worker ring, `min_aperture` wide.
- /// Only consulted under [`RoutingStrategy::Aperture`]. Call before the
- /// dispatcher is shared.
- pub fn set_aperture(&mut self, tracker: Arc<PeerTracker>, min_aperture: usize) {
- self.pool_source.set_aperture(tracker, min_aperture);
- }
-
- /// The worker pool source, shared with the batcher state machine.
- pub fn worker_pool_source(&self) -> WorkerPoolSource {
- self.pool_source.clone()
- }
-
- /// Inject the debug UI recorder. Call before the dispatcher is shared.
- pub fn set_debug_recorder(&mut self, recorder: Arc<DebugRecorder>) {
- self.debug_recorder = Some(recorder);
- }
-
- /// Point-in-time load/pin/stash snapshot for the debug UI.
- pub fn debug_load(&self) -> DispatcherLoad {
- let inner = self.inner.lock().unwrap();
- let per_worker: Vec<LoadEntry> = inner
- .in_flight
- .iter()
- .map(|(worker, in_flight)| LoadEntry {
- worker: worker.to_string(),
- in_flight: *in_flight,
- })
- .collect();
- DispatcherLoad {
- total_in_flight: per_worker.iter().map(|e| e.in_flight).sum(),
- per_worker,
- pin_count: inner.scheduler.pin_count(),
- stashed_messages: inner.scheduler.stashed_messages(),
- stashed_batches: inner.scheduler.stashed_batches(),
- }
- }
-
- /// Routing strategy and current aperture slice for the debug UI. Runs the
- /// same ring/slice computation as assignment, over a worker view the caller
- /// captured in one registry effects — so within one debug response the ring,
- /// slice, and worker rows can't disagree under churn.
- pub fn debug_routing(&self, workers: Vec<WorkerId>, healthy: &[WorkerId]) -> RoutingDebug {
- let ring = aperture::sorted_ring(workers);
- let slice = self.pool_source.slice(&ring, healthy);
- RoutingDebug {
- strategy: self.strategy.as_str().to_string(),
- min_aperture: self.pool_source.min_aperture(),
- ring: ring.iter().map(|w| w.to_string()).collect(),
- slice: slice.map(|s| s.iter().map(|w| w.to_string()).collect()),
- }
- }
-
- /// Capture the worker world for one seam call: routable workers, the
- /// fresh-key candidates (aperture-narrowed when configured), per-worker
- /// health, and the current load table. The scheduler decides over this
- /// snapshot instead of querying the registry itself.
- fn worker_snapshot(&self, in_flight: &WorkerLoad) -> WorkerSnapshot {
- let WorkerPool {
- healthy,
- candidates,
- } = self.pool_source.pool();
- let workers = self
- .registry
- .workers()
- .into_iter()
- .map(|worker| {
- let health = WorkerHealth {
- dead: self.registry.is_dead(&worker),
- draining: self.registry.is_draining(&worker),
- };
- (worker, health)
- })
- .collect();
- WorkerSnapshot::new(healthy, candidates, in_flight.clone(), workers)
- }
-
- /// Assign a batch of messages to workers. Demuxes the messages into
- /// groups first, as the collect path does for a poll, then assigns them
- /// like [`Dispatcher::assign_and_send`]. Test-only entry point; the
- /// epoch is fixed at 0.
- pub fn assign(&self, batch_id: &str, messages: Vec<SerializedKafkaMessage>) -> Vec<SubBatch> {
- let mut inner = self.inner.lock().unwrap();
- self.assign_groups(&mut inner, batch_id, 0, demux(messages))
- }
-
- /// Assign a poll's groups to workers, then hand each sub-batch to `send`
- /// before releasing the lock. A key admitted here because nothing of
- /// its is deferred must enter its worker stream before a failed-send
- /// settlement can stash an older group for it: with the lock released in
- /// between, the stash could land first, the worker stream's fence could
- /// lift, and the newer group would ride the next stream ahead of the
- /// older one. `send` must not block.
- ///
- /// The scheduler decides per group (honor the pin, defer, route fresh, or
- /// hold an unroutable group); see [`PinStashScheduler::on_groups`].
- /// Sends one `SubBatch` per worker. Deferred groups stay in the stash and
- /// are flushed later via [`Dispatcher::flush_deferred`].
- pub fn assign_and_send<T>(
- &self,
- batch_id: &str,
- assignment_epoch: u64,
- groups: Vec<Group>,
- send: impl FnMut(SubBatch) -> T,
- ) -> Submission<T> {
- let mut inner = self.inner.lock().unwrap();
- let pending = self
- .assign_groups(&mut inner, batch_id, assignment_epoch, groups)
- .into_iter()
- .map(send)
- .collect();
- let retained = inner.scheduler.has_batch(batch_id);
- Submission { pending, retained }
- }
-
- fn assign_groups(
- &self,
- inner: &mut DispatcherInner,
- batch_id: &str,
- assignment_epoch: u64,
- groups: Vec<Group>,
- ) -> Vec<SubBatch> {
- let GroupedMessages {
- groups: runs,
- unkeyed_count,
- } = routing_groups(groups);
-
- if unkeyed_count > 0 {
- counter!("ingestion_consumer_dispatcher_unkeyed_messages_total")
- .increment(unkeyed_count);
- }
-
- let routing_keys = runs.len();
- histogram!("ingestion_consumer_routing_keys_per_batch").record(routing_keys as f64);
-
- let snapshot = self.worker_snapshot(&inner.in_flight);
- let SchedulerEffects {
- dispatches,
- deferred,
- ..
- } = inner
- .scheduler
- .on_groups(&snapshot, batch_id, assignment_epoch, runs);
- let assignments = self.note_and_assemble(dispatches);
-
- // Add each worker's message volume to its outstanding load.
- for (worker, message_count) in assignments.routed_counts() {
- *inner.in_flight.entry(worker.clone()).or_insert(0) += message_count;
- counter!(
- "ingestion_consumer_dispatcher_sub_batches_assigned_total",
- "worker" => worker.clone(),
- )
- .increment(1);
- counter!(
- "ingestion_consumer_dispatcher_messages_routed_total",
- "worker" => worker.clone(),
- )
- .increment(message_count as u64);
- }
-
- for (reason, count) in [
- ("drain", deferred.drain),
- ("queued_behind_deferral", deferred.queued_behind_deferral),
- ("unroutable", deferred.unroutable),
- ] {
- if count > 0 {
- record_if(&self.debug_recorder, || DebugEventKind::Deferred {
- batch_id: batch_id.to_string(),
- reason,
- groups: count,
- });
- }
- }
- record_if(&self.debug_recorder, || DebugEventKind::BatchAssigned {
- batch_id: batch_id.to_string(),
- routing_keys,
- sub_batches: assignments.sub_batch_infos(),
- deferred_groups: deferred.drain + deferred.queued_behind_deferral,
- unroutable_groups: deferred.unroutable,
- });
-
- assignments.into_sub_batches()
- }
-
- /// Note each dispatch with the key-order sentinel — dispatch order is the
- /// intended per-key send order, still under the inner lock — and assemble
- /// the per-worker sub-batches.
- fn note_and_assemble(&self, dispatches: Vec<Dispatch>) -> WorkerAssignments {
- let mut assignments = WorkerAssignments::new();
- let mut sentinel = self.key_sentinel.batch();
- for dispatch in dispatches {
- sentinel.note_sent(&dispatch.routing_key, &dispatch.messages, dispatch.kind);
- assignments.add_dispatch(dispatch);
- }
- assignments
- }
-
- /// Record a batch's arrival order for the stash. Must be called from the
- /// consumer loop in true batch order, before assignment — 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.inner
- .lock()
- .unwrap()
- .scheduler
- .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) {
- self.inner.lock().unwrap().scheduler.release_batch(batch_id);
- }
-
- /// Whether `batch_id` still has deferred groups awaiting flush.
- pub fn has_deferred(&self, batch_id: &str) -> bool {
- self.inner.lock().unwrap().scheduler.has_batch(batch_id)
- }
-
- /// Whether the batch still has deferred groups awaiting a flush.
- pub fn has_unfinished_flush(&self, batch_id: &str) -> bool {
- self.inner.lock().unwrap().scheduler.has_batch(batch_id)
- }
-
- /// 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 {
- self.inner.lock().unwrap().scheduler.has_batch(batch_id)
- }
-
- /// Whether the worker has any in-flight (sent, unresolved) messages. The
- /// reaper uses this to promptly complete a drain for a worker that was idle
- /// when it left the pool — its in-flight never resolves, so the registry's
- /// `complete_drain` (which fires from settlement) never would.
- pub fn has_in_flight(&self, worker: &WorkerId) -> bool {
- self.inner
- .lock()
- .unwrap()
- .in_flight
- .get(worker)
- .is_some_and(|&n| n > 0)
- }
-
- /// Total messages currently held in the stash across all batches. Exposed
- /// for observability and for tests to synchronize on deferral.
- pub fn stashed_messages(&self) -> usize {
- self.inner.lock().unwrap().scheduler.stashed_messages()
- }
-
- /// Number of live sticky pins. Exposed so tests can assert the pin table
- /// drains back to zero once all in-flight work has resolved — a leak here
- /// permanently skews routing.
- pub fn pin_count(&self) -> usize {
- self.inner.lock().unwrap().scheduler.pin_count()
- }
-
- /// Total outstanding (sent, unresolved) messages across all workers.
- /// Exposed so tests can assert the load accounting drains back to zero.
- pub fn total_in_flight(&self) -> usize {
- self.inner.lock().unwrap().in_flight.values().sum()
- }
-
- /// Defer messages whose send failed (the worker died mid-send) so they can
- /// be replayed in order. Production resolves a failed send atomically via
- /// [`Dispatcher::settle`]; this two-step path (defer, then a delivered-
- /// shaped settle) remains for tests that drive the halves separately, and
- /// must run **before** its settle so the ref-count drop doesn't evict the
- /// pin while the key still has work to replay.
- pub fn defer_failed(&self, batch_id: &str, messages: Vec<SerializedKafkaMessage>) {
- let mut inner = self.inner.lock().unwrap();
- let deferred_count = inner
- .scheduler
- .stash_failed(batch_id, runs_by_routing_key(messages));
- drop(inner);
- if deferred_count > 0 {
- counter!(
- "ingestion_consumer_dispatcher_deferred_groups_total",
- "reason" => "send_failed",
- )
- .increment(deferred_count);
- record_if(&self.debug_recorder, || DebugEventKind::Deferred {
- batch_id: batch_id.to_string(),
- reason: "send_failed",
- groups: deferred_count,
- });
- }
- }
-
- /// Flush a batch's deferred groups: fire the scheduler's retry deadline
- /// and send what routed. Groups that can't route yet (no healthy worker)
- /// stay stashed — call again after a backoff. Cross-key order is preserved
- /// because the caller flushes batches oldest-first.
- pub fn flush_deferred(&self, batch_id: &str) -> Vec<SubBatch> {
- let mut inner = self.inner.lock().unwrap();
- self.flush_groups(&mut inner, batch_id)
- }
-
- /// Flush, then hand each sub-batch to `send` before releasing the lock,
- /// for the same reason as `assign_and_send`. `send` must not block.
- pub fn flush_deferred_and_send<T>(
- &self,
- batch_id: &str,
- send: impl FnMut(SubBatch) -> T,
- ) -> Vec<T> {
- let mut inner = self.inner.lock().unwrap();
- self.flush_groups(&mut inner, batch_id)
- .into_iter()
- .map(send)
- .collect()
- }
-
- fn flush_groups(&self, inner: &mut DispatcherInner, batch_id: &str) -> Vec<SubBatch> {
- let snapshot = self.worker_snapshot(&inner.in_flight);
- let SchedulerEffects { dispatches, .. } = inner.scheduler.on_deadline(&snapshot, batch_id);
- if dispatches.is_empty() {
- return Vec::new();
- }
- let assignments = self.note_and_assemble(dispatches);
-
- for (worker, message_count) in assignments.routed_counts() {
- *inner.in_flight.entry(worker.clone()).or_insert(0) += message_count;
- counter!(
- "ingestion_consumer_dispatcher_deferred_flushed_total",
- "worker" => worker.to_string(),
- )
- .increment(message_count as u64);
- }
-
- if !assignments.by_worker.is_empty() {
- record_if(&self.debug_recorder, || DebugEventKind::DeferredFlushed {
- batch_id: batch_id.to_string(),
- sub_batches: assignments.sub_batch_infos(),
- });
- }
-
- assignments.into_sub_batches()
- }
-
- /// Resolve one send in a single seam call: subtract its load, requeue a
- /// failure's messages, clear deferrals, and evict idle pins. `failed`
- /// carries a failed send's batch id and messages; the scheduler requeues
- /// them before it releases the keys, so a newer send cannot overtake the
- /// failed messages. `from_flush` must be true only when resolving a
- /// flushed sub-batch: it decrements the key's outstanding deferral count,
- /// so the key keeps deferring newer messages from the moment it was first
- /// deferred until its flushed messages have actually landed.
- pub fn settle(
- &self,
- worker: &WorkerId,
- message_count: usize,
- routing_keys: &[String],
- from_flush: bool,
- failed: Option<(String, Vec<SerializedKafkaMessage>)>,
- ) {
- let unsent = self.settle_and_send(
- worker,
- message_count,
- routing_keys,
- from_flush,
- failed,
- |sub_batch| sub_batch,
- );
- debug_assert!(
- unsent.is_empty(),
- "settle dropped dispatches; use settle_and_send"
- );
- }
-
- /// Like [`Dispatcher::settle`], and additionally hands the settlement's
- /// dispatches to `send` under the lock — the key table releases a key's
- /// next run at settlement, and sending under the lock keeps a key's runs
- /// entering its worker's stream in dispatch order. The caller must await
- /// every returned send and settle it exactly once.
- pub fn settle_and_send<T>(
- &self,
- worker: &WorkerId,
- message_count: usize,
- routing_keys: &[String],
- from_flush: bool,
- failed: Option<(String, Vec<SerializedKafkaMessage>)>,
- send: impl FnMut(SubBatch) -> T,
- ) -> Vec<T> {
- let mut inner = self.inner.lock().unwrap();
-
- let now_zero = match inner.in_flight.get_mut(worker) {
- Some(load) => {
- *load = load.saturating_sub(message_count);
- *load == 0
- }
- None => false,
- };
- if now_zero {
- inner.in_flight.remove(worker);
- // A draining worker with no in-flight left has finished its work —
- // mark it reapable so it's removed promptly rather than at the timeout.
- if self.registry.is_draining(worker) {
- self.registry.complete_drain(worker);
- }
- }
-
- let failed_batch_id = failed.as_ref().map(|(batch_id, _)| batch_id.clone());
- let outcome = match failed {
- None => SettlementOutcome::Delivered,
- Some((batch_id, messages)) => SettlementOutcome::Failed {
- batch_id,
- runs: runs_by_routing_key(messages),
- },
- };
- let snapshot = self.worker_snapshot(&inner.in_flight);
- let effects = inner.scheduler.on_settled(
- &snapshot,
- Settlement {
- worker: worker.clone(),
- message_count,
- routing_keys: routing_keys.to_vec(),
- from_flush,
- outcome,
- },
- );
-
- let SchedulerEffects {
- dispatches,
- deferred,
- evicted_keys,
- } = effects;
-
- if !evicted_keys.is_empty() {
- let mut sentinel = self.key_sentinel.batch();
- for key in &evicted_keys {
- sentinel.evict(key);
- }
- counter!(
- "ingestion_consumer_dispatcher_pin_evictions_total",
- "reason" => "resolved",
- )
- .increment(evicted_keys.len() as u64);
- }
-
- let sent: Vec<T> = if dispatches.is_empty() {
- Vec::new()
- } else {
- let assignments = self.note_and_assemble(dispatches);
- for (worker, message_count) in assignments.routed_counts() {
- *inner.in_flight.entry(worker.clone()).or_insert(0) += message_count;
- counter!(
- "ingestion_consumer_dispatcher_sub_batches_assigned_total",
- "worker" => worker.clone(),
- )
- .increment(1);
- counter!(
- "ingestion_consumer_dispatcher_messages_routed_total",
- "worker" => worker.clone(),
- )
- .increment(message_count as u64);
- }
- assignments
- .into_sub_batches()
- .into_iter()
- .map(send)
- .collect()
- };
- drop(inner);
-
- if deferred.send_failed > 0 {
- record_if(&self.debug_recorder, || DebugEventKind::Deferred {
- batch_id: failed_batch_id.unwrap_or_default(),
- reason: "send_failed",
- groups: deferred.send_failed,
- });
- }
- record_if(&self.debug_recorder, || DebugEventKind::SubBatchResolved {
- worker: worker.to_string(),
- messages: message_count,
- routing_keys: routing_keys.len(),
- cleared_deferral: from_flush,
- });
- sent
- }
-
- /// Call when a worker ACKed a sub-batch (success path only, **before**
- /// its settle so the sentinel state isn't evicted first).
- /// Advances each key's ACK high-water mark in the order sentinel.
- pub fn on_sub_batch_acked(&self, key_offsets: &[KeyOffset]) {
- let mut sentinel = self.key_sentinel.batch();
- for key_offset in key_offsets {
- sentinel.note_acked(&key_offset.routing_key, key_offset.max_offset);
- }
- }
-
- /// A delivered-shaped settle, kept for tests that drive the resolve
- /// protocol directly; production calls [`Dispatcher::settle`].
- /// `clears_deferral` maps to the settlement's `from_flush`.
- pub fn on_sub_batch_resolved(
- &self,
- worker: &WorkerId,
- message_count: usize,
- routing_keys: &[String],
- clears_deferral: bool,
- _send_failed: bool,
- ) {
- self.settle(worker, message_count, routing_keys, clears_deferral, None);
- }
-
- /// Record the outcome of a send attempt for passive health tracking.
- /// Delegates to the underlying WorkerRegistry.
- pub fn record_send_outcome(&self, worker: &str, is_error: bool) {
- self.registry.record_outcome(worker, is_error);
- }
-}
-
-struct GroupedMessages {
- groups: Vec<KeyRun>,
- unkeyed_count: u64,
-}
-
-/// Demux messages into groups the way the collect path does for a poll.
-fn demux(messages: Vec<SerializedKafkaMessage>) -> Vec<Group> {
- let mut accumulator = Accumulator::default();
- for message in messages {
- accumulator.push(Partition(message.partition), message.into());
- }
- accumulator.into_groups()
-}
-
-/// Name a failed send's messages for the stash, one run per routing key.
-pub(crate) fn runs_by_routing_key(messages: Vec<SerializedKafkaMessage>) -> Vec<KeyRun> {
- routing_groups(demux(messages)).groups
-}
-
-#[cfg(test)]
-fn group_messages_by_routing_key(messages: Vec<SerializedKafkaMessage>) -> GroupedMessages {
- routing_groups(demux(messages))
-}
-
-/// Name each group for the scheduler. A keyed group's routing key is its
-/// Kafka key. An unkeyed message has no order to preserve, so it can go to
-/// any worker: a synthetic per-message key spreads such messages across
-/// workers instead of pinning them all to one shared fallback key.
-///
-/// The scheduler's pin table is keyed by routing key alone, so a key that
-/// arrives on two partitions in one poll (a partition-count change leaves its
-/// backlog on the old partition) merges into one group: two groups for one
-/// key could route to two workers at once.
-fn routing_groups(groups: Vec<Group>) -> GroupedMessages {
- let mut unkeyed_count = 0u64;
- let mut merged: Vec<KeyRun> = Vec::with_capacity(groups.len());
- let mut index_by_key: HashMap<String, usize> = HashMap::new();
- for group in groups {
- let routing_key = match group.key {
- Some(key) => key,
- None => {
- unkeyed_count += 1;
- let first = group.messages.first().map_or(Offset(-1), |m| m.offset);
- format!(":{}:{}", group.partition, first)
- }
- };
- let messages = group.messages.into_iter().map(|m| m.message);
- match index_by_key.get(&routing_key) {
- Some(&index) => merged[index].messages.extend(messages),
- None => {
- index_by_key.insert(routing_key.clone(), merged.len());
- merged.push(KeyRun {
- routing_key,
- messages: messages.collect(),
- });
- }
- }
- }
-
- GroupedMessages {
- groups: merged,
- unkeyed_count,
- }
-}
-
-#[cfg(test)]
-mod tests {
- use std::collections::HashMap;
-
- use crate::order_sentinel::SendKind;
- use crate::scheduler::Pin;
- use std::sync::Arc;
- use std::time::Duration;
-
- use super::*;
- use crate::worker_registry::{WorkerRegistry, WorkerRegistryConfig};
-
- // ---- helpers ----
-
- fn worker_url(i: usize) -> String {
- format!("http://worker:{}", 9001 + i)
- }
-
- fn wid(i: usize) -> WorkerId {
- WorkerId::from(worker_url(i).as_str())
- }
-
- fn make_msg(key: &str) -> SerializedKafkaMessage {
- SerializedKafkaMessage {
- topic: "test".into(),
- partition: 0,
- offset: 0,
- timestamp: 0,
- key: Some(key.to_string()),
- value: None,
- headers: HashMap::new(),
- }
- }
-
- fn make_msgs(keys: &[&str]) -> Vec<SerializedKafkaMessage> {
- keys.iter().map(|k| make_msg(k)).collect()
- }
-
- fn make_msg_at(key: &str, offset: i64) -> SerializedKafkaMessage {
- SerializedKafkaMessage {
- offset,
- ..make_msg(key)
- }
- }
-
- fn make_unkeyed_msg() -> SerializedKafkaMessage {
- SerializedKafkaMessage {
- topic: "test".into(),
- partition: 7,
- offset: 42,
- timestamp: 0,
- key: None,
- value: None,
- headers: HashMap::new(),
- }
- }
-
- /// Registry with N healthy workers and no cooldown. `dead_declaration` is
- /// very short so tests can drive a worker to dead quickly.
- fn healthy_registry(n: usize) -> Arc<WorkerRegistry> {
- let urls: Vec<String> = (0..n).map(worker_url).collect();
- let config = WorkerRegistryConfig {
- probe_interval: Duration::from_millis(50),
- dead_declaration: Duration::from_millis(30),
- passive_window: Duration::from_millis(500),
- passive_error_threshold: 0.5,
- passive_min_samples: 2,
- degraded_hold: Duration::from_millis(50),
- min_state_duration: Duration::ZERO,
- probe_failure_threshold: 2,
- drain_timeout: Duration::from_secs(5),
- };
- Arc::new(WorkerRegistry::new(&urls, config))
- }
-
- fn in_flight_of(dispatcher: &Dispatcher, worker: &WorkerId) -> usize {
- dispatcher
- .inner
- .lock()
- .unwrap()
- .in_flight
- .get(worker)
- .copied()
- .unwrap_or(0)
- }
-
- // ---- routing key ----
-
- #[test]
- fn test_group_messages_by_routing_key_uses_kafka_key() {
- let grouped = group_messages_by_routing_key(vec![make_msg("tok:user-1")]);
-
- assert_eq!(grouped.unkeyed_count, 0);
- assert_eq!(grouped.groups[0].routing_key, "tok:user-1");
- }
-
- #[test]
- fn test_group_messages_by_routing_key_uses_synthetic_key_for_unkeyed_messages() {
- let grouped = group_messages_by_routing_key(vec![make_unkeyed_msg()]);
-
- assert_eq!(grouped.unkeyed_count, 1);
- assert_eq!(grouped.groups.len(), 1);
- assert_eq!(grouped.groups[0].routing_key, ":7:42");
- assert_eq!(grouped.groups[0].messages.len(), 1);
- }
-
- #[test]
- fn test_group_messages_by_routing_key_groups_same_routing_key() {
- let grouped = group_messages_by_routing_key(make_msgs(&["tok:user-1", "tok:user-1"]));
-
- assert_eq!(grouped.unkeyed_count, 0);
- assert_eq!(grouped.groups.len(), 1);
- assert_eq!(grouped.groups[0].routing_key, "tok:user-1");
- assert_eq!(grouped.groups[0].messages.len(), 2);
- }
-
- #[test]
- fn test_same_routing_key_on_two_partitions_stays_one_group() {
- let grouped = group_messages_by_routing_key(vec![
- SerializedKafkaMessage {
- partition: 0,
- offset: 1,
- ..make_msg("tok:user-1")
- },
- SerializedKafkaMessage {
- partition: 3,
- offset: 9,
- ..make_msg("tok:user-1")
- },
- ]);
-
- assert_eq!(
- grouped.groups.len(),
- 1,
- "one key must not split across workers"
- );
- assert_eq!(grouped.groups[0].messages.len(), 2);
- }
-
- // ---- worker assignments ----
-
- #[test]
- fn test_worker_assignments_merges_groups_for_same_worker() {
- let mut assignments = WorkerAssignments::new();
-
- assignments.add_dispatch(Dispatch {
- worker: wid(1),
- routing_key: "tok:user-1".to_string(),
- messages: make_msgs(&["tok:user-1"]),
- kind: SendKind::Fresh,
- assignment_epoch: None,
- });
- assignments.add_dispatch(Dispatch {
- worker: wid(1),
- routing_key: "tok:user-2".to_string(),
- messages: make_msgs(&["tok:user-2"]),
- kind: SendKind::Fresh,
- assignment_epoch: None,
- });
-
- assert_eq!(
- assignments.routed_counts().collect::<Vec<_>>(),
- vec![(wid(1), 2)]
- );
-
- let sub_batches = assignments.into_sub_batches();
- assert_eq!(sub_batches.len(), 1);
- assert_eq!(sub_batches[0].worker, wid(1));
- assert_eq!(sub_batches[0].messages.len(), 2);
- assert_eq!(
- sub_batches[0].routing_keys,
- vec!["tok:user-1".to_string(), "tok:user-2".to_string()]
- );
- }
-
- #[test]
- fn test_key_offsets_only_track_keyed_messages() {
- // An unkeyed (overflow) message lands on an arbitrary partition; its
- // offset advancing an ACK watermark would make a later keyed send
- // look like a resend_after_ack.
- let mut assignments = WorkerAssignments::new();
- assignments.add_dispatch(Dispatch {
- worker: wid(1),
- routing_key: "tok:user-1".to_string(),
- messages: vec![make_msg_at("tok:user-1", 100)],
- kind: SendKind::Fresh,
- assignment_epoch: None,
- });
- let sub_batches = assignments.into_sub_batches();
- assert_eq!(sub_batches[0].key_offsets.len(), 1);
- assert_eq!(sub_batches[0].key_offsets[0].routing_key, "tok:user-1");
- assert_eq!(sub_batches[0].key_offsets[0].max_offset, 100);
-
- // An unkeyed group produces no ACK watermark at all.
- let mut assignments = WorkerAssignments::new();
- assignments.add_dispatch(Dispatch {
- worker: wid(1),
- routing_key: ":7:42".to_string(),
- messages: vec![make_unkeyed_msg()],
- kind: SendKind::Fresh,
- assignment_epoch: None,
- });
- assert!(assignments.into_sub_batches()[0].key_offsets.is_empty());
- }
-
- // ---- basic assignment ----
-
- #[test]
- fn test_single_worker_all_messages_go_there() {
- let registry = healthy_registry(1);
- let dispatcher = Dispatcher::new(registry);
-
- let sub_batches = dispatcher.assign("b", make_msgs(&["t:a", "t:b", "t:c"]));
-
- assert_eq!(sub_batches.len(), 1);
- assert_eq!(sub_batches[0].worker, wid(0));
- assert_eq!(sub_batches[0].messages.len(), 3);
- }
-
- #[test]
- fn test_empty_batch_returns_no_sub_batches() {
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(registry);
- assert!(dispatcher.assign("b", vec![]).is_empty());
- }
-
- #[test]
- fn test_same_key_merges_within_batch() {
- let registry = healthy_registry(3);
- let dispatcher = Dispatcher::new(registry);
-
- let batch1 = dispatcher.assign("b", make_msgs(&["t:user-1"]));
- assert_eq!(batch1.len(), 1);
- let worker = batch1[0].worker.clone();
- dispatcher.on_sub_batch_resolved(
- &worker,
- batch1[0].messages.len(),
- &batch1[0].routing_keys,
- false,
- false,
- );
-
- // Both user-1 messages merge into one sub-batch.
- let batch2 = dispatcher.assign("b", make_msgs(&["t:user-1", "t:user-1"]));
- assert_eq!(batch2.len(), 1);
- }
-
- // ---- sticky pins ----
-
- #[test]
- fn test_pin_is_sticky_across_batches() {
- let registry = healthy_registry(3);
- let dispatcher = Dispatcher::new(registry);
-
- // First batch pins "t:user-1" to some worker.
- let b1 = dispatcher.assign("b", make_msgs(&["t:user-1"]));
- let pinned_worker = b1[0].worker.clone();
-
- // Do NOT resolve b1 — pin stays alive with ref_count=1.
-
- // Second batch: same key must hit the same worker.
- let b2 = dispatcher.assign("b", make_msgs(&["t:user-1"]));
- assert_eq!(b2.len(), 1);
- assert_eq!(b2[0].worker, pinned_worker);
- }
-
- #[test]
- fn test_different_keys_may_go_to_different_workers() {
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(registry);
-
- // With 2 workers, P2C spreads 2 fresh keys across them.
- let sub_batches = dispatcher.assign("b", make_msgs(&["t:user-1", "t:user-2"]));
-
- let total_msgs: usize = sub_batches.iter().map(|b| b.messages.len()).sum();
- assert_eq!(total_msgs, 2);
- }
-
- // ---- ref counting ----
-
- #[test]
- fn test_pin_evicted_when_ref_count_reaches_zero() {
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(registry);
-
- let b1 = dispatcher.assign("b", make_msgs(&["t:user-1"]));
- let worker = b1[0].worker.clone();
-
- assert!(dispatcher
- .inner
- .lock()
- .unwrap()
- .scheduler
- .pins
- .contains_key("t:user-1"));
-
- dispatcher.on_sub_batch_resolved(
- &worker,
- b1[0].messages.len(),
- &b1[0].routing_keys,
- false,
- false,
- );
-
- assert!(!dispatcher
- .inner
- .lock()
- .unwrap()
- .scheduler
- .pins
- .contains_key("t:user-1"));
- }
-
- #[test]
- fn test_pin_ref_count_accumulates_across_batches() {
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(registry);
-
- let b1 = dispatcher.assign("b", make_msgs(&["t:user-1"]));
- let worker = b1[0].worker.clone();
-
- // Second batch, same key, pin not yet resolved: ref_count should be 2.
- dispatcher.assign("b", make_msgs(&["t:user-1"]));
- assert_eq!(
- dispatcher.inner.lock().unwrap().scheduler.pins["t:user-1"].ref_count,
- 2
- );
-
- // Resolve first sub-batch: ref_count drops to 1, pin stays.
- dispatcher.on_sub_batch_resolved(
- &worker,
- b1[0].messages.len(),
- &b1[0].routing_keys,
- false,
- false,
- );
- {
- let inner = dispatcher.inner.lock().unwrap();
- assert!(inner.scheduler.pins.contains_key("t:user-1"));
- assert_eq!(inner.scheduler.pins["t:user-1"].ref_count, 1);
- }
- }
-
- // ---- in-flight load ----
-
- #[test]
- fn test_in_flight_messages_incremented_by_message_count_on_assign() {
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(registry);
-
- // Two messages for one key → one sub-batch carrying two messages.
- let b1 = dispatcher.assign("b", make_msgs(&["t:user-1", "t:user-1"]));
- let worker = b1[0].worker.clone();
-
- assert_eq!(in_flight_of(&dispatcher, &worker), 2);
- }
-
- #[test]
- fn test_in_flight_messages_decremented_on_resolve() {
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(registry);
-
- 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,
- false,
- );
-
- assert_eq!(in_flight_of(&dispatcher, &worker), 0);
- }
-
- #[test]
- fn test_in_flight_messages_counts_every_message_to_worker() {
- // Three distinct keys routed to the single worker merge into one
- // sub-batch, but in-flight load tracks the total message volume (3),
- // not the sub-batch count.
- let registry = healthy_registry(1);
- let dispatcher = Dispatcher::new(registry);
-
- dispatcher.assign("b", make_msgs(&["t:a", "t:b", "t:c"]));
-
- assert_eq!(in_flight_of(&dispatcher, &wid(0)), 3);
- }
-
- // ---- load balancing ----
-
- #[test]
- fn test_routing_balances_by_message_volume_not_group_count() {
- // Regression: load is tracked by message count, not sub-batch presence.
- // One heavy key (10 msgs) plus five small keys (1 msg each) must not all
- // pile onto one worker — the small keys go to the other worker until
- // load is balanced.
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(registry);
-
- let mut specs: Vec<&str> = vec!["t:heavy"; 10];
- for d in ["t:a", "t:b", "t:c", "t:d", "t:e"] {
- specs.push(d);
- }
-
- let sub_batches = dispatcher.assign("b", make_msgs(&specs));
- assert_eq!(sub_batches.len(), 2, "both workers must carry messages");
-
- let load0 = in_flight_of(&dispatcher, &wid(0));
- let load1 = in_flight_of(&dispatcher, &wid(1));
- assert_eq!(load0 + load1, 15);
-
- // The heavy key lands alone on one worker; the five singles fill the
- // other. With per-sub-batch accounting the singles would all dump onto
- // one worker, giving 15 vs 1.
- let (heavy, light) = if load0 >= load1 {
- (load0, load1)
- } else {
- (load1, load0)
- };
- assert_eq!(heavy, 10);
- assert_eq!(light, 5);
- }
-
- // ---- dead worker handling ----
-
- #[tokio::test]
- async fn test_dead_worker_pin_dropped_and_rerouted() {
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- // Pin "user-1" to whichever worker gets it first.
- let b1 = dispatcher.assign("b", make_msgs(&["t:user-1"]));
- let original_worker = b1[0].worker.clone();
- let other_worker = if original_worker == wid(0) {
- wid(1)
- } else {
- wid(0)
- };
-
- // Drive the pinned worker to dead via passive signal.
- for _ in 0..5 {
- registry.record_outcome(&original_worker, true);
- }
- tokio::time::sleep(Duration::from_millis(40)).await;
- assert!(registry.is_dead(&original_worker));
-
- // Resolve b1 so the dead worker has no in-flight (the max_in_flight=1
- // ordering: the previous batch completes before the next assigns). The
- // zero-ref pin is evicted, so the key re-routes to the live worker.
- dispatcher.on_sub_batch_resolved(
- &original_worker,
- b1[0].messages.len(),
- &b1[0].routing_keys,
- false,
- false,
- );
-
- let b2 = dispatcher.assign("b", make_msgs(&["t:user-1"]));
- assert_eq!(b2.len(), 1);
- assert_eq!(b2[0].worker, other_worker);
- }
-
- #[test]
- fn test_all_workers_dead_returns_empty() {
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- // Force both workers to Unhealthy via passive signal (min_state_duration=0).
- for i in 0..2 {
- for _ in 0..5 {
- registry.record_outcome(&worker_url(i), true);
- }
- }
-
- // Both workers are Unhealthy — the dispatcher should not route to them.
- let b = dispatcher.assign("b", make_msgs(&["t:user-1"]));
- assert!(b.is_empty());
- }
-
- // ---- P2C routing strategy ----
-
- fn p2c_dispatcher(n: usize, seed: u64) -> Dispatcher {
- Dispatcher::with_strategy_seeded(healthy_registry(n), RoutingStrategy::P2c, seed)
- }
-
- #[test]
- fn test_p2c_single_worker_all_messages_go_there() {
- let dispatcher = p2c_dispatcher(1, 1);
-
- let sub_batches = dispatcher.assign("b", make_msgs(&["t:a", "t:b", "t:c"]));
-
- assert_eq!(sub_batches.len(), 1);
- assert_eq!(sub_batches[0].worker, wid(0));
- assert_eq!(sub_batches[0].messages.len(), 3);
- }
-
- #[test]
- fn test_p2c_pin_is_sticky_across_batches() {
- let dispatcher = p2c_dispatcher(3, 7);
-
- // First batch pins "t:user-1"; do NOT resolve so the pin stays alive.
- let b1 = dispatcher.assign("b", make_msgs(&["t:user-1"]));
- let pinned_worker = b1[0].worker.clone();
-
- // Second batch with the same key must hit the same worker, bypassing P2C.
- let b2 = dispatcher.assign("b", make_msgs(&["t:user-1"]));
- assert_eq!(b2.len(), 1);
- assert_eq!(b2[0].worker, pinned_worker);
- }
-
- #[test]
- fn test_p2c_spreads_fresh_keys_across_two_workers() {
- // With two workers, P2C samples both and the load bump after the first
- // key steers the second to the other worker — one message each.
- let dispatcher = p2c_dispatcher(2, 3);
-
- let sub_batches = dispatcher.assign("b", make_msgs(&["t:user-1", "t:user-2"]));
-
- assert_eq!(sub_batches.len(), 2, "both workers must carry a message");
- let total: usize = sub_batches.iter().map(|b| b.messages.len()).sum();
- assert_eq!(total, 2);
- }
-
- #[test]
- fn test_p2c_prefers_least_loaded_of_two_workers() {
- // With two workers P2C always compares both, so a pre-loaded worker 0
- // sends the fresh key to worker 1.
- let dispatcher = p2c_dispatcher(2, 9);
- dispatcher.inner.lock().unwrap().in_flight.insert(wid(0), 5);
-
- let b = dispatcher.assign("b", make_msgs(&["t:fresh"]));
- assert_eq!(b.len(), 1);
- assert_eq!(b[0].worker, wid(1));
- }
-
- #[tokio::test]
- async fn test_p2c_all_workers_dead_returns_empty() {
- let registry = healthy_registry(2);
- let dispatcher =
- Dispatcher::with_strategy_seeded(Arc::clone(&registry), RoutingStrategy::P2c, 1);
-
- for i in 0..2 {
- for _ in 0..5 {
- registry.record_outcome(&worker_url(i), true);
- }
- }
-
- let b = dispatcher.assign("b", make_msgs(&["t:user-1"]));
- assert!(b.is_empty());
- }
-
- // ---- deterministic aperture ----
-
- fn peer_tracker(self_ip: &str, peer_ips: &[&str]) -> Arc<PeerTracker> {
- let tracker = PeerTracker::new(self_ip.parse().unwrap());
- tracker.set_peers(&peer_ips.iter().map(|ip| ip.parse().unwrap()).collect());
- tracker
- }
-
- #[test]
- fn test_aperture_routes_unpinned_keys_within_ring_slice() {
- // Peer 1 of 2 over a 6-worker ring, configured width 2 floored to
- // ceil(6/2)=3 for coverage, owns ring positions 3-5; every fresh key
- // must land there, nowhere else.
- let mut dispatcher =
- Dispatcher::with_strategy(healthy_registry(6), RoutingStrategy::Aperture);
- dispatcher.set_aperture(peer_tracker("10.0.0.2", &["10.0.0.1", "10.0.0.2"]), 2);
-
- let msgs: Vec<_> = (0..10).map(|i| make_msg(&format!("t:u{i}"))).collect();
- let sub_batches = dispatcher.assign("b", msgs);
-
- let total: usize = sub_batches.iter().map(|b| b.messages.len()).sum();
- assert_eq!(total, 10);
- assert!(
- sub_batches
- .iter()
- .all(|b| b.worker == wid(3) || b.worker == wid(4) || b.worker == wid(5)),
- "all sub-batches must stay within the dispatcher's ring slice"
- );
- }
-
- #[test]
- fn test_aperture_slices_tile_across_peers_without_overlap() {
- // Two dispatchers with complementary indices must route into disjoint
- // slices — the property that keeps the fleet covering the whole pool.
- let keys: Vec<_> = (0..10).map(|i| format!("u{i}")).collect();
- let mut used: Vec<Vec<WorkerId>> = Vec::new();
- for self_ip in ["10.0.0.1", "10.0.0.2"] {
- let mut dispatcher =
- Dispatcher::with_strategy(healthy_registry(6), RoutingStrategy::Aperture);
- dispatcher.set_aperture(peer_tracker(self_ip, &["10.0.0.1", "10.0.0.2"]), 2);
- let msgs: Vec<_> = keys.iter().map(|k| make_msg(k)).collect();
- used.push(
- dispatcher
- .assign("b", msgs)
- .iter()
- .map(|b| b.worker.clone())
- .collect(),
- );
- }
- assert!(
- used[0].iter().all(|w| !used[1].contains(w)),
- "peer slices must not overlap: {used:?}"
- );
- }
-
- #[test]
- fn test_aperture_falls_back_to_full_pool_while_self_unknown() {
- // Before this pod is a ready endpoint (self_index None), aperture must
- // not stall or funnel everything through a guessed slice — it routes
- // over the full pool like plain P2C.
- let mut dispatcher =
- Dispatcher::with_strategy_seeded(healthy_registry(4), RoutingStrategy::Aperture, 7);
- dispatcher.set_aperture(peer_tracker("10.0.0.9", &["10.0.0.1", "10.0.0.2"]), 1);
-
- let msgs: Vec<_> = (0..30).map(|i| make_msg(&format!("t:u{i}"))).collect();
- let sub_batches = dispatcher.assign("b", msgs);
-
- let total: usize = sub_batches.iter().map(|b| b.messages.len()).sum();
- assert_eq!(total, 30, "no messages may be dropped or stalled");
- assert!(
- sub_batches.len() > 1,
- "fallback must spread beyond a single-worker slice"
- );
- }
-
- #[test]
- fn test_aperture_honors_pin_outside_ring_slice() {
- // Peer 1 of 2 over a 6-worker ring owns ring positions 3-5. A key
- // pinned to worker 0 — outside the slice — must keep routing there:
- // the slice narrows candidates for *fresh* keys only, and rerouting
- // a pinned key would break per-key ordering.
- let mut dispatcher =
- Dispatcher::with_strategy(healthy_registry(6), RoutingStrategy::Aperture);
- dispatcher.set_aperture(peer_tracker("10.0.0.2", &["10.0.0.1", "10.0.0.2"]), 2);
- dispatcher.inner.lock().unwrap().scheduler.pins.insert(
- "t:pinned".to_string(),
- Pin {
- worker: wid(0),
- ref_count: 1,
- },
- );
-
- let sub_batches = dispatcher.assign("b", make_msgs(&["t:pinned"]));
-
- assert_eq!(sub_batches.len(), 1);
- assert_eq!(
- sub_batches[0].worker,
- wid(0),
- "pinned key must stay on its out-of-slice worker"
- );
- }
-
- #[test]
- fn test_debug_routing_reports_the_live_aperture_slice() {
- // The debug payload must mirror what `assign` would use: same ring,
- // same slice (peer 1 of 2 over 6 workers → floored width 3, positions
- // 3-5). A drift here would make the control-plane UI lie during an
- // incident.
- let registry = healthy_registry(6);
- let mut dispatcher =
- Dispatcher::with_strategy(Arc::clone(&registry), RoutingStrategy::Aperture);
- dispatcher.set_aperture(peer_tracker("10.0.0.2", &["10.0.0.1", "10.0.0.2"]), 2);
-
- let routing = dispatcher.debug_routing(registry.workers(), &registry.healthy_workers());
-
- assert_eq!(routing.strategy, "aperture");
- assert_eq!(routing.min_aperture, Some(2));
- assert_eq!(routing.ring.len(), 6);
- assert_eq!(
- routing.slice,
- Some(vec![
- wid(3).to_string(),
- wid(4).to_string(),
- wid(5).to_string()
- ])
- );
-
- // Non-aperture strategies report no slice — the UI shows full pool.
- let registry = healthy_registry(2);
- let p2c = Dispatcher::with_strategy(Arc::clone(&registry), RoutingStrategy::P2c);
- let routing = p2c.debug_routing(registry.workers(), &registry.healthy_workers());
- assert_eq!(routing.strategy, "p2c");
- assert!(routing.slice.is_none());
- }
-
- // ---- graceful drain ----
-
- #[test]
- fn test_draining_worker_gets_no_new_keys() {
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
- registry.start_draining(&worker_url(0));
-
- let msgs: Vec<_> = (0..10).map(|i| make_msg(&format!("t:u{i}"))).collect();
- let sub_batches = dispatcher.assign("b", msgs);
-
- assert!(
- sub_batches.iter().all(|b| b.worker != wid(0)),
- "no new keys may route to a draining worker"
- );
- }
-
- #[test]
- fn test_unroutable_fresh_key_defers_until_a_worker_returns() {
- // A fresh (unpinned) key arriving while NO worker is routable — e.g.
- // the whole pool is draining during a deploy overlap — must be deferred
- // like pinned keys are, not silently dropped. A drop fails the batch and
- // restarts the process even though a worker may return moments later.
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- registry.start_draining(&worker_url(0));
- registry.start_draining(&worker_url(1));
-
- let b = dispatcher.assign("batch-1", make_msgs(&["t:fresh"]));
- assert!(b.is_empty(), "nothing is routable while the pool drains");
- assert!(
- dispatcher.has_deferred("batch-1"),
- "an unroutable fresh key must be deferred, not dropped"
- );
-
- // A worker rejoins — the deferred group flushes to it, nothing was lost.
- registry.add_worker(wid(0));
- let flushed = dispatcher.flush_deferred("batch-1");
- assert_eq!(flushed.len(), 1);
- assert_eq!(flushed[0].worker, wid(0));
- assert_eq!(flushed[0].messages.len(), 1);
- assert!(!dispatcher.has_deferred("batch-1"));
- }
-
- #[test]
- fn test_fresh_key_queues_behind_its_own_deferred_groups() {
- // batch-1 defers a fresh key because nothing was routable; a worker
- // then returns BEFORE batch-1 is flushed. batch-2's messages for the
- // key have no pin to defer behind — they must still queue behind the
- // stashed batch-1 group instead of routing ahead of it.
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
- registry.start_draining(&worker_url(0));
- registry.start_draining(&worker_url(1));
-
- assert!(dispatcher.assign("batch-1", make_msgs(&["t:k"])).is_empty());
- assert!(dispatcher.has_deferred("batch-1"));
-
- registry.add_worker(wid(0));
-
- let b2 = dispatcher.assign("batch-2", make_msgs(&["t:k"]));
- assert!(
- b2.is_empty(),
- "newer messages must not race ahead of the key's stashed ones"
- );
- assert!(dispatcher.has_deferred("batch-2"));
-
- // Flush oldest-first: each batch delivers its own group, and batch-2
- // stays sticky to the pin batch-1's flush created.
- let f1 = dispatcher.flush_deferred("batch-1");
- assert_eq!(f1.len(), 1);
- dispatcher.on_sub_batch_resolved(
- &f1[0].worker,
- f1[0].messages.len(),
- &f1[0].routing_keys,
- true,
- false,
- );
- let f2 = dispatcher.flush_deferred("batch-2");
- assert_eq!(f2.len(), 1);
- assert_eq!(f2[0].worker, f1[0].worker);
- }
-
- #[test]
- fn test_pinned_key_defers_off_draining_worker() {
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- // Pin "user-1"; do NOT resolve, so the pin stays live on its worker.
- let b1 = dispatcher.assign("batch-1", make_msgs(&["t:user-1"]));
- let pinned = b1[0].worker.clone();
-
- registry.start_draining(&pinned);
-
- // The live pin points at a draining worker — new messages for the key are
- // deferred (held), not sent and not rerouted, so they can't effects the
- // earlier in-flight message still being processed on that worker.
- let b2 = dispatcher.assign("batch-2", make_msgs(&["t:user-1"]));
- assert!(
- b2.is_empty(),
- "messages for a draining-pinned key must be deferred, not routed"
- );
- assert!(dispatcher.has_deferred("batch-2"));
- }
-
- #[test]
- fn test_deferral_reason_splits_drain_seed_from_cascade() {
- let registry = healthy_registry(2);
- let mut dispatcher = Dispatcher::new(Arc::clone(&registry));
- 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"
- );
- }
-
- /// 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(&registry));
-
- 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 (with 2 workers, P2C places on the lighter one).
- 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"
- );
- }
-
- #[tokio::test]
- async fn test_pinned_key_defers_off_dead_worker() {
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- let b1 = dispatcher.assign("batch-1", make_msgs(&["t:user-1"]));
- let pinned = b1[0].worker.clone();
-
- // Kill the pinned worker via passive signal, leaving b1 in-flight.
- for _ in 0..5 {
- registry.record_outcome(&pinned, true);
- }
- tokio::time::sleep(Duration::from_millis(40)).await;
- assert!(registry.is_dead(&pinned));
-
- let b2 = dispatcher.assign("batch-2", make_msgs(&["t:user-1"]));
- assert!(
- b2.is_empty(),
- "messages for a dead-pinned key with in-flight must be deferred"
- );
- assert!(dispatcher.has_deferred("batch-2"));
- }
-
- #[test]
- fn test_flush_deferred_routes_to_healthy_worker_and_repins() {
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- // Pin user-1, then drain its worker so the next batch defers.
- let b1 = dispatcher.assign("batch-1", make_msgs(&["t:user-1"]));
- let pinned = b1[0].worker.clone();
- registry.start_draining(&pinned);
- let b2 = dispatcher.assign("batch-2", make_msgs(&["t:user-1"]));
- assert!(b2.is_empty());
-
- // Resolve batch-1's in-flight so the worker finishes draining.
- dispatcher.on_sub_batch_resolved(
- &pinned,
- b1[0].messages.len(),
- &b1[0].routing_keys,
- false,
- false,
- );
-
- // Flushing batch-2 re-routes the deferred group onto the surviving worker.
- let flushed = dispatcher.flush_deferred("batch-2");
- assert_eq!(flushed.len(), 1);
- assert_ne!(
- flushed[0].worker, pinned,
- "deferred group routes off drainer"
- );
- assert_eq!(flushed[0].routing_keys, vec!["t:user-1".to_string()]);
- assert!(
- !dispatcher.has_deferred("batch-2"),
- "nothing left after flush"
- );
- }
-
- #[test]
- fn test_flush_deferred_records_debug_event() {
- let registry = healthy_registry(2);
- let mut dispatcher = Dispatcher::new(Arc::clone(&registry));
- let recorder = DebugRecorder::new(100, Duration::from_secs(60));
- dispatcher.set_debug_recorder(Arc::clone(&recorder));
-
- let b1 = dispatcher.assign("batch-1", make_msgs(&["t:user-1"]));
- let pinned = b1[0].worker.clone();
- registry.start_draining(&pinned);
- 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,
- false,
- );
-
- let flushed = dispatcher.flush_deferred("batch-2");
- assert_eq!(flushed.len(), 1);
-
- let flush_events: Vec<_> = recorder
- .backlog()
- .into_iter()
- .filter_map(|e| match e.kind {
- DebugEventKind::DeferredFlushed {
- batch_id,
- sub_batches,
- } => Some((batch_id, sub_batches)),
- _ => None,
- })
- .collect();
- assert_eq!(
- flush_events.len(),
- 1,
- "flush_deferred must record a DeferredFlushed debug event"
- );
- let (batch_id, sub_batches) = &flush_events[0];
- assert_eq!(batch_id, "batch-2");
- assert_eq!(sub_batches.len(), 1);
- assert_eq!(sub_batches[0].worker, flushed[0].worker.to_string());
- assert_eq!(sub_batches[0].messages, 1);
- }
-
- #[test]
- fn test_defer_keeps_pin_alive_until_flushed() {
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- let b1 = dispatcher.assign("batch-1", make_msgs(&["t:user-1"]));
- let pinned = b1[0].worker.clone();
- registry.start_draining(&pinned);
- dispatcher.assign("batch-2", make_msgs(&["t:user-1"]));
-
- // Resolving batch-1 drops ref_count to 0, but the deferred batch-2 group
- // must keep the pin from being evicted (so order is preserved on flush).
- dispatcher.on_sub_batch_resolved(
- &pinned,
- b1[0].messages.len(),
- &b1[0].routing_keys,
- false,
- false,
- );
- assert_eq!(
- dispatcher.pin_count(),
- 1,
- "pin retained while deferred pending"
- );
-
- // After flushing, the pin is repointed and stays (now ref-counted by the
- // flushed sub-batch), but nothing is deferred anymore.
- dispatcher.flush_deferred("batch-2");
- assert!(!dispatcher.has_deferred("batch-2"));
- }
-
- #[test]
- fn test_settle_failure_requeues_before_releasing_the_key() {
- // The one-call settlement must stash the failed messages before it
- // drops the ref-count: reordered, the pin would evict with work still
- // pending and the key's next arrival could route ahead of the replay.
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- let b1 = dispatcher.assign("batch-1", make_msgs(&["t:user-1"]));
- let worker = b1[0].worker.clone();
-
- dispatcher.settle(
- &worker,
- b1[0].messages.len(),
- &b1[0].routing_keys,
- false,
- Some(("batch-1".to_string(), b1[0].messages.clone())),
- );
-
- assert!(
- dispatcher.has_deferred("batch-1"),
- "failed messages stashed"
- );
- assert_eq!(
- dispatcher.pin_count(),
- 1,
- "pin retained while the failed messages await replay"
- );
- assert_eq!(dispatcher.total_in_flight(), 0, "load released");
- }
-
- #[test]
- fn test_defer_failed_holds_messages_for_replay() {
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- let b1 = dispatcher.assign("batch-1", make_msgs(&["t:user-1"]));
- let worker = b1[0].worker.clone();
-
- // Simulate a send failure: defer the failed messages, then resolve.
- dispatcher.defer_failed("batch-1", make_msgs(&["t:user-1"]));
- dispatcher.on_sub_batch_resolved(
- &worker,
- b1[0].messages.len(),
- &b1[0].routing_keys,
- false,
- false,
- );
-
- assert!(
- dispatcher.has_deferred("batch-1"),
- "failed messages held for replay"
- );
- assert_eq!(
- dispatcher.pin_count(),
- 1,
- "pin kept for the deferred replay"
- );
-
- let flushed = dispatcher.flush_deferred("batch-1");
- assert_eq!(flushed.len(), 1);
- assert!(!dispatcher.has_deferred("batch-1"));
- }
-
- /// A `defer_failed` racing an in-progress assignment must not land between
- /// a key's admission and its enqueue: the admitted newer group would then
- /// ride the worker stream ahead of the stashed older one.
- #[test]
- fn test_assign_and_send_enqueues_before_a_racing_defer_failed_lands() {
- let registry = healthy_registry(1);
- let dispatcher = Arc::new(Dispatcher::new(registry));
- let b1 = dispatcher.assign("batch-1", make_msgs(&["t:user-1"]));
- assert_eq!(b1.len(), 1, "batch-1 pins the key with an in-flight send");
-
- let racing = Arc::clone(&dispatcher);
- let mut race = None;
- let sent = dispatcher.assign_and_send(
- "batch-2",
- 0,
- demux(make_msgs(&["t:user-1"])),
- |sub_batch| {
- // Admitted behind batch-1's live pin. batch-1's send now fails
- // and tries to stash its messages before this group is enqueued.
- let dispatcher = Arc::clone(&racing);
- let handle = std::thread::spawn(move || {
- dispatcher.defer_failed("batch-1", make_msgs(&["t:user-1"]));
- });
- std::thread::sleep(Duration::from_millis(50));
- assert!(
- !handle.is_finished(),
- "defer_failed must wait until the admitted group is enqueued"
- );
- race = Some(handle);
- sub_batch
- },
- );
- assert_eq!(
- sent.pending.len(),
- 1,
- "batch-2 was admitted and handed to send"
- );
- race.take().expect("send ran").join().expect("defer_failed");
-
- // The stash landed after the enqueue, so newer work for the key now
- // queues behind it instead of being admitted.
- let b3 = dispatcher.assign("batch-3", make_msgs(&["t:user-1"]));
- assert!(b3.is_empty(), "newer work defers behind the stashed group");
- assert!(dispatcher.has_deferred("batch-3"));
- }
-
- #[test]
- fn test_rejoin_during_drain_keeps_deferring_until_flushed() {
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- // Pin user-1, keep it in-flight, then drain its worker.
- let b1 = dispatcher.assign("batch-1", make_msgs(&["t:user-1"]));
- let pinned = b1[0].worker.clone();
- registry.start_draining(&pinned);
-
- // batch-2 defers behind the draining pin.
- let b2 = dispatcher.assign("batch-2", make_msgs(&["t:user-1"]));
- assert!(b2.is_empty());
- assert!(dispatcher.has_deferred("batch-2"));
-
- // The worker rejoins (EndpointSlice re-adds it) — draining is cleared.
- registry.add_worker(pinned.clone());
- assert!(!registry.is_draining(&pinned));
-
- // Even so, new messages must keep deferring: the key still has deferred
- // groups outstanding, so honoring the (now-healthy-again) pin would let
- // newer messages jump ahead of the older deferred ones.
- let b3 = dispatcher.assign("batch-3", make_msgs(&["t:user-1"]));
- assert!(
- b3.is_empty(),
- "must keep deferring while earlier deferred work is unflushed"
- );
- assert!(dispatcher.has_deferred("batch-3"));
-
- // Resolve batch-1's in-flight, then flush the deferred batches in order
- // and resolve the flushed sub-batches (which clears the deferral).
- dispatcher.on_sub_batch_resolved(
- &pinned,
- b1[0].messages.len(),
- &b1[0].routing_keys,
- false,
- false,
- );
- for batch in ["batch-2", "batch-3"] {
- let flushed = dispatcher.flush_deferred(batch);
- assert_eq!(flushed.len(), 1);
- dispatcher.on_sub_batch_resolved(
- &flushed[0].worker,
- flushed[0].messages.len(),
- &flushed[0].routing_keys,
- true,
- false,
- );
- }
- assert!(!dispatcher.has_deferred("batch-2") && !dispatcher.has_deferred("batch-3"));
-
- // With the stash drained, a fresh batch honors the pin again.
- let b4 = dispatcher.assign("batch-4", make_msgs(&["t:user-1"]));
- assert_eq!(b4.len(), 1, "honors the pin once nothing is deferred");
- }
-
- #[test]
- fn test_flushed_key_keeps_deferring_until_acked() {
- // The ordering-critical case: after a key is flushed to a survivor, its
- // messages are in flight but not yet ACKed. A newer batch for the same key
- // must keep deferring until that flush lands — otherwise it could be
- // routed onto the fresh pin and race the not-yet-acked flushed messages.
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- let b1 = dispatcher.assign("batch-1", make_msgs(&["t:user-1"]));
- let pinned = b1[0].worker.clone();
- registry.start_draining(&pinned);
-
- // batch-2 defers; batch-1 resolves; flush batch-2 to the survivor.
- assert!(dispatcher
- .assign("batch-2", make_msgs(&["t:user-1"]))
- .is_empty());
- dispatcher.on_sub_batch_resolved(
- &pinned,
- b1[0].messages.len(),
- &b1[0].routing_keys,
- false,
- false,
- );
- let flushed = dispatcher.flush_deferred("batch-2");
- assert_eq!(flushed.len(), 1);
-
- // Flushed but NOT yet resolved → a newer batch must still defer.
- let b3 = dispatcher.assign("batch-3", make_msgs(&["t:user-1"]));
- assert!(
- b3.is_empty(),
- "newer messages must not race the in-flight flushed messages"
- );
-
- // Once the flush ACKs (clears_deferral), the key is free to be honored.
- dispatcher.on_sub_batch_resolved(
- &flushed[0].worker,
- flushed[0].messages.len(),
- &flushed[0].routing_keys,
- true,
- 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.
- let f3 = dispatcher.flush_deferred("batch-3");
- assert_eq!(f3.len(), 1);
- dispatcher.on_sub_batch_resolved(
- &f3[0].worker,
- f3[0].messages.len(),
- &f3[0].routing_keys,
- true,
- false,
- );
- let b4 = dispatcher.assign("batch-4", make_msgs(&["t:user-1"]));
- assert_eq!(
- b4.len(),
- 1,
- "honors the pin once all flushed work has landed"
- );
- }
-
- #[test]
- fn test_cross_batch_deferred_flush_preserves_order() {
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- // batch-1 pins user-1 (offset 0); keep it in-flight, then drain its worker.
- let b1 = dispatcher.assign("batch-1", vec![make_msg_at("t:user-1", 0)]);
- let pinned = b1[0].worker.clone();
- registry.start_draining(&pinned);
-
- // The next two batches each carry user-1's next message — both defer,
- // each held under its own batch, behind the draining pin.
- let b2 = dispatcher.assign("batch-2", vec![make_msg_at("t:user-1", 1)]);
- let b3 = dispatcher.assign("batch-3", vec![make_msg_at("t:user-1", 2)]);
- assert!(
- b2.is_empty() && b3.is_empty(),
- "both must defer behind the drainer"
- );
-
- // Drain finishes when batch-1's in-flight resolves.
- dispatcher.on_sub_batch_resolved(
- &pinned,
- b1[0].messages.len(),
- &b1[0].routing_keys,
- false,
- false,
- );
-
- // Flush oldest-first (as complete_oldest_batch does): each batch yields
- // only its own message, in Kafka offset order.
- let f2 = dispatcher.flush_deferred("batch-2");
- let f3 = dispatcher.flush_deferred("batch-3");
- assert_eq!(offsets(&f2), vec![1], "batch-2 flushes its own message");
- assert_eq!(offsets(&f3), vec![2], "batch-3 flushes its own message");
- assert!(!dispatcher.has_deferred("batch-2") && !dispatcher.has_deferred("batch-3"));
- }
-
- #[test]
- fn test_cross_batch_deferred_flush_stays_on_one_survivor() {
- // A key deferred across multiple batches during a drain must re-home to a
- // SINGLE survivor — otherwise one key's events scatter across
- // workers and lose person-batching locality. Needs >=2 survivors after a
- // drain, so 3 workers. (With 2 workers there's one survivor and the bug is
- // masked, which is why `..._preserves_order` above can't catch it.)
- let registry = healthy_registry(3);
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- // Pin user-1, keep it in-flight, then drain its worker.
- let b1 = dispatcher.assign("batch-1", make_msgs(&["t:user-1"]));
- let pinned = b1[0].worker.clone();
- registry.start_draining(&pinned);
-
- // Two later batches each carry user-1 → both defer behind the drainer.
- assert!(dispatcher
- .assign("batch-2", make_msgs(&["t:user-1"]))
- .is_empty());
- assert!(dispatcher
- .assign("batch-3", make_msgs(&["t:user-1"]))
- .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,
- 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
- // survivor's load, so batch-3's P2C pick scatters to the lighter other one.
- let f2 = dispatcher.flush_deferred("batch-2");
- let f3 = dispatcher.flush_deferred("batch-3");
- assert_eq!(f2.len(), 1);
- assert_eq!(f3.len(), 1);
- assert_ne!(f2[0].worker, pinned, "re-homes off the drainer");
- assert_eq!(
- f3[0].worker, f2[0].worker,
- "a key deferred across batches must re-home to one survivor, not scatter"
- );
- }
-
- fn offsets(sub_batches: &[SubBatch]) -> Vec<i64> {
- sub_batches
- .iter()
- .flat_map(|b| b.messages.iter().map(|m| m.offset))
- .collect()
- }
-
- #[test]
- fn test_resolve_completes_drain_when_in_flight_hits_zero() {
- let registry = healthy_registry(1);
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- // Send a batch to worker 0, then mark it draining while in-flight.
- let b = dispatcher.assign("b", make_msgs(&["t:a"]));
- let worker = b[0].worker.clone();
- registry.start_draining(&worker);
- assert!(
- registry.reapable_workers().is_empty(),
- "not reapable while in-flight remains"
- );
-
- // Resolving the last in-flight sub-batch should mark it reapable.
- dispatcher.on_sub_batch_resolved(
- &worker,
- b[0].messages.len(),
- &b[0].routing_keys,
- false,
- false,
- );
- assert_eq!(registry.reapable_workers(), vec![worker]);
- }
-
- #[test]
- fn test_idle_drained_worker_reaped_via_reaper_path() {
- // A worker drained while idle has no in-flight to resolve, so
- // `on_sub_batch_resolved`/`complete_drain` never fire for it. The reaper
- // instead completes the drain when `has_in_flight` is false. This checks
- // the accessors that path relies on.
- let registry = healthy_registry(2);
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- let idle = wid(0);
- registry.start_draining(&idle);
-
- // Reaper's condition holds: the worker is draining and has no in-flight.
- assert!(registry.draining_workers().contains(&idle));
- assert!(
- !dispatcher.has_in_flight(&idle),
- "idle worker has no in-flight"
- );
- assert!(
- registry.reapable_workers().is_empty(),
- "not reapable yet — its deadline is the full drain timeout"
- );
-
- // The reaper completes the drain → immediately reapable, no timeout wait.
- registry.complete_drain(&idle);
- assert_eq!(registry.reapable_workers(), vec![idle]);
- }
-}
diff --git a/rust/ingestion-consumer/src/grpc_transport.rs b/rust/ingestion-consumer/src/grpc_transport.rs
index 97392fb2fa46..fc96fb878eb5 100644
--- a/rust/ingestion-consumer/src/grpc_transport.rs
+++ b/rust/ingestion-consumer/src/grpc_transport.rs
@@ -21,16 +21,15 @@
//!
//! **Failure fences the whole worker stream.** A nack, stream break, or connect
//! failure resolves every queued and un-acked item, in enqueue order, with a
-//! [`SendError`] carrying the messages back — the callers' existing
-//! `defer_failed` path then stashes them, and the dispatcher's outstanding
-//! counts hold all newer work for those keys until the failed groups are
-//! retried (oldest first) and acked. Each fenced send also carries a
-//! [`FenceGuard`]; the worker stream keeps fencing every new arrival until all guards
-//! are dropped, which closes the gap between a send resolving and its
-//! caller stashing, where the consumer loop could otherwise enqueue a fenced
-//! key's next group and the next stream would send it first. Nothing for a
-//! fenced key can leapfrog the failure, because everything for it was either
-//! in the ledger, the queue, or fenced on arrival.
+//! [`SendError`] carrying the messages back. The batcher then requeues them
+//! at the front of their keys' queues, and holds all newer work for those
+//! keys until the failed messages are retried (oldest first) and acked. Each
+//! fenced send also carries a [`FenceGuard`]; the worker stream keeps fencing
+//! every new arrival until all guards are dropped, which closes the gap
+//! between a send resolving and its caller requeuing, where a newer send for
+//! a fenced key could otherwise be enqueued and ride the next stream first.
+//! Nothing for a fenced key can leapfrog the failure, because everything for
+//! it was either in the ledger, the queue, or fenced on arrival.
//!
//! Backpressure: the queue is unbounded (so enqueue stays synchronous and
//! ordered) but the worker stream keeps at most `max_unacked` sub-batches un-acked on
@@ -118,7 +117,7 @@ impl PendingWorkerStreamSend {
messages.extend(std::mem::take(&mut err.messages));
match &mut failure {
// Keep the first failure's error; fold later guards
- // into it so the stream fences until all are stashed.
+ // into it so the stream fences until all are requeued.
Some(first) => match (&mut first.fence_guard, err.fence_guard.take()) {
(Some(guard), Some(other)) => guard.merge(other),
(slot @ None, other) => *slot = other,
@@ -815,10 +814,11 @@ impl WorkerStreamRunner {
/// Resolve everything outstanding as failed, **in enqueue order**: the
/// un-acked ledger first, then anything still queued (which was enqueued
- /// after everything in the ledger). Order matters because the callers'
- /// `defer_failed` stashes groups by batch sequence — resolving in order
- /// keeps every fenced key's groups stashed oldest-first, so the retry
- /// (oldest first) is the same request that failed.
+ /// after everything in the ledger). Order matters because the batcher
+ /// requeues each failed send at the front of its keys' queues, so
+ /// resolving in order keeps every fenced key's messages queued
+ /// oldest-first and the retry (oldest first) is the same request that
+ /// failed.
fn fence(
&self,
pending_first: Option<WorkerStreamItem>,
@@ -867,7 +867,7 @@ impl WorkerStreamRunner {
/// A fence in progress. Every fenced send carries a [`FenceGuard`]; until all
/// of them are dropped the worker stream fails each new arrival too, so a send
-/// enqueued before the fenced messages are stashed cannot ride the next
+/// enqueued before the fenced messages are requeued cannot ride the next
/// stream ahead of them.
struct Fence {
retriable: bool,
@@ -939,7 +939,7 @@ enum StreamEnd {
/// The transport dropped the queue sender — worker removed or shutdown.
QueueClosed,
/// The stream broke; the fence holds what was resolved as failed and
- /// keeps fencing until those callers have stashed their messages.
+ /// keeps fencing until those callers have requeued their messages.
Failed(Fence),
/// The stream ended cleanly with nothing outstanding.
Idle,
diff --git a/rust/ingestion-consumer/src/lib.rs b/rust/ingestion-consumer/src/lib.rs
index b96e5d7c2399..f8c1e6e1554e 100644
--- a/rust/ingestion-consumer/src/lib.rs
+++ b/rust/ingestion-consumer/src/lib.rs
@@ -7,15 +7,12 @@ pub mod config;
pub mod consumer;
pub mod debug_recorder;
pub mod discovery;
-pub mod dispatcher;
pub mod grpc_transport;
pub mod kafka_stats;
pub mod ledger_rejection;
pub mod order_sentinel;
pub mod readiness;
pub mod routing;
-pub mod scheduler;
-pub mod stash;
pub mod transport;
pub mod types;
pub mod worker_registry;
diff --git a/rust/ingestion-consumer/src/main.rs b/rust/ingestion-consumer/src/main.rs
index bedd0413cffc..ba247d7eabc6 100644
--- a/rust/ingestion-consumer/src/main.rs
+++ b/rust/ingestion-consumer/src/main.rs
@@ -19,17 +19,19 @@ use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{EnvFilter, Layer};
-use ingestion_consumer::batcher::Batcher;
+use ingestion_consumer::aperture;
+use ingestion_consumer::batcher::worker_pool::WorkerPoolSource;
+use ingestion_consumer::batcher::{Batcher, BatcherObserver};
use ingestion_consumer::config::Config;
use ingestion_consumer::consumer::IngestionConsumer;
-use ingestion_consumer::debug_recorder::{DebugLoad, DebugRecorder, DebugState, WorkerStatus};
+use ingestion_consumer::debug_recorder::{
+ BatcherLoad, DebugLoad, DebugRecorder, DebugState, RoutingDebug, WorkerStatus,
+};
use ingestion_consumer::discovery::{
DiscoveryMode, EndpointSliceDiscovery, StaticDiscovery, WorkerDiscovery,
};
-use ingestion_consumer::dispatcher::Dispatcher;
use ingestion_consumer::grpc_transport::{GrpcPort, GrpcTransport};
use ingestion_consumer::routing::RoutingStrategy;
-use ingestion_consumer::scheduler::SchedulerKind;
use ingestion_consumer::worker_registry::{WorkerId, WorkerRegistry, WorkerRegistryConfig};
common_alloc::used!();
@@ -251,12 +253,9 @@ async fn async_main(config: Config) -> Result<()> {
None
};
- let mut dispatcher = Dispatcher::with_strategy(Arc::clone(&registry), config.routing_strategy);
- if let Some(recorder) = &debug_recorder {
- dispatcher.set_debug_recorder(Arc::clone(recorder));
- }
+ let mut pool_source = WorkerPoolSource::new(Arc::clone(&registry), config.routing_strategy);
match &peer_tracker {
- Some(tracker) => dispatcher.set_aperture(Arc::clone(tracker), config.min_aperture),
+ Some(tracker) => pool_source.set_aperture(Arc::clone(tracker), config.min_aperture),
None if config.routing_strategy == RoutingStrategy::Aperture => {
warn!(
"INGESTION_ROUTING_STRATEGY=aperture without peer awareness (PEER_SERVICE_NAME); \
@@ -265,7 +264,6 @@ async fn async_main(config: Config) -> Result<()> {
}
None => {}
}
- let dispatcher = Arc::new(dispatcher);
let grpc_port = if config.ingestion_worker_grpc_port_offset > 0 {
GrpcPort::OffsetFromHttp(config.ingestion_worker_grpc_port_offset)
@@ -287,6 +285,14 @@ async fn async_main(config: Config) -> Result<()> {
transport.set_assignment_epoch(assignment_epoch);
let transport = Arc::new(transport);
+ // The batcher owns the dispatch orchestration; the consumer loop only
+ // submits polls to it and reads group completions back.
+ let state_machine = config
+ .batcher_state_machine()
+ .map_err(|err| anyhow::anyhow!("invalid batcher configuration: {err}"))?;
+ let (batcher, batcher_outputs) =
+ Batcher::new(state_machine, pool_source.clone(), Arc::clone(&transport));
+
// Select the worker discovery provider and start it (static applies the
// configured list immediately; endpointslice watches and keeps in sync).
let discovery: Box<dyn WorkerDiscovery> = match config.worker_discovery_mode {
@@ -350,7 +356,8 @@ async fn async_main(config: Config) -> Result<()> {
let group_id = config.ingestion_consumer_group_id.clone();
{
let registry = Arc::clone(&registry);
- let dispatcher = Arc::clone(&dispatcher);
+ let pool_source = pool_source.clone();
+ let observer = batcher.observer();
let peer_tracker = peer_tracker.clone();
let group_id = group_id.clone();
let secret = Arc::clone(&secret);
@@ -363,7 +370,8 @@ async fn async_main(config: Config) -> Result<()> {
Ok(axum::Json(build_debug_load(
&group_id,
&registry,
- &dispatcher,
+ &pool_source,
+ &observer,
&peer_tracker,
)))
};
@@ -374,7 +382,8 @@ async fn async_main(config: Config) -> Result<()> {
{
let recorder = Arc::clone(recorder);
let registry = Arc::clone(&registry);
- let dispatcher = Arc::clone(&dispatcher);
+ let pool_source = pool_source.clone();
+ let observer = batcher.observer();
let peer_tracker = peer_tracker.clone();
let group_id = group_id.clone();
let secret = Arc::clone(&secret);
@@ -384,12 +393,17 @@ async fn async_main(config: Config) -> Result<()> {
let result = if !debug_authorized(&headers, &secret) {
Err(axum::http::StatusCode::UNAUTHORIZED)
} else {
- let load =
- build_debug_load(&group_id, &registry, &dispatcher, &peer_tracker);
+ let load = build_debug_load(
+ &group_id,
+ &registry,
+ &pool_source,
+ &observer,
+ &peer_tracker,
+ );
Ok(axum::Json(DebugState {
group_id: load.group_id,
workers: load.workers,
- dispatcher: load.dispatcher,
+ batcher: load.batcher,
peer_index: load.peer_index,
peer_count: load.peer_count,
routing: load.routing,
@@ -490,27 +504,6 @@ async fn async_main(config: Config) -> Result<()> {
}
}
- // The batcher owns the dispatch orchestration; the consumer loop only
- // submits polls to it and reads group completions back.
- let (batcher, batcher_outputs) = match config.scheduler {
- SchedulerKind::PinStash => Batcher::new(
- Arc::clone(&dispatcher),
- Arc::clone(&transport),
- consumer_handle.clone(),
- Duration::from_millis(config.consumer_deferred_flush_timeout_ms),
- ),
- SchedulerKind::KeyTable => {
- let state_machine = config
- .batcher_state_machine()
- .map_err(|err| anyhow::anyhow!("invalid key-table configuration: {err}"))?;
- Batcher::with_state_machine(
- state_machine,
- dispatcher.worker_pool_source(),
- Arc::clone(&transport),
- )
- }
- };
-
// Reap drained workers: once a departed worker has finished its in-flight
// batches (or hit the drain timeout), remove it from the registry and prune
// its transport semaphore. No-op in static mode (workers never drain).
@@ -595,12 +588,13 @@ fn constant_time_eq(a: &str, b: &str) -> bool {
a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}
-/// Merge the registry's health snapshots with the dispatcher's in-flight load
-/// into the `/debug/load` payload.
+/// Merge the registry's health snapshots with the batcher's load into the
+/// `/debug/load` payload.
fn build_debug_load(
group_id: &str,
- registry: &ingestion_consumer::worker_registry::WorkerRegistry,
- dispatcher: &Dispatcher,
+ registry: &WorkerRegistry,
+ pool_source: &WorkerPoolSource,
+ observer: &BatcherObserver,
peer_tracker: &Option<Arc<k8s_awareness::PeerTracker>>,
) -> DebugLoad {
let (peer_index, peer_count) = match peer_tracker {
@@ -610,45 +604,47 @@ fn build_debug_load(
}
None => (None, None),
};
- let dispatcher_load = dispatcher.debug_load();
// One registry pass feeds the worker rows AND the routing ring/slice, so a
// worker joining or changing health mid-request can't make the payload
// show slice badges that contradict the worker table.
let snapshots = registry.health_snapshots();
- let ring_workers: Vec<WorkerId> = snapshots
- .iter()
- .map(|snap| WorkerId::from(snap.url.as_str()))
- .collect();
+ let ring = aperture::sorted_ring(
+ snapshots
+ .iter()
+ .map(|snap| WorkerId::from(snap.url.as_str()))
+ .collect(),
+ );
let healthy: Vec<WorkerId> = snapshots
.iter()
.filter(|snap| snap.routable)
.map(|snap| WorkerId::from(snap.url.as_str()))
.collect();
- let routing = dispatcher.debug_routing(ring_workers, &healthy);
+ let slice = pool_source.slice(&ring, &healthy);
+ let routing = RoutingDebug {
+ strategy: pool_source.strategy().as_str().to_string(),
+ min_aperture: pool_source.min_aperture(),
+ ring: ring.iter().map(|w| w.to_string()).collect(),
+ slice: slice.map(|s| s.iter().map(|w| w.to_string()).collect()),
+ };
let workers = snapshots
.into_iter()
- .map(|snap| {
- let in_flight_messages = dispatcher_load
- .per_worker
- .iter()
- .find(|entry| entry.worker == snap.url)
- .map(|entry| entry.in_flight)
- .unwrap_or(0);
- WorkerStatus {
- url: snap.url,
- state: snap.state,
- draining: snap.draining,
- consecutive_probe_failures: snap.consecutive_probe_failures,
- passive_error_rate: snap.passive_error_rate,
- passive_samples: snap.passive_samples,
- in_flight_messages,
- }
+ .map(|snap| WorkerStatus {
+ busy: observer.has_in_flight(&WorkerId::from(snap.url.as_str())),
+ url: snap.url,
+ state: snap.state,
+ draining: snap.draining,
+ consecutive_probe_failures: snap.consecutive_probe_failures,
+ passive_error_rate: snap.passive_error_rate,
+ passive_samples: snap.passive_samples,
})
.collect();
DebugLoad {
group_id: group_id.to_string(),
workers,
- dispatcher: dispatcher_load,
+ batcher: BatcherLoad {
+ total_in_flight: observer.total_in_flight(),
+ pending_messages: observer.pending_messages(),
+ },
peer_index,
peer_count,
routing,
diff --git a/rust/ingestion-consumer/src/order_sentinel.rs b/rust/ingestion-consumer/src/order_sentinel.rs
index bb5e78fdb244..bb9073e1de3f 100644
--- a/rust/ingestion-consumer/src/order_sentinel.rs
+++ b/rust/ingestion-consumer/src/order_sentinel.rs
@@ -4,13 +4,12 @@
//! **Per-key send order** ([`KeyOrderSentinel`]): for every routing key
//! (the Kafka message key), messages must be handed to workers in Kafka offset
//! order, and a message must never be re-sent after it was ACKed. Replays of
-//! un-ACKed messages on the retry paths ([`SendKind::Resend`]: send failure →
-//! deferred flush) are legal at-least-once behavior and are counted separately
-//! (`ingestion_consumer_key_replays_total`) rather than flagged; the same
-//! regression on a fresh assignment is a `send_below_last_sent` violation.
-//! Checked in the dispatcher at assignment time — the
-//! point that defines the intended per-key order — under the pin-table lock.
-//! Only messages produced with a Kafka key participate: null-key production
+//! un-ACKed messages on the retry paths ([`SendKind::Resend`]: a failed or
+//! partially acked send's replay) are legal at-least-once behavior and are
+//! counted separately (`ingestion_consumer_key_replays_total`) rather than
+//! flagged; the same regression on a fresh send is a `send_below_last_sent`
+//! violation. Checked by the batcher as it begins each send, the point that
+//! defines the intended per-key order. Only messages produced with a Kafka key participate: null-key production
//! (e.g. overflow rerouting) spreads a routing key across partitions,
//! deliberately forfeiting per-key order, so there is no invariant to check
//! and offsets from different partitions are not comparable. Skipped messages
@@ -88,9 +87,9 @@ pub enum SendKind {
/// single partition, so their offsets must only move forward; a regression
/// is a [`KeyOrderViolationKind::SendBelowLastSent`] violation.
Fresh,
- /// 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.
+ /// A replay of messages whose earlier send failed or came back
+ /// unfinished. Repeating un-ACKed offsets is expected at-least-once
+ /// behavior, not a violation.
Resend,
}
@@ -111,10 +110,10 @@ struct KeyState {
last_acked: Option<i64>,
}
-/// Tracks per-routing-key send/ACK progress and checks every assignment
-/// against it. State lives exactly as long as the key's pin: the dispatcher
-/// evicts it when the pin is evicted (all sends resolved, nothing deferred),
-/// so the map is bounded by in-flight work — the same bound as the pin table.
+/// Tracks per-routing-key send/ACK progress and checks every send against
+/// it. State lives exactly as long as the batcher tracks the key: the batcher
+/// evicts it when the key has nothing queued or in flight, so the map is
+/// bounded by the batcher's key table.
///
/// A key whose state was evicted rebaselines on its next send. That is sound
/// within a process: the key's messages arrive from its single partition in
@@ -358,9 +357,9 @@ impl SentinelBatch<'_> {
}
}
- /// Drop a key's state. Call when its pin is evicted — every send has
- /// resolved and nothing is deferred, so there is nothing left to order
- /// against and future offsets are necessarily higher.
+ /// Drop a key's state. Call when the batcher drops the key, once every
+ /// send has resolved and nothing is queued, so there is nothing left to
+ /// order against and future offsets are necessarily higher.
pub fn evict(&mut self, routing_key: &str) {
if let Some(keys) = self.keys.as_mut() {
keys.remove(routing_key);
@@ -422,7 +421,7 @@ pub struct SentinelContext {
/// rebalances. Distinct from the offset ledger's generations, which move
/// per partition and stamp offset accounting rather than stream order.
assignment_epoch: Option<AssignmentEpoch>,
- /// Called with the revoked `(topic, partition)` pairs, so the scheduler
+ /// Called with the revoked `(topic, partition)` pairs, so the batcher
/// can drop their queued messages before the new owner replays them.
revoke_hook: OnceLock<RevokeHook>,
}
@@ -456,7 +455,7 @@ impl SentinelContext {
/// A context with its own free-standing sentinels, ledger, and commit
/// pacer, for tests and tools that build the Kafka consumer separately
- /// from the dispatcher.
+ /// from the batcher.
pub fn detached() -> Self {
Self::new(
Arc::new(CommitSentinel::new(ImmediateCommitPacer::new())),
@@ -624,7 +623,7 @@ mod tests {
sentinel
.batch()
.note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)], SendKind::Fresh);
- // Send failed (no ACK) → deferred flush re-sends the same messages.
+ // Send failed (no ACK) → the replay re-sends the same messages.
assert!(sentinel
.batch()
.note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)], SendKind::Resend)
diff --git a/rust/ingestion-consumer/src/routing.rs b/rust/ingestion-consumer/src/routing.rs
index 0c527102868d..cbebce92db36 100644
--- a/rust/ingestion-consumer/src/routing.rs
+++ b/rust/ingestion-consumer/src/routing.rs
@@ -1,11 +1,11 @@
-//! Worker selection strategies for unpinned routing keys.
+//! Worker selection strategies for the batcher's requests.
//!
-//! The dispatcher owns the stateful concerns (grouping, sticky pins, ref-counts,
-//! in-flight accounting). This module is the pure decision layer: given the set
-//! of healthy workers and their per-worker load, pick a target. Keeping it free
-//! of dispatcher state makes the algorithms trivially unit-testable and lets the
-//! routing policy evolve (P2C cost functions, subsetting) without touching the
-//! dispatcher's bookkeeping.
+//! The batcher's worker assigner owns the stateful concerns (per-worker
+//! request and message load). This module is the pure decision layer: given
+//! the set of healthy workers and their per-worker load, pick a target.
+//! Keeping it free of batcher state makes the algorithms trivially
+//! unit-testable and lets the routing policy evolve (P2C cost functions,
+//! subsetting) without touching the batcher's bookkeeping.
use std::collections::HashMap;
use std::str::FromStr;
@@ -15,8 +15,7 @@ use rand::{Rng, SeedableRng};
use crate::worker_registry::WorkerId;
-/// How unpinned routing keys are assigned to workers. Pinned keys always go to
-/// their existing worker regardless of strategy.
+/// How requests are placed on workers.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum RoutingStrategy {
/// Power-of-two-choices: sample two random workers, pick the lighter. Herd
@@ -24,7 +23,7 @@ pub enum RoutingStrategy {
/// samples a different random pair instead of converging on one global best.
#[default]
P2c,
- /// Deterministic aperture: each dispatcher routes unpinned keys only within
+ /// Deterministic aperture: each consumer places requests only within
/// its slice of the worker ring (see [`crate::aperture`]), with P2C
/// selection inside the slice. Consolidates small batches onto few workers
/// while the fleet's slices still tile the whole pool. Requires peer
@@ -66,7 +65,7 @@ fn load_of(load: &WorkerLoad, worker: &WorkerId) -> usize {
}
/// Stateful worker selector. Holds the routing strategy and, for P2C, the RNG
-/// used to sample candidates. One per dispatcher; selection requires `&mut self`
+/// used to sample candidates. One per batcher; selection requires `&mut self`
/// because P2C advances the RNG.
pub struct Router {
strategy: RoutingStrategy,
@@ -95,12 +94,12 @@ impl Router {
self.strategy
}
- /// Select a worker for one group. `healthy` lists candidate worker ids;
+ /// Select a worker for one request. `healthy` lists candidate worker ids;
/// `load` is the current per-worker load (outstanding messages plus what has
/// been provisionally assigned earlier in this round). Returns `None` when
/// no workers are healthy.
pub fn select(&mut self, healthy: &[WorkerId], load: &WorkerLoad) -> Option<WorkerId> {
- // Aperture narrows the candidate slice upstream (in the dispatcher);
+ // Aperture narrows the candidate slice upstream (in the worker pool);
// within the slice it selects exactly like P2C.
select_p2c(healthy, load, &mut self.rng)
}
diff --git a/rust/ingestion-consumer/src/scheduler.rs b/rust/ingestion-consumer/src/scheduler.rs
deleted file mode 100644
index 11d9eebe3c82..000000000000
--- a/rust/ingestion-consumer/src/scheduler.rs
+++ /dev/null
@@ -1,1075 +0,0 @@
-//! The scheduler seam: every ordering and placement decision in the batcher,
-//! behind one interface.
-//!
-//! The scheduler decides which runs may go to a worker now, and where.
-//! Nothing else in the batcher decides that. The seam is event-shaped: a
-//! group arrives (`on_groups`), a request settles with success or failure
-//! (`on_settled`), a retry deadline fires (`on_deadline`). Each call is one
-//! event, runs to completion, does no I/O, takes no locks, and returns its
-//! effects as data: the dispatches to send, the deferral counts, and the
-//! evicted keys. The caller owns the lock, the worker-health snapshot
-//! ([`WorkerSnapshot`]), the in-flight load accounting, the sentinels, and the
-//! sends.
-//!
-//! [`PinStashScheduler`] is the current semantics moved out of the
-//! dispatcher: sticky pins, the stash, deferral on drain, and the
-//! oldest-first flush pacing. The key-table scheduler replaces it behind
-//! this same interface.
-
-use std::collections::HashMap;
-use std::str::FromStr;
-
-use metrics::{counter, gauge};
-
-use crate::order_sentinel::SendKind;
-use crate::routing::{Router, WorkerLoad};
-use crate::stash::{DeferredGroup, Stash};
-use crate::types::SerializedKafkaMessage;
-use crate::worker_registry::WorkerId;
-
-/// A point-in-time snapshot of the worker world, captured by the caller
-/// before a seam call so the scheduler decides over data instead of querying
-/// the registry and the peer tracker itself.
-pub struct WorkerSnapshot {
- /// Routable workers.
- pub healthy: Vec<WorkerId>,
- /// Candidates for fresh keys: the aperture ring slice when narrowing
- /// applies, otherwise the healthy pool.
- pub candidates: Vec<WorkerId>,
- /// Outstanding messages per worker (the caller's in-flight table).
- pub load: WorkerLoad,
- /// Health per known worker. A worker absent here is dead (removed from
- /// the registry) and not draining, matching the registry's answers.
- workers: HashMap<WorkerId, WorkerHealth>,
-}
-
-pub struct WorkerHealth {
- pub dead: bool,
- pub draining: bool,
-}
-
-impl WorkerSnapshot {
- pub fn new(
- healthy: Vec<WorkerId>,
- candidates: Vec<WorkerId>,
- load: WorkerLoad,
- workers: HashMap<WorkerId, WorkerHealth>,
- ) -> Self {
- Self {
- healthy,
- candidates,
- load,
- workers,
- }
- }
-
- pub fn is_dead(&self, worker: &WorkerId) -> bool {
- self.workers.get(worker).is_none_or(|health| health.dead)
- }
-
- pub fn is_draining(&self, worker: &WorkerId) -> bool {
- self.workers
- .get(worker)
- .is_some_and(|health| health.draining)
- }
-}
-
-/// One run of one key's messages arriving at the seam.
-pub struct KeyRun {
- pub routing_key: String,
- pub messages: Vec<SerializedKafkaMessage>,
-}
-
-/// One run of one key, placed on the chosen worker.
-pub struct Dispatch {
- pub worker: WorkerId,
- pub routing_key: String,
- pub messages: Vec<SerializedKafkaMessage>,
- /// Fresh assignment or a retry of deferred work; the key-order sentinel
- /// notes the send under this kind.
- pub kind: SendKind,
- /// The run's epoch, for stamping its completions. `None` from the
- /// pin-stash scheduler, whose caller stamps from the flush ticket.
- pub assignment_epoch: Option<u64>,
-}
-
-/// One resolved send arriving at the seam.
-pub struct Settlement {
- pub worker: WorkerId,
- /// The resolved send's message count, for the caller's load accounting;
- /// the scheduler does not read it.
- pub message_count: usize,
- /// Unique routing keys the send carried.
- pub routing_keys: Vec<String>,
- /// True when the send came from a deferred flush: the settlement then
- /// clears one deferral per key.
- pub from_flush: bool,
- pub outcome: SettlementOutcome,
-}
-
-pub enum SettlementOutcome {
- Delivered,
- /// The send failed; its runs come back for replay, already named by the
- /// caller. Requeue happens before the keys are released, in this one
- /// call, so a newer send can never overtake the failed messages.
- ///
- /// The settlement's `routing_keys` must name every run's key: a run
- /// whose key is missing is requeued but never released, and the key
- /// stays outstanding forever.
- Failed {
- batch_id: String,
- runs: Vec<KeyRun>,
- },
-}
-
-/// Groups deferred by one seam call, by reason. The caller emits the debug
-/// events from these; the scheduler emits its own counters.
-#[derive(Default)]
-pub struct DeferredCounts {
- /// The key's worker is draining or dead.
- pub drain: u64,
- /// The key already has deferred work; newer messages queue behind it.
- pub queued_behind_deferral: u64,
- /// No worker was routable.
- pub unroutable: u64,
- /// A failed send's messages went back to the stash.
- pub send_failed: u64,
-}
-
-impl DeferredCounts {
- pub fn total(&self) -> u64 {
- self.drain + self.queued_behind_deferral + self.unroutable + self.send_failed
- }
-}
-
-/// One seam call's effects, as data.
-#[must_use]
-#[derive(Default)]
-pub struct SchedulerEffects {
- /// Runs to send now, in decision order. The caller establishes send
- /// order from this order and must send every dispatch, from every seam
- /// call: the scheduler already counts the dispatched keys as in flight,
- /// so a dropped dispatch strands them.
- pub dispatches: Vec<Dispatch>,
- pub deferred: DeferredCounts,
- /// Keys evicted from the scheduler's state: nothing is in flight,
- /// queued, or deferred for them, so their order-sentinel state can go.
- pub evicted_keys: Vec<String>,
-}
-
-impl SchedulerEffects {
- pub(crate) fn with_dispatch_capacity(capacity: usize) -> Self {
- Self {
- dispatches: Vec::with_capacity(capacity),
- ..Self::default()
- }
- }
-}
-
-/// Which scheduler implementation the dispatcher runs. Selected by config;
-/// the switch back is the rollback.
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
-pub enum SchedulerKind {
- #[default]
- PinStash,
- KeyTable,
-}
-
-impl FromStr for SchedulerKind {
- type Err = String;
-
- fn from_str(s: &str) -> Result<Self, Self::Err> {
- match s.trim().to_lowercase().as_str() {
- "pin_stash" | "pin-stash" | "pinstash" => Ok(SchedulerKind::PinStash),
- "key_table" | "key-table" | "keytable" => Ok(SchedulerKind::KeyTable),
- other => Err(format!(
- "unknown scheduler '{other}' (expected 'pin_stash' or 'key_table')"
- )),
- }
- }
-}
-
-/// The decision core: which runs may go to a worker now, and where.
-///
-/// The caller owes the seam two things: it sends every dispatch an effects
-/// value carries, and every sent dispatch settles exactly once via
-/// [`Scheduler::on_settled`]. Settlement is the key-table scheduler's only
-/// release path for an outstanding key, so a dropped dispatch or a lost
-/// settlement wedges that key permanently.
-pub trait Scheduler {
- /// One poll's key runs arrived, in batch order, collected under
- /// `assignment_epoch`. A key may repeat; its runs merge in queue order.
- fn on_groups(
- &mut self,
- snapshot: &WorkerSnapshot,
- batch_id: &str,
- assignment_epoch: u64,
- groups: Vec<KeyRun>,
- ) -> SchedulerEffects;
-
- /// A send settled, with success or failure.
- fn on_settled(&mut self, snapshot: &WorkerSnapshot, settlement: Settlement)
- -> SchedulerEffects;
-
- /// The flush deadline for one batch's deferred work fired. Deadlines
- /// fire oldest batch first.
- fn on_deadline(&mut self, snapshot: &WorkerSnapshot, batch_id: &str) -> SchedulerEffects;
-}
-
-/// Sticky pin for one routing key. Tracks which worker owns the key and how
-/// many in-flight batches reference it. The pin is evicted when ref_count
-/// reaches 0 and the key has no deferred groups outstanding (see [`Stash`]).
-pub(crate) struct Pin {
- pub(crate) worker: WorkerId,
- pub(crate) ref_count: u32,
-}
-
-/// 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 current scheduling semantics, moved out of the dispatcher: sticky
-/// per-key pins, the deferred-message stash, and load-aware placement via the
-/// configured routing strategy.
-pub struct PinStashScheduler {
- /// Kafka message key → sticky assignment.
- pub(crate) pins: HashMap<String, Pin>,
- /// Messages deferred because their key's worker is draining/dead, keyed by
- /// batch, plus per-key outstanding counts. Flushed on `on_deadline`.
- pub(crate) stash: Stash,
- /// Worker selector for unpinned keys. Owned here because placement is a
- /// scheduling decision; P2C selection mutates the RNG.
- router: Router,
-}
-
-impl PinStashScheduler {
- pub fn new(router: Router) -> Self {
- Self {
- pins: HashMap::new(),
- stash: Stash::new(),
- router,
- }
- }
-
- /// Record a batch's arrival order for the stash. Must be called in true
- /// batch order, before `on_groups` — failed sends re-defer in gather
- /// order, so no later call site can establish the order reliably.
- pub fn register_batch(&mut self, batch_id: &str) {
- self.stash.register_batch(batch_id);
- }
-
- /// Forget a fully completed (committed) batch's arrival order and any
- /// leftover ledger state.
- pub fn release_batch(&mut self, batch_id: &str) {
- self.stash.release_batch(batch_id);
- }
-
- /// Whether `batch_id` still has deferred groups awaiting a retry.
- pub fn has_batch(&self, batch_id: &str) -> bool {
- self.stash.has_batch(batch_id)
- }
-
- pub fn pin_count(&self) -> usize {
- self.pins.len()
- }
-
- pub fn stashed_messages(&self) -> usize {
- self.stash.message_count()
- }
-
- pub fn stashed_batches(&self) -> usize {
- self.stash.batch_count()
- }
-
- /// Stash a failed send's runs for replay. Returns the number of groups
- /// stashed. Used by the failed-settlement arm, and directly by the
- /// caller's two-step test path.
- pub(crate) fn stash_failed(&mut self, batch_id: &str, runs: Vec<KeyRun>) -> u64 {
- let deferred = runs.len() as u64;
- for run in runs {
- self.stash.defer(
- batch_id,
- DeferredGroup {
- routing_key: run.routing_key,
- messages: run.messages,
- },
- );
- }
- record_stash_gauges(&self.stash);
- deferred
- }
-}
-
-impl Scheduler for PinStashScheduler {
- /// Per group:
- /// - honor an existing pin to a worker still taking work;
- /// - **defer** (stash under `batch_id`) a key pinned to a draining/dead
- /// worker, or one that already has deferred groups pending, so newer
- /// messages can't race ahead of the key's earlier ones;
- /// - otherwise route fresh via the configured strategy — or defer the
- /// group when no worker is routable at all, so a transient full-pool
- /// outage holds messages instead of failing the batch.
- fn on_groups(
- &mut self,
- snapshot: &WorkerSnapshot,
- batch_id: &str,
- _assignment_epoch: u64,
- groups: Vec<KeyRun>,
- ) -> SchedulerEffects {
- let mut effects = SchedulerEffects::with_dispatch_capacity(groups.len());
- let mut working_load = working_load(snapshot);
- let mut unpinned_groups: Vec<KeyRun> = Vec::new();
-
- for group in groups {
- let pinned_worker = self.pins.get(&group.routing_key).map(|p| p.worker.clone());
- match pinned_worker {
- Some(worker)
- if !self.stash.is_deferring(&group.routing_key)
- && !snapshot.is_dead(&worker)
- && !snapshot.is_draining(&worker) =>
- {
- // Live pin on a worker still taking work, nothing deferred
- // ahead of it — honor it.
- self.pins.get_mut(&group.routing_key).unwrap().ref_count += 1;
- bump_load(&mut working_load, &worker, group.messages.len());
- effects.dispatches.push(Dispatch {
- worker,
- routing_key: group.routing_key,
- messages: group.messages,
- kind: SendKind::Fresh,
- assignment_epoch: None,
- });
- }
- Some(_) => {
- // Pinned to a draining/dead worker, or the key already has
- // deferred groups pending — defer so newer messages can't
- // race ahead of the key's earlier in-flight/deferred ones.
- // 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 self.stash.is_deferring(&group.routing_key) {
- effects.deferred.queued_behind_deferral += 1;
- } else {
- effects.deferred.drain += 1;
- }
- self.stash.defer(
- batch_id,
- DeferredGroup {
- routing_key: group.routing_key,
- messages: group.messages,
- },
- );
- }
- None if self.stash.is_deferring(&group.routing_key) => {
- // No pin, but the key already has stashed groups (it was
- // unroutable earlier) — newer messages must queue behind
- // them, not race ahead.
- self.stash.defer(
- batch_id,
- DeferredGroup {
- routing_key: group.routing_key,
- messages: group.messages,
- },
- );
- effects.deferred.queued_behind_deferral += 1;
- }
- None => unpinned_groups.push(group),
- }
- }
-
- for group in unpinned_groups {
- let Some(worker) = self.router.select(&snapshot.candidates, &working_load) else {
- // No routable worker right now (e.g. the whole pool is draining
- // during a deploy overlap). Stash the group so the retry
- // deadline can route it once a worker returns — dropping it
- // would fail the whole batch and restart the process for a
- // transient condition.
- counter!("ingestion_consumer_dispatcher_unroutable_messages_total")
- .increment(group.messages.len() as u64);
- self.stash.defer(
- batch_id,
- DeferredGroup {
- routing_key: group.routing_key,
- messages: group.messages,
- },
- );
- effects.deferred.unroutable += 1;
- continue;
- };
-
- bump_load(&mut working_load, &worker, group.messages.len());
- self.pins.insert(
- group.routing_key.clone(),
- Pin {
- worker: worker.clone(),
- ref_count: 1,
- },
- );
- effects.dispatches.push(Dispatch {
- worker,
- routing_key: group.routing_key,
- messages: group.messages,
- kind: SendKind::Fresh,
- assignment_epoch: None,
- });
- }
-
- emit_deferred_counters(&effects.deferred);
- gauge!("ingestion_consumer_dispatcher_pins_total").set(self.pins.len() as f64);
- record_stash_gauges(&self.stash);
-
- effects
- }
-
- /// Subtracting the send from the caller's load table and completing a
- /// drain stay with the caller; here the settlement clears deferrals,
- /// requeues a failure, decrements ref-counts, and evicts idle pins so the
- /// key is re-assigned on its next arrival.
- fn on_settled(
- &mut self,
- _snapshot: &WorkerSnapshot,
- settlement: Settlement,
- ) -> SchedulerEffects {
- let mut effects = SchedulerEffects::default();
-
- if let SettlementOutcome::Failed { batch_id, runs } = settlement.outcome {
- // Re-stash the failed runs first, so the ref-count drop below
- // doesn't evict the pin while the key still has work to replay.
- // On the flush path this pairs with the `from_flush` decrement, so
- // the outstanding count nets to unchanged (never dipping to zero)
- // and the key keeps deferring across the retry.
- effects.deferred.send_failed = self.stash_failed(&batch_id, runs);
- emit_deferred_counters(&effects.deferred);
- }
-
- for key in &settlement.routing_keys {
- // For a flushed send, the key's flushed chunk has now landed —
- // clear one outstanding deferral before checking whether it can
- // evict.
- if settlement.from_flush {
- self.stash.completed(key);
- }
- // Don't evict a pin while the key still has deferred groups
- // awaiting a retry — new messages must keep deferring behind them
- // to preserve per-key order.
- let still_deferring = self.stash.is_deferring(key);
- if let Some(pin) = self.pins.get_mut(key) {
- // Skip stale resolves: a key's pin may have been re-pointed to
- // a different worker (e.g. by a deferred flush). A resolve
- // from the original send must not touch the new pin's
- // ref_count.
- if pin.worker != settlement.worker {
- continue;
- }
- pin.ref_count = pin.ref_count.saturating_sub(1);
- if pin.ref_count == 0 && !still_deferring {
- self.pins.remove(key);
- // All sends for the key resolved and nothing is deferred —
- // its order-sentinel history has nothing left to check.
- effects.evicted_keys.push(key.clone());
- }
- }
- }
-
- gauge!("ingestion_consumer_dispatcher_pins_total").set(self.pins.len() as f64);
- record_stash_gauges(&self.stash);
-
- effects
- }
-
- /// Retry a batch's deferred groups: route each to a healthy worker now
- /// that the key's earlier in-flight has resolved, re-pinning it. Groups
- /// that can't route yet (no healthy worker) stay stashed for the next
- /// deadline. Cross-key order is preserved because the caller fires
- /// deadlines oldest batch first.
- fn on_deadline(&mut self, snapshot: &WorkerSnapshot, batch_id: &str) -> SchedulerEffects {
- let groups = self.stash.take_batch(batch_id);
- if groups.is_empty() {
- return SchedulerEffects::default();
- }
-
- let mut effects = SchedulerEffects::with_dispatch_capacity(groups.len());
- let mut working_load = working_load(snapshot);
-
- for group in groups {
- // Prefer the key's existing pin when it still points to a healthy
- // worker, so a key deferred across several batches re-homes to a
- // single survivor — preserving per-key (person-batching)
- // locality instead of scattering its messages across workers.
- // 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(
- &self.pins,
- &group.routing_key,
- &snapshot.healthy,
- &working_load,
- );
- let worker = match sticky {
- Some(worker) => worker,
- None => {
- let Some(worker) = self.router.select(&snapshot.healthy, &working_load) else {
- // No healthy worker yet — keep it stashed for a later
- // deadline.
- self.stash.put_back(batch_id, group);
- continue;
- };
- worker
- }
- };
- bump_load(&mut working_load, &worker, group.messages.len());
- // Re-pin the key to the new worker. The deferral is NOT cleared here:
- // the flushed messages are now in flight but not yet ACKed, so the key
- // must keep deferring until that send resolves (see the `from_flush`
- // path in `on_settled`). Otherwise a newer batch could honor
- // this fresh pin and race the not-yet-landed flushed messages.
- match self.pins.get_mut(&group.routing_key) {
- Some(pin) => {
- pin.worker = worker.clone();
- pin.ref_count += 1;
- }
- None => {
- self.pins.insert(
- group.routing_key.clone(),
- Pin {
- worker: worker.clone(),
- ref_count: 1,
- },
- );
- }
- }
- effects.dispatches.push(Dispatch {
- worker,
- routing_key: group.routing_key,
- messages: group.messages,
- kind: SendKind::Resend,
- assignment_epoch: None,
- });
- }
-
- gauge!("ingestion_consumer_dispatcher_pins_total").set(self.pins.len() as f64);
- record_stash_gauges(&self.stash);
-
- effects
- }
-}
-
-/// 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 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)
-}
-
-/// Working load for one seam call: each healthy worker's outstanding load,
-/// bumped as runs are placed, so placement within the call accounts for
-/// earlier picks.
-pub(crate) fn working_load(snapshot: &WorkerSnapshot) -> WorkerLoad {
- snapshot
- .healthy
- .iter()
- .map(|w| (w.clone(), snapshot.load.get(w).copied().unwrap_or(0)))
- .collect()
-}
-
-/// Add `count` to a worker's working load for this round, if it is a candidate.
-/// Workers that aren't routing candidates (e.g. a pin honored on an unhealthy
-/// worker) have no entry and don't affect selection, so they're skipped.
-pub(crate) fn bump_load(working_load: &mut WorkerLoad, worker: &WorkerId, count: usize) {
- if let Some(load) = working_load.get_mut(worker) {
- *load = load.saturating_add(count);
- }
-}
-
-fn emit_deferred_counters(deferred: &DeferredCounts) {
- for (reason, count) in [
- ("drain", deferred.drain),
- ("queued_behind_deferral", deferred.queued_behind_deferral),
- ("unroutable", deferred.unroutable),
- ("send_failed", deferred.send_failed),
- ] {
- if count > 0 {
- counter!(
- "ingestion_consumer_dispatcher_deferred_groups_total",
- "reason" => reason,
- )
- .increment(count);
- }
- }
-}
-
-/// Publish point-in-time stash depth so a drain's backlog is observable and can
-/// be alerted on if it fails to drain to zero. Call after every mutation.
-fn record_stash_gauges(stash: &Stash) {
- gauge!("ingestion_consumer_dispatcher_stashed_batches").set(stash.batch_count() as f64);
- gauge!("ingestion_consumer_dispatcher_stashed_groups").set(stash.len() as f64);
- gauge!("ingestion_consumer_dispatcher_stashed_messages").set(stash.message_count() as f64);
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::routing::RoutingStrategy;
-
- const A: &str = "http://worker:1";
- const B: &str = "http://worker:2";
-
- fn wid(s: &str) -> WorkerId {
- WorkerId::from(s)
- }
-
- fn msg(key: &str) -> SerializedKafkaMessage {
- SerializedKafkaMessage {
- topic: "test".into(),
- partition: 0,
- offset: 0,
- timestamp: 0,
- key: Some(key.to_string()),
- value: None,
- headers: HashMap::new(),
- }
- }
-
- fn run(key: &str, n: usize) -> KeyRun {
- KeyRun {
- routing_key: key.to_string(),
- messages: (0..n).map(|_| msg(key)).collect(),
- }
- }
-
- /// Snapshot where every listed worker is live, with the given loads.
- /// Workers in `draining` are marked draining (and excluded from
- /// healthy/candidates, matching what the dispatcher passes). Workers not
- /// listed at all are absent from the health map, i.e. dead.
- fn snapshot(live: &[&str], draining: &[&str], load: &[(&str, usize)]) -> WorkerSnapshot {
- let healthy: Vec<WorkerId> = live.iter().map(|w| wid(w)).collect();
- let mut workers: HashMap<WorkerId, WorkerHealth> = HashMap::new();
- for w in live {
- workers.insert(
- wid(w),
- WorkerHealth {
- dead: false,
- draining: false,
- },
- );
- }
- for w in draining {
- workers.insert(
- wid(w),
- WorkerHealth {
- dead: false,
- draining: true,
- },
- );
- }
- let load: WorkerLoad = load.iter().map(|(w, n)| (wid(w), *n)).collect();
- WorkerSnapshot::new(healthy.clone(), healthy, load, workers)
- }
-
- fn scheduler() -> PinStashScheduler {
- PinStashScheduler::new(Router::with_seed(RoutingStrategy::P2c, 0))
- }
-
- fn delivered(worker: &str, keys: &[&str], from_flush: bool) -> Settlement {
- Settlement {
- worker: wid(worker),
- message_count: keys.len(),
- routing_keys: keys.iter().map(|k| k.to_string()).collect(),
- from_flush,
- outcome: SettlementOutcome::Delivered,
- }
- }
-
- fn failed(worker: &str, batch_id: &str, runs: Vec<KeyRun>, from_flush: bool) -> Settlement {
- Settlement {
- worker: wid(worker),
- message_count: runs.iter().map(|r| r.messages.len()).sum(),
- routing_keys: runs.iter().map(|r| r.routing_key.clone()).collect(),
- from_flush,
- outcome: SettlementOutcome::Failed {
- batch_id: batch_id.to_string(),
- runs,
- },
- }
- }
-
- // ---- on_groups: placement ----
-
- #[test]
- fn test_fresh_key_is_routed_pinned_and_dispatched_fresh() {
- let mut sched = scheduler();
- sched.register_batch("b1");
-
- let effects = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", 0, vec![run("t:a", 2)]);
-
- assert_eq!(effects.dispatches.len(), 1);
- assert_eq!(effects.dispatches[0].worker, wid(A));
- assert_eq!(effects.dispatches[0].kind, SendKind::Fresh);
- assert_eq!(effects.deferred.total(), 0);
- let pin = sched.pins.get("t:a").expect("key is pinned");
- assert_eq!(pin.ref_count, 1);
- }
-
- #[test]
- fn test_pinned_key_sticks_to_its_worker_despite_load() {
- let mut sched = scheduler();
- sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
-
- // B is now available and far less loaded — the pin still wins.
- sched.register_batch("b2");
- let effects = sched.on_groups(
- &snapshot(&[A, B], &[], &[(A, 10_000)]),
- "b2",
- 0,
- vec![run("t:a", 1)],
- );
-
- assert_eq!(effects.dispatches[0].worker, wid(A));
- assert_eq!(sched.pins.get("t:a").unwrap().ref_count, 2);
- }
-
- #[test]
- fn test_intra_batch_placement_accounts_for_earlier_picks() {
- let mut sched = scheduler();
- sched.register_batch("b1");
-
- // Two fresh equal-size groups, two idle workers: the first pick must
- // bump the working load so the second group lands on the other worker.
- let effects = sched.on_groups(
- &snapshot(&[A, B], &[], &[]),
- "b1",
- 0,
- vec![run("t:a", 3), run("t:b", 3)],
- );
-
- assert_eq!(effects.dispatches.len(), 2);
- assert_ne!(effects.dispatches[0].worker, effects.dispatches[1].worker);
- }
-
- #[test]
- fn test_unroutable_group_is_stashed_not_dropped() {
- let mut sched = scheduler();
- sched.register_batch("b1");
-
- let effects = sched.on_groups(&snapshot(&[], &[], &[]), "b1", 0, vec![run("t:a", 2)]);
-
- assert!(effects.dispatches.is_empty());
- assert_eq!(effects.deferred.unroutable, 1);
- assert_eq!(sched.pin_count(), 0, "an unrouted group takes no pin");
- assert!(sched.has_batch("b1"));
- assert_eq!(sched.stashed_messages(), 2);
- }
-
- // ---- on_groups: deferral ----
-
- #[test]
- fn test_pinned_key_defers_when_worker_draining() {
- let mut sched = scheduler();
- sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[A, B], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
- let pinned = sched.pins.get("t:a").unwrap().worker.clone();
- let pinned_str = pinned.to_string();
-
- sched.register_batch("b2");
- let survivor = if pinned == wid(A) { B } else { A };
- let effects = sched.on_groups(
- &snapshot(&[survivor], &[&pinned_str], &[]),
- "b2",
- 0,
- vec![run("t:a", 1)],
- );
-
- assert!(effects.dispatches.is_empty(), "must not reorder the key");
- assert_eq!(effects.deferred.drain, 1);
- assert!(sched.has_batch("b2"));
- }
-
- #[test]
- fn test_pinned_key_defers_when_worker_absent_from_snapshot() {
- let mut sched = scheduler();
- sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
-
- // A is gone from the health map entirely (removed from the registry):
- // absent must count as dead, not as healthy.
- sched.register_batch("b2");
- let effects = sched.on_groups(&snapshot(&[B], &[], &[]), "b2", 0, vec![run("t:a", 1)]);
-
- assert!(effects.dispatches.is_empty());
- assert_eq!(effects.deferred.drain, 1);
- }
-
- #[test]
- fn test_deferring_key_keeps_deferring_even_when_worker_recovers() {
- let mut sched = scheduler();
- sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
- sched.register_batch("b2");
- let _ = sched.on_groups(&snapshot(&[B], &[A], &[]), "b2", 0, vec![run("t:a", 1)]);
-
- // A is healthy again, but b2's deferred group hasn't flushed — newer
- // messages must queue behind it, and count as cascade, not drain.
- sched.register_batch("b3");
- let effects = sched.on_groups(&snapshot(&[A, B], &[], &[]), "b3", 0, vec![run("t:a", 1)]);
-
- assert!(effects.dispatches.is_empty());
- assert_eq!(effects.deferred.queued_behind_deferral, 1);
- assert_eq!(effects.deferred.drain, 0);
- }
-
- #[test]
- fn test_unpinned_key_queues_behind_its_stashed_groups() {
- let mut sched = scheduler();
- sched.register_batch("b1");
- // Unroutable: stashed with no pin.
- let _ = sched.on_groups(&snapshot(&[], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
-
- // A worker appears, but the stashed group must go first.
- sched.register_batch("b2");
- let effects = sched.on_groups(&snapshot(&[A], &[], &[]), "b2", 0, vec![run("t:a", 1)]);
-
- assert!(effects.dispatches.is_empty());
- assert_eq!(effects.deferred.queued_behind_deferral, 1);
- }
-
- // ---- on_settled ----
-
- #[test]
- fn test_settlement_evicts_idle_pin() {
- let mut sched = scheduler();
- sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
-
- let effects = sched.on_settled(&snapshot(&[A], &[], &[]), delivered(A, &["t:a"], false));
-
- assert_eq!(effects.evicted_keys, vec!["t:a".to_string()]);
- assert_eq!(sched.pin_count(), 0);
- }
-
- #[test]
- fn test_settlement_keeps_pin_while_key_still_defers() {
- let mut sched = scheduler();
- sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
- sched.register_batch("b2");
- let _ = sched.on_groups(&snapshot(&[B], &[A], &[]), "b2", 0, vec![run("t:a", 1)]);
-
- // b1's send lands, dropping the ref-count to zero — but b2's deferred
- // group is still stashed, so the pin must survive for it.
- let effects = sched.on_settled(&snapshot(&[B], &[A], &[]), delivered(A, &["t:a"], false));
-
- assert!(effects.evicted_keys.is_empty());
- assert_eq!(sched.pin_count(), 1);
- }
-
- #[test]
- fn test_stale_settlement_does_not_touch_repointed_pin() {
- let mut sched = scheduler();
- sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
- sched.register_batch("b2");
- let _ = sched.on_groups(&snapshot(&[B], &[A], &[]), "b2", 0, vec![run("t:a", 1)]);
-
- // The deferred flush re-points the pin to B while b1's send is still
- // unresolved on A.
- let effects = sched.on_deadline(&snapshot(&[B], &[A], &[]), "b2");
- assert_eq!(effects.dispatches[0].worker, wid(B));
- let ref_count = sched.pins.get("t:a").unwrap().ref_count;
-
- // b1's resolve from A must not decrement the new pin's ref-count.
- let effects = sched.on_settled(&snapshot(&[B], &[A], &[]), delivered(A, &["t:a"], false));
-
- assert!(effects.evicted_keys.is_empty());
- assert_eq!(sched.pins.get("t:a").unwrap().ref_count, ref_count);
- }
-
- #[test]
- fn test_failed_settlement_restashes_before_releasing_the_key() {
- let mut sched = scheduler();
- sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[A, B], &[], &[]), "b1", 0, vec![run("t:a", 2)]);
-
- let effects = sched.on_settled(
- &snapshot(&[A, B], &[], &[]),
- failed(A, "b1", vec![run("t:a", 2)], false),
- );
-
- assert_eq!(effects.deferred.send_failed, 1);
- assert!(
- effects.evicted_keys.is_empty(),
- "the pin must survive: the key still has work to replay"
- );
- assert_eq!(sched.stashed_messages(), 2);
-
- // Newer messages queue behind the replay instead of overtaking it.
- sched.register_batch("b2");
- let effects = sched.on_groups(&snapshot(&[A, B], &[], &[]), "b2", 0, vec![run("t:a", 1)]);
- assert!(effects.dispatches.is_empty());
- assert_eq!(effects.deferred.queued_behind_deferral, 1);
- }
-
- #[test]
- fn test_failed_flush_keeps_key_deferring() {
- let mut sched = scheduler();
- sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
- let effects = sched.on_deadline(&snapshot(&[A], &[], &[]), "b1");
- assert_eq!(effects.dispatches.len(), 1);
-
- // The flushed send fails: the re-stash and the from_flush decrement
- // must net out so the key never stops deferring across the retry.
- let _ = sched.on_settled(
- &snapshot(&[A], &[], &[]),
- failed(A, "b1", vec![run("t:a", 1)], true),
- );
-
- sched.register_batch("b2");
- let effects = sched.on_groups(&snapshot(&[A], &[], &[]), "b2", 0, vec![run("t:a", 1)]);
- assert!(effects.dispatches.is_empty());
- assert_eq!(effects.deferred.queued_behind_deferral, 1);
- }
-
- // ---- on_deadline ----
-
- #[test]
- fn test_deadline_with_nothing_stashed_is_a_noop() {
- let mut sched = scheduler();
-
- let effects = sched.on_deadline(&snapshot(&[A], &[], &[]), "b1");
-
- assert!(effects.dispatches.is_empty());
- assert_eq!(effects.deferred.total(), 0);
- assert!(effects.evicted_keys.is_empty());
- }
-
- #[test]
- fn test_deadline_keeps_group_stashed_when_no_worker_is_healthy() {
- let mut sched = scheduler();
- sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
-
- let effects = sched.on_deadline(&snapshot(&[], &[], &[]), "b1");
-
- assert!(effects.dispatches.is_empty());
- assert!(sched.has_batch("b1"), "kept for a later deadline");
- assert_eq!(sched.stashed_messages(), 1);
- }
-
- #[test]
- fn test_flushed_key_keeps_deferring_until_the_flush_settles() {
- let mut sched = scheduler();
- sched.register_batch("b1");
- let _ = sched.on_groups(&snapshot(&[A], &[], &[]), "b1", 0, vec![run("t:a", 1)]);
- sched.register_batch("b2");
- let _ = sched.on_groups(&snapshot(&[B], &[A], &[]), "b2", 0, vec![run("t:a", 1)]);
- let _ = sched.on_settled(&snapshot(&[B], &[A], &[]), delivered(A, &["t:a"], false));
-
- let effects = sched.on_deadline(&snapshot(&[B], &[A], &[]), "b2");
- assert_eq!(effects.dispatches.len(), 1);
- assert_eq!(effects.dispatches[0].kind, SendKind::Resend);
- assert_eq!(
- effects.dispatches[0].worker,
- wid(B),
- "re-pinned off the drainer"
- );
-
- // The flushed send is in flight but not ACKed — newer messages must
- // not honor the fresh pin and race it.
- sched.register_batch("b3");
- let effects = sched.on_groups(&snapshot(&[B], &[A], &[]), "b3", 0, vec![run("t:a", 1)]);
- assert!(effects.dispatches.is_empty());
- assert_eq!(effects.deferred.queued_behind_deferral, 1);
-
- // The flush ACKs: the deferral clears, the pin evicts, b3's group is
- // free to flush and the key's life cycle ends clean.
- let effects = sched.on_settled(&snapshot(&[B], &[A], &[]), delivered(B, &["t:a"], true));
- assert!(effects.evicted_keys.is_empty(), "b3's group still stashed");
- let effects = sched.on_deadline(&snapshot(&[B], &[A], &[]), "b3");
- assert_eq!(effects.dispatches.len(), 1);
- let effects = sched.on_settled(&snapshot(&[B], &[A], &[]), delivered(B, &["t:a"], true));
- assert_eq!(effects.evicted_keys, vec!["t:a".to_string()]);
- assert_eq!(sched.pin_count(), 0);
- assert_eq!(sched.stashed_messages(), 0);
- }
-
- // ---- sticky pin at flush time ----
-
- #[test]
- fn test_sticky_pin_honored_when_healthy_and_load_comparable() {
- let mut pins = HashMap::new();
- pins.insert(
- "t:a".to_string(),
- Pin {
- worker: wid(A),
- ref_count: 1,
- },
- );
- let healthy = [wid(A), wid(B)];
- // Load within min * FACTOR + SLACK: an idle candidate must not
- // disqualify a pin holding a few hundred messages.
- let load: WorkerLoad = [(wid(A), STICKY_PIN_LOAD_SLACK), (wid(B), 0)].into();
-
- assert_eq!(sticky_pin_for(&pins, "t:a", &healthy, &load), Some(wid(A)));
-
- let load: WorkerLoad = [(wid(A), STICKY_PIN_LOAD_SLACK + 1), (wid(B), 0)].into();
- assert_eq!(
- sticky_pin_for(&pins, "t:a", &healthy, &load),
- None,
- "beyond the slack the pin yields to load"
- );
- }
-
- #[test]
- fn test_sticky_pin_declined_when_worker_unhealthy() {
- let mut pins = HashMap::new();
- pins.insert(
- "t:a".to_string(),
- Pin {
- worker: wid(A),
- ref_count: 1,
- },
- );
-
- assert_eq!(
- sticky_pin_for(&pins, "t:a", &[wid(B)], &WorkerLoad::new()),
- None
- );
- assert_eq!(
- sticky_pin_for(&pins, "t:other", &[wid(A)], &WorkerLoad::new()),
- None,
- "no pin, no stickiness"
- );
- }
-}
diff --git a/rust/ingestion-consumer/src/stash.rs b/rust/ingestion-consumer/src/stash.rs
deleted file mode 100644
index 6e06e156a109..000000000000
--- a/rust/ingestion-consumer/src/stash.rs
+++ /dev/null
@@ -1,340 +0,0 @@
-//! Deferred-message stash for graceful drain / worker loss.
-//!
-//! When a routing key is pinned to a worker that is draining or dead, new
-//! messages for that key can't be sent there (it must finish and exit) and
-//! can't be re-routed elsewhere yet (the key's earlier messages are still in
-//! flight on that worker — re-routing now would reorder the key). So
-//! they are *stashed* here until the worker's in-flight resolves, then flushed
-//! (re-routed) in 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
-//! has deferred work pending.
-//!
-//! A group contributes 1 to its key's outstanding count from [`Stash::defer`]
-//! until [`Stash::completed`] (i.e. until it has actually been routed). Pulling
-//! groups out to attempt a flush ([`Stash::take_batch`]) and putting back the
-//! ones that couldn't route ([`Stash::put_back`]) do not change the count.
-
-use std::collections::{HashMap, VecDeque};
-
-use crate::types::SerializedKafkaMessage;
-
-/// Messages for one routing key, deferred because the key's pinned worker is
-/// draining or dead.
-pub struct DeferredGroup {
- pub routing_key: String,
- pub messages: Vec<SerializedKafkaMessage>,
-}
-
-impl DeferredGroup {
- pub fn message_count(&self) -> usize {
- self.messages.len()
- }
-}
-
-struct Entry {
- batch_seq: u64,
- batch_id: String,
- messages: Vec<SerializedKafkaMessage>,
-}
-
-#[derive(Default)]
-pub struct Stash {
- /// 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>,
-}
-
-impl Stash {
- pub fn new() -> Self {
- 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.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
- /// messages for such a key must keep deferring, and its pin must not be
- /// evicted.
- pub fn is_deferring(&self, routing_key: &str) -> bool {
- self.outstanding.get(routing_key).is_some_and(|&n| n > 0)
- }
-
- /// Whether `batch_id` has any deferred groups still awaiting flush.
- pub fn has_batch(&self, batch_id: &str) -> bool {
- self.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
- /// route them. Routed groups must be acknowledged with [`Stash::completed`];
- /// groups that couldn't route are returned via [`Stash::put_back`]. Neither
- /// this call nor `put_back` changes outstanding counts — only `completed` does.
- pub fn take_batch(&mut self, batch_id: &str) -> Vec<DeferredGroup> {
- 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
- }
-
- /// 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);
- 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
- /// key's outstanding count.
- pub fn completed(&mut self, routing_key: &str) {
- if let Some(n) = self.outstanding.get_mut(routing_key) {
- *n -= 1;
- if *n == 0 {
- self.outstanding.remove(routing_key);
- }
- }
- }
-
- /// Total deferred groups currently stashed (for metrics/tests).
- pub fn len(&self) -> usize {
- self.queues.values().map(VecDeque::len).sum()
- }
-
- pub fn is_empty(&self) -> bool {
- self.queues.is_empty()
- }
-
- /// Number of batches that currently have deferred groups awaiting flush.
- pub fn batch_count(&self) -> usize {
- self.batch_live.len()
- }
-
- /// Total deferred messages currently stashed across all batches and groups.
- pub fn message_count(&self) -> usize {
- self.queues
- .values()
- .flat_map(|queue| queue.iter())
- .map(|entry| entry.messages.len())
- .sum()
- }
-}
-
-#[cfg(test)]
-mod tests {
- use std::collections::HashMap;
-
- use super::*;
- use crate::types::SerializedKafkaMessage;
-
- fn msg(key: &str) -> SerializedKafkaMessage {
- SerializedKafkaMessage {
- topic: "test".into(),
- partition: 0,
- offset: 0,
- timestamp: 0,
- key: Some(key.to_string()),
- value: None,
- headers: HashMap::new(),
- }
- }
-
- fn group(key: &str, n: usize) -> DeferredGroup {
- DeferredGroup {
- routing_key: key.to_string(),
- messages: (0..n).map(|_| msg(key)).collect(),
- }
- }
-
- #[test]
- fn test_defer_marks_key_deferring() {
- let mut stash = Stash::new();
- assert!(!stash.is_deferring("t:a"));
-
- stash.defer("batch-1", group("t:a", 2));
- assert!(stash.is_deferring("t:a"));
- assert!(stash.has_batch("batch-1"));
- assert_eq!(stash.len(), 1);
- }
-
- #[test]
- fn test_completed_clears_deferring_only_when_count_hits_zero() {
- let mut stash = Stash::new();
- // Same key deferred by two batches → outstanding count 2.
- stash.defer("batch-1", group("t:a", 1));
- stash.defer("batch-2", group("t:a", 1));
- assert!(stash.is_deferring("t:a"));
-
- stash.completed("t:a");
- assert!(
- stash.is_deferring("t:a"),
- "still deferring with one outstanding"
- );
-
- stash.completed("t:a");
- assert!(
- !stash.is_deferring("t:a"),
- "no longer deferring once all routed"
- );
- }
-
- #[test]
- fn test_take_batch_removes_groups_without_changing_outstanding() {
- let mut stash = Stash::new();
- stash.defer("batch-1", group("t:a", 1));
-
- let taken = stash.take_batch("batch-1");
- assert_eq!(taken.len(), 1);
- assert!(!stash.has_batch("batch-1"), "batch's groups are removed");
- assert!(
- stash.is_deferring("t:a"),
- "taking to attempt a flush must not clear the outstanding count"
- );
- }
-
- #[test]
- fn test_put_back_re_stashes_without_double_counting() {
- let mut stash = Stash::new();
- stash.defer("batch-1", group("t:a", 1));
- let mut taken = stash.take_batch("batch-1");
-
- // Couldn't route — put it back.
- stash.put_back("batch-1", taken.pop().unwrap());
- assert!(stash.has_batch("batch-1"));
- assert!(stash.is_deferring("t:a"));
-
- // Now it routes: take + completed → count clears.
- let mut taken = stash.take_batch("batch-1");
- stash.completed(&taken.pop().unwrap().routing_key);
- assert!(!stash.is_deferring("t:a"));
- }
-
- #[test]
- fn test_completed_beyond_outstanding_is_noop() {
- // A spurious extra completion (e.g. a double resolve for the same key)
- // must be a no-op — not an underflow that would leave the key
- // "deferring" forever and stall it permanently.
- let mut stash = Stash::new();
- stash.defer("batch-1", group("t:a", 1));
-
- stash.completed("t:a");
- assert!(!stash.is_deferring("t:a"));
-
- stash.completed("t:a");
- assert!(!stash.is_deferring("t:a"));
- }
-
- #[test]
- fn test_take_unknown_batch_is_empty() {
- let mut stash = Stash::new();
- assert!(stash.take_batch("nope").is_empty());
- }
-
- #[test]
- fn test_depth_counts_batches_groups_and_messages() {
- let mut stash = Stash::new();
- stash.defer("batch-1", group("t:a", 2));
- stash.defer("batch-1", group("t:b", 1));
- stash.defer("batch-2", group("t:a", 3));
-
- assert_eq!(stash.batch_count(), 2);
- assert_eq!(stash.len(), 3, "three groups across two batches");
- assert_eq!(stash.message_count(), 6, "2 + 1 + 3 messages");
-
- // Taking a batch out to attempt a flush drops it from the depth counts.
- let _ = stash.take_batch("batch-1");
- assert_eq!(stash.batch_count(), 1);
- assert_eq!(stash.message_count(), 3);
- }
-}
diff --git a/rust/ingestion-consumer/src/transport.rs b/rust/ingestion-consumer/src/transport.rs
index c46b1118fd24..f7fee8c4f385 100644
--- a/rust/ingestion-consumer/src/transport.rs
+++ b/rust/ingestion-consumer/src/transport.rs
@@ -63,20 +63,21 @@ pub enum SendOutcome {
}
/// Failure from a worker stream send, carrying back the sub-batch's messages
-/// so the caller can defer/replay them (the worker may have died mid-send and
-/// the messages were never accepted).
+/// so the caller can requeue and replay them (the worker may have died
+/// mid-send and the messages were never accepted).
#[derive(Debug)]
pub struct SendError {
pub error: TransportError,
pub messages: Vec<SerializedKafkaMessage>,
- /// Set on a fenced worker stream send. Hold it until `messages` are stashed: the
- /// worker stream keeps fencing new arrivals until every guard from that fence is
- /// dropped, so nothing enqueued before the stash lands can reach the
- /// worker ahead of the fenced groups on the next stream.
+ /// Set on a fenced worker stream send. Hold it until `messages` are
+ /// requeued: the worker stream keeps fencing new arrivals until every
+ /// guard from that fence is dropped, so nothing enqueued before the
+ /// requeue lands can reach the worker ahead of the fenced messages on the
+ /// next stream.
pub fence_guard: Option<FenceGuard>,
}
-/// Tells a fencing worker stream that one fenced send's messages are stashed.
+/// Tells a fencing worker stream that one fenced send's messages are requeued.
pub struct FenceGuard {
/// One release per fenced send this guard stands for: a split sub-batch
/// fenced across several chunks merges their guards into one.
diff --git a/rust/ingestion-consumer/src/worker_registry.rs b/rust/ingestion-consumer/src/worker_registry.rs
index a64ca493a9d8..abbaf478d521 100644
--- a/rust/ingestion-consumer/src/worker_registry.rs
+++ b/rust/ingestion-consumer/src/worker_registry.rs
@@ -14,7 +14,7 @@ use crate::debug_recorder::{record_if, DebugEventKind, DebugRecorder, WorkerHeal
const PASSIVE_WINDOW_MAX_ENTRIES: usize = 10_000;
/// Stable identity for a worker: its base HTTP URL (e.g. `http://10.0.0.1:9001`).
-/// Used as the key for health, routing pins, and in-flight load so the worker
+/// Used as the key for health, placement, and in-flight load so the worker
/// set can change at runtime without the index-shifting hazards of a `Vec`.
pub type WorkerId = Arc<str>;
@@ -245,9 +245,8 @@ impl From<&Config> for WorkerRegistryConfig {
/// All transitions respect a `min_state_duration` cooldown to prevent flapping.
///
/// A worker that has been `Unhealthy` for at least `dead_declaration` is
-/// considered **dead** — the Dispatcher uses this to drop sticky pins so the
-/// next batch can re-route around the worker. A worker removed from the pool
-/// entirely is also reported dead.
+/// considered **dead**. A worker removed from the pool entirely is also
+/// reported dead.
pub struct WorkerRegistry {
workers: DashMap<WorkerId, WorkerHealth>,
config: WorkerRegistryConfig,
@@ -339,7 +338,7 @@ impl WorkerRegistry {
}
/// Whether a worker is dead — Unhealthy for at least `dead_declaration`, or
- /// no longer in the pool at all (so its sticky pins get dropped).
+ /// no longer in the pool at all.
pub fn is_dead(&self, worker: &str) -> bool {
self.workers
.get(worker)
diff --git a/rust/ingestion-consumer/tests/batcher_integration_test.rs b/rust/ingestion-consumer/tests/batcher_integration_test.rs
new file mode 100644
index 000000000000..8a3ea12978ed
--- /dev/null
+++ b/rust/ingestion-consumer/tests/batcher_integration_test.rs
@@ -0,0 +1,101 @@
+mod common;
+
+use std::collections::HashMap;
+use std::sync::Arc;
+use std::time::Duration;
+
+use common_kafka_consumer::Partition;
+
+use common::one_message_batcher;
+use ingestion_consumer::batcher::worker_pool::WorkerPoolSource;
+use ingestion_consumer::grpc_transport::{GrpcPort, GrpcTransport};
+use ingestion_consumer::routing::RoutingStrategy;
+use ingestion_consumer::types::{Accumulator, SerializedKafkaMessage};
+use ingestion_consumer::worker_registry::{WorkerRegistry, WorkerRegistryConfig};
+
+fn fast_config() -> WorkerRegistryConfig {
+ WorkerRegistryConfig {
+ probe_interval: Duration::from_millis(15),
+ dead_declaration: Duration::from_millis(40),
+ passive_window: Duration::from_secs(60),
+ passive_error_threshold: 0.01,
+ passive_min_samples: 1000,
+ degraded_hold: Duration::from_millis(30),
+ min_state_duration: Duration::ZERO,
+ probe_failure_threshold: 2,
+ drain_timeout: Duration::from_secs(5),
+ }
+}
+
+fn make_msg(key: &str) -> SerializedKafkaMessage {
+ SerializedKafkaMessage {
+ topic: "test".into(),
+ partition: 0,
+ offset: 0,
+ timestamp: 0,
+ key: Some(key.to_string()),
+ value: None,
+ headers: HashMap::new(),
+ }
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn purging_a_just_submitted_batch_is_not_fatal() {
+ let registry = Arc::new(WorkerRegistry::new(&[], fast_config()));
+ let pool_source = WorkerPoolSource::new(registry, RoutingStrategy::P2c);
+ let transport = Arc::new(GrpcTransport::new(
+ GrpcPort::OffsetFromHttp(0),
+ 1,
+ Duration::from_secs(30),
+ ));
+ let (batcher, mut outputs) = one_message_batcher(
+ pool_source,
+ transport,
+ Duration::from_secs(10),
+ Duration::from_millis(20),
+ );
+
+ let mut accumulator = Accumulator::default();
+ accumulator.push(Partition(0), make_msg("a").into());
+ batcher.submit(accumulator);
+ // No await between submit and purge: the batcher task receives both
+ // before it runs, and discards the submission when it applies the purge.
+ batcher.revoker().purge_revoked(&[("test".to_string(), 0)]);
+
+ match tokio::time::timeout(Duration::from_millis(100), outputs.errors.recv()).await {
+ Err(_) => {}
+ Ok(Some(error)) => panic!("revoked work must not report a routing failure: {error}"),
+ Ok(None) => panic!("batcher error channel closed unexpectedly"),
+ }
+}
+
+#[tokio::test]
+async fn dropping_an_idle_batcher_closes_its_outputs() {
+ let registry = Arc::new(WorkerRegistry::new(&[], fast_config()));
+ let pool_source = WorkerPoolSource::new(registry, RoutingStrategy::P2c);
+ let transport = Arc::new(GrpcTransport::new(
+ GrpcPort::OffsetFromHttp(0),
+ 1,
+ Duration::from_secs(30),
+ ));
+ let (batcher, mut outputs) = one_message_batcher(
+ pool_source,
+ transport,
+ Duration::from_secs(10),
+ Duration::from_millis(20),
+ );
+
+ drop(batcher);
+
+ let completion = tokio::time::timeout(Duration::from_millis(100), outputs.completions.recv())
+ .await
+ .expect("dropping the batcher must not leave an idle retry task retaining its senders");
+ assert!(
+ completion.is_none(),
+ "an idle dropped batcher cannot produce a completion"
+ );
+ assert!(
+ outputs.errors.recv().await.is_none(),
+ "all output senders close with the dropped batcher"
+ );
+}
diff --git a/rust/ingestion-consumer/tests/common/mod.rs b/rust/ingestion-consumer/tests/common/mod.rs
index d332180e8bdf..593d7f35277c 100644
--- a/rust/ingestion-consumer/tests/common/mod.rs
+++ b/rust/ingestion-consumer/tests/common/mod.rs
@@ -10,12 +10,10 @@ use ingestion_consumer::batcher::packer::{PackTargets, Packer};
use ingestion_consumer::batcher::retry_policy::RetryPolicy;
use ingestion_consumer::batcher::state_machine::{BatcherStateMachine, RequestBudget};
use ingestion_consumer::batcher::worker_assigner::WorkerAssigner;
+use ingestion_consumer::batcher::worker_pool::WorkerPoolSource;
use ingestion_consumer::batcher::{Batcher, BatcherOutputs};
-use ingestion_consumer::dispatcher::Dispatcher;
use ingestion_consumer::grpc_transport::GrpcTransport;
use ingestion_consumer::routing::Router;
-use ingestion_consumer::scheduler::SchedulerKind;
-use lifecycle::Handle;
pub const PRODUCTION_PACK_TARGETS: PackTargets = PackTargets {
events: NonZeroUsize::new(500),
@@ -29,58 +27,16 @@ pub const ONE_MESSAGE_PER_REQUEST: PackTargets = PackTargets {
latency_budget: Duration::ZERO,
};
-#[allow(clippy::too_many_arguments)]
+/// A batcher over `pool_source`'s workers, with the transport's un-acked cap
+/// as its per-worker request cap.
pub fn batcher(
- kind: SchedulerKind,
- dispatcher: &Arc<Dispatcher>,
+ pool_source: WorkerPoolSource,
transport: Arc<GrpcTransport>,
- handle: Handle,
stall_timeout: Duration,
retry_delay: Duration,
pack_targets: PackTargets,
budget: Option<RequestBudget>,
) -> (Batcher, BatcherOutputs) {
- match kind {
- SchedulerKind::PinStash => {
- debug_assert!(budget.is_none(), "pin_stash sends no budget");
- Batcher::new(Arc::clone(dispatcher), transport, handle, stall_timeout)
- }
- SchedulerKind::KeyTable => packing_key_table_batcher(
- dispatcher,
- transport,
- stall_timeout,
- retry_delay,
- pack_targets,
- budget,
- ),
- }
-}
-
-pub fn key_table_batcher(
- dispatcher: &Dispatcher,
- transport: Arc<GrpcTransport>,
- stall_timeout: Duration,
- retry_delay: Duration,
-) -> (Batcher, BatcherOutputs) {
- packing_key_table_batcher(
- dispatcher,
- transport,
- stall_timeout,
- retry_delay,
- ONE_MESSAGE_PER_REQUEST,
- None,
- )
-}
-
-fn packing_key_table_batcher(
- dispatcher: &Dispatcher,
- transport: Arc<GrpcTransport>,
- stall_timeout: Duration,
- retry_delay: Duration,
- pack_targets: PackTargets,
- budget: Option<RequestBudget>,
-) -> (Batcher, BatcherOutputs) {
- let pool_source = dispatcher.worker_pool_source();
let assigner =
WorkerAssigner::new(Router::new(pool_source.strategy()), transport.max_unacked())
.expect("valid request cap");
@@ -94,5 +50,22 @@ fn packing_key_table_batcher(
)
.expect("valid stall timeout")
.with_request_budget(budget);
- Batcher::with_state_machine(state_machine, pool_source, transport)
+ Batcher::new(state_machine, pool_source, transport)
+}
+
+/// A batcher that sends every message in its own request.
+pub fn one_message_batcher(
+ pool_source: WorkerPoolSource,
+ transport: Arc<GrpcTransport>,
+ stall_timeout: Duration,
+ retry_delay: Duration,
+) -> (Batcher, BatcherOutputs) {
+ batcher(
+ pool_source,
+ transport,
+ stall_timeout,
+ retry_delay,
+ ONE_MESSAGE_PER_REQUEST,
+ None,
+ )
}
diff --git a/rust/ingestion-consumer/tests/dispatcher_integration_test.rs b/rust/ingestion-consumer/tests/dispatcher_integration_test.rs
deleted file mode 100644
index abccaac7d0f4..000000000000
--- a/rust/ingestion-consumer/tests/dispatcher_integration_test.rs
+++ /dev/null
@@ -1,526 +0,0 @@
-mod common;
-
-use std::collections::HashMap;
-use std::sync::atomic::{AtomicBool, Ordering};
-use std::sync::Arc;
-use std::time::Duration;
-
-use common_kafka_consumer::Partition;
-
-use axum::extract::State;
-use axum::response::IntoResponse;
-use axum::routing::get;
-use axum::Router;
-use tokio::net::TcpListener;
-use tokio_util::sync::CancellationToken;
-
-use common::key_table_batcher;
-use ingestion_consumer::dispatcher::Dispatcher;
-use ingestion_consumer::grpc_transport::{GrpcPort, GrpcTransport};
-use ingestion_consumer::routing::RoutingStrategy;
-use ingestion_consumer::types::{Accumulator, SerializedKafkaMessage};
-use ingestion_consumer::worker_registry::{WorkerRegistry, WorkerRegistryConfig, WorkerState};
-
-// ---- FakeWorker ----
-
-#[derive(Clone)]
-struct WorkerCtrl {
- is_healthy: Arc<AtomicBool>,
-}
-
-async fn ready_handler(State(ctrl): State<WorkerCtrl>) -> impl IntoResponse {
- if ctrl.is_healthy.load(Ordering::Relaxed) {
- axum::http::StatusCode::OK
- } else {
- axum::http::StatusCode::SERVICE_UNAVAILABLE
- }
-}
-
-struct FakeWorker {
- pub url: String,
- is_healthy: Arc<AtomicBool>,
- handle: tokio::task::JoinHandle<()>,
-}
-
-impl FakeWorker {
- async fn start() -> Self {
- let is_healthy = Arc::new(AtomicBool::new(true));
- let ctrl = WorkerCtrl {
- is_healthy: Arc::clone(&is_healthy),
- };
-
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
-
- let app = Router::new()
- .route("/_ready", get(ready_handler))
- .with_state(ctrl);
-
- let handle = tokio::spawn(async move {
- axum::serve(listener, app)
- .await
- .expect("fake worker server error");
- });
-
- Self {
- url: format!("http://{addr}"),
- is_healthy,
- handle,
- }
- }
-
- fn set_healthy(&self, healthy: bool) {
- self.is_healthy.store(healthy, Ordering::Relaxed);
- }
-}
-
-impl Drop for FakeWorker {
- fn drop(&mut self) {
- self.handle.abort();
- }
-}
-
-// ---- helpers ----
-
-fn fast_config() -> WorkerRegistryConfig {
- WorkerRegistryConfig {
- probe_interval: Duration::from_millis(15),
- dead_declaration: Duration::from_millis(40),
- passive_window: Duration::from_secs(60),
- passive_error_threshold: 0.01,
- passive_min_samples: 1000,
- degraded_hold: Duration::from_millis(30),
- min_state_duration: Duration::ZERO,
- probe_failure_threshold: 2,
- drain_timeout: Duration::from_secs(5),
- }
-}
-
-fn make_msg(key: &str) -> SerializedKafkaMessage {
- SerializedKafkaMessage {
- topic: "test".into(),
- partition: 0,
- offset: 0,
- timestamp: 0,
- key: Some(key.to_string()),
- value: None,
- headers: HashMap::new(),
- }
-}
-
-async fn wait_for_state(registry: &WorkerRegistry, worker: &str, expected: WorkerState) {
- let deadline = tokio::time::Instant::now() + Duration::from_secs(3);
- loop {
- if registry.state(worker) == expected {
- return;
- }
- assert!(
- tokio::time::Instant::now() < deadline,
- "timed out waiting for worker {worker} to become {expected:?}"
- );
- tokio::time::sleep(Duration::from_millis(5)).await;
- }
-}
-
-async fn wait_for_dead(registry: &WorkerRegistry, worker: &str) {
- let deadline = tokio::time::Instant::now() + Duration::from_secs(3);
- loop {
- if registry.is_dead(worker) {
- return;
- }
- assert!(
- tokio::time::Instant::now() < deadline,
- "timed out waiting for worker {worker} to be declared dead"
- );
- tokio::time::sleep(Duration::from_millis(5)).await;
- }
-}
-
-async fn wait_for_not_unhealthy(registry: &WorkerRegistry, worker: &str) {
- let deadline = tokio::time::Instant::now() + Duration::from_secs(3);
- loop {
- if registry.state(worker) != WorkerState::Unhealthy {
- return;
- }
- assert!(
- tokio::time::Instant::now() < deadline,
- "timed out waiting for worker {worker} to leave Unhealthy"
- );
- tokio::time::sleep(Duration::from_millis(5)).await;
- }
-}
-
-// ---- tests ----
-
-/// Fresh keys must not be assigned to an Unhealthy worker, even though the
-/// worker's server is still up (just returning 503 on /_ready).
-#[tokio::test]
-async fn test_new_keys_skip_unhealthy_worker() {
- let w0 = FakeWorker::start().await;
- let w1 = FakeWorker::start().await;
-
- let urls = vec![w0.url.clone(), w1.url.clone()];
- let registry = Arc::new(WorkerRegistry::new(&urls, fast_config()));
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- let token = CancellationToken::new();
- Arc::clone(&registry).start_probing(token.clone());
-
- w1.set_healthy(false);
- wait_for_state(&registry, &w1.url, WorkerState::Unhealthy).await;
-
- let keys: Vec<_> = (0..10).map(|i| make_msg(&format!("t:user-{i}"))).collect();
- let sub_batches = dispatcher.assign("b", keys);
-
- assert!(
- sub_batches.iter().all(|b| b.worker.as_ref() == w0.url),
- "all assignments should go to w0; workers used: {:?}",
- sub_batches
- .iter()
- .map(|b| b.worker.to_string())
- .collect::<Vec<_>>()
- );
-
- token.cancel();
-}
-
-/// A key pinned to a worker while it was healthy must be re-routed to a
-/// healthy worker after the original worker is declared dead.
-#[tokio::test]
-async fn test_pinned_key_rerouted_after_dead_declaration() {
- let w0 = FakeWorker::start().await;
- let w1 = FakeWorker::start().await;
-
- let urls = vec![w0.url.clone(), w1.url.clone()];
- let registry = Arc::new(WorkerRegistry::new(&urls, fast_config()));
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- let token = CancellationToken::new();
- Arc::clone(&registry).start_probing(token.clone());
-
- // Pin "t:user-1" to whichever worker gets it first. Hold the sub-batch
- // open (don't call on_sub_batch_resolved) so the pin stays alive.
- let b1 = dispatcher.assign("b", vec![make_msg("t:user-1")]);
- assert_eq!(b1.len(), 1);
- let pinned_to = b1[0].worker.clone();
- let other = if pinned_to.as_ref() == w0.url {
- w1.url.clone()
- } else {
- w0.url.clone()
- };
-
- // Kill the pinned worker's health endpoint.
- if pinned_to.as_ref() == w0.url {
- w0.set_healthy(false);
- } else {
- w1.set_healthy(false);
- }
-
- // Wait for Unhealthy then dead declaration.
- wait_for_state(&registry, &pinned_to, WorkerState::Unhealthy).await;
- wait_for_dead(&registry, &pinned_to).await;
-
- // 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,
- false,
- );
-
- // Next assign: the evicted pin means the key re-routes to the live worker.
- let b2 = dispatcher.assign("b", vec![make_msg("t:user-1")]);
- assert_eq!(b2.len(), 1, "expected exactly one sub-batch");
- assert_eq!(
- b2[0].worker.as_ref(),
- other,
- "user-1 should reroute to the live worker after {pinned_to} is dead"
- );
-
- token.cancel();
-}
-
-/// When a dead worker's health endpoint starts returning 200 again, the probe
-/// should drive it through Degraded and eventually back to Healthy, at which
-/// point the dispatcher routes new keys to it again.
-#[tokio::test]
-async fn test_worker_recovery_detected_by_probe() {
- let w0 = FakeWorker::start().await;
- let w1 = FakeWorker::start().await;
-
- // w1 starts unhealthy so the probe detects it failing from the beginning.
- w1.set_healthy(false);
-
- let urls = vec![w0.url.clone(), w1.url.clone()];
- let registry = Arc::new(WorkerRegistry::new(&urls, fast_config()));
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- let token = CancellationToken::new();
- Arc::clone(&registry).start_probing(token.clone());
-
- wait_for_state(&registry, &w1.url, WorkerState::Unhealthy).await;
-
- // Recover w1.
- w1.set_healthy(true);
-
- // Wait until w1 leaves Unhealthy (Degraded or Healthy).
- wait_for_not_unhealthy(&registry, &w1.url).await;
-
- // Assign a large set of fresh keys. Both workers should get some, since w1
- // is now at least Degraded (Healthy | Degraded both receive assignments).
- let keys: Vec<_> = (0..40).map(|i| make_msg(&format!("t:user-{i}"))).collect();
- let sub_batches = dispatcher.assign("b", keys);
-
- let workers_used: std::collections::HashSet<String> =
- sub_batches.iter().map(|b| b.worker.to_string()).collect();
- assert!(
- workers_used.contains(&w1.url),
- "w1 should receive new keys after recovery; workers used: {workers_used:?}"
- );
-
- token.cancel();
-}
-
-/// With 3 workers, one dying mid-flight:
-/// - Keys pinned to the dead worker are evicted and re-routed to the survivors.
-/// - No new keys reach the dead worker.
-#[tokio::test]
-async fn test_three_workers_one_dies_and_load_rebalances() {
- let workers = [
- FakeWorker::start().await,
- FakeWorker::start().await,
- FakeWorker::start().await,
- ];
-
- let urls: Vec<String> = workers.iter().map(|w| w.url.clone()).collect();
- let registry = Arc::new(WorkerRegistry::new(&urls, fast_config()));
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- let token = CancellationToken::new();
- Arc::clone(&registry).start_probing(token.clone());
-
- let first = dispatcher.assign(
- "b",
- vec![
- make_msg("t:key-a"),
- make_msg("t:key-b"),
- make_msg("t:key-c"),
- ],
- );
-
- // Kill the worker that holds the first sub-batch and wait for dead
- // declaration (first batch stays open throughout).
- let dead_sub = &first[0];
- let dead = workers
- .iter()
- .find(|w| w.url == dead_sub.worker.as_ref())
- .unwrap();
- let dead_key = dead_sub.routing_keys[0].clone();
- dead.set_healthy(false);
- wait_for_state(&registry, &dead.url, WorkerState::Unhealthy).await;
- wait_for_dead(&registry, &dead.url).await;
-
- // Fresh keys must only land on the survivors.
- let fresh = dispatcher.assign(
- "b",
- vec![
- make_msg("t:new-1"),
- make_msg("t:new-2"),
- make_msg("t:new-3"),
- ],
- );
- assert!(
- fresh.iter().all(|b| b.worker.as_ref() != dead.url),
- "fresh keys must not route to the dead worker; workers used: {:?}",
- fresh
- .iter()
- .map(|b| b.worker.to_string())
- .collect::<Vec<_>>()
- );
-
- // Resolve the dead worker's in-flight sub-batch (max_in_flight=1: the
- // prior batch completes before the next assigns), evicting its now
- // zero-ref pins.
- dispatcher.on_sub_batch_resolved(
- &dead_sub.worker,
- dead_sub.messages.len(),
- &dead_sub.routing_keys,
- false,
- false,
- );
-
- // The key that was pinned to the dead worker must re-route to a survivor.
- let rerouted = dispatcher.assign("b", vec![make_msg(&dead_key)]);
- assert_eq!(
- rerouted.len(),
- 1,
- "rerouted key must produce exactly one sub-batch"
- );
- assert_ne!(
- rerouted[0].worker.as_ref(),
- dead.url,
- "key previously pinned to the dead worker must reroute to a live worker"
- );
-
- token.cancel();
-}
-
-/// When every worker is Unhealthy, assign must return an empty vec — no
-/// messages can be routed and nothing must be dropped silently.
-#[tokio::test]
-async fn test_all_workers_unhealthy_returns_empty() {
- let w0 = FakeWorker::start().await;
- let w1 = FakeWorker::start().await;
-
- w0.set_healthy(false);
- w1.set_healthy(false);
-
- let urls = vec![w0.url.clone(), w1.url.clone()];
- let registry = Arc::new(WorkerRegistry::new(&urls, fast_config()));
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- let token = CancellationToken::new();
- Arc::clone(&registry).start_probing(token.clone());
-
- wait_for_state(&registry, &w0.url, WorkerState::Unhealthy).await;
- wait_for_state(&registry, &w1.url, WorkerState::Unhealthy).await;
-
- let sub_batches = dispatcher.assign("b", vec![make_msg("t:user-1")]);
- assert!(
- sub_batches.is_empty(),
- "expected empty assignment when all workers are unhealthy"
- );
-
- token.cancel();
-}
-
-/// Graceful drain end-to-end at the dispatcher level: a draining worker keeps
-/// its in-flight pin (new messages defer rather than reroute or pile onto it),
-/// the liveness probe does not evict it while draining, and once its in-flight
-/// resolves it becomes reapable and the deferred key reroutes to a survivor.
-#[tokio::test]
-async fn test_draining_worker_defers_then_flushes_to_survivor() {
- let w0 = FakeWorker::start().await;
- let w1 = FakeWorker::start().await;
-
- let urls = vec![w0.url.clone(), w1.url.clone()];
- let registry = Arc::new(WorkerRegistry::new(&urls, fast_config()));
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
-
- let token = CancellationToken::new();
- Arc::clone(&registry).start_probing(token.clone());
-
- // Pin user-1 to whichever worker gets it; hold the sub-batch open.
- let b1 = dispatcher.assign("batch-1", vec![make_msg("t:user-1")]);
- let pinned = b1[0].worker.clone();
- let other = if pinned.as_ref() == w0.url {
- w1.url.clone()
- } else {
- w0.url.clone()
- };
-
- // Begin draining (as an EndpointSlice removal would).
- registry.start_draining(&pinned);
-
- // New messages for user-1 defer — not sent to the drainer, not yet rerouted.
- let b2 = dispatcher.assign("batch-2", vec![make_msg("t:user-1")]);
- assert!(
- b2.is_empty(),
- "must defer while the pinned worker is draining"
- );
- assert!(dispatcher.has_deferred("batch-2"));
-
- // The drainer is still alive and healthy — the probe must not evict it while
- // it finishes in-flight work (its /_ready still returns 200 here).
- tokio::time::sleep(Duration::from_millis(120)).await;
- assert!(
- !registry.is_dead(&pinned),
- "drainer must not be probed to death"
- );
- assert!(
- registry.reapable_workers().is_empty(),
- "not reapable while in-flight remains"
- );
-
- // Resolve batch-1: the drainer finishes and becomes reapable.
- dispatcher.on_sub_batch_resolved(
- &pinned,
- b1[0].messages.len(),
- &b1[0].routing_keys,
- false,
- false,
- );
- assert_eq!(registry.reapable_workers(), vec![pinned.clone()]);
-
- // Flushing batch-2 reroutes the deferred key onto the surviving worker.
- let flushed = dispatcher.flush_deferred("batch-2");
- assert_eq!(flushed.len(), 1);
- assert_eq!(flushed[0].worker.as_ref(), other);
- assert!(!dispatcher.has_deferred("batch-2"));
-
- token.cancel();
-}
-
-#[tokio::test(flavor = "current_thread")]
-async fn purging_a_just_submitted_key_table_batch_is_not_fatal() {
- let registry = Arc::new(WorkerRegistry::new(&[], fast_config()));
- let dispatcher = Arc::new(Dispatcher::with_strategy(registry, RoutingStrategy::P2c));
- let transport = Arc::new(GrpcTransport::new(
- GrpcPort::OffsetFromHttp(0),
- 1,
- Duration::from_secs(30),
- ));
- let (batcher, mut outputs) = key_table_batcher(
- &dispatcher,
- transport,
- Duration::from_secs(10),
- Duration::from_millis(20),
- );
-
- let mut accumulator = Accumulator::default();
- accumulator.push(Partition(0), make_msg("a").into());
- batcher.submit(accumulator);
- // No await between submit and purge: the batcher task receives both
- // before it runs, and discards the submission when it applies the purge.
- batcher.revoker().purge_revoked(&[("test".to_string(), 0)]);
-
- match tokio::time::timeout(Duration::from_millis(100), outputs.errors.recv()).await {
- Err(_) => {}
- Ok(Some(error)) => panic!("revoked work must not report a routing failure: {error}"),
- Ok(None) => panic!("batcher error channel closed unexpectedly"),
- }
-}
-
-#[tokio::test]
-async fn dropping_an_idle_key_table_batcher_closes_its_outputs() {
- let registry = Arc::new(WorkerRegistry::new(&[], fast_config()));
- let dispatcher = Arc::new(Dispatcher::with_strategy(registry, RoutingStrategy::P2c));
- let transport = Arc::new(GrpcTransport::new(
- GrpcPort::OffsetFromHttp(0),
- 1,
- Duration::from_secs(30),
- ));
- let (batcher, mut outputs) = key_table_batcher(
- &dispatcher,
- transport,
- Duration::from_secs(10),
- Duration::from_millis(20),
- );
-
- drop(batcher);
-
- let completion = tokio::time::timeout(Duration::from_millis(100), outputs.completions.recv())
- .await
- .expect("dropping the batcher must not leave an idle retry task retaining its senders");
- assert!(
- completion.is_none(),
- "an idle dropped batcher cannot produce a completion"
- );
- assert!(
- outputs.errors.recv().await.is_none(),
- "all output senders close with the dropped batcher"
- );
-}
diff --git a/rust/ingestion-consumer/tests/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rs
index ce56aec8d517..7d9975c759e5 100644
--- a/rust/ingestion-consumer/tests/e2e_integration_test.rs
+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs
@@ -5,7 +5,7 @@
mod common;
-use std::collections::{HashMap, HashSet};
+use std::collections::HashSet;
use std::num::{NonZeroU32, NonZeroUsize};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
@@ -31,15 +31,13 @@ use uuid::Uuid;
use common_kafka_consumer::{TopicOffsetLedger, TopicPartition};
use ingestion_consumer::batcher::packer::PackTargets;
use ingestion_consumer::batcher::state_machine::RequestBudget;
+use ingestion_consumer::batcher::worker_pool::WorkerPoolSource;
use ingestion_consumer::batcher::BatcherObserver;
use ingestion_consumer::consumer::{IngestionConsumer, IngestionConsumerOptions};
use ingestion_consumer::discovery::reconcile_membership;
-use ingestion_consumer::dispatcher::Dispatcher;
use ingestion_consumer::grpc_transport::{GrpcPort, GrpcTransport};
use ingestion_consumer::order_sentinel::SentinelContext;
use ingestion_consumer::routing::RoutingStrategy;
-use ingestion_consumer::scheduler::SchedulerKind;
-use ingestion_consumer::types::SerializedKafkaMessage;
use ingestion_consumer::worker_registry::{
WorkerId, WorkerRegistry, WorkerRegistryConfig, WorkerState,
};
@@ -599,7 +597,6 @@ impl WorkerIngestService for FakeWorkerGrpc {
// ── Test harness ───────────────────────────────────────────────────────────
struct Harness {
- scheduler: SchedulerKind,
pub workers: Vec<FakeWorker>,
pub registry: Arc<WorkerRegistry>,
pub observer: BatcherObserver,
@@ -697,7 +694,6 @@ fn spawn_reaper(
impl Harness {
async fn start(
- kind: SchedulerKind,
topic: &str,
partitions: i32,
worker_count: usize,
@@ -706,7 +702,6 @@ impl Harness {
registry_config: WorkerRegistryConfig,
) -> Self {
Self::start_inner(
- kind,
topic,
partitions,
worker_count,
@@ -725,7 +720,6 @@ impl Harness {
/// request except an escalated key's resend.
async fn start_budgeted(topic: &str, partitions: i32) -> Self {
Self::start_inner(
- SchedulerKind::KeyTable,
topic,
partitions,
1,
@@ -754,7 +748,6 @@ impl Harness {
#[allow(clippy::too_many_arguments)]
async fn start_with_pack_targets(
- kind: SchedulerKind,
topic: &str,
partitions: i32,
worker_count: usize,
@@ -764,7 +757,6 @@ impl Harness {
pack_targets: PackTargets,
) -> Self {
Self::start_inner(
- kind,
topic,
partitions,
worker_count,
@@ -780,7 +772,6 @@ impl Harness {
}
async fn start_with_liveness(
- kind: SchedulerKind,
topic: &str,
worker_count: usize,
deferred_flush_timeout: Duration,
@@ -788,7 +779,6 @@ impl Harness {
stall_threshold: u32,
) -> Self {
Self::start_inner(
- kind,
topic,
1,
worker_count,
@@ -808,9 +798,8 @@ impl Harness {
/// Like `start`, but bounds batch collection by payload bytes as well as
/// count (`CONSUMER_BATCH_SIZE_KB`). Single worker and partition, so each
/// sub-batch is one whole Kafka batch.
- async fn start_byte_capped(kind: SchedulerKind, topic: &str, batch_size_bytes: usize) -> Self {
+ async fn start_byte_capped(topic: &str, batch_size_bytes: usize) -> Self {
Self::start_inner(
- kind,
topic,
1,
1,
@@ -827,7 +816,6 @@ impl Harness {
#[allow(clippy::too_many_arguments)]
async fn start_inner(
- kind: SchedulerKind,
topic: &str,
partitions: i32,
worker_count: usize,
@@ -852,10 +840,7 @@ impl Harness {
let probe_token = CancellationToken::new();
Arc::clone(&registry).start_probing(probe_token.clone());
- let dispatcher = Arc::new(Dispatcher::with_strategy(
- Arc::clone(&registry),
- RoutingStrategy::default(),
- ));
+ let pool_source = WorkerPoolSource::new(Arc::clone(&registry), RoutingStrategy::default());
let registry_for_test = Arc::clone(&registry);
let transport = Arc::new(test_transport());
@@ -873,10 +858,8 @@ impl Harness {
let kafka_consumer = make_kafka_consumer_with_context(topic, &group_id, None, context);
let (batcher, outputs) = common::batcher(
- kind,
- &dispatcher,
+ pool_source,
Arc::clone(&transport),
- handle.clone(),
deferred_flush_timeout,
Duration::from_millis(200),
pack_targets,
@@ -912,7 +895,6 @@ impl Harness {
tokio::time::sleep(Duration::from_millis(300)).await;
Self {
- scheduler: kind,
workers,
registry: registry_for_test,
observer,
@@ -939,7 +921,7 @@ impl Harness {
}
/// Start a fresh consumer stack — a new Kafka client in the same consumer
- /// group, plus new registry/dispatcher/transport — against the same topic
+ /// group, plus new registry/batcher/transport — against the same topic
/// and workers, modeling a pod restart. Only the FakeWorkers survive,
/// mirroring production where worker pods outlive a consumer pod.
async fn restart_consumer(&mut self, registry_config: WorkerRegistryConfig) {
@@ -947,10 +929,7 @@ impl Harness {
let registry = Arc::new(WorkerRegistry::new(&worker_urls, registry_config));
Arc::clone(&registry).start_probing(self._probe_token.clone());
- let dispatcher = Arc::new(Dispatcher::with_strategy(
- Arc::clone(&registry),
- RoutingStrategy::default(),
- ));
+ let pool_source = WorkerPoolSource::new(Arc::clone(&registry), RoutingStrategy::default());
let transport = Arc::new(test_transport());
let mut manager = Manager::builder("e2e-test-restarted")
@@ -964,10 +943,8 @@ impl Harness {
let kafka_consumer =
make_kafka_consumer_with_context(&self.topic, &self.group_id, None, context);
let (batcher, outputs) = common::batcher(
- self.scheduler,
- &dispatcher,
+ pool_source,
Arc::clone(&transport),
- handle.clone(),
self.deferred_flush_timeout,
Duration::from_millis(200),
self.pack_targets,
@@ -1061,19 +1038,14 @@ impl Harness {
let registry = Arc::new(WorkerRegistry::new(&worker_urls, fast_registry_config()));
let probe = CancellationToken::new();
Arc::clone(&registry).start_probing(probe.clone());
- let dispatcher = Arc::new(Dispatcher::with_strategy(
- Arc::clone(&registry),
- RoutingStrategy::default(),
- ));
+ let pool_source = WorkerPoolSource::new(Arc::clone(&registry), RoutingStrategy::default());
let transport = Arc::new(test_transport());
let mut manager = Manager::builder("e2e-c2").with_trap_signals(false).build();
let handle = manager.register("consumer", ComponentOptions::new());
let shutdown = handle.shutdown_token();
let (batcher, outputs) = common::batcher(
- self.scheduler,
- &dispatcher,
+ pool_source,
Arc::clone(&transport),
- handle.clone(),
self.deferred_flush_timeout,
Duration::from_millis(200),
self.pack_targets,
@@ -1168,27 +1140,17 @@ fn sole_arrived_worker(harness: &Harness) -> usize {
/// Kafka partition order is preserved per distinct_id on each worker.
///
-/// With concurrent_batches=1 (sequential processing), pins are evicted after
-/// each batch resolves, so the same distinct_id can be assigned to different
-/// workers across batches. The guarantee is narrower: wherever a distinct_id's
-/// messages land, they arrive in Kafka sequence order on that worker.
-///
-/// Cross-batch stickiness (all distinct_id events always to the same pod) is
-/// the responsibility of the concurrent-batches layer: when concurrent_batches>1,
-/// the Dispatcher's ref-counted pins keep the assignment alive across overlapping
-/// in-flight batches. That invariant is tested in the concurrent-batches suite.
+/// A key is placed on a worker as each of its requests is sent, so the same
+/// distinct_id can land on different workers across requests. The guarantee
+/// is narrower: wherever a distinct_id's messages land, they arrive in Kafka
+/// sequence order on that worker.
#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash, common::PRODUCTION_PACK_TARGETS)]
-#[case::key_table(SchedulerKind::KeyTable, common::PRODUCTION_PACK_TARGETS)]
-#[case::key_table_one_message(SchedulerKind::KeyTable, common::ONE_MESSAGE_PER_REQUEST)]
+#[case::production_targets(common::PRODUCTION_PACK_TARGETS)]
+#[case::one_message_per_request(common::ONE_MESSAGE_PER_REQUEST)]
#[tokio::test]
-async fn messages_per_distinct_id_arrive_in_order(
- #[case] kind: SchedulerKind,
- #[case] pack_targets: PackTargets,
-) {
+async fn messages_per_distinct_id_arrive_in_order(#[case] pack_targets: PackTargets) {
let topic = format!("e2e-ordering-{}", Uuid::new_v4());
let harness = Harness::start_with_pack_targets(
- kind,
&topic,
3,
2,
@@ -1491,13 +1453,10 @@ async fn a_message_that_never_fits_the_budget_lands_without_one() {
/// (the second crosses it). The count cap alone cannot express that, which is
/// the regression: a lane whose events are large gets the memory of a full
/// count batch no matter how the count is tuned.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn byte_bound_caps_batches_below_the_count_bound(#[case] kind: SchedulerKind) {
+async fn byte_bound_caps_batches_below_the_count_bound() {
let topic = format!("e2e-bytecap-{}", Uuid::new_v4());
- let harness = Harness::start_byte_capped(kind, &topic, 4096).await;
+ let harness = Harness::start_byte_capped(&topic, 4096).await;
let producer = make_producer();
let payload = vec![b'x'; 2048];
@@ -1537,13 +1496,10 @@ async fn byte_bound_caps_batches_below_the_count_bound(#[case] kind: SchedulerKi
/// always admitted. Checking after would let one oversized payload produce an
/// empty batch and wedge its partition — the message can never be skipped, and
/// no smaller batch can ever contain it.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn message_larger_than_byte_bound_is_still_delivered(#[case] kind: SchedulerKind) {
+async fn message_larger_than_byte_bound_is_still_delivered() {
let topic = format!("e2e-bytecap-oversize-{}", Uuid::new_v4());
- let harness = Harness::start_byte_capped(kind, &topic, 4096).await;
+ let harness = Harness::start_byte_capped(&topic, 4096).await;
let producer = make_producer();
produce_raw(
@@ -1569,14 +1525,10 @@ async fn message_larger_than_byte_bound_is_still_delivered(#[case] kind: Schedul
/// When a worker becomes unhealthy, its sticky pins are dropped and subsequent
/// messages for the same key are rerouted to a healthy worker.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn failing_worker_triggers_rerouting(#[case] kind: SchedulerKind) {
+async fn failing_worker_triggers_rerouting() {
let topic = format!("e2e-failover-{}", Uuid::new_v4());
let harness = Harness::start(
- kind,
&topic,
2,
2,
@@ -1632,14 +1584,10 @@ async fn failing_worker_triggers_rerouting(#[case] kind: SchedulerKind) {
/// A worker whose sends fail (5xx through every retry) is a fault for passive
/// health, not backpressure: the failed sends must degrade it even though the
/// readiness probe keeps passing.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn failed_sends_degrade_passive_health(#[case] kind: SchedulerKind) {
+async fn failed_sends_degrade_passive_health() {
let topic = format!("e2e-passive-fault-{}", Uuid::new_v4());
let harness = Harness::start(
- kind,
&topic,
1,
1,
@@ -1670,14 +1618,10 @@ async fn failed_sends_degrade_passive_health(#[case] kind: SchedulerKind) {
/// subsequent messages for the same distinct_id reroute in order to a surviving
/// worker. The drainer stays alive throughout (it is not failed), so the probe
/// must not declare it dead.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn draining_worker_takes_no_new_work_and_reroutes_in_order(#[case] kind: SchedulerKind) {
+async fn draining_worker_takes_no_new_work_and_reroutes_in_order() {
let topic = format!("e2e-drain-{}", Uuid::new_v4());
let harness = Harness::start(
- kind,
&topic,
2,
2,
@@ -1762,14 +1706,10 @@ async fn draining_worker_takes_no_new_work_and_reroutes_in_order(#[case] kind: S
// ── Failure-triggered defer + flush at the consumer level ────────────────────
//
-// These drive the consumer's defer→stash→flush loop end-to-end through real
-// Kafka. A "blocking" worker holds a batch in flight so a test can flip it to a
-// failure before it responds; the failed send then exercises `defer_failed` and
-// the `complete_oldest_batch` flush loop. (The drain-triggered defer needs a
-// drain signal injected between two overlapping batch assigns, which isn't
-// reachable from a black-box test; that path is covered by the dispatcher unit
-// and dispatcher_integration tests, which drive `assign`/`flush_deferred`
-// directly.)
+// These drive the batcher's requeue-and-replay loop end-to-end through real
+// Kafka. A "blocking" worker holds a request in flight so a test can flip it
+// to a failure before it responds; the failed send then exercises the
+// batcher's requeue and its retry wakeup.
/// Whether `url` is currently routable (healthy or degraded) per the registry.
fn in_pool(harness: &Harness, url: &str) -> bool {
@@ -1780,38 +1720,12 @@ fn in_pool(harness: &Harness, url: &str) -> bool {
.any(|w| w.as_ref() == url)
}
-/// Whether `url` is routable per a bare registry (no Harness).
-fn registry_has(registry: &WorkerRegistry, url: &str) -> bool {
- registry.healthy_workers().iter().any(|w| w.as_ref() == url)
-}
-
-/// Build a dispatcher-level message for a distinct_id carrying `seq` in its body,
-/// so a FakeWorker records it the same way it records produced Kafka records.
-fn worker_msg(distinct_id: &str, seq: usize) -> SerializedKafkaMessage {
- let mut headers = HashMap::new();
- headers.insert("token".to_string(), "tok".to_string());
- headers.insert("distinct_id".to_string(), distinct_id.to_string());
- SerializedKafkaMessage {
- topic: "t".into(),
- partition: 0,
- offset: seq as i64,
- timestamp: 0,
- key: Some(format!("tok:{distinct_id}")),
- value: Some(format!(r#"{{"seq":{seq}}}"#)),
- headers,
- }
-}
-
/// A send that fails mid-flight is deferred and replayed, in order, to the
/// surviving worker — no loss, no duplication, no reordering.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn send_failure_mid_flight_replays_to_survivor_in_order(#[case] kind: SchedulerKind) {
+async fn send_failure_mid_flight_replays_to_survivor_in_order() {
let topic = format!("e2e-replay-single-{}", Uuid::new_v4());
let harness = Harness::start(
- kind,
&topic,
1,
2,
@@ -1864,11 +1778,8 @@ async fn send_failure_mid_flight_replays_to_survivor_in_order(#[case] kind: Sche
/// In a batch split across two workers, only the failed sub-batch is deferred
/// and replayed; the successful one is not re-sent. Everything ends up on the
/// survivor, in order, with the failed worker having recorded nothing.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn partial_send_failure_replays_only_the_failed_subbatch(#[case] kind: SchedulerKind) {
+async fn partial_send_failure_replays_only_the_failed_subbatch() {
let topic = format!("e2e-replay-partial-{}", Uuid::new_v4());
// Each four-message key fills its own request, so there are two sub-batches.
let one_key_of_four_per_request = PackTargets {
@@ -1877,7 +1788,6 @@ async fn partial_send_failure_replays_only_the_failed_subbatch(#[case] kind: Sch
latency_budget: Duration::ZERO,
};
let harness = Harness::start_with_pack_targets(
- kind,
&topic,
1,
2,
@@ -1940,22 +1850,13 @@ async fn partial_send_failure_replays_only_the_failed_subbatch(#[case] kind: Sch
/// worker returns, then drains in order. Waiting for a worker, and waiting on
/// a slow one once found, both outlast the liveness deadline here: neither is
/// a stall, so the lifecycle monitor must not shut the consumer down.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn deferred_flush_retries_until_a_worker_recovers(#[case] kind: SchedulerKind) {
+async fn deferred_flush_retries_until_a_worker_recovers() {
let topic = format!("e2e-replay-wait-{}", Uuid::new_v4());
let liveness_deadline = Duration::from_millis(1500);
- let harness = Harness::start_with_liveness(
- kind,
- &topic,
- 2,
- Duration::from_secs(60),
- liveness_deadline,
- 2,
- )
- .await;
+ let harness =
+ Harness::start_with_liveness(&topic, 2, Duration::from_secs(60), liveness_deadline, 2)
+ .await;
let producer = make_producer();
// Take worker 1 out of the pool so the batch routes to worker 0.
@@ -1994,16 +1895,16 @@ async fn deferred_flush_retries_until_a_worker_recovers(#[case] kind: SchedulerK
wait_until(
Duration::from_secs(10),
"the failed send to be deferred",
- || harness.observer.held_messages() > 0,
+ || harness.observer.pending_messages() > 0,
)
.await;
// The deferred work is held steady — the flush loop is backing off, not
// dropping anything — for as long as no worker is available.
- let held = harness.observer.held_messages();
+ let held = harness.observer.pending_messages();
tokio::time::sleep(liveness_deadline * 4).await;
assert_eq!(
- harness.observer.held_messages(),
+ harness.observer.pending_messages(),
held,
"deferred work must be held steady while no worker is available"
);
@@ -2048,18 +1949,13 @@ async fn deferred_flush_retries_until_a_worker_recovers(#[case] kind: SchedulerK
/// With no worker ever coming back, the batch must still fail: the flush
/// loop's own `deferred_flush_timeout` ends it, not a liveness stall, so the
/// exit lands at the flush timeout rather than at the (shorter) stall window.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn no_worker_exit_comes_from_the_flush_timeout_not_a_liveness_stall(
- #[case] kind: SchedulerKind,
-) {
+async fn no_worker_exit_comes_from_the_flush_timeout_not_a_liveness_stall() {
let topic = format!("e2e-flush-timeout-liveness-{}", Uuid::new_v4());
let flush_timeout = Duration::from_secs(4);
let liveness_deadline = Duration::from_millis(1500);
let mut harness =
- Harness::start_with_liveness(kind, &topic, 2, flush_timeout, liveness_deadline, 2).await;
+ Harness::start_with_liveness(&topic, 2, flush_timeout, liveness_deadline, 2).await;
let producer = make_producer();
harness.workers[1].healthy.store(false, Ordering::SeqCst);
@@ -2084,7 +1980,7 @@ async fn no_worker_exit_comes_from_the_flush_timeout_not_a_liveness_stall(
wait_until(
Duration::from_secs(10),
"the failed send to be deferred",
- || harness.observer.held_messages() > 0,
+ || harness.observer.pending_messages() > 0,
)
.await;
let deferred_at = tokio::time::Instant::now();
@@ -2111,16 +2007,13 @@ async fn no_worker_exit_comes_from_the_flush_timeout_not_a_liveness_stall(
/// liveness deadline and the flush timeout: every landing resets the flush
/// deadline, and the wait in between keeps the heartbeat going. Two keys land
/// in two flush rounds, the first only after the original deadline has passed.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn slow_deferred_drain_with_progress_outlasts_the_flush_timeout(#[case] kind: SchedulerKind) {
+async fn slow_deferred_drain_with_progress_outlasts_the_flush_timeout() {
let topic = format!("e2e-slow-drain-{}", Uuid::new_v4());
let flush_timeout = Duration::from_secs(3);
let liveness_deadline = Duration::from_millis(1500);
let harness =
- Harness::start_with_liveness(kind, &topic, 3, flush_timeout, liveness_deadline, 2).await;
+ Harness::start_with_liveness(&topic, 3, flush_timeout, liveness_deadline, 2).await;
let producer = make_producer();
// Workers 1 and 2 out, so both keys route to worker 0 together.
@@ -2174,7 +2067,7 @@ async fn slow_deferred_drain_with_progress_outlasts_the_flush_timeout(#[case] ki
harness.workers[2].ingest_ok.store(false, Ordering::SeqCst);
drop(guard2);
wait_until(Duration::from_secs(10), "worker 2 to answer", || {
- harness.workers[2].arrived_count() == 1 && harness.observer.held_messages() > 0
+ harness.workers[2].arrived_count() == 1 && harness.observer.pending_messages() > 0
})
.await;
let guard2 = harness.workers[2].block().await;
@@ -2236,17 +2129,12 @@ async fn slow_deferred_drain_with_progress_outlasts_the_flush_timeout(#[case] ki
/// A failed multi-key sub-batch replays every key, each in its own Kafka order,
/// once a worker is available.
#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash, common::PRODUCTION_PACK_TARGETS)]
-#[case::key_table(SchedulerKind::KeyTable, common::PRODUCTION_PACK_TARGETS)]
-#[case::key_table_one_message(SchedulerKind::KeyTable, common::ONE_MESSAGE_PER_REQUEST)]
+#[case::production_targets(common::PRODUCTION_PACK_TARGETS)]
+#[case::one_message_per_request(common::ONE_MESSAGE_PER_REQUEST)]
#[tokio::test]
-async fn multi_key_send_failure_replays_every_key_in_order(
- #[case] kind: SchedulerKind,
- #[case] pack_targets: PackTargets,
-) {
+async fn multi_key_send_failure_replays_every_key_in_order(#[case] pack_targets: PackTargets) {
let topic = format!("e2e-replay-multikey-{}", Uuid::new_v4());
let harness = Harness::start_with_pack_targets(
- kind,
&topic,
3,
2,
@@ -2309,14 +2197,10 @@ async fn multi_key_send_failure_replays_every_key_in_order(
/// A replay whose target also fails is re-deferred and retried until it lands —
/// cascading failures during flush never lose or reorder the deferred work.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn flush_target_failure_re_defers_then_replays_in_order(#[case] kind: SchedulerKind) {
+async fn flush_target_failure_re_defers_then_replays_in_order() {
let topic = format!("e2e-replay-cascade-{}", Uuid::new_v4());
let harness = Harness::start(
- kind,
&topic,
1,
2,
@@ -2375,7 +2259,7 @@ async fn flush_target_failure_re_defers_then_replays_in_order(#[case] kind: Sche
wait_until(
Duration::from_secs(10),
"re-deferred work to be held after the replay target also fails",
- || harness.observer.held_messages() > 0,
+ || harness.observer.pending_messages() > 0,
)
.await;
@@ -2399,99 +2283,16 @@ async fn flush_target_failure_re_defers_then_replays_in_order(#[case] kind: Sche
harness.stop().await;
}
-/// Drain-triggered defer through the dispatcher + real worker stream transport
-/// — the path the consumer drives. The Kafka poll loop can't inject a drain between two
-/// overlapping batch assigns deterministically (it assigns available batches
-/// back-to-back and parks in `complete_oldest_batch` the moment data dries up),
-/// so this models the consumer's exact sequence — assign, drain, assign (defer),
-/// resolve, flush — and delivers over a real stream, asserting the deferred key
-/// lands on the survivor in order.
-#[tokio::test]
-async fn drain_defer_flush_delivers_to_survivor_over_stream() {
- let w0 = FakeWorker::start().await;
- let w1 = FakeWorker::start().await;
- let urls = vec![w0.url.clone(), w1.url.clone()];
- let workers = [w0, w1];
-
- let registry = Arc::new(WorkerRegistry::new(&urls, fast_registry_config()));
- let probe_token = CancellationToken::new();
- Arc::clone(&registry).start_probing(probe_token.clone());
- let dispatcher = Dispatcher::new(Arc::clone(&registry));
- let transport = test_transport();
-
- // batch-1: user-1 pins to a worker. Send it for real but DON'T resolve, so it
- // is genuinely in flight on that worker.
- let b1 = dispatcher.assign("batch-1", vec![worker_msg("user-1", 0)]);
- assert_eq!(b1.len(), 1);
- let pinned_url = b1[0].worker.to_string();
- let pinned_idx = workers.iter().position(|w| w.url == pinned_url).unwrap();
- let survivor_idx = 1 - pinned_idx;
- transport
- .begin_send(&pinned_url, "batch-1", b1[0].messages.clone(), false)
- .wait()
- .await
- .expect("batch-1 send");
-
- // Drain the pinned worker. The next batch for the key must defer (its worker
- // is draining and still has in-flight work — rerouting now would reorder it).
- registry.start_draining(&pinned_url);
- let b2 = dispatcher.assign("batch-2", vec![worker_msg("user-1", 1)]);
- assert!(b2.is_empty(), "must defer while the pinned worker drains");
- assert!(dispatcher.has_deferred("batch-2"));
-
- // Resolve batch-1 (the drainer finishes its in-flight), then flush batch-2:
- // it re-routes to the survivor.
- dispatcher.on_sub_batch_resolved(
- &b1[0].worker,
- b1[0].messages.len(),
- &b1[0].routing_keys,
- false,
- false,
- );
- let f2 = dispatcher.flush_deferred("batch-2");
- assert_eq!(f2.len(), 1);
- assert_eq!(
- f2[0].worker.to_string(),
- workers[survivor_idx].url,
- "deferred group flushes to the survivor, not the drainer"
- );
- transport
- .begin_send(
- f2[0].worker.as_ref(),
- "batch-2",
- f2[0].messages.clone(),
- false,
- )
- .wait()
- .await
- .expect("batch-2 flush send");
-
- // The drainer kept its in-flight seq 0; the deferred seq 1 landed on the
- // survivor — delivered over a real stream, in order, with nothing lost.
- assert_eq!(workers[pinned_idx].seqs_for("user-1"), vec![0]);
- assert_eq!(workers[survivor_idx].seqs_for("user-1"), vec![1]);
- assert!(
- registry_has(&registry, &workers[survivor_idx].url),
- "survivor stayed routable throughout"
- );
-
- probe_token.cancel();
-}
-
// ── Pool-wide outages, forced reap, crash restart, ambiguous ACKs ────────────
/// A transient full-pool drain — every worker leaving at once, as during a
/// deploy overlap — must not fail the batch: fresh keys that can't route
/// anywhere are held and delivered once a worker returns, instead of being
/// dropped (which fails the batch and restarts the process).
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn full_pool_drain_holds_fresh_keys_until_a_worker_returns(#[case] kind: SchedulerKind) {
+async fn full_pool_drain_holds_fresh_keys_until_a_worker_returns() {
let topic = format!("e2e-full-drain-{}", Uuid::new_v4());
let harness = Harness::start(
- kind,
&topic,
1,
2,
@@ -2538,26 +2339,14 @@ async fn full_pool_drain_holds_fresh_keys_until_a_worker_returns(#[case] kind: S
/// while its request is still live. The reap must not break the in-flight
/// resolve, and the key's deferred messages must re-route to a survivor in
/// order once the held batch completes.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn forced_reap_at_drain_timeout_reroutes_deferred_work(#[case] kind: SchedulerKind) {
+async fn forced_reap_at_drain_timeout_reroutes_deferred_work() {
let topic = format!("e2e-forced-reap-{}", Uuid::new_v4());
let registry_config = WorkerRegistryConfig {
drain_timeout: Duration::from_millis(400),
..fast_registry_config()
};
- let harness = Harness::start(
- kind,
- &topic,
- 1,
- 2,
- 2,
- Duration::from_secs(60),
- registry_config,
- )
- .await;
+ let harness = Harness::start(&topic, 1, 2, 2, Duration::from_secs(60), registry_config).await;
let producer = make_producer();
let mut guards: Vec<Option<tokio::sync::OwnedMutexGuard<()>>> = Vec::new();
@@ -2585,7 +2374,7 @@ async fn forced_reap_at_drain_timeout_reroutes_deferred_work(#[case] kind: Sched
produce(&producer, &topic, 0, "tok", "user-1", seq).await;
}
wait_until(Duration::from_secs(10), "batch 2 to defer", || {
- harness.observer.held_messages() > 0
+ harness.observer.pending_messages() > 0
})
.await;
@@ -2632,14 +2421,10 @@ async fn forced_reap_at_drain_timeout_reroutes_deferred_work(#[case] kind: Sched
/// committed must not lose anything: the restarted consumer resumes from the
/// last commit and redelivers. Duplicates are allowed (at-least-once); loss is
/// not.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn consumer_crash_before_commit_redelivers_without_loss(#[case] kind: SchedulerKind) {
+async fn consumer_crash_before_commit_redelivers_without_loss() {
let topic = format!("e2e-restart-{}", Uuid::new_v4());
let mut harness = Harness::start(
- kind,
&topic,
1,
2,
@@ -2693,14 +2478,10 @@ async fn consumer_crash_before_commit_redelivers_without_loss(#[case] kind: Sche
/// The broker-committed offset is the ledger frontier — one past everything
/// the workers accepted — and a restart resumes from it with no loss and no
/// redelivery.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn the_committed_offset_is_the_ledger_frontier(#[case] kind: SchedulerKind) {
+async fn the_committed_offset_is_the_ledger_frontier() {
let topic = format!("e2e-ledger-commit-{}", Uuid::new_v4());
let mut harness = Harness::start(
- kind,
&topic,
1,
1,
@@ -2750,14 +2531,10 @@ async fn the_committed_offset_is_the_ledger_frontier(#[case] kind: SchedulerKind
/// from a failed send, so the consumer replays the batch: duplicates are the
/// accepted cost of at-least-once, loss never is, and the replay lands behind
/// the original delivery.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn lost_ack_after_processing_replays_without_loss(#[case] kind: SchedulerKind) {
+async fn lost_ack_after_processing_replays_without_loss() {
let topic = format!("e2e-lost-ack-{}", Uuid::new_v4());
let harness = Harness::start(
- kind,
&topic,
1,
2,
@@ -2817,14 +2594,10 @@ async fn lost_ack_after_processing_replays_without_loss(#[case] kind: SchedulerK
/// committed, redelivered after restart) rather than spinning forever. Until a
/// DLQ path exists, a poison batch crash-loops the process by design; this
/// pins the "safe" half of that trade-off.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn poison_batch_fails_safely_without_committing(#[case] kind: SchedulerKind) {
+async fn poison_batch_fails_safely_without_committing() {
let topic = format!("e2e-poison-{}", Uuid::new_v4());
let mut harness = Harness::start(
- kind,
&topic,
1,
2,
@@ -2860,14 +2633,10 @@ async fn poison_batch_fails_safely_without_committing(#[case] kind: SchedulerKin
/// sent violates the transport contract. The consumer must treat the batch as
/// incomplete and fail it — never commit offsets over an under-acknowledged
/// batch, which would silently lose the unaccounted messages.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn partial_acceptance_fails_the_batch_without_commit(#[case] kind: SchedulerKind) {
+async fn partial_acceptance_fails_the_batch_without_commit() {
let topic = format!("e2e-partial-accept-{}", Uuid::new_v4());
let mut harness = Harness::start(
- kind,
&topic,
1,
2,
@@ -2904,14 +2673,10 @@ async fn partial_acceptance_fails_the_batch_without_commit(#[case] kind: Schedul
/// A drainer that crashes mid-drain (its in-flight send fails instead of
/// finishing) must not wedge the drain: both its failed in-flight batch and
/// the work deferred behind it replay to the survivor, in order.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn drainer_crash_mid_drain_replays_to_survivor_in_order(#[case] kind: SchedulerKind) {
+async fn drainer_crash_mid_drain_replays_to_survivor_in_order() {
let topic = format!("e2e-drain-crash-{}", Uuid::new_v4());
let harness = Harness::start(
- kind,
&topic,
1,
2,
@@ -2946,7 +2711,7 @@ async fn drainer_crash_mid_drain_replays_to_survivor_in_order(#[case] kind: Sche
produce(&producer, &topic, 0, "tok", "user-1", seq).await;
}
wait_until(Duration::from_secs(10), "batch 2 to defer", || {
- harness.observer.held_messages() > 0
+ harness.observer.pending_messages() > 0
})
.await;
@@ -2975,17 +2740,14 @@ async fn drainer_crash_mid_drain_replays_to_survivor_in_order(#[case] kind: Sche
/// max_in_flight > 1: everything is stashed while nothing is routable, then
/// drains to the first recovered worker with per-key order intact.
#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash, common::PRODUCTION_PACK_TARGETS)]
-#[case::key_table(SchedulerKind::KeyTable, common::PRODUCTION_PACK_TARGETS)]
-#[case::key_table_one_message(SchedulerKind::KeyTable, common::ONE_MESSAGE_PER_REQUEST)]
+#[case::production_targets(common::PRODUCTION_PACK_TARGETS)]
+#[case::one_message_per_request(common::ONE_MESSAGE_PER_REQUEST)]
#[tokio::test]
async fn full_pool_send_failure_with_multiple_keys_recovers_in_order(
- #[case] kind: SchedulerKind,
#[case] pack_targets: PackTargets,
) {
let topic = format!("e2e-pool-loss-{}", Uuid::new_v4());
let harness = Harness::start_with_pack_targets(
- kind,
&topic,
2,
2,
@@ -3028,7 +2790,7 @@ async fn full_pool_send_failure_with_multiple_keys_recovers_in_order(
wait_until(
Duration::from_secs(10),
"all failed work to be stashed",
- || harness.observer.held_messages() == 8,
+ || harness.observer.pending_messages() == 8,
)
.await;
@@ -3055,14 +2817,10 @@ async fn full_pool_send_failure_with_multiple_keys_recovers_in_order(
/// Messages without token/distinct_id headers route under synthetic
/// per-message keys; a send failure must replay them exactly once, like any
/// other message.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn headerless_messages_survive_send_failure_replay(#[case] kind: SchedulerKind) {
+async fn headerless_messages_survive_send_failure_replay() {
let topic = format!("e2e-headerless-{}", Uuid::new_v4());
let harness = Harness::start(
- kind,
&topic,
1,
2,
@@ -3132,14 +2890,10 @@ async fn headerless_messages_survive_send_failure_replay(#[case] kind: Scheduler
/// A non-UTF-8 payload cannot round-trip the string wire format — its body is
/// nulled in transit today (a known content-loss gap) — but the event itself
/// must still route via its headers and reach a worker, not be dropped.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn non_utf8_payload_is_delivered_not_lost(#[case] kind: SchedulerKind) {
+async fn non_utf8_payload_is_delivered_not_lost() {
let topic = format!("e2e-non-utf8-{}", Uuid::new_v4());
let harness = Harness::start(
- kind,
&topic,
1,
1,
@@ -3185,14 +2939,10 @@ async fn non_utf8_payload_is_delivered_not_lost(#[case] kind: SchedulerKind) {
/// A full fleet replacement, reconciled exactly as EndpointSlice discovery
/// does: the desired set flips to brand-new workers, the old ones drain and
/// are reaped, and traffic keeps flowing — exactly once, in per-key order.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn fleet_redeploy_migrates_work_to_new_workers_without_loss(#[case] kind: SchedulerKind) {
+async fn fleet_redeploy_migrates_work_to_new_workers_without_loss() {
let topic = format!("e2e-redeploy-{}", Uuid::new_v4());
let mut harness = Harness::start(
- kind,
&topic,
2,
2,
@@ -3263,14 +3013,10 @@ async fn fleet_redeploy_migrates_work_to_new_workers_without_loss(#[case] kind:
/// the first while it holds an uncommitted in-flight batch. Redelivery of that
/// batch on the new owner may duplicate (at-least-once) — but nothing may be
/// lost across the handover.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn second_consumer_joining_the_group_preserves_all_messages(#[case] kind: SchedulerKind) {
+async fn second_consumer_joining_the_group_preserves_all_messages() {
let topic = format!("e2e-two-consumers-{}", Uuid::new_v4());
let harness = Harness::start(
- kind,
&topic,
2,
2,
@@ -3335,16 +3081,12 @@ async fn second_consumer_joining_the_group_preserves_all_messages(#[case] kind:
/// partition then starts another generation. A ledger bug here would
/// surface as ledger errors or a wedged loop, so continued delivery after
/// both handovers is the health signal.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn partition_lost_and_regained_keeps_the_consumer_alive(#[case] kind: SchedulerKind) {
+async fn partition_lost_and_regained_keeps_the_consumer_alive() {
let topic = format!("e2e-regain-{}", Uuid::new_v4());
// Room for many in-flight batches, so the first consumer keeps polling
// while its batches are held and the rebalance can land underneath them.
let harness = Harness::start(
- kind,
&topic,
2,
2,
@@ -3456,11 +3198,8 @@ async fn partition_lost_and_regained_keeps_the_consumer_alive(#[case] kind: Sche
/// the same `group.instance.id`, so the broker fences the first. The fenced
/// instance's client is permanently dead — the consumer must exit (so the pod
/// restarts) rather than keep polling it while reporting healthy.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn fenced_static_member_exits_on_fatal_error(#[case] kind: SchedulerKind) {
+async fn fenced_static_member_exits_on_fatal_error() {
let topic = format!("e2e-fenced-{}", Uuid::new_v4());
create_topic(&topic, 1).await;
@@ -3469,10 +3208,7 @@ async fn fenced_static_member_exits_on_fatal_error(#[case] kind: SchedulerKind)
let registry = Arc::new(WorkerRegistry::new(&urls, fast_registry_config()));
let probe = CancellationToken::new();
Arc::clone(&registry).start_probing(probe.clone());
- let dispatcher = Arc::new(Dispatcher::with_strategy(
- Arc::clone(&registry),
- RoutingStrategy::default(),
- ));
+ let pool_source = WorkerPoolSource::new(Arc::clone(&registry), RoutingStrategy::default());
let transport = Arc::new(test_transport());
let mut manager = Manager::builder("e2e-fenced")
.with_trap_signals(false)
@@ -3480,10 +3216,8 @@ async fn fenced_static_member_exits_on_fatal_error(#[case] kind: SchedulerKind)
let handle = manager.register("consumer", ComponentOptions::new());
let group = format!("e2e-{}", Uuid::new_v4());
let (batcher, outputs) = common::batcher(
- kind,
- &dispatcher,
+ pool_source,
Arc::clone(&transport),
- handle.clone(),
Duration::from_secs(60),
Duration::from_millis(200),
common::PRODUCTION_PACK_TARGETS,
@@ -3620,12 +3354,7 @@ fn spawn_churn(
})
}
-async fn run_churn_suite(
- kind: SchedulerKind,
- churn: Churn,
- max_in_flight: usize,
- strict_order: bool,
-) {
+async fn run_churn_suite(churn: Churn, max_in_flight: usize, strict_order: bool) {
let topic = format!("e2e-churn-{churn:?}-mif{max_in_flight}-{}", Uuid::new_v4());
let dids = 8usize;
let per_did = 60usize;
@@ -3633,7 +3362,6 @@ async fn run_churn_suite(
let partitions = 4i32;
let harness = Harness::start(
- kind,
&topic,
partitions,
4,
@@ -3698,70 +3426,48 @@ async fn run_churn_suite(
}
}
- // Once everything is delivered and churn has quiesced, the dispatcher's
- // bookkeeping must drain back to zero. A leak in any of these permanently
- // skews routing (stale pins / phantom load) or strands messages (stash).
+ // Once everything is delivered and churn has quiesced, the batcher's
+ // bookkeeping must drain back to zero. A leak here permanently skews
+ // placement (phantom load) or strands messages (pending forever).
wait_until(
Duration::from_secs(10),
- "dispatcher pins/in-flight/stash to drain to zero after churn",
- || {
- harness.observer.held_messages() == 0
- && harness.observer.pin_count() == 0
- && harness.observer.total_in_flight() == 0
- },
+ "batcher pending/in-flight to drain to zero after churn",
+ || harness.observer.pending_messages() == 0 && harness.observer.total_in_flight() == 0,
)
.await;
harness.stop().await;
}
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn churn_drain_preserves_order_at_max_in_flight_2(#[case] kind: SchedulerKind) {
- run_churn_suite(kind, Churn::Drain, 2, true).await;
+async fn churn_drain_preserves_order_at_max_in_flight_2() {
+ run_churn_suite(Churn::Drain, 2, true).await;
}
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn churn_drain_preserves_order_at_max_in_flight_3(#[case] kind: SchedulerKind) {
- run_churn_suite(kind, Churn::Drain, 3, true).await;
+async fn churn_drain_preserves_order_at_max_in_flight_3() {
+ run_churn_suite(Churn::Drain, 3, true).await;
}
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn churn_send_failures_are_exactly_once_at_max_in_flight_3(#[case] kind: SchedulerKind) {
- run_churn_suite(kind, Churn::Fail, 3, false).await;
+async fn churn_send_failures_are_exactly_once_at_max_in_flight_3() {
+ run_churn_suite(Churn::Fail, 3, false).await;
}
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn churn_mixed_drain_and_failures_are_exactly_once_at_max_in_flight_3(
- #[case] kind: SchedulerKind,
-) {
- run_churn_suite(kind, Churn::Mixed, 3, false).await;
+async fn churn_mixed_drain_and_failures_are_exactly_once_at_max_in_flight_3() {
+ run_churn_suite(Churn::Mixed, 3, false).await;
}
/// A flapping worker — ready (in the pool) but failing every send — must not pin
/// a batch's offsets forever. The flush loop enforces its deadline on the
/// re-defer path too, so the consumer fails the batch within the configured
/// flush timeout instead of spinning. Runs at max_in_flight > 1.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn flapping_worker_does_not_pin_batch_past_flush_timeout(#[case] kind: SchedulerKind) {
+async fn flapping_worker_does_not_pin_batch_past_flush_timeout() {
let topic = format!("e2e-flap-{}", Uuid::new_v4());
// Short flush timeout so the bound is observable quickly; concurrency > 1.
let mut harness = Harness::start(
- kind,
&topic,
1,
2,
@@ -3819,14 +3525,10 @@ async fn flapping_worker_does_not_pin_batch_past_flush_timeout(#[case] kind: Sch
/// A worker that nacks fences its worker stream: the fenced messages fail back into
/// the deferral path with nothing lost, and once the worker leaves the pool
/// the keys re-route to the survivor in order.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn nacking_worker_fences_worker_stream_and_reroutes_in_order(#[case] kind: SchedulerKind) {
+async fn nacking_worker_fences_worker_stream_and_reroutes_in_order() {
let topic = format!("e2e-fence-{}", Uuid::new_v4());
let harness = Harness::start(
- kind,
&topic,
2,
2,
@@ -3875,20 +3577,16 @@ async fn nacking_worker_fences_worker_stream_and_reroutes_in_order(#[case] kind:
/// One routing key arriving on two partitions: a partition-count change
/// leaves a key's backlog on its old partition while new messages land on the
-/// new one. The dispatcher merges such a key into one sub-batch (the pin
-/// table is partition-blind), so the batcher must split the completion back
-/// per partition — mis-attributed coverage would leave the poll uncommitted
+/// new one. The batcher merges such a key into one run (its key table is
+/// partition-blind), so it must split the completion back per partition —
+/// mis-attributed coverage would leave the poll uncommitted
/// and wedge the consumer. Two waves prove commits keep flowing: with
/// max_in_flight = 1, the second wave can only deliver after the first wave's
/// polls completed.
-#[rstest]
-#[case::pin_stash(SchedulerKind::PinStash)]
-#[case::key_table(SchedulerKind::KeyTable)]
#[tokio::test]
-async fn same_key_across_partitions_completes_and_commits(#[case] kind: SchedulerKind) {
+async fn same_key_across_partitions_completes_and_commits() {
let topic = format!("e2e-cross-partition-key-{}", Uuid::new_v4());
let harness = Harness::start(
- kind,
&topic,
2,
1,
diff --git a/rust/ingestion-consumer/tests/grpc_transport_test.rs b/rust/ingestion-consumer/tests/grpc_transport_test.rs
index 6b4627e1bc8e..2b226f8f2095 100644
--- a/rust/ingestion-consumer/tests/grpc_transport_test.rs
+++ b/rust/ingestion-consumer/tests/grpc_transport_test.rs
@@ -3,7 +3,7 @@
//! Each test targets one property the worker stream must hold for per-key ordering:
//! wire order equals enqueue order, acks correlate out of order, and a
//! failure fences everything outstanding (in order, with the messages handed
-//! back) so the dispatcher's deferral path can replay it.
+//! back) so the batcher can requeue and replay it.
mod common;
@@ -13,9 +13,9 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;
-use common::key_table_batcher;
+use common::one_message_batcher;
use common_kafka_consumer::Partition;
-use ingestion_consumer::dispatcher::Dispatcher;
+use ingestion_consumer::batcher::worker_pool::WorkerPoolSource;
use ingestion_consumer::grpc_transport::{GrpcPort, GrpcTransport, SendOptions};
use ingestion_consumer::routing::RoutingStrategy;
use ingestion_consumer::transport::{SendOutcome, TransportError};
@@ -584,7 +584,7 @@ async fn a_failure_fences_a_later_sub_batch_the_worker_already_acked(
// Regression: with more than one un-acked sub-batch, the worker may ack
// seq 2 before seq 1. If seq 2 resolved on its own ack, its caller would
// release its keys and never replay it, while seq 1's later failure
- // stashed only seq 1 — the older messages would replay after the newer
+ // requeued only seq 1 — the older messages would replay after the newer
// ones. A failure must fence the acked-but-unresolved tail too.
let (ack_tx, ack_rx) = mpsc::unbounded_channel();
let mock = start_mock(AckMode::Manual, Some(ack_rx)).await;
@@ -629,11 +629,11 @@ async fn a_failure_fences_a_later_sub_batch_the_worker_already_acked(
}
#[tokio::test]
-async fn sends_enqueued_during_a_fence_are_fenced_until_the_callers_stash() {
- // Regression: a fence resolves its sends before their callers stash the
+async fn sends_enqueued_during_a_fence_are_fenced_until_the_callers_requeue() {
+ // Regression: a fence resolves its sends before their callers requeue the
// messages. In that gap the consumer loop can still enqueue a fenced
// key's next group; if the next stream sent it, it would reach the worker
- // ahead of the stashed older group. The worker stream must keep fencing until
+ // ahead of the requeued older messages. The worker stream must keep fencing until
// every fenced caller drops its guard.
let mock = start_mock(AckMode::NackSeq(1), None).await;
let transport = GrpcTransport::new(
@@ -663,7 +663,7 @@ async fn sends_enqueued_during_a_fence_are_fenced_until_the_callers_stash() {
));
assert_eq!(mock.received.lock().await.len(), 1);
- // Both callers stashed: the worker stream resumes and the next send reaches the
+ // Both callers requeued: the worker stream resumes and the next send reaches the
// worker on a fresh stream.
drop(guard);
drop(second_err);
@@ -823,7 +823,7 @@ async fn a_nack_fences_everything_outstanding_in_order() {
assert_eq!(first_err.messages.len(), 1);
assert_eq!(
first_err.messages[0].offset, 1,
- "messages come back for deferral"
+ "messages come back for the requeue"
);
assert!(matches!(
first_err.error,
@@ -918,7 +918,7 @@ async fn a_worker_that_stops_acking_fences_after_the_watchdog_window() {
.await
.expect("watchdog must fence, not wait forever")
.expect_err("un-acked send fails back to the caller");
- assert_eq!(err.messages.len(), 1, "messages come back for deferral");
+ assert_eq!(err.messages.len(), 1, "messages come back for the requeue");
assert_eq!(err.messages[0].offset, 1);
}
@@ -966,7 +966,7 @@ async fn a_stuck_oldest_sub_batch_fences_even_while_siblings_keep_acking() {
.await
.expect("stuck send must fence on its own deadline, not wait for the feed to stop")
.expect_err("un-acked oldest send fails back to the caller");
- assert_eq!(err.messages.len(), 1, "messages come back for deferral");
+ assert_eq!(err.messages.len(), 1, "messages come back for the requeue");
assert_eq!(err.messages[0].offset, 1);
feeder.abort();
@@ -1007,7 +1007,7 @@ async fn removing_a_worker_fences_its_in_flight_send_with_messages() {
.await
.expect("reaped worker stream must fence, not hang")
.expect_err("reaped worker fences the in-flight send");
- assert_eq!(err.messages.len(), 1, "messages come back for deferral");
+ assert_eq!(err.messages.len(), 1, "messages come back for the requeue");
assert_eq!(err.messages[0].offset, 1);
}
@@ -1029,7 +1029,7 @@ async fn a_busy_status_fences_as_retriable_with_messages() {
.wait()
.await
.expect_err("busy fences the worker stream");
- assert_eq!(err.messages.len(), 1, "messages come back for deferral");
+ assert_eq!(err.messages.len(), 1, "messages come back for the requeue");
assert!(err.error.is_retriable(), "busy is retriable backpressure");
assert!(matches!(err.error, TransportError::WorkerStreamBusy(_)));
}
@@ -1138,7 +1138,7 @@ fn registry_config() -> WorkerRegistryConfig {
}
#[tokio::test]
-async fn key_table_watchdog_bounds_overlapping_busy_retries() {
+async fn the_watchdog_bounds_overlapping_busy_retries() {
let (attempts_tx, mut attempts_rx) = mpsc::unbounded_channel();
let first_addr = start_controlled_busy_worker(0, attempts_tx.clone()).await;
let second_addr = start_controlled_busy_worker(1, attempts_tx).await;
@@ -1147,14 +1147,14 @@ async fn key_table_watchdog_bounds_overlapping_busy_retries() {
format!("http://{second_addr}"),
];
let registry = Arc::new(WorkerRegistry::new(&worker_urls, registry_config()));
- let dispatcher = Arc::new(Dispatcher::with_strategy(registry, RoutingStrategy::P2c));
+ let pool_source = WorkerPoolSource::new(registry, RoutingStrategy::P2c);
let transport = Arc::new(GrpcTransport::new(
GrpcPort::OffsetFromHttp(0),
1,
Duration::from_secs(30),
));
- let (batcher, mut outputs) = key_table_batcher(
- &dispatcher,
+ let (batcher, mut outputs) = one_message_batcher(
+ pool_source,
transport,
Duration::from_millis(100),
Duration::from_millis(20),
@@ -1226,19 +1226,19 @@ async fn key_table_watchdog_bounds_overlapping_busy_retries() {
}
#[tokio::test]
-async fn key_table_retries_a_busy_send_until_it_completes() {
+async fn a_busy_send_is_retried_until_it_completes() {
let (attempts_tx, mut attempts_rx) = mpsc::unbounded_channel();
let addr = start_controlled_busy_worker(0, attempts_tx).await;
let worker_urls = vec![format!("http://{addr}")];
let registry = Arc::new(WorkerRegistry::new(&worker_urls, registry_config()));
- let dispatcher = Arc::new(Dispatcher::with_strategy(registry, RoutingStrategy::P2c));
+ let pool_source = WorkerPoolSource::new(registry, RoutingStrategy::P2c);
let transport = Arc::new(GrpcTransport::new(
GrpcPort::OffsetFromHttp(0),
1,
Duration::from_secs(30),
));
- let (batcher, mut outputs) = key_table_batcher(
- &dispatcher,
+ let (batcher, mut outputs) = one_message_batcher(
+ pool_source,
transport,
Duration::from_millis(500),
Duration::from_millis(20),
@@ -1272,19 +1272,19 @@ async fn key_table_retries_a_busy_send_until_it_completes() {
}
#[tokio::test]
-async fn key_table_watchdog_allows_in_flight_success_after_the_deadline() {
+async fn the_watchdog_allows_in_flight_success_after_the_deadline() {
let (attempts_tx, mut attempts_rx) = mpsc::unbounded_channel();
let addr = start_controlled_busy_worker(0, attempts_tx).await;
let worker_urls = vec![format!("http://{addr}")];
let registry = Arc::new(WorkerRegistry::new(&worker_urls, registry_config()));
- let dispatcher = Arc::new(Dispatcher::with_strategy(registry, RoutingStrategy::P2c));
+ let pool_source = WorkerPoolSource::new(registry, RoutingStrategy::P2c);
let transport = Arc::new(GrpcTransport::new(
GrpcPort::OffsetFromHttp(0),
1,
Duration::from_secs(30),
));
- let (batcher, mut outputs) = key_table_batcher(
- &dispatcher,
+ let (batcher, mut outputs) = one_message_batcher(
+ pool_source,
transport,
Duration::from_millis(100),
Duration::from_millis(20),
diff --git a/rust/ingestion-control-plane/src/ui/consumer_debug.html b/rust/ingestion-control-plane/src/ui/consumer_debug.html
index 4de6cc4d11c2..4f2c0d4b8f81 100644
--- a/rust/ingestion-control-plane/src/ui/consumer_debug.html
+++ b/rust/ingestion-control-plane/src/ui/consumer_debug.html
@@ -54,7 +54,7 @@
td .bar { height: 6px; border-radius: 3px; background: var(--accent); min-width: 2px; }
.pill { display: inline-block; padding: 1px 7px; border-radius: 10px; font-size: 11px; font-weight: 600; white-space: nowrap; }
.pill.healthy, .pill.committed { background: rgba(63,185,80,0.16); color: var(--good); }
- .pill.degraded, .pill.retrying, .pill.stashed { background: rgba(210,153,34,0.16); color: var(--warn); }
+ .pill.degraded, .pill.retrying { background: rgba(210,153,34,0.16); color: var(--warn); }
.pill.unhealthy, .pill.stalled, .pill.failed { background: rgba(248,81,73,0.16); color: var(--error); }
.pill.draining, .pill.inflight { background: rgba(139,147,161,0.18); color: var(--muted); }
.pill.accent { background: rgba(79,124,255,0.18); color: #a9c0ff; }
@@ -101,7 +101,6 @@
.node { background: var(--panel-2); border: 1px solid var(--border); border-radius: 8px; padding: 10px 12px; min-width: 150px; }
.node .title { font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); margin-bottom: 6px; }
.node .big { font-family: var(--mono); font-size: 15px; }
- .node.stash { border-color: rgba(210,153,34,0.5); }
.node.worker.acked { border-color: rgba(63,185,80,0.4); }
.node.worker.stalled { border-color: rgba(248,81,73,0.5); }
.arrow { align-self: center; color: var(--muted); font-size: 20px; }
@@ -111,7 +110,6 @@
.flow { position: relative; padding: 6px 4px 10px; overflow-x: auto; margin-bottom: 18px; }
.flow-main { display: flex; gap: 82px; align-items: center; }
.flow-col { display: flex; flex-direction: column; gap: 16px; justify-content: center; }
- .flow-defer { margin-top: 32px; padding-left: 250px; }
.flow .node { position: relative; z-index: 1; min-width: 122px; }
.flow svg { position: absolute; top: 0; left: 0; z-index: 0; pointer-events: none; overflow: visible; }
.node.src { border-color: rgba(79,124,255,0.45); }
@@ -158,14 +156,14 @@
<!-- left: live state -->
<div style="display:flex; flex-direction:column; gap:14px;">
<section class="panel">
- <h2>Dispatcher load</h2>
+ <h2>Batcher load</h2>
<div class="stats" id="disp-stats"></div>
</section>
<section class="panel">
<h2>Workers</h2>
<table>
<thead>
- <tr><th>Worker</th><th>State</th><th>In-flight</th><th>Fails</th><th>Err</th></tr>
+ <tr><th>Worker</th><th>State</th><th>Busy</th><th>Fails</th><th>Err</th></tr>
</thead>
<tbody id="workers"><tr><td class="empty" colspan="5">Waiting for data…</td></tr></tbody>
</table>
@@ -185,7 +183,6 @@
Event stream
<span class="controls">
<label><input type="checkbox" id="pause" /> pause</label>
- <label><input type="checkbox" id="hide-resolved" /> hide resolves</label>
</span>
</h2>
<div id="feed"><div class="empty">Waiting for events…</div></div>
@@ -287,24 +284,23 @@
$("routing").textContent = routingText;
const sliceSet = new Set(r.slice || []);
- const d = s.dispatcher;
- // In-flight is transient (a batch is assigned→sent→resolved in ms), so a
+ // A consumer pod from before the batcher rename still answers with
+ // `dispatcher`; read whichever key the pod sends during a rollout.
+ const d = s.batcher || s.dispatcher || {};
+ // In-flight is transient (a request is sent→resolved in ms), so a
// single sample often reads 0. Hold the peak over a short window so the
// panel reflects the concurrency actually happening.
const now = Date.now();
- loadSamples.push({ t: now, v: d.total_in_flight });
+ loadSamples.push({ t: now, v: d.total_in_flight ?? 0 });
loadSamples = loadSamples.filter((x) => now - x.t <= PEAK_WINDOW_MS);
const peak = loadSamples.reduce((m, x) => Math.max(m, x.v), 0);
$("disp-stats").innerHTML = [
- ["in-flight", d.total_in_flight],
+ ["in-flight", d.total_in_flight ?? 0],
["peak 4s", peak],
- ["pins", d.pin_count],
- ["stashed", d.stashed_messages],
- ["stash batches", d.stashed_batches],
+ ["pending", d.pending_messages ?? 0],
].map(([l, n]) => `<div class="stat"><div class="n">${n}</div><div class="l">${l}</div></div>`).join("");
- const maxLoad = Math.max(1, ...s.workers.map((w) => w.in_flight_messages));
// Stable order — slice members first, then by IP. Sorting by load made
// rows jump around on every poll.
const workerSortKey = (url) => {
@@ -320,14 +316,12 @@
workerSortKey(a.url).localeCompare(workerSortKey(b.url))).map((w) => {
const cls = w.draining ? "draining" : w.state;
const label = w.draining ? "draining" : w.state;
- const pct = Math.round((w.in_flight_messages / maxLoad) * 100);
const rate = (w.passive_error_rate * 100).toFixed(0) + "%";
- const slice = sliceSet.has(w.url) ? ` <span class="badge-min" title="in this dispatcher's aperture slice">slice</span>` : "";
+ const slice = sliceSet.has(w.url) ? ` <span class="badge-min" title="in this consumer's aperture slice">slice</span>` : "";
return `<tr>
<td class="mono">${shortWorker(w.url)}${slice}</td>
<td><span class="pill ${cls}">${label}</span></td>
- <td class="mono"><div style="display:flex;align-items:center;gap:8px;">
- <div class="bar" style="width:${pct}%"></div><span>${w.in_flight_messages}</span></div></td>
+ <td><span class="pill ${w.busy ? "accent" : "inflight"}">${w.busy ? "busy" : "idle"}</span></td>
<td class="mono">${w.consecutive_probe_failures}</td>
<td class="mono">${rate}</td>
</tr>`;
@@ -349,7 +343,7 @@
let b = batches[id];
if (!b) {
b = { id, ts: null, messages: 0, distinct_ids: 0, partitions: [],
- assigned: [], flushed: [], deferred: [], retries: [], exhausted: [], splits: [],
+ assigned: [], retries: [], exhausted: [], splits: [],
committed: null, events: [] };
batches[id] = b;
batchOrder.push(id);
@@ -366,11 +360,6 @@
b.events.push(ev);
switch (ev.type) {
case "BatchDispatched": b.messages = ev.messages; b.partitions = ev.partitions; break;
- case "BatchAssigned":
- b.assigned = ev.sub_batches; b.distinct_ids = ev.distinct_ids;
- b.deferredGroups = (b.deferredGroups || 0) + ev.deferred_groups + ev.unroutable_groups; break;
- case "Deferred": b.deferred.push({ reason: ev.reason, groups: ev.groups, ts: ev.ts_ms }); break;
- case "DeferredFlushed": ev.sub_batches.forEach((s) => b.flushed.push({ ...s, ts: ev.ts_ms })); break;
case "SendRetry": b.retries.push({ worker: ev.worker, attempt: ev.attempt, reason: ev.reason, ts: ev.ts_ms }); break;
case "SendSplit": b.splits.push({ worker: ev.worker, reason: ev.reason, chunks: ev.chunks, messages: ev.messages, ts: ev.ts_ms }); break;
case "SendExhausted": b.exhausted.push({ worker: ev.worker, error: ev.error, ts: ev.ts_ms }); break;
@@ -399,15 +388,14 @@
function batchStatus(b) {
if (b.committed) return "committed";
if (b.exhausted.length) return "stalled";
- if (b.deferred.length) return "stashed";
if (b.retries.length) return "retrying";
return "inflight";
}
- // A batch whose lifecycle involved a retry or stash — the interesting ones,
- // even if they ultimately committed cleanly.
+ // A batch whose lifecycle involved a retry or a failure: the interesting
+ // ones, even if they ultimately committed cleanly.
function hadIssue(b) {
- return b.retries.length || b.deferred.length || b.exhausted.length;
+ return b.retries.length || b.exhausted.length;
}
// ---------- live feed rendering ----------
@@ -415,19 +403,6 @@
switch (ev.type) {
case "ConsumerStarted": return ["accent", `▶ consumer started — group <code>${ev.group_id}</code>, ${ev.workers.length} worker(s)`];
case "BatchDispatched": return ["", `batch <code>${shortId(ev.batch_id)}</code> dispatched — ${ev.messages} msgs, ${ev.partitions.length} partition(s)`];
- case "BatchAssigned": {
- const routes = ev.sub_batches.map((s) => `${shortWorker(s.worker)}:${s.messages}`).join(" ");
- let extra = "";
- if (ev.deferred_groups) extra += ` ⏸${ev.deferred_groups} deferred`;
- if (ev.unroutable_groups) extra += ` ⚠${ev.unroutable_groups} unroutable`;
- return ["accent", `batch <code>${shortId(ev.batch_id)}</code> assigned — ${ev.distinct_ids} distinct_ids → ${routes || "—"}<span class="tag">${extra}</span>`];
- }
- case "SubBatchResolved": return ["", `resolved — ${shortWorker(ev.worker)} acked ${ev.messages} msgs (${ev.distinct_ids} ids)${ev.cleared_deferral ? '<span class="tag"> · cleared deferral</span>' : ""}`];
- case "Deferred": return ["warn", `⏸ deferred [${ev.reason}] — ${ev.groups} group(s), batch <code>${shortId(ev.batch_id)}</code>`];
- case "DeferredFlushed": {
- const routes = ev.sub_batches.map((s) => `${shortWorker(s.worker)}:${s.messages}`).join(" ");
- return ["warn", `↻ flushed deferred — batch <code>${shortId(ev.batch_id)}</code> → ${routes}`];
- }
case "BatchCommitted": return ["good", `✓ committed batch <code>${shortId(ev.batch_id)}</code> — ${ev.accepted} msgs in ${ev.duration_ms}ms`];
case "BatchFailed": return ["error", `✗ batch failed — ${ev.error}`];
case "SendRetry": return ["warn", `↻ retry #${ev.attempt} [${ev.reason}] — ${shortWorker(ev.worker)}, batch <code>${shortId(ev.batch_id)}</code>`];
@@ -440,7 +415,6 @@
}
function appendFeed(ev) {
- if (ev.type === "SubBatchResolved" && $("hide-resolved").checked) return;
const [cls, html] = describe(ev);
const feed = $("feed");
if (feedEmpty) { feed.innerHTML = ""; feedEmpty = false; }
@@ -468,8 +442,8 @@
renderPending = false;
$("badge-batches").textContent = batchOrder.length ? `(${batchOrder.length})` : "";
$("badge-commits").textContent = commits.length ? (oooCount ? `(${commits.length} · ⚠${oooCount})` : `(${commits.length})`) : "";
- // While the list is paused, freeze it so a stashed batch doesn't scroll
- // away before you can click it — but keep an open detail view live.
+ // While the list is paused, freeze it so a batch doesn't scroll away
+ // before you can click it, but keep an open detail view live.
if (activeTab === "batches" && (!$("batches-pause").checked || selectedBatch)) renderBatches();
if (activeTab === "commits") renderCommits();
}, 250);
@@ -477,9 +451,8 @@
function workerAgg(b) {
const m = {};
- const touch = (w) => (m[w] = m[w] || { worker: w, messages: 0, assignedMsgs: 0, flushedMsgs: 0, flushCount: 0, retries: 0, splits: 0, flushed: false, exhausted: false });
+ const touch = (w) => (m[w] = m[w] || { worker: w, messages: 0, assignedMsgs: 0, retries: 0, splits: 0, exhausted: false });
b.assigned.forEach((s) => { const x = touch(s.worker); x.messages += s.messages; x.assignedMsgs += s.messages; });
- b.flushed.forEach((s) => { const x = touch(s.worker); x.messages += s.messages; x.flushedMsgs += s.messages; x.flushed = true; x.flushCount += 1; });
b.retries.forEach((r) => (touch(r.worker).retries += 1));
b.splits.forEach((s) => (touch(s.worker).splits += 1));
b.exhausted.forEach((e) => (touch(e.worker).exhausted = true));
@@ -495,7 +468,7 @@
let ids = batchOrder.slice().reverse();
if (issuesOnly) ids = ids.filter((id) => hadIssue(batches[id]));
if (!ids.length) {
- view.innerHTML = `<div class="empty">${issuesOnly ? "No batches with retries or stash yet…" : "Waiting for batches…"}</div>`;
+ view.innerHTML = `<div class="empty">${issuesOnly ? "No batches with retries or failures yet…" : "Waiting for batches…"}</div>`;
return;
}
const rows = ids.map((id) => {
@@ -507,7 +480,6 @@
const retries = b.retries.length;
if (retries) badges.push(`<span class="badge-min warn">↻${retries}</span>`);
if (b.splits.length) badges.push(`<span class="badge-min warn">✂${b.splits.length}</span>`);
- if (b.deferred.length) badges.push(`<span class="badge-min warn">⏸${b.deferred.length}</span>`);
if (b.exhausted.length) badges.push(`<span class="badge-min error">✗${b.exhausted.length}</span>`);
return `<div class="brow" data-id="${id}">
<span class="id">${shortId(id)}</span>
@@ -532,25 +504,13 @@
["workers", workers.length],
["retries", b.retries.length],
["splits", b.splits.length],
- ["stashed", b.deferred.reduce((a, d) => a + d.groups, 0)],
].map(([l, n]) => `<div class="stat"><div class="n">${n}</div><div class="l">${l}</div></div>`).join("");
const flow = buildFlow(b, workers);
- // Annotate flushes with the stash dwell time so defer → retry gaps are
- // readable without diffing timestamps by hand. Measured from the first
- // deferral of the current stash cycle: several Deferred events can pile
- // up before one flush, and the earliest is what waited longest.
- let cycleDeferTs = null;
const timeline = b.events.map((ev) => {
const [cls, html] = describe(ev);
- let extra = "";
- if (ev.type === "Deferred" && cycleDeferTs === null) cycleDeferTs = ev.ts_ms;
- if (ev.type === "DeferredFlushed" && cycleDeferTs !== null) {
- extra = `<span class="tag"> · waited ${fmtDur(ev.ts_ms - cycleDeferTs)}</span>`;
- cycleDeferTs = null;
- }
- return `<div class="item ${cls}"><span class="t">${fmtTime(ev.ts_ms)}</span>${html}${extra}</div>`;
+ return `<div class="item ${cls}"><span class="t">${fmtTime(ev.ts_ms)}</span>${html}</div>`;
}).join("");
const fresh = openDetailId !== b.id;
@@ -561,7 +521,6 @@
<h2 style="border:none;padding:0 0 8px;">Flow · batch ${shortId(b.id)}</h2>
<div class="flow-legend">
<span><i style="background:#4f7cff"></i>routed</span>
- <span><i style="background:#d29922"></i>deferred / flushed</span>
<span><i style="background:#f85149"></i>send failed</span>
<span><i style="background:#3fb950"></i>acked / committed</span>
</div>
@@ -575,52 +534,22 @@
}
// Build the node/edge model for a batch's flow graph. Nodes sit in four
- // lanes (Kafka → assign → workers → commit); the stash lane hangs below and
- // the defer/flush edges connect it explicitly to assign and the workers.
+ // lanes (Kafka → assign → workers → commit).
function buildFlow(b, workers) {
- const idx = {};
- workers.forEach((w, i) => (idx[w.worker] = i));
- 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);
- const firstDefer = hasStash ? b.deferred[0].ts : null;
- const firstFlush = b.flushed.length ? Math.min(...b.flushed.map((s) => s.ts)) : null;
- const flushedBy = {};
- b.flushed.forEach((s) => {
- const f = (flushedBy[s.worker] = flushedBy[s.worker] || { messages: 0, ts: s.ts });
- f.messages += s.messages;
- f.ts = Math.max(f.ts, s.ts);
- });
-
const partsShort = b.partitions.map((p) => `${p.partition}@${p.offset}`).join(" ") || "—";
const sourceNode = `<div class="node src" id="n-source"><div class="title">Kafka batch</div><div class="big">${b.messages}</div><div class="sub">msgs · p ${partsShort}</div></div>`;
const assignNode = `<div class="node" id="n-assign"><div class="title">Assign</div><div class="big">${b.distinct_ids}</div><div class="sub">distinct_ids</div></div>`;
const workerNodes = workers.map((w, i) => {
const cls = w.exhausted ? "stalled" : b.committed ? "acked" : "";
- // Headline = messages this worker was initially assigned (bounded by the
- // batch), or, for a worker that only received re-routed work, the flushed
- // count. Re-routes are shown as a count, not summed into the headline —
- // a re-flushed sub-batch is the same messages retried, not new ones.
- const primary = w.assignedMsgs > 0 ? w.assignedMsgs : w.flushedMsgs;
const badges = [];
if (w.retries) badges.push(`<span class="badge-min warn">↻${w.retries}</span>`);
if (w.splits) badges.push(`<span class="badge-min warn">✂×${w.splits}</span>`);
- if (w.flushCount) badges.push(`<span class="badge-min warn">re-routed ×${w.flushCount}</span>`);
if (w.exhausted) badges.push(`<span class="badge-min error">exhausted</span>`);
if (!w.exhausted && b.committed) badges.push(`<span class="badge-min">✓ acked</span>`);
- return `<div class="node worker ${cls}" id="n-w-${i}"><div class="title">${shortWorker(w.worker)}</div><div class="big">${primary}</div><div class="sub">${badges.join(" ") || "sent"}</div></div>`;
+ return `<div class="node worker ${cls}" id="n-w-${i}"><div class="title">${shortWorker(w.worker)}</div><div class="big">${w.assignedMsgs}</div><div class="sub">${badges.join(" ") || "sent"}</div></div>`;
}).join("") || '<div class="node" id="n-w-none"><div class="sub">not yet assigned</div></div>';
- const reasons = Object.entries(deferBy).filter(([, n]) => n > 0).map(([r, n]) => `${r}: ${n}`).join(" · ");
- const stashTiming = b.flushed.length
- ? `↻ flushed after ${fmtDur(firstFlush - firstDefer)}`
- : "awaiting flush";
- const stashNode = hasStash
- ? `<div class="node stash" id="n-stash"><div class="title">Stash / defer</div><div class="big">${totalDeferred}</div><div class="sub">${reasons}</div><div class="sub">⏸ ${fmtTime(firstDefer)}</div><div class="sub">${stashTiming}</div></div>`
- : "";
-
const sinkNode = b.committed
? `<div class="node sink-ok" id="n-sink"><div class="title">Committed</div><div class="big">${b.committed.accepted}</div><div class="sub">${b.committed.duration_ms}ms · ${b.committed.partitions.map((p) => `${p.partition}@${p.offset}`).join(" ")}</div></div>`
: `<div class="node sink-pending" id="n-sink"><div class="title">In-flight</div><div class="sub">not committed</div></div>`;
@@ -632,7 +561,6 @@
<div class="flow-col">${workerNodes}</div>
<div class="flow-col">${sinkNode}</div>
</div>
- ${hasStash ? `<div class="flow-defer">${stashNode}</div>` : ""}
<svg></svg>
</div>`;
@@ -641,19 +569,6 @@
edges.push({ from: "n-source", to: "n-assign", label: `${b.messages} msgs`, color: C.accent });
workers.forEach((w, i) => { if (w.assignedMsgs > 0) edges.push({ from: "n-assign", to: `n-w-${i}`, label: `sent ${w.assignedMsgs}${w.retries ? ` · ↻${w.retries}` : ""}`, color: w.retries ? C.warn : C.muted }); });
- if (hasStash) {
- let incoming = 0;
- const da = deferBy.drain + deferBy.queued_behind_deferral + deferBy.unroutable;
- if (da > 0) {
- 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++;
- }
- workers.forEach((w, i) => { if (w.exhausted) { edges.push({ from: `n-w-${i}`, to: "n-stash", label: "send failed", color: C.error }); incoming++; } });
- if (deferBy.send_failed > 0 && incoming === 0) edges.push({ from: "n-assign", to: "n-stash", label: "send failed", color: C.error });
- Object.entries(flushedBy).forEach(([worker, f]) => { const i = idx[worker]; if (i != null) edges.push({ from: "n-stash", to: `n-w-${i}`, label: `flushed ${f.messages} · +${fmtDur(f.ts - firstDefer)}`, color: C.warn }); });
- }
-
if (b.committed) {
if (workers.length) workers.forEach((w, i) => { if (!w.exhausted) edges.push({ from: `n-w-${i}`, to: "n-sink", label: "acked", color: C.good }); });
else edges.push({ from: "n-assign", to: "n-sink", label: "", color: C.good });
diff --git a/rust/ingestion-control-plane/src/ui/index.html b/rust/ingestion-control-plane/src/ui/index.html
index 59f199e28afb..7c7a9f8d6405 100644
--- a/rust/ingestion-control-plane/src/ui/index.html
+++ b/rust/ingestion-control-plane/src/ui/index.html
@@ -946,14 +946,14 @@
return el("table", {},
el("thead", {}, el("tr", {},
el("th", {}, "pod"), el("th", {}, "ip"), el("th", {}, "phase"), el("th", {}, "restarts"), el("th", {}, "started"),
- el("th", {}, "peer"), el("th", {}, "workers"), el("th", {}, "in flight"), el("th", {}, "stashed"))),
+ el("th", {}, "peer"), el("th", {}, "workers"), el("th", {}, "in flight"), el("th", {}, "pending"))),
el("tbody", {}, group.pods.map((pod) => {
const key = `${pod.namespace}/${pod.name}`;
const live = {
peer: el("td", { class: "mono muted" }, "…"),
workers: el("td", { class: "mono muted" }, "…"),
inFlight: el("td", { class: "mono muted" }, "…"),
- stashed: el("td", { class: "mono muted" }, "…"),
+ pending: el("td", { class: "mono muted" }, "…"),
};
this.liveCells.set(key, live);
if (this.loads.has(key)) this.paintLoad(key);
@@ -963,7 +963,7 @@
el("td", {}, el("span", { class: `pill ${pod.ready ? "good" : "warn"}` }, pod.phase || "?")),
el("td", { class: "mono" }, String(pod.restarts)),
el("td", { class: "muted mono" }, pod.started_at ? `${new Date(pod.started_at).toLocaleString()} (${fmtAgo(pod.started_at)})` : "–"),
- live.peer, live.workers, live.inFlight, live.stashed);
+ live.peer, live.workers, live.inFlight, live.pending);
row.addEventListener("click", () => this.selectPod(pod, row));
return row;
}))
@@ -996,7 +996,7 @@
if (!cells || !result) return;
if (!result.ok) {
cells.peer.replaceChildren(el("span", { class: "pill bad" }, "unreachable"));
- for (const cell of [cells.workers, cells.inFlight, cells.stashed]) cell.replaceChildren("–");
+ for (const cell of [cells.workers, cells.inFlight, cells.pending]) cell.replaceChildren("–");
return;
}
const { load } = result;
@@ -1009,10 +1009,12 @@
set(cells.workers, routable === load.workers.length
? `${routable}/${load.workers.length}`
: el("span", { class: "pill warn" }, `${routable}/${load.workers.length}`));
- set(cells.inFlight, fmtInt(load.dispatcher.total_in_flight));
- set(cells.stashed, load.dispatcher.stashed_messages > 0
- ? el("span", { class: "pill warn" }, fmtInt(load.dispatcher.stashed_messages))
- : "0");
+ // A consumer pod from before the batcher rename still answers with
+ // `dispatcher`; read whichever key the pod sends during a rollout.
+ const batcher = load.batcher || load.dispatcher || {};
+ set(cells.inFlight, fmtInt(batcher.total_in_flight ?? 0));
+ const pending = batcher.pending_messages ?? 0;
+ set(cells.pending, pending > 0 ? el("span", { class: "pill warn" }, fmtInt(pending)) : "0");
},
selectPod(pod, row) {