//! 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::kubernetes::wait_ready::{PodGet, PodProxyWaitTarget}; const SUCCEEDED_POD_SUSPEND_PUBLICATION_GRACE: Duration = Duration::from_secs(180); #[derive(Clone, Copy)] enum ReadinessLookupMode<'a> { SettledOrGet { deadline: Option, }, CachedPrecheck { deadline: Instant, target: &'a PodProxyWaitTarget<'a>, }, ImmediateGetFallback { deadline: Instant, target: &'a PodProxyWaitTarget<'a>, observed: &'a tokio::sync::watch::Sender>, }, } impl ReadinessLookupMode<'_> { fn deadline(self) -> Option { match self { Self::SettledOrGet { deadline } => deadline, Self::CachedPrecheck { deadline, .. } | Self::ImmediateGetFallback { deadline, .. } => { Some(deadline) } } } } /// Failure observed by a shared in-flight single-pod `GET` in /// `KubernetesSubstrate::pod_get_coalescer`. #[derive(Debug)] pub(in crate::controllers::substrate::kubernetes) enum PodGetFailure { Kube(KubeError), TimedOut(Duration), } enum CoalescedPodGetError { Shared(Arc), CallerDeadlineElapsed, } enum CoalescedPodGet { Owned(Option>), Joined(Option>), } impl CoalescedPodGet { fn into_pod(self) -> Option> { match self { Self::Owned(pod) | Self::Joined(pod) => pod, } } } type NodeDetails<'a> = (&'a str, String, NodeId, String, Option); #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(in crate::controllers::substrate::kubernetes) enum ResolutionGetKind<'a> { /// Normal cache-miss fallback: shares an in-flight per-pod `GET` via /// [`KubernetesSubstrate::fetch_sandbox_pod_bounded`], reconfirming with a /// fresh `GET` when `expected_uid` disagrees with the coalesced `Some(pod)` /// or when a `SettledOnly` caller joined a `GET` that observed an unsettled /// `Pending` pod before the caller entered. CoalescedFallback { expected_uid: Option<&'a str>, policy: CacheTrustPolicy, }, /// Lifecycle confirmation before mutating tracking or deleting a terminal /// pod: issues a fresh bounded `GET` started after the observation being /// verified so it never inherits a pre-create or pre-replacement response /// from an earlier coalesced caller. FreshConfirmation, } /// How [`KubernetesSubstrate::lookup_cached_pod`] decides whether a cached /// [`SandboxPodView`] is authoritative while the reflector watch is healthy. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(in crate::controllers::substrate::kubernetes) enum CacheTrustPolicy { /// Trusts settled entries (`status.podIP`, terminal phase, or unbound /// `Pending+Unschedulable`) on a healthy watch; unsettled `Pending` waits /// on `pod_events` up to `reflector_wait` and then falls through to `GET`. SettledOnly, /// Trusts all cached entries (including `Pending`) while the reflector /// watch is healthy; degraded or mid-re-list watches fall through to `GET`. SettledOrHealthyWatch, } /// Whether a [`CacheTrustPolicy::SettledOnly`] caller that joined an already /// in-flight `GET` must reconfirm with a fresh `GET`. Unlike a post-entry /// reflector observation, a pre-caller `Pending` response — including unbound /// `Pending + Unschedulable` — could bind before the caller entered; only an /// assigned `PodIp` or terminal phase is monotone across that window. fn settled_only_join_needs_recheck(pod: &SandboxPodView) -> bool { assigned_pod_ip(pod).ok().flatten().is_none() && terminal_pod_phase(pod).is_none() } pub(super) fn classify_kube_read_error(err: &KubeError, error_context: &str) -> SubstrateError { 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}"), } } } fn pod_get_timeout_kube_error(budget: Duration) -> KubeError { KubeError::Service(Box::new(std::io::Error::new( std::io::ErrorKind::TimedOut, format!("pod read timed out after {budget:?}"), ))) } fn shared_pod_get_kube_error(err: Arc) -> KubeError { match Arc::try_unwrap(err) { Ok(PodGetFailure::Kube(kube_err)) => kube_err, Ok(PodGetFailure::TimedOut(budget)) => pod_get_timeout_kube_error(budget), Err(shared) => match shared.as_ref() { PodGetFailure::Kube(KubeError::Api(status)) => KubeError::Api(status.clone()), PodGetFailure::Kube(other) if is_transient_kube_read_error(other) => { KubeError::Service(Box::new(std::io::Error::other(other.to_string()))) } PodGetFailure::Kube(other) => KubeError::Api( kube::core::Status::failure(&other.to_string(), "ClientError") .with_code(400) .boxed(), ), PodGetFailure::TimedOut(budget) => pod_get_timeout_kube_error(*budget), }, } } 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, bounded-and-coalesced /// kube-apiserver `GET` fallback semantics, trusting `Pending` entries /// while the reflector watch is healthy. /// /// Callers that require an IP-settled view even on a healthy watch (such as /// warm-pool claim checks, unfenced teardown runtime probes, and legacy /// wake binding) call [`Self::read_sandbox_pod_settled`] or /// [`Self::resolve_pod_instance_settled`]. pub async fn read_sandbox_pod( &self, pod_name: &str, ) -> Result>, KubeError> { self.read_sandbox_pod_with_policy(pod_name, CacheTrustPolicy::SettledOrHealthyWatch) .await } /// Reads `pod_name` trusting the reflector cache only once the cached /// status is settled on a healthy watch, falling back to a bounded, /// coalesced `GET` on unsettled `Pending` entries or an unhealthy watch. pub(in crate::controllers::substrate::kubernetes) async fn read_sandbox_pod_settled( &self, pod_name: &str, ) -> Result>, KubeError> { self.read_sandbox_pod_with_policy(pod_name, CacheTrustPolicy::SettledOnly) .await } async fn read_sandbox_pod_with_policy( &self, pod_name: &str, policy: CacheTrustPolicy, ) -> Result>, KubeError> { if let Some(pod) = self .read_cached_sandbox_pod_for_uid(pod_name, None, self.budgets.reflector_wait, policy) .await { return Ok(Some(pod)); } let budget = self.budgets.readiness_pod_get; let outcome = self .coalesced_pod_get(pod_name, Instant::now() + budget) .await .map_err(|err| match err { CoalescedPodGetError::Shared(shared) => { if let PodGetFailure::TimedOut(elapsed) = shared.as_ref() { tracing::warn!( pod_name, timeout_ms = elapsed.as_millis(), "bounded Kubernetes pod GET timed out; failing fast" ); } shared_pod_get_kube_error(shared) } CoalescedPodGetError::CallerDeadlineElapsed => { tracing::warn!( pod_name, timeout_ms = budget.as_millis(), "bounded Kubernetes pod GET timed out; failing fast" ); pod_get_timeout_kube_error(budget) } })?; if let CoalescedPodGet::Joined(Some(ref pod)) = outcome && policy == CacheTrustPolicy::SettledOnly && settled_only_join_needs_recheck(pod) { return match timeout(budget, fetch_sandbox_pod_uncached(&self.k8s, pod_name)).await { Ok(result) => result, Err(_) => { tracing::warn!( pod_name, timeout_ms = budget.as_millis(), "bounded Kubernetes pod GET timed out; failing fast" ); Err(pod_get_timeout_kube_error(budget)) } }; } Ok(outcome.into_pod()) } /// Cache-first pod read under [`CacheTrustPolicy::SettledOnly`] whose /// fallback is a fresh bounded `GET`, filtered to `expected_uid` when set. /// /// Used before reusing annotations stamped on an existing restore pod so a /// deleted `Pending` pod still lingering in the reflector cache cannot mask /// a newer remote snapshot in Postgres. pub(in crate::controllers::substrate::kubernetes) async fn read_sandbox_pod_settled_bounded( &self, pod_name: &str, expected_uid: Option<&str>, error_context: &str, ) -> Result>, SubstrateError> { if let Some(pod) = self .read_cached_sandbox_pod_for_uid( pod_name, expected_uid, self.budgets.reflector_wait, CacheTrustPolicy::SettledOnly, ) .await { return Ok(Some(pod)); } Ok(self .fetch_sandbox_pod_fresh_bounded(pod_name, error_context) .await? .filter(|pod| expected_uid.is_none_or(|uid| pod.uid() == Some(uid)))) } fn healthy_pod_watch_generation(&self) -> Option { self.pod_client_index .healthy_watch_generation(self.pod_reflector_ready.is_ready()) } pub(in crate::controllers::substrate::kubernetes) fn pod_reflector_watch_healthy( &self, ) -> bool { self.healthy_pod_watch_generation().is_some() } /// Look up a cached pod under `policy`, bracketing `pod_store` with /// `healthy_pod_watch_generation` so a watch fault or re-list between the /// two samples invalidates cache trust. Retries once if a re-list finished /// mid-sample (`InitDone` updates `pod_store` before bumping generation). fn lookup_cached_pod( &self, pod_name: &str, expected_uid: Option<&str>, policy: CacheTrustPolicy, ) -> Option> { for _ in 0..2 { let gen_before = self.healthy_pod_watch_generation(); let pod = self.lookup_sandbox_pod(pod_name); let gen_after = self.healthy_pod_watch_generation(); if gen_before.is_some() && gen_before == gen_after && let Some(pod) = pod && expected_uid.is_none_or(|expected| pod.uid() == Some(expected)) && (policy == CacheTrustPolicy::SettledOrHealthyWatch || pod_status_is_settled(&pod)) { return Some(pod); } if gen_before == gen_after || gen_after.is_none() { return None; } } None } /// Re-evaluates `probe` when the reflector signals `pod_name`, a whole-store /// relist or watch-error transition, 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(super::pod_reflector::PodEventSignal::Pod(event_pod_name))) if event_pod_name != pod_name => { if !self.pod_reflector_watch_healthy() || Instant::now() >= deadline { return probe(); } } Ok(Ok( super::pod_reflector::PodEventSignal::Pod(_) | super::pod_reflector::PodEventSignal::Relisted | super::pod_reflector::PodEventSignal::CacheDegraded, )) | Ok(Err(tokio::sync::broadcast::error::RecvError::Lagged(_))) => { break; } Ok(Err(tokio::sync::broadcast::error::RecvError::Closed)) | Err(_) => { return probe(); } } } } probe() } pub(in crate::controllers::substrate::kubernetes) 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 } async fn coalesced_pod_get( &self, pod_name: &str, caller_deadline: Instant, ) -> Result { let owner_budget = self.budgets.readiness_pod_get; for _ in 0..2 { if Instant::now() >= caller_deadline { return Err(CoalescedPodGetError::CallerDeadlineElapsed); } let k8s = self.k8s.clone(); let name = pod_name.to_owned(); match self .pod_get_coalescer .join_or_start(pod_name.to_owned(), caller_deadline, move || async move { match timeout(owner_budget, fetch_sandbox_pod_uncached(&k8s, &name)).await { Ok(Ok(pod)) => Ok(pod), Ok(Err(err)) => Err(PodGetFailure::Kube(err)), Err(_) => Err(PodGetFailure::TimedOut(owner_budget)), } }) .await { Ok(pplx_space_work_coalescer::WorkOutcome::Owned(pod)) => { return Ok(CoalescedPodGet::Owned(pod)); } Ok(pplx_space_work_coalescer::WorkOutcome::Joined(pod)) => { return Ok(CoalescedPodGet::Joined(pod)); } Ok(pplx_space_work_coalescer::WorkOutcome::Failed { error, .. }) => { return Err(CoalescedPodGetError::Shared(error)); } Err(pplx_space_work_coalescer::JoinError::DeadlineElapsed) => { return Err(CoalescedPodGetError::CallerDeadlineElapsed); } Err(pplx_space_work_coalescer::JoinError::RunAbandoned) if Instant::now() < caller_deadline => {} Err(pplx_space_work_coalescer::JoinError::RunAbandoned) => { return Err(CoalescedPodGetError::CallerDeadlineElapsed); } } } Err(CoalescedPodGetError::CallerDeadlineElapsed) } async fn fetch_sandbox_pod_coalesced( &self, pod_name: &str, error_context: &str, ) -> Result { let budget = self.budgets.readiness_pod_get; self.coalesced_pod_get(pod_name, Instant::now() + budget) .await .map_err(|err| match err { CoalescedPodGetError::Shared(shared) => match shared.as_ref() { PodGetFailure::Kube(kube_err) => { classify_kube_read_error(kube_err, error_context) } PodGetFailure::TimedOut(elapsed) => { self.bounded_pod_get_timed_out(pod_name, error_context, *elapsed) } }, CoalescedPodGetError::CallerDeadlineElapsed => { self.bounded_pod_get_timed_out(pod_name, error_context, budget) } }) } fn bounded_pod_get_timed_out( &self, pod_name: &str, error_context: &str, budget: Duration, ) -> SubstrateError { tracing::warn!( pod_name, error_context, timeout_ms = budget.as_millis(), "bounded Kubernetes pod GET timed out; failing fast" ); kube_api_unavailable( error_context, format_args!("pod read timed out after {budget:?}"), ) } async fn fetch_sandbox_pod_fresh_bounded( &self, pod_name: &str, error_context: &str, ) -> Result>, SubstrateError> { let budget = self.budgets.readiness_pod_get; match timeout(budget, fetch_sandbox_pod_uncached(&self.k8s, pod_name)).await { Ok(Ok(pod)) => Ok(pod), Ok(Err(kube_err)) => Err(classify_kube_read_error(&kube_err, error_context)), Err(_) => Err(self.bounded_pod_get_timed_out(pod_name, error_context, budget)), } } /// Bounded (`budgets.readiness_pod_get`), per-pod-coalesced single-pod /// `GET` that maps `429`/`408`/`5xx`/transport errors and `GET` timeouts to /// [`SubstrateError::KubeApiUnavailable`] via [`kube_api_unavailable`], reconfirming /// via a fresh bounded `GET` on UID mismatch or when a `SettledOnly` caller /// joins a pre-caller non-terminal pod without an assigned IP (including an /// unbound `Pending + Unschedulable` pod that could bind before the caller /// arrived). pub(in crate::controllers::substrate::kubernetes) async fn fetch_sandbox_pod_bounded( &self, pod_name: &str, expected_uid: Option<&str>, policy: CacheTrustPolicy, error_context: &str, ) -> Result>, SubstrateError> { let coalesced = self .fetch_sandbox_pod_coalesced(pod_name, error_context) .await?; let uid_mismatch = match &coalesced { CoalescedPodGet::Owned(Some(pod)) | CoalescedPodGet::Joined(Some(pod)) => { expected_uid.is_some_and(|expected| pod.uid() != Some(expected)) } _ => false, }; let joined_unsettled = matches!( &coalesced, CoalescedPodGet::Joined(Some(pod)) if policy == CacheTrustPolicy::SettledOnly && settled_only_join_needs_recheck(pod) ); if uid_mismatch || joined_unsettled { return self .fetch_sandbox_pod_fresh_bounded(pod_name, error_context) .await; } Ok(coalesced.into_pod()) } /// A readiness-slice budget expiry is an unknown observation (`PodGet::TimedOut`), /// never an authoritative 404 — cancelling the hung readiness request at /// `deadline` so post-budget cleanup reads observe fresh apiserver state, and /// keeping `kube_error_for_substrate`'s `Timeout` classification so create /// readiness still preserves an already-reachable node runtime on transient /// apiserver faults — while non-readiness reads fail fast as `Unavailable` /// (coalesced via [`Self::fetch_sandbox_pod_bounded`] on cache-miss reads, /// or fresh via [`Self::fetch_sandbox_pod_fresh_bounded`] on lifecycle /// confirmation checks). pub(in crate::controllers::substrate::kubernetes) async fn get_pod_for_resolution( &self, pod_name: &str, readiness_deadline: Option, kind: ResolutionGetKind<'_>, error_context: &str, ) -> Result { let Some(deadline) = readiness_deadline else { let observed = match kind { ResolutionGetKind::CoalescedFallback { expected_uid, policy, } => { self.fetch_sandbox_pod_bounded(pod_name, expected_uid, policy, error_context) .await? } ResolutionGetKind::FreshConfirmation => { self.fetch_sandbox_pod_fresh_bounded(pod_name, error_context) .await? } }; return Ok(PodGet::Observed(observed)); }; let now = Instant::now(); if now >= deadline { return Ok(PodGet::TimedOut); } match tokio::time::timeout_at( deadline.min(now + self.budgets.readiness_pod_get), fetch_sandbox_pod_uncached(&self.k8s, pod_name), ) .await { Ok(Ok(observed)) => Ok(PodGet::Observed(observed)), Ok(Err(kube_err)) => Err(kube_error_for_substrate(error_context, kube_err)), Err(_) => { tracing::debug!(pod_name, "readiness pod GET timed out"); Ok(PodGet::TimedOut) } } } pub(in super::super) async fn live_execution_pod_snapshot( &self, id: SandboxId, g: i64, ) -> Result, time::OffsetDateTime)>, SubstrateError> { let ok = |r: &super::super::store::ActiveExecutionStatusRow| { r.generation == g && !is_suspended_lifecycle(&r.lifecycle) && r.state != ActiveExecutionState::RecoveryFailed }; let row = self.store.active_execution_status(id).await?.filter(ok); Ok(row.map(|r| (r.pod_uid.map(|u| u.as_str().to_owned()), r.updated_at))) } /// `retry` states what the calling operation's retry would do; see /// [`PlacementRetryDisposition`]. It is a parameter because this helper /// serves both `create` (whose retry mints a new sandbox) and /// `start`/`wake`/`access` (whose retry converges). /// /// Two call sites pass a constant that is not their operation's: /// `resolve_pod_ip` and `wait_ready`'s `reflect_until_pod_ip_assigned` are /// each reached from create readiness *and* from wake/access/delete, and /// both pass `RetryDuplicatesExecution`. That is the safe direction — it /// costs a converging caller a 500 where a 503 would have done, rather /// than risking a duplicate sandbox — but it does mean contention on those /// two paths is not retryable even for operations that converge. Relaxing /// either one requires threading the disposition down through it, not /// flipping the constant. pub(in crate::controllers::substrate::kubernetes) async fn remember_pod_node_placement( &self, sandbox_id: SandboxId, pod: &SandboxPodView, retry: PlacementRetryDisposition, ) -> Result, SubstrateError> { self.remember_pod_node_placement_for_execution(sandbox_id, pod, None, retry) .await } async fn resolve_pod_node_details<'a>( &self, pod: &'a SandboxPodView, ) -> Result>, SubstrateError> { let Some(node_name) = assigned_pod_node_name(pod) else { return Ok(None); }; // Watcher-backed cache is the warm path. Fall back to a direct API // get when the reflector hasn't populated this Node yet — startup // races and slow API-server lists must not break placement that the // scheduler has already committed. let node = match self.k8s.caches.node_by_name(node_name) { Some(node) => node, None => { let nodes: Api = Api::all(self.k8s.client.clone()); let fetched = nodes.get(node_name).await.map_err(|err| match err { kube::Error::Api(resp) if resp.code == 404 => SubstrateError::Unavailable { message: format!( "Kubernetes node {node_name} no longer exists; cannot preserve node-local sandbox placement" ), }, other => SubstrateError::Failed { message: format!("failed to query Kubernetes node {node_name}: {other}"), }, })?; std::sync::Arc::new(fetched) } }; let node_uid = node .metadata .uid .as_deref() .ok_or_else(|| SubstrateError::Failed { message: format!("Kubernetes node {node_name} has no metadata.uid"), })? .to_owned(); let role = SpaceNodeRole::Worker; let node_id = space_k8s_node_id(node_name, role.as_str()); let instance_id = k8s_node_instance_id(&node); let address = k8s_node_internal_ip(&node).ok_or_else(|| SubstrateError::Unavailable { message: format!( "Kubernetes node {node_name} has no InternalIP; cannot authenticate node-local reconciliation" ), })?; Ok(Some((node_name, node_uid, node_id, address, instance_id))) } pub(in super::super) async fn remember_pod_node_placement_for_execution( &self, id: SandboxId, pod: &SandboxPodView, exp: Option<(i64, super::super::store::ExpectedPodFence<'_>, Option<&str>)>, retry: PlacementRetryDisposition, ) -> Result, SubstrateError> { let Some(r) = self.resolve_pod_node_details(pod).await? else { return Ok(None); }; let (nid, p) = (r.2, Self::to_pod_placement(id, &r)); let ok = self .store .persist_pod_node_placement_for_execution(p, exp, retry) .await?; Ok((ok || exp.is_none()).then_some(nid)) } pub(in super::super) async fn remember_pod_metadata_and_placement( &self, id: SandboxId, exp: (i64, super::super::store::ExpectedPodFence<'_>), pod: &SandboxPodView, ip: Option<&str>, (with_place, retry): (bool, PlacementRetryDisposition), ) -> Result)>, SubstrateError> { let r = if with_place { self.resolve_pod_node_details(pod).await? } else { None }; let p = r.as_ref().map(|d| Self::to_pod_placement(id, d)); let (c, n) = (pod.client_id(), assigned_pod_node_name(pod)); let f = self.store.persist_pod_metadata_and_placement( id, exp, (pod.uid(), ip, n, c.as_ref()), (p, retry), ); f.await } fn to_pod_placement<'a>(sandbox_id: SandboxId, d: &'a NodeDetails<'a>) -> PodNodePlacement<'a> { PodNodePlacement { sandbox_id, node_name: d.0, node_uid: &d.1, node_id: d.2, role: SpaceNodeRole::Worker, address: Some(&d.3), instance_id: d.4.as_ref(), } } /// 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 expected_uid = row.pod_uid.as_ref().map(PodUid::as_str); let pod = match self .read_cached_sandbox_pod_for_uid( &row.pod_name, expected_uid, self.budgets.reflector_wait, CacheTrustPolicy::SettledOrHealthyWatch, ) .await { Some(pod) => pod, None => match self .fetch_sandbox_pod_bounded( &row.pod_name, expected_uid, CacheTrustPolicy::SettledOrHealthyWatch, "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() || expected_uid != 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)) } pub(in crate::controllers::substrate::kubernetes) async fn resolve_pod_ip_settled( &self, sandbox_id: SandboxId, ) -> Result, SubstrateError> { Ok(self .resolve_pod_instance_settled(sandbox_id) .await? .map(|pod| pod.ip)) } /// Bound direct pod GETs without putting the store mutations in the /// resolver under the shorter GET timeout. A timed-out read leaves the /// IP unresolved so readiness can keep observing the shared reflector. /// 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_with_mode( sandbox_id, target, ReadinessLookupMode::SettledOrGet { deadline: Some(deadline), }, None, ) .await } pub(in crate::controllers::substrate::kubernetes) async fn resolve_cached_pod_ip_for_readiness( &self, sandbox_id: SandboxId, target: &PodProxyWaitTarget<'_>, deadline: Instant, ) -> Result, SubstrateError> { self.resolve_pod_ip_with_mode( sandbox_id, target, ReadinessLookupMode::CachedPrecheck { deadline, target }, None, ) .await } pub(in crate::controllers::substrate::kubernetes) async fn fallback_resolve_pod_ip_for_readiness( &self, sandbox_id: SandboxId, target: &PodProxyWaitTarget<'_>, deadline: Instant, observed: &tokio::sync::watch::Sender>, ) -> Result, SubstrateError> { let mut timed_out = false; let resolved = self .resolve_pod_ip_with_mode( sandbox_id, target, ReadinessLookupMode::ImmediateGetFallback { deadline, target, observed, }, Some(&mut timed_out), ) .await?; Ok(if timed_out { PodGet::TimedOut } else { PodGet::Observed(resolved) }) } async fn resolve_pod_ip_with_mode<'a>( &self, sandbox_id: SandboxId, target: &PodProxyWaitTarget<'a>, mode: ReadinessLookupMode<'a>, timed_out: Option<&mut bool>, ) -> Result, SubstrateError> { Ok(self .resolve_pod_instance_inner(sandbox_id, mode, timed_out, CacheTrustPolicy::SettledOnly) .await? .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_inner( sandbox_id, ReadinessLookupMode::SettledOrGet { deadline: None }, None, CacheTrustPolicy::SettledOrHealthyWatch, ) .await } /// Like [`Self::resolve_pod_instance`], but requires an IP-settled view on /// cached `Pending` entries so callers that treat `Ok(None)` as "no live /// runtime" re-verify via `pod_events` / bounded `GET` before skipping RPCs. pub(in crate::controllers::substrate::kubernetes) async fn resolve_pod_instance_settled( &self, sandbox_id: SandboxId, ) -> Result, SubstrateError> { self.resolve_pod_instance_inner( sandbox_id, ReadinessLookupMode::SettledOrGet { deadline: None }, None, CacheTrustPolicy::SettledOnly, ) .await } async fn resolve_pod_instance_inner( &self, sandbox_id: SandboxId, mode: ReadinessLookupMode<'_>, timed_out: Option<&mut bool>, policy: CacheTrustPolicy, ) -> Result, SubstrateError> { let readiness_deadline = mode.deadline(); 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 observe_in_flight_readiness_only = match mode { ReadinessLookupMode::CachedPrecheck { target, .. } | ReadinessLookupMode::ImmediateGetFallback { target, .. } => { if row.generation != target.generation { return Ok(None); } if let (Some(expected_uid), Some(row_uid)) = (target.pod_uid, row.pod_uid.as_ref()) && row_uid.as_str() != expected_uid { return Ok(None); } (row.state == ActiveExecutionState::Creating && target.pod_uid.is_some() && row.pod_uid.is_none()) || row.state == ActiveExecutionState::Recovering } ReadinessLookupMode::SettledOrGet { .. } => false, }; let pod = if execution_pod_lookup_in_flight(row.state) && !observe_in_flight_readiness_only { 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, ResolutionGetKind::FreshConfirmation, "failed to verify stale creating restore pod", ) .await? } else { match mode { ReadinessLookupMode::SettledOrGet { deadline } => { let reflector_wait = deadline.map_or(self.budgets.reflector_wait, |deadline| { self.budgets .reflector_wait .min(deadline.saturating_duration_since(Instant::now())) }); let expected_uid = row.pod_uid.as_ref().map(PodUid::as_str); if let Some(pod) = self .read_cached_sandbox_pod_for_uid( &row.pod_name, expected_uid, reflector_wait, policy, ) .await { PodGet::Observed(Some(pod)) } else { self.get_pod_for_resolution( &row.pod_name, readiness_deadline, ResolutionGetKind::CoalescedFallback { expected_uid, policy, }, "failed to query K8s pod", ) .await? } } ReadinessLookupMode::CachedPrecheck { deadline, target } => { let eu = row.pod_uid.as_ref().map(PodUid::as_str); let cached = self.lookup_sandbox_pod(&row.pod_name); if let Some(pod) = cached.filter(|p| eu.is_none_or(|u| p.uid() == Some(u))) { if !target.names(&pod) { return Ok(None); } let has_ip = current_pod_ip_with_source( &pod, row.pod_uid.as_ref(), row.pod_ip.as_deref(), )? .is_some(); if has_ip || terminal_pod_phase(&pod).is_some() || unbound_unschedulable_message(&pod).is_some() { PodGet::Observed(Some(pod)) } else { return Ok(None); } } else if row.pod_ip.is_some() { self.get_pod_for_resolution( &row.pod_name, Some(deadline), ResolutionGetKind::CoalescedFallback { expected_uid: eu, policy, }, "failed to query K8s pod", ) .await? } else { return Ok(None); } } ReadinessLookupMode::ImmediateGetFallback { deadline, target, .. } => { let expected_uid = row.pod_uid.as_ref().map(PodUid::as_str); if let Some(pod) = self.lookup_sandbox_pod(&row.pod_name) && target.names(&pod) && expected_uid.is_none_or(|uid| pod.uid() == Some(uid)) && pod_status_is_settled(&pod) { PodGet::Observed(Some(pod)) } else { self.get_pod_for_resolution( &row.pod_name, Some(deadline), ResolutionGetKind::CoalescedFallback { expected_uid, policy, }, "failed to query K8s pod", ) .await? } } } }; let PodGet::Observed(pod) = pod else { if let Some(flag) = timed_out { *flag = true; } return Ok(None); }; let pod = match pod { Some(pod) => pod, None => { if observe_in_flight_readiness_only { return Ok(None); } // The filtered reflector store excludes terminal pods. During // suspend that creates a cache miss before a finalizer-blocked // Kubernetes object is actually absent, so a cache miss alone // must never authorize execution retirement. let PodGet::Observed(pod) = self .get_pod_for_resolution( &row.pod_name, readiness_deadline, ResolutionGetKind::FreshConfirmation, "failed to verify missing Kubernetes sandbox pod", ) .await? else { if let Some(flag) = timed_out { *flag = true; } return Ok(None); }; match pod { Some(pod) => pod, None => { if row.state == ActiveExecutionState::RecoveryFailed { match self .store .converge_failed_recovery_after_pod_absence_if_generation( sandbox_id, row.generation, row.pod_uid.as_ref().map(PodUid::as_str), row.pod_ip.as_deref(), row.k8s_node_name.as_deref(), ) .await? { FailedRecoveryPodAbsenceOutcome::NotMatched => {} FailedRecoveryPodAbsenceOutcome::ClaimPreserved => tracing::debug!( sandbox_id = %sandbox_id, generation = row.generation, pod_name = %row.pod_name, "failed recovery pod is absent; clearing cached route and preserving execution claim" ), FailedRecoveryPodAbsenceOutcome::ConvergedSuspended => { tracing::info!( sandbox_id = %sandbox_id, generation = row.generation, pod_name = %row.pod_name, "failed recovery pod is absent; converged current durable snapshot to suspended" ) } } return Ok(None); } if row.lifecycle == SandboxLifecycle::Suspending.as_str() && let Some(pod_uid) = row.pod_uid.as_ref() && self .store .finalize_missing_suspending_pod_with_current_snapshot( sandbox_id, row.generation, pod_uid.as_str(), ) .await? { tracing::info!( sandbox_id = %sandbox_id, generation = row.generation, pod_name = %row.pod_name, "finalized suspended sandbox after its pod disappeared with a current durable snapshot" ); return Ok(None); } // A drain-held cleanup clears nothing and logs that itself. match self .store .forget_missing_pod_tracking_if_unchanged( sandbox_id, &row, row.pod_uid.as_ref().map(PodUid::as_str), ) .await? { PodTrackingCleanup::ExecutionChanged => { return Err(SubstrateError::LockContention { message: "sandbox execution changed concurrently during missing-pod cleanup" .to_string(), }); } PodTrackingCleanup::Deferred(PodTeardownOwner::NodeDrain(_)) => {} PodTrackingCleanup::Retired | PodTrackingCleanup::Unmatched | PodTrackingCleanup::Deferred(PodTeardownOwner::Suspend) => { tracing::warn!( sandbox_id = %sandbox_id, pod_name = %row.pod_name, cached_pod_ip = ?row.pod_ip, "tracked Kubernetes sandbox pod is authoritatively absent; clearing cached pod IP" ); } } return Ok(None); } } } }; if let ReadinessLookupMode::CachedPrecheck { target, .. } | ReadinessLookupMode::ImmediateGetFallback { target, .. } = mode && !target.names(&pod) { return Ok(None); } if observe_in_flight_readiness_only && let Some(row_uid) = row.pod_uid.as_ref() && pod.uid() != Some(row_uid.as_str()) { return Ok(None); } let pod = if let Some(cached_phase) = terminal_pod_phase(&pod) { if observe_in_flight_readiness_only { return Ok(None); } let PodGet::Observed(authoritative_pod) = self .get_pod_for_resolution( &row.pod_name, readiness_deadline, ResolutionGetKind::FreshConfirmation, "failed to verify terminal Kubernetes sandbox pod", ) .await? else { if let Some(flag) = timed_out { *flag = true; } return Ok(None); }; if let ReadinessLookupMode::CachedPrecheck { target, .. } | ReadinessLookupMode::ImmediateGetFallback { target, .. } = mode && authoritative_pod .as_deref() .is_some_and(|auth_pod| !target.names(auth_pod)) { return Ok(None); } if let Some(phase) = terminal_cleanup_phase_after_uncached_check( cached_phase, authoritative_pod.as_deref(), ) { let publication_grace_remaining = authoritative_pod .as_ref() .filter(|_| phase == TerminalPodPhase::Succeeded) .and_then(|pod| { succeeded_pod_publication_grace_remaining(pod, jiff::Timestamp::now()) }); 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)); } tracing::info!( sandbox_id = %sandbox_id, pod_name = %row.pod_name, 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" ); self.delete_pod_and_forget_tracking( sandbox_id, &row.pod_name, row.generation, PodTrackingCleanupCause::MissingPodObservation, ) .await?; 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) { return Err(SubstrateError::Unschedulable { message: format!("sandbox pod is unschedulable: {message}"), }); } let pod_fence = row.pod_fence(); let current_node_name = assigned_pod_node_name(&pod).map(str::to_owned); let bail_noop = |what: &'static str| { if let ReadinessLookupMode::ImmediateGetFallback { observed, .. } = mode { observed.send_replace(None); } tracing::warn!(sandbox_id = %sandbox_id, generation = row.generation, "{what} write no-oped after pod lookup: the execution was retired or replaced mid-flight"); None }; let pod_uid = pod.uid().map(str::to_owned); 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 should_persist_metadata = if observe_in_flight_readiness_only && row.state == ActiveExecutionState::Creating { pod_ip_string.is_some() } else { row.pod_uid.as_ref().map(PodUid::as_str) != pod_uid.as_deref() || row.pod_ip.as_deref() != pod_ip_string.as_deref() }; let needs_placement = row.k8s_node_name.as_deref() != current_node_name.as_deref(); let disp = PlacementRetryDisposition::RetryDuplicatesExecution; if should_persist_metadata { let wp = needs_placement && current_node_name.is_some(); let (f, ip) = ((row.generation, pod_fence), pod_ip_string.as_deref()); let r = self.remember_pod_metadata_and_placement(sandbox_id, f, &pod, ip, (wp, disp)); match r.await { Ok(Some(_)) => {} Ok(None) => return Ok(bail_noop("pod metadata")), Err(err) if wp => return Err(err), Err(e) => tracing::warn!(%sandbox_id, ?e, "failed to persist pod metadata"), } } else if needs_placement && current_node_name.is_some() { let exp = Some((row.generation, pod_fence, pod.uid())); let r = self.remember_pod_node_placement_for_execution(sandbox_id, &pod, exp, disp); if r.await?.is_none() { return Ok(bail_noop("pod placement")); } } if let ReadinessLookupMode::ImmediateGetFallback { observed, .. } = mode && current_node_name.is_some() { observed.send_replace(Some((*pod).clone())); } if !should_persist_metadata && 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" ); } } Ok(resolved.map(|(ip, source)| ResolvedPodInstance { ip, source, pod_uid: pod_uid.as_deref().and_then(|uid| PodUid::parse(uid).ok()), generation: row.generation, sandbox_restoring: is_restoring_lifecycle(&row.lifecycle), })) } } #[cfg(test)] mod tests;