: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): worker discovery via Kubernetes EndpointSlices (#64788)
José Sequeirab119ee28ebb9
diff --git a/nodejs/tests/service-e2e/rust-ingestion-consumer.test.ts b/nodejs/tests/service-e2e/rust-ingestion-consumer.test.tsindex 5b5dba1e05b2..2aad5756a043 100644--- a/nodejs/tests/service-e2e/rust-ingestion-consumer.test.ts+++ b/nodejs/tests/service-e2e/rust-ingestion-consumer.test.ts@@ -151,16 +151,16 @@ describe('Rust ingestion consumer with Node ingestion API workers', () => {const metricsAfterInitialBatch = await waitForRoutedMetrics(rustConsumer, rustMetricsPort, {expectedMessages: initialEvents.length,- expectedWorkers: ['0', '1'],+ expectedWorkers: [workers[0].url, workers[1].url],expectedMinCommits: 2,})const initialWorker0Routed = getPrometheusSample(metricsAfterInitialBatch, {name: 'ingestion_consumer_dispatcher_messages_routed_total',- labels: { worker: '0' },+ labels: { worker: workers[0].url },})const initialWorker1Routed = getPrometheusSample(metricsAfterInitialBatch, {name: 'ingestion_consumer_dispatcher_messages_routed_total',- labels: { worker: '1' },+ labels: { worker: workers[1].url },})expect(initialWorker0Routed).toBeGreaterThan(0)expect(initialWorker1Routed).toBeGreaterThan(0)@@ -273,18 +273,18 @@ describe('Rust ingestion consumer with Node ingestion API workers', () => {await assertKafkaIngestionState(groupId, allEvents)await waitForRoutedMetrics(rustConsumer, rustMetricsPort, {expectedMessages: healthyEvents.length,- expectedWorkers: ['0', '1'],+ expectedWorkers: [workers[0].url, workers[1].url],expectedMinCommits: 1,})const metricsAfterHealthyBatch = await fetchMetrics(rustConsumer, rustMetricsPort)const worker0RoutedAfterHealthyBatch = getPrometheusSample(metricsAfterHealthyBatch, {name: 'ingestion_consumer_dispatcher_messages_routed_total',- labels: { worker: '0' },+ labels: { worker: workers[0].url },})const worker1RoutedAfterHealthyBatch = getPrometheusSample(metricsAfterHealthyBatch, {name: 'ingestion_consumer_dispatcher_messages_routed_total',- labels: { worker: '1' },+ labels: { worker: workers[1].url },})expect(worker0RoutedAfterHealthyBatch).toBeGreaterThan(0)expect(worker1RoutedAfterHealthyBatch).toBeGreaterThan(0)@@ -309,13 +309,13 @@ describe('Rust ingestion consumer with Node ingestion API workers', () => {expect(getPrometheusSample(metrics, {name: 'ingestion_consumer_dispatcher_messages_routed_total',- labels: { worker: '0' },+ labels: { worker: workers[0].url },})).toBe(worker0RoutedAfterHealthyBatch)expect(getPrometheusSample(metrics, {name: 'ingestion_consumer_dispatcher_messages_routed_total',- labels: { worker: '1' },+ labels: { worker: workers[1].url },})).toBeGreaterThanOrEqual(worker1RoutedAfterHealthyBatch + failoverEvents.length)expect(@@ -329,7 +329,7 @@ describe('Rust ingestion consumer with Node ingestion API workers', () => {const metricsBeforeRecovery = await fetchMetrics(rustConsumer, rustMetricsPort)const worker0RoutedBeforeRecovery = getPrometheusSample(metricsBeforeRecovery, {name: 'ingestion_consumer_dispatcher_messages_routed_total',- labels: { worker: '0' },+ labels: { worker: workers[0].url },})workers[0] = await restartNodeIngestionApiWorker(services, workers[0], 'node-worker-1-recovered')@@ -353,7 +353,7 @@ describe('Rust ingestion consumer with Node ingestion API workers', () => {expect(getPrometheusSample(metrics, {name: 'ingestion_consumer_dispatcher_messages_routed_total',- labels: { worker: '0' },+ labels: { worker: workers[0].url },})).toBeGreaterThan(worker0RoutedBeforeRecovery)expect(diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 3a866af75493..8a4e75f4b771 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -4978,8 +4978,11 @@ dependencies = ["axum 0.7.9","chrono","common-alloc",+ "dashmap 6.1.0","envconfig","futures",+ "k8s-openapi",+ "kube","lifecycle","metrics","metrics-exporter-prometheus",diff --git a/rust/ingestion-consumer/Cargo.toml b/rust/ingestion-consumer/Cargo.tomlindex 46a4ec36d20e..fc3118f71c62 100644--- a/rust/ingestion-consumer/Cargo.toml+++ b/rust/ingestion-consumer/Cargo.toml@@ -8,8 +8,11 @@ anyhow = { workspace = true }axum = { workspace = true }chrono = { workspace = true }common-alloc = { path = "../common/alloc" }+dashmap = { workspace = true }envconfig = { workspace = true }futures = { workspace = true }+k8s-openapi = { version = "0.24", features = ["latest"] }+kube = { version = "0.98", features = ["client", "runtime"] }lifecycle = { path = "../common/lifecycle" }metrics = { workspace = true }metrics-exporter-prometheus = { workspace = true }diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rsindex 3a5d69f94ff9..c88fe890400e 100644--- a/rust/ingestion-consumer/src/config.rs+++ b/rust/ingestion-consumer/src/config.rs@@ -2,6 +2,7 @@ use envconfig::Envconfig;use rdkafka::ClientConfig;use tracing::info;+use crate::discovery::DiscoveryMode;use crate::kafka_config::ConsumerConfigBuilder;use crate::routing::RoutingStrategy;@@ -143,6 +144,27 @@ pub struct Config {#[envconfig(default = "")]pub internal_api_secret: String,+ // ---- Worker discovery ----+ /// How the worker pool is discovered: `static` (use WORKER_ADDRESSES — the+ /// co-located sidecar default) or `endpointslice` (watch a Kubernetes+ /// Service's EndpointSlices for a separately-deployed, autoscaled worker pool).+ #[envconfig(from = "WORKER_DISCOVERY_MODE", default = "static")]+ pub worker_discovery_mode: DiscoveryMode,++ /// EndpointSlice mode: Kubernetes Service name whose EndpointSlices list the+ /// worker pods (label selector `kubernetes.io/service-name=<name>`).+ #[envconfig(from = "WORKER_SERVICE_NAME", default = "")]+ pub worker_service_name: String,++ /// EndpointSlice mode: namespace of the worker Service. Defaults to the+ /// pod's own namespace via the downward-API `POD_NAMESPACE` env var.+ #[envconfig(from = "POD_NAMESPACE", default = "default")]+ pub worker_namespace: String,++ /// EndpointSlice mode: the worker pods' HTTP port (the ingestion-api port).+ #[envconfig(from = "WORKER_PORT", default = "9001")]+ pub worker_port: u16,+/// 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).diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rsindex e84f78db610d..9277894e4b9b 100644--- a/rust/ingestion-consumer/src/consumer.rs+++ b/rust/ingestion-consumer/src/consumer.rs@@ -12,6 +12,7 @@ use tokio::task::JoinHandle;use tracing::{error, info, warn};use crate::config::Config;+use crate::discovery::DiscoveryMode;use crate::dispatcher::Dispatcher;use crate::transport::HttpTransport;use crate::types::SerializedKafkaMessage;@@ -112,8 +113,14 @@ impl IngestionConsumer {transport: Arc<HttpTransport>,handle: Handle,) -> anyhow::Result<Self> {- let worker_urls = config.worker_urls();- if worker_urls.is_empty() {+ // In endpointslice mode the worker set comes from discovery, so there is+ // no static readiness list — main gates startup on the first discovered+ // worker. In static mode we keep the configured list for readiness.+ let worker_urls = match config.worker_discovery_mode {+ DiscoveryMode::Static => config.worker_urls(),+ DiscoveryMode::EndpointSlice => Vec::new(),+ };+ if config.worker_discovery_mode == DiscoveryMode::Static && worker_urls.is_empty() {anyhow::bail!("No worker addresses configured");}@@ -219,19 +226,11 @@ impl IngestionConsumer {let task_batch_id = batch_id.clone();let dispatcher = Arc::clone(&self.dispatcher);let transport = Arc::clone(&self.transport);- let worker_urls = self.worker_urls.clone();let group_id = self.group_id.clone();let handle = tokio::spawn(async move {- Self::process_collected_batch(- collected,- task_batch_id,- dispatcher,- transport,- worker_urls,- group_id,- )- .await+ Self::process_collected_batch(collected, task_batch_id, dispatcher, transport, group_id)+ .await});info!(@@ -303,7 +302,6 @@ impl IngestionConsumer {batch_id: String,dispatcher: Arc<Dispatcher>,transport: Arc<HttpTransport>,- worker_urls: Vec<String>,group_id: String,) -> anyhow::Result<ProcessedBatch> {let batch_size = collected.messages.len();@@ -351,18 +349,19 @@ impl IngestionConsumer {for sub_batch in sub_batches {let transport = Arc::clone(&transport);let dispatcher = Arc::clone(&dispatcher);- let url = worker_urls[sub_batch.worker_idx].clone();+ let worker = sub_batch.worker.clone();let bid = batch_id.clone();- let worker_idx = sub_batch.worker_idx;let routing_keys = sub_batch.routing_keys.clone();let message_count = sub_batch.messages.len();handles.push(tokio::spawn(async move {- let result = transport.send_batch(&url, &bid, sub_batch.messages).await;+ let result = transport+ .send_batch(&worker, &bid, sub_batch.messages)+ .await;let is_error = result.is_err();- dispatcher.on_sub_batch_resolved(worker_idx, message_count, &routing_keys);- dispatcher.record_send_outcome(worker_idx, is_error);+ dispatcher.on_sub_batch_resolved(&worker, message_count, &routing_keys);+ dispatcher.record_send_outcome(&worker, is_error);result}));diff --git a/rust/ingestion-consumer/src/discovery.rs b/rust/ingestion-consumer/src/discovery.rsnew file mode 100644index 000000000000..73f8e36e924b--- /dev/null+++ b/rust/ingestion-consumer/src/discovery.rs@@ -0,0 +1,513 @@+//! Worker pool discovery.+//!+//! The [`WorkerRegistry`] owns worker membership and health; this module is the+//! source that drives it. Two providers implement [`WorkerDiscovery`]:+//!+//! - [`StaticDiscovery`] — a fixed list from `WORKER_ADDRESSES` (the co-located+//! sidecar). Applies the set once; no background task.+//! - [`EndpointSliceDiscovery`] — watches a Kubernetes Service's EndpointSlices+//! and keeps the registry in sync as worker pods join/leave (the+//! separately-deployed pool). Adapted from personhog-router's discovery, but+//! reconciles the registry directly instead of feeding a Tower balancer.+//!+//! Routing stays client-side in the dispatcher; discovery only supplies the+//! member list (and prunes per-worker transport state on removal).++use std::collections::{HashMap, HashSet};+use std::net::{IpAddr, SocketAddr};+use std::str::FromStr;+use std::sync::Arc;+use std::time::Duration;++use futures::StreamExt;+use k8s_openapi::api::discovery::v1::EndpointSlice;+use kube::api::Api;+use kube::runtime::watcher::{self, Config as WatcherConfig, Event};+use kube::Client;+use metrics::{counter, gauge};+use tokio::task::JoinHandle;+use tokio_util::sync::CancellationToken;+use tracing::{info, warn};++use crate::transport::HttpTransport;+use crate::worker_registry::{WorkerId, WorkerRegistry};++/// Pause before re-listing after the watcher stream closes, so a persistently+/// failing watcher degrades to a slow retry rather than a hot loop.+const WATCHER_RESTART_BACKOFF: Duration = Duration::from_secs(1);++/// How the worker pool is discovered.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]+pub enum DiscoveryMode {+ /// Fixed list from `WORKER_ADDRESSES` (co-located sidecar).+ #[default]+ Static,+ /// Watch a Kubernetes Service's EndpointSlices (separate worker deployment).+ EndpointSlice,+}++impl FromStr for DiscoveryMode {+ type Err = String;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ match s.trim().to_lowercase().as_str() {+ "static" => Ok(DiscoveryMode::Static),+ "endpointslice" | "endpoint-slice" | "endpoint_slice" => {+ Ok(DiscoveryMode::EndpointSlice)+ }+ other => Err(format!(+ "unknown worker discovery mode '{other}' (expected 'static' or 'endpointslice')"+ )),+ }+ }+}++/// A source of worker-pool membership. `start` applies the initial set to the+/// registry and, for dynamic sources, spawns a task that keeps it in sync until+/// `cancel` fires; it returns the task handle (None for static sources).+pub trait WorkerDiscovery: Send {+ fn start(+ self: Box<Self>,+ registry: Arc<WorkerRegistry>,+ transport: Arc<HttpTransport>,+ cancel: CancellationToken,+ ) -> Option<JoinHandle<()>>;+}++/// Reconcile the registry and transport to a desired worker set: add workers+/// that are new, drop workers that are gone (and prune their transport state).+fn reconcile_membership(+ registry: &WorkerRegistry,+ transport: &HttpTransport,+ desired: &HashSet<WorkerId>,+) {+ let current: HashSet<WorkerId> = registry.workers().into_iter().collect();++ for worker in desired.difference(¤t) {+ registry.add_worker(worker.clone());+ }+ for worker in current.difference(desired) {+ registry.remove_worker(worker);+ transport.remove_worker(worker);+ }++ gauge!("ingestion_consumer_discovery_workers").set(desired.len() as f64);+}++/// Parse an EndpointSlice into the set of ready socket addresses. An endpoint is+/// ready when `conditions.ready` is true or absent (per the K8s spec); endpoints+/// with `ready = false` (e.g. draining pods) and unparseable addresses are skipped.+fn extract_ready_addrs(slice: &EndpointSlice, port: u16) -> HashSet<SocketAddr> {+ let mut addrs = HashSet::new();+ for endpoint in slice.endpoints.iter() {+ let ready = endpoint+ .conditions+ .as_ref()+ .and_then(|c| c.ready)+ .unwrap_or(true);+ if !ready {+ continue;+ }+ for addr_str in &endpoint.addresses {+ if let Ok(ip) = addr_str.parse::<IpAddr>() {+ addrs.insert(SocketAddr::new(ip, port));+ }+ }+ }+ addrs+}++fn addr_to_worker(addr: SocketAddr) -> WorkerId {+ WorkerId::from(format!("http://{addr}").as_str())+}++fn slice_key(slice: &EndpointSlice) -> String {+ slice+ .metadata+ .name+ .clone()+ .or_else(|| slice.metadata.uid.clone())+ .unwrap_or_else(|| "unknown".to_string())+}++/// Fixed worker list from configuration.+pub struct StaticDiscovery {+ urls: Vec<String>,+}++impl StaticDiscovery {+ pub fn new(urls: Vec<String>) -> Self {+ Self { urls }+ }+}++impl WorkerDiscovery for StaticDiscovery {+ fn start(+ self: Box<Self>,+ registry: Arc<WorkerRegistry>,+ transport: Arc<HttpTransport>,+ _cancel: CancellationToken,+ ) -> Option<JoinHandle<()>> {+ let desired: HashSet<WorkerId> = self+ .urls+ .iter()+ .map(|u| WorkerId::from(u.as_str()))+ .collect();+ reconcile_membership(®istry, &transport, &desired);+ None+ }+}++/// Watches a Kubernetes Service's EndpointSlices and reconciles the registry as+/// worker pods become ready / leave.+pub struct EndpointSliceDiscovery {+ client: Client,+ namespace: String,+ service_name: String,+ port: u16,+}++impl EndpointSliceDiscovery {+ pub fn new(client: Client, namespace: String, service_name: String, port: u16) -> Self {+ Self {+ client,+ namespace,+ service_name,+ port,+ }+ }++ async fn run(+ self,+ registry: Arc<WorkerRegistry>,+ transport: Arc<HttpTransport>,+ cancel: CancellationToken,+ ) {+ let api: Api<EndpointSlice> = Api::namespaced(self.client.clone(), &self.namespace);+ let label_selector = format!("kubernetes.io/service-name={}", self.service_name);++ info!(+ service = %self.service_name,+ namespace = %self.namespace,+ port = self.port,+ "starting EndpointSlice worker discovery"+ );++ // Ready addresses per slice name, so one slice changing doesn't clobber+ // addresses contributed by other slices. Kept across watcher restarts:+ // a fresh watcher re-lists from `Init`, which clears and repopulates it.+ let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();++ // The `kube` watcher reconnects internally on errors, so a `None` only+ // surfaces when the stream is definitively closed. Re-enter the watcher+ // rather than leaving the worker pool frozen until the pod restarts.+ loop {+ let config = WatcherConfig::default().labels(&label_selector);+ let stream = watcher::watcher(api.clone(), config);+ tokio::pin!(stream);++ loop {+ tokio::select! {+ _ = cancel.cancelled() => {+ info!("EndpointSlice discovery cancelled");+ return;+ }+ item = stream.next() => {+ match item {+ Some(Ok(event)) => {+ if let Some(desired) = Self::apply_event(event, &mut slices, self.port) {+ reconcile_membership(®istry, &transport, &desired);+ }+ }+ Some(Err(e)) => {+ warn!(error = %e, "EndpointSlice watcher error, stream will retry");+ counter!("ingestion_consumer_discovery_errors_total").increment(1);+ }+ None => {+ warn!("EndpointSlice watcher stream ended, restarting");+ counter!("ingestion_consumer_discovery_errors_total").increment(1);+ break;+ }+ }+ }+ }+ }++ // Brief pause before re-listing, so a persistently-closing stream+ // can't become a hot reconnect loop.+ tokio::select! {+ _ = cancel.cancelled() => {+ info!("EndpointSlice discovery cancelled");+ return;+ }+ _ = tokio::time::sleep(WATCHER_RESTART_BACKOFF) => {}+ }+ }+ }++ /// Apply a watch event to the per-slice state, returning the desired worker+ /// set to reconcile — or `None` when no reconcile is needed (the `Init`+ /// re-list start, where we keep serving the current set until `InitDone`).+ fn apply_event(+ event: Event<EndpointSlice>,+ slices: &mut HashMap<String, HashSet<SocketAddr>>,+ port: u16,+ ) -> Option<HashSet<WorkerId>> {+ match event {+ Event::Apply(slice) | Event::InitApply(slice) => {+ slices.insert(slice_key(&slice), extract_ready_addrs(&slice, port));+ }+ Event::Delete(slice) => {+ slices.remove(&slice_key(&slice));+ }+ // Re-list starting: clear slice state but DON'T reconcile, so the+ // registry keeps serving the current workers until InitDone.+ Event::Init => {+ slices.clear();+ return None;+ }+ Event::InitDone => {}+ }++ Some(+ slices+ .values()+ .flatten()+ .copied()+ .map(addr_to_worker)+ .collect(),+ )+ }+}++impl WorkerDiscovery for EndpointSliceDiscovery {+ fn start(+ self: Box<Self>,+ registry: Arc<WorkerRegistry>,+ transport: Arc<HttpTransport>,+ cancel: CancellationToken,+ ) -> Option<JoinHandle<()>> {+ let this = *self;+ Some(tokio::spawn(async move {+ this.run(registry, transport, cancel).await+ }))+ }+}++#[cfg(test)]+mod tests {+ use std::time::Duration;++ use k8s_openapi::api::discovery::v1::{Endpoint as K8sEndpoint, EndpointConditions};+ use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta;++ use super::*;+ use crate::worker_registry::WorkerRegistryConfig;++ // ---- mode parsing ----++ #[test]+ fn test_discovery_mode_parses_known_values() {+ assert_eq!("static".parse(), Ok(DiscoveryMode::Static));+ assert_eq!("endpointslice".parse(), Ok(DiscoveryMode::EndpointSlice));+ assert_eq!("endpoint-slice".parse(), Ok(DiscoveryMode::EndpointSlice));+ assert_eq!(" EndpointSlice ".parse(), Ok(DiscoveryMode::EndpointSlice));+ }++ #[test]+ fn test_discovery_mode_rejects_unknown_and_defaults_static() {+ assert!("dns".parse::<DiscoveryMode>().is_err());+ assert_eq!(DiscoveryMode::default(), DiscoveryMode::Static);+ }++ // ---- extract_ready_addrs ----++ fn endpoint(addresses: &[&str], ready: Option<bool>) -> K8sEndpoint {+ K8sEndpoint {+ addresses: addresses.iter().map(|s| s.to_string()).collect(),+ conditions: ready.map(|r| EndpointConditions {+ ready: Some(r),+ ..Default::default()+ }),+ ..Default::default()+ }+ }++ fn slice(name: &str, endpoints: Vec<K8sEndpoint>) -> EndpointSlice {+ EndpointSlice {+ metadata: ObjectMeta {+ name: Some(name.to_string()),+ ..Default::default()+ },+ address_type: "IPv4".to_string(),+ endpoints,+ ports: None,+ }+ }++ fn sock(s: &str, port: u16) -> SocketAddr {+ SocketAddr::new(s.parse().unwrap(), port)+ }++ #[test]+ fn test_extract_ready_addrs_includes_ready_and_nil_conditions() {+ let s = slice(+ "s1",+ vec![+ endpoint(&["10.0.0.1"], Some(true)),+ endpoint(&["10.0.0.2"], Some(false)),+ endpoint(&["10.0.0.3"], None),+ ],+ );+ assert_eq!(+ extract_ready_addrs(&s, 9001),+ HashSet::from([sock("10.0.0.1", 9001), sock("10.0.0.3", 9001)])+ );+ }++ #[test]+ fn test_extract_ready_addrs_skips_unparseable() {+ let s = slice("s1", vec![endpoint(&["not-an-ip", "10.0.0.5"], None)]);+ assert_eq!(+ extract_ready_addrs(&s, 9001),+ HashSet::from([sock("10.0.0.5", 9001)])+ );+ }++ // ---- apply_event ----++ fn worker(ip: &str, port: u16) -> WorkerId {+ WorkerId::from(format!("http://{ip}:{port}").as_str())+ }++ #[test]+ fn test_apply_event_apply_and_delete() {+ let mut slices = HashMap::new();++ let desired = EndpointSliceDiscovery::apply_event(+ Event::Apply(slice("s1", vec![endpoint(&["10.0.0.1"], Some(true))])),+ &mut slices,+ 9001,+ )+ .unwrap();+ assert_eq!(desired, HashSet::from([worker("10.0.0.1", 9001)]));++ let desired = EndpointSliceDiscovery::apply_event(+ Event::Delete(slice("s1", vec![])),+ &mut slices,+ 9001,+ )+ .unwrap();+ assert!(desired.is_empty());+ }++ #[test]+ fn test_apply_event_init_keeps_serving_until_init_done() {+ let mut slices = HashMap::new();+ EndpointSliceDiscovery::apply_event(+ Event::Apply(slice("s1", vec![endpoint(&["10.0.0.1"], Some(true))])),+ &mut slices,+ 9001,+ );++ // Init returns None — caller must NOT reconcile (keep serving current set).+ assert!(EndpointSliceDiscovery::apply_event(Event::Init, &mut slices, 9001).is_none());+ assert!(slices.is_empty());++ // Re-list with a different pod, then InitDone reconciles to the new set.+ EndpointSliceDiscovery::apply_event(+ Event::InitApply(slice("s1", vec![endpoint(&["10.0.0.9"], Some(true))])),+ &mut slices,+ 9001,+ );+ let desired =+ EndpointSliceDiscovery::apply_event(Event::InitDone, &mut slices, 9001).unwrap();+ assert_eq!(desired, HashSet::from([worker("10.0.0.9", 9001)]));+ }++ #[test]+ fn test_apply_event_aggregates_across_slices() {+ let mut slices = HashMap::new();+ EndpointSliceDiscovery::apply_event(+ Event::Apply(slice("s1", vec![endpoint(&["10.0.0.1"], Some(true))])),+ &mut slices,+ 9001,+ );+ let desired = EndpointSliceDiscovery::apply_event(+ Event::Apply(slice("s2", vec![endpoint(&["10.0.0.2"], Some(true))])),+ &mut slices,+ 9001,+ )+ .unwrap();+ assert_eq!(+ desired,+ HashSet::from([worker("10.0.0.1", 9001), worker("10.0.0.2", 9001)])+ );+ }++ // ---- reconcile_membership ----++ fn test_registry() -> WorkerRegistry {+ WorkerRegistry::new(+ &[],+ WorkerRegistryConfig {+ probe_interval: Duration::from_millis(50),+ dead_declaration: Duration::from_millis(100),+ passive_window: Duration::from_millis(500),+ passive_error_threshold: 0.5,+ passive_min_samples: 5,+ degraded_hold: Duration::from_millis(50),+ min_state_duration: Duration::ZERO,+ probe_failure_threshold: 2,+ },+ )+ }++ fn test_transport() -> HttpTransport {+ HttpTransport::new(Duration::from_secs(1), 0, None, &[], 1)+ }++ #[test]+ fn test_reconcile_adds_and_removes_workers() {+ let registry = test_registry();+ let transport = test_transport();++ reconcile_membership(+ ®istry,+ &transport,+ &HashSet::from([worker("10.0.0.1", 9001), worker("10.0.0.2", 9001)]),+ );+ let mut got: Vec<String> = registry.workers().iter().map(|w| w.to_string()).collect();+ got.sort();+ assert_eq!(got, vec!["http://10.0.0.1:9001", "http://10.0.0.2:9001"]);++ // Reconcile to a new set: .1 drops, .3 joins, .2 stays.+ reconcile_membership(+ ®istry,+ &transport,+ &HashSet::from([worker("10.0.0.2", 9001), worker("10.0.0.3", 9001)]),+ );+ let mut got: Vec<String> = registry.workers().iter().map(|w| w.to_string()).collect();+ got.sort();+ assert_eq!(got, vec!["http://10.0.0.2:9001", "http://10.0.0.3:9001"]);+ }++ #[test]+ fn test_static_discovery_populates_registry() {+ let registry = Arc::new(test_registry());+ let transport = Arc::new(test_transport());++ let discovery = Box::new(StaticDiscovery::new(vec![+ "http://w:1".to_string(),+ "http://w:2".to_string(),+ ]));+ let handle = discovery.start(+ Arc::clone(®istry),+ Arc::clone(&transport),+ CancellationToken::new(),+ );++ assert!(handle.is_none(), "static discovery spawns no task");+ assert_eq!(registry.worker_count(), 2);+ }+}diff --git a/rust/ingestion-consumer/src/dispatcher.rs b/rust/ingestion-consumer/src/dispatcher.rsindex 6875b1b6a8fb..528a28e9d452 100644--- a/rust/ingestion-consumer/src/dispatcher.rs+++ b/rust/ingestion-consumer/src/dispatcher.rs@@ -3,15 +3,15 @@ use std::sync::{Arc, Mutex};use metrics::{counter, gauge, histogram};-use crate::routing::{Router, RoutingStrategy};+use crate::routing::{Router, RoutingStrategy, WorkerLoad};use crate::types::SerializedKafkaMessage;-use crate::worker_registry::{WorkerRegistry, WorkerState};+use crate::worker_registry::{WorkerId, WorkerRegistry};/// A slice of a batch assigned to one worker, carrying the messages and the/// routing keys of all distinct_ids included. Routing keys are needed to/// decrement pin ref-counts when the sub-batch resolves.pub struct SubBatch {- pub worker_idx: usize,+ pub worker: WorkerId,pub messages: Vec<SerializedKafkaMessage>,/// Unique routing keys contained in this sub-batch. Pass back to/// `Dispatcher::on_sub_batch_resolved` on ACK or DLQ.@@ -22,7 +22,7 @@ pub struct SubBatch {/// many in-flight batches currently reference it. The pin is evicted when/// ref_count reaches 0.struct Pin {- worker_idx: usize,+ worker: WorkerId,ref_count: u32,}@@ -33,37 +33,24 @@ struct PinTable {/// 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>,+ /// by sub-batch count. A worker with no outstanding messages has no entry.+ in_flight: WorkerLoad,}impl PinTable {- fn new(worker_count: usize) -> Self {+ fn new() -> Self {Self {pins: HashMap::new(),- in_flight_messages: vec![0; worker_count],+ in_flight: WorkerLoad::new(),}}/// Drop all pins targeting dead workers. Returns the count of evictions.fn drop_dead_pins(&mut self, registry: &WorkerRegistry) -> usize {let before = self.pins.len();- self.pins.retain(|_, pin| !registry.is_dead(pin.worker_idx));+ self.pins.retain(|_, pin| !registry.is_dead(&pin.worker));before - self.pins.len()}-- /// 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!(- registry.state(idx),- WorkerState::Healthy | WorkerState::Degraded- )- })- .collect()- }}struct MessageGroup {@@ -88,56 +75,40 @@ impl WorkerSubBatchBuilder {#[derive(Default)]struct WorkerAssignments {- by_worker: HashMap<usize, WorkerSubBatchBuilder>,- /// 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>,+ by_worker: HashMap<WorkerId, WorkerSubBatchBuilder>,}impl WorkerAssignments {- fn new(worker_count: usize) -> Self {- Self {- by_worker: HashMap::new(),- provisional_messages: vec![0; worker_count],- }+ fn new() -> Self {+ Self::default()}- fn provisional_messages(&self) -> &[usize] {- &self.provisional_messages- }-- fn add_group(&mut self, worker_idx: usize, group: MessageGroup) {+ fn add_group(&mut self, worker: WorkerId, group: MessageGroup) {let builder = self.by_worker- .entry(worker_idx)+ .entry(worker).or_insert_with(|| WorkerSubBatchBuilder {messages: Vec::new(),routing_keys: Vec::new(),});- // Accumulate by message volume, not group count, so a worker holding one- // heavy key counts as more loaded than one holding several tiny keys.- self.provisional_messages[worker_idx] =- self.provisional_messages[worker_idx].saturating_add(group.messages.len());-builder.messages.extend(group.messages);builder.routing_keys.push(group.routing_key);}- fn routed_counts(&self) -> impl Iterator<Item = (usize, usize)> + '_ {+ fn routed_counts(&self) -> impl Iterator<Item = (WorkerId, usize)> + '_ {self.by_worker.iter().filter(|(_, builder)| !builder.is_empty())- .map(|(&worker_idx, builder)| (worker_idx, builder.message_count()))+ .map(|(worker, builder)| (worker.clone(), builder.message_count()))}fn into_sub_batches(self) -> Vec<SubBatch> {self.by_worker.into_iter().filter(|(_, builder)| !builder.is_empty())- .map(|(worker_idx, builder)| SubBatch {- worker_idx,+ .map(|(worker, builder)| SubBatch {+ worker,messages: builder.messages,routing_keys: builder.routing_keys,})@@ -152,8 +123,8 @@ impl WorkerAssignments {/// 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-/// when the last referencing batch resolves.+/// (ref-counted pin). Pins are dropped when a worker is declared dead (or leaves+/// the pool) or when the last referencing batch resolves.////// **Recovery**: `on_sub_batch_resolved` decrements ref-counts and subtracts/// the sub-batch's messages from the worker's outstanding load. Zero-count@@ -174,9 +145,8 @@ impl Dispatcher {/// 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)),+ pin_table: Mutex::new(PinTable::new()),registry,router: Mutex::new(Router::new(strategy)),}@@ -189,9 +159,8 @@ impl Dispatcher {strategy: RoutingStrategy,seed: u64,) -> Self {- let worker_count = registry.worker_count();Self {- pin_table: Mutex::new(PinTable::new(worker_count)),+ pin_table: Mutex::new(PinTable::new()),registry,router: Mutex::new(Router::with_seed(strategy, seed)),}@@ -231,18 +200,27 @@ impl Dispatcher {histogram!("ingestion_consumer_distinct_ids_per_batch").record(key_groups.len() as f64);- let worker_count = table.in_flight_messages.len();- let mut assignments = WorkerAssignments::new(worker_count);+ let mut assignments = WorkerAssignments::new();++ // Candidate workers and their working load for this round. `working_load`+ // starts from each candidate's outstanding load and is bumped as groups+ // are assigned, so intra-batch placement accounts for earlier picks.+ let healthy = self.registry.healthy_workers();+ let mut working_load: WorkerLoad = healthy+ .iter()+ .map(|w| (w.clone(), table.in_flight.get(w).copied().unwrap_or(0)))+ .collect();let mut unpinned_groups: Vec<MessageGroup> = Vec::new();for group in key_groups {match table.pins.get_mut(&group.routing_key) {- Some(pin) if !self.registry.is_dead(pin.worker_idx) => {+ Some(pin) if !self.registry.is_dead(&pin.worker) => {// Existing live pin — honor it.pin.ref_count += 1;- let worker_idx = pin.worker_idx;- assignments.add_group(worker_idx, group);+ let worker = pin.worker.clone();+ bump_load(&mut working_load, &worker, group.messages.len());+ assignments.add_group(worker, group);}_ => {// No pin or pinned to a dead worker — drop stale entry and@@ -256,7 +234,6 @@ impl Dispatcher {// 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() {@@ -264,41 +241,36 @@ impl Dispatcher {}for group in unpinned_groups {- let Some(worker_idx) = router.select(- &healthy,- &table.in_flight_messages,- assignments.provisional_messages(),- ) else {+ let Some(worker) = router.select(&healthy, &working_load) else {// All workers unhealthy — this key cannot be assigned.counter!("ingestion_consumer_dispatcher_unroutable_messages_total").increment(group.messages.len() as u64);continue;};+ bump_load(&mut working_load, &worker, group.messages.len());table.pins.insert(group.routing_key.clone(),Pin {- worker_idx,+ worker: worker.clone(),ref_count: 1,},);-- assignments.add_group(worker_idx, group);+ assignments.add_group(worker, group);}drop(router);// Add each worker's message volume to its outstanding load.- for (worker_idx, message_count) in assignments.routed_counts() {- table.in_flight_messages[worker_idx] =- table.in_flight_messages[worker_idx].saturating_add(message_count);+ for (worker, message_count) in assignments.routed_counts() {+ *table.in_flight.entry(worker.clone()).or_insert(0) += message_count;counter!("ingestion_consumer_dispatcher_sub_batches_assigned_total",- "worker" => worker_idx.to_string(),+ "worker" => worker.clone(),).increment(1);counter!("ingestion_consumer_dispatcher_messages_routed_total",- "worker" => worker_idx.to_string(),+ "worker" => worker.clone(),).increment(message_count as u64);}@@ -314,14 +286,22 @@ impl Dispatcher {/// on its next arrival. `message_count` must match the sub-batch's length.pub fn on_sub_batch_resolved(&self,- worker_idx: usize,+ worker: &WorkerId,message_count: usize,routing_keys: &[String],) {let mut table = self.pin_table.lock().unwrap();- table.in_flight_messages[worker_idx] =- table.in_flight_messages[worker_idx].saturating_sub(message_count);+ let now_zero = match table.in_flight.get_mut(worker) {+ Some(load) => {+ *load = load.saturating_sub(message_count);+ *load == 0+ }+ None => false,+ };+ if now_zero {+ table.in_flight.remove(worker);+ }let mut evictions = 0usize;for key in routing_keys {@@ -330,7 +310,7 @@ impl Dispatcher {// old pin and `assign` may create a new one for a different worker using// the same key. A DLQ resolve from the original dead sub-batch would// otherwise corrupt the new pin's ref_count.- if pin.worker_idx != worker_idx {+ if pin.worker != *worker {continue;}pin.ref_count = pin.ref_count.saturating_sub(1);@@ -354,8 +334,17 @@ impl Dispatcher {/// Record the outcome of a send attempt for passive health tracking./// Delegates to the underlying WorkerRegistry.- pub fn record_send_outcome(&self, worker_idx: usize, is_error: bool) {- self.registry.record_outcome(worker_idx, is_error);+ pub fn record_send_outcome(&self, worker: &str, is_error: bool) {+ self.registry.record_outcome(worker, is_error);+ }+}++/// Add `count` to a worker's working load for this round, if it is a candidate.+/// Workers that aren't routing candidates (e.g. a pin honored on an unhealthy+/// worker) have no entry and don't affect selection, so they're skipped.+fn bump_load(working_load: &mut WorkerLoad, worker: &WorkerId, count: usize) {+ if let Some(load) = working_load.get_mut(worker) {+ *load = load.saturating_add(count);}}@@ -411,6 +400,14 @@ mod tests {// ---- helpers ----+ fn worker_url(i: usize) -> String {+ format!("http://worker:{}", 9001 + i)+ }++ fn wid(i: usize) -> WorkerId {+ WorkerId::from(worker_url(i).as_str())+ }+fn make_msg(token: &str, distinct_id: &str) -> SerializedKafkaMessage {let mut headers = HashMap::new();headers.insert("token".to_string(), token.to_string());@@ -445,9 +442,7 @@ mod tests {/// Registry with N healthy workers and no cooldown. `dead_declaration` is/// very short so tests can drive a worker to dead quickly.fn healthy_registry(n: usize) -> Arc<WorkerRegistry> {- let urls: Vec<String> = (0..n)- .map(|i| format!("http://worker:{}", 9001 + i))- .collect();+ let urls: Vec<String> = (0..n).map(worker_url).collect();let config = WorkerRegistryConfig {probe_interval: Duration::from_millis(50),dead_declaration: Duration::from_millis(30),@@ -461,6 +456,17 @@ mod tests {Arc::new(WorkerRegistry::new(&urls, config))}+ fn in_flight_of(dispatcher: &Dispatcher, worker: &WorkerId) -> usize {+ dispatcher+ .pin_table+ .lock()+ .unwrap()+ .in_flight+ .get(worker)+ .copied()+ .unwrap_or(0)+ }+// ---- routing key ----#[test]@@ -507,32 +513,31 @@ mod tests {#[test]fn test_worker_assignments_merges_groups_for_same_worker() {- let mut assignments = WorkerAssignments::new(2);+ let mut assignments = WorkerAssignments::new();assignments.add_group(- 1,+ wid(1),MessageGroup {routing_key: "tok:user-1".to_string(),messages: make_msgs(&[("tok", "user-1")]),},);assignments.add_group(- 1,+ wid(1),MessageGroup {routing_key: "tok:user-2".to_string(),messages: make_msgs(&[("tok", "user-2")]),},);- assert_eq!(assignments.provisional_messages(), &[0, 2]);assert_eq!(assignments.routed_counts().collect::<Vec<_>>(),- vec![(1, 2)]+ vec![(wid(1), 2)]);let sub_batches = assignments.into_sub_batches();assert_eq!(sub_batches.len(), 1);- assert_eq!(sub_batches[0].worker_idx, 1);+ assert_eq!(sub_batches[0].worker, wid(1));assert_eq!(sub_batches[0].messages.len(), 2);assert_eq!(sub_batches[0].routing_keys,@@ -550,7 +555,7 @@ mod tests {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].worker, wid(0));assert_eq!(sub_batches[0].messages.len(), 3);}@@ -562,20 +567,22 @@ mod tests {}#[test]- fn test_same_distinct_id_goes_to_same_worker_across_batches() {+ fn test_same_distinct_id_merges_within_batch() {let registry = healthy_registry(3);let dispatcher = Dispatcher::new(registry);let batch1 = dispatcher.assign(make_msgs(&[("t", "user-1")]));assert_eq!(batch1.len(), 1);- let worker = batch1[0].worker_idx;- dispatcher.on_sub_batch_resolved(worker, batch1[0].messages.len(), &batch1[0].routing_keys);+ let worker = batch1[0].worker.clone();+ dispatcher.on_sub_batch_resolved(+ &worker,+ batch1[0].messages.len(),+ &batch1[0].routing_keys,+ );- // Second batch: same key must go to same worker (pin still alive until resolved).- // We resolved already, so the pin was evicted — it will re-pin to the same or- // different worker. What we care about is that within a batch, same key → same worker.+ // Both user-1 messages merge into one sub-batch.let batch2 = dispatcher.assign(make_msgs(&[("t", "user-1"), ("t", "user-1")]));- assert_eq!(batch2.len(), 1); // both user-1 messages merge into one sub-batch+ assert_eq!(batch2.len(), 1);}// ---- sticky pins ----@@ -587,14 +594,14 @@ mod tests {// First batch pins "t:user-1" to some worker.let b1 = dispatcher.assign(make_msgs(&[("t", "user-1")]));- let pinned_worker = b1[0].worker_idx;+ let pinned_worker = b1[0].worker.clone();// Do NOT resolve b1 — pin stays alive with ref_count=1.// Second batch: same key must hit the same worker.let b2 = dispatcher.assign(make_msgs(&[("t", "user-1")]));assert_eq!(b2.len(), 1);- assert_eq!(b2[0].worker_idx, pinned_worker);+ assert_eq!(b2[0].worker, pinned_worker);}#[test]@@ -617,21 +624,23 @@ mod tests {let dispatcher = Dispatcher::new(registry);let b1 = dispatcher.assign(make_msgs(&[("t", "user-1")]));- let worker = b1[0].worker_idx;+ let worker = b1[0].worker.clone();- // Pin exists (ref_count = 1).- {- let table = dispatcher.pin_table.lock().unwrap();- assert!(table.pins.contains_key("t:user-1"));- }+ assert!(dispatcher+ .pin_table+ .lock()+ .unwrap()+ .pins+ .contains_key("t:user-1"));- dispatcher.on_sub_batch_resolved(worker, b1[0].messages.len(), &b1[0].routing_keys);+ dispatcher.on_sub_batch_resolved(&worker, b1[0].messages.len(), &b1[0].routing_keys);- // Pin evicted (ref_count hit 0).- {- let table = dispatcher.pin_table.lock().unwrap();- assert!(!table.pins.contains_key("t:user-1"));- }+ assert!(!dispatcher+ .pin_table+ .lock()+ .unwrap()+ .pins+ .contains_key("t:user-1"));}#[test]@@ -640,19 +649,17 @@ mod tests {let dispatcher = Dispatcher::new(registry);let b1 = dispatcher.assign(make_msgs(&[("t", "user-1")]));- let worker = b1[0].worker_idx;+ let worker = b1[0].worker.clone();// Second batch, same key, pin not yet resolved: ref_count should be 2.dispatcher.assign(make_msgs(&[("t", "user-1")]));-- {- let table = dispatcher.pin_table.lock().unwrap();- let pin = table.pins.get("t:user-1").unwrap();- assert_eq!(pin.ref_count, 2);- }+ assert_eq!(+ dispatcher.pin_table.lock().unwrap().pins["t:user-1"].ref_count,+ 2+ );// Resolve first sub-batch: ref_count drops to 1, pin stays.- dispatcher.on_sub_batch_resolved(worker, b1[0].messages.len(), &b1[0].routing_keys);+ dispatcher.on_sub_batch_resolved(&worker, b1[0].messages.len(), &b1[0].routing_keys);{let table = dispatcher.pin_table.lock().unwrap();assert!(table.pins.contains_key("t:user-1"));@@ -669,10 +676,9 @@ mod tests {// Two messages for one key → one sub-batch carrying two messages.let b1 = dispatcher.assign(make_msgs(&[("t", "user-1"), ("t", "user-1")]));- let worker = b1[0].worker_idx;+ let worker = b1[0].worker.clone();- let table = dispatcher.pin_table.lock().unwrap();- assert_eq!(table.in_flight_messages[worker], 2);+ assert_eq!(in_flight_of(&dispatcher, &worker), 2);}#[test]@@ -681,12 +687,11 @@ mod tests {let dispatcher = Dispatcher::new(registry);let b1 = dispatcher.assign(make_msgs(&[("t", "user-1"), ("t", "user-1")]));- let worker = b1[0].worker_idx;+ let worker = b1[0].worker.clone();- dispatcher.on_sub_batch_resolved(worker, b1[0].messages.len(), &b1[0].routing_keys);+ dispatcher.on_sub_batch_resolved(&worker, b1[0].messages.len(), &b1[0].routing_keys);- let table = dispatcher.pin_table.lock().unwrap();- assert_eq!(table.in_flight_messages[worker], 0);+ assert_eq!(in_flight_of(&dispatcher, &worker), 0);}#[test]@@ -699,8 +704,7 @@ mod tests {dispatcher.assign(make_msgs(&[("t", "a"), ("t", "b"), ("t", "c")]));- let table = dispatcher.pin_table.lock().unwrap();- assert_eq!(table.in_flight_messages[0], 3);+ assert_eq!(in_flight_of(&dispatcher, &wid(0)), 3);}// ---- bin-packing ----@@ -711,22 +715,24 @@ mod tests {let dispatcher = Dispatcher::new(registry);// Artificially load worker 0 with 3 outstanding messages.- {- let mut table = dispatcher.pin_table.lock().unwrap();- table.in_flight_messages[0] = 3;- }+ dispatcher+ .pin_table+ .lock()+ .unwrap()+ .in_flight+ .insert(wid(0), 3);// A fresh key should go to worker 1 (load = 0).let b = dispatcher.assign(make_msgs(&[("t", "fresh")]));assert_eq!(b.len(), 1);- assert_eq!(b[0].worker_idx, 1);+ assert_eq!(b[0].worker, wid(1));}#[test]fn test_bin_packing_balances_by_message_volume_not_group_count() {// Regression: load is tracked by message count, not sub-batch presence.// One heavy key (10 msgs) plus five small keys (1 msg each) must not all- // pile onto worker 0 — the small keys bin-pack onto the other worker+ // pile onto one worker — the small keys bin-pack onto the other worker// until load is balanced.let registry = healthy_registry(2);let dispatcher = Dispatcher::new(registry);@@ -739,14 +745,13 @@ mod tests {let sub_batches = dispatcher.assign(make_msgs(&specs));assert_eq!(sub_batches.len(), 2, "both workers must carry messages");- let table = dispatcher.pin_table.lock().unwrap();- let load0 = table.in_flight_messages[0];- let load1 = table.in_flight_messages[1];+ let load0 = in_flight_of(&dispatcher, &wid(0));+ let load1 = in_flight_of(&dispatcher, &wid(1));assert_eq!(load0 + load1, 15);// The heavy key lands alone on one worker; the five singles fill the- // other. With the old 0/1 accounting the singles would all dump onto- // worker 0, giving 15 vs 1.+ // other. With per-sub-batch accounting the singles would all dump onto+ // one worker, giving 15 vs 1.let (heavy, light) = if load0 >= load1 {(load0, load1)} else {@@ -765,20 +770,24 @@ mod tests {// Pin "user-1" to whichever worker gets it first.let b1 = dispatcher.assign(make_msgs(&[("t", "user-1")]));- let original_worker = b1[0].worker_idx;- let other_worker = 1 - original_worker;+ let original_worker = b1[0].worker.clone();+ let other_worker = if original_worker == wid(0) {+ wid(1)+ } else {+ wid(0)+ };// Drive the pinned worker to dead via passive signal.for _ in 0..5 {- registry.record_outcome(original_worker, true);+ registry.record_outcome(&original_worker, true);}tokio::time::sleep(Duration::from_millis(40)).await;- assert!(registry.is_dead(original_worker));+ assert!(registry.is_dead(&original_worker));// Next batch: pin must be dropped and key rerouted to the live worker.let b2 = dispatcher.assign(make_msgs(&[("t", "user-1")]));assert_eq!(b2.len(), 1);- assert_eq!(b2[0].worker_idx, other_worker);+ assert_eq!(b2[0].worker, other_worker);}#[test]@@ -787,14 +796,13 @@ mod tests {let dispatcher = Dispatcher::new(Arc::clone(®istry));// Force both workers to Unhealthy via passive signal (min_state_duration=0).- for idx in 0..2 {+ for i in 0..2 {for _ in 0..5 {- registry.record_outcome(idx, true);+ registry.record_outcome(&worker_url(i), true);}}- // Both workers are Unhealthy (not yet dead, but Unhealthy).- // Dispatcher should not route to Unhealthy workers.+ // Both workers are Unhealthy — the dispatcher should not route to them.let b = dispatcher.assign(make_msgs(&[("t", "user-1")]));assert!(b.is_empty());}@@ -812,7 +820,7 @@ mod tests {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].worker, wid(0));assert_eq!(sub_batches[0].messages.len(), 3);}@@ -822,18 +830,18 @@ mod tests {// 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;+ let pinned_worker = b1[0].worker.clone();// 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);+ assert_eq!(b2[0].worker, pinned_worker);}#[test]fn test_p2c_spreads_fresh_keys_across_two_workers() {- // With two workers, P2C samples both and the provisional bump after the- // first key steers the second to the other worker — one message each.+ // With two workers, P2C samples both and the load bump after the first+ // key steers the second to the other worker — one message each.let dispatcher = p2c_dispatcher(2, 3);let sub_batches = dispatcher.assign(make_msgs(&[("t", "user-1"), ("t", "user-2")]));@@ -848,14 +856,16 @@ mod tests {// 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;- }+ dispatcher+ .pin_table+ .lock()+ .unwrap()+ .in_flight+ .insert(wid(0), 5);let b = dispatcher.assign(make_msgs(&[("t", "fresh")]));assert_eq!(b.len(), 1);- assert_eq!(b[0].worker_idx, 1);+ assert_eq!(b[0].worker, wid(1));}#[tokio::test]@@ -864,9 +874,9 @@ mod tests {let dispatcher =Dispatcher::with_strategy_seeded(Arc::clone(®istry), RoutingStrategy::P2c, 1);- for idx in 0..2 {+ for i in 0..2 {for _ in 0..5 {- registry.record_outcome(idx, true);+ registry.record_outcome(&worker_url(i), true);}}diff --git a/rust/ingestion-consumer/src/lib.rs b/rust/ingestion-consumer/src/lib.rsindex 5ee64b036fb7..d4f3924500ba 100644--- a/rust/ingestion-consumer/src/lib.rs+++ b/rust/ingestion-consumer/src/lib.rs@@ -1,5 +1,6 @@pub mod config;pub mod consumer;+pub mod discovery;pub mod dispatcher;pub mod kafka_config;pub mod routing;diff --git a/rust/ingestion-consumer/src/main.rs b/rust/ingestion-consumer/src/main.rsindex 79bbbe0f92a1..42b6abf465f6 100644--- a/rust/ingestion-consumer/src/main.rs+++ b/rust/ingestion-consumer/src/main.rs@@ -19,6 +19,9 @@ use tracing_subscriber::{EnvFilter, Layer};use ingestion_consumer::config::Config;use ingestion_consumer::consumer::IngestionConsumer;+use ingestion_consumer::discovery::{+ DiscoveryMode, EndpointSliceDiscovery, StaticDiscovery, WorkerDiscovery,+};use ingestion_consumer::dispatcher::Dispatcher;use ingestion_consumer::transport::HttpTransport;use ingestion_consumer::worker_registry::{WorkerRegistry, WorkerRegistryConfig};@@ -126,22 +129,12 @@ async fn async_main(config: Config) -> Result<()> {let guard = manager.monitor_background();- let worker_urls = config.worker_urls();-- // Build the worker health registry and start background probe tasks.- let registry_config = WorkerRegistryConfig {- probe_interval: Duration::from_millis(config.worker_probe_interval_ms),- dead_declaration: Duration::from_millis(config.worker_dead_declaration_ms),- passive_window: Duration::from_millis(config.worker_passive_window_ms),- passive_error_threshold: config.worker_passive_error_threshold,- passive_min_samples: config.worker_passive_min_samples,- degraded_hold: Duration::from_millis(config.worker_degraded_hold_ms),- min_state_duration: Duration::from_millis(config.worker_min_state_duration_ms),- probe_failure_threshold: config.worker_probe_failure_threshold,- };- let registry = Arc::new(WorkerRegistry::new(&worker_urls, registry_config));+ // Build the worker health registry empty; the discovery provider below+ // populates it (statically from config, or dynamically from EndpointSlices).+ let registry_config = WorkerRegistryConfig::from(&config);+ let registry = Arc::new(WorkerRegistry::new(&[], registry_config));- // Probe tasks run until the consumer shuts down.+ // Probe tasks run until shutdown.let probe_token = CancellationToken::new();Arc::clone(®istry).start_probing(probe_token.clone());@@ -155,21 +148,64 @@ 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 transport = Arc::new(HttpTransport::new(Duration::from_millis(config.http_timeout_ms),config.max_retries,api_secret,- &worker_urls,+ &[],config.ingestion_worker_concurrent_batches,));+ // Select the worker discovery provider and start it (static applies the+ // configured list immediately; endpointslice watches and keeps in sync).+ let discovery_token = CancellationToken::new();+ let discovery: Box<dyn WorkerDiscovery> = match config.worker_discovery_mode {+ DiscoveryMode::Static => Box::new(StaticDiscovery::new(config.worker_urls())),+ DiscoveryMode::EndpointSlice => {+ if config.worker_service_name.is_empty() {+ anyhow::bail!("WORKER_SERVICE_NAME is required for endpointslice discovery");+ }+ let client = kube::Client::try_default()+ .await+ .context("Failed to create Kubernetes client for EndpointSlice discovery")?;+ Box::new(EndpointSliceDiscovery::new(+ client,+ config.worker_namespace.clone(),+ config.worker_service_name.clone(),+ config.worker_port,+ ))+ }+ };+ let _discovery_handle = discovery.start(+ Arc::clone(®istry),+ Arc::clone(&transport),+ discovery_token.clone(),+ );++ // For dynamic discovery, wait for the first workers before consuming so the+ // first batch has somewhere to route.+ if config.worker_discovery_mode == DiscoveryMode::EndpointSlice {+ info!("Waiting for the first workers from EndpointSlice discovery");+ while registry.worker_count() == 0 {+ tokio::select! {+ _ = consumer_handle.shutdown_recv() => {+ info!("Shutdown received while waiting for worker discovery");+ break;+ }+ _ = tokio::time::sleep(Duration::from_millis(250)) => {}+ }+ }+ }+let consumer = IngestionConsumer::new(&config, dispatcher, transport, consumer_handle).context("Failed to create Kafka consumer")?;tokio::spawn(async move {consumer.process().await;- // Cancel probe tasks once the consumer loop exits.+ // Cancel background tasks once the consumer loop exits.probe_token.cancel();+ discovery_token.cancel();});// Build and serve the health/metrics HTTP serverdiff --git a/rust/ingestion-consumer/src/routing.rs b/rust/ingestion-consumer/src/routing.rsindex e67ae73549fd..2398a232970d 100644--- a/rust/ingestion-consumer/src/routing.rs+++ b/rust/ingestion-consumer/src/routing.rs@@ -7,18 +7,21 @@//! routing policy evolve (P2C cost functions, subsetting) without touching the//! dispatcher's bookkeeping.+use std::collections::HashMap;use std::str::FromStr;use rand::rngs::StdRng;use rand::{Rng, SeedableRng};+use crate::worker_registry::WorkerId;+/// How unpinned routing keys are assigned to workers. Pinned keys always go to/// their existing worker regardless of strategy.#[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.+ /// Largest-first bin-packing onto the 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@@ -41,6 +44,14 @@ impl FromStr for RoutingStrategy {}}+/// Per-worker load for a single routing decision, keyed by worker id. A missing+/// entry counts as zero load.+pub type WorkerLoad = HashMap<WorkerId, usize>;++fn load_of(load: &WorkerLoad, worker: &WorkerId) -> usize {+ load.get(worker).copied().unwrap_or(0)+}+/// 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.@@ -78,58 +89,43 @@ impl Router {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> {+ /// Select a worker for one group. `healthy` lists candidate worker ids;+ /// `load` is the current per-worker load (outstanding messages plus what has+ /// been provisionally assigned earlier in this round). Returns `None` when+ /// no workers are healthy.+ pub fn select(&mut self, healthy: &[WorkerId], load: &WorkerLoad) -> Option<WorkerId> {match self.strategy {- RoutingStrategy::BinPack => select_least_loaded(healthy, in_flight, provisional),- RoutingStrategy::P2c => select_p2c(healthy, in_flight, provisional, &mut self.rng),+ RoutingStrategy::BinPack => select_least_loaded(healthy, load),+ RoutingStrategy::P2c => select_p2c(healthy, load, &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 least-loaded healthy worker. Ties resolve to the first such worker+/// in `healthy`.+fn select_least_loaded(healthy: &[WorkerId], load: &WorkerLoad) -> Option<WorkerId> {+ healthy.iter().min_by_key(|w| load_of(load, w)).cloned()}/// 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];+fn select_p2c(healthy: &[WorkerId], load: &WorkerLoad, rng: &mut impl Rng) -> Option<WorkerId> {match healthy.len() {0 => None,- 1 => Some(healthy[0]),+ 1 => Some(healthy[0].clone()),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.+ // correct even if a caller ever passes duplicate worker ids.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 })+ let (a, b) = (&healthy[i], &healthy[j]);+ Some(if load_of(load, a) <= load_of(load, b) {+ a.clone()+ } else {+ b.clone()+ })}}}@@ -138,6 +134,18 @@ fn select_p2c(mod tests {use super::*;+ fn wid(s: &str) -> WorkerId {+ WorkerId::from(s)+ }++ fn load(pairs: &[(&str, usize)]) -> WorkerLoad {+ pairs.iter().map(|(w, n)| (wid(w), *n)).collect()+ }++ const A: &str = "http://w:1";+ const B: &str = "http://w:2";+ const C: &str = "http://w:3";+// ---- strategy parsing ----#[test]@@ -168,41 +176,29 @@ mod tests {#[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)- );+ let healthy = [wid(A), wid(B), wid(C)];+ let l = load(&[(A, 5), (B, 1), (C, 3)]);+ assert_eq!(select_least_loaded(&healthy, &l), Some(wid(B)));}#[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)- );+ fn test_least_loaded_treats_missing_as_zero() {+ let healthy = [wid(A), wid(B)];+ // B has no entry → load 0 → lighter than A.+ let l = load(&[(A, 2)]);+ assert_eq!(select_least_loaded(&healthy, &l), Some(wid(B)));}#[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)- );+ fn test_least_loaded_breaks_ties_to_first_in_slice() {+ let healthy = [wid(A), wid(B), wid(C)];+ let l = load(&[(A, 2), (B, 2), (C, 2)]);+ assert_eq!(select_least_loaded(&healthy, &l), Some(wid(A)));}#[test]fn test_least_loaded_empty_pool_returns_none() {- assert_eq!(select_least_loaded(&[], &[], &[]), None);+ assert_eq!(select_least_loaded(&[], &WorkerLoad::new()), None);}// ---- p2c ----@@ -210,68 +206,68 @@ mod tests {#[test]fn test_p2c_empty_pool_returns_none() {let mut rng = StdRng::seed_from_u64(1);- assert_eq!(select_p2c(&[], &[], &[], &mut rng), None);+ assert_eq!(select_p2c(&[], &WorkerLoad::new(), &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));+ assert_eq!(+ select_p2c(&[wid(C)], &load(&[(C, 9)]), &mut rng),+ Some(wid(C))+ );}#[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.+ let healthy = [wid(A), wid(B)];+ let l = load(&[(A, 3), (B, 0)]);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),+ select_p2c(&healthy, &l, &mut rng),+ Some(wid(B)),"seed {seed}");}}#[test]- fn test_p2c_terminates_with_duplicate_indices() {+ fn test_p2c_terminates_with_duplicate_ids() {// Regression: selection must not loop even if the candidate slice- // contains duplicate worker indices.+ // contains duplicate worker ids.+ let healthy = [wid(C), wid(C)];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)+ select_p2c(&healthy, &WorkerLoad::new(), &mut rng),+ Some(wid(C)));}}#[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 healthy = [wid(A), wid(B), wid(C)];+ let l = load(&[(A, 2), (C, 5)]);let mut rng = StdRng::seed_from_u64(7);for _ in 0..200 {- let pick = select_p2c(&healthy, &in_flight, &provisional, &mut rng).unwrap();+ let pick = select_p2c(&healthy, &l, &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];+ fn test_p2c_spreads_across_pool() {+ let healthy = [wid(A), wid(B), wid(C)];let mut rng = StdRng::seed_from_u64(42);- let mut seen = [false; 4];+ let mut seen = std::collections::HashSet::new();for _ in 0..200 {- let pick = select_p2c(&healthy, &in_flight, &provisional, &mut rng).unwrap();- seen[pick] = true;+ seen.insert(select_p2c(&healthy, &WorkerLoad::new(), &mut rng).unwrap());}- assert!(seen.iter().all(|&s| s), "every worker should be reachable");+ assert_eq!(seen.len(), 3, "every worker should be reachable");}// ---- router dispatch ----@@ -280,7 +276,9 @@ mod tests {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));+ let healthy = [wid(A), wid(B), wid(C)];+ let l = load(&[(A, 4), (B, 1), (C, 2)]);+ assert_eq!(router.select(&healthy, &l), Some(wid(B)));}#[test]diff --git a/rust/ingestion-consumer/src/transport.rs b/rust/ingestion-consumer/src/transport.rsindex 385d19aade95..0302b0889c84 100644--- a/rust/ingestion-consumer/src/transport.rs+++ b/rust/ingestion-consumer/src/transport.rs@@ -1,7 +1,7 @@-use std::collections::HashMap;use std::sync::Arc;use std::time::Duration;+use dashmap::DashMap;use metrics::{counter, gauge, histogram};use rand::Rng;use tokio::sync::Semaphore;@@ -48,11 +48,16 @@ impl Drop for InFlightGuard {/// and retries with a longer, jittered backoff. This keeps the consumer correct/// when a worker is shared by other callers and its true capacity isn't a/// number this consumer can reserve in advance.+///+/// Semaphores are created lazily on first send to a worker and pruned via+/// [`remove_worker`](HttpTransport::remove_worker), so the worker pool can+/// change at runtime (workers joining/leaving via discovery).pub struct HttpTransport {client: reqwest::Client,max_retries: u32,api_secret: Option<String>,- worker_semaphores: HashMap<String, Arc<Semaphore>>,+ worker_semaphores: DashMap<String, Arc<Semaphore>>,+ worker_concurrent_batches: usize,}impl HttpTransport {@@ -74,22 +79,42 @@ impl HttpTransport {.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();+ // Pre-seed semaphores for the initial worker set; new workers get one+ // lazily on first send (see `semaphore_for`).+ let worker_semaphores = DashMap::new();+ for url in worker_urls {+ worker_semaphores.insert(+ url.clone(),+ Arc::new(Semaphore::new(worker_concurrent_batches)),+ );+ }Self {client,max_retries,api_secret,worker_semaphores,+ worker_concurrent_batches,+ }+ }++ /// Get the worker's concurrency semaphore, creating it on first use so the+ /// transport serves workers added at runtime without explicit registration.+ fn semaphore_for(&self, worker_url: &str) -> Arc<Semaphore> {+ if let Some(sem) = self.worker_semaphores.get(worker_url) {+ return sem.clone();}+ self.worker_semaphores+ .entry(worker_url.to_string())+ .or_insert_with(|| Arc::new(Semaphore::new(self.worker_concurrent_batches)))+ .clone()+ }++ /// Drop a worker's semaphore after it leaves the pool, so departed workers+ /// don't accumulate. In-flight sends already hold a cloned `Arc`, so their+ /// permits remain valid until they complete.+ pub fn remove_worker(&self, worker_url: &str) {+ self.worker_semaphores.remove(worker_url);}/// Check if a worker is ready by probing its health endpoint.@@ -154,11 +179,7 @@ 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();+ let semaphore = self.semaphore_for(worker_url);// Atomic "did we actually have to wait?" check. `available_permits`// followed by `acquire_owned` would race — a permit could be released@@ -304,9 +325,6 @@ pub enum TransportError {#[error("Worker returned error: {0}")]WorkerError(String),- #[error("Unknown worker URL: {0}")]- UnknownWorker(String),-#[error("All retries exhausted")]RetriesExhausted,}@@ -323,7 +341,6 @@ impl TransportError {TransportError::Http(_) => true,TransportError::WorkerBusy(_) => true,TransportError::WorkerError(_) => true,- TransportError::UnknownWorker(_) => false,TransportError::RetriesExhausted => false,}}@@ -356,7 +373,7 @@ mod tests {#[test]fn test_client_errors_are_not_retriable() {assert!(!TransportError::HttpStatus(400, "bad".into()).is_retriable());- assert!(!TransportError::UnknownWorker("x".into()).is_retriable());+ assert!(!TransportError::RetriesExhausted.is_retriable());}#[test]diff --git a/rust/ingestion-consumer/src/worker_registry.rs b/rust/ingestion-consumer/src/worker_registry.rsindex 11a6a06f6326..a0709f2974f6 100644--- a/rust/ingestion-consumer/src/worker_registry.rs+++ b/rust/ingestion-consumer/src/worker_registry.rs@@ -1,7 +1,9 @@use std::collections::VecDeque;-use std::sync::{Arc, Mutex};+use std::sync::Arc;use std::time::{Duration, Instant};+use dashmap::mapref::entry::Entry;+use dashmap::DashMap;use metrics::{counter, gauge, histogram};use tokio_util::sync::CancellationToken;use tracing::{info, warn};@@ -10,6 +12,11 @@ use crate::config::Config;const PASSIVE_WINDOW_MAX_ENTRIES: usize = 10_000;+/// Stable identity for a worker: its base HTTP URL (e.g. `http://10.0.0.1:9001`).+/// Used as the key for health, routing pins, and in-flight load so the worker+/// set can change at runtime without the index-shifting hazards of a `Vec`.+pub type WorkerId = Arc<str>;+#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum WorkerState {Healthy,@@ -48,7 +55,20 @@ fn set_state_gauge(worker_url: &str, current: WorkerState) {}}-/// Per-worker mutable health state, behind a Mutex.+/// Clear the state-set gauge for a worker that has left the pool, so a departed+/// worker doesn't linger at 1 in dashboards.+fn clear_state_gauge(worker_url: &str) {+ for state in WorkerState::ALL {+ gauge!(+ "ingestion_consumer_worker_health_state",+ "worker" => worker_url.to_string(),+ "state" => state.as_str(),+ )+ .set(0.0);+ }+}++/// Per-worker mutable health state.struct WorkerHealth {state: WorkerState,state_entered_at: Instant,@@ -183,7 +203,9 @@ impl From<&Config> for WorkerRegistryConfig {}}-/// Tracks the health state of each Node.js worker using two independent signals:+/// Tracks the health state of each Node.js worker, keyed by worker URL so the+/// set can change at runtime (workers joining/leaving the pool). Uses two+/// independent signals:////// - **Active probe**: GET `/_ready` every `probe_interval`. Two consecutive/// failures move the worker to `Unhealthy`; one success starts the recovery@@ -197,9 +219,10 @@ impl From<&Config> for WorkerRegistryConfig {////// A worker that has been `Unhealthy` for at least `dead_declaration` is/// considered **dead** — the Dispatcher uses this to drop sticky pins so the-/// next batch can re-route around the worker.+/// next batch can re-route around the worker. A worker removed from the pool+/// entirely is also reported dead.pub struct WorkerRegistry {- workers: Vec<(String, Mutex<WorkerHealth>)>,+ workers: DashMap<WorkerId, WorkerHealth>,config: WorkerRegistryConfig,client: reqwest::Client,}@@ -213,14 +236,11 @@ impl WorkerRegistry {.build().expect("failed to create probe HTTP client");- let workers: Vec<(String, Mutex<WorkerHealth>)> = worker_urls- .iter()- .map(|url| (url.clone(), Mutex::new(WorkerHealth::new())))- .collect();-- // Emit the initial state for every worker so the gauge exists from- // startup rather than only after the first transition.- for (url, _) in &workers {+ let workers = DashMap::new();+ for url in worker_urls {+ workers.insert(WorkerId::from(url.as_str()), WorkerHealth::new());+ // Emit the initial state so the gauge exists from startup rather+ // than only after the first transition.set_state_gauge(url, WorkerState::Healthy);}@@ -235,22 +255,74 @@ impl WorkerRegistry {self.workers.len()}- pub fn state(&self, worker_idx: usize) -> WorkerState {- self.workers[worker_idx].1.lock().unwrap().state+ /// Snapshot of all current worker ids.+ pub fn workers(&self) -> Vec<WorkerId> {+ self.workers.iter().map(|e| e.key().clone()).collect()}- pub fn is_dead(&self, worker_idx: usize) -> bool {- self.workers[worker_idx]- .1- .lock()- .unwrap()- .is_dead(self.config.dead_declaration)+ /// Snapshot of worker ids currently eligible for routing (Healthy or+ /// Degraded). Returned in arbitrary order.+ pub fn healthy_workers(&self) -> Vec<WorkerId> {+ self.workers+ .iter()+ .filter(|e| {+ matches!(+ e.value().state,+ WorkerState::Healthy | WorkerState::Degraded+ )+ })+ .map(|e| e.key().clone())+ .collect()+ }++ /// Current state of a worker. An unknown worker (already removed from the+ /// pool) reports `Unhealthy` so callers never route to it.+ pub fn state(&self, worker: &str) -> WorkerState {+ self.workers+ .get(worker)+ .map(|h| h.state)+ .unwrap_or(WorkerState::Unhealthy)+ }++ /// Whether a worker is dead — Unhealthy for at least `dead_declaration`, or+ /// no longer in the pool at all (so its sticky pins get dropped).+ pub fn is_dead(&self, worker: &str) -> bool {+ self.workers+ .get(worker)+ .map(|h| h.is_dead(self.config.dead_declaration))+ .unwrap_or(true)+ }++ /// Add a worker to the pool if not already present (starts Healthy).+ /// Idempotent — re-adding an existing worker preserves its current health.+ pub fn add_worker(&self, worker: WorkerId) {+ // `entry` makes the check-and-insert atomic — a plain+ // `contains_key` + `insert` could let a concurrent caller overwrite a+ // fresh `WorkerHealth` and reset health state.+ let Entry::Vacant(slot) = self.workers.entry(worker.clone()) else {+ return;+ };+ set_state_gauge(&worker, WorkerState::Healthy);+ info!(worker = %worker, "Worker added to pool");+ slot.insert(WorkerHealth::new());+ counter!("ingestion_consumer_worker_membership_total", "action" => "add").increment(1);+ }++ /// Remove a worker from the pool (e.g. it left the EndpointSlice).+ pub fn remove_worker(&self, worker: &str) {+ if self.workers.remove(worker).is_some() {+ clear_state_gauge(worker);+ info!(worker = %worker, "Worker removed from pool");+ counter!("ingestion_consumer_worker_membership_total", "action" => "remove")+ .increment(1);+ }}/// Record the outcome of a `send_batch` call for the passive signal.- pub fn record_outcome(&self, worker_idx: usize, is_error: bool) {- let (url, health_lock) = &self.workers[worker_idx];- let mut health = health_lock.lock().unwrap();+ pub fn record_outcome(&self, worker: &str, is_error: bool) {+ let Some(mut health) = self.workers.get_mut(worker) else {+ return;+ };health.passive_window.push_back((Instant::now(), is_error));if health.passive_window.len() > PASSIVE_WINDOW_MAX_ENTRIES {@@ -260,7 +332,7 @@ impl WorkerRegistry {let (error_rate, sample_count) = health.passive_error_rate(self.config.passive_window);gauge!("ingestion_consumer_worker_passive_error_rate",- "worker" => url.clone(),+ "worker" => worker.to_string(),).set(error_rate);@@ -273,80 +345,80 @@ impl WorkerRegistry {WorkerState::Unhealthy => None,};if let Some(new_state) = target {- health.try_transition(new_state, self.config.min_state_duration, url);+ health.try_transition(new_state, self.config.min_state_duration, worker);}}}- /// Spawn a background probe task for each worker. The tasks run until- /// `token` is cancelled. Call this on an `Arc<WorkerRegistry>` so each- /// task can hold its own clone of the registry.+ /// Spawn a single background task that probes every current worker each+ /// `probe_interval`. Runs until `token` is cancelled. The worker set is+ /// re-read each tick, so workers added/removed at runtime are picked up.pub fn start_probing(self: Arc<Self>, token: CancellationToken) {- for idx in 0..self.workers.len() {- let registry = self.clone();- let token = token.clone();- tokio::spawn(async move {- registry.run_probe(idx, token).await;- });- }+ tokio::spawn(async move {+ loop {+ tokio::select! {+ _ = token.cancelled() => break,+ _ = tokio::time::sleep(self.config.probe_interval) => {}+ }++ let workers = self.workers();+ let probes = workers.into_iter().map(|worker| {+ let registry = Arc::clone(&self);+ async move { registry.probe_once(&worker).await }+ });+ futures::future::join_all(probes).await;+ }+ });}- async fn run_probe(&self, worker_idx: usize, token: CancellationToken) {- let (url, _) = &self.workers[worker_idx];- let url = url.clone();+ async fn probe_once(&self, worker: &str) {+ let start = Instant::now();+ let result = self.client.get(format!("{worker}/_ready")).send().await;+ let elapsed = start.elapsed();+ let is_success = result.map(|r| r.status().is_success()).unwrap_or(false);- loop {- tokio::select! {- _ = token.cancelled() => break,- _ = tokio::time::sleep(self.config.probe_interval) => {}- }+ histogram!(+ "ingestion_consumer_worker_probe_duration_seconds",+ "worker" => worker.to_string(),+ "outcome" => if is_success { "success" } else { "failure" },+ )+ .record(elapsed.as_secs_f64());- let start = Instant::now();- let result = self.client.get(format!("{url}/_ready")).send().await;- let elapsed = start.elapsed();- let is_success = result.map(|r| r.status().is_success()).unwrap_or(false);-- histogram!(- "ingestion_consumer_worker_probe_duration_seconds",- "worker" => url.clone(),- "outcome" => if is_success { "success" } else { "failure" },- )- .record(elapsed.as_secs_f64());-- let (worker_url, health_lock) = &self.workers[worker_idx];- let mut health = health_lock.lock().unwrap();-- if is_success {- health.consecutive_probe_failures = 0;-- let new_state = match health.state {- WorkerState::Unhealthy => Some(WorkerState::Degraded),- WorkerState::Degraded => {- if health.state_entered_at.elapsed() >= self.config.degraded_hold {- Some(WorkerState::Healthy)- } else {- None- }+ // The worker may have been removed between the snapshot and now.+ let Some(mut health) = self.workers.get_mut(worker) else {+ return;+ };++ if is_success {+ health.consecutive_probe_failures = 0;++ let new_state = match health.state {+ WorkerState::Unhealthy => Some(WorkerState::Degraded),+ WorkerState::Degraded => {+ if health.state_entered_at.elapsed() >= self.config.degraded_hold {+ Some(WorkerState::Healthy)+ } else {+ None}- WorkerState::Healthy => None,- };- if let Some(s) = new_state {- health.try_transition(s, self.config.min_state_duration, worker_url);}- } else {- health.consecutive_probe_failures += 1;- warn!(- worker = %worker_url,- consecutive_failures = health.consecutive_probe_failures,- "Worker probe failed"+ WorkerState::Healthy => None,+ };+ if let Some(s) = new_state {+ health.try_transition(s, self.config.min_state_duration, worker);+ }+ } else {+ health.consecutive_probe_failures += 1;+ warn!(+ worker = %worker,+ consecutive_failures = health.consecutive_probe_failures,+ "Worker probe failed"+ );+ if health.consecutive_probe_failures >= self.config.probe_failure_threshold {+ health.try_transition(+ WorkerState::Unhealthy,+ self.config.min_state_duration,+ worker,);- if health.consecutive_probe_failures >= self.config.probe_failure_threshold {- health.try_transition(- WorkerState::Unhealthy,- self.config.min_state_duration,- worker_url,- );- }}}}@@ -358,6 +430,10 @@ mod tests {use super::*;+ const W1: &str = "http://worker:9001";+ const W2: &str = "http://worker:9002";+ const W3: &str = "http://worker:9003";+fn no_cooldown_config() -> WorkerRegistryConfig {WorkerRegistryConfig {probe_interval: Duration::from_millis(50),@@ -371,83 +447,76 @@ mod tests {}}- fn worker_urls() -> Vec<String> {- vec!["http://worker:9001".to_string()]+ fn one_worker() -> Vec<String> {+ vec![W1.to_string()]}- fn multi_worker_urls() -> Vec<String> {- vec![- "http://worker:9001".to_string(),- "http://worker:9002".to_string(),- "http://worker:9003".to_string(),- ]+ fn three_workers() -> Vec<String> {+ vec![W1.to_string(), W2.to_string(), W3.to_string()]}// --- Passive signal transitions ---#[test]fn test_passive_healthy_to_degraded() {- let registry = WorkerRegistry::new(&worker_urls(), no_cooldown_config());+ let registry = WorkerRegistry::new(&one_worker(), no_cooldown_config());// 3 errors = 100% error rate, 3 samples ≥ min_samples=3, rate > threshold=0.5- registry.record_outcome(0, true);- registry.record_outcome(0, true);- registry.record_outcome(0, true);+ registry.record_outcome(W1, true);+ registry.record_outcome(W1, true);+ registry.record_outcome(W1, true);- assert_eq!(registry.state(0), WorkerState::Degraded);+ assert_eq!(registry.state(W1), WorkerState::Degraded);}#[test]fn test_passive_degraded_to_unhealthy() {- let registry = WorkerRegistry::new(&worker_urls(), no_cooldown_config());+ let registry = WorkerRegistry::new(&one_worker(), no_cooldown_config());- // Reach Degraded- registry.record_outcome(0, true);- registry.record_outcome(0, true);- registry.record_outcome(0, true);- assert_eq!(registry.state(0), WorkerState::Degraded);+ for _ in 0..3 {+ registry.record_outcome(W1, true);+ }+ assert_eq!(registry.state(W1), WorkerState::Degraded);// One more error pushes Degraded → Unhealthy (still above threshold)- registry.record_outcome(0, true);- assert_eq!(registry.state(0), WorkerState::Unhealthy);+ registry.record_outcome(W1, true);+ assert_eq!(registry.state(W1), WorkerState::Unhealthy);}#[test]fn test_passive_below_threshold_stays_healthy() {- let registry = WorkerRegistry::new(&worker_urls(), no_cooldown_config());+ let registry = WorkerRegistry::new(&one_worker(), no_cooldown_config());// 1 error out of 3 = 33% < threshold=50%- registry.record_outcome(0, true);- registry.record_outcome(0, false);- registry.record_outcome(0, false);+ registry.record_outcome(W1, true);+ registry.record_outcome(W1, false);+ registry.record_outcome(W1, false);- assert_eq!(registry.state(0), WorkerState::Healthy);+ assert_eq!(registry.state(W1), WorkerState::Healthy);}#[test]fn test_passive_below_min_samples_stays_healthy() {- let registry = WorkerRegistry::new(&worker_urls(), no_cooldown_config());+ let registry = WorkerRegistry::new(&one_worker(), no_cooldown_config());// 2 errors but only 2 samples < min_samples=3- registry.record_outcome(0, true);- registry.record_outcome(0, true);+ registry.record_outcome(W1, true);+ registry.record_outcome(W1, true);- assert_eq!(registry.state(0), WorkerState::Healthy);+ assert_eq!(registry.state(W1), WorkerState::Healthy);}#[test]fn test_passive_unhealthy_stays_unhealthy() {- let registry = WorkerRegistry::new(&worker_urls(), no_cooldown_config());+ let registry = WorkerRegistry::new(&one_worker(), no_cooldown_config());- // Drive to Unhealthyfor _ in 0..4 {- registry.record_outcome(0, true);+ registry.record_outcome(W1, true);}- assert_eq!(registry.state(0), WorkerState::Unhealthy);+ assert_eq!(registry.state(W1), WorkerState::Unhealthy);- // More errors don't change anything- registry.record_outcome(0, true);- assert_eq!(registry.state(0), WorkerState::Unhealthy);+ registry.record_outcome(W1, true);+ assert_eq!(registry.state(W1), WorkerState::Unhealthy);}// --- Cooldown ---@@ -458,27 +527,24 @@ mod tests {min_state_duration: Duration::from_secs(100),..no_cooldown_config()};- let registry = WorkerRegistry::new(&worker_urls(), config);+ let registry = WorkerRegistry::new(&one_worker(), config);- // Threshold crossed but cooldown blocks Healthy → Degraded- registry.record_outcome(0, true);- registry.record_outcome(0, true);- registry.record_outcome(0, true);+ registry.record_outcome(W1, true);+ registry.record_outcome(W1, true);+ registry.record_outcome(W1, true);- assert_eq!(registry.state(0), WorkerState::Healthy);+ assert_eq!(registry.state(W1), WorkerState::Healthy);}// --- Probe-driven transitions (via direct WorkerHealth manipulation) ---#[test]fn test_probe_failures_to_unhealthy() {- let registry = WorkerRegistry::new(&worker_urls(), no_cooldown_config());- let (url, health_lock) = ®istry.workers[0];- let mut health = health_lock.lock().unwrap();+ let registry = WorkerRegistry::new(&one_worker(), no_cooldown_config());+ let mut health = registry.workers.get_mut(W1).unwrap();- // Simulate 2 consecutive probe failureshealth.consecutive_probe_failures = 2;- let transitioned = health.try_transition(WorkerState::Unhealthy, Duration::ZERO, url);+ let transitioned = health.try_transition(WorkerState::Unhealthy, Duration::ZERO, W1);assert!(transitioned);assert_eq!(health.state, WorkerState::Unhealthy);@@ -487,16 +553,13 @@ mod tests {#[test]fn test_probe_success_unhealthy_to_degraded() {- let registry = WorkerRegistry::new(&worker_urls(), no_cooldown_config());- let (url, health_lock) = ®istry.workers[0];- let mut health = health_lock.lock().unwrap();+ let registry = WorkerRegistry::new(&one_worker(), no_cooldown_config());+ let mut health = registry.workers.get_mut(W1).unwrap();- // Start in Unhealthy- health.try_transition(WorkerState::Unhealthy, Duration::ZERO, url);+ health.try_transition(WorkerState::Unhealthy, Duration::ZERO, W1);assert_eq!(health.state, WorkerState::Unhealthy);- // Probe success → Degraded- let transitioned = health.try_transition(WorkerState::Degraded, Duration::ZERO, url);+ let transitioned = health.try_transition(WorkerState::Degraded, Duration::ZERO, W1);assert!(transitioned);assert_eq!(health.state, WorkerState::Degraded);@@ -505,12 +568,9 @@ mod tests {#[test]fn test_probe_failure_threshold_not_reached() {- let registry = WorkerRegistry::new(&worker_urls(), no_cooldown_config());- let (_, health_lock) = ®istry.workers[0];- let mut health = health_lock.lock().unwrap();+ let registry = WorkerRegistry::new(&one_worker(), no_cooldown_config());+ let health = registry.workers.get(W1).unwrap();- // Only 1 failure — below threshold of 2- health.consecutive_probe_failures = 1;assert_eq!(health.state, WorkerState::Healthy);}@@ -522,23 +582,79 @@ mod tests {dead_declaration: Duration::from_millis(30),..no_cooldown_config()};- let registry = WorkerRegistry::new(&worker_urls(), config);+ let registry = WorkerRegistry::new(&one_worker(), config);- // Drive to Unhealthyfor _ in 0..4 {- registry.record_outcome(0, true);+ registry.record_outcome(W1, true);}- assert_eq!(registry.state(0), WorkerState::Unhealthy);- assert!(!registry.is_dead(0));+ assert_eq!(registry.state(W1), WorkerState::Unhealthy);+ assert!(!registry.is_dead(W1));tokio::time::sleep(Duration::from_millis(40)).await;- assert!(registry.is_dead(0));+ assert!(registry.is_dead(W1));}#[test]fn test_healthy_worker_is_not_dead() {- let registry = WorkerRegistry::new(&worker_urls(), no_cooldown_config());- assert!(!registry.is_dead(0));+ let registry = WorkerRegistry::new(&one_worker(), no_cooldown_config());+ assert!(!registry.is_dead(W1));+ }++ // --- Membership ---++ #[test]+ fn test_unknown_worker_is_dead_and_unhealthy() {+ let registry = WorkerRegistry::new(&one_worker(), no_cooldown_config());+ assert!(registry.is_dead("http://worker:9999"));+ assert_eq!(registry.state("http://worker:9999"), WorkerState::Unhealthy);+ }++ #[test]+ fn test_add_worker_makes_it_healthy_and_routable() {+ let registry = WorkerRegistry::new(&one_worker(), no_cooldown_config());+ assert_eq!(registry.worker_count(), 1);++ registry.add_worker(WorkerId::from(W2));+ assert_eq!(registry.worker_count(), 2);+ assert_eq!(registry.state(W2), WorkerState::Healthy);+ assert!(registry.healthy_workers().iter().any(|w| w.as_ref() == W2));+ }++ #[test]+ fn test_add_worker_is_idempotent_and_preserves_state() {+ let registry = WorkerRegistry::new(&one_worker(), no_cooldown_config());+ // Drive W1 to Degraded, then re-add it — must not reset to Healthy.+ for _ in 0..3 {+ registry.record_outcome(W1, true);+ }+ assert_eq!(registry.state(W1), WorkerState::Degraded);++ registry.add_worker(WorkerId::from(W1));+ assert_eq!(registry.worker_count(), 1);+ assert_eq!(registry.state(W1), WorkerState::Degraded);+ }++ #[test]+ fn test_remove_worker_drops_it_from_pool() {+ let registry = WorkerRegistry::new(&three_workers(), no_cooldown_config());+ registry.remove_worker(W2);++ assert_eq!(registry.worker_count(), 2);+ assert!(registry.is_dead(W2));+ assert!(!registry.healthy_workers().iter().any(|w| w.as_ref() == W2));+ }++ #[test]+ fn test_healthy_workers_excludes_unhealthy() {+ let registry = WorkerRegistry::new(&three_workers(), no_cooldown_config());+ for _ in 0..4 {+ registry.record_outcome(W2, true);+ }+ assert_eq!(registry.state(W2), WorkerState::Unhealthy);++ let healthy = registry.healthy_workers();+ assert_eq!(healthy.len(), 2);+ assert!(!healthy.iter().any(|w| w.as_ref() == W2));}// --- Passive window pruning ---@@ -551,22 +667,18 @@ mod tests {passive_error_threshold: 0.5,..no_cooldown_config()};- let registry = WorkerRegistry::new(&worker_urls(), config);+ let registry = WorkerRegistry::new(&one_worker(), config);- // 2 errors → should cross threshold- registry.record_outcome(0, true);- registry.record_outcome(0, true);- assert_eq!(registry.state(0), WorkerState::Degraded);+ registry.record_outcome(W1, true);+ registry.record_outcome(W1, true);+ assert_eq!(registry.state(W1), WorkerState::Degraded);- // Wait for window to expire, then add successes — error rate dropstokio::time::sleep(Duration::from_millis(40)).await;- registry.record_outcome(0, false);- registry.record_outcome(0, false);+ registry.record_outcome(W1, false);+ registry.record_outcome(W1, false);- // The old errors are pruned; now 0/2 = 0% error ratelet (rate, count) = {- let (_, health_lock) = ®istry.workers[0];- let mut health = health_lock.lock().unwrap();+ let mut health = registry.workers.get_mut(W1).unwrap();health.passive_error_rate(Duration::from_millis(30))};@@ -578,41 +690,21 @@ mod tests {#[test]fn test_worker_count() {- let registry = WorkerRegistry::new(&multi_worker_urls(), no_cooldown_config());+ let registry = WorkerRegistry::new(&three_workers(), no_cooldown_config());assert_eq!(registry.worker_count(), 3);}#[test]fn test_states_are_independent_per_worker() {- let registry = WorkerRegistry::new(&multi_worker_urls(), no_cooldown_config());+ let registry = WorkerRegistry::new(&three_workers(), no_cooldown_config());- // Drive worker 1 to Unhealthy; workers 0 and 2 are untouched- for _ in 0..4 {- registry.record_outcome(1, true);- }-- assert_eq!(registry.state(0), WorkerState::Healthy);- assert_eq!(registry.state(1), WorkerState::Unhealthy);- assert_eq!(registry.state(2), WorkerState::Healthy);- }-- #[test]- fn test_workers_can_be_in_different_states() {- let registry = WorkerRegistry::new(&multi_worker_urls(), no_cooldown_config());-- // Worker 0: Healthy (no errors)- // Worker 1: Degraded (just crossed passive threshold)- registry.record_outcome(1, true);- registry.record_outcome(1, true);- registry.record_outcome(1, true);- // Worker 2: Unhealthyfor _ in 0..4 {- registry.record_outcome(2, true);+ registry.record_outcome(W2, true);}- assert_eq!(registry.state(0), WorkerState::Healthy);- assert_eq!(registry.state(1), WorkerState::Degraded);- assert_eq!(registry.state(2), WorkerState::Unhealthy);+ assert_eq!(registry.state(W1), WorkerState::Healthy);+ assert_eq!(registry.state(W2), WorkerState::Unhealthy);+ assert_eq!(registry.state(W3), WorkerState::Healthy);}#[tokio::test]@@ -621,58 +713,39 @@ mod tests {dead_declaration: Duration::from_millis(30),..no_cooldown_config()};- let registry = WorkerRegistry::new(&multi_worker_urls(), config);+ let registry = WorkerRegistry::new(&three_workers(), config);- // Drive only worker 2 to Unhealthyfor _ in 0..4 {- registry.record_outcome(2, true);+ registry.record_outcome(W3, true);}tokio::time::sleep(Duration::from_millis(40)).await;- assert!(!registry.is_dead(0));- assert!(!registry.is_dead(1));- assert!(registry.is_dead(2));- }-- #[test]- fn test_outcome_targets_correct_worker() {- let registry = WorkerRegistry::new(&multi_worker_urls(), no_cooldown_config());-- // Record enough errors on worker 2 to cross threshold- registry.record_outcome(2, true);- registry.record_outcome(2, true);- registry.record_outcome(2, true);-- // Workers 0 and 1 must be unaffected- assert_eq!(registry.state(0), WorkerState::Healthy);- assert_eq!(registry.state(1), WorkerState::Healthy);- assert_eq!(registry.state(2), WorkerState::Degraded);+ assert!(!registry.is_dead(W1));+ assert!(!registry.is_dead(W2));+ assert!(registry.is_dead(W3));}// --- consecutive_probe_failures reset on transition ---#[test]fn test_probe_failure_count_reset_on_passive_transition() {- let registry = WorkerRegistry::new(&worker_urls(), no_cooldown_config());+ let registry = WorkerRegistry::new(&one_worker(), no_cooldown_config());- // One probe failure accumulates count=1.- {- let (_, health_lock) = ®istry.workers[0];- let mut health = health_lock.lock().unwrap();- health.consecutive_probe_failures = 1;- }+ registry+ .workers+ .get_mut(W1)+ .unwrap()+ .consecutive_probe_failures = 1;- // Passive signal drives Healthy → Degraded; try_transition must reset count.- registry.record_outcome(0, true);- registry.record_outcome(0, true);- registry.record_outcome(0, true);- assert_eq!(registry.state(0), WorkerState::Degraded);+ registry.record_outcome(W1, true);+ registry.record_outcome(W1, true);+ registry.record_outcome(W1, true);+ assert_eq!(registry.state(W1), WorkerState::Degraded);- let (_, health_lock) = ®istry.workers[0];- let health = health_lock.lock().unwrap();assert_eq!(- health.consecutive_probe_failures, 0,+ registry.workers.get(W1).unwrap().consecutive_probe_failures,+ 0,"try_transition must reset consecutive_probe_failures so the Degraded epoch needs a full probe_failure_threshold failures to reach Unhealthy");}@@ -681,16 +754,14 @@ mod tests {#[test]fn test_passive_window_capped_at_max_entries() {- let registry = WorkerRegistry::new(&worker_urls(), no_cooldown_config());+ let registry = WorkerRegistry::new(&one_worker(), no_cooldown_config());for _ in 0..PASSIVE_WINDOW_MAX_ENTRIES + 10 {- registry.record_outcome(0, false);+ registry.record_outcome(W1, false);}- let (_, health_lock) = ®istry.workers[0];- let health = health_lock.lock().unwrap();assert!(- health.passive_window.len() <= PASSIVE_WINDOW_MAX_ENTRIES,+ registry.workers.get(W1).unwrap().passive_window.len() <= PASSIVE_WINDOW_MAX_ENTRIES,"passive_window must not exceed PASSIVE_WINDOW_MAX_ENTRIES");}@@ -699,11 +770,10 @@ mod tests {#[test]fn test_transition_to_same_state_is_noop() {- let registry = WorkerRegistry::new(&worker_urls(), no_cooldown_config());- let (url, health_lock) = ®istry.workers[0];- let mut health = health_lock.lock().unwrap();+ let registry = WorkerRegistry::new(&one_worker(), no_cooldown_config());+ let mut health = registry.workers.get_mut(W1).unwrap();- let transitioned = health.try_transition(WorkerState::Healthy, Duration::ZERO, url);+ let transitioned = health.try_transition(WorkerState::Healthy, Duration::ZERO, W1);assert!(!transitioned);assert_eq!(health.state, WorkerState::Healthy);diff --git a/rust/ingestion-consumer/tests/dispatcher_integration_test.rs b/rust/ingestion-consumer/tests/dispatcher_integration_test.rsindex 82b01d85f800..808b69000ee0 100644--- a/rust/ingestion-consumer/tests/dispatcher_integration_test.rs+++ b/rust/ingestion-consumer/tests/dispatcher_integration_test.rs@@ -117,43 +117,43 @@ fn make_msg(token: &str, distinct_id: &str) -> SerializedKafkaMessage {}}-async fn wait_for_state(registry: &WorkerRegistry, worker_idx: usize, expected: WorkerState) {+async fn wait_for_state(registry: &WorkerRegistry, worker: &str, expected: WorkerState) {let deadline = tokio::time::Instant::now() + Duration::from_secs(3);loop {- if registry.state(worker_idx) == expected {+ if registry.state(worker) == expected {return;}assert!(tokio::time::Instant::now() < deadline,- "timed out waiting for worker {worker_idx} to become {expected:?}"+ "timed out waiting for worker {worker} to become {expected:?}");tokio::time::sleep(Duration::from_millis(5)).await;}}-async fn wait_for_dead(registry: &WorkerRegistry, worker_idx: usize) {+async fn wait_for_dead(registry: &WorkerRegistry, worker: &str) {let deadline = tokio::time::Instant::now() + Duration::from_secs(3);loop {- if registry.is_dead(worker_idx) {+ if registry.is_dead(worker) {return;}assert!(tokio::time::Instant::now() < deadline,- "timed out waiting for worker {worker_idx} to be declared dead"+ "timed out waiting for worker {worker} to be declared dead");tokio::time::sleep(Duration::from_millis(5)).await;}}-async fn wait_for_not_unhealthy(registry: &WorkerRegistry, worker_idx: usize) {+async fn wait_for_not_unhealthy(registry: &WorkerRegistry, worker: &str) {let deadline = tokio::time::Instant::now() + Duration::from_secs(3);loop {- if registry.state(worker_idx) != WorkerState::Unhealthy {+ if registry.state(worker) != WorkerState::Unhealthy {return;}assert!(tokio::time::Instant::now() < deadline,- "timed out waiting for worker {worker_idx} to leave Unhealthy"+ "timed out waiting for worker {worker} to leave Unhealthy");tokio::time::sleep(Duration::from_millis(5)).await;}@@ -176,7 +176,7 @@ async fn test_new_keys_skip_unhealthy_worker() {Arc::clone(®istry).start_probing(token.clone());w1.set_healthy(false);- wait_for_state(®istry, 1, WorkerState::Unhealthy).await;+ wait_for_state(®istry, &w1.url, WorkerState::Unhealthy).await;let keys: Vec<_> = (0..10).map(|i| make_msg("t", &format!("user-{i}")))@@ -184,9 +184,12 @@ async fn test_new_keys_skip_unhealthy_worker() {let sub_batches = dispatcher.assign(keys);assert!(- sub_batches.iter().all(|b| b.worker_idx == 0),+ sub_batches.iter().all(|b| b.worker.as_ref() == w0.url),"all assignments should go to w0; workers used: {:?}",- sub_batches.iter().map(|b| b.worker_idx).collect::<Vec<_>>()+ sub_batches+ .iter()+ .map(|b| b.worker.to_string())+ .collect::<Vec<_>>());token.cancel();@@ -210,26 +213,31 @@ async fn test_pinned_key_rerouted_after_dead_declaration() {// open (don't call on_sub_batch_resolved) so the pin stays alive.let b1 = dispatcher.assign(vec![make_msg("t", "user-1")]);assert_eq!(b1.len(), 1);- let pinned_to = b1[0].worker_idx;- let other = 1 - pinned_to;+ let pinned_to = b1[0].worker.clone();+ let other = if pinned_to.as_ref() == w0.url {+ w1.url.clone()+ } else {+ w0.url.clone()+ };// Kill the pinned worker's health endpoint.- if pinned_to == 0 {+ if pinned_to.as_ref() == w0.url {w0.set_healthy(false);} else {w1.set_healthy(false);}// Wait for Unhealthy then dead declaration.- wait_for_state(®istry, pinned_to, WorkerState::Unhealthy).await;- wait_for_dead(®istry, pinned_to).await;+ wait_for_state(®istry, &pinned_to, WorkerState::Unhealthy).await;+ wait_for_dead(®istry, &pinned_to).await;// Next assign: the stale pin is evicted and the key re-routes to the live worker.let b2 = dispatcher.assign(vec![make_msg("t", "user-1")]);assert_eq!(b2.len(), 1, "expected exactly one sub-batch");assert_eq!(- b2[0].worker_idx, other,- "user-1 should reroute to w{other} after w{pinned_to} is dead"+ b2[0].worker.as_ref(),+ other,+ "user-1 should reroute to the live worker after {pinned_to} is dead");token.cancel();@@ -253,13 +261,13 @@ async fn test_worker_recovery_detected_by_probe() {let token = CancellationToken::new();Arc::clone(®istry).start_probing(token.clone());- wait_for_state(®istry, 1, WorkerState::Unhealthy).await;+ wait_for_state(®istry, &w1.url, WorkerState::Unhealthy).await;// Recover w1.w1.set_healthy(true);// Wait until w1 leaves Unhealthy (Degraded or Healthy).- wait_for_not_unhealthy(®istry, 1).await;+ wait_for_not_unhealthy(®istry, &w1.url).await;// Assign a large set of fresh keys. Both workers should get some, since w1// is now at least Degraded (Healthy | Degraded both receive assignments).@@ -268,10 +276,10 @@ async fn test_worker_recovery_detected_by_probe() {.collect();let sub_batches = dispatcher.assign(keys);- let workers_used: std::collections::HashSet<usize> =- sub_batches.iter().map(|b| b.worker_idx).collect();+ let workers_used: std::collections::HashSet<String> =+ sub_batches.iter().map(|b| b.worker.to_string()).collect();assert!(- workers_used.contains(&1),+ workers_used.contains(&w1.url),"w1 should receive new keys after recovery; workers used: {workers_used:?}");@@ -307,23 +315,23 @@ async fn test_three_workers_one_dies_and_load_rebalances() {3,"3 keys across 3 workers must yield 3 sub-batches");- let workers_covered: std::collections::HashSet<usize> =- first.iter().map(|b| b.worker_idx).collect();+ let workers_covered: std::collections::HashSet<String> =+ first.iter().map(|b| b.worker.to_string()).collect();assert_eq!(workers_covered.len(), 3, "all 3 workers must receive a pin");// Remember which routing key was pinned to w1 — we'll re-assign it later// to verify it migrates to a live worker.let w1_key = first.iter()- .find(|b| b.worker_idx == 1)+ .find(|b| b.worker.as_ref() == w1.url).unwrap().routing_keys[0].clone();// Kill w1 and wait for dead declaration (first batch stays open throughout).w1.set_healthy(false);- wait_for_state(®istry, 1, WorkerState::Unhealthy).await;- wait_for_dead(®istry, 1).await;+ wait_for_state(®istry, &w1.url, WorkerState::Unhealthy).await;+ wait_for_dead(®istry, &w1.url).await;// Fresh keys must only land on w0 or w2.let fresh = dispatcher.assign(vec![@@ -332,9 +340,12 @@ async fn test_three_workers_one_dies_and_load_rebalances() {make_msg("t", "new-3"),]);assert!(- fresh.iter().all(|b| b.worker_idx != 1),+ fresh.iter().all(|b| b.worker.as_ref() != w1.url),"fresh keys must not route to dead w1; workers used: {:?}",- fresh.iter().map(|b| b.worker_idx).collect::<Vec<_>>()+ fresh+ .iter()+ .map(|b| b.worker.to_string())+ .collect::<Vec<_>>());// The key that was pinned to w1 must re-route to w0 or w2 on its next assign.@@ -347,7 +358,8 @@ async fn test_three_workers_one_dies_and_load_rebalances() {"rerouted key must produce exactly one sub-batch");assert_ne!(- rerouted[0].worker_idx, 1,+ rerouted[0].worker.as_ref(),+ w1.url,"key previously pinned to w1 must reroute to a live worker, not w1");@@ -371,8 +383,8 @@ async fn test_all_workers_unhealthy_returns_empty() {let token = CancellationToken::new();Arc::clone(®istry).start_probing(token.clone());- wait_for_state(®istry, 0, WorkerState::Unhealthy).await;- wait_for_state(®istry, 1, WorkerState::Unhealthy).await;+ wait_for_state(®istry, &w0.url, WorkerState::Unhealthy).await;+ wait_for_state(®istry, &w1.url, WorkerState::Unhealthy).await;let sub_batches = dispatcher.assign(vec![make_msg("t", "user-1")]);assert!(diff --git a/rust/ingestion-consumer/tests/transport_integration_test.rs b/rust/ingestion-consumer/tests/transport_integration_test.rsindex b27d73d422d6..05a4277b6f97 100644--- a/rust/ingestion-consumer/tests/transport_integration_test.rs+++ b/rust/ingestion-consumer/tests/transport_integration_test.rs@@ -316,23 +316,22 @@ async fn transport_fails_on_unreachable_worker() {}#[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);+async fn transport_lazily_creates_semaphore_for_unseeded_worker() {+ // Dynamic membership: a worker not seeded at construction (discovered at+ // runtime) gets a semaphore created on first send and is served normally.+ let received = Arc::new(Mutex::new(Vec::new()));+ let (url, _handle) = start_mock_worker(received.clone()).await;++ // Construct with an empty worker set — the target is "unknown" at build time.+ let transport = HttpTransport::new(Duration::from_secs(5), 0, None, &[], 1);let messages = vec![make_message("tok", "user", 0, "{}")];- let err = transport- .send_batch("http://unknown-worker:9999", "batch-x", messages)+ let accepted = transport+ .send_batch(&url, "batch-lazy", messages).await- .unwrap_err();+ .expect("send to an unseeded worker should succeed via lazy semaphore creation");- assert!(- matches!(err, TransportError::UnknownWorker(_)),- "expected UnknownWorker, got {err:?}"- );+ assert_eq!(accepted, 1);}#[tokio::test]@@ -475,17 +474,16 @@ async fn dispatcher_and_transport_end_to_end() {let mut handles = Vec::new();for sub_batch in sub_batches {let t = transport.clone();- let url = worker_urls[sub_batch.worker_idx].clone();+ let worker = sub_batch.worker.clone();let routing_keys = sub_batch.routing_keys.clone();- let worker_idx = sub_batch.worker_idx;let message_count = sub_batch.messages.len();let d = Arc::clone(&dispatcher);handles.push(tokio::spawn(async move {let result = t- .send_batch(&url, "batch-e2e", sub_batch.messages)+ .send_batch(&worker, "batch-e2e", sub_batch.messages).await.unwrap();- d.on_sub_batch_resolved(worker_idx, message_count, &routing_keys);+ d.on_sub_batch_resolved(&worker, message_count, &routing_keys);result}));}