:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(ingestion-consumer): defer unroutable keys instead of dropping them (#67698)
José Sequeiraf5da831451d1
diff --git a/nodejs/tests/service-e2e/rust-ingestion-consumer.test.ts b/nodejs/tests/service-e2e/rust-ingestion-consumer.test.tsindex 8a1731355253..ef12ecdf84bf 100644--- a/nodejs/tests/service-e2e/rust-ingestion-consumer.test.ts+++ b/nodejs/tests/service-e2e/rust-ingestion-consumer.test.ts@@ -374,8 +374,14 @@ describe('Rust ingestion consumer with Node ingestion API workers', () => {}})- test('Rust consumer exits when all Node ingestion API workers are down', async () => {- const { workers, rustConsumer, rustMetricsPort } = await startRustNodeStack(services)+ 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+ // 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, {+ CONSUMER_DEFERRED_FLUSH_TIMEOUT_MS: '5000',+ })const producer = await KafkaProducerWrapper.create(undefined)const team = { ...DEFAULT_TEAM, id: TEST_TEAM_ID, api_token: TEST_TEAM_TOKEN }const distinctIds = createDistinctIds(8)@@ -399,7 +405,7 @@ describe('Rust ingestion consumer with Node ingestion API workers', () => {const exit = await rustConsumer.waitForExit(60_000)expect(exit.exitCode).not.toBe(0)- expect(exit.output).toContain('No healthy workers available to route batch')+ expect(exit.output).toContain('deferred messages could not be flushed within timeout')await waitForTopicMessageCount(KAFKA_EVENTS_JSON, 0)} finally {await producer.disconnect()@@ -435,7 +441,8 @@ async function startNodeWorkerSet(services: ServiceProcess[]): Promise<NodeWorkeasync function startRustConsumerForWorkers(services: ServiceProcess[],- workers: NodeWorker[]+ workers: NodeWorker[],+ extraRustEnv: Record<string, string> = {}): Promise<Omit<RustNodeStack, 'workers'>> {const rustMetricsPort = await getFreePort()const groupId = `rust-node-e2e-${Date.now()}-${Math.random().toString(16).slice(2)}`@@ -443,7 +450,8 @@ async function startRustConsumerForWorkers('rust-consumer',workers.map((worker) => worker.url),rustMetricsPort,- groupId+ groupId,+ extraRustEnv)services.push(rustConsumer)await rustConsumer.waitForHttpOk(`http://127.0.0.1:${rustMetricsPort}/_readiness`)@@ -451,9 +459,12 @@ async function startRustConsumerForWorkers(return { rustConsumer, rustMetricsPort, groupId }}-async function startRustNodeStack(services: ServiceProcess[]): Promise<RustNodeStack> {+async function startRustNodeStack(+ services: ServiceProcess[],+ extraRustEnv: Record<string, string> = {}+): Promise<RustNodeStack> {const workers = await startNodeWorkerSet(services)- const rust = await startRustConsumerForWorkers(services, workers)+ const rust = await startRustConsumerForWorkers(services, workers, extraRustEnv)return { workers, ...rust }}@@ -498,7 +509,8 @@ function startRustIngestionConsumer(name: string,workers: string[],metricsPort: number,- groupId: string+ groupId: string,+ extraEnv: Record<string, string> = {}): ServiceProcess {return new ServiceProcess(name, 'cargo', ['run', '-p', 'ingestion-consumer'], {cwd: RUST_ROOT,@@ -527,6 +539,7 @@ function startRustIngestionConsumer(BIND_HOST: '127.0.0.1',BIND_PORT: metricsPort.toString(),EXPORT_PROMETHEUS: 'true',+ ...extraEnv,},})}diff --git a/rust/ingestion-consumer/README.md b/rust/ingestion-consumer/README.mdnew file mode 100644index 000000000000..b5fd6d2ff820--- /dev/null+++ b/rust/ingestion-consumer/README.md@@ -0,0 +1,45 @@+# ingestion-consumer++Rust Kafka consumer that routes analytics events to Node.js ingestion workers over HTTP with sticky per-`distinct_id` assignment.+It reads batches from Kafka, groups messages by `token:distinct_id`, pins each key to a worker (preserving per-person ordering), scatters sub-batches over HTTP, 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.++## Testing++- `cargo test -p ingestion-consumer --lib` — unit tests.+- `cargo test -p ingestion-consumer --tests` — integration suites; the e2e suite requires Kafka on `localhost:9092`.++## Follow-up work++Known gaps in priority order.+The details below are grounded in the current code — re-verify limits and paths before building on them.++### 1. Sub-batch size cap and 413 handling (incident-class)++Sub-batches have no size bound: a batch (default 500 messages, each up to ~1 MB of Kafka payload) can merge onto one worker as a single HTTP request, while the worker's express app rejects bodies over 20 MB (`nodejs/src/common/api/router.ts`) with a 413.+The transport treats 4xx as non-retriable, so the same oversized sub-batch re-sends until the deferred-flush timeout, the process exits, Kafka redelivers, and it crash-loops deterministically — a stalled partition triggered by an ordinary burst of large events.+Fix: cap sub-batch payload size at build time (chunks sent sequentially per worker to preserve per-key order), plus a defensive split-in-half retry on 413.++### 2. Commit-error observability++`commit_offsets` uses `CommitMode::Async` and never observes the result; persistent commit failure (e.g. after a rebalance) is invisible until restart-time redelivery.+Fix: a `ConsumerContext` with an offset-commit callback feeding a failure counter and a last-successful-commit gauge, alertable.+The same context provides rebalance callbacks — log partition assignment changes at minimum.++### 3. DLQ for poison messages++A message a worker permanently rejects (4xx, or persistent `status:"error"`) has no dead-letter path: after the flush timeout the batch 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.+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.++### Smaller items++- Probe timeout is hardcoded to `probe_interval / 2`; a slow-but-serving worker's `/_ready` can flap it unhealthy. Make it independently configurable.+- Non-UTF-8 payload/header nulling has no metric — add a counter and a rate-limited warning even before the DLQ work lands.diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rsindex 3b86fa240114..d3b2f35b6b4c 100644--- a/rust/ingestion-consumer/src/config.rs+++ b/rust/ingestion-consumer/src/config.rs@@ -121,6 +121,13 @@ pub struct Config {#[envconfig(default = "500")]pub consumer_batch_timeout_ms: u64,+ /// Upper bound on retrying a batch's deferred messages (held because no+ /// worker was routable) before failing the batch (milliseconds). Bounds how+ /// long a full worker outage holds offsets before the process exits and+ /// restarts.+ #[envconfig(default = "60000")]+ pub consumer_deferred_flush_timeout_ms: u64,+/// Maximum Kafka batches to process concurrently. Matches the Node.js/// CONSUMER_MAX_BACKGROUND_TASKS setting used by the Kafka consumer wrapper.#[envconfig(from = "CONSUMER_MAX_BACKGROUND_TASKS", default = "1")]diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rsindex 1633cabec3d1..4e33b71afa5c 100644--- a/rust/ingestion-consumer/src/consumer.rs+++ b/rust/ingestion-consumer/src/consumer.rs@@ -17,10 +17,6 @@ use crate::dispatcher::{Dispatcher, SubBatch};use crate::transport::HttpTransport;use crate::types::SerializedKafkaMessage;-/// Max time `complete_oldest_batch` will keep retrying to flush a batch's-/// deferred groups (waiting for a healthy worker) before failing the batch.-const DEFERRED_FLUSH_TIMEOUT: Duration = Duration::from_secs(60);-/// Statistics gathered while collecting a batch, used to emit parity metrics.struct BatchStats {/// Max Kafka message timestamp (ms) per (topic, partition) — for `latest_processed_timestamp_ms`.@@ -76,8 +72,8 @@ pub struct IngestionConsumerOptions {pub max_in_flight_batches: usize,pub group_id: String,/// Upper bound on how long `complete_oldest_batch` retries flushing a batch's- /// deferred groups before failing the batch. Defaults to- /// [`DEFERRED_FLUSH_TIMEOUT`] in `new`.+ /// deferred groups before failing the batch. `new` takes it from+ /// `CONSUMER_DEFERRED_FLUSH_TIMEOUT_MS` (default 60s).pub deferred_flush_timeout: Duration,}@@ -159,7 +155,9 @@ impl IngestionConsumer {batch_size: config.consumer_batch_size,batch_timeout: Duration::from_millis(config.consumer_batch_timeout_ms),max_in_flight_batches: config.consumer_max_background_tasks.max(1),- deferred_flush_timeout: DEFERRED_FLUSH_TIMEOUT,+ deferred_flush_timeout: Duration::from_millis(+ config.consumer_deferred_flush_timeout_ms,+ ),handle,group_id: config.ingestion_consumer_group_id.clone(),})@@ -329,7 +327,7 @@ impl IngestionConsumer {/// Flush a completed batch's deferred groups (keys whose worker was/// draining/dead), re-routing them to healthy workers and accumulating the/// accepted count. Retries with backoff while a flush can't route (no healthy- /// worker yet), bounded by `DEFERRED_FLUSH_TIMEOUT`. Called serialized,+ /// worker yet), bounded by `deferred_flush_timeout`. Called serialized,/// oldest-first, so a key's deferred messages flush in Kafka order.async fn flush_deferred(&self,diff --git a/rust/ingestion-consumer/src/discovery.rs b/rust/ingestion-consumer/src/discovery.rsindex 8d3a7900bac1..7e6606ab7ab0 100644--- a/rust/ingestion-consumer/src/discovery.rs+++ b/rust/ingestion-consumer/src/discovery.rs@@ -77,7 +77,9 @@ pub trait WorkerDiscovery: Send {/// Reconcile the registry to a desired worker set: add workers that are new and/// re-admit any that rejoined, and mark departed workers as draining (they keep/// finishing in-flight work; the reaper removes them once drained or timed out).-fn reconcile_membership(registry: &WorkerRegistry, desired: &HashSet<WorkerId>) {+/// Public so integration tests can drive membership changes the same way the+/// discovery providers do.+pub fn reconcile_membership(registry: &WorkerRegistry, desired: &HashSet<WorkerId>) {let current: HashSet<WorkerId> = registry.workers().into_iter().collect();for worker in desired.difference(¤t) {diff --git a/rust/ingestion-consumer/src/dispatcher.rs b/rust/ingestion-consumer/src/dispatcher.rsindex 03e172154a17..b423a6d06825 100644--- a/rust/ingestion-consumer/src/dispatcher.rs+++ b/rust/ingestion-consumer/src/dispatcher.rs@@ -171,7 +171,9 @@ impl Dispatcher {/// - **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.+ /// - 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.////// Returns one `SubBatch` per worker to send now. Deferred groups stay in/// the stash and are flushed later via [`Dispatcher::flush_deferred`].@@ -203,6 +205,7 @@ impl Dispatcher {let mut unpinned_groups: Vec<MessageGroup> = Vec::new();let mut deferred_count = 0u64;+ let mut unroutable_deferred_count = 0u64;for group in key_groups {let pinned_worker = table.pins.get(&group.routing_key).map(|p| p.worker.clone());@@ -231,6 +234,19 @@ impl Dispatcher {);deferred_count += 1;}+ None if table.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.+ table.stash.defer(+ batch_id,+ DeferredGroup {+ routing_key: group.routing_key,+ messages: group.messages,+ },+ );+ deferred_count += 1;+ }None => unpinned_groups.push(group),}}@@ -246,9 +262,21 @@ impl Dispatcher {for group in unpinned_groups {let Some(worker) = router.select(&healthy, &working_load) else {- // All workers unhealthy — this key cannot be assigned.+ // No routable worker right now (e.g. the whole pool is draining+ // during a deploy overlap). Stash the group so the flush loop+ // 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);+ table.stash.defer(+ batch_id,+ DeferredGroup {+ routing_key: group.routing_key,+ messages: group.messages,+ },+ );+ unroutable_deferred_count += 1;continue;};@@ -286,6 +314,13 @@ impl Dispatcher {).increment(deferred_count);}+ if unroutable_deferred_count > 0 {+ counter!(+ "ingestion_consumer_dispatcher_deferred_groups_total",+ "reason" => "unroutable",+ )+ .increment(unroutable_deferred_count);+ }gauge!("ingestion_consumer_dispatcher_pins_total").set(table.pins.len() as f64);record_stash_gauges(&table.stash);@@ -316,6 +351,19 @@ impl Dispatcher {self.pin_table.lock().unwrap().stash.message_count()}+ /// 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.pin_table.lock().unwrap().pins.len()+ }++ /// 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.pin_table.lock().unwrap().in_flight.values().sum()+ }+/// Defer messages whose send failed (the worker died mid-send) so they can be/// replayed in order. Must be called **before** `on_sub_batch_resolved` for/// the failed sub-batch, so the ref-count drop doesn't evict the pin while@@ -654,10 +702,6 @@ mod tests {.unwrap_or(0)}- fn pin_count(dispatcher: &Dispatcher) -> usize {- dispatcher.pin_table.lock().unwrap().pins.len()- }-// ---- routing key ----#[test]@@ -1102,6 +1146,74 @@ mod tests {);}+ #[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(®istry));++ 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(®istry));+ 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,+ );+ 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);@@ -1190,7 +1302,7 @@ mod tests {// must keep the pin from being evicted (so order is preserved on flush).dispatcher.on_sub_batch_resolved(&pinned, b1[0].messages.len(), &b1[0].routing_keys, false);assert_eq!(- pin_count(&dispatcher),+ dispatcher.pin_count(),1,"pin retained while deferred pending");@@ -1218,7 +1330,7 @@ mod tests {"failed messages held for replay");assert_eq!(- pin_count(&dispatcher),+ dispatcher.pin_count(),1,"pin kept for the deferred replay");diff --git a/rust/ingestion-consumer/src/stash.rs b/rust/ingestion-consumer/src/stash.rsindex 6a4d43c1fdce..ff6471de9cdc 100644--- a/rust/ingestion-consumer/src/stash.rs+++ b/rust/ingestion-consumer/src/stash.rs@@ -218,6 +218,21 @@ mod tests {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();diff --git a/rust/ingestion-consumer/tests/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rsindex a6d224ee79f6..495e63812a35 100644--- a/rust/ingestion-consumer/tests/e2e_integration_test.rs+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs@@ -3,7 +3,7 @@//! Requires Kafka on localhost:9092 (available via docker-compose).//! Each test creates a uniquely-named topic to avoid cross-test interference.-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::{Arc, Mutex};use std::time::Duration;@@ -11,6 +11,7 @@ use std::time::Duration;use axum::extract::Json as AxumJson;use axum::routing::{get, post};use axum::Router;+use futures::StreamExt;use lifecycle::{ComponentOptions, Manager};use rdkafka::admin::{AdminClient, AdminOptions, NewTopic, TopicReplication};use rdkafka::client::DefaultClientContext;@@ -24,6 +25,7 @@ use tokio_util::sync::CancellationToken;use uuid::Uuid;use ingestion_consumer::consumer::{IngestionConsumer, IngestionConsumerOptions};+use ingestion_consumer::discovery::reconcile_membership;use ingestion_consumer::dispatcher::Dispatcher;use ingestion_consumer::transport::HttpTransport;use ingestion_consumer::types::{IngestBatchRequest, IngestBatchResponse, SerializedKafkaMessage};@@ -90,6 +92,29 @@ async fn produce(.expect("produce failed");}+/// Produce a record with full control over payload bytes and optional headers —+/// for malformed-input scenarios (missing routing headers, non-UTF-8 bytes).+async fn produce_raw(+ producer: &FutureProducer,+ topic: &str,+ partition: i32,+ key: &str,+ payload: &[u8],+ headers: Option<OwnedHeaders>,+) {+ let mut record = FutureRecord::to(topic)+ .key(key)+ .payload(payload)+ .partition(partition);+ if let Some(h) = headers {+ record = record.headers(h);+ }+ producer+ .send(record, Timeout::After(Duration::from_secs(5)))+ .await+ .expect("produce failed");+}+// ── Fake worker ────────────────────────────────────────────────────────────struct FakeWorker {@@ -102,6 +127,16 @@ struct FakeWorker {/// fails every send — a "flapping" worker, used to exercise the flush loop's/// re-defer path and its timeout bound.pub ingest_ok: Arc<AtomicBool>,+ /// When set, the next /ingest request is processed and recorded but answered+ /// with an error — a "lost ACK". Models the ambiguous outcome where the+ /// worker did the work but the consumer never learns it, so it replays.+ pub ack_lost_once: Arc<AtomicBool>,+ /// When true, every /ingest request is rejected with HTTP 400 without+ /// ingesting anything — a poison batch this worker will never accept.+ pub reject_4xx: Arc<AtomicBool>,+ /// When set, the next /ingest request is ingested in full but reports one+ /// message fewer than sent — a partial-acceptance contract violation.+ pub underreport_once: Arc<AtomicBool>,/// Number of /ingest requests that have reached the handler. Counted before/// the gate, so a test can observe a batch is in-flight even while held.arrived: Arc<AtomicUsize>,@@ -133,6 +168,9 @@ impl FakeWorker {let received: Arc<Mutex<Vec<(String, usize)>>> = Arc::new(Mutex::new(Vec::new()));let healthy = Arc::new(AtomicBool::new(true));let ingest_ok = Arc::new(AtomicBool::new(true));+ let ack_lost_once = Arc::new(AtomicBool::new(false));+ let reject_4xx = Arc::new(AtomicBool::new(false));+ let underreport_once = Arc::new(AtomicBool::new(false));let arrived = Arc::new(AtomicUsize::new(0));let gate = Arc::new(tokio::sync::Mutex::new(()));@@ -159,6 +197,9 @@ impl FakeWorker {let recv = Arc::clone(&received);let h = Arc::clone(&healthy);let ingest_ok = Arc::clone(&ingest_ok);+ let ack_lost_once = Arc::clone(&ack_lost_once);+ let reject_4xx = Arc::clone(&reject_4xx);+ let underreport_once = Arc::clone(&underreport_once);let arrived = Arc::clone(&arrived);let gate = Arc::clone(&gate);let delivery_log = delivery_log.clone();@@ -166,6 +207,9 @@ impl FakeWorker {let recv = recv.clone();let h = h.clone();let ingest_ok = ingest_ok.clone();+ let ack_lost_once = ack_lost_once.clone();+ let reject_4xx = reject_4xx.clone();+ let underreport_once = underreport_once.clone();let arrived = arrived.clone();let gate = gate.clone();let delivery_log = delivery_log.clone();@@ -188,6 +232,19 @@ impl FakeWorker {}),);}+ // A poison batch: permanently rejected with a client+ // error, nothing ingested.+ if reject_4xx.load(Ordering::SeqCst) {+ return (+ axum::http::StatusCode::BAD_REQUEST,+ AxumJson(IngestBatchResponse {+ batch_id: req.batch_id,+ status: "error".to_string(),+ accepted: 0,+ error: Some("poison batch".to_string()),+ }),+ );+ }let accepted = req.messages.len() as u32;let entries: Vec<(String, usize)> = req.messages@@ -213,12 +270,32 @@ impl FakeWorker {if let Some(log) = &delivery_log {log.lock().unwrap().extend(entries);}+ // The work is done and recorded, but the ACK is lost:+ // answer with an error so the consumer must replay.+ if ack_lost_once.swap(false, Ordering::SeqCst) {+ return (+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,+ AxumJson(IngestBatchResponse {+ batch_id: req.batch_id,+ status: "error".to_string(),+ accepted: 0,+ error: Some("ack lost".to_string()),+ }),+ );+ }+ // Partial acceptance: everything was ingested, but the+ // response claims one message fewer than sent.+ let reported = if underreport_once.swap(false, Ordering::SeqCst) {+ accepted.saturating_sub(1)+ } else {+ accepted+ };(axum::http::StatusCode::OK,AxumJson(IngestBatchResponse {batch_id: req.batch_id,status: "ok".to_string(),- accepted,+ accepted: reported,error: None,}),)@@ -237,6 +314,9 @@ impl FakeWorker {received,healthy,ingest_ok,+ ack_lost_once,+ reject_4xx,+ underreport_once,arrived,gate,_task: task,@@ -280,6 +360,62 @@ struct Harness {pub shutdown: CancellationToken,task: Option<tokio::task::JoinHandle<()>>,_probe_token: CancellationToken,+ topic: String,+ /// Consumer group id, kept so `restart_consumer` rejoins the same group.+ group_id: String,+ max_in_flight: usize,+ deferred_flush_timeout: Duration,+}++/// Build a Kafka consumer subscribed to `topic` in `group_id`, configured like+/// the production batch consumer (no auto commit/store, earliest reset). The+/// short session timeout makes group handovers observable quickly in tests.+/// `instance_id` opts into static membership (`group.instance.id`).+fn make_kafka_consumer(topic: &str, group_id: &str, instance_id: Option<&str>) -> StreamConsumer {+ let mut config = ClientConfig::new();+ config+ .set("bootstrap.servers", KAFKA_BROKERS)+ .set("group.id", group_id)+ .set("auto.offset.reset", "earliest")+ .set("enable.auto.commit", "false")+ .set("enable.auto.offset.store", "false")+ .set("session.timeout.ms", "6000")+ .set("socket.timeout.ms", "5000");+ if let Some(id) = instance_id {+ config.set("group.instance.id", id);+ }+ let kafka_consumer: StreamConsumer = config.create().expect("kafka consumer");+ kafka_consumer.subscribe(&[topic]).expect("subscribe");+ kafka_consumer+}++/// Reap drained workers exactly as `main.rs` does in production: complete the+/// drain of an idle drainer, then remove reaped workers from the registry and+/// transport. Runs until `token` is cancelled. (A faster tick than production's+/// 1s keeps test scenarios responsive.)+fn spawn_reaper(+ registry: Arc<WorkerRegistry>,+ transport: Arc<HttpTransport>,+ dispatcher: Arc<Dispatcher>,+ token: CancellationToken,+) {+ tokio::spawn(async move {+ loop {+ tokio::select! {+ _ = token.cancelled() => break,+ _ = tokio::time::sleep(Duration::from_millis(100)) => {}+ }+ for worker in registry.draining_workers() {+ if !dispatcher.has_in_flight(&worker) {+ registry.complete_drain(&worker);+ }+ }+ for worker in registry.reapable_workers() {+ registry.remove_worker(&worker);+ transport.remove_worker(&worker);+ }+ }+ });}impl Harness {@@ -314,6 +450,12 @@ impl Harness {&worker_urls,1,));+ spawn_reaper(+ Arc::clone(®istry),+ Arc::clone(&transport),+ Arc::clone(&dispatcher),+ probe_token.clone(),+ );let mut manager = Manager::builder("e2e-test").with_trap_signals(false)@@ -321,16 +463,8 @@ impl Harness {let handle = manager.register("consumer", ComponentOptions::new());let shutdown = handle.shutdown_token();- let kafka_consumer: StreamConsumer = ClientConfig::new()- .set("bootstrap.servers", KAFKA_BROKERS)- .set("group.id", format!("e2e-{}", Uuid::new_v4()))- .set("auto.offset.reset", "earliest")- .set("enable.auto.commit", "false")- .set("enable.auto.offset.store", "false")- .set("socket.timeout.ms", "5000")- .create()- .expect("kafka consumer");- kafka_consumer.subscribe(&[topic]).expect("subscribe");+ let group_id = format!("e2e-{}", Uuid::new_v4());+ let kafka_consumer = make_kafka_consumer(topic, &group_id, None);let consumer = IngestionConsumer::from_parts(kafka_consumer,@@ -360,9 +494,75 @@ impl Harness {shutdown,task: Some(task),_probe_token: probe_token,+ topic: topic.to_string(),+ group_id,+ max_in_flight,+ deferred_flush_timeout,+ }+ }++ /// Simulate a crash: abort the consumer task in place — no shutdown signal,+ /// no draining, no offset commit — as an OOM-kill would.+ fn crash_consumer(&mut self) {+ if let Some(task) = self.task.take() {+ task.abort();}}+ /// Start a fresh consumer stack — a new Kafka client in the same consumer+ /// group, plus new registry/dispatcher/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) {+ let worker_urls: Vec<String> = self.workers.iter().map(|w| w.url.clone()).collect();++ let registry = Arc::new(WorkerRegistry::new(&worker_urls, registry_config));+ Arc::clone(®istry).start_probing(self._probe_token.clone());+ let dispatcher = Arc::new(Dispatcher::new(Arc::clone(®istry)));+ let transport = Arc::new(HttpTransport::new(+ Duration::from_secs(5),+ 0,+ None,+ &worker_urls,+ 1,+ ));+ spawn_reaper(+ Arc::clone(®istry),+ Arc::clone(&transport),+ Arc::clone(&dispatcher),+ self._probe_token.clone(),+ );++ let mut manager = Manager::builder("e2e-test-restarted")+ .with_trap_signals(false)+ .build();+ let handle = manager.register("consumer", ComponentOptions::new());+ self.shutdown = handle.shutdown_token();++ let kafka_consumer = make_kafka_consumer(&self.topic, &self.group_id, None);+ let consumer = IngestionConsumer::from_parts(+ kafka_consumer,+ Arc::clone(&dispatcher),+ transport,+ worker_urls,+ IngestionConsumerOptions {+ batch_size: 50,+ batch_timeout: Duration::from_millis(100),+ max_in_flight_batches: self.max_in_flight,+ group_id: "e2e-test".to_string(),+ deferred_flush_timeout: self.deferred_flush_timeout,+ },+ handle,+ );++ self.registry = registry;+ self.dispatcher = dispatcher;+ self.task = Some(tokio::spawn(async move { consumer.process().await }));++ // Give the restarted consumer time to rejoin the group and start polling.+ tokio::time::sleep(Duration::from_millis(300)).await;+ }+/// Wait for the consumer's process loop to exit on its own (e.g. after it/// fails a batch), up to `timeout`. Returns true if it exited within the bound.async fn wait_for_consumer_exit(&mut self, timeout: Duration) -> bool {@@ -588,13 +788,17 @@ async fn draining_worker_takes_no_new_work_and_reroutes_in_order() {let drain_url = harness.workers[drain_idx].url.clone();harness.registry.start_draining(&drain_url);- // A draining worker is alive, not failed: its /_ready still returns 200, and- // the probe skips draining workers — it must never be declared dead.- tokio::time::sleep(Duration::from_millis(400)).await;- assert!(- !harness.registry.is_dead(&drain_url),- "a draining (but alive) worker must not be probed to death"- );+ // With the reaper running (as in production), an idle drainer is promptly+ // reaped — cleanly removed from the pool once its in-flight hits zero —+ // rather than lingering or being probed to death mid-drain.+ wait_until(Duration::from_secs(2), "idle drainer to be reaped", || {+ !harness+ .registry+ .workers()+ .iter()+ .any(|w| w.as_ref() == drain_url)+ })+ .await;// Batch 2: 4 more messages for user-1. The drainer takes no new work, so// these must route to the live worker, in order.@@ -1102,158 +1306,989 @@ async fn drain_defer_flush_delivers_to_survivor_over_http() {probe_token.cancel();}-// ── max_in_flight > 1 churn / invariant suite ────────────────────────────────-//-// At max_in_flight > 1 the consumer processes batches concurrently, so exact-// scenarios can't be scripted deterministically. These tests instead run a high-// volume across many distinct_ids while aggressively churning the worker pool,-// and assert the correctness INVARIANTS on the cross-worker delivery log:-// - exactly-once: every produced (distinct_id, seq) is delivered once — no-// loss, no duplication;-// - ordering: under graceful drain, each distinct_id's messages are delivered-// in Kafka order despite rerouting (a regression of the deferred-replay-// ordering shows up here as an out-of-order seq).-//-// Drain churn (the graceful-drain feature) preserves order, so it is asserted-// strictly. Send-failure churn falls back to at-least-once replay, which can-// interleave a failed-then-replayed message with a later same-key success on a-// flapping worker; those variants assert exactly-once but not strict order.--#[derive(Clone, Copy, Debug)]-enum Churn {- Drain,- Fail,- Mixed,-}--async fn sleep_or_cancel(token: &CancellationToken, ms: u64) -> bool {- tokio::select! {- _ = token.cancelled() => true,- _ = tokio::time::sleep(Duration::from_millis(ms)) => false,- }-}--/// Continuously churn the worker pool until cancelled, affecting one worker at a-/// time so the pool always keeps a healthy majority (progress is always-/// possible). Drain = leave/rejoin the pool (EndpointSlice-style); Fail = stay-/// ready but error sends (a crash mid-send). Restores all workers on exit.-fn spawn_churn(- harness: &Harness,- churn: Churn,- token: CancellationToken,-) -> tokio::task::JoinHandle<()> {- let registry = Arc::clone(&harness.registry);- let controls: Vec<(String, Arc<AtomicBool>)> = harness- .workers- .iter()- .map(|w| (w.url.clone(), Arc::clone(&w.ingest_ok)))- .collect();- tokio::spawn(async move {- let mut i = 0usize;- while !token.is_cancelled() {- let (url, ingest_ok) = &controls[i % controls.len()];- let drain = match churn {- Churn::Drain => true,- Churn::Fail => false,- Churn::Mixed => i.is_multiple_of(2),- };- if drain {- registry.start_draining(url);- if sleep_or_cancel(&token, 120).await {- break;- }- registry.add_worker(WorkerId::from(url.as_str()));- } else {- ingest_ok.store(false, Ordering::SeqCst);- if sleep_or_cancel(&token, 120).await {- break;- }- ingest_ok.store(true, Ordering::SeqCst);- }- // A gap with everyone healthy so the backlog can drain.- if sleep_or_cancel(&token, 80).await {- break;- }- i += 1;- }- for (url, ingest_ok) in &controls {- ingest_ok.store(true, Ordering::SeqCst);- registry.add_worker(WorkerId::from(url.as_str()));- }- })-}--async fn run_churn_suite(churn: Churn, max_in_flight: usize, strict_order: bool) {- let topic = format!("e2e-churn-{churn:?}-mif{max_in_flight}-{}", Uuid::new_v4());- let dids = 8usize;- let per_did = 60usize;- let total = dids * per_did;- let partitions = 4i32;+// ── 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).+#[tokio::test]+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(&topic,- partitions,- 4,- max_in_flight,+ 1,+ 2,+ 1,Duration::from_secs(60),fast_registry_config(),).await;let producer = make_producer();- let churn_token = CancellationToken::new();- let churn_handle = spawn_churn(&harness, churn, churn_token.clone());-- // Interleave distinct_ids so each Kafka batch mixes many keys.- for seq in 0..per_did {- for d in 0..dids {- produce(- &producer,- &topic,- (d as i32) % partitions,- "tok",- &format!("user-{d}"),- seq,- )- .await;- }+ // The whole pool drains before any message arrives.+ for w in &harness.workers {+ harness.registry.start_draining(&w.url);}- harness.wait_for(total, Duration::from_secs(90)).await;+ for seq in 0..4usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ }- // Quiesce churn so the final assertions see a settled log.- churn_token.cancel();- let _ = churn_handle.await;+ // Let the consumer collect and process the batch while nothing is routable.+ tokio::time::sleep(Duration::from_millis(800)).await;+ assert_eq!(+ harness.workers.iter().map(|w| w.count()).sum::<usize>(),+ 0,+ "nothing can be delivered while the whole pool is drained"+ );- let log = harness.delivery_log.lock().unwrap().clone();+ // One worker returns — the held messages must deliver to it, in order.+ harness+ .registry+ .add_worker(WorkerId::from(harness.workers[0].url.as_str()));+ harness.wait_for(4, Duration::from_secs(10)).await;assert_eq!(- log.len(),- total,- "exactly-once: expected {total} deliveries, got {}",- log.len()+ harness.workers[0].seqs_for("user-1"),+ vec![0, 1, 2, 3],+ "held messages must deliver in order once a worker returns");- let expected: Vec<usize> = (0..per_did).collect();- for d in 0..dids {- let did = format!("user-{d}");- let seqs: Vec<usize> = log- .iter()- .filter(|(id, _)| *id == did)- .map(|(_, s)| *s)- .collect();- let mut sorted = seqs.clone();- sorted.sort_unstable();- assert_eq!(- sorted, expected,- "{did}: messages lost or duplicated under {churn:?} churn: {seqs:?}"- );- if strict_order {- assert_eq!(- seqs, expected,- "{did}: messages delivered out of order under {churn:?} churn: {seqs:?}"- );- }+ harness.stop().await;+}++/// A worker that leaves the pool but never finishes its in-flight work is+/// force-reaped at the drain timeout — removed from the registry and transport+/// 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.+#[tokio::test]+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(&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();+ for w in &harness.workers {+ guards.push(Some(w.block().await));+ }++ // Batch 1 (seq 0–3) reaches its worker and is held in flight there.+ for seq in 0..4usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;}+ wait_until(Duration::from_secs(10), "batch to reach a worker", || {+ harness.workers.iter().any(|w| w.arrived_count() > 0)+ })+ .await;+ let pinned = sole_arrived_worker(&harness);+ let survivor = 1 - pinned;+ let pinned_url = harness.workers[pinned].url.clone();++ // The pinned worker leaves the pool while its batch is still in flight.+ harness.registry.start_draining(&pinned_url);++ // Batch 2 (seq 4–7) arrives while batch 1 is held → defers behind the drainer.+ for seq in 4..8usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ }+ wait_until(Duration::from_secs(10), "batch 2 to defer", || {+ harness.dispatcher.stashed_messages() > 0+ })+ .await;++ // The drain timeout passes with the batch still held → the reaper force-+ // removes the worker while its request is live.+ wait_until(+ Duration::from_secs(10),+ "the drainer to be force-reaped",+ || {+ !harness+ .registry+ .workers()+ .iter()+ .any(|w| w.as_ref() == pinned_url)+ },+ )+ .await;++ // Release everything: batch 1 completes on the (already removed) worker,+ // then batch 2 flushes to the survivor.+ guards.clear();+ harness.wait_for(8, Duration::from_secs(15)).await;++ assert_eq!(+ harness.workers[pinned].seqs_for("user-1"),+ vec![0, 1, 2, 3],+ "the reaped worker keeps exactly its in-flight batch"+ );+ assert_eq!(+ harness.workers[survivor].seqs_for("user-1"),+ vec![4, 5, 6, 7],+ "deferred messages re-route to the survivor in order"+ );++ harness.stop().await;+}++/// A consumer crash after a batch reached a worker but before its offsets were+/// committed must not lose anything: the restarted consumer resumes from the+/// last commit and redelivers. Duplicates are allowed (at-least-once); loss is+/// not.+#[tokio::test]+async fn consumer_crash_before_commit_redelivers_without_loss() {+ let topic = format!("e2e-restart-{}", Uuid::new_v4());+ let mut harness = Harness::start(+ &topic,+ 1,+ 2,+ 1,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;+ let producer = make_producer();++ // Hold both workers so the first batch is in flight but never ACKs — its+ // offsets are never committed.+ let mut guards: Vec<Option<tokio::sync::OwnedMutexGuard<()>>> = Vec::new();+ for w in &harness.workers {+ guards.push(Some(w.block().await));+ }++ for seq in 0..6usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ }+ wait_until(Duration::from_secs(10), "batch to reach a worker", || {+ harness.workers.iter().any(|w| w.arrived_count() > 0)+ })+ .await;++ // Crash the consumer mid-flight, then release the held requests. Whether+ // the worker ends up recording that first delivery is exactly the ambiguity+ // a restart must tolerate: duplicates allowed, loss not.+ harness.crash_consumer();+ guards.clear();++ harness.restart_consumer(fast_registry_config()).await;++ wait_until(+ Duration::from_secs(30),+ "every message to be redelivered after the crash",+ || {+ let delivered: HashSet<usize> = harness+ .workers+ .iter()+ .flat_map(|w| w.seqs_for("user-1"))+ .collect();+ (0..6).all(|seq| delivered.contains(&seq))+ },+ )+ .await;++ harness.stop().await;+}++/// A worker that processes a batch but whose ACK is lost is indistinguishable+/// 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.+#[tokio::test]+async fn lost_ack_after_processing_replays_without_loss() {+ let topic = format!("e2e-lost-ack-{}", Uuid::new_v4());+ let harness = Harness::start(+ &topic,+ 1,+ 2,+ 1,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;+ let producer = make_producer();++ // Arm both workers (the batch could land on either): the first /ingest each+ // receives is processed and recorded, but answered with an error.+ for w in &harness.workers {+ w.ack_lost_once.store(true, Ordering::SeqCst);+ }++ for seq in 0..4usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ }++ // Original delivery (recorded, ACK lost) + replay → 8 recorded entries.+ harness.wait_for(8, Duration::from_secs(15)).await;++ let log = harness.delivery_log.lock().unwrap().clone();+ let seqs: Vec<usize> = log+ .iter()+ .filter(|(did, _)| did.as_str() == "user-1")+ .map(|(_, s)| *s)+ .collect();+ assert!(+ seqs.len() > 4,+ "the lost ACK must force a replay (duplicates expected): {seqs:?}"+ );+ let mut seen = HashSet::new();+ let first_deliveries: Vec<usize> = seqs.iter().copied().filter(|s| seen.insert(*s)).collect();+ assert_eq!(+ first_deliveries,+ vec![0, 1, 2, 3],+ "no loss, and first deliveries in Kafka order: {seqs:?}"+ );++ harness.stop().await;+}++// ── Poison batches and contract violations ───────────────────────────────────++/// A batch every worker permanently rejects with a 4xx must fail the consumer+/// within the flush timeout — failing safe (nothing ingested, nothing+/// 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.+#[tokio::test]+async fn poison_batch_fails_safely_without_committing() {+ let topic = format!("e2e-poison-{}", Uuid::new_v4());+ let mut harness = Harness::start(+ &topic,+ 1,+ 2,+ 1,+ Duration::from_secs(2),+ fast_registry_config(),+ )+ .await;+ let producer = make_producer();++ for w in &harness.workers {+ w.reject_4xx.store(true, Ordering::SeqCst);+ }++ for seq in 0..4usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ }++ assert!(+ harness+ .wait_for_consumer_exit(Duration::from_secs(20))+ .await,+ "the consumer must fail the poison batch within the flush timeout"+ );+ assert_eq!(+ harness.workers.iter().map(|w| w.count()).sum::<usize>(),+ 0,+ "a rejected poison batch must not be partially ingested"+ );+}++/// A worker that ingests a batch but reports fewer accepted messages than were+/// 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.+#[tokio::test]+async fn partial_acceptance_fails_the_batch_without_commit() {+ let topic = format!("e2e-partial-accept-{}", Uuid::new_v4());+ let mut harness = Harness::start(+ &topic,+ 1,+ 2,+ 1,+ Duration::from_secs(2),+ fast_registry_config(),+ )+ .await;+ let producer = make_producer();++ for w in &harness.workers {+ w.underreport_once.store(true, Ordering::SeqCst);+ }++ for seq in 0..4usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ }++ assert!(+ harness+ .wait_for_consumer_exit(Duration::from_secs(20))+ .await,+ "an under-acknowledged batch must fail the consumer, not commit"+ );+ assert_eq!(+ harness.workers.iter().map(|w| w.count()).sum::<usize>(),+ 4,+ "the worker did ingest the batch — redelivery after restart may duplicate, never lose"+ );+}++// ── Drain edge cases and malformed input ─────────────────────────────────────++/// 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.+#[tokio::test]+async fn drainer_crash_mid_drain_replays_to_survivor_in_order() {+ let topic = format!("e2e-drain-crash-{}", Uuid::new_v4());+ let harness = Harness::start(+ &topic,+ 1,+ 2,+ 2,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;+ let producer = make_producer();++ let mut guards: Vec<Option<tokio::sync::OwnedMutexGuard<()>>> = Vec::new();+ for w in &harness.workers {+ guards.push(Some(w.block().await));+ }++ // Batch 1 (seq 0–3) is held in flight on its worker.+ for seq in 0..4usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ }+ wait_until(Duration::from_secs(10), "batch to reach a worker", || {+ harness.workers.iter().any(|w| w.arrived_count() > 0)+ })+ .await;+ let drainer = sole_arrived_worker(&harness);+ let survivor = 1 - drainer;++ // The worker begins draining; batch 2 (seq 4–7) defers behind it.+ harness+ .registry+ .start_draining(&harness.workers[drainer].url);+ for seq in 4..8usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ }+ wait_until(Duration::from_secs(10), "batch 2 to defer", || {+ harness.dispatcher.stashed_messages() > 0+ })+ .await;++ // The drainer crashes mid-drain: its held request fails instead of finishing.+ harness.workers[drainer]+ .healthy+ .store(false, Ordering::SeqCst);+ guards.clear();++ harness.wait_for(8, Duration::from_secs(15)).await;+ assert_eq!(+ harness.workers[drainer].count(),+ 0,+ "the crashed drainer ingested nothing"+ );+ assert_eq!(+ harness.workers[survivor].seqs_for("user-1"),+ (0..8).collect::<Vec<_>>(),+ "all work replays to the survivor in order"+ );++ harness.stop().await;+}++/// The whole pool failing at once with multiple keys in flight, at+/// max_in_flight > 1: everything is stashed while nothing is routable, then+/// drains to the first recovered worker with per-key order intact.+#[tokio::test]+async fn full_pool_send_failure_with_multiple_keys_recovers_in_order() {+ let topic = format!("e2e-pool-loss-{}", Uuid::new_v4());+ let harness = Harness::start(+ &topic,+ 2,+ 2,+ 3,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;+ let producer = make_producer();++ let mut guards: Vec<Option<tokio::sync::OwnedMutexGuard<()>>> = Vec::new();+ for w in &harness.workers {+ guards.push(Some(w.block().await));+ }++ // Two equal keys on two partitions bin-pack one per worker.+ for seq in 0..4usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ produce(&producer, &topic, 1, "tok", "user-2", seq).await;+ }+ wait_until(+ Duration::from_secs(10),+ "both workers to hold a sub-batch",+ || harness.workers.iter().all(|w| w.arrived_count() > 0),+ )+ .await;++ // The whole pool fails at once with work in flight — everything must be+ // stashed, not lost, while nothing is routable.+ for w in &harness.workers {+ w.healthy.store(false, Ordering::SeqCst);+ }+ guards.clear();+ wait_until(+ Duration::from_secs(10),+ "all failed work to be stashed",+ || harness.dispatcher.stashed_messages() == 8,+ )+ .await;++ // One worker recovers → everything drains to it, per-key order intact.+ harness.workers[1].healthy.store(true, Ordering::SeqCst);+ harness.wait_for(8, Duration::from_secs(15)).await;++ assert_eq!(+ harness.workers[0].count(),+ 0,+ "the still-dead worker recorded nothing"+ );+ for user in ["user-1", "user-2"] {+ assert_eq!(+ harness.workers[1].seqs_for(user),+ (0..4).collect::<Vec<_>>(),+ "{user} must drain to the recovered worker in order"+ );+ }++ harness.stop().await;+}++/// Messages without token/distinct_id headers route under synthetic+/// per-message keys; a send failure must replay them exactly once, like any+/// other message.+#[tokio::test]+async fn headerless_messages_survive_send_failure_replay() {+ let topic = format!("e2e-headerless-{}", Uuid::new_v4());+ let harness = Harness::start(+ &topic,+ 1,+ 2,+ 1,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;+ let producer = make_producer();++ // Take worker 1 out so the batch lands on worker 0 as one sub-batch.+ harness.workers[1].healthy.store(false, Ordering::SeqCst);+ wait_until(+ Duration::from_secs(10),+ "worker 1 to leave the pool",+ || !in_pool(&harness, &harness.workers[1].url),+ )+ .await;++ let guard0 = harness.workers[0].block().await;+ for seq in 0..3usize {+ produce_raw(+ &producer,+ &topic,+ 0,+ &format!("k{seq}"),+ format!(r#"{{"seq":{seq}}}"#).as_bytes(),+ None,+ )+ .await;+ }+ wait_until(Duration::from_secs(10), "batch to reach worker 0", || {+ harness.workers[0].arrived_count() > 0+ })+ .await;++ // Fail worker 0 and recover worker 1 as the replay target.+ harness.workers[0].healthy.store(false, Ordering::SeqCst);+ harness.workers[1].healthy.store(true, Ordering::SeqCst);+ wait_until(+ Duration::from_secs(10),+ "worker 1 to rejoin the pool",+ || in_pool(&harness, &harness.workers[1].url),+ )+ .await;+ drop(guard0);++ harness.wait_for(3, Duration::from_secs(15)).await;+ assert_eq!(+ harness.workers[0].count(),+ 0,+ "failed worker recorded nothing"+ );+ // Headerless messages record under an empty distinct_id; all three must+ // replay exactly once (order across distinct synthetic keys is undefined).+ let mut seqs = harness.workers[1].seqs_for("");+ seqs.sort_unstable();+ assert_eq!(+ seqs,+ vec![0, 1, 2],+ "headerless messages must replay exactly once"+ );++ harness.stop().await;+}++/// 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.+#[tokio::test]+async fn non_utf8_payload_is_delivered_not_lost() {+ let topic = format!("e2e-non-utf8-{}", Uuid::new_v4());+ let harness = Harness::start(+ &topic,+ 1,+ 1,+ 1,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;+ let producer = make_producer();++ let headers = OwnedHeaders::new()+ .insert(Header {+ key: "token",+ value: Some("tok"),+ })+ .insert(Header {+ key: "distinct_id",+ value: Some("user-1"),+ });+ // 0xF0 0x28 0x8C 0x28 is invalid UTF-8.+ produce_raw(+ &producer,+ &topic,+ 0,+ "k",+ &[0xF0, 0x28, 0x8C, 0x28],+ Some(headers),+ )+ .await;++ harness.wait_for(1, Duration::from_secs(10)).await;+ assert_eq!(+ harness.workers[0].seqs_for("user-1"),+ vec![0],+ "the event must arrive (with its body nulled) rather than be dropped"+ );++ harness.stop().await;+}++// ── Fleet redeploy and consumer-group membership ─────────────────────────────++/// 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.+#[tokio::test]+async fn fleet_redeploy_migrates_work_to_new_workers_without_loss() {+ let topic = format!("e2e-redeploy-{}", Uuid::new_v4());+ let mut harness = Harness::start(+ &topic,+ 2,+ 2,+ 2,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;+ let producer = make_producer();++ // Steady traffic on two keys lands on the old fleet.+ for seq in 0..10usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ produce(&producer, &topic, 1, "tok", "user-2", seq).await;+ }+ harness.wait_for(20, Duration::from_secs(15)).await;++ // The fleet is replaced wholesale.+ let new_a = FakeWorker::start_logged(Arc::clone(&harness.delivery_log)).await;+ let new_b = FakeWorker::start_logged(Arc::clone(&harness.delivery_log)).await;+ let desired: HashSet<WorkerId> = [new_a.url.as_str(), new_b.url.as_str()]+ .into_iter()+ .map(WorkerId::from)+ .collect();+ reconcile_membership(&harness.registry, &desired);+ let old_count = harness.workers.len();+ harness.workers.push(new_a);+ harness.workers.push(new_b);++ // Traffic continues through the switchover.+ for seq in 10..20usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ produce(&producer, &topic, 1, "tok", "user-2", seq).await;+ }+ harness.wait_for(40, Duration::from_secs(20)).await;++ // The old fleet is drained and reaped out of the pool entirely.+ wait_until(Duration::from_secs(5), "old workers to be reaped", || {+ harness.registry.worker_count() == 2+ })+ .await;++ // Exactly once, in per-key order, across the redeploy.+ let log = harness.delivery_log.lock().unwrap().clone();+ assert_eq!(log.len(), 40, "exactly-once across the redeploy");+ for user in ["user-1", "user-2"] {+ let seqs: Vec<usize> = log+ .iter()+ .filter(|(d, _)| d.as_str() == user)+ .map(|(_, s)| *s)+ .collect();+ assert_eq!(+ seqs,+ (0..20).collect::<Vec<_>>(),+ "{user} must stay in order across the redeploy: {seqs:?}"+ );+ }+ let new_fleet_received: usize = harness.workers[old_count..].iter().map(|w| w.count()).sum();+ assert!(+ new_fleet_received > 0,+ "the new fleet must take over the traffic"+ );++ harness.stop().await;+}++/// A second consumer joining the same group rebalances partitions away from+/// 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.+#[tokio::test]+async fn second_consumer_joining_the_group_preserves_all_messages() {+ let topic = format!("e2e-two-consumers-{}", Uuid::new_v4());+ let harness = Harness::start(+ &topic,+ 2,+ 2,+ 1,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;+ let producer = make_producer();++ // The first consumer owns both partitions and has an uncommitted batch+ // held in flight.+ let mut guards: Vec<Option<tokio::sync::OwnedMutexGuard<()>>> = Vec::new();+ for w in &harness.workers {+ guards.push(Some(w.block().await));+ }+ for seq in 0..5usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ produce(&producer, &topic, 1, "tok", "user-2", seq).await;+ }+ wait_until(Duration::from_secs(10), "work to reach a worker", || {+ harness.workers.iter().any(|w| w.arrived_count() > 0)+ })+ .await;++ // A second consumer joins the same group with its own routing stack but+ // the same worker pool.+ let worker_urls: Vec<String> = harness.workers.iter().map(|w| w.url.clone()).collect();+ let registry2 = Arc::new(WorkerRegistry::new(&worker_urls, fast_registry_config()));+ let probe2 = CancellationToken::new();+ Arc::clone(®istry2).start_probing(probe2.clone());+ let dispatcher2 = Arc::new(Dispatcher::new(Arc::clone(®istry2)));+ let transport2 = Arc::new(HttpTransport::new(+ Duration::from_secs(5),+ 0,+ None,+ &worker_urls,+ 1,+ ));+ let mut manager2 = Manager::builder("e2e-c2").with_trap_signals(false).build();+ let handle2 = manager2.register("consumer", ComponentOptions::new());+ let shutdown2 = handle2.shutdown_token();+ let consumer2 = IngestionConsumer::from_parts(+ make_kafka_consumer(&topic, &harness.group_id, None),+ dispatcher2,+ transport2,+ worker_urls,+ IngestionConsumerOptions {+ batch_size: 50,+ batch_timeout: Duration::from_millis(100),+ max_in_flight_batches: 1,+ group_id: "e2e-test".to_string(),+ deferred_flush_timeout: Duration::from_secs(60),+ },+ handle2,+ );+ let task2 = tokio::spawn(async move { consumer2.process().await });++ // Release the held batch so the first consumer resumes polling and the+ // rebalance can complete, then keep traffic flowing on both partitions.+ guards.clear();+ tokio::time::sleep(Duration::from_secs(2)).await;+ for seq in 5..10usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ produce(&producer, &topic, 1, "tok", "user-2", seq).await;+ }++ wait_until(+ Duration::from_secs(30),+ "every message to be delivered at least once across the rebalance",+ || {+ ["user-1", "user-2"].iter().all(|user| {+ let delivered: HashSet<usize> = harness+ .workers+ .iter()+ .flat_map(|w| w.seqs_for(user))+ .collect();+ (0..10).all(|s| delivered.contains(&s))+ })+ },+ )+ .await;++ shutdown2.cancel();+ let _ = tokio::time::timeout(Duration::from_secs(3), task2).await;+ probe2.cancel();+ harness.stop().await;+}++/// A same-name pod restart racing its old instance: a second member joins with+/// 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.+#[tokio::test]+async fn fenced_static_member_exits_on_fatal_error() {+ let topic = format!("e2e-fenced-{}", Uuid::new_v4());+ create_topic(&topic, 1).await;++ let worker = FakeWorker::start().await;+ let urls = vec![worker.url.clone()];+ let registry = Arc::new(WorkerRegistry::new(&urls, fast_registry_config()));+ let probe = CancellationToken::new();+ Arc::clone(®istry).start_probing(probe.clone());+ let dispatcher = Arc::new(Dispatcher::new(Arc::clone(®istry)));+ let transport = Arc::new(HttpTransport::new(+ Duration::from_secs(5),+ 0,+ None,+ &urls,+ 1,+ ));+ let mut manager = Manager::builder("e2e-fenced")+ .with_trap_signals(false)+ .build();+ let handle = manager.register("consumer", ComponentOptions::new());+ let group = format!("e2e-{}", Uuid::new_v4());+ let consumer = IngestionConsumer::from_parts(+ make_kafka_consumer(&topic, &group, Some("pod-1")),+ dispatcher,+ transport,+ urls,+ IngestionConsumerOptions {+ batch_size: 50,+ batch_timeout: Duration::from_millis(100),+ max_in_flight_batches: 1,+ group_id: "e2e-test".to_string(),+ deferred_flush_timeout: Duration::from_secs(60),+ },+ handle,+ );+ let task = tokio::spawn(async move { consumer.process().await });++ // Prove the first instance is consuming before it gets fenced.+ let producer = make_producer();+ produce(&producer, &topic, 0, "tok", "user-1", 0).await;+ wait_until(Duration::from_secs(10), "first instance to consume", || {+ worker.count() >= 1+ })+ .await;++ // The usurper joins with the SAME instance id; polling drives the join.+ let usurper = make_kafka_consumer(&topic, &group, Some("pod-1"));+ let usurper_task = tokio::spawn(async move {+ let mut stream = usurper.stream();+ let _ = tokio::time::timeout(Duration::from_secs(30), stream.next()).await;+ });++ let exited = tokio::time::timeout(Duration::from_secs(30), task)+ .await+ .is_ok();+ assert!(+ exited,+ "the fenced instance must exit with a fatal error, not keep polling a dead client"+ );++ usurper_task.abort();+ probe.cancel();+}++// ── max_in_flight > 1 churn / invariant suite ────────────────────────────────+//+// At max_in_flight > 1 the consumer processes batches concurrently, so exact+// scenarios can't be scripted deterministically. These tests instead run a high+// volume across many distinct_ids while aggressively churning the worker pool,+// and assert the correctness INVARIANTS on the cross-worker delivery log:+// - exactly-once: every produced (distinct_id, seq) is delivered once — no+// loss, no duplication;+// - ordering: under graceful drain, each distinct_id's messages are delivered+// in Kafka order despite rerouting (a regression of the deferred-replay+// ordering shows up here as an out-of-order seq).+//+// Drain churn (the graceful-drain feature) preserves order, so it is asserted+// strictly. Send-failure churn falls back to at-least-once replay, which can+// interleave a failed-then-replayed message with a later same-key success on a+// flapping worker; those variants assert exactly-once but not strict order.++#[derive(Clone, Copy, Debug)]+enum Churn {+ Drain,+ Fail,+ Mixed,+}++async fn sleep_or_cancel(token: &CancellationToken, ms: u64) -> bool {+ tokio::select! {+ _ = token.cancelled() => true,+ _ = tokio::time::sleep(Duration::from_millis(ms)) => false,+ }+}++/// Continuously churn the worker pool until cancelled, affecting one worker at a+/// time so the pool always keeps a healthy majority (progress is always+/// possible). Drain = leave/rejoin the pool (EndpointSlice-style); Fail = stay+/// ready but error sends (a crash mid-send). Restores all workers on exit.+fn spawn_churn(+ harness: &Harness,+ churn: Churn,+ token: CancellationToken,+) -> tokio::task::JoinHandle<()> {+ let registry = Arc::clone(&harness.registry);+ let controls: Vec<(String, Arc<AtomicBool>)> = harness+ .workers+ .iter()+ .map(|w| (w.url.clone(), Arc::clone(&w.ingest_ok)))+ .collect();+ tokio::spawn(async move {+ let mut i = 0usize;+ while !token.is_cancelled() {+ let (url, ingest_ok) = &controls[i % controls.len()];+ let drain = match churn {+ Churn::Drain => true,+ Churn::Fail => false,+ Churn::Mixed => i.is_multiple_of(2),+ };+ if drain {+ registry.start_draining(url);+ if sleep_or_cancel(&token, 120).await {+ break;+ }+ registry.add_worker(WorkerId::from(url.as_str()));+ } else {+ ingest_ok.store(false, Ordering::SeqCst);+ if sleep_or_cancel(&token, 120).await {+ break;+ }+ ingest_ok.store(true, Ordering::SeqCst);+ }+ // A gap with everyone healthy so the backlog can drain.+ if sleep_or_cancel(&token, 80).await {+ break;+ }+ i += 1;+ }+ for (url, ingest_ok) in &controls {+ ingest_ok.store(true, Ordering::SeqCst);+ registry.add_worker(WorkerId::from(url.as_str()));+ }+ })+}++async fn run_churn_suite(churn: Churn, max_in_flight: usize, strict_order: bool) {+ let topic = format!("e2e-churn-{churn:?}-mif{max_in_flight}-{}", Uuid::new_v4());+ let dids = 8usize;+ let per_did = 60usize;+ let total = dids * per_did;+ let partitions = 4i32;++ let harness = Harness::start(+ &topic,+ partitions,+ 4,+ max_in_flight,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;+ let producer = make_producer();++ let churn_token = CancellationToken::new();+ let churn_handle = spawn_churn(&harness, churn, churn_token.clone());++ // Interleave distinct_ids so each Kafka batch mixes many keys.+ for seq in 0..per_did {+ for d in 0..dids {+ produce(+ &producer,+ &topic,+ (d as i32) % partitions,+ "tok",+ &format!("user-{d}"),+ seq,+ )+ .await;+ }+ }++ harness.wait_for(total, Duration::from_secs(90)).await;++ // Quiesce churn so the final assertions see a settled log.+ churn_token.cancel();+ let _ = churn_handle.await;++ let log = harness.delivery_log.lock().unwrap().clone();+ assert_eq!(+ log.len(),+ total,+ "exactly-once: expected {total} deliveries, got {}",+ log.len()+ );++ let expected: Vec<usize> = (0..per_did).collect();+ for d in 0..dids {+ let did = format!("user-{d}");+ let seqs: Vec<usize> = log+ .iter()+ .filter(|(id, _)| *id == did)+ .map(|(_, s)| *s)+ .collect();+ let mut sorted = seqs.clone();+ sorted.sort_unstable();+ assert_eq!(+ sorted, expected,+ "{did}: messages lost or duplicated under {churn:?} churn: {seqs:?}"+ );+ if strict_order {+ assert_eq!(+ seqs, expected,+ "{did}: messages delivered out of order under {churn:?} churn: {seqs:?}"+ );+ }+ }++ // 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).+ wait_until(+ Duration::from_secs(10),+ "dispatcher pins/in-flight/stash to drain to zero after churn",+ || {+ harness.dispatcher.stashed_messages() == 0+ && harness.dispatcher.pin_count() == 0+ && harness.dispatcher.total_in_flight() == 0+ },+ )+ .await;harness.stop().await;}