: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): expose real-time debug API from rust ingestion consumer (#70667)
José Sequeirad81afd05fc76
diff --git a/rust/ingestion-consumer/README.md b/rust/ingestion-consumer/README.mdindex e53ef05050d1..f510e5fc4cdf 100644--- a/rust/ingestion-consumer/README.md+++ b/rust/ingestion-consumer/README.md@@ -27,6 +27,18 @@ It measures the invariant at its end point: the worker's grouping stage processeRebalances reset all baselines (`ingestion_consumer_rebalances_total{event}` counts them), so partition handoffs don't fire false positives.Null-key messages (e.g. overflow rerouting) are excluded from the consumer-side key checks: the producer deliberately spreads such a routing key across partitions, forfeiting per-key order, so offsets from different partitions are not comparable and there is no invariant to check. The worker-side check is unaffected — it scopes keys per partition, an invariant that holds for all traffic.+## Debug API++Set `DEBUG_API_ENABLED=true` **and** `DEBUG_API_SECRET` to mount a real-time debug API on the health server (default `:3301`), for dev and incident debugging; off by default.+Every request must present the secret as `X-Debug-Api-Secret`; enabling without a secret fails closed (nothing is mounted).+The secret is dedicated to this control-plane→consumer hop — deliberately not `INTERNAL_API_SECRET` (see `.agents/security.md`).+The ingestion control plane UI consumes these endpoints to render the consumer's live state.+`debug_recorder.rs` keeps a bounded in-memory buffer of structured lifecycle events — batch dispatch/assignment/commit, deferrals and flushes, send retries/exhaustion, worker health and membership — recorded at the same points that emit metrics, and it never influences routing.++- `/debug/load` — cheap JSON snapshot (worker health + dispatcher in-flight/pins/stash), safe to poll fast.+- `/debug/state` — the same plus the retained event backlog.+- `/debug/events` — SSE stream: backlog replay, then live events (concurrent subscribers capped at 8; 429 beyond).+## Testing- `cargo test -p ingestion-consumer --lib` — unit tests.diff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rsindex 981643d7f7dc..f38998086c6c 100644--- a/rust/ingestion-consumer/src/config.rs+++ b/rust/ingestion-consumer/src/config.rs@@ -133,6 +133,23 @@ pub struct Config {#[envconfig(from = "CONSUMER_MAX_BACKGROUND_TASKS", default = "1")]pub consumer_max_background_tasks: usize,+ // ---- Debug API ----+ /// Serve the real-time debug API (`/debug/load`, `/debug/state`,+ /// `/debug/events` SSE) on the health server, recording structured events+ /// (batch lifecycle, deferrals, retries, worker health) into a bounded+ /// in-memory buffer. Consumed by the ingestion control plane UI. A pure+ /// observer for dev and incident debugging; off by default. Requires+ /// DEBUG_API_SECRET — enabling without a secret mounts nothing.+ #[envconfig(from = "DEBUG_API_ENABLED", default = "false")]+ pub debug_api_enabled: bool,++ /// Shared secret callers must present as `X-Debug-Api-Secret` on every+ /// `/debug/*` request. Dedicated to this one control-plane→consumer hop+ /// (deliberately not `INTERNAL_API_SECRET` — see .agents/security.md).+ /// Empty fails closed: the debug API is not mounted without it.+ #[envconfig(from = "DEBUG_API_SECRET", default = "")]+ pub debug_api_secret: String,+// ---- Ordering sentinels ----/// Kill switch for the ordering sentinels (per-partition commit/// contiguity/monotonicity checks and per-key send-order checks). They arediff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rsindex 988dbe50a758..f4d6d5b1c693 100644--- a/rust/ingestion-consumer/src/consumer.rs+++ b/rust/ingestion-consumer/src/consumer.rs@@ -12,6 +12,7 @@ use tokio::task::JoinHandle;use tracing::{error, info, warn};use crate::config::Config;+use crate::debug_recorder::{record_if, DebugEventKind, DebugRecorder, PartitionOffset};use crate::discovery::DiscoveryMode;use crate::dispatcher::{Dispatcher, SubBatch};use crate::order_sentinel::{CommitSentinel, OffsetSpan, SentinelContext};@@ -76,6 +77,8 @@ pub struct IngestionConsumerOptions {/// deferred groups before failing the batch. `new` takes it from/// `CONSUMER_DEFERRED_FLUSH_TIMEOUT_MS` (default 60s).pub deferred_flush_timeout: Duration,+ /// Debug event recorder; `None` unless `DEBUG_API_ENABLED`.+ pub debug_recorder: Option<Arc<DebugRecorder>>,}/// The main consumer loop: reads from Kafka, routes messages by distinct_id@@ -95,6 +98,8 @@ pub struct IngestionConsumer {/// Validates commit contiguity/monotonicity per partition. Shared with the/// consumer's [`SentinelContext`], which resets baselines on rebalance.commit_sentinel: Arc<CommitSentinel>,+ /// Debug event recorder; `None` unless `DEBUG_API_ENABLED`.+ debug_recorder: Option<Arc<DebugRecorder>>,}impl IngestionConsumer {@@ -113,6 +118,7 @@ impl IngestionConsumer {let commit_sentinel = consumer.context().commit_sentinel();Self {commit_sentinel,+ debug_recorder: options.debug_recorder,consumer: Arc::new(consumer),dispatcher,transport,@@ -131,6 +137,7 @@ impl IngestionConsumer {dispatcher: Arc<Dispatcher>,transport: Arc<HttpTransport>,handle: Handle,+ debug_recorder: Option<Arc<DebugRecorder>>,) -> anyhow::Result<Self> {// In endpointslice mode the worker set comes from discovery, so there is// no static readiness list — main gates startup on the first discovered@@ -164,6 +171,7 @@ impl IngestionConsumer {Ok(Self {consumer: Arc::new(consumer),commit_sentinel,+ debug_recorder,dispatcher,transport,worker_urls,@@ -196,6 +204,10 @@ impl IngestionConsumer {}info!("Consumer loop starting");+ record_if(&self.debug_recorder, || DebugEventKind::ConsumerStarted {+ group_id: self.group_id.clone(),+ workers: self.worker_urls.clone(),+ });// Verify async commits actually land: librdkafka drops the result of// manual async commits (see the note on SentinelContext), so poll the@@ -262,6 +274,11 @@ impl IngestionConsumer {fn spawn_batch_processing(&self, collected: CollectedBatch) -> InFlightBatch {let batch_size = collected.messages.len();let batch_id = make_batch_id();+ record_if(&self.debug_recorder, || DebugEventKind::BatchDispatched {+ batch_id: batch_id.clone(),+ messages: batch_size,+ partitions: debug_partition_offsets(&collected.offsets, &collected.stats.max_lag_ms),+ });let task_batch_id = batch_id.clone();let dispatcher = Arc::clone(&self.dispatcher);let transport = Arc::clone(&self.transport);@@ -319,6 +336,12 @@ impl IngestionConsumer {// delivery across worker or pipeline failures.self.commit_offsets(&processed.offsets)?;emit_latest_processed_timestamp_metrics(&processed.stats, &self.group_id);+ record_if(&self.debug_recorder, || DebugEventKind::BatchCommitted {+ batch_id: batch_id.clone(),+ accepted: processed.total_accepted,+ duration_ms: processed.elapsed.as_millis() as u64,+ partitions: debug_partition_offsets(&processed.offsets, &processed.stats.max_lag_ms),+ });histogram!("ingestion_consumer_batch_processing_duration_seconds").record(processed.elapsed.as_secs_f64());@@ -397,6 +420,10 @@ impl IngestionConsumer {fn fail_batch_processing(&self, err: anyhow::Error) {error!(error = %err, "Batch processing failed");counter!("ingestion_consumer_batch_errors_total").increment(1);+ record_if(&self.debug_recorder, || DebugEventKind::BatchFailed {+ batch_id: None,+ error: format!("{err:#}"),+ });self.handle.signal_failure(format!("Batch processing failed: {err:#}"));}@@ -693,6 +720,25 @@ impl IngestionConsumer {}}+/// Per-partition max offset + observed lag for the debug UI's batch events.+fn debug_partition_offsets(+ offsets: &HashMap<(String, i32), OffsetSpan>,+ max_lag_ms: &HashMap<(String, i32), i64>,+) -> Vec<PartitionOffset> {+ offsets+ .iter()+ .map(|((topic, partition), span)| PartitionOffset {+ topic: topic.clone(),+ partition: *partition,+ offset: span.last,+ lag_ms: max_lag_ms+ .get(&(topic.clone(), *partition))+ .copied()+ .unwrap_or(0),+ })+ .collect()+}+/// Aborts the wrapped task when dropped, covering every `process()` exit path.struct AbortOnDrop(JoinHandle<()>);diff --git a/rust/ingestion-consumer/src/debug_recorder.rs b/rust/ingestion-consumer/src/debug_recorder.rsnew file mode 100644index 000000000000..eb41e4561637--- /dev/null+++ b/rust/ingestion-consumer/src/debug_recorder.rs@@ -0,0 +1,306 @@+//! In-memory event recorder powering the real-time debug API (consumed by the+//! ingestion control plane UI).+//!+//! When `DEBUG_API_ENABLED` is set, an `Arc<DebugRecorder>` is injected into+//! the dispatcher, consumer, transport, and worker registry. Each records a+//! structured [`DebugEvent`] at the same points it already emits metrics —+//! batch assignment, sub-batch resolution, deferral/flush, retries, worker+//! health transitions. The recorder keeps a bounded rolling window of recent+//! events (for a client connecting mid-stream to see history) and broadcasts+//! every new event to live subscribers (the SSE feed at `/debug/events`).+//!+//! It is a pure observer: it never influences routing. When the feature is off,+//! the recorder is `None` everywhere and nothing is constructed or recorded.++use std::collections::VecDeque;+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::{Arc, Mutex};+use std::time::{Duration, SystemTime, UNIX_EPOCH};++use serde::Serialize;+use tokio::sync::broadcast;++/// One worker's slice of an assigned (or flushed) batch.+#[derive(Clone, Serialize)]+pub struct SubBatchInfo {+ pub worker: String,+ pub messages: usize,+ pub distinct_ids: usize,+}++/// A topic-partition and the batch's max offset there, with observed lag.+#[derive(Clone, Serialize)]+pub struct PartitionOffset {+ pub topic: String,+ pub partition: i32,+ pub offset: i64,+ pub lag_ms: i64,+}++/// The distinct event kinds recorded across the consumer's lifecycle. Serialized+/// with an internal `type` tag so the UI can switch on it.+#[derive(Clone, Serialize)]+#[serde(tag = "type")]+pub enum DebugEventKind {+ /// Consumer loop started — doubles as a restart marker (the buffer is empty+ /// after a process restart, and this is the first event the UI sees).+ ConsumerStarted {+ group_id: String,+ workers: Vec<String>,+ },+ /// A Kafka batch was collected and handed to a processing task.+ BatchDispatched {+ batch_id: String,+ messages: usize,+ partitions: Vec<PartitionOffset>,+ },+ /// The dispatcher grouped a batch by routing key and assigned sub-batches.+ BatchAssigned {+ batch_id: String,+ distinct_ids: usize,+ sub_batches: Vec<SubBatchInfo>,+ deferred_groups: u64,+ unroutable_groups: u64,+ },+ /// A sub-batch resolved (ACK), releasing the worker's outstanding load.+ SubBatchResolved {+ worker: String,+ messages: usize,+ distinct_ids: usize,+ cleared_deferral: bool,+ },+ /// Messages were stashed rather than sent (`reason`: drain/unroutable/send_failed).+ Deferred {+ batch_id: String,+ reason: &'static str,+ groups: u64,+ },+ /// Previously-deferred groups were re-routed to healthy workers.+ DeferredFlushed {+ batch_id: String,+ sub_batches: Vec<SubBatchInfo>,+ },+ /// A batch's offsets were committed to Kafka.+ BatchCommitted {+ batch_id: String,+ accepted: u32,+ duration_ms: u64,+ partitions: Vec<PartitionOffset>,+ },+ /// Batch processing failed; the process will exit and restart.+ BatchFailed {+ batch_id: Option<String>,+ error: String,+ },+ /// A send to a worker was retried (`reason`: busy/error).+ SendRetry {+ worker: String,+ batch_id: String,+ attempt: u32,+ reason: &'static str,+ },+ /// A send exhausted its retries; the messages are deferred for replay.+ SendExhausted {+ worker: String,+ batch_id: String,+ messages: usize,+ error: String,+ },+ /// A worker moved between health states.+ WorkerStateChanged {+ worker: String,+ from: &'static str,+ to: &'static str,+ },+ /// A worker joined, drained, or left the pool (`action`: add/drain/remove).+ WorkerMembership {+ worker: String,+ action: &'static str,+ },+}++/// A recorded event with a monotonic sequence number and wall-clock timestamp.+#[derive(Clone, Serialize)]+pub struct DebugEvent {+ pub seq: u64,+ pub ts_ms: u64,+ #[serde(flatten)]+ pub kind: DebugEventKind,+}++// ---- Point-in-time state snapshot (served at /debug/state) ----++/// One worker's health as seen by the registry.+#[derive(Serialize)]+pub struct WorkerHealthSnapshot {+ pub url: String,+ pub state: String,+ pub draining: bool,+ pub consecutive_probe_failures: u32,+ pub passive_error_rate: f64,+ pub passive_samples: usize,+}++/// Per-worker outstanding in-flight load.+#[derive(Serialize)]+pub struct LoadEntry {+ pub worker: String,+ pub in_flight: usize,+}++/// The dispatcher's current load/pin/stash accounting.+#[derive(Serialize)]+pub struct DispatcherLoad {+ pub per_worker: Vec<LoadEntry>,+ pub total_in_flight: usize,+ pub pin_count: usize,+ pub stashed_messages: usize,+ pub stashed_batches: usize,+}++/// Merged worker row: registry health plus the dispatcher's in-flight count.+#[derive(Serialize)]+pub struct WorkerStatus {+ pub url: String,+ pub state: String,+ pub draining: bool,+ pub consecutive_probe_failures: u32,+ pub passive_error_rate: f64,+ pub passive_samples: usize,+ pub in_flight_messages: usize,+}++/// The full snapshot returned by `/debug/state` (workers + load + event backlog).+#[derive(Serialize)]+pub struct DebugState {+ pub group_id: String,+ pub workers: Vec<WorkerStatus>,+ pub dispatcher: DispatcherLoad,+ pub events: Vec<DebugEvent>,+}++/// Lightweight snapshot returned by `/debug/load` — workers + dispatcher load+/// only, no event backlog, so the UI can poll it at a high rate cheaply.+#[derive(Serialize)]+pub struct DebugLoad {+ pub group_id: String,+ pub workers: Vec<WorkerStatus>,+ pub dispatcher: DispatcherLoad,+}++/// Bounded rolling event buffer plus a broadcast channel for live subscribers.+pub struct DebugRecorder {+ buffer: Mutex<VecDeque<DebugEvent>>,+ tx: broadcast::Sender<DebugEvent>,+ seq: AtomicU64,+ max_events: usize,+ window: Duration,+}++impl DebugRecorder {+ /// Create a recorder retaining at most `max_events` within `window`.+ pub fn new(max_events: usize, window: Duration) -> Arc<Self> {+ let (tx, _rx) = broadcast::channel(1024);+ Arc::new(Self {+ buffer: Mutex::new(VecDeque::new()),+ tx,+ seq: AtomicU64::new(0),+ max_events: max_events.max(1),+ window,+ })+ }++ /// Record an event: stamp it, evict anything past the count/time bounds, and+ /// broadcast to live subscribers. Cheap and non-blocking; a slow or absent+ /// subscriber never blocks the caller (broadcast drops for laggards).+ pub fn record(&self, kind: DebugEventKind) {+ let seq = self.seq.fetch_add(1, Ordering::Relaxed);+ let ts_ms = now_ms();+ let event = DebugEvent { seq, ts_ms, kind };++ {+ let mut buf = self.buffer.lock().unwrap();+ buf.push_back(event.clone());+ while buf.len() > self.max_events {+ buf.pop_front();+ }+ let cutoff = ts_ms.saturating_sub(self.window.as_millis() as u64);+ while buf.front().is_some_and(|e| e.ts_ms < cutoff) {+ buf.pop_front();+ }+ }++ // Ignore the error when there are no subscribers — the buffer still holds+ // the event for a client that connects later.+ let _ = self.tx.send(event);+ }++ /// Snapshot of the retained events, oldest first.+ pub fn backlog(&self) -> Vec<DebugEvent> {+ self.buffer.lock().unwrap().iter().cloned().collect()+ }++ /// Subscribe to the live event stream.+ pub fn subscribe(&self) -> broadcast::Receiver<DebugEvent> {+ self.tx.subscribe()+ }+}++/// Record an event iff a recorder is present. Takes a closure so callers pay+/// nothing to build the event payload when the debug UI is disabled.+pub fn record_if(recorder: &Option<Arc<DebugRecorder>>, event: impl FnOnce() -> DebugEventKind) {+ if let Some(recorder) = recorder {+ recorder.record(event());+ }+}++fn now_ms() -> u64 {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default()+ .as_millis() as u64+}++#[cfg(test)]+mod tests {+ use super::*;++ fn membership(action: &'static str) -> DebugEventKind {+ DebugEventKind::WorkerMembership {+ worker: "http://w:9001".to_string(),+ action,+ }+ }++ #[test]+ fn backlog_is_bounded_by_capacity_and_keeps_newest() {+ let rec = DebugRecorder::new(3, Duration::from_secs(300));+ for _ in 0..5 {+ rec.record(membership("add"));+ }+ let backlog = rec.backlog();+ // Only the 3 most recent survive, in order, and sequence numbers are+ // monotonic — so a client sees a contiguous recent window, not a gap.+ assert_eq!(backlog.len(), 3);+ assert_eq!(+ backlog.iter().map(|e| e.seq).collect::<Vec<_>>(),+ vec![2, 3, 4]+ );+ }++ #[test]+ fn subscribers_receive_events_recorded_after_subscribing() {+ let rec = DebugRecorder::new(10, Duration::from_secs(300));+ let mut rx = rec.subscribe();+ rec.record(membership("drain"));+ let event = rx.try_recv().expect("subscriber should receive the event");+ assert_eq!(event.seq, 0);+ assert!(matches!(+ event.kind,+ DebugEventKind::WorkerMembership {+ action: "drain",+ ..+ }+ ));+ }+}diff --git a/rust/ingestion-consumer/src/dispatcher.rs b/rust/ingestion-consumer/src/dispatcher.rsindex 6223c2b13a72..3c30f5e26df8 100644--- a/rust/ingestion-consumer/src/dispatcher.rs+++ b/rust/ingestion-consumer/src/dispatcher.rs@@ -3,6 +3,9 @@ use std::sync::{Arc, Mutex};use metrics::{counter, gauge, histogram};+use crate::debug_recorder::{+ record_if, DebugEventKind, DebugRecorder, DispatcherLoad, LoadEntry, SubBatchInfo,+};use crate::order_sentinel::KeyOrderSentinel;use crate::routing::{Router, RoutingStrategy, WorkerLoad};use crate::stash::{DeferredGroup, Stash};@@ -126,6 +129,18 @@ impl WorkerAssignments {builder.routing_keys.push(group.routing_key);}+ fn sub_batch_infos(&self) -> Vec<SubBatchInfo> {+ self.by_worker+ .iter()+ .filter(|(_, builder)| !builder.is_empty())+ .map(|(worker, builder)| SubBatchInfo {+ worker: worker.to_string(),+ messages: builder.message_count(),+ distinct_ids: builder.routing_keys.len(),+ })+ .collect()+ }+fn routed_counts(&self) -> impl Iterator<Item = (WorkerId, usize)> + '_ {self.by_worker.iter()@@ -170,6 +185,8 @@ 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>,+ /// Debug event recorder; `None` unless `DEBUG_API_ENABLED`.+ debug_recorder: Option<Arc<DebugRecorder>>,}impl Dispatcher {@@ -185,6 +202,7 @@ impl Dispatcher {registry,router: Mutex::new(Router::new(strategy)),key_sentinel: Arc::new(KeyOrderSentinel::new()),+ debug_recorder: None,}}@@ -200,6 +218,7 @@ impl Dispatcher {registry,router: Mutex::new(Router::with_seed(strategy, seed)),key_sentinel: Arc::new(KeyOrderSentinel::new()),+ debug_recorder: None,}}@@ -209,6 +228,31 @@ impl Dispatcher {Arc::clone(&self.key_sentinel)}+ /// 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);+ }++ /// Point-in-time load/pin/stash snapshot for the debug UI.+ pub fn debug_load(&self) -> DispatcherLoad {+ let table = self.pin_table.lock().unwrap();+ let per_worker: Vec<LoadEntry> = table+ .in_flight+ .iter()+ .map(|(worker, in_flight)| LoadEntry {+ worker: worker.to_string(),+ in_flight: *in_flight,+ })+ .collect();+ DispatcherLoad {+ total_in_flight: per_worker.iter().map(|e| e.in_flight).sum(),+ per_worker,+ pin_count: table.pins.len(),+ stashed_messages: table.stash.message_count(),+ stashed_batches: table.stash.batch_count(),+ }+ }+/// Assign a batch of messages to workers.////// Groups messages by routing key, then per group:@@ -235,7 +279,8 @@ impl Dispatcher {.increment(missing_header_count);}- histogram!("ingestion_consumer_distinct_ids_per_batch").record(key_groups.len() as f64);+ let distinct_ids = key_groups.len();+ histogram!("ingestion_consumer_distinct_ids_per_batch").record(distinct_ids as f64);let mut assignments = WorkerAssignments::new();@@ -373,6 +418,28 @@ impl Dispatcher {gauge!("ingestion_consumer_dispatcher_pins_total").set(table.pins.len() as f64);record_stash_gauges(&table.stash);+ if deferred_count > 0 {+ record_if(&self.debug_recorder, || DebugEventKind::Deferred {+ batch_id: batch_id.to_string(),+ reason: "drain",+ groups: deferred_count,+ });+ }+ if unroutable_deferred_count > 0 {+ record_if(&self.debug_recorder, || DebugEventKind::Deferred {+ batch_id: batch_id.to_string(),+ reason: "unroutable",+ groups: unroutable_deferred_count,+ });+ }+ record_if(&self.debug_recorder, || DebugEventKind::BatchAssigned {+ batch_id: batch_id.to_string(),+ distinct_ids,+ sub_batches: assignments.sub_batch_infos(),+ deferred_groups: deferred_count,+ unroutable_groups: unroutable_deferred_count,+ });+assignments.into_sub_batches()}@@ -436,6 +503,11 @@ impl Dispatcher {"reason" => "send_failed",).increment(deferred_count);+ record_if(&self.debug_recorder, || DebugEventKind::Deferred {+ batch_id: batch_id.to_string(),+ reason: "send_failed",+ groups: deferred_count,+ });}record_stash_gauges(&table.stash);}@@ -613,6 +685,14 @@ impl Dispatcher {}gauge!("ingestion_consumer_dispatcher_pins_total").set(table.pins.len() as f64);+ drop(table);++ record_if(&self.debug_recorder, || DebugEventKind::SubBatchResolved {+ worker: worker.to_string(),+ messages: message_count,+ distinct_ids: routing_keys.len(),+ cleared_deferral: clears_deferral,+ });}/// Record the outcome of a send attempt for passive health tracking.diff --git a/rust/ingestion-consumer/src/lib.rs b/rust/ingestion-consumer/src/lib.rsindex abf99ce87969..38a5a31f4675 100644--- a/rust/ingestion-consumer/src/lib.rs+++ b/rust/ingestion-consumer/src/lib.rs@@ -1,5 +1,6 @@pub mod config;pub mod consumer;+pub mod debug_recorder;pub mod discovery;pub mod dispatcher;pub mod kafka_config;diff --git a/rust/ingestion-consumer/src/main.rs b/rust/ingestion-consumer/src/main.rsindex f6f1faed1989..9b059f319282 100644--- a/rust/ingestion-consumer/src/main.rs+++ b/rust/ingestion-consumer/src/main.rs@@ -7,6 +7,7 @@ use axum::routing::get;use axum::Router;use envconfig::Envconfig;use futures::future::ready;+use futures::StreamExt;use lifecycle::{ComponentOptions, Manager};use metrics_exporter_prometheus::{Matcher, PrometheusBuilder};use tokio::net::TcpListener;@@ -19,6 +20,7 @@ use tracing_subscriber::{EnvFilter, Layer};use ingestion_consumer::config::Config;use ingestion_consumer::consumer::IngestionConsumer;+use ingestion_consumer::debug_recorder::{DebugLoad, DebugRecorder, DebugState, WorkerStatus};use ingestion_consumer::discovery::{DiscoveryMode, EndpointSliceDiscovery, StaticDiscovery, WorkerDiscovery,};@@ -150,19 +152,38 @@ async fn async_main(config: Config) -> Result<()> {let guard = manager.monitor_background();+ // Debug event recorder: a bounded in-memory event buffer plus live+ // broadcast, injected into every component below and served by the /debug+ // API (consumed by the ingestion control plane UI). `None` (the default)+ // records nothing. Fail closed: enabling without the dedicated secret+ // mounts nothing rather than exposing the API unauthenticated.+ let debug_recorder = if config.debug_api_enabled && !config.debug_api_secret.is_empty() {+ Some(DebugRecorder::new(5_000, Duration::from_secs(900)))+ } else {+ if config.debug_api_enabled {+ error!("DEBUG_API_ENABLED is set but DEBUG_API_SECRET is empty; debug API disabled");+ }+ None+ };+// Build the worker health registry empty; the discovery provider below// populates it (statically from config, or dynamically from EndpointSlices).let registry_config = WorkerRegistryConfig::from(&config);- let registry = Arc::new(WorkerRegistry::new(&[], registry_config));+ let mut registry = WorkerRegistry::new(&[], registry_config);+ if let Some(recorder) = &debug_recorder {+ registry.set_debug_recorder(Arc::clone(recorder));+ }+ let registry = Arc::new(registry);// Probe tasks run until shutdown.let probe_token = CancellationToken::new();Arc::clone(®istry).start_probing(probe_token.clone());- let dispatcher = Arc::new(Dispatcher::with_strategy(- Arc::clone(®istry),- config.routing_strategy,- ));+ let mut dispatcher = Dispatcher::with_strategy(Arc::clone(®istry), config.routing_strategy);+ if let Some(recorder) = &debug_recorder {+ dispatcher.set_debug_recorder(Arc::clone(recorder));+ }+ let dispatcher = Arc::new(dispatcher);let api_secret = if config.internal_api_secret.is_empty() {None@@ -170,13 +191,17 @@ async fn async_main(config: Config) -> Result<()> {Some(config.internal_api_secret.clone())};// Transport semaphores are created lazily per worker, so it starts empty.- let transport = Arc::new(HttpTransport::new(+ let mut transport = HttpTransport::new(Duration::from_millis(config.http_timeout_ms),config.max_retries,api_secret,&[],config.ingestion_worker_concurrent_batches,- ));+ );+ if let Some(recorder) = &debug_recorder {+ transport.set_debug_recorder(Arc::clone(recorder));+ }+ let transport = Arc::new(transport);// Select the worker discovery provider and start it (static applies the// configured list immediately; endpointslice watches and keeps in sync).@@ -262,6 +287,120 @@ async fn async_main(config: Config) -> Result<()> {app = app.route("/metrics", get(move || ready(handle.render())));}+ // Debug API: fast load snapshots, a full state snapshot, and the live SSE+ // event feed, consumed by the ingestion control plane UI. Only mounted+ // when DEBUG_API_ENABLED, and every request must present the dedicated+ // DEBUG_API_SECRET (the health server binds broadly by default, so the+ // routes must not be open to anything that can reach the port).+ if let Some(recorder) = &debug_recorder {+ let secret: Arc<str> = Arc::from(config.debug_api_secret.as_str());+ let group_id = config.ingestion_consumer_group_id.clone();+ {+ let registry = Arc::clone(®istry);+ let dispatcher = Arc::clone(&dispatcher);+ let group_id = group_id.clone();+ let secret = Arc::clone(&secret);+ app = app.route(+ "/debug/load",+ get(move |headers: axum::http::HeaderMap| {+ let result = if !debug_authorized(&headers, &secret) {+ Err(axum::http::StatusCode::UNAUTHORIZED)+ } else {+ Ok(axum::Json(build_debug_load(+ &group_id,+ ®istry,+ &dispatcher,+ )))+ };+ ready(result)+ }),+ );+ }+ {+ let recorder = Arc::clone(recorder);+ let registry = Arc::clone(®istry);+ let dispatcher = Arc::clone(&dispatcher);+ let group_id = group_id.clone();+ let secret = Arc::clone(&secret);+ app = app.route(+ "/debug/state",+ get(move |headers: axum::http::HeaderMap| {+ let result = if !debug_authorized(&headers, &secret) {+ Err(axum::http::StatusCode::UNAUTHORIZED)+ } else {+ let load = build_debug_load(&group_id, ®istry, &dispatcher);+ Ok(axum::Json(DebugState {+ group_id: load.group_id,+ workers: load.workers,+ dispatcher: load.dispatcher,+ events: recorder.backlog(),+ }))+ };+ ready(result)+ }),+ );+ }+ {+ let recorder = Arc::clone(recorder);+ let secret = Arc::clone(&secret);+ // Cap concurrent SSE subscribers: each replays the retained backlog+ // and then holds a connection open, so an unbounded count could+ // pressure the shared health server.+ let active_subscribers = Arc::new(std::sync::atomic::AtomicUsize::new(0));+ app = app.route(+ "/debug/events",+ get(move |headers: axum::http::HeaderMap| {+ let response = if !debug_authorized(&headers, &secret) {+ Err(axum::http::StatusCode::UNAUTHORIZED)+ } else if active_subscribers.fetch_add(1, std::sync::atomic::Ordering::SeqCst)+ >= MAX_SSE_SUBSCRIBERS+ {+ active_subscribers.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);+ Err(axum::http::StatusCode::TOO_MANY_REQUESTS)+ } else {+ // Decrements when the stream (and the closure owning the+ // guard) is dropped, covering client disconnects.+ let guard = SseSlotGuard(Arc::clone(&active_subscribers));+ // Subscribe BEFORE snapshotting the backlog so an event+ // recorded in between lands in the channel instead of+ // being missed; the seq filter below drops the overlap+ // (events present in both the backlog and the channel).+ let rx = recorder.subscribe();+ let backlog = recorder.backlog();+ let last_backlog_seq = backlog.last().map(|e| e.seq);+ let live = futures::stream::unfold(rx, |mut rx| async {+ loop {+ // A lagged subscriber skips dropped events+ // rather than dying.+ match rx.recv().await {+ Ok(event) => return Some((event, rx)),+ Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {+ continue+ }+ Err(tokio::sync::broadcast::error::RecvError::Closed) => {+ return None+ }+ }+ }+ })+ .filter(move |event| {+ ready(last_backlog_seq.is_none_or(|seq| event.seq > seq))+ });+ let stream = futures::stream::iter(backlog)+ .chain(live)+ .map(move |event| {+ let _held = &guard;+ axum::response::sse::Event::default().json_data(&event)+ });+ Ok(axum::response::Sse::new(stream)+ .keep_alive(axum::response::sse::KeepAlive::default()))+ };+ ready(response)+ }),+ );+ }+ }+let bind = config.bind_address();info!(address = %bind, "Health/metrics server starting");let listener = TcpListener::bind(&bind).await?;@@ -291,8 +430,14 @@ async fn async_main(config: Config) -> Result<()> {}}- let consumer = IngestionConsumer::new(&config, dispatcher, transport, consumer_handle)- .context("Failed to create Kafka consumer")?;+ let consumer = IngestionConsumer::new(+ &config,+ Arc::clone(&dispatcher),+ transport,+ consumer_handle,+ debug_recorder,+ )+ .context("Failed to create Kafka consumer")?;tokio::spawn(async move {consumer.process().await;@@ -306,3 +451,70 @@ async fn async_main(config: Config) -> Result<()> {info!("Ingestion consumer stopped");Ok(())}++/// Maximum concurrent `/debug/events` SSE subscribers.+const MAX_SSE_SUBSCRIBERS: usize = 8;++/// Releases an SSE subscriber slot when the stream is dropped.+struct SseSlotGuard(Arc<std::sync::atomic::AtomicUsize>);++impl Drop for SseSlotGuard {+ fn drop(&mut self) {+ self.0.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);+ }+}++/// Whether the request carries the dedicated debug API secret. The secret is+/// never empty here (an empty secret disables the API entirely).+fn debug_authorized(headers: &axum::http::HeaderMap, secret: &str) -> bool {+ headers+ .get("x-debug-api-secret")+ .and_then(|value| value.to_str().ok())+ .is_some_and(|presented| constant_time_eq(presented, secret))+}++/// Compare without short-circuiting on the first mismatched byte, so response+/// timing doesn't leak how much of the secret matched.+fn constant_time_eq(a: &str, b: &str) -> bool {+ let (a, b) = (a.as_bytes(), b.as_bytes());+ if a.len() != b.len() {+ return false;+ }+ a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0+}++/// Merge the registry's health snapshots with the dispatcher's in-flight load+/// into the `/debug/load` payload.+fn build_debug_load(+ group_id: &str,+ registry: &ingestion_consumer::worker_registry::WorkerRegistry,+ dispatcher: &Dispatcher,+) -> DebugLoad {+ let dispatcher_load = dispatcher.debug_load();+ let workers = registry+ .health_snapshots()+ .into_iter()+ .map(|snap| {+ let in_flight_messages = dispatcher_load+ .per_worker+ .iter()+ .find(|entry| entry.worker == snap.url)+ .map(|entry| entry.in_flight)+ .unwrap_or(0);+ WorkerStatus {+ url: snap.url,+ state: snap.state,+ draining: snap.draining,+ consecutive_probe_failures: snap.consecutive_probe_failures,+ passive_error_rate: snap.passive_error_rate,+ passive_samples: snap.passive_samples,+ in_flight_messages,+ }+ })+ .collect();+ DebugLoad {+ group_id: group_id.to_string(),+ workers,+ dispatcher: dispatcher_load,+ }+}diff --git a/rust/ingestion-consumer/src/transport.rs b/rust/ingestion-consumer/src/transport.rsindex cd7abc98bb1a..f729d84b2177 100644--- a/rust/ingestion-consumer/src/transport.rs+++ b/rust/ingestion-consumer/src/transport.rs@@ -7,6 +7,7 @@ use rand::Rng;use tokio::sync::Semaphore;use tracing::{error, info, warn};+use crate::debug_recorder::{record_if, DebugEventKind, DebugRecorder};use crate::types::{IngestBatchRequest, IngestBatchResponse, SerializedKafkaMessage};/// RAII guard that tracks the number of batches currently in flight to a@@ -61,6 +62,8 @@ pub struct HttpTransport {/// Process-unique sender id stamped on every request, so the worker-side/// feed-order sentinel can rebaseline when the consumer restarts.consumer_id: String,+ /// Debug event recorder; `None` unless `DEBUG_API_ENABLED`.+ debug_recorder: Option<Arc<DebugRecorder>>,}impl HttpTransport {@@ -99,9 +102,15 @@ impl HttpTransport {worker_semaphores,worker_concurrent_batches,consumer_id: make_consumer_id(),+ debug_recorder: None,}}+ /// Inject the debug UI recorder. Call before the transport is shared.+ pub fn set_debug_recorder(&mut self, recorder: Arc<DebugRecorder>) {+ self.debug_recorder = Some(recorder);+ }+/// Get the worker's concurrency semaphore, creating it on first use so the/// transport serves workers added at runtime without explicit registration.fn semaphore_for(&self, worker_url: &str) -> Arc<Semaphore> {@@ -231,6 +240,12 @@ impl HttpTransport {"reason" => if last_was_busy { "busy" } else { "error" },).increment(1);+ record_if(&self.debug_recorder, || DebugEventKind::SendRetry {+ worker: worker_url.to_string(),+ batch_id: batch_id.to_string(),+ attempt,+ reason: if last_was_busy { "busy" } else { "error" },+ });}let start = std::time::Instant::now();@@ -295,6 +310,12 @@ impl HttpTransport {);counter!("ingestion_consumer_transport_exhausted_total", "worker" => worker_url.to_string()).increment(1);+ record_if(&self.debug_recorder, || DebugEventKind::SendExhausted {+ worker: worker_url.to_string(),+ batch_id: batch_id.to_string(),+ messages: message_count,+ error: err.to_string(),+ });Err(SendError {error: err,messages: request.messages,diff --git a/rust/ingestion-consumer/src/worker_registry.rs b/rust/ingestion-consumer/src/worker_registry.rsindex 406fd6daea4a..4fcbdba19fe5 100644--- a/rust/ingestion-consumer/src/worker_registry.rs+++ b/rust/ingestion-consumer/src/worker_registry.rs@@ -9,6 +9,7 @@ use tokio_util::sync::CancellationToken;use tracing::{info, warn};use crate::config::Config;+use crate::debug_recorder::{record_if, DebugEventKind, DebugRecorder, WorkerHealthSnapshot};const PASSIVE_WINDOW_MAX_ENTRIES: usize = 10_000;@@ -112,6 +113,7 @@ impl WorkerHealth {new_state: WorkerState,min_state_duration: Duration,worker_url: &str,+ recorder: &Option<Arc<DebugRecorder>>,) -> bool {if self.state == new_state {return false;@@ -151,6 +153,11 @@ impl WorkerHealth {).increment(1);set_state_gauge(worker_url, new_state);+ record_if(recorder, || DebugEventKind::WorkerStateChanged {+ worker: worker_url.to_string(),+ from: old_state.as_str(),+ to: new_state.as_str(),+ });true}@@ -238,6 +245,8 @@ pub struct WorkerRegistry {workers: DashMap<WorkerId, WorkerHealth>,config: WorkerRegistryConfig,client: reqwest::Client,+ /// Debug event recorder; `None` unless `DEBUG_API_ENABLED`.+ debug_recorder: Option<Arc<DebugRecorder>>,}impl WorkerRegistry {@@ -261,9 +270,38 @@ impl WorkerRegistry {workers,config,client,+ debug_recorder: None,}}+ /// Inject the debug UI recorder. Call before the registry is shared.+ pub fn set_debug_recorder(&mut self, recorder: Arc<DebugRecorder>) {+ self.debug_recorder = Some(recorder);+ }++ /// Per-worker health snapshot for the debug UI. Prunes each worker's+ /// passive window as a side effect (same as the metrics path).+ pub fn health_snapshots(&self) -> Vec<WorkerHealthSnapshot> {+ let passive_window = self.config.passive_window;+ self.workers+ .iter_mut()+ .map(|mut entry| {+ let url = entry.key().to_string();+ let health = entry.value_mut();+ let (passive_error_rate, passive_samples) =+ health.passive_error_rate(passive_window);+ WorkerHealthSnapshot {+ url,+ state: health.state.as_str().to_string(),+ draining: health.is_draining(),+ consecutive_probe_failures: health.consecutive_probe_failures,+ passive_error_rate,+ passive_samples,+ }+ })+ .collect()+ }+pub fn worker_count(&self) -> usize {self.workers.len()}@@ -329,6 +367,10 @@ impl WorkerRegistry {slot.insert(WorkerHealth::new());counter!("ingestion_consumer_worker_membership_total", "action" => "add").increment(1);+ record_if(&self.debug_recorder, || DebugEventKind::WorkerMembership {+ worker: worker.to_string(),+ action: "add",+ });}}}@@ -348,6 +390,10 @@ impl WorkerRegistry {info!(worker = %worker, "Worker draining (no new work; finishing in-flight)");counter!("ingestion_consumer_worker_membership_total", "action" => "drain").increment(1);+ record_if(&self.debug_recorder, || DebugEventKind::WorkerMembership {+ worker: worker.to_string(),+ action: "drain",+ });}}@@ -396,6 +442,10 @@ impl WorkerRegistry {info!(worker = %worker, "Worker removed from pool");counter!("ingestion_consumer_worker_membership_total", "action" => "remove").increment(1);+ record_if(&self.debug_recorder, || DebugEventKind::WorkerMembership {+ worker: worker.to_string(),+ action: "remove",+ });}}@@ -426,7 +476,12 @@ impl WorkerRegistry {WorkerState::Unhealthy => None,};if let Some(new_state) = target {- health.try_transition(new_state, self.config.min_state_duration, worker);+ health.try_transition(+ new_state,+ self.config.min_state_duration,+ worker,+ &self.debug_recorder,+ );}}}@@ -493,7 +548,12 @@ impl WorkerRegistry {WorkerState::Healthy => None,};if let Some(s) = new_state {- health.try_transition(s, self.config.min_state_duration, worker);+ health.try_transition(+ s,+ self.config.min_state_duration,+ worker,+ &self.debug_recorder,+ );}} else {health.consecutive_probe_failures += 1;@@ -507,6 +567,7 @@ impl WorkerRegistry {WorkerState::Unhealthy,self.config.min_state_duration,worker,+ &self.debug_recorder,);}}@@ -634,7 +695,7 @@ mod tests {let mut health = registry.workers.get_mut(W1).unwrap();health.consecutive_probe_failures = 2;- let transitioned = health.try_transition(WorkerState::Unhealthy, Duration::ZERO, W1);+ let transitioned = health.try_transition(WorkerState::Unhealthy, Duration::ZERO, W1, &None);assert!(transitioned);assert_eq!(health.state, WorkerState::Unhealthy);@@ -646,10 +707,10 @@ mod tests {let registry = WorkerRegistry::new(&one_worker(), no_cooldown_config());let mut health = registry.workers.get_mut(W1).unwrap();- health.try_transition(WorkerState::Unhealthy, Duration::ZERO, W1);+ health.try_transition(WorkerState::Unhealthy, Duration::ZERO, W1, &None);assert_eq!(health.state, WorkerState::Unhealthy);- let transitioned = health.try_transition(WorkerState::Degraded, Duration::ZERO, W1);+ let transitioned = health.try_transition(WorkerState::Degraded, Duration::ZERO, W1, &None);assert!(transitioned);assert_eq!(health.state, WorkerState::Degraded);@@ -938,7 +999,7 @@ mod tests {let registry = WorkerRegistry::new(&one_worker(), no_cooldown_config());let mut health = registry.workers.get_mut(W1).unwrap();- let transitioned = health.try_transition(WorkerState::Healthy, Duration::ZERO, W1);+ let transitioned = health.try_transition(WorkerState::Healthy, Duration::ZERO, W1, &None);assert!(!transitioned);assert_eq!(health.state, WorkerState::Healthy);diff --git a/rust/ingestion-consumer/tests/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rsindex a8efe2ac2ed6..be186d55b732 100644--- a/rust/ingestion-consumer/tests/e2e_integration_test.rs+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs@@ -484,6 +484,7 @@ impl Harness {max_in_flight_batches: max_in_flight,group_id: "e2e-test".to_string(),deferred_flush_timeout,+ debug_recorder: None,},handle,);@@ -558,6 +559,7 @@ impl Harness {max_in_flight_batches: self.max_in_flight,group_id: "e2e-test".to_string(),deferred_flush_timeout: self.deferred_flush_timeout,+ debug_recorder: None,},handle,);@@ -2029,6 +2031,7 @@ async fn second_consumer_joining_the_group_preserves_all_messages() {max_in_flight_batches: 1,group_id: "e2e-test".to_string(),deferred_flush_timeout: Duration::from_secs(60),+ debug_recorder: None,},handle2,);@@ -2103,6 +2106,7 @@ async fn fenced_static_member_exits_on_fatal_error() {max_in_flight_batches: 1,group_id: "e2e-test".to_string(),deferred_flush_timeout: Duration::from_secs(60),+ debug_recorder: None,},handle,);