: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(personhog): steer placement away from old-generation pods during rollouts (#75770)
Zach Brown99108b143150
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 0b8d48ecbf91..ada5b3065537 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -8527,6 +8527,8 @@ dependencies = ["envconfig","foyer","health",+ "k8s-awareness",+ "kube","lifecycle","metrics","personhog-common",diff --git a/rust/common/k8s-awareness/src/watcher.rs b/rust/common/k8s-awareness/src/watcher.rsindex 31772823eceb..5c954d93214d 100644--- a/rust/common/k8s-awareness/src/watcher.rs+++ b/rust/common/k8s-awareness/src/watcher.rs@@ -66,6 +66,19 @@ impl K8sAwareness {Ok(pod_info)}+ /// Start watching a controller known by reference — the entry point+ /// for consumers that learn controllers from member registrations+ /// rather than pod-name discovery (the coordinator sees each pod's+ /// self-reported controller ref and has no pod of its own to+ /// discover from). Idempotent: an already-watched controller is a+ /// no-op.+ pub async fn watch_controller(+ &self,+ controller: &ControllerRef,+ ) -> Result<(), K8sAwarenessError> {+ self.ensure_watching(controller).await+ }+/// Classify why a member is departing based on its controller's current intent.////// Returns `DepartureReason::Unknown` if the controller isn't being watcheddiff --git a/rust/personhog-coordination/src/coordinator.rs b/rust/personhog-coordination/src/coordinator.rsindex 6de94dfaf1ed..8ae223a53668 100644--- a/rust/personhog-coordination/src/coordinator.rs+++ b/rust/personhog-coordination/src/coordinator.rs@@ -1322,6 +1322,22 @@ async fn filter_pods_for_k8s(continue;}+ // Lazily start the controller watch from the registration's own+ // ref — the coordinator has no pod of its own to discover from,+ // and without a watch `classify_departure` has no intent to+ // consult. Idempotent, so calling per evaluation is cheap; the+ // first evaluation after a watch starts may still classify+ // Unknown, which safely leaves the pod active until intent+ // arrives.+ if let Err(e) = k8s.watch_controller(controller).await {+ tracing::warn!(+ controller = %controller,+ error = %e,+ "failed to start controller watch; treating pod as active"+ );+ continue;+ }+let reason = k8s.classify_departure(controller, generation).await;match (&controller.kind, pod.status, reason) {diff --git a/rust/personhog-coordination/tests/k3s_integration.rs b/rust/personhog-coordination/tests/k3s_integration.rsindex 3f9118f16318..3761250ffe4c 100644--- a/rust/personhog-coordination/tests/k3s_integration.rs+++ b/rust/personhog-coordination/tests/k3s_integration.rs@@ -473,14 +473,27 @@ async fn deployment_rollout_reassigns_partitions() {tokio::time::sleep(Duration::from_secs(3)).await;- // Set up etcd store and coordination+ // Set up etcd store and coordination. The coordinator gets its own+ // fresh K8sAwareness — NOT the instance the test scaffolding already+ // primed with discover_controller above — so this test exercises the+ // production bootstrap path: the coordinator must start controller+ // watches itself, lazily, from the refs pods carry in their+ // registrations. Sharing the scaffolding instance would mask a+ // coordinator that never starts watches (classify would keep+ // answering from the scaffolding's watch, which is exactly how this+ // gap previously escaped the suite).let store = test_store("deploy-rollout-k3s").await;store.set_total_partitions(NUM_PARTITIONS).await.unwrap();+ let coordinator_awareness = Arc::new(K8sAwareness::new(+ k8s_client.clone(),+ NAMESPACE.to_string(),+ k8s_cancel.clone(),+ ));let cancel = CancellationToken::new();let _coord = start_coordinator_k8s(Arc::clone(&store),- Some(Arc::clone(&awareness)),+ Some(coordinator_awareness),cancel.clone(),);let _router = start_router(Arc::clone(&store), "router-0", cancel.clone());diff --git a/rust/personhog-leader/Cargo.toml b/rust/personhog-leader/Cargo.tomlindex 08175b613d95..47347c071a59 100644--- a/rust/personhog-leader/Cargo.toml+++ b/rust/personhog-leader/Cargo.toml@@ -13,6 +13,8 @@ common-kafka = { path = "../common/kafka" }common-ingestion-warnings = { path = "../common/ingestion_warnings" }common-metrics = { path = "../common/metrics" }common-alloc = { path = "../common/alloc" }+k8s-awareness = { path = "../common/k8s-awareness" }+kube = { version = "0.98", features = ["client"] }lifecycle = { path = "../common/lifecycle" }async-trait = { workspace = true }@@ -28,6 +30,7 @@ rdkafka = { workspace = true }serde_json = { workspace = true }sqlx = { workspace = true }tokio = { workspace = true }+tokio-util = { workspace = true }tonic = { workspace = true }tracing = { workspace = true }tracing-subscriber = { workspace = true }diff --git a/rust/personhog-leader/src/config.rs b/rust/personhog-leader/src/config.rsindex 6b4d37a44e0b..25f71766ff95 100644--- a/rust/personhog-leader/src/config.rs+++ b/rust/personhog-leader/src/config.rs@@ -1,3 +1,4 @@+use std::fs;use std::net::SocketAddr;use std::time::Duration;@@ -229,6 +230,20 @@ pub struct Config {#[envconfig(default = "")]pub pod_ip: String,+ /// Enable K8s awareness: at startup the leader discovers its owning+ /// controller (Deployment) and generation (pod-template-hash) and+ /// registers them, so the coordinator can steer placement away from+ /// old-generation pods during rollouts instead of handing partitions+ /// to pods that are about to be replaced. Requires RBAC to read+ /// pods, replicasets, and deployments in the pod's namespace.+ #[envconfig(default = "false")]+ pub k8s_awareness_enabled: bool,++ /// Kubernetes namespace for controller discovery. If empty,+ /// auto-reads from the service account mount.+ #[envconfig(default = "")]+ pub k8s_namespace: String,+#[envconfig(default = "30")]pub lease_ttl: i64,@@ -272,6 +287,18 @@ impl Config {pub fn heartbeat_interval(&self) -> Duration {Duration::from_secs(self.heartbeat_interval_secs)}++ /// Resolve the K8s namespace from config or the service account mount.+ pub fn resolve_k8s_namespace(&self) -> Result<String, String> {+ if !self.k8s_namespace.is_empty() {+ return Ok(self.k8s_namespace.clone());+ }+ fs::read_to_string("/var/run/secrets/kubernetes.io/serviceaccount/namespace")+ .map(|s| s.trim().to_string())+ .map_err(|e| {+ format!("k8s_namespace not set and failed to read from service account: {e}")+ })+ }}/// Derive the `host:port` this leader should advertise for routing.diff --git a/rust/personhog-leader/src/main.rs b/rust/personhog-leader/src/main.rsindex fa906d342335..38e21bcae352 100644--- a/rust/personhog-leader/src/main.rs+++ b/rust/personhog-leader/src/main.rs@@ -7,12 +7,16 @@ use common_kafka::kafka_producer::create_kafka_producer;use common_metrics::setup_metrics_routes;use dashmap::DashMap;use envconfig::Envconfig;+use k8s_awareness::{K8sAwareness, PodInfo};+use kube::Client;use lifecycle::{ComponentOptions, Manager};use personhog_common::async_gzip::{AsyncGzipConfig, AsyncGzipLayer};use personhog_common::grpc::{tracked_tcp_incoming, GrpcLoadShedLayer, GrpcMetricsLayer};use personhog_coordination::pod::{PodConfig, PodHandle};use personhog_coordination::store::PersonhogStore;use personhog_proto::personhog::leader::v1::person_hog_leader_server::PersonHogLeaderServer;+use tokio::time::timeout;+use tokio_util::sync::CancellationToken;use tonic::codec::CompressionEncoding;use tonic::transport::Server;use tracing::level_filters::LevelFilter;@@ -253,8 +257,47 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {.expect("Invalid advertise address configuration");tracing::info!(%advertise_address, "advertising gRPC address for routing");+ // Discover this pod's owning controller and generation so the+ // coordinator can steer placement away from old-generation pods+ // during rollouts. Fail-open, and bounded: this runs before the pod+ // handle and gRPC server exist, so an unresponsive API server must+ // cost a few seconds of startup at worst — never availability.+ let (controller, generation, k8s_awareness) = if config.k8s_awareness_enabled {+ let discovery = discover_own_controller(&config, coordination_handle.shutdown_token());+ match timeout(K8S_DISCOVERY_TIMEOUT, discovery).await {+ Ok(Ok((awareness, info))) => {+ tracing::info!(+ controller = %info.controller,+ generation = %info.generation,+ "K8s awareness enabled; controller discovered"+ );+ (Some(info.controller), info.generation, Some(awareness))+ }+ Ok(Err(e)) => {+ tracing::warn!(+ error = %e,+ "K8s awareness enabled but controller discovery failed; \+ registering without rollout awareness"+ );+ (None, String::new(), None)+ }+ Err(_) => {+ tracing::warn!(+ timeout = ?K8S_DISCOVERY_TIMEOUT,+ "K8s awareness enabled but controller discovery timed out; \+ registering without rollout awareness"+ );+ (None, String::new(), None)+ }+ }+ } else {+ (None, String::new(), None)+ };+let pod_config = PodConfig {pod_name: config.pod_name.clone(),+ generation,+ controller,lease_ttl: config.lease_ttl,heartbeat_interval: config.heartbeat_interval(),advertise_address: Some(advertise_address),@@ -277,7 +320,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {});}- let pod = PodHandle::new(store, pod_config, Arc::new(handler), None);+ let pod = PodHandle::new(store, pod_config, Arc::new(handler), k8s_awareness);tokio::spawn(async move {let _guard = coordination_handle.process_scope();@@ -451,3 +494,27 @@ async fn run_dirty_index_prune_loop(}}}++/// How long startup may spend on controller discovery before falling+/// open. Generous against a healthy API server (three small reads);+/// tight against an unresponsive one, which must not delay serving.+const K8S_DISCOVERY_TIMEOUT: Duration = Duration::from_secs(5);++/// Build a K8s awareness client and discover this pod's owning controller+/// and generation. The awareness handle is returned alongside so the pod+/// can also classify its own departure at drain time.+async fn discover_own_controller(+ config: &Config,+ cancel: CancellationToken,+) -> Result<(Arc<K8sAwareness>, PodInfo), String> {+ let namespace = config.resolve_k8s_namespace()?;+ let client = Client::try_default()+ .await+ .map_err(|e| format!("failed to create K8s client: {e}"))?;+ let awareness = Arc::new(K8sAwareness::new(client, namespace, cancel));+ let info = awareness+ .discover_controller(&config.pod_name)+ .await+ .map_err(|e| format!("controller discovery failed: {e}"))?;+ Ok((awareness, info))+}