:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ingestion-consumer): send sub-batches over ordered gRPC lanes (#85238)
José Sequeiradcbb613b4ea4
diff --git a/.github/workflows/ci-nodejs.yml b/.github/workflows/ci-nodejs.ymlindex b93be440db89..c29da0b43010 100644--- a/.github/workflows/ci-nodejs.yml+++ b/.github/workflows/ci-nodejs.yml@@ -770,6 +770,10 @@ jobs:- name: Build Node.js workspace dependenciesrun: bin/turbo --filter=@posthog/nodejs prepare+ # ingestion-consumer depends on ingestion-worker-proto, whose build script runs protoc.+ - name: Install protoc+ uses: ./.github/actions/setup-protoc+- name: Pre-build Rust ingestion consumerworking-directory: rustrun: cargo build -p ingestion-consumerdiff --git a/nodejs/src/common/generated/ingestion-worker/ingestion/worker/v1/worker_pb.ts b/nodejs/src/common/generated/ingestion-worker/ingestion/worker/v1/worker_pb.tsindex 067f69e671fa..78d462dd1d1d 100644--- a/nodejs/src/common/generated/ingestion-worker/ingestion/worker/v1/worker_pb.ts+++ b/nodejs/src/common/generated/ingestion-worker/ingestion/worker/v1/worker_pb.ts@@ -10,7 +10,7 @@ import { enumDesc, fileDesc, messageDesc, serviceDesc } from '@bufbuild/protobufexport const file_ingestion_worker_v1_worker: GenFile =/*@__PURE__*/fileDesc(- 'CiBpbmdlc3Rpb24vd29ya2VyL3YxL3dvcmtlci5wcm90bxITaW5nZXN0aW9uLndvcmtlci52MSKDAQoTSW5nZXN0U3RyZWFtUmVxdWVzdBIxCgVoZWxsbxgBIAEoCzIgLmluZ2VzdGlvbi53b3JrZXIudjEuU3RyZWFtSGVsbG9IABIyCglzdWJfYmF0Y2gYAiABKAsyHS5pbmdlc3Rpb24ud29ya2VyLnYxLlN1YkJhdGNoSABCBQoDbXNnIjgKC1N0cmVhbUhlbGxvEhMKC2NvbnN1bWVyX2lkGAEgASgJEhQKDHN0cmVhbV9lcG9jaBgCIAEoBCKIAQoIU3ViQmF0Y2gSCwoDc2VxGAEgASgEEhAKCGJhdGNoX2lkGAIgASgJEjMKCG1lc3NhZ2VzGAMgAygLMiEuaW5nZXN0aW9uLndvcmtlci52MS5LYWZrYU1lc3NhZ2USDgoGcmVwbGF5GAQgASgIEhgKEGFzc2lnbm1lbnRfZXBvY2gYBSABKAQi/AEKDEthZmthTWVzc2FnZRINCgV0b3BpYxgBIAEoCRIRCglwYXJ0aXRpb24YAiABKAUSDgoGb2Zmc2V0GAMgASgDEhEKCXRpbWVzdGFtcBgEIAEoAxIQCgNrZXkYBSABKAlIAIgBARISCgV2YWx1ZRgGIAEoCUgBiAEBEj8KB2hlYWRlcnMYByADKAsyLi5pbmdlc3Rpb24ud29ya2VyLnYxLkthZmthTWVzc2FnZS5IZWFkZXJzRW50cnkaLgoMSGVhZGVyc0VudHJ5EgsKA2tleRgBIAEoCRINCgV2YWx1ZRgCIAEoCToCOAFCBgoEX2tleUIICgZfdmFsdWUigQEKFEluZ2VzdFN0cmVhbVJlc3BvbnNlEjEKBXJlYWR5GAEgASgLMiAuaW5nZXN0aW9uLndvcmtlci52MS5TdHJlYW1SZWFkeUgAEi8KA2FjaxgCIAEoCzIgLmluZ2VzdGlvbi53b3JrZXIudjEuU3ViQmF0Y2hBY2tIAEIFCgNtc2ciDQoLU3RyZWFtUmVhZHkicAoLU3ViQmF0Y2hBY2sSCwoDc2VxGAEgASgEEjMKBnN0YXR1cxgCIAEoDjIjLmluZ2VzdGlvbi53b3JrZXIudjEuU3ViQmF0Y2hTdGF0dXMSEAoIYWNjZXB0ZWQYAyABKA0SDQoFZXJyb3IYBCABKAkqaAoOU3ViQmF0Y2hTdGF0dXMSIAocU1VCX0JBVENIX1NUQVRVU19VTlNQRUNJRklFRBAAEhcKE1NVQl9CQVRDSF9TVEFUVVNfT0sQARIbChdTVUJfQkFUQ0hfU1RBVFVTX0ZBSUxFRBACMncKDFdvcmtlckluZ2VzdBJnCgxJbmdlc3RTdHJlYW0SKC5pbmdlc3Rpb24ud29ya2VyLnYxLkluZ2VzdFN0cmVhbVJlcXVlc3QaKS5pbmdlc3Rpb24ud29ya2VyLnYxLkluZ2VzdFN0cmVhbVJlc3BvbnNlKAEwAWIGcHJvdG8z'+ 'CiBpbmdlc3Rpb24vd29ya2VyL3YxL3dvcmtlci5wcm90bxITaW5nZXN0aW9uLndvcmtlci52MSKDAQoTSW5nZXN0U3RyZWFtUmVxdWVzdBIxCgVoZWxsbxgBIAEoCzIgLmluZ2VzdGlvbi53b3JrZXIudjEuU3RyZWFtSGVsbG9IABIyCglzdWJfYmF0Y2gYAiABKAsyHS5pbmdlc3Rpb24ud29ya2VyLnYxLlN1YkJhdGNoSABCBQoDbXNnIjgKC1N0cmVhbUhlbGxvEhMKC2NvbnN1bWVyX2lkGAEgASgJEhQKDHN0cmVhbV9lcG9jaBgCIAEoBCKIAQoIU3ViQmF0Y2gSCwoDc2VxGAEgASgEEhAKCGJhdGNoX2lkGAIgASgJEjMKCG1lc3NhZ2VzGAMgAygLMiEuaW5nZXN0aW9uLndvcmtlci52MS5LYWZrYU1lc3NhZ2USDgoGcmVwbGF5GAQgASgIEhgKEGFzc2lnbm1lbnRfZXBvY2gYBSABKAQi/AEKDEthZmthTWVzc2FnZRINCgV0b3BpYxgBIAEoCRIRCglwYXJ0aXRpb24YAiABKAUSDgoGb2Zmc2V0GAMgASgDEhEKCXRpbWVzdGFtcBgEIAEoAxIQCgNrZXkYBSABKAlIAIgBARISCgV2YWx1ZRgGIAEoCUgBiAEBEj8KB2hlYWRlcnMYByADKAsyLi5pbmdlc3Rpb24ud29ya2VyLnYxLkthZmthTWVzc2FnZS5IZWFkZXJzRW50cnkaLgoMSGVhZGVyc0VudHJ5EgsKA2tleRgBIAEoCRINCgV2YWx1ZRgCIAEoCToCOAFCBgoEX2tleUIICgZfdmFsdWUigQEKFEluZ2VzdFN0cmVhbVJlc3BvbnNlEjEKBXJlYWR5GAEgASgLMiAuaW5nZXN0aW9uLndvcmtlci52MS5TdHJlYW1SZWFkeUgAEi8KA2FjaxgCIAEoCzIgLmluZ2VzdGlvbi53b3JrZXIudjEuU3ViQmF0Y2hBY2tIAEIFCgNtc2ciDQoLU3RyZWFtUmVhZHkicAoLU3ViQmF0Y2hBY2sSCwoDc2VxGAEgASgEEjMKBnN0YXR1cxgCIAEoDjIjLmluZ2VzdGlvbi53b3JrZXIudjEuU3ViQmF0Y2hTdGF0dXMSEAoIYWNjZXB0ZWQYAyABKA0SDQoFZXJyb3IYBCABKAkqgwEKDlN1YkJhdGNoU3RhdHVzEiAKHFNVQl9CQVRDSF9TVEFUVVNfVU5TUEVDSUZJRUQQABIXChNTVUJfQkFUQ0hfU1RBVFVTX09LEAESGwoXU1VCX0JBVENIX1NUQVRVU19GQUlMRUQQAhIZChVTVUJfQkFUQ0hfU1RBVFVTX0JVU1kQAzJ3CgxXb3JrZXJJbmdlc3QSZwoMSW5nZXN0U3RyZWFtEiguaW5nZXN0aW9uLndvcmtlci52MS5Jbmdlc3RTdHJlYW1SZXF1ZXN0GikuaW5nZXN0aW9uLndvcmtlci52MS5Jbmdlc3RTdHJlYW1SZXNwb25zZSgBMAFiBnByb3RvMw')/**@@ -309,6 +309,17 @@ export enum SubBatchStatus {* @generated from enum value: SUB_BATCH_STATUS_FAILED = 2;*/FAILED = 2,++ /**+ * The worker was momentarily at capacity and did not process the sub-batch.+ * This is transient backpressure, not a failure: the consumer replays the+ * sub-batch (in order) without treating the worker as broken. The consumer+ * treats any status it does not recognize the same way, so future non-fatal+ * statuses stay backward compatible.+ *+ * @generated from enum value: SUB_BATCH_STATUS_BUSY = 3;+ */+ BUSY = 3,}/**diff --git a/proto/ingestion/worker/v1/worker.proto b/proto/ingestion/worker/v1/worker.protoindex 99ece0acd775..bda91550a31e 100644--- a/proto/ingestion/worker/v1/worker.proto+++ b/proto/ingestion/worker/v1/worker.proto@@ -81,6 +81,12 @@ enum SubBatchStatus {// sub-batches may already carry the same routing keys, so per-key order on// this stream is unrecoverable.SUB_BATCH_STATUS_FAILED = 2;+ // The worker was momentarily at capacity and did not process the sub-batch.+ // This is transient backpressure, not a failure: the consumer replays the+ // sub-batch (in order) without treating the worker as broken. The consumer+ // treats any status it does not recognize the same way, so future non-fatal+ // statuses stay backward compatible.+ SUB_BATCH_STATUS_BUSY = 3;}// IngestStreamResponse is one frame on the worker-to-consumer stream.diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 177c0f85525f..10768e48226e 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -6009,6 +6009,7 @@ dependencies = ["envconfig","flate2","futures",+ "ingestion-worker-proto","k8s-awareness","kube","lifecycle",@@ -6022,7 +6023,9 @@ dependencies = ["serde_json","thiserror 2.0.18","tokio",+ "tokio-stream","tokio-util",+ "tonic 0.12.3","tower-http 0.5.2","tracing","tracing-subscriber",diff --git a/rust/ingestion-consumer/Cargo.toml b/rust/ingestion-consumer/Cargo.tomlindex dbe9aa244c5d..8efece40e62a 100644--- a/rust/ingestion-consumer/Cargo.toml+++ b/rust/ingestion-consumer/Cargo.toml@@ -13,6 +13,7 @@ dashmap = { workspace = true }envconfig = { workspace = true }flate2 = { workspace = true }futures = { workspace = true }+ingestion-worker-proto = { path = "../ingestion-worker-proto" }k8s-awareness = { path = "../common/k8s-awareness" }kube = { version = "0.98", features = ["client", "runtime"] }lifecycle = { path = "../common/lifecycle" }@@ -29,7 +30,9 @@ serde = { workspace = true }serde_json = { workspace = true }thiserror = { workspace = true }tokio = { workspace = true }+tokio-stream = { version = "0.1", features = ["net"] }tokio-util = { workspace = true }+tonic = { workspace = true }tracing = { workspace = true }tracing-subscriber = { workspace = true, features = ["env-filter", "json"] }diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rsindex a19a9df87e50..677175605238 100644--- a/rust/ingestion-consumer/src/config.rs+++ b/rust/ingestion-consumer/src/config.rs@@ -6,6 +6,7 @@ use tracing::info;use crate::discovery::DiscoveryMode;use crate::kafka_config::ConsumerConfigBuilder;use crate::routing::RoutingStrategy;+use crate::transports::TransportMode;/// Configuration for the ingestion consumer.///@@ -248,6 +249,35 @@ pub struct Config {#[envconfig(default = "")]pub internal_api_secret: String,+ /// How sub-batches reach the workers: `http` (concurrent POST /ingest+ /// requests) or `grpc` (one ordered WorkerIngest stream per worker, which+ /// closes the wire-reordering window concurrent HTTP requests leave open).+ /// The worker must serve the stream (`INGESTION_API_GRPC_ENABLED`) before+ /// a consumer switches to `grpc`.+ #[envconfig(from = "INGESTION_TRANSPORT", default = "http")]+ pub ingestion_transport: TransportMode,++ /// The worker pods' gRPC port (`INGESTION_API_GRPC_PORT` on the Node.js+ /// side). Worker streams derive each worker's stream address from its HTTP URL's+ /// host plus this port.+ #[envconfig(from = "INGESTION_WORKER_GRPC_PORT", default = "6739")]+ pub ingestion_worker_grpc_port: u16,++ /// When non-zero, override the fixed gRPC port: each worker's stream+ /// address becomes its HTTP port plus this offset. For single-host setups+ /// (local dev) where workers share an IP and differ only by port.+ #[envconfig(from = "INGESTION_WORKER_GRPC_PORT_OFFSET", default = "0")]+ pub ingestion_worker_grpc_port_offset: u16,++ /// Fence a worker stream (fail its un-acked and queued sub-batches into the+ /// deferral path, reconnect, re-route) when un-acked work sees no ack for+ /// this long (milliseconds). The stream has no per-send timeout, so this+ /// watchdog is what turns a worker that stops acking into a re-route+ /// instead of a silent forever-wait. Sized above the worst-case batch+ /// processing time, like the HTTP timeout it replaces.+ #[envconfig(from = "INGESTION_WORKER_STREAM_ACK_TIMEOUT_MS", default = "60000")]+ pub ingestion_worker_stream_ack_timeout_ms: u64,+// ---- Worker discovery ----/// How the worker pool is discovered: `static` (use WORKER_ADDRESSES — the/// co-located sidecar default) or `endpointslice` (watch a Kubernetesdiff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rsindex 5775753abbf3..1c1e58252e62 100644--- a/rust/ingestion-consumer/src/consumer.rs+++ b/rust/ingestion-consumer/src/consumer.rs@@ -16,10 +16,12 @@ use tracing::{error, info, warn};use crate::config::Config;use crate::debug_recorder::{record_if, DebugEventKind, DebugRecorder, PartitionOffset};use crate::discovery::DiscoveryMode;-use crate::dispatcher::{Dispatcher, EagerFlush, SubBatch};+use crate::dispatcher::{Dispatcher, EagerFlush, KeyOffset, SubBatch};use crate::order_sentinel::{CommitSentinel, OffsetSpan, SentinelContext};-use crate::transport::HttpTransport;+use crate::transport::SendError;+use crate::transports::{PendingSend, Transport};use crate::types::SerializedKafkaMessage;+use crate::worker_registry::WorkerId;/// Statistics gathered while collecting a batch, used to emit parity metrics.struct BatchStats {@@ -68,6 +70,16 @@ struct InFlightBatch {handle: JoinHandle<anyhow::Result<ProcessedBatch>>,}+/// A sub-batch whose send order is already established on its worker's stream+/// (`Transport::begin_send`), plus the metadata the resolve protocol needs.+struct PendingSubBatch {+ worker: WorkerId,+ routing_keys: Vec<String>,+ key_offsets: Vec<KeyOffset>,+ message_count: usize,+ pending: PendingSend,+}+/// Options for constructing an [`IngestionConsumer`] from pre-built parts./// Used in integration tests where the Kafka consumer is created externally.pub struct IngestionConsumerOptions {@@ -96,7 +108,7 @@ pub struct IngestionConsumerOptions {pub struct IngestionConsumer {consumer: Arc<StreamConsumer<SentinelContext>>,dispatcher: Arc<Dispatcher>,- transport: Arc<HttpTransport>,+ transport: Arc<Transport>,worker_urls: Vec<String>,batch_size: usize,batch_size_bytes: usize,@@ -120,7 +132,7 @@ impl IngestionConsumer {pub fn from_parts(consumer: StreamConsumer<SentinelContext>,dispatcher: Arc<Dispatcher>,- transport: Arc<HttpTransport>,+ transport: Arc<Transport>,worker_urls: Vec<String>,options: IngestionConsumerOptions,handle: Handle,@@ -149,7 +161,7 @@ impl IngestionConsumer {pub fn new(config: &Config,dispatcher: Arc<Dispatcher>,- transport: Arc<HttpTransport>,+ transport: Arc<Transport>,handle: Handle,debug_recorder: Option<Arc<DebugRecorder>>,) -> anyhow::Result<Self> {@@ -176,7 +188,10 @@ impl IngestionConsumer {commit_sentinel.set_enabled(config.consumer_order_sentinel_enabled);let key_sentinel = dispatcher.key_order_sentinel();key_sentinel.set_enabled(config.consumer_order_sentinel_enabled);- let context = SentinelContext::new(Arc::clone(&commit_sentinel), key_sentinel);+ let mut context = SentinelContext::new(Arc::clone(&commit_sentinel), key_sentinel);+ if let Transport::Grpc(grpc) = &*transport {+ context.set_assignment_epoch(grpc.assignment_epoch());+ }let consumer: StreamConsumer<SentinelContext> =client_config.create_with_context(context)?;consumer.subscribe(&[&config.ingestion_consumer_consume_topic])?;@@ -327,7 +342,15 @@ impl IngestionConsumer {});let assign_start = Instant::now();let messages = std::mem::take(&mut collected.messages);- let sub_batches = self.dispatcher.assign(&batch_id, messages);+ // Send order is established here too, still on the consumer loop and+ // under the dispatcher's lock: `begin_send` is synchronous, so a key's+ // sub-batches enter its worker's stream in assignment order — spawned+ // tasks racing to send would scramble it.+ let pending = self+ .dispatcher+ .assign_and_send(&batch_id, messages, |sub_batch| {+ Self::begin_send(&self.transport, &batch_id, sub_batch, false)+ });// Assignment serializes on the consumer loop (it no longer overlaps// batch collection) — watch this stays a small fraction of the batch// collection interval.@@ -336,7 +359,6 @@ impl IngestionConsumer {let task_batch_id = batch_id.clone();let dispatcher = Arc::clone(&self.dispatcher);- let transport = Arc::clone(&self.transport);let group_id = self.group_id.clone();let max_batch_size = self.batch_size;let max_batch_bytes = self.batch_size_bytes;@@ -344,11 +366,10 @@ impl IngestionConsumer {let handle = tokio::spawn(async move {Self::process_collected_batch(collected,- sub_batches,+ pending,batch_size,task_batch_id,dispatcher,- transport,group_id,max_batch_size,max_batch_bytes,@@ -464,8 +485,14 @@ impl IngestionConsumer {anyhow::bail!("deferred messages made no progress within the flush timeout");}let mut accepted_this_round = 0u32;- let sub_batches = self.dispatcher.flush_deferred(batch_id);- if sub_batches.is_empty() {+ // Serialized on the consumer loop, oldest batch first, so+ // begin_send order preserves the flush's key order.+ let pending = self+ .dispatcher+ .flush_deferred_and_send(batch_id, |sub_batch| {+ Self::begin_send(&self.transport, batch_id, sub_batch, true)+ });+ if pending.is_empty() {// Nothing routable right now (no healthy worker), or the// remaining work is in flight on the eager path — wait.tokio::select! {@@ -478,13 +505,7 @@ impl IngestionConsumer {}} else {accepted_this_round += self- .heartbeat_while(Self::scatter(- &self.dispatcher,- &self.transport,- batch_id,- sub_batches,- true,- ))+ .heartbeat_while(Self::scatter(&self.dispatcher, batch_id, pending, true)).await?;}// Eager-path acceptances count as progress too — a batch whose@@ -507,43 +528,45 @@ impl IngestionConsumer {/// Receive eagerly-released deferred groups from the dispatcher and send/// each on its own task. A send's resolution may release the key's next/// group, which arrives back on this channel — the chain advances at ACK- /// speed instead of batch-completion speed.+ /// speed instead of batch-completion speed. `begin_send` runs here, in+ /// channel-receive order, before the awaiting task spawns.async fn run_eager_flush_loop(dispatcher: Arc<Dispatcher>,- transport: Arc<HttpTransport>,+ transport: Arc<Transport>,mut rx: mpsc::UnboundedReceiver<EagerFlush>,) {while let Some(flush) = rx.recv().await {+ let EagerFlush {+ batch_id,+ sub_batch,+ } = flush;+ let pending = Self::begin_send(&transport, &batch_id, sub_batch, true);let dispatcher = Arc::clone(&dispatcher);- let transport = Arc::clone(&transport);tokio::spawn(async move {- Self::send_eager_flush(dispatcher, transport, flush).await;+ Self::send_eager_flush(dispatcher, batch_id, pending).await;});}}- /// Send one eagerly-released sub-batch, mirroring `scatter`'s resolve- /// protocol, and settle it in the owning batch's ledger. On failure the- /// messages re-stash under the owning batch (before the resolve, so the- /// pin survives) and the completion-time backstop retries them.+ /// Await one eagerly-released sub-batch send, mirroring `scatter`'s+ /// resolve protocol, and settle it in the owning batch's ledger. On+ /// failure the messages re-stash under the owning batch (before the+ /// resolve, so the pin survives) and the completion-time backstop retries+ /// them.async fn send_eager_flush(dispatcher: Arc<Dispatcher>,- transport: Arc<HttpTransport>,- flush: EagerFlush,+ batch_id: String,+ pending: PendingSubBatch,) {- let EagerFlush {- batch_id,- sub_batch,- } = flush;- let worker = sub_batch.worker.clone();- let routing_keys = sub_batch.routing_keys.clone();- let key_offsets = sub_batch.key_offsets.clone();- let message_count = sub_batch.messages.len();-- match transport- .send_batch(&worker, &batch_id, sub_batch.messages, true)- .await- {+ let PendingSubBatch {+ worker,+ routing_keys,+ key_offsets,+ message_count,+ pending,+ } = pending;++ match pending.wait().await {Ok(accepted) => {dispatcher.on_sub_batch_acked(&key_offsets);// Credit before the resolve: the resolve may hand the batch's@@ -565,10 +588,21 @@ impl IngestionConsumer {// across defer_failed (+1) and the clears_deferral resolve// (-1) the count nets to unchanged and never dips to zero —// newer batches keep deferring behind the re-stashed group.- dispatcher.defer_failed(&batch_id, send_err.messages);+ // A busy worker is backpressure, not a fault: re-route the work+ // but keep it off the worker's health, so passive health tracks+ // real faults.+ let SendError {+ error,+ messages,+ fence_guard,+ } = send_err;+ let is_fault = !error.is_backpressure();+ dispatcher.defer_failed(&batch_id, messages);+ // Stashed: let the worker stream stop fencing new arrivals.+ drop(fence_guard);dispatcher.eager_flush_failed(&batch_id);dispatcher.on_sub_batch_resolved(&worker, message_count, &routing_keys, true, true);- dispatcher.record_send_outcome(&worker, true);+ dispatcher.record_send_outcome(&worker, is_fault);}}}@@ -584,18 +618,44 @@ impl IngestionConsumer {.signal_failure(format!("Batch processing failed: {err:#}"));}- /// Scatter a batch's pre-assigned sub-batches to workers, gather results,- /// and feed passive health signals. Assignment already happened on the- /// consumer loop (see `spawn_batch_processing`); offset commits happen- /// later, in Kafka batch order, in `complete_oldest_batch`.+ /// Establish a sub-batch's send order. Synchronous and non-blocking on+ /// purpose: called where send order is decided (under the dispatcher's+ /// lock on the consumer loop, and in the eager flush loop), so a key's+ /// sub-batches enter its worker's stream in exactly that order.+ fn begin_send(+ transport: &Transport,+ batch_id: &str,+ sub_batch: SubBatch,+ replay: bool,+ ) -> PendingSubBatch {+ let SubBatch {+ worker,+ messages,+ routing_keys,+ key_offsets,+ } = sub_batch;+ let message_count = messages.len();+ let pending = transport.begin_send(&worker, batch_id, messages, replay);+ PendingSubBatch {+ worker,+ routing_keys,+ key_offsets,+ message_count,+ pending,+ }+ }++ /// Await a batch's pre-ordered sub-batch sends, gather results, and feed+ /// passive health signals. Assignment and send ordering already happened+ /// on the consumer loop (see `spawn_batch_processing`); offset commits+ /// happen later, in Kafka batch order, in `complete_oldest_batch`.#[allow(clippy::too_many_arguments)]async fn process_collected_batch(collected: CollectedBatch,- sub_batches: Vec<SubBatch>,+ pending: Vec<PendingSubBatch>,batch_size: usize,batch_id: String,dispatcher: Arc<Dispatcher>,- transport: Arc<HttpTransport>,group_id: String,max_batch_size: usize,max_batch_bytes: usize,@@ -651,13 +711,12 @@ impl IngestionConsumer {// Nothing to send and no flush-path activity (deferred, in-flight// eager, or already eagerly accepted) → no usable workers.- if sub_batches.is_empty() && !dispatcher.batch_has_flush_activity(&batch_id) {+ if pending.is_empty() && !dispatcher.batch_has_flush_activity(&batch_id) {counter!("ingestion_consumer_no_healthy_workers_total").increment(1);anyhow::bail!("No healthy workers available to route batch");}- let total_accepted =- Self::scatter(&dispatcher, &transport, &batch_id, sub_batches, false).await?;+ let total_accepted = Self::scatter(&dispatcher, &batch_id, pending, false).await?;Ok(ProcessedBatch {offsets: collected.offsets,@@ -668,37 +727,36 @@ impl IngestionConsumer {})}- /// Send sub-batches to workers in parallel and resolve each in the- /// dispatcher. On a send failure (the worker died mid-send), the failed- /// messages are deferred — before the resolve, so the pin isn't evicted —- /// to be replayed in order. Returns the number of messages accepted.+ /// 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. Returns the number of+ /// messages accepted.///- /// `from_flush` is true when sending sub-batches produced by `flush_deferred`:+ /// `from_flush` is true when awaiting sub-batches produced by `flush_deferred`:/// the resolve then clears one deferral per key, so a key stays deferring from/// when it was first held until its flushed messages actually land (preventing/// a newer batch from racing them).async fn scatter(dispatcher: &Arc<Dispatcher>,- transport: &Arc<HttpTransport>,batch_id: &str,- sub_batches: Vec<SubBatch>,+ pending: Vec<PendingSubBatch>,from_flush: bool,) -> anyhow::Result<u32> {- let mut handles = Vec::with_capacity(sub_batches.len());- for sub_batch in sub_batches {- let transport = Arc::clone(transport);+ let mut handles = Vec::with_capacity(pending.len());+ for sub_batch in pending {let dispatcher = Arc::clone(dispatcher);- let worker = sub_batch.worker.clone();+ let PendingSubBatch {+ worker,+ routing_keys,+ key_offsets,+ message_count,+ pending,+ } = sub_batch;let bid = batch_id.to_string();- let routing_keys = sub_batch.routing_keys.clone();- let key_offsets = sub_batch.key_offsets.clone();- let message_count = sub_batch.messages.len();handles.push(tokio::spawn(async move {- match transport- .send_batch(&worker, &bid, sub_batch.messages, from_flush)- .await- {+ match pending.wait().await {Ok(accepted) => {// Advance ACK high-water marks before the resolve, which// may evict the keys' sentinel state.@@ -720,7 +778,18 @@ impl IngestionConsumer {// with the `clears_deferral` decrement in the resolve, so the// outstanding count nets to unchanged (never dipping to zero)// and the key keeps deferring across the retry.- dispatcher.defer_failed(&bid, send_err.messages);+ // 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();+ dispatcher.defer_failed(&bid, messages);+ // Stashed: let the worker stream stop fencing new arrivals.+ drop(fence_guard);dispatcher.on_sub_batch_resolved(&worker,message_count,@@ -728,7 +797,7 @@ impl IngestionConsumer {from_flush,true,);- dispatcher.record_send_outcome(&worker, true);+ dispatcher.record_send_outcome(&worker, is_fault);0}}diff --git a/rust/ingestion-consumer/src/dispatcher.rs b/rust/ingestion-consumer/src/dispatcher.rsindex 9cd85fc0e8e7..f7e26366734d 100644--- a/rust/ingestion-consumer/src/dispatcher.rs+++ b/rust/ingestion-consumer/src/dispatcher.rs@@ -339,7 +339,34 @@ impl Dispatcher {/// the stash and are flushed later via [`Dispatcher::flush_deferred`].pub fn assign(&self, batch_id: &str, messages: Vec<SerializedKafkaMessage>) -> Vec<SubBatch> {let mut table = self.pin_table.lock().unwrap();+ self.assign_locked(&mut table, batch_id, messages)+ }++ /// Assign, then hand each sub-batch to `send` before releasing the pin+ /// table. A key admitted here because nothing of its is deferred must+ /// enter its worker stream before `defer_failed` 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.+ pub fn assign_and_send<T>(+ &self,+ batch_id: &str,+ messages: Vec<SerializedKafkaMessage>,+ send: impl FnMut(SubBatch) -> T,+ ) -> Vec<T> {+ let mut table = self.pin_table.lock().unwrap();+ self.assign_locked(&mut table, batch_id, messages)+ .into_iter()+ .map(send)+ .collect()+ }+ fn assign_locked(+ &self,+ table: &mut PinTable,+ batch_id: &str,+ messages: Vec<SerializedKafkaMessage>,+ ) -> Vec<SubBatch> {let GroupedMessages {groups: key_groups,missing_header_count,@@ -709,6 +736,24 @@ impl Dispatcher {/// the consumer flushes batches oldest-first.pub fn flush_deferred(&self, batch_id: &str) -> Vec<SubBatch> {let mut table = self.pin_table.lock().unwrap();+ self.flush_deferred_locked(&mut table, batch_id)+ }++ /// Flush, then hand each sub-batch to `send` before releasing the pin+ /// table, 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 table = self.pin_table.lock().unwrap();+ self.flush_deferred_locked(&mut table, batch_id)+ .into_iter()+ .map(send)+ .collect()+ }++ fn flush_deferred_locked(&self, table: &mut PinTable, batch_id: &str) -> Vec<SubBatch> {let groups = table.stash.take_batch(batch_id);if groups.is_empty() {return Vec::new();@@ -2393,6 +2438,44 @@ mod tests {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", 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.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);diff --git a/rust/ingestion-consumer/src/grpc_transport.rs b/rust/ingestion-consumer/src/grpc_transport.rsnew file mode 100644index 000000000000..ae21cc405b36--- /dev/null+++ b/rust/ingestion-consumer/src/grpc_transport.rs@@ -0,0 +1,861 @@+//! Ordered streaming transport: one `WorkerIngest` stream per worker.+//!+//! Each worker stream owns a bidirectional gRPC stream to its worker and drains an+//! ordered queue: enqueue order is send order is the worker's feed order,+//! which is the per-key ordering guarantee concurrent HTTP requests cannot+//! give. `begin_send` enqueues synchronously — call it where send order is+//! decided (the consumer loop, right after assignment) — and hands back a+//! [`PendingWorkerStreamSend`] the caller awaits like an HTTP response.+//!+//! **Acks resolve in send order.** The worker acks sub-batches as they+//! complete, out of order. The worker stream records each ack in its ledger and+//! resolves only the consecutive acked prefix, so a send never succeeds+//! while an earlier one is still open: if that earlier one then fails, the+//! later one is still in the ledger and fences with it, instead of having+//! already released its keys and left the older messages to replay after+//! the newer ones.+//!+//! **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.+//!+//! 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+//! the stream; queue depth is bounded in practice by the consumer's+//! `max_in_flight_batches`, whose batches cannot complete until their sends+//! resolve.++use std::collections::VecDeque;+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::Arc;+use std::time::Duration;++use dashmap::DashMap;+use ingestion_worker_proto::ingestion::worker::v1::worker_ingest_client::WorkerIngestClient;+use ingestion_worker_proto::ingestion::worker::v1::{+ ingest_stream_request, ingest_stream_response, IngestStreamRequest, IngestStreamResponse,+ KafkaMessage, StreamHello, SubBatch, SubBatchStatus,+};+use metrics::{counter, gauge};+use tokio::sync::{mpsc, oneshot};+use tokio_stream::wrappers::UnboundedReceiverStream;+use tracing::{error, info, warn};++use crate::readiness;+use crate::transport::{+ split_by_size, FenceGuard, SendError, TransportError, DEFAULT_MAX_BODY_BYTES,+};+use crate::types::SerializedKafkaMessage;++/// An acked chunk: the worker's accepted count, with the messages handed+/// back so a split send can reassemble the whole sub-batch on failure.+struct Accepted {+ accepted: u32,+ messages: Vec<SerializedKafkaMessage>,+}++type StreamReply = Result<Accepted, SendError>;++/// An enqueued sub-batch awaiting its acks; resolves like an HTTP send. A+/// sub-batch over the size cap rides the stream as several consecutive+/// chunks, one receiver each.+pub struct PendingWorkerStreamSend {+ chunks: Vec<oneshot::Receiver<StreamReply>>,+}++impl PendingWorkerStreamSend {+ /// All-or-nothing, like `HttpTransport::send_batch`: `Ok` only when every+ /// chunk was accepted; on any failure the `SendError` carries back the+ /// full original message set, in order, so the caller defers all of it.+ /// Already-accepted chunks then replay, which is ordinary at-least-once.+ pub async fn wait(self) -> Result<u32, SendError> {+ let mut accepted_total = 0u32;+ let mut messages: Vec<SerializedKafkaMessage> = Vec::new();+ let mut failure: Option<SendError> = None;+ for rx in self.chunks {+ let reply = match rx.await {+ Ok(reply) => reply,+ // The worker stream task died without resolving its items — a+ // bug, not an operational failure. The messages are gone, so+ // the batch cannot reach its accepted total and the consumer+ // exits and replays.+ Err(_) => Err(SendError {+ error: TransportError::WorkerStreamClosed,+ messages: Vec::new(),+ fence_guard: None,+ }),+ };+ match reply {+ Ok(accepted) => {+ accepted_total += accepted.accepted;+ messages.extend(accepted.messages);+ }+ Err(mut err) => {+ 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.+ Some(first) => match (&mut first.fence_guard, err.fence_guard.take()) {+ (Some(guard), Some(other)) => guard.merge(other),+ (slot @ None, other) => *slot = other,+ (Some(_), None) => {}+ },+ None => failure = Some(err),+ }+ }+ }+ }+ match failure {+ None => Ok(accepted_total),+ Some(mut err) => {+ err.messages = messages;+ Err(err)+ }+ }+ }+}++struct WorkerStreamItem {+ batch_id: String,+ messages: Vec<SerializedKafkaMessage>,+ replay: bool,+ reply: oneshot::Sender<StreamReply>,+}++struct WorkerStream {+ tx: mpsc::UnboundedSender<WorkerStreamItem>,+}++/// How a worker's gRPC address is derived from its HTTP URL.+#[derive(Clone, Copy, Debug)]+pub enum GrpcPort {+ /// Every worker serves gRPC on this port — the production shape, where+ /// workers are distinct pod IPs sharing one containerPort.+ Fixed(u16),+ /// gRPC port = the worker URL's HTTP port plus this offset — for+ /// single-host setups (local dev, tests) where workers share an IP and+ /// differ only by port.+ OffsetFromHttp(u16),+}++/// Sends sub-batches over one ordered `WorkerIngest` stream per worker.+pub struct GrpcTransport {+ worker_streams: DashMap<String, Arc<WorkerStream>>,+ consumer_id: String,+ /// How each worker's stream address is derived from its HTTP URL.+ grpc_port: GrpcPort,+ /// Max un-acked sub-batches per worker stream (aligned with the worker's+ /// `concurrentBatches`, like the HTTP semaphore it replaces).+ max_unacked: usize,+ /// Fence the worker stream when un-acked work sees no ack for this long.+ ack_timeout: Duration,+ /// Bumped on Kafka partition assignment; stamped on every sub-batch so+ /// the worker sentinel rebaselines across rebalances.+ assignment_epoch: Arc<AtomicU64>,+ /// Readiness probing stays HTTP: workers always serve `/_ready`.+ probe_client: reqwest::Client,+ /// Cap on one frame's estimated size. A sub-batch over it is sent as+ /// consecutive chunks (see `begin_send`), so no frame crosses the worker's+ /// message limit — the HTTP body cap, applied per frame.+ max_body_bytes: usize,+}++impl GrpcTransport {+ pub fn new(grpc_port: GrpcPort, max_unacked: usize, ack_timeout: Duration) -> Self {+ assert!(max_unacked > 0, "max_unacked must be > 0");+ Self {+ worker_streams: DashMap::new(),+ consumer_id: make_consumer_id(),+ grpc_port,+ max_unacked,+ ack_timeout,+ max_body_bytes: DEFAULT_MAX_BODY_BYTES,+ assignment_epoch: Arc::new(AtomicU64::new(1)),+ probe_client: reqwest::Client::builder()+ .timeout(readiness::PROBE_TIMEOUT)+ .build()+ .expect("failed to create probe client"),+ }+ }++ /// Shared epoch counter; the consumer's rebalance context bumps it.+ pub fn assignment_epoch(&self) -> Arc<AtomicU64> {+ Arc::clone(&self.assignment_epoch)+ }++ /// Override the per-frame size cap. Call before the transport is shared.+ pub fn set_max_body_bytes(&mut self, bytes: usize) {+ assert!(bytes > 0, "max_body_bytes must be > 0");+ self.max_body_bytes = bytes;+ }++ /// Enqueue a sub-batch on the worker's stream. Synchronous on purpose: call+ /// in send order (the consumer loop / serialized flush paths) — the worker stream+ /// preserves enqueue order onto the stream.+ ///+ /// A sub-batch whose estimated size exceeds `max_body_bytes` goes on the+ /// stream as consecutive chunks, so one frame never crosses the worker's+ /// message limit. Consecutive chunks on one ordered stream keep the+ /// sub-batch's order, and the caller still sees one send.+ pub fn begin_send(+ &self,+ worker_url: &str,+ batch_id: &str,+ messages: Vec<SerializedKafkaMessage>,+ replay: bool,+ ) -> PendingWorkerStreamSend {+ let chunks = split_by_size(messages, self.max_body_bytes);+ if chunks.len() > 1 {+ counter!(+ "ingestion_consumer_transport_batch_splits_total",+ "reason" => "size_estimate"+ )+ .increment((chunks.len() - 1) as u64);+ }+ let stream = self.worker_stream_for(worker_url);+ let receivers = chunks+ .into_iter()+ .map(|messages| {+ let (reply, rx) = oneshot::channel();+ let item = WorkerStreamItem {+ batch_id: batch_id.to_string(),+ messages,+ replay,+ reply,+ };+ if let Err(send_err) = stream.tx.send(item) {+ // Worker stream task gone (removed worker): fail the send+ // immediately with its messages so the caller defers and+ // re-routes.+ let item = send_err.0;+ let _ = item.reply.send(Err(SendError {+ error: TransportError::WorkerStreamClosed,+ messages: item.messages,+ fence_guard: None,+ }));+ }+ rx+ })+ .collect();+ PendingWorkerStreamSend { chunks: receivers }+ }++ fn worker_stream_for(&self, worker_url: &str) -> Arc<WorkerStream> {+ if let Some(stream) = self.worker_streams.get(worker_url) {+ return stream.clone();+ }+ self.worker_streams+ .entry(worker_url.to_string())+ .or_insert_with(|| Arc::new(self.spawn_worker_stream(worker_url)))+ .clone()+ }++ fn spawn_worker_stream(&self, worker_url: &str) -> WorkerStream {+ let (tx, rx) = mpsc::unbounded_channel();+ let runner = WorkerStreamRunner {+ worker_url: Arc::from(worker_url),+ grpc_url: grpc_url(worker_url, self.grpc_port),+ consumer_id: self.consumer_id.clone(),+ max_unacked: self.max_unacked,+ ack_timeout: self.ack_timeout,+ assignment_epoch: Arc::clone(&self.assignment_epoch),+ };+ tokio::spawn(async move { runner.run(rx).await });+ WorkerStream { tx }+ }++ /// Tear down a departed worker's stream. Dropping it closes its queue+ /// sender, so the runner fences whatever is still in flight **in order**,+ /// with the messages intact, and exits on its own. Aborting the task would+ /// instead drop the un-acked sends unresolved, which the caller can only+ /// recover by crashing and replaying — so let the graceful path run.+ pub fn remove_worker(&self, worker_url: &str) {+ self.worker_streams.remove(worker_url);+ }++ /// Check if a worker is ready by probing its HTTP health endpoint.+ pub async fn check_ready(&self, worker_url: &str) -> bool {+ readiness::check_ready(&self.probe_client, worker_url).await+ }++ /// Wait until all workers are ready, polling with backoff.+ pub async fn wait_for_workers_ready(+ &self,+ worker_urls: &[String],+ shutdown: &lifecycle::Handle,+ ) -> anyhow::Result<()> {+ readiness::wait_for_workers_ready(&self.probe_client, worker_urls, shutdown).await+ }+}++/// One un-acked sub-batch on the stream.+struct LedgerEntry {+ seq: u64,+ item: WorkerStreamItem,+ /// Per-send ack deadline, armed when the sub-batch went on the wire. The+ /// watchdog fences on the oldest entry's deadline, so a stuck sub-batch+ /// times out even while its siblings keep acking.+ deadline: tokio::time::Instant,+ /// The worker's accepted count once acked. The entry stays in the ledger+ /// until every earlier entry is acked too, so a fence still reaches it.+ acked: Option<u32>,+}++/// An open stream: the request sender and the worker's ack stream.+type OpenStream = (+ mpsc::UnboundedSender<IngestStreamRequest>,+ tonic::Streaming<IngestStreamResponse>,+);++/// One event off the ack stream: a frame, a clean end (`None`), or an error.+type AckEvent = Result<Option<IngestStreamResponse>, tonic::Status>;++struct WorkerStreamRunner {+ worker_url: Arc<str>,+ grpc_url: String,+ consumer_id: String,+ max_unacked: usize,+ ack_timeout: Duration,+ assignment_epoch: Arc<AtomicU64>,+}++impl WorkerStreamRunner {+ /// Worker stream lifecycle: connect, stream until something breaks, fence+ /// everything outstanding, reconnect. Ends when the transport drops the+ /// queue sender (worker removed or shutdown).+ async fn run(self, mut queue: mpsc::UnboundedReceiver<WorkerStreamItem>) {+ let mut stream_epoch = 0u64;+ let mut backoff = Duration::from_millis(100);+ loop {+ stream_epoch += 1;+ match self.run_stream(&mut queue, stream_epoch).await {+ StreamEnd::QueueClosed => {+ info!(worker = %self.worker_url, "Worker stream queue closed, exiting");+ return;+ }+ StreamEnd::Failed(fence) => {+ counter!(+ "ingestion_consumer_worker_stream_teardowns_total",+ "worker" => self.worker_url.clone(),+ )+ .increment(1);+ let fenced = fence.settle(&mut queue).await;+ if fenced > 0 {+ counter!(+ "ingestion_consumer_worker_stream_fenced_sub_batches_total",+ "worker" => self.worker_url.clone(),+ )+ .increment(fenced as u64);+ }+ tokio::time::sleep(jittered(backoff)).await;+ backoff = (backoff * 2).min(Duration::from_secs(5));+ }+ StreamEnd::Idle => {+ // Stream ended cleanly with nothing outstanding (e.g. the+ // worker restarted gracefully) — reconnect without delay+ // escalation.+ backoff = Duration::from_millis(100);+ }+ }+ }+ }++ /// Run one stream incarnation. Returns how it ended; on `Failed`, every+ /// queued and un-acked item has been resolved as failed, in order.+ async fn run_stream(+ &self,+ queue: &mut mpsc::UnboundedReceiver<WorkerStreamItem>,+ stream_epoch: u64,+ ) -> StreamEnd {+ // Hold sends until there is work: connecting eagerly on an idle worker stream+ // would spin reconnects against a worker that never gets traffic.+ let first = match queue.recv().await {+ Some(item) => item,+ None => return StreamEnd::QueueClosed,+ };++ let mut ledger: VecDeque<LedgerEntry> = VecDeque::new();+ let mut pending_first = Some(first);++ let (out_tx, mut acks) = match self.open_stream(stream_epoch).await {+ Ok(stream) => stream,+ Err(reason) => return self.fence(pending_first.take(), &mut ledger, queue, reason),+ };++ let mut next_seq = 1u64;+ gauge!("ingestion_consumer_worker_stream_ledger_depth", "worker" => self.worker_url.clone())+ .set(0.0);++ loop {+ if let Err(end) = self.fill_ledger(+ &out_tx,+ queue,+ &mut pending_first,+ &mut ledger,+ &mut next_seq,+ ) {+ return end;+ }+ let ack = match self+ .await_next_ack(&mut acks, queue, &mut pending_first, &mut ledger)+ .await+ {+ Ok(Some(ack)) => ack,+ Ok(None) => continue,+ Err(end) => return end,+ };+ if let Err(end) = self.handle_ack(ack, queue, &mut pending_first, &mut ledger) {+ return end;+ }+ }+ }++ /// Connect, greet, and open the ack stream. On failure the caller fences+ /// with the returned reason.+ async fn open_stream(&self, stream_epoch: u64) -> Result<OpenStream, &'static str> {+ // The inner connect_timeout bounds TCP only; the outer bound covers+ // everything else in connection setup (e.g. an h2 handshake that+ // never completes because the far side is not actually h2).+ let endpoint = match tonic::transport::Endpoint::from_shared(self.grpc_url.clone()) {+ Ok(endpoint) => endpoint.connect_timeout(Duration::from_secs(5)),+ Err(err) => {+ error!(worker = %self.worker_url, grpc_url = %self.grpc_url, error = %err, "Invalid worker stream address");+ return Err("invalid address");+ }+ };+ let channel = match tokio::time::timeout(self.ack_timeout, endpoint.connect()).await {+ Ok(Ok(channel)) => channel,+ Ok(Err(err)) => {+ warn!(+ worker = %self.worker_url,+ grpc_url = %self.grpc_url,+ error = %err,+ "Worker stream connect failed"+ );+ return Err("connect failed");+ }+ Err(_) => {+ warn!(+ worker = %self.worker_url,+ grpc_url = %self.grpc_url,+ timeout_ms = self.ack_timeout.as_millis() as u64,+ "Worker stream connect timed out"+ );+ return Err("connect timeout");+ }+ };++ let mut client = WorkerIngestClient::new(channel)+ .send_compressed(tonic::codec::CompressionEncoding::Gzip)+ .accept_compressed(tonic::codec::CompressionEncoding::Gzip);++ let (out_tx, out_rx) = mpsc::unbounded_channel::<IngestStreamRequest>();+ let hello = IngestStreamRequest {+ msg: Some(ingest_stream_request::Msg::Hello(StreamHello {+ consumer_id: self.consumer_id.clone(),+ stream_epoch,+ })),+ };+ if out_tx.send(hello).is_err() {+ return Err("stream closed");+ }++ // Stream-open resolves only when the worker's response headers (its+ // greeting) arrive; bound it so a worker that never greets fences+ // instead of deadlocking the worker stream — the failure mode that wedged+ // production before the greeting existed.+ match tokio::time::timeout(+ self.ack_timeout,+ client.ingest_stream(UnboundedReceiverStream::new(out_rx)),+ )+ .await+ {+ Ok(Ok(response)) => Ok((out_tx, response.into_inner())),+ Err(_) => {+ warn!(+ worker = %self.worker_url,+ grpc_url = %self.grpc_url,+ timeout_ms = self.ack_timeout.as_millis() as u64,+ "Worker stream stream open timed out — no greeting from the worker"+ );+ Err("stream open timeout")+ }+ Ok(Err(status)) => {+ warn!(worker = %self.worker_url, grpc_url = %self.grpc_url, status = %status, "Worker stream stream open failed");+ Err("stream open failed")+ }+ }+ }++ /// Send the held first item, then pull more only while the ledger has+ /// room — the worker-aligned concurrency cap. `Err` ends the stream.+ fn fill_ledger(+ &self,+ out_tx: &mpsc::UnboundedSender<IngestStreamRequest>,+ queue: &mut mpsc::UnboundedReceiver<WorkerStreamItem>,+ pending_first: &mut Option<WorkerStreamItem>,+ ledger: &mut VecDeque<LedgerEntry>,+ next_seq: &mut u64,+ ) -> Result<(), StreamEnd> {+ while ledger.len() < self.max_unacked {+ let item = match pending_first.take() {+ Some(item) => Some(item),+ None => match queue.try_recv() {+ Ok(item) => Some(item),+ Err(mpsc::error::TryRecvError::Empty) => None,+ Err(mpsc::error::TryRecvError::Disconnected) => {+ return Err(if ledger.is_empty() {+ StreamEnd::QueueClosed+ } else {+ // Resolve the tail before exiting.+ self.fence(None, ledger, queue, "queue closed")+ });+ }+ },+ };+ let Some(item) = item else { break };+ let seq = *next_seq;+ *next_seq += 1;+ let request = IngestStreamRequest {+ msg: Some(ingest_stream_request::Msg::SubBatch(SubBatch {+ seq,+ batch_id: item.batch_id.clone(),+ messages: item.messages.iter().map(to_proto_message).collect(),+ replay: item.replay,+ assignment_epoch: self.assignment_epoch.load(Ordering::Relaxed),+ })),+ };+ let deadline = tokio::time::Instant::now() + self.ack_timeout;+ let sent = out_tx.send(request).is_ok();+ ledger.push_back(LedgerEntry {+ seq,+ item,+ deadline,+ acked: None,+ });+ if !sent {+ return Err(self.fence(None, ledger, queue, "stream closed mid-send"));+ }+ gauge!("ingestion_consumer_worker_stream_ledger_depth", "worker" => self.worker_url.clone())+ .set(ledger.len() as f64);+ }+ Ok(())+ }++ /// Wait for an ack, or for new work when the ledger has room. `Ok(None)`+ /// means new work was held in `pending_first`; `Err` ends the stream.+ ///+ /// The ack-progress watchdog bounds how long the oldest un-acked+ /// sub-batch may sit unacked. Each entry carries its own deadline, armed+ /// when it was sent, so the watchdog keys on the oldest (front) entry,+ /// which is never acked (acked prefixes pop at once): a stuck sub-batch+ /// fences even while its siblings keep acking — the per-send bound the+ /// HTTP timeout it replaces gave. A worker that stops acking (saturated+ /// by other consumers, wedged, half-dead network) becomes a fence — and+ /// so a defer-and-reroute — rather than a silent forever-wait.+ async fn await_next_ack(+ &self,+ acks: &mut tonic::Streaming<IngestStreamResponse>,+ queue: &mut mpsc::UnboundedReceiver<WorkerStreamItem>,+ pending_first: &mut Option<WorkerStreamItem>,+ ledger: &mut VecDeque<LedgerEntry>,+ ) -> Result<Option<AckEvent>, StreamEnd> {+ let Some(front) = ledger.front() else {+ return match queue.recv().await {+ Some(item) => {+ *pending_first = Some(item);+ Ok(None)+ }+ None => Err(StreamEnd::QueueClosed),+ };+ };+ let watchdog = tokio::time::sleep_until(front.deadline);+ tokio::select! {+ ack = acks.message() => Ok(Some(ack)),+ _ = watchdog => {+ warn!(+ worker = %self.worker_url,+ unacked = ledger.len(),+ timeout_ms = self.ack_timeout.as_millis() as u64,+ "No ack progress within the watchdog window — fencing worker stream"+ );+ Err(self.fence(pending_first.take(), ledger, queue, "ack progress timeout"))+ }+ item = queue.recv(), if ledger.len() < self.max_unacked => match item {+ Some(item) => {+ *pending_first = Some(item);+ Ok(None)+ }+ None => Err(self.fence(None, ledger, queue, "queue closed")),+ }+ }+ }++ /// Apply one ack-stream event to the ledger. `Err` ends the stream.+ fn handle_ack(+ &self,+ ack: AckEvent,+ queue: &mut mpsc::UnboundedReceiver<WorkerStreamItem>,+ pending_first: &mut Option<WorkerStreamItem>,+ ledger: &mut VecDeque<LedgerEntry>,+ ) -> Result<(), StreamEnd> {+ let frame = match ack {+ Ok(Some(frame)) => frame,+ Ok(None) => {+ return Err(if ledger.is_empty() && pending_first.is_none() {+ StreamEnd::Idle+ } else {+ self.fence(pending_first.take(), ledger, queue, "stream ended")+ });+ }+ Err(status) => {+ warn!(worker = %self.worker_url, status = %status, "Worker stream stream failed");+ return Err(self.fence(pending_first.take(), ledger, queue, "stream error"));+ }+ };+ // `ready` is the worker's greeting (and any future keepalive): it+ // exists to flush response headers, not to resolve work. A frame this+ // consumer predates is ignored the same way.+ let response = match frame.msg {+ Some(ingest_stream_response::Msg::Ack(ack)) => ack,+ Some(ingest_stream_response::Msg::Ready(_)) | None => return Ok(()),+ };+ if response.status == SubBatchStatus::Failed as i32 {+ warn!(+ worker = %self.worker_url,+ seq = response.seq,+ error = %response.error,+ "Worker nacked sub-batch — fencing worker stream"+ );+ return Err(self.fence(None, ledger, queue, "sub-batch nacked"));+ }+ if response.status != SubBatchStatus::Ok as i32 {+ // BUSY, or any status this consumer predates: transient+ // backpressure, not a fault. Fence in order (the ordered stream+ // cannot retry one sub-batch in place) but as retriable, so the+ // work re-routes without marking the worker unhealthy.+ warn!(+ worker = %self.worker_url,+ seq = response.seq,+ status = response.status,+ "Worker signalled busy — fencing worker stream as retriable"+ );+ return Err(self.fence_with(true, None, ledger, queue, "worker busy"));+ }+ let Some(entry) = ledger+ .iter_mut()+ .find(|e| e.seq == response.seq && e.acked.is_none())+ else {+ warn!(worker = %self.worker_url, seq = response.seq, "Ack for unknown seq — fencing worker stream");+ return Err(self.fence(None, ledger, queue, "unknown ack seq"));+ };+ entry.acked = Some(response.accepted);+ counter!(+ "ingestion_consumer_transport_requests_total",+ "worker" => self.worker_url.clone(),+ "status" => "ok"+ )+ .increment(1);+ // Resolve only the acked prefix: a later ack waits for every earlier+ // seq, so a failure ahead of it still fences it instead of letting it+ // release its keys first.+ while ledger.front().is_some_and(|e| e.acked.is_some()) {+ let entry = ledger.pop_front().expect("front is present");+ let accepted = entry.acked.expect("front is acked");+ let WorkerStreamItem {+ reply, messages, ..+ } = entry.item;+ let _ = reply.send(Ok(Accepted { accepted, messages }));+ }+ gauge!("ingestion_consumer_worker_stream_ledger_depth", "worker" => self.worker_url.clone())+ .set(ledger.len() as f64);+ Ok(())+ }++ /// 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.+ fn fence(+ &self,+ pending_first: Option<WorkerStreamItem>,+ ledger: &mut VecDeque<LedgerEntry>,+ queue: &mut mpsc::UnboundedReceiver<WorkerStreamItem>,+ reason: &'static str,+ ) -> StreamEnd {+ self.fence_with(false, pending_first, ledger, queue, reason)+ }++ /// `retriable` distinguishes transient backpressure (a busy worker) from a+ /// real fault: the fenced sends carry a retriable error so the caller+ /// re-routes them without counting the worker as unhealthy, and the metric+ /// records `busy` rather than `error`.+ fn fence_with(+ &self,+ retriable: bool,+ pending_first: Option<WorkerStreamItem>,+ ledger: &mut VecDeque<LedgerEntry>,+ queue: &mut mpsc::UnboundedReceiver<WorkerStreamItem>,+ reason: &'static str,+ ) -> StreamEnd {+ let mut fence = Fence::new(retriable, reason);+ for entry in ledger.drain(..) {+ fence.fail(entry.item);+ }+ if let Some(item) = pending_first {+ fence.fail(item);+ }+ while let Ok(item) = queue.try_recv() {+ fence.fail(item);+ }+ counter!(+ "ingestion_consumer_transport_requests_total",+ "worker" => self.worker_url.clone(),+ "status" => if retriable { "busy" } else { "error" }+ )+ .increment(1);+ gauge!("ingestion_consumer_worker_stream_ledger_depth", "worker" => self.worker_url.clone())+ .set(0.0);+ StreamEnd::Failed(fence)+ }+}++/// 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+/// stream ahead of them.+struct Fence {+ retriable: bool,+ reason: &'static str,+ released_tx: mpsc::UnboundedSender<()>,+ released_rx: mpsc::UnboundedReceiver<()>,+ /// Guards handed out and not yet dropped.+ outstanding: usize,+ fenced: usize,+}++impl Fence {+ fn new(retriable: bool, reason: &'static str) -> Self {+ let (released_tx, released_rx) = mpsc::unbounded_channel();+ Self {+ retriable,+ reason,+ released_tx,+ released_rx,+ outstanding: 0,+ fenced: 0,+ }+ }++ fn fail(&mut self, item: WorkerStreamItem) {+ let error = if self.retriable {+ TransportError::WorkerStreamBusy(self.reason)+ } else {+ TransportError::WorkerStreamFailed(self.reason)+ };+ self.outstanding += 1;+ self.fenced += 1;+ // A caller that already dropped its receiver drops the guard here,+ // which releases it at once.+ let _ = item.reply.send(Err(SendError {+ error,+ messages: item.messages,+ fence_guard: Some(FenceGuard::new(self.released_tx.clone())),+ }));+ }++ /// Fail arrivals until every fenced caller has dropped its guard. Returns+ /// how many sends the fence failed in total.+ async fn settle(mut self, queue: &mut mpsc::UnboundedReceiver<WorkerStreamItem>) -> usize {+ while self.outstanding > 0 {+ // Releases first: a caller drops its guard before it can enqueue+ // again, so a release already waiting must not lose to the send+ // that followed it and fence that send for nothing.+ tokio::select! {+ biased;+ released = self.released_rx.recv() => {+ if released.is_some() {+ self.outstanding -= 1;+ }+ }+ item = queue.recv() => match item {+ Some(item) => self.fail(item),+ // Queue closed: nothing more can arrive, and the runner+ // exits on its next receive.+ None => break,+ },+ }+ }+ self.fenced+ }+}++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.+ Failed(Fence),+ /// The stream ended cleanly with nothing outstanding.+ Idle,+}++fn to_proto_message(message: &SerializedKafkaMessage) -> KafkaMessage {+ KafkaMessage {+ topic: message.topic.clone(),+ partition: message.partition,+ offset: message.offset,+ timestamp: message.timestamp,+ key: message.key.clone(),+ value: message.value.clone(),+ headers: message.headers.clone(),+ }+}++/// Derive the worker's gRPC address from its HTTP URL: same host, gRPC port.+/// Worker URLs are `http://<host-or-ip>:<port>` (see `discovery::addr_to_worker`).+fn grpc_url(worker_url: &str, grpc_port: GrpcPort) -> String {+ let without_scheme = worker_url+ .strip_prefix("http://")+ .or_else(|| worker_url.strip_prefix("https://"))+ .unwrap_or(worker_url);+ let (host, http_port) = match without_scheme.rfind(':') {+ // Don't split inside an unbracketed IPv6 literal.+ Some(idx) if !without_scheme[idx + 1..].contains(']') => (+ &without_scheme[..idx],+ without_scheme[idx + 1..].parse::<u16>().unwrap_or(0),+ ),+ _ => (without_scheme, 0),+ };+ let port = match grpc_port {+ GrpcPort::Fixed(port) => port,+ GrpcPort::OffsetFromHttp(offset) => http_port.saturating_add(offset),+ };+ format!("http://{host}:{port}")+}++fn jittered(base: Duration) -> Duration {+ let jitter = rand::random::<f64>() * 0.5 + 0.75;+ base.mul_f64(jitter)+}++/// Process-unique sender id, matching the HTTP transport's semantics.+fn make_consumer_id() -> String {+ let ts = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_millis();+ let rand: u32 = rand::random();+ format!("{ts:x}-{rand:08x}")+}diff --git a/rust/ingestion-consumer/src/lib.rs b/rust/ingestion-consumer/src/lib.rsindex d5e3087379a6..75de663af429 100644--- a/rust/ingestion-consumer/src/lib.rs+++ b/rust/ingestion-consumer/src/lib.rs@@ -4,11 +4,14 @@ pub mod consumer;pub mod debug_recorder;pub mod discovery;pub mod dispatcher;+pub mod grpc_transport;pub mod kafka_config;pub mod kafka_stats;pub mod order_sentinel;+pub mod readiness;pub mod routing;pub mod stash;pub mod transport;+pub mod transports;pub mod types;pub mod worker_registry;diff --git a/rust/ingestion-consumer/src/main.rs b/rust/ingestion-consumer/src/main.rsindex 6f554588fdd1..7d8e03718f44 100644--- a/rust/ingestion-consumer/src/main.rs+++ b/rust/ingestion-consumer/src/main.rs@@ -25,8 +25,10 @@ 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::transport::HttpTransport;+use ingestion_consumer::transports::{Transport, TransportMode};use ingestion_consumer::worker_registry::{WorkerId, WorkerRegistry, WorkerRegistryConfig};common_alloc::used!();@@ -239,19 +241,42 @@ async fn async_main(config: Config) -> Result<()> {} else {Some(config.internal_api_secret.clone())};- // Transport semaphores are created lazily per worker, so it starts empty.- let mut transport = HttpTransport::new(- Duration::from_millis(config.http_timeout_ms),- config.max_retries,- api_secret,- &[],- config.ingestion_worker_concurrent_batches,- config.transport_compression_enabled,+ let transport = match config.ingestion_transport {+ TransportMode::Http => {+ // Transport semaphores are created lazily per worker, so it starts empty.+ let mut transport = HttpTransport::new(+ Duration::from_millis(config.http_timeout_ms),+ config.max_retries,+ api_secret,+ &[],+ config.ingestion_worker_concurrent_batches,+ config.transport_compression_enabled,+ );+ transport.set_max_body_bytes(config.transport_max_body_bytes);+ if let Some(recorder) = &debug_recorder {+ transport.set_debug_recorder(Arc::clone(recorder));+ }+ Transport::Http(Arc::new(transport))+ }+ TransportMode::Grpc => {+ let grpc_port = if config.ingestion_worker_grpc_port_offset > 0 {+ GrpcPort::OffsetFromHttp(config.ingestion_worker_grpc_port_offset)+ } else {+ GrpcPort::Fixed(config.ingestion_worker_grpc_port)+ };+ let mut transport = GrpcTransport::new(+ grpc_port,+ config.ingestion_worker_concurrent_batches,+ Duration::from_millis(config.ingestion_worker_stream_ack_timeout_ms),+ );+ transport.set_max_body_bytes(config.transport_max_body_bytes);+ Transport::Grpc(Arc::new(transport))+ }+ };+ info!(+ transport = config.ingestion_transport.as_str(),+ "Worker transport selected");- transport.set_max_body_bytes(config.transport_max_body_bytes);- if let Some(recorder) = &debug_recorder {- transport.set_debug_recorder(Arc::clone(recorder));- }let transport = Arc::new(transport);// Select the worker discovery provider and start it (static applies thediff --git a/rust/ingestion-consumer/src/order_sentinel.rs b/rust/ingestion-consumer/src/order_sentinel.rsindex ad1920bc0cc1..e000dc46588c 100644--- a/rust/ingestion-consumer/src/order_sentinel.rs+++ b/rust/ingestion-consumer/src/order_sentinel.rs@@ -41,7 +41,7 @@//! The sentinels are pure observers: they never influence routing or commits.use std::collections::HashMap;-use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};use std::sync::{Arc, Mutex};use std::time::{SystemTime, UNIX_EPOCH};@@ -563,6 +563,10 @@ impl KeyOrderSentinel {pub struct SentinelContext {commit_sentinel: Arc<CommitSentinel>,key_sentinel: Arc<KeyOrderSentinel>,+ /// Bumped on every partition assignment; the gRPC transport stamps it on+ /// sub-batches so the worker's feed-order sentinel rebaselines across+ /// rebalances. `None` on the HTTP transport.+ assignment_epoch: Option<Arc<AtomicU64>>,}impl SentinelContext {@@ -570,9 +574,16 @@ impl SentinelContext {Self {commit_sentinel,key_sentinel,+ assignment_epoch: None,}}+ /// Wire the gRPC transport's assignment-epoch counter. Call before the+ /// context is handed to the Kafka consumer.+ pub fn set_assignment_epoch(&mut self, epoch: Arc<AtomicU64>) {+ self.assignment_epoch = Some(epoch);+ }+/// A context with its own free-standing sentinels, for tests and tools/// that build the Kafka consumer separately from the dispatcher.pub fn detached() -> Self {@@ -620,6 +631,9 @@ impl ConsumerContext for SentinelContext {if let Rebalance::Assign(tpl) = rebalance {counter!("ingestion_consumer_rebalances_total", "event" => "assign").increment(1);info!(partitions = tpl.count(), "Rebalance: partitions assigned");+ if let Some(epoch) = &self.assignment_epoch {+ epoch.fetch_add(1, Ordering::Relaxed);+ }}}diff --git a/rust/ingestion-consumer/src/readiness.rs b/rust/ingestion-consumer/src/readiness.rsnew file mode 100644index 000000000000..e0938db7c2dc--- /dev/null+++ b/rust/ingestion-consumer/src/readiness.rs@@ -0,0 +1,60 @@+//! Worker readiness probing, shared by both transports: workers always+//! serve `/_ready` over HTTP, whichever transport carries the batches.++use std::time::Duration;++use tracing::{info, warn};++/// Bound on one `/_ready` probe. A worker that accepts the connection but+/// never answers must not stall startup or shutdown.+pub const PROBE_TIMEOUT: Duration = Duration::from_secs(5);++/// Probe a worker's `/_ready` endpoint.+pub async fn check_ready(client: &reqwest::Client, worker_url: &str) -> bool {+ let url = format!("{worker_url}/_ready");+ match client.get(&url).timeout(PROBE_TIMEOUT).send().await {+ Ok(resp) => resp.status().is_success(),+ Err(_) => false,+ }+}++/// Wait until every worker is ready, polling with backoff. Probes run+/// concurrently, and shutdown wins over an in-progress round.+pub async fn wait_for_workers_ready(+ client: &reqwest::Client,+ worker_urls: &[String],+ shutdown: &lifecycle::Handle,+) -> anyhow::Result<()> {+ let poll_interval = Duration::from_secs(2);+ loop {+ let round = async {+ let results =+ futures::future::join_all(worker_urls.iter().map(|url| check_ready(client, url)))+ .await;+ let mut all_ready = true;+ for (url, ready) in worker_urls.iter().zip(results) {+ if !ready {+ warn!(worker = %url, "Worker not ready");+ all_ready = false;+ }+ }+ all_ready+ };+ let all_ready = tokio::select! {+ _ = shutdown.shutdown_recv() => {+ anyhow::bail!("Shutdown received while waiting for workers");+ }+ all_ready = round => all_ready,+ };+ if all_ready {+ info!(workers = worker_urls.len(), "All workers ready");+ return Ok(());+ }+ tokio::select! {+ _ = shutdown.shutdown_recv() => {+ anyhow::bail!("Shutdown received while waiting for workers");+ }+ _ = tokio::time::sleep(poll_interval) => {}+ }+ }+}diff --git a/rust/ingestion-consumer/src/transport.rs b/rust/ingestion-consumer/src/transport.rsindex ee93c817fdc2..04ad0c9fca57 100644--- a/rust/ingestion-consumer/src/transport.rs+++ b/rust/ingestion-consumer/src/transport.rs@@ -9,9 +9,10 @@ use flate2::Compression;use metrics::{counter, gauge, histogram};use rand::Rng;use tokio::sync::Semaphore;-use tracing::{error, info, warn};+use tracing::{error, warn};use crate::debug_recorder::{record_if, DebugEventKind, DebugRecorder};+use crate::readiness;use crate::types::{IngestBatchRequest, IngestBatchResponse, SerializedKafkaMessage};/// Default cap on the serialized JSON size of one /ingest request body. The@@ -158,11 +159,7 @@ impl HttpTransport {/// Check if a worker is ready by probing its health endpoint.pub async fn check_ready(&self, worker_url: &str) -> bool {- let url = format!("{worker_url}/_ready");- match self.client.get(&url).send().await {- Ok(resp) => resp.status().is_success(),- Err(_) => false,- }+ readiness::check_ready(&self.client, worker_url).await}/// Wait until all workers are ready, polling with backoff.@@ -172,29 +169,7 @@ impl HttpTransport {worker_urls: &[String],shutdown: &lifecycle::Handle,) -> anyhow::Result<()> {- let poll_interval = Duration::from_secs(2);-- loop {- let mut all_ready = true;- for url in worker_urls {- if !self.check_ready(url).await {- warn!(worker = %url, "Worker not ready");- all_ready = false;- }- }-- if all_ready {- info!(workers = worker_urls.len(), "All workers ready");- return Ok(());- }-- tokio::select! {- _ = shutdown.shutdown_recv() => {- anyhow::bail!("Shutdown received while waiting for workers");- }- _ = tokio::time::sleep(poll_interval) => {}- }- }+ readiness::wait_for_workers_ready(&self.client, worker_urls, shutdown).await}/// Send a sub-batch to a worker. Returns the number of accepted messages.@@ -307,12 +282,14 @@ impl HttpTransport {return Err(SendError {error: TransportError::PayloadTooLarge(String::new()),messages: reassemble(sent, messages, queue),+ fence_guard: None,});}ChunkOutcome::Failed { error, messages } => {return Err(SendError {error,messages: reassemble(sent, messages, queue),+ fence_guard: None,});}}@@ -559,7 +536,7 @@ fn approx_message_size(msg: &SerializedKafkaMessage) -> usize {/// Split a sub-batch into chunks whose estimated serialized size stays under/// `max_body_bytes`, preserving message order. A single message estimated/// above the cap gets its own chunk — it can't be split further.-fn split_by_size(+pub(crate) fn split_by_size(messages: Vec<SerializedKafkaMessage>,max_body_bytes: usize,) -> Vec<Vec<SerializedKafkaMessage>> {@@ -588,6 +565,45 @@ fn split_by_size(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.+ pub fence_guard: Option<FenceGuard>,+}++/// Tells a fencing worker stream that one fenced send's messages are stashed.+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.+ released: Vec<tokio::sync::mpsc::UnboundedSender<()>>,+}++impl FenceGuard {+ pub(crate) fn new(released: tokio::sync::mpsc::UnboundedSender<()>) -> Self {+ Self {+ released: vec![released],+ }+ }++ /// Fold `other` into this guard, so both release only when this one drops.+ pub(crate) fn merge(&mut self, mut other: FenceGuard) {+ self.released.append(&mut other.released);+ }+}++impl Drop for FenceGuard {+ fn drop(&mut self) {+ for released in &self.released {+ let _ = released.send(());+ }+ }+}++impl std::fmt::Debug for FenceGuard {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str("FenceGuard")+ }}#[derive(Debug, thiserror::Error)]@@ -612,6 +628,15 @@ pub enum TransportError {#[error("All retries exhausted")]RetriesExhausted,++ #[error("Worker stream failed: {0}")]+ WorkerStreamFailed(&'static str),++ #[error("Worker stream busy: {0}")]+ WorkerStreamBusy(&'static str),++ #[error("Worker stream closed without resolving the send")]+ WorkerStreamClosed,}impl TransportError {@@ -629,8 +654,25 @@ impl TransportError {TransportError::PayloadTooLarge(_) => false,TransportError::WorkerError(_) => true,TransportError::RetriesExhausted => false,+ // Worker stream failures resolve through the deferral path, not the HTTP+ // retry loop — never retried in place.+ TransportError::WorkerStreamFailed(_) => false,+ // A busy worker stream is transient backpressure (like WorkerBusy), so the+ // fenced work re-routes as retriable rather than a worker fault.+ TransportError::WorkerStreamBusy(_) => true,+ TransportError::WorkerStreamClosed => false,}}++ /// Backpressure the worker signalled deliberately (503 or a busy worker stream).+ /// Distinct from `is_retriable`: connection errors and 5xx are retriable+ /// too, but they are worker faults and must count against passive health.+ pub fn is_backpressure(&self) -> bool {+ matches!(+ self,+ TransportError::WorkerBusy(_) | TransportError::WorkerStreamBusy(_)+ )+ }}/// Backoff before a retry. A busy worker (503) gets a longer base plus jitter so@@ -681,6 +723,16 @@ mod tests {assert!(TransportError::WorkerBusy("at capacity".into()).is_retriable());}+ #[test]+ fn test_only_busy_errors_are_backpressure() {+ assert!(TransportError::WorkerBusy("at capacity".into()).is_backpressure());+ assert!(TransportError::WorkerStreamBusy("busy").is_backpressure());+ assert!(!TransportError::HttpStatus(500, "boom".into()).is_backpressure());+ assert!(!TransportError::WorkerError("boom".into()).is_backpressure());+ assert!(!TransportError::WorkerStreamFailed("nack").is_backpressure());+ assert!(!TransportError::RetriesExhausted.is_backpressure());+ }+#[test]fn test_client_errors_are_not_retriable() {assert!(!TransportError::HttpStatus(400, "bad".into()).is_retriable());diff --git a/rust/ingestion-consumer/src/transports.rs b/rust/ingestion-consumer/src/transports.rsnew file mode 100644index 000000000000..6b413c805714--- /dev/null+++ b/rust/ingestion-consumer/src/transports.rs@@ -0,0 +1,151 @@+//! Transport selection: HTTP request/response vs ordered gRPC worker streams.+//!+//! The consumer talks to workers through one [`Transport`], picked by+//! `INGESTION_TRANSPORT`. Sends are two-phase everywhere: [`Transport::begin_send`]+//! establishes send order and must be called where that order is decided (the+//! consumer loop right after assignment, or the serialized flush paths);+//! [`PendingSend::wait`] resolves like an HTTP response. The HTTP transport+//! implements `begin_send` lazily (nothing happens until `wait`), which keeps+//! its behavior identical to the direct `send_batch` call it replaces; the+//! gRPC transport enqueues synchronously onto the worker's ordered stream.++use std::str::FromStr;+use std::sync::Arc;++use crate::grpc_transport::{GrpcTransport, PendingWorkerStreamSend};+use crate::transport::{HttpTransport, SendError};+use crate::types::SerializedKafkaMessage;++/// Which transport carries sub-batches to the workers.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub enum TransportMode {+ #[default]+ Http,+ Grpc,+}++impl FromStr for TransportMode {+ type Err = String;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ match s.trim().to_lowercase().as_str() {+ "http" => Ok(TransportMode::Http),+ "grpc" => Ok(TransportMode::Grpc),+ other => Err(format!(+ "unknown ingestion transport '{other}' (expected 'http' or 'grpc')"+ )),+ }+ }+}++impl TransportMode {+ pub fn as_str(&self) -> &'static str {+ match self {+ TransportMode::Http => "http",+ TransportMode::Grpc => "grpc",+ }+ }+}++/// The consumer's worker transport.+pub enum Transport {+ Http(Arc<HttpTransport>),+ Grpc(Arc<GrpcTransport>),+}++/// A sub-batch whose send order is established; await it for the outcome.+pub enum PendingSend {+ Http {+ transport: Arc<HttpTransport>,+ worker_url: String,+ batch_id: String,+ messages: Vec<SerializedKafkaMessage>,+ replay: bool,+ },+ Grpc(PendingWorkerStreamSend),+}++impl PendingSend {+ pub async fn wait(self) -> Result<u32, SendError> {+ match self {+ PendingSend::Http {+ transport,+ worker_url,+ batch_id,+ messages,+ replay,+ } => {+ transport+ .send_batch(&worker_url, &batch_id, messages, replay)+ .await+ }+ PendingSend::Grpc(pending) => pending.wait().await,+ }+ }+}++impl Transport {+ /// Establish send order for a sub-batch. Synchronous — call it in the+ /// order sends must reach the worker; the per-key ordering guarantee on+ /// the gRPC path is exactly "begin_send order per worker".+ pub fn begin_send(+ &self,+ worker_url: &str,+ batch_id: &str,+ messages: Vec<SerializedKafkaMessage>,+ replay: bool,+ ) -> PendingSend {+ match self {+ Transport::Http(transport) => PendingSend::Http {+ transport: Arc::clone(transport),+ worker_url: worker_url.to_string(),+ batch_id: batch_id.to_string(),+ messages,+ replay,+ },+ Transport::Grpc(transport) => {+ PendingSend::Grpc(transport.begin_send(worker_url, batch_id, messages, replay))+ }+ }+ }++ pub async fn wait_for_workers_ready(+ &self,+ worker_urls: &[String],+ shutdown: &lifecycle::Handle,+ ) -> anyhow::Result<()> {+ match self {+ Transport::Http(transport) => {+ transport+ .wait_for_workers_ready(worker_urls, shutdown)+ .await+ }+ Transport::Grpc(transport) => {+ transport+ .wait_for_workers_ready(worker_urls, shutdown)+ .await+ }+ }+ }++ /// Drop a departed worker's transport state (semaphore or worker stream).+ pub fn remove_worker(&self, worker_url: &str) {+ match self {+ Transport::Http(transport) => transport.remove_worker(worker_url),+ Transport::Grpc(transport) => transport.remove_worker(worker_url),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_transport_mode_parses_known_values() {+ assert_eq!("http".parse(), Ok(TransportMode::Http));+ assert_eq!(" gRPC ".parse(), Ok(TransportMode::Grpc));+ assert!("carrier-pigeon".parse::<TransportMode>().is_err());+ assert_eq!(TransportMode::default(), TransportMode::Http);+ }+}diff --git a/rust/ingestion-consumer/tests/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rsindex 42500f5bb18d..c1da42c5f958 100644--- a/rust/ingestion-consumer/tests/e2e_integration_test.rs+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs@@ -27,10 +27,21 @@ use uuid::Uuid;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::transport::HttpTransport;+use ingestion_consumer::transports::Transport;use ingestion_consumer::types::{IngestBatchRequest, IngestBatchResponse, SerializedKafkaMessage};-use ingestion_consumer::worker_registry::{WorkerId, WorkerRegistry, WorkerRegistryConfig};+use ingestion_consumer::worker_registry::{+ WorkerId, WorkerRegistry, WorkerRegistryConfig, WorkerState,+};+use ingestion_worker_proto::ingestion::worker::v1::worker_ingest_server::{+ WorkerIngest as WorkerIngestService, WorkerIngestServer,+};+use ingestion_worker_proto::ingestion::worker::v1::{+ ingest_stream_request, ingest_stream_response, IngestStreamRequest, IngestStreamResponse,+ StreamReady, SubBatchAck, SubBatchStatus,+};const KAFKA_BROKERS: &str = "localhost:9092";@@ -315,11 +326,48 @@ impl FakeWorker {// Like the real Express worker, inflate gzipped request bodies..layer(tower_http::decompression::RequestDecompressionLayer::new());- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ // Bind HTTP on an ephemeral port and gRPC on that port + 1, so the+ // gRPC transport's OffsetFromHttp mode can address each worker.+ // Rebind both if the adjacent port happens to be taken.+ let (listener, grpc_listener) = loop {+ let http = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let Some(grpc_port) = http.local_addr().unwrap().port().checked_add(1) else {+ continue;+ };+ match TcpListener::bind(("127.0.0.1", grpc_port)).await {+ Ok(grpc) => break (http, grpc),+ Err(_) => continue,+ }+ };let addr = listener.local_addr().unwrap();let url = format!("http://127.0.0.1:{}", addr.port());let task = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ let grpc_service = FakeWorkerGrpc {+ received: Arc::clone(&received),+ healthy: Arc::clone(&healthy),+ ingest_ok: Arc::clone(&ingest_ok),+ ack_lost_once: Arc::clone(&ack_lost_once),+ reject_4xx: Arc::clone(&reject_4xx),+ underreport_once: Arc::clone(&underreport_once),+ arrived: Arc::clone(&arrived),+ gate: Arc::clone(&gate),+ delivery_log,+ };+ tokio::spawn(async move {+ tonic::transport::Server::builder()+ .add_service(+ WorkerIngestServer::new(grpc_service)+ .accept_compressed(tonic::codec::CompressionEncoding::Gzip)+ .send_compressed(tonic::codec::CompressionEncoding::Gzip),+ )+ .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(+ grpc_listener,+ ))+ .await+ .unwrap();+ });+Self {url,received,@@ -366,6 +414,125 @@ impl FakeWorker {}}+/// The FakeWorker's WorkerIngest implementation, sharing the HTTP handler's+/// state and knobs so gRPC scenarios drive the same failure modes. Per the+/// protocol, any failure ends the stream (a nack means the worker stream is dead).+struct FakeWorkerGrpc {+ received: Arc<Mutex<Vec<(String, usize)>>>,+ healthy: Arc<AtomicBool>,+ ingest_ok: Arc<AtomicBool>,+ ack_lost_once: Arc<AtomicBool>,+ reject_4xx: Arc<AtomicBool>,+ underreport_once: Arc<AtomicBool>,+ arrived: Arc<AtomicUsize>,+ gate: Arc<tokio::sync::Mutex<()>>,+ delivery_log: Option<DeliveryLog>,+}++#[tonic::async_trait]+impl WorkerIngestService for FakeWorkerGrpc {+ type IngestStreamStream = tokio_stream::wrappers::UnboundedReceiverStream<+ Result<IngestStreamResponse, tonic::Status>,+ >;++ async fn ingest_stream(+ &self,+ request: tonic::Request<tonic::Streaming<IngestStreamRequest>>,+ ) -> Result<tonic::Response<Self::IngestStreamStream>, tonic::Status> {+ let mut inbound = request.into_inner();+ let (tx, rx) = tokio::sync::mpsc::unbounded_channel();+ let received = Arc::clone(&self.received);+ let healthy = Arc::clone(&self.healthy);+ let ingest_ok = Arc::clone(&self.ingest_ok);+ let ack_lost_once = Arc::clone(&self.ack_lost_once);+ let reject_4xx = Arc::clone(&self.reject_4xx);+ let underreport_once = Arc::clone(&self.underreport_once);+ let arrived = Arc::clone(&self.arrived);+ let gate = Arc::clone(&self.gate);+ let delivery_log = self.delivery_log.clone();++ tokio::spawn(async move {+ // Mirror the real worker: greet with `ready` so response headers+ // flush; the worker stream must ignore it.+ let _ = tx.send(Ok(IngestStreamResponse {+ msg: Some(ingest_stream_response::Msg::Ready(StreamReady {})),+ }));+ let nack = |tx: &tokio::sync::mpsc::UnboundedSender<+ Result<IngestStreamResponse, tonic::Status>,+ >,+ seq: u64,+ reason: &str| {+ let _ = tx.send(Ok(IngestStreamResponse {+ msg: Some(ingest_stream_response::Msg::Ack(SubBatchAck {+ seq,+ status: SubBatchStatus::Failed as i32,+ accepted: 0,+ error: reason.to_string(),+ })),+ }));+ };+ while let Ok(Some(frame)) = inbound.message().await {+ let Some(ingest_stream_request::Msg::SubBatch(sub_batch)) = frame.msg else {+ continue;+ };+ arrived.fetch_add(1, Ordering::SeqCst);+ // Block here while a test holds the gate (slow worker).+ let _hold = gate.lock().await;+ if !healthy.load(Ordering::Relaxed) || !ingest_ok.load(Ordering::Relaxed) {+ nack(&tx, sub_batch.seq, "worker unhealthy");+ return;+ }+ if reject_4xx.load(Ordering::SeqCst) {+ nack(&tx, sub_batch.seq, "poison batch");+ return;+ }+ let entries: Vec<(String, usize)> = sub_batch+ .messages+ .iter()+ .map(|msg| {+ let did = msg.headers.get("distinct_id").cloned().unwrap_or_default();+ let seq = msg+ .value+ .as_deref()+ .and_then(|v| serde_json::from_str::<serde_json::Value>(v).ok())+ .and_then(|v| v["seq"].as_u64())+ .unwrap_or(0) as usize;+ (did, seq)+ })+ .collect();+ received.lock().unwrap().extend(entries.iter().cloned());+ if let Some(log) = &delivery_log {+ log.lock().unwrap().extend(entries);+ }+ // Work done and recorded, but the ACK is lost: fail the stream+ // so the consumer fences and replays.+ if ack_lost_once.swap(false, Ordering::SeqCst) {+ nack(&tx, sub_batch.seq, "ack lost");+ return;+ }+ let accepted = sub_batch.messages.len() as u32;+ let reported = if underreport_once.swap(false, Ordering::SeqCst) {+ accepted.saturating_sub(1)+ } else {+ accepted+ };+ let _ = tx.send(Ok(IngestStreamResponse {+ msg: Some(ingest_stream_response::Msg::Ack(SubBatchAck {+ seq: sub_batch.seq,+ status: SubBatchStatus::Ok as i32,+ accepted: reported,+ error: String::new(),+ })),+ }));+ }+ });++ Ok(tonic::Response::new(+ tokio_stream::wrappers::UnboundedReceiverStream::new(rx),+ ))+ }+}+// ── Test harness ───────────────────────────────────────────────────────────struct Harness {@@ -418,7 +585,7 @@ fn make_kafka_consumer(/// 1s keeps test scenarios responsive.)fn spawn_reaper(registry: Arc<WorkerRegistry>,- transport: Arc<HttpTransport>,+ transport: Arc<Transport>,dispatcher: Arc<Dispatcher>,token: CancellationToken,) {@@ -458,6 +625,7 @@ impl Harness {deferred_flush_timeout,registry_config,0,+ false,ComponentOptions::new(),).await@@ -478,6 +646,7 @@ impl Harness {deferred_flush_timeout,fast_registry_config(),0,+ false,ComponentOptions::new().with_liveness_deadline(liveness_deadline).with_stall_threshold(stall_threshold),@@ -497,6 +666,32 @@ impl Harness {Duration::from_secs(60),fast_registry_config(),batch_size_bytes,+ false,+ ComponentOptions::new(),+ )+ .await+ }++ /// Like `start`, but the consumer sends over WorkerIngest gRPC worker streams+ /// (`GrpcPort::OffsetFromHttp(1)` — each FakeWorker serves gRPC on its+ /// HTTP port + 1).+ async fn start_grpc(+ topic: &str,+ partitions: i32,+ worker_count: usize,+ max_in_flight: usize,+ deferred_flush_timeout: Duration,+ registry_config: WorkerRegistryConfig,+ ) -> Self {+ Self::start_inner(+ topic,+ partitions,+ worker_count,+ max_in_flight,+ deferred_flush_timeout,+ registry_config,+ 0,+ true,ComponentOptions::new(),).await@@ -511,6 +706,7 @@ impl Harness {deferred_flush_timeout: Duration,registry_config: WorkerRegistryConfig,batch_size_bytes: usize,+ grpc: bool,component_options: ComponentOptions,) -> Self {create_topic(topic, partitions).await;@@ -529,14 +725,24 @@ impl Harness {let dispatcher = Arc::new(Dispatcher::new(Arc::clone(®istry)));let registry_for_test = Arc::clone(®istry);let dispatcher_for_test = Arc::clone(&dispatcher);- let transport = Arc::new(HttpTransport::new(- Duration::from_secs(5),- 0, // no retries — errors surface immediately for health tracking- None,- &worker_urls,- 1,- true,- ));+ let transport = Arc::new(if grpc {+ // Short ack timeout so a stalled scenario fences within a test's+ // patience rather than production's 60s.+ Transport::Grpc(Arc::new(GrpcTransport::new(+ GrpcPort::OffsetFromHttp(1),+ 1,+ Duration::from_secs(10),+ )))+ } else {+ Transport::Http(Arc::new(HttpTransport::new(+ Duration::from_secs(5),+ 0, // no retries — errors surface immediately for health tracking+ None,+ &worker_urls,+ 1,+ true,+ )))+ });spawn_reaper(Arc::clone(®istry),Arc::clone(&transport),@@ -611,14 +817,14 @@ impl Harness {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(+ let transport = Arc::new(Transport::Http(Arc::new(HttpTransport::new(Duration::from_secs(5),0,None,&worker_urls,1,true,- ));+ ))));spawn_reaper(Arc::clone(®istry),Arc::clone(&transport),@@ -925,6 +1131,38 @@ async fn failing_worker_triggers_rerouting() {harness.stop().await;}+/// 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.+#[tokio::test]+async fn failed_sends_degrade_passive_health() {+ let topic = format!("e2e-passive-fault-{}", Uuid::new_v4());+ let harness = Harness::start(+ &topic,+ 1,+ 1,+ 1,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;+ let producer = make_producer();++ harness.workers[0].ingest_ok.store(false, Ordering::SeqCst);+ produce(&producer, &topic, 0, "tok", "user-1", 0).await;++ let worker = harness.workers[0].url.clone();+ wait_until(+ Duration::from_secs(10),+ "failed sends to degrade the worker",+ || harness.registry.state(&worker) != WorkerState::Healthy,+ )+ .await;++ harness.workers[0].ingest_ok.store(true, Ordering::SeqCst);+ harness.stop().await;+}+/// Graceful drain end-to-end: a worker that begins draining receives no new/// work, keeps the messages it already has (no reprocessing, no loss), and/// subsequent messages for the same distinct_id reroute in order to a surviving@@ -2371,14 +2609,14 @@ async fn second_consumer_joining_the_group_preserves_all_messages() {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(+ let transport2 = Arc::new(Transport::Http(Arc::new(HttpTransport::new(Duration::from_secs(5),0,None,&worker_urls,1,true,- ));+ ))));let mut manager2 = Manager::builder("e2e-c2").with_trap_signals(false).build();let handle2 = manager2.register("consumer", ComponentOptions::new());let shutdown2 = handle2.shutdown_token();@@ -2447,14 +2685,14 @@ async fn fenced_static_member_exits_on_fatal_error() {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(+ let transport = Arc::new(Transport::Http(Arc::new(HttpTransport::new(Duration::from_secs(5),0,None,&urls,1,true,- ));+ ))));let mut manager = Manager::builder("e2e-fenced").with_trap_signals(false).build();@@ -2756,3 +2994,100 @@ async fn flapping_worker_does_not_pin_batch_past_flush_timeout() {"nothing should be delivered (target only errors; other is down)");}++// ── gRPC transport (WorkerIngest worker streams) ────────────────────────────────────++/// The full Kafka → assign → worker stream → stream → ack → commit loop over the gRPC+/// transport: every message arrives exactly once, and each distinct_id's+/// messages arrive in order on whichever worker its worker stream delivered them to.+#[tokio::test]+async fn grpc_messages_per_distinct_id_arrive_in_order() {+ let topic = format!("e2e-grpc-ordering-{}", Uuid::new_v4());+ let harness = Harness::start_grpc(+ &topic,+ 3,+ 2,+ 1,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;++ let producer = make_producer();+ for seq in 0..8usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ produce(&producer, &topic, 1, "tok", "user-2", seq).await;+ produce(&producer, &topic, 2, "tok", "user-3", seq).await;+ }++ harness.wait_for(24, Duration::from_secs(15)).await;++ let total: usize = harness.workers.iter().map(|w| w.count()).sum();+ assert_eq!(total, 24, "expected 24 messages total, got {total}");++ for worker in &harness.workers {+ for user in ["user-1", "user-2", "user-3"] {+ let seqs = worker.seqs_for(user);+ assert!(+ seqs.windows(2).all(|w| w[0] < w[1]),+ "{user} arrived out of order on a worker: {seqs:?}"+ );+ }+ }++ harness.stop().await;+}++/// 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 — the same recovery contract+/// the HTTP transport gets from its request errors.+#[tokio::test]+async fn grpc_nacking_worker_fences_worker_stream_and_reroutes_in_order() {+ let topic = format!("e2e-grpc-fence-{}", Uuid::new_v4());+ let harness = Harness::start_grpc(+ &topic,+ 2,+ 2,+ 1,+ Duration::from_secs(60),+ fast_registry_config(),+ )+ .await;++ let producer = make_producer();++ for seq in 0..4usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ produce(&producer, &topic, 1, "tok", "user-2", seq).await;+ }+ harness.wait_for(8, Duration::from_secs(10)).await;++ // Take down the worker that owns user-1: its stream nacks (fencing the+ // worker stream) and its /_ready fails (dropping it from the pool and its pins).+ let dead_idx = if !harness.workers[0].seqs_for("user-1").is_empty() {+ 0+ } else {+ 1+ };+ let live_idx = 1 - dead_idx;+ harness.workers[dead_idx]+ .healthy+ .store(false, Ordering::Relaxed);+ tokio::time::sleep(Duration::from_millis(600)).await;++ for seq in 4..8usize {+ produce(&producer, &topic, 0, "tok", "user-1", seq).await;+ }+ harness.wait_for(12, Duration::from_secs(15)).await;++ let live_seqs = harness.workers[live_idx].seqs_for("user-1");+ let batch2_seqs: Vec<usize> = live_seqs.iter().copied().filter(|&s| s >= 4).collect();+ assert_eq!(+ batch2_seqs,+ vec![4, 5, 6, 7],+ "post-fence messages for user-1 missing or out-of-order on the live worker: {live_seqs:?}"+ );++ harness.stop().await;+}diff --git a/rust/ingestion-consumer/tests/grpc_transport_test.rs b/rust/ingestion-consumer/tests/grpc_transport_test.rsnew file mode 100644index 000000000000..1ed9f1780639--- /dev/null+++ b/rust/ingestion-consumer/tests/grpc_transport_test.rs@@ -0,0 +1,742 @@+//! Worker stream-level tests for the gRPC transport against an in-process mock worker.+//!+//! 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.++use std::collections::HashMap;+use std::net::SocketAddr;+use std::sync::Arc;+use std::time::Duration;++use ingestion_consumer::grpc_transport::{GrpcPort, GrpcTransport};+use ingestion_consumer::transport::TransportError;+use ingestion_consumer::types::SerializedKafkaMessage;+use ingestion_worker_proto::ingestion::worker::v1::worker_ingest_server::{+ WorkerIngest, WorkerIngestServer,+};+use ingestion_worker_proto::ingestion::worker::v1::{+ ingest_stream_request, ingest_stream_response, IngestStreamRequest, IngestStreamResponse,+ StreamReady, SubBatch, SubBatchAck, SubBatchStatus,+};+use tokio::sync::{mpsc, Mutex};+use tokio_stream::wrappers::UnboundedReceiverStream;+use tokio_stream::StreamExt;+use tonic::{Request, Response, Status, Streaming};++/// What the mock does with each sub-batch it reads.+#[derive(Clone, Copy)]+enum AckMode {+ /// Ack immediately, in read order.+ Immediate,+ /// Buffer everything; the test triggers acks explicitly.+ Manual,+ /// Nack the sub-batch with this seq (and ack the others immediately).+ NackSeq(u64),+ /// Report busy for the sub-batch with this seq (and ack the others).+ BusySeq(u64),+ /// Ack every sub-batch immediately except this seq, which is never acked —+ /// a stuck oldest entry while its siblings keep acking.+ AckExceptSeq(u64),+}++/// Manual mode: the test drives the worker's acks through this.+#[derive(Clone, Copy)]+enum ManualAck {+ Ok { seq: u64, accepted: u32 },+ Nack(u64),+}++type ManualAcks = Arc<Mutex<Option<mpsc::UnboundedReceiver<ManualAck>>>>;++struct MockWorker {+ mode: AckMode,+ /// Sub-batches in the order the worker read them, across all streams.+ received: Arc<Mutex<Vec<SubBatch>>>,+ /// Hellos in connection order (stream epochs prove reconnects).+ hellos: Arc<Mutex<Vec<u64>>>,+ manual_acks: ManualAcks,+}++#[tonic::async_trait]+impl WorkerIngest for MockWorker {+ type IngestStreamStream = UnboundedReceiverStream<Result<IngestStreamResponse, Status>>;++ async fn ingest_stream(+ &self,+ request: Request<Streaming<IngestStreamRequest>>,+ ) -> Result<Response<Self::IngestStreamStream>, Status> {+ let mut inbound = request.into_inner();+ let (tx, rx) = mpsc::unbounded_channel();+ let mode = self.mode;+ let received = Arc::clone(&self.received);+ let hellos = Arc::clone(&self.hellos);+ let manual = self.manual_acks.lock().await.take();++ tokio::spawn(async move {+ // Mirror the real worker: greet with `ready` so response headers+ // flush; the worker stream must ignore it.+ let _ = tx.send(Ok(IngestStreamResponse {+ msg: Some(ingest_stream_response::Msg::Ready(StreamReady {})),+ }));+ if let Some(mut manual) = manual {+ let tx = tx.clone();+ tokio::spawn(async move {+ while let Some(ack) = manual.recv().await {+ let ack = match ack {+ ManualAck::Ok { seq, accepted } => SubBatchAck {+ seq,+ status: SubBatchStatus::Ok as i32,+ accepted,+ error: String::new(),+ },+ ManualAck::Nack(seq) => SubBatchAck {+ seq,+ status: SubBatchStatus::Failed as i32,+ accepted: 0,+ error: "poisoned".to_string(),+ },+ };+ let _ = tx.send(Ok(IngestStreamResponse {+ msg: Some(ingest_stream_response::Msg::Ack(ack)),+ }));+ }+ });+ }+ while let Some(Ok(frame)) = inbound.next().await {+ match frame.msg {+ Some(ingest_stream_request::Msg::Hello(hello)) => {+ hellos.lock().await.push(hello.stream_epoch);+ }+ Some(ingest_stream_request::Msg::SubBatch(sub_batch)) => {+ let seq = sub_batch.seq;+ let accepted = sub_batch.messages.len() as u32;+ received.lock().await.push(sub_batch);+ match mode {+ AckMode::Immediate => {+ let _ = tx.send(Ok(IngestStreamResponse {+ msg: Some(ingest_stream_response::Msg::Ack(SubBatchAck {+ seq,+ status: SubBatchStatus::Ok as i32,+ accepted,+ error: String::new(),+ })),+ }));+ }+ AckMode::NackSeq(nack) if seq == nack => {+ let _ = tx.send(Ok(IngestStreamResponse {+ msg: Some(ingest_stream_response::Msg::Ack(SubBatchAck {+ seq,+ status: SubBatchStatus::Failed as i32,+ accepted: 0,+ error: "poisoned".to_string(),+ })),+ }));+ }+ AckMode::NackSeq(_) => {+ let _ = tx.send(Ok(IngestStreamResponse {+ msg: Some(ingest_stream_response::Msg::Ack(SubBatchAck {+ seq,+ status: SubBatchStatus::Ok as i32,+ accepted,+ error: String::new(),+ })),+ }));+ }+ AckMode::BusySeq(busy) if seq == busy => {+ let _ = tx.send(Ok(IngestStreamResponse {+ msg: Some(ingest_stream_response::Msg::Ack(SubBatchAck {+ seq,+ status: SubBatchStatus::Busy as i32,+ accepted: 0,+ error: "at capacity".to_string(),+ })),+ }));+ }+ AckMode::BusySeq(_) => {+ let _ = tx.send(Ok(IngestStreamResponse {+ msg: Some(ingest_stream_response::Msg::Ack(SubBatchAck {+ seq,+ status: SubBatchStatus::Ok as i32,+ accepted,+ error: String::new(),+ })),+ }));+ }+ AckMode::AckExceptSeq(stuck) if seq == stuck => {}+ AckMode::AckExceptSeq(_) => {+ let _ = tx.send(Ok(IngestStreamResponse {+ msg: Some(ingest_stream_response::Msg::Ack(SubBatchAck {+ seq,+ status: SubBatchStatus::Ok as i32,+ accepted,+ error: String::new(),+ })),+ }));+ }+ AckMode::Manual => {}+ }+ }+ None => {}+ }+ }+ });++ Ok(Response::new(UnboundedReceiverStream::new(rx)))+ }+}++struct MockHandle {+ addr: SocketAddr,+ received: Arc<Mutex<Vec<SubBatch>>>,+ hellos: Arc<Mutex<Vec<u64>>>,+}++async fn start_mock(+ mode: AckMode,+ manual: Option<mpsc::UnboundedReceiver<ManualAck>>,+) -> MockHandle {+ let received = Arc::new(Mutex::new(Vec::new()));+ let hellos = Arc::new(Mutex::new(Vec::new()));+ let worker = MockWorker {+ mode,+ received: Arc::clone(&received),+ hellos: Arc::clone(&hellos),+ manual_acks: Arc::new(Mutex::new(manual)),+ };+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ tokio::spawn(async move {+ tonic::transport::Server::builder()+ .add_service(+ WorkerIngestServer::new(worker)+ .accept_compressed(tonic::codec::CompressionEncoding::Gzip)+ .send_compressed(tonic::codec::CompressionEncoding::Gzip),+ )+ .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener))+ .await+ .unwrap();+ });+ MockHandle {+ addr,+ received,+ hellos,+ }+}++fn msg(distinct_id: &str, offset: i64) -> 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: "events".to_string(),+ partition: 0,+ offset,+ timestamp: 0,+ key: Some(distinct_id.to_string()),+ value: Some("{}".to_string()),+ headers,+ }+}++/// The worker stream's worker URL: HTTP port is fake, the gRPC port is the mock's.+fn worker_url(addr: SocketAddr) -> String {+ format!("http://{}:9001", addr.ip())+}++#[tokio::test]+async fn sub_batches_reach_the_worker_in_enqueue_order() {+ let mock = start_mock(AckMode::Immediate, None).await;+ let transport = GrpcTransport::new(+ GrpcPort::Fixed(mock.addr.port()),+ 2,+ Duration::from_secs(30),+ );+ let url = worker_url(mock.addr);++ // Enqueue three sub-batches back to back — more than the un-acked cap, so+ // ordering must survive the ledger pacing too.+ let pending: Vec<_> = (0..3)+ .map(|i| transport.begin_send(&url, &format!("batch-{i}"), vec![msg("d1", i)], false))+ .collect();+ for (i, p) in pending.into_iter().enumerate() {+ let accepted = p.wait().await.expect("send should succeed");+ assert_eq!(accepted, 1, "sub-batch {i}");+ }++ let received = mock.received.lock().await;+ let batch_ids: Vec<_> = received.iter().map(|s| s.batch_id.clone()).collect();+ assert_eq!(batch_ids, vec!["batch-0", "batch-1", "batch-2"]);+ let seqs: Vec<_> = received.iter().map(|s| s.seq).collect();+ assert_eq!(seqs, vec![1, 2, 3], "seq is per-stream monotonic from 1");+}++#[tokio::test]+async fn out_of_order_acks_resolve_the_right_sends() {+ let (ack_tx, ack_rx) = mpsc::unbounded_channel();+ let mock = start_mock(AckMode::Manual, Some(ack_rx)).await;+ let transport = GrpcTransport::new(+ GrpcPort::Fixed(mock.addr.port()),+ 2,+ Duration::from_secs(30),+ );+ let url = worker_url(mock.addr);++ let first = transport.begin_send(&url, "batch-1", vec![msg("d1", 1), msg("d1", 2)], false);+ let second = transport.begin_send(&url, "batch-2", vec![msg("d2", 3)], false);++ // Wait until both are on the wire, then ack seq 2 before seq 1 with+ // distinct counts — each pending must get its own, and the later one+ // must not resolve ahead of the earlier one.+ wait_for_received(&mock, 2).await;+ ack_tx+ .send(ManualAck::Ok {+ seq: 2,+ accepted: 1,+ })+ .unwrap();+ let second = tokio::spawn(second.wait());+ tokio::time::sleep(Duration::from_millis(200)).await;+ assert!(+ !second.is_finished(),+ "a later ack must wait for every earlier seq"+ );+ ack_tx+ .send(ManualAck::Ok {+ seq: 1,+ accepted: 2,+ })+ .unwrap();+ assert_eq!(first.wait().await.expect("first ack"), 2);+ assert_eq!(second.await.unwrap().expect("second ack"), 1);+}++async fn wait_for_received(mock: &MockHandle, count: usize) {+ let deadline = tokio::time::Instant::now() + Duration::from_secs(10);+ while mock.received.lock().await.len() < count {+ assert!(+ tokio::time::Instant::now() < deadline,+ "sub-batches never reached the worker"+ );+ tokio::time::sleep(Duration::from_millis(5)).await;+ }+}++#[tokio::test]+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+ // 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;+ let transport = GrpcTransport::new(+ GrpcPort::Fixed(mock.addr.port()),+ 2,+ Duration::from_secs(30),+ );+ let url = worker_url(mock.addr);++ let first = transport.begin_send(&url, "batch-1", vec![msg("d1", 1)], false);+ let second = transport.begin_send(&url, "batch-2", vec![msg("d1", 2)], false);+ wait_for_received(&mock, 2).await;++ ack_tx+ .send(ManualAck::Ok {+ seq: 2,+ accepted: 1,+ })+ .unwrap();+ let second = tokio::spawn(second.wait());+ tokio::time::sleep(Duration::from_millis(200)).await;+ assert!(!second.is_finished(), "seq 2 must wait for seq 1");++ ack_tx.send(ManualAck::Nack(1)).unwrap();+ let first_err = first.wait().await.expect_err("nacked send must fail");+ assert_eq!(first_err.messages[0].offset, 1);+ assert!(matches!(+ first_err.error,+ TransportError::WorkerStreamFailed(_)+ ));+ let second_err = second+ .await+ .unwrap()+ .expect_err("an acked send behind a failure must fence with it");+ assert_eq!(+ second_err.messages[0].offset, 2,+ "messages come back for deferral"+ );+}++#[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+ // 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+ // every fenced caller drops its guard.+ let mock = start_mock(AckMode::NackSeq(1), None).await;+ let transport = GrpcTransport::new(+ GrpcPort::Fixed(mock.addr.port()),+ 1,+ Duration::from_secs(30),+ );+ let url = worker_url(mock.addr);++ let first = transport.begin_send(&url, "batch-1", vec![msg("d1", 1)], false);+ let first_err = first.wait().await.expect_err("nacked send must fail");+ let guard = first_err+ .fence_guard+ .expect("a fenced send carries a guard");++ // Enqueued while the fence is unacknowledged: fails without riding a+ // stream.+ let second = transport.begin_send(&url, "batch-2", vec![msg("d1", 2)], false);+ let second_err = tokio::time::timeout(Duration::from_secs(2), second.wait())+ .await+ .expect("a send during a fence must fail promptly")+ .expect_err("a send during a fence must fail");+ assert_eq!(second_err.messages[0].offset, 2);+ assert!(matches!(+ second_err.error,+ TransportError::WorkerStreamFailed(_)+ ));+ assert_eq!(mock.received.lock().await.len(), 1);++ // Both callers stashed: the worker stream resumes and the next send reaches the+ // worker on a fresh stream.+ drop(guard);+ drop(second_err);+ let third = transport.begin_send(&url, "batch-3", vec![msg("d1", 3)], false);+ let _ = tokio::time::timeout(Duration::from_secs(5), third.wait())+ .await+ .expect("the worker stream must resume once the fence is released");+ let batch_ids: Vec<_> = mock+ .received+ .lock()+ .await+ .iter()+ .map(|s| s.batch_id.clone())+ .collect();+ assert_eq!(batch_ids, vec!["batch-1", "batch-3"]);+}++#[tokio::test]+async fn an_oversized_sub_batch_rides_the_stream_as_ordered_chunks() {+ // The worker caps one frame; a sub-batch over the cap must split into+ // consecutive frames on the same stream instead of one frame the worker+ // rejects, fences, and replays forever.+ let mock = start_mock(AckMode::Immediate, None).await;+ let mut transport = GrpcTransport::new(+ GrpcPort::Fixed(mock.addr.port()),+ 2,+ Duration::from_secs(30),+ );+ // Frame size cap in bytes. One `msg()` estimates to ~143 bytes, so this+ // fits exactly one message per frame and three messages become three frames.+ transport.set_max_body_bytes(200);+ let url = worker_url(mock.addr);++ let pending = transport.begin_send(+ &url,+ "batch-1",+ vec![msg("d1", 1), msg("d1", 2), msg("d1", 3)],+ false,+ );+ let accepted = pending.wait().await.expect("all chunks accepted");+ assert_eq!(accepted, 3, "accepted counts sum across chunks");++ let received = mock.received.lock().await;+ let frames: Vec<(u64, &str, Vec<i64>)> = received+ .iter()+ .map(|s| {+ (+ s.seq,+ s.batch_id.as_str(),+ s.messages.iter().map(|m| m.offset).collect(),+ )+ })+ .collect();+ assert_eq!(+ frames,+ vec![+ (1, "batch-1", vec![1]),+ (2, "batch-1", vec![2]),+ (3, "batch-1", vec![3]),+ ],+ "one message per frame, consecutive seqs, in offset order"+ );+}++#[tokio::test]+async fn a_failed_chunk_hands_back_the_whole_sub_batch() {+ // All-or-nothing like the HTTP path: chunk 1 is acked, chunk 2 nacked, so+ // the send fails with every message (acked ones included) for deferral,+ // and carries a fence guard.+ let mock = start_mock(AckMode::NackSeq(2), None).await;+ let mut transport = GrpcTransport::new(+ GrpcPort::Fixed(mock.addr.port()),+ 2,+ Duration::from_secs(30),+ );+ // Frame size cap in bytes. One `msg()` estimates to ~143 bytes, so this+ // fits exactly one message per frame and three messages become three frames.+ transport.set_max_body_bytes(200);+ let url = worker_url(mock.addr);++ let pending = transport.begin_send(+ &url,+ "batch-1",+ vec![msg("d1", 1), msg("d1", 2), msg("d1", 3)],+ false,+ );+ let err = pending+ .wait()+ .await+ .expect_err("a nacked chunk fails the send");+ assert!(matches!(err.error, TransportError::WorkerStreamFailed(_)));+ let offsets: Vec<i64> = err.messages.iter().map(|m| m.offset).collect();+ assert_eq!(+ offsets,+ vec![1, 2, 3],+ "the whole sub-batch comes back in order"+ );+ assert!(err.fence_guard.is_some(), "a fenced send carries a guard");+}++#[tokio::test]+async fn a_nack_fences_everything_outstanding_in_order() {+ // Regression: on a failure, every un-acked and queued sub-batch must fail+ // back to the caller with its messages (for the deferral path), and+ // nothing may be silently retried on the next stream — a later sub-batch+ // surviving the fence would leapfrog the failed one and reorder its keys.+ let mock = start_mock(AckMode::NackSeq(1), None).await;+ let transport = GrpcTransport::new(+ GrpcPort::Fixed(mock.addr.port()),+ 1,+ Duration::from_secs(30),+ );+ let url = worker_url(mock.addr);++ // With max_unacked=1, the second and third wait in the queue behind the+ // first — the nack must fence all three.+ let first = transport.begin_send(&url, "batch-1", vec![msg("d1", 1)], false);+ let second = transport.begin_send(&url, "batch-2", vec![msg("d1", 2)], false);+ let third = transport.begin_send(&url, "batch-3", vec![msg("d2", 3)], false);++ let first_err = first.wait().await.expect_err("nacked send must fail");+ assert_eq!(first_err.messages.len(), 1);+ assert_eq!(+ first_err.messages[0].offset, 1,+ "messages come back for deferral"+ );+ assert!(matches!(+ first_err.error,+ TransportError::WorkerStreamFailed(_)+ ));++ let second_err = second+ .wait()+ .await+ .expect_err("queued send behind the nack must fail");+ assert_eq!(second_err.messages[0].offset, 2);+ let third_err = third+ .wait()+ .await+ .expect_err("queued send behind the nack must fail");+ assert_eq!(third_err.messages[0].offset, 3);++ // Only the nacked sub-batch reached the worker; the fenced ones never+ // rode a stream.+ assert_eq!(mock.received.lock().await.len(), 1);+}++#[tokio::test]+async fn the_worker_stream_reconnects_with_a_new_stream_epoch_after_a_fence() {+ let mock = start_mock(AckMode::NackSeq(1), None).await;+ let transport = GrpcTransport::new(+ GrpcPort::Fixed(mock.addr.port()),+ 2,+ Duration::from_secs(30),+ );+ let url = worker_url(mock.addr);++ let first = transport.begin_send(&url, "batch-1", vec![msg("d1", 1)], false);+ first.wait().await.expect_err("nacked");++ // The retry (as the deferral path would issue it) lands on a fresh stream+ // with a bumped epoch and replay=true, and succeeds: seq 1 is nacked only+ // once because NackSeq(1) nacks by seq, proving this send is seq 1 on a+ // NEW stream... so use a different worker mode expectation: the second+ // stream's seq-1 sub-batch is nacked again by this mock, which is fine —+ // what we assert is the reconnect (two hellos, increasing epochs).+ let retry = transport.begin_send(&url, "batch-1", vec![msg("d1", 1)], true);+ retry+ .wait()+ .await+ .expect_err("mock nacks seq 1 on every stream");++ let hellos = mock.hellos.lock().await;+ assert_eq!(hellos.len(), 2, "one hello per stream incarnation");+ assert!(+ hellos[1] > hellos[0],+ "stream epoch must increase on reconnect"+ );+}++#[tokio::test]+async fn a_dead_worker_fences_instead_of_hanging() {+ // Connect failure (nothing listening): the send must resolve with its+ // messages rather than waiting forever — the caller's deferral path owns+ // the retry pacing.+ let transport = GrpcTransport::new(GrpcPort::Fixed(1), 1, Duration::from_secs(30));+ let pending = transport.begin_send(+ "http://127.0.0.1:9001",+ "batch-1",+ vec![msg("d1", 1)],+ false,+ );+ let err = tokio::time::timeout(Duration::from_secs(10), pending.wait())+ .await+ .expect("must resolve, not hang")+ .expect_err("connect failure");+ assert_eq!(err.messages.len(), 1);+}++#[tokio::test]+async fn a_worker_that_stops_acking_fences_after_the_watchdog_window() {+ // Regression: a worker at capacity (or wedged) simply never acks, and the+ // worker stream has no per-send timeout — without the watchdog the consumer waits+ // forever and the whole pod wedges, as seen in production. The fence must+ // hand the messages back so the deferral path re-routes them.+ let (_ack_tx, ack_rx) = mpsc::unbounded_channel();+ let mock = start_mock(AckMode::Manual, Some(ack_rx)).await;+ let transport = GrpcTransport::new(+ GrpcPort::Fixed(mock.addr.port()),+ 2,+ Duration::from_millis(200),+ );+ let url = worker_url(mock.addr);++ let pending = transport.begin_send(&url, "batch-1", vec![msg("d1", 1)], false);+ let err = tokio::time::timeout(Duration::from_secs(10), pending.wait())+ .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[0].offset, 1);+}++#[tokio::test]+async fn a_stuck_oldest_sub_batch_fences_even_while_siblings_keep_acking() {+ // Regression: the watchdog must bound each sub-batch's own wait, not the+ // worker stream's time since its last ack. With more than one un-acked sub-batch, a+ // worker that keeps acking newer sub-batches but never the oldest used to+ // reset a single shared deadline on every ack, so the stuck send waited+ // forever and its Kafka batch never completed — the wedge the watchdog+ // exists to prevent.+ let mock = start_mock(AckMode::AckExceptSeq(1), None).await;+ let transport = Arc::new(GrpcTransport::new(+ GrpcPort::Fixed(mock.addr.port()),+ 2,+ Duration::from_millis(500),+ ));+ let url = worker_url(mock.addr);++ // Enqueued first, so it is seq 1 — the one the worker never acks.+ let stuck = transport.begin_send(&url, "batch-stuck", vec![msg("d1", 1)], false);++ // Keep feeding siblings faster than the ack timeout. Each is acked and+ // drained (the worker stream holds at most one alongside the stuck entry), so a+ // watchdog keyed on the last ack would never fire.+ let feeder = {+ let transport = Arc::clone(&transport);+ let url = url.clone();+ tokio::spawn(async move {+ for i in 0..40 {+ let _ = transport.begin_send(+ &url,+ &format!("sibling-{i}"),+ vec![msg("d2", 100 + i)],+ false,+ );+ tokio::time::sleep(Duration::from_millis(80)).await;+ }+ })+ };++ // The stuck send must fence on its own deadline (~500ms), well before the+ // feed stops (~3.2s) — proving sibling acks do not extend its wait.+ let err = tokio::time::timeout(Duration::from_secs(2), stuck.wait())+ .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[0].offset, 1);++ feeder.abort();+}++#[tokio::test]+async fn removing_a_worker_fences_its_in_flight_send_with_messages() {+ // Regression: reaping a worker that still has in-flight work must resolve+ // its un-acked sends with the messages intact, so the deferral path can+ // replay them. Aborting the worker stream task instead dropped the sends unresolved,+ // which the caller could only recover by crashing and replaying.+ let (_ack_tx, ack_rx) = mpsc::unbounded_channel();+ let mock = start_mock(AckMode::Manual, Some(ack_rx)).await;+ let transport = GrpcTransport::new(+ GrpcPort::Fixed(mock.addr.port()),+ 2,+ Duration::from_millis(200),+ );+ let url = worker_url(mock.addr);++ let pending = transport.begin_send(&url, "batch-1", vec![msg("d1", 1)], false);+ // Wait until the send is on the wire (in the worker stream's ledger) before reaping.+ for _ in 0..200 {+ if mock.received.lock().await.len() == 1 {+ break;+ }+ tokio::time::sleep(Duration::from_millis(5)).await;+ }+ assert_eq!(+ mock.received.lock().await.len(),+ 1,+ "send reached the worker"+ );++ transport.remove_worker(&url);++ let err = tokio::time::timeout(Duration::from_secs(5), pending.wait())+ .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[0].offset, 1);+}++#[tokio::test]+async fn a_busy_status_fences_as_retriable_with_messages() {+ // A worker reporting busy is applying backpressure, not failing: the fenced+ // sends must carry their messages (to replay) and classify as retriable, so+ // the consumer re-routes without counting the worker as unhealthy.+ let mock = start_mock(AckMode::BusySeq(1), None).await;+ let transport = GrpcTransport::new(+ GrpcPort::Fixed(mock.addr.port()),+ 1,+ Duration::from_secs(30),+ );+ let url = worker_url(mock.addr);++ let pending = transport.begin_send(&url, "batch-1", vec![msg("d1", 1)], false);+ let err = pending+ .wait()+ .await+ .expect_err("busy fences the worker stream");+ assert_eq!(err.messages.len(), 1, "messages come back for deferral");+ assert!(err.error.is_retriable(), "busy is retriable backpressure");+ assert!(matches!(err.error, TransportError::WorkerStreamBusy(_)));+}