: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-control-plane): add etcd explorer and personhog topology tools (#80663)
José Sequeira90e7e439f444
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex fe788e3eea90..92931a3123da 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -6067,6 +6067,7 @@ name = "ingestion-control-plane"version = "0.1.0"dependencies = ["anyhow",+ "assignment-coordination","axum 0.7.9","chrono","common-alloc",@@ -6075,11 +6076,13 @@ dependencies = ["common-types","dashmap 6.1.0","envconfig",+ "etcd-client","futures","hdrhistogram","health","k8s-awareness","kube",+ "personhog-coordination","rdkafka","reqwest 0.12.28","rustls 0.23.37",diff --git a/rust/ingestion-control-plane/Cargo.toml b/rust/ingestion-control-plane/Cargo.tomlindex 5002ae24a889..98589781e4f4 100644--- a/rust/ingestion-control-plane/Cargo.toml+++ b/rust/ingestion-control-plane/Cargo.toml@@ -6,9 +6,11 @@ publish = false[dependencies]anyhow = { workspace = true }+assignment-coordination = { path = "../common/assignment-coordination" }axum = { workspace = true }chrono = { workspace = true }common-alloc = { path = "../common/alloc" }+etcd-client = "0.18"common-database = { path = "../common/database" }common-metrics = { path = "../common/metrics" }common-types = { path = "../common/types" }@@ -19,6 +21,7 @@ hdrhistogram = { workspace = true }health = { path = "../common/health" }k8s-awareness = { path = "../common/k8s-awareness" }kube = { version = "0.98", features = ["client"] }+personhog-coordination = { path = "../personhog-coordination" }rdkafka = { workspace = true }reqwest = { workspace = true }rustls = { version = "0.23", default-features = false, features = ["ring", "std"] }diff --git a/rust/ingestion-control-plane/README.md b/rust/ingestion-control-plane/README.mdindex 0ece4fca339c..b6cfff3a58c1 100644--- a/rust/ingestion-control-plane/README.md+++ b/rust/ingestion-control-plane/README.md@@ -21,6 +21,16 @@ Clicking a team, event, or distinct_id in an analysis result opens the message bLists live ingestion-consumer pods and serves the consumer's routing debug UI per pod at `/pods/<namespace>/<name>/` (static pods use the `static` pseudo-namespace), backed by a proxy to the pod's debug API (`/debug/state`, `/debug/load`, SSE `/debug/events`). The UI lives here; the consumer only exposes the JSON/SSE API (gated behind `DEBUG_UI_ENABLED` on the consumer side).+### Personhog topology++Protocol-aware view of personhog's etcd coordination state (`PERSONHOG_ETCD_PREFIX`, default `/personhog/`): the whole prefix is read in one consistent snapshot and interpreted with the `personhog-coordination` types and the coordinator's own pure predicates, so the derived diagnostics cannot drift from the protocol. Shows the elected coordinator, registered pods and routers (with remaining lease TTLs), per-partition ownership, and in-flight handoffs with their phase age and what each is waiting on — distinguishing a stuck participant ("waiting on freeze acks from router-2") from a stuck coordinator ("quorum met; waiting on the coordinator to advance"). Derived issues cover stuck handoffs past their per-phase deadline, assignments owned by unregistered pods with no replanning handoff, lingering `Complete` records the coordinator hasn't cleaned up, dead new owners awaiting cancellation, unassigned partitions, stale acks from previous handoff attempts, and unparseable records. The deadline knobs (`PERSONHOG_HANDOFF_DEADLINE_SECS`, `PERSONHOG_WARMING_DEADLINE_SECS`) must match the coordinator's to agree with its cancellation decisions. Read-only: the tool never writes coordination state, and a force-reassignment must go through a handoff record, never a raw assignment write.++### Etcd explorer++Generic key browser for the same etcd cluster: keys under a prefix render as a collapsible tree (with per-key version, lease, and size; the top level and single-child chains expand automatically), and a key's detail shows its value, revisions, and remaining lease TTL, with edit, create, and delete. Operations are bounded to `ETCD_ALLOWED_PREFIXES`. Writes bypass every coordination protocol, so each one confirms first; writing a lease-backed key warns that it detaches the key from its lease, and writing a personhog `assignments/` key gets an extra warning because routers only observe ownership through handoff `Complete` events — a raw assignment write is invisible to them and leaves an unfenced old owner serving. Deletes are single-key only; there is deliberately no prefix delete.++Both etcd tools are disabled (their APIs return 503) unless `ETCD_ENDPOINTS` is set.+## Configuration| Env var | Default | Notes |@@ -45,6 +55,11 @@ Lists live ingestion-consumer pods and serves the consumer's routing debug UI pe| `POD_LABEL_SELECTORS` | `ingestion-analytics-main/app=ingestion-analytics-main,ingestion-analytics-async/app=ingestion-analytics-async` | One `namespace/key=value` per entry (each lane runs in its own namespace); bare `key=value` uses `K8S_NAMESPACE` || `K8S_NAMESPACE` | `posthog` | Default namespace for unqualified selector entries || `DEBUG_PORT` | `3301` | Consumer debug API port (kubernetes mode) |+| `ETCD_ENDPOINTS` | empty | Comma-separated etcd endpoints; empty disables the etcd explorer and personhog topology tools |+| `ETCD_ALLOWED_PREFIXES` | `/` | Comma-separated key prefixes the etcd explorer may read and write |+| `PERSONHOG_ETCD_PREFIX` | `/personhog/` | Prefix the personhog coordination state lives under; must match the personhog services' `ETCD_PREFIX` |+| `PERSONHOG_HANDOFF_DEADLINE_SECS` | `120` | Per-phase deadline for flagging stuck handoffs; must match `COORDINATOR_HANDOFF_DEADLINE_SECS` |+| `PERSONHOG_WARMING_DEADLINE_SECS` | `1800` | Warming-phase deadline; must match `COORDINATOR_WARMING_DEADLINE_SECS` |## Local development@@ -68,4 +83,4 @@ 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.+- Kubernetes mode needs RBAC: `get`/`list` on `pods` in the ingestion namespace, and network egress to pod IPs on the debug port, Kafka, the Postgres replica, and (when the etcd tools are enabled) the personhog etcd cluster.diff --git a/rust/ingestion-control-plane/src/api.rs b/rust/ingestion-control-plane/src/api.rsindex ea5b26aee654..16dfda8f3a25 100644--- a/rust/ingestion-control-plane/src/api.rs+++ b/rust/ingestion-control-plane/src/api.rs@@ -14,10 +14,12 @@ use uuid::Uuid;use k8s_awareness::DiscoveredPod;+use crate::etcd;use crate::jobs::{AnalysisRequest, JobView};use crate::kafka::browse::{self, BrowseParams, BrowseStop, MessageFilter, MessageRecord};use crate::kafka::client;use crate::kafka::lag::{self, ConsumerTarget, GroupLag, LagOverview};+use crate::personhog;use crate::proxy;use crate::state::AppState;use crate::ui;@@ -311,6 +313,123 @@ async fn get_messages(}))}+/// The configured etcd handle, or 503 when `ETCD_ENDPOINTS` is unset.+fn etcd_handle(state: &AppState) -> Result<Arc<crate::etcd::EtcdHandle>, ApiError> {+ state+ .etcd+ .clone()+ .ok_or_else(|| ApiError::unavailable("etcd tools are disabled (ETCD_ENDPOINTS not set)"))+}++async fn etcd_client(state: &AppState) -> Result<etcd_client::Client, ApiError> {+ etcd_handle(state)?+ .client()+ .await+ .map_err(|e| ApiError::unavailable(format!("etcd unreachable: {e:#}")))+}++/// Every explorer operation must stay under one of the configured allowed+/// prefixes, so a deployment can scope what this unauthenticated-but-+/// internal tool may touch.+fn validated_etcd_key<'a>(state: &AppState, key: &'a str) -> Result<&'a str, ApiError> {+ if key.is_empty() {+ return Err(ApiError::bad_request("key must not be empty"));+ }+ let allowed = state.config.etcd_allowed_prefix_list();+ if !allowed.iter().any(|prefix| key.starts_with(prefix)) {+ return Err(ApiError::bad_request(format!(+ "key '{key}' is outside the allowed prefixes {allowed:?}"+ )));+ }+ Ok(key)+}++#[derive(Deserialize)]+struct EtcdKeysQuery {+ prefix: String,+ from_key: Option<String>,+ limit: Option<i64>,+}++async fn etcd_list_keys(+ State(state): State<AppState>,+ Query(query): Query<EtcdKeysQuery>,+) -> Result<Json<etcd::KeyList>, ApiError> {+ validated_etcd_key(&state, &query.prefix)?;+ let limit = query.limit.unwrap_or(500).clamp(1, 1000);+ let client = etcd_client(&state).await?;+ let list = etcd::list_keys(&client, &query.prefix, query.from_key.as_deref(), limit)+ .await+ .map_err(|e| ApiError::upstream(format!("etcd list failed: {e:#}")))?;+ Ok(Json(list))+}++#[derive(Deserialize)]+struct EtcdKeyQuery {+ key: String,+}++async fn etcd_get_key(+ State(state): State<AppState>,+ Query(query): Query<EtcdKeyQuery>,+) -> Result<Json<etcd::KeyDetail>, ApiError> {+ validated_etcd_key(&state, &query.key)?;+ let client = etcd_client(&state).await?;+ let detail = etcd::get_key(&client, &query.key)+ .await+ .map_err(|e| ApiError::upstream(format!("etcd get failed: {e:#}")))?+ .ok_or_else(|| ApiError::not_found(format!("no key '{}'", query.key)))?;+ Ok(Json(detail))+}++#[derive(Deserialize)]+struct EtcdPutRequest {+ key: String,+ value: String,+}++async fn etcd_put_key(+ State(state): State<AppState>,+ Json(request): Json<EtcdPutRequest>,+) -> Result<Json<serde_json::Value>, ApiError> {+ validated_etcd_key(&state, &request.key)?;+ let client = etcd_client(&state).await?;+ let revision = etcd::put_key(&client, &request.key, &request.value)+ .await+ .map_err(|e| ApiError::upstream(format!("etcd put failed: {e:#}")))?;+ Ok(Json(json!({ "revision": revision })))+}++async fn etcd_delete_key(+ State(state): State<AppState>,+ Query(query): Query<EtcdKeyQuery>,+) -> Result<StatusCode, ApiError> {+ validated_etcd_key(&state, &query.key)?;+ let client = etcd_client(&state).await?;+ let deleted = etcd::delete_key(&client, &query.key)+ .await+ .map_err(|e| ApiError::upstream(format!("etcd delete failed: {e:#}")))?;+ if deleted {+ Ok(StatusCode::NO_CONTENT)+ } else {+ Err(ApiError::not_found(format!("no key '{}'", query.key)))+ }+}++async fn personhog_topology(+ State(state): State<AppState>,+) -> Result<Json<personhog::TopologyView>, ApiError> {+ let client = etcd_client(&state).await?;+ let deadlines = personhog::Deadlines {+ handoff: Duration::from_secs(state.config.personhog_handoff_deadline_secs),+ warming: Duration::from_secs(state.config.personhog_warming_deadline_secs),+ };+ let view = personhog::fetch_topology(&client, &state.config.personhog_etcd_prefix, &deadlines)+ .await+ .map_err(|e| ApiError::upstream(format!("personhog topology failed: {e:#}")))?;+ Ok(Json(view))+}+#[derive(Serialize)]struct PodsResponse {pods: Vec<DiscoveredPod>,@@ -337,6 +456,12 @@ pub fn router(state: AppState) -> Router {get(get_analysis).delete(cancel_analysis),).route("/api/pods", get(list_pods))+ .route("/api/etcd/keys", get(etcd_list_keys))+ .route(+ "/api/etcd/key",+ get(etcd_get_key).put(etcd_put_key).delete(etcd_delete_key),+ )+ .route("/api/personhog/topology", get(personhog_topology))// The consumer debug UI is served per pod; its relative `debug/...`// fetches resolve to the proxy route below. Pods are addressed by// namespace + name so identical names across lanes cannot collide.diff --git a/rust/ingestion-control-plane/src/config.rs b/rust/ingestion-control-plane/src/config.rsindex df4f0ce15fd9..88ba808de8b1 100644--- a/rust/ingestion-control-plane/src/config.rs+++ b/rust/ingestion-control-plane/src/config.rs@@ -146,6 +146,31 @@ pub struct Config {#[envconfig(default = "1000")]pub kafka_fetch_poll_timeout_ms: u64,++ /// Comma-separated etcd endpoints for the etcd explorer and personhog+ /// topology tools. Empty disables both tools.+ #[envconfig(from = "ETCD_ENDPOINTS", default = "")]+ pub etcd_endpoints: String,++ /// Comma-separated key prefixes the etcd explorer may read and write.+ /// Every operation's key must fall under one of them.+ #[envconfig(from = "ETCD_ALLOWED_PREFIXES", default = "/")]+ pub etcd_allowed_prefixes: String,++ /// Key prefix the personhog coordination state lives under; must match+ /// the personhog services' `ETCD_PREFIX`.+ #[envconfig(from = "PERSONHOG_ETCD_PREFIX", default = "/personhog/")]+ pub personhog_etcd_prefix: String,++ /// Per-phase handoff deadline used to flag stuck handoffs; must match+ /// the coordinator's `COORDINATOR_HANDOFF_DEADLINE_SECS` to agree with+ /// its cancellation decisions.+ #[envconfig(from = "PERSONHOG_HANDOFF_DEADLINE_SECS", default = "120")]+ pub personhog_handoff_deadline_secs: u64,++ /// Warming-phase deadline, mirroring `COORDINATOR_WARMING_DEADLINE_SECS`.+ #[envconfig(from = "PERSONHOG_WARMING_DEADLINE_SECS", default = "1800")]+ pub personhog_warming_deadline_secs: u64,}impl Config {@@ -153,6 +178,24 @@ impl Config {Self::init_from_env()}+ pub fn etcd_endpoint_list(&self) -> Vec<String> {+ self.etcd_endpoints+ .split(',')+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(str::to_string)+ .collect()+ }++ pub fn etcd_allowed_prefix_list(&self) -> Vec<String> {+ self.etcd_allowed_prefixes+ .split(',')+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(str::to_string)+ .collect()+ }+pub fn pod_targets(&self) -> Vec<PodTarget> {self.pod_label_selectors.split(',')diff --git a/rust/ingestion-control-plane/src/etcd.rs b/rust/ingestion-control-plane/src/etcd.rsnew file mode 100644index 000000000000..abd4ebe38f8c--- /dev/null+++ b/rust/ingestion-control-plane/src/etcd.rs@@ -0,0 +1,226 @@+use anyhow::Context;+use assignment_coordination::store::{EtcdStore, StoreConfig};+use etcd_client::{Client, GetOptions, SortOrder, SortTarget};+use serde::Serialize;+use tokio::sync::Mutex;++use crate::config::Config;++/// Lazily connected etcd client shared by the explorer and the personhog+/// topology tools. Connecting lazily keeps the service starting (and its+/// other tools working) when etcd is unreachable; the first request that+/// needs etcd pays the connect and surfaces the error.+pub struct EtcdHandle {+ endpoints: Vec<String>,+ client: Mutex<Option<Client>>,+}++impl EtcdHandle {+ /// `None` when `ETCD_ENDPOINTS` is unset, which disables the etcd tools.+ pub fn from_config(config: &Config) -> Option<Self> {+ let endpoints = config.etcd_endpoint_list();+ if endpoints.is_empty() {+ return None;+ }+ Some(Self {+ endpoints,+ client: Mutex::new(None),+ })+ }++ /// `Client` clones share one gRPC channel, and the channel reconnects on+ /// its own, so a connection established once is reused for the process+ /// lifetime.+ pub async fn client(&self) -> anyhow::Result<Client> {+ let mut guard = self.client.lock().await;+ if let Some(client) = guard.as_ref() {+ return Ok(client.clone());+ }+ // Connect through EtcdStore so its transport tuning (connect+ // timeout, HTTP/2 keepalive) stays defined in one place.+ let store = EtcdStore::connect(StoreConfig {+ endpoints: self.endpoints.clone(),+ prefix: String::new(),+ })+ .await+ .with_context(|| format!("connecting to etcd at {:?}", self.endpoints))?;+ let client = store.client().clone();+ *guard = Some(client.clone());+ Ok(client)+ }+}++/// The exclusive upper bound of the key range sharing `prefix`: the prefix+/// with its last non-0xff byte incremented (trailing 0xff bytes dropped).+/// Falls back to etcd's "all keys from here" sentinel (`[0]`) when every+/// byte is 0xff.+fn prefix_range_end(prefix: &[u8]) -> Vec<u8> {+ let mut end = prefix.to_vec();+ while let Some(last) = end.last_mut() {+ if *last < 0xff {+ *last += 1;+ return end;+ }+ end.pop();+ }+ vec![0]+}++#[derive(Serialize)]+pub struct KeyMeta {+ pub key: String,+ pub create_revision: i64,+ pub mod_revision: i64,+ pub version: i64,+ /// 0 when no lease is attached.+ pub lease: i64,+ pub value_bytes: usize,+}++#[derive(Serialize)]+pub struct KeyList {+ pub keys: Vec<KeyMeta>,+ /// More keys exist under the prefix beyond this page.+ pub more: bool,+ /// Total keys under the prefix (not just this page).+ pub count: i64,+ pub revision: i64,+ /// Cursor for the next page; pass as `from_key`.+ pub next_from_key: Option<String>,+}++#[derive(Serialize)]+pub struct KeyDetail {+ pub key: String,+ /// Lossy UTF-8 rendering of the value; check `value_is_utf8` before+ /// editing and writing it back.+ pub value: String,+ pub value_is_utf8: bool,+ pub value_bytes: usize,+ pub create_revision: i64,+ pub mod_revision: i64,+ pub version: i64,+ pub lease: i64,+ /// Remaining seconds on the attached lease, when one exists and the+ /// lookup succeeded.+ pub lease_ttl_secs: Option<i64>,+ pub lease_granted_ttl_secs: Option<i64>,+}++pub async fn list_keys(+ client: &Client,+ prefix: &str,+ from_key: Option<&str>,+ limit: i64,+) -> anyhow::Result<KeyList> {+ let start = from_key.filter(|k| k.as_bytes() > prefix.as_bytes());+ let options = GetOptions::new()+ .with_range(prefix_range_end(prefix.as_bytes()))+ .with_limit(limit)+ .with_sort(SortTarget::Key, SortOrder::Ascend);+ let resp = client+ .clone()+ .get(start.unwrap_or(prefix), Some(options))+ .await+ .context("etcd range read")?;++ let keys: Vec<KeyMeta> = resp+ .kvs()+ .iter()+ .map(|kv| KeyMeta {+ key: String::from_utf8_lossy(kv.key()).into_owned(),+ create_revision: kv.create_revision(),+ mod_revision: kv.mod_revision(),+ version: kv.version(),+ lease: kv.lease(),+ value_bytes: kv.value().len(),+ })+ .collect();+ // The next page starts just after the last key: its bytes plus a zero+ // byte is the smallest possible successor.+ let next_from_key = if resp.more() {+ keys.last().map(|meta| format!("{}\0", meta.key))+ } else {+ None+ };+ Ok(KeyList {+ more: resp.more(),+ count: resp.count(),+ revision: resp.header().map(|h| h.revision()).unwrap_or(0),+ next_from_key,+ keys,+ })+}++pub async fn get_key(client: &Client, key: &str) -> anyhow::Result<Option<KeyDetail>> {+ let resp = client+ .clone()+ .get(key, None)+ .await+ .context("etcd key read")?;+ let Some(kv) = resp.kvs().first() else {+ return Ok(None);+ };++ let (lease_ttl_secs, lease_granted_ttl_secs) = if kv.lease() != 0 {+ match client.clone().lease_time_to_live(kv.lease(), None).await {+ Ok(lease) => (Some(lease.ttl()), Some(lease.granted_ttl())),+ // The lease can expire between the key read and this lookup;+ // the key detail is still useful without it.+ Err(_) => (None, None),+ }+ } else {+ (None, None)+ };++ Ok(Some(KeyDetail {+ key: String::from_utf8_lossy(kv.key()).into_owned(),+ value: String::from_utf8_lossy(kv.value()).into_owned(),+ value_is_utf8: std::str::from_utf8(kv.value()).is_ok(),+ value_bytes: kv.value().len(),+ create_revision: kv.create_revision(),+ mod_revision: kv.mod_revision(),+ version: kv.version(),+ lease: kv.lease(),+ lease_ttl_secs,+ lease_granted_ttl_secs,+ }))+}++/// Plain put, never attaching a lease: writing a value to a lease-backed+/// key detaches it from its lease, which the UI warns about before saving.+pub async fn put_key(client: &Client, key: &str, value: &str) -> anyhow::Result<i64> {+ let resp = client+ .clone()+ .put(key, value, None)+ .await+ .context("etcd put")?;+ Ok(resp.header().map(|h| h.revision()).unwrap_or(0))+}++/// Single-key delete only; the explorer deliberately has no prefix delete.+pub async fn delete_key(client: &Client, key: &str) -> anyhow::Result<bool> {+ let resp = client+ .clone()+ .delete(key, None)+ .await+ .context("etcd delete")?;+ Ok(resp.deleted() > 0)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn prefix_range_end_increments_the_last_byte() {+ assert_eq!(prefix_range_end(b"/personhog/"), b"/personhog0".to_vec());+ assert_eq!(prefix_range_end(b"/"), b"0".to_vec());+ }++ #[test]+ fn prefix_range_end_handles_trailing_0xff() {+ assert_eq!(prefix_range_end(&[b'a', 0xff]), vec![b'b']);+ assert_eq!(prefix_range_end(&[0xff, 0xff]), vec![0]);+ }+}diff --git a/rust/ingestion-control-plane/src/lib.rs b/rust/ingestion-control-plane/src/lib.rsindex a084a46d0048..5d0ef05aeafa 100644--- a/rust/ingestion-control-plane/src/lib.rs+++ b/rust/ingestion-control-plane/src/lib.rs@@ -1,9 +1,11 @@pub mod api;pub mod cache;pub mod config;+pub mod etcd;pub mod jobs;pub mod k8s;pub mod kafka;+pub mod personhog;pub mod proxy;pub mod state;pub mod teams;diff --git a/rust/ingestion-control-plane/src/personhog.rs b/rust/ingestion-control-plane/src/personhog.rsnew file mode 100644index 000000000000..fa52bc6fbbec--- /dev/null+++ b/rust/ingestion-control-plane/src/personhog.rs@@ -0,0 +1,917 @@+//! Personhog topology view: one consistent etcd snapshot of the+//! coordination prefix, interpreted with the same types and pure+//! predicates the coordinator itself runs (`personhog-coordination`), so+//! the diagnostics cannot drift from the protocol.++use std::collections::HashMap;+use std::time::Duration;++use chrono::{DateTime, Utc};+use etcd_client::{Client, GetOptions};+use personhog_coordination::protocol::{+ drain_satisfied, freeze_quorum_met, missing_freeze_ackers, past_phase_deadline, warm_satisfied,+};+use personhog_coordination::types::{+ HandoffPhase, HandoffState, LeaderInfo, PartitionAssignment, PodDrainedAck, PodStatus,+ PodWarmedAck, RegisteredPod, RegisteredRouter, RouterFreezeAck,+};+use serde::Serialize;++/// A `Complete` handoff older than this without cleanup suggests the+/// coordinator is not running its cleanup pass.+const COMPLETE_CLEANUP_GRACE: Duration = Duration::from_secs(60);++pub struct Deadlines {+ pub handoff: Duration,+ pub warming: Duration,+}++/// One raw key-value from the coordination prefix, as fetched.+pub struct RawKv {+ pub key: String,+ pub value: Vec<u8>,+ pub lease: i64,+}++/// The coordination prefix, parsed into records. Unparseable or unknown+/// keys are carried as findings instead of failing the snapshot — an ops+/// tool must render a broken keyspace, not error on it.+#[derive(Default)]+pub struct RawSnapshot {+ pub pods: Vec<(RegisteredPod, i64)>,+ pub routers: Vec<(RegisteredRouter, i64)>,+ pub assignments: Vec<PartitionAssignment>,+ pub handoffs: Vec<HandoffState>,+ pub freeze_acks: Vec<RouterFreezeAck>,+ pub drained_acks: Vec<PodDrainedAck>,+ pub warmed_acks: Vec<PodWarmedAck>,+ pub leader: Option<(LeaderInfo, i64)>,+ pub total_partitions: Option<u32>,+ pub parse_errors: Vec<String>,+ pub unknown_keys: Vec<String>,+ pub revision: i64,+}++pub fn parse_snapshot(kvs: &[RawKv], prefix: &str, revision: i64) -> RawSnapshot {+ let mut snapshot = RawSnapshot {+ revision,+ ..RawSnapshot::default()+ };++ fn parse<T: serde::de::DeserializeOwned>(kv: &RawKv, errors: &mut Vec<String>) -> Option<T> {+ match serde_json::from_slice(&kv.value) {+ Ok(value) => Some(value),+ Err(e) => {+ errors.push(format!("unparseable record at {}: {e}", kv.key));+ None+ }+ }+ }++ for kv in kvs {+ let Some(suffix) = kv.key.strip_prefix(prefix) else {+ snapshot.unknown_keys.push(kv.key.clone());+ continue;+ };+ let errors = &mut snapshot.parse_errors;+ if suffix.starts_with("pods/") {+ if let Some(pod) = parse::<RegisteredPod>(kv, errors) {+ snapshot.pods.push((pod, kv.lease));+ }+ } else if suffix.starts_with("routers/") {+ if let Some(router) = parse::<RegisteredRouter>(kv, errors) {+ snapshot.routers.push((router, kv.lease));+ }+ } else if suffix.starts_with("assignments/") {+ if let Some(assignment) = parse::<PartitionAssignment>(kv, errors) {+ snapshot.assignments.push(assignment);+ }+ } else if suffix.starts_with("handoffs/") {+ if let Some(handoff) = parse::<HandoffState>(kv, errors) {+ snapshot.handoffs.push(handoff);+ }+ } else if suffix.starts_with("freeze_acks/") {+ if let Some(ack) = parse::<RouterFreezeAck>(kv, errors) {+ snapshot.freeze_acks.push(ack);+ }+ } else if suffix.starts_with("drained_acks/") {+ if let Some(ack) = parse::<PodDrainedAck>(kv, errors) {+ snapshot.drained_acks.push(ack);+ }+ } else if suffix.starts_with("warmed_acks/") {+ if let Some(ack) = parse::<PodWarmedAck>(kv, errors) {+ snapshot.warmed_acks.push(ack);+ }+ } else if suffix == "coordinator/leader" {+ if let Some(leader) = parse::<LeaderInfo>(kv, errors) {+ snapshot.leader = Some((leader, kv.lease));+ }+ } else if suffix == "config/total_partitions" {+ match std::str::from_utf8(&kv.value)+ .ok()+ .and_then(|s| s.parse::<u32>().ok())+ {+ Some(count) => snapshot.total_partitions = Some(count),+ None => errors.push(format!("invalid total_partitions at {}", kv.key)),+ }+ } else {+ snapshot.unknown_keys.push(kv.key.clone());+ }+ }+ snapshot+}++#[derive(Serialize, Clone, Copy, PartialEq, Eq, Debug)]+#[serde(rename_all = "lowercase")]+pub enum Severity {+ Error,+ Warning,+ Info,+}++#[derive(Serialize, Debug)]+pub struct Issue {+ pub severity: Severity,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub partition: Option<u32>,+ pub summary: String,+}++#[derive(Serialize)]+pub struct LeaderView {+ pub holder: String,+ pub lease_id: i64,+ pub lease_ttl_secs: Option<i64>,+}++#[derive(Serialize)]+pub struct PodView {+ pub pod_name: String,+ pub status: String,+ pub registered_at: i64,+ pub last_heartbeat: i64,+ pub advertise_address: Option<String>,+ pub lease_ttl_secs: Option<i64>,+ pub partitions: Vec<u32>,+}++#[derive(Serialize)]+pub struct RouterView {+ pub router_name: String,+ pub registered_at: i64,+ pub last_heartbeat: i64,+ pub lease_ttl_secs: Option<i64>,+}++#[derive(Serialize)]+pub struct HandoffView {+ pub old_owner: Option<String>,+ pub new_owner: String,+ pub phase: HandoffPhase,+ pub handoff_id: String,+ pub started_at: i64,+ pub phase_age_secs: Option<i64>,+ pub past_deadline: bool,+ /// What the protocol is currently waiting for, in operator terms.+ pub waiting_on: Option<String>,+ pub missing_freeze_ackers: Vec<String>,+ pub old_owner_registered: Option<bool>,+ pub new_owner_registered: bool,+}++#[derive(Serialize)]+pub struct PartitionView {+ pub partition: u32,+ pub owner: Option<String>,+ pub owner_registered: Option<bool>,+ pub advertise_address: Option<String>,+ pub handoff: Option<HandoffView>,+}++#[derive(Serialize)]+pub struct TopologyView {+ pub fetched_at: DateTime<Utc>,+ pub revision: i64,+ pub prefix: String,+ pub total_partitions: Option<u32>,+ pub leader: Option<LeaderView>,+ pub pods: Vec<PodView>,+ pub routers: Vec<RouterView>,+ pub partitions: Vec<PartitionView>,+ pub issues: Vec<Issue>,+}++fn phase_age_secs(handoff: &HandoffState, now_ms: i64) -> Option<i64> {+ let entered_ms = if handoff.phase_entered_at_ms > 0 {+ handoff.phase_entered_at_ms+ } else if handoff.started_at > 0 {+ handoff.started_at.saturating_mul(1000)+ } else {+ return None;+ };+ Some(now_ms.saturating_sub(entered_ms) / 1000)+}++/// What a non-terminal handoff is waiting for, using the coordinator's+/// own advance predicates. A phase whose predicate is already satisfied+/// is waiting on the coordinator itself — the signal that distinguishes+/// a stuck participant from a stuck coordinator.+fn waiting_on(+ handoff: &HandoffState,+ routers: &[RegisteredRouter],+ pods: &[RegisteredPod],+ freeze_acks: &[RouterFreezeAck],+ drained_acks: &[PodDrainedAck],+ warmed_acks: &[PodWarmedAck],+) -> Option<String> {+ match handoff.phase {+ HandoffPhase::Freezing => {+ if freeze_quorum_met(routers, freeze_acks, handoff) {+ Some("freeze quorum met; waiting on the coordinator to advance".to_string())+ } else {+ let missing = missing_freeze_ackers(routers, freeze_acks, handoff);+ Some(format!(+ "waiting on freeze acks from {}",+ missing.join(", ")+ ))+ }+ }+ HandoffPhase::Draining => {+ if drain_satisfied(pods, drained_acks, handoff) {+ Some("drain satisfied; waiting on the coordinator to advance".to_string())+ } else {+ let owner = handoff.old_owner.as_deref().unwrap_or("?");+ Some(format!("waiting on a drained ack from old owner {owner}"))+ }+ }+ HandoffPhase::Warming => {+ if warm_satisfied(warmed_acks, handoff) {+ Some("warmed; waiting on the coordinator to complete".to_string())+ } else {+ Some(format!(+ "waiting on a warmed ack from new owner {}",+ handoff.new_owner+ ))+ }+ }+ HandoffPhase::Complete => None,+ }+}++pub fn derive_view(+ raw: RawSnapshot,+ lease_ttls: &HashMap<i64, i64>,+ prefix: &str,+ now_ms: i64,+ deadlines: &Deadlines,+) -> TopologyView {+ let mut issues: Vec<Issue> = Vec::new();++ for error in &raw.parse_errors {+ issues.push(Issue {+ severity: Severity::Error,+ partition: None,+ summary: error.clone(),+ });+ }+ if !raw.unknown_keys.is_empty() {+ issues.push(Issue {+ severity: Severity::Info,+ partition: None,+ summary: format!(+ "{} key(s) under the prefix outside the known layout: {}",+ raw.unknown_keys.len(),+ raw.unknown_keys.join(", ")+ ),+ });+ }++ if raw.total_partitions.is_none() {+ issues.push(Issue {+ severity: Severity::Error,+ partition: None,+ summary: "config/total_partitions is missing: the coordinator cannot plan, and \+ leaders and routers fail at startup"+ .to_string(),+ });+ }+ if raw.leader.is_none() && (!raw.pods.is_empty() || !raw.routers.is_empty()) {+ issues.push(Issue {+ severity: Severity::Warning,+ partition: None,+ summary: "no coordinator leader is elected".to_string(),+ });+ }++ let pods: Vec<RegisteredPod> = raw.pods.iter().map(|(p, _)| p.clone()).collect();+ let routers: Vec<RegisteredRouter> = raw.routers.iter().map(|(r, _)| r.clone()).collect();+ let pod_registered = |name: &str| pods.iter().any(|p| p.pod_name == name);++ for (pod, _) in &raw.pods {+ if pod.status == PodStatus::Draining {+ issues.push(Issue {+ severity: Severity::Info,+ partition: None,+ summary: format!("pod {} is draining", pod.pod_name),+ });+ }+ }++ let assignments_by_partition: HashMap<u32, &PartitionAssignment> =+ raw.assignments.iter().map(|a| (a.partition, a)).collect();+ let handoffs_by_partition: HashMap<u32, &HandoffState> =+ raw.handoffs.iter().map(|h| (h.partition, h)).collect();++ // Partitions worth a row: everything under the configured count, plus+ // anything that has state anyway (misconfiguration shows itself).+ let mut partition_ids: Vec<u32> = (0..raw.total_partitions.unwrap_or(0)).collect();+ for partition in assignments_by_partition+ .keys()+ .chain(handoffs_by_partition.keys())+ {+ if !partition_ids.contains(partition) {+ partition_ids.push(*partition);+ }+ }+ partition_ids.sort_unstable();++ let mut partitions: Vec<PartitionView> = Vec::with_capacity(partition_ids.len());+ for partition in partition_ids {+ let assignment = assignments_by_partition.get(&partition);+ let handoff = handoffs_by_partition.get(&partition);++ if let Some(total) = raw.total_partitions {+ if partition >= total && (assignment.is_some() || handoff.is_some()) {+ issues.push(Issue {+ severity: Severity::Warning,+ partition: Some(partition),+ summary: format!(+ "partition {partition} has state but total_partitions is {total}"+ ),+ });+ }+ if partition < total && assignment.is_none() && handoff.is_none() {+ issues.push(Issue {+ severity: Severity::Warning,+ partition: Some(partition),+ summary: format!("partition {partition} has no assignment and no handoff"),+ });+ }+ }++ let owner_registered = assignment.map(|a| pod_registered(&a.owner));+ if let (Some(assignment), Some(false), None) = (assignment, owner_registered, handoff) {+ issues.push(Issue {+ severity: Severity::Error,+ partition: Some(partition),+ summary: format!(+ "partition {partition} owner {} is not registered and no handoff is \+ replanning it",+ assignment.owner+ ),+ });+ }++ let freeze_acks: Vec<RouterFreezeAck> = raw+ .freeze_acks+ .iter()+ .filter(|a| a.partition == partition)+ .cloned()+ .collect();+ let drained_acks: Vec<PodDrainedAck> = raw+ .drained_acks+ .iter()+ .filter(|a| a.partition == partition)+ .cloned()+ .collect();+ let warmed_acks: Vec<PodWarmedAck> = raw+ .warmed_acks+ .iter()+ .filter(|a| a.partition == partition)+ .cloned()+ .collect();++ // Acks not matching the live handoff attempt are inert by design+ // (quorum checks correlate by handoff_id); surface them so an+ // operator doesn't mistake them for progress.+ let current_id = handoff.map(|h| h.handoff_id.as_str());+ let stale_acks = freeze_acks+ .iter()+ .map(|a| a.handoff_id.as_str())+ .chain(drained_acks.iter().map(|a| a.handoff_id.as_str()))+ .chain(warmed_acks.iter().map(|a| a.handoff_id.as_str()))+ .filter(|id| Some(*id) != current_id)+ .count();+ if stale_acks > 0 {+ issues.push(Issue {+ severity: Severity::Info,+ partition: Some(partition),+ summary: format!(+ "partition {partition} has {stale_acks} ack(s) for another handoff attempt \+ (inert; cleaned up with the record)"+ ),+ });+ }++ let handoff_view = handoff.map(|h| {+ let past_deadline =+ past_phase_deadline(h, now_ms, deadlines.handoff, deadlines.warming);+ let age = phase_age_secs(h, now_ms);+ let waiting = waiting_on(+ h,+ &routers,+ &pods,+ &freeze_acks,+ &drained_acks,+ &warmed_acks,+ );+ let new_owner_registered = pod_registered(&h.new_owner);++ if past_deadline {+ issues.push(Issue {+ severity: Severity::Error,+ partition: Some(partition),+ summary: format!(+ "handoff for partition {partition} is past its {:?} deadline ({}): {}",+ h.phase,+ age.map(|secs| format!("{secs}s in phase"))+ .unwrap_or_else(|| "age unknown".to_string()),+ waiting.as_deref().unwrap_or("unknown wait")+ ),+ });+ }+ if h.phase != HandoffPhase::Complete && !new_owner_registered {+ issues.push(Issue {+ severity: Severity::Warning,+ partition: Some(partition),+ summary: format!(+ "handoff for partition {partition} targets unregistered pod {}; the \+ planner will cancel or replace it",+ h.new_owner+ ),+ });+ }+ if h.phase == HandoffPhase::Complete+ && age.is_some_and(|secs| secs > COMPLETE_CLEANUP_GRACE.as_secs() as i64)+ {+ issues.push(Issue {+ severity: Severity::Warning,+ partition: Some(partition),+ summary: format!(+ "completed handoff for partition {partition} has not been cleaned up; \+ the coordinator may not be running"+ ),+ });+ }++ HandoffView {+ old_owner: h.old_owner.clone(),+ new_owner: h.new_owner.clone(),+ phase: h.phase,+ handoff_id: h.handoff_id.clone(),+ started_at: h.started_at,+ phase_age_secs: age,+ past_deadline,+ waiting_on: waiting,+ missing_freeze_ackers: missing_freeze_ackers(&routers, &freeze_acks, h),+ old_owner_registered: h.old_owner.as_deref().map(pod_registered),+ new_owner_registered,+ }+ });++ partitions.push(PartitionView {+ partition,+ owner: assignment.map(|a| a.owner.clone()),+ owner_registered,+ advertise_address: assignment.and_then(|a| a.advertise_address.clone()),+ handoff: handoff_view,+ });+ }++ let mut pod_partitions: HashMap<&str, Vec<u32>> = HashMap::new();+ for assignment in &raw.assignments {+ pod_partitions+ .entry(assignment.owner.as_str())+ .or_default()+ .push(assignment.partition);+ }++ let severity_rank = |severity: Severity| match severity {+ Severity::Error => 0,+ Severity::Warning => 1,+ Severity::Info => 2,+ };+ issues.sort_by_key(|issue| (severity_rank(issue.severity), issue.partition));++ TopologyView {+ fetched_at: Utc::now(),+ revision: raw.revision,+ prefix: prefix.to_string(),+ total_partitions: raw.total_partitions,+ leader: raw.leader.as_ref().map(|(leader, _)| LeaderView {+ holder: leader.holder.clone(),+ lease_id: leader.lease_id,+ lease_ttl_secs: lease_ttls.get(&leader.lease_id).copied(),+ }),+ pods: raw+ .pods+ .iter()+ .map(|(pod, lease)| {+ let mut partitions = pod_partitions+ .get(pod.pod_name.as_str())+ .cloned()+ .unwrap_or_default();+ partitions.sort_unstable();+ PodView {+ pod_name: pod.pod_name.clone(),+ status: format!("{:?}", pod.status),+ registered_at: pod.registered_at,+ last_heartbeat: pod.last_heartbeat,+ advertise_address: pod.advertise_address.clone(),+ lease_ttl_secs: lease_ttls.get(lease).copied(),+ partitions,+ }+ })+ .collect(),+ routers: raw+ .routers+ .iter()+ .map(|(router, lease)| RouterView {+ router_name: router.router_name.clone(),+ registered_at: router.registered_at,+ last_heartbeat: router.last_heartbeat,+ lease_ttl_secs: lease_ttls.get(lease).copied(),+ })+ .collect(),+ partitions,+ issues,+ }+}++/// The lease ids the view wants remaining TTLs for.+pub fn lease_ids(raw: &RawSnapshot) -> Vec<i64> {+ let mut ids: Vec<i64> = raw+ .pods+ .iter()+ .map(|(_, lease)| *lease)+ .chain(raw.routers.iter().map(|(_, lease)| *lease))+ .chain(raw.leader.iter().map(|(_, lease)| *lease))+ .filter(|lease| *lease != 0)+ .collect();+ ids.sort_unstable();+ ids.dedup();+ ids+}++pub async fn fetch_topology(+ client: &Client,+ prefix: &str,+ deadlines: &Deadlines,+) -> anyhow::Result<TopologyView> {+ let resp = client+ .clone()+ .get(prefix, Some(GetOptions::new().with_prefix()))+ .await?;+ let revision = resp.header().map(|h| h.revision()).unwrap_or(0);+ let kvs: Vec<RawKv> = resp+ .kvs()+ .iter()+ .map(|kv| RawKv {+ key: String::from_utf8_lossy(kv.key()).into_owned(),+ value: kv.value().to_vec(),+ lease: kv.lease(),+ })+ .collect();+ let raw = parse_snapshot(&kvs, prefix, revision);++ let mut lease_ttls: HashMap<i64, i64> = HashMap::new();+ for lease in lease_ids(&raw) {+ // A lease can expire between the snapshot and this lookup; the+ // view just shows no TTL for it.+ if let Ok(lease_info) = client.clone().lease_time_to_live(lease, None).await {+ if lease_info.ttl() >= 0 {+ lease_ttls.insert(lease, lease_info.ttl());+ }+ }+ }++ Ok(derive_view(+ raw,+ &lease_ttls,+ prefix,+ Utc::now().timestamp_millis(),+ deadlines,+ ))+}++#[cfg(test)]+mod tests {+ use super::*;++ const PREFIX: &str = "/personhog/";++ fn deadlines() -> Deadlines {+ Deadlines {+ handoff: Duration::from_secs(120),+ warming: Duration::from_secs(1800),+ }+ }++ fn kv(suffix: &str, value: serde_json::Value, lease: i64) -> RawKv {+ RawKv {+ key: format!("{PREFIX}{suffix}"),+ value: serde_json::to_vec(&value).unwrap(),+ lease,+ }+ }++ fn pod_kv(name: &str) -> RawKv {+ kv(+ &format!("pods/{name}"),+ serde_json::json!({+ "pod_name": name,+ "status": "Ready",+ "registered_at": 100,+ "last_heartbeat": 200,+ }),+ 7,+ )+ }++ fn router_kv(name: &str) -> RawKv {+ kv(+ &format!("routers/{name}"),+ serde_json::json!({+ "router_name": name,+ "registered_at": 100,+ "last_heartbeat": 200,+ }),+ 8,+ )+ }++ fn assignment_kv(partition: u32, owner: &str) -> RawKv {+ kv(+ &format!("assignments/{partition}"),+ serde_json::json!({+ "partition": partition,+ "owner": owner,+ "status": "Active",+ }),+ 0,+ )+ }++ fn handoff_kv(+ partition: u32,+ phase: &str,+ old_owner: Option<&str>,+ new_owner: &str,+ quorum: &[&str],+ phase_entered_at_ms: i64,+ ) -> RawKv {+ kv(+ &format!("handoffs/{partition}"),+ serde_json::json!({+ "partition": partition,+ "old_owner": old_owner,+ "new_owner": new_owner,+ "phase": phase,+ "started_at": 1,+ "handoff_id": "hid-1",+ "freeze_quorum": quorum,+ "phase_entered_at_ms": phase_entered_at_ms,+ }),+ 0,+ )+ }++ fn total_partitions_kv(count: u32) -> RawKv {+ RawKv {+ key: format!("{PREFIX}config/total_partitions"),+ value: count.to_string().into_bytes(),+ lease: 0,+ }+ }++ fn view(kvs: &[RawKv], now_ms: i64) -> TopologyView {+ let raw = parse_snapshot(kvs, PREFIX, 42);+ derive_view(raw, &HashMap::new(), PREFIX, now_ms, &deadlines())+ }++ fn issue_summaries(view: &TopologyView, severity: Severity) -> Vec<&str> {+ view.issues+ .iter()+ .filter(|issue| issue.severity == severity)+ .map(|issue| issue.summary.as_str())+ .collect()+ }++ #[test]+ fn a_stuck_freezing_handoff_names_the_missing_router() {+ let kvs = vec![+ total_partitions_kv(1),+ pod_kv("pod-a"),+ pod_kv("pod-b"),+ router_kv("router-0"),+ router_kv("router-1"),+ assignment_kv(0, "pod-a"),+ handoff_kv(+ 0,+ "Freezing",+ Some("pod-a"),+ "pod-b",+ &["router-0", "router-1"],+ 1_000,+ ),+ kv(+ "freeze_acks/0/router-0",+ serde_json::json!({+ "router_name": "router-0",+ "partition": 0,+ "acked_at": 2,+ "handoff_id": "hid-1",+ }),+ 0,+ ),+ ];+ // 10 minutes in phase: past the 120s Freezing deadline.+ let topology = view(&kvs, 601_000);++ let handoff = topology.partitions[0].handoff.as_ref().unwrap();+ assert!(handoff.past_deadline);+ assert_eq!(handoff.missing_freeze_ackers, vec!["router-1"]);+ assert!(handoff+ .waiting_on+ .as_ref()+ .unwrap()+ .contains("waiting on freeze acks from router-1"));+ assert!(issue_summaries(&topology, Severity::Error)+ .iter()+ .any(|s| s.contains("past its Freezing deadline")));+ }++ #[test]+ fn a_satisfied_phase_points_at_the_coordinator() {+ let kvs = vec![+ total_partitions_kv(1),+ pod_kv("pod-b"),+ assignment_kv(0, "pod-b"),+ // Draining with a dead old owner: drain is vacuously satisfied,+ // so the wait is on the coordinator itself.+ handoff_kv(0, "Draining", Some("pod-gone"), "pod-b", &[], 1_000),+ ];+ let topology = view(&kvs, 10_000);++ let handoff = topology.partitions[0].handoff.as_ref().unwrap();+ assert_eq!(+ handoff.waiting_on.as_deref(),+ Some("drain satisfied; waiting on the coordinator to advance")+ );+ }++ #[test]+ fn a_dead_owner_without_a_handoff_is_an_error_and_with_one_is_not() {+ let kvs = vec![+ total_partitions_kv(2),+ pod_kv("pod-b"),+ assignment_kv(0, "pod-gone"),+ assignment_kv(1, "pod-gone"),+ handoff_kv(1, "Warming", Some("pod-gone"), "pod-b", &[], 9_000),+ ];+ let topology = view(&kvs, 10_000);++ let errors = issue_summaries(&topology, Severity::Error);+ assert!(errors+ .iter()+ .any(|s| s.contains("partition 0 owner pod-gone")));+ assert!(!errors.iter().any(|s| s.contains("partition 1 owner")));+ }++ #[test]+ fn a_lingering_complete_handoff_flags_the_coordinator() {+ let kvs = vec![+ total_partitions_kv(1),+ pod_kv("pod-b"),+ assignment_kv(0, "pod-b"),+ handoff_kv(0, "Complete", None, "pod-b", &[], 1_000),+ ];+ let topology = view(&kvs, 601_000);++ assert!(issue_summaries(&topology, Severity::Warning)+ .iter()+ .any(|s| s.contains("has not been cleaned up")));+ // Complete is terminal: never past deadline.+ assert!(+ !topology.partitions[0]+ .handoff+ .as_ref()+ .unwrap()+ .past_deadline+ );+ }++ #[test]+ fn unassigned_and_out_of_range_partitions_are_flagged() {+ let kvs = vec![+ total_partitions_kv(2),+ pod_kv("pod-a"),+ assignment_kv(0, "pod-a"),+ assignment_kv(5, "pod-a"),+ ];+ let topology = view(&kvs, 10_000);++ let warnings = issue_summaries(&topology, Severity::Warning);+ assert!(warnings+ .iter()+ .any(|s| s.contains("partition 1 has no assignment and no handoff")));+ assert!(warnings+ .iter()+ .any(|s| s.contains("partition 5 has state but total_partitions is 2")));+ // The out-of-range partition still renders a row.+ assert!(topology.partitions.iter().any(|p| p.partition == 5));+ }++ #[test]+ fn stale_acks_are_inert_info_and_matching_acks_are_not() {+ let kvs = vec![+ total_partitions_kv(1),+ pod_kv("pod-a"),+ pod_kv("pod-b"),+ router_kv("router-0"),+ assignment_kv(0, "pod-a"),+ handoff_kv(0, "Freezing", Some("pod-a"), "pod-b", &["router-0"], 9_000),+ kv(+ "freeze_acks/0/router-0",+ serde_json::json!({+ "router_name": "router-0",+ "partition": 0,+ "acked_at": 2,+ "handoff_id": "a-previous-attempt",+ }),+ 0,+ ),+ ];+ let topology = view(&kvs, 10_000);++ assert!(issue_summaries(&topology, Severity::Info)+ .iter()+ .any(|s| s.contains("ack(s) for another handoff attempt")));+ // The stale ack must not satisfy the quorum.+ let handoff = topology.partitions[0].handoff.as_ref().unwrap();+ assert_eq!(handoff.missing_freeze_ackers, vec!["router-0"]);+ }++ #[test]+ fn missing_total_partitions_is_an_error_without_unassigned_noise() {+ let kvs = vec![pod_kv("pod-a"), assignment_kv(0, "pod-a")];+ let topology = view(&kvs, 10_000);++ assert!(issue_summaries(&topology, Severity::Error)+ .iter()+ .any(|s| s.contains("config/total_partitions is missing")));+ assert!(!issue_summaries(&topology, Severity::Warning)+ .iter()+ .any(|s| s.contains("no assignment")));+ }++ #[test]+ fn a_dead_new_owner_warns_and_unparseable_records_surface() {+ let mut kvs = vec![+ total_partitions_kv(1),+ pod_kv("pod-a"),+ assignment_kv(0, "pod-a"),+ handoff_kv(0, "Warming", Some("pod-a"), "pod-gone", &[], 9_000),+ ];+ kvs.push(RawKv {+ key: format!("{PREFIX}pods/broken"),+ value: b"not json".to_vec(),+ lease: 0,+ });+ let topology = view(&kvs, 10_000);++ assert!(issue_summaries(&topology, Severity::Warning)+ .iter()+ .any(|s| s.contains("targets unregistered pod pod-gone")));+ assert!(issue_summaries(&topology, Severity::Error)+ .iter()+ .any(|s| s.contains("unparseable record at /personhog/pods/broken")));+ }++ #[test]+ fn pods_carry_their_assigned_partitions_and_lease_ttls() {+ let kvs = vec![+ total_partitions_kv(2),+ pod_kv("pod-a"),+ assignment_kv(1, "pod-a"),+ assignment_kv(0, "pod-a"),+ ];+ let raw = parse_snapshot(&kvs, PREFIX, 42);+ let ttls = HashMap::from([(7, 21)]);+ let topology = derive_view(raw, &ttls, PREFIX, 10_000, &deadlines());++ assert_eq!(topology.pods[0].partitions, vec![0, 1]);+ assert_eq!(topology.pods[0].lease_ttl_secs, Some(21));+ assert_eq!(topology.revision, 42);+ }+}diff --git a/rust/ingestion-control-plane/src/state.rs b/rust/ingestion-control-plane/src/state.rsindex b8802899229a..4b0133efb24b 100644--- a/rust/ingestion-control-plane/src/state.rs+++ b/rust/ingestion-control-plane/src/state.rs@@ -6,6 +6,7 @@ use tokio::sync::Semaphore;use crate::cache::TtlCache;use crate::config::Config;+use crate::etcd::EtcdHandle;use crate::jobs::JobRegistry;use crate::k8s::PodDiscovery;use crate::kafka::lag::{ConsumerTarget, LagOverview};@@ -25,6 +26,8 @@ pub struct AppState {/// Caps concurrent synchronous message-browse scans; each holds a Kafka/// consumer on the blocking pool for up to the browse deadline.pub browse_permits: Arc<Semaphore>,+ /// `None` when `ETCD_ENDPOINTS` is unset; the etcd tools then 503.+ pub etcd: Option<Arc<EtcdHandle>>,}impl AppState {@@ -49,6 +52,11 @@ impl AppState {}};+ let etcd = EtcdHandle::from_config(&config);+ if etcd.is_none() {+ tracing::info!("ETCD_ENDPOINTS not set; etcd tools disabled");+ }+// No overall request timeout: the debug proxy pipes long-lived SSE// streams. Connect timeout still bounds unreachable pods.let http = reqwest::Client::builder()@@ -68,6 +76,7 @@ impl AppState {config.overview_cache_ttl_secs,))),browse_permits: Arc::new(Semaphore::new(config.browse_max_concurrent.max(1))),+ etcd: etcd.map(Arc::new),config: Arc::new(config),})}diff --git a/rust/ingestion-control-plane/src/ui/index.html b/rust/ingestion-control-plane/src/ui/index.htmlindex 7c2fada02045..59f199e28afb 100644--- a/rust/ingestion-control-plane/src/ui/index.html+++ b/rust/ingestion-control-plane/src/ui/index.html@@ -155,6 +155,23 @@.chip .x { background: none; border: 0; color: var(--muted); cursor: pointer; padding: 0 4px; font-size: 12px; }.chip .x:hover { color: var(--error); }tr.msg-detail td { background: var(--panel-2); }+ .tree-row {+ display: flex; align-items: center; gap: 6px; padding: 3px 14px 3px 0;+ cursor: pointer; font-size: 12px;+ }+ .tree-row:hover { background: rgba(79,124,255,0.06); }+ .tree-row.selected { background: rgba(79,124,255,0.1); }+ .tree-row .chev { width: 14px; color: var(--muted); flex: 0 0 auto; text-align: center; }+ .tree-row .meta {+ margin-left: auto; display: flex; gap: 10px; align-items: center;+ color: var(--muted); font-family: var(--mono); font-size: 11px; padding-right: 14px;+ }+ textarea.kv-value {+ width: 100%; min-height: 180px; background: var(--bg); color: var(--text);+ border: 1px solid var(--border); border-radius: 6px; padding: 10px;+ font-family: var(--mono); font-size: 11px; box-sizing: border-box; resize: vertical;+ }+ textarea.kv-value:focus { outline: none; border-color: var(--accent); }pre.payload {margin: 0 0 8px; padding: 10px; background: var(--bg); border: 1px solid var(--border); border-radius: 6px;font-family: var(--mono); font-size: 11px; white-space: pre-wrap; word-break: break-word;@@ -1038,8 +1055,423 @@},};+ // ---------- section: etcd explorer ----------+ // Generic prefix-bounded key browser with edit/create/delete. Raw+ // writes to coordination state are protocol-dangerous, so every write+ // confirms first, with an extra warning for assignment keys.+ const etcdSection = {+ id: "etcd",+ title: "Etcd explorer",+ description: "Browse keys under a prefix, inspect values and lease state, and edit, create, or delete keys. Writes bypass every coordination protocol: use with care.",+ prefix: "/personhog/",+ rows: [],+ nextFromKey: null,+ totalCount: null,+ selectedKey: null,+ mount(root) {+ this.rows = [];+ this.nextFromKey = null;+ this.selectedKey = null;+ this.query = "";+ this.openState = new Map();++ const search = el("input", {+ type: "search", class: "search", placeholder: "Filter loaded keys…",+ oninput: () => { this.query = search.value.trim().toLowerCase(); this.renderTree(); },+ });+ this.ui = {+ prefixInput: el("input", {+ type: "text", class: "search", value: this.prefix, spellcheck: "false",+ onkeydown: (e) => { if (e.key === "Enter") this.reload(); },+ }),+ search,+ matchCount: el("span", { class: "muted mono count" }),+ status: el("span", { class: "muted mono" }),+ loadMoreBtn: el("button", { class: "small", onclick: () => this.fetchPage() }, "Load more"),+ error: el("div", {}),+ treeBody: el("div", { style: "padding: 4px 0 8px" }),+ detail: el("div", {}),+ };++ root.append(+ el("div", { class: "panel" },+ el("h2", {}, "Keys", this.ui.status),+ el("div", { class: "row toolbar" },+ el("span", { class: "muted" }, "prefix"),+ this.ui.prefixInput,+ el("button", { class: "small", onclick: () => this.reload() }, "Load"),+ el("button", { class: "small", onclick: () => this.openEditor(null) }, "New key"),+ this.ui.loadMoreBtn),+ el("div", { class: "row toolbar" }, this.ui.search, this.ui.matchCount),+ this.ui.error,+ this.ui.treeBody),+ this.ui.detail+ );+ this.reload();+ },++ reload() {+ this.prefix = this.ui.prefixInput.value.trim();+ this.rows = [];+ this.nextFromKey = null;+ this.totalCount = null;+ this.openState = new Map();+ this.renderStatus();+ this.fetchPage();+ },++ async fetchPage() {+ if (!this.prefix) return;+ const params = new URLSearchParams({ prefix: this.prefix });+ if (this.nextFromKey) params.set("from_key", this.nextFromKey);+ this.ui.loadMoreBtn.disabled = true;+ try {+ const data = await fetchJSON(`api/etcd/keys?${params}`);+ this.rows = this.rows.concat(data.keys);+ this.nextFromKey = data.next_from_key;+ this.totalCount = data.count;+ this.ui.error.replaceChildren();+ this.renderTree();+ } catch (e) {+ this.ui.error.replaceChildren(el("div", { class: "error-box" }, String(e)));+ }+ this.renderStatus();+ },++ renderStatus() {+ this.ui.status.textContent = this.totalCount === null+ ? ""+ : `${fmtInt(this.rows.length)} of ${fmtInt(this.totalCount)} keys loaded`;+ this.ui.loadMoreBtn.disabled = !this.nextFromKey;+ this.ui.loadMoreBtn.style.display = this.nextFromKey ? "" : "none";+ },++ // The loaded keys form a tree on `/`. A node can be both a value+ // and a directory (etcd allows `/a` and `/a/b` to coexist): its+ // chevron toggles the children, clicking the row opens the value.+ buildTree(rows) {+ const root = { name: "", path: "", children: new Map(), leaf: null, count: 0 };+ for (const row of rows) {+ const parts = row.key.split("/").filter((s) => s !== "");+ let node = root;+ let path = "";+ for (let i = 0; i < parts.length; i++) {+ path += "/" + parts[i];+ if (!node.children.has(parts[i])) {+ node.children.set(parts[i], { name: parts[i], path, children: new Map(), leaf: null, count: 0 });+ }+ node = node.children.get(parts[i]);+ node.count++;+ if (i === parts.length - 1) node.leaf = row;+ }+ }+ return root;+ },++ isOpen(node, depth) {+ if (this.query) return true;+ if (this.openState.has(node.path)) return this.openState.get(node.path);+ // Top-level and single-child chains open by default, so the+ // common deep prefix does not cost a click per segment.+ return depth === 0 || node.children.size === 1;+ },++ toggleDir(node, depth) {+ this.openState.set(node.path, !this.isOpen(node, depth));+ this.renderTree();+ },++ renderTree() {+ const q = this.query;+ const rows = q ? this.rows.filter((row) => row.key.toLowerCase().includes(q)) : this.rows;+ this.ui.matchCount.textContent = q ? `${fmtInt(rows.length)} of ${fmtInt(this.rows.length)}` : fmtInt(this.rows.length);+ if (!rows.length) {+ this.ui.treeBody.replaceChildren(el("div", { class: "empty" }, q ? "No matches." : "No keys loaded. Set a prefix and load."));+ return;+ }+ const byName = (a, b) => a.name.localeCompare(b.name, undefined, { numeric: true });+ const lines = [];+ const renderNode = (node, depth) => {+ const isDir = node.children.size > 0;+ const open = isDir && this.isOpen(node, depth);+ const meta = node.leaf+ ? el("span", { class: "meta" },+ node.leaf.lease && node.leaf.lease !== 0 ? el("span", { class: "pill accent", title: `lease ${node.leaf.lease}` }, "leased") : null,+ el("span", {}, `v${fmtInt(node.leaf.version)}`),+ el("span", {}, fmtBytes(node.leaf.value_bytes)))+ : el("span", { class: "meta" }, `${fmtInt(node.count)} key${node.count === 1 ? "" : "s"}`);+ lines.push(el("div", {+ class: `tree-row ${node.leaf && node.leaf.key === this.selectedKey ? "selected" : ""}`,+ style: `padding-left: ${14 + depth * 16}px`,+ title: node.leaf ? node.leaf.key : node.path,+ onclick: () => node.leaf ? this.openKey(node.leaf.key) : this.toggleDir(node, depth),+ },+ isDir+ ? el("span", { class: "chev", onclick: (e) => { e.stopPropagation(); this.toggleDir(node, depth); } }, open ? "▾" : "▸")+ : el("span", { class: "chev" }),+ el("span", { class: "mono" }, isDir && !node.leaf ? `${node.name}/` : node.name),+ meta));+ if (open) {+ for (const child of [...node.children.values()].sort(byName)) renderNode(child, depth + 1);+ }+ };+ const root = this.buildTree(rows);+ for (const node of [...root.children.values()].sort(byName)) renderNode(node, 0);+ this.ui.treeBody.replaceChildren(...lines);+ },++ async openKey(key) {+ this.selectedKey = key;+ this.renderTree();+ try {+ const detail = await fetchJSON(`api/etcd/key?key=${encodeURIComponent(key)}`);+ this.renderDetail(detail);+ } catch (e) {+ this.ui.detail.replaceChildren(el("div", { class: "panel" }, el("div", { class: "error-box" }, String(e))));+ }+ },++ confirmWrite(action, key) {+ let message = `${action} etcd key:\n\n${key}\n\nThis bypasses every coordination protocol.`;+ if (key.includes("/assignments/")) {+ message += "\n\n⚠️ This is a personhog ASSIGNMENT key. Writing it directly is forbidden by the protocol: routers only observe ownership through handoff Complete events, so a raw write leaves an unfenced old owner serving beside the new one. A force-reassignment must create a handoff record instead.";+ }+ return window.confirm(message);+ },++ renderDetail(detail) {+ let pretty = detail.value;+ try { pretty = JSON.stringify(JSON.parse(detail.value), null, 2); } catch { /* not JSON */ }+ const meta = el("div", { class: "row" },+ el("span", { class: "pill muted" }, `version ${fmtInt(detail.version)}`),+ el("span", { class: "pill muted" }, `mod rev ${fmtInt(detail.mod_revision)}`),+ el("span", { class: "pill muted" }, `create rev ${fmtInt(detail.create_revision)}`),+ detail.lease !== 0+ ? el("span", { class: "pill accent", title: `lease ${detail.lease}` },+ detail.lease_ttl_secs === null ? "leased (ttl unknown)" : `lease ${detail.lease_ttl_secs}s / ${detail.lease_granted_ttl_secs}s`)+ : null,+ el("span", { class: "muted mono" }, fmtBytes(detail.value_bytes)),+ el("span", { class: "row", style: "padding: 0; margin-left: auto" },+ el("button", { class: "small", disabled: !detail.value_is_utf8, title: detail.value_is_utf8 ? "" : "Value is not UTF-8; editing would corrupt it", onclick: () => this.openEditor(detail) }, "Edit"),+ el("button", { class: "small", onclick: () => this.deleteKey(detail.key) }, "Delete")));+ this.ui.detail.replaceChildren(+ el("div", { class: "panel" },+ el("h2", {}, el("span", { class: "ns" }, detail.key)),+ meta,+ el("div", { style: "padding: 0 14px 12px" }, el("pre", { class: "payload" }, pretty)))+ );+ },++ // `detail === null` creates a new key; otherwise edits in place.+ openEditor(detail) {+ const keyInput = el("input", {+ type: "text", class: "search", style: "width: 100%; box-sizing: border-box",+ value: detail ? detail.key : this.prefix, spellcheck: "false",+ readonly: !!detail,+ });+ const valueInput = el("textarea", { class: "kv-value", spellcheck: "false" });+ valueInput.value = detail ? detail.value : "";+ const error = el("div", {});+ const save = async () => {+ const key = keyInput.value.trim();+ if (!key) return;+ if (detail && detail.lease !== 0 &&+ !window.confirm(`${key}\n\nThis key is lease-backed; writing it detaches it from its lease, so it will no longer expire with its owner. Continue?`)) return;+ if (!this.confirmWrite("Write", key)) return;+ try {+ await fetchJSON("api/etcd/key", {+ method: "PUT",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ key, value: valueInput.value }),+ });+ this.reload();+ this.openKey(key);+ } catch (e) {+ error.replaceChildren(el("div", { class: "error-box" }, String(e)));+ }+ };+ this.ui.detail.replaceChildren(+ el("div", { class: "panel" },+ el("h2", {}, detail ? `Edit ${detail.key}` : "New key"),+ el("div", { style: "padding: 10px 14px", class: "mono" },+ detail ? null : el("div", { style: "margin-bottom: 8px" }, keyInput),+ valueInput),+ error,+ el("div", { class: "row" },+ el("button", { onclick: save }, "Save"),+ el("button", { class: "small", onclick: () => detail ? this.renderDetail(detail) : this.ui.detail.replaceChildren() }, "Cancel")))+ );+ },++ async deleteKey(key) {+ if (!this.confirmWrite("Delete", key)) return;+ try {+ await fetchJSON(`api/etcd/key?key=${encodeURIComponent(key)}`, { method: "DELETE" });+ this.selectedKey = null;+ this.ui.detail.replaceChildren();+ this.reload();+ } catch (e) {+ this.ui.detail.replaceChildren(el("div", { class: "panel" }, el("div", { class: "error-box" }, String(e))));+ }+ },+ };++ // ---------- section: personhog topology ----------+ // Protocol-aware view over the personhog coordination prefix: pods,+ // routers, assignments, and in-flight handoffs, with server-derived+ // issues (stuck handoffs, dead owners, missing acks) computed by the+ // same predicates the coordinator runs.+ const personhogSection = {+ id: "personhog",+ title: "Personhog topology",+ description: "Live view of personhog's etcd coordination state: coordinator, pods, routers, partition ownership, and in-flight handoffs, with derived issues. Refreshes every 5 seconds.",+ timers: [],+ refreshSeq: 0,+ unmount() {+ this.timers.forEach(clearInterval);+ this.timers = [];+ },+ mount(root) {+ this.ui = {+ summary: el("div", { class: "row", style: "padding: 0 0 10px" }),+ issuesBody: el("div", {}, el("div", { class: "empty" }, "Loading…")),+ partitionsBody: el("div", {}, el("div", { class: "empty" }, "Loading…")),+ podsBody: el("div", {}, el("div", { class: "empty" }, "Loading…")),+ routersBody: el("div", {}, el("div", { class: "empty" }, "Loading…")),+ };+ this.partitionsView = listView({+ placeholder: "Filter by partition, owner, or phase…",+ pageSize: 100,+ matches: (p, q) =>+ String(p.partition).includes(q) ||+ (p.owner || "").toLowerCase().includes(q) ||+ (p.handoff ? p.handoff.phase.toLowerCase().includes(q) : false),+ renderTable: (rows) => this.renderPartitionsTable(rows),+ emptyText: "No partitions.",+ });+ root.append(+ this.ui.summary,+ el("div", { class: "panel" }, el("h2", {}, "Issues"), this.ui.issuesBody),+ el("div", { class: "panel" }, el("h2", {}, "Partitions"), this.ui.partitionsBody),+ el("div", { class: "panel" }, el("h2", {}, "Pods"), this.ui.podsBody),+ el("div", { class: "panel" }, el("h2", {}, "Routers"), this.ui.routersBody)+ );+ this.refresh();+ this.timers.push(setInterval(() => this.refresh(), 5000));+ },++ async refresh() {+ const seq = ++this.refreshSeq;+ let data;+ try {+ data = await fetchJSON("api/personhog/topology");+ } catch (e) {+ if (seq !== this.refreshSeq) return;+ this.ui.summary.replaceChildren(el("div", { class: "error-box", style: "flex: 1 1 100%" }, String(e)));+ return;+ }+ if (seq !== this.refreshSeq) return;+ this.render(data);+ },++ render(data) {+ const readyPods = data.pods.filter((p) => p.status === "Ready").length;+ const errors = data.issues.filter((issue) => issue.severity === "error").length;+ const warnings = data.issues.filter((issue) => issue.severity === "warning").length;+ // replaceChildren stringifies nulls instead of skipping them like+ // el() does, so absent pills must be filtered out.+ this.ui.summary.replaceChildren(...[+ data.leader+ ? el("span", { class: "pill good", title: `lease ${data.leader.lease_id}${data.leader.lease_ttl_secs !== null ? ` · ttl ${data.leader.lease_ttl_secs}s` : ""}` }, `coordinator ${data.leader.holder}`)+ : el("span", { class: "pill bad" }, "no coordinator"),+ el("span", { class: "pill muted" },+ data.total_partitions === null ? "total_partitions missing" : `${fmtInt(data.total_partitions)} partitions`),+ el("span", { class: `pill ${readyPods === data.pods.length && readyPods > 0 ? "good" : "warn"}` },+ `${fmtInt(readyPods)}/${fmtInt(data.pods.length)} pods ready`),+ el("span", { class: "pill muted" }, `${fmtInt(data.routers.length)} router${data.routers.length === 1 ? "" : "s"}`),+ errors ? el("span", { class: "pill bad" }, `${fmtInt(errors)} error${errors === 1 ? "" : "s"}`) : null,+ warnings ? el("span", { class: "pill warn" }, `${fmtInt(warnings)} warning${warnings === 1 ? "" : "s"}`) : null,+ el("span", { class: "muted mono", style: "margin-left: auto" },+ `rev ${fmtInt(data.revision)} · as of ${new Date(data.fetched_at).toLocaleTimeString()}`),+ ].filter(Boolean));++ const pillFor = { error: "bad", warning: "warn", info: "muted" };+ this.ui.issuesBody.replaceChildren(+ data.issues.length === 0+ ? el("div", { class: "empty" }, "No issues detected.")+ : el("div", { style: "padding: 6px 0" }, data.issues.map((issue) =>+ el("div", { class: "row", style: "padding: 4px 14px" },+ el("span", { class: `pill ${pillFor[issue.severity] || "muted"}` }, issue.severity),+ el("span", {}, issue.summary))))+ );++ this.partitionsView.setRows(data.partitions);+ this.ui.partitionsBody.replaceChildren(this.partitionsView.body);+ this.ui.podsBody.replaceChildren(this.renderPodsTable(data.pods));+ this.ui.routersBody.replaceChildren(this.renderRoutersTable(data.routers));+ },++ renderPartitionsTable(rows) {+ return el("table", {},+ el("thead", {}, el("tr", {},+ el("th", {}, "partition"), el("th", {}, "owner"), el("th", {}, "address"),+ el("th", {}, "handoff"), el("th", {}, "waiting on"))),+ el("tbody", {}, rows.map((p) => {+ const h = p.handoff;+ const phasePill = h+ ? el("span", {+ class: `pill ${h.past_deadline ? "bad" : h.phase === "Complete" ? "good" : "accent"}`,+ title: `${h.old_owner ? `${h.old_owner} → ` : ""}${h.new_owner} · ${h.handoff_id}`,+ }, `${h.phase}${h.phase_age_secs !== null ? ` ${h.phase_age_secs}s` : ""}${h.past_deadline ? " ⏰" : ""}`)+ : el("span", { class: "muted" }, "–");+ return el("tr", {},+ el("td", { class: "mono" }, String(p.partition)),+ el("td", { class: "mono" }, p.owner+ ? el("span", {}, p.owner, " ", p.owner_registered === false ? el("span", { class: "pill bad" }, "gone") : null)+ : el("span", { class: "pill warn" }, "unassigned")),+ el("td", { class: "muted mono" }, p.advertise_address || "–"),+ el("td", {}, phasePill),+ el("td", { class: "muted" }, h && h.waiting_on ? h.waiting_on : "–"));+ }))+ );+ },++ renderPodsTable(pods) {+ if (!pods.length) return el("div", { class: "empty" }, "No pods registered.");+ return el("table", {},+ el("thead", {}, el("tr", {},+ el("th", {}, "pod"), el("th", {}, "status"), el("th", {}, "address"),+ el("th", {}, "lease ttl"), el("th", {}, "heartbeat"), el("th", {}, "partitions"))),+ el("tbody", {}, pods.map((pod) =>+ el("tr", {},+ el("td", { class: "mono" }, pod.pod_name),+ el("td", {}, el("span", { class: `pill ${pod.status === "Ready" ? "good" : "warn"}` }, pod.status)),+ el("td", { class: "muted mono" }, pod.advertise_address || "–"),+ el("td", { class: "mono" }, pod.lease_ttl_secs === null ? "–" : `${pod.lease_ttl_secs}s`),+ el("td", { class: "muted mono" }, pod.last_heartbeat ? fmtAgo(pod.last_heartbeat * 1000) : "–"),+ el("td", { class: "mono", title: pod.partitions.join(", ") },+ `${fmtInt(pod.partitions.length)}`))+ ))+ );+ },++ renderRoutersTable(routers) {+ if (!routers.length) return el("div", { class: "empty" }, "No routers registered.");+ return el("table", {},+ el("thead", {}, el("tr", {},+ el("th", {}, "router"), el("th", {}, "lease ttl"), el("th", {}, "heartbeat"))),+ el("tbody", {}, routers.map((router) =>+ el("tr", {},+ el("td", { class: "mono" }, router.router_name),+ el("td", { class: "mono" }, router.lease_ttl_secs === null ? "–" : `${router.lease_ttl_secs}s`),+ el("td", { class: "muted mono" }, router.last_heartbeat ? fmtAgo(router.last_heartbeat * 1000) : "–"))+ ))+ );+ },+ };+// ---------- boot ----------- SECTIONS.push(lagSection, debugSection);+ SECTIONS.push(lagSection, debugSection, personhogSection, etcdSection);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));