From 94df2a8baf8fd735e29635170abe03365c55c4fd Mon Sep 17 00:00:00 2001 From: Gigi Sayfan Date: Sun, 29 Nov 2026 19:23:39 -0800 Subject: [PATCH] [space-api] split wait_ready and create_readiness modules --- .../create_readiness.rs | 976 +---------------- .../create_readiness/node_refusal.rs | 977 ++++++++++++++++++ .../substrate/kubernetes/wait_ready.rs | 661 +----------- .../wait_ready/connected_command_ready.rs | 661 ++++++++++++ 4 files changed, 1649 insertions(+), 1626 deletions(-) create mode 100644 crates/l40_api/api/src/controllers/substrate/kubernetes/adapter_characterization_tests/create_readiness/node_refusal.rs create mode 100644 crates/l40_api/api/src/controllers/substrate/kubernetes/wait_ready/connected_command_ready.rs diff --git a/crates/l40_api/api/src/controllers/substrate/kubernetes/adapter_characterization_tests/create_readiness.rs b/crates/l40_api/api/src/controllers/substrate/kubernetes/adapter_characterization_tests/create_readiness.rs index 1b5b127ad2..e79a9b293d 100644 --- a/crates/l40_api/api/src/controllers/substrate/kubernetes/adapter_characterization_tests/create_readiness.rs +++ b/crates/l40_api/api/src/controllers/substrate/kubernetes/adapter_characterization_tests/create_readiness.rs @@ -7,7 +7,7 @@ //! scripted apiserver and worker. use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex, OnceLock}; +use std::sync::{Arc, Mutex}; use axum::http::{Method, StatusCode}; use futures_util::FutureExt as _; @@ -18,8 +18,8 @@ use sqlx::{Postgres, Transaction}; use super::super::scripted_test_doubles::{ CallObserver, KubeReply, KubeRequest, ScriptedReply, ScriptedWorker, ScriptedWorkerConfig, - kube_status, pod_path, pod_reply, query_field_selectors, requests_matching, - scripted_kube_client, scripted_kube_client_async, start_scripted_worker, + kube_status, pod_path, pod_reply, requests_matching, scripted_kube_client, + scripted_kube_client_async, start_scripted_worker, }; use super::super::tests::{insert_test_sandbox_row, substrate_with_inventory_caches_and_pool}; use super::*; @@ -654,975 +654,7 @@ async fn create_readiness_failure_keeps_or_releases_only_what_its_arm_owns( Ok(()) } -// ── node refusal ──────────────────────────────────────────────────────────── - -const EVENTS_PATH: &str = "/api/v1/namespaces/space/events"; - -/// Kubelet's event for a sandbox whose disk is smaller than its template's -/// rootfs, as the shim and node-manager word it. -const INVALID_DISK_REFUSAL: &str = "Failed to create pod sandbox: rpc error: code = \ - InvalidArgument desc = failed to start sandbox \"0123\": failed to create containerd task: \ - failed to create shim task: sbx-manager Wake [space-err=InvalidArgument]: prepare sandbox \ - failed: code: 'Client specified an invalid argument', message: \"rootfs_size_mb=300 is \ - smaller than cloned rootfs size 451 MiB\""; - -/// A refusal another attempt can get past. -const RETRYABLE_REFUSAL: &str = "Failed to create pod sandbox: rpc error: code = Unavailable \ - desc = failed to create shim task: sbx-manager Wake [space-err=Unavailable]: node-manager \ - is restarting"; - -const MEMORY_REFUSAL: &str = "Failed to create pod sandbox: rpc error: code = ResourceExhausted \ - desc = sbx-manager Wake [space-err=ResourceExhausted]: network allocate failed: \ - node memory admission refused: insufficient node memory"; -const QUEUE_REFUSAL: &str = "Failed to create pod sandbox: rpc error: code = ResourceExhausted \ - desc = sbx-manager Wake [space-err=ResourceExhausted]: lifecycle queue full"; - -/// What the node records for the create's pod sandbox, and how the apiserver -/// answers the create's watch of those events. -#[derive(Debug, Clone, Copy, PartialEq)] -enum NodeRefusal { - /// The node refuses the request as invalid. - Invalid, - /// The node refuses for a reason another attempt can get past. - Retryable, - /// The node refuses the request as invalid, and the apiserver throttles - /// the first watch of the pod's events. - InvalidAfterThrottledWatch, - /// A memory refusal is already recorded when readiness begins, while - /// kubelet has already assigned the pod an IP on a healthy worker: the - /// assigned IP wins over the stale refusal. - MemoryAfterPodIpAssigned, - Memory, - MemoryWithFlagOff, - MemoryWithFlagUnset, - QueueFull, -} - -/// Invalid requests and opt-in memory refusals fail with the node's reason, -/// delete the pod and retire its execution, unless kubelet has already assigned -/// the pod an IP (`InvalidArgument` defers only to a reflector-cached IP so an -/// invalid request never waits on Postgres or an uncached Pod `GET`, whereas -/// pre-recorded `MemoryAdmission` checks `resolve_pod_ip_for_readiness`). Other -/// refusals leave kubelet to retry until the readiness deadline. Events come -/// from the process's one reason-filtered watch, including after the apiserver -/// throttles it, and the create reads none of its own. Same-poll lookup-error, -/// expired-deadline, and stalled-lookup arbitration in -/// `wait_for_pod_ip_assignment` are pinned by -/// `pod_ip_wait_arbitrates_refusal_boundaries`. -#[rstest::rstest] -#[case::invalid_request_fails_the_create(NodeRefusal::Invalid)] -#[case::other_refusals_wait_for_the_deadline(NodeRefusal::Retryable)] -#[case::a_throttled_watch_is_watched_again(NodeRefusal::InvalidAfterThrottledWatch)] -#[case::assigned_pod_ip_beats_prerecorded_refusal(NodeRefusal::MemoryAfterPodIpAssigned)] -#[case::memory_refusal_is_retryable(NodeRefusal::Memory)] -#[case::memory_refusal_waits_with_flag_off(NodeRefusal::MemoryWithFlagOff)] -#[case::memory_refusal_waits_by_default(NodeRefusal::MemoryWithFlagUnset)] -#[case::queue_full_keeps_kubelet_retry(NodeRefusal::QueueFull)] -#[tokio::test(flavor = "current_thread")] -async fn create_handles_node_refusal(#[case] refusal: NodeRefusal) -> TestResult { - let enabled = if matches!( - refusal, - NodeRefusal::Invalid | NodeRefusal::MemoryWithFlagOff - ) { - "false" - } else { - "true" - }; - if !crate::test_support::enter_sim_worker_process_with_owned_token_files_and(&[( - "SPACE_CREATE_FAIL_FAST_ON_NODE_REJECTION", - (refusal != NodeRefusal::MemoryWithFlagUnset).then(|| std::ffi::OsStr::new(enabled)), - )]) { - return Ok(()); - } - let pod_has_ip = refusal == NodeRefusal::MemoryAfterPodIpAssigned; - let fails_fast = matches!( - refusal, - NodeRefusal::Invalid | NodeRefusal::InvalidAfterThrottledWatch | NodeRefusal::Memory - ); - let message = match refusal { - NodeRefusal::Invalid | NodeRefusal::InvalidAfterThrottledWatch => INVALID_DISK_REFUSAL, - NodeRefusal::Memory - | NodeRefusal::MemoryAfterPodIpAssigned - | NodeRefusal::MemoryWithFlagOff - | NodeRefusal::MemoryWithFlagUnset => MEMORY_REFUSAL, - NodeRefusal::QueueFull => QUEUE_REFUSAL, - NodeRefusal::Retryable => RETRYABLE_REFUSAL, - }; - let db = pplx_space_db_test_fixtures::pg_test_db().await?; - let sandbox_id = SandboxId::new(); - insert_test_sandbox_row(&db.pool, sandbox_id, "creating").await?; - let worker = if pod_has_ip { - start_scripted_worker(ScriptedWorkerConfig::new([])).await? - } else { - start_scripted_worker(ScriptedWorkerConfig::new([( - SPACED_WAIT_READY, - ScriptedReply::Hang, - )])) - .await? - }; - - let release_on_pod_get = matches!( - refusal, - NodeRefusal::Invalid | NodeRefusal::Memory | NodeRefusal::MemoryWithFlagOff - ); - let expects_recorded_memory_refusal = matches!( - refusal, - NodeRefusal::MemoryAfterPodIpAssigned - | NodeRefusal::MemoryWithFlagOff - | NodeRefusal::MemoryWithFlagUnset - ); - let pod_name: Arc>> = Arc::default(); - let post_returned_at: Arc>> = Arc::default(); - let pod_gets = Arc::new(AtomicUsize::new(0)); - let release_refusal = Arc::new(tokio::sync::Notify::new()); - let refusal_released = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let rejections: Arc> = - Arc::default(); - let sentinel: Arc>> = - Arc::default(); - let sentinel_observed = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let sentinel_notify = Arc::new(tokio::sync::Notify::new()); - let pod_watch_opened = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let pod_watch_notify = Arc::new(tokio::sync::Notify::new()); - let event_watches = Arc::new(AtomicUsize::new(0)); - let reply_pod_name = Arc::clone(&pod_name); - let reply_post_returned_at = Arc::clone(&post_returned_at); - let reply_pod_gets = Arc::clone(&pod_gets); - let reply_release_refusal = Arc::clone(&release_refusal); - let reply_refusal_released = Arc::clone(&refusal_released); - let reply_rejections = Arc::clone(&rejections); - let reply_sentinel = Arc::clone(&sentinel); - let reply_sentinel_observed = Arc::clone(&sentinel_observed); - let reply_sentinel_notify = Arc::clone(&sentinel_notify); - let reply_pod_watch_opened = Arc::clone(&pod_watch_opened); - let reply_pod_watch_notify = Arc::clone(&pod_watch_notify); - let reply_event_watches = Arc::clone(&event_watches); - let (client, log) = scripted_kube_client_async(move |request| { - let pod_name = Arc::clone(&reply_pod_name); - let post_returned_at = Arc::clone(&reply_post_returned_at); - let pod_gets = Arc::clone(&reply_pod_gets); - let release_refusal = Arc::clone(&reply_release_refusal); - let refusal_released = Arc::clone(&reply_refusal_released); - let rejections = Arc::clone(&reply_rejections); - let sentinel = Arc::clone(&reply_sentinel); - let sentinel_observed = Arc::clone(&reply_sentinel_observed); - let sentinel_notify = Arc::clone(&reply_sentinel_notify); - let pod_watch_opened = Arc::clone(&reply_pod_watch_opened); - let pod_watch_notify = Arc::clone(&reply_pod_watch_notify); - let event_watches = Arc::clone(&reply_event_watches); - async move { - let name = pod_name.lock().unwrap().clone(); - let pending_pod = |name: &str| { - pod_reply(&sandbox_pod( - name, - &format!("{name}-uid"), - sandbox_id, - 1, - "Pending", - None, - )) - }; - let pod_state = |name: &str| { - if pod_has_ip { - pod_reply(&running_pod(name, sandbox_id, Some(WORKER_NODE))) - } else { - pending_pod(name) - } - }; - let observe_released_refusal = |name: &str| { - let refusal_released = Arc::clone(&refusal_released); - let release_refusal = Arc::clone(&release_refusal); - let rejections = Arc::clone(&rejections); - let sentinel = Arc::clone(&sentinel); - let sentinel_observed = Arc::clone(&sentinel_observed); - let sentinel_notify = Arc::clone(&sentinel_notify); - let target_uid = format!("{name}-uid"); - async move { - refusal_released.store(true, Ordering::SeqCst); - release_refusal.notify_waiters(); - let wait = sentinel.lock().unwrap().take(); - if let Some(wait) = wait { - let _ = wait.refused(false).await; - if expects_recorded_memory_refusal { - let recorded = rejections - .get() - .expect("rejection watch initialized before create") - .register(&target_uid) - .recorded(true); - if !matches!( - &recorded, - Some(SubstrateError::Unavailable { message }) - if message.contains("node memory admission refused") - ) { - return Err(kube_status( - StatusCode::INTERNAL_SERVER_ERROR, - &format!( - "expected recorded memory refusal for {target_uid}, got {recorded:?}" - ), - )); - } - } - sentinel_observed.store(true, Ordering::SeqCst); - sentinel_notify.notify_waiters(); - } - Ok(()) - } - }; - match request.method { - Method::POST if request.path == PODS_PATH => { - let name = requested_pod_name(&request); - *pod_name.lock().unwrap() = Some(name.clone()); - if !release_on_pod_get && let Err(reply) = observe_released_refusal(&name).await - { - return reply; - } - *post_returned_at.lock().unwrap() = Some(Instant::now()); - pending_pod(&name) - } - // The per-pod watch never reports an IP. - Method::GET if request.path == PODS_PATH => { - pod_watch_opened.store(true, Ordering::SeqCst); - pod_watch_notify.notify_waiters(); - KubeReply::Hang - } - Method::GET if name.as_deref().map(pod_path).as_ref() == Some(&request.path) => { - let name = name.as_deref().expect("the pod was created"); - if release_on_pod_get && pod_gets.fetch_add(1, Ordering::SeqCst) == 0 { - if let Err(reply) = observe_released_refusal(name).await { - return reply; - } - KubeReply::Hang - } else { - pod_state(name) - } - } - Method::GET if request.path == EVENTS_PATH => { - let reason_only_selector = query_field_selectors(request.query.as_deref()) - .as_slice() - == ["reason=FailedCreatePodSandBox"]; - let watching = request - .query - .as_deref() - .is_some_and(|query| query.contains("watch=true")); - if !watching { - return KubeReply::Json( - StatusCode::OK, - serde_json::json!({ - "apiVersion": "v1", - "kind": "EventList", - "metadata": { "resourceVersion": "1" }, - "items": [], - }), - ); - } - // Real Kubernetes excludes `Warning` Events when an extra - // predicate (such as `type=Normal`) narrows the selector. - if !reason_only_selector { - return KubeReply::Hang; - } - let watch = event_watches.fetch_add(1, Ordering::SeqCst); - if refusal == NodeRefusal::InvalidAfterThrottledWatch && watch == 0 { - return kube_status(StatusCode::TOO_MANY_REQUESTS, "TooManyRequests"); - } - let first_refusal_watch = - usize::from(refusal == NodeRefusal::InvalidAfterThrottledWatch); - if watch > first_refusal_watch { - return KubeReply::Hang; - } - // The watch opened before the create: the node's refusal - // arrives once the target phase releases it, followed by a - // sentinel event so non-fail-fast and pre-recorded cases - // confirm the tracker processed the pod's event in stream - // order. - let name = loop { - let notified = release_refusal.notified(); - tokio::pin!(notified); - notified.as_mut().enable(); - if refusal_released.load(Ordering::SeqCst) - && let Some(name) = pod_name.lock().unwrap().clone() - { - break name; - } - notified.await; - }; - KubeReply::WatchEvents(vec![ - serde_json::json!({ - "type": "ADDED", - "object": { - "apiVersion": "v1", - "kind": "Event", - "metadata": { - "name": format!("{name}.1"), - "namespace": "space", - "resourceVersion": "2", - }, - "involvedObject": { - "kind": "Pod", - "name": name, - "uid": format!("{name}-uid"), - }, - "reason": "FailedCreatePodSandBox", - "message": message, - "type": "Warning", - }, - }), - serde_json::json!({ - "type": "ADDED", - "object": { - "apiVersion": "v1", - "kind": "Event", - "metadata": { - "name": "sentinel.1", - "namespace": "space", - "resourceVersion": "3", - }, - "involvedObject": { - "kind": "Pod", - "name": "sentinel", - "uid": "sentinel-uid", - }, - "reason": "FailedCreatePodSandBox", - "message": INVALID_DISK_REFUSAL, - "type": "Warning", - }, - }), - ]) - } - Method::DELETE if name.as_deref().map(pod_path).as_ref() == Some(&request.path) => { - kube_status(StatusCode::OK, "Success") - } - _ => kube_status(StatusCode::BAD_REQUEST, "BadRequest"), - } - } - }); - let mut substrate = - substrate_on(db.pool.clone(), client, &worker).with_pod_sandbox_rejection_watch(); - assert!( - substrate.task_tracker.is_empty(), - "the shared refusal watch runs on its own handle-scoped tracker" - ); - if refusal == NodeRefusal::Invalid { - // `run_with` cancels `shutdown_token` at SIGTERM before draining - // in-flight HTTP creates; the refusal watch stays live until the - // substrate drops. - substrate.shutdown_token.cancel(); - tokio::task::yield_now().await; - } - let _ = rejections.set(substrate.pod_sandbox_rejections.detached_handle()); - if !fails_fast || pod_has_ip { - *sentinel.lock().unwrap() = Some(substrate.pod_sandbox_rejections.register("sentinel-uid")); - } - let readiness_timeout = Duration::from_secs(60); - substrate.k8s.create_data_plane_ready_timeout = readiness_timeout; - // Keep readiness budgets well above wall-clock scheduling jitter; non-fail-fast - // cases advance Tokio's clock only after the sentinel confirms the refusal was - // observed while the create waited. - substrate.budgets = phase_ending_budgets(substrate.budgets); - substrate.budgets.readiness_pod_get = Duration::from_secs(10); - let inputs = CreateInputs::new(); - let template_ref = inputs.template_ref(); - - let started = Instant::now(); - let create_fut = substrate.create_execution(inputs.create_request(sandbox_id, &template_ref)); - tokio::pin!(create_fut); - let outcome = if !fails_fast && !pod_has_ip { - tokio::time::timeout(Duration::from_secs(10), async { - loop { - let notified = sentinel_notify.notified(); - tokio::pin!(notified); - notified.as_mut().enable(); - if sentinel_observed.load(Ordering::SeqCst) { - break Ok::<(), String>(()); - } - tokio::select! { - res = &mut create_fut => { - break Err(format!( - "create settled before the refusal sentinel was observed: {:?}", - res.err() - )); - } - () = &mut notified => {} - } - } - }) - .await - .map_err(|_| "refusal sentinel must be observed while create waits")??; - if expects_recorded_memory_refusal { - let name = pod_name - .lock() - .unwrap() - .clone() - .expect("the pod was created before releasing the refusal"); - let recorded = substrate - .pod_sandbox_rejections - .register(&format!("{name}-uid")) - .recorded(true); - assert!( - matches!( - &recorded, - Some(SubstrateError::Unavailable { message }) - if message.contains("node memory admission refused") - ), - "target pod must have its memory refusal recorded before readiness proceeds: {recorded:?}" - ); - } - if release_on_pod_get { - let during_pod_get = - std::future::poll_fn(|cx| std::task::Poll::Ready(create_fut.as_mut().poll(cx))) - .await; - if let std::task::Poll::Ready(res) = during_pod_get { - return Err(format!( - "non-fail-fast refusal must not end the create during the initial pod GET: {:?}", - res.err() - ) - .into()); - } - tokio::time::pause(); - tokio::time::advance(Duration::from_secs(11)).await; - tokio::time::resume(); - } - tokio::time::timeout(Duration::from_secs(10), async { - loop { - let notified = pod_watch_notify.notified(); - tokio::pin!(notified); - notified.as_mut().enable(); - if pod_watch_opened.load(Ordering::SeqCst) { - break Ok::<(), String>(()); - } - tokio::select! { - res = &mut create_fut => { - break Err(format!( - "create settled before entering the pod readiness watch: {:?}", - res.err() - )); - } - () = &mut notified => {} - } - } - }) - .await - .map_err(|_| "non-fail-fast create must enter the pod readiness watch")??; - let during_watch = - std::future::poll_fn(|cx| std::task::Poll::Ready(create_fut.as_mut().poll(cx))).await; - if let std::task::Poll::Ready(res) = during_watch { - return Err(format!( - "non-fail-fast refusal must keep waiting in the pod readiness watch: {:?}", - res.err() - ) - .into()); - } - let post_at = post_returned_at - .lock() - .unwrap() - .expect("the pod was created before entering the readiness watch"); - tokio::time::pause(); - let before_deadline = post_at + readiness_timeout - Duration::from_secs(2); - assert!( - Instant::now() < before_deadline, - "watch setup overran the {readiness_timeout:?} readiness budget" - ); - tokio::select! { - res = &mut create_fut => { - tokio::time::resume(); - return Err(format!( - "non-fail-fast refusal settled before its {readiness_timeout:?} readiness deadline: {:?}", - res.err() - ) - .into()); - } - () = tokio::time::sleep_until(before_deadline) => {} - } - tokio::time::resume(); - if let Ok(res) = tokio::time::timeout(Duration::from_millis(50), &mut create_fut).await { - return Err(format!( - "non-fail-fast refusal settled before its {readiness_timeout:?} readiness deadline: {:?}", - res.err() - ) - .into()); - } - assert!( - requests_matching(&log, &Method::DELETE).is_empty(), - "pod must not be torn down before its {readiness_timeout:?} readiness deadline" - ); - tokio::time::pause(); - tokio::time::advance(Duration::from_secs(5)).await; - tokio::time::resume(); - tokio::time::timeout(Duration::from_secs(10), &mut create_fut) - .await - .map_err(|_| "the create must end once its readiness deadline elapses")? - } else { - tokio::time::timeout(Duration::from_secs(15), &mut create_fut) - .await - .map_err(|_| "the create must end")? - }; - let elapsed = started.elapsed(); - let pod_name = pod_name - .lock() - .unwrap() - .clone() - .expect("the pod was created"); - substrate.pod_sandbox_rejections.shutdown().await; - substrate.shutdown_token.cancel(); - substrate.task_tracker.close(); - substrate.task_tracker.wait().await; - let event_reads: Vec<_> = requests_matching(&log, &Method::GET) - .into_iter() - .filter(|request| request.path == EVENTS_PATH) - .collect(); - assert!(!event_reads.is_empty(), "the process watches refusals"); - for read in &event_reads { - let query = read.query.as_deref().unwrap_or_default(); - assert_eq!( - query_field_selectors(read.query.as_deref()), - ["reason=FailedCreatePodSandBox"], - "every Events read uses only the reason-filtered selector: {query}" - ); - assert!( - !query.contains(&pod_name) && !query.contains("involvedObject"), - "every read is the process's watch, none the create's own: {query}" - ); - } - if pod_has_ip { - let created = outcome.map_err(|err| { - format!("an assigned pod IP must beat a pre-recorded refusal: {err:?}") - })?; - assert_eq!( - created - .binding - .expect("cold create binds its pod") - .execution_object_id, - format!("{pod_name}-uid") - ); - assert!( - requests_matching(&log, &Method::DELETE).is_empty(), - "a ready pod with an assigned IP must not be deleted" - ); - assert_eq!(active_execution_count(&db.pool, sandbox_id).await?, 1); - return Ok(()); - } - let error = outcome.err().ok_or("the pod never got an IP")?; - if !fails_fast { - assert!( - sentinel_observed.load(Ordering::SeqCst), - "the refusal event must be observed before accepting a readiness timeout" - ); - assert!( - matches!( - error, - SubstrateError::Timeout { - phase: Some(WaitReadyTimeoutPhase::PodNeverReady), - .. - } - ), - "expected the pod-IP readiness deadline (PodNeverReady), got {error:?}" - ); - return Ok(()); - } - - match (&error, refusal) { - (SubstrateError::Unavailable { message }, NodeRefusal::Memory) => { - assert!(message.contains("node memory admission refused")); - } - ( - SubstrateError::InvalidRequest { message }, - NodeRefusal::Invalid | NodeRefusal::InvalidAfterThrottledWatch, - ) => { - assert!(message.contains("smaller than cloned rootfs size 451 MiB")); - } - _ => panic!("expected the node's refusal, got {error:?}"), - } - // Far inside the production readiness budget, with room for a throttled - // watch's jittered DefaultBackoff and a loaded runner. The watch assertion - // above, not this bound, is what rules out polling. - assert!( - elapsed < Duration::from_secs(5), - "the refusal, not the readiness budget or initial pod GET timeout, ends the create: {elapsed:?}" - ); - let deletes = requests_matching(&log, &Method::DELETE); - let [delete] = deletes.as_slice() else { - panic!("expected one pod delete, got {deletes:?}"); - }; - assert_eq!(delete.path, pod_path(&pod_name)); - assert_eq!( - active_execution_count(&db.pool, sandbox_id).await?, - 0, - "the execution must be retired" - ); - Ok(()) -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum RefusalBoundary { - /// The initial Pod `GET` fails with a 503 on the same poll that records a - /// refusal: `biased;` polls the lookup arm first and must still surface the - /// recorded refusal rather than the 503 lookup error. - LookupErrorAndRefusalReadyTogether, - /// The pod-IP wait deadline expires on the same poll that records a - /// refusal: `biased;` polls `timeout_at` first (`resolved = None`) and must - /// still surface the recorded refusal rather than `Ok(None)`. - ExpiredDeadlineAndRefusalReadyTogether, - /// A pre-recorded memory refusal runs its IP-resolution precheck while the - /// execution table is locked past `deadline`: `timeout_at(deadline, ...)` - /// ends the precheck and surfaces the recorded refusal instead of stalling. - StalledPrecheckBoundsAtDeadline, - /// A memory refusal arrives after `wait_for_pod_ip_assignment` has already - /// started with a cached pod IP while the execution table is locked: the - /// lookup keeps running until `deadline` so the cached IP can still win, and - /// then bounds at `deadline` with the recorded refusal instead of stalling. - ConcurrentRefusalBoundsCachedIpStalledLookup, - /// Same concurrent memory refusal while `wait_for_pod_ip_assignment` is - /// parked on the locked execution table with a cached pod IP, except the - /// lock releases before `deadline`: the kept in-flight resolver finishes - /// and returns the cached pod IP rather than dropping the lookup for the - /// refusal. - ConcurrentRefusalLetsCachedIpWinBeforeDeadline, -} - -#[rstest::rstest] -#[case::lookup_error_yields_to_recorded_refusal( - RefusalBoundary::LookupErrorAndRefusalReadyTogether -)] -#[case::expired_deadline_yields_to_recorded_refusal( - RefusalBoundary::ExpiredDeadlineAndRefusalReadyTogether -)] -#[case::stalled_precheck_bounds_at_deadline_and_returns_refusal( - RefusalBoundary::StalledPrecheckBoundsAtDeadline -)] -#[case::concurrent_refusal_defers_for_cached_ip_then_bounds_at_deadline( - RefusalBoundary::ConcurrentRefusalBoundsCachedIpStalledLookup -)] -#[case::concurrent_refusal_lets_cached_ip_win_before_deadline( - RefusalBoundary::ConcurrentRefusalLetsCachedIpWinBeforeDeadline -)] -#[tokio::test(flavor = "current_thread")] -async fn pod_ip_wait_arbitrates_refusal_boundaries( - #[case] boundary: RefusalBoundary, -) -> TestResult { - let db = pplx_space_db_test_fixtures::pg_test_db().await?; - let sandbox_id = SandboxId::new(); - let pod_name = "space-sbx-refusal-boundary-g1"; - let pod_uid = "space-sbx-refusal-boundary-g1-uid"; - insert_test_sandbox_row(&db.pool, sandbox_id, "creating").await?; - sqlx::query(sql!( - "INSERT INTO sandbox_k8s_executions - (sandbox_id, generation, pod_name, pod_namespace, pod_uid, state, active) - VALUES ($1, 1, $2, 'space', $3, 'running', TRUE)" - )) - .bind(sandbox_id) - .bind(pod_name) - .bind(pod_uid) - .execute(&db.pool) - .await?; - - let make_refusal_event = |message: &str| -> k8s_openapi::api::core::v1::Event { - serde_json::from_value(serde_json::json!({ - "apiVersion": "v1", - "kind": "Event", - "metadata": { - "name": "refusal-boundary.1", - "namespace": "space", - "resourceVersion": "2", - }, - "involvedObject": { - "kind": "Pod", - "name": pod_name, - "uid": pod_uid, - }, - "reason": "FailedCreatePodSandBox", - "message": message, - "type": "Warning", - })) - .expect("valid refusal Event JSON") - }; - - let cached_pods = if matches!( - boundary, - RefusalBoundary::ConcurrentRefusalBoundsCachedIpStalledLookup - | RefusalBoundary::ConcurrentRefusalLetsCachedIpWinBeforeDeadline - ) { - vec![running_pod(pod_name, sandbox_id, Some(WORKER_NODE))] - } else { - Vec::new() - }; - let mut substrate = - substrate_with_inventory_caches_and_pool(cached_pods, vec![worker_node()], db.pool.clone()); - substrate.budgets.reflector_wait = Duration::ZERO; - let rejections = substrate.pod_sandbox_rejections.clone(); - let wall_now = jiff::Timestamp::now(); - - let pod_watch_opened = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let pod_watch_notify = Arc::new(tokio::sync::Notify::new()); - let client = match boundary { - RefusalBoundary::LookupErrorAndRefusalReadyTogether => { - let rejections = rejections.clone(); - let event = make_refusal_event(INVALID_DISK_REFUSAL); - let (client, _) = scripted_kube_client(move |request| { - if request.method == Method::GET && request.path == pod_path(pod_name) { - rejections.observe(&event, wall_now, Instant::now()); - kube_status(StatusCode::SERVICE_UNAVAILABLE, "ServiceUnavailable") - } else { - kube_status(StatusCode::BAD_REQUEST, "BadRequest") - } - }); - client - } - RefusalBoundary::ExpiredDeadlineAndRefusalReadyTogether => { - let pending = sandbox_pod(pod_name, pod_uid, sandbox_id, 1, "Pending", None); - let opened = Arc::clone(&pod_watch_opened); - let notify = Arc::clone(&pod_watch_notify); - let (client, _) = scripted_kube_client(move |request| { - if request.method == Method::GET && request.path == pod_path(pod_name) { - pod_reply(&pending) - } else if request.method == Method::GET && request.path == PODS_PATH { - opened.store(true, Ordering::SeqCst); - notify.notify_waiters(); - KubeReply::Hang - } else { - kube_status(StatusCode::BAD_REQUEST, "BadRequest") - } - }); - client - } - RefusalBoundary::StalledPrecheckBoundsAtDeadline - | RefusalBoundary::ConcurrentRefusalBoundsCachedIpStalledLookup - | RefusalBoundary::ConcurrentRefusalLetsCachedIpWinBeforeDeadline => { - let (client, _) = scripted_kube_client(|_| KubeReply::Hang); - client - } - }; - substrate.k8s.client = client; - - let mut table_lock = None; - if matches!( - boundary, - RefusalBoundary::StalledPrecheckBoundsAtDeadline - | RefusalBoundary::ConcurrentRefusalBoundsCachedIpStalledLookup - | RefusalBoundary::ConcurrentRefusalLetsCachedIpWinBeforeDeadline - ) { - if boundary == RefusalBoundary::StalledPrecheckBoundsAtDeadline { - rejections.observe( - &make_refusal_event(MEMORY_REFUSAL), - wall_now, - Instant::now(), - ); - } - let mut tx = db.pool.begin().await?; - sqlx::query(sql!( - "LOCK TABLE sandbox_k8s_executions IN ACCESS EXCLUSIVE MODE" - )) - .execute(&mut *tx) - .await?; - table_lock = Some(tx); - } - - let refusal = ( - substrate.pod_sandbox_rejections.register(pod_uid), - matches!( - boundary, - RefusalBoundary::StalledPrecheckBoundsAtDeadline - | RefusalBoundary::ConcurrentRefusalBoundsCachedIpStalledLookup - | RefusalBoundary::ConcurrentRefusalLetsCachedIpWinBeforeDeadline - ), - ); - let target = super::super::wait_ready::PodProxyWaitTarget { - pod_name, - pod_uid: Some(pod_uid), - generation: 1, - }; - let outcome: Result<_, String> = async { - let deadline = Instant::now() + Duration::from_secs(5); - let wait_fut = substrate.wait_for_pod_ip_assignment( - crate::metrics::sandbox::api::SandboxApiMetricIdentity::ecw("create"), - sandbox_id, - &target, - deadline, - "create", - Some(&refusal), - ); - tokio::pin!(wait_fut); - async fn assert_stalled_lookup_settles_at_deadline( - mut wait_fut: std::pin::Pin<&mut F>, - deadline: Instant, - label: &'static str, - ) -> Result - where - F: std::future::Future, - F::Output: std::fmt::Debug, - { - let margin = Duration::from_millis(50); - tokio::time::pause(); - let remaining = deadline.saturating_duration_since(Instant::now()); - if remaining <= Duration::from_secs(4) { - tokio::time::resume(); - return Err(format!( - "{label} consumed too much of deadline before clock pause: {remaining:?}" - )); - } - tokio::time::advance(remaining - margin).await; - let before_deadline = - std::future::poll_fn(|cx| std::task::Poll::Ready(wait_fut.as_mut().poll(cx))).await; - if let std::task::Poll::Ready(res) = before_deadline { - tokio::time::resume(); - return Err(format!( - "{label} must remain pending {margin:?} before deadline: {res:?}" - )); - } - let timed = tokio::time::timeout(margin * 2, &mut wait_fut).await; - let settled_at = Instant::now(); - tokio::time::resume(); - let res = - timed.map_err(|_| format!("{label} must settle within {margin:?} after deadline"))?; - if settled_at < deadline || settled_at > deadline + margin { - return Err(format!( - "{label} settled outside [deadline, deadline + {margin:?}]: \ - after_deadline={:?}", - settled_at.checked_duration_since(deadline), - )); - } - Ok(res) - } - - match boundary { - RefusalBoundary::LookupErrorAndRefusalReadyTogether => { - tokio::time::timeout(Duration::from_secs(2), &mut wait_fut) - .await - .map_err(|_| "lookup-error boundary must settle immediately".to_owned()) - } - RefusalBoundary::ExpiredDeadlineAndRefusalReadyTogether => { - tokio::time::timeout(Duration::from_secs(2), async { - loop { - let notified = pod_watch_notify.notified(); - tokio::pin!(notified); - notified.as_mut().enable(); - if pod_watch_opened.load(Ordering::SeqCst) { - break Ok(()); - } - tokio::select! { - res = &mut wait_fut => { - break Err(format!( - "wait finished before pod watch opened: {res:?}" - )); - } - () = &mut notified => {} - } - } - }) - .await - .map_err(|_| "pod watch must open before deadline".to_owned())??; - tokio::time::pause(); - // Drive Tokio's timer wheel strictly past `deadline` while - // `wait_fut` stays parked so `timeout_at(deadline, raced)` is - // already ready on the very next poll; `advance` alone only - // bumps `Instant::now()` without firing the timer entry. - tokio::time::sleep_until(deadline + Duration::from_millis(10)).await; - rejections.observe( - &make_refusal_event(INVALID_DISK_REFUSAL), - wall_now, - Instant::now(), - ); - let polled = - std::future::poll_fn(|cx| std::task::Poll::Ready(wait_fut.as_mut().poll(cx))) - .await; - tokio::time::resume(); - match polled { - std::task::Poll::Ready(res) => Ok(res), - std::task::Poll::Pending => Err( - "expired-deadline boundary must settle on the first poll once both timeout and refusal are ready" - .to_owned(), - ), - } - } - RefusalBoundary::StalledPrecheckBoundsAtDeadline => { - if tokio::time::timeout(Duration::from_millis(15), &mut wait_fut) - .await - .is_ok() - { - return Err( - "stalled precheck must park on the locked execution table before deadline" - .to_owned(), - ); - } - assert_stalled_lookup_settles_at_deadline(wait_fut, deadline, "stalled precheck") - .await - } - RefusalBoundary::ConcurrentRefusalBoundsCachedIpStalledLookup - | RefusalBoundary::ConcurrentRefusalLetsCachedIpWinBeforeDeadline => { - if tokio::time::timeout(Duration::from_millis(15), &mut wait_fut) - .await - .is_ok() - { - return Err( - "initial lookup must park on the locked execution table before refusal arrives" - .to_owned(), - ); - } - rejections.observe( - &make_refusal_event(MEMORY_REFUSAL), - wall_now, - Instant::now(), - ); - let immediate = - std::future::poll_fn(|cx| std::task::Poll::Ready(wait_fut.as_mut().poll(cx))) - .await; - if let std::task::Poll::Ready(res) = immediate { - return Err(format!( - "a cached pod IP must keep the lookup running until deadline: {res:?}" - )); - } - if boundary == RefusalBoundary::ConcurrentRefusalBoundsCachedIpStalledLookup { - assert_stalled_lookup_settles_at_deadline( - wait_fut, - deadline, - "concurrent refusal", - ) - .await - } else { - if let Some(tx) = table_lock.take() { - tx.rollback() - .await - .map_err(|err| format!("failed to release table lock: {err}"))?; - } - let res = tokio::time::timeout(Duration::from_secs(2), &mut wait_fut) - .await - .map_err(|_| { - "kept lookup must resolve cached pod IP once table lock releases" - .to_owned() - })?; - if Instant::now() >= deadline { - return Err( - "cached pod IP lookup must complete before deadline".to_owned() - ); - } - Ok(res) - } - } - } - } - .await; - if let Some(tx) = table_lock { - tx.rollback().await?; - } - let outcome = outcome?; - - match (boundary, outcome) { - ( - RefusalBoundary::LookupErrorAndRefusalReadyTogether - | RefusalBoundary::ExpiredDeadlineAndRefusalReadyTogether, - Err(SubstrateError::InvalidRequest { message }), - ) => assert!(message.contains("smaller than cloned rootfs size 451 MiB")), - ( - RefusalBoundary::StalledPrecheckBoundsAtDeadline - | RefusalBoundary::ConcurrentRefusalBoundsCachedIpStalledLookup, - Err(SubstrateError::Unavailable { message }), - ) => assert!(message.contains("node memory admission refused")), - ( - RefusalBoundary::ConcurrentRefusalLetsCachedIpWinBeforeDeadline, - Ok(Some((pod_ip, super::super::support::PodIpSource::Published))), - ) => assert_eq!(pod_ip.to_string(), "127.0.0.1"), - (_, other) => panic!("{boundary:?}: unexpected outcome {other:?}"), - } - Ok(()) -} +mod node_refusal; // ── joined create ─────────────────────────────────────────────────────────── diff --git a/crates/l40_api/api/src/controllers/substrate/kubernetes/adapter_characterization_tests/create_readiness/node_refusal.rs b/crates/l40_api/api/src/controllers/substrate/kubernetes/adapter_characterization_tests/create_readiness/node_refusal.rs new file mode 100644 index 0000000000..3e1261f19b --- /dev/null +++ b/crates/l40_api/api/src/controllers/substrate/kubernetes/adapter_characterization_tests/create_readiness/node_refusal.rs @@ -0,0 +1,977 @@ +//! Node-refusal characterization tests for `create_execution` and `wait_for_pod_ip_assignment`. + +use std::sync::OnceLock; + +use super::super::super::scripted_test_doubles::query_field_selectors; +use super::*; + +// ── node refusal ──────────────────────────────────────────────────────────── + +const EVENTS_PATH: &str = "/api/v1/namespaces/space/events"; + +/// Kubelet's event for a sandbox whose disk is smaller than its template's +/// rootfs, as the shim and node-manager word it. +const INVALID_DISK_REFUSAL: &str = "Failed to create pod sandbox: rpc error: code = \ + InvalidArgument desc = failed to start sandbox \"0123\": failed to create containerd task: \ + failed to create shim task: sbx-manager Wake [space-err=InvalidArgument]: prepare sandbox \ + failed: code: 'Client specified an invalid argument', message: \"rootfs_size_mb=300 is \ + smaller than cloned rootfs size 451 MiB\""; + +/// A refusal another attempt can get past. +const RETRYABLE_REFUSAL: &str = "Failed to create pod sandbox: rpc error: code = Unavailable \ + desc = failed to create shim task: sbx-manager Wake [space-err=Unavailable]: node-manager \ + is restarting"; + +const MEMORY_REFUSAL: &str = "Failed to create pod sandbox: rpc error: code = ResourceExhausted \ + desc = sbx-manager Wake [space-err=ResourceExhausted]: network allocate failed: \ + node memory admission refused: insufficient node memory"; +const QUEUE_REFUSAL: &str = "Failed to create pod sandbox: rpc error: code = ResourceExhausted \ + desc = sbx-manager Wake [space-err=ResourceExhausted]: lifecycle queue full"; + +/// What the node records for the create's pod sandbox, and how the apiserver +/// answers the create's watch of those events. +#[derive(Debug, Clone, Copy, PartialEq)] +enum NodeRefusal { + /// The node refuses the request as invalid. + Invalid, + /// The node refuses for a reason another attempt can get past. + Retryable, + /// The node refuses the request as invalid, and the apiserver throttles + /// the first watch of the pod's events. + InvalidAfterThrottledWatch, + /// A memory refusal is already recorded when readiness begins, while + /// kubelet has already assigned the pod an IP on a healthy worker: the + /// assigned IP wins over the stale refusal. + MemoryAfterPodIpAssigned, + Memory, + MemoryWithFlagOff, + MemoryWithFlagUnset, + QueueFull, +} + +/// Invalid requests and opt-in memory refusals fail with the node's reason, +/// delete the pod and retire its execution, unless kubelet has already assigned +/// the pod an IP (`InvalidArgument` defers only to a reflector-cached IP so an +/// invalid request never waits on Postgres or an uncached Pod `GET`, whereas +/// pre-recorded `MemoryAdmission` checks `resolve_pod_ip_for_readiness`). Other +/// refusals leave kubelet to retry until the readiness deadline. Events come +/// from the process's one reason-filtered watch, including after the apiserver +/// throttles it, and the create reads none of its own. Same-poll lookup-error, +/// expired-deadline, and stalled-lookup arbitration in +/// `wait_for_pod_ip_assignment` are pinned by +/// `pod_ip_wait_arbitrates_refusal_boundaries`. +#[rstest::rstest] +#[case::invalid_request_fails_the_create(NodeRefusal::Invalid)] +#[case::other_refusals_wait_for_the_deadline(NodeRefusal::Retryable)] +#[case::a_throttled_watch_is_watched_again(NodeRefusal::InvalidAfterThrottledWatch)] +#[case::assigned_pod_ip_beats_prerecorded_refusal(NodeRefusal::MemoryAfterPodIpAssigned)] +#[case::memory_refusal_is_retryable(NodeRefusal::Memory)] +#[case::memory_refusal_waits_with_flag_off(NodeRefusal::MemoryWithFlagOff)] +#[case::memory_refusal_waits_by_default(NodeRefusal::MemoryWithFlagUnset)] +#[case::queue_full_keeps_kubelet_retry(NodeRefusal::QueueFull)] +#[tokio::test(flavor = "current_thread")] +async fn create_handles_node_refusal(#[case] refusal: NodeRefusal) -> TestResult { + let enabled = if matches!( + refusal, + NodeRefusal::Invalid | NodeRefusal::MemoryWithFlagOff + ) { + "false" + } else { + "true" + }; + if !crate::test_support::enter_sim_worker_process_with_owned_token_files_and(&[( + "SPACE_CREATE_FAIL_FAST_ON_NODE_REJECTION", + (refusal != NodeRefusal::MemoryWithFlagUnset).then(|| std::ffi::OsStr::new(enabled)), + )]) { + return Ok(()); + } + let pod_has_ip = refusal == NodeRefusal::MemoryAfterPodIpAssigned; + let fails_fast = matches!( + refusal, + NodeRefusal::Invalid | NodeRefusal::InvalidAfterThrottledWatch | NodeRefusal::Memory + ); + let message = match refusal { + NodeRefusal::Invalid | NodeRefusal::InvalidAfterThrottledWatch => INVALID_DISK_REFUSAL, + NodeRefusal::Memory + | NodeRefusal::MemoryAfterPodIpAssigned + | NodeRefusal::MemoryWithFlagOff + | NodeRefusal::MemoryWithFlagUnset => MEMORY_REFUSAL, + NodeRefusal::QueueFull => QUEUE_REFUSAL, + NodeRefusal::Retryable => RETRYABLE_REFUSAL, + }; + let db = pplx_space_db_test_fixtures::pg_test_db().await?; + let sandbox_id = SandboxId::new(); + insert_test_sandbox_row(&db.pool, sandbox_id, "creating").await?; + let worker = if pod_has_ip { + start_scripted_worker(ScriptedWorkerConfig::new([])).await? + } else { + start_scripted_worker(ScriptedWorkerConfig::new([( + SPACED_WAIT_READY, + ScriptedReply::Hang, + )])) + .await? + }; + + let release_on_pod_get = matches!( + refusal, + NodeRefusal::Invalid | NodeRefusal::Memory | NodeRefusal::MemoryWithFlagOff + ); + let expects_recorded_memory_refusal = matches!( + refusal, + NodeRefusal::MemoryAfterPodIpAssigned + | NodeRefusal::MemoryWithFlagOff + | NodeRefusal::MemoryWithFlagUnset + ); + let pod_name: Arc>> = Arc::default(); + let post_returned_at: Arc>> = Arc::default(); + let pod_gets = Arc::new(AtomicUsize::new(0)); + let release_refusal = Arc::new(tokio::sync::Notify::new()); + let refusal_released = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let rejections: Arc< + OnceLock, + > = Arc::default(); + let sentinel: Arc>> = + Arc::default(); + let sentinel_observed = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let sentinel_notify = Arc::new(tokio::sync::Notify::new()); + let pod_watch_opened = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let pod_watch_notify = Arc::new(tokio::sync::Notify::new()); + let event_watches = Arc::new(AtomicUsize::new(0)); + let reply_pod_name = Arc::clone(&pod_name); + let reply_post_returned_at = Arc::clone(&post_returned_at); + let reply_pod_gets = Arc::clone(&pod_gets); + let reply_release_refusal = Arc::clone(&release_refusal); + let reply_refusal_released = Arc::clone(&refusal_released); + let reply_rejections = Arc::clone(&rejections); + let reply_sentinel = Arc::clone(&sentinel); + let reply_sentinel_observed = Arc::clone(&sentinel_observed); + let reply_sentinel_notify = Arc::clone(&sentinel_notify); + let reply_pod_watch_opened = Arc::clone(&pod_watch_opened); + let reply_pod_watch_notify = Arc::clone(&pod_watch_notify); + let reply_event_watches = Arc::clone(&event_watches); + let (client, log) = scripted_kube_client_async(move |request| { + let pod_name = Arc::clone(&reply_pod_name); + let post_returned_at = Arc::clone(&reply_post_returned_at); + let pod_gets = Arc::clone(&reply_pod_gets); + let release_refusal = Arc::clone(&reply_release_refusal); + let refusal_released = Arc::clone(&reply_refusal_released); + let rejections = Arc::clone(&reply_rejections); + let sentinel = Arc::clone(&reply_sentinel); + let sentinel_observed = Arc::clone(&reply_sentinel_observed); + let sentinel_notify = Arc::clone(&reply_sentinel_notify); + let pod_watch_opened = Arc::clone(&reply_pod_watch_opened); + let pod_watch_notify = Arc::clone(&reply_pod_watch_notify); + let event_watches = Arc::clone(&reply_event_watches); + async move { + let name = pod_name.lock().unwrap().clone(); + let pending_pod = |name: &str| { + pod_reply(&sandbox_pod( + name, + &format!("{name}-uid"), + sandbox_id, + 1, + "Pending", + None, + )) + }; + let pod_state = |name: &str| { + if pod_has_ip { + pod_reply(&running_pod(name, sandbox_id, Some(WORKER_NODE))) + } else { + pending_pod(name) + } + }; + let observe_released_refusal = |name: &str| { + let refusal_released = Arc::clone(&refusal_released); + let release_refusal = Arc::clone(&release_refusal); + let rejections = Arc::clone(&rejections); + let sentinel = Arc::clone(&sentinel); + let sentinel_observed = Arc::clone(&sentinel_observed); + let sentinel_notify = Arc::clone(&sentinel_notify); + let target_uid = format!("{name}-uid"); + async move { + refusal_released.store(true, Ordering::SeqCst); + release_refusal.notify_waiters(); + let wait = sentinel.lock().unwrap().take(); + if let Some(wait) = wait { + let _ = wait.refused(false).await; + if expects_recorded_memory_refusal { + let recorded = rejections + .get() + .expect("rejection watch initialized before create") + .register(&target_uid) + .recorded(true); + if !matches!( + &recorded, + Some(SubstrateError::Unavailable { message }) + if message.contains("node memory admission refused") + ) { + return Err(kube_status( + StatusCode::INTERNAL_SERVER_ERROR, + &format!( + "expected recorded memory refusal for {target_uid}, got {recorded:?}" + ), + )); + } + } + sentinel_observed.store(true, Ordering::SeqCst); + sentinel_notify.notify_waiters(); + } + Ok(()) + } + }; + match request.method { + Method::POST if request.path == PODS_PATH => { + let name = requested_pod_name(&request); + *pod_name.lock().unwrap() = Some(name.clone()); + if !release_on_pod_get && let Err(reply) = observe_released_refusal(&name).await + { + return reply; + } + *post_returned_at.lock().unwrap() = Some(Instant::now()); + pending_pod(&name) + } + // The per-pod watch never reports an IP. + Method::GET if request.path == PODS_PATH => { + pod_watch_opened.store(true, Ordering::SeqCst); + pod_watch_notify.notify_waiters(); + KubeReply::Hang + } + Method::GET if name.as_deref().map(pod_path).as_ref() == Some(&request.path) => { + let name = name.as_deref().expect("the pod was created"); + if release_on_pod_get && pod_gets.fetch_add(1, Ordering::SeqCst) == 0 { + if let Err(reply) = observe_released_refusal(name).await { + return reply; + } + KubeReply::Hang + } else { + pod_state(name) + } + } + Method::GET if request.path == EVENTS_PATH => { + let reason_only_selector = query_field_selectors(request.query.as_deref()) + .as_slice() + == ["reason=FailedCreatePodSandBox"]; + let watching = request + .query + .as_deref() + .is_some_and(|query| query.contains("watch=true")); + if !watching { + return KubeReply::Json( + StatusCode::OK, + serde_json::json!({ + "apiVersion": "v1", + "kind": "EventList", + "metadata": { "resourceVersion": "1" }, + "items": [], + }), + ); + } + // Real Kubernetes excludes `Warning` Events when an extra + // predicate (such as `type=Normal`) narrows the selector. + if !reason_only_selector { + return KubeReply::Hang; + } + let watch = event_watches.fetch_add(1, Ordering::SeqCst); + if refusal == NodeRefusal::InvalidAfterThrottledWatch && watch == 0 { + return kube_status(StatusCode::TOO_MANY_REQUESTS, "TooManyRequests"); + } + let first_refusal_watch = + usize::from(refusal == NodeRefusal::InvalidAfterThrottledWatch); + if watch > first_refusal_watch { + return KubeReply::Hang; + } + // The watch opened before the create: the node's refusal + // arrives once the target phase releases it, followed by a + // sentinel event so non-fail-fast and pre-recorded cases + // confirm the tracker processed the pod's event in stream + // order. + let name = loop { + let notified = release_refusal.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + if refusal_released.load(Ordering::SeqCst) + && let Some(name) = pod_name.lock().unwrap().clone() + { + break name; + } + notified.await; + }; + KubeReply::WatchEvents(vec![ + serde_json::json!({ + "type": "ADDED", + "object": { + "apiVersion": "v1", + "kind": "Event", + "metadata": { + "name": format!("{name}.1"), + "namespace": "space", + "resourceVersion": "2", + }, + "involvedObject": { + "kind": "Pod", + "name": name, + "uid": format!("{name}-uid"), + }, + "reason": "FailedCreatePodSandBox", + "message": message, + "type": "Warning", + }, + }), + serde_json::json!({ + "type": "ADDED", + "object": { + "apiVersion": "v1", + "kind": "Event", + "metadata": { + "name": "sentinel.1", + "namespace": "space", + "resourceVersion": "3", + }, + "involvedObject": { + "kind": "Pod", + "name": "sentinel", + "uid": "sentinel-uid", + }, + "reason": "FailedCreatePodSandBox", + "message": INVALID_DISK_REFUSAL, + "type": "Warning", + }, + }), + ]) + } + Method::DELETE if name.as_deref().map(pod_path).as_ref() == Some(&request.path) => { + kube_status(StatusCode::OK, "Success") + } + _ => kube_status(StatusCode::BAD_REQUEST, "BadRequest"), + } + } + }); + let mut substrate = + substrate_on(db.pool.clone(), client, &worker).with_pod_sandbox_rejection_watch(); + assert!( + substrate.task_tracker.is_empty(), + "the shared refusal watch runs on its own handle-scoped tracker" + ); + if refusal == NodeRefusal::Invalid { + // `run_with` cancels `shutdown_token` at SIGTERM before draining + // in-flight HTTP creates; the refusal watch stays live until the + // substrate drops. + substrate.shutdown_token.cancel(); + tokio::task::yield_now().await; + } + let _ = rejections.set(substrate.pod_sandbox_rejections.detached_handle()); + if !fails_fast || pod_has_ip { + *sentinel.lock().unwrap() = Some(substrate.pod_sandbox_rejections.register("sentinel-uid")); + } + let readiness_timeout = Duration::from_secs(60); + substrate.k8s.create_data_plane_ready_timeout = readiness_timeout; + // Keep readiness budgets well above wall-clock scheduling jitter; non-fail-fast + // cases advance Tokio's clock only after the sentinel confirms the refusal was + // observed while the create waited. + substrate.budgets = phase_ending_budgets(substrate.budgets); + substrate.budgets.readiness_pod_get = Duration::from_secs(10); + let inputs = CreateInputs::new(); + let template_ref = inputs.template_ref(); + + let started = Instant::now(); + let create_fut = substrate.create_execution(inputs.create_request(sandbox_id, &template_ref)); + tokio::pin!(create_fut); + let outcome = if !fails_fast && !pod_has_ip { + tokio::time::timeout(Duration::from_secs(10), async { + loop { + let notified = sentinel_notify.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + if sentinel_observed.load(Ordering::SeqCst) { + break Ok::<(), String>(()); + } + tokio::select! { + res = &mut create_fut => { + break Err(format!( + "create settled before the refusal sentinel was observed: {:?}", + res.err() + )); + } + () = &mut notified => {} + } + } + }) + .await + .map_err(|_| "refusal sentinel must be observed while create waits")??; + if expects_recorded_memory_refusal { + let name = pod_name + .lock() + .unwrap() + .clone() + .expect("the pod was created before releasing the refusal"); + let recorded = substrate + .pod_sandbox_rejections + .register(&format!("{name}-uid")) + .recorded(true); + assert!( + matches!( + &recorded, + Some(SubstrateError::Unavailable { message }) + if message.contains("node memory admission refused") + ), + "target pod must have its memory refusal recorded before readiness proceeds: {recorded:?}" + ); + } + if release_on_pod_get { + let during_pod_get = + std::future::poll_fn(|cx| std::task::Poll::Ready(create_fut.as_mut().poll(cx))) + .await; + if let std::task::Poll::Ready(res) = during_pod_get { + return Err(format!( + "non-fail-fast refusal must not end the create during the initial pod GET: {:?}", + res.err() + ) + .into()); + } + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(11)).await; + tokio::time::resume(); + } + tokio::time::timeout(Duration::from_secs(10), async { + loop { + let notified = pod_watch_notify.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + if pod_watch_opened.load(Ordering::SeqCst) { + break Ok::<(), String>(()); + } + tokio::select! { + res = &mut create_fut => { + break Err(format!( + "create settled before entering the pod readiness watch: {:?}", + res.err() + )); + } + () = &mut notified => {} + } + } + }) + .await + .map_err(|_| "non-fail-fast create must enter the pod readiness watch")??; + let during_watch = + std::future::poll_fn(|cx| std::task::Poll::Ready(create_fut.as_mut().poll(cx))).await; + if let std::task::Poll::Ready(res) = during_watch { + return Err(format!( + "non-fail-fast refusal must keep waiting in the pod readiness watch: {:?}", + res.err() + ) + .into()); + } + let post_at = post_returned_at + .lock() + .unwrap() + .expect("the pod was created before entering the readiness watch"); + tokio::time::pause(); + let before_deadline = post_at + readiness_timeout - Duration::from_secs(2); + assert!( + Instant::now() < before_deadline, + "watch setup overran the {readiness_timeout:?} readiness budget" + ); + tokio::select! { + res = &mut create_fut => { + tokio::time::resume(); + return Err(format!( + "non-fail-fast refusal settled before its {readiness_timeout:?} readiness deadline: {:?}", + res.err() + ) + .into()); + } + () = tokio::time::sleep_until(before_deadline) => {} + } + tokio::time::resume(); + if let Ok(res) = tokio::time::timeout(Duration::from_millis(50), &mut create_fut).await { + return Err(format!( + "non-fail-fast refusal settled before its {readiness_timeout:?} readiness deadline: {:?}", + res.err() + ) + .into()); + } + assert!( + requests_matching(&log, &Method::DELETE).is_empty(), + "pod must not be torn down before its {readiness_timeout:?} readiness deadline" + ); + tokio::time::pause(); + tokio::time::advance(Duration::from_secs(5)).await; + tokio::time::resume(); + tokio::time::timeout(Duration::from_secs(10), &mut create_fut) + .await + .map_err(|_| "the create must end once its readiness deadline elapses")? + } else { + tokio::time::timeout(Duration::from_secs(15), &mut create_fut) + .await + .map_err(|_| "the create must end")? + }; + let elapsed = started.elapsed(); + let pod_name = pod_name + .lock() + .unwrap() + .clone() + .expect("the pod was created"); + substrate.pod_sandbox_rejections.shutdown().await; + substrate.shutdown_token.cancel(); + substrate.task_tracker.close(); + substrate.task_tracker.wait().await; + let event_reads: Vec<_> = requests_matching(&log, &Method::GET) + .into_iter() + .filter(|request| request.path == EVENTS_PATH) + .collect(); + assert!(!event_reads.is_empty(), "the process watches refusals"); + for read in &event_reads { + let query = read.query.as_deref().unwrap_or_default(); + assert_eq!( + query_field_selectors(read.query.as_deref()), + ["reason=FailedCreatePodSandBox"], + "every Events read uses only the reason-filtered selector: {query}" + ); + assert!( + !query.contains(&pod_name) && !query.contains("involvedObject"), + "every read is the process's watch, none the create's own: {query}" + ); + } + if pod_has_ip { + let created = outcome.map_err(|err| { + format!("an assigned pod IP must beat a pre-recorded refusal: {err:?}") + })?; + assert_eq!( + created + .binding + .expect("cold create binds its pod") + .execution_object_id, + format!("{pod_name}-uid") + ); + assert!( + requests_matching(&log, &Method::DELETE).is_empty(), + "a ready pod with an assigned IP must not be deleted" + ); + assert_eq!(active_execution_count(&db.pool, sandbox_id).await?, 1); + return Ok(()); + } + let error = outcome.err().ok_or("the pod never got an IP")?; + if !fails_fast { + assert!( + sentinel_observed.load(Ordering::SeqCst), + "the refusal event must be observed before accepting a readiness timeout" + ); + assert!( + matches!( + error, + SubstrateError::Timeout { + phase: Some(WaitReadyTimeoutPhase::PodNeverReady), + .. + } + ), + "expected the pod-IP readiness deadline (PodNeverReady), got {error:?}" + ); + return Ok(()); + } + + match (&error, refusal) { + (SubstrateError::Unavailable { message }, NodeRefusal::Memory) => { + assert!(message.contains("node memory admission refused")); + } + ( + SubstrateError::InvalidRequest { message }, + NodeRefusal::Invalid | NodeRefusal::InvalidAfterThrottledWatch, + ) => { + assert!(message.contains("smaller than cloned rootfs size 451 MiB")); + } + _ => panic!("expected the node's refusal, got {error:?}"), + } + // Far inside the production readiness budget, with room for a throttled + // watch's jittered DefaultBackoff and a loaded runner. The watch assertion + // above, not this bound, is what rules out polling. + assert!( + elapsed < Duration::from_secs(5), + "the refusal, not the readiness budget or initial pod GET timeout, ends the create: {elapsed:?}" + ); + let deletes = requests_matching(&log, &Method::DELETE); + let [delete] = deletes.as_slice() else { + panic!("expected one pod delete, got {deletes:?}"); + }; + assert_eq!(delete.path, pod_path(&pod_name)); + assert_eq!( + active_execution_count(&db.pool, sandbox_id).await?, + 0, + "the execution must be retired" + ); + Ok(()) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum RefusalBoundary { + /// The initial Pod `GET` fails with a 503 on the same poll that records a + /// refusal: `biased;` polls the lookup arm first and must still surface the + /// recorded refusal rather than the 503 lookup error. + LookupErrorAndRefusalReadyTogether, + /// The pod-IP wait deadline expires on the same poll that records a + /// refusal: `biased;` polls `timeout_at` first (`resolved = None`) and must + /// still surface the recorded refusal rather than `Ok(None)`. + ExpiredDeadlineAndRefusalReadyTogether, + /// A pre-recorded memory refusal runs its IP-resolution precheck while the + /// execution table is locked past `deadline`: `timeout_at(deadline, ...)` + /// ends the precheck and surfaces the recorded refusal instead of stalling. + StalledPrecheckBoundsAtDeadline, + /// A memory refusal arrives after `wait_for_pod_ip_assignment` has already + /// started with a cached pod IP while the execution table is locked: the + /// lookup keeps running until `deadline` so the cached IP can still win, and + /// then bounds at `deadline` with the recorded refusal instead of stalling. + ConcurrentRefusalBoundsCachedIpStalledLookup, + /// Same concurrent memory refusal while `wait_for_pod_ip_assignment` is + /// parked on the locked execution table with a cached pod IP, except the + /// lock releases before `deadline`: the kept in-flight resolver finishes + /// and returns the cached pod IP rather than dropping the lookup for the + /// refusal. + ConcurrentRefusalLetsCachedIpWinBeforeDeadline, +} + +#[rstest::rstest] +#[case::lookup_error_yields_to_recorded_refusal( + RefusalBoundary::LookupErrorAndRefusalReadyTogether +)] +#[case::expired_deadline_yields_to_recorded_refusal( + RefusalBoundary::ExpiredDeadlineAndRefusalReadyTogether +)] +#[case::stalled_precheck_bounds_at_deadline_and_returns_refusal( + RefusalBoundary::StalledPrecheckBoundsAtDeadline +)] +#[case::concurrent_refusal_defers_for_cached_ip_then_bounds_at_deadline( + RefusalBoundary::ConcurrentRefusalBoundsCachedIpStalledLookup +)] +#[case::concurrent_refusal_lets_cached_ip_win_before_deadline( + RefusalBoundary::ConcurrentRefusalLetsCachedIpWinBeforeDeadline +)] +#[tokio::test(flavor = "current_thread")] +async fn pod_ip_wait_arbitrates_refusal_boundaries( + #[case] boundary: RefusalBoundary, +) -> TestResult { + let db = pplx_space_db_test_fixtures::pg_test_db().await?; + let sandbox_id = SandboxId::new(); + let pod_name = "space-sbx-refusal-boundary-g1"; + let pod_uid = "space-sbx-refusal-boundary-g1-uid"; + insert_test_sandbox_row(&db.pool, sandbox_id, "creating").await?; + sqlx::query(sql!( + "INSERT INTO sandbox_k8s_executions + (sandbox_id, generation, pod_name, pod_namespace, pod_uid, state, active) + VALUES ($1, 1, $2, 'space', $3, 'running', TRUE)" + )) + .bind(sandbox_id) + .bind(pod_name) + .bind(pod_uid) + .execute(&db.pool) + .await?; + + let make_refusal_event = |message: &str| -> k8s_openapi::api::core::v1::Event { + serde_json::from_value(serde_json::json!({ + "apiVersion": "v1", + "kind": "Event", + "metadata": { + "name": "refusal-boundary.1", + "namespace": "space", + "resourceVersion": "2", + }, + "involvedObject": { + "kind": "Pod", + "name": pod_name, + "uid": pod_uid, + }, + "reason": "FailedCreatePodSandBox", + "message": message, + "type": "Warning", + })) + .expect("valid refusal Event JSON") + }; + + let cached_pods = if matches!( + boundary, + RefusalBoundary::ConcurrentRefusalBoundsCachedIpStalledLookup + | RefusalBoundary::ConcurrentRefusalLetsCachedIpWinBeforeDeadline + ) { + vec![running_pod(pod_name, sandbox_id, Some(WORKER_NODE))] + } else { + Vec::new() + }; + let mut substrate = + substrate_with_inventory_caches_and_pool(cached_pods, vec![worker_node()], db.pool.clone()); + substrate.budgets.reflector_wait = Duration::ZERO; + let rejections = substrate.pod_sandbox_rejections.clone(); + let wall_now = jiff::Timestamp::now(); + + let pod_watch_opened = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let pod_watch_notify = Arc::new(tokio::sync::Notify::new()); + let client = match boundary { + RefusalBoundary::LookupErrorAndRefusalReadyTogether => { + let rejections = rejections.clone(); + let event = make_refusal_event(INVALID_DISK_REFUSAL); + let (client, _) = scripted_kube_client(move |request| { + if request.method == Method::GET && request.path == pod_path(pod_name) { + rejections.observe(&event, wall_now, Instant::now()); + kube_status(StatusCode::SERVICE_UNAVAILABLE, "ServiceUnavailable") + } else { + kube_status(StatusCode::BAD_REQUEST, "BadRequest") + } + }); + client + } + RefusalBoundary::ExpiredDeadlineAndRefusalReadyTogether => { + let pending = sandbox_pod(pod_name, pod_uid, sandbox_id, 1, "Pending", None); + let opened = Arc::clone(&pod_watch_opened); + let notify = Arc::clone(&pod_watch_notify); + let (client, _) = scripted_kube_client(move |request| { + if request.method == Method::GET && request.path == pod_path(pod_name) { + pod_reply(&pending) + } else if request.method == Method::GET && request.path == PODS_PATH { + opened.store(true, Ordering::SeqCst); + notify.notify_waiters(); + KubeReply::Hang + } else { + kube_status(StatusCode::BAD_REQUEST, "BadRequest") + } + }); + client + } + RefusalBoundary::StalledPrecheckBoundsAtDeadline + | RefusalBoundary::ConcurrentRefusalBoundsCachedIpStalledLookup + | RefusalBoundary::ConcurrentRefusalLetsCachedIpWinBeforeDeadline => { + let (client, _) = scripted_kube_client(|_| KubeReply::Hang); + client + } + }; + substrate.k8s.client = client; + + let mut table_lock = None; + if matches!( + boundary, + RefusalBoundary::StalledPrecheckBoundsAtDeadline + | RefusalBoundary::ConcurrentRefusalBoundsCachedIpStalledLookup + | RefusalBoundary::ConcurrentRefusalLetsCachedIpWinBeforeDeadline + ) { + if boundary == RefusalBoundary::StalledPrecheckBoundsAtDeadline { + rejections.observe( + &make_refusal_event(MEMORY_REFUSAL), + wall_now, + Instant::now(), + ); + } + let mut tx = db.pool.begin().await?; + sqlx::query(sql!( + "LOCK TABLE sandbox_k8s_executions IN ACCESS EXCLUSIVE MODE" + )) + .execute(&mut *tx) + .await?; + table_lock = Some(tx); + } + + let refusal = ( + substrate.pod_sandbox_rejections.register(pod_uid), + matches!( + boundary, + RefusalBoundary::StalledPrecheckBoundsAtDeadline + | RefusalBoundary::ConcurrentRefusalBoundsCachedIpStalledLookup + | RefusalBoundary::ConcurrentRefusalLetsCachedIpWinBeforeDeadline + ), + ); + let target = super::super::super::wait_ready::PodProxyWaitTarget { + pod_name, + pod_uid: Some(pod_uid), + generation: 1, + }; + let outcome: Result<_, String> = async { + let deadline = Instant::now() + Duration::from_secs(5); + let wait_fut = substrate.wait_for_pod_ip_assignment( + crate::metrics::sandbox::api::SandboxApiMetricIdentity::ecw("create"), + sandbox_id, + &target, + deadline, + "create", + Some(&refusal), + ); + tokio::pin!(wait_fut); + async fn assert_stalled_lookup_settles_at_deadline( + mut wait_fut: std::pin::Pin<&mut F>, + deadline: Instant, + label: &'static str, + ) -> Result + where + F: std::future::Future, + F::Output: std::fmt::Debug, + { + let margin = Duration::from_millis(50); + tokio::time::pause(); + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining <= Duration::from_secs(4) { + tokio::time::resume(); + return Err(format!( + "{label} consumed too much of deadline before clock pause: {remaining:?}" + )); + } + tokio::time::advance(remaining - margin).await; + let before_deadline = + std::future::poll_fn(|cx| std::task::Poll::Ready(wait_fut.as_mut().poll(cx))).await; + if let std::task::Poll::Ready(res) = before_deadline { + tokio::time::resume(); + return Err(format!( + "{label} must remain pending {margin:?} before deadline: {res:?}" + )); + } + let timed = tokio::time::timeout(margin * 2, &mut wait_fut).await; + let settled_at = Instant::now(); + tokio::time::resume(); + let res = + timed.map_err(|_| format!("{label} must settle within {margin:?} after deadline"))?; + if settled_at < deadline || settled_at > deadline + margin { + return Err(format!( + "{label} settled outside [deadline, deadline + {margin:?}]: \ + after_deadline={:?}", + settled_at.checked_duration_since(deadline), + )); + } + Ok(res) + } + + match boundary { + RefusalBoundary::LookupErrorAndRefusalReadyTogether => { + tokio::time::timeout(Duration::from_secs(2), &mut wait_fut) + .await + .map_err(|_| "lookup-error boundary must settle immediately".to_owned()) + } + RefusalBoundary::ExpiredDeadlineAndRefusalReadyTogether => { + tokio::time::timeout(Duration::from_secs(2), async { + loop { + let notified = pod_watch_notify.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + if pod_watch_opened.load(Ordering::SeqCst) { + break Ok(()); + } + tokio::select! { + res = &mut wait_fut => { + break Err(format!( + "wait finished before pod watch opened: {res:?}" + )); + } + () = &mut notified => {} + } + } + }) + .await + .map_err(|_| "pod watch must open before deadline".to_owned())??; + tokio::time::pause(); + // Drive Tokio's timer wheel strictly past `deadline` while + // `wait_fut` stays parked so `timeout_at(deadline, raced)` is + // already ready on the very next poll; `advance` alone only + // bumps `Instant::now()` without firing the timer entry. + tokio::time::sleep_until(deadline + Duration::from_millis(10)).await; + rejections.observe( + &make_refusal_event(INVALID_DISK_REFUSAL), + wall_now, + Instant::now(), + ); + let polled = + std::future::poll_fn(|cx| std::task::Poll::Ready(wait_fut.as_mut().poll(cx))) + .await; + tokio::time::resume(); + match polled { + std::task::Poll::Ready(res) => Ok(res), + std::task::Poll::Pending => Err( + "expired-deadline boundary must settle on the first poll once both timeout and refusal are ready" + .to_owned(), + ), + } + } + RefusalBoundary::StalledPrecheckBoundsAtDeadline => { + if tokio::time::timeout(Duration::from_millis(15), &mut wait_fut) + .await + .is_ok() + { + return Err( + "stalled precheck must park on the locked execution table before deadline" + .to_owned(), + ); + } + assert_stalled_lookup_settles_at_deadline(wait_fut, deadline, "stalled precheck") + .await + } + RefusalBoundary::ConcurrentRefusalBoundsCachedIpStalledLookup + | RefusalBoundary::ConcurrentRefusalLetsCachedIpWinBeforeDeadline => { + if tokio::time::timeout(Duration::from_millis(15), &mut wait_fut) + .await + .is_ok() + { + return Err( + "initial lookup must park on the locked execution table before refusal arrives" + .to_owned(), + ); + } + rejections.observe( + &make_refusal_event(MEMORY_REFUSAL), + wall_now, + Instant::now(), + ); + let immediate = + std::future::poll_fn(|cx| std::task::Poll::Ready(wait_fut.as_mut().poll(cx))) + .await; + if let std::task::Poll::Ready(res) = immediate { + return Err(format!( + "a cached pod IP must keep the lookup running until deadline: {res:?}" + )); + } + if boundary == RefusalBoundary::ConcurrentRefusalBoundsCachedIpStalledLookup { + assert_stalled_lookup_settles_at_deadline( + wait_fut, + deadline, + "concurrent refusal", + ) + .await + } else { + if let Some(tx) = table_lock.take() { + tx.rollback() + .await + .map_err(|err| format!("failed to release table lock: {err}"))?; + } + let res = tokio::time::timeout(Duration::from_secs(2), &mut wait_fut) + .await + .map_err(|_| { + "kept lookup must resolve cached pod IP once table lock releases" + .to_owned() + })?; + if Instant::now() >= deadline { + return Err( + "cached pod IP lookup must complete before deadline".to_owned() + ); + } + Ok(res) + } + } + } + } + .await; + if let Some(tx) = table_lock { + tx.rollback().await?; + } + let outcome = outcome?; + + match (boundary, outcome) { + ( + RefusalBoundary::LookupErrorAndRefusalReadyTogether + | RefusalBoundary::ExpiredDeadlineAndRefusalReadyTogether, + Err(SubstrateError::InvalidRequest { message }), + ) => assert!(message.contains("smaller than cloned rootfs size 451 MiB")), + ( + RefusalBoundary::StalledPrecheckBoundsAtDeadline + | RefusalBoundary::ConcurrentRefusalBoundsCachedIpStalledLookup, + Err(SubstrateError::Unavailable { message }), + ) => assert!(message.contains("node memory admission refused")), + ( + RefusalBoundary::ConcurrentRefusalLetsCachedIpWinBeforeDeadline, + Ok(Some((pod_ip, super::super::super::support::PodIpSource::Published))), + ) => assert_eq!(pod_ip.to_string(), "127.0.0.1"), + (_, other) => panic!("{boundary:?}: unexpected outcome {other:?}"), + } + Ok(()) +} diff --git a/crates/l40_api/api/src/controllers/substrate/kubernetes/wait_ready.rs b/crates/l40_api/api/src/controllers/substrate/kubernetes/wait_ready.rs index 9716e0eef6..29a03838c9 100644 --- a/crates/l40_api/api/src/controllers/substrate/kubernetes/wait_ready.rs +++ b/crates/l40_api/api/src/controllers/substrate/kubernetes/wait_ready.rs @@ -1,191 +1,16 @@ +mod connected_command_ready; + +pub(super) use connected_command_ready::CommandReadyPod; +#[cfg(test)] +pub(super) use connected_command_ready::ConnectedCommandReadiness; + use super::store::PlacementRetryDisposition; use super::support::*; use super::*; -use pplx_space_api_route::wait_ready_lifecycle_request; -#[derive(Clone, Copy)] -pub(super) enum CommandReadyPod<'a> { - PreResolved(PodIp), - /// Preserve the pre-route legacy behavior: resolve the active execution on - /// each retry without claiming that guest readiness proves route identity. - ResolveLegacy, - SelectedRoute { - route_identity: &'a pplx_space_sbx_mgr_client::proto::SpaceApiRouteIdentity, - pod_ip: Option, - }, -} +const LOG_TARGET: &str = module_path!(); impl KubernetesSubstrate { - pub(super) async fn worker_client_for_pod_ip( - &self, - pod_ip: PodIp, - ) -> Result { - let endpoint = Self::endpoint_for_pod_ip(pod_ip, self.k8s.sandbox_proxy_port) - .map_err(ControllerError::from)?; - connect_worker(endpoint).await - } - - /// [`Self::worker_client_for_pod_ip`] on the channel kept for `pod`'s - /// instance while its connection is open; see - /// [`super::pod_worker_channels`]. A failed dial fails the same way. - pub(super) async fn kept_worker_client( - &self, - pod: &ResolvedPodInstance, - ) -> Result { - let port = self.k8s.sandbox_proxy_port; - let key = super::pod_worker_channels::PodWorkerKey { - addr: pod.ip.socket_addr(port), - pod_uid: pod.pod_uid.clone(), - generation: pod.generation, - }; - let pod_ip = pod.ip; - self.pod_worker_channels - .client(key, async move { - let endpoint = - Self::endpoint_for_pod_ip(pod_ip, port).map_err(ControllerError::from)?; - crate::controllers::substrate::connect_worker_watched(endpoint).await - }) - .await - } - - /// The kept worker client a runtime or access path hands out for - /// `sandbox_id`'s resolved `pod`. A Native data-plane request (see - /// [`crate::controllers::substrate::native_access`]) gets - /// [`Self::native_kept_worker_client`]; every other caller gets - /// [`Self::kept_worker_client`], unchanged. - pub(super) async fn access_kept_worker_client( - &self, - sandbox_id: SandboxId, - pod: &ResolvedPodInstance, - ) -> Result { - if crate::controllers::substrate::native_access::active() { - return self.native_kept_worker_client(sandbox_id, pod).await; - } - self.kept_worker_client(pod).await - } - - /// [`Self::kept_worker_client`] for a Native data-plane request, which - /// fails over from a pod that does not answer instead of waiting out the - /// full connect budget on its address. - /// - /// A miss first dials once within [`POD_WORKER_FIRST_DIAL_TIMEOUT`]. If - /// that fails, the sandbox's pod is resolved again: the same instance is - /// dialed with the full connect budget, as every other caller dials it; a - /// replacement is dialed at its own address; and no pod returns the first - /// dial's error, so the caller's recovery path takes over at once. The - /// client also reports how it used its connection if the request holds it - /// long; see [`super::super::KeptCallReport`]. - pub(super) async fn native_kept_worker_client( - &self, - sandbox_id: SandboxId, - pod: &ResolvedPodInstance, - ) -> Result { - let first = self - .kept_worker_client_reported(pod, Some(POD_WORKER_FIRST_DIAL_TIMEOUT)) - .await; - let Err(first_error) = first else { - return first; - }; - let current = match self.resolve_pod_instance(sandbox_id).await { - Ok(Some(current)) => current, - Ok(None) => { - pplx_space_grpc_metrics::client_channel_cache("worker-node-api", "pod_gone"); - return Err(first_error); - } - Err(_) => return Err(first_error), - }; - if current.sandbox_restoring { - // A replacement mid-restore isn't dialed for a user request (see - // `join_restore_before_dial`); the caller's recovery joins it. - return Err(first_error); - } - if !current.same_instance(pod) { - pplx_space_grpc_metrics::client_channel_cache("worker-node-api", "pod_moved"); - } - self.kept_worker_client_reported(¤t, None).await - } - - /// The kept client for `pod`, its miss dialed with the default policy - /// or, given `first_dial`, once within it; reported as - /// [`super::super::KeptCallReport`] describes. - async fn kept_worker_client_reported( - &self, - pod: &ResolvedPodInstance, - first_dial: Option, - ) -> Result { - let port = self.k8s.sandbox_proxy_port; - let key = super::pod_worker_channels::PodWorkerKey { - addr: pod.ip.socket_addr(port), - pod_uid: pod.pod_uid.clone(), - generation: pod.generation, - }; - let pod_ip = pod.ip; - let (client, handout) = self - .pod_worker_channels - .client_with_handout(key, async move { - let endpoint = - Self::endpoint_for_pod_ip(pod_ip, port).map_err(ControllerError::from)?; - let Some(bound) = first_dial else { - return crate::controllers::substrate::connect_worker_watched(endpoint).await; - }; - // Bounding the attempt from outside, rather than through the - // endpoint's connect timeout, leaves the kept channel's own - // redials at the bound every other caller's channel has. - tokio::time::timeout( - bound, - crate::controllers::substrate::connect_worker_watched_with( - endpoint, - pplx_space_common_grpc::GrpcRetryPolicy::none(), - ), - ) - .await - .unwrap_or_else(|_| { - Err(ControllerError::service_unavailable(format!( - "node-api not reachable: no connection within {bound:?}" - ))) - }) - }) - .await?; - Ok(client.with_report(handout.kept, handout.connection_age, handout.idle)) - } - - pub(super) fn should_allow_access_recovery( - sandbox: &Sandbox, - activity: ExecutionActivityKind, - ) -> Result<(), ControllerError> { - if is_dormant_lifecycle(&sandbox.lifecycle) - && !activity.allows_implicit_wake(&sandbox.auto_lifecycle) - { - return Err( - match sandbox - .lifecycle - .parse::() - { - Ok(lifecycle) => ControllerError::sandbox_not_running( - crate::controllers::SandboxNotRunning { - sandbox_id: sandbox.id, - lifecycle, - }, - "sandbox is not running", - ), - Err(_) => ControllerError::new( - axum::http::StatusCode::CONFLICT, - "sandbox is not running", - ), - }, - ); - } - - if !is_wake_recovery_lifecycle(&sandbox.lifecycle) { - return Err(ControllerError::service_unavailable(format!( - "sandbox cannot be recovered while lifecycle is {}", - sandbox.lifecycle - ))); - } - - Ok(()) - } - /// Watch the pod until Kubernetes publishes its IP, sending each view of /// it to `observed` once its placement is recorded. A pod other than the /// one `target` names is ignored. @@ -801,453 +626,6 @@ impl KubernetesSubstrate { } } - pub(super) async fn poll_until_command_ready( - &self, - sandbox_id: SandboxId, - metric_identity: crate::metrics::sandbox::api::SandboxApiMetricIdentity, - ready_timeout: Duration, - pod: CommandReadyPod<'_>, - // Sandbox template, threaded through only so the - // `sandbox.api.create.command_ready_timeout` counter can carry a - // template tag when the create deadline fires. Ignored for non-create - // operations. - template: Option<&str>, - ) -> Result { - let started_at = Instant::now(); - let deadline = started_at + ready_timeout; - let mut poll_backoff = CommandReadyPollBackoff::new(started_at, deadline); - let mut node_api_connected_at = None; - // Tracks whether a pod IP ever resolved, so a deadline that fires - // with no IP is attributed to `pod_never_ready` rather than to a - // proxy/guest phase the wait never reached. - let mut resolved_ip_seen = false; - // Tracks whether any guest-ready probe returned `Code::Unavailable`. - // Cascade-amplifier signal: a deadline that fires after a probe - // genuinely returned gRPC `Unavailable` is the node-mgr-brownout - // symptom, and the timeout message names node-mgr so callers can - // classify the failure and route cleanup to the reconciler instead - // of spawning more cleanup load. TCP connect failures and per-probe - // deadline misses do NOT set this — they have other dominant causes - // (e.g. a wedged sbx-mgr) and naming node-mgr for them sends the - // on-call chasing the wrong service. - let mut saw_unavailable_probe = false; - let ( - selected_route_identity, - mut selected_route_pod_ip, - pre_resolved_pod_ip, - resolve_legacy, - ) = match pod { - CommandReadyPod::PreResolved(pod_ip) => (None, None, Some(pod_ip), false), - CommandReadyPod::ResolveLegacy => (None, None, None, true), - CommandReadyPod::SelectedRoute { - route_identity, - pod_ip, - } => (Some(route_identity), pod_ip, None, false), - }; - let mut connection: Option<(PodIp, RuntimeClient)> = None; - let mut selected_pod_resolution_error = None; - - loop { - if let Some(route_identity) = selected_route_identity - && selected_route_pod_ip.is_none() - { - match self.selected_wake_pod_ip(sandbox_id, route_identity).await { - Ok(pod_ip) => { - selected_route_pod_ip = pod_ip; - selected_pod_resolution_error = None; - } - Err(SubstrateError::Timeout { message, .. }) => { - // A live route remains selected; retry transient - // apiserver resolution at the slow cadence through the - // caller's readiness deadline. Identity/UID changes - // stay terminal and never enter this arm. - selected_pod_resolution_error = Some(message); - } - Err(error) => return Err(error), - } - } - let resolved_pod_ip = if resolve_legacy { - self.resolve_pod_ip(sandbox_id).await? - } else { - selected_route_pod_ip.or(pre_resolved_pod_ip) - }; - if let Some(pod_ip) = resolved_pod_ip { - resolved_ip_seen = true; - if connection - .as_ref() - .is_none_or(|(connected_ip, _)| *connected_ip != pod_ip) - { - let connect_started_at = Instant::now(); - let client = Self::pod_worker_client( - pod_ip, - self.k8s.sandbox_proxy_port, - START_WAIT_CONNECT_TIMEOUT.min(remaining_ready_window(deadline)), - ) - .await; - if client.is_some() { - record_api_wait_ready_latency( - sandbox_id, - metric_identity, - "node_api_connect", - "success", - connect_started_at, - None, - ); - } - connection = client.map(|client| (pod_ip, client)); - if connection.is_none() && selected_route_identity.is_some() { - // Before retrying a failed authenticated connection, - // revalidate the live Pod UID/IP and selected route. - selected_route_pod_ip = None; - } - } - // A failed TCP connect to the sandbox pod proxy is NOT a - // node-mgr signal: the proxy can be down because the shim's - // LaunchSandbox is hung on a wedged sbx-mgr just as easily - // as on a stuck node-mgr. The deadline classification below - // reports it as `proxy_unreachable` (via - // `node_api_connected_at` staying `None`) without naming a - // service, and the create path's defer-cleanup decision - // keys off the `Timeout` variant itself. - let mut reset_connection = false; - if let Some((_, client)) = connection.as_mut() { - if node_api_connected_at.is_none() { - node_api_connected_at = Some(Instant::now()); - record_api_wait_ready_latency( - sandbox_id, - metric_identity, - "node_api_first_connect", - "success", - started_at, - None, - ); - record_api_wait_ready_latency( - sandbox_id, - metric_identity, - "placement", - "success", - started_at, - None, - ); - } - - let probe_started_at = Instant::now(); - // No probe outlives the wait's deadline, so a short wait, - // such as a Native create's, ends when it says. - let probe_timeout = - START_WAIT_COMMAND_PROBE_TIMEOUT.min(remaining_ready_window(deadline)); - let probe = client.spaced_wait_ready(wait_ready_lifecycle_request( - SpacedWaitReadyRequest { - sandbox_id: sandbox_id.to_string(), - timeout: Some(duration_to_proto(probe_timeout)), - }, - )); - match timeout(probe_timeout, probe).await { - Ok(Ok(_)) => { - record_api_wait_ready_latency( - sandbox_id, - metric_identity, - "command_probe", - "success", - probe_started_at, - None, - ); - record_api_wait_ready_latency( - sandbox_id, - metric_identity, - "total", - "success", - started_at, - None, - ); - if let Some(node_api_connected_at) = node_api_connected_at { - record_api_wait_ready_latency( - sandbox_id, - metric_identity, - "command_ready_after_placement", - "success", - node_api_connected_at, - Some("placement"), - ); - } - if let (Some(route_identity), Some(selected_pod_ip)) = - (selected_route_identity, selected_route_pod_ip) - { - return self - .selected_wake_binding( - sandbox_id, - route_identity, - selected_pod_ip, - ) - .await; - } - let execution = self - .store - .active_execution_status(sandbox_id) - .await? - .ok_or_else(|| SubstrateError::Unavailable { - message: "sandbox has no active Kubernetes execution".to_string(), - })?; - return Ok(ExecutionBinding { - execution_object_id: execution.pod_name, - runtime_endpoint: Self::endpoint_for_pod_ip( - pod_ip, - self.k8s.sandbox_proxy_port, - )?, - execution_generation: execution_generation_to_u64( - execution.generation, - )?, - }); - } - Ok(Err(err)) - if err.code() == Code::FailedPrecondition - && (err.message().contains("not started") - || err.message().contains("sandbox is starting") - || err.message().contains("wait for start to complete")) => {} - Ok(Err(err)) if err.code() == Code::Unavailable => { - saw_unavailable_probe = true; - reset_connection = true; - } - Ok(Err(err)) => { - record_api_wait_ready_error( - sandbox_id, - metric_identity, - "command_probe", - "grpc_error", - grpc_code_tag(err.code()), - ); - return Err(SubstrateError::Failed { - message: format!("sandbox failed before start completed: {err}"), - }); - } - Err(_) => { - // Per-probe deadline elapsed: connected to the - // proxy but `spaced_wait_ready` didn't respond - // in time. Not a node-mgr signal — the probe - // hung rather than returning `Unavailable` — so - // the eventual deadline reports `guest_not_ready` - // without naming a service. - reset_connection = true; - } - } - } - if reset_connection { - // Tonic channels reconnect internally. Once a probe fails, - // retaining the channel could silently reconnect to a - // reassigned Pod IP without rechecking the immutable UID. - // Rebuild legacy/pre-resolved transports too, matching the - // pre-cache behavior instead of burning the full deadline - // on one half-open channel. - connection = None; - if selected_route_identity.is_some() { - selected_route_pod_ip = None; - } - } - } - - if Instant::now() >= deadline { - if metric_identity.op == "create" { - crate::metrics::sandbox::api::create_command_ready_timeout( - sandbox_id, template, - ); - } - let phase = if !resolved_ip_seen { - WaitReadyTimeoutPhase::PodNeverReady - } else if node_api_connected_at.is_none() { - WaitReadyTimeoutPhase::ProxyUnreachable - } else { - WaitReadyTimeoutPhase::GuestNotReady - }; - let mut error = command_ready_timeout_error(phase, saw_unavailable_probe); - if let (SubstrateError::Timeout { message, .. }, Some(resolution_error)) = - (&mut error, selected_pod_resolution_error.as_deref()) - { - message.push_str(&format!("; last pod resolution error: {resolution_error}")); - } - return Err(error); - } - - let delay = poll_backoff.next_delay(); - // Recompute after connection/probe handling: either path may have - // invalidated a previously selected IP in this same iteration. - // The slow clamp must apply immediately or a brownout produces an - // uncached Pod GET and several store reads every 250 ms. - let waiting_for_selected_pod_ip = - selected_route_identity.is_some() && selected_route_pod_ip.is_none(); - let delay = if waiting_for_selected_pod_ip { - delay - .max(START_WAIT_SLOW_POLL_INTERVAL) - .min(deadline.saturating_duration_since(Instant::now())) - } else { - delay - }; - sleep(delay).await; - } - } - - pub(super) async fn poll_connected_client_until_command_ready( - &self, - client: &mut NodeApiClient, - sandbox_id: SandboxId, - metric_identity: crate::metrics::sandbox::api::SandboxApiMetricIdentity, - ready_timeout: Duration, - binding: ExecutionBinding, - template: Option<&str>, - ) -> Result { - let probes = match Self::probe_connected_client_until_command_ready( - client, - sandbox_id, - metric_identity, - ready_timeout, - ) - .await? - { - ConnectedCommandReadiness::Ready => return Ok(binding), - ConnectedCommandReadiness::TimedOut(probes) => probes, - }; - if metric_identity.op == "create" { - crate::metrics::sandbox::api::create_command_ready_timeout(sandbox_id, template); - } - // The caller reached the node for the adoption's setup and Wake, so - // the timeout names the guest's phase. A probe that could not reach - // the node also ends in `DeadlineExceeded`; the warning carries what - // the probes returned. Keep it out of the message: a transport - // signature there would make the timeout reclaimable and spend - // another readiness budget on the same pod. - tracing::warn!( - sandbox_id = %sandbox_id, - deadline_exceeded_probes = probes.deadline_exceeded, - last_probe_code = ?probes.last_status.as_ref().map(tonic::Status::code), - last_probe_message = probes.last_status.as_ref().map(tonic::Status::message), - "pooled sandbox command readiness wait timed out" - ); - Err(command_ready_timeout_error( - WaitReadyTimeoutPhase::GuestNotReady, - probes.saw_unavailable, - )) - } - - /// Probes the connected node until the guest reports command readiness - /// or `ready_timeout` passes. Starts no probe once the deadline has - /// passed: one with no budget left would end before it reached the node. - pub(super) async fn probe_connected_client_until_command_ready( - client: &mut NodeApiClient, - sandbox_id: SandboxId, - metric_identity: crate::metrics::sandbox::api::SandboxApiMetricIdentity, - ready_timeout: Duration, - ) -> Result { - let started_at = Instant::now(); - let deadline = started_at + ready_timeout; - let mut poll_backoff = CommandReadyPollBackoff::new(started_at, deadline); - let node_api_connected_at = Instant::now(); - let mut probes = SwallowedCommandProbes::default(); - - record_api_wait_ready_latency( - sandbox_id, - metric_identity, - "node_api_first_connect", - "success", - started_at, - None, - ); - record_api_wait_ready_latency( - sandbox_id, - metric_identity, - "placement", - "success", - started_at, - None, - ); - - loop { - let probe_started_at = Instant::now(); - if probe_started_at >= deadline { - return Ok(ConnectedCommandReadiness::TimedOut(probes)); - } - - let probe_timeout = (START_WAIT_COMMAND_PROBE_TIMEOUT - + START_WAIT_COMMAND_PROBE_CLIENT_MARGIN) - .min(deadline.saturating_duration_since(probe_started_at)); - let mut worker_client = RetryingWorkerApiClient::new(client); - let probe = worker_client.spaced_wait_ready_with_metadata( - wait_ready_lifecycle_request(SpacedWaitReadyRequest { - sandbox_id: sandbox_id.to_string(), - timeout: Some(duration_to_proto(START_WAIT_COMMAND_PROBE_TIMEOUT)), - }), - probe_timeout, - ); - match timeout(probe_timeout, probe).await { - Ok(Ok(_)) => { - record_api_wait_ready_latency( - sandbox_id, - metric_identity, - "command_probe", - "success", - probe_started_at, - None, - ); - record_api_wait_ready_latency( - sandbox_id, - metric_identity, - "total", - "success", - started_at, - None, - ); - record_api_wait_ready_latency( - sandbox_id, - metric_identity, - "command_ready_after_placement", - "success", - node_api_connected_at, - Some("placement"), - ); - return Ok(ConnectedCommandReadiness::Ready); - } - Ok(Err(err)) - if err.code() == Code::FailedPrecondition - && (err.message().contains("not started") - || err.message().contains("sandbox is starting") - || err.message().contains("wait for start to complete")) => - { - probes.last_status = Some(err); - } - Ok(Err(err)) if err.code() == Code::Unavailable => { - probes.saw_unavailable = true; - probes.last_status = Some(err); - } - // Not ready yet, like the outer timeout below: the readiness - // deadline, not one probe, decides when the guest has failed - // to start. Three sources end a probe this way: the client's - // per-probe deadline, which ends a probe for a guest that is - // not ready because the node keeps waiting for it; the - // retrying client running out of its budget while the node - // refuses connections; and the node's own expired wait. - Ok(Err(err)) if err.code() == Code::DeadlineExceeded => { - probes.deadline_exceeded += 1; - probes.last_status = Some(err); - } - Ok(Err(err)) => { - record_api_wait_ready_error( - sandbox_id, - metric_identity, - "command_probe", - "grpc_error", - grpc_code_tag(err.code()), - ); - return Err(SubstrateError::Failed { - message: format!("sandbox failed before start completed: {err}"), - }); - } - // The same bound as the client's deadline, which usually - // fires first. - Err(_) => probes.deadline_exceeded += 1, - } - - sleep(poll_backoff.next_delay()).await; - } - } - pub(super) async fn ensure_active_execution_pod_proxy_reachable( &self, metric_identity: crate::metrics::sandbox::api::SandboxApiMetricIdentity, @@ -1289,31 +667,6 @@ impl KubernetesSubstrate { } } -/// How [`KubernetesSubstrate::probe_connected_client_until_command_ready`] -/// ended. -pub(super) enum ConnectedCommandReadiness { - Ready, - /// The readiness deadline passed first. - TimedOut(SwallowedCommandProbes), -} - -/// What the readiness probes the poll swallowed returned, for the warning at -/// the deadline. A node that stops answering and a guest that never reports -/// both end every probe at its deadline, which the timeout's phase cannot -/// tell apart. -#[derive(Debug, Default)] -pub(super) struct SwallowedCommandProbes { - /// See `poll_until_command_ready`: set only by a probe that genuinely - /// returned gRPC `Unavailable`, so the timeout message names node-mgr - /// only when a probe actually implicated it. - pub(super) saw_unavailable: bool, - /// Probes that ended in `DeadlineExceeded`, counting those the outer - /// timeout ended without a status. - pub(super) deadline_exceeded: usize, - /// The latest status a probe returned. - pub(super) last_status: Option, -} - /// Identity of the execution pod a proxy-reachability wait targets. Groups /// the execution-row fields so `wait_for_pod_proxy_reachable`'s signature /// stays under clippy's `too_many_arguments` ceiling as knobs are added. diff --git a/crates/l40_api/api/src/controllers/substrate/kubernetes/wait_ready/connected_command_ready.rs b/crates/l40_api/api/src/controllers/substrate/kubernetes/wait_ready/connected_command_ready.rs new file mode 100644 index 0000000000..4d4beffde8 --- /dev/null +++ b/crates/l40_api/api/src/controllers/substrate/kubernetes/wait_ready/connected_command_ready.rs @@ -0,0 +1,661 @@ +use pplx_space_api_route::wait_ready_lifecycle_request; + +use super::super::support::*; +use super::super::*; + +#[derive(Clone, Copy)] +pub(in crate::controllers::substrate::kubernetes) enum CommandReadyPod<'a> { + PreResolved(PodIp), + /// Preserve the pre-route legacy behavior: resolve the active execution on + /// each retry without claiming that guest readiness proves route identity. + ResolveLegacy, + SelectedRoute { + route_identity: &'a pplx_space_sbx_mgr_client::proto::SpaceApiRouteIdentity, + pod_ip: Option, + }, +} + +/// How [`KubernetesSubstrate::probe_connected_client_until_command_ready`] +/// ended. +pub(in crate::controllers::substrate::kubernetes) enum ConnectedCommandReadiness { + Ready, + /// The readiness deadline passed first. + TimedOut(SwallowedCommandProbes), +} + +/// What the readiness probes the poll swallowed returned, for the warning at +/// the deadline. A node that stops answering and a guest that never reports +/// both end every probe at its deadline, which the timeout's phase cannot +/// tell apart. +#[derive(Debug, Default)] +pub(in crate::controllers::substrate::kubernetes) struct SwallowedCommandProbes { + /// See `poll_until_command_ready`: set only by a probe that genuinely + /// returned gRPC `Unavailable`, so the timeout message names node-mgr + /// only when a probe actually implicated it. + pub(in crate::controllers::substrate::kubernetes) saw_unavailable: bool, + /// Probes that ended in `DeadlineExceeded`, counting those the outer + /// timeout ended without a status. + pub(in crate::controllers::substrate::kubernetes) deadline_exceeded: usize, + /// The latest status a probe returned. + pub(in crate::controllers::substrate::kubernetes) last_status: Option, +} + +impl KubernetesSubstrate { + pub(in crate::controllers::substrate::kubernetes) async fn poll_until_command_ready( + &self, + sandbox_id: SandboxId, + metric_identity: crate::metrics::sandbox::api::SandboxApiMetricIdentity, + ready_timeout: Duration, + pod: CommandReadyPod<'_>, + // Sandbox template, threaded through only so the + // `sandbox.api.create.command_ready_timeout` counter can carry a + // template tag when the create deadline fires. Ignored for non-create + // operations. + template: Option<&str>, + ) -> Result { + let started_at = Instant::now(); + let deadline = started_at + ready_timeout; + let mut poll_backoff = CommandReadyPollBackoff::new(started_at, deadline); + let mut node_api_connected_at = None; + // Tracks whether a pod IP ever resolved, so a deadline that fires + // with no IP is attributed to `pod_never_ready` rather than to a + // proxy/guest phase the wait never reached. + let mut resolved_ip_seen = false; + // Tracks whether any guest-ready probe returned `Code::Unavailable`. + // Cascade-amplifier signal: a deadline that fires after a probe + // genuinely returned gRPC `Unavailable` is the node-mgr-brownout + // symptom, and the timeout message names node-mgr so callers can + // classify the failure and route cleanup to the reconciler instead + // of spawning more cleanup load. TCP connect failures and per-probe + // deadline misses do NOT set this — they have other dominant causes + // (e.g. a wedged sbx-mgr) and naming node-mgr for them sends the + // on-call chasing the wrong service. + let mut saw_unavailable_probe = false; + let ( + selected_route_identity, + mut selected_route_pod_ip, + pre_resolved_pod_ip, + resolve_legacy, + ) = match pod { + CommandReadyPod::PreResolved(pod_ip) => (None, None, Some(pod_ip), false), + CommandReadyPod::ResolveLegacy => (None, None, None, true), + CommandReadyPod::SelectedRoute { + route_identity, + pod_ip, + } => (Some(route_identity), pod_ip, None, false), + }; + let mut connection: Option<(PodIp, RuntimeClient)> = None; + let mut selected_pod_resolution_error = None; + + loop { + if let Some(route_identity) = selected_route_identity + && selected_route_pod_ip.is_none() + { + match self.selected_wake_pod_ip(sandbox_id, route_identity).await { + Ok(pod_ip) => { + selected_route_pod_ip = pod_ip; + selected_pod_resolution_error = None; + } + Err(SubstrateError::Timeout { message, .. }) => { + // A live route remains selected; retry transient + // apiserver resolution at the slow cadence through the + // caller's readiness deadline. Identity/UID changes + // stay terminal and never enter this arm. + selected_pod_resolution_error = Some(message); + } + Err(error) => return Err(error), + } + } + let resolved_pod_ip = if resolve_legacy { + self.resolve_pod_ip(sandbox_id).await? + } else { + selected_route_pod_ip.or(pre_resolved_pod_ip) + }; + if let Some(pod_ip) = resolved_pod_ip { + resolved_ip_seen = true; + if connection + .as_ref() + .is_none_or(|(connected_ip, _)| *connected_ip != pod_ip) + { + let connect_started_at = Instant::now(); + let client = Self::pod_worker_client( + pod_ip, + self.k8s.sandbox_proxy_port, + START_WAIT_CONNECT_TIMEOUT.min(remaining_ready_window(deadline)), + ) + .await; + if client.is_some() { + record_api_wait_ready_latency( + sandbox_id, + metric_identity, + "node_api_connect", + "success", + connect_started_at, + None, + ); + } + connection = client.map(|client| (pod_ip, client)); + if connection.is_none() && selected_route_identity.is_some() { + // Before retrying a failed authenticated connection, + // revalidate the live Pod UID/IP and selected route. + selected_route_pod_ip = None; + } + } + // A failed TCP connect to the sandbox pod proxy is NOT a + // node-mgr signal: the proxy can be down because the shim's + // LaunchSandbox is hung on a wedged sbx-mgr just as easily + // as on a stuck node-mgr. The deadline classification below + // reports it as `proxy_unreachable` (via + // `node_api_connected_at` staying `None`) without naming a + // service, and the create path's defer-cleanup decision + // keys off the `Timeout` variant itself. + let mut reset_connection = false; + if let Some((_, client)) = connection.as_mut() { + if node_api_connected_at.is_none() { + node_api_connected_at = Some(Instant::now()); + record_api_wait_ready_latency( + sandbox_id, + metric_identity, + "node_api_first_connect", + "success", + started_at, + None, + ); + record_api_wait_ready_latency( + sandbox_id, + metric_identity, + "placement", + "success", + started_at, + None, + ); + } + + let probe_started_at = Instant::now(); + // No probe outlives the wait's deadline, so a short wait, + // such as a Native create's, ends when it says. + let probe_timeout = + START_WAIT_COMMAND_PROBE_TIMEOUT.min(remaining_ready_window(deadline)); + let probe = client.spaced_wait_ready(wait_ready_lifecycle_request( + SpacedWaitReadyRequest { + sandbox_id: sandbox_id.to_string(), + timeout: Some(duration_to_proto(probe_timeout)), + }, + )); + match timeout(probe_timeout, probe).await { + Ok(Ok(_)) => { + record_api_wait_ready_latency( + sandbox_id, + metric_identity, + "command_probe", + "success", + probe_started_at, + None, + ); + record_api_wait_ready_latency( + sandbox_id, + metric_identity, + "total", + "success", + started_at, + None, + ); + if let Some(node_api_connected_at) = node_api_connected_at { + record_api_wait_ready_latency( + sandbox_id, + metric_identity, + "command_ready_after_placement", + "success", + node_api_connected_at, + Some("placement"), + ); + } + if let (Some(route_identity), Some(selected_pod_ip)) = + (selected_route_identity, selected_route_pod_ip) + { + return self + .selected_wake_binding( + sandbox_id, + route_identity, + selected_pod_ip, + ) + .await; + } + let execution = self + .store + .active_execution_status(sandbox_id) + .await? + .ok_or_else(|| SubstrateError::Unavailable { + message: "sandbox has no active Kubernetes execution".to_string(), + })?; + return Ok(ExecutionBinding { + execution_object_id: execution.pod_name, + runtime_endpoint: Self::endpoint_for_pod_ip( + pod_ip, + self.k8s.sandbox_proxy_port, + )?, + execution_generation: execution_generation_to_u64( + execution.generation, + )?, + }); + } + Ok(Err(err)) + if err.code() == Code::FailedPrecondition + && (err.message().contains("not started") + || err.message().contains("sandbox is starting") + || err.message().contains("wait for start to complete")) => {} + Ok(Err(err)) if err.code() == Code::Unavailable => { + saw_unavailable_probe = true; + reset_connection = true; + } + Ok(Err(err)) => { + record_api_wait_ready_error( + sandbox_id, + metric_identity, + "command_probe", + "grpc_error", + grpc_code_tag(err.code()), + ); + return Err(SubstrateError::Failed { + message: format!("sandbox failed before start completed: {err}"), + }); + } + Err(_) => { + // Per-probe deadline elapsed: connected to the + // proxy but `spaced_wait_ready` didn't respond + // in time. Not a node-mgr signal — the probe + // hung rather than returning `Unavailable` — so + // the eventual deadline reports `guest_not_ready` + // without naming a service. + reset_connection = true; + } + } + } + if reset_connection { + // Tonic channels reconnect internally. Once a probe fails, + // retaining the channel could silently reconnect to a + // reassigned Pod IP without rechecking the immutable UID. + // Rebuild legacy/pre-resolved transports too, matching the + // pre-cache behavior instead of burning the full deadline + // on one half-open channel. + connection = None; + if selected_route_identity.is_some() { + selected_route_pod_ip = None; + } + } + } + + if Instant::now() >= deadline { + if metric_identity.op == "create" { + crate::metrics::sandbox::api::create_command_ready_timeout( + sandbox_id, template, + ); + } + let phase = if !resolved_ip_seen { + WaitReadyTimeoutPhase::PodNeverReady + } else if node_api_connected_at.is_none() { + WaitReadyTimeoutPhase::ProxyUnreachable + } else { + WaitReadyTimeoutPhase::GuestNotReady + }; + let mut error = command_ready_timeout_error(phase, saw_unavailable_probe); + if let (SubstrateError::Timeout { message, .. }, Some(resolution_error)) = + (&mut error, selected_pod_resolution_error.as_deref()) + { + message.push_str(&format!("; last pod resolution error: {resolution_error}")); + } + return Err(error); + } + + let delay = poll_backoff.next_delay(); + // Recompute after connection/probe handling: either path may have + // invalidated a previously selected IP in this same iteration. + // The slow clamp must apply immediately or a brownout produces an + // uncached Pod GET and several store reads every 250 ms. + let waiting_for_selected_pod_ip = + selected_route_identity.is_some() && selected_route_pod_ip.is_none(); + let delay = if waiting_for_selected_pod_ip { + delay + .max(START_WAIT_SLOW_POLL_INTERVAL) + .min(deadline.saturating_duration_since(Instant::now())) + } else { + delay + }; + sleep(delay).await; + } + } + + pub(in crate::controllers::substrate::kubernetes) async fn poll_connected_client_until_command_ready( + &self, + client: &mut NodeApiClient, + sandbox_id: SandboxId, + metric_identity: crate::metrics::sandbox::api::SandboxApiMetricIdentity, + ready_timeout: Duration, + binding: ExecutionBinding, + template: Option<&str>, + ) -> Result { + let probes = match Self::probe_connected_client_until_command_ready( + client, + sandbox_id, + metric_identity, + ready_timeout, + ) + .await? + { + ConnectedCommandReadiness::Ready => return Ok(binding), + ConnectedCommandReadiness::TimedOut(probes) => probes, + }; + if metric_identity.op == "create" { + crate::metrics::sandbox::api::create_command_ready_timeout(sandbox_id, template); + } + // The caller reached the node for the adoption's setup and Wake, so + // the timeout names the guest's phase. A probe that could not reach + // the node also ends in `DeadlineExceeded`; the warning carries what + // the probes returned. Keep it out of the message: a transport + // signature there would make the timeout reclaimable and spend + // another readiness budget on the same pod. + tracing::warn!( + target: super::LOG_TARGET, + sandbox_id = %sandbox_id, + deadline_exceeded_probes = probes.deadline_exceeded, + last_probe_code = ?probes.last_status.as_ref().map(tonic::Status::code), + last_probe_message = probes.last_status.as_ref().map(tonic::Status::message), + "pooled sandbox command readiness wait timed out" + ); + Err(command_ready_timeout_error( + WaitReadyTimeoutPhase::GuestNotReady, + probes.saw_unavailable, + )) + } + + /// Probes the connected node until the guest reports command readiness + /// or `ready_timeout` passes. Starts no probe once the deadline has + /// passed: one with no budget left would end before it reached the node. + pub(in crate::controllers::substrate::kubernetes) async fn probe_connected_client_until_command_ready( + client: &mut NodeApiClient, + sandbox_id: SandboxId, + metric_identity: crate::metrics::sandbox::api::SandboxApiMetricIdentity, + ready_timeout: Duration, + ) -> Result { + let started_at = Instant::now(); + let deadline = started_at + ready_timeout; + let mut poll_backoff = CommandReadyPollBackoff::new(started_at, deadline); + let node_api_connected_at = Instant::now(); + let mut probes = SwallowedCommandProbes::default(); + + record_api_wait_ready_latency( + sandbox_id, + metric_identity, + "node_api_first_connect", + "success", + started_at, + None, + ); + record_api_wait_ready_latency( + sandbox_id, + metric_identity, + "placement", + "success", + started_at, + None, + ); + + loop { + let probe_started_at = Instant::now(); + if probe_started_at >= deadline { + return Ok(ConnectedCommandReadiness::TimedOut(probes)); + } + + let probe_timeout = (START_WAIT_COMMAND_PROBE_TIMEOUT + + START_WAIT_COMMAND_PROBE_CLIENT_MARGIN) + .min(deadline.saturating_duration_since(probe_started_at)); + let mut worker_client = RetryingWorkerApiClient::new(client); + let probe = worker_client.spaced_wait_ready_with_metadata( + wait_ready_lifecycle_request(SpacedWaitReadyRequest { + sandbox_id: sandbox_id.to_string(), + timeout: Some(duration_to_proto(START_WAIT_COMMAND_PROBE_TIMEOUT)), + }), + probe_timeout, + ); + match timeout(probe_timeout, probe).await { + Ok(Ok(_)) => { + record_api_wait_ready_latency( + sandbox_id, + metric_identity, + "command_probe", + "success", + probe_started_at, + None, + ); + record_api_wait_ready_latency( + sandbox_id, + metric_identity, + "total", + "success", + started_at, + None, + ); + record_api_wait_ready_latency( + sandbox_id, + metric_identity, + "command_ready_after_placement", + "success", + node_api_connected_at, + Some("placement"), + ); + return Ok(ConnectedCommandReadiness::Ready); + } + Ok(Err(err)) + if err.code() == Code::FailedPrecondition + && (err.message().contains("not started") + || err.message().contains("sandbox is starting") + || err.message().contains("wait for start to complete")) => + { + probes.last_status = Some(err); + } + Ok(Err(err)) if err.code() == Code::Unavailable => { + probes.saw_unavailable = true; + probes.last_status = Some(err); + } + // Not ready yet, like the outer timeout below: the readiness + // deadline, not one probe, decides when the guest has failed + // to start. Three sources end a probe this way: the client's + // per-probe deadline, which ends a probe for a guest that is + // not ready because the node keeps waiting for it; the + // retrying client running out of its budget while the node + // refuses connections; and the node's own expired wait. + Ok(Err(err)) if err.code() == Code::DeadlineExceeded => { + probes.deadline_exceeded += 1; + probes.last_status = Some(err); + } + Ok(Err(err)) => { + record_api_wait_ready_error( + sandbox_id, + metric_identity, + "command_probe", + "grpc_error", + grpc_code_tag(err.code()), + ); + return Err(SubstrateError::Failed { + message: format!("sandbox failed before start completed: {err}"), + }); + } + // The same bound as the client's deadline, which usually + // fires first. + Err(_) => probes.deadline_exceeded += 1, + } + + sleep(poll_backoff.next_delay()).await; + } + } + + pub(in crate::controllers::substrate::kubernetes) async fn worker_client_for_pod_ip( + &self, + pod_ip: PodIp, + ) -> Result { + let endpoint = Self::endpoint_for_pod_ip(pod_ip, self.k8s.sandbox_proxy_port) + .map_err(ControllerError::from)?; + connect_worker(endpoint).await + } + + /// [`Self::worker_client_for_pod_ip`] on the channel kept for `pod`'s + /// instance while its connection is open; see + /// [`super::super::pod_worker_channels`]. A failed dial fails the same way. + pub(in crate::controllers::substrate::kubernetes) async fn kept_worker_client( + &self, + pod: &ResolvedPodInstance, + ) -> Result { + let port = self.k8s.sandbox_proxy_port; + let key = super::super::pod_worker_channels::PodWorkerKey { + addr: pod.ip.socket_addr(port), + pod_uid: pod.pod_uid.clone(), + generation: pod.generation, + }; + let pod_ip = pod.ip; + self.pod_worker_channels + .client(key, async move { + let endpoint = + Self::endpoint_for_pod_ip(pod_ip, port).map_err(ControllerError::from)?; + crate::controllers::substrate::connect_worker_watched(endpoint).await + }) + .await + } + + /// The kept worker client a runtime or access path hands out for + /// `sandbox_id`'s resolved `pod`. A Native data-plane request (see + /// [`crate::controllers::substrate::native_access`]) gets + /// [`Self::native_kept_worker_client`]; every other caller gets + /// [`Self::kept_worker_client`], unchanged. + pub(in crate::controllers::substrate::kubernetes) async fn access_kept_worker_client( + &self, + sandbox_id: SandboxId, + pod: &ResolvedPodInstance, + ) -> Result { + if crate::controllers::substrate::native_access::active() { + return self.native_kept_worker_client(sandbox_id, pod).await; + } + self.kept_worker_client(pod).await + } + + /// [`Self::kept_worker_client`] for a Native data-plane request, which + /// fails over from a pod that does not answer instead of waiting out the + /// full connect budget on its address. + /// + /// A miss first dials once within [`POD_WORKER_FIRST_DIAL_TIMEOUT`]. If + /// that fails, the sandbox's pod is resolved again: the same instance is + /// dialed with the full connect budget, as every other caller dials it; a + /// replacement is dialed at its own address; and no pod returns the first + /// dial's error, so the caller's recovery path takes over at once. The + /// client also reports how it used its connection if the request holds it + /// long; see [`super::super::super::KeptCallReport`]. + pub(in crate::controllers::substrate::kubernetes) async fn native_kept_worker_client( + &self, + sandbox_id: SandboxId, + pod: &ResolvedPodInstance, + ) -> Result { + let first = self + .kept_worker_client_reported(pod, Some(POD_WORKER_FIRST_DIAL_TIMEOUT)) + .await; + let Err(first_error) = first else { + return first; + }; + let current = match self.resolve_pod_instance(sandbox_id).await { + Ok(Some(current)) => current, + Ok(None) => { + pplx_space_grpc_metrics::client_channel_cache("worker-node-api", "pod_gone"); + return Err(first_error); + } + Err(_) => return Err(first_error), + }; + if current.sandbox_restoring { + // A replacement mid-restore isn't dialed for a user request (see + // `join_restore_before_dial`); the caller's recovery joins it. + return Err(first_error); + } + if !current.same_instance(pod) { + pplx_space_grpc_metrics::client_channel_cache("worker-node-api", "pod_moved"); + } + self.kept_worker_client_reported(¤t, None).await + } + + /// The kept client for `pod`, its miss dialed with the default policy + /// or, given `first_dial`, once within it; reported as + /// [`super::super::super::KeptCallReport`] describes. + async fn kept_worker_client_reported( + &self, + pod: &ResolvedPodInstance, + first_dial: Option, + ) -> Result { + let port = self.k8s.sandbox_proxy_port; + let key = super::super::pod_worker_channels::PodWorkerKey { + addr: pod.ip.socket_addr(port), + pod_uid: pod.pod_uid.clone(), + generation: pod.generation, + }; + let pod_ip = pod.ip; + let (client, handout) = self + .pod_worker_channels + .client_with_handout(key, async move { + let endpoint = + Self::endpoint_for_pod_ip(pod_ip, port).map_err(ControllerError::from)?; + let Some(bound) = first_dial else { + return crate::controllers::substrate::connect_worker_watched(endpoint).await; + }; + // Bounding the attempt from outside, rather than through the + // endpoint's connect timeout, leaves the kept channel's own + // redials at the bound every other caller's channel has. + tokio::time::timeout( + bound, + crate::controllers::substrate::connect_worker_watched_with( + endpoint, + pplx_space_common_grpc::GrpcRetryPolicy::none(), + ), + ) + .await + .unwrap_or_else(|_| { + Err(ControllerError::service_unavailable(format!( + "node-api not reachable: no connection within {bound:?}" + ))) + }) + }) + .await?; + Ok(client.with_report(handout.kept, handout.connection_age, handout.idle)) + } + + pub(in crate::controllers::substrate::kubernetes) fn should_allow_access_recovery( + sandbox: &Sandbox, + activity: ExecutionActivityKind, + ) -> Result<(), ControllerError> { + if is_dormant_lifecycle(&sandbox.lifecycle) + && !activity.allows_implicit_wake(&sandbox.auto_lifecycle) + { + return Err( + match sandbox + .lifecycle + .parse::() + { + Ok(lifecycle) => ControllerError::sandbox_not_running( + crate::controllers::SandboxNotRunning { + sandbox_id: sandbox.id, + lifecycle, + }, + "sandbox is not running", + ), + Err(_) => ControllerError::new( + axum::http::StatusCode::CONFLICT, + "sandbox is not running", + ), + }, + ); + } + + if !is_wake_recovery_lifecycle(&sandbox.lifecycle) { + return Err(ControllerError::service_unavailable(format!( + "sandbox cannot be recovered while lifecycle is {}", + sandbox.lifecycle + ))); + } + + Ok(()) + } +}