Skip to content

: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.

fix(k8s-awareness): add timeout to stream.next() and use try_read() in classify_departure (#61858)

mendral-app[bot]823cbff22cc6
diff --git a/rust/common/k8s-awareness/src/watcher.rs b/rust/common/k8s-awareness/src/watcher.rs
index 6296808b0968..c1097cd1cc33 100644
--- a/rust/common/k8s-awareness/src/watcher.rs
+++ b/rust/common/k8s-awareness/src/watcher.rs
@@ -1,5 +1,6 @@
use std::collections::HashMap;
use std::sync::Arc;
+use std::time::Duration;
use futures::StreamExt;
use k8s_openapi::api::apps::v1::{Deployment, ReplicaSet, StatefulSet};
@@ -14,6 +15,11 @@ use crate::detection;
use crate::discovery::{self, DiscoveryError};
use crate::types::{ClusterIntent, ControllerKind, ControllerRef, DepartureReason, PodInfo};
+/// Timeout for `stream.next()` in watcher loops. Prevents the watcher task from
+/// blocking indefinitely when the K8s API server is unreachable, which would
+/// otherwise create a deadlock path (the assigner cannot make progress).
+const STREAM_NEXT_TIMEOUT: Duration = Duration::from_secs(30);
+
#[derive(Debug, thiserror::Error)]
pub enum K8sAwarenessError {
#[error("discovery failed: {0}")]
@@ -61,20 +67,29 @@ impl K8sAwareness {
/// Classify why a member is departing based on its controller's current intent.
///
- /// Returns `DepartureReason::Unknown` if the controller isn't being watched.
+ /// Returns `DepartureReason::Unknown` if the controller isn't being watched
+ /// or if the lock is contended (avoids blocking the assigner).
pub async fn classify_departure(
&self,
controller: &ControllerRef,
generation: &str,
) -> DepartureReason {
- let controllers = self.controllers.read().await;
- match controllers.get(controller) {
- Some(intent) => detection::classify_departure(intent, generation),
- None => {
- warn!(
- controller = %controller,
- "no cluster intent available, returning Unknown"
- );
+ // Use try_read to avoid blocking if the watcher is updating controllers.
+ // If the lock is contended, return Unknown — the assigner will treat the
+ // consumer as active, which is the safe default.
+ match self.controllers.try_read() {
+ Ok(controllers) => match controllers.get(controller) {
+ Some(intent) => detection::classify_departure(intent, generation),
+ None => {
+ warn!(
+ controller = %controller,
+ "no cluster intent available, returning Unknown"
+ );
+ DepartureReason::Unknown
+ }
+ },
+ Err(_) => {
+ debug!(controller = %controller, "controllers lock contended, returning Unknown");
DepartureReason::Unknown
}
}
@@ -158,9 +173,9 @@ async fn run_deployment_watcher(
loop {
tokio::select! {
_ = cancel.cancelled() => break,
- item = stream.next() => {
+ item = tokio::time::timeout(STREAM_NEXT_TIMEOUT, stream.next()) => {
match item {
- Some(Ok(event)) => {
+ Ok(Some(Ok(event))) => {
handle_deployment_event(
client,
namespace,
@@ -170,17 +185,23 @@ async fn run_deployment_watcher(
event,
).await;
}
- Some(Err(e)) => {
+ Ok(Some(Err(e))) => {
warn!(
controller = %controller,
error = %e,
"deployment watcher error, stream will retry"
);
}
- None => {
+ Ok(None) => {
info!(controller = %controller, "deployment watcher stream ended");
break;
}
+ Err(_elapsed) => {
+ debug!(
+ controller = %controller,
+ "deployment watcher stream.next() timed out, retrying"
+ );
+ }
}
}
}
@@ -387,22 +408,28 @@ async fn run_statefulset_watcher(
loop {
tokio::select! {
_ = cancel.cancelled() => break,
- item = stream.next() => {
+ item = tokio::time::timeout(STREAM_NEXT_TIMEOUT, stream.next()) => {
match item {
- Some(Ok(event)) => {
+ Ok(Some(Ok(event))) => {
handle_statefulset_event(controller, controllers, watching, event).await;
}
- Some(Err(e)) => {
+ Ok(Some(Err(e))) => {
warn!(
controller = %controller,
error = %e,
"statefulset watcher error, stream will retry"
);
}
- None => {
+ Ok(None) => {
info!(controller = %controller, "statefulset watcher stream ended");
break;
}
+ Err(_elapsed) => {
+ debug!(
+ controller = %controller,
+ "statefulset watcher stream.next() timed out, retrying"
+ );
+ }
}
}
}