Skip to content

: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.

feat(ingestion-consumer): deterministic aperture routing strategy (#71939)

José Sequeira7425af5e7887
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index f270dedef2c6..b63398b224f8 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -5306,7 +5306,7 @@ dependencies = [
"dashmap 6.1.0",
"envconfig",
"futures",
- "k8s-openapi",
+ "k8s-awareness",
"kube",
"lifecycle",
"metrics",
@@ -5714,6 +5714,7 @@ dependencies = [
"http 1.4.0",
"k8s-openapi",
"kube",
+ "metrics",
"rstest",
"serde",
"serde_json",
@@ -7638,7 +7639,6 @@ dependencies = [
"http-body 1.0.1",
"http-body-util",
"k8s-awareness",
- "k8s-openapi",
"kube",
"lifecycle",
"metrics",
diff --git a/rust/common/k8s-awareness/Cargo.toml b/rust/common/k8s-awareness/Cargo.toml
index bd28d29ca910..80308cbc20d6 100644
--- a/rust/common/k8s-awareness/Cargo.toml
+++ b/rust/common/k8s-awareness/Cargo.toml
@@ -8,6 +8,7 @@ publish = false
k8s-openapi = { version = "0.24", features = ["latest"] }
kube = { version = "0.98", features = ["runtime", "client"] }
futures = { workspace = true }
+metrics = { workspace = true }
serde = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true }
diff --git a/rust/common/k8s-awareness/src/endpoints.rs b/rust/common/k8s-awareness/src/endpoints.rs
new file mode 100644
index 000000000000..852f4af7db25
--- /dev/null
+++ b/rust/common/k8s-awareness/src/endpoints.rs
@@ -0,0 +1,299 @@
+//! Service-membership watching via EndpointSlices.
+//!
+//! Watches the EndpointSlices of one Service and publishes the set of ready
+//! endpoint IPs on a `tokio::sync::watch` channel whenever membership changes.
+//! This is the single shared implementation of a pattern that previously lived
+//! as diverging copies in personhog-router and ingestion-consumer; consumers
+//! subscribe and map IPs onto whatever they balance over (worker URLs, tonic
+//! endpoints, peer rings).
+//!
+//! Semantics:
+//! - An endpoint counts as ready when `conditions.ready` is true or absent
+//! (the K8s spec treats a nil ready field as "assume ready"); unready
+//! endpoints and unparseable addresses are skipped.
+//! - State is aggregated per slice, so one slice changing doesn't clobber
+//! addresses contributed by another.
+//! - On a watcher re-list (`Init`), the last published set keeps serving until
+//! `InitDone`, so subscribers never observe a transient empty set.
+//! - When the watch stream ends, the watcher re-lists after a short backoff
+//! instead of dying — a frozen membership set is worse than a stale one.
+
+use std::collections::{HashMap, HashSet};
+use std::net::IpAddr;
+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;
+use tokio::sync::watch;
+use tokio::task::JoinHandle;
+use tokio_util::sync::CancellationToken;
+use tracing::{info, warn};
+
+/// 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);
+
+/// Watch `service_name`'s EndpointSlices in `namespace`, publishing the ready
+/// endpoint IPs on every membership change until `cancel` fires.
+///
+/// The receiver's initial value is the empty set, meaning "not yet known":
+/// subscribers driven by `changed()` only observe real publishes, so they
+/// never act on the placeholder.
+pub fn watch_service_members(
+ client: Client,
+ namespace: String,
+ service_name: String,
+ cancel: CancellationToken,
+) -> (watch::Receiver<HashSet<IpAddr>>, JoinHandle<()>) {
+ let (tx, rx) = watch::channel(HashSet::new());
+ let handle = tokio::spawn(async move {
+ run(client, namespace, service_name, tx, cancel).await;
+ });
+ (rx, handle)
+}
+
+async fn run(
+ client: Client,
+ namespace: String,
+ service_name: String,
+ tx: watch::Sender<HashSet<IpAddr>>,
+ cancel: CancellationToken,
+) {
+ let api: Api<EndpointSlice> = Api::namespaced(client, &namespace);
+ let label_selector = format!("kubernetes.io/service-name={service_name}");
+ let service_label: Arc<str> = Arc::from(service_name.as_str());
+
+ info!(
+ service = %service_name,
+ namespace = %namespace,
+ "starting EndpointSlice membership watch"
+ );
+
+ // Ready addresses per slice name. Kept across watcher restarts: a fresh
+ // watcher re-lists from `Init`, which clears and repopulates it.
+ let mut slices: HashMap<String, HashSet<IpAddr>> = 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 membership 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!(service = %service_name, "EndpointSlice membership watch cancelled");
+ return;
+ }
+ item = stream.next() => {
+ match item {
+ Some(Ok(event)) => {
+ if let Some(desired) = apply_event(event, &mut slices) {
+ // Don't wake subscribers for no-op reconciles.
+ tx.send_if_modified(|current| {
+ if *current == desired {
+ false
+ } else {
+ *current = desired;
+ true
+ }
+ });
+ }
+ }
+ Some(Err(e)) => {
+ warn!(error = %e, service = %service_name, "EndpointSlice watcher error, stream will retry");
+ counter!(
+ "k8s_awareness_endpoint_watch_errors_total",
+ "service" => Arc::clone(&service_label),
+ )
+ .increment(1);
+ }
+ None => {
+ warn!(service = %service_name, "EndpointSlice watcher stream ended, restarting");
+ counter!(
+ "k8s_awareness_endpoint_watch_restarts_total",
+ "service" => Arc::clone(&service_label),
+ )
+ .increment(1);
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ tokio::select! {
+ _ = cancel.cancelled() => {
+ info!(service = %service_name, "EndpointSlice membership watch cancelled");
+ return;
+ }
+ _ = tokio::time::sleep(WATCHER_RESTART_BACKOFF) => {}
+ }
+ }
+}
+
+/// Parse an EndpointSlice into the set of ready endpoint IPs.
+fn extract_ready_ips(slice: &EndpointSlice) -> HashSet<IpAddr> {
+ 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(ip);
+ }
+ }
+ }
+ addrs
+}
+
+fn slice_key(slice: &EndpointSlice) -> String {
+ slice
+ .metadata
+ .name
+ .clone()
+ .or_else(|| slice.metadata.uid.clone())
+ .unwrap_or_else(|| "unknown".to_string())
+}
+
+/// Apply a watch event to the per-slice state, returning the desired member
+/// set to publish — or `None` when no update is due (the `Init` re-list start,
+/// where the last published set keeps serving until `InitDone`).
+fn apply_event(
+ event: Event<EndpointSlice>,
+ slices: &mut HashMap<String, HashSet<IpAddr>>,
+) -> Option<HashSet<IpAddr>> {
+ match event {
+ Event::Apply(slice) | Event::InitApply(slice) => {
+ slices.insert(slice_key(&slice), extract_ready_ips(&slice));
+ }
+ Event::Delete(slice) => {
+ slices.remove(&slice_key(&slice));
+ }
+ Event::Init => {
+ slices.clear();
+ return None;
+ }
+ Event::InitDone => {}
+ }
+
+ Some(slices.values().flatten().copied().collect())
+}
+
+#[cfg(test)]
+mod tests {
+ use k8s_openapi::api::discovery::v1::{Endpoint as K8sEndpoint, EndpointConditions};
+ use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta;
+
+ use super::*;
+
+ fn ip(s: &str) -> IpAddr {
+ s.parse().unwrap()
+ }
+
+ 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,
+ }
+ }
+
+ #[test]
+ fn test_extract_ready_ips_ready_semantics() {
+ // ready=true and absent conditions are in; ready=false and garbage
+ // addresses are out. Conditions present with nil ready also count as
+ // ready, per the K8s spec.
+ 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),
+ endpoint(&["not-an-ip"], Some(true)),
+ K8sEndpoint {
+ addresses: vec!["10.0.0.4".to_string()],
+ conditions: Some(EndpointConditions::default()),
+ ..Default::default()
+ },
+ ],
+ );
+ assert_eq!(
+ extract_ready_ips(&s),
+ HashSet::from([ip("10.0.0.1"), ip("10.0.0.3"), ip("10.0.0.4")])
+ );
+ }
+
+ #[test]
+ fn test_apply_event_aggregates_across_slices() {
+ let mut slices = HashMap::new();
+
+ let desired = apply_event(
+ Event::Apply(slice("s1", vec![endpoint(&["10.0.0.1"], Some(true))])),
+ &mut slices,
+ )
+ .unwrap();
+ assert_eq!(desired, HashSet::from([ip("10.0.0.1")]));
+
+ let desired = apply_event(
+ Event::Apply(slice("s2", vec![endpoint(&["10.0.0.2"], Some(true))])),
+ &mut slices,
+ )
+ .unwrap();
+ assert_eq!(desired, HashSet::from([ip("10.0.0.1"), ip("10.0.0.2")]));
+
+ // Deleting one slice must not clobber the other slice's addresses.
+ let desired = apply_event(Event::Delete(slice("s1", vec![])), &mut slices).unwrap();
+ assert_eq!(desired, HashSet::from([ip("10.0.0.2")]));
+ }
+
+ #[test]
+ fn test_apply_event_relist_keeps_serving_until_init_done() {
+ let mut slices = HashMap::new();
+ apply_event(
+ Event::Apply(slice("s1", vec![endpoint(&["10.0.0.1"], Some(true))])),
+ &mut slices,
+ );
+
+ // Init returns None — the last published set keeps serving through the
+ // re-list, so subscribers never observe a transient empty set.
+ assert!(apply_event(Event::Init, &mut slices).is_none());
+ assert!(slices.is_empty());
+
+ // Re-list finds a different pod; InitDone applies the new set.
+ apply_event(
+ Event::InitApply(slice("s1", vec![endpoint(&["10.0.0.9"], Some(true))])),
+ &mut slices,
+ );
+ let desired = apply_event(Event::InitDone, &mut slices).unwrap();
+ assert_eq!(desired, HashSet::from([ip("10.0.0.9")]));
+ }
+}
diff --git a/rust/common/k8s-awareness/src/lib.rs b/rust/common/k8s-awareness/src/lib.rs
index 5c2b34a4e70d..3346e5af570f 100644
--- a/rust/common/k8s-awareness/src/lib.rs
+++ b/rust/common/k8s-awareness/src/lib.rs
@@ -1,5 +1,7 @@
mod detection;
mod discovery;
+mod endpoints;
+mod peers;
pub mod types;
mod watcher;
@@ -7,5 +9,7 @@ pub use detection::classify_departure;
pub use discovery::{
discover_controller, get_pod, list_pods_by_selector, DiscoveredPod, DiscoveryError,
};
+pub use endpoints::watch_service_members;
+pub use peers::{PeerSet, PeerTracker};
pub use types::{ClusterIntent, ControllerKind, ControllerRef, DepartureReason, PodInfo};
pub use watcher::{K8sAwareness, K8sAwarenessError};
diff --git a/rust/common/k8s-awareness/src/peers.rs b/rust/common/k8s-awareness/src/peers.rs
new file mode 100644
index 000000000000..96ab390830b9
--- /dev/null
+++ b/rust/common/k8s-awareness/src/peers.rs
@@ -0,0 +1,194 @@
+//! Peer awareness: the ready members of a pod's own Service, in a canonical
+//! order every replica agrees on, plus this pod's position among them.
+//!
+//! A thin consumer of [`crate::watch_service_members`]: each replica follows
+//! its own Service's membership and maintains a [`PeerSet`] snapshot — the
+//! sorted ready peer IPs and this pod's index within them (located via its own
+//! pod IP). Because every replica sees the same EndpointSlices and applies the
+//! same ordering, `(self_index, peer_count)` is a coordination-free agreement,
+//! usable for deterministic subsetting, ring slicing, or any scheme where
+//! replicas must partition work without talking to each other.
+//!
+//! Snapshots are read from hot paths, so they sit behind an `Arc` swap in a
+//! `std::sync::RwLock`: readers clone an `Arc` and never block on the watcher.
+
+use std::collections::HashSet;
+use std::net::IpAddr;
+use std::sync::{Arc, RwLock};
+
+use kube::Client;
+use metrics::gauge;
+use tokio::sync::watch;
+use tokio::task::JoinHandle;
+use tokio_util::sync::CancellationToken;
+
+/// Point-in-time view of a Service's ready members.
+#[derive(Debug, Clone, PartialEq, Eq, Default)]
+pub struct PeerSet {
+ /// Ready peer pod IPs, sorted — the canonical order all replicas agree on.
+ pub peers: Vec<IpAddr>,
+ /// This pod's position in `peers`. `None` until this pod is itself a ready
+ /// endpoint (e.g. during startup, or while failing readiness probes).
+ pub self_index: Option<usize>,
+}
+
+impl PeerSet {
+ pub fn peer_count(&self) -> usize {
+ self.peers.len()
+ }
+}
+
+/// Tracks the ready members of one Service. Construct with the pod's own IP,
+/// then drive it from the shared membership watch via [`PeerTracker::watch`],
+/// or apply membership directly with [`PeerTracker::set_peers`] (tests,
+/// non-K8s setups).
+pub struct PeerTracker {
+ self_ip: IpAddr,
+ current: RwLock<Arc<PeerSet>>,
+}
+
+impl PeerTracker {
+ pub fn new(self_ip: IpAddr) -> Arc<Self> {
+ Arc::new(Self {
+ self_ip,
+ current: RwLock::new(Arc::new(PeerSet::default())),
+ })
+ }
+
+ /// The current peer set. Cheap (one `Arc` clone); safe on hot paths.
+ pub fn snapshot(&self) -> Arc<PeerSet> {
+ Arc::clone(&self.current.read().unwrap())
+ }
+
+ /// Replace the peer membership with `addrs`, recomputing order and self
+ /// index.
+ pub fn set_peers(&self, addrs: &HashSet<IpAddr>) {
+ let mut peers: Vec<IpAddr> = addrs.iter().copied().collect();
+ peers.sort_unstable();
+ let self_index = peers.iter().position(|ip| *ip == self.self_ip);
+ *self.current.write().unwrap() = Arc::new(PeerSet { peers, self_index });
+ }
+
+ /// Watch `service_name`'s EndpointSlices in `namespace` and keep this
+ /// tracker in sync until `cancel` fires.
+ pub fn watch(
+ self: &Arc<Self>,
+ client: Client,
+ namespace: String,
+ service_name: String,
+ cancel: CancellationToken,
+ ) -> JoinHandle<()> {
+ let (members, _watch_task) =
+ crate::watch_service_members(client, namespace, service_name.clone(), cancel.clone());
+ self.follow(members, service_name, cancel)
+ }
+
+ /// Apply every update from a membership receiver until `cancel` fires or
+ /// the sender goes away. Split from [`PeerTracker::watch`] so tests can
+ /// drive the loop with a plain channel.
+ pub fn follow(
+ self: &Arc<Self>,
+ mut members: watch::Receiver<HashSet<IpAddr>>,
+ service_name: String,
+ cancel: CancellationToken,
+ ) -> JoinHandle<()> {
+ let tracker = Arc::clone(self);
+ tokio::spawn(async move {
+ let service_label: Arc<str> = Arc::from(service_name.as_str());
+ loop {
+ tokio::select! {
+ _ = cancel.cancelled() => return,
+ changed = members.changed() => {
+ if changed.is_err() {
+ return;
+ }
+ let addrs = members.borrow_and_update().clone();
+ tracker.set_peers(&addrs);
+ let set = tracker.snapshot();
+ gauge!(
+ "k8s_awareness_peer_count",
+ "service" => Arc::clone(&service_label),
+ )
+ .set(set.peer_count() as f64);
+ // -1 means "self not (yet) a ready member".
+ gauge!(
+ "k8s_awareness_peer_index",
+ "service" => Arc::clone(&service_label),
+ )
+ .set(set.self_index.map_or(-1.0, |i| i as f64));
+ }
+ }
+ }
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use tokio::sync::watch as tokio_watch;
+
+ use super::*;
+
+ fn ip(s: &str) -> IpAddr {
+ s.parse().unwrap()
+ }
+
+ #[test]
+ fn test_set_peers_sorts_canonically_and_locates_self() {
+ // Insertion order must not matter: two replicas fed the same set in a
+ // different order have to agree on every peer's index.
+ let tracker = PeerTracker::new(ip("10.0.0.5"));
+ tracker.set_peers(&HashSet::from([
+ ip("10.0.0.9"),
+ ip("10.0.0.5"),
+ ip("10.0.0.1"),
+ ]));
+
+ let set = tracker.snapshot();
+ assert_eq!(
+ set.peers,
+ vec![ip("10.0.0.1"), ip("10.0.0.5"), ip("10.0.0.9")]
+ );
+ assert_eq!(set.self_index, Some(1));
+ assert_eq!(set.peer_count(), 3);
+ }
+
+ #[test]
+ fn test_self_index_none_until_self_is_ready() {
+ let tracker = PeerTracker::new(ip("10.0.0.5"));
+ tracker.set_peers(&HashSet::from([ip("10.0.0.1"), ip("10.0.0.9")]));
+ assert_eq!(tracker.snapshot().self_index, None);
+
+ // Self becomes a ready endpoint → gains an index.
+ tracker.set_peers(&HashSet::from([
+ ip("10.0.0.1"),
+ ip("10.0.0.9"),
+ ip("10.0.0.5"),
+ ]));
+ assert_eq!(tracker.snapshot().self_index, Some(1));
+ }
+
+ #[tokio::test]
+ async fn test_follow_applies_membership_updates() {
+ let tracker = PeerTracker::new(ip("10.0.0.2"));
+ let (tx, rx) = tokio_watch::channel(HashSet::new());
+ let cancel = CancellationToken::new();
+ let handle = tracker.follow(rx, "svc".to_string(), cancel.clone());
+
+ tx.send(HashSet::from([ip("10.0.0.2"), ip("10.0.0.1")]))
+ .unwrap();
+ // The follower runs on the runtime; wait for the update to land.
+ for _ in 0..100 {
+ if tracker.snapshot().peer_count() == 2 {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(5)).await;
+ }
+ let set = tracker.snapshot();
+ assert_eq!(set.peers, vec![ip("10.0.0.1"), ip("10.0.0.2")]);
+ assert_eq!(set.self_index, Some(1));
+
+ cancel.cancel();
+ handle.await.unwrap();
+ }
+}
diff --git a/rust/ingestion-consumer/Cargo.toml b/rust/ingestion-consumer/Cargo.toml
index a008e7c0490b..3ddff3252208 100644
--- a/rust/ingestion-consumer/Cargo.toml
+++ b/rust/ingestion-consumer/Cargo.toml
@@ -11,7 +11,7 @@ common-alloc = { path = "../common/alloc" }
dashmap = { workspace = true }
envconfig = { workspace = true }
futures = { workspace = true }
-k8s-openapi = { version = "0.24", features = ["latest"] }
+k8s-awareness = { path = "../common/k8s-awareness" }
kube = { version = "0.98", features = ["client", "runtime"] }
lifecycle = { path = "../common/lifecycle" }
metrics = { workspace = true }
diff --git a/rust/ingestion-consumer/src/aperture.rs b/rust/ingestion-consumer/src/aperture.rs
new file mode 100644
index 000000000000..ce651e0d91c6
--- /dev/null
+++ b/rust/ingestion-consumer/src/aperture.rs
@@ -0,0 +1,194 @@
+//! Deterministic aperture: ring-slice candidate selection.
+//!
+//! Every dispatcher sorts the full worker set into the same ring, takes the
+//! slice starting at `peer_index * ring_len / peer_count`, and routes its
+//! unpinned groups only within that slice (via the configured selection
+//! strategy). Because peers agree on both the ring order (same EndpointSlices,
+//! same sort) and their own indices ([`k8s_awareness::PeerTracker`]), the
+//! slices tile the ring without any coordination — each dispatcher talks to
+//! a handful of workers instead of the whole pool, which is what keeps
+//! sub-batches consolidated. Modeled on Finagle's deterministic aperture.
+//!
+//! The configured width is a *minimum*: it's floored at
+//! `ceil(ring_len / peer_count)` — the narrowest equal slices that can cover
+//! the ring — so the union of the fleet's slices covers every worker even
+//! when workers outnumber `width x dispatchers`. Every peer computes the same
+//! floor from the same inputs, so the property stays coordination-free.
+//!
+//! Unroutable ring positions (unhealthy or draining workers) are skipped and
+//! the slice extends further around the ring, so the *effective* width holds
+//! under partial failure.
+
+use std::collections::HashSet;
+
+use crate::worker_registry::WorkerId;
+
+/// The candidate workers for one assignment round: walk the ring from this
+/// dispatcher's slice start, collecting healthy workers until the effective
+/// width (`width` floored at `ceil(ring_len / peer_count)` for coverage) is
+/// reached or the ring is exhausted. `ring` is the canonically sorted full
+/// worker set; `healthy` the subset this dispatcher may route to.
+///
+/// Returns `None` (caller falls back to the full healthy pool) when the
+/// slice can't be computed: no peers known yet, an out-of-range index, or an
+/// empty ring.
+pub fn ring_slice(
+ ring: &[WorkerId],
+ healthy: &[WorkerId],
+ peer_index: Option<usize>,
+ peer_count: usize,
+ width: usize,
+) -> Option<Vec<WorkerId>> {
+ let index = peer_index?;
+ if ring.is_empty() || peer_count == 0 || index >= peer_count || width == 0 {
+ return None;
+ }
+
+ // Coverage floor: consecutive slice starts are at most `ceil(len/peers)`
+ // apart, so any narrower width would leave ring positions no dispatcher
+ // ever routes fresh keys to. Flooring the width there guarantees the
+ // union of the fleet's slices covers the whole ring for any pool/peer
+ // ratio, at the cost of slight slice overlap when the division is uneven.
+ let width = width.max(ring.len().div_ceil(peer_count));
+
+ let healthy_set: HashSet<&WorkerId> = healthy.iter().collect();
+ let start = index * ring.len() / peer_count;
+
+ let mut candidates = Vec::with_capacity(width.min(ring.len()));
+ for offset in 0..ring.len() {
+ let worker = &ring[(start + offset) % ring.len()];
+ if healthy_set.contains(worker) {
+ candidates.push(worker.clone());
+ if candidates.len() == width {
+ break;
+ }
+ }
+ }
+
+ if candidates.is_empty() {
+ return None;
+ }
+ Some(candidates)
+}
+
+/// The canonical worker ring: the full registered set, sorted. All dispatchers
+/// see the same EndpointSlices, so sorting gives them the same ring.
+pub fn sorted_ring(mut workers: Vec<WorkerId>) -> Vec<WorkerId> {
+ workers.sort_unstable();
+ workers
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn wid(n: usize) -> WorkerId {
+ WorkerId::from(format!("http://10.0.0.{n}:6738").as_str())
+ }
+
+ fn ring(n: usize) -> Vec<WorkerId> {
+ sorted_ring((1..=n).map(wid).collect())
+ }
+
+ #[test]
+ fn test_slices_tile_the_ring_across_peers() {
+ // 3 peers x width 2 over 6 workers: each peer gets a distinct pair and
+ // the union covers the whole ring — the coordination-free guarantee
+ // the whole design rests on.
+ let ring = ring(6);
+ let mut seen = Vec::new();
+ for index in 0..3 {
+ let slice = ring_slice(&ring, &ring, Some(index), 3, 2).unwrap();
+ assert_eq!(slice.len(), 2, "peer {index}");
+ seen.extend(slice);
+ }
+ let mut sorted = seen.clone();
+ sorted.sort_unstable();
+ sorted.dedup();
+ assert_eq!(sorted.len(), 6, "slices must tile the ring without overlap");
+ }
+
+ #[test]
+ fn test_width_floored_so_slices_cover_an_oversized_ring() {
+ // 2 peers x configured width 3 over 8 workers: unfloored slices would
+ // be spaced 4 apart and leave positions 3 and 7 with zero unpinned
+ // traffic. The ceil(8/2)=4 floor widens each slice just enough that
+ // the union covers the whole ring.
+ let ring = ring(8);
+ let mut seen = HashSet::new();
+ for index in 0..2 {
+ let slice = ring_slice(&ring, &ring, Some(index), 2, 3).unwrap();
+ assert_eq!(slice.len(), 4, "peer {index} floored to ceil(8/2)");
+ seen.extend(slice);
+ }
+ assert_eq!(seen.len(), 8, "every ring position must be covered");
+ }
+
+ #[test]
+ fn test_width_floor_overlaps_slices_on_uneven_division() {
+ // 3 peers over 7 workers: starts 0, 2, 4 with floor ceil(7/3)=3 give
+ // slices {0,1,2}, {2,3,4}, {4,5,6} — full coverage, with boundary
+ // positions shared by two peers rather than left uncovered.
+ let ring = ring(7);
+ let mut seen = HashSet::new();
+ for index in 0..3 {
+ seen.extend(ring_slice(&ring, &ring, Some(index), 3, 1).unwrap());
+ }
+ assert_eq!(seen.len(), 7, "uneven division must still cover the ring");
+ }
+
+ #[test]
+ fn test_slice_wraps_around_the_ring() {
+ // Last peer's slice starts near the ring end and wraps to the front.
+ let ring = ring(5);
+ let slice = ring_slice(&ring, &ring, Some(2), 3, 3).unwrap();
+ // start = 2 * 5 / 3 = 3 → positions 3, 4, 0.
+ assert_eq!(
+ slice,
+ vec![ring[3].clone(), ring[4].clone(), ring[0].clone()]
+ );
+ }
+
+ #[test]
+ fn test_slice_extends_past_unhealthy_workers() {
+ // An unroutable worker inside the slice must not shrink the effective
+ // width — the slice walks on around the ring.
+ let ring = ring(6);
+ let healthy: Vec<WorkerId> = ring.iter().filter(|w| **w != ring[1]).cloned().collect();
+ let slice = ring_slice(&ring, &healthy, Some(0), 3, 2).unwrap();
+ assert_eq!(slice, vec![ring[0].clone(), ring[2].clone()]);
+ }
+
+ #[test]
+ fn test_width_capped_by_healthy_pool() {
+ let ring = ring(3);
+ let slice = ring_slice(&ring, &ring, Some(0), 1, 10).unwrap();
+ assert_eq!(
+ slice.len(),
+ 3,
+ "width beyond the pool returns every healthy worker"
+ );
+ }
+
+ #[test]
+ fn test_fallback_cases_return_none() {
+ let ring = ring(4);
+ assert!(
+ ring_slice(&ring, &ring, None, 3, 2).is_none(),
+ "self not ready yet"
+ );
+ assert!(
+ ring_slice(&ring, &ring, Some(3), 3, 2).is_none(),
+ "index out of range"
+ );
+ assert!(ring_slice(&[], &[], Some(0), 3, 2).is_none(), "empty ring");
+ assert!(
+ ring_slice(&ring, &[], Some(0), 3, 2).is_none(),
+ "nothing healthy"
+ );
+ assert!(
+ ring_slice(&ring, &ring, Some(0), 0, 2).is_none(),
+ "no peers"
+ );
+ }
+}
diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rs
index f38998086c6c..169b6563abe6 100644
--- a/rust/ingestion-consumer/src/config.rs
+++ b/rust/ingestion-consumer/src/config.rs
@@ -225,6 +225,29 @@ pub struct Config {
#[envconfig(from = "INGESTION_ROUTING_STRATEGY", default = "binpack")]
pub routing_strategy: RoutingStrategy,
+ /// Minimum aperture width for `INGESTION_ROUTING_STRATEGY=aperture`: how
+ /// many workers this dispatcher's ring slice spans. The effective width
+ /// is floored at `ceil(pool / dispatchers)` so the fleet's slices always
+ /// cover the whole pool, no matter the pool/dispatcher ratio. Small
+ /// values maximize sub-batch consolidation; the width becomes
+ /// feedback-driven in a later stage.
+ #[envconfig(from = "INGESTION_MIN_APERTURE", default = "3")]
+ pub min_aperture: usize,
+
+ // ---- Peer awareness ----
+ /// Kubernetes Service whose EndpointSlices list this consumer's own peer
+ /// pods. Enables coordination-free peer awareness (each pod's stable index
+ /// among its replicas), the basis for deterministic aperture routing.
+ /// Empty (default) disables it. The Service is looked up in the pod's own
+ /// namespace (`POD_NAMESPACE`).
+ #[envconfig(from = "PEER_SERVICE_NAME", default = "")]
+ pub peer_service_name: String,
+
+ /// This pod's IP from the downward API, used to locate self in the peer
+ /// Service's EndpointSlices. Required when PEER_SERVICE_NAME is set.
+ #[envconfig(from = "POD_IP")]
+ pub pod_ip: Option<String>,
+
// ---- Worker health / registry ----
/// How often to probe each worker's /_ready endpoint (milliseconds).
#[envconfig(default = "5000")]
diff --git a/rust/ingestion-consumer/src/debug_recorder.rs b/rust/ingestion-consumer/src/debug_recorder.rs
index eb41e4561637..dbf2e9973661 100644
--- a/rust/ingestion-consumer/src/debug_recorder.rs
+++ b/rust/ingestion-consumer/src/debug_recorder.rs
@@ -176,6 +176,11 @@ pub struct DebugState {
pub group_id: String,
pub workers: Vec<WorkerStatus>,
pub dispatcher: DispatcherLoad,
+ /// This pod's index among its ready peers; `None` while not yet ready or
+ /// when peer awareness is disabled.
+ pub peer_index: Option<usize>,
+ /// Ready peer count; `None` when peer awareness is disabled.
+ pub peer_count: Option<usize>,
pub events: Vec<DebugEvent>,
}
@@ -186,6 +191,10 @@ pub struct DebugLoad {
pub group_id: String,
pub workers: Vec<WorkerStatus>,
pub dispatcher: DispatcherLoad,
+ /// See [`DebugState::peer_index`].
+ pub peer_index: Option<usize>,
+ /// See [`DebugState::peer_count`].
+ pub peer_count: Option<usize>,
}
/// Bounded rolling event buffer plus a broadcast channel for live subscribers.
diff --git a/rust/ingestion-consumer/src/discovery.rs b/rust/ingestion-consumer/src/discovery.rs
index 7e6606ab7ab0..9a29c25c473b 100644
--- a/rust/ingestion-consumer/src/discovery.rs
+++ b/rust/ingestion-consumer/src/discovery.rs
@@ -5,38 +5,28 @@
//!
//! - [`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.
+//! - [`EndpointSliceDiscovery`] — subscribes to the shared EndpointSlice
+//! membership watch ([`k8s_awareness::watch_service_members`]) and keeps the
+//! registry in sync as worker pods join/leave (the separately-deployed pool).
//!
//! Routing stays client-side in the dispatcher; discovery only supplies the
//! member list. A departed worker is marked *draining* (it keeps finishing
//! in-flight work) rather than removed outright; the reaper in `main` removes it
//! from the registry and transport once it has drained or timed out.
-use std::collections::{HashMap, HashSet};
-use std::net::{IpAddr, SocketAddr};
+use std::collections::HashSet;
+use std::net::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 metrics::gauge;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tracing::{info, warn};
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 {
@@ -98,42 +88,10 @@ pub fn reconcile_membership(registry: &WorkerRegistry, desired: &HashSet<WorkerI
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>,
@@ -161,8 +119,8 @@ impl WorkerDiscovery for StaticDiscovery {
}
}
-/// Watches a Kubernetes Service's EndpointSlices and reconciles the registry as
-/// worker pods become ready / leave.
+/// Subscribes to the shared EndpointSlice membership watch for the worker
+/// Service and reconciles the registry as worker pods become ready / leave.
pub struct EndpointSliceDiscovery {
client: Client,
namespace: String,
@@ -181,9 +139,6 @@ impl EndpointSliceDiscovery {
}
async fn run(self, registry: Arc<WorkerRegistry>, 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,
@@ -191,90 +146,35 @@ impl EndpointSliceDiscovery {
"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();
+ let (mut members, _watch_task) = k8s_awareness::watch_service_members(
+ self.client,
+ self.namespace,
+ self.service_name,
+ cancel.clone(),
+ );
- // 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(&registry, &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;
+ changed = members.changed() => {
+ if changed.is_err() {
+ // The watch task only exits on cancellation, so a
+ // closed channel means shutdown is underway.
+ warn!("EndpointSlice membership watch closed");
+ return;
+ }
+ let desired: HashSet<WorkerId> = members
+ .borrow_and_update()
+ .iter()
+ .map(|ip| addr_to_worker(SocketAddr::new(*ip, self.port)))
+ .collect();
+ reconcile_membership(&registry, &desired);
+ }
}
- Event::InitDone => {}
}
-
- Some(
- slices
- .values()
- .flatten()
- .copied()
- .map(addr_to_worker)
- .collect(),
- )
}
}
@@ -295,9 +195,6 @@ impl WorkerDiscovery for EndpointSliceDiscovery {
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;
@@ -317,133 +214,12 @@ mod tests {
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 ----
+ // ---- reconcile_membership ----
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(
&[],
diff --git a/rust/ingestion-consumer/src/dispatcher.rs b/rust/ingestion-consumer/src/dispatcher.rs
index be9d39059023..5d34a49bf789 100644
--- a/rust/ingestion-consumer/src/dispatcher.rs
+++ b/rust/ingestion-consumer/src/dispatcher.rs
@@ -1,8 +1,10 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
+use k8s_awareness::PeerTracker;
use metrics::{counter, gauge, histogram};
+use crate::aperture;
use crate::debug_recorder::{
record_if, DebugEventKind, DebugRecorder, DispatcherLoad, LoadEntry, SubBatchInfo,
};
@@ -185,6 +187,10 @@ pub struct Dispatcher {
/// order: pin_table → sentinel; the sentinel never takes the pin table),
/// so its check order matches the intended per-key send order.
key_sentinel: Arc<KeyOrderSentinel>,
+ /// Peer tracker + aperture width for [`RoutingStrategy::Aperture`]: this
+ /// dispatcher's ring slice is derived from its agreed peer index. `None`
+ /// (or a not-yet-known peer index) falls back to the full healthy pool.
+ aperture: Option<(Arc<PeerTracker>, usize)>,
/// Debug event recorder; `None` unless `DEBUG_API_ENABLED`.
debug_recorder: Option<Arc<DebugRecorder>>,
}
@@ -202,6 +208,7 @@ impl Dispatcher {
registry,
router: Mutex::new(Router::new(strategy)),
key_sentinel: Arc::new(KeyOrderSentinel::new()),
+ aperture: None,
debug_recorder: None,
}
}
@@ -218,6 +225,7 @@ impl Dispatcher {
registry,
router: Mutex::new(Router::with_seed(strategy, seed)),
key_sentinel: Arc::new(KeyOrderSentinel::new()),
+ aperture: None,
debug_recorder: None,
}
}
@@ -228,6 +236,14 @@ impl Dispatcher {
Arc::clone(&self.key_sentinel)
}
+ /// Enable deterministic-aperture candidate narrowing: unpinned keys route
+ /// within this dispatcher's slice of the worker ring, `min_aperture` wide.
+ /// Only consulted under [`RoutingStrategy::Aperture`]. Call before the
+ /// dispatcher is shared.
+ pub fn set_aperture(&mut self, tracker: Arc<PeerTracker>, min_aperture: usize) {
+ self.aperture = Some((tracker, min_aperture.max(1)));
+ }
+
/// Inject the debug UI recorder. Call before the dispatcher is shared.
pub fn set_debug_recorder(&mut self, recorder: Arc<DebugRecorder>) {
self.debug_recorder = Some(recorder);
@@ -352,8 +368,29 @@ impl Dispatcher {
unpinned_groups.sort_unstable_by(|a, b| b.messages.len().cmp(&a.messages.len()));
}
+ // Aperture: narrow the candidates to this dispatcher's ring slice, so
+ // the fleet's slices tile the pool and each batch consolidates onto
+ // few workers. Falls back to the full healthy pool while the peer set
+ // is unknown (startup, peer awareness disabled).
+ let narrowed = if router.strategy() == RoutingStrategy::Aperture {
+ self.aperture.as_ref().and_then(|(tracker, width)| {
+ let peers = tracker.snapshot();
+ let ring = aperture::sorted_ring(self.registry.workers());
+ aperture::ring_slice(
+ &ring,
+ &healthy,
+ peers.self_index,
+ peers.peer_count(),
+ *width,
+ )
+ })
+ } else {
+ None
+ };
+ let candidates: &[WorkerId] = narrowed.as_deref().unwrap_or(&healthy);
+
for group in unpinned_groups {
- let Some(worker) = router.select(&healthy, &working_load) else {
+ let Some(worker) = router.select(candidates, &working_load) else {
// No routable worker right now (e.g. the whole pool is draining
// during a deploy overlap). Stash the group so the flush loop
// can route it once a worker returns — dropping it would fail
@@ -1321,6 +1358,108 @@ mod tests {
assert!(b.is_empty());
}
+ // ---- deterministic aperture ----
+
+ fn peer_tracker(self_ip: &str, peer_ips: &[&str]) -> Arc<PeerTracker> {
+ let tracker = PeerTracker::new(self_ip.parse().unwrap());
+ tracker.set_peers(&peer_ips.iter().map(|ip| ip.parse().unwrap()).collect());
+ tracker
+ }
+
+ #[test]
+ fn test_aperture_routes_unpinned_keys_within_ring_slice() {
+ // Peer 1 of 2 over a 6-worker ring, configured width 2 floored to
+ // ceil(6/2)=3 for coverage, owns ring positions 3-5; every fresh key
+ // must land there, nowhere else.
+ let mut dispatcher =
+ Dispatcher::with_strategy(healthy_registry(6), RoutingStrategy::Aperture);
+ dispatcher.set_aperture(peer_tracker("10.0.0.2", &["10.0.0.1", "10.0.0.2"]), 2);
+
+ let msgs: Vec<_> = (0..10).map(|i| make_msg("t", &format!("u{i}"))).collect();
+ let sub_batches = dispatcher.assign("b", msgs);
+
+ let total: usize = sub_batches.iter().map(|b| b.messages.len()).sum();
+ assert_eq!(total, 10);
+ assert!(
+ sub_batches
+ .iter()
+ .all(|b| b.worker == wid(3) || b.worker == wid(4) || b.worker == wid(5)),
+ "all sub-batches must stay within the dispatcher's ring slice"
+ );
+ }
+
+ #[test]
+ fn test_aperture_slices_tile_across_peers_without_overlap() {
+ // Two dispatchers with complementary indices must route into disjoint
+ // slices — the property that keeps the fleet covering the whole pool.
+ let keys: Vec<_> = (0..10).map(|i| format!("u{i}")).collect();
+ let mut used: Vec<Vec<WorkerId>> = Vec::new();
+ for self_ip in ["10.0.0.1", "10.0.0.2"] {
+ let mut dispatcher =
+ Dispatcher::with_strategy(healthy_registry(6), RoutingStrategy::Aperture);
+ dispatcher.set_aperture(peer_tracker(self_ip, &["10.0.0.1", "10.0.0.2"]), 2);
+ let msgs: Vec<_> = keys.iter().map(|k| make_msg("t", k)).collect();
+ used.push(
+ dispatcher
+ .assign("b", msgs)
+ .iter()
+ .map(|b| b.worker.clone())
+ .collect(),
+ );
+ }
+ assert!(
+ used[0].iter().all(|w| !used[1].contains(w)),
+ "peer slices must not overlap: {used:?}"
+ );
+ }
+
+ #[test]
+ fn test_aperture_falls_back_to_full_pool_while_self_unknown() {
+ // Before this pod is a ready endpoint (self_index None), aperture must
+ // not stall or funnel everything through a guessed slice — it routes
+ // over the full pool like plain P2C.
+ let mut dispatcher =
+ Dispatcher::with_strategy_seeded(healthy_registry(4), RoutingStrategy::Aperture, 7);
+ dispatcher.set_aperture(peer_tracker("10.0.0.9", &["10.0.0.1", "10.0.0.2"]), 1);
+
+ let msgs: Vec<_> = (0..30).map(|i| make_msg("t", &format!("u{i}"))).collect();
+ let sub_batches = dispatcher.assign("b", msgs);
+
+ let total: usize = sub_batches.iter().map(|b| b.messages.len()).sum();
+ assert_eq!(total, 30, "no messages may be dropped or stalled");
+ assert!(
+ sub_batches.len() > 1,
+ "fallback must spread beyond a single-worker slice"
+ );
+ }
+
+ #[test]
+ fn test_aperture_honors_pin_outside_ring_slice() {
+ // Peer 1 of 2 over a 6-worker ring owns ring positions 3-5. A key
+ // pinned to worker 0 — outside the slice — must keep routing there:
+ // the slice narrows candidates for *fresh* keys only, and rerouting
+ // a pinned key would break per-key ordering.
+ let mut dispatcher =
+ Dispatcher::with_strategy(healthy_registry(6), RoutingStrategy::Aperture);
+ dispatcher.set_aperture(peer_tracker("10.0.0.2", &["10.0.0.1", "10.0.0.2"]), 2);
+ dispatcher.pin_table.lock().unwrap().pins.insert(
+ "t:pinned".to_string(),
+ Pin {
+ worker: wid(0),
+ ref_count: 1,
+ },
+ );
+
+ let sub_batches = dispatcher.assign("b", make_msgs(&[("t", "pinned")]));
+
+ assert_eq!(sub_batches.len(), 1);
+ assert_eq!(
+ sub_batches[0].worker,
+ wid(0),
+ "pinned key must stay on its out-of-slice worker"
+ );
+ }
+
// ---- graceful drain ----
#[test]
diff --git a/rust/ingestion-consumer/src/lib.rs b/rust/ingestion-consumer/src/lib.rs
index 38a5a31f4675..1062f92deeef 100644
--- a/rust/ingestion-consumer/src/lib.rs
+++ b/rust/ingestion-consumer/src/lib.rs
@@ -1,3 +1,4 @@
+pub mod aperture;
pub mod config;
pub mod consumer;
pub mod debug_recorder;
diff --git a/rust/ingestion-consumer/src/main.rs b/rust/ingestion-consumer/src/main.rs
index 9b059f319282..74013c7f7b89 100644
--- a/rust/ingestion-consumer/src/main.rs
+++ b/rust/ingestion-consumer/src/main.rs
@@ -12,7 +12,7 @@ use lifecycle::{ComponentOptions, Manager};
use metrics_exporter_prometheus::{Matcher, PrometheusBuilder};
use tokio::net::TcpListener;
use tokio_util::sync::CancellationToken;
-use tracing::{error, info};
+use tracing::{error, info, warn};
use tracing_subscriber::fmt;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
@@ -25,6 +25,7 @@ use ingestion_consumer::discovery::{
DiscoveryMode, EndpointSliceDiscovery, StaticDiscovery, WorkerDiscovery,
};
use ingestion_consumer::dispatcher::Dispatcher;
+use ingestion_consumer::routing::RoutingStrategy;
use ingestion_consumer::transport::HttpTransport;
use ingestion_consumer::worker_registry::{WorkerRegistry, WorkerRegistryConfig};
@@ -179,10 +180,48 @@ async fn async_main(config: Config) -> Result<()> {
let probe_token = CancellationToken::new();
Arc::clone(&registry).start_probing(probe_token.clone());
+ // Peer awareness: track this consumer's own ready replicas via its
+ // Service's EndpointSlices, giving every pod a stable agreed index among
+ // its peers (the basis for deterministic aperture routing). Fails open:
+ // misconfiguration disables peer awareness rather than blocking startup.
+ let discovery_token = CancellationToken::new();
+ let peer_tracker: Option<Arc<k8s_awareness::PeerTracker>> =
+ if config.peer_service_name.is_empty() {
+ None
+ } else if let Some(self_ip) = config.pod_ip.as_deref().and_then(|s| s.parse().ok()) {
+ let client = kube::Client::try_default()
+ .await
+ .context("Failed to create Kubernetes client for peer discovery")?;
+ let tracker = k8s_awareness::PeerTracker::new(self_ip);
+ tracker.watch(
+ client,
+ config.worker_namespace.clone(),
+ config.peer_service_name.clone(),
+ discovery_token.clone(),
+ );
+ Some(tracker)
+ } else {
+ error!(
+ pod_ip = ?config.pod_ip,
+ "PEER_SERVICE_NAME is set but POD_IP is missing or invalid; peer awareness disabled"
+ );
+ None
+ };
+
let mut dispatcher = Dispatcher::with_strategy(Arc::clone(&registry), config.routing_strategy);
if let Some(recorder) = &debug_recorder {
dispatcher.set_debug_recorder(Arc::clone(recorder));
}
+ match &peer_tracker {
+ Some(tracker) => dispatcher.set_aperture(Arc::clone(tracker), config.min_aperture),
+ None if config.routing_strategy == RoutingStrategy::Aperture => {
+ warn!(
+ "INGESTION_ROUTING_STRATEGY=aperture without peer awareness (PEER_SERVICE_NAME); \
+ routing falls back to p2c over the full pool"
+ );
+ }
+ None => {}
+ }
let dispatcher = Arc::new(dispatcher);
let api_secret = if config.internal_api_secret.is_empty() {
@@ -205,7 +244,6 @@ async fn async_main(config: Config) -> Result<()> {
// 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 => {
@@ -298,6 +336,7 @@ async fn async_main(config: Config) -> Result<()> {
{
let registry = Arc::clone(&registry);
let dispatcher = Arc::clone(&dispatcher);
+ let peer_tracker = peer_tracker.clone();
let group_id = group_id.clone();
let secret = Arc::clone(&secret);
app = app.route(
@@ -310,6 +349,7 @@ async fn async_main(config: Config) -> Result<()> {
&group_id,
&registry,
&dispatcher,
+ &peer_tracker,
)))
};
ready(result)
@@ -320,6 +360,7 @@ async fn async_main(config: Config) -> Result<()> {
let recorder = Arc::clone(recorder);
let registry = Arc::clone(&registry);
let dispatcher = Arc::clone(&dispatcher);
+ let peer_tracker = peer_tracker.clone();
let group_id = group_id.clone();
let secret = Arc::clone(&secret);
app = app.route(
@@ -328,11 +369,14 @@ async fn async_main(config: Config) -> Result<()> {
let result = if !debug_authorized(&headers, &secret) {
Err(axum::http::StatusCode::UNAUTHORIZED)
} else {
- let load = build_debug_load(&group_id, &registry, &dispatcher);
+ let load =
+ build_debug_load(&group_id, &registry, &dispatcher, &peer_tracker);
Ok(axum::Json(DebugState {
group_id: load.group_id,
workers: load.workers,
dispatcher: load.dispatcher,
+ peer_index: load.peer_index,
+ peer_count: load.peer_count,
events: recorder.backlog(),
}))
};
@@ -489,7 +533,15 @@ fn build_debug_load(
group_id: &str,
registry: &ingestion_consumer::worker_registry::WorkerRegistry,
dispatcher: &Dispatcher,
+ peer_tracker: &Option<Arc<k8s_awareness::PeerTracker>>,
) -> DebugLoad {
+ let (peer_index, peer_count) = match peer_tracker {
+ Some(tracker) => {
+ let peers = tracker.snapshot();
+ (peers.self_index, Some(peers.peer_count()))
+ }
+ None => (None, None),
+ };
let dispatcher_load = dispatcher.debug_load();
let workers = registry
.health_snapshots()
@@ -516,5 +568,7 @@ fn build_debug_load(
group_id: group_id.to_string(),
workers,
dispatcher: dispatcher_load,
+ peer_index,
+ peer_count,
}
}
diff --git a/rust/ingestion-consumer/src/routing.rs b/rust/ingestion-consumer/src/routing.rs
index 2398a232970d..006db9a6e078 100644
--- a/rust/ingestion-consumer/src/routing.rs
+++ b/rust/ingestion-consumer/src/routing.rs
@@ -28,6 +28,13 @@ pub enum RoutingStrategy {
/// resistant when many consumers share a worker pool, because each consumer
/// samples a different random pair instead of converging on one global best.
P2c,
+ /// Deterministic aperture: each dispatcher routes unpinned keys only within
+ /// its slice of the worker ring (see [`crate::aperture`]), with P2C
+ /// selection inside the slice. Consolidates small batches onto few workers
+ /// while the fleet's slices still tile the whole pool. Requires peer
+ /// awareness (`PEER_SERVICE_NAME`); behaves as plain P2C over the full
+ /// pool while the peer set is unknown.
+ Aperture,
}
impl FromStr for RoutingStrategy {
@@ -37,8 +44,9 @@ impl FromStr for RoutingStrategy {
match s.trim().to_lowercase().as_str() {
"binpack" | "bin_pack" | "bin-pack" => Ok(RoutingStrategy::BinPack),
"p2c" | "power_of_two" | "power-of-two" => Ok(RoutingStrategy::P2c),
+ "aperture" => Ok(RoutingStrategy::Aperture),
other => Err(format!(
- "unknown routing strategy '{other}' (expected 'binpack' or 'p2c')"
+ "unknown routing strategy '{other}' (expected 'binpack', 'p2c', or 'aperture')"
)),
}
}
@@ -96,7 +104,11 @@ impl Router {
pub fn select(&mut self, healthy: &[WorkerId], load: &WorkerLoad) -> Option<WorkerId> {
match self.strategy {
RoutingStrategy::BinPack => select_least_loaded(healthy, load),
- RoutingStrategy::P2c => select_p2c(healthy, load, &mut self.rng),
+ // Aperture narrows the candidate slice upstream (in the
+ // dispatcher); within the slice it selects exactly like P2C.
+ RoutingStrategy::P2c | RoutingStrategy::Aperture => {
+ select_p2c(healthy, load, &mut self.rng)
+ }
}
}
}
@@ -154,6 +166,7 @@ mod tests {
assert_eq!("bin-pack".parse(), Ok(RoutingStrategy::BinPack));
assert_eq!("p2c".parse(), Ok(RoutingStrategy::P2c));
assert_eq!("power-of-two".parse(), Ok(RoutingStrategy::P2c));
+ assert_eq!("aperture".parse(), Ok(RoutingStrategy::Aperture));
}
#[test]
diff --git a/rust/personhog-router/Cargo.toml b/rust/personhog-router/Cargo.toml
index 3296d122039a..862bee654f79 100644
--- a/rust/personhog-router/Cargo.toml
+++ b/rust/personhog-router/Cargo.toml
@@ -14,7 +14,6 @@ k8s-awareness = { path = "../common/k8s-awareness" }
common-alloc = { path = "../common/alloc" }
metrics-exporter-prometheus = { workspace = true }
lifecycle = { path = "../common/lifecycle" }
-k8s-openapi = { version = "0.24", features = ["latest"] }
kube = { version = "0.98", features = ["client", "runtime"] }
async-trait = { workspace = true }
diff --git a/rust/personhog-router/src/backend/discovery.rs b/rust/personhog-router/src/backend/discovery.rs
index 1e7728c198ca..44f2c3399785 100644
--- a/rust/personhog-router/src/backend/discovery.rs
+++ b/rust/personhog-router/src/backend/discovery.rs
@@ -1,11 +1,7 @@
-use std::collections::{HashMap, HashSet};
-use std::net::{IpAddr, SocketAddr};
+use std::collections::HashSet;
+use std::net::SocketAddr;
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 tokio::sync::mpsc::Sender;
use tokio::sync::watch;
@@ -23,6 +19,11 @@ pub struct EndpointConfig {
pub keepalive_timeout: Option<Duration>,
}
+/// Feeds replica endpoints into a tonic balance channel, driven by the shared
+/// EndpointSlice membership watch ([`k8s_awareness::watch_service_members`]).
+/// This crate only owns the transport side: diffing the member set into
+/// `Change::Insert`/`Change::Remove`, building tonic `Endpoint`s, and exposing
+/// readiness.
pub struct EndpointDiscovery {
client: Client,
namespace: String,
@@ -55,33 +56,6 @@ impl DiscoveryReadiness {
}
}
-/// Parses an EndpointSlice and returns the set of ready socket addresses.
-///
-/// An endpoint is considered ready when `conditions.ready` is `true` or when
-/// `conditions` is absent entirely (the K8s spec treats a nil ready field as
-/// "assume ready"). Endpoints with `ready = false` are skipped. Address
-/// strings that fail IP parsing are also skipped silently.
-pub 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
-}
-
impl EndpointDiscovery {
pub fn new(
client: Client,
@@ -141,10 +115,6 @@ impl EndpointDiscovery {
}
pub async fn run(self) {
- let api: Api<EndpointSlice> = Api::namespaced(self.client.clone(), &self.namespace);
- let label_selector = format!("kubernetes.io/service-name={}", self.service_name);
- let config = WatcherConfig::default().labels(&label_selector);
-
info!(
service = %self.service_name,
namespace = %self.namespace,
@@ -152,12 +122,13 @@ impl EndpointDiscovery {
"starting EndpointSlice discovery"
);
- let stream = watcher::watcher(api, config);
- tokio::pin!(stream);
+ let (mut members, _watch_task) = k8s_awareness::watch_service_members(
+ self.client.clone(),
+ self.namespace.clone(),
+ self.service_name.clone(),
+ self.cancel.clone(),
+ );
- // Track addrs per slice name so we can correctly reconcile when one
- // slice changes without clobbering addrs from other slices.
- let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
let mut active_addrs: HashSet<SocketAddr> = HashSet::new();
loop {
@@ -166,73 +137,29 @@ impl EndpointDiscovery {
info!("endpoint discovery cancelled");
break;
}
- item = stream.next() => {
- match item {
- Some(Ok(event)) => {
- self.handle_event(event, &mut slices, &mut active_addrs).await;
- }
- Some(Err(e)) => {
- warn!(error = %e, "EndpointSlice watcher error, stream will retry");
- metrics::counter!("personhog_router_discovery_errors_total").increment(1);
- }
- None => {
- warn!("EndpointSlice watcher stream ended unexpectedly");
- metrics::counter!("personhog_router_discovery_stream_terminated_total").increment(1);
- break;
- }
+ changed = members.changed() => {
+ if changed.is_err() {
+ // The watch task only exits on cancellation, so a
+ // closed channel means shutdown is underway.
+ warn!("EndpointSlice membership watch closed");
+ break;
}
+ let desired: HashSet<SocketAddr> = members
+ .borrow_and_update()
+ .iter()
+ .map(|ip| SocketAddr::new(*ip, self.port))
+ .collect();
+ self.sync_active(&desired, &mut active_addrs).await;
}
}
}
}
- async fn handle_event(
- &self,
- event: Event<EndpointSlice>,
- slices: &mut HashMap<String, HashSet<SocketAddr>>,
- active_addrs: &mut HashSet<SocketAddr>,
- ) {
- match event {
- Event::Apply(slice) | Event::InitApply(slice) => {
- let slice_key = slice
- .metadata
- .name
- .clone()
- .or_else(|| slice.metadata.uid.clone())
- .unwrap_or_else(|| "unknown".to_string());
- let new_addrs = extract_ready_addrs(&slice, self.port);
- slices.insert(slice_key, new_addrs);
- self.sync_active(slices, active_addrs).await;
- }
- Event::Delete(slice) => {
- let slice_key = slice
- .metadata
- .name
- .or_else(|| slice.metadata.uid.clone())
- .unwrap_or_else(|| "unknown".to_string());
- slices.remove(&slice_key);
- self.sync_active(slices, active_addrs).await;
- }
- Event::Init => {
- // Clear the slice map but keep active_addrs intact so the
- // balancer continues serving on stale endpoints during the
- // re-list. InitApply events will rebuild `slices`, and
- // InitDone will reconcile against `active_addrs`.
- slices.clear();
- }
- Event::InitDone => {
- self.sync_active(slices, active_addrs).await;
- }
- }
- }
-
async fn sync_active(
&self,
- slices: &HashMap<String, HashSet<SocketAddr>>,
+ desired: &HashSet<SocketAddr>,
active_addrs: &mut HashSet<SocketAddr>,
) {
- let desired: HashSet<SocketAddr> = slices.values().flatten().copied().collect();
-
for addr in desired.difference(active_addrs) {
let endpoint = self.build_endpoint(*addr);
if self.tx.send(Change::Insert(*addr, endpoint)).await.is_ok() {
@@ -241,14 +168,14 @@ impl EndpointDiscovery {
}
}
- for addr in active_addrs.difference(&desired) {
+ for addr in active_addrs.difference(desired) {
if self.tx.send(Change::Remove(*addr)).await.is_ok() {
metrics::counter!("personhog_router_discovery_updates_total", "action" => "remove")
.increment(1);
}
}
- *active_addrs = desired;
+ *active_addrs = desired.clone();
let count = active_addrs.len();
metrics::gauge!("personhog_router_discovery_endpoints_active").set(count as f64);
let _ = self.ready_tx.send(count > 0);
@@ -276,52 +203,17 @@ impl EndpointDiscovery {
#[cfg(test)]
mod tests {
- use std::collections::{HashMap, HashSet};
+ use std::collections::HashSet;
use std::net::SocketAddr;
- use k8s_openapi::api::discovery::v1::EndpointSlice;
- use k8s_openapi::api::discovery::v1::{Endpoint as K8sEndpoint, EndpointConditions};
- use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta;
- use kube::runtime::watcher::Event;
use tokio::sync::mpsc;
use tonic::transport::Endpoint;
use tower::discover::Change;
- use super::{extract_ready_addrs, EndpointDiscovery};
+ use super::EndpointDiscovery;
// ── helpers ──────────────────────────────────────────────────────────────
- fn make_endpoint_with_conditions(addresses: Vec<&str>, ready: Option<bool>) -> K8sEndpoint {
- K8sEndpoint {
- addresses: addresses.into_iter().map(str::to_string).collect(),
- conditions: ready.map(|r| EndpointConditions {
- ready: Some(r),
- ..Default::default()
- }),
- ..Default::default()
- }
- }
-
- fn make_endpoint_no_conditions(addresses: Vec<&str>) -> K8sEndpoint {
- K8sEndpoint {
- addresses: addresses.into_iter().map(str::to_string).collect(),
- conditions: None,
- ..Default::default()
- }
- }
-
- fn make_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 addr(ip: &str, port: u16) -> SocketAddr {
format!("{ip}:{port}").parse().unwrap()
}
@@ -357,156 +249,17 @@ mod tests {
.collect()
}
- // ── extract_ready_addrs ───────────────────────────────────────────────────
-
- #[test]
- fn extract_ready_addrs_returns_empty_for_empty_slice() {
- let slice = make_slice("s1", vec![]);
- let result = extract_ready_addrs(&slice, 50051);
- assert!(
- result.is_empty(),
- "expected empty set for empty EndpointSlice"
- );
- }
-
- #[test]
- fn extract_ready_addrs_includes_endpoint_with_ready_true() {
- let slice = make_slice(
- "s1",
- vec![make_endpoint_with_conditions(vec!["10.0.0.1"], Some(true))],
- );
- let result = extract_ready_addrs(&slice, 50051);
- assert_eq!(result, HashSet::from([addr("10.0.0.1", 50051)]));
- }
-
- #[test]
- fn extract_ready_addrs_excludes_endpoint_with_ready_false() {
- let slice = make_slice(
- "s1",
- vec![make_endpoint_with_conditions(vec!["10.0.0.1"], Some(false))],
- );
- let result = extract_ready_addrs(&slice, 50051);
- assert!(
- result.is_empty(),
- "ready=false endpoint must not be included"
- );
- }
-
- #[test]
- fn extract_ready_addrs_includes_endpoint_with_no_conditions() {
- // Absent conditions field defaults to ready=true per K8s spec.
- let slice = make_slice("s1", vec![make_endpoint_no_conditions(vec!["10.0.0.2"])]);
- let result = extract_ready_addrs(&slice, 50051);
- assert_eq!(result, HashSet::from([addr("10.0.0.2", 50051)]));
- }
-
- #[test]
- fn extract_ready_addrs_includes_endpoint_with_conditions_but_nil_ready() {
- // Conditions present but ready field is None — also defaults to true.
- let slice = make_slice(
- "s1",
- vec![K8sEndpoint {
- addresses: vec!["10.0.0.3".to_string()],
- conditions: Some(EndpointConditions {
- ready: None,
- ..Default::default()
- }),
- ..Default::default()
- }],
- );
- let result = extract_ready_addrs(&slice, 50051);
- assert_eq!(result, HashSet::from([addr("10.0.0.3", 50051)]));
- }
-
- #[test]
- fn extract_ready_addrs_uses_provided_port() {
- let slice = make_slice(
- "s1",
- vec![make_endpoint_with_conditions(vec!["10.0.0.1"], Some(true))],
- );
- assert_eq!(
- extract_ready_addrs(&slice, 9090),
- HashSet::from([addr("10.0.0.1", 9090)]),
- );
- assert_eq!(
- extract_ready_addrs(&slice, 1234),
- HashSet::from([addr("10.0.0.1", 1234)]),
- );
- }
-
- #[test]
- fn extract_ready_addrs_skips_unparseable_address() {
- let slice = make_slice(
- "s1",
- vec![K8sEndpoint {
- addresses: vec!["not-an-ip".to_string(), "10.0.0.5".to_string()],
- conditions: None,
- ..Default::default()
- }],
- );
- let result = extract_ready_addrs(&slice, 50051);
- // The valid address is included; the bad one is silently skipped.
- assert_eq!(result, HashSet::from([addr("10.0.0.5", 50051)]));
- }
-
- #[test]
- fn extract_ready_addrs_handles_mixed_ready_and_not_ready_endpoints() {
- let slice = make_slice(
- "s1",
- vec![
- make_endpoint_with_conditions(vec!["10.0.0.1"], Some(true)),
- make_endpoint_with_conditions(vec!["10.0.0.2"], Some(false)),
- make_endpoint_no_conditions(vec!["10.0.0.3"]),
- ],
- );
- let result = extract_ready_addrs(&slice, 50051);
- assert_eq!(
- result,
- HashSet::from([addr("10.0.0.1", 50051), addr("10.0.0.3", 50051)]),
- );
- }
-
- #[test]
- fn extract_ready_addrs_handles_multiple_addresses_per_endpoint() {
- let slice = make_slice(
- "s1",
- vec![make_endpoint_with_conditions(
- vec!["10.0.0.1", "10.0.0.2"],
- Some(true),
- )],
- );
- let result = extract_ready_addrs(&slice, 50051);
- assert_eq!(
- result,
- HashSet::from([addr("10.0.0.1", 50051), addr("10.0.0.2", 50051)]),
- );
- }
-
- #[test]
- fn extract_ready_addrs_handles_ipv6_address() {
- let slice = make_slice(
- "s1",
- vec![make_endpoint_with_conditions(vec!["::1"], Some(true))],
- );
- let result = extract_ready_addrs(&slice, 50051);
- assert_eq!(
- result,
- HashSet::from(["[::1]:50051".parse::<SocketAddr>().unwrap()])
- );
- }
-
// ── sync_active ───────────────────────────────────────────────────────────
#[tokio::test]
async fn sync_active_sends_insert_for_new_addr() {
let (tx, mut rx) = mpsc::channel(64);
- let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
+ let (discovery, readiness) = EndpointDiscovery::new_for_test(50051, tx);
- let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
- slices.insert("s1".to_string(), HashSet::from([addr("10.0.0.1", 50051)]));
+ let desired = HashSet::from([addr("10.0.0.1", 50051)]);
let mut active: HashSet<SocketAddr> = HashSet::new();
- discovery.sync_active(&slices, &mut active).await;
+ discovery.sync_active(&desired, &mut active).await;
let changes = drain_changes(&mut rx);
assert_eq!(
@@ -515,18 +268,19 @@ mod tests {
"should insert the new addr",
);
assert!(removed_addrs(&changes).is_empty(), "no removes expected");
- assert_eq!(active, HashSet::from([addr("10.0.0.1", 50051)]));
+ assert_eq!(active, desired);
+ assert!(readiness.is_ready(), "ready once an endpoint is active");
}
#[tokio::test]
async fn sync_active_sends_remove_for_gone_addr() {
let (tx, mut rx) = mpsc::channel(64);
- let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
+ let (discovery, readiness) = EndpointDiscovery::new_for_test(50051, tx);
- let slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
+ let desired: HashSet<SocketAddr> = HashSet::new();
let mut active: HashSet<SocketAddr> = HashSet::from([addr("10.0.0.1", 50051)]);
- discovery.sync_active(&slices, &mut active).await;
+ discovery.sync_active(&desired, &mut active).await;
let changes = drain_changes(&mut rx);
assert!(inserted_addrs(&changes).is_empty(), "no inserts expected");
@@ -536,6 +290,7 @@ mod tests {
"should remove the addr that disappeared from desired",
);
assert!(active.is_empty());
+ assert!(!readiness.is_ready(), "not ready with zero endpoints");
}
#[tokio::test]
@@ -543,11 +298,10 @@ mod tests {
let (tx, mut rx) = mpsc::channel(64);
let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
- let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
- slices.insert("s1".to_string(), HashSet::from([addr("10.0.0.1", 50051)]));
- let mut active: HashSet<SocketAddr> = HashSet::from([addr("10.0.0.1", 50051)]);
+ let desired = HashSet::from([addr("10.0.0.1", 50051)]);
+ let mut active = desired.clone();
- discovery.sync_active(&slices, &mut active).await;
+ discovery.sync_active(&desired, &mut active).await;
let changes = drain_changes(&mut rx);
assert!(
@@ -557,20 +311,16 @@ mod tests {
}
#[tokio::test]
- async fn sync_active_updates_active_to_desired() {
+ async fn sync_active_diffs_mixed_insert_and_remove() {
let (tx, mut rx) = mpsc::channel(64);
let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
// Desired: {.1, .2}; Active: {.1, .3}
- let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
- slices.insert(
- "s1".to_string(),
- HashSet::from([addr("10.0.0.1", 50051), addr("10.0.0.2", 50051)]),
- );
+ let desired = HashSet::from([addr("10.0.0.1", 50051), addr("10.0.0.2", 50051)]);
let mut active: HashSet<SocketAddr> =
HashSet::from([addr("10.0.0.1", 50051), addr("10.0.0.3", 50051)]);
- discovery.sync_active(&slices, &mut active).await;
+ discovery.sync_active(&desired, &mut active).await;
let changes = drain_changes(&mut rx);
assert_eq!(
@@ -583,397 +333,6 @@ mod tests {
HashSet::from([addr("10.0.0.3", 50051)]),
"only the gone addr is removed",
);
- assert_eq!(
- active,
- HashSet::from([addr("10.0.0.1", 50051), addr("10.0.0.2", 50051)]),
- );
- }
-
- #[tokio::test]
- async fn sync_active_aggregates_addrs_across_slices() {
- let (tx, mut rx) = mpsc::channel(64);
- let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
-
- let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
- slices.insert("s1".to_string(), HashSet::from([addr("10.0.0.1", 50051)]));
- slices.insert("s2".to_string(), HashSet::from([addr("10.0.0.2", 50051)]));
- let mut active: HashSet<SocketAddr> = HashSet::new();
-
- discovery.sync_active(&slices, &mut active).await;
-
- let changes = drain_changes(&mut rx);
- assert_eq!(
- inserted_addrs(&changes),
- HashSet::from([addr("10.0.0.1", 50051), addr("10.0.0.2", 50051)]),
- );
- }
-
- // ── handle_event ─────────────────────────────────────────────────────────
-
- #[tokio::test]
- async fn handle_event_apply_inserts_ready_addrs() {
- let (tx, mut rx) = mpsc::channel(64);
- let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
-
- let mut slices = HashMap::new();
- let mut active = HashSet::new();
-
- let slice = make_slice(
- "s1",
- vec![make_endpoint_with_conditions(vec!["10.0.0.1"], Some(true))],
- );
- discovery
- .handle_event(Event::Apply(slice), &mut slices, &mut active)
- .await;
-
- let changes = drain_changes(&mut rx);
- assert_eq!(
- inserted_addrs(&changes),
- HashSet::from([addr("10.0.0.1", 50051)]),
- );
- assert_eq!(active, HashSet::from([addr("10.0.0.1", 50051)]));
- }
-
- #[tokio::test]
- async fn handle_event_init_apply_inserts_ready_addrs() {
- let (tx, mut rx) = mpsc::channel(64);
- let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
-
- let mut slices = HashMap::new();
- let mut active = HashSet::new();
-
- let slice = make_slice(
- "s1",
- vec![make_endpoint_with_conditions(vec!["10.0.0.2"], Some(true))],
- );
- discovery
- .handle_event(Event::InitApply(slice), &mut slices, &mut active)
- .await;
-
- let changes = drain_changes(&mut rx);
- assert_eq!(
- inserted_addrs(&changes),
- HashSet::from([addr("10.0.0.2", 50051)]),
- );
- }
-
- #[tokio::test]
- async fn handle_event_delete_removes_slice_addrs_and_syncs() {
- let (tx, mut rx) = mpsc::channel(64);
- let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
-
- let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
- slices.insert("s1".to_string(), HashSet::from([addr("10.0.0.1", 50051)]));
- let mut active: HashSet<SocketAddr> = HashSet::from([addr("10.0.0.1", 50051)]);
-
- let slice = make_slice("s1", vec![]);
- discovery
- .handle_event(Event::Delete(slice), &mut slices, &mut active)
- .await;
-
- let changes = drain_changes(&mut rx);
- assert_eq!(
- removed_addrs(&changes),
- HashSet::from([addr("10.0.0.1", 50051)]),
- "delete should trigger removal of the slice's addrs",
- );
- assert!(active.is_empty());
- assert!(!slices.contains_key("s1"), "slice entry should be gone");
- }
-
- #[tokio::test]
- async fn handle_event_delete_one_slice_does_not_remove_other_slice_addrs() {
- // Critical multi-slice test: deleting s1 must not touch s2's addrs.
- let (tx, mut rx) = mpsc::channel(64);
- let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
-
- let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
- slices.insert("s1".to_string(), HashSet::from([addr("10.0.0.1", 50051)]));
- slices.insert("s2".to_string(), HashSet::from([addr("10.0.0.2", 50051)]));
- let mut active: HashSet<SocketAddr> =
- HashSet::from([addr("10.0.0.1", 50051), addr("10.0.0.2", 50051)]);
-
- let slice = make_slice("s1", vec![]);
- discovery
- .handle_event(Event::Delete(slice), &mut slices, &mut active)
- .await;
-
- let changes = drain_changes(&mut rx);
- assert_eq!(
- removed_addrs(&changes),
- HashSet::from([addr("10.0.0.1", 50051)]),
- "only s1's addr is removed",
- );
- assert!(
- inserted_addrs(&changes).is_empty(),
- "s2's addr is still active and must not be re-inserted",
- );
- assert_eq!(
- active,
- HashSet::from([addr("10.0.0.2", 50051)]),
- "s2's addr must remain in the active set",
- );
- }
-
- #[tokio::test]
- async fn handle_event_init_clears_slices_but_preserves_active_addrs() {
- let (tx, mut rx) = mpsc::channel(64);
- let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
-
- let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
- slices.insert("s1".to_string(), HashSet::from([addr("10.0.0.1", 50051)]));
- let mut active: HashSet<SocketAddr> = HashSet::from([addr("10.0.0.1", 50051)]);
-
- discovery
- .handle_event(Event::Init, &mut slices, &mut active)
- .await;
-
- let changes = drain_changes(&mut rx);
- assert!(
- changes.is_empty(),
- "Init must not send any changes — stale endpoints stay in the balancer during re-list",
- );
- assert_eq!(
- active,
- HashSet::from([addr("10.0.0.1", 50051)]),
- "active_addrs must be preserved so the balancer keeps serving during re-list",
- );
- assert!(slices.is_empty(), "slices map must be cleared for re-list");
- }
-
- #[tokio::test]
- async fn handle_event_init_noop_when_no_active_addrs() {
- let (tx, mut rx) = mpsc::channel(64);
- let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
-
- let mut slices = HashMap::new();
- let mut active: HashSet<SocketAddr> = HashSet::new();
-
- discovery
- .handle_event(Event::Init, &mut slices, &mut active)
- .await;
-
- let changes = drain_changes(&mut rx);
- assert!(
- changes.is_empty(),
- "Init with no active addrs sends nothing"
- );
- }
-
- #[tokio::test]
- async fn handle_event_init_done_reconciles_active_with_slices() {
- let (tx, mut rx) = mpsc::channel(64);
- let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
-
- // Simulate post-re-list state: slices has the fresh set, active_addrs
- // still has stale endpoints from before Init.
- let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
- slices.insert("s1".to_string(), HashSet::from([addr("10.0.0.2", 50051)]));
- let mut active: HashSet<SocketAddr> = HashSet::from([addr("10.0.0.1", 50051)]);
-
- discovery
- .handle_event(Event::InitDone, &mut slices, &mut active)
- .await;
-
- let changes = drain_changes(&mut rx);
- assert_eq!(
- inserted_addrs(&changes),
- HashSet::from([addr("10.0.0.2", 50051)]),
- "new addr from re-listed slice is inserted",
- );
- assert_eq!(
- removed_addrs(&changes),
- HashSet::from([addr("10.0.0.1", 50051)]),
- "stale addr not in re-listed slices is removed",
- );
- assert_eq!(
- active,
- HashSet::from([addr("10.0.0.2", 50051)]),
- "active matches the re-listed state",
- );
- }
-
- #[tokio::test]
- async fn handle_event_init_done_noop_when_active_matches_slices() {
- let (tx, mut rx) = mpsc::channel(64);
- let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
-
- let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
- slices.insert("s1".to_string(), HashSet::from([addr("10.0.0.1", 50051)]));
- let mut active: HashSet<SocketAddr> = HashSet::from([addr("10.0.0.1", 50051)]);
-
- discovery
- .handle_event(Event::InitDone, &mut slices, &mut active)
- .await;
-
- let changes = drain_changes(&mut rx);
- assert!(
- changes.is_empty(),
- "no changes when active already matches re-listed slices",
- );
- }
-
- #[tokio::test]
- async fn handle_event_apply_updates_existing_slice_addrs() {
- // Simulates a pod being replaced: the same slice name gets new addrs.
- let (tx, mut rx) = mpsc::channel(64);
- let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
-
- let mut slices: HashMap<String, HashSet<SocketAddr>> = HashMap::new();
- slices.insert("s1".to_string(), HashSet::from([addr("10.0.0.1", 50051)]));
- let mut active: HashSet<SocketAddr> = HashSet::from([addr("10.0.0.1", 50051)]);
-
- let updated_slice = make_slice(
- "s1",
- vec![make_endpoint_with_conditions(vec!["10.0.0.9"], Some(true))],
- );
- discovery
- .handle_event(Event::Apply(updated_slice), &mut slices, &mut active)
- .await;
-
- let changes = drain_changes(&mut rx);
- assert_eq!(
- inserted_addrs(&changes),
- HashSet::from([addr("10.0.0.9", 50051)]),
- "new addr is inserted",
- );
- assert_eq!(
- removed_addrs(&changes),
- HashSet::from([addr("10.0.0.1", 50051)]),
- "old addr is removed",
- );
- assert_eq!(active, HashSet::from([addr("10.0.0.9", 50051)]));
- }
-
- #[tokio::test]
- async fn handle_event_apply_slice_without_name_falls_back_to_uid() {
- let (tx, mut rx) = mpsc::channel(64);
- let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
-
- let mut slices = HashMap::new();
- let mut active = HashSet::new();
-
- let mut slice = make_slice(
- "s1",
- vec![make_endpoint_with_conditions(vec!["10.0.0.1"], Some(true))],
- );
- slice.metadata.name = None;
- slice.metadata.uid = Some("abc-123".to_string());
-
- discovery
- .handle_event(Event::Apply(slice), &mut slices, &mut active)
- .await;
-
- assert!(
- slices.contains_key("abc-123"),
- "unnamed slice stored under UID key"
- );
- let changes = drain_changes(&mut rx);
- assert!(
- !inserted_addrs(&changes).is_empty(),
- "addr is still inserted"
- );
- }
-
- #[tokio::test]
- async fn handle_event_apply_slice_without_name_or_uid_uses_unknown() {
- let (tx, mut rx) = mpsc::channel(64);
- let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
-
- let mut slices = HashMap::new();
- let mut active = HashSet::new();
-
- let mut slice = make_slice(
- "s1",
- vec![make_endpoint_with_conditions(vec!["10.0.0.1"], Some(true))],
- );
- slice.metadata.name = None;
- slice.metadata.uid = None;
-
- discovery
- .handle_event(Event::Apply(slice), &mut slices, &mut active)
- .await;
-
- assert!(
- slices.contains_key("unknown"),
- "slice with no name or UID stored under 'unknown' key"
- );
- let changes = drain_changes(&mut rx);
- assert!(
- !inserted_addrs(&changes).is_empty(),
- "addr is still inserted"
- );
- }
-
- // ── Init → re-list → InitDone full flow ─────────────────────────────────
-
- #[tokio::test]
- async fn relist_flow_preserves_endpoints_and_reconciles_on_init_done() {
- let (tx, mut rx) = mpsc::channel(64);
- let (discovery, _readiness) = EndpointDiscovery::new_for_test(50051, tx);
-
- let mut slices = HashMap::new();
- let mut active = HashSet::new();
-
- // Initial state: two pods discovered.
- let slice = make_slice(
- "s1",
- vec![
- make_endpoint_with_conditions(vec!["10.0.0.1"], Some(true)),
- make_endpoint_with_conditions(vec!["10.0.0.2"], Some(true)),
- ],
- );
- discovery
- .handle_event(Event::Apply(slice), &mut slices, &mut active)
- .await;
- drain_changes(&mut rx);
-
- // API server drops the watch — Init fires.
- discovery
- .handle_event(Event::Init, &mut slices, &mut active)
- .await;
- let changes = drain_changes(&mut rx);
- assert!(
- changes.is_empty(),
- "Init must not send any removes — stale endpoints stay in the balancer",
- );
- assert_eq!(
- active,
- HashSet::from([addr("10.0.0.1", 50051), addr("10.0.0.2", 50051)]),
- "active_addrs preserved during re-list",
- );
-
- // Re-list: pod .2 is gone, pod .3 is new.
- let relisted_slice = make_slice(
- "s1",
- vec![
- make_endpoint_with_conditions(vec!["10.0.0.1"], Some(true)),
- make_endpoint_with_conditions(vec!["10.0.0.3"], Some(true)),
- ],
- );
- discovery
- .handle_event(Event::InitApply(relisted_slice), &mut slices, &mut active)
- .await;
- // InitApply calls sync_active, but we want to verify the full flow
- // through InitDone, so drain these intermediate changes.
- drain_changes(&mut rx);
-
- // InitDone signals re-list is complete.
- discovery
- .handle_event(Event::InitDone, &mut slices, &mut active)
- .await;
- let final_changes = drain_changes(&mut rx);
-
- // At this point active should exactly match the re-listed state.
- assert_eq!(
- active,
- HashSet::from([addr("10.0.0.1", 50051), addr("10.0.0.3", 50051)]),
- "active reflects re-listed endpoints",
- );
- // InitDone sync_active is a no-op here because InitApply already reconciled.
- assert!(
- final_changes.is_empty(),
- "InitDone is a no-op when InitApply already reconciled",
- );
+ assert_eq!(active, desired);
}
}