:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(ingestion-consumer): cap per-worker batches with semaphore (#58802)
José Sequeira3339223ac196
diff --git a/nodejs/src/ingestion/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/analytics/joined-ingestion-pipeline.tsindex 38a307e47939..f3b3a3355ccb 100644--- a/nodejs/src/ingestion/analytics/joined-ingestion-pipeline.ts+++ b/nodejs/src/ingestion/analytics/joined-ingestion-pipeline.ts@@ -67,6 +67,14 @@ export interface JoinedIngestionPipelineConfig {>splitAiEventsConfig: SplitAiEventsStepConfigperDistinctIdOptions: EventPipelineRunnerOptions+ /**+ * Maximum number of batches the BatchingPipeline will accept concurrently.+ * Sourced from `INGESTION_WORKER_CONCURRENT_BATCHES` and MUST match the+ * Rust consumer's per-worker `Semaphore` capacity — divergence causes+ * either idle capacity (consumer under-limits) or HTTP 503s+ * (`ingestion_api_batch_capacity_rejections_total`).+ */+ concurrentBatches: number}export interface JoinedIngestionPipelineDeps {@@ -125,6 +133,7 @@ export function createJoinedIngestionPipeline<outputs,splitAiEventsConfig,perDistinctIdOptions,+ concurrentBatches,} = configconst {@@ -223,6 +232,9 @@ export function createJoinedIngestionPipeline<.pipe(createFlushEventFiltersBatchAppMetricsStep()),// Batch stores (personsStore, groupStore) are singletons that don't support// concurrent batches yet — they accumulate state across events and flush once.- { concurrentBatches: 1 }+ // The Rust consumer's per-worker Semaphore caps in-flight batches at the+ // same value (INGESTION_WORKER_CONCURRENT_BATCHES); divergence shows up as+ // HTTP 503s in `ingestion_api_batch_capacity_rejections_total`.+ { concurrentBatches })}diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.tsindex 763948fd633c..cbc446a9004c 100644--- a/nodejs/src/ingestion/config.ts+++ b/nodejs/src/ingestion/config.ts@@ -110,6 +110,12 @@ export type IngestionConsumerConfig = {INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID: stringINGESTION_OVERFLOW_PRESERVE_PARTITION_LOCALITY: boolean+ // Maximum in-flight batches per worker (BatchingPipeline.concurrentBatches).+ // Mirrors INGESTION_WORKER_CONCURRENT_BATCHES on the Rust consumer side —+ // both values MUST agree, otherwise either the Rust consumer over-limits+ // (idle worker capacity) or the worker rejects with HTTP 503.+ INGESTION_WORKER_CONCURRENT_BATCHES: number+// Person batch writing configPERSON_BATCH_WRITING_DB_WRITE_MODE: PersonBatchWritingDbWriteModePERSON_BATCH_WRITING_USE_BATCH_UPDATES: boolean@@ -219,6 +225,7 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {INGESTION_OVERFLOW_ENABLED: false,INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID: '',INGESTION_OVERFLOW_PRESERVE_PARTITION_LOCALITY: false,+ INGESTION_WORKER_CONCURRENT_BATCHES: 1,// Person batch writing configPERSON_BATCH_WRITING_DB_WRITE_MODE: 'NO_ASSERT',diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.tsindex 7625464ae08e..dbbd704a1fd1 100644--- a/nodejs/src/ingestion/ingestion-consumer.ts+++ b/nodejs/src/ingestion/ingestion-consumer.ts@@ -272,6 +272,7 @@ export class IngestionConsumer {PERSON_JSONB_SIZE_ESTIMATE_ENABLE: this.config.PERSON_JSONB_SIZE_ESTIMATE_ENABLE,PERSON_PROPERTIES_UPDATE_ALL: this.config.PERSON_PROPERTIES_UPDATE_ALL,},+ concurrentBatches: this.config.INGESTION_WORKER_CONCURRENT_BATCHES,}const joinedPipelineDeps: JoinedIngestionPipelineDeps = {personsStore: this.personsStore,diff --git a/nodejs/src/ingestion/pipelines/batching-pipeline.ts b/nodejs/src/ingestion/pipelines/batching-pipeline.tsindex fa22c9d80785..3ece1b8fed0a 100644--- a/nodejs/src/ingestion/pipelines/batching-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/batching-pipeline.ts@@ -3,7 +3,9 @@ import { createOkContext } from './helpers'import { Pipeline, PipelineResultWithContext } from './pipeline.interface'import { PipelineResult, isOkResult } from './results'-export type FeedResult = { ok: true } | { ok: false; reason: string }+export type FeedRejectionKind = 'at_capacity' | 'before_batch_failed'++export type FeedResult = { ok: true } | { ok: false; kind: FeedRejectionKind; reason: string }export interface BatchingContext {messageId: number@@ -123,7 +125,11 @@ export class BatchingPipeline<async feed(elements: OkResultWithContext<TInput, CInput>[]): Promise<FeedResult> {if (this.batches.size >= this.options.concurrentBatches) {- return { ok: false, reason: `at concurrent batch capacity (${this.options.concurrentBatches})` }+ return {+ ok: false,+ kind: 'at_capacity',+ reason: `at concurrent batch capacity (${this.options.concurrentBatches})`,+ }}const batchId = this.nextBatchId++@@ -132,7 +138,11 @@ export class BatchingPipeline<const beforeResult = await this.beforePipeline.process(createOkContext(beforeInput, {}))if (!isOkResult(beforeResult.result)) {- return { ok: false, reason: `beforeBatch hook returned non-ok result for batch ${batchId}` }+ return {+ ok: false,+ kind: 'before_batch_failed',+ reason: `beforeBatch hook returned non-ok result for batch ${batchId}`,+ }}const { elements: mappedElements, batchContext } = beforeResult.result.valuediff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex 2b8b3c7ae8e9..442871b3bbac 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -123,6 +123,11 @@ const batchErrors = new Counter({help: 'Total number of batch processing errors',})+const batchCapacityRejections = new Counter({+ name: 'ingestion_api_batch_capacity_rejections_total',+ help: 'Total number of batches rejected because the pipeline was at concurrent batch capacity',+})+/*** Ingestion API server that exposes the ingestion pipeline as an HTTP endpoint.*@@ -340,6 +345,7 @@ export class IngestionApiServer implements NodeServer {PERSON_JSONB_SIZE_ESTIMATE_ENABLE: this.config.PERSON_JSONB_SIZE_ESTIMATE_ENABLE,PERSON_PROPERTIES_UPDATE_ALL: this.config.PERSON_PROPERTIES_UPDATE_ALL,},+ concurrentBatches: this.config.INGESTION_WORKER_CONCURRENT_BATCHES,}const joinedPipelineDeps: JoinedIngestionPipelineDeps = {personsStore,@@ -376,7 +382,9 @@ export class IngestionApiServer implements NodeServer {private async handleIngestRequest(req: { body: IngestBatchRequest },- res: { status: (code: number) => { json: (body: IngestBatchResponse) => void } }+ res: {+ status: (code: number) => { json: (body: IngestBatchResponse) => void }+ }): Promise<void> {const { batch_id, messages: serializedMessages } = req.body@@ -393,6 +401,29 @@ export class IngestionApiServer implements NodeServer {const batch = messages.map((message) => createOkContext({ message }, { message }))const feedResult = await this.joinedPipeline.feed(batch)if (!feedResult.ok) {+ // Capacity rejection should not happen under correct consumer+ // behavior — the Rust consumer holds a per-worker Semaphore+ // sized to INGESTION_WORKER_CONCURRENT_BATCHES and is supposed+ // to wait (natural backpressure) before sending a batch that+ // would exceed the worker's capacity. If we land here, the+ // consumer's tracking is wrong or its env-var value disagrees+ // with ours. Respond 503 so the consumer surfaces it as a+ // distinct error (TransportError::WorkerBusy) and the alarm is+ // visible in `ingestion_api_batch_capacity_rejections_total`.+ // Use the typed `kind` discriminator (not the human-readable+ // `reason` string) so a future BatchingPipeline message tweak+ // can't silently downgrade us to a fall-through 500 — which+ // the Rust transport treats as retriable.+ if (feedResult.kind === 'at_capacity') {+ batchCapacityRejections.inc()+ res.status(503).json({+ batch_id: batch_id ?? '',+ status: 'error',+ accepted: 0,+ error: feedResult.reason,+ })+ return+ }throw new Error(`Pipeline rejected batch: ${feedResult.reason}`)}@@ -406,9 +437,6 @@ export class IngestionApiServer implements NodeServer {// Wait for all side effects — the HTTP response is the ACK to the// Rust consumer, so all work must finish before responding.- // Note: the joined pipeline has a hardcoded concurrency of 1, so- // feed() will reject if a batch is already being processed. This- // is fine for now since we process each request sequentially.await Promise.all([this.promiseScheduler.waitForAll(), this.hogTransformer.processInvocationResults()])batchesProcessed.inc()diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rsindex b34eba216bfe..aa8dae3a103d 100644--- a/rust/ingestion-consumer/src/config.rs+++ b/rust/ingestion-consumer/src/config.rs@@ -121,6 +121,15 @@ pub struct Config {#[envconfig(default = "3")]pub max_retries: u32,+ /// Maximum in-flight batches per worker. MUST match+ /// `INGESTION_WORKER_CONCURRENT_BATCHES` on the Node.js side, which is+ /// passed into `BatchingPipeline.concurrentBatches`. The consumer caps+ /// itself via a per-worker `Semaphore`; the worker still responds 503+ /// if it sees `feed()` rejection, so any divergence is observable via+ /// `ingestion_api_batch_capacity_rejections_total`.+ #[envconfig(from = "INGESTION_WORKER_CONCURRENT_BATCHES", default = "1")]+ pub ingestion_worker_concurrent_batches: usize,+/// Shared secret for authenticating with Node.js workers (X-Internal-Api-Secret header)#[envconfig(default = "")]pub internal_api_secret: String,diff --git a/rust/ingestion-consumer/src/main.rs b/rust/ingestion-consumer/src/main.rsindex 0588d4c8aa96..eb376a2a99c5 100644--- a/rust/ingestion-consumer/src/main.rs+++ b/rust/ingestion-consumer/src/main.rs@@ -105,10 +105,13 @@ async fn async_main(config: Config) -> Result<()> {} else {Some(config.internal_api_secret.clone())};+ let worker_urls = config.worker_urls();let transport = Arc::new(HttpTransport::new(Duration::from_millis(config.http_timeout_ms),config.max_retries,api_secret,+ &worker_urls,+ config.ingestion_worker_concurrent_batches,));let consumer = IngestionConsumer::new(&config, transport, consumer_handle)diff --git a/rust/ingestion-consumer/src/transport.rs b/rust/ingestion-consumer/src/transport.rsindex cc4fe76dabc5..65b547b2be6d 100644--- a/rust/ingestion-consumer/src/transport.rs+++ b/rust/ingestion-consumer/src/transport.rs@@ -1,6 +1,9 @@+use std::collections::HashMap;+use std::sync::Arc;use std::time::Duration;use metrics::{counter, histogram};+use tokio::sync::Semaphore;use tracing::{error, info, warn};use crate::types::{IngestBatchRequest, IngestBatchResponse, SerializedKafkaMessage};@@ -9,24 +12,56 @@ use crate::types::{IngestBatchRequest, IngestBatchResponse, SerializedKafkaMessa////// Uses reqwest with connection pooling (one pool per worker URL)./// Retries on 5xx/timeout with exponential backoff.+///+/// Per-worker `Semaphore`s cap how many concurrent batches we can have in+/// flight to each worker URL. The capacity must match the worker's own+/// `BatchingPipeline.concurrentBatches` setting (controlled by+/// `INGESTION_WORKER_CONCURRENT_BATCHES` on both sides). When all permits+/// are held, `send_batch` waits — this is the natural backpressure that+/// replaces retry-on-503. A 503 escaping to the transport indicates a+/// contract violation (mis-configured limits or a Rust-side timeout+/// leaving a worker still processing) and is treated as non-retriable.pub struct HttpTransport {client: reqwest::Client,max_retries: u32,api_secret: Option<String>,+ worker_semaphores: HashMap<String, Arc<Semaphore>>,}impl HttpTransport {- pub fn new(timeout: Duration, max_retries: u32, api_secret: Option<String>) -> Self {+ pub fn new(+ timeout: Duration,+ max_retries: u32,+ api_secret: Option<String>,+ worker_urls: &[String],+ worker_concurrent_batches: usize,+ ) -> Self {+ assert!(+ worker_concurrent_batches > 0,+ "worker_concurrent_batches must be > 0"+ );+let client = reqwest::Client::builder().timeout(timeout).pool_max_idle_per_host(4).build().expect("failed to create HTTP client");+ let worker_semaphores = worker_urls+ .iter()+ .map(|url| {+ (+ url.clone(),+ Arc::new(Semaphore::new(worker_concurrent_batches)),+ )+ })+ .collect();+Self {client,max_retries,api_secret,+ worker_semaphores,}}@@ -72,6 +107,12 @@ impl HttpTransport {}/// Send a sub-batch to a worker. Returns the number of accepted messages.+ ///+ /// Acquires a permit from the worker's `Semaphore` before sending. If+ /// `worker_concurrent_batches` permits are already held, the call waits+ /// here — that's the natural backpressure. The permit is released on+ /// drop, covering all return paths (success, retriable error, retries+ /// exhausted, non-retriable error).pub async fn send_batch(&self,worker_url: &str,@@ -86,6 +127,31 @@ impl HttpTransport {let url = format!("{worker_url}/ingest");+ let semaphore = self+ .worker_semaphores+ .get(worker_url)+ .ok_or_else(|| TransportError::UnknownWorker(worker_url.to_string()))?+ .clone();++ // Atomic "did we actually have to wait?" check. `available_permits`+ // followed by `acquire_owned` would race — a permit could be released+ // between the two (false positive) or stolen (false negative). Using+ // `try_acquire_owned` first gives an accurate backpressure counter.+ let _permit = match semaphore.clone().try_acquire_owned() {+ Ok(permit) => permit,+ Err(_) => {+ counter!(+ "ingestion_consumer_transport_backpressure_waits_total",+ "worker" => worker_url.to_string()+ )+ .increment(1);+ semaphore+ .acquire_owned()+ .await+ .expect("worker semaphore must not be closed")+ }+ };+let mut last_err = None;for attempt in 0..=self.max_retries {if attempt > 0 {@@ -122,7 +188,12 @@ impl HttpTransport {let elapsed = start.elapsed();histogram!("ingestion_consumer_transport_duration_seconds", "worker" => worker_url.to_string()).record(elapsed.as_secs_f64());- counter!("ingestion_consumer_transport_requests_total", "worker" => worker_url.to_string(), "status" => "error")+ let status_label = if matches!(err, TransportError::WorkerBusy(_)) {+ "busy"+ } else {+ "error"+ };+ counter!("ingestion_consumer_transport_requests_total", "worker" => worker_url.to_string(), "status" => status_label).increment(1);warn!(@@ -166,6 +237,15 @@ impl HttpTransport {let response = req_builder.send().await?;let status = response.status();+ // 503 means the worker is at concurrent batch capacity. The previous+ // batch is still being processed — surface as a distinct error so the+ // caller can apply a longer backoff instead of hammering with 100ms+ // retries (which all bounce off the same in-flight batch).+ if status == reqwest::StatusCode::SERVICE_UNAVAILABLE {+ let body = response.text().await.unwrap_or_default();+ return Err(TransportError::WorkerBusy(body));+ }+if status.is_client_error() || status.is_server_error() {let body = response.text().await.unwrap_or_default();return Err(TransportError::HttpStatus(status.as_u16(), body));@@ -181,23 +261,35 @@ pub enum TransportError {#[error("HTTP request failed: {0}")]Http(#[from] reqwest::Error),+ #[error("Worker busy (HTTP 503): {0}")]+ WorkerBusy(String),+#[error("Worker returned HTTP {0}: {1}")]HttpStatus(u16, String),#[error("Worker returned error: {0}")]WorkerError(String),+ #[error("Unknown worker URL: {0}")]+ UnknownWorker(String),+#[error("All retries exhausted")]RetriesExhausted,}impl TransportError {/// 4xx errors are non-transient and should not be retried.+ /// `WorkerBusy` (HTTP 503) is also non-retriable: the consumer's per-worker+ /// semaphore is supposed to prevent it from ever firing, so it indicates a+ /// contract violation rather than a transient condition — retrying just+ /// hammers an already-overloaded worker.pub fn is_retriable(&self) -> bool {match self {TransportError::HttpStatus(status, _) => *status >= 500,TransportError::Http(_) => true,+ TransportError::WorkerBusy(_) => false,TransportError::WorkerError(_) => true,+ TransportError::UnknownWorker(_) => false,TransportError::RetriesExhausted => false,}}diff --git a/rust/ingestion-consumer/tests/transport_integration_test.rs b/rust/ingestion-consumer/tests/transport_integration_test.rsindex 8b7fd7cd67bc..ebb7e6952c50 100644--- a/rust/ingestion-consumer/tests/transport_integration_test.rs+++ b/rust/ingestion-consumer/tests/transport_integration_test.rs@@ -1,14 +1,17 @@use std::collections::HashMap;+use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::{Arc, Mutex};use std::time::Duration;use axum::extract::Json;+use axum::response::IntoResponse;use axum::routing::post;use axum::Router;use tokio::net::TcpListener;+use tokio::time::sleep;use ingestion_consumer::router::MessageRouter;-use ingestion_consumer::transport::HttpTransport;+use ingestion_consumer::transport::{HttpTransport, TransportError};use ingestion_consumer::types::{IngestBatchRequest, IngestBatchResponse, SerializedKafkaMessage};fn make_message(@@ -89,12 +92,84 @@ async fn start_failing_worker() -> (String, tokio::task::JoinHandle<()>) {(url, handle)}+/// Spin up a mock worker that always returns 503 (worker-busy contract violation).+async fn start_always_busy_worker() -> (String, tokio::task::JoinHandle<()>) {+ let app = Router::new().route(+ "/ingest",+ post(|Json(req): Json<IngestBatchRequest>| async move {+ (+ axum::http::StatusCode::SERVICE_UNAVAILABLE,+ axum::Json(IngestBatchResponse {+ batch_id: req.batch_id,+ status: "error".to_string(),+ accepted: 0,+ error: Some("at concurrent batch capacity (1)".to_string()),+ }),+ )+ .into_response()+ }),+ );++ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let url = format!("http://127.0.0.1:{}", addr.port());++ let handle = tokio::spawn(async move {+ axum::serve(listener, app).await.unwrap();+ });++ (url, handle)+}++/// Spin up a mock worker that sleeps `delay` before responding ok. Records+/// the max number of overlapping in-flight requests it ever observed.+async fn start_slow_worker(+ delay: Duration,+ max_concurrent: Arc<AtomicUsize>,+) -> (String, tokio::task::JoinHandle<()>) {+ let in_flight = Arc::new(AtomicUsize::new(0));+ let app = Router::new().route(+ "/ingest",+ post({+ let in_flight = in_flight.clone();+ let max_concurrent = max_concurrent.clone();+ move |Json(req): Json<IngestBatchRequest>| {+ let in_flight = in_flight.clone();+ let max_concurrent = max_concurrent.clone();+ async move {+ let now = in_flight.fetch_add(1, Ordering::SeqCst) + 1;+ max_concurrent.fetch_max(now, Ordering::SeqCst);+ sleep(delay).await;+ in_flight.fetch_sub(1, Ordering::SeqCst);+ Json(IngestBatchResponse {+ batch_id: req.batch_id,+ status: "ok".to_string(),+ accepted: req.messages.len() as u32,+ error: None,+ })+ }+ }+ }),+ );++ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let url = format!("http://127.0.0.1:{}", addr.port());++ let handle = tokio::spawn(async move {+ axum::serve(listener, app).await.unwrap();+ });++ (url, handle)+}+#[tokio::test]async fn transport_sends_batch_and_receives_ack() {let received = Arc::new(Mutex::new(Vec::new()));let (url, _handle) = start_mock_worker(received.clone()).await;- let transport = HttpTransport::new(Duration::from_secs(5), 0, None);+ let urls = vec![url.clone()];+ let transport = HttpTransport::new(Duration::from_secs(5), 0, None, &urls, 1);let messages = vec![make_message("tok1", "user-a", 0, r#"{"event":"$pageview"}"#),@@ -126,7 +201,8 @@ async fn transport_sends_batch_and_receives_ack() {async fn transport_retries_on_server_error() {let (url, _handle) = start_failing_worker().await;- let transport = HttpTransport::new(Duration::from_secs(1), 2, None);+ let urls = vec![url.clone()];+ let transport = HttpTransport::new(Duration::from_secs(1), 2, None, &urls, 1);let messages = vec![make_message("tok", "user", 0, "{}")];@@ -134,17 +210,164 @@ async fn transport_retries_on_server_error() {assert!(result.is_err());}+#[tokio::test]+async fn transport_fails_fast_on_worker_busy_without_retry() {+ // The Rust consumer's per-worker semaphore is supposed to prevent 503s.+ // If the worker still returns 503, that's a contract violation, not a+ // transient state — fail immediately rather than hammering an already+ // overloaded worker.+ let (url, _handle) = start_always_busy_worker().await;++ let urls = vec![url.clone()];+ // max_retries = 3 — irrelevant for this path since WorkerBusy is non-retriable.+ let transport = HttpTransport::new(Duration::from_secs(5), 3, None, &urls, 1);++ let messages = vec![make_message("tok", "user", 0, "{}")];++ let start = std::time::Instant::now();+ let err = transport+ .send_batch(&url, "batch-busy", messages)+ .await+ .unwrap_err();+ let elapsed = start.elapsed();++ assert!(+ matches!(err, TransportError::WorkerBusy(_)),+ "expected WorkerBusy, got {err:?}"+ );+ // No retry backoff should have been applied (would have been ≥100ms+200ms+400ms = 700ms).+ assert!(+ elapsed < Duration::from_millis(200),+ "expected fail-fast on 503 (<200ms), got {elapsed:?}"+ );+}+#[tokio::test]async fn transport_fails_on_unreachable_worker() {- let transport = HttpTransport::new(Duration::from_secs(1), 0, None);+ let url = "http://127.0.0.1:1".to_string();+ let urls = vec![url.clone()];+ let transport = HttpTransport::new(Duration::from_secs(1), 0, None, &urls, 1);let messages = vec![make_message("tok", "user", 0, "{}")];- let result = transport- .send_batch("http://127.0.0.1:1", "batch-fail", messages)- .await;+ let result = transport.send_batch(&url, "batch-fail", messages).await;assert!(result.is_err());}+#[tokio::test]+async fn transport_rejects_send_to_unknown_worker() {+ // Caller bug: send_batch invoked with a URL that wasn't registered at+ // construction. We bail with UnknownWorker rather than silently bypassing+ // the semaphore.+ let urls = vec!["http://known-worker:9001".to_string()];+ let transport = HttpTransport::new(Duration::from_secs(1), 0, None, &urls, 1);++ let messages = vec![make_message("tok", "user", 0, "{}")];+ let err = transport+ .send_batch("http://unknown-worker:9999", "batch-x", messages)+ .await+ .unwrap_err();++ assert!(+ matches!(err, TransportError::UnknownWorker(_)),+ "expected UnknownWorker, got {err:?}"+ );+}++#[tokio::test]+async fn transport_serializes_concurrent_sends_to_same_worker() {+ // With concurrency=1 and a 500ms-slow worker, two parallel send_batch+ // calls must serialize: total elapsed ≈ 1s (not 500ms), and the worker+ // never sees more than 1 concurrent request.+ let max_concurrent = Arc::new(AtomicUsize::new(0));+ let (url, _h) = start_slow_worker(Duration::from_millis(500), max_concurrent.clone()).await;++ let urls = vec![url.clone()];+ let transport = Arc::new(HttpTransport::new(+ Duration::from_secs(5),+ 0,+ None,+ &urls,+ 1,+ ));++ let start = std::time::Instant::now();+ let mut handles = Vec::new();+ for i in 0..2 {+ let t = transport.clone();+ let u = url.clone();+ handles.push(tokio::spawn(async move {+ t.send_batch(+ &u,+ &format!("batch-{i}"),+ vec![make_message("tok", "u", 0, "{}")],+ )+ .await+ .unwrap()+ }));+ }+ for h in handles {+ h.await.unwrap();+ }+ let elapsed = start.elapsed();++ assert_eq!(+ max_concurrent.load(Ordering::SeqCst),+ 1,+ "semaphore must serialize calls to the same worker"+ );+ assert!(+ elapsed >= Duration::from_millis(900),+ "expected ≥900ms for serialized 500ms calls, got {elapsed:?}"+ );+}++#[tokio::test]+async fn transport_parallelizes_across_different_workers() {+ // Semaphores are per-URL: two different workers must run in parallel.+ let max_a = Arc::new(AtomicUsize::new(0));+ let max_b = Arc::new(AtomicUsize::new(0));+ let (url_a, _h_a) = start_slow_worker(Duration::from_millis(500), max_a.clone()).await;+ let (url_b, _h_b) = start_slow_worker(Duration::from_millis(500), max_b.clone()).await;++ let urls = vec![url_a.clone(), url_b.clone()];+ let transport = Arc::new(HttpTransport::new(+ Duration::from_secs(5),+ 0,+ None,+ &urls,+ 1,+ ));++ let start = std::time::Instant::now();+ let t1 = {+ let t = transport.clone();+ let u = url_a.clone();+ tokio::spawn(async move {+ t.send_batch(&u, "batch-a", vec![make_message("tok", "u", 0, "{}")])+ .await+ .unwrap()+ })+ };+ let t2 = {+ let t = transport.clone();+ let u = url_b.clone();+ tokio::spawn(async move {+ t.send_batch(&u, "batch-b", vec![make_message("tok", "u", 0, "{}")])+ .await+ .unwrap()+ })+ };+ t1.await.unwrap();+ t2.await.unwrap();+ let elapsed = start.elapsed();++ // ≈ 500ms (parallel), well under 1s (which would mean serialized).+ assert!(+ elapsed < Duration::from_millis(900),+ "expected ≈500ms for parallel workers, got {elapsed:?}"+ );+}+#[tokio::test]async fn router_and_transport_end_to_end() {// Start 2 mock workers@@ -155,7 +378,13 @@ async fn router_and_transport_end_to_end() {let worker_urls = [url_1.clone(), url_2.clone()];let router = MessageRouter::new(worker_urls.len());- let transport = Arc::new(HttpTransport::new(Duration::from_secs(5), 0, None));+ let transport = Arc::new(HttpTransport::new(+ Duration::from_secs(5),+ 0,+ None,+ &worker_urls,+ 1,+ ));// Create messages for multiple distinct_idslet messages = vec![@@ -223,7 +452,8 @@ async fn wire_format_preserves_unicode_and_null_fields() {let received = Arc::new(Mutex::new(Vec::new()));let (url, _handle) = start_mock_worker(received.clone()).await;- let transport = HttpTransport::new(Duration::from_secs(5), 0, None);+ let urls = vec![url.clone()];+ let transport = HttpTransport::new(Duration::from_secs(5), 0, None, &urls, 1);let messages = vec![SerializedKafkaMessage {topic: "test".to_string(),