//! Pod read paths: cached and uncached sandbox pod reads, pod IP resolution, //! and remembering the node a resolved pod landed on. use super::*; use crate::controllers::substrate::PooledExecutionClaim; use crate::controllers::substrate::kubernetes::store::ConditionalPodMetadataWrite; use crate::controllers::substrate::kubernetes::wait_ready::PodProxyWaitTarget; const SUCCEEDED_POD_SUSPEND_PUBLICATION_GRACE: Duration = Duration::from_secs(180); #[derive(Debug)] pub(in crate::controllers::substrate::kubernetes) enum PodGet { Observed(Option>), DeadlineElapsed, } pub(super) enum MissingPodResolution { Retired, Reresolve, } pub(super) enum NoReachableRuntimeFence { Holds, Reresolve, Inactive, } /// How [`KubernetesSubstrate::lookup_cached_pod`] decides whether a cached /// [`SandboxPodView`] is authoritative without an apiserver `GET`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum CacheTrustPolicy { /// Post-watch readiness fallback polling (`poll_until_pod_ip_assigned`): /// terminal entries (`Succeeded`, `Failed`) short-circuit immediately, and /// settled non-terminal entries (`status.podIP` published or unbound /// `Pending`+`Unschedulable`) short-circuit while the reflector watch is /// healthy. After the per-pod watch ends or errors, an unsettled `Pending` /// entry in `pod_store` falls through to an uncached `GET` once /// `reflector_wait` elapses rather than suppressing fallback polling. SettledOnly, /// Resolution, initial readiness check, and status reads: terminal entries /// (`Succeeded`, `Failed`) are accepted even across a watch fault because /// `resolve_pod_instance_inner` re-verifies terminal phases with an /// uncached `GET` before retiring an execution; non-terminal cached pods /// (including `Running`+IP and `Pending`) are trusted only while the /// reflector watch is healthy so a degraded watch falls through to an /// uncached `GET`. SettledOrHealthyWatch, /// Warm-pool claim adoption (`read_pooled_claim_pod`): cached pods are /// trusted only while the reflector watch is healthy, because claim /// adoption hands a cached `Running`+IP pod directly to a caller without a /// follow-up uncached `GET` and must not adopt a pod that died during a /// watch disconnect. HealthyWatchOnly, /// Post-conflict unfenced teardown retry (`FenceReadFreshness::MustBeAuthoritative`): /// bypasses `pod_store` completely so a retry after a `409 Conflict` delete /// precondition failure cannot re-read the stale pre-conflict `resourceVersion` /// from cache. BypassCache, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum UnaddressedLivePodPolicy { /// Readiness, status, and wake callers treat a live pod without an IP yet /// as `Ok(None)` so readiness waiting can proceed. ReturnNone, /// Unfenced destructive teardown (`confirmed_unfenced_runtime`) returns a /// `(uid, resourceVersion)`-fenced `NoReachableRuntime` delete target for /// any live pod without a runtime IP yet (unbound or bound pre-CNI), so /// Kubernetes rejects the delete with `409 Conflict` if the pod acquires a /// runtime IP concurrently and Pass 2 re-resolves and stops the VM. FenceUnfencedTeardown, } #[derive(Debug, Clone)] pub(in crate::controllers::substrate::kubernetes) enum PooledClaimPodObservation { /// Authoritative cached or uncached view of the claimed pod (`None` when an /// uncached apiserver `GET` confirmed `404`). Observed(Option>), /// A healthy reflector still holds a pre-`Running` snapshot of the claimed /// pod's UID after `reflector_wait`; the caller preserves the warm slot /// rather than retiring it or issuing an uncached `GET`. ReflectorLagging, } fn pooled_claim_pod_reflector_lagging(claim: &PooledExecutionClaim, pod: &SandboxPodView) -> bool { let Some(expected_uid) = claim.pod_uid.as_ref().map(PodUid::as_str) else { return false; }; // Warm-pool slots only reach `ready` after `mark_slot_ready` observed the // pod `Running` with `claim.pod_ip` under `expected_uid`, and a `Running` // pod never transitions back to `Pending` under the same UID. Any // non-deleting, non-terminal cached snapshot of `expected_uid` that isn't // usable yet (including an earlier `Pending` + `Unschedulable` scheduling // cycle before capacity freed up) is therefore pre-`Running` reflector lag. !pod.is_deleting() && matches!(pod.phase(), None | Some("Pending")) && pod.uid() == Some(expected_uid) && pod.pod_ip().is_none_or(|ip| ip == claim.pod_ip.as_str()) && !pooled_claim_pod_is_usable(claim, Some(pod)) } fn pooled_claim_pod_cache_is_authoritative( claim: &PooledExecutionClaim, pod: &SandboxPodView, ) -> bool { let Some(expected_uid) = claim.pod_uid.as_ref().map(PodUid::as_str) else { return false; }; pod.uid() == Some(expected_uid) && !pooled_claim_pod_reflector_lagging(claim, pod) } pub(super) fn terminal_cleanup_phase_after_uncached_check( cached_phase: TerminalPodPhase, authoritative_pod: Option<&SandboxPodView>, ) -> Option { match authoritative_pod { Some(pod) => terminal_pod_phase(pod), None => Some(cached_phase), } } pub(super) fn succeeded_pod_publication_grace_remaining( pod: &SandboxPodView, now: jiff::Timestamp, ) -> Option { if terminal_pod_phase(pod) != Some(TerminalPodPhase::Succeeded) { return None; } let finished_at = pod .container_statuses() .all() .filter_map(|state| state.terminated.as_ref()?.finished_at) .max()?; let grace = jiff::SignedDuration::from_secs( i64::try_from(SUCCEEDED_POD_SUSPEND_PUBLICATION_GRACE.as_secs()).ok()?, ); let deadline = finished_at.checked_add(grace).ok()?; let remaining = deadline.duration_since(now); Some( Duration::try_from(remaining) .ok()? .min(SUCCEEDED_POD_SUSPEND_PUBLICATION_GRACE), ) } impl KubernetesSubstrate { /// The cached view of `pod_name`, shared with the store rather than /// copied: the `Arc` is a refcount bump, not a deep clone. pub fn lookup_sandbox_pod(&self, pod_name: &str) -> Option> { let key = ObjectRef::::new(pod_name).within(&self.k8s.sandbox_namespace); self.pod_store.get(&key) } /// Read a sandbox pod directly from the apiserver, bypassing the /// reflector cache. Use on paths that must verify cached terminal state /// before deleting a carrier pod. pub async fn read_sandbox_pod_uncached( &self, pod_name: &str, ) -> Result>, KubeError> { fetch_sandbox_pod_uncached(&self.k8s, pod_name).await } /// Like [`Self::read_sandbox_pod_uncached`], but in `namespace` rather than /// the configured sandbox namespace. For callers proving a pod absent from /// an execution row's recorded `pod_namespace`: reading a pod tracked in /// another namespace from the configured one would 404 and read as absent. pub async fn read_sandbox_pod_uncached_in_namespace( &self, namespace: &str, pod_name: &str, ) -> Result>, KubeError> { fetch_sandbox_pod_uncached_in(&self.k8s, namespace, pod_name).await } /// Reads a sandbox pod with cache-first, event-wait, kube-apiserver- /// fallback semantics. /// /// 1. **Authoritative cache hit** (settled pod, or `Pending` while the /// sandbox-pod reflector has completed its initial sync and its watch /// isn't failing or mid-re-list) → return cached immediately with no /// wait and no apiserver `GET`. /// 2. **Cache miss on a healthy reflector** → wait up to /// `SubstrateBudgets::reflector_wait` on the shared reflector event /// stream, aborting early if the watch faults, and return cached as soon /// as the entry becomes authoritative. /// 3. **Cache miss after the event budget** or **degraded/unready /// reflector** → fall through to a single direct `GET /pods/{name}`. /// /// A quiet watch stays healthy however long it delivers no events /// (`client_live_pods.rs`): kube's watcher reconnects on idle timeout, and /// `watch_failing` flips only on a watch error, stream end, or active /// re-list (`Init`..`InitDone`). pub async fn read_sandbox_pod( &self, pod_name: &str, ) -> Result>, KubeError> { if let Some(pod) = self .read_settled_sandbox_pod(pod_name, self.budgets.reflector_wait) .await { return Ok(Some(pod)); } timeout( self.budgets.readiness_pod_get, fetch_sandbox_pod_uncached(&self.k8s, pod_name), ) .await .map_err(|_| { tracing::warn!( pod_name, timeout_ms = self.budgets.readiness_pod_get.as_millis(), "bounded Kubernetes pod GET timed out; failing fast" ); KubeError::Service(Box::new(std::io::Error::new( std::io::ErrorKind::TimedOut, format!( "pod read timed out after {:?}", self.budgets.readiness_pod_get ), ))) })? } fn healthy_pod_watch_generation(&self) -> Option { self.pod_client_index .healthy_watch_generation(self.pod_reflector_ready.is_ready()) } fn pod_reflector_watch_healthy(&self) -> bool { self.healthy_pod_watch_generation().is_some() } /// Look up a cached pod under `policy`, validating the reflector watch /// generation before and after reading `pod_store` (`InitDone` swaps the /// store before advancing the healthy generation). If a re-list completed /// between the two samples, retries once against the newly installed store /// so the immediate healthy-cache path stays zero-wait. fn lookup_cached_pod( &self, pod_name: &str, expected_uid: Option<&str>, policy: CacheTrustPolicy, ) -> Option> { if matches!(policy, CacheTrustPolicy::BypassCache) { return None; } for _ in 0..2 { let gen_before = self.healthy_pod_watch_generation(); if matches!(policy, CacheTrustPolicy::HealthyWatchOnly) && gen_before.is_none() { return None; } let pod = self.lookup_sandbox_pod(pod_name); let gen_after = self.healthy_pod_watch_generation(); if let Some(pod) = pod { if expected_uid.is_some_and(|expected| pod.uid() != Some(expected)) { if gen_before == gen_after || gen_after.is_none() { return None; } continue; } match policy { CacheTrustPolicy::SettledOnly => { if pod_status_is_monotonic(&pod) || (gen_before.is_some() && gen_before == gen_after && pod_status_is_settled(&pod)) { return Some(pod); } if gen_before == gen_after || gen_after.is_none() { return None; } } CacheTrustPolicy::SettledOrHealthyWatch => { if pod_status_is_monotonic(&pod) { return Some(pod); } if gen_before.is_some() && gen_before == gen_after { return Some(pod); } if gen_before == gen_after || gen_after.is_none() { return None; } } CacheTrustPolicy::HealthyWatchOnly => { if gen_before.is_some() && gen_before == gen_after { return Some(pod); } gen_after?; } CacheTrustPolicy::BypassCache => unreachable!("handled before loop"), } } else if gen_before == gen_after || gen_after.is_none() { return None; } } None } /// Re-evaluates `probe` when the reflector signals `pod_name`, a nameless /// watch-state change, or `Lagged` until it yields, the watch turns /// unhealthy, or `wait` elapses; probes once more before giving up. async fn await_cached( &self, pod_name: &str, wait: Duration, mut probe: impl FnMut() -> Option, ) -> Option { let mut rx = self.pod_events.subscribe(); let deadline = Instant::now() + wait; loop { if let Some(found) = probe() { return Some(found); } if !self.pod_reflector_watch_healthy() || Instant::now() >= deadline { break; } loop { match timeout_at(deadline, rx.recv()).await { Ok(Ok(event_pod_name)) if !event_pod_name.is_empty() && event_pod_name != pod_name => { if !self.pod_reflector_watch_healthy() || Instant::now() >= deadline { return probe(); } } Ok(Ok(_)) | Ok(Err(tokio::sync::broadcast::error::RecvError::Lagged(_))) => { break; } Ok(Err(tokio::sync::broadcast::error::RecvError::Closed)) | Err(_) => { return probe(); } } } } probe() } async fn read_settled_sandbox_pod( &self, pod_name: &str, reflector_wait: Duration, ) -> Option> { self.read_cached_sandbox_pod_for_uid( pod_name, None, reflector_wait, CacheTrustPolicy::SettledOrHealthyWatch, ) .await } pub(super) async fn read_cached_sandbox_pod_for_uid( &self, pod_name: &str, expected_uid: Option<&str>, reflector_wait: Duration, policy: CacheTrustPolicy, ) -> Option> { if let Some(pod) = self.lookup_cached_pod(pod_name, expected_uid, policy) { crate::metrics::sandbox::api::read_sandbox_pod_outcome("cache_settled"); return Some(pod); } if !self.pod_reflector_watch_healthy() || reflector_wait.is_zero() { crate::metrics::sandbox::api::read_sandbox_pod_outcome("get_fallback"); return None; } if let Some(pod) = self .await_cached(pod_name, reflector_wait, || { self.lookup_cached_pod(pod_name, expected_uid, policy) }) .await { crate::metrics::sandbox::api::read_sandbox_pod_outcome("event_settled"); return Some(pod); } crate::metrics::sandbox::api::read_sandbox_pod_outcome("get_fallback"); None } /// Observe a claimed warm-pool pod with reflector catch-up and a bounded /// degraded-reflector `GET` fallback. /// /// Uses [`CacheTrustPolicy::HealthyWatchOnly`] so a pod that died during a /// watch disconnect is verified via `GET` rather than adopted from stale /// cache. When a healthy reflector still holds a pre-`Running` snapshot of /// the claimed pod's UID after `budgets.reflector_wait`, returns /// [`PooledClaimPodObservation::ReflectorLagging`] without issuing an /// apiserver `GET` so callers release or retry the slot rather than /// retiring healthy warm capacity on reflector lag. pub(in crate::controllers::substrate::kubernetes) async fn read_pooled_claim_pod( &self, claim: &PooledExecutionClaim, error_context: &str, ) -> Result { self.read_pooled_claim_pod_with_wait(claim, self.budgets.reflector_wait, error_context) .await } pub(in crate::controllers::substrate::kubernetes) async fn read_pooled_claim_pod_with_wait( &self, claim: &PooledExecutionClaim, reflector_wait: Duration, error_context: &str, ) -> Result { let authoritative_hit = || { self.lookup_cached_pod(&claim.pod_name, None, CacheTrustPolicy::HealthyWatchOnly) .filter(|pod| pooled_claim_pod_cache_is_authoritative(claim, pod)) }; if let Some(pod) = authoritative_hit() { crate::metrics::sandbox::api::read_sandbox_pod_outcome("cache_settled"); return Ok(PooledClaimPodObservation::Observed(Some(pod))); } if self.pod_reflector_watch_healthy() && !reflector_wait.is_zero() && let Some(pod) = self .await_cached(&claim.pod_name, reflector_wait, authoritative_hit) .await { crate::metrics::sandbox::api::read_sandbox_pod_outcome("event_settled"); return Ok(PooledClaimPodObservation::Observed(Some(pod))); } if let Some(pod) = self.lookup_cached_pod(&claim.pod_name, None, CacheTrustPolicy::HealthyWatchOnly) { if pooled_claim_pod_cache_is_authoritative(claim, &pod) { crate::metrics::sandbox::api::read_sandbox_pod_outcome("event_settled"); return Ok(PooledClaimPodObservation::Observed(Some(pod))); } if pooled_claim_pod_reflector_lagging(claim, &pod) { crate::metrics::sandbox::api::read_sandbox_pod_outcome("reflector_lagging"); return Ok(PooledClaimPodObservation::ReflectorLagging); } } crate::metrics::sandbox::api::read_sandbox_pod_outcome("get_fallback"); let pod = self .fetch_sandbox_pod_bounded(&claim.pod_name, error_context) .await?; Ok(PooledClaimPodObservation::Observed(pod)) } pub(in crate::controllers::substrate::kubernetes) async fn fetch_sandbox_pod_bounded( &self, pod_name: &str, error_context: &str, ) -> Result>, SubstrateError> { let observed = timeout( self.budgets.readiness_pod_get, fetch_sandbox_pod_uncached(&self.k8s, pod_name), ) .await .map_err(|_| { tracing::warn!( pod_name, error_context, timeout_ms = self.budgets.readiness_pod_get.as_millis(), "bounded Kubernetes pod GET timed out; failing fast" ); kube_api_unavailable( error_context, format_args!( "pod read timed out after {:?}", self.budgets.readiness_pod_get ), ) })?; Self::classify_fail_fast_pod_get(observed, error_context) } pub(in crate::controllers::substrate::kubernetes) async fn fetch_sandbox_pod_until_deadline( &self, pod_name: &str, outer_deadline: Instant, error_context: &str, ) -> Result { let now = Instant::now(); if now >= outer_deadline { return Ok(PodGet::DeadlineElapsed); } let get_deadline = now + self.budgets.readiness_pod_get; let effective_deadline = outer_deadline.min(get_deadline); let observed = match timeout_at( effective_deadline, fetch_sandbox_pod_uncached(&self.k8s, pod_name), ) .await { Ok(observed) => observed, Err(_) if get_deadline < outer_deadline => { tracing::warn!( pod_name, error_context, timeout_ms = self.budgets.readiness_pod_get.as_millis(), "bounded Kubernetes pod GET timed out; failing fast" ); return Err(kube_api_unavailable( error_context, format_args!( "pod read timed out after {:?}", self.budgets.readiness_pod_get ), )); } Err(_) => { tracing::debug!(pod_name, "readiness pod GET hit phase deadline"); return Ok(PodGet::DeadlineElapsed); } }; Self::classify_fail_fast_pod_get(observed, error_context).map(PodGet::Observed) } fn classify_fail_fast_pod_get( observed: Result>, KubeError>, error_context: &str, ) -> Result>, SubstrateError> { observed.map_err(|err| { if is_kube_api_throttling_error(&err) { kube_api_unavailable(error_context, format_args!("throttling: {err}")) } else if is_transient_kube_read_error(&err) { kube_api_unavailable(error_context, format_args!("transient failure: {err}")) } else { SubstrateError::Failed { message: format!("{error_context}: {err}"), } } }) } /// Bound direct pod GETs against `readiness_deadline` and /// `budgets.readiness_pod_get`. /// /// - When `readiness_deadline` is `Some(deadline)`, expiry of `deadline` /// itself returns `Ok(PodGet::DeadlineElapsed)` (an unknown observation, /// never an authoritative 404) so the readiness caller reports its /// phase-deadline `504` timeout, while expiry of `readiness_pod_get` /// *before* `deadline` fails fast with retryable /// `SubstrateError::Unavailable` (`503`). /// - When `readiness_deadline` is `None`, the call is still bounded by /// `budgets.readiness_pod_get` and classifies `429`/`408`/`5xx`/transport /// errors and timeouts as retryable `SubstrateError::Unavailable` (`503`) /// rather than stalling indefinitely (`kube_client::Config` disables /// `read_timeout`). async fn get_pod_for_resolution( &self, pod_name: &str, readiness_deadline: Option, error_context: &str, ) -> Result { if let Some(deadline) = readiness_deadline { return self .fetch_sandbox_pod_until_deadline(pod_name, deadline, error_context) .await; } self.fetch_sandbox_pod_bounded(pod_name, error_context) .await .map(PodGet::Observed) } /// Read-only counterpart to the repairing resolver. Missing, terminal, or /// replaced pods belong to recovery; a reachability probe cannot delete /// them or change execution tracking while its request can be cancelled. pub(in crate::controllers::substrate::kubernetes) async fn resolve_reachable_pod_ip( &self, sandbox_id: SandboxId, ) -> Result, SubstrateError> { let Some(row) = self.store.active_execution_status(sandbox_id).await? else { return Ok(None); }; // A restoring pod is not reachable for a request: see // `join_restore_before_dial`. if is_suspended_lifecycle(&row.lifecycle) || is_restoring_lifecycle(&row.lifecycle) || execution_pod_lookup_in_flight(row.state) || row.pod_uid.is_none() || row.pod_ip.is_none() { return Ok(None); } let pod = match self .read_cached_sandbox_pod_for_uid( &row.pod_name, row.pod_uid.as_ref().map(PodUid::as_str), self.budgets.reflector_wait, CacheTrustPolicy::SettledOrHealthyWatch, ) .await { Some(pod) => pod, None => match self .fetch_sandbox_pod_bounded(&row.pod_name, "failed to read reachable sandbox pod") .await? { Some(pod) => pod, None => return Ok(None), }, }; if pod.is_deleting() || terminal_pod_phase(&pod).is_some() || unbound_unschedulable_message(&pod).is_some() || row.pod_uid.as_ref().map(PodUid::as_str) != pod.uid() { return Ok(None); } let address = current_pod_ip_with_source(&pod, row.pod_uid.as_ref(), row.pod_ip.as_deref())?; // Let the owned path publish changed routing evidence before returning // a client; otherwise ingress would repeatedly resolve stale metadata. if row.pod_ip != address.map(|(ip, _)| ip.to_string()) || row.k8s_node_name.as_deref() != assigned_pod_node_name(&pod) { return Ok(None); } let Some(address) = address else { return Ok(None); }; // An address kubelet has not published is reachable only while the // worker behind it reports this execution. let target = PodProxyWaitTarget { pod_name: row.pod_name.as_str(), pod_uid: row.pod_uid.as_ref().map(PodUid::as_str), generation: row.generation, }; Ok(self .verified_runtime_pod_ip(sandbox_id, address, &target) .await .ok() .flatten()) } pub(in crate::controllers::substrate::kubernetes) async fn resolve_pod_ip( &self, sandbox_id: SandboxId, ) -> Result, SubstrateError> { Ok(self .resolve_pod_instance(sandbox_id) .await? .map(|pod| pod.ip)) } /// Like [`Self::resolve_pod_instance`], using [`CacheTrustPolicy::SettledOnly`] /// so single-shot callers (`completed_execution_binding`) verify the /// resolved execution's generation, pod name, and UID alongside its IP. pub(super) async fn resolve_pod_instance_settled( &self, sandbox_id: SandboxId, ) -> Result, SubstrateError> { self.resolve_pod_instance_inner( sandbox_id, None, None, CacheTrustPolicy::SettledOnly, PlacementRetryDisposition::RetryConverges, UnaddressedLivePodPolicy::ReturnNone, ) .await .map_err(ResolvePodInstanceError::into_substrate_error) } /// Bound direct pod GETs without putting the store mutations in the /// resolver under the shorter GET timeout. An expired `deadline` returns /// `Ok(None)` so readiness reports its phase timeout, while a /// `readiness_pod_get` timeout before `deadline` or a transient apiserver /// read failure (`429`/`408`/`5xx`/transport) fails fast with /// [`SubstrateError::Unavailable`]. Only an address for the execution and /// pod `target` names is returned, with where it comes from. pub(in crate::controllers::substrate::kubernetes) async fn resolve_pod_ip_for_readiness( &self, sandbox_id: SandboxId, target: &PodProxyWaitTarget<'_>, deadline: Instant, ) -> Result, SubstrateError> { self.resolve_pod_ip_for_readiness_with_policy( sandbox_id, target, deadline, CacheTrustPolicy::SettledOrHealthyWatch, ) .await } /// Like [`Self::resolve_pod_ip_for_readiness`], for post-watch fallback /// polling (`poll_until_pod_ip_assigned`): uses [`CacheTrustPolicy::SettledOnly`] /// so an unsettled `Pending` entry in `pod_store` does not suppress fallback /// `GET`s after the per-pod watch ends or errors. pub(in crate::controllers::substrate::kubernetes) async fn resolve_pod_ip_for_readiness_poll( &self, sandbox_id: SandboxId, target: &PodProxyWaitTarget<'_>, deadline: Instant, ) -> Result, SubstrateError> { self.resolve_pod_ip_for_readiness_with_policy( sandbox_id, target, deadline, CacheTrustPolicy::SettledOnly, ) .await } async fn resolve_pod_ip_for_readiness_with_policy( &self, sandbox_id: SandboxId, target: &PodProxyWaitTarget<'_>, deadline: Instant, policy: CacheTrustPolicy, ) -> Result, SubstrateError> { Ok(self .resolve_pod_instance_inner( sandbox_id, Some(deadline), Some((target.generation, target.pod_uid)), policy, PlacementRetryDisposition::RetryDuplicatesExecution, UnaddressedLivePodPolicy::ReturnNone, ) .await .map_err(ResolvePodInstanceError::into_substrate_error)? .filter(|pod| { pod.generation == target.generation && target .pod_uid .is_none_or(|uid| pod.pod_uid.as_ref().map(PodUid::as_str) == Some(uid)) }) .map(|pod| (pod.ip, pod.source))) } /// [`Self::resolve_pod_ip`], with the identity of the pod the address /// belongs to. pub(in crate::controllers::substrate::kubernetes) async fn resolve_pod_instance( &self, sandbox_id: SandboxId, ) -> Result, SubstrateError> { self.resolve_pod_instance_classified(sandbox_id) .await .map_err(ResolvePodInstanceError::into_substrate_error) } pub(in crate::controllers::substrate::kubernetes) async fn resolve_pod_instance_classified( &self, sandbox_id: SandboxId, ) -> Result, ResolvePodInstanceError> { self.resolve_pod_instance_inner( sandbox_id, None, None, CacheTrustPolicy::SettledOrHealthyWatch, PlacementRetryDisposition::RetryConverges, UnaddressedLivePodPolicy::ReturnNone, ) .await } /// Like [`Self::resolve_pod_instance_classified`], using /// [`CacheTrustPolicy::SettledOnly`] and /// [`UnaddressedLivePodPolicy::FenceUnfencedTeardown`] for unfenced /// destructive teardown (`confirmed_unfenced_runtime`), which has no /// caller-supplied `resourceVersion` delete precondition and therefore must /// re-verify unsettled cached `Pending` snapshots, fence unbound IP-less /// deletes by `(uid, resourceVersion)`, and refuse to treat a bound IP-less /// pod as having no runtime. pub(in crate::controllers::substrate::kubernetes) async fn resolve_pod_instance_settled_classified( &self, sandbox_id: SandboxId, bypass_cache: bool, ) -> Result, ResolvePodInstanceError> { let policy = if bypass_cache { CacheTrustPolicy::BypassCache } else { CacheTrustPolicy::SettledOnly }; self.resolve_pod_instance_inner( sandbox_id, None, None, policy, PlacementRetryDisposition::RetryConverges, UnaddressedLivePodPolicy::FenceUnfencedTeardown, ) .await } async fn resolve_pod_instance_inner( &self, sandbox_id: SandboxId, readiness_deadline: Option, expected_target: Option<(i64, Option<&str>)>, policy: CacheTrustPolicy, retry: PlacementRetryDisposition, unaddressed_policy: UnaddressedLivePodPolicy, ) -> Result, ResolvePodInstanceError> { for allow_reresolve in [true, false] { let Some(row) = self.store.active_execution_status(sandbox_id).await? else { return Ok(None); }; if is_suspended_lifecycle(&row.lifecycle) { return Ok(None); } let observed_pod_uid = row.pod_uid.as_ref().map(PodUid::as_str); if let Some((expected_generation, expected_uid)) = expected_target && (row.generation != expected_generation || expected_uid .is_some_and(|uid| observed_pod_uid.is_some_and(|tracked| tracked != uid))) { return Ok(None); } let (pod, verified_uncached) = if execution_pod_lookup_in_flight(row.state) { if !stale_restore_execution_create( &row.lifecycle, row.state, row.create_age_expired, ) { return Ok(None); } ( self.get_pod_for_resolution( &row.pod_name, readiness_deadline, "failed to verify stale creating restore pod", ) .await?, true, ) } else if matches!(policy, CacheTrustPolicy::BypassCache) { ( self.get_pod_for_resolution( &row.pod_name, readiness_deadline, "failed to query K8s pod", ) .await?, true, ) } else { let reflector_wait = readiness_deadline.map_or(self.budgets.reflector_wait, |deadline| { self.budgets .reflector_wait .min(deadline.saturating_duration_since(Instant::now())) }); if let Some(pod) = self .read_cached_sandbox_pod_for_uid( &row.pod_name, observed_pod_uid, reflector_wait, policy, ) .await { (PodGet::Observed(Some(pod)), false) } else { ( self.get_pod_for_resolution( &row.pod_name, readiness_deadline, "failed to query K8s pod", ) .await?, true, ) } }; let PodGet::Observed(pod) = pod else { return Ok(None); }; let (pod, verified_uncached) = match pod { Some(pod) => (pod, verified_uncached), None => { // A cache miss alone must never authorize execution retirement, // because a finalizer-blocked or unlisted pod can be absent // from the cache while still present on the apiserver. When the // `None` above already came from an uncached `GET` // (`verified_uncached`), reuse that 404 observation rather than // issuing a second back-to-back apiserver `GET`. let authoritative = if verified_uncached { None } else { let PodGet::Observed(pod) = self .get_pod_for_resolution( &row.pod_name, readiness_deadline, "failed to verify missing Kubernetes sandbox pod", ) .await? else { return Ok(None); }; pod }; match authoritative { Some(pod) => (pod, true), None => { match self .retire_missing_pod_for_resolution( sandbox_id, &row, observed_pod_uid, allow_reresolve, ) .await? { MissingPodResolution::Reresolve => continue, MissingPodResolution::Retired => return Ok(None), } } } } }; let (pod, verified_uncached) = if !verified_uncached && unbound_unschedulable_message(&pod).is_some() { let PodGet::Observed(authoritative_pod) = self .get_pod_for_resolution( &row.pod_name, readiness_deadline, "failed to verify unschedulable Kubernetes sandbox pod", ) .await? else { return Ok(None); }; match authoritative_pod { Some(authoritative_pod) => (authoritative_pod, true), None => { match self .retire_missing_pod_for_resolution( sandbox_id, &row, observed_pod_uid, allow_reresolve, ) .await? { MissingPodResolution::Reresolve => continue, MissingPodResolution::Retired => return Ok(None), } } } } else { (pod, verified_uncached) }; let pod = if let Some(cached_phase) = terminal_pod_phase(&pod) { let authoritative_pod = if verified_uncached { Some(pod) } else { let PodGet::Observed(authoritative_pod) = self .get_pod_for_resolution( &row.pod_name, readiness_deadline, "failed to verify terminal Kubernetes sandbox pod", ) .await? else { return Ok(None); }; authoritative_pod }; if let Some(phase) = terminal_cleanup_phase_after_uncached_check( cached_phase, authoritative_pod.as_deref(), ) { let Some(authoritative_pod) = authoritative_pod else { match self .retire_missing_pod_for_resolution( sandbox_id, &row, observed_pod_uid, allow_reresolve, ) .await? { MissingPodResolution::Reresolve => continue, MissingPodResolution::Retired => return Ok(None), } }; // When a terminal pod sits at `row.pod_name` under a // different UID than `observed_pod_uid`, re-read the // execution row once first so a concurrent generation // advance or `pod_uid` persist settles before cleanup. If // the second pass still sees `row` pinned to // `observed_pod_uid`, that pod is gone and `authoritative_pod` // is an unpersisted terminal pod at the same per-generation // name: fall through to delete `authoritative_pod` fenced on // its UID and retire `row` fenced on `observed_pod_uid`. if observed_pod_uid.is_some() && authoritative_pod.uid() != observed_pod_uid && allow_reresolve { continue; } let publication_grace_remaining = (phase == TerminalPodPhase::Succeeded) .then(|| { succeeded_pod_publication_grace_remaining( &authoritative_pod, jiff::Timestamp::now(), ) }) .flatten(); if row.lifecycle == SandboxLifecycle::Suspending.as_str() && publication_grace_remaining.is_some() { tracing::info!( sandbox_id = %sandbox_id, pod_name = %row.pod_name, generation = row.generation, pod_uid = ?row.pod_uid, lifecycle = %row.lifecycle, grace_remaining_ms = publication_grace_remaining .map(|remaining| remaining.as_millis()), "deferring successful terminal pod cleanup while suspend publication may still arrive" ); return Err(SubstrateError::suspend_in_flight(sandbox_id).into()); } let delete_pod_uid = authoritative_pod.uid().or(observed_pod_uid); tracing::info!( sandbox_id = %sandbox_id, pod_name = %row.pod_name, delete_pod_uid = ?delete_pod_uid, tracked_pod_uid = ?observed_pod_uid, cached_phase = %cached_phase, phase = %phase, cached_pod_ip = ?row.pod_ip, "tracked Kubernetes sandbox pod is terminal after uncached verification; deleting it and clearing cached pod IP" ); match self .delete_terminal_pod_and_forget_missing_tracking( sandbox_id, &row.pod_name, row.generation, delete_pod_uid, observed_pod_uid, ) .await? { super::delete::TerminalPodCleanupOutcome::ReplacedOnApiserver if allow_reresolve => { tracing::debug!( sandbox_id = %sandbox_id, generation = row.generation, pod_name = %row.pod_name, delete_pod_uid = ?delete_pod_uid, "terminal-pod delete precondition rejected by replacement pod on apiserver; re-resolving" ); continue; } super::delete::TerminalPodCleanupOutcome::ReplacedOnApiserver => { return Err(kube_api_unavailable( "failed to confirm terminal Kubernetes sandbox pod deletion", format_args!("pod {}; keeping execution tracking", row.pod_name), ) .into()); } super::delete::TerminalPodCleanupOutcome::Tracking( MissingPodTrackingCleanupOutcome::NotMatched, ) if allow_reresolve => { tracing::debug!( sandbox_id = %sandbox_id, generation = row.generation, pod_name = %row.pod_name, delete_pod_uid = ?delete_pod_uid, tracked_pod_uid = ?observed_pod_uid, "terminal-pod tracking cleanup skipped after concurrent execution update; re-resolving" ); continue; } super::delete::TerminalPodCleanupOutcome::Tracking( MissingPodTrackingCleanupOutcome::NotMatched, ) => { self.classify_exhausted_cleanup_cas_mismatch( sandbox_id, "terminal-pod cleanup", ) .await?; return Ok(None); } super::delete::TerminalPodCleanupOutcome::Tracking( MissingPodTrackingCleanupOutcome::Forgotten | MissingPodTrackingCleanupOutcome::DeferredToSuspend | MissingPodTrackingCleanupOutcome::SandboxAbsent, ) => { return Ok(None); } } } tracing::info!( sandbox_id = %sandbox_id, pod_name = %row.pod_name, cached_phase = %cached_phase, cached_pod_ip = ?row.pod_ip, "cached Kubernetes sandbox pod was terminal but uncached pod is still active; keeping tracking" ); authoritative_pod .expect("non-terminal verification result requires an existing pod") } else { pod }; if let Some(message) = unbound_unschedulable_message(&pod) { match self .verify_no_reachable_runtime_fence( sandbox_id, &row, observed_pod_uid, row.pod_ip.as_deref(), row.k8s_node_name.as_deref(), pod.uid(), allow_reresolve, "unschedulable pod resolution", ) .await? { NoReachableRuntimeFence::Holds => { let pod_fence = no_reachable_runtime_delete_fence( row.generation, &row.pod_name, observed_pod_uid, &pod, true, ); if unaddressed_policy == UnaddressedLivePodPolicy::FenceUnfencedTeardown && pod_fence.is_none() { return Err(ResolvePodInstanceError::Substrate( SubstrateError::Unavailable { message: format!( "sandbox pod {} is unschedulable ({message}) and has no UID \ for fenced teardown", row.pod_name ), }, )); } return Err(ResolvePodInstanceError::NoReachableRuntime { err: SubstrateError::Unschedulable { message: format!("sandbox pod is unschedulable: {message}"), }, pod_fence, }); } NoReachableRuntimeFence::Reresolve => continue, NoReachableRuntimeFence::Inactive => return Ok(None), } } let pod_uid = pod.uid().map(str::to_owned); if let Some((_, Some(expected_uid))) = expected_target && pod_uid.as_deref() != Some(expected_uid) { return Ok(None); } let resolved = current_pod_ip_with_source(&pod, row.pod_uid.as_ref(), row.pod_ip.as_deref())?; let pod_ip = resolved.map(|(ip, _)| ip); let pod_ip_string = pod_ip.map(|ip| ip.to_string()); let pod_client = pod.client_id(); let mut tracked_pod_uid = observed_pod_uid; let mut tracked_pod_ip = row.pod_ip.as_deref(); let mut tracked_node_name = row.k8s_node_name.as_deref(); if observed_pod_uid != pod_uid.as_deref() || row.pod_ip.as_deref() != pod_ip_string.as_deref() { match self .store .persist_pod_metadata_if_observed_pod_uid( sandbox_id, row.generation, observed_pod_uid, row.pod_ip.as_deref(), pod_uid.as_deref(), pod_ip_string.as_deref(), pod_client.as_ref(), ) .await? { ConditionalPodMetadataWrite::Written(state) if state != ActiveExecutionState::Suspended => { tracked_pod_uid = pod_uid.as_deref(); tracked_pod_ip = pod_ip_string.as_deref(); } ConditionalPodMetadataWrite::ObservedMetadataChanged | ConditionalPodMetadataWrite::NoActiveGeneration | ConditionalPodMetadataWrite::Written(_) => { if allow_reresolve { tracing::debug!( sandbox_id = %sandbox_id, generation = row.generation, observed_pod_uid = ?observed_pod_uid, candidate_pod_uid = ?pod_uid, "pod metadata write lost its execution fence to a concurrent update; re-resolving" ); continue; } self.classify_exhausted_cleanup_cas_mismatch( sandbox_id, "pod metadata write", ) .await?; return Ok(None); } } } else if self.k8s.activation_client_attribution.is_enabled() && let Some(pod_uid) = pod_uid.as_deref() && crate::controllers::substrate::kubernetes::store::attribution_update( &row.lifecycle, Some(pod_uid), Some(pod_uid), pod_client.as_ref(), row.activating_client_id.as_ref(), ) .is_some() { // The pod is the one the row tracks, and only the record lags its // label: repair the record alone, leaving the row's state as it is. if let Err(err) = self .store .repair_runtime_attribution( sandbox_id, row.generation, pod_uid, pod_client.as_ref(), ) .await { tracing::warn!( sandbox_id = %sandbox_id, generation = row.generation, error = %err, "failed to repair the sandbox's activating client after pod lookup" ); } } let current_node_name = assigned_pod_node_name(&pod).map(str::to_owned); // Under unfenced teardown, also verify the node when `resolved` is // `None` and `row.k8s_node_name` already matches `current_node_name` // so a bound IP-less pod on a deleted (`404`) node still classifies // as `NodeUnreachable` rather than stalling teardown indefinitely. let should_check_node = row.k8s_node_name.as_deref() != current_node_name.as_deref() || (unaddressed_policy == UnaddressedLivePodPolicy::FenceUnfencedTeardown && resolved.is_none() && current_node_name.is_some()); if should_check_node { match self .remember_pod_node_placement_if_generation_pod_uid_until_deadline( sandbox_id, row.generation, tracked_pod_uid, &pod, readiness_deadline, retry, ) .await { Ok(node_placement::NodePlacementObservation::DeadlineElapsed) => { return Ok(None); } Ok(node_placement::NodePlacementObservation::Observed(Some((_, false)))) => { if allow_reresolve { tracing::debug!( sandbox_id = %sandbox_id, generation = row.generation, expected_pod_uid = ?tracked_pod_uid, "pod node placement write lost its execution fence to a concurrent update; re-resolving" ); continue; } self.classify_exhausted_cleanup_cas_mismatch( sandbox_id, "pod node-placement write", ) .await?; return Ok(None); } Ok(node_placement::NodePlacementObservation::Observed(Some((_, true)))) => { tracked_node_name = current_node_name.as_deref(); } Ok(node_placement::NodePlacementObservation::Observed(None)) => {} Err(PodNodePlacementError::Substrate(err)) => { return Err(ResolvePodInstanceError::Substrate(err)); } Err(PodNodePlacementError::NodeUnreachable(err)) => { // Re-verify the pod directly even when `pod` came from an // uncached GET: the Node lookup and metadata write ran in // between, so a replacement pod may already occupy // `row.pod_name` on a healthy node before its UID reaches // `sandbox_k8s_executions`. let PodGet::Observed(authoritative_pod) = self .get_pod_for_resolution( &row.pod_name, readiness_deadline, "failed to verify Kubernetes sandbox pod on unreachable node", ) .await? else { return Ok(None); }; let Some(authoritative_pod) = authoritative_pod else { match self .retire_missing_pod_for_resolution( sandbox_id, &row, tracked_pod_uid, allow_reresolve, ) .await? { MissingPodResolution::Reresolve => continue, MissingPodResolution::Retired => return Ok(None), } }; if authoritative_pod.uid() != pod.uid() || assigned_pod_node_name(&authoritative_pod) != current_node_name.as_deref() || terminal_pod_phase(&authoritative_pod).is_some() { if allow_reresolve { continue; } self.classify_exhausted_cleanup_cas_mismatch( sandbox_id, "unreachable-node pod verification", ) .await?; return Ok(None); } let live_pod_uid = authoritative_pod.uid().map(str::to_owned); match self .verify_no_reachable_runtime_fence( sandbox_id, &row, tracked_pod_uid, tracked_pod_ip, tracked_node_name, live_pod_uid.as_deref(), allow_reresolve, "unreachable-node pod resolution", ) .await? { NoReachableRuntimeFence::Holds => { let pod_fence = no_reachable_runtime_delete_fence( row.generation, &row.pod_name, tracked_pod_uid, &authoritative_pod, false, ); if unaddressed_policy == UnaddressedLivePodPolicy::FenceUnfencedTeardown && pod_fence.is_none() { return Err(ResolvePodInstanceError::Substrate( SubstrateError::Unavailable { message: format!( "{err}; sandbox pod {} has no UID for fenced teardown", row.pod_name ), }, )); } return Err(ResolvePodInstanceError::NoReachableRuntime { err, pod_fence, }); } NoReachableRuntimeFence::Reresolve => continue, NoReachableRuntimeFence::Inactive => return Ok(None), } } } } if resolved.is_none() && unaddressed_policy == UnaddressedLivePodPolicy::FenceUnfencedTeardown { match self .verify_no_reachable_runtime_fence( sandbox_id, &row, tracked_pod_uid, tracked_pod_ip, tracked_node_name, pod_uid.as_deref(), allow_reresolve, "unaddressed pod resolution", ) .await? { NoReachableRuntimeFence::Holds => { let Some(pod_fence) = no_reachable_runtime_delete_fence( row.generation, &row.pod_name, tracked_pod_uid, &pod, true, ) else { return Err(ResolvePodInstanceError::Substrate( SubstrateError::Unavailable { message: format!( "sandbox pod {} has no runtime IP yet and has no UID \ for fenced teardown", row.pod_name ), }, )); }; let message = match current_node_name.as_deref() { Some(node_name) => format!( "sandbox pod {} is bound to node {node_name} without a runtime IP yet", row.pod_name ), None => { format!("sandbox pod {} is not bound to a node yet", row.pod_name) } }; return Err(ResolvePodInstanceError::NoReachableRuntime { err: SubstrateError::Unavailable { message }, pod_fence: Some(pod_fence), }); } NoReachableRuntimeFence::Reresolve => continue, NoReachableRuntimeFence::Inactive => return Ok(None), } } return Ok(resolved.map(|(ip, source)| ResolvedPodInstance { ip, source, pod_name: row.pod_name, pod_uid: pod_uid.as_deref().and_then(|uid| PodUid::parse(uid).ok()), generation: row.generation, sandbox_restoring: is_restoring_lifecycle(&row.lifecycle), })); } Ok(None) } } fn no_reachable_runtime_delete_fence( generation: i64, pod_name: &str, tracked_pod_uid: Option<&str>, pod: &SandboxPodView, include_resource_version: bool, ) -> Option> { let pod_name = PodName::parse(pod_name).ok()?; let pod_uid = pod.uid().and_then(|uid| PodUid::parse(uid).ok())?; let resource_version = include_resource_version .then(|| { pod.resource_version() .and_then(|version| PodResourceVersion::parse(version).ok()) }) .flatten(); Some(Box::new(NoReachableRuntimeDeleteFence { generation, pod_name, pod_uid, tracked_pod_uid: tracked_pod_uid.and_then(|uid| PodUid::parse(uid).ok()), resource_version, })) } mod node_placement; mod resolution_fences; pub(in crate::controllers::substrate::kubernetes) use node_placement::NodePlacementObservation; #[cfg(test)] mod tests;