: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): add P2C routing strategy behind config flag (#64326)
José Sequeira424b1e02f5e7
diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex 590b61ef188f..615e708cd69c 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -1,5 +1,5 @@import { Message } from 'node-rdkafka'-import { Counter, Histogram } from 'prom-client'+import { Counter, Gauge, Histogram } from 'prom-client'import { IntegrationManagerService } from '~/cdp/services/managers/integration-manager.service'@@ -131,6 +131,11 @@ const batchCapacityRejections = new Counter({help: 'Total number of batches rejected because the pipeline was at concurrent batch capacity',})+const batchesInFlight = new Gauge({+ name: 'ingestion_api_batches_in_flight',+ help: 'Number of accepted batches currently being processed by the ingestion API (concurrent batches)',+})+/*** Ingestion API server that exposes the ingestion pipeline as an HTTP endpoint.*@@ -413,6 +418,10 @@ export class IngestionApiServer implements NodeServer {const startTime = Date.now()+ // Tracks whether this batch was accepted, so the `finally` only+ // decrements the in-flight gauge for batches that incremented it.+ let inFlight = false+try {const messages: Message[] = serializedMessages.map(deserializeKafkaMessage)@@ -445,6 +454,11 @@ export class IngestionApiServer implements NodeServer {throw new Error(`Pipeline rejected batch: ${feedResult.reason}`)}+ // Batch accepted into the pipeline — it now occupies a concurrent+ // slot until processing completes below.+ batchesInFlight.inc()+ inFlight = true+let result = await this.joinedPipeline.next()while (result !== null) {for (const sideEffect of result.sideEffects ?? []) {@@ -478,6 +492,10 @@ export class IngestionApiServer implements NodeServer {void this.stop(error)}res.status(500).json({ batch_id, status: 'error', accepted: 0, error: error.message })+ } finally {+ if (inFlight) {+ batchesInFlight.dec()+ }}}diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rsindex 9411ebea7e3d..2f56167d370e 100644--- a/rust/ingestion-consumer/src/config.rs+++ b/rust/ingestion-consumer/src/config.rs@@ -3,6 +3,7 @@ use rdkafka::ClientConfig;use tracing::info;use crate::kafka_config::ConsumerConfigBuilder;+use crate::routing::RoutingStrategy;/// Configuration for the ingestion consumer.///@@ -139,6 +140,12 @@ pub struct Config {#[envconfig(default = "")]pub internal_api_secret: String,+ /// How unpinned routing keys are assigned to workers: `binpack` (default,+ /// least-loaded — accurate for the co-located sidecar) or `p2c`+ /// (power-of-two-choices — herd-resistant for a shared worker pool).+ #[envconfig(from = "INGESTION_ROUTING_STRATEGY", default = "binpack")]+ pub routing_strategy: RoutingStrategy,+// ---- Worker health / registry ----/// How often to probe each worker's /_ready endpoint (milliseconds).#[envconfig(default = "5000")]diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rsindex 59a41594ad33..e84f78db610d 100644--- a/rust/ingestion-consumer/src/consumer.rs+++ b/rust/ingestion-consumer/src/consumer.rs@@ -165,6 +165,10 @@ impl IngestionConsumer {let mut accepting_new_batches = true;while accepting_new_batches || !in_flight_batches.is_empty() {+ // Consumer-level concurrency: how many Kafka batches are being+ // processed in parallel, bounded by `max_in_flight_batches`.+ gauge!("ingestion_consumer_in_flight_batches").set(in_flight_batches.len() as f64);+if accepting_new_batches && in_flight_batches.len() < self.max_in_flight_batches {tokio::select! {_ = self.handle.shutdown_recv() => {diff --git a/rust/ingestion-consumer/src/dispatcher.rs b/rust/ingestion-consumer/src/dispatcher.rsindex 0b67049120a5..6875b1b6a8fb 100644--- a/rust/ingestion-consumer/src/dispatcher.rs+++ b/rust/ingestion-consumer/src/dispatcher.rs@@ -3,6 +3,7 @@ use std::sync::{Arc, Mutex};use metrics::{counter, gauge, histogram};+use crate::routing::{Router, RoutingStrategy};use crate::types::SerializedKafkaMessage;use crate::worker_registry::{WorkerRegistry, WorkerState};@@ -29,9 +30,9 @@ struct Pin {struct PinTable {/// `"{token}:{distinct_id}"` → sticky assignment.pins: HashMap<String, Pin>,- /// Outstanding (in-flight) message count per worker. Used for bin-packing:- /// new key-groups are assigned to whichever healthy worker carries the- /// fewest outstanding messages, so load is balanced by volume rather than+ /// Outstanding (in-flight) message count per worker. Both routing strategies+ /// use it as the per-worker load signal so new key-groups land on+ /// lightly-loaded workers — load is balanced by message volume rather than/// by sub-batch count.in_flight_messages: Vec<usize>,}@@ -51,15 +52,9 @@ impl PinTable {before - self.pins.len()}- /// Pick the healthy/degraded worker carrying the fewest outstanding- /// messages — existing in-flight load plus what has been provisionally- /// assigned earlier in this round. Returns None when no healthy workers- /// exist.- fn least_loaded_healthy(- &self,- registry: &WorkerRegistry,- provisional: &[usize],- ) -> Option<usize> {+ /// Candidate worker indices for routing: those currently healthy or+ /// degraded (dead/unhealthy workers are excluded). Returned in index order.+ fn healthy_workers(&self, registry: &WorkerRegistry) -> Vec<usize> {(0..self.in_flight_messages.len()).filter(|&idx| {matches!(@@ -67,7 +62,7 @@ impl PinTable {WorkerState::Healthy | WorkerState::Degraded)})- .min_by_key(|&idx| self.in_flight_messages[idx] + provisional[idx])+ .collect()}}@@ -94,8 +89,9 @@ impl WorkerSubBatchBuilder {#[derive(Default)]struct WorkerAssignments {by_worker: HashMap<usize, WorkerSubBatchBuilder>,- /// Messages provisionally assigned to each worker so far this round. Drives- /// least-loaded bin-packing so the largest groups steer load by volume.+ /// Messages provisionally assigned to each worker so far this round. Both+ /// routing strategies add it to in-flight load so intra-batch placement+ /// accounts for groups already routed earlier in the same round.provisional_messages: Vec<usize>,}@@ -152,8 +148,8 @@ impl WorkerAssignments {/// Routes batches to Node.js workers with sticky per-distinct_id assignment.////// **Assignment** (`assign`): groups messages by `token:distinct_id`, honors-/// existing pins for live workers, bin-packs new keys onto the least-loaded-/// healthy worker, and returns one `SubBatch` per worker.+/// existing pins for live workers, routes new keys onto a healthy worker via the+/// configured [`RoutingStrategy`], and returns one `SubBatch` per worker.////// **Stickiness**: a routing key stays on the same worker across batches/// (ref-counted pin). Pins are dropped when a worker is declared dead or@@ -165,14 +161,39 @@ impl WorkerAssignments {pub struct Dispatcher {pin_table: Mutex<PinTable>,registry: Arc<WorkerRegistry>,+ /// Worker selector for unpinned keys. Behind its own mutex because P2C+ /// selection mutates the RNG.+ router: Mutex<Router>,}impl Dispatcher {+ /// Construct a dispatcher with the default routing strategy.pub fn new(registry: Arc<WorkerRegistry>) -> Self {+ Self::with_strategy(registry, RoutingStrategy::default())+ }++ /// Construct a dispatcher with an explicit routing strategy.+ pub fn with_strategy(registry: Arc<WorkerRegistry>, strategy: RoutingStrategy) -> Self {+ let worker_count = registry.worker_count();+ Self {+ pin_table: Mutex::new(PinTable::new(worker_count)),+ registry,+ router: Mutex::new(Router::new(strategy)),+ }+ }++ /// Test-only constructor with a seeded RNG so P2C selection is deterministic.+ #[cfg(test)]+ fn with_strategy_seeded(+ registry: Arc<WorkerRegistry>,+ strategy: RoutingStrategy,+ seed: u64,+ ) -> Self {let worker_count = registry.worker_count();Self {pin_table: Mutex::new(PinTable::new(worker_count)),registry,+ router: Mutex::new(Router::with_seed(strategy, seed)),}}@@ -182,8 +203,8 @@ impl Dispatcher {/// 1. Drop pins for workers that are now dead./// 2. Group messages by routing key./// 3. Honor existing pins for live workers; collect unassigned groups.- /// 4. Largest-first bin-pack unassigned groups onto healthy/degraded- /// workers by current outstanding message load.+ /// 4. Route unassigned groups onto healthy/degraded workers via the+ /// configured strategy (bin-packing or P2C)./// 5. Add routed messages to in-flight load and bump pin ref-counts./// 6. Return one `SubBatch` per worker.///@@ -225,21 +246,29 @@ impl Dispatcher {}_ => {// No pin or pinned to a dead worker — drop stale entry and- // queue for bin-packing.+ // queue for routing by the configured strategy.table.pins.remove(&group.routing_key);unpinned_groups.push(group);}}}- // Largest-first bin-pack: assign the biggest key-groups first so- // heavy hitters drive the load distribution.- unpinned_groups.sort_unstable_by(|a, b| b.messages.len().cmp(&a.messages.len()));+ // Route the unpinned groups via the configured strategy. Bin-packing+ // wants the biggest groups placed first so heavy hitters drive the load+ // distribution; P2C is per-group and order-independent.+ let healthy = table.healthy_workers(&self.registry);+ let mut router = self.router.lock().unwrap();++ if router.prefers_largest_first() {+ unpinned_groups.sort_unstable_by(|a, b| b.messages.len().cmp(&a.messages.len()));+ }for group in unpinned_groups {- let Some(worker_idx) =- table.least_loaded_healthy(&self.registry, assignments.provisional_messages())- else {+ let Some(worker_idx) = router.select(+ &healthy,+ &table.in_flight_messages,+ assignments.provisional_messages(),+ ) else {// All workers unhealthy — this key cannot be assigned.counter!("ingestion_consumer_dispatcher_unroutable_messages_total").increment(group.messages.len() as u64);@@ -256,6 +285,7 @@ impl Dispatcher {assignments.add_group(worker_idx, group);}+ drop(router);// Add each worker's message volume to its outstanding load.for (worker_idx, message_count) in assignments.routed_counts() {@@ -768,4 +798,79 @@ mod tests {let b = dispatcher.assign(make_msgs(&[("t", "user-1")]));assert!(b.is_empty());}++ // ---- P2C routing strategy ----++ fn p2c_dispatcher(n: usize, seed: u64) -> Dispatcher {+ Dispatcher::with_strategy_seeded(healthy_registry(n), RoutingStrategy::P2c, seed)+ }++ #[test]+ fn test_p2c_single_worker_all_messages_go_there() {+ let dispatcher = p2c_dispatcher(1, 1);++ let sub_batches = dispatcher.assign(make_msgs(&[("t", "a"), ("t", "b"), ("t", "c")]));++ assert_eq!(sub_batches.len(), 1);+ assert_eq!(sub_batches[0].worker_idx, 0);+ assert_eq!(sub_batches[0].messages.len(), 3);+ }++ #[test]+ fn test_p2c_pin_is_sticky_across_batches() {+ let dispatcher = p2c_dispatcher(3, 7);++ // First batch pins "t:user-1"; do NOT resolve so the pin stays alive.+ let b1 = dispatcher.assign(make_msgs(&[("t", "user-1")]));+ let pinned_worker = b1[0].worker_idx;++ // Second batch with the same key must hit the same worker, bypassing P2C.+ let b2 = dispatcher.assign(make_msgs(&[("t", "user-1")]));+ assert_eq!(b2.len(), 1);+ assert_eq!(b2[0].worker_idx, pinned_worker);+ }++ #[test]+ fn test_p2c_spreads_fresh_keys_across_two_workers() {+ // With two workers, P2C samples both and the provisional bump after the+ // first key steers the second to the other worker — one message each.+ let dispatcher = p2c_dispatcher(2, 3);++ let sub_batches = dispatcher.assign(make_msgs(&[("t", "user-1"), ("t", "user-2")]));++ assert_eq!(sub_batches.len(), 2, "both workers must carry a message");+ let total: usize = sub_batches.iter().map(|b| b.messages.len()).sum();+ assert_eq!(total, 2);+ }++ #[test]+ fn test_p2c_prefers_least_loaded_of_two_workers() {+ // With two workers P2C always compares both, so a pre-loaded worker 0+ // sends the fresh key to worker 1.+ let dispatcher = p2c_dispatcher(2, 9);+ {+ let mut table = dispatcher.pin_table.lock().unwrap();+ table.in_flight_messages[0] = 5;+ }++ let b = dispatcher.assign(make_msgs(&[("t", "fresh")]));+ assert_eq!(b.len(), 1);+ assert_eq!(b[0].worker_idx, 1);+ }++ #[tokio::test]+ async fn test_p2c_all_workers_dead_returns_empty() {+ let registry = healthy_registry(2);+ let dispatcher =+ Dispatcher::with_strategy_seeded(Arc::clone(®istry), RoutingStrategy::P2c, 1);++ for idx in 0..2 {+ for _ in 0..5 {+ registry.record_outcome(idx, true);+ }+ }++ let b = dispatcher.assign(make_msgs(&[("t", "user-1")]));+ assert!(b.is_empty());+ }}diff --git a/rust/ingestion-consumer/src/lib.rs b/rust/ingestion-consumer/src/lib.rsindex d68e268faed2..5ee64b036fb7 100644--- a/rust/ingestion-consumer/src/lib.rs+++ b/rust/ingestion-consumer/src/lib.rs@@ -2,6 +2,7 @@ pub mod config;pub mod consumer;pub mod dispatcher;pub mod kafka_config;+pub mod routing;pub mod transport;pub mod types;pub mod worker_registry;diff --git a/rust/ingestion-consumer/src/main.rs b/rust/ingestion-consumer/src/main.rsindex 1e335bba82c7..79bbbe0f92a1 100644--- a/rust/ingestion-consumer/src/main.rs+++ b/rust/ingestion-consumer/src/main.rs@@ -145,7 +145,10 @@ async fn async_main(config: Config) -> Result<()> {let probe_token = CancellationToken::new();Arc::clone(®istry).start_probing(probe_token.clone());- let dispatcher = Arc::new(Dispatcher::new(Arc::clone(®istry)));+ let dispatcher = Arc::new(Dispatcher::with_strategy(+ Arc::clone(®istry),+ config.routing_strategy,+ ));let api_secret = if config.internal_api_secret.is_empty() {Nonediff --git a/rust/ingestion-consumer/src/routing.rs b/rust/ingestion-consumer/src/routing.rsnew file mode 100644index 000000000000..e67ae73549fd--- /dev/null+++ b/rust/ingestion-consumer/src/routing.rs@@ -0,0 +1,292 @@+//! Worker selection strategies for unpinned routing keys.+//!+//! The dispatcher owns the stateful concerns (grouping, sticky pins, ref-counts,+//! in-flight accounting). This module is the pure decision layer: given the set+//! of healthy workers and their per-worker load, pick a target. Keeping it free+//! of dispatcher state makes the algorithms trivially unit-testable and lets the+//! routing policy evolve (P2C cost functions, subsetting) without touching the+//! dispatcher's bookkeeping.++use std::str::FromStr;++use rand::rngs::StdRng;+use rand::{Rng, SeedableRng};++/// How unpinned routing keys are assigned to workers. Pinned keys always go to+/// their existing worker regardless of strategy.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub enum RoutingStrategy {+ /// Largest-first bin-packing onto the globally least-loaded worker. Accurate+ /// when one consumer exclusively owns its workers (the co-located sidecar),+ /// because then this consumer's in-flight counts are the ground truth.+ #[default]+ BinPack,+ /// Power-of-two-choices: sample two random workers, pick the lighter. Herd+ /// resistant when many consumers share a worker pool, because each consumer+ /// samples a different random pair instead of converging on one global best.+ P2c,+}++impl FromStr for RoutingStrategy {+ type Err = String;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ match s.trim().to_lowercase().as_str() {+ "binpack" | "bin_pack" | "bin-pack" => Ok(RoutingStrategy::BinPack),+ "p2c" | "power_of_two" | "power-of-two" => Ok(RoutingStrategy::P2c),+ other => Err(format!(+ "unknown routing strategy '{other}' (expected 'binpack' or 'p2c')"+ )),+ }+ }+}++/// Stateful worker selector. Holds the routing strategy and, for P2C, the RNG+/// used to sample candidates. One per dispatcher; selection requires `&mut self`+/// because P2C advances the RNG.+pub struct Router {+ strategy: RoutingStrategy,+ rng: StdRng,+}++impl Router {+ /// Production constructor — seeds the RNG from system entropy.+ pub fn new(strategy: RoutingStrategy) -> Self {+ Self {+ strategy,+ rng: StdRng::from_entropy(),+ }+ }++ /// Deterministic constructor for tests — seeds the RNG from a fixed value.+ #[cfg(test)]+ pub fn with_seed(strategy: RoutingStrategy, seed: u64) -> Self {+ Self {+ strategy,+ rng: StdRng::seed_from_u64(seed),+ }+ }++ pub fn strategy(&self) -> RoutingStrategy {+ self.strategy+ }++ /// Whether the caller should present groups largest-first before selecting.+ /// Bin-packing wants the heavy hitters placed first so they drive the load+ /// distribution; P2C is per-group and order-independent.+ pub fn prefers_largest_first(&self) -> bool {+ matches!(self.strategy, RoutingStrategy::BinPack)+ }++ /// Select a worker for one group. `healthy` lists candidate worker indices;+ /// `in_flight` and `provisional` are indexed by worker index, and a worker's+ /// load is their sum (outstanding messages plus what has been provisionally+ /// assigned earlier in this round). Returns `None` when no workers are+ /// healthy.+ pub fn select(+ &mut self,+ healthy: &[usize],+ in_flight: &[usize],+ provisional: &[usize],+ ) -> Option<usize> {+ match self.strategy {+ RoutingStrategy::BinPack => select_least_loaded(healthy, in_flight, provisional),+ RoutingStrategy::P2c => select_p2c(healthy, in_flight, provisional, &mut self.rng),+ }+ }+}++/// Pick the globally least-loaded healthy worker. Ties resolve to the lowest+/// worker index (matching the prior `min_by_key` behavior).+fn select_least_loaded(+ healthy: &[usize],+ in_flight: &[usize],+ provisional: &[usize],+) -> Option<usize> {+ healthy+ .iter()+ .copied()+ .min_by_key(|&idx| in_flight[idx] + provisional[idx])+}++/// Pick the lighter of two distinct random healthy workers. Degenerates to the+/// single worker when the pool has one, and to `None` when it is empty.+fn select_p2c(+ healthy: &[usize],+ in_flight: &[usize],+ provisional: &[usize],+ rng: &mut impl Rng,+) -> Option<usize> {+ let load = |idx: usize| in_flight[idx] + provisional[idx];+ match healthy.len() {+ 0 => None,+ 1 => Some(healthy[0]),+ len => {+ // Sample two distinct *positions* in one step (no redraw loop): pick+ // the first, then offset by 1..len to land on a different position.+ // This terminates regardless of the slice's contents, so it stays+ // correct even if a caller ever passes duplicate worker indices.+ let i = rng.gen_range(0..len);+ let j = (i + 1 + rng.gen_range(0..len - 1)) % len;+ let (a, b) = (healthy[i], healthy[j]);+ Some(if load(a) <= load(b) { a } else { b })+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ // ---- strategy parsing ----++ #[test]+ fn test_routing_strategy_parses_known_values() {+ assert_eq!("binpack".parse(), Ok(RoutingStrategy::BinPack));+ assert_eq!("bin-pack".parse(), Ok(RoutingStrategy::BinPack));+ assert_eq!("p2c".parse(), Ok(RoutingStrategy::P2c));+ assert_eq!("power-of-two".parse(), Ok(RoutingStrategy::P2c));+ }++ #[test]+ fn test_routing_strategy_is_case_and_whitespace_insensitive() {+ assert_eq!(" P2C ".parse(), Ok(RoutingStrategy::P2c));+ assert_eq!("BinPack".parse(), Ok(RoutingStrategy::BinPack));+ }++ #[test]+ fn test_routing_strategy_rejects_unknown_value() {+ assert!("round-robin".parse::<RoutingStrategy>().is_err());+ }++ #[test]+ fn test_routing_strategy_defaults_to_binpack() {+ assert_eq!(RoutingStrategy::default(), RoutingStrategy::BinPack);+ }++ // ---- least-loaded ----++ #[test]+ fn test_least_loaded_picks_minimum_load() {+ let healthy = [0, 1, 2];+ let in_flight = [5, 1, 3];+ let provisional = [0, 0, 0];+ assert_eq!(+ select_least_loaded(&healthy, &in_flight, &provisional),+ Some(1)+ );+ }++ #[test]+ fn test_least_loaded_sums_in_flight_and_provisional() {+ let healthy = [0, 1];+ let in_flight = [0, 1];+ // Provisional flips which worker is lighter.+ let provisional = [3, 0];+ assert_eq!(+ select_least_loaded(&healthy, &in_flight, &provisional),+ Some(1)+ );+ }++ #[test]+ fn test_least_loaded_breaks_ties_to_lowest_index() {+ let healthy = [0, 1, 2];+ let in_flight = [2, 2, 2];+ let provisional = [0, 0, 0];+ assert_eq!(+ select_least_loaded(&healthy, &in_flight, &provisional),+ Some(0)+ );+ }++ #[test]+ fn test_least_loaded_empty_pool_returns_none() {+ assert_eq!(select_least_loaded(&[], &[], &[]), None);+ }++ // ---- p2c ----++ #[test]+ fn test_p2c_empty_pool_returns_none() {+ let mut rng = StdRng::seed_from_u64(1);+ assert_eq!(select_p2c(&[], &[], &[], &mut rng), None);+ }++ #[test]+ fn test_p2c_single_worker_returns_it() {+ let mut rng = StdRng::seed_from_u64(1);+ assert_eq!(select_p2c(&[2], &[0, 0, 9], &[0, 0, 0], &mut rng), Some(2));+ }++ #[test]+ fn test_p2c_two_workers_always_picks_lighter() {+ // With exactly two candidates, sampling-without-replacement always draws+ // both, so the lighter one is chosen deterministically regardless of seed.+ for seed in 0..16 {+ let mut rng = StdRng::seed_from_u64(seed);+ assert_eq!(+ select_p2c(&[0, 1], &[3, 0], &[0, 0], &mut rng),+ Some(1),+ "seed {seed}"+ );+ }+ }++ #[test]+ fn test_p2c_terminates_with_duplicate_indices() {+ // Regression: selection must not loop even if the candidate slice+ // contains duplicate worker indices.+ let mut rng = StdRng::seed_from_u64(1);+ for _ in 0..50 {+ assert_eq!(+ select_p2c(&[2, 2], &[0, 0, 0], &[0, 0, 0], &mut rng),+ Some(2)+ );+ }+ }++ #[test]+ fn test_p2c_only_ever_returns_a_healthy_worker() {+ let healthy = [1, 3, 4];+ let in_flight = [0, 2, 0, 5, 1];+ let provisional = [0; 5];+ let mut rng = StdRng::seed_from_u64(7);+ for _ in 0..200 {+ let pick = select_p2c(&healthy, &in_flight, &provisional, &mut rng).unwrap();+ assert!(healthy.contains(&pick));+ }+ }++ #[test]+ fn test_p2c_spreads_load_across_pool() {+ // A heavily skewed start should let P2C drain onto every worker over many+ // rounds (it never gets stuck on one). Assert all workers get picked.+ let healthy = [0, 1, 2, 3];+ let in_flight = [0, 0, 0, 0];+ let provisional = [0; 4];+ let mut rng = StdRng::seed_from_u64(42);+ let mut seen = [false; 4];+ for _ in 0..200 {+ let pick = select_p2c(&healthy, &in_flight, &provisional, &mut rng).unwrap();+ seen[pick] = true;+ }+ assert!(seen.iter().all(|&s| s), "every worker should be reachable");+ }++ // ---- router dispatch ----++ #[test]+ fn test_router_binpack_selects_least_loaded() {+ let mut router = Router::new(RoutingStrategy::BinPack);+ assert!(router.prefers_largest_first());+ assert_eq!(router.select(&[0, 1, 2], &[4, 1, 2], &[0, 0, 0]), Some(1));+ }++ #[test]+ fn test_router_p2c_does_not_prefer_largest_first() {+ let router = Router::with_seed(RoutingStrategy::P2c, 1);+ assert!(!router.prefers_largest_first());+ assert_eq!(router.strategy(), RoutingStrategy::P2c);+ }+}diff --git a/rust/ingestion-consumer/src/transport.rs b/rust/ingestion-consumer/src/transport.rsindex 65b547b2be6d..59e73d361329 100644--- a/rust/ingestion-consumer/src/transport.rs+++ b/rust/ingestion-consumer/src/transport.rs@@ -2,12 +2,37 @@ use std::collections::HashMap;use std::sync::Arc;use std::time::Duration;-use metrics::{counter, histogram};+use metrics::{counter, gauge, histogram};use tokio::sync::Semaphore;use tracing::{error, info, warn};use crate::types::{IngestBatchRequest, IngestBatchResponse, SerializedKafkaMessage};+/// RAII guard that tracks the number of batches currently in flight to a+/// worker. Increments the gauge on creation and decrements on drop, so every+/// `send_batch` return path (success, error, retries exhausted, panic unwind)+/// is covered — mirroring the lifetime of the worker's `Semaphore` permit.+struct InFlightGuard {+ worker_url: String,+}++impl InFlightGuard {+ fn new(worker_url: &str) -> Self {+ gauge!("ingestion_consumer_transport_concurrent_batches", "worker" => worker_url.to_string())+ .increment(1.0);+ Self {+ worker_url: worker_url.to_string(),+ }+ }+}++impl Drop for InFlightGuard {+ fn drop(&mut self) {+ gauge!("ingestion_consumer_transport_concurrent_batches", "worker" => self.worker_url.clone())+ .decrement(1.0);+ }+}+/// Sends batches to Node.js worker processes over HTTP.////// Uses reqwest with connection pooling (one pool per worker URL).@@ -152,6 +177,10 @@ impl HttpTransport {}};+ // Now that the permit is held, this batch is genuinely in flight to the+ // worker. The guard decrements the gauge on every return path.+ let _in_flight = InFlightGuard::new(worker_url);+let mut last_err = None;for attempt in 0..=self.max_retries {if attempt > 0 {