From 697998f39a2647a8b9e811a8a1f6862db8d895fa Mon Sep 17 00:00:00 2001 From: Erfan Yousefi Date: Wed, 24 Jun 2026 13:24:57 +0200 Subject: [PATCH] fix(state): keep list visible during relist; drop blank-window on reconnect MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On every watcher reconnect, Event::Init emitted StateDelta::Reset which wiped the entire kind from the store, so the table blanked for ~2s while 10k pods re-populated from the fresh list. Replace the wipe with reflector-style generation reconciliation: - per-(context, kind) generation counter in StateStore - RelistStart (Event::Init) bumps the generation; the existing set stays visible - each apply stamps the current generation (refreshing still-present objects) - RelistEnd (Event::InitDone) sweeps only entities left at an older generation (objects that disappeared while disconnected and were absent from the relist) The previous list now stays fully visible throughout a relist and reconciles atomically at the end — no blank window. Also adds a perf micro-benchmark (perf_to_value_vs_dynamic_parse) that measured per-event to_value at ~5% of initial sync, deprioritizing the metadata-watch rewrite (ROADMAP 1.2). Validation: fmt, check, test (72 passed / 4 ignored), release build all green. Bench: no regression (sync 2.03s, RSS 64.6MB). Co-Authored-By: Claude Opus 4.8 (1M context) --- ROADMAP.md | 22 +++++-- src/cluster/kube_provider.rs | 123 ++++++++++++++++++++++++++++++++++- src/model.rs | 16 ++++- src/state/store.rs | 116 ++++++++++++++++++++++++++++----- 4 files changed, 250 insertions(+), 27 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index bb2db1f..c8524b5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -87,10 +87,14 @@ Root problem: full object JSON kept for every entity. `docs/design/phase-1.1-lean-entity-model.md`. **Measured (kwok 10k pods, 1 ctx): RSS 482MB -> 85.5MB (5.6x); pulse 7.62ms -> 0.36ms (21x).** 71 tests pass. Residual per-event `to_value` remains (initial sync ~unchanged) -> Phase 1.2. -- [ ] **1.2 Metadata/table-mode watches** — list watchers deserialize full typed objects - (`Api` etc., `spawn_watch_for_kind` kube_provider.rs:928). Move list kinds to - `PartialObjectMetadata` (metadata-only) or server-side Table where viable; hydrate full - objects only on describe. Cuts deserialize + transfer + heap. +- [-] **1.2 Metadata/table-mode watches** — DEPRIORITIZED after measurement (2026-06-24). + Micro-bench (`perf_to_value_vs_dynamic_parse`, kube_provider.rs) on a 2.6KB pod: + `to_value` 5.4µs/obj, typed parse 5.0µs, dynamic parse 7.9µs. Current ingest serde + (parse+to_value) ≈ 104ms/10k; dynamic ≈ 79ms/10k → net **~25ms saved over 10k**, and dynamic + parse is *slower* than typed. Against a 2.1s initial sync, serde is ~5%. Sync is dominated by the + initial LIST (network/pagination) + channel delivery + store.apply, not serialization. Not worth + the watch-layer rewrite. Revisit only if a real cluster with fat objects (10-15KB) shifts the + ratio, or fold a watcher list `page_size` bump into 3.x. - [ ] **1.3 Warm-context memory bound** — entities for warm contexts (warm_contexts TTL, kube_provider.rs:321) can dominate RSS at 20 ctx. Cap/evict entity sets for non-active contexts; verify store shrinks when watchers stop (today `Reset` only fires on relist). @@ -116,9 +120,13 @@ Root problem: full object JSON kept for every entity. --- ## Phase 3 — Stability under churn/scale -- [ ] **3.1 Reset/relist without blank window** — `Event::Init`→`StateDelta::Reset` wipes a - whole kind on every reconnect (kube_provider.rs:769, store.rs:138) then repopulates, - blanking the table during a 10k-pod relist. Mark stale + atomic replace (generation id). +- [x] **3.1 Reset/relist without blank window** — DONE. Replaced `StateDelta::Reset` (wiped the + whole kind on every reconnect) with `RelistStart`/`RelistEnd` + a per-(ctx,kind) generation in the + store: `Event::Init` bumps the generation (old set stays visible), each apply refreshes objects to + the new generation, `Event::InitDone` sweeps only entities left at an older generation (truly gone + while disconnected). No blank window during a 10k-pod relist. Unit test + `relist_keeps_data_visible_and_sweeps_only_gone_objects`; bench confirms no perf/RSS regression + (sync 2.03s, RSS 64.6MB). 72 tests pass. - [ ] **3.2 Delta backpressure/coalescing** — single shared `mpsc` (cap 2048) for all watchers (lib.rs:62). Define policy under simultaneous initial-lists: per-context lanes and/or coalescing so a big relist doesn't delay input/other contexts. diff --git a/src/cluster/kube_provider.rs b/src/cluster/kube_provider.rs index 7165ea1..00aca45 100644 --- a/src/cluster/kube_provider.rs +++ b/src/cluster/kube_provider.rs @@ -787,7 +787,8 @@ where tx.send(StateDelta::Remove(key)).await.map_err(|_| ())?; } Event::Init => { - tx.send(StateDelta::Reset { + // (Re)list starting: mark the current set stale but keep showing it (no blank window). + tx.send(StateDelta::RelistStart { context: context.to_string(), kind, }) @@ -800,7 +801,13 @@ where } } Event::InitDone => { - // Marker that initial list state has been fully emitted. + // Initial list fully emitted: sweep entities not refreshed during this relist. + tx.send(StateDelta::RelistEnd { + context: context.to_string(), + kind, + }) + .await + .map_err(|_| ())?; } } Ok(()) @@ -1039,6 +1046,118 @@ mod tests { }; use tokio::sync::Mutex; + // Representative non-trivial pod (labels, annotations, 2 containers w/ env+resources, status). + fn representative_pod_json() -> serde_json::Value { + json!({ + "apiVersion": "v1", "kind": "Pod", + "metadata": { + "name": "api-7d9f8c6b5d-abcde", "namespace": "team-payments", + "uid": "f1e2d3c4-b5a6-7890-1234-567890abcdef", + "resourceVersion": "1048576", "creationTimestamp": "2026-06-20T10:00:00Z", + "labels": { + "app": "api", "app.kubernetes.io/name": "api", "app.kubernetes.io/instance": "api-prod", + "app.kubernetes.io/version": "1.42.0", "pod-template-hash": "7d9f8c6b5d", + "team": "payments", "tier": "backend", "env": "prod" + }, + "annotations": { + "kubectl.kubernetes.io/restartedAt": "2026-06-20T10:00:00Z", + "prometheus.io/scrape": "true", "prometheus.io/port": "9090", + "checksum/config": "9f8e7d6c5b4a39281706f5e4d3c2b1a0998877665544332211", + "sidecar.istio.io/status": "{\"version\":\"1.20\",\"initContainers\":[\"istio-init\"],\"containers\":[\"istio-proxy\"]}" + }, + "ownerReferences": [ { "apiVersion": "apps/v1", "kind": "ReplicaSet", "name": "api-7d9f8c6b5d", "uid": "aabbccdd", "controller": true } ] + }, + "spec": { + "nodeName": "ip-10-0-12-34.eu-north-1.compute.internal", + "serviceAccountName": "api", + "containers": [ + { + "name": "api", "image": "registry.example.com/payments/api:1.42.0", + "ports": [ { "containerPort": 8080, "name": "http" }, { "containerPort": 9090, "name": "metrics" } ], + "env": [ + { "name": "LOG_LEVEL", "value": "info" }, { "name": "DB_HOST", "value": "aurora.internal" }, + { "name": "DB_PORT", "value": "5432" }, { "name": "POD_IP", "valueFrom": { "fieldRef": { "fieldPath": "status.podIP" } } } + ], + "resources": { "requests": { "cpu": "250m", "memory": "256Mi" }, "limits": { "cpu": "1", "memory": "512Mi" } }, + "volumeMounts": [ { "name": "config", "mountPath": "/etc/api" }, { "name": "kube-api-access", "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount", "readOnly": true } ] + }, + { + "name": "istio-proxy", "image": "docker.io/istio/proxyv2:1.20", + "resources": { "requests": { "cpu": "100m", "memory": "128Mi" }, "limits": { "cpu": "2", "memory": "1Gi" } }, + "env": [ { "name": "PILOT_CERT_PROVIDER", "value": "istiod" } ] + } + ] + }, + "status": { + "phase": "Running", "podIP": "10.0.12.200", "hostIP": "10.0.12.34", "startTime": "2026-06-20T10:00:01Z", + "conditions": [ + { "type": "Initialized", "status": "True", "lastTransitionTime": "2026-06-20T10:00:02Z" }, + { "type": "Ready", "status": "True", "lastTransitionTime": "2026-06-20T10:00:10Z" }, + { "type": "ContainersReady", "status": "True", "lastTransitionTime": "2026-06-20T10:00:10Z" }, + { "type": "PodScheduled", "status": "True", "lastTransitionTime": "2026-06-20T10:00:00Z" } + ], + "containerStatuses": [ + { "name": "api", "ready": true, "restartCount": 0, "image": "registry.example.com/payments/api:1.42.0", "started": true, "state": { "running": { "startedAt": "2026-06-20T10:00:05Z" } } }, + { "name": "istio-proxy", "ready": true, "restartCount": 1, "image": "docker.io/istio/proxyv2:1.20", "started": true, "state": { "running": { "startedAt": "2026-06-20T10:00:06Z" } } } + ] + } + }) + } + + #[test] + #[ignore = "performance benchmark"] + fn perf_to_value_vs_dynamic_parse() { + use k8s_openapi::api::core::v1::Pod; + use kube::core::DynamicObject; + + let wire = serde_json::to_string(&representative_pod_json()).expect("serialize"); + let iters = 50_000u32; + + // Current ingest path: parse wire -> typed Pod, then serde_json::to_value(pod). + let pod: Pod = serde_json::from_str(&wire).expect("pod parse"); + let start = Instant::now(); + let mut acc = 0usize; + for _ in 0..iters { + let v = serde_json::to_value(&pod).expect("to_value"); + acc = acc.wrapping_add(v.as_object().map(|o| o.len()).unwrap_or(0)); + } + let to_value_per = start.elapsed() / iters; + + // Parse cost comparison: typed Pod vs DynamicObject (proposed ingest). + let start = Instant::now(); + for _ in 0..iters { + let p: Pod = serde_json::from_str(&wire).expect("pod parse"); + acc = acc.wrapping_add(p.metadata.name.is_some() as usize); + } + let pod_parse_per = start.elapsed() / iters; + + let start = Instant::now(); + for _ in 0..iters { + let d: DynamicObject = serde_json::from_str(&wire).expect("dynamic parse"); + acc = acc.wrapping_add(d.metadata.name.is_some() as usize); + } + let dyn_parse_per = start.elapsed() / iters; + + std::hint::black_box(acc); + eprintln!( + "[perf] wire={}B to_value/obj={:?} pod_parse/obj={:?} dyn_parse/obj={:?}", + wire.len(), + to_value_per, + pod_parse_per, + dyn_parse_per + ); + eprintln!( + "[perf] current ingest serde ≈ pod_parse+to_value = {:?}/obj -> 10k = {:?}", + pod_parse_per + to_value_per, + (pod_parse_per + to_value_per) * 10_000 + ); + eprintln!( + "[perf] proposed (dynamic) serde ≈ dyn_parse = {:?}/obj -> 10k = {:?}", + dyn_parse_per, + dyn_parse_per * 10_000 + ); + } + #[test] fn select_warm_contexts_respects_limit_and_ttl() { let now = Instant::now(); diff --git a/src/model.rs b/src/model.rs index e8570a4..559ca1c 100644 --- a/src/model.rs +++ b/src/model.rs @@ -221,8 +221,20 @@ pub struct NodeCapacity { pub enum StateDelta { Upsert(ResourceEntity), Remove(ResourceKey), - Reset { context: String, kind: ResourceKind }, - Error { context: String, message: String }, + /// A (re)list of this kind is starting — mark the existing set stale, keep showing it. + RelistStart { + context: String, + kind: ResourceKind, + }, + /// The (re)list finished — sweep entities not refreshed during it. + RelistEnd { + context: String, + kind: ResourceKind, + }, + Error { + context: String, + message: String, + }, } #[derive(Debug, Clone)] diff --git a/src/state/store.rs b/src/state/store.rs index 3f630af..44502de 100644 --- a/src/state/store.rs +++ b/src/state/store.rs @@ -2,11 +2,22 @@ use std::collections::{HashMap, HashSet}; use crate::model::{ResourceEntity, ResourceKey, ResourceKind, StateDelta}; +/// Stored entity plus the relist generation it was last seen in. On reconnect we bump the +/// generation, refresh still-present objects to the new generation as their applies arrive, and +/// sweep anything left at an older generation — so the previous list stays visible the whole time +/// instead of blanking. +#[derive(Debug)] +struct EntitySlot { + entity: ResourceEntity, + generation: u64, +} + #[derive(Debug, Default)] pub struct StateStore { - entities: HashMap, + entities: HashMap, context_kind_index: HashMap<(String, ResourceKind), HashSet>, namespaces_by_context: HashMap>, + current_generation: HashMap<(String, ResourceKind), u64>, errors: HashMap, revision: u64, } @@ -16,7 +27,8 @@ impl StateStore { match delta { StateDelta::Upsert(entity) => self.upsert(entity), StateDelta::Remove(key) => self.remove(&key), - StateDelta::Reset { context, kind } => self.reset_kind(&context, kind), + StateDelta::RelistStart { context, kind } => self.relist_start(&context, kind), + StateDelta::RelistEnd { context, kind } => self.relist_end(&context, kind), StateDelta::Error { context, message } => { self.errors.insert(context, message); } @@ -36,7 +48,7 @@ impl StateStore { keys.iter() .filter_map(|key| { - let entity = self.entities.get(key)?; + let entity = &self.entities.get(key)?.entity; if let Some(target_ns) = namespace && entity.key.namespace.as_deref() != Some(target_ns) { @@ -48,7 +60,7 @@ impl StateStore { } pub fn get(&self, key: &ResourceKey) -> Option<&ResourceEntity> { - self.entities.get(key) + self.entities.get(key).map(|slot| &slot.entity) } pub fn count(&self, context: &str, kind: ResourceKind, namespace: Option<&str>) -> usize { @@ -103,14 +115,16 @@ impl StateStore { fn upsert(&mut self, entity: ResourceEntity) { let key = entity.key.clone(); + // Stamp with the active generation for this (context, kind) so a relist sweep keeps it. + let generation = self + .current_generation + .get(&(key.context.clone(), key.kind)) + .copied() + .unwrap_or(0); - if let Some(existing) = self.entities.insert(key.clone(), entity) - && let Some(index) = self - .context_kind_index - .get_mut(&(existing.key.context.clone(), existing.key.kind)) - { - index.remove(&existing.key); - } + // Re-inserting the same key into the index HashSet is a no-op, so no removal needed. + self.entities + .insert(key.clone(), EntitySlot { entity, generation }); if let Some(ns) = key.namespace.clone() { self.namespaces_by_context @@ -135,11 +149,38 @@ impl StateStore { } } - fn reset_kind(&mut self, context: &str, kind: ResourceKind) { - if let Some(keys) = self.context_kind_index.remove(&(context.to_string(), kind)) { - for key in keys { - self.entities.remove(&key); - } + /// Begin a (re)list for a kind: bump its generation. Existing entities keep their old + /// generation and stay visible until the matching `relist_end` sweeps whatever wasn't refreshed. + fn relist_start(&mut self, context: &str, kind: ResourceKind) { + *self + .current_generation + .entry((context.to_string(), kind)) + .or_insert(0) += 1; + } + + /// Finish a (re)list: drop entities still at an older generation (objects that disappeared + /// while disconnected and were absent from the fresh list). + fn relist_end(&mut self, context: &str, kind: ResourceKind) { + let generation = self + .current_generation + .get(&(context.to_string(), kind)) + .copied() + .unwrap_or(0); + let Some(keys) = self.context_kind_index.get(&(context.to_string(), kind)) else { + return; + }; + let stale: Vec = keys + .iter() + .filter(|key| { + self.entities + .get(*key) + .map(|slot| slot.generation < generation) + .unwrap_or(false) + }) + .cloned() + .collect(); + for key in stale { + self.remove(&key); } } } @@ -188,4 +229,47 @@ mod tests { assert!(store.get(&key).is_none()); } + + #[test] + fn relist_keeps_data_visible_and_sweeps_only_gone_objects() { + let mut store = StateStore::default(); + // Initial list: two pods. + store.apply(StateDelta::RelistStart { + context: "dev".to_string(), + kind: ResourceKind::Pods, + }); + store.apply(StateDelta::Upsert(mk_entity("dev", Some("a"), "pod-a"))); + store.apply(StateDelta::Upsert(mk_entity("dev", Some("a"), "pod-b"))); + store.apply(StateDelta::RelistEnd { + context: "dev".to_string(), + kind: ResourceKind::Pods, + }); + assert_eq!(store.list("dev", ResourceKind::Pods, None).len(), 2); + + // Reconnect/relist: pod-a is still present, pod-b is gone, pod-c is new. + store.apply(StateDelta::RelistStart { + context: "dev".to_string(), + kind: ResourceKind::Pods, + }); + // Mid-relist the previous set must remain fully visible (no blank window). + assert_eq!(store.list("dev", ResourceKind::Pods, None).len(), 2); + store.apply(StateDelta::Upsert(mk_entity("dev", Some("a"), "pod-a"))); + store.apply(StateDelta::Upsert(mk_entity("dev", Some("a"), "pod-c"))); + // Still 3 visible until the relist ends (pod-b not yet swept). + assert_eq!(store.list("dev", ResourceKind::Pods, None).len(), 3); + store.apply(StateDelta::RelistEnd { + context: "dev".to_string(), + kind: ResourceKind::Pods, + }); + + let names: std::collections::HashSet = store + .list("dev", ResourceKind::Pods, None) + .into_iter() + .map(|e| e.key.name.clone()) + .collect(); + assert_eq!(names.len(), 2); + assert!(names.contains("pod-a")); + assert!(names.contains("pod-c")); + assert!(!names.contains("pod-b")); + } }