: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): discover pods and kafka targets in control plane (#70828)
José Sequeira6df5920e5e64
diff --git a/rust/common/k8s-awareness/src/discovery.rs b/rust/common/k8s-awareness/src/discovery.rsindex 6d9d30412383..69f77a14fa77 100644--- a/rust/common/k8s-awareness/src/discovery.rs+++ b/rust/common/k8s-awareness/src/discovery.rs@@ -113,6 +113,7 @@ fn is_not_found(e: &kube::Error) -> bool {#[derive(Debug, Clone, Serialize)]pub struct DiscoveredPod {pub name: String,+ pub namespace: String,pub ip: Option<String>,pub node: Option<String>,pub phase: Option<String>,@@ -140,6 +141,7 @@ impl From<Pod> for DiscoveredPod {.sum();Self {name: pod.metadata.name.unwrap_or_default(),+ namespace: pod.metadata.namespace.unwrap_or_default(),ip: status.pod_ip,node: pod.spec.and_then(|s| s.node_name),phase: status.phase,@@ -185,6 +187,7 @@ mod tests {let pod: Pod = serde_json::from_value(serde_json::json!({"metadata": {"name": "consumer-abc",+ "namespace": "ingestion-analytics-main","labels": {"app": "ingestion-analytics-main", "pod-template-hash": "x1"}},"spec": {"nodeName": "node-1", "containers": []},@@ -203,6 +206,7 @@ mod tests {let discovered = DiscoveredPod::from(pod);assert_eq!(discovered.name, "consumer-abc");+ assert_eq!(discovered.namespace, "ingestion-analytics-main");assert_eq!(discovered.ip.as_deref(), Some("10.0.0.7"));assert_eq!(discovered.node.as_deref(), Some("node-1"));assert_eq!(discovered.phase.as_deref(), Some("Running"));diff --git a/rust/ingestion-control-plane/README.md b/rust/ingestion-control-plane/README.mdindex 162d4de0fac9..8132edd59eff 100644--- a/rust/ingestion-control-plane/README.md+++ b/rust/ingestion-control-plane/README.md@@ -8,7 +8,7 @@ Internal web tool for the ingestion team. Single binary serving an embedded UI,### Lagging partitions-Scans every configured consumer group (committed offsets vs watermarks) and sorts by total outstanding messages. Drilling into a group shows per-partition lag; from there an analysis job reads a slice of the partition and aggregates **message headers only** (payloads are dropped, only their size is recorded):+Discovers ingestion topics and consumer groups from the cluster by prefix (a group maps to the topics it has committed offsets on — no per-environment target config), scans committed offsets vs watermarks, and sorts by total outstanding messages. Drilling into a group shows per-partition lag; from there an analysis job reads a slice of the partition and aggregates **message headers only** (payloads are dropped, only their size is recorded):- `head` mode starts at the group's committed offset — what the consumer is stuck on.- `tail` mode samples the newest messages before the high watermark — what's arriving now.@@ -17,7 +17,7 @@ Results are broken down per token (resolved to `team_id` via Postgres when `DATA### Consumer debug-Lists live ingestion-consumer pods and serves the consumer's routing debug UI per pod at `/pods/<name>/`, backed by a proxy to the pod's debug API (`/debug/state`, `/debug/load`, SSE `/debug/events`). The UI lives here; the consumer only exposes the JSON/SSE API (gated behind `DEBUG_UI_ENABLED` on the consumer side).+Lists live ingestion-consumer pods and serves the consumer's routing debug UI per pod at `/pods/<namespace>/<name>/` (static pods use the `static` pseudo-namespace), backed by a proxy to the pod's debug API (`/debug/state`, `/debug/load`, SSE `/debug/events`). The UI lives here; the consumer only exposes the JSON/SSE API (gated behind `DEBUG_UI_ENABLED` on the consumer side).## Configuration@@ -26,15 +26,18 @@ Lists live ingestion-consumer pods and serves the consumer's routing debug UI pe| `BIND_HOST` / `BIND_PORT` | `0.0.0.0` / `3305` | Single listener: UI, API, `/_liveness`, `/_readiness`, `/metrics` || `KAFKA_HOSTS` | `localhost:19092` | || `KAFKA_TLS` | `false` | |-| `CONSUMER_TARGETS` | `events-ingestion-consumer=events_plugin_ingestion` | Comma list of `group=topic` pairs |+| `TOPIC_PREFIX` | `ingestion-` | Topics are discovered from cluster metadata by prefix |+| `GROUP_PREFIX` | `ingestion-` | Consumer groups are discovered by prefix; a group maps to the topics it has committed offsets on |+| `DISCOVERY_CACHE_TTL_SECS` | `300` | Discovered targets are cached; topology changes rarely |+| `OVERVIEW_CACHE_TTL_SECS` | `15` | Overview scans are cached with single-flight refresh, bounding broker load from repeated requests || `DATABASE_URL` | empty | Read replica; empty disables token → team resolution || `ANALYSIS_MESSAGE_COUNT` | `10000` | Messages per analysis || `ANALYSIS_DEADLINE_SECS` | `120` | || `ANALYSIS_MAX_FETCH_BYTES` | `536870912` | Kafka transfers full records even for header-only analysis || `POD_DISCOVERY_MODE` | `kubernetes` | `static` for local testing || `STATIC_PODS` | `local=127.0.0.1:3301` | `name=host:port` pairs for static mode |-| `POD_LABEL_SELECTORS` | `app=ingestion-analytics-main,app=ingestion-analytics-async` | One `key=value` per entry |-| `K8S_NAMESPACE` | `posthog` | |+| `POD_LABEL_SELECTORS` | `ingestion-analytics-main/app=ingestion-analytics-main,ingestion-analytics-async/app=ingestion-analytics-async` | One `namespace/key=value` per entry (each lane runs in its own namespace); bare `key=value` uses `K8S_NAMESPACE` |+| `K8S_NAMESPACE` | `posthog` | Default namespace for unqualified selector entries || `DEBUG_PORT` | `3301` | Consumer debug API port (kubernetes mode) |## Local development@@ -45,9 +48,10 @@ DATABASE_URL=postgres://posthog:posthog@db:5432/posthog \KAFKA_HOSTS=localhost:9092 \cargo run -p ingestion-control-plane --example seed_lag-# Run the service against it, with a locally running ingestion-consumer on :3401:+# Run the service against it, with a locally running ingestion-consumer on :3401.+# The seeded ingestion-lag-demo topic/group are picked up by the default+# `ingestion-` discovery prefixes:BIND_PORT=3305 KAFKA_HOSTS=localhost:9092 \- CONSUMER_TARGETS="test-group=icp-test-topic" \DATABASE_URL=postgres://posthog:posthog@db:5432/posthog \POD_DISCOVERY_MODE=static STATIC_PODS="local-consumer=127.0.0.1:3401" \cargo run -p ingestion-control-planediff --git a/rust/ingestion-control-plane/examples/seed_lag.rs b/rust/ingestion-control-plane/examples/seed_lag.rsindex 8708d584f75f..42fe0021792a 100644--- a/rust/ingestion-control-plane/examples/seed_lag.rs+++ b/rust/ingestion-control-plane/examples/seed_lag.rs@@ -15,7 +15,7 @@//! ```//!//! Env knobs: `KAFKA_HOSTS` (default `localhost:9092`), `TOPIC` (default-//! `icp-test-topic`), `GROUP` (default `test-group`), `HOT_MESSAGES`+//! `ingestion-lag-demo`), `GROUP` (default `ingestion-lag-demo`), `HOT_MESSAGES`//! (default 2000). With `DATABASE_URL` set, real team tokens are used so the//! control plane's token -> team resolution shows real team ids.@@ -93,8 +93,8 @@ async fn fetch_tokens(database_url: &str) -> Vec<String> {#[tokio::main]async fn main() {let kafka_hosts = env_or("KAFKA_HOSTS", "localhost:9092");- let topic = env_or("TOPIC", "icp-test-topic");- let group = env_or("GROUP", "test-group");+ let topic = env_or("TOPIC", "ingestion-lag-demo");+ let group = env_or("GROUP", "ingestion-lag-demo");let hot_messages: usize = env_or("HOT_MESSAGES", "2000").parse().expect("HOT_MESSAGES must be a number");diff --git a/rust/ingestion-control-plane/src/api.rs b/rust/ingestion-control-plane/src/api.rsindex 9bed95ec9750..55ab1d38ab1f 100644--- a/rust/ingestion-control-plane/src/api.rs+++ b/rust/ingestion-control-plane/src/api.rs@@ -12,7 +12,7 @@ use uuid::Uuid;use k8s_awareness::DiscoveredPod;use crate::jobs::{AnalysisRequest, JobView};-use crate::kafka::lag::{self, GroupLag, GroupLagSummary};+use crate::kafka::lag::{self, ConsumerTarget, GroupLag, LagOverview};use crate::proxy;use crate::state::AppState;use crate::ui;@@ -65,22 +65,73 @@ impl IntoResponse for ApiError {}}-async fn get_lag_overview(State(state): State<AppState>) -> Json<Vec<GroupLagSummary>> {- Json(lag::scan_all_groups(&state.config).await)+/// The API only accepts exact group/topic pairs present in the (cached)+/// discovered targets — prefix checks alone would let a fabricated group+/// read any prefixed topic, and the tool must not become a generic Kafka+/// browser. Prefix mismatches fail fast with a clearer message.+async fn validated_target(+ state: &AppState,+ group: &str,+ topic: &str,+) -> Result<ConsumerTarget, ApiError> {+ if !group.starts_with(&state.config.group_prefix) {+ return Err(ApiError::bad_request(format!(+ "group '{group}' is outside the '{}' prefix",+ state.config.group_prefix+ )));+ }+ if !topic.starts_with(&state.config.topic_prefix) {+ return Err(ApiError::bad_request(format!(+ "topic '{topic}' is outside the '{}' prefix",+ state.config.topic_prefix+ )));+ }++ let targets = state+ .discovery+ .get_or_refresh(|| lag::discover_targets(&state.config))+ .await+ .map_err(|e| ApiError::upstream(format!("target discovery failed: {e:#}")))?;+ let target = ConsumerTarget {+ group: group.to_string(),+ topic: topic.to_string(),+ };+ if !targets.contains(&target) {+ return Err(ApiError::bad_request(format!(+ "'{group}' / '{topic}' is not a discovered consumer target \+ (discovery refreshes every {}s)",+ state.config.discovery_cache_ttl_secs+ )));+ }+ Ok(target)+}++async fn get_lag_overview(State(state): State<AppState>) -> Result<Json<LagOverview>, ApiError> {+ let overview = state+ .overview+ .get_or_refresh(|| async {+ let targets = state+ .discovery+ .get_or_refresh(|| lag::discover_targets(&state.config))+ .await?;+ Ok(lag::scan_targets(&state.config, targets.as_ref().clone()).await)+ })+ .await+ .map_err(|e| ApiError::upstream(format!("lag overview failed: {e:#}")))?;+ Ok(Json(overview.as_ref().clone()))}#[derive(Deserialize)]struct LagQuery {group: String,+ topic: String,}async fn get_lag(State(state): State<AppState>,Query(query): Query<LagQuery>,) -> Result<Json<GroupLag>, ApiError> {- let target = state.config.target_for_group(&query.group).ok_or_else(|| {- ApiError::bad_request(format!("unknown consumer group '{}'", query.group))- })?;+ let target = validated_target(&state, &query.group, &query.topic).await?;let group_lag = lag::scan_group_lag(&state.config, &target).await@@ -93,12 +144,7 @@ async fn create_analysis(State(state): State<AppState>,Json(request): Json<AnalysisRequest>,) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> {- let target = state- .config- .target_for_group(&request.group)- .ok_or_else(|| {- ApiError::bad_request(format!("unknown consumer group '{}'", request.group))- })?;+ let target = validated_target(&state, &request.group, &request.topic).await?;if request.partition < 0 {return Err(ApiError::bad_request("partition must be non-negative"));}@@ -175,8 +221,12 @@ pub fn router(state: AppState) -> Router {).route("/api/pods", get(list_pods))// The consumer debug UI is served per pod; its relative `debug/...`- // fetches resolve to the proxy route below.- .route("/pods/:name/", get(ui::consumer_debug))- .route("/pods/:name/debug/*rest", get(proxy::proxy_debug))+ // fetches resolve to the proxy route below. Pods are addressed by+ // namespace + name so identical names across lanes cannot collide.+ .route("/pods/:namespace/:name/", get(ui::consumer_debug))+ .route(+ "/pods/:namespace/:name/debug/*rest",+ get(proxy::proxy_debug),+ ).with_state(state)}diff --git a/rust/ingestion-control-plane/src/cache.rs b/rust/ingestion-control-plane/src/cache.rsnew file mode 100644index 000000000000..8be1732de75a--- /dev/null+++ b/rust/ingestion-control-plane/src/cache.rs@@ -0,0 +1,105 @@+use std::future::Future;+use std::sync::Arc;+use std::time::{Duration, Instant};++use tokio::sync::Mutex;++/// A single-value TTL cache with single-flight refresh: the mutex is held+/// across the refresh, so concurrent callers wait for one in-flight refresh+/// and share its result instead of each triggering their own. Kafka topology+/// (topics, groups, partitions) changes rarely, and this also stops repeated+/// requests from multiplying broker-wide scans.+pub struct TtlCache<T> {+ ttl: Duration,+ inner: Mutex<Option<(Instant, Arc<T>)>>,+}++impl<T> TtlCache<T> {+ pub fn new(ttl: Duration) -> Self {+ Self {+ ttl,+ inner: Mutex::new(None),+ }+ }++ /// Return the cached value if fresh, otherwise run `refresh` and cache+ /// its result. A failed refresh leaves any previous (stale) entry in+ /// place so the next caller retries.+ pub async fn get_or_refresh<F, Fut>(&self, refresh: F) -> anyhow::Result<Arc<T>>+ where+ F: FnOnce() -> Fut,+ Fut: Future<Output = anyhow::Result<T>>,+ {+ let mut guard = self.inner.lock().await;+ if let Some((refreshed_at, value)) = &*guard {+ if refreshed_at.elapsed() < self.ttl {+ return Ok(Arc::clone(value));+ }+ }+ let value = Arc::new(refresh().await?);+ *guard = Some((Instant::now(), Arc::clone(&value)));+ Ok(value)+ }+}++#[cfg(test)]+mod tests {+ use std::sync::atomic::{AtomicU32, Ordering};++ use super::*;++ #[tokio::test]+ async fn serves_cached_value_within_ttl_and_refreshes_after() {+ let cache = TtlCache::new(Duration::from_secs(60));+ let calls = AtomicU32::new(0);+ let refresh = || {+ calls.fetch_add(1, Ordering::SeqCst);+ async { Ok(42u32) }+ };++ assert_eq!(*cache.get_or_refresh(refresh).await.unwrap(), 42);+ assert_eq!(*cache.get_or_refresh(refresh).await.unwrap(), 42);+ assert_eq!(calls.load(Ordering::SeqCst), 1);++ let expired = TtlCache::new(Duration::ZERO);+ assert_eq!(*expired.get_or_refresh(refresh).await.unwrap(), 42);+ assert_eq!(*expired.get_or_refresh(refresh).await.unwrap(), 42);+ assert_eq!(calls.load(Ordering::SeqCst), 3);+ }++ #[tokio::test]+ async fn failed_refresh_is_retried_by_next_caller() {+ let cache: TtlCache<u32> = TtlCache::new(Duration::from_secs(60));+ let result = cache+ .get_or_refresh(|| async { Err(anyhow::anyhow!("broker down")) })+ .await;+ assert!(result.is_err());+ assert_eq!(*cache.get_or_refresh(|| async { Ok(7) }).await.unwrap(), 7);+ }++ #[tokio::test]+ async fn concurrent_callers_share_one_refresh() {+ let cache: Arc<TtlCache<u32>> = Arc::new(TtlCache::new(Duration::from_secs(60)));+ let calls = Arc::new(AtomicU32::new(0));+ let tasks: Vec<_> = (0..8)+ .map(|_| {+ let cache = Arc::clone(&cache);+ let calls = Arc::clone(&calls);+ tokio::spawn(async move {+ *cache+ .get_or_refresh(|| async {+ calls.fetch_add(1, Ordering::SeqCst);+ tokio::time::sleep(Duration::from_millis(20)).await;+ Ok(1u32)+ })+ .await+ .unwrap()+ })+ })+ .collect();+ for task in tasks {+ assert_eq!(task.await.unwrap(), 1);+ }+ assert_eq!(calls.load(Ordering::SeqCst), 1);+ }+}diff --git a/rust/ingestion-control-plane/src/config.rs b/rust/ingestion-control-plane/src/config.rsindex 5dc67a18171b..c5df18d9e783 100644--- a/rust/ingestion-control-plane/src/config.rs+++ b/rust/ingestion-control-plane/src/config.rs@@ -1,12 +1,30 @@+use std::str::FromStr;+use envconfig::Envconfig;-/// A consumer group and the topic it consumes, as configured via-/// `CONSUMER_TARGETS` (`group=topic` pairs). Groups and topics differ per-/// ingestion lane, so they must be configured together.-#[derive(Debug, Clone, PartialEq, Eq)]-pub struct ConsumerTarget {- pub group: String,- pub topic: String,+/// How consumer pods are discovered, mirroring the ingestion-consumer's+/// typed `DiscoveryMode`.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub enum PodDiscoveryMode {+ /// Query the Kubernetes API for pods matching the configured targets.+ #[default]+ Kubernetes,+ /// Fixed list from `STATIC_PODS` (local testing).+ Static,+}++impl FromStr for PodDiscoveryMode {+ type Err = String;++ fn from_str(s: &str) -> Result<Self, Self::Err> {+ match s.trim().to_lowercase().as_str() {+ "kubernetes" | "k8s" => Ok(PodDiscoveryMode::Kubernetes),+ "static" => Ok(PodDiscoveryMode::Static),+ other => Err(format!(+ "unknown pod discovery mode '{other}' (expected 'kubernetes' or 'static')"+ )),+ }+ }}#[derive(Envconfig, Clone)]@@ -26,10 +44,26 @@ pub struct Config {#[envconfig(from = "KAFKA_CLIENT_RACK")]pub kafka_client_rack: Option<String>,- /// Comma-separated `group=topic` pairs, e.g.- /// `ingestion-analytics-main=ingestion-analytics-main-1024,ingestion-analytics-async=ingestion-analytics-async-8`.- #[envconfig(default = "events-ingestion-consumer=events_plugin_ingestion")]- pub consumer_targets: String,+ /// Topics and consumer groups are discovered from the cluster by prefix+ /// instead of being configured per environment; a group is associated+ /// with a topic when it has committed offsets on it. The prefixes also+ /// bound which groups/topics the API may scan.+ #[envconfig(default = "ingestion-")]+ pub topic_prefix: String,++ #[envconfig(default = "ingestion-")]+ pub group_prefix: String,++ /// Topology (topics, groups, partitions) changes rarely; discovered+ /// targets are cached this long.+ #[envconfig(default = "300")]+ pub discovery_cache_ttl_secs: u64,++ /// The lag overview triggers broker-wide offset/watermark scans; results+ /// are cached (with single-flight refresh) this long so repeated requests+ /// coalesce instead of multiplying broker load.+ #[envconfig(default = "15")]+ pub overview_cache_ttl_secs: u64,/// Read-replica Postgres URL for token -> team_id resolution. When unset,/// resolution is disabled and analyses report `team_id: null`.@@ -57,17 +91,24 @@ pub struct Config {/// the fixed `STATIC_PODS` list (local testing, like the/// ingestion-consumer's static worker discovery).#[envconfig(default = "kubernetes")]- pub pod_discovery_mode: String,+ pub pod_discovery_mode: PodDiscoveryMode,/// Comma-separated `name=host:port` entries used by static discovery.#[envconfig(default = "local=127.0.0.1:3301")]pub static_pods: String,+ /// Default namespace for `POD_LABEL_SELECTORS` entries without an+ /// explicit `namespace/` prefix.#[envconfig(default = "posthog")]pub k8s_namespace: String,/// Comma-separated pod label selectors, one per consumer deployment.- #[envconfig(default = "app=ingestion-analytics-main,app=ingestion-analytics-async")]+ /// Entries may be namespace-qualified (`namespace/key=value`) since each+ /// ingestion lane runs in its own namespace; bare `key=value` entries use+ /// `K8S_NAMESPACE`.+ #[envconfig(+ default = "ingestion-analytics-main/app=ingestion-analytics-main,ingestion-analytics-async/app=ingestion-analytics-async"+ )]pub pod_label_selectors: String,/// Port the ingestion-consumer serves its debug API on.@@ -94,38 +135,46 @@ impl Config {Self::init_from_env()}- pub fn targets(&self) -> Vec<ConsumerTarget> {- parse_targets(&self.consumer_targets)- }-- pub fn target_for_group(&self, group: &str) -> Option<ConsumerTarget> {- self.targets().into_iter().find(|t| t.group == group)- }-- pub fn label_selectors(&self) -> Vec<String> {+ pub fn pod_targets(&self) -> Vec<PodTarget> {self.pod_label_selectors.split(',').map(str::trim).filter(|s| !s.is_empty())- .map(String::from)+ .map(|entry| match entry.split_once('/') {+ // Only treat the prefix as a namespace when it is a valid+ // namespace name. Label keys may themselves contain `/`+ // (`app.kubernetes.io/name=x`), but their prefixes are DNS+ // subdomains with dots, which namespace names cannot contain.+ // A selector with a prefixed label key must be written+ // namespace-qualified (`ns/team.example.com/role=x`).+ Some((namespace, selector)) if is_valid_namespace(namespace.trim()) => PodTarget {+ namespace: namespace.trim().to_string(),+ selector: selector.trim().to_string(),+ },+ _ => PodTarget {+ namespace: self.k8s_namespace.clone(),+ selector: entry.to_string(),+ },+ }).collect()}}-fn parse_targets(raw: &str) -> Vec<ConsumerTarget> {- raw.split(',')- .filter_map(|pair| {- let (group, topic) = pair.trim().split_once('=')?;- let (group, topic) = (group.trim(), topic.trim());- if group.is_empty() || topic.is_empty() {- return None;- }- Some(ConsumerTarget {- group: group.to_string(),- topic: topic.to_string(),- })- })- .collect()+/// RFC 1123 label: lowercase alphanumerics and `-`, no leading/trailing `-`.+fn is_valid_namespace(s: &str) -> bool {+ !s.is_empty()+ && s.len() <= 63+ && !s.starts_with('-')+ && !s.ends_with('-')+ && s.chars()+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')+}++/// One pod-discovery target: a label selector scoped to a namespace.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct PodTarget {+ pub namespace: String,+ pub selector: String,}#[cfg(test)]@@ -133,20 +182,44 @@ mod tests {use super::*;#[test]- fn parses_group_topic_pairs_and_skips_malformed_entries() {- let targets = parse_targets(- "ingestion-analytics-main=ingestion-analytics-main-1024, ingestion-analytics-async=ingestion-analytics-async-8,bad-entry,=no-group,no-topic=",+ fn pod_targets_support_namespace_prefix_with_default_fallback() {+ let mut config = Config::init_with_defaults().expect("config defaults are valid");+ config.k8s_namespace = "default-ns".to_string();+ config.pod_label_selectors =+ "ingestion-analytics-main/app=ingestion-analytics-main, app=bare-selector".to_string();++ assert_eq!(+ config.pod_targets(),+ vec![+ PodTarget {+ namespace: "ingestion-analytics-main".to_string(),+ selector: "app=ingestion-analytics-main".to_string(),+ },+ PodTarget {+ namespace: "default-ns".to_string(),+ selector: "app=bare-selector".to_string(),+ },+ ]);+ }++ #[test]+ fn prefixed_label_keys_are_not_mistaken_for_namespaces() {+ let mut config = Config::init_with_defaults().expect("config defaults are valid");+ config.k8s_namespace = "default-ns".to_string();+ config.pod_label_selectors =+ "app.kubernetes.io/name=consumer,my-ns/app.kubernetes.io/name=consumer".to_string();+assert_eq!(- targets,+ config.pod_targets(),vec![- ConsumerTarget {- group: "ingestion-analytics-main".to_string(),- topic: "ingestion-analytics-main-1024".to_string(),+ PodTarget {+ namespace: "default-ns".to_string(),+ selector: "app.kubernetes.io/name=consumer".to_string(),},- ConsumerTarget {- group: "ingestion-analytics-async".to_string(),- topic: "ingestion-analytics-async-8".to_string(),+ PodTarget {+ namespace: "my-ns".to_string(),+ selector: "app.kubernetes.io/name=consumer".to_string(),},]);diff --git a/rust/ingestion-control-plane/src/jobs.rs b/rust/ingestion-control-plane/src/jobs.rsindex a3c5c60ac003..8a97459eee9b 100644--- a/rust/ingestion-control-plane/src/jobs.rs+++ b/rust/ingestion-control-plane/src/jobs.rs@@ -10,11 +10,11 @@ use tokio::sync::Semaphore;use tokio_util::sync::CancellationToken;use uuid::Uuid;-use crate::config::{Config, ConsumerTarget};+use crate::config::Config;use crate::kafka::analysis::Aggregates;use crate::kafka::client;use crate::kafka::fetch::{self, FetchParams, TruncatedReason};-use crate::kafka::lag::{self, PartitionBounds};+use crate::kafka::lag::{self, ConsumerTarget, PartitionBounds};use crate::teams::TeamResolver;/// Finished jobs kept around for the UI; older ones are evicted on insert.@@ -162,6 +162,7 @@ pub struct JobView {#[derive(Debug, Deserialize)]pub struct AnalysisRequest {pub group: String,+ pub topic: String,pub partition: i32,#[serde(default)]pub mode: AnalysisMode,diff --git a/rust/ingestion-control-plane/src/k8s.rs b/rust/ingestion-control-plane/src/k8s.rsindex 566a27732baa..6d5cb04a2772 100644--- a/rust/ingestion-control-plane/src/k8s.rs+++ b/rust/ingestion-control-plane/src/k8s.rs@@ -5,7 +5,10 @@ use k8s_awareness::DiscoveredPod;use kube::Client;use tokio::sync::OnceCell;-use crate::config::Config;+use crate::config::{Config, PodDiscoveryMode};++/// Pseudo-namespace that static pods are listed and resolved under.+pub const STATIC_NAMESPACE: &str = "static";/// A fixed proxy target used by static discovery (local testing), mirroring/// the ingestion-consumer's static worker discovery.@@ -27,12 +30,9 @@ pub enum PodDiscovery {impl PodDiscovery {pub fn from_config(config: &Config) -> anyhow::Result<Self> {- match config.pod_discovery_mode.as_str() {- "kubernetes" => Ok(Self::Kubernetes(OnceCell::new())),- "static" => Ok(Self::Static(parse_static_pods(&config.static_pods)?)),- other => Err(anyhow!(- "invalid POD_DISCOVERY_MODE '{other}' (expected 'kubernetes' or 'static')"- )),+ match config.pod_discovery_mode {+ PodDiscoveryMode::Kubernetes => Ok(Self::Kubernetes(OnceCell::new())),+ PodDiscoveryMode::Static => Ok(Self::Static(parse_static_pods(&config.static_pods)?)),}}@@ -57,6 +57,7 @@ impl PodDiscovery {.unwrap_or(&static_pod.address);DiscoveredPod {name: static_pod.name.clone(),+ namespace: STATIC_NAMESPACE.to_string(),ip: Some(host.to_string()),node: None,phase: Some("Static".to_string()),@@ -70,44 +71,65 @@ impl PodDiscovery {Self::Kubernetes(cell) => {let client = Self::client(cell).await?;let mut pods = Vec::new();- for selector in config.label_selectors() {+ for target in config.pod_targets() {let mut found = k8s_awareness::list_pods_by_selector(client,- &config.k8s_namespace,- &selector,+ &target.namespace,+ &target.selector,).await- .with_context(|| format!("list pods for selector '{selector}'"))?;+ .with_context(|| {+ format!(+ "list pods for selector '{}' in namespace '{}'",+ target.selector, target.namespace+ )+ })?;pods.append(&mut found);}- pods.sort_by(|a, b| a.name.cmp(&b.name));- pods.dedup_by(|a, b| a.name == b.name);+ pods.sort_by(|a, b| {+ (a.namespace.as_str(), a.name.as_str())+ .cmp(&(b.namespace.as_str(), b.name.as_str()))+ });+ pods.dedup_by(|a, b| a.namespace == b.namespace && a.name == b.name);Ok(pods)}}}- /// Resolve a pod name to the `host:port` of its debug API. In kubernetes- /// mode the pod is fetched fresh from the API and must match one of the- /// configured label selectors — the debug proxy must never dial a- /// client-chosen host.+ /// Resolve a namespace-qualified pod to the `host:port` of its debug API.+ /// In kubernetes mode the namespace must be one of the configured targets+ /// and the pod is fetched fresh from the API and must match one of that+ /// namespace's label selectors — the debug proxy must never dial a+ /// client-chosen host. Static pods live under the `static` pseudo-namespace.pub async fn resolve_proxy_target(&self,config: &Config,+ namespace: &str,name: &str,) -> anyhow::Result<Option<String>> {match self {Self::Static(static_pods) => Ok(static_pods.iter()+ .filter(|_| namespace == STATIC_NAMESPACE).find(|static_pod| static_pod.name == name).map(|static_pod| static_pod.address.clone())),Self::Kubernetes(cell) => {+ let targets = config.pod_targets();+ let selectors: Vec<&str> = targets+ .iter()+ .filter(|t| t.namespace == namespace)+ .map(|t| t.selector.as_str())+ .collect();+ // Only namespaces we are configured to discover are dialable.+ if selectors.is_empty() {+ return Ok(None);+ }let client = Self::client(cell).await?;- let pod = k8s_awareness::get_pod(client, &config.k8s_namespace, name)+ let pod = k8s_awareness::get_pod(client, namespace, name).await- .with_context(|| format!("fetch pod '{name}'"))?;+ .with_context(|| format!("fetch pod '{name}' in '{namespace}'"))?;Ok(pod- .filter(|p| matches_any_selector(&p.labels, &config.label_selectors()))+ .filter(|p| matches_any_selector(&p.labels, &selectors)).and_then(|p| p.ip).map(|ip| format!("{ip}:{}", config.debug_port)))}@@ -138,7 +160,7 @@ fn parse_static_pods(raw: &str) -> anyhow::Result<Vec<StaticPod>> {}/// Each configured selector is a single `key=value` pair.-fn matches_any_selector(labels: &BTreeMap<String, String>, selectors: &[String]) -> bool {+fn matches_any_selector(labels: &BTreeMap<String, String>, selectors: &[&str]) -> bool {selectors.iter().any(|selector| {selector.split_once('=').is_some_and(|(key, value)| {labels.get(key.trim()).map(String::as_str) == Some(value.trim())@@ -160,9 +182,9 @@ mod tests {#[test]fn matches_when_any_selector_matches() {let pod_labels = labels(&[("app", "ingestion-analytics-main"), ("team", "ingestion")]);- let selectors = vec![- "app=ingestion-analytics-async".to_string(),- "app=ingestion-analytics-main".to_string(),+ let selectors = [+ "app=ingestion-analytics-async",+ "app=ingestion-analytics-main",];assert!(matches_any_selector(&pod_labels, &selectors));}@@ -172,12 +194,9 @@ mod tests {let pod_labels = labels(&[("app", "some-other-service")]);assert!(!matches_any_selector(&pod_labels,- &["app=ingestion-analytics-main".to_string()]- ));- assert!(!matches_any_selector(- &pod_labels,- &["no-equals".to_string()]+ &["app=ingestion-analytics-main"]));+ assert!(!matches_any_selector(&pod_labels, &["no-equals"]));}#[test]@@ -214,12 +233,12 @@ mod tests {assert!(pods[0].ready);let target = discovery- .resolve_proxy_target(&config, "local")+ .resolve_proxy_target(&config, STATIC_NAMESPACE, "local").await.unwrap();assert_eq!(target.as_deref(), Some("127.0.0.1:3301"));let missing = discovery- .resolve_proxy_target(&config, "unknown")+ .resolve_proxy_target(&config, STATIC_NAMESPACE, "unknown").await.unwrap();assert_eq!(missing, None);diff --git a/rust/ingestion-control-plane/src/kafka/lag.rs b/rust/ingestion-control-plane/src/kafka/lag.rsindex 744077f87b25..f0a03f18510e 100644--- a/rust/ingestion-control-plane/src/kafka/lag.rs+++ b/rust/ingestion-control-plane/src/kafka/lag.rs@@ -8,9 +8,129 @@ use rdkafka::consumer::{BaseConsumer, Consumer};use rdkafka::{Offset, TopicPartitionList};use serde::Serialize;-use crate::config::{Config, ConsumerTarget};+use crate::config::Config;use crate::kafka::client;+/// A consumer group and one topic it consumes, discovered from the cluster+/// by prefix: topics and groups matching the configured prefixes, associated+/// wherever the group has committed offsets on the topic.+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+pub struct ConsumerTarget {+ pub group: String,+ pub topic: String,+}++/// Discover consumer targets from the cluster. Runs one metadata request,+/// one group-list request, and one OffsetFetch per matching group (bounded+/// concurrency), all on the blocking pool.+pub async fn discover_targets(config: &Config) -> anyhow::Result<Vec<ConsumerTarget>> {+ let timeout = Duration::from_millis(config.kafka_metadata_timeout_ms);++ let (topics, groups) = {+ let config = config.clone();+ tokio::task::spawn_blocking(move || fetch_prefixed_topics_and_groups(&config, timeout))+ .await+ .context("discovery task panicked")??+ };++ let topics = Arc::new(topics);+ let mut targets: Vec<ConsumerTarget> = stream::iter(groups)+ .map(|group| {+ let config = config.clone();+ let topics = Arc::clone(&topics);+ async move {+ tokio::task::spawn_blocking(move || {+ fetch_group_topics(&config, &group, &topics, timeout)+ })+ .await+ .context("group association task panicked")?+ }+ })+ .buffer_unordered(8)+ .collect::<Vec<_>>()+ .await+ .into_iter()+ .collect::<anyhow::Result<Vec<_>>>()?+ .into_iter()+ .flatten()+ .collect();++ targets.sort_by(|a, b| a.group.cmp(&b.group).then(a.topic.cmp(&b.topic)));+ Ok(targets)+}++type TopicsWithPartitions = Vec<(String, Vec<i32>)>;++fn fetch_prefixed_topics_and_groups(+ config: &Config,+ timeout: Duration,+) -> anyhow::Result<(TopicsWithPartitions, Vec<String>)> {+ let consumer = client::metadata_consumer(config).context("create metadata client")?;+ let metadata = consumer+ .fetch_metadata(None, timeout)+ .context("fetch cluster metadata")?;+ let topics: TopicsWithPartitions = metadata+ .topics()+ .iter()+ .filter(|t| t.name().starts_with(&config.topic_prefix))+ .map(|t| {+ (+ t.name().to_string(),+ t.partitions().iter().map(|p| p.id()).collect(),+ )+ })+ .collect();++ let group_list = consumer+ .fetch_group_list(None, timeout)+ .context("fetch consumer group list")?;+ let groups: Vec<String> = group_list+ .groups()+ .iter()+ .map(|g| g.name().to_string())+ .filter(|name| name.starts_with(&config.group_prefix) && name != client::INSPECTOR_GROUP_ID)+ .collect();++ Ok((topics, groups))+}++/// A group's topics are those it has committed offsets on, read with a+/// single OffsetFetch spanning every candidate partition.+fn fetch_group_topics(+ config: &Config,+ group: &str,+ topics: &TopicsWithPartitions,+ timeout: Duration,+) -> anyhow::Result<Vec<ConsumerTarget>> {+ let consumer = client::group_offsets_consumer(config, group).context("create group client")?;+ let mut tpl = TopicPartitionList::new();+ for (topic, partitions) in topics {+ for partition in partitions {+ tpl.add_partition(topic, *partition);+ }+ }+ let committed = consumer+ .committed_offsets(tpl, timeout)+ .with_context(|| format!("fetch committed offsets for group '{group}'"))?;++ let mut group_topics: Vec<String> = committed+ .elements()+ .iter()+ .filter(|elem| matches!(elem.offset(), Offset::Offset(_)))+ .map(|elem| elem.topic().to_string())+ .collect();+ group_topics.sort();+ group_topics.dedup();++ Ok(group_topics+ .into_iter()+ .map(|topic| ConsumerTarget {+ group: group.to_string(),+ topic,+ })+ .collect())+}+#[derive(Debug, Clone, Serialize)]pub struct PartitionLag {pub partition: i32,@@ -107,7 +227,7 @@ pub async fn scan_group_lag(config: &Config, target: &ConsumerTarget) -> anyhow:/// One row of the all-groups overview: total outstanding messages per/// configured consumer target. Scan failures are reported inline so one/// broken topic doesn't blank the whole overview.-#[derive(Debug, Serialize)]+#[derive(Debug, Clone, Serialize)]pub struct GroupLagSummary {pub group: String,pub topic: String,@@ -119,8 +239,17 @@ pub struct GroupLagSummary {}/// Scan every configured target concurrently, sorted by total lag desc.-pub async fn scan_all_groups(config: &Config) -> Vec<GroupLagSummary> {- let summaries = futures::future::join_all(config.targets().into_iter().map(|target| async {+/// The full overview, cached by the API layer; `fetched_at` tells the UI how+/// stale the cached scan is.+#[derive(Debug, Clone, Serialize)]+pub struct LagOverview {+ pub fetched_at: String,+ pub groups: Vec<GroupLagSummary>,+}++pub async fn scan_targets(config: &Config, targets: Vec<ConsumerTarget>) -> LagOverview {+ let fetched_at = chrono::Utc::now().to_rfc3339();+ let summaries = futures::future::join_all(targets.into_iter().map(|target| async {match scan_group_lag(config, &target).await {Ok(group_lag) => GroupLagSummary {group: target.group,@@ -144,7 +273,10 @@ pub async fn scan_all_groups(config: &Config) -> Vec<GroupLagSummary> {let mut summaries = summaries;summaries.sort_by(|a, b| b.total_lag.cmp(&a.total_lag).then(a.group.cmp(&b.group)));- summaries+ LagOverview {+ fetched_at,+ groups: summaries,+ }}/// Watermarks and committed offset for a single partition, read at analysisdiff --git a/rust/ingestion-control-plane/src/lib.rs b/rust/ingestion-control-plane/src/lib.rsindex 81feb6c7de81..a084a46d0048 100644--- a/rust/ingestion-control-plane/src/lib.rs+++ b/rust/ingestion-control-plane/src/lib.rs@@ -1,4 +1,5 @@pub mod api;+pub mod cache;pub mod config;pub mod jobs;pub mod k8s;diff --git a/rust/ingestion-control-plane/src/proxy.rs b/rust/ingestion-control-plane/src/proxy.rsindex 82babdde33e5..945f4a5e83a3 100644--- a/rust/ingestion-control-plane/src/proxy.rs+++ b/rust/ingestion-control-plane/src/proxy.rs@@ -29,12 +29,12 @@ fn build_upstream_url(target: &str, rest: &str, query: Option<&str>) -> String {}}-/// Proxy `GET /pods/:name/debug/<rest>` to the pod's debug API. The upstream-/// body is piped through as a byte stream, which also carries SSE-/// (`/debug/events`) without buffering.+/// Proxy `GET /pods/:namespace/:name/debug/<rest>` to the pod's debug API.+/// The upstream body is piped through as a byte stream, which also carries+/// SSE (`/debug/events`) without buffering.pub async fn proxy_debug(State(state): State<AppState>,- Path((name, rest)): Path<(String, String)>,+ Path((namespace, name, rest)): Path<(String, String, String)>,RawQuery(query): RawQuery,) -> Result<Response, ApiError> {if !is_safe_debug_path(&rest) {@@ -43,10 +43,10 @@ pub async fn proxy_debug(let target = state.pods- .resolve_proxy_target(&state.config, &name)+ .resolve_proxy_target(&state.config, &namespace, &name).await.map_err(|e| ApiError::unavailable(format!("pod discovery unavailable: {e:#}")))?- .ok_or_else(|| ApiError::not_found(format!("no matching pod '{name}'")))?;+ .ok_or_else(|| ApiError::not_found(format!("no matching pod '{namespace}/{name}'")))?;let url = build_upstream_url(&target, &rest, query.as_deref());let mut request = state.http.get(&url);diff --git a/rust/ingestion-control-plane/src/state.rs b/rust/ingestion-control-plane/src/state.rsindex 5ddc13db00ab..14ebefe15ccd 100644--- a/rust/ingestion-control-plane/src/state.rs+++ b/rust/ingestion-control-plane/src/state.rs@@ -3,9 +3,11 @@ use std::time::Duration;use common_database::PoolConfig;+use crate::cache::TtlCache;use crate::config::Config;use crate::jobs::JobRegistry;use crate::k8s::PodDiscovery;+use crate::kafka::lag::{ConsumerTarget, LagOverview};use crate::teams::TeamResolver;#[derive(Clone)]@@ -15,6 +17,10 @@ pub struct AppState {pub teams: Arc<TeamResolver>,pub pods: Arc<PodDiscovery>,pub http: reqwest::Client,+ /// Discovered group/topic targets; topology changes rarely.+ pub discovery: Arc<TtlCache<Vec<ConsumerTarget>>>,+ /// Overview scan results; short TTL + single-flight bounds broker load.+ pub overview: Arc<TtlCache<LagOverview>>,}impl AppState {@@ -51,6 +57,12 @@ impl AppState {teams: Arc::new(TeamResolver::new(pool)),pods: Arc::new(PodDiscovery::from_config(&config)?),http,+ discovery: Arc::new(TtlCache::new(Duration::from_secs(+ config.discovery_cache_ttl_secs,+ ))),+ overview: Arc::new(TtlCache::new(Duration::from_secs(+ config.overview_cache_ttl_secs,+ ))),config: Arc::new(config),})}diff --git a/rust/ingestion-control-plane/src/ui/index.html b/rust/ingestion-control-plane/src/ui/index.htmlindex 5d2333b326ba..4abaa729d32f 100644--- a/rust/ingestion-control-plane/src/ui/index.html+++ b/rust/ingestion-control-plane/src/ui/index.html@@ -181,7 +181,7 @@description:"All ingestion consumer groups sorted by outstanding messages. Drill into a group, then analyze what a lagging partition contains.",timers: [],- selectedGroup: null,+ selectedTarget: null,currentJobId: null,unmount() {this.timers.forEach(clearInterval);@@ -189,16 +189,17 @@},mount(root) {const overviewBody = el("div", {}, el("div", { class: "empty" }, "Scanning consumer groups…"));+ const overviewFetchedAt = el("span", { class: "muted mono", style: "text-transform: none; letter-spacing: 0" });const partitionsTitle = el("span", {}, "Partitions");const partitionsBody = el("div", {}, el("div", { class: "empty" }, "Select a consumer group above."));const analysisTitle = el("span", {}, "Analysis");const analysisBody = el("div", {}, el("div", { class: "empty" }, "Start an analysis from a partition row: head reads from the group's committed offset, tail samples the newest messages."));- this.ui = { overviewBody, partitionsTitle, partitionsBody, analysisTitle, analysisBody };+ this.ui = { overviewBody, overviewFetchedAt, partitionsTitle, partitionsBody, analysisTitle, analysisBody };root.append(el("div", { class: "panel" },- el("h2", {}, "Consumer groups", el("button", { class: "small", onclick: () => this.refreshOverview() }, "Refresh")),+ el("h2", {}, "Consumer groups", el("span", { class: "row", style: "padding:0" }, overviewFetchedAt, el("button", { class: "small", onclick: () => this.refreshOverview() }, "Refresh"))),overviewBody),el("div", { class: "panel" },el("h2", {}, partitionsTitle, el("button", { class: "small", onclick: () => this.refreshPartitions() }, "Refresh")),@@ -211,9 +212,11 @@},async refreshOverview() {- const { overviewBody } = this.ui;+ const { overviewBody, overviewFetchedAt } = this.ui;try {- const rows = await fetchJSON("api/lag/overview");+ const data = await fetchJSON("api/lag/overview");+ const rows = data.groups;+ overviewFetchedAt.textContent = `as of ${new Date(data.fetched_at).toLocaleTimeString()}`;if (!rows.length) {overviewBody.replaceChildren(el("div", { class: "empty" }, "No consumer targets configured."));return;@@ -230,7 +233,7 @@el("td", { class: "mono" }, row.group),el("td", { class: "mono" }, row.topic),el("td", { colspan: "4" }, el("span", { class: "pill bad", title: row.error }, "scan failed")))- : el("tr", { class: `clickable ${row.group === this.selectedGroup ? "selected" : ""}`, onclick: () => this.selectGroup(row.group) },+ : el("tr", { class: `clickable ${this.selectedTarget && row.group === this.selectedTarget.group && row.topic === this.selectedTarget.topic ? "selected" : ""}`, onclick: () => this.selectTarget(row) },el("td", { class: "mono" }, row.group),el("td", { class: "mono" }, row.topic),el("td", { class: "mono" }, fmtInt(row.partitions)),@@ -249,19 +252,19 @@}},- selectGroup(group) {- this.selectedGroup = group;+ selectTarget(target) {+ this.selectedTarget = { group: target.group, topic: target.topic };this.refreshOverview();this.refreshPartitions();},async refreshPartitions() {const { partitionsTitle, partitionsBody } = this.ui;- if (!this.selectedGroup) return;- partitionsTitle.textContent = `Partitions — ${this.selectedGroup}`;+ if (!this.selectedTarget) return;+ partitionsTitle.textContent = `Partitions — ${this.selectedTarget.group} (${this.selectedTarget.topic})`;partitionsBody.replaceChildren(el("div", { class: "empty" }, "Scanning…"));try {- const data = await fetchJSON(`api/lag?group=${encodeURIComponent(this.selectedGroup)}`);+ const data = await fetchJSON(`api/lag?group=${encodeURIComponent(this.selectedTarget.group)}&topic=${encodeURIComponent(this.selectedTarget.topic)}`);const maxLag = Math.max(1, ...data.partitions.map((p) => p.lag));partitionsBody.replaceChildren(el("table", {},@@ -300,7 +303,7 @@const resp = await fetchJSON("api/analyses", {method: "POST",headers: { "content-type": "application/json" },- body: JSON.stringify({ group: this.selectedGroup, partition, mode }),+ body: JSON.stringify({ ...this.selectedTarget, partition, mode }),});this.currentJobId = resp.job_id;this.pollJob();@@ -443,11 +446,11 @@}podsBody.replaceChildren(el("table", {},- el("thead", {}, el("tr", {}, el("th", {}, "pod"), el("th", {}, "app"), el("th", {}, "ip"), el("th", {}, "phase"), el("th", {}, "restarts"), el("th", {}, "started"))),+ el("thead", {}, el("tr", {}, el("th", {}, "pod"), el("th", {}, "namespace"), el("th", {}, "ip"), el("th", {}, "phase"), el("th", {}, "restarts"), el("th", {}, "started"))),el("tbody", {}, data.pods.map((pod) =>- el("tr", { class: `clickable ${pod.name === this.selectedPod ? "selected" : ""}`, onclick: () => this.selectPod(pod.name) },+ el("tr", { class: `clickable ${pod.name === this.selectedPod ? "selected" : ""}`, onclick: () => this.selectPod(pod) },el("td", { class: "mono" }, pod.name),- el("td", {}, pod.labels.app || "–"),+ el("td", {}, pod.namespace || "–"),el("td", { class: "mono" }, pod.ip || "–"),el("td", {}, el("span", { class: `pill ${pod.ready ? "good" : "warn"}` }, pod.phase || "?")),el("td", { class: "mono" }, String(pod.restarts)),@@ -460,13 +463,13 @@}},- selectPod(name) {- this.selectedPod = name;+ selectPod(pod) {+ this.selectedPod = pod.name;this.refreshPods();- const url = `pods/${encodeURIComponent(name)}/`;+ const url = `pods/${encodeURIComponent(pod.namespace)}/${encodeURIComponent(pod.name)}/`;this.ui.viewer.replaceChildren(el("div", { class: "panel" },- el("h2", {}, `Debug — ${name}`,+ el("h2", {}, `Debug — ${pod.name}`,el("a", { href: url, target: "_blank", style: "color: var(--accent); font-size: 11px; text-transform: none; letter-spacing: 0" }, "open in new tab ↗")),el("iframe", { class: "debug", src: url })));