: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): add ingestion control plane service (#70694)
José Sequeira249dc40e21f3
diff --git a/.github/rust-images.yml b/.github/rust-images.ymlindex b0c139913293..75fc66dfae60 100644--- a/.github/rust-images.yml+++ b/.github/rust-images.yml@@ -88,6 +88,12 @@dockerfile: ./rust/Dockerfileproject: mtvzx98zjn+# Internal web tool for the ingestion team (lag analysis, consumer debug+# visualizer).+- image: ingestion-control-plane+ dockerfile: ./rust/Dockerfile+ project: x5whcmg6rl+- image: kafka-deduplicatordockerfile: ./rust/Dockerfileproject: vznmbshh6qdiff --git a/rust/Cargo.lock b/rust/Cargo.lockindex ea77b09f69ea..9df733bdcb79 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -5251,6 +5251,37 @@ dependencies = ["uuid",]+[[package]]+name = "ingestion-control-plane"+version = "0.1.0"+dependencies = [+ "anyhow",+ "axum 0.7.9",+ "chrono",+ "common-alloc",+ "common-database",+ "common-metrics",+ "common-types",+ "dashmap 6.1.0",+ "envconfig",+ "futures",+ "hdrhistogram",+ "health",+ "k8s-awareness",+ "kube",+ "rdkafka",+ "reqwest 0.12.28",+ "rustls 0.23.37",+ "serde",+ "serde_json",+ "sqlx",+ "tokio",+ "tokio-util",+ "tracing",+ "tracing-subscriber",+ "uuid",+]+[[package]]name = "inout"version = "0.1.4"diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex b50728877f8c..c2db14eae22c 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -48,6 +48,7 @@ members = ["kafka-assigner","kafka-assigner-proto","ingestion-consumer",+ "ingestion-control-plane","kafka-deduplicator","personhog-common","personhog-coordination",diff --git a/rust/common/k8s-awareness/src/discovery.rs b/rust/common/k8s-awareness/src/discovery.rsindex 80252a9e3908..6d9d30412383 100644--- a/rust/common/k8s-awareness/src/discovery.rs+++ b/rust/common/k8s-awareness/src/discovery.rs@@ -1,7 +1,10 @@+use std::collections::BTreeMap;+use k8s_openapi::api::apps::v1::ReplicaSet;use k8s_openapi::api::core::v1::Pod;-use kube::api::Api;+use kube::api::{Api, ListParams};use kube::Client;+use serde::Serialize;use crate::types::{ControllerKind, ControllerRef, PodInfo};@@ -104,3 +107,125 @@ pub async fn discover_controller(fn is_not_found(e: &kube::Error) -> bool {matches!(e, kube::Error::Api(resp) if resp.code == 404)}++/// A pod matched by a label selector, with the metadata an operator-facing+/// tool cares about.+#[derive(Debug, Clone, Serialize)]+pub struct DiscoveredPod {+ pub name: String,+ pub ip: Option<String>,+ pub node: Option<String>,+ pub phase: Option<String>,+ pub ready: bool,+ pub started_at: Option<String>,+ pub restarts: i32,+ pub labels: BTreeMap<String, String>,+}++impl From<Pod> for DiscoveredPod {+ fn from(pod: Pod) -> Self {+ let status = pod.status.unwrap_or_default();+ let ready = status+ .conditions+ .as_deref()+ .unwrap_or_default()+ .iter()+ .any(|c| c.type_ == "Ready" && c.status == "True");+ let restarts = status+ .container_statuses+ .as_deref()+ .unwrap_or_default()+ .iter()+ .map(|c| c.restart_count)+ .sum();+ Self {+ name: pod.metadata.name.unwrap_or_default(),+ ip: status.pod_ip,+ node: pod.spec.and_then(|s| s.node_name),+ phase: status.phase,+ ready,+ started_at: status.start_time.map(|t| t.0.to_rfc3339()),+ restarts,+ labels: pod.metadata.labels.unwrap_or_default(),+ }+ }+}++/// List pods in a namespace matching a label selector (e.g. `app=my-service`).+pub async fn list_pods_by_selector(+ client: &Client,+ namespace: &str,+ selector: &str,+) -> Result<Vec<DiscoveredPod>, kube::Error> {+ let pods: Api<Pod> = Api::namespaced(client.clone(), namespace);+ let list = pods.list(&ListParams::default().labels(selector)).await?;+ Ok(list.items.into_iter().map(DiscoveredPod::from).collect())+}++/// Fetch a single pod by name, returning `None` when it doesn't exist.+pub async fn get_pod(+ client: &Client,+ namespace: &str,+ name: &str,+) -> Result<Option<DiscoveredPod>, kube::Error> {+ let pods: Api<Pod> = Api::namespaced(client.clone(), namespace);+ match pods.get(name).await {+ Ok(pod) => Ok(Some(DiscoveredPod::from(pod))),+ Err(e) if is_not_found(&e) => Ok(None),+ Err(e) => Err(e),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn maps_pod_fields_to_discovered_pod() {+ let pod: Pod = serde_json::from_value(serde_json::json!({+ "metadata": {+ "name": "consumer-abc",+ "labels": {"app": "ingestion-analytics-main", "pod-template-hash": "x1"}+ },+ "spec": {"nodeName": "node-1", "containers": []},+ "status": {+ "phase": "Running",+ "podIP": "10.0.0.7",+ "startTime": "2026-07-14T08:00:00Z",+ "conditions": [{"type": "Ready", "status": "True"}],+ "containerStatuses": [+ {"name": "c", "restartCount": 3, "ready": true, "image": "i", "imageID": "",+ "state": {}, "lastState": {}}+ ]+ }+ }))+ .expect("valid pod fixture");++ let discovered = DiscoveredPod::from(pod);+ assert_eq!(discovered.name, "consumer-abc");+ 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"));+ assert!(discovered.ready);+ assert_eq!(discovered.restarts, 3);+ assert_eq!(+ discovered.labels.get("app").map(String::as_str),+ Some("ingestion-analytics-main")+ );+ assert!(discovered.started_at.is_some());+ }++ #[test]+ fn missing_status_yields_not_ready_pod() {+ let pod: Pod = serde_json::from_value(serde_json::json!({+ "metadata": {"name": "pending-pod"}+ }))+ .expect("valid pod fixture");++ let discovered = DiscoveredPod::from(pod);+ assert_eq!(discovered.name, "pending-pod");+ assert!(!discovered.ready);+ assert_eq!(discovered.ip, None);+ assert_eq!(discovered.restarts, 0);+ }+}diff --git a/rust/common/k8s-awareness/src/lib.rs b/rust/common/k8s-awareness/src/lib.rsindex 8236423748f1..5c2b34a4e70d 100644--- a/rust/common/k8s-awareness/src/lib.rs+++ b/rust/common/k8s-awareness/src/lib.rs@@ -4,6 +4,8 @@ pub mod types;mod watcher;pub use detection::classify_departure;-pub use discovery::{discover_controller, DiscoveryError};+pub use discovery::{+ discover_controller, get_pod, list_pods_by_selector, DiscoveredPod, DiscoveryError,+};pub use types::{ClusterIntent, ControllerKind, ControllerRef, DepartureReason, PodInfo};pub use watcher::{K8sAwareness, K8sAwarenessError};diff --git a/rust/ingestion-control-plane/Cargo.toml b/rust/ingestion-control-plane/Cargo.tomlnew file mode 100644index 000000000000..5002ae24a889--- /dev/null+++ b/rust/ingestion-control-plane/Cargo.toml@@ -0,0 +1,35 @@+[package]+name = "ingestion-control-plane"+version = "0.1.0"+edition = "2021"+publish = false++[dependencies]+anyhow = { workspace = true }+axum = { workspace = true }+chrono = { workspace = true }+common-alloc = { path = "../common/alloc" }+common-database = { path = "../common/database" }+common-metrics = { path = "../common/metrics" }+common-types = { path = "../common/types" }+dashmap = { workspace = true }+envconfig = { workspace = true }+futures = { workspace = true }+hdrhistogram = { workspace = true }+health = { path = "../common/health" }+k8s-awareness = { path = "../common/k8s-awareness" }+kube = { version = "0.98", features = ["client"] }+rdkafka = { workspace = true }+reqwest = { workspace = true }+rustls = { version = "0.23", default-features = false, features = ["ring", "std"] }+serde = { workspace = true }+serde_json = { workspace = true }+sqlx = { workspace = true }+tokio = { workspace = true }+tokio-util = { workspace = true }+tracing = { workspace = true }+tracing-subscriber = { workspace = true }+uuid = { workspace = true }++[lints]+workspace = truediff --git a/rust/ingestion-control-plane/README.md b/rust/ingestion-control-plane/README.mdnew file mode 100644index 000000000000..162d4de0fac9--- /dev/null+++ b/rust/ingestion-control-plane/README.md@@ -0,0 +1,61 @@+# Ingestion control plane++Internal web tool for the ingestion team. Single binary serving an embedded UI, with a sidebar of tools that is meant to grow over time.++> **⚠️ Purely internal service — never expose publicly.** This tool has no authentication of its own and its analysis results contain cross-customer data (team tokens, distinct_ids, event names). It must only be deployed behind the internal ingress (VPN/SSO), reachable by PostHog employees exclusively. It is an operational tool, not a product surface.++## Tools++### 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):++- `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.++Results are broken down per token (resolved to `team_id` via Postgres when `DATABASE_URL` is set), with events and distinct_ids nested under each token, plus a message-size distribution and header-flag counts. Analyses use a dedicated consumer group (`ingestion-control-plane-inspector`) and never touch the real group's offsets.++### 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).++## Configuration++| Env var | Default | Notes |+| --- | --- | --- |+| `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 |+| `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` | |+| `DEBUG_PORT` | `3301` | Consumer debug API port (kubernetes mode) |++## Local development++```sh+# Seed a lagging-partition scenario (one dominant team on partition 0):+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:+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-plane+```++Then open `http://localhost:3305/`.++## Deployment notes++- Image `ingestion-control-plane` is built via `.github/rust-images.yml`; a deploy needs a matrix entry in `rust-docker-build.yml` plus a charts-repo app.+- Kubernetes mode needs RBAC: `get`/`list` on `pods` in the ingestion namespace, and network egress to pod IPs on the debug port, Kafka, and the Postgres replica.diff --git a/rust/ingestion-control-plane/examples/seed_lag.rs b/rust/ingestion-control-plane/examples/seed_lag.rsnew file mode 100644index 000000000000..8708d584f75f--- /dev/null+++ b/rust/ingestion-control-plane/examples/seed_lag.rs@@ -0,0 +1,222 @@+//! Seed a realistic lagging-partition scenario into local Kafka.+//!+//! Partition 0 becomes the "problem partition": one dominant team (70% of+//! messages, a single hot distinct_id, large payloads) drowns out a mixed+//! background of other teams and events, and the consumer group's committed+//! offset is left near the start so the partition shows heavy lag. Partitions+//! 1 and 2 get light, balanced traffic and are committed at their high+//! watermark (healthy).+//!+//! Run against the dev stack:+//!+//! ```sh+//! DATABASE_URL=postgres://posthog:posthog@db:5432/posthog \+//! cargo run -p ingestion-control-plane --example seed_lag+//! ```+//!+//! Env knobs: `KAFKA_HOSTS` (default `localhost:9092`), `TOPIC` (default+//! `icp-test-topic`), `GROUP` (default `test-group`), `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.++use std::time::Duration;++use common_types::CapturedEventHeaders;+use rdkafka::admin::{AdminClient, AdminOptions, NewTopic, TopicReplication};+use rdkafka::client::DefaultClientContext;+use rdkafka::config::ClientConfig;+use rdkafka::consumer::{BaseConsumer, Consumer};+use rdkafka::message::OwnedHeaders;+use rdkafka::producer::{FutureProducer, FutureRecord, Producer};+use rdkafka::{Offset, TopicPartitionList};++const BACKGROUND_EVENTS: &[&str] = &["$identify", "$autocapture", "$screen", "survey sent"];++fn env_or(key: &str, default: &str) -> String {+ std::env::var(key).unwrap_or_else(|_| default.to_string())+}++fn headers(token: &str, distinct_id: &str, event: &str, historical: bool) -> OwnedHeaders {+ CapturedEventHeaders {+ token: Some(token.to_string()),+ distinct_id: Some(distinct_id.to_string()),+ session_id: None,+ timestamp: Some(chrono::Utc::now().timestamp_millis().to_string()),+ event: Some(event.to_string()),+ uuid: Some(uuid::Uuid::new_v4().to_string()),+ now: Some(chrono::Utc::now().to_rfc3339()),+ force_disable_person_processing: None,+ historical_migration: historical.then_some(true),+ skip_heatmap_processing: None,+ dlq_reason: None,+ dlq_step: None,+ dlq_timestamp: None,+ content_encoding: None,+ }+ .into()+}++async fn fetch_tokens(database_url: &str) -> Vec<String> {+ let fallback: Vec<String> = ["phc_demo_a", "phc_demo_b", "phc_demo_c", "phc_demo_d"]+ .iter()+ .map(|t| t.to_string())+ .collect();+ if database_url.is_empty() {+ return fallback;+ }+ match sqlx::postgres::PgPoolOptions::new()+ .max_connections(1)+ .connect(database_url)+ .await+ {+ Ok(pool) => {+ match sqlx::query_scalar::<_, String>(+ "SELECT api_token FROM posthog_team ORDER BY id LIMIT 4",+ )+ .fetch_all(&pool)+ .await+ {+ Ok(tokens) if !tokens.is_empty() => {+ println!("using {} real team tokens from DATABASE_URL", tokens.len());+ tokens+ }+ _ => fallback,+ }+ }+ Err(e) => {+ println!("DATABASE_URL unreachable ({e}); using demo tokens");+ fallback+ }+ }+}++#[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 hot_messages: usize = env_or("HOT_MESSAGES", "2000")+ .parse()+ .expect("HOT_MESSAGES must be a number");+ let database_url = env_or("DATABASE_URL", "");++ let tokens = fetch_tokens(&database_url).await;+ let dominant = &tokens[0];+ let others = &tokens[1..];++ let mut base = ClientConfig::new();+ base.set("bootstrap.servers", &kafka_hosts);++ // Ensure the topic exists with 3 partitions.+ let admin: AdminClient<DefaultClientContext> = base.create().expect("create admin client");+ // Per-topic results may be "already exists"; only the request must succeed.+ admin+ .create_topics(+ &[NewTopic::new(&topic, 3, TopicReplication::Fixed(1))],+ &AdminOptions::new(),+ )+ .await+ .expect("create_topics request failed")+ .into_iter()+ .for_each(drop);++ let producer: FutureProducer = base.create().expect("create producer");+ let big_payload = "x".repeat(8 * 1024);++ let mut produced = 0usize;+ let mut send = |partition: i32,+ token: &str,+ distinct_id: &str,+ event: &str,+ payload: String,+ historical: bool| {+ let key = format!("{token}:{distinct_id}");+ let record = FutureRecord::to(&topic)+ .partition(partition)+ .key(&key)+ .payload(&payload)+ .headers(headers(token, distinct_id, event, historical));+ // Fire-and-forget into the local producer queue; flushed below.+ producer.send_result(record).expect("producer queue full");+ produced += 1;+ };++ // Partition 0: dominant team drowning out mixed background traffic.+ let dominant_count = hot_messages * 7 / 10;+ for i in 0..hot_messages {+ if i % 10 < 7 {+ send(+ 0,+ dominant,+ "hot-device-1",+ "$pageview",+ big_payload.clone(),+ i % 33 == 0,+ );+ } else {+ let token = &others[i % others.len()];+ let event = BACKGROUND_EVENTS[i % BACKGROUND_EVENTS.len()];+ let payload = "y".repeat(300 + (i * 37) % 1700);+ send(+ 0,+ token,+ &format!("user-{}", i % 120),+ event,+ payload,+ false,+ );+ }+ }++ // Partitions 1-2: light, balanced traffic.+ for partition in [1, 2] {+ for i in 0..150usize {+ let token = &tokens[i % tokens.len()];+ let event = BACKGROUND_EVENTS[i % BACKGROUND_EVENTS.len()];+ let payload = "z".repeat(200 + (i * 53) % 1300);+ send(+ partition,+ token,+ &format!("user-{partition}-{}", i % 40),+ event,+ payload,+ false,+ );+ }+ }++ producer+ .flush(Duration::from_secs(30))+ .expect("flush producer");+ println!("produced {produced} messages to '{topic}' ({dominant_count} dominant on p0)");++ // Commit offsets for the group: p0 stuck near the start, p1/p2 caught up.+ let consumer: BaseConsumer = {+ let mut cfg = base.clone();+ cfg.set("group.id", &group)+ .set("enable.auto.commit", "false");+ cfg.create().expect("create offset consumer")+ };+ let (_, hwm1) = consumer+ .fetch_watermarks(&topic, 1, Duration::from_secs(10))+ .expect("watermarks p1");+ let (_, hwm2) = consumer+ .fetch_watermarks(&topic, 2, Duration::from_secs(10))+ .expect("watermarks p2");++ let mut tpl = TopicPartitionList::new();+ tpl.add_partition_offset(&topic, 0, Offset::Offset(50))+ .expect("tpl p0");+ tpl.add_partition_offset(&topic, 1, Offset::Offset(hwm1))+ .expect("tpl p1");+ tpl.add_partition_offset(&topic, 2, Offset::Offset(hwm2))+ .expect("tpl p2");+ consumer+ .commit(&tpl, rdkafka::consumer::CommitMode::Sync)+ .expect("commit offsets");++ println!(+ "committed offsets for group '{group}': p0=50 (lagging), p1={hwm1}, p2={hwm2} (caught up)"+ );+ println!("open the control plane UI and refresh the lag view");+}diff --git a/rust/ingestion-control-plane/src/api.rs b/rust/ingestion-control-plane/src/api.rsnew file mode 100644index 000000000000..9bed95ec9750--- /dev/null+++ b/rust/ingestion-control-plane/src/api.rs@@ -0,0 +1,182 @@+use std::sync::Arc;++use axum::extract::{Path, Query, State};+use axum::http::StatusCode;+use axum::response::{IntoResponse, Response};+use axum::routing::get;+use axum::{Json, Router};+use serde::{Deserialize, Serialize};+use serde_json::json;+use uuid::Uuid;++use k8s_awareness::DiscoveredPod;++use crate::jobs::{AnalysisRequest, JobView};+use crate::kafka::lag::{self, GroupLag, GroupLagSummary};+use crate::proxy;+use crate::state::AppState;+use crate::ui;++pub struct ApiError {+ status: StatusCode,+ message: String,+}++impl ApiError {+ pub fn bad_request(message: impl Into<String>) -> Self {+ Self {+ status: StatusCode::BAD_REQUEST,+ message: message.into(),+ }+ }++ pub fn not_found(message: impl Into<String>) -> Self {+ Self {+ status: StatusCode::NOT_FOUND,+ message: message.into(),+ }+ }++ pub fn upstream(message: impl Into<String>) -> Self {+ Self {+ status: StatusCode::BAD_GATEWAY,+ message: message.into(),+ }+ }++ pub fn unavailable(message: impl Into<String>) -> Self {+ Self {+ status: StatusCode::SERVICE_UNAVAILABLE,+ message: message.into(),+ }+ }++ pub fn too_many_requests(message: impl Into<String>) -> Self {+ Self {+ status: StatusCode::TOO_MANY_REQUESTS,+ message: message.into(),+ }+ }+}++impl IntoResponse for ApiError {+ fn into_response(self) -> Response {+ (self.status, Json(json!({ "error": self.message }))).into_response()+ }+}++async fn get_lag_overview(State(state): State<AppState>) -> Json<Vec<GroupLagSummary>> {+ Json(lag::scan_all_groups(&state.config).await)+}++#[derive(Deserialize)]+struct LagQuery {+ group: 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 group_lag = lag::scan_group_lag(&state.config, &target)+ .await+ .map_err(|e| ApiError::upstream(format!("lag scan failed: {e:#}")))?;++ Ok(Json(group_lag))+}++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))+ })?;+ if request.partition < 0 {+ return Err(ApiError::bad_request("partition must be non-negative"));+ }+ let Some(slot) = state.jobs.try_reserve_slot() else {+ return Err(ApiError::too_many_requests(+ "too many pending analyses; wait for current jobs to finish or cancel one",+ ));+ };++ let job_id = state+ .jobs+ .start(+ Arc::clone(&state.config),+ Arc::clone(&state.teams),+ target,+ request,+ slot,+ )+ .await+ .map_err(|e| ApiError::upstream(format!("failed to start analysis: {e:#}")))?;++ Ok((StatusCode::ACCEPTED, Json(json!({ "job_id": job_id }))))+}++async fn list_analyses(State(state): State<AppState>) -> Json<Vec<JobView>> {+ Json(state.jobs.list())+}++async fn get_analysis(+ State(state): State<AppState>,+ Path(id): Path<Uuid>,+) -> Result<Json<JobView>, ApiError> {+ let job = state+ .jobs+ .get(&id)+ .ok_or_else(|| ApiError::not_found(format!("no analysis job '{id}'")))?;+ Ok(Json(job.view()))+}++async fn cancel_analysis(+ State(state): State<AppState>,+ Path(id): Path<Uuid>,+) -> Result<StatusCode, ApiError> {+ if state.jobs.cancel(&id) {+ Ok(StatusCode::NO_CONTENT)+ } else {+ Err(ApiError::not_found(format!("no analysis job '{id}'")))+ }+}++#[derive(Serialize)]+struct PodsResponse {+ pods: Vec<DiscoveredPod>,+}++async fn list_pods(State(state): State<AppState>) -> Result<Json<PodsResponse>, ApiError> {+ let pods = state+ .pods+ .list_pods(&state.config)+ .await+ .map_err(|e| ApiError::unavailable(format!("pod discovery unavailable: {e:#}")))?;+ Ok(Json(PodsResponse { pods }))+}++pub fn router(state: AppState) -> Router {+ Router::new()+ .route("/", get(ui::index))+ .route("/api/lag", get(get_lag))+ .route("/api/lag/overview", get(get_lag_overview))+ .route("/api/analyses", get(list_analyses).post(create_analysis))+ .route(+ "/api/analyses/:id",+ get(get_analysis).delete(cancel_analysis),+ )+ .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))+ .with_state(state)+}diff --git a/rust/ingestion-control-plane/src/config.rs b/rust/ingestion-control-plane/src/config.rsnew file mode 100644index 000000000000..5dc67a18171b--- /dev/null+++ b/rust/ingestion-control-plane/src/config.rs@@ -0,0 +1,154 @@+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,+}++#[derive(Envconfig, Clone)]+pub struct Config {+ #[envconfig(from = "BIND_HOST", default = "0.0.0.0")]+ pub host: String,++ #[envconfig(from = "BIND_PORT", default = "3305")]+ pub port: u16,++ #[envconfig(default = "localhost:19092")]+ pub kafka_hosts: String,++ #[envconfig(default = "false")]+ pub kafka_tls: bool,++ #[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,++ /// Read-replica Postgres URL for token -> team_id resolution. When unset,+ /// resolution is disabled and analyses report `team_id: null`.+ #[envconfig(from = "DATABASE_URL")]+ pub database_url: Option<String>,++ #[envconfig(default = "2")]+ pub pg_max_connections: u32,++ #[envconfig(default = "10000")]+ pub analysis_message_count: u64,++ #[envconfig(default = "120")]+ pub analysis_deadline_secs: u64,++ /// Kafka transfers full records even though we only analyze headers, so+ /// bound the bytes fetched per analysis. 512 MiB by default.+ #[envconfig(default = "536870912")]+ pub analysis_max_fetch_bytes: u64,++ #[envconfig(default = "2")]+ pub analysis_max_concurrent_jobs: usize,++ /// `kubernetes` discovers consumer pods via the K8s API; `static` uses+ /// the fixed `STATIC_PODS` list (local testing, like the+ /// ingestion-consumer's static worker discovery).+ #[envconfig(default = "kubernetes")]+ pub pod_discovery_mode: String,++ /// Comma-separated `name=host:port` entries used by static discovery.+ #[envconfig(default = "local=127.0.0.1:3301")]+ pub static_pods: String,++ #[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")]+ pub pod_label_selectors: String,++ /// Port the ingestion-consumer serves its debug API on.+ #[envconfig(default = "3301")]+ pub debug_port: u16,++ /// Secret presented as `X-Debug-Api-Secret` on every proxied debug API+ /// request. Must match the consumers' `DEBUG_API_SECRET` (the AWS secret+ /// `ingestion-consumer-debug-api-secrets` in each environment); the+ /// consumer rejects unauthenticated requests, so leaving this unset only+ /// works against local consumers running without auth.+ #[envconfig(from = "DEBUG_API_SECRET")]+ pub debug_api_secret: Option<String>,++ #[envconfig(default = "10000")]+ pub kafka_metadata_timeout_ms: u64,++ #[envconfig(default = "1000")]+ pub kafka_fetch_poll_timeout_ms: u64,+}++impl Config {+ pub fn init_with_defaults() -> Result<Self, envconfig::Error> {+ 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> {+ self.pod_label_selectors+ .split(',')+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(String::from)+ .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()+}++#[cfg(test)]+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=",+ );+ assert_eq!(+ targets,+ vec![+ ConsumerTarget {+ group: "ingestion-analytics-main".to_string(),+ topic: "ingestion-analytics-main-1024".to_string(),+ },+ ConsumerTarget {+ group: "ingestion-analytics-async".to_string(),+ topic: "ingestion-analytics-async-8".to_string(),+ },+ ]+ );+ }+}diff --git a/rust/ingestion-control-plane/src/jobs.rs b/rust/ingestion-control-plane/src/jobs.rsnew file mode 100644index 000000000000..a3c5c60ac003--- /dev/null+++ b/rust/ingestion-control-plane/src/jobs.rs@@ -0,0 +1,522 @@+use std::sync::atomic::{AtomicI64, AtomicU64, AtomicUsize, Ordering};+use std::sync::{Arc, Mutex};+use std::time::Duration;++use anyhow::Context;+use chrono::{DateTime, Utc};+use dashmap::DashMap;+use serde::{Deserialize, Serialize};+use tokio::sync::Semaphore;+use tokio_util::sync::CancellationToken;+use uuid::Uuid;++use crate::config::{Config, ConsumerTarget};+use crate::kafka::analysis::Aggregates;+use crate::kafka::client;+use crate::kafka::fetch::{self, FetchParams, TruncatedReason};+use crate::kafka::lag::{self, PartitionBounds};+use crate::teams::TeamResolver;++/// Finished jobs kept around for the UI; older ones are evicted on insert.+const MAX_RETAINED_JOBS: usize = 20;+/// Running-plus-queued cap; submissions beyond it are rejected up front,+/// before any Kafka metadata work.+const MAX_PENDING_JOBS: usize = 8;+const MAX_JOB_AGE: Duration = Duration::from_secs(3600);+const TOP_K: usize = 50;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]+#[serde(rename_all = "snake_case")]+pub enum AnalysisMode {+ /// Start at the group's committed offset: what the consumer is stuck on.+ #[default]+ Committed,+ /// Sample the last N messages before the high watermark: what's arriving now.+ Tail,+}++/// Fully resolved analysis parameters, echoed back on job status.+#[derive(Debug, Clone, Serialize)]+pub struct AnalysisSpec {+ pub group: String,+ pub topic: String,+ pub partition: i32,+ pub mode: AnalysisMode,+ pub start_offset: i64,+ pub end_offset_exclusive: i64,+ pub requested_messages: u64,+ pub low_watermark: i64,+ pub high_watermark: i64,+ pub committed_offset: Option<i64>,+}++#[derive(Debug, Clone, Serialize)]+pub struct AnalysisResult {+ pub messages_analyzed: u64,+ pub next_offset: i64,+ pub truncated_reason: Option<TruncatedReason>,+ pub duration_ms: u64,+ #[serde(flatten)]+ pub aggregates: Aggregates,+}++pub struct Progress {+ fetched: AtomicU64,+ current_offset: AtomicI64,+ bytes_read: AtomicU64,+ target: u64,+}++impl Progress {+ fn new(start_offset: i64, target: u64) -> Self {+ Self {+ fetched: AtomicU64::new(0),+ current_offset: AtomicI64::new(start_offset),+ bytes_read: AtomicU64::new(0),+ target,+ }+ }++ pub fn record(&self, next_offset: i64, bytes: u64) {+ self.fetched.fetch_add(1, Ordering::Relaxed);+ self.current_offset.store(next_offset, Ordering::Relaxed);+ self.bytes_read.fetch_add(bytes, Ordering::Relaxed);+ }++ fn snapshot(&self) -> ProgressView {+ ProgressView {+ fetched: self.fetched.load(Ordering::Relaxed),+ target: self.target,+ current_offset: self.current_offset.load(Ordering::Relaxed),+ bytes_read: self.bytes_read.load(Ordering::Relaxed),+ }+ }+}++#[derive(Debug, Clone, Serialize)]+pub struct ProgressView {+ pub fetched: u64,+ pub target: u64,+ pub current_offset: i64,+ pub bytes_read: u64,+}++enum JobPhase {+ Running,+ Done(Box<AnalysisResult>),+ Failed(String),+}++pub struct Job {+ pub id: Uuid,+ pub spec: AnalysisSpec,+ pub created_at: DateTime<Utc>,+ pub progress: Progress,+ pub cancel: CancellationToken,+ phase: Mutex<JobPhase>,+}++impl Job {+ fn set_phase(&self, phase: JobPhase) {+ *self.phase.lock().expect("job phase mutex poisoned") = phase;+ }++ fn is_finished(&self) -> bool {+ !matches!(+ *self.phase.lock().expect("job phase mutex poisoned"),+ JobPhase::Running+ )+ }++ pub fn view(&self) -> JobView {+ let (state, result, error) = match &*self.phase.lock().expect("job phase mutex poisoned") {+ JobPhase::Running => ("running", None, None),+ JobPhase::Done(result) => ("done", Some(result.as_ref().clone()), None),+ JobPhase::Failed(message) => ("failed", None, Some(message.clone())),+ };+ JobView {+ id: self.id,+ state,+ spec: self.spec.clone(),+ created_at: self.created_at.to_rfc3339(),+ progress: self.progress.snapshot(),+ result,+ error,+ }+ }+}++#[derive(Serialize)]+pub struct JobView {+ pub id: Uuid,+ pub state: &'static str,+ pub spec: AnalysisSpec,+ pub created_at: String,+ pub progress: ProgressView,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub result: Option<AnalysisResult>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub error: Option<String>,+}++#[derive(Debug, Deserialize)]+pub struct AnalysisRequest {+ pub group: String,+ pub partition: i32,+ #[serde(default)]+ pub mode: AnalysisMode,+ pub start_offset: Option<i64>,+ pub message_count: Option<u64>,+}++pub struct JobRegistry {+ jobs: DashMap<Uuid, Arc<Job>>,+ concurrency: Arc<Semaphore>,+ /// Admissions granted but not yet inserted into `jobs` (a submission is+ /// between `try_reserve_slot` and the insert in `start`). Counted against+ /// `MAX_PENDING_JOBS` so concurrent submissions can't all pass the cap+ /// while none has registered its job yet.+ reserved: Arc<AtomicUsize>,+}++/// An admitted submission's slot. Held from admission until the job is+/// registered (or the submission fails), releasing on drop so every exit+/// path — including a panicking bounds lookup — frees the slot.+pub struct JobSlot {+ reserved: Arc<AtomicUsize>,+}++impl Drop for JobSlot {+ fn drop(&mut self) {+ self.reserved.fetch_sub(1, Ordering::SeqCst);+ }+}++impl JobRegistry {+ pub fn new(max_concurrent_jobs: usize) -> Self {+ Self {+ jobs: DashMap::new(),+ concurrency: Arc::new(Semaphore::new(max_concurrent_jobs.max(1))),+ reserved: Arc::new(AtomicUsize::new(0)),+ }+ }++ pub fn get(&self, id: &Uuid) -> Option<Arc<Job>> {+ self.jobs.get(id).map(|entry| Arc::clone(entry.value()))+ }++ pub fn list(&self) -> Vec<JobView> {+ let mut views: Vec<JobView> = self.jobs.iter().map(|entry| entry.value().view()).collect();+ views.sort_by(|a, b| b.created_at.cmp(&a.created_at));+ views+ }++ /// Atomically reserve an admission slot, or `None` when running + queued+ /// jobs plus in-flight submissions have reached the cap. The reservation+ /// is CAS-serialized on `reserved`, so concurrent submissions can't all+ /// pass the cap while none has registered its job yet (the check-then-act+ /// race the old boolean pre-check had). Pass the slot to+ /// [`JobRegistry::start`], which holds it until the job is registered.+ pub fn try_reserve_slot(&self) -> Option<JobSlot> {+ self.reserved+ .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |reserved| {+ let unfinished = self+ .jobs+ .iter()+ .filter(|entry| !entry.value().is_finished())+ .count();+ (unfinished + reserved < MAX_PENDING_JOBS).then_some(reserved + 1)+ })+ .ok()?;+ Some(JobSlot {+ reserved: Arc::clone(&self.reserved),+ })+ }++ pub fn cancel(&self, id: &Uuid) -> bool {+ match self.jobs.get(id) {+ Some(entry) => {+ entry.value().cancel.cancel();+ true+ }+ None => false,+ }+ }++ /// Evict finished jobs beyond the retention cap and anything past max age.+ fn evict(&self) {+ let now = Utc::now();+ let mut finished: Vec<(Uuid, DateTime<Utc>)> = self+ .jobs+ .iter()+ .filter(|entry| entry.value().is_finished())+ .map(|entry| (entry.value().id, entry.value().created_at))+ .collect();+ finished.sort_by_key(|(_, created_at)| *created_at);++ let excess = finished.len().saturating_sub(MAX_RETAINED_JOBS);+ for (id, created_at) in finished.iter() {+ let too_old = (now - *created_at).to_std().unwrap_or_default() > MAX_JOB_AGE;+ let over_cap = finished+ .iter()+ .position(|(fid, _)| fid == id)+ .is_some_and(|pos| pos < excess);+ if too_old || over_cap {+ self.jobs.remove(id);+ }+ }+ }++ /// Validate the request against fresh watermarks, register the job, and+ /// spawn its fetch task. Returns the job id immediately. `slot` is the+ /// admission reserved by [`JobRegistry::try_reserve_slot`]; it is held+ /// across the watermark lookup and released once the job is registered+ /// (or on any failure path), so the pending cap counts this submission+ /// the whole time.+ pub async fn start(+ self: &Arc<Self>,+ config: Arc<Config>,+ teams: Arc<TeamResolver>,+ target: ConsumerTarget,+ request: AnalysisRequest,+ slot: JobSlot,+ ) -> anyhow::Result<Uuid> {+ let timeout = Duration::from_millis(config.kafka_metadata_timeout_ms);+ let bounds = {+ let config = Arc::clone(&config);+ let target = target.clone();+ let partition = request.partition;+ tokio::task::spawn_blocking(move || {+ lag::fetch_partition_bounds_blocking(&config, &target, partition, timeout)+ })+ .await+ .context("bounds task panicked")??+ };++ let requested_messages = request+ .message_count+ .unwrap_or(config.analysis_message_count)+ .clamp(1, 1_000_000);+ let (start_offset, end_offset_exclusive) = resolve_offsets(+ request.mode,+ request.start_offset,+ requested_messages,+ bounds,+ );++ let spec = AnalysisSpec {+ group: target.group.clone(),+ topic: target.topic.clone(),+ partition: request.partition,+ mode: request.mode,+ start_offset,+ end_offset_exclusive,+ requested_messages,+ low_watermark: bounds.low_watermark,+ high_watermark: bounds.high_watermark,+ committed_offset: bounds.committed_offset,+ };++ let job = Arc::new(Job {+ id: Uuid::new_v4(),+ spec: spec.clone(),+ created_at: Utc::now(),+ progress: Progress::new(+ start_offset,+ (end_offset_exclusive - start_offset).max(0) as u64,+ ),+ cancel: CancellationToken::new(),+ phase: Mutex::new(JobPhase::Running),+ });++ let job_id = job.id;+ self.evict();+ self.jobs.insert(job_id, Arc::clone(&job));+ // The job is now visible to the cap via `jobs`; release the reservation+ // only after the insert so the sum never dips below the true count.+ drop(slot);++ let registry = Arc::clone(self);+ tokio::spawn(async move {+ let _permit = registry+ .concurrency+ .acquire()+ .await+ .expect("job semaphore closed");+ run_job(config, teams, job).await;+ });++ Ok(job_id)+ }+}++async fn run_job(config: Arc<Config>, teams: Arc<TeamResolver>, job: Arc<Job>) {+ let params = FetchParams {+ topic: job.spec.topic.clone(),+ partition: job.spec.partition,+ start_offset: job.spec.start_offset,+ end_offset_exclusive: job.spec.end_offset_exclusive,+ requested_end_offset: job.spec.start_offset + job.spec.requested_messages as i64,+ deadline: Duration::from_secs(config.analysis_deadline_secs),+ max_bytes: config.analysis_max_fetch_bytes,+ poll_timeout: Duration::from_millis(config.kafka_fetch_poll_timeout_ms),+ };++ let outcome = {+ let job = Arc::clone(&job);+ let config = Arc::clone(&config);+ tokio::task::spawn_blocking(move || {+ let consumer = client::fetch_consumer(&config).context("create fetch client")?;+ fetch::run_fetch(&consumer, ¶ms, &job.progress, &job.cancel)+ })+ .await+ .context("fetch task panicked")+ .and_then(|res| res)+ };++ match outcome {+ Ok(outcome) => {+ let mut aggregates = outcome.aggregator.finish(TOP_K);+ let tokens: Vec<String> = aggregates+ .top_tokens+ .iter()+ .map(|t| t.token.clone())+ .collect();+ let team_ids = teams.resolve(&tokens).await;+ for token_count in &mut aggregates.top_tokens {+ token_count.team_id = team_ids.get(&token_count.token).copied().flatten();+ }+ job.set_phase(JobPhase::Done(Box::new(AnalysisResult {+ messages_analyzed: aggregates.messages,+ next_offset: outcome.next_offset,+ truncated_reason: outcome.truncated_reason,+ duration_ms: outcome.duration_ms,+ aggregates,+ })));+ }+ Err(e) => {+ tracing::warn!(job_id = %job.id, error = %e, "analysis job failed");+ job.set_phase(JobPhase::Failed(format!("{e:#}")));+ }+ }+}++/// Resolve the fetch range for a request. An explicit `start_offset` wins;+/// otherwise `committed` mode starts at the group's committed offset (falling+/// back to the low watermark when the group never committed) and `tail` mode+/// starts `count` messages before the high watermark. Everything is clamped+/// to the retained `[low, high]` range.+fn resolve_offsets(+ mode: AnalysisMode,+ explicit_start: Option<i64>,+ count: u64,+ bounds: PartitionBounds,+) -> (i64, i64) {+ let low = bounds.low_watermark;+ let high = bounds.high_watermark;+ let start = match (explicit_start, mode) {+ (Some(start), _) => start,+ (None, AnalysisMode::Committed) => bounds.committed_offset.unwrap_or(low),+ (None, AnalysisMode::Tail) => high.saturating_sub(count as i64),+ }+ .clamp(low, high);+ let end = (start + count as i64).min(high);+ (start, end)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn admission_slots_are_bounded_and_released_on_drop() {+ // Regression for the check-then-act race: N concurrent submissions all+ // passed a boolean cap check before any registered its job. Reserving+ // must count in-flight submissions, and a dropped slot (failed+ // submission) must free capacity.+ let registry = JobRegistry::new(1);+ let slots: Vec<JobSlot> = std::iter::from_fn(|| registry.try_reserve_slot())+ .take(MAX_PENDING_JOBS + 1)+ .collect();+ assert_eq!(slots.len(), MAX_PENDING_JOBS, "cap must bind before insert");+ assert!(registry.try_reserve_slot().is_none());++ drop(slots);+ assert!(+ registry.try_reserve_slot().is_some(),+ "released slots must re-admit"+ );+ }++ fn bounds(low: i64, high: i64, committed: Option<i64>) -> PartitionBounds {+ PartitionBounds {+ low_watermark: low,+ high_watermark: high,+ committed_offset: committed,+ }+ }++ #[test]+ fn committed_mode_starts_at_committed_offset() {+ let (start, end) = resolve_offsets(+ AnalysisMode::Committed,+ None,+ 100,+ bounds(0, 1000, Some(400)),+ );+ assert_eq!((start, end), (400, 500));+ }++ #[test]+ fn committed_mode_falls_back_to_low_watermark() {+ let (start, end) =+ resolve_offsets(AnalysisMode::Committed, None, 100, bounds(50, 1000, None));+ assert_eq!((start, end), (50, 150));+ }++ #[test]+ fn tail_mode_samples_before_high_watermark() {+ let (start, end) =+ resolve_offsets(AnalysisMode::Tail, None, 100, bounds(0, 1000, Some(400)));+ assert_eq!((start, end), (900, 1000));+ }++ #[test]+ fn tail_mode_clamps_to_low_watermark() {+ let (start, end) = resolve_offsets(AnalysisMode::Tail, None, 500, bounds(700, 1000, None));+ assert_eq!((start, end), (700, 1000));+ }++ #[test]+ fn explicit_start_offset_wins_and_is_clamped() {+ let (start, end) = resolve_offsets(+ AnalysisMode::Committed,+ Some(5),+ 100,+ bounds(10, 1000, Some(400)),+ );+ assert_eq!((start, end), (10, 110));+ }++ #[test]+ fn range_is_clamped_to_high_watermark() {+ let (start, end) = resolve_offsets(+ AnalysisMode::Committed,+ None,+ 10_000,+ bounds(0, 100, Some(40)),+ );+ assert_eq!((start, end), (40, 100));+ }++ #[test]+ fn committed_at_high_watermark_yields_empty_range() {+ let (start, end) = resolve_offsets(+ AnalysisMode::Committed,+ None,+ 100,+ bounds(0, 100, Some(100)),+ );+ assert_eq!((start, end), (100, 100));+ }+}diff --git a/rust/ingestion-control-plane/src/k8s.rs b/rust/ingestion-control-plane/src/k8s.rsnew file mode 100644index 000000000000..566a27732baa--- /dev/null+++ b/rust/ingestion-control-plane/src/k8s.rs@@ -0,0 +1,233 @@+use std::collections::BTreeMap;++use anyhow::{anyhow, Context};+use k8s_awareness::DiscoveredPod;+use kube::Client;+use tokio::sync::OnceCell;++use crate::config::Config;++/// A fixed proxy target used by static discovery (local testing), mirroring+/// the ingestion-consumer's static worker discovery.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct StaticPod {+ pub name: String,+ /// `host:port` of the pod's debug API.+ pub address: String,+}++/// Discovers ingestion-consumer pods. In `kubernetes` mode the client is+/// created lazily on first use so the service still starts (and the Kafka+/// tools still work) outside a cluster; in `static` mode a fixed list of+/// `name=host:port` targets is served instead.+pub enum PodDiscovery {+ Kubernetes(OnceCell<Client>),+ Static(Vec<StaticPod>),+}++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')"+ )),+ }+ }++ async fn client(cell: &OnceCell<Client>) -> anyhow::Result<&Client> {+ cell.get_or_try_init(|| async {+ Client::try_default().await.context(+ "no Kubernetes environment detected (in-cluster service account or kubeconfig)",+ )+ })+ .await+ }++ pub async fn list_pods(&self, config: &Config) -> anyhow::Result<Vec<DiscoveredPod>> {+ match self {+ Self::Static(static_pods) => Ok(static_pods+ .iter()+ .map(|static_pod| {+ let host = static_pod+ .address+ .rsplit_once(':')+ .map(|(host, _)| host)+ .unwrap_or(&static_pod.address);+ DiscoveredPod {+ name: static_pod.name.clone(),+ ip: Some(host.to_string()),+ node: None,+ phase: Some("Static".to_string()),+ ready: true,+ started_at: None,+ restarts: 0,+ labels: BTreeMap::from([("app".to_string(), "static".to_string())]),+ }+ })+ .collect()),+ Self::Kubernetes(cell) => {+ let client = Self::client(cell).await?;+ let mut pods = Vec::new();+ for selector in config.label_selectors() {+ let mut found = k8s_awareness::list_pods_by_selector(+ client,+ &config.k8s_namespace,+ &selector,+ )+ .await+ .with_context(|| format!("list pods for selector '{selector}'"))?;+ pods.append(&mut found);+ }+ pods.sort_by(|a, b| a.name.cmp(&b.name));+ pods.dedup_by(|a, b| 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.+ pub async fn resolve_proxy_target(+ &self,+ config: &Config,+ name: &str,+ ) -> anyhow::Result<Option<String>> {+ match self {+ Self::Static(static_pods) => Ok(static_pods+ .iter()+ .find(|static_pod| static_pod.name == name)+ .map(|static_pod| static_pod.address.clone())),+ Self::Kubernetes(cell) => {+ let client = Self::client(cell).await?;+ let pod = k8s_awareness::get_pod(client, &config.k8s_namespace, name)+ .await+ .with_context(|| format!("fetch pod '{name}'"))?;+ Ok(pod+ .filter(|p| matches_any_selector(&p.labels, &config.label_selectors()))+ .and_then(|p| p.ip)+ .map(|ip| format!("{ip}:{}", config.debug_port)))+ }+ }+ }+}++fn parse_static_pods(raw: &str) -> anyhow::Result<Vec<StaticPod>> {+ raw.split(',')+ .map(str::trim)+ .filter(|entry| !entry.is_empty())+ .map(|entry| {+ let (name, address) = entry.split_once('=').ok_or_else(|| {+ anyhow!("invalid STATIC_PODS entry '{entry}' (expected name=host:port)")+ })?;+ let (name, address) = (name.trim(), address.trim());+ if name.is_empty() || address.is_empty() {+ return Err(anyhow!(+ "invalid STATIC_PODS entry '{entry}' (expected name=host:port)"+ ));+ }+ Ok(StaticPod {+ name: name.to_string(),+ address: address.to_string(),+ })+ })+ .collect()+}++/// Each configured selector is a single `key=value` pair.+fn matches_any_selector(labels: &BTreeMap<String, String>, selectors: &[String]) -> bool {+ selectors.iter().any(|selector| {+ selector.split_once('=').is_some_and(|(key, value)| {+ labels.get(key.trim()).map(String::as_str) == Some(value.trim())+ })+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn labels(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {+ pairs+ .iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect()+ }++ #[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(),+ ];+ assert!(matches_any_selector(&pod_labels, &selectors));+ }++ #[test]+ fn rejects_unmatched_labels_and_malformed_selectors() {+ 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()]+ ));+ }++ #[test]+ fn parses_static_pod_entries() {+ let pods = parse_static_pods("local=127.0.0.1:3301, other=10.0.0.5:3301").unwrap();+ assert_eq!(+ pods,+ vec![+ StaticPod {+ name: "local".to_string(),+ address: "127.0.0.1:3301".to_string(),+ },+ StaticPod {+ name: "other".to_string(),+ address: "10.0.0.5:3301".to_string(),+ },+ ]+ );+ }++ #[test]+ fn rejects_malformed_static_pod_entries() {+ assert!(parse_static_pods("just-an-address:3301").is_err());+ }++ #[tokio::test]+ async fn static_discovery_lists_and_resolves_without_k8s() {+ let discovery = PodDiscovery::Static(parse_static_pods("local=127.0.0.1:3301").unwrap());+ let config = test_config();++ let pods = discovery.list_pods(&config).await.unwrap();+ assert_eq!(pods.len(), 1);+ assert_eq!(pods[0].name, "local");+ assert!(pods[0].ready);++ let target = discovery+ .resolve_proxy_target(&config, "local")+ .await+ .unwrap();+ assert_eq!(target.as_deref(), Some("127.0.0.1:3301"));+ let missing = discovery+ .resolve_proxy_target(&config, "unknown")+ .await+ .unwrap();+ assert_eq!(missing, None);+ }++ fn test_config() -> Config {+ // envconfig has no direct "from defaults" constructor without env;+ // init from the current environment, which applies the defaults.+ Config::init_with_defaults().expect("config defaults are valid")+ }+}diff --git a/rust/ingestion-control-plane/src/kafka/analysis.rs b/rust/ingestion-control-plane/src/kafka/analysis.rsnew file mode 100644index 000000000000..875936378187--- /dev/null+++ b/rust/ingestion-control-plane/src/kafka/analysis.rs@@ -0,0 +1,405 @@+use std::collections::HashMap;++use common_types::CapturedEventHeaders;+use hdrhistogram::Histogram;+use serde::Serialize;++/// Cap on tracked token cardinality; messages for tokens beyond it are+/// counted in `token_overflow`.+const MAX_TRACKED_TOKENS: usize = 1_000;++/// Global cap on tracked distinct_id cardinality (across all tokens); beyond+/// it new ids are counted in the owning token's `distinct_id_overflow` so a+/// pathological partition can't balloon memory.+const MAX_TRACKED_DISTINCT_IDS: usize = 50_000;++/// Cumulative size-histogram bucket boundaries (bytes).+const SIZE_BUCKETS: &[u64] = &[+ 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304, 16777216,+];++/// How many events / distinct_ids to report per token.+const NESTED_TOP_K: usize = 10;++#[derive(Debug, Clone, Serialize)]+pub struct KeyCount {+ pub key: String,+ pub count: u64,+ /// Percentage relative to the owning token's messages.+ pub pct: f64,+}++/// Per-token (i.e. per-team) breakdown: events and distinct_ids are only+/// meaningful within a token, so they are nested here rather than reported+/// globally.+#[derive(Debug, Clone, Serialize)]+pub struct TokenBreakdown {+ pub token: String,+ pub team_id: Option<i32>,+ pub count: u64,+ /// Percentage relative to all analyzed messages.+ pub pct: f64,+ pub total_bytes: u64,+ pub top_events: Vec<KeyCount>,+ pub top_distinct_ids: Vec<KeyCount>,+ pub distinct_ids_tracked: u64,+ pub distinct_id_overflow: u64,+}++#[derive(Debug, Clone, Serialize)]+pub struct SizeBucket {+ pub le: u64,+ pub count: u64,+}++#[derive(Debug, Clone, Serialize)]+pub struct SizeStats {+ pub count: u64,+ pub min: u64,+ pub max: u64,+ pub mean: f64,+ pub p50: u64,+ pub p90: u64,+ pub p99: u64,+ pub total_bytes: u64,+ pub histogram: Vec<SizeBucket>,+}++#[derive(Debug, Clone, Default, Serialize)]+pub struct FlagCounts {+ pub historical_migration: u64,+ pub force_disable_person_processing: u64,+ pub missing_headers: u64,+ pub missing_token: u64,+}++/// Aggregates produced by one analysis run. `team_id` on tokens is filled in+/// afterwards by the token resolver.+#[derive(Debug, Clone, Serialize)]+pub struct Aggregates {+ pub messages: u64,+ pub top_tokens: Vec<TokenBreakdown>,+ pub tokens_tracked: u64,+ /// Messages whose token was beyond the tracked-token cap.+ pub token_overflow: u64,+ pub sizes: SizeStats,+ pub flags: FlagCounts,+}++#[derive(Default)]+struct TokenAgg {+ count: u64,+ total_bytes: u64,+ events: HashMap<String, u64>,+ distinct_ids: HashMap<String, u64>,+ distinct_id_overflow: u64,+}++/// Incremental, header-only aggregation over a partition's messages.+/// Pure data structure: feed it `(headers, payload_size)` pairs and call+/// [`Aggregator::finish`].+pub struct Aggregator {+ messages: u64,+ tokens: HashMap<String, TokenAgg>,+ token_overflow: u64,+ tracked_distinct_ids: usize,+ sizes: Histogram<u64>,+ total_bytes: u64,+ flags: FlagCounts,+}++impl Default for Aggregator {+ fn default() -> Self {+ Self::new()+ }+}++impl Aggregator {+ pub fn new() -> Self {+ let mut sizes = Histogram::new(3).expect("3 significant figures is always valid");+ sizes.auto(true);+ Self {+ messages: 0,+ tokens: HashMap::new(),+ token_overflow: 0,+ tracked_distinct_ids: 0,+ sizes,+ total_bytes: 0,+ flags: FlagCounts::default(),+ }+ }++ pub fn record(&mut self, headers: Option<&CapturedEventHeaders>, payload_size: u64) {+ self.messages += 1;+ self.total_bytes += payload_size;+ // Values beyond the auto-resized range cannot fail to record.+ self.sizes.record(payload_size).ok();++ let Some(headers) = headers else {+ self.flags.missing_headers += 1;+ return;+ };++ if headers.historical_migration == Some(true) {+ self.flags.historical_migration += 1;+ }+ if headers.force_disable_person_processing == Some(true) {+ self.flags.force_disable_person_processing += 1;+ }++ let Some(token) = &headers.token else {+ self.flags.missing_token += 1;+ return;+ };++ if self.tokens.len() >= MAX_TRACKED_TOKENS && !self.tokens.contains_key(token) {+ self.token_overflow += 1;+ return;+ }+ let token_agg = self.tokens.entry(token.clone()).or_default();+ token_agg.count += 1;+ token_agg.total_bytes += payload_size;++ if let Some(event) = &headers.event {+ *token_agg.events.entry(event.clone()).or_default() += 1;+ }+ if let Some(distinct_id) = &headers.distinct_id {+ if token_agg.distinct_ids.contains_key(distinct_id) {+ *token_agg+ .distinct_ids+ .entry(distinct_id.clone())+ .or_default() += 1;+ } else if self.tracked_distinct_ids < MAX_TRACKED_DISTINCT_IDS {+ token_agg.distinct_ids.insert(distinct_id.clone(), 1);+ self.tracked_distinct_ids += 1;+ } else {+ token_agg.distinct_id_overflow += 1;+ }+ }+ }++ pub fn finish(self, top_k: usize) -> Aggregates {+ let messages = self.messages;+ let overall_pct = |count: u64| {+ if messages == 0 {+ 0.0+ } else {+ (count as f64 / messages as f64) * 100.0+ }+ };++ let mut histogram = Vec::with_capacity(SIZE_BUCKETS.len());+ for &le in SIZE_BUCKETS {+ histogram.push(SizeBucket {+ le,+ count: self.sizes.count_between(0, le),+ });+ }++ // Zero out stats for an empty analysis (e.g. a committed offset+ // already at the high watermark) rather than deriving them from an+ // empty histogram.+ let sizes = if self.sizes.is_empty() {+ SizeStats {+ count: 0,+ min: 0,+ max: 0,+ mean: 0.0,+ p50: 0,+ p90: 0,+ p99: 0,+ total_bytes: self.total_bytes,+ histogram,+ }+ } else {+ SizeStats {+ count: self.sizes.len(),+ min: self.sizes.min(),+ max: self.sizes.max(),+ mean: self.sizes.mean(),+ p50: self.sizes.value_at_quantile(0.5),+ p90: self.sizes.value_at_quantile(0.9),+ p99: self.sizes.value_at_quantile(0.99),+ total_bytes: self.total_bytes,+ histogram,+ }+ };++ let tokens_tracked = self.tokens.len() as u64;+ let mut entries: Vec<(String, TokenAgg)> = self.tokens.into_iter().collect();+ entries.sort_by(|a, b| b.1.count.cmp(&a.1.count).then_with(|| a.0.cmp(&b.0)));++ let top_tokens = entries+ .into_iter()+ .take(top_k)+ .map(|(token, agg)| {+ let token_pct = |count: u64| {+ if agg.count == 0 {+ 0.0+ } else {+ (count as f64 / agg.count as f64) * 100.0+ }+ };+ let distinct_ids_tracked = agg.distinct_ids.len() as u64;+ TokenBreakdown {+ token,+ team_id: None,+ count: agg.count,+ pct: overall_pct(agg.count),+ total_bytes: agg.total_bytes,+ top_events: top_counts(agg.events, NESTED_TOP_K, token_pct),+ top_distinct_ids: top_counts(agg.distinct_ids, NESTED_TOP_K, token_pct),+ distinct_ids_tracked,+ distinct_id_overflow: agg.distinct_id_overflow,+ }+ })+ .collect();++ Aggregates {+ messages,+ top_tokens,+ tokens_tracked,+ token_overflow: self.token_overflow,+ sizes,+ flags: self.flags,+ }+ }+}++fn top_counts(+ counts: HashMap<String, u64>,+ top_k: usize,+ pct: impl Fn(u64) -> f64,+) -> Vec<KeyCount> {+ let mut entries: Vec<(String, u64)> = counts.into_iter().collect();+ entries.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));+ entries+ .into_iter()+ .take(top_k)+ .map(|(key, count)| KeyCount {+ key,+ count,+ pct: pct(count),+ })+ .collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ fn headers(token: &str, distinct_id: &str, event: &str) -> CapturedEventHeaders {+ CapturedEventHeaders {+ token: Some(token.to_string()),+ distinct_id: Some(distinct_id.to_string()),+ session_id: None,+ timestamp: None,+ event: Some(event.to_string()),+ uuid: None,+ now: None,+ force_disable_person_processing: None,+ historical_migration: None,+ skip_heatmap_processing: None,+ dlq_reason: None,+ dlq_step: None,+ dlq_timestamp: None,+ content_encoding: None,+ }+ }++ #[test]+ fn nests_events_and_distinct_ids_per_token() {+ let mut agg = Aggregator::new();+ for _ in 0..6 {+ agg.record(Some(&headers("token_a", "user_hot", "$pageview")), 100);+ }+ agg.record(Some(&headers("token_a", "user_other", "$identify")), 100);+ for _ in 0..3 {+ agg.record(Some(&headers("token_b", "user_b", "$identify")), 1000);+ }+ let result = agg.finish(10);++ assert_eq!(result.messages, 10);+ assert_eq!(result.top_tokens.len(), 2);++ let a = &result.top_tokens[0];+ assert_eq!(a.token, "token_a");+ assert_eq!(a.count, 7);+ assert!((a.pct - 70.0).abs() < f64::EPSILON);+ assert_eq!(a.total_bytes, 700);+ assert_eq!(a.top_events[0].key, "$pageview");+ assert_eq!(a.top_events[0].count, 6);+ // Nested pct is relative to the token, not all messages.+ assert!((a.top_events[0].pct - (6.0 / 7.0 * 100.0)).abs() < 0.001);+ assert_eq!(a.top_distinct_ids[0].key, "user_hot");++ let b = &result.top_tokens[1];+ assert_eq!(b.token, "token_b");+ assert_eq!(b.top_events[0].key, "$identify");+ assert!((b.top_events[0].pct - 100.0).abs() < f64::EPSILON);+ }++ #[test]+ fn respects_top_k_for_tokens() {+ let mut agg = Aggregator::new();+ for i in 0..20 {+ agg.record(Some(&headers(&format!("token_{i}"), "d", "e")), 10);+ }+ let result = agg.finish(5);+ assert_eq!(result.top_tokens.len(), 5);+ assert_eq!(result.tokens_tracked, 20);+ }++ #[test]+ fn counts_missing_headers_and_flags() {+ let mut agg = Aggregator::new();+ agg.record(None, 50);+ let mut h = headers("t", "d", "e");+ h.historical_migration = Some(true);+ h.force_disable_person_processing = Some(true);+ agg.record(Some(&h), 60);+ let mut no_token = headers("t", "d", "e");+ no_token.token = None;+ agg.record(Some(&no_token), 70);++ let result = agg.finish(10);+ assert_eq!(result.flags.missing_headers, 1);+ assert_eq!(result.flags.historical_migration, 1);+ assert_eq!(result.flags.force_disable_person_processing, 1);+ assert_eq!(result.flags.missing_token, 1);+ }++ #[test]+ fn size_histogram_buckets_are_cumulative() {+ let mut agg = Aggregator::new();+ agg.record(None, 100);+ agg.record(None, 2000);+ agg.record(None, 2_000_000);+ let result = agg.finish(10);++ let bucket = |le: u64| {+ result+ .sizes+ .histogram+ .iter()+ .find(|b| b.le == le)+ .unwrap()+ .count+ };+ assert_eq!(bucket(256), 1);+ assert_eq!(bucket(4096), 2);+ assert_eq!(bucket(16777216), 3);+ }++ #[test]+ fn empty_aggregation_is_well_formed() {+ let result = Aggregator::new().finish(10);+ assert_eq!(result.messages, 0);+ assert_eq!(result.sizes.count, 0);+ assert_eq!(result.sizes.mean, 0.0);+ assert_eq!(result.sizes.p99, 0);+ assert!(result.top_tokens.is_empty());+ // The result must stay JSON-serializable (no NaN from empty stats).+ assert!(serde_json::to_string(&result).is_ok());+ }+}diff --git a/rust/ingestion-control-plane/src/kafka/client.rs b/rust/ingestion-control-plane/src/kafka/client.rsnew file mode 100644index 000000000000..06773a9ff2e5--- /dev/null+++ b/rust/ingestion-control-plane/src/kafka/client.rs@@ -0,0 +1,59 @@+use rdkafka::config::ClientConfig;+use rdkafka::consumer::BaseConsumer;+use rdkafka::error::KafkaResult;++use crate::config::Config;++/// Group id used by message-fetching consumers. Distinct from any real+/// ingestion group so inspection can never touch production offsets.+pub const INSPECTOR_GROUP_ID: &str = "ingestion-control-plane-inspector";++fn base_client_config(config: &Config) -> ClientConfig {+ let mut cfg = ClientConfig::new();+ cfg.set("bootstrap.servers", &config.kafka_hosts);+ // Certificate verification is disabled against MSK across the whole+ // workspace (see common-kafka and ingestion-consumer's kafka_config);+ // stay consistent with the fleet.+ if config.kafka_tls {+ cfg.set("security.protocol", "ssl")+ .set("enable.ssl.certificate.verification", "false");+ }+ if let Some(rack) = config+ .kafka_client_rack+ .as_deref()+ .filter(|r| !r.is_empty())+ {+ cfg.set("client.rack", rack);+ }+ cfg+}++/// Lightweight client for metadata and watermark queries: no group id,+/// never subscribes or polls.+pub fn metadata_consumer(config: &Config) -> KafkaResult<BaseConsumer> {+ base_client_config(config).create()+}++/// Client for reading a consumer group's committed offsets. Auto commit and+/// auto offset store are disabled so instantiating it with the real group id+/// can never mutate that group's stored offsets.+pub fn group_offsets_consumer(config: &Config, group: &str) -> KafkaResult<BaseConsumer> {+ let mut cfg = base_client_config(config);+ cfg.set("group.id", group)+ .set("enable.auto.commit", "false")+ .set("enable.auto.offset.store", "false");+ cfg.create()+}++/// Client for fetching message ranges during an analysis. Uses the inspector+/// group id and bounds librdkafka's prefetch queue so a partition of large+/// messages doesn't balloon memory.+pub fn fetch_consumer(config: &Config) -> KafkaResult<BaseConsumer> {+ let mut cfg = base_client_config(config);+ cfg.set("group.id", INSPECTOR_GROUP_ID)+ .set("enable.auto.commit", "false")+ .set("enable.auto.offset.store", "false")+ .set("queued.max.messages.kbytes", "65536")+ .set("fetch.message.max.bytes", "10485760");+ cfg.create()+}diff --git a/rust/ingestion-control-plane/src/kafka/fetch.rs b/rust/ingestion-control-plane/src/kafka/fetch.rsnew file mode 100644index 000000000000..d91819b934be--- /dev/null+++ b/rust/ingestion-control-plane/src/kafka/fetch.rs@@ -0,0 +1,115 @@+use std::time::{Duration, Instant};++use anyhow::Context;+use common_types::CapturedEventHeaders;+use rdkafka::consumer::{BaseConsumer, Consumer};+use rdkafka::message::Message;+use rdkafka::{Offset, TopicPartitionList};+use serde::Serialize;+use tokio_util::sync::CancellationToken;++use crate::jobs::Progress;+use crate::kafka::analysis::Aggregator;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum TruncatedReason {+ Deadline,+ ByteBudget,+ ReachedHwm,+ Canceled,+}++pub struct FetchParams {+ pub topic: String,+ pub partition: i32,+ pub start_offset: i64,+ /// Where to stop reading (already clamped to the high watermark).+ pub end_offset_exclusive: i64,+ /// `start_offset + requested message count`, before clamping; used to+ /// report `reached_hwm` truncation.+ pub requested_end_offset: i64,+ pub deadline: Duration,+ pub max_bytes: u64,+ pub poll_timeout: Duration,+}++pub struct FetchOutcome {+ pub aggregator: Aggregator,+ /// Next unread offset when the fetch stopped.+ pub next_offset: i64,+ pub truncated_reason: Option<TruncatedReason>,+ pub duration_ms: u64,+}++/// Read `[start_offset, end_offset_exclusive)` from one partition, feeding+/// header-only samples into an [`Aggregator`]. Payloads are dropped+/// immediately; only their length is recorded. Synchronous — run on the+/// blocking pool.+pub fn run_fetch(+ consumer: &BaseConsumer,+ params: &FetchParams,+ progress: &Progress,+ cancel: &CancellationToken,+) -> anyhow::Result<FetchOutcome> {+ let mut tpl = TopicPartitionList::new();+ tpl.add_partition_offset(+ ¶ms.topic,+ params.partition,+ Offset::Offset(params.start_offset),+ )+ .context("build assignment")?;+ consumer.assign(&tpl).context("assign partition")?;++ let started = Instant::now();+ let mut aggregator = Aggregator::new();+ let mut next_offset = params.start_offset;+ let mut bytes_read: u64 = 0;+ let mut truncated_reason = None;++ while next_offset < params.end_offset_exclusive {+ if cancel.is_cancelled() {+ truncated_reason = Some(TruncatedReason::Canceled);+ break;+ }+ if started.elapsed() >= params.deadline {+ truncated_reason = Some(TruncatedReason::Deadline);+ break;+ }++ let Some(result) = consumer.poll(params.poll_timeout) else {+ continue;+ };+ let message = result.context("poll partition")?;+ // librdkafka prefetches; drop anything past the requested range.+ if message.offset() >= params.end_offset_exclusive {+ break;+ }++ let payload_size = message.payload_len() as u64;+ let headers = message+ .headers()+ .map(|h| CapturedEventHeaders::from(h.detach()));+ aggregator.record(headers.as_ref(), payload_size);++ next_offset = message.offset() + 1;+ bytes_read += payload_size;+ progress.record(next_offset, payload_size);++ if bytes_read >= params.max_bytes {+ truncated_reason = Some(TruncatedReason::ByteBudget);+ break;+ }+ }++ if truncated_reason.is_none() && params.end_offset_exclusive < params.requested_end_offset {+ truncated_reason = Some(TruncatedReason::ReachedHwm);+ }++ Ok(FetchOutcome {+ aggregator,+ next_offset,+ truncated_reason,+ duration_ms: started.elapsed().as_millis() as u64,+ })+}diff --git a/rust/ingestion-control-plane/src/kafka/lag.rs b/rust/ingestion-control-plane/src/kafka/lag.rsnew file mode 100644index 000000000000..744077f87b25--- /dev/null+++ b/rust/ingestion-control-plane/src/kafka/lag.rs@@ -0,0 +1,271 @@+use std::collections::HashMap;+use std::sync::Arc;+use std::time::Duration;++use anyhow::{anyhow, Context};+use futures::stream::{self, StreamExt};+use rdkafka::consumer::{BaseConsumer, Consumer};+use rdkafka::{Offset, TopicPartitionList};+use serde::Serialize;++use crate::config::{Config, ConsumerTarget};+use crate::kafka::client;++#[derive(Debug, Clone, Serialize)]+pub struct PartitionLag {+ pub partition: i32,+ pub low_watermark: i64,+ pub high_watermark: i64,+ pub committed_offset: Option<i64>,+ pub lag: i64,+}++#[derive(Debug, Serialize)]+pub struct GroupLag {+ pub group: String,+ pub topic: String,+ pub fetched_at: String,+ pub partitions: Vec<PartitionLag>,+}++/// Remaining messages for the group on one partition.+///+/// A committed offset below the low watermark means retention already deleted+/// messages past it, so only `high - low` messages are actually fetchable; a+/// committed offset above the high watermark (possible when reading the two+/// values non-atomically) clamps to zero. Without any commit, the whole+/// retained range is outstanding.+pub fn compute_lag(low: i64, high: i64, committed: Option<i64>) -> i64 {+ match committed {+ Some(c) => high - c.clamp(low, high),+ None => high - low,+ }+}++/// Scan committed offsets and watermarks for every partition of the target+/// group's topic. All rdkafka metadata calls are synchronous and run on the+/// blocking pool.+pub async fn scan_group_lag(config: &Config, target: &ConsumerTarget) -> anyhow::Result<GroupLag> {+ let timeout = Duration::from_millis(config.kafka_metadata_timeout_ms);+ let fetched_at = chrono::Utc::now().to_rfc3339();++ let (partitions, committed, consumer) = {+ let config = config.clone();+ let target = target.clone();+ tokio::task::spawn_blocking(move || {+ fetch_partitions_and_committed(&config, &target, timeout)+ })+ .await+ .context("offset scan task panicked")??+ };++ let consumer = Arc::new(consumer);+ let topic = target.topic.clone();+ let mut partition_lags: Vec<PartitionLag> = stream::iter(partitions)+ .map(|partition| {+ let consumer = Arc::clone(&consumer);+ let topic = topic.clone();+ async move {+ tokio::task::spawn_blocking(move || {+ consumer+ .fetch_watermarks(&topic, partition, timeout)+ .map(|(low, high)| (partition, low, high))+ .with_context(|| format!("fetch watermarks for partition {partition}"))+ })+ .await+ .context("watermark task panicked")?+ }+ })+ .buffer_unordered(16)+ .collect::<Vec<_>>()+ .await+ .into_iter()+ .map(|res| {+ res.map(|(partition, low, high)| {+ let committed_offset = committed.get(&partition).copied().flatten();+ PartitionLag {+ partition,+ low_watermark: low,+ high_watermark: high,+ committed_offset,+ lag: compute_lag(low, high, committed_offset),+ }+ })+ })+ .collect::<anyhow::Result<_>>()?;++ partition_lags.sort_by(|a, b| b.lag.cmp(&a.lag).then(a.partition.cmp(&b.partition)));++ Ok(GroupLag {+ group: target.group.clone(),+ topic: target.topic.clone(),+ fetched_at,+ partitions: partition_lags,+ })+}++/// 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)]+pub struct GroupLagSummary {+ pub group: String,+ pub topic: String,+ pub partitions: usize,+ pub lagging_partitions: usize,+ pub total_lag: i64,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub error: Option<String>,+}++/// 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 {+ match scan_group_lag(config, &target).await {+ Ok(group_lag) => GroupLagSummary {+ group: target.group,+ topic: target.topic,+ partitions: group_lag.partitions.len(),+ lagging_partitions: group_lag.partitions.iter().filter(|p| p.lag > 0).count(),+ total_lag: group_lag.partitions.iter().map(|p| p.lag).sum(),+ error: None,+ },+ Err(e) => GroupLagSummary {+ group: target.group,+ topic: target.topic,+ partitions: 0,+ lagging_partitions: 0,+ total_lag: 0,+ error: Some(format!("{e:#}")),+ },+ }+ }))+ .await;++ let mut summaries = summaries;+ summaries.sort_by(|a, b| b.total_lag.cmp(&a.total_lag).then(a.group.cmp(&b.group)));+ summaries+}++/// Watermarks and committed offset for a single partition, read at analysis+/// submit time. Synchronous — run on the blocking pool.+#[derive(Debug, Clone, Copy)]+pub struct PartitionBounds {+ pub low_watermark: i64,+ pub high_watermark: i64,+ pub committed_offset: Option<i64>,+}++pub fn fetch_partition_bounds_blocking(+ config: &Config,+ target: &ConsumerTarget,+ partition: i32,+ timeout: Duration,+) -> anyhow::Result<PartitionBounds> {+ let metadata_consumer = client::metadata_consumer(config).context("create metadata client")?;+ let (low_watermark, high_watermark) = metadata_consumer+ .fetch_watermarks(&target.topic, partition, timeout)+ .with_context(|| {+ format!(+ "fetch watermarks for '{}' partition {partition}",+ target.topic+ )+ })?;++ let group_consumer =+ client::group_offsets_consumer(config, &target.group).context("create group client")?;+ let mut tpl = TopicPartitionList::new();+ tpl.add_partition(&target.topic, partition);+ let committed_tpl = group_consumer+ .committed_offsets(tpl, timeout)+ .with_context(|| format!("fetch committed offset for group '{}'", target.group))?;+ let committed_offset = committed_tpl+ .find_partition(&target.topic, partition)+ .and_then(|elem| match elem.offset() {+ Offset::Offset(o) => Some(o),+ _ => None,+ });++ Ok(PartitionBounds {+ low_watermark,+ high_watermark,+ committed_offset,+ })+}++type PartitionsAndCommitted = (Vec<i32>, HashMap<i32, Option<i64>>, BaseConsumer);++fn fetch_partitions_and_committed(+ config: &Config,+ target: &ConsumerTarget,+ timeout: Duration,+) -> anyhow::Result<PartitionsAndCommitted> {+ let metadata_consumer = client::metadata_consumer(config).context("create metadata client")?;+ let metadata = metadata_consumer+ .fetch_metadata(Some(&target.topic), timeout)+ .with_context(|| format!("fetch metadata for topic '{}'", target.topic))?;+ let topic_metadata = metadata+ .topics()+ .iter()+ .find(|t| t.name() == target.topic)+ .ok_or_else(|| anyhow!("topic '{}' not found", target.topic))?;+ if let Some(err) = topic_metadata.error() {+ return Err(anyhow!(+ "broker returned error for topic '{}': {err:?}",+ target.topic+ ));+ }+ let partitions: Vec<i32> = topic_metadata.partitions().iter().map(|p| p.id()).collect();+ if partitions.is_empty() {+ return Err(anyhow!("topic '{}' has no partitions", target.topic));+ }++ let group_consumer =+ client::group_offsets_consumer(config, &target.group).context("create group client")?;+ let mut tpl = TopicPartitionList::new();+ for partition in &partitions {+ tpl.add_partition(&target.topic, *partition);+ }+ let committed_tpl = group_consumer+ .committed_offsets(tpl, timeout)+ .with_context(|| format!("fetch committed offsets for group '{}'", target.group))?;++ let committed: HashMap<i32, Option<i64>> = committed_tpl+ .elements()+ .iter()+ .map(|elem| {+ let offset = match elem.offset() {+ Offset::Offset(o) => Some(o),+ _ => None,+ };+ (elem.partition(), offset)+ })+ .collect();++ Ok((partitions, committed, metadata_consumer))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn lag_is_high_minus_committed() {+ assert_eq!(compute_lag(0, 100, Some(40)), 60);+ }++ #[test]+ fn no_commit_means_whole_retained_range() {+ assert_eq!(compute_lag(10, 100, None), 90);+ }++ #[test]+ fn committed_below_low_watermark_clamps_to_retained_range() {+ assert_eq!(compute_lag(50, 100, Some(10)), 50);+ }++ #[test]+ fn committed_above_high_watermark_clamps_to_zero() {+ assert_eq!(compute_lag(0, 100, Some(120)), 0);+ }+}diff --git a/rust/ingestion-control-plane/src/kafka/mod.rs b/rust/ingestion-control-plane/src/kafka/mod.rsnew file mode 100644index 000000000000..7f42bfdc69d1--- /dev/null+++ b/rust/ingestion-control-plane/src/kafka/mod.rs@@ -0,0 +1,4 @@+pub mod analysis;+pub mod client;+pub mod fetch;+pub mod lag;diff --git a/rust/ingestion-control-plane/src/lib.rs b/rust/ingestion-control-plane/src/lib.rsnew file mode 100644index 000000000000..81feb6c7de81--- /dev/null+++ b/rust/ingestion-control-plane/src/lib.rs@@ -0,0 +1,9 @@+pub mod api;+pub mod config;+pub mod jobs;+pub mod k8s;+pub mod kafka;+pub mod proxy;+pub mod state;+pub mod teams;+pub mod ui;diff --git a/rust/ingestion-control-plane/src/main.rs b/rust/ingestion-control-plane/src/main.rsnew file mode 100644index 000000000000..343476be5e42--- /dev/null+++ b/rust/ingestion-control-plane/src/main.rs@@ -0,0 +1,85 @@+use std::future::ready;+use std::time::Duration;++use axum::routing::get;+use common_metrics::setup_metrics_routes;+use health::{readiness_handler, HealthRegistry};+use ingestion_control_plane::api;+use ingestion_control_plane::config::Config;+use ingestion_control_plane::state::AppState;+use tokio::signal;+use tracing::info;+use tracing::level_filters::LevelFilter;+use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer};++common_alloc::used!();++async fn shutdown() {+ let mut term = signal::unix::signal(signal::unix::SignalKind::terminate())+ .expect("failed to register SIGTERM handler");+ let mut interrupt = signal::unix::signal(signal::unix::SignalKind::interrupt())+ .expect("failed to register SIGINT handler");++ tokio::select! {+ _ = term.recv() => {},+ _ = interrupt.recv() => {},+ };++ info!("Shutting down gracefully...");+}++fn setup_tracing() {+ let log_layer = tracing_subscriber::fmt::layer().json().with_filter(+ EnvFilter::builder()+ .with_default_directive(LevelFilter::INFO.into())+ .from_env_lossy(),+ );+ tracing_subscriber::registry().with(log_layer).init();+}++#[tokio::main]+async fn main() {+ setup_tracing();+ info!("Starting ingestion-control-plane...");++ // kube's rustls-based client needs a process-wide crypto provider.+ rustls::crypto::ring::default_provider()+ .install_default()+ .expect("failed to install rustls crypto provider");++ let config = Config::init_with_defaults().expect("failed to load config");+ let bind = format!("{}:{}", config.host, config.port);++ // This service has no long-running pipeline to healthcheck; a heartbeat+ // task proves the runtime is alive so the liveness probe passes.+ let health_registry = HealthRegistry::new("liveness");+ let heartbeat = health_registry+ .register("heartbeat".to_string(), Duration::from_secs(30))+ .await;+ tokio::spawn(async move {+ loop {+ heartbeat.report_healthy().await;+ tokio::time::sleep(Duration::from_secs(10)).await;+ }+ });++ let state = AppState::new(config).expect("failed to initialize app state");++ let router = api::router(state)+ .route("/_readiness", get(readiness_handler))+ .route(+ "/_liveness",+ get(move || ready(health_registry.get_status())),+ );+ let router = setup_metrics_routes(router);++ info!("Listening on {}", bind);+ let listener = tokio::net::TcpListener::bind(bind)+ .await+ .expect("could not bind port");++ axum::serve(listener, router)+ .with_graceful_shutdown(shutdown())+ .await+ .expect("server failed");+}diff --git a/rust/ingestion-control-plane/src/proxy.rs b/rust/ingestion-control-plane/src/proxy.rsnew file mode 100644index 000000000000..82babdde33e5--- /dev/null+++ b/rust/ingestion-control-plane/src/proxy.rs@@ -0,0 +1,115 @@+use axum::body::Body;+use axum::extract::{Path, RawQuery, State};+use axum::http::{header, StatusCode};+use axum::response::Response;++use crate::api::ApiError;+use crate::state::AppState;++/// The wildcard path is interpolated into the upstream URL; dot segments —+/// including percent-encoded ones, which URL parsers decode and normalize —+/// could otherwise escape the `/debug/` prefix and reach other endpoints on+/// the pod. Debug API paths only ever use simple names, so enforce a strict+/// character allowlist instead of chasing encodings.+fn is_safe_debug_path(rest: &str) -> bool {+ !rest.is_empty()+ && rest.split('/').all(|segment| {+ !segment.is_empty()+ && !segment.starts_with('.')+ && segment+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.')+ })+}++fn build_upstream_url(target: &str, rest: &str, query: Option<&str>) -> String {+ match query {+ Some(query) => format!("http://{target}/debug/{rest}?{query}"),+ None => format!("http://{target}/debug/{rest}"),+ }+}++/// 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.+pub async fn proxy_debug(+ State(state): State<AppState>,+ Path((name, rest)): Path<(String, String)>,+ RawQuery(query): RawQuery,+) -> Result<Response, ApiError> {+ if !is_safe_debug_path(&rest) {+ return Err(ApiError::bad_request("invalid debug path"));+ }++ let target = state+ .pods+ .resolve_proxy_target(&state.config, &name)+ .await+ .map_err(|e| ApiError::unavailable(format!("pod discovery unavailable: {e:#}")))?+ .ok_or_else(|| ApiError::not_found(format!("no matching pod '{name}'")))?;++ let url = build_upstream_url(&target, &rest, query.as_deref());+ let mut request = state.http.get(&url);+ // The consumer's debug API fails closed: every request must carry the+ // shared per-hop secret. Attached here — never forwarded from the browser —+ // so the control plane is the trust boundary for its clients.+ if let Some(secret) = state+ .config+ .debug_api_secret+ .as_deref()+ .filter(|s| !s.is_empty())+ {+ request = request.header("X-Debug-Api-Secret", secret);+ }+ let upstream = request+ .send()+ .await+ .map_err(|e| ApiError::upstream(format!("debug API request to '{name}' failed: {e}")))?;++ let status =+ StatusCode::from_u16(upstream.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);+ let mut builder = Response::builder()+ .status(status)+ .header(header::CACHE_CONTROL, "no-cache");+ if let Some(content_type) = upstream.headers().get(header::CONTENT_TYPE) {+ builder = builder.header(header::CONTENT_TYPE, content_type);+ }+ builder+ .body(Body::from_stream(upstream.bytes_stream()))+ .map_err(|e| ApiError::upstream(format!("failed to build proxy response: {e}")))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn rejects_dot_segments_encodings_and_empty_paths() {+ assert!(is_safe_debug_path("state"));+ assert!(is_safe_debug_path("events"));+ assert!(is_safe_debug_path("some/nested/path-1_2.json"));+ assert!(!is_safe_debug_path(""));+ assert!(!is_safe_debug_path(".."));+ assert!(!is_safe_debug_path("../metrics"));+ assert!(!is_safe_debug_path("state/../../admin"));+ assert!(!is_safe_debug_path("./state"));+ assert!(!is_safe_debug_path("..\\metrics"));+ // Percent-encoded dot segments (single- or double-encoded) would be+ // normalized out of /debug/ by the upstream URL parser.+ assert!(!is_safe_debug_path("%2e%2e/metrics"));+ assert!(!is_safe_debug_path("%252e%252e/metrics"));+ assert!(!is_safe_debug_path("state//admin"));+ }++ #[test]+ fn forwards_query_string() {+ assert_eq!(+ build_upstream_url("10.0.0.7:3301", "events", Some("limit=10")),+ "http://10.0.0.7:3301/debug/events?limit=10"+ );+ assert_eq!(+ build_upstream_url("10.0.0.7:3301", "state", None),+ "http://10.0.0.7:3301/debug/state"+ );+ }+}diff --git a/rust/ingestion-control-plane/src/state.rs b/rust/ingestion-control-plane/src/state.rsnew file mode 100644index 000000000000..5ddc13db00ab--- /dev/null+++ b/rust/ingestion-control-plane/src/state.rs@@ -0,0 +1,57 @@+use std::sync::Arc;+use std::time::Duration;++use common_database::PoolConfig;++use crate::config::Config;+use crate::jobs::JobRegistry;+use crate::k8s::PodDiscovery;+use crate::teams::TeamResolver;++#[derive(Clone)]+pub struct AppState {+ pub config: Arc<Config>,+ pub jobs: Arc<JobRegistry>,+ pub teams: Arc<TeamResolver>,+ pub pods: Arc<PodDiscovery>,+ pub http: reqwest::Client,+}++impl AppState {+ pub fn new(config: Config) -> anyhow::Result<Self> {+ // Treat set-but-empty like unset so a templated empty env var can't+ // half-enable resolution with an unusable URL.+ let pool = match config.database_url.as_deref().filter(|url| !url.is_empty()) {+ None => {+ tracing::info!("DATABASE_URL not set; token -> team resolution disabled");+ None+ }+ Some(database_url) => {+ let pool_config = PoolConfig {+ max_connections: config.pg_max_connections,+ pool_name: Some("ingestion-control-plane".to_string()),+ ..PoolConfig::default()+ };+ Some(common_database::get_pool_with_config(+ database_url,+ pool_config,+ )?)+ }+ };++ // No overall request timeout: the debug proxy pipes long-lived SSE+ // streams. Connect timeout still bounds unreachable pods.+ let http = reqwest::Client::builder()+ .connect_timeout(Duration::from_secs(2))+ .build()+ .expect("reqwest client construction cannot fail with static config");++ Ok(Self {+ jobs: Arc::new(JobRegistry::new(config.analysis_max_concurrent_jobs)),+ teams: Arc::new(TeamResolver::new(pool)),+ pods: Arc::new(PodDiscovery::from_config(&config)?),+ http,+ config: Arc::new(config),+ })+ }+}diff --git a/rust/ingestion-control-plane/src/teams.rs b/rust/ingestion-control-plane/src/teams.rsnew file mode 100644index 000000000000..15c59337df64--- /dev/null+++ b/rust/ingestion-control-plane/src/teams.rs@@ -0,0 +1,71 @@+use std::collections::HashMap;++use dashmap::DashMap;+use sqlx::PgPool;++/// Resolves capture tokens to team ids against the app database read replica.+/// Tokens are effectively immutable, so hits and misses are cached for the+/// process lifetime. With no pool configured, every token resolves to `None`.+pub struct TeamResolver {+ pool: Option<PgPool>,+ cache: DashMap<String, Option<i32>>,+}++impl TeamResolver {+ pub fn new(pool: Option<PgPool>) -> Self {+ Self {+ pool,+ cache: DashMap::new(),+ }+ }++ pub async fn resolve(&self, tokens: &[String]) -> HashMap<String, Option<i32>> {+ let mut resolved: HashMap<String, Option<i32>> = HashMap::new();+ let mut misses: Vec<String> = Vec::new();+ for token in tokens {+ match self.cache.get(token) {+ Some(entry) => {+ resolved.insert(token.clone(), *entry.value());+ }+ None => misses.push(token.clone()),+ }+ }++ let Some(pool) = &self.pool else {+ for token in misses {+ resolved.insert(token, None);+ }+ return resolved;+ };++ if !misses.is_empty() {+ match sqlx::query_as::<_, (i32, String)>(+ "SELECT id, api_token FROM posthog_team WHERE api_token = ANY($1)",+ )+ .bind(&misses)+ .fetch_all(pool)+ .await+ {+ Ok(rows) => {+ let found: HashMap<String, i32> =+ rows.into_iter().map(|(id, token)| (token, id)).collect();+ for token in misses {+ let team_id = found.get(&token).copied();+ self.cache.insert(token.clone(), team_id);+ resolved.insert(token, team_id);+ }+ }+ Err(e) => {+ // Team resolution is best-effort enrichment; the analysis+ // is still useful without it.+ tracing::warn!(error = %e, "token -> team resolution failed");+ for token in misses {+ resolved.insert(token, None);+ }+ }+ }+ }++ resolved+ }+}diff --git a/rust/ingestion-control-plane/src/ui.rs b/rust/ingestion-control-plane/src/ui.rsnew file mode 100644index 000000000000..a169744d58d2--- /dev/null+++ b/rust/ingestion-control-plane/src/ui.rs@@ -0,0 +1,12 @@+use axum::response::Html;++pub async fn index() -> Html<&'static str> {+ Html(include_str!("ui/index.html"))+}++/// The ingestion-consumer's debug UI, served per pod at `/pods/:name/` so its+/// relative `debug/...` fetches resolve to this service's per-pod proxy. The+/// UI lives here (the control plane); the consumer only exposes the debug API.+pub async fn consumer_debug() -> Html<&'static str> {+ Html(include_str!("ui/consumer_debug.html"))+}diff --git a/rust/ingestion-control-plane/src/ui/consumer_debug.html b/rust/ingestion-control-plane/src/ui/consumer_debug.htmlnew file mode 100644index 000000000000..a213e30f76b7--- /dev/null+++ b/rust/ingestion-control-plane/src/ui/consumer_debug.html@@ -0,0 +1,717 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>Ingestion consumer · routing debug</title>+ <style>+ :root {+ --bg: #14161a;+ --panel: #1c1f26;+ --panel-2: #23272f;+ --border: #2c313b;+ --text: #e6e9ef;+ --muted: #8b93a1;+ --accent: #4f7cff;+ --good: #3fb950;+ --warn: #d29922;+ --error: #f85149;+ --mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;+ }+ * { box-sizing: border-box; }+ body {+ margin: 0;+ background: var(--bg);+ color: var(--text);+ font: 13px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;+ }+ header {+ display: flex; align-items: baseline; gap: 16px;+ padding: 12px 18px; border-bottom: 1px solid var(--border);+ background: var(--panel); position: sticky; top: 0; z-index: 5; flex-wrap: wrap;+ }+ header h1 { font-size: 15px; margin: 0; font-weight: 600; }+ header .meta { color: var(--muted); font-family: var(--mono); font-size: 12px; }+ .dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 6px; }+ .dot.live { background: var(--good); box-shadow: 0 0 6px var(--good); }+ .dot.down { background: var(--error); }+ .layout { display: grid; grid-template-columns: minmax(0, 360px) minmax(0, 1fr); gap: 14px; padding: 14px; }+ @media (max-width: 900px) { .layout { grid-template-columns: 1fr; } }+ .panel { background: var(--panel); border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }+ .panel > h2 {+ font-size: 12px; text-transform: uppercase; letter-spacing: 0.06em;+ color: var(--muted); margin: 0; padding: 10px 14px; border-bottom: 1px solid var(--border);+ display: flex; justify-content: space-between; align-items: center;+ }+ .stats { display: flex; flex-wrap: wrap; gap: 10px; padding: 12px 14px; }+ .stat { background: var(--panel-2); border: 1px solid var(--border); border-radius: 6px; padding: 8px 12px; min-width: 84px; }+ .stat .n { font-size: 20px; font-weight: 600; font-family: var(--mono); }+ .stat .l { font-size: 11px; color: var(--muted); }+ table { width: 100%; border-collapse: collapse; }+ th, td { text-align: left; padding: 7px 14px; border-bottom: 1px solid var(--border); font-size: 12px; }+ th { color: var(--muted); font-weight: 500; font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; }+ td.mono, th.mono { font-family: var(--mono); }+ td .bar { height: 6px; border-radius: 3px; background: var(--accent); min-width: 2px; }+ .pill { display: inline-block; padding: 1px 7px; border-radius: 10px; font-size: 11px; font-weight: 600; white-space: nowrap; }+ .pill.healthy, .pill.committed { background: rgba(63,185,80,0.16); color: var(--good); }+ .pill.degraded, .pill.retrying, .pill.stashed { background: rgba(210,153,34,0.16); color: var(--warn); }+ .pill.unhealthy, .pill.stalled, .pill.failed { background: rgba(248,81,73,0.16); color: var(--error); }+ .pill.draining, .pill.inflight { background: rgba(139,147,161,0.18); color: var(--muted); }+ .pill.accent { background: rgba(79,124,255,0.18); color: #a9c0ff; }++ /* tabs */+ .tabs { display: flex; gap: 4px; padding: 8px 14px 0; border-bottom: 1px solid var(--border); background: var(--panel); }+ .tab { padding: 7px 14px; font-size: 12px; color: var(--muted); cursor: pointer; border: 1px solid transparent; border-bottom: none; border-radius: 6px 6px 0 0; }+ .tab.active { color: var(--text); background: var(--panel-2); border-color: var(--border); }+ .tab .badge { color: var(--muted); font-family: var(--mono); font-size: 11px; margin-left: 4px; }++ /* live feed */+ #feed { max-height: calc(100vh - 190px); overflow-y: auto; font-family: var(--mono); font-size: 12px; }+ .ev { padding: 5px 14px; border-bottom: 1px solid var(--border); display: flex; gap: 10px; align-items: baseline; }+ .ev .t { color: var(--muted); flex: 0 0 62px; font-size: 11px; }+ .ev .body { flex: 1 1 auto; word-break: break-word; }+ .ev.accent .body { color: #a9c0ff; }+ .ev.good .body { color: #7ee787; }+ .ev.warn .body { color: #e3b341; }+ .ev.error .body { color: #ff7b72; }+ .ev .tag { color: var(--muted); font-size: 11px; }+ code { color: #d2a8ff; }+ .empty { padding: 18px 14px; color: var(--muted); }+ .controls { display: flex; gap: 8px; align-items: center; }+ .controls label { color: var(--muted); font-size: 11px; }++ /* batches list */+ #batches-view { max-height: calc(100vh - 190px); overflow-y: auto; }+ .brow { display: grid; grid-template-columns: 96px 90px 1fr auto; gap: 10px; align-items: center; padding: 8px 14px; border-bottom: 1px solid var(--border); cursor: pointer; }+ .brow:hover { background: var(--panel-2); }+ .brow .id { font-family: var(--mono); color: #d2a8ff; }+ .brow .badges { display: flex; gap: 5px; flex-wrap: wrap; justify-content: flex-end; }+ .badge-min { font-size: 10px; padding: 1px 6px; border-radius: 8px; background: var(--panel-2); color: var(--muted); border: 1px solid var(--border); white-space: nowrap; }+ .badge-min.warn { color: var(--warn); border-color: rgba(210,153,34,0.4); }+ .badge-min.error { color: var(--error); border-color: rgba(248,81,73,0.4); }+ .brow .tm { color: var(--muted); font-family: var(--mono); font-size: 11px; }++ /* batch detail */+ .detail { padding: 14px; }+ .back { color: var(--accent); cursor: pointer; font-size: 12px; margin-bottom: 12px; display: inline-block; }+ .dsum { display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 16px; }+ .diagram { display: flex; align-items: stretch; gap: 14px; flex-wrap: wrap; margin-bottom: 18px; }+ .node { background: var(--panel-2); border: 1px solid var(--border); border-radius: 8px; padding: 10px 12px; min-width: 150px; }+ .node .title { font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); margin-bottom: 6px; }+ .node .big { font-family: var(--mono); font-size: 15px; }+ .node.stash { border-color: rgba(210,153,34,0.5); }+ .node.worker.acked { border-color: rgba(63,185,80,0.4); }+ .node.worker.stalled { border-color: rgba(248,81,73,0.5); }+ .arrow { align-self: center; color: var(--muted); font-size: 20px; }+ .wgrid { display: flex; gap: 12px; flex-wrap: wrap; }++ /* flow graph */+ .flow { position: relative; padding: 6px 4px 10px; overflow-x: auto; margin-bottom: 18px; }+ .flow-main { display: flex; gap: 82px; align-items: center; }+ .flow-col { display: flex; flex-direction: column; gap: 16px; justify-content: center; }+ .flow-defer { margin-top: 32px; padding-left: 250px; }+ .flow .node { position: relative; z-index: 1; min-width: 122px; }+ .flow svg { position: absolute; top: 0; left: 0; z-index: 0; pointer-events: none; overflow: visible; }+ .node.src { border-color: rgba(79,124,255,0.45); }+ .node.sink-ok { border-color: rgba(63,185,80,0.5); }+ .node.sink-pending { opacity: 0.75; }+ .edge-label { font-size: 10px; font-family: var(--mono); }+ .flow-legend { display: flex; flex-wrap: wrap; gap: 14px; margin-bottom: 10px; color: var(--muted); font-size: 11px; }+ .flow-legend i { display: inline-block; width: 12px; height: 3px; border-radius: 2px; margin-right: 5px; vertical-align: middle; }+ .node .line { font-size: 12px; color: var(--text); }+ .node .sub { font-size: 11px; color: var(--muted); }+ .tl { border-left: 2px solid var(--border); margin-left: 6px; padding-left: 14px; }+ .tl .item { position: relative; padding: 4px 0; font-size: 12px; }+ .tl .item::before { content: ""; position: absolute; left: -20px; top: 9px; width: 8px; height: 8px; border-radius: 50%; background: var(--accent); }+ .tl .item.good::before { background: var(--good); }+ .tl .item.warn::before { background: var(--warn); }+ .tl .item.error::before { background: var(--error); }+ .tl .item .t { color: var(--muted); font-family: var(--mono); font-size: 11px; margin-right: 8px; }++ /* commits */+ .banner { margin: 12px 14px 0; padding: 8px 12px; border-radius: 6px; font-size: 12px; }+ .banner.ok { background: rgba(63,185,80,0.12); color: var(--good); }+ .banner.bad { background: rgba(248,81,73,0.14); color: var(--error); font-weight: 600; }+ #commits { max-height: calc(100vh - 240px); overflow-y: auto; }+ tr.ooo td { background: rgba(248,81,73,0.12); }+ .offchips { display: flex; flex-wrap: wrap; gap: 6px; }+ .offchip { display: inline-flex; align-items: baseline; gap: 6px; padding: 2px 8px; border-radius: 6px;+ background: var(--panel-2); border: 1px solid var(--border); font-family: var(--mono); font-size: 12px; }+ .offchip .pl { color: var(--muted); font-size: 11px; }+ .offchip .ov { color: var(--text); }+ .offchip.bad { background: rgba(248,81,73,0.14); border-color: rgba(248,81,73,0.5); }+ .offchip.bad .ov { color: var(--error); font-weight: 700; }+ .offchip .was { color: var(--error); font-size: 11px; }+ </style>+ </head>+ <body>+ <header>+ <h1>Ingestion consumer</h1>+ <span class="meta" id="group">group —</span>+ <span class="meta"><span class="dot down" id="conn-dot"></span><span id="conn">connecting…</span></span>+ </header>++ <div class="layout">+ <!-- left: live state -->+ <div style="display:flex; flex-direction:column; gap:14px;">+ <section class="panel">+ <h2>Dispatcher load</h2>+ <div class="stats" id="disp-stats"></div>+ </section>+ <section class="panel">+ <h2>Workers</h2>+ <table>+ <thead>+ <tr><th>Worker</th><th>State</th><th>In-flight</th><th>Fails</th><th>Err</th></tr>+ </thead>+ <tbody id="workers"><tr><td class="empty" colspan="5">Waiting for data…</td></tr></tbody>+ </table>+ </section>+ </div>++ <!-- right: tabbed detail -->+ <section class="panel">+ <div class="tabs">+ <div class="tab active" data-tab="feed">Live feed</div>+ <div class="tab" data-tab="batches">Batches <span class="badge" id="badge-batches"></span></div>+ <div class="tab" data-tab="commits">Commits <span class="badge" id="badge-commits"></span></div>+ </div>++ <div id="tab-feed">+ <h2>+ Event stream+ <span class="controls">+ <label><input type="checkbox" id="pause" /> pause</label>+ <label><input type="checkbox" id="hide-resolved" /> hide resolves</label>+ </span>+ </h2>+ <div id="feed"><div class="empty">Waiting for events…</div></div>+ </div>++ <div id="tab-batches" style="display:none;">+ <h2>+ Batches+ <span class="controls">+ <label><input type="checkbox" id="batches-pause" /> pause list</label>+ <label><input type="checkbox" id="batches-issues" /> issues only</label>+ </span>+ </h2>+ <div id="batches-view"><div class="empty">Waiting for batches…</div></div>+ </div>++ <div id="tab-commits" style="display:none;">+ <div id="commit-banner"></div>+ <div id="commits"><div class="empty">Waiting for commits…</div></div>+ </div>+ </section>+ </div>++ <script>+ const MAX_FEED = 600;+ const MAX_BATCHES = 400;+ const MAX_COMMITS = 400;++ const seen = new Set();+ let feedEmpty = true;+ let activeTab = "feed";+ let selectedBatch = null;+ let openDetailId = null;++ // client-side models rebuilt from the event stream+ let batches = {};+ let batchOrder = [];+ let commits = [];+ let partitionHigh = {}; // "topic/partition" -> highest committed offset+ let oooCount = 0;+ let renderPending = false;++ const $ = (id) => document.getElementById(id);++ // Replace a scroll container's contents without losing the user's place.+ // "prepend": newest rows arrive at the top, so keep the rows currently in+ // view fixed (unless the user is already at the top, where we follow the+ // newest). "append": content grows below the viewport, so just restore.+ function setHTML(el, html, mode) {+ if (!mode || mode === "none") { el.innerHTML = html; return; }+ const prevTop = el.scrollTop;+ const prevHeight = el.scrollHeight;+ const nearTop = prevTop <= 4;+ el.innerHTML = html;+ if (mode === "prepend") el.scrollTop = nearTop ? 0 : prevTop + (el.scrollHeight - prevHeight);+ else el.scrollTop = prevTop;+ }++ const shortId = (id) => (id ? id.slice(-8) : "—");+ const shortWorker = (w) => (w || "").replace(/^https?:\/\//, "");+ const fmtTime = (ms) => {+ const d = new Date(ms);+ return d.toLocaleTimeString("en-US", { hour12: false }) + "." + String(d.getMilliseconds()).padStart(3, "0");+ };++ // ---------- point-in-time load (polled fast, no event backlog) ----------+ let loadSamples = []; // rolling {t, v} of total in-flight, for a peak-hold+ const PEAK_WINDOW_MS = 4000;++ async function refreshState() {+ let s;+ try { s = await (await fetch("debug/load")).json(); } catch (e) { return; }+ $("group").textContent = "group " + s.group_id;++ 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+ // panel reflects the concurrency actually happening.+ const now = Date.now();+ loadSamples.push({ t: now, v: d.total_in_flight });+ loadSamples = loadSamples.filter((x) => now - x.t <= PEAK_WINDOW_MS);+ const peak = loadSamples.reduce((m, x) => Math.max(m, x.v), 0);++ $("disp-stats").innerHTML = [+ ["in-flight", d.total_in_flight],+ ["peak 4s", peak],+ ["pins", d.pin_count],+ ["stashed", d.stashed_messages],+ ["stash batches", d.stashed_batches],+ ].map(([l, n]) => `<div class="stat"><div class="n">${n}</div><div class="l">${l}</div></div>`).join("");++ const maxLoad = Math.max(1, ...s.workers.map((w) => w.in_flight_messages));+ $("workers").innerHTML = s.workers.length+ ? s.workers.sort((a, b) => b.in_flight_messages - a.in_flight_messages).map((w) => {+ const cls = w.draining ? "draining" : w.state;+ 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) + "%";+ return `<tr>+ <td class="mono">${shortWorker(w.url)}</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>+ <td class="mono">${w.consecutive_probe_failures}</td>+ <td class="mono">${rate}</td>+ </tr>`;+ }).join("")+ : `<tr><td class="empty" colspan="5">No workers</td></tr>`;+ }++ // ---------- event → model ----------+ function resetModels() {+ seen.clear();+ batches = {}; batchOrder = []; commits = []; partitionHigh = {}; oooCount = 0;+ selectedBatch = null;+ $("feed").innerHTML = '<div class="empty">Waiting for events…</div>';+ feedEmpty = true;+ scheduleRender();+ }++ function batchFor(id) {+ let b = batches[id];+ if (!b) {+ b = { id, ts: null, messages: 0, distinct_ids: 0, partitions: [],+ assigned: [], flushed: [], deferred: [], retries: [], exhausted: [],+ committed: null, events: [] };+ batches[id] = b;+ batchOrder.push(id);+ while (batchOrder.length > MAX_BATCHES) delete batches[batchOrder.shift()];+ }+ return b;+ }++ function updateModel(ev) {+ const id = ev.batch_id;+ if (id) {+ const b = batchFor(id);+ if (b.ts === null) b.ts = ev.ts_ms;+ b.events.push(ev);+ switch (ev.type) {+ case "BatchDispatched": b.messages = ev.messages; b.partitions = ev.partitions; break;+ case "BatchAssigned":+ b.assigned = ev.sub_batches; b.distinct_ids = ev.distinct_ids;+ b.deferredGroups = (b.deferredGroups || 0) + ev.deferred_groups + ev.unroutable_groups; break;+ case "Deferred": b.deferred.push({ reason: ev.reason, groups: ev.groups }); break;+ case "DeferredFlushed": ev.sub_batches.forEach((s) => b.flushed.push(s)); break;+ case "SendRetry": b.retries.push({ worker: ev.worker, attempt: ev.attempt, reason: ev.reason }); break;+ case "SendExhausted": b.exhausted.push({ worker: ev.worker, error: ev.error }); break;+ case "BatchCommitted":+ b.committed = { accepted: ev.accepted, duration_ms: ev.duration_ms, partitions: ev.partitions, ts: ev.ts_ms };+ recordCommit(ev); break;+ }+ }+ if (ev.type === "ConsumerStarted") { batches = {}; batchOrder = []; commits = []; partitionHigh = {}; oooCount = 0; }+ }++ function recordCommit(ev) {+ const rows = ev.partitions.map((p) => {+ const key = p.topic + "/" + p.partition;+ const prev = partitionHigh[key];+ const outOfOrder = prev !== undefined && p.offset <= prev;+ if (prev === undefined || p.offset > prev) partitionHigh[key] = p.offset;+ return { topic: p.topic, partition: p.partition, offset: p.offset, prev, outOfOrder };+ });+ const bad = rows.some((r) => r.outOfOrder);+ if (bad) oooCount++;+ commits.unshift({ ts: ev.ts_ms, batch_id: ev.batch_id, accepted: ev.accepted, duration_ms: ev.duration_ms, rows, outOfOrder: bad });+ while (commits.length > MAX_COMMITS) commits.pop();+ }++ function batchStatus(b) {+ if (b.committed) return "committed";+ if (b.exhausted.length) return "stalled";+ if (b.deferred.length) return "stashed";+ if (b.retries.length) return "retrying";+ return "inflight";+ }++ // A batch whose lifecycle involved a retry or stash — the interesting ones,+ // even if they ultimately committed cleanly.+ function hadIssue(b) {+ return b.retries.length || b.deferred.length || b.exhausted.length;+ }++ // ---------- live feed rendering ----------+ function describe(ev) {+ switch (ev.type) {+ case "ConsumerStarted": return ["accent", `▶ consumer started — group <code>${ev.group_id}</code>, ${ev.workers.length} worker(s)`];+ case "BatchDispatched": return ["", `batch <code>${shortId(ev.batch_id)}</code> dispatched — ${ev.messages} msgs, ${ev.partitions.length} partition(s)`];+ case "BatchAssigned": {+ const routes = ev.sub_batches.map((s) => `${shortWorker(s.worker)}:${s.messages}`).join(" ");+ let extra = "";+ if (ev.deferred_groups) extra += ` ⏸${ev.deferred_groups} deferred`;+ if (ev.unroutable_groups) extra += ` ⚠${ev.unroutable_groups} unroutable`;+ return ["accent", `batch <code>${shortId(ev.batch_id)}</code> assigned — ${ev.distinct_ids} distinct_ids → ${routes || "—"}<span class="tag">${extra}</span>`];+ }+ case "SubBatchResolved": return ["", `resolved — ${shortWorker(ev.worker)} acked ${ev.messages} msgs (${ev.distinct_ids} ids)${ev.cleared_deferral ? '<span class="tag"> · cleared deferral</span>' : ""}`];+ case "Deferred": return ["warn", `⏸ deferred [${ev.reason}] — ${ev.groups} group(s), batch <code>${shortId(ev.batch_id)}</code>`];+ case "DeferredFlushed": {+ const routes = ev.sub_batches.map((s) => `${shortWorker(s.worker)}:${s.messages}`).join(" ");+ return ["warn", `↻ flushed deferred — batch <code>${shortId(ev.batch_id)}</code> → ${routes}`];+ }+ case "BatchCommitted": return ["good", `✓ committed batch <code>${shortId(ev.batch_id)}</code> — ${ev.accepted} msgs in ${ev.duration_ms}ms`];+ case "BatchFailed": return ["error", `✗ batch failed — ${ev.error}`];+ case "SendRetry": return ["warn", `↻ retry #${ev.attempt} [${ev.reason}] — ${shortWorker(ev.worker)}, batch <code>${shortId(ev.batch_id)}</code>`];+ case "SendExhausted": return ["error", `✗ send exhausted — ${shortWorker(ev.worker)}: ${ev.error}`];+ case "WorkerStateChanged": return [ev.to === "unhealthy" ? "error" : ev.to === "healthy" ? "good" : "warn", `worker ${shortWorker(ev.worker)} ${ev.from} → ${ev.to}`];+ case "WorkerMembership": return ["accent", `worker ${shortWorker(ev.worker)} ${ev.action}`];+ default: return ["", ev.type];+ }+ }++ function appendFeed(ev) {+ if (ev.type === "SubBatchResolved" && $("hide-resolved").checked) return;+ const [cls, html] = describe(ev);+ const feed = $("feed");+ if (feedEmpty) { feed.innerHTML = ""; feedEmpty = false; }+ const row = document.createElement("div");+ row.className = "ev " + cls;+ row.innerHTML = `<span class="t">${fmtTime(ev.ts_ms)}</span><span class="body">${html}</span>`;+ feed.insertBefore(row, feed.firstChild);+ while (feed.childElementCount > MAX_FEED) feed.removeChild(feed.lastChild);+ }++ function addEvent(ev) {+ if (seen.has(ev.seq)) return;+ seen.add(ev.seq);+ if (seen.size > 50000) seen.clear();+ updateModel(ev);+ if (!$("pause").checked) appendFeed(ev);+ scheduleRender();+ }++ // ---------- batches + commits rendering (throttled) ----------+ function scheduleRender() {+ if (renderPending) return;+ renderPending = true;+ setTimeout(() => {+ renderPending = false;+ $("badge-batches").textContent = batchOrder.length ? `(${batchOrder.length})` : "";+ $("badge-commits").textContent = commits.length ? (oooCount ? `(${commits.length} · ⚠${oooCount})` : `(${commits.length})`) : "";+ // While the list is paused, freeze it so a stashed batch doesn't scroll+ // away before you can click it — but keep an open detail view live.+ if (activeTab === "batches" && (!$("batches-pause").checked || selectedBatch)) renderBatches();+ if (activeTab === "commits") renderCommits();+ }, 250);+ }++ function workerAgg(b) {+ const m = {};+ const touch = (w) => (m[w] = m[w] || { worker: w, messages: 0, assignedMsgs: 0, flushedMsgs: 0, flushCount: 0, retries: 0, flushed: false, exhausted: false });+ b.assigned.forEach((s) => { const x = touch(s.worker); x.messages += s.messages; x.assignedMsgs += s.messages; });+ b.flushed.forEach((s) => { const x = touch(s.worker); x.messages += s.messages; x.flushedMsgs += s.messages; x.flushed = true; x.flushCount += 1; });+ b.retries.forEach((r) => (touch(r.worker).retries += 1));+ b.exhausted.forEach((e) => (touch(e.worker).exhausted = true));+ return Object.values(m);+ }++ function renderBatches() {+ const view = $("batches-view");+ if (selectedBatch && batches[selectedBatch]) { renderBatchDetail(batches[selectedBatch]); return; }+ selectedBatch = null;+ openDetailId = null;+ const issuesOnly = $("batches-issues").checked;+ let ids = batchOrder.slice().reverse();+ if (issuesOnly) ids = ids.filter((id) => hadIssue(batches[id]));+ if (!ids.length) {+ view.innerHTML = `<div class="empty">${issuesOnly ? "No batches with retries or stash yet…" : "Waiting for batches…"}</div>`;+ return;+ }+ const rows = ids.map((id) => {+ const b = batches[id];+ const st = batchStatus(b);+ const workers = workerAgg(b);+ const badges = [];+ badges.push(`<span class="badge-min">${workers.length}w</span>`);+ const retries = b.retries.length;+ if (retries) badges.push(`<span class="badge-min warn">↻${retries}</span>`);+ if (b.deferred.length) badges.push(`<span class="badge-min warn">⏸${b.deferred.length}</span>`);+ if (b.exhausted.length) badges.push(`<span class="badge-min error">✗${b.exhausted.length}</span>`);+ return `<div class="brow" data-id="${id}">+ <span class="id">${shortId(id)}</span>+ <span><span class="pill ${st}">${st === "inflight" ? "in-flight" : st}</span></span>+ <span class="badges">${badges.join("")}</span>+ <span class="tm">${b.messages} msg · ${b.ts ? fmtTime(b.ts) : ""}</span>+ </div>`;+ }).join("");+ setHTML(view, `<div class="blist">${rows}</div>`, "prepend");+ view.querySelectorAll(".brow").forEach((el) => el.addEventListener("click", () => { selectedBatch = el.dataset.id; renderBatchDetail(batches[selectedBatch]); }));+ }++ function renderBatchDetail(b) {+ const view = $("batches-view");+ const st = batchStatus(b);+ const workers = workerAgg(b);++ const sum = [+ ["status", `<span class="pill ${st}">${st === "inflight" ? "in-flight" : st}</span>`],+ ["messages", b.messages],+ ["distinct_ids", b.distinct_ids],+ ["workers", workers.length],+ ["retries", b.retries.length],+ ["stashed", b.deferred.reduce((a, d) => a + d.groups, 0)],+ ].map(([l, n]) => `<div class="stat"><div class="n">${n}</div><div class="l">${l}</div></div>`).join("");++ const flow = buildFlow(b, workers);++ const timeline = b.events.map((ev) => {+ const [cls, html] = describe(ev);+ return `<div class="item ${cls}"><span class="t">${fmtTime(ev.ts_ms)}</span>${html}</div>`;+ }).join("");++ const fresh = openDetailId !== b.id;+ openDetailId = b.id;+ const detailHtml = `<div class="detail">+ <span class="back" id="back">← all batches</span>+ <div class="dsum">${sum}</div>+ <h2 style="border:none;padding:0 0 8px;">Flow · batch ${shortId(b.id)}</h2>+ <div class="flow-legend">+ <span><i style="background:#4f7cff"></i>routed</span>+ <span><i style="background:#d29922"></i>deferred / flushed</span>+ <span><i style="background:#f85149"></i>send failed</span>+ <span><i style="background:#3fb950"></i>acked / committed</span>+ </div>+ ${flow.html}+ <h2 style="border:none;padding:0 0 8px;">Lifecycle</h2>+ <div class="tl">${timeline}</div>+ </div>`;+ setHTML(view, detailHtml, fresh ? "none" : "append");+ $("back").addEventListener("click", () => { selectedBatch = null; renderBatches(); });+ requestAnimationFrame(() => drawEdges(document.getElementById("flow"), flow.edges));+ }++ // Build the node/edge model for a batch's flow graph. Nodes sit in four+ // lanes (Kafka → assign → workers → commit); the stash lane hangs below and+ // the defer/flush edges connect it explicitly to assign and the workers.+ function buildFlow(b, workers) {+ const idx = {};+ workers.forEach((w, i) => (idx[w.worker] = i));+ const deferBy = { drain: 0, unroutable: 0, send_failed: 0 };+ b.deferred.forEach((d) => (deferBy[d.reason] = (deferBy[d.reason] || 0) + d.groups));+ const hasStash = b.deferred.length > 0;+ const totalDeferred = b.deferred.reduce((a, d) => a + d.groups, 0);+ const flushedBy = {};+ b.flushed.forEach((s) => (flushedBy[s.worker] = (flushedBy[s.worker] || 0) + s.messages));++ const partsShort = b.partitions.map((p) => `${p.partition}@${p.offset}`).join(" ") || "—";+ const sourceNode = `<div class="node src" id="n-source"><div class="title">Kafka batch</div><div class="big">${b.messages}</div><div class="sub">msgs · p ${partsShort}</div></div>`;+ const assignNode = `<div class="node" id="n-assign"><div class="title">Assign</div><div class="big">${b.distinct_ids}</div><div class="sub">distinct_ids</div></div>`;++ const workerNodes = workers.map((w, i) => {+ const cls = w.exhausted ? "stalled" : b.committed ? "acked" : "";+ // Headline = messages this worker was initially assigned (bounded by the+ // batch), or, for a worker that only received re-routed work, the flushed+ // count. Re-routes are shown as a count, not summed into the headline —+ // a re-flushed sub-batch is the same messages retried, not new ones.+ const primary = w.assignedMsgs > 0 ? w.assignedMsgs : w.flushedMsgs;+ const badges = [];+ if (w.retries) badges.push(`<span class="badge-min warn">↻${w.retries}</span>`);+ if (w.flushCount) badges.push(`<span class="badge-min warn">re-routed ×${w.flushCount}</span>`);+ if (w.exhausted) badges.push(`<span class="badge-min error">exhausted</span>`);+ if (!w.exhausted && b.committed) badges.push(`<span class="badge-min">✓ acked</span>`);+ return `<div class="node worker ${cls}" id="n-w-${i}"><div class="title">${shortWorker(w.worker)}</div><div class="big">${primary}</div><div class="sub">${badges.join(" ") || "sent"}</div></div>`;+ }).join("") || '<div class="node" id="n-w-none"><div class="sub">not yet assigned</div></div>';++ const reasons = Object.entries(deferBy).filter(([, n]) => n > 0).map(([r, n]) => `${r}: ${n}`).join(" · ");+ const stashNode = hasStash+ ? `<div class="node stash" id="n-stash"><div class="title">Stash / defer</div><div class="big">${totalDeferred}</div><div class="sub">${reasons}</div><div class="sub">${b.flushed.length ? "↻ flushed & re-routed" : "awaiting flush"}</div></div>`+ : "";++ const sinkNode = b.committed+ ? `<div class="node sink-ok" id="n-sink"><div class="title">Committed</div><div class="big">${b.committed.accepted}</div><div class="sub">${b.committed.duration_ms}ms · ${b.committed.partitions.map((p) => `${p.partition}@${p.offset}`).join(" ")}</div></div>`+ : `<div class="node sink-pending" id="n-sink"><div class="title">In-flight</div><div class="sub">not committed</div></div>`;++ const html = `<div class="flow" id="flow">+ <div class="flow-main">+ <div class="flow-col">${sourceNode}</div>+ <div class="flow-col">${assignNode}</div>+ <div class="flow-col">${workerNodes}</div>+ <div class="flow-col">${sinkNode}</div>+ </div>+ ${hasStash ? `<div class="flow-defer">${stashNode}</div>` : ""}+ <svg></svg>+ </div>`;++ const C = { muted: "#8b93a1", warn: "#d29922", good: "#3fb950", error: "#f85149", accent: "#4f7cff" };+ const edges = [];+ edges.push({ from: "n-source", to: "n-assign", label: `${b.messages} msgs`, color: C.accent });+ workers.forEach((w, i) => { if (w.assignedMsgs > 0) edges.push({ from: "n-assign", to: `n-w-${i}`, label: `sent ${w.assignedMsgs}`, color: C.muted }); });++ if (hasStash) {+ let incoming = 0;+ const da = deferBy.drain + deferBy.unroutable;+ if (da > 0) {+ const lbl = [deferBy.drain ? "drain" : "", deferBy.unroutable ? "unroutable" : ""].filter(Boolean).join("/");+ edges.push({ from: "n-assign", to: "n-stash", label: `deferred (${lbl})`, color: C.warn });+ incoming++;+ }+ workers.forEach((w, i) => { if (w.exhausted) { edges.push({ from: `n-w-${i}`, to: "n-stash", label: "send failed", color: C.error }); incoming++; } });+ if (deferBy.send_failed > 0 && incoming === 0) edges.push({ from: "n-assign", to: "n-stash", label: "send failed", color: C.error });+ Object.entries(flushedBy).forEach(([worker, msgs]) => { const i = idx[worker]; if (i != null) edges.push({ from: "n-stash", to: `n-w-${i}`, label: `flushed ${msgs}`, color: C.warn }); });+ }++ if (b.committed) {+ if (workers.length) workers.forEach((w, i) => { if (!w.exhausted) edges.push({ from: `n-w-${i}`, to: "n-sink", label: "acked", color: C.good }); });+ else edges.push({ from: "n-assign", to: "n-sink", label: "", color: C.good });+ }++ return { html, edges };+ }++ const cid = (c) => c.replace("#", "");+ const escapeXml = (s) => String(s).replace(/[<>&]/g, (m) => ({ "<": "<", ">": ">", "&": "&" }[m]));++ // Draw SVG edges between the flow nodes, anchored on the box borders with a+ // smooth orthogonal-ish bezier and a coloured arrowhead + label.+ function drawEdges(container, edges) {+ if (!container) return;+ const svg = container.querySelector("svg");+ if (!svg) return;+ const crect = container.getBoundingClientRect();+ const rectOf = (id) => {+ const el = document.getElementById(id);+ if (!el) return null;+ const r = el.getBoundingClientRect();+ return { cx: r.left + r.width / 2 - crect.left, cy: r.top + r.height / 2 - crect.top, hw: r.width / 2, hh: r.height / 2 };+ };+ const border = (r, ox, oy) => {+ const dx = ox - r.cx, dy = oy - r.cy;+ if (!dx && !dy) return { x: r.cx, y: r.cy };+ const s = 1 / Math.max(Math.abs(dx) / r.hw, Math.abs(dy) / r.hh);+ return { x: r.cx + dx * s, y: r.cy + dy * s };+ };++ const colorSet = {};+ edges.forEach((e) => (colorSet[e.color] = true));+ let defs = "<defs>";+ Object.keys(colorSet).forEach((c) => {+ defs += `<marker id="arw-${cid(c)}" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0 L10 5 L0 10 z" fill="${c}"/></marker>`;+ });+ defs += "</defs>";++ let body = "";+ edges.forEach((e) => {+ const rs = rectOf(e.from), rt = rectOf(e.to);+ if (!rs || !rt) return;+ const sa = border(rs, rt.cx, rt.cy), ta = border(rt, rs.cx, rs.cy);+ const horiz = Math.abs(rt.cx - rs.cx) >= Math.abs(rt.cy - rs.cy);+ const mx = (sa.x + ta.x) / 2, my = (sa.y + ta.y) / 2;+ const c1 = horiz ? { x: mx, y: sa.y } : { x: sa.x, y: my };+ const c2 = horiz ? { x: mx, y: ta.y } : { x: ta.x, y: my };+ body += `<path d="M ${sa.x} ${sa.y} C ${c1.x} ${c1.y}, ${c2.x} ${c2.y}, ${ta.x} ${ta.y}" fill="none" stroke="${e.color}" stroke-width="1.6" opacity="0.9" marker-end="url(#arw-${cid(e.color)})"/>`;+ if (e.label) {+ const lw = e.label.length * 5.7 + 10;+ body += `<rect x="${mx - lw / 2}" y="${my - 8}" width="${lw}" height="15" rx="3" fill="#1c1f26" stroke="${e.color}" stroke-opacity="0.35"/>`;+ body += `<text x="${mx}" y="${my + 2.5}" text-anchor="middle" class="edge-label" fill="${e.color}">${escapeXml(e.label)}</text>`;+ }+ });++ svg.setAttribute("width", container.scrollWidth);+ svg.setAttribute("height", container.scrollHeight);+ svg.innerHTML = defs + body;+ }++ function renderCommits() {+ const banner = $("commit-banner");+ banner.innerHTML = oooCount+ ? `<div class="banner bad">⚠ ${oooCount} out-of-order commit(s) detected — offsets went backwards for a partition</div>`+ : commits.length ? `<div class="banner ok">✓ all ${commits.length} commits are in order (offsets monotonic per partition)</div>` : "";++ const el = $("commits");+ if (!commits.length) { el.innerHTML = '<div class="empty">Waiting for commits…</div>'; return; }+ const rows = commits.map((c) => {+ const chips = c.rows+ .slice()+ .sort((a, b) => a.partition - b.partition)+ .map((r) =>+ `<span class="offchip ${r.outOfOrder ? "bad" : ""}" title="${r.topic}">+ <span class="pl">P${r.partition}</span>+ <span class="ov">${r.offset}</span>+ ${r.outOfOrder ? `<span class="was">↓ was ${r.prev}</span>` : ""}+ </span>`+ ).join("");+ return `<tr class="${c.outOfOrder ? "ooo" : ""}">+ <td class="mono">${fmtTime(c.ts)}</td>+ <td class="mono">${shortId(c.batch_id)}</td>+ <td class="mono">${c.accepted}</td>+ <td><div class="offchips">${chips}</div></td>+ <td>${c.outOfOrder ? '<span class="pill failed">out of order</span>' : ""}</td>+ </tr>`;+ }).join("");+ setHTML(el, `<table><thead><tr><th>Time</th><th>Batch</th><th>Msgs</th><th>Committed offset per partition</th><th></th></tr></thead><tbody>${rows}</tbody></table>`, "prepend");+ }++ // ---------- tabs ----------+ document.querySelectorAll(".tab").forEach((t) =>+ t.addEventListener("click", () => {+ activeTab = t.dataset.tab;+ document.querySelectorAll(".tab").forEach((x) => x.classList.toggle("active", x === t));+ $("tab-feed").style.display = activeTab === "feed" ? "" : "none";+ $("tab-batches").style.display = activeTab === "batches" ? "" : "none";+ $("tab-commits").style.display = activeTab === "commits" ? "" : "none";+ if (activeTab === "batches") renderBatches();+ if (activeTab === "commits") renderCommits();+ })+ );++ // Re-render immediately when the batch filters change (and on un-pause).+ $("batches-issues").addEventListener("change", renderBatches);+ $("batches-pause").addEventListener("change", () => { if (!$("batches-pause").checked) renderBatches(); });+ // Redraw the flow graph's edges when the layout width changes.+ window.addEventListener("resize", () => {+ if (activeTab === "batches" && selectedBatch && batches[selectedBatch]) renderBatchDetail(batches[selectedBatch]);+ });++ // ---------- live SSE ----------+ function connect() {+ const es = new EventSource("debug/events");+ es.onopen = () => {+ $("conn").textContent = "live"; $("conn-dot").className = "dot live";+ resetModels(); // reconnect/restart replays the backlog; rebuild cleanly+ };+ es.onmessage = (m) => { try { addEvent(JSON.parse(m.data)); } catch (e) {} };+ es.onerror = () => { $("conn").textContent = "reconnecting…"; $("conn-dot").className = "dot down"; };+ }++ refreshState();+ setInterval(refreshState, 600);+ connect();+ </script>+ </body>+</html>diff --git a/rust/ingestion-control-plane/src/ui/index.html b/rust/ingestion-control-plane/src/ui/index.htmlnew file mode 100644index 000000000000..5d2333b326ba--- /dev/null+++ b/rust/ingestion-control-plane/src/ui/index.html@@ -0,0 +1,485 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>Ingestion control plane</title>+ <style>+ :root {+ --bg: #14161a;+ --panel: #1c1f26;+ --panel-2: #23272f;+ --border: #2c313b;+ --text: #e6e9ef;+ --muted: #8b93a1;+ --accent: #4f7cff;+ --good: #3fb950;+ --warn: #d29922;+ --error: #f85149;+ --mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;+ }+ * { box-sizing: border-box; }+ body {+ margin: 0;+ background: var(--bg);+ color: var(--text);+ font: 13px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;+ }+ .app { display: flex; min-height: 100vh; }++ /* sidebar */+ .side {+ flex: 0 0 210px; background: var(--panel); border-right: 1px solid var(--border);+ padding: 14px 10px; position: sticky; top: 0; height: 100vh;+ }+ .side .brand { font-weight: 600; font-size: 14px; padding: 4px 10px 14px; }+ .side .nav-item {+ display: block; padding: 8px 10px; border-radius: 6px; color: var(--muted);+ cursor: pointer; margin-bottom: 2px; font-size: 13px;+ }+ .side .nav-item:hover { background: var(--panel-2); color: var(--text); }+ .side .nav-item.active { background: var(--panel-2); color: var(--text); border-left: 2px solid var(--accent); }++ /* main */+ .main { flex: 1 1 auto; padding: 16px; min-width: 0; }+ .main h1 { font-size: 16px; margin: 0 0 4px; }+ .main .desc { color: var(--muted); margin: 0 0 14px; font-size: 12px; }++ .panel { background: var(--panel); border: 1px solid var(--border); border-radius: 8px; overflow: hidden; margin-bottom: 14px; }+ .panel > h2 {+ font-size: 12px; text-transform: uppercase; letter-spacing: 0.06em;+ color: var(--muted); margin: 0; padding: 10px 14px; border-bottom: 1px solid var(--border);+ display: flex; justify-content: space-between; align-items: center; gap: 8px;+ }+ .row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; padding: 10px 14px; }++ table { width: 100%; border-collapse: collapse; }+ th, td { text-align: left; padding: 6px 14px; border-bottom: 1px solid var(--border); font-size: 12px; }+ th { color: var(--muted); font-weight: 500; font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; }+ td.mono, th.mono { font-family: var(--mono); }+ tr.clickable:hover td { background: rgba(79,124,255,0.06); cursor: pointer; }+ tr.selected td { background: rgba(79,124,255,0.1); }+ td .bar { height: 6px; border-radius: 3px; background: var(--accent); min-width: 2px; display: inline-block; vertical-align: middle; }+ td .bar.hot { background: var(--error); }+ td .bar.warm { background: var(--warn); }++ .pill { display: inline-block; padding: 1px 7px; border-radius: 10px; font-size: 11px; font-weight: 600; white-space: nowrap; }+ .pill.good { background: rgba(63,185,80,0.16); color: var(--good); }+ .pill.warn { background: rgba(210,153,34,0.16); color: var(--warn); }+ .pill.bad { background: rgba(248,81,73,0.16); color: var(--error); }+ .pill.muted { background: rgba(139,147,161,0.18); color: var(--muted); }+ .pill.accent { background: rgba(79,124,255,0.18); color: #a9c0ff; }++ button, select {+ background: var(--panel-2); color: var(--text); border: 1px solid var(--border);+ border-radius: 6px; padding: 5px 10px; font-size: 12px; cursor: pointer; font-family: inherit;+ }+ button:hover { border-color: var(--accent); }+ button:disabled { opacity: 0.5; cursor: default; }+ button.small { padding: 2px 8px; font-size: 11px; }+ .muted { color: var(--muted); }+ .mono { font-family: var(--mono); }+ .empty { padding: 18px 14px; color: var(--muted); }+ .error-box { padding: 10px 14px; color: var(--error); font-family: var(--mono); font-size: 12px; white-space: pre-wrap; }++ .progress { background: var(--panel-2); border-radius: 4px; height: 8px; overflow: hidden; min-width: 160px; }+ .progress > div { background: var(--accent); height: 100%; transition: width 0.3s; }++ /* token breakdown */+ .token-block { border-bottom: 1px solid var(--border); }+ .token-head { display: flex; gap: 10px; align-items: center; padding: 9px 14px; background: var(--panel-2); flex-wrap: wrap; }+ .token-head .tok { font-family: var(--mono); cursor: pointer; }+ .token-head .tok:hover { color: #a9c0ff; }+ .token-head .share { margin-left: auto; display: flex; gap: 10px; align-items: center; }+ .token-head .bar { height: 7px; border-radius: 3px; background: var(--accent); }+ .token-cols { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 4px 20px; padding: 8px 14px 12px; }+ .token-cols h3 { font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); margin: 4px 0; }+ .krow { display: flex; align-items: center; gap: 8px; padding: 2px 0; font-size: 12px; }+ .krow .key { font-family: var(--mono); flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: pointer; }+ .krow .key:hover { color: #a9c0ff; }+ .krow .cnt { color: var(--muted); font-family: var(--mono); font-size: 11px; flex: 0 0 auto; margin-left: auto; }+ .krow .kbar { height: 5px; border-radius: 3px; background: var(--accent); flex: 0 0 auto; }++ .cols { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 12px; padding: 12px 14px; }+ .col h3 { font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); margin: 0 0 6px; }+ .hist-row { display: flex; align-items: center; gap: 8px; padding: 2px 0; font-size: 11px; }+ .hist-row .lbl { flex: 0 0 70px; text-align: right; color: var(--muted); font-family: var(--mono); }+ .hist-row .hbar { height: 10px; border-radius: 2px; background: var(--accent); }+ .hist-row .hcnt { color: var(--muted); font-family: var(--mono); }++ iframe.debug { width: 100%; height: calc(100vh - 300px); border: 0; background: var(--bg); display: block; }+ </style>+ </head>+ <body>+ <div class="app">+ <nav class="side">+ <div class="brand">Ingestion control plane</div>+ <div id="nav"></div>+ </nav>+ <main class="main" id="content"></main>+ </div>++ <script>+ "use strict";++ // ---------- helpers ----------+ const el = (tag, attrs = {}, ...children) => {+ const node = document.createElement(tag);+ for (const [k, v] of Object.entries(attrs)) {+ if (k === "class") node.className = v;+ else if (k.startsWith("on")) node.addEventListener(k.slice(2), v);+ else node.setAttribute(k, v);+ }+ for (const child of children.flat()) {+ if (child === null || child === undefined) continue;+ node.append(child.nodeType ? child : document.createTextNode(child));+ }+ return node;+ };+ const fmtInt = (n) => (n === null || n === undefined ? "–" : Number(n).toLocaleString("en-US"));+ const fmtBytes = (n) => {+ if (n === null || n === undefined) return "–";+ const units = ["B", "KB", "MB", "GB"];+ let value = Number(n), unit = 0;+ while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit++; }+ return `${value >= 100 ? value.toFixed(0) : value.toFixed(1)} ${units[unit]}`;+ };+ const fetchJSON = async (url, opts) => {+ const resp = await fetch(url, opts);+ const body = await resp.json().catch(() => ({}));+ if (!resp.ok) throw new Error(body.error || `${resp.status} ${resp.statusText}`);+ return body;+ };+ const copy = (text) => navigator.clipboard && navigator.clipboard.writeText(text);+ const copyable = (text, cls) =>+ el("span", { class: cls, title: `${text} (click to copy)`, onclick: () => copy(text) }, text);++ // Section registry: extending the tool = appending an entry here.+ const SECTIONS = [];+ let activeSection = null;++ function navigate(id) {+ const section = SECTIONS.find((s) => s.id === id) || SECTIONS[0];+ if (activeSection && activeSection.unmount) activeSection.unmount();+ activeSection = section;+ for (const item of document.querySelectorAll(".nav-item")) {+ item.classList.toggle("active", item.dataset.id === section.id);+ }+ const content = document.getElementById("content");+ content.replaceChildren(+ el("h1", {}, section.title),+ el("p", { class: "desc" }, section.description)+ );+ section.mount(content);+ location.hash = section.id;+ }++ // ---------- section: partition lag ----------+ const lagSection = {+ id: "lag",+ title: "Lagging partitions",+ description:+ "All ingestion consumer groups sorted by outstanding messages. Drill into a group, then analyze what a lagging partition contains.",+ timers: [],+ selectedGroup: null,+ currentJobId: null,+ unmount() {+ this.timers.forEach(clearInterval);+ this.timers = [];+ },+ mount(root) {+ const overviewBody = el("div", {}, el("div", { class: "empty" }, "Scanning consumer groups…"));+ 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 };++ root.append(+ el("div", { class: "panel" },+ el("h2", {}, "Consumer groups", el("button", { class: "small", onclick: () => this.refreshOverview() }, "Refresh")),+ overviewBody),+ el("div", { class: "panel" },+ el("h2", {}, partitionsTitle, el("button", { class: "small", onclick: () => this.refreshPartitions() }, "Refresh")),+ partitionsBody),+ el("div", { class: "panel" }, el("h2", {}, analysisTitle), analysisBody)+ );++ this.refreshOverview();+ this.timers.push(setInterval(() => this.pollJob(), 700));+ },++ async refreshOverview() {+ const { overviewBody } = this.ui;+ try {+ const rows = await fetchJSON("api/lag/overview");+ if (!rows.length) {+ overviewBody.replaceChildren(el("div", { class: "empty" }, "No consumer targets configured."));+ return;+ }+ const maxLag = Math.max(1, ...rows.map((r) => r.total_lag));+ overviewBody.replaceChildren(+ el("table", {},+ el("thead", {}, el("tr", {},+ el("th", {}, "group"), el("th", {}, "topic"), el("th", {}, "partitions"),+ el("th", {}, "lagging"), el("th", {}, "total lag"), el("th", {}, ""))),+ el("tbody", {}, rows.map((row) =>+ row.error+ ? el("tr", {},+ 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("td", { class: "mono" }, row.group),+ el("td", { class: "mono" }, row.topic),+ el("td", { class: "mono" }, fmtInt(row.partitions)),+ el("td", {}, row.lagging_partitions > 0+ ? el("span", { class: "pill warn" }, fmtInt(row.lagging_partitions))+ : el("span", { class: "pill good" }, "0")),+ el("td", { class: "mono" }, fmtInt(row.total_lag)),+ el("td", {}, row.total_lag > 0+ ? el("span", { class: `bar ${row.total_lag > maxLag * 0.66 ? "hot" : row.total_lag > maxLag * 0.33 ? "warm" : ""}`, style: `width:${Math.max(2, (row.total_lag / maxLag) * 140)}px` })+ : null))+ ))+ )+ );+ } catch (e) {+ overviewBody.replaceChildren(el("div", { class: "error-box" }, String(e)));+ }+ },++ selectGroup(group) {+ this.selectedGroup = group;+ this.refreshOverview();+ this.refreshPartitions();+ },++ async refreshPartitions() {+ const { partitionsTitle, partitionsBody } = this.ui;+ if (!this.selectedGroup) return;+ partitionsTitle.textContent = `Partitions — ${this.selectedGroup}`;+ partitionsBody.replaceChildren(el("div", { class: "empty" }, "Scanning…"));+ try {+ const data = await fetchJSON(`api/lag?group=${encodeURIComponent(this.selectedGroup)}`);+ const maxLag = Math.max(1, ...data.partitions.map((p) => p.lag));+ partitionsBody.replaceChildren(+ el("table", {},+ el("thead", {}, el("tr", {},+ el("th", {}, "partition"), el("th", {}, "low"), el("th", {}, "high"),+ el("th", {}, "committed"), el("th", {}, "lag"), el("th", {}, ""), el("th", {}, "analyze"))),+ el("tbody", {}, data.partitions.map((p) => {+ const width = Math.max(2, Math.round((p.lag / maxLag) * 140));+ const heat = p.lag === 0 ? "" : p.lag > maxLag * 0.66 ? "hot" : p.lag > maxLag * 0.33 ? "warm" : "";+ return el("tr", {},+ el("td", { class: "mono" }, String(p.partition)),+ el("td", { class: "mono" }, fmtInt(p.low_watermark)),+ el("td", { class: "mono" }, fmtInt(p.high_watermark)),+ el("td", { class: "mono" }, p.committed_offset === null ? "–" : fmtInt(p.committed_offset)),+ el("td", { class: "mono" }, fmtInt(p.lag)),+ el("td", {}, p.lag > 0 ? el("span", { class: `bar ${heat}`, style: `width:${width}px` }) : null),+ el("td", {},+ el("button", { class: "small", onclick: () => this.startAnalysis(p.partition, "committed") }, "head"),+ " ",+ el("button", { class: "small", onclick: () => this.startAnalysis(p.partition, "tail") }, "tail"))+ );+ }))+ )+ );+ } catch (e) {+ partitionsBody.replaceChildren(el("div", { class: "error-box" }, String(e)));+ }+ },++ // One analysis at a time: starting a new one cancels and replaces the current.+ async startAnalysis(partition, mode) {+ if (this.currentJobId) {+ fetchJSON(`api/analyses/${this.currentJobId}`, { method: "DELETE" }).catch(() => {});+ }+ try {+ const resp = await fetchJSON("api/analyses", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ group: this.selectedGroup, partition, mode }),+ });+ this.currentJobId = resp.job_id;+ this.pollJob();+ } catch (e) {+ this.ui.analysisBody.replaceChildren(el("div", { class: "error-box" }, String(e)));+ }+ },++ async pollJob() {+ if (!this.currentJobId) return;+ const { analysisTitle, analysisBody } = this.ui;+ let job;+ try {+ job = await fetchJSON(`api/analyses/${this.currentJobId}`);+ } catch {+ return;+ }+ analysisTitle.textContent = `Analysis — ${job.spec.group} p${job.spec.partition} (${job.spec.mode})`;+ if (job.state === "running") {+ const pctDone = job.progress.target ? (job.progress.fetched / job.progress.target) * 100 : 100;+ analysisBody.replaceChildren(+ el("div", { class: "row" },+ el("span", { class: "pill accent" }, "running"),+ el("div", { class: "progress" }, el("div", { style: `width:${pctDone.toFixed(0)}%` })),+ el("span", { class: "muted mono" },+ `${fmtInt(job.progress.fetched)}/${fmtInt(job.progress.target)} messages · ${fmtBytes(job.progress.bytes_read)} · offset ${fmtInt(job.progress.current_offset)}`),+ el("button", { class: "small", onclick: () => fetchJSON(`api/analyses/${this.currentJobId}`, { method: "DELETE" }) }, "cancel"))+ );+ } else if (job.state === "failed") {+ analysisBody.replaceChildren(el("div", { class: "error-box" }, job.error || "analysis failed"));+ this.currentJobId = null;+ } else if (job.result) {+ analysisBody.replaceChildren(renderAnalysisResult(job));+ this.currentJobId = null;+ }+ },+ };++ function renderAnalysisResult(job) {+ const r = job.result;+ const chips = el(+ "div",+ { class: "row" },+ el("span", { class: "pill accent" }, `${fmtInt(r.messages_analyzed)} messages`),+ el("span", { class: "pill muted" }, `offsets ${fmtInt(job.spec.start_offset)} → ${fmtInt(r.next_offset)}`),+ el("span", { class: "pill muted" }, `${r.duration_ms} ms`),+ el("span", { class: "pill muted" }, fmtBytes(r.sizes.total_bytes)),+ r.truncated_reason ? el("span", { class: "pill warn" }, `truncated: ${r.truncated_reason}`) : null,+ r.flags.historical_migration ? el("span", { class: "pill warn" }, `historical: ${fmtInt(r.flags.historical_migration)}`) : null,+ r.flags.force_disable_person_processing ? el("span", { class: "pill muted" }, `no-person: ${fmtInt(r.flags.force_disable_person_processing)}`) : null,+ r.flags.missing_headers ? el("span", { class: "pill bad" }, `missing headers: ${fmtInt(r.flags.missing_headers)}`) : null,+ r.flags.missing_token ? el("span", { class: "pill bad" }, `missing token: ${fmtInt(r.flags.missing_token)}`) : null,+ r.token_overflow ? el("span", { class: "pill warn" }, `token overflow: ${fmtInt(r.token_overflow)}`) : null+ );++ const topList = (title, rows) => {+ const max = Math.max(1, ...rows.map((row) => row.count));+ return el("div", {},+ el("h3", {}, title),+ rows.length === 0 ? el("div", { class: "muted" }, "none") : null,+ rows.map((row) =>+ el("div", { class: "krow" },+ el("span", { class: "kbar", style: `width:${Math.max(3, (row.count / max) * 80)}px` }),+ copyable(row.key, "key"),+ el("span", { class: "cnt" }, `${fmtInt(row.count)} · ${row.pct.toFixed(1)}%`))+ )+ );+ };++ const maxTokenCount = Math.max(1, ...r.top_tokens.map((t) => t.count));+ const tokenBlocks = r.top_tokens.map((t) =>+ el("div", { class: "token-block" },+ el("div", { class: "token-head" },+ el("span", { class: t.team_id === null ? "pill muted" : "pill accent" }, t.team_id === null ? "team ?" : `team ${t.team_id}`),+ copyable(t.token, "tok"),+ el("span", { class: "share" },+ el("span", { class: "bar", style: `width:${Math.max(3, (t.count / maxTokenCount) * 160)}px` }),+ el("span", { class: "mono muted" }, `${fmtInt(t.count)} msgs · ${t.pct.toFixed(1)}% · ${fmtBytes(t.total_bytes)}`))),+ el("div", { class: "token-cols" },+ topList("events", t.top_events),+ topList(+ t.distinct_id_overflow+ ? `distinct_ids (${fmtInt(t.distinct_ids_tracked)} tracked, ${fmtInt(t.distinct_id_overflow)} overflow)`+ : "distinct_ids",+ t.top_distinct_ids+ ))+ )+ );++ // Cumulative histogram buckets -> per-bucket counts for display.+ let previous = 0;+ const histRows = [];+ const maxBucket = Math.max(1, ...r.sizes.histogram.map((b, i, arr) => b.count - (i ? arr[i - 1].count : 0)));+ for (const bucket of r.sizes.histogram) {+ const count = bucket.count - previous;+ previous = bucket.count;+ histRows.push(+ el("div", { class: "hist-row" },+ el("span", { class: "lbl" }, `≤ ${fmtBytes(bucket.le)}`),+ el("span", { class: "hbar", style: `width:${Math.max(1, (count / maxBucket) * 160)}px` }),+ el("span", { class: "hcnt" }, fmtInt(count)))+ );+ }+ const sizes = el("div", { class: "cols" },+ el("div", { class: "col" },+ el("h3", {}, "message size"),+ el("div", { class: "muted mono", style: "margin-bottom:6px" },+ `min ${fmtBytes(r.sizes.min)} · p50 ${fmtBytes(r.sizes.p50)} · p90 ${fmtBytes(r.sizes.p90)} · p99 ${fmtBytes(r.sizes.p99)} · max ${fmtBytes(r.sizes.max)}`),+ histRows));++ return el("div", {}, chips, ...tokenBlocks, sizes);+ }++ // ---------- section: consumer debug ----------+ const debugSection = {+ id: "debug",+ title: "Consumer debug",+ description: "Live ingestion-consumer pods; selecting one opens its full routing debug UI, backed by this service's per-pod proxy.",+ unmount() {},+ mount(root) {+ const podsBody = el("div", {}, el("div", { class: "empty" }, "Loading pods…"));+ const viewer = el("div", {});+ this.ui = { podsBody, viewer };+ root.append(+ el("div", { class: "panel" },+ el("h2", {}, "Pods", el("button", { class: "small", onclick: () => this.refreshPods() }, "Refresh")),+ podsBody),+ viewer+ );+ this.refreshPods();+ },++ async refreshPods() {+ const { podsBody } = this.ui;+ try {+ const data = await fetchJSON("api/pods");+ if (!data.pods.length) {+ podsBody.replaceChildren(el("div", { class: "empty" }, "No matching pods found."));+ return;+ }+ 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("tbody", {}, data.pods.map((pod) =>+ el("tr", { class: `clickable ${pod.name === this.selectedPod ? "selected" : ""}`, onclick: () => this.selectPod(pod.name) },+ el("td", { class: "mono" }, pod.name),+ el("td", {}, pod.labels.app || "–"),+ 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)),+ el("td", { class: "muted mono" }, pod.started_at ? new Date(pod.started_at).toLocaleString() : "–"))+ ))+ )+ );+ } catch (e) {+ podsBody.replaceChildren(el("div", { class: "error-box" }, String(e)));+ }+ },++ selectPod(name) {+ this.selectedPod = name;+ this.refreshPods();+ const url = `pods/${encodeURIComponent(name)}/`;+ this.ui.viewer.replaceChildren(+ el("div", { class: "panel" },+ el("h2", {}, `Debug — ${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 }))+ );+ },+ };++ // ---------- boot ----------+ SECTIONS.push(lagSection, debugSection);+ const nav = document.getElementById("nav");+ for (const section of SECTIONS) {+ nav.append(el("span", { class: "nav-item", "data-id": section.id, onclick: () => navigate(section.id) }, section.title));+ }+ navigate(location.hash.replace("#", "") || SECTIONS[0].id);+ </script>+ </body>+</html>