: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): expose routing strategy and aperture slice in debug API (#72284)
José Sequeira842507ac1d51
diff --git a/rust/ingestion-consumer/src/debug_recorder.rs b/rust/ingestion-consumer/src/debug_recorder.rsindex dbf2e9973661..a620139cb4c4 100644--- a/rust/ingestion-consumer/src/debug_recorder.rs+++ b/rust/ingestion-consumer/src/debug_recorder.rs@@ -136,6 +136,8 @@ pub struct WorkerHealthSnapshot {pub url: String,pub state: String,pub draining: bool,+ /// Eligible for routing right now (Healthy or Degraded, not draining).+ pub routable: bool,pub consecutive_probe_failures: u32,pub passive_error_rate: f64,pub passive_samples: usize,@@ -158,6 +160,23 @@ pub struct DispatcherLoad {pub stashed_batches: usize,}+/// The dispatcher's routing configuration and, under aperture, its current+/// ring slice — computed by the same code the assignment path uses, so what+/// this reports is what the next batch would route with.+#[derive(Serialize)]+pub struct RoutingDebug {+ /// Configured strategy (`binpack`, `p2c`, `aperture`).+ pub strategy: String,+ /// Configured minimum aperture width; `None` when aperture is not wired.+ pub min_aperture: Option<usize>,+ /// The canonical sorted worker ring shared by all peers.+ pub ring: Vec<String>,+ /// This dispatcher's current slice candidates for unpinned keys; `None`+ /// when routing uses the full healthy pool (non-aperture strategy, or+ /// aperture falling back while the peer set is unknown).+ pub slice: Option<Vec<String>>,+}+/// Merged worker row: registry health plus the dispatcher's in-flight count.#[derive(Serialize)]pub struct WorkerStatus {@@ -181,6 +200,7 @@ pub struct DebugState {pub peer_index: Option<usize>,/// Ready peer count; `None` when peer awareness is disabled.pub peer_count: Option<usize>,+ pub routing: RoutingDebug,pub events: Vec<DebugEvent>,}@@ -195,6 +215,7 @@ pub struct DebugLoad {pub peer_index: Option<usize>,/// See [`DebugState::peer_count`].pub peer_count: Option<usize>,+ pub routing: RoutingDebug,}/// Bounded rolling event buffer plus a broadcast channel for live subscribers.diff --git a/rust/ingestion-consumer/src/dispatcher.rs b/rust/ingestion-consumer/src/dispatcher.rsindex 5d34a49bf789..417309dc5aff 100644--- a/rust/ingestion-consumer/src/dispatcher.rs+++ b/rust/ingestion-consumer/src/dispatcher.rs@@ -6,7 +6,7 @@ use metrics::{counter, gauge, histogram};use crate::aperture;use crate::debug_recorder::{- record_if, DebugEventKind, DebugRecorder, DispatcherLoad, LoadEntry, SubBatchInfo,+ record_if, DebugEventKind, DebugRecorder, DispatcherLoad, LoadEntry, RoutingDebug, SubBatchInfo,};use crate::order_sentinel::KeyOrderSentinel;use crate::routing::{Router, RoutingStrategy, WorkerLoad};@@ -269,6 +269,29 @@ impl Dispatcher {}}+ /// Routing strategy and current aperture slice for the debug UI. Runs the+ /// same ring/slice computation as `assign`, over a worker view the caller+ /// captured in one registry pass — so within one debug response the ring,+ /// slice, and worker rows can't disagree under churn.+ pub fn debug_routing(&self, workers: Vec<WorkerId>, healthy: &[WorkerId]) -> RoutingDebug {+ let strategy = self.router.lock().unwrap().strategy();+ let ring = aperture::sorted_ring(workers);+ let slice = if strategy == RoutingStrategy::Aperture {+ self.aperture.as_ref().and_then(|(tracker, width)| {+ let peers = tracker.snapshot();+ aperture::ring_slice(&ring, healthy, peers.self_index, peers.peer_count(), *width)+ })+ } else {+ None+ };+ RoutingDebug {+ strategy: strategy.as_str().to_string(),+ min_aperture: self.aperture.as_ref().map(|(_, width)| *width),+ ring: ring.iter().map(|w| w.to_string()).collect(),+ slice: slice.map(|s| s.iter().map(|w| w.to_string()).collect()),+ }+ }+/// Assign a batch of messages to workers.////// Groups messages by routing key, then per group:@@ -1460,6 +1483,39 @@ mod tests {);}+ #[test]+ fn test_debug_routing_reports_the_live_aperture_slice() {+ // The debug payload must mirror what `assign` would use: same ring,+ // same slice (peer 1 of 2 over 6 workers → floored width 3, positions+ // 3-5). A drift here would make the control-plane UI lie during an+ // incident.+ let registry = healthy_registry(6);+ let mut dispatcher =+ Dispatcher::with_strategy(Arc::clone(®istry), RoutingStrategy::Aperture);+ dispatcher.set_aperture(peer_tracker("10.0.0.2", &["10.0.0.1", "10.0.0.2"]), 2);++ let routing = dispatcher.debug_routing(registry.workers(), ®istry.healthy_workers());++ assert_eq!(routing.strategy, "aperture");+ assert_eq!(routing.min_aperture, Some(2));+ assert_eq!(routing.ring.len(), 6);+ assert_eq!(+ routing.slice,+ Some(vec![+ wid(3).to_string(),+ wid(4).to_string(),+ wid(5).to_string()+ ])+ );++ // Non-aperture strategies report no slice — the UI shows full pool.+ let registry = healthy_registry(2);+ let p2c = Dispatcher::with_strategy(Arc::clone(®istry), RoutingStrategy::P2c);+ let routing = p2c.debug_routing(registry.workers(), ®istry.healthy_workers());+ assert_eq!(routing.strategy, "p2c");+ assert!(routing.slice.is_none());+ }+// ---- graceful drain ----#[test]diff --git a/rust/ingestion-consumer/src/main.rs b/rust/ingestion-consumer/src/main.rsindex 91a2ddb0f928..4ee0adbbd232 100644--- a/rust/ingestion-consumer/src/main.rs+++ b/rust/ingestion-consumer/src/main.rs@@ -27,7 +27,7 @@ use ingestion_consumer::discovery::{use ingestion_consumer::dispatcher::Dispatcher;use ingestion_consumer::routing::RoutingStrategy;use ingestion_consumer::transport::HttpTransport;-use ingestion_consumer::worker_registry::{WorkerRegistry, WorkerRegistryConfig};+use ingestion_consumer::worker_registry::{WorkerId, WorkerRegistry, WorkerRegistryConfig};common_alloc::used!();@@ -378,6 +378,7 @@ async fn async_main(config: Config) -> Result<()> {dispatcher: load.dispatcher,peer_index: load.peer_index,peer_count: load.peer_count,+ routing: load.routing,events: recorder.backlog(),}))};@@ -544,8 +545,21 @@ fn build_debug_load(None => (None, None),};let dispatcher_load = dispatcher.debug_load();- let workers = registry- .health_snapshots()+ // One registry pass feeds the worker rows AND the routing ring/slice, so a+ // worker joining or changing health mid-request can't make the payload+ // show slice badges that contradict the worker table.+ let snapshots = registry.health_snapshots();+ let ring_workers: Vec<WorkerId> = snapshots+ .iter()+ .map(|snap| WorkerId::from(snap.url.as_str()))+ .collect();+ let healthy: Vec<WorkerId> = snapshots+ .iter()+ .filter(|snap| snap.routable)+ .map(|snap| WorkerId::from(snap.url.as_str()))+ .collect();+ let routing = dispatcher.debug_routing(ring_workers, &healthy);+ let workers = snapshots.into_iter().map(|snap| {let in_flight_messages = dispatcher_load@@ -571,5 +585,6 @@ fn build_debug_load(dispatcher: dispatcher_load,peer_index,peer_count,+ routing,}}diff --git a/rust/ingestion-consumer/src/routing.rs b/rust/ingestion-consumer/src/routing.rsindex 006db9a6e078..f07a7234a4d9 100644--- a/rust/ingestion-consumer/src/routing.rs+++ b/rust/ingestion-consumer/src/routing.rs@@ -52,6 +52,17 @@ impl FromStr for RoutingStrategy {}}+impl RoutingStrategy {+ /// Canonical config-string form, as accepted by [`FromStr`].+ pub fn as_str(&self) -> &'static str {+ match self {+ RoutingStrategy::BinPack => "binpack",+ RoutingStrategy::P2c => "p2c",+ RoutingStrategy::Aperture => "aperture",+ }+ }+}+/// 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>;diff --git a/rust/ingestion-consumer/src/worker_registry.rs b/rust/ingestion-consumer/src/worker_registry.rsindex 4fcbdba19fe5..a64ca493a9d8 100644--- a/rust/ingestion-consumer/src/worker_registry.rs+++ b/rust/ingestion-consumer/src/worker_registry.rs@@ -103,6 +103,13 @@ impl WorkerHealth {self.drain_deadline.is_some()}+ /// Whether this worker is currently eligible for routing: Healthy or+ /// Degraded, and not draining. The single definition behind both+ /// [`WorkerRegistry::healthy_workers`] and the debug snapshot.+ fn is_routable(&self) -> bool {+ !self.is_draining() && matches!(self.state, WorkerState::Healthy | WorkerState::Degraded)+ }+/// Attempt a state transition. Returns true if the transition happened.////// Transitions to the same state are ignored. Transitions within@@ -294,6 +301,7 @@ impl WorkerRegistry {url,state: health.state.as_str().to_string(),draining: health.is_draining(),+ routable: health.is_routable(),consecutive_probe_failures: health.consecutive_probe_failures,passive_error_rate,passive_samples,@@ -316,13 +324,7 @@ impl WorkerRegistry {pub fn healthy_workers(&self) -> Vec<WorkerId> {self.workers.iter()- .filter(|e| {- !e.value().is_draining()- && matches!(- e.value().state,- WorkerState::Healthy | WorkerState::Degraded- )- })+ .filter(|e| e.value().is_routable()).map(|e| e.key().clone()).collect()}diff --git a/rust/ingestion-control-plane/src/ui/consumer_debug.html b/rust/ingestion-control-plane/src/ui/consumer_debug.htmlindex 4e022899fc79..78d2f6e6b29d 100644--- a/rust/ingestion-control-plane/src/ui/consumer_debug.html+++ b/rust/ingestion-control-plane/src/ui/consumer_debug.html@@ -150,6 +150,7 @@<header><h1>Ingestion consumer</h1><span class="meta" id="group">group —</span>+ <span class="meta" id="routing">routing —</span><span class="meta"><span class="dot down" id="conn-dot"></span><span id="conn">connecting…</span></span></header>@@ -271,6 +272,21 @@try { s = await (await fetch("debug/load")).json(); } catch (e) { return; }$("group").textContent = "group " + s.group_id;+ // Routing summary: strategy, and under aperture this pod's peer+ // position plus its current ring slice (or the full-pool fallback).+ const r = s.routing || {};+ let routingText = "routing " + (r.strategy || "—");+ if (r.strategy === "aperture") {+ routingText += s.peer_index != null && s.peer_count+ ? ` · peer ${s.peer_index + 1}/${s.peer_count}`+ : " · peers unknown";+ routingText += r.slice+ ? ` · slice ${r.slice.length}/${r.ring.length}`+ : " · full-pool fallback";+ }+ $("routing").textContent = routingText;+ const sliceSet = new Set(r.slice || []);+const d = s.dispatcher;// In-flight is transient (a batch is assigned→sent→resolved in ms), so a// single sample often reads 0. Hold the peak over a short window so the@@ -295,8 +311,9 @@const label = w.draining ? "draining" : w.state;const pct = Math.round((w.in_flight_messages / maxLoad) * 100);const rate = (w.passive_error_rate * 100).toFixed(0) + "%";+ const slice = sliceSet.has(w.url) ? ` <span class="badge-min" title="in this dispatcher's aperture slice">slice</span>` : "";return `<tr>- <td class="mono">${shortWorker(w.url)}</td>+ <td class="mono">${shortWorker(w.url)}${slice}</td><td><span class="pill ${cls}">${label}</span></td><td class="mono"><div style="display:flex;align-items:center;gap:8px;"><div class="bar" style="width:${pct}%"></div><span>${w.in_flight_messages}</span></div></td>