From 5128730c604b1f8456beb17853c5126241a758d2 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 30 Nov 2026 14:18:07 -0800 Subject: [PATCH 1/7] fix(kubernetes): keep HA reconciliation from deleting a restarting supervisor Only the lease holder reconciles sandbox runtimes, while any gateway replica can serve a lifecycle RPC, so the driver's process-local lifecycle gate does not exclude a restart on another replica. A reconciliation that refreshed a stopped Sandbox could delete the supervisor Pod the restart had just created under the same name, and the restart then failed with "sandbox not found" when it ungated that Pod. Reconciliation could also suspend a bootstrap whose fence bindings the lifecycle request had not recorded yet. Restart now marks the Sandbox Preparing before it creates the supervisor Pod. Reconciliation leaves a fresh Preparing bootstrap to its request until the bootstrap grace period expires, and rereads the Sandbox before deleting a stopped sandbox's supervisor Pod, skipping the deletion if the Sandbox changed. Signed-off-by: Matthew Grossman --- crates/openshell-driver-kubernetes/README.md | 8 + .../openshell-driver-kubernetes/src/driver.rs | 255 +++++++++++++----- .../src/lifecycle_tests.rs | 192 ++++++++++++- 3 files changed, 379 insertions(+), 76 deletions(-) diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index bb2c4e49fb..2a556515ac 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -398,6 +398,14 @@ snapshot cannot delete a supervisor created by a concurrent restart in the same driver instance. The gate preserves concurrency across sandboxes; it does not provide distributed exclusion between separate gateway or driver processes. +In a high-availability gateway, only the lease holder reconciles, while any +replica can serve a lifecycle RPC. The Sandbox CR coordinates the two. A +restart marks the CR `Preparing` before it creates the supervisor Pod, and +reconciliation leaves a fresh `Preparing` bootstrap to its request until the +bootstrap grace period expires. Before it deletes the supervisor Pod of a +stopped sandbox, reconciliation reads the CR again and skips the deletion if the +CR changed after its refresh. + ## GPU Support When a sandbox requests GPU support, the driver checks node allocatable capacity diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index fab746d814..794a8934e2 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -4452,33 +4452,6 @@ impl KubernetesComputeDriver { agent_gid, ), )?; - let supervisor = match &placement { - SupervisorPlacement::Dedicated => GenerationSupervisor::Dedicated { - pod_uid: self - .create_sandbox_runtime_supervisor( - &namespace, - &names, - sandbox_id, - &sandbox_name, - sandbox_runtime_sandbox_owner_reference( - cr_name, - cr_uid, - &sandbox_api.resource.api_version, - false, - ), - agent_uid, - agent_gid, - &main_process_spec, - &log_level, - staged.upstream_proxy_ca_bundle.is_some(), - ) - .await?, - connection: control_connection, - }, - SupervisorPlacement::Shared { route } => GenerationSupervisor::Shared { - route: route.clone(), - }, - }; let mut volumes = object .data @@ -4505,6 +4478,41 @@ impl KubernetesComputeDriver { sandbox_secret["secretName"] = serde_json::json!(names.sandbox_secret); let image_pull_secrets = self.generation_image_pull_secret_names(&names); let restart = async { + // Only the lease holder reconciles, and its lifecycle gate does + // not cover requests served by other replicas. Mark the Sandbox + // Preparing before creating the supervisor Pod so reconciliation + // that refreshed the stopped Sandbox cannot delete the new Pod. + patch_dynamic_object_with_resource_version_retry(&sandbox_api.api, cr_name, |version| { + sandbox_runtime_restart_begin_patch(version, generation.as_str()) + }) + .await?; + let supervisor = match &placement { + SupervisorPlacement::Dedicated => GenerationSupervisor::Dedicated { + pod_uid: self + .create_sandbox_runtime_supervisor( + &namespace, + &names, + sandbox_id, + &sandbox_name, + sandbox_runtime_sandbox_owner_reference( + cr_name, + cr_uid, + &sandbox_api.resource.api_version, + false, + ), + agent_uid, + agent_gid, + &main_process_spec, + &log_level, + staged.upstream_proxy_ca_bundle.is_some(), + ) + .await?, + connection: control_connection, + }, + SupervisorPlacement::Shared { route } => GenerationSupervisor::Shared { + route: route.clone(), + }, + }; patch_dynamic_object_with_resource_version_retry( &sandbox_api.api, cr_name, @@ -4559,20 +4567,24 @@ impl KubernetesComputeDriver { &launch_authentication, staged, ) - .await + .await?; + Ok(supervisor) } .await; - if let Err(error) = restart { - // The restart patch may not have recorded the sandbox instance yet. - self.remove_shared_instance(&placement); - if let Err(rollback_error) = self.stop_sandbox_inner(sandbox_id).await { - return Err(KubernetesDriverError::Message(format!( - "restart failed: {error}; rollback remains pending: {rollback_error}" - ))); + let supervisor = match restart { + Ok(supervisor) => supervisor, + Err(error) => { + // The restart patch may not have recorded the sandbox instance yet. + self.remove_shared_instance(&placement); + if let Err(rollback_error) = self.stop_sandbox_inner(sandbox_id).await { + return Err(KubernetesDriverError::Message(format!( + "restart failed: {error}; rollback remains pending: {rollback_error}" + ))); + } + return Err(error); } - return Err(error); - } + }; Ok(kubernetes_runtime_identity( &namespace, cr_uid, @@ -4708,41 +4720,53 @@ impl KubernetesComputeDriver { .await .map_err(KubernetesDriverError::from_kube)? { - let deletion_timeout = kubernetes_pod_termination_timeout(&pod); - match pods - .delete( - &names.supervisor_pod, - &DeleteParams::foreground().preconditions(Preconditions { - uid: pod.metadata.uid, - resource_version: None, - }), - ) + self.delete_sandbox_runtime_supervisor_pod_with_uid(namespace, &names, pod) + .await?; + } + Ok(()) + } + + /// Delete `pod` by UID and wait until it is gone. + async fn delete_sandbox_runtime_supervisor_pod_with_uid( + &self, + namespace: &str, + names: &SandboxRuntimeNames, + pod: Pod, + ) -> Result<(), KubernetesDriverError> { + let pods = Api::::namespaced(self.client.clone(), namespace); + let deletion_timeout = kubernetes_pod_termination_timeout(&pod); + match pods + .delete( + &names.supervisor_pod, + &DeleteParams::foreground().preconditions(Preconditions { + uid: pod.metadata.uid, + resource_version: None, + }), + ) + .await + { + Ok(_) => {} + Err(KubeError::Api(error)) if error.code == 404 => return Ok(()), + Err(error) => return Err(KubernetesDriverError::from_kube(error)), + } + let deadline = tokio::time::Instant::now() + deletion_timeout; + loop { + if pods + .get_opt(&names.supervisor_pod) .await + .map_err(KubernetesDriverError::from_kube)? + .is_none() { - Ok(_) => {} - Err(KubeError::Api(error)) if error.code == 404 => return Ok(()), - Err(error) => return Err(KubernetesDriverError::from_kube(error)), + return Ok(()); } - let deadline = tokio::time::Instant::now() + deletion_timeout; - loop { - if pods - .get_opt(&names.supervisor_pod) - .await - .map_err(KubernetesDriverError::from_kube)? - .is_none() - { - break; - } - if tokio::time::Instant::now() >= deadline { - return Err(KubernetesDriverError::Message(format!( - "timed out after {}s waiting for supervisor Pod deletion", - deletion_timeout.as_secs() - ))); - } - tokio::time::sleep(Duration::from_millis(100)).await; + if tokio::time::Instant::now() >= deadline { + return Err(KubernetesDriverError::Message(format!( + "timed out after {}s waiting for supervisor Pod deletion", + deletion_timeout.as_secs() + ))); } + tokio::time::sleep(Duration::from_millis(100)).await; } - Ok(()) } async fn delete_sandbox_runtime_supervisor( @@ -5046,6 +5070,20 @@ impl KubernetesComputeDriver { continue; } let object = refreshed; + // A lifecycle request on another replica holds another gate. It + // keeps the bootstrap Preparing until it has bound and released + // the generation, so leave a fresh one to it and reap it once + // stale. + if sandbox_runtime_bootstrap_phase(&object) + == Some(SandboxRuntimeBootstrapPhase::Preparing) + && !sandbox_runtime_bootstrap_is_stale( + &object, + SystemTime::now(), + Duration::from_secs(self.config.runtime_bootstrap_grace_seconds), + ) + { + continue; + } if let Err(error) = self.admit_stored_resources(&object).await { warn!(%sandbox_id, reason = %error.message(), "Sandbox resource admission revalidation failed"); if error.code() == tonic::Code::FailedPrecondition { @@ -5216,6 +5254,7 @@ impl KubernetesComputeDriver { } match self .reconcile_sandbox_runtime_supervisor( + &api.api, &sandbox_id, namespace, desired_running, @@ -5223,7 +5262,8 @@ impl KubernetesComputeDriver { ) .await { - Ok(()) => {} + Ok(true) => {} + Ok(false) => continue, Err(KubernetesDriverError::Precondition(error)) => { warn!(sandbox_id, %error, "sandbox-runtime companion is missing; suspending workload"); self.suspend_sandbox_runtime_after_dependency_failure(&lookup_api, &object) @@ -5621,22 +5661,29 @@ impl KubernetesComputeDriver { } } + /// Returns `false` without deleting anything when the Sandbox changed + /// after `object` was read. async fn reconcile_sandbox_runtime_supervisor( &self, + sandbox_api: &Api, sandbox_id: &str, namespace: &str, desired_running: bool, object: &DynamicObject, - ) -> Result<(), KubernetesDriverError> { - let generations = sandbox_runtime_generation(object); + ) -> Result { if !desired_running { return self - .delete_sandbox_runtime_supervisor(sandbox_id, namespace, generations.as_slice()) + .delete_stopped_sandbox_runtime_supervisor( + sandbox_api, + sandbox_id, + namespace, + object, + ) .await; } if let SupervisorPlacement::Shared { .. } = supervisor_placement(object)? { // Sandbox instance availability is part of control availability. - return Ok(()); + return Ok(true); } // The boundary Service was checked by verify_sandbox_runtime_control_path. let names = SandboxRuntimeNames::new(sandbox_id); @@ -5658,7 +5705,50 @@ impl KubernetesComputeDriver { names.supervisor_pod )) })?; - Ok(()) + Ok(true) + } + + /// Delete the supervisor Pod and generation Secrets of a stopped Sandbox. + /// + /// A restart on another replica may create a new supervisor Pod under the + /// same name after `object` was read. It marks the Sandbox first, so the + /// Pod is deleted only if the Sandbox is unchanged after the Pod is read. + async fn delete_stopped_sandbox_runtime_supervisor( + &self, + sandbox_api: &Api, + sandbox_id: &str, + namespace: &str, + object: &DynamicObject, + ) -> Result { + let names = SandboxRuntimeNames::new(sandbox_id); + let pods = Api::::namespaced(self.client.clone(), namespace); + if let Some(pod) = pods + .get_opt(&names.supervisor_pod) + .await + .map_err(KubernetesDriverError::from_kube)? + { + let name = object.metadata.name.as_deref().unwrap_or_default(); + let current = sandbox_api + .get_opt(name) + .await + .map_err(KubernetesDriverError::from_kube)?; + let unchanged = current.is_some_and(|current| { + current.metadata.uid == object.metadata.uid + && current.metadata.resource_version == object.metadata.resource_version + }); + if !unchanged { + return Ok(false); + } + self.delete_sandbox_runtime_supervisor_pod_with_uid(namespace, &names, pod) + .await?; + } + self.delete_sandbox_runtime_generation_secrets( + sandbox_id, + namespace, + sandbox_runtime_generation(object).as_slice(), + ) + .await?; + Ok(true) } fn spawn_sandbox_runtime_periodic_reconcile( @@ -8817,6 +8907,25 @@ fn sandbox_runtime_stop_begin_patch(resource_version: &str) -> serde_json::Value }) } +fn sandbox_runtime_restart_begin_patch( + resource_version: &str, + generation: &str, +) -> serde_json::Value { + serde_json::json!({ + "metadata": { + "resourceVersion": resource_version, + "annotations": { + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAPPING: "true", + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_STARTED_AT: openshell_core::time::now_ms().to_string(), + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION: "restart", + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE: SandboxRuntimeBootstrapPhase::Preparing.as_str(), + ANNOTATION_SANDBOX_RUNTIME_GENERATION: generation, + ANNOTATION_SANDBOX_RUNTIME_READINESS: "unavailable", + }, + }, + }) +} + fn sandbox_runtime_suspension_patch( api_version: &str, resource_version: &str, diff --git a/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs b/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs index afe894fd39..2ff39542cb 100644 --- a/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs +++ b/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs @@ -185,7 +185,7 @@ mod lifecycle_reconciliation { } fn restarted_snapshot(version: &str) -> serde_json::Value { - let mut object = snapshot(version, Some(SandboxRuntimeBootstrapPhase::Preparing)); + let mut object = snapshot(version, Some(SandboxRuntimeBootstrapPhase::Released)); object["metadata"]["resourceVersion"] = serde_json::json!("43"); let annotations = &mut object["metadata"]["annotations"]; annotations[ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION] = serde_json::json!("restart"); @@ -322,6 +322,192 @@ mod lifecycle_reconciliation { ] } + type RecordedRequests = Arc>>; + + /// A cluster as seen by the lease holder's reconciliation while another + /// gateway replica runs a lifecycle RPC. Each read of the Sandbox + /// resource returns the next of `sandbox_reads`, repeating the last. The + /// supervisor Pod exists until it is deleted. Every request is recorded, + /// and requests the fixture does not model fail with 404. + fn other_replica_driver( + version: &'static str, + sandbox_reads: Vec, + ) -> (KubernetesComputeDriver, RecordedRequests) { + let names = SandboxRuntimeNames::new("sandbox-1"); + let mut fence = workload_fence("openshell", &names, 5500); + for (policy, component) in [ + (&mut fence.workload_policy, "sandbox-workload-fence"), + (&mut fence.supervisor_policy, "sandbox-supervisor-egress"), + ] { + policy.metadata.labels.get_or_insert_default().extend([ + ( + LABEL_MANAGED_BY.to_string(), + LABEL_MANAGED_BY_VALUE.to_string(), + ), + ("openshell.ai/component".to_string(), component.to_string()), + ]); + policy.metadata.uid = Some(format!("{component}-uid")); + policy.metadata.generation = Some(1); + } + let workload_policy = serde_json::to_value(&fence.workload_policy).unwrap(); + let supervisor_policy = serde_json::to_value(&fence.supervisor_policy).unwrap(); + let sandboxes = format!("/apis/agents.x-k8s.io/{version}/namespaces/openshell/sandboxes"); + let sandbox = format!("{sandboxes}/sandbox-cr"); + let requests = RecordedRequests::default(); + let recorded = requests.clone(); + let sandbox_reads = Arc::new(std::sync::Mutex::new(VecDeque::from(sandbox_reads))); + let supervisor_deleted = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let service = tower::service_fn(move |request: http::Request| { + let method = request.method().clone(); + let path = request.uri().path().to_string(); + recorded.lock().unwrap().push((method.clone(), path.clone())); + let next_sandbox = || { + let mut reads = sandbox_reads.lock().unwrap(); + if reads.len() > 1 { + reads.pop_front().unwrap() + } else { + reads.front().unwrap().clone() + } + }; + let ok = |body: serde_json::Value| Some((http::StatusCode::OK, body)); + let response = match (&method, path.as_str()) { + (&http::Method::GET, path) if path == sandboxes => ok(serde_json::json!({ + "apiVersion": format!("{SANDBOX_GROUP}/{version}"), + "kind": "SandboxList", + "items": [sandbox_reads.lock().unwrap().front().unwrap().clone()] + })), + (&http::Method::GET, path) if path == sandbox => ok(next_sandbox()), + ( + &http::Method::GET, + "/apis/networking.k8s.io/v1/namespaces/openshell/networkpolicies/openshell-sandbox-workloads", + ) => ok(workload_policy.clone()), + ( + &http::Method::GET, + "/apis/networking.k8s.io/v1/namespaces/openshell/networkpolicies/openshell-sandbox-supervisors", + ) => ok(supervisor_policy.clone()), + (&http::Method::GET, "/api/v1/namespaces/openshell/pods/os-supervisor-sandbox-1") + if !supervisor_deleted.load(std::sync::atomic::Ordering::SeqCst) => + { + ok(serde_json::json!({ + "apiVersion": "v1", "kind": "Pod", + "metadata": { + "name": "os-supervisor-sandbox-1", + "uid": "restarting-supervisor-uid" + }, + "spec": {"containers": []}, "status": {"phase": "Pending"} + })) + } + ( + &http::Method::DELETE, + "/api/v1/namespaces/openshell/pods/os-supervisor-sandbox-1", + ) => { + supervisor_deleted.store(true, std::sync::atomic::Ordering::SeqCst); + ok(serde_json::json!({ + "apiVersion": "v1", "kind": "Status", "status": "Success" + })) + } + _ => None, + }; + let (status, body) = response.unwrap_or_else(|| { + ( + http::StatusCode::NOT_FOUND, + serde_json::json!({ + "apiVersion": "v1", "kind": "Status", "status": "Failure", + "reason": "NotFound", "code": 404, "message": "not modeled" + }), + ) + }); + async move { Ok::<_, std::convert::Infallible>(kube_test_response(status, body)) } + }); + let client = Client::new(service, "openshell"); + let driver = KubernetesComputeDriver { + client: client.clone(), + watch_client: client, + sandbox_api_version: Arc::new(OnceCell::new()), + lifecycle_gates: Arc::default(), + config: KubernetesComputeConfig::default(), + network_trust_bundle: None, + operator_allowlist: None, + shared_supervisor: None, + }; + driver.sandbox_api_version.set(version).unwrap(); + (driver, requests) + } + + /// A stopped Sandbox that a lifecycle RPC on another replica has begun to + /// boot: the workload is still suspended and no generation is bound. + fn claimed_snapshot(version: &str, operation: &str) -> serde_json::Value { + let mut object = snapshot(version, Some(SandboxRuntimeBootstrapPhase::Preparing)); + object["metadata"]["resourceVersion"] = serde_json::json!("43"); + let annotations = object["metadata"]["annotations"].as_object_mut().unwrap(); + annotations.remove(ANNOTATION_SANDBOX_RUNTIME_SUPERVISOR_UID); + annotations.insert( + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION.to_string(), + serde_json::json!(operation), + ); + annotations.insert( + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_STARTED_AT.to_string(), + serde_json::json!(openshell_core::time::now_ms().to_string()), + ); + object + } + + fn mutations(requests: &RecordedRequests) -> Vec<(http::Method, String)> { + requests + .lock() + .unwrap() + .iter() + .filter(|(method, _)| *method != http::Method::GET) + .cloned() + .collect() + } + + // Issue #5781: only the lease holder reconciles, but a start may run on + // any replica, so the local lifecycle gate cannot exclude it. The holder + // refreshed the stopped Sandbox just before the restart claimed it and + // then read the supervisor Pod the restart had created. + #[tokio::test] + async fn reconciliation_preserves_a_supervisor_another_replica_is_restarting() { + for version in [SANDBOX_VERSION_V1ALPHA1, SANDBOX_VERSION_V1BETA1] { + let (driver, requests) = other_replica_driver( + version, + vec![snapshot(version, None), claimed_snapshot(version, "restart")], + ); + driver.reconcile_sandbox_runtime_resources().await; + assert_eq!(mutations(&requests), vec![], "{version}"); + } + } + + #[tokio::test] + async fn reconciliation_deletes_the_supervisor_of_an_unchanged_stopped_sandbox() { + for version in [SANDBOX_VERSION_V1ALPHA1, SANDBOX_VERSION_V1BETA1] { + let (driver, requests) = other_replica_driver(version, vec![snapshot(version, None)]); + driver.reconcile_sandbox_runtime_resources().await; + assert!( + mutations(&requests).contains(&( + http::Method::DELETE, + "/api/v1/namespaces/openshell/pods/os-supervisor-sandbox-1".to_string() + )), + "{version}" + ); + } + } + + // A lifecycle RPC on another replica records the generation's bindings + // only once its workload Pod exists. Until then, a Preparing bootstrap is + // not drift and must not be suspended. + #[tokio::test] + async fn reconciliation_leaves_a_fresh_bootstrap_to_its_lifecycle_request() { + for version in [SANDBOX_VERSION_V1ALPHA1, SANDBOX_VERSION_V1BETA1] { + for operation in ["create", "restart"] { + let (driver, requests) = + other_replica_driver(version, vec![claimed_snapshot(version, operation)]); + driver.reconcile_sandbox_runtime_resources().await; + assert_eq!(mutations(&requests), vec![], "{version} {operation}"); + } + } + } + #[tokio::test] async fn stale_stop_snapshots_cannot_delete_a_restarted_supervisor() { for version in [SANDBOX_VERSION_V1ALPHA1, SANDBOX_VERSION_V1BETA1] { @@ -364,8 +550,8 @@ mod lifecycle_reconciliation { .gate_for("sandbox-1") .lock_owned() .await; - // Restart may already have created its Pod while the CR is still - // stopped. Reconciliation must skip even reading that companion. + // Reconciliation must skip even reading the companions of a sandbox + // whose lifecycle request holds this replica's gate. driver.reconcile_sandbox_runtime_resources().await; drop(guard); driver.reconcile_sandbox_runtime_resources().await; From 447f041270cb48ce197c709d09186e2dfc196468 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 30 Nov 2026 14:38:18 -0800 Subject: [PATCH 2/7] refactor(kubernetes): fold Preparing into the reconcile phase dispatch Address review of the HA restart race fix: - Dispatch on the bootstrap phase once, after resource admission. A Preparing bootstrap is left to its lifecycle request and only reaped once stale, so the shared-control-policy exception for Preparing is no longer reachable and is removed. - Build bootstrap claim annotations in one helper for create, stop and restart. The restart Running patch no longer rewrites the claim or resets its grace clock. - Return unit from supervisor reconciliation; later writes are already pinned to the Sandbox resourceVersion. - Wait for the deleted supervisor Pod by UID so a replacement Pod with the same name does not stall reconciliation. - Share test fixtures and cover stale-bootstrap reaping and the UID wait. Signed-off-by: Matthew Grossman --- crates/openshell-driver-kubernetes/README.md | 5 +- .../openshell-driver-kubernetes/src/driver.rs | 284 +++++++++--------- .../src/lifecycle_tests.rs | 200 +++++++----- 3 files changed, 274 insertions(+), 215 deletions(-) diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index 2a556515ac..4a4c2e419e 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -401,8 +401,9 @@ provide distributed exclusion between separate gateway or driver processes. In a high-availability gateway, only the lease holder reconciles, while any replica can serve a lifecycle RPC. The Sandbox CR coordinates the two. A restart marks the CR `Preparing` before it creates the supervisor Pod, and -reconciliation leaves a fresh `Preparing` bootstrap to its request until the -bootstrap grace period expires. Before it deletes the supervisor Pod of a +reconciliation leaves a `Preparing` bootstrap to its request until the +bootstrap grace period expires, then reaps it: a stale restart is suspended and +a stale create is deleted. Before it deletes the supervisor Pod of a stopped sandbox, reconciliation reads the CR again and skips the deletion if the CR changed after its refresh. diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index 794a8934e2..631cd7f4e8 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -580,6 +580,49 @@ async fn patch_dynamic_object_with_resource_version_retry( .map_err(KubernetesDriverError::from_kube) } +/// Delete `pod` by UID and wait until it is gone. A Pod that has since been +/// created under the same name, such as by a restart on another replica, is +/// left running and does not extend the wait. +async fn delete_supervisor_pod_and_wait( + pods: &Api, + pod: Pod, +) -> Result<(), KubernetesDriverError> { + let name = pod.metadata.name.clone().unwrap_or_default(); + let uid = pod.metadata.uid.clone(); + let deletion_timeout = kubernetes_pod_termination_timeout(&pod); + match pods + .delete( + &name, + &DeleteParams::foreground().preconditions(Preconditions { + uid: uid.clone(), + resource_version: None, + }), + ) + .await + { + Ok(_) => {} + Err(KubeError::Api(error)) if error.code == 404 => return Ok(()), + Err(error) => return Err(KubernetesDriverError::from_kube(error)), + } + let deadline = tokio::time::Instant::now() + deletion_timeout; + loop { + let current = pods + .get_opt(&name) + .await + .map_err(KubernetesDriverError::from_kube)?; + if current.is_none_or(|current| current.metadata.uid != uid) { + return Ok(()); + } + if tokio::time::Instant::now() >= deadline { + return Err(KubernetesDriverError::Message(format!( + "timed out after {}s waiting for supervisor Pod deletion", + deletion_timeout.as_secs() + ))); + } + tokio::time::sleep(Duration::from_millis(100)).await; + } +} + impl From for openshell_core::ComputeDriverError { fn from(err: KubernetesDriverError) -> Self { match err { @@ -2688,26 +2731,11 @@ impl KubernetesComputeDriver { .to_string(), ); add_trace_context_annotation(&mut annotations); - annotations.insert( - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAPPING.to_string(), - "true".to_string(), - ); - annotations.insert( - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_STARTED_AT.to_string(), - openshell_core::time::now_ms().to_string(), - ); - annotations.insert( - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION.to_string(), - "create".to_string(), - ); - annotations.insert( - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE.to_string(), - SandboxRuntimeBootstrapPhase::Preparing.as_str().to_string(), - ); - annotations.insert( - ANNOTATION_SANDBOX_RUNTIME_GENERATION.to_string(), - generation.clone(), - ); + annotations.extend(sandbox_runtime_bootstrap_claim( + "create", + SandboxRuntimeBootstrapPhase::Preparing, + Some(&generation), + )); annotations.insert( ANNOTATION_SANDBOX_RUNTIME_MAIN_PROCESS_SPEC.to_string(), main_process_spec.clone(), @@ -2991,13 +3019,6 @@ impl KubernetesComputeDriver { ) })? .map_err(KubernetesDriverError::from_kube)?; - // A bootstrap still installing has not bound its policy yet. - if stored.is_none() - && sandbox_runtime_bootstrap_phase(object) - == Some(SandboxRuntimeBootstrapPhase::Preparing) - { - return Ok(()); - } let stored = stored.ok_or_else(|| { KubernetesDriverError::Precondition(format!( "shared control NetworkPolicy {} is missing", @@ -4529,13 +4550,9 @@ impl KubernetesComputeDriver { route.as_str().into(), ), }; + // The restart claim already started the bootstrap. running_patch["metadata"]["annotations"] = serde_json::json!({ - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAPPING: "true", - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_STARTED_AT: openshell_core::time::now_ms().to_string(), - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION: "restart", - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE: SandboxRuntimeBootstrapPhase::Preparing.as_str(), ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_SESSION: launch_authentication.supervisor.session_id.to_string(), - ANNOTATION_SANDBOX_RUNTIME_GENERATION: generation.as_str(), ANNOTATION_SANDBOX_RUNTIME_SUPERVISOR_UID: supervisor_uid, ANNOTATION_SANDBOX_RUNTIME_CONTROL_CONNECTION: control_connection.as_str(), ANNOTATION_SANDBOX_RUNTIME_CONTROL_GENERATION: generation.as_str(), @@ -4720,55 +4737,11 @@ impl KubernetesComputeDriver { .await .map_err(KubernetesDriverError::from_kube)? { - self.delete_sandbox_runtime_supervisor_pod_with_uid(namespace, &names, pod) - .await?; + delete_supervisor_pod_and_wait(&pods, pod).await?; } Ok(()) } - /// Delete `pod` by UID and wait until it is gone. - async fn delete_sandbox_runtime_supervisor_pod_with_uid( - &self, - namespace: &str, - names: &SandboxRuntimeNames, - pod: Pod, - ) -> Result<(), KubernetesDriverError> { - let pods = Api::::namespaced(self.client.clone(), namespace); - let deletion_timeout = kubernetes_pod_termination_timeout(&pod); - match pods - .delete( - &names.supervisor_pod, - &DeleteParams::foreground().preconditions(Preconditions { - uid: pod.metadata.uid, - resource_version: None, - }), - ) - .await - { - Ok(_) => {} - Err(KubeError::Api(error)) if error.code == 404 => return Ok(()), - Err(error) => return Err(KubernetesDriverError::from_kube(error)), - } - let deadline = tokio::time::Instant::now() + deletion_timeout; - loop { - if pods - .get_opt(&names.supervisor_pod) - .await - .map_err(KubernetesDriverError::from_kube)? - .is_none() - { - return Ok(()); - } - if tokio::time::Instant::now() >= deadline { - return Err(KubernetesDriverError::Message(format!( - "timed out after {}s waiting for supervisor Pod deletion", - deletion_timeout.as_secs() - ))); - } - tokio::time::sleep(Duration::from_millis(100)).await; - } - } - async fn delete_sandbox_runtime_supervisor( &self, sandbox_id: &str, @@ -5070,20 +5043,6 @@ impl KubernetesComputeDriver { continue; } let object = refreshed; - // A lifecycle request on another replica holds another gate. It - // keeps the bootstrap Preparing until it has bound and released - // the generation, so leave a fresh one to it and reap it once - // stale. - if sandbox_runtime_bootstrap_phase(&object) - == Some(SandboxRuntimeBootstrapPhase::Preparing) - && !sandbox_runtime_bootstrap_is_stale( - &object, - SystemTime::now(), - Duration::from_secs(self.config.runtime_bootstrap_grace_seconds), - ) - { - continue; - } if let Err(error) = self.admit_stored_resources(&object).await { warn!(%sandbox_id, reason = %error.message(), "Sandbox resource admission revalidation failed"); if error.code() == tonic::Code::FailedPrecondition { @@ -5098,31 +5057,40 @@ impl KubernetesComputeDriver { .as_deref() .unwrap_or(&self.config.namespace); let cr_name = object.metadata.name.as_deref().unwrap_or_default(); - if sandbox_runtime_bootstrap_phase(&object) - == Some(SandboxRuntimeBootstrapPhase::Releasing) - { - self.reconcile_sandbox_runtime_control_release( - &lookup_api, - &object, - &sandbox_id, - namespace, - cr_name, - ) - .await; - continue; - } - if sandbox_runtime_bootstrap_phase(&object) - == Some(SandboxRuntimeBootstrapPhase::Suspending) - { - self.reconcile_sandbox_runtime_suspending( - &lookup_api, - &object, - &sandbox_id, - namespace, - cr_name, - ) - .await; - continue; + match sandbox_runtime_bootstrap_phase(&object) { + Some(SandboxRuntimeBootstrapPhase::Preparing) => { + // The lifecycle request that set Preparing owns the + // bootstrap until it has bound and released the + // generation. It may run on another replica, outside this + // replica's lifecycle gate, so reconciliation only reaps + // it once the grace period runs out. + self.reap_stale_sandbox_runtime_bootstrap(&lookup_api, &object) + .await; + continue; + } + Some(SandboxRuntimeBootstrapPhase::Releasing) => { + self.reconcile_sandbox_runtime_control_release( + &lookup_api, + &object, + &sandbox_id, + namespace, + cr_name, + ) + .await; + continue; + } + Some(SandboxRuntimeBootstrapPhase::Suspending) => { + self.reconcile_sandbox_runtime_suspending( + &lookup_api, + &object, + &sandbox_id, + namespace, + cr_name, + ) + .await; + continue; + } + Some(SandboxRuntimeBootstrapPhase::Released) | None => {} } let names = SandboxRuntimeNames::new(&sandbox_id); let policies = Api::::namespaced(self.client.clone(), namespace); @@ -5262,8 +5230,7 @@ impl KubernetesComputeDriver { ) .await { - Ok(true) => {} - Ok(false) => continue, + Ok(()) => {} Err(KubernetesDriverError::Precondition(error)) => { warn!(sandbox_id, %error, "sandbox-runtime companion is missing; suspending workload"); self.suspend_sandbox_runtime_after_dependency_failure(&lookup_api, &object) @@ -5661,8 +5628,6 @@ impl KubernetesComputeDriver { } } - /// Returns `false` without deleting anything when the Sandbox changed - /// after `object` was read. async fn reconcile_sandbox_runtime_supervisor( &self, sandbox_api: &Api, @@ -5670,7 +5635,7 @@ impl KubernetesComputeDriver { namespace: &str, desired_running: bool, object: &DynamicObject, - ) -> Result { + ) -> Result<(), KubernetesDriverError> { if !desired_running { return self .delete_stopped_sandbox_runtime_supervisor( @@ -5683,7 +5648,7 @@ impl KubernetesComputeDriver { } if let SupervisorPlacement::Shared { .. } = supervisor_placement(object)? { // Sandbox instance availability is part of control availability. - return Ok(true); + return Ok(()); } // The boundary Service was checked by verify_sandbox_runtime_control_path. let names = SandboxRuntimeNames::new(sandbox_id); @@ -5705,7 +5670,7 @@ impl KubernetesComputeDriver { names.supervisor_pod )) })?; - Ok(true) + Ok(()) } /// Delete the supervisor Pod and generation Secrets of a stopped Sandbox. @@ -5713,13 +5678,14 @@ impl KubernetesComputeDriver { /// A restart on another replica may create a new supervisor Pod under the /// same name after `object` was read. It marks the Sandbox first, so the /// Pod is deleted only if the Sandbox is unchanged after the Pod is read. + /// Otherwise this deletes nothing; the next pass sees the change. async fn delete_stopped_sandbox_runtime_supervisor( &self, sandbox_api: &Api, sandbox_id: &str, namespace: &str, object: &DynamicObject, - ) -> Result { + ) -> Result<(), KubernetesDriverError> { let names = SandboxRuntimeNames::new(sandbox_id); let pods = Api::::namespaced(self.client.clone(), namespace); if let Some(pod) = pods @@ -5737,18 +5703,16 @@ impl KubernetesComputeDriver { && current.metadata.resource_version == object.metadata.resource_version }); if !unchanged { - return Ok(false); + return Ok(()); } - self.delete_sandbox_runtime_supervisor_pod_with_uid(namespace, &names, pod) - .await?; + delete_supervisor_pod_and_wait(&pods, pod).await?; } self.delete_sandbox_runtime_generation_secrets( sandbox_id, namespace, sandbox_runtime_generation(object).as_slice(), ) - .await?; - Ok(true) + .await } fn spawn_sandbox_runtime_periodic_reconcile( @@ -8892,21 +8856,56 @@ fn sandbox_operating_state_patch( } } +/// Annotations that start a bootstrap transition and its grace period. +fn sandbox_runtime_bootstrap_claim( + operation: &str, + phase: SandboxRuntimeBootstrapPhase, + generation: Option<&str>, +) -> BTreeMap { + let mut annotations = BTreeMap::from([ + ( + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAPPING.to_string(), + "true".to_string(), + ), + ( + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_STARTED_AT.to_string(), + openshell_core::time::now_ms().to_string(), + ), + ( + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION.to_string(), + operation.to_string(), + ), + ( + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE.to_string(), + phase.as_str().to_string(), + ), + ]); + if let Some(generation) = generation { + annotations.insert( + ANNOTATION_SANDBOX_RUNTIME_GENERATION.to_string(), + generation.to_string(), + ); + } + annotations +} + fn sandbox_runtime_stop_begin_patch(resource_version: &str) -> serde_json::Value { + let mut annotations = + sandbox_runtime_bootstrap_claim("stop", SandboxRuntimeBootstrapPhase::Releasing, None); + annotations.insert( + ANNOTATION_SANDBOX_RUNTIME_READINESS.to_string(), + "unavailable".to_string(), + ); serde_json::json!({ "metadata": { "resourceVersion": resource_version, - "annotations": { - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAPPING: "true", - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_STARTED_AT: openshell_core::time::now_ms().to_string(), - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION: "stop", - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE: SandboxRuntimeBootstrapPhase::Releasing.as_str(), - ANNOTATION_SANDBOX_RUNTIME_READINESS: "unavailable", - }, + "annotations": annotations, }, }) } +/// Claim a stopped Sandbox for a restart before it creates the supervisor +/// Pod. The Running patch adds the generation's bindings. fn sandbox_runtime_restart_begin_patch( resource_version: &str, generation: &str, @@ -8914,14 +8913,11 @@ fn sandbox_runtime_restart_begin_patch( serde_json::json!({ "metadata": { "resourceVersion": resource_version, - "annotations": { - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAPPING: "true", - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_STARTED_AT: openshell_core::time::now_ms().to_string(), - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION: "restart", - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE: SandboxRuntimeBootstrapPhase::Preparing.as_str(), - ANNOTATION_SANDBOX_RUNTIME_GENERATION: generation, - ANNOTATION_SANDBOX_RUNTIME_READINESS: "unavailable", - }, + "annotations": sandbox_runtime_bootstrap_claim( + "restart", + SandboxRuntimeBootstrapPhase::Preparing, + Some(generation), + ), }, }) } diff --git a/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs b/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs index 2ff39542cb..dc8a601330 100644 --- a/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs +++ b/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs @@ -129,8 +129,15 @@ mod lifecycle_reconciliation { Ok::<_, std::convert::Infallible>(response) } }); - let client = Client::new(service, "openshell"); - let driver = KubernetesComputeDriver { + ( + test_driver(Client::new(service, "openshell")), + steps, + Arc::default(), + ) + } + + fn test_driver(client: Client) -> KubernetesComputeDriver { + KubernetesComputeDriver { client: client.clone(), watch_client: client, sandbox_api_version: Arc::new(OnceCell::new()), @@ -139,8 +146,30 @@ mod lifecycle_reconciliation { network_trust_bundle: None, operator_allowlist: None, shared_supervisor: None, - }; - (driver, steps, Arc::default()) + } + } + + /// The namespace fence as installed and labeled by the driver. + fn labeled_workload_fence() -> (serde_json::Value, serde_json::Value) { + let mut fence = workload_fence("openshell", &SandboxRuntimeNames::new("sandbox-1"), 5500); + for (policy, component) in [ + (&mut fence.workload_policy, "sandbox-workload-fence"), + (&mut fence.supervisor_policy, "sandbox-supervisor-egress"), + ] { + policy.metadata.labels.get_or_insert_default().extend([ + ( + LABEL_MANAGED_BY.to_string(), + LABEL_MANAGED_BY_VALUE.to_string(), + ), + ("openshell.ai/component".to_string(), component.to_string()), + ]); + policy.metadata.uid = Some(format!("{component}-uid")); + policy.metadata.generation = Some(1); + } + ( + serde_json::to_value(&fence.workload_policy).unwrap(), + serde_json::to_value(&fence.supervisor_policy).unwrap(), + ) } fn snapshot(version: &str, phase: Option) -> serde_json::Value { @@ -238,40 +267,22 @@ mod lifecycle_reconciliation { ) } - fn preparing_dependencies() -> Vec { - let mut fence = workload_fence("openshell", &SandboxRuntimeNames::new("sandbox-1"), 5500); - for (policy, component) in [ - (&mut fence.workload_policy, "sandbox-workload-fence"), - (&mut fence.supervisor_policy, "sandbox-supervisor-egress"), - ] { - policy.metadata.labels.get_or_insert_default().extend([ - ( - LABEL_MANAGED_BY.to_string(), - LABEL_MANAGED_BY_VALUE.to_string(), - ), - ("openshell.ai/component".to_string(), component.to_string()), - ]); - policy.metadata.uid = Some(format!("{component}-uid")); - policy.metadata.generation = Some(1); - } + /// Reads reconciliation makes for a restart whose bootstrap is released + /// but not yet complete. + fn released_restart_dependencies() -> Vec { + let (workload_policy, supervisor_policy) = labeled_workload_fence(); let workload = || { ( http::Method::GET, "/apis/networking.k8s.io/v1/namespaces/openshell/networkpolicies/openshell-sandbox-workloads", - kube_test_response( - http::StatusCode::OK, - serde_json::to_value(&fence.workload_policy).unwrap(), - ), + kube_test_response(http::StatusCode::OK, workload_policy.clone()), ) }; let supervisor = || { ( http::Method::GET, "/apis/networking.k8s.io/v1/namespaces/openshell/networkpolicies/openshell-sandbox-supervisors", - kube_test_response( - http::StatusCode::OK, - serde_json::to_value(&fence.supervisor_policy).unwrap(), - ), + kube_test_response(http::StatusCode::OK, supervisor_policy.clone()), ) }; vec![ @@ -333,24 +344,7 @@ mod lifecycle_reconciliation { version: &'static str, sandbox_reads: Vec, ) -> (KubernetesComputeDriver, RecordedRequests) { - let names = SandboxRuntimeNames::new("sandbox-1"); - let mut fence = workload_fence("openshell", &names, 5500); - for (policy, component) in [ - (&mut fence.workload_policy, "sandbox-workload-fence"), - (&mut fence.supervisor_policy, "sandbox-supervisor-egress"), - ] { - policy.metadata.labels.get_or_insert_default().extend([ - ( - LABEL_MANAGED_BY.to_string(), - LABEL_MANAGED_BY_VALUE.to_string(), - ), - ("openshell.ai/component".to_string(), component.to_string()), - ]); - policy.metadata.uid = Some(format!("{component}-uid")); - policy.metadata.generation = Some(1); - } - let workload_policy = serde_json::to_value(&fence.workload_policy).unwrap(); - let supervisor_policy = serde_json::to_value(&fence.supervisor_policy).unwrap(); + let (workload_policy, supervisor_policy) = labeled_workload_fence(); let sandboxes = format!("/apis/agents.x-k8s.io/{version}/namespaces/openshell/sandboxes"); let sandbox = format!("{sandboxes}/sandbox-cr"); let requests = RecordedRequests::default(); @@ -419,24 +413,15 @@ mod lifecycle_reconciliation { }); async move { Ok::<_, std::convert::Infallible>(kube_test_response(status, body)) } }); - let client = Client::new(service, "openshell"); - let driver = KubernetesComputeDriver { - client: client.clone(), - watch_client: client, - sandbox_api_version: Arc::new(OnceCell::new()), - lifecycle_gates: Arc::default(), - config: KubernetesComputeConfig::default(), - network_trust_bundle: None, - operator_allowlist: None, - shared_supervisor: None, - }; + let driver = test_driver(Client::new(service, "openshell")); driver.sandbox_api_version.set(version).unwrap(); (driver, requests) } - /// A stopped Sandbox that a lifecycle RPC on another replica has begun to - /// boot: the workload is still suspended and no generation is bound. - fn claimed_snapshot(version: &str, operation: &str) -> serde_json::Value { + /// A stopped Sandbox that a lifecycle RPC on another replica began to + /// boot at `started_at_ms`: the workload is still suspended and no + /// generation is bound. + fn claimed_snapshot(version: &str, operation: &str, started_at_ms: i64) -> serde_json::Value { let mut object = snapshot(version, Some(SandboxRuntimeBootstrapPhase::Preparing)); object["metadata"]["resourceVersion"] = serde_json::json!("43"); let annotations = object["metadata"]["annotations"].as_object_mut().unwrap(); @@ -447,11 +432,24 @@ mod lifecycle_reconciliation { ); annotations.insert( ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_STARTED_AT.to_string(), - serde_json::json!(openshell_core::time::now_ms().to_string()), + serde_json::json!(started_at_ms.to_string()), ); object } + fn fresh_claim(version: &str, operation: &str) -> serde_json::Value { + claimed_snapshot(version, operation, openshell_core::time::now_ms()) + } + + fn requests_to(requests: &RecordedRequests, method: &http::Method, path: &str) -> usize { + requests + .lock() + .unwrap() + .iter() + .filter(|(m, p)| m == method && p == path) + .count() + } + fn mutations(requests: &RecordedRequests) -> Vec<(http::Method, String)> { requests .lock() @@ -462,18 +460,23 @@ mod lifecycle_reconciliation { .collect() } - // Issue #5781: only the lease holder reconciles, but a start may run on - // any replica, so the local lifecycle gate cannot exclude it. The holder - // refreshed the stopped Sandbox just before the restart claimed it and - // then read the supervisor Pod the restart had created. + // Only the lease holder reconciles, but a restart may run on any + // replica, outside the holder's lifecycle gate. The holder refreshed the + // stopped Sandbox just before the restart claimed it, then read the + // supervisor Pod the restart created under the same name. #[tokio::test] async fn reconciliation_preserves_a_supervisor_another_replica_is_restarting() { for version in [SANDBOX_VERSION_V1ALPHA1, SANDBOX_VERSION_V1BETA1] { let (driver, requests) = other_replica_driver( version, - vec![snapshot(version, None), claimed_snapshot(version, "restart")], + vec![snapshot(version, None), fresh_claim(version, "restart")], ); driver.reconcile_sandbox_runtime_resources().await; + // Cleanup found the Pod and reread the Sandbox, past its refresh, + // before it gave up. + let sandbox = + format!("/apis/agents.x-k8s.io/{version}/namespaces/openshell/sandboxes/sandbox-cr"); + assert_eq!(requests_to(&requests, &http::Method::GET, &sandbox), 2, "{version}"); assert_eq!(mutations(&requests), vec![], "{version}"); } } @@ -501,13 +504,72 @@ mod lifecycle_reconciliation { for version in [SANDBOX_VERSION_V1ALPHA1, SANDBOX_VERSION_V1BETA1] { for operation in ["create", "restart"] { let (driver, requests) = - other_replica_driver(version, vec![claimed_snapshot(version, operation)]); + other_replica_driver(version, vec![fresh_claim(version, operation)]); driver.reconcile_sandbox_runtime_resources().await; assert_eq!(mutations(&requests), vec![], "{version} {operation}"); } } } + // The same claim, abandoned past the grace period, is reaped: a stale + // restart is suspended and a stale create is deleted. + #[tokio::test] + async fn reconciliation_reaps_a_stale_bootstrap() { + let grace_ms = i64::try_from(KubernetesComputeConfig::default().runtime_bootstrap_grace_seconds).unwrap() * 1000; + let started_at_ms = openshell_core::time::now_ms() - grace_ms - 1000; + for version in [SANDBOX_VERSION_V1ALPHA1, SANDBOX_VERSION_V1BETA1] { + let sandbox = + format!("/apis/agents.x-k8s.io/{version}/namespaces/openshell/sandboxes/sandbox-cr"); + for (operation, method) in [ + ("create", http::Method::DELETE), + ("restart", http::Method::PATCH), + ] { + let (driver, requests) = other_replica_driver( + version, + vec![claimed_snapshot(version, operation, started_at_ms)], + ); + driver.reconcile_sandbox_runtime_resources().await; + assert_eq!( + mutations(&requests), + vec![(method, sandbox.clone())], + "{version} {operation}" + ); + } + } + } + + #[tokio::test] + async fn supervisor_deletion_does_not_wait_for_a_replacement_pod() { + let pod = |uid: &str| { + serde_json::json!({ + "apiVersion": "v1", "kind": "Pod", + "metadata": {"name": "os-supervisor-sandbox-1", "uid": uid}, + "spec": {"containers": []}, "status": {"phase": "Pending"} + }) + }; + let replacement = pod("replacement-uid"); + let service = tower::service_fn(move |request: http::Request| { + let body = match *request.method() { + http::Method::DELETE => { + serde_json::json!({"apiVersion": "v1", "kind": "Status", "status": "Success"}) + } + _ => replacement.clone(), + }; + async move { + Ok::<_, std::convert::Infallible>(kube_test_response(http::StatusCode::OK, body)) + } + }); + let pods = Api::::namespaced(Client::new(service, "openshell"), "openshell"); + let original = serde_json::from_value(pod("original-uid")).unwrap(); + tokio::time::timeout( + Duration::from_secs(5), + delete_supervisor_pod_and_wait(&pods, original), + ) + .await + .expect("a Pod with another UID ends the wait") + .unwrap(); + } + #[tokio::test] async fn stale_stop_snapshots_cannot_delete_a_restarted_supervisor() { for version in [SANDBOX_VERSION_V1ALPHA1, SANDBOX_VERSION_V1BETA1] { @@ -524,7 +586,7 @@ mod lifecycle_reconciliation { listed(version, snapshot(version, phase)), refreshed(version, restarted_snapshot(version)), ]; - steps.extend(preparing_dependencies()); + steps.extend(released_restart_dependencies()); let (driver, steps, _) = read_only_driver(steps); driver.sandbox_api_version.set(version).unwrap(); driver.reconcile_sandbox_runtime_resources().await; @@ -541,7 +603,7 @@ mod lifecycle_reconciliation { listed(version, snapshot(version, None)), refreshed(version, restarted_snapshot(version)), ]; - steps.extend(preparing_dependencies()); + steps.extend(released_restart_dependencies()); let (driver, steps, _) = read_only_driver(steps); driver.sandbox_api_version.set(version).unwrap(); let clone = driver.clone(); From 959c76cf9699432a69872d5193d513e55225fca1 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 30 Nov 2026 16:09:10 -0800 Subject: [PATCH 3/7] docs(kubernetes): narrow the HA coordination claim and state the overwrite race Signed-off-by: Matthew Grossman --- crates/openshell-driver-kubernetes/README.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index 4a4c2e419e..1f39befca6 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -399,13 +399,14 @@ driver instance. The gate preserves concurrency across sandboxes; it does not provide distributed exclusion between separate gateway or driver processes. In a high-availability gateway, only the lease holder reconciles, while any -replica can serve a lifecycle RPC. The Sandbox CR coordinates the two. A -restart marks the CR `Preparing` before it creates the supervisor Pod, and -reconciliation leaves a `Preparing` bootstrap to its request until the +replica can serve a lifecycle RPC. A restart marks the CR `Preparing` before it +creates the supervisor Pod, and reconciliation respects that claim until the bootstrap grace period expires, then reaps it: a stale restart is suspended and -a stale create is deleted. Before it deletes the supervisor Pod of a -stopped sandbox, reconciliation reads the CR again and skips the deletion if the -CR changed after its refresh. +a stale create is deleted. Before it deletes the supervisor Pod of a stopped +sandbox, reconciliation reads the CR again and skips the deletion if the CR +changed after its refresh. Lifecycle writes to the CR retry on resourceVersion +conflicts without checking whether another replica started a transition, so a +request on one replica can still overwrite a suspension started by another. ## GPU Support From 60011c07bea97453e004cec487c95a64c074efda Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 30 Nov 2026 17:33:06 -0800 Subject: [PATCH 4/7] refactor(kubernetes): pass the CR name to stopped-supervisor deletion The reconcile loop already has the Sandbox CR name, so take it from the caller instead of re-deriving it from the object. Document that the resourceVersion check before the UID-preconditioned Pod delete is best effort, not atomic. Signed-off-by: Matthew Grossman --- crates/openshell-driver-kubernetes/src/driver.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index 631cd7f4e8..da7786eeca 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -5223,6 +5223,7 @@ impl KubernetesComputeDriver { match self .reconcile_sandbox_runtime_supervisor( &api.api, + cr_name, &sandbox_id, namespace, desired_running, @@ -5631,6 +5632,7 @@ impl KubernetesComputeDriver { async fn reconcile_sandbox_runtime_supervisor( &self, sandbox_api: &Api, + cr_name: &str, sandbox_id: &str, namespace: &str, desired_running: bool, @@ -5640,6 +5642,7 @@ impl KubernetesComputeDriver { return self .delete_stopped_sandbox_runtime_supervisor( sandbox_api, + cr_name, sandbox_id, namespace, object, @@ -5679,9 +5682,14 @@ impl KubernetesComputeDriver { /// same name after `object` was read. It marks the Sandbox first, so the /// Pod is deleted only if the Sandbox is unchanged after the Pod is read. /// Otherwise this deletes nothing; the next pass sees the change. + /// + /// The resourceVersion comparison and the delete are separate requests, + /// so this is best effort, not atomic. The delete itself targets the + /// Pod's UID, so it never removes a Pod created after the read. async fn delete_stopped_sandbox_runtime_supervisor( &self, sandbox_api: &Api, + cr_name: &str, sandbox_id: &str, namespace: &str, object: &DynamicObject, @@ -5693,9 +5701,8 @@ impl KubernetesComputeDriver { .await .map_err(KubernetesDriverError::from_kube)? { - let name = object.metadata.name.as_deref().unwrap_or_default(); let current = sandbox_api - .get_opt(name) + .get_opt(cr_name) .await .map_err(KubernetesDriverError::from_kube)?; let unchanged = current.is_some_and(|current| { From ca8e42f0ae9b324f31831cb30f6f063d96c6a7a2 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Tue, 1 Dec 2026 08:18:46 -0800 Subject: [PATCH 5/7] fix(kubernetes): require a UID before deleting a supervisor Pod Without a UID the delete precondition was empty, so the delete could remove a replacement Pod created under the same name, and the wait returned immediately. A Pod read from the API server always has a name and UID, so treat a missing one as an error. Signed-off-by: Matthew Grossman --- crates/openshell-driver-kubernetes/src/driver.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index da7786eeca..72c917c7a4 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -587,14 +587,19 @@ async fn delete_supervisor_pod_and_wait( pods: &Api, pod: Pod, ) -> Result<(), KubernetesDriverError> { - let name = pod.metadata.name.clone().unwrap_or_default(); - let uid = pod.metadata.uid.clone(); + // A stored Pod always has both. Without a UID the delete below would + // not be pinned to this Pod and could remove a replacement. + let (Some(name), Some(uid)) = (pod.metadata.name.clone(), pod.metadata.uid.clone()) else { + return Err(KubernetesDriverError::Message( + "supervisor Pod has no name or UID".to_string(), + )); + }; let deletion_timeout = kubernetes_pod_termination_timeout(&pod); match pods .delete( &name, &DeleteParams::foreground().preconditions(Preconditions { - uid: uid.clone(), + uid: Some(uid.clone()), resource_version: None, }), ) @@ -610,7 +615,7 @@ async fn delete_supervisor_pod_and_wait( .get_opt(&name) .await .map_err(KubernetesDriverError::from_kube)?; - if current.is_none_or(|current| current.metadata.uid != uid) { + if current.is_none_or(|current| current.metadata.uid.as_deref() != Some(uid.as_str())) { return Ok(()); } if tokio::time::Instant::now() >= deadline { From f5daf8b2846cff2b842db89c113fa813e25aa3d2 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Tue, 1 Dec 2026 08:18:46 -0800 Subject: [PATCH 6/7] docs(kubernetes): document HA reconciliation ordering and Preparing checks - Mark the blind restart claim retry with TODO(#6108). - Note that the stopped-supervisor cleanup must read the Pod before rereading the Sandbox. - State in the README that drift checks are deferred while a claim holds and that the workload Pod stays gated until release. - Assert that the fresh-claim test reaches the Preparing arm by comparing its requests with the stale claim's. Signed-off-by: Matthew Grossman --- crates/openshell-driver-kubernetes/README.md | 5 +++- .../openshell-driver-kubernetes/src/driver.rs | 7 +++++ .../src/lifecycle_tests.rs | 29 +++++++++++++++++-- 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index 1f39befca6..e9dc9fa63c 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -402,7 +402,10 @@ In a high-availability gateway, only the lease holder reconciles, while any replica can serve a lifecycle RPC. A restart marks the CR `Preparing` before it creates the supervisor Pod, and reconciliation respects that claim until the bootstrap grace period expires, then reaps it: a stale restart is suspended and -a stale create is deleted. Before it deletes the supervisor Pod of a stopped +a stale create is deleted. While the claim holds, reconciliation still re-checks +resource admission but defers fence and control-path drift checks. The workload +Pod stays behind its scheduling gate until the request releases the bootstrap. +Before it deletes the supervisor Pod of a stopped sandbox, reconciliation reads the CR again and skips the deletion if the CR changed after its refresh. Lifecycle writes to the CR retry on resourceVersion conflicts without checking whether another replica started a transition, so a diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index 72c917c7a4..5408f6a5f0 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -4508,6 +4508,8 @@ impl KubernetesComputeDriver { // not cover requests served by other replicas. Mark the Sandbox // Preparing before creating the supervisor Pod so reconciliation // that refreshed the stopped Sandbox cannot delete the new Pod. + // TODO(#6108): this retry reclaims the Sandbox even if another + // replica moved it to Suspending or Releasing after the read. patch_dynamic_object_with_resource_version_retry(&sandbox_api.api, cr_name, |version| { sandbox_runtime_restart_begin_patch(version, generation.as_str()) }) @@ -5691,6 +5693,11 @@ impl KubernetesComputeDriver { /// The resourceVersion comparison and the delete are separate requests, /// so this is best effort, not atomic. The delete itself targets the /// Pod's UID, so it never removes a Pod created after the read. + /// + /// Keep the Pod read before the Sandbox reread. A restart claims the + /// Sandbox before it creates the Pod, so a Pod read first is only deleted + /// if no claim landed before the reread. Reading the Sandbox first would + /// let a restart claim it and create its Pod between the two reads. async fn delete_stopped_sandbox_runtime_supervisor( &self, sandbox_api: &Api, diff --git a/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs b/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs index dc8a601330..6faaa69a86 100644 --- a/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs +++ b/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs @@ -441,6 +441,12 @@ mod lifecycle_reconciliation { claimed_snapshot(version, operation, openshell_core::time::now_ms()) } + /// A claim start time just past the default bootstrap grace period. + fn stale_claim_started_at_ms() -> i64 { + let grace_seconds = KubernetesComputeConfig::default().runtime_bootstrap_grace_seconds; + openshell_core::time::now_ms() - i64::try_from(grace_seconds).unwrap() * 1000 - 1000 + } + fn requests_to(requests: &RecordedRequests, method: &http::Method, path: &str) -> usize { requests .lock() @@ -507,6 +513,26 @@ mod lifecycle_reconciliation { other_replica_driver(version, vec![fresh_claim(version, operation)]); driver.reconcile_sandbox_runtime_resources().await; assert_eq!(mutations(&requests), vec![], "{version} {operation}"); + + // The same claim gone stale makes the same reads and then + // writes, so the fresh claim reached the Preparing arm rather + // than stopping on an unmodeled request. + let (driver, stale_requests) = other_replica_driver( + version, + vec![claimed_snapshot(version, operation, stale_claim_started_at_ms())], + ); + driver.reconcile_sandbox_runtime_resources().await; + let mut stale_requests = stale_requests.lock().unwrap().clone(); + let stale_write = stale_requests.pop(); + assert!( + stale_write.is_some_and(|(method, _)| method != http::Method::GET), + "{version} {operation}" + ); + assert_eq!( + *requests.lock().unwrap(), + stale_requests, + "{version} {operation}" + ); } } } @@ -515,8 +541,7 @@ mod lifecycle_reconciliation { // restart is suspended and a stale create is deleted. #[tokio::test] async fn reconciliation_reaps_a_stale_bootstrap() { - let grace_ms = i64::try_from(KubernetesComputeConfig::default().runtime_bootstrap_grace_seconds).unwrap() * 1000; - let started_at_ms = openshell_core::time::now_ms() - grace_ms - 1000; + let started_at_ms = stale_claim_started_at_ms(); for version in [SANDBOX_VERSION_V1ALPHA1, SANDBOX_VERSION_V1BETA1] { let sandbox = format!("/apis/agents.x-k8s.io/{version}/namespaces/openshell/sandboxes/sandbox-cr"); From 1d9fc743d9cac8f5f56cfce10a0cd53a774c6e6c Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Tue, 1 Dec 2026 15:00:27 -0800 Subject: [PATCH 7/7] fix(kubernetes): enforce the namespace fence during a fresh bootstrap The Preparing arm skipped create_sandbox_runtime_fence, which main ran for every phase before bootstrap dispatch. The namespace fence does not depend on the bootstrap claim, so a deleted or altered fence went unrestored for up to the bootstrap grace period while the supervisor Pod ran. Check it before deferring to the claim holder, and document what the grace period defers. Signed-off-by: Matthew Grossman --- crates/openshell-driver-kubernetes/README.md | 3 +- .../openshell-driver-kubernetes/src/driver.rs | 70 ++++++++++++++----- .../src/lifecycle_tests.rs | 32 ++++++++- docs/how-it-works/gateways/configuration.mdx | 4 ++ 4 files changed, 90 insertions(+), 19 deletions(-) diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index e9dc9fa63c..a08e7816cc 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -403,7 +403,8 @@ replica can serve a lifecycle RPC. A restart marks the CR `Preparing` before it creates the supervisor Pod, and reconciliation respects that claim until the bootstrap grace period expires, then reaps it: a stale restart is suspended and a stale create is deleted. While the claim holds, reconciliation still re-checks -resource admission but defers fence and control-path drift checks. The workload +resource admission and the namespace workload fence, but defers the generation +fence and control-path drift checks. The workload Pod stays behind its scheduling gate until the request releases the bootstrap. Before it deletes the supervisor Pod of a stopped sandbox, reconciliation reads the CR again and skips the deletion if the CR diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index 5408f6a5f0..e8eb3f30e9 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -5064,15 +5064,28 @@ impl KubernetesComputeDriver { .as_deref() .unwrap_or(&self.config.namespace); let cr_name = object.metadata.name.as_deref().unwrap_or_default(); + let names = SandboxRuntimeNames::new(&sandbox_id); match sandbox_runtime_bootstrap_phase(&object) { Some(SandboxRuntimeBootstrapPhase::Preparing) => { // The lifecycle request that set Preparing owns the // bootstrap until it has bound and released the // generation. It may run on another replica, outside this // replica's lifecycle gate, so reconciliation only reaps - // it once the grace period runs out. - self.reap_stale_sandbox_runtime_bootstrap(&lookup_api, &object) - .await; + // it once the grace period runs out. The namespace fence + // does not depend on that claim, so it is still enforced. + if self + .reconcile_sandbox_runtime_fence( + &lookup_api, + &object, + &sandbox_id, + namespace, + &names, + ) + .await + { + self.reap_stale_sandbox_runtime_bootstrap(&lookup_api, &object) + .await; + } continue; } Some(SandboxRuntimeBootstrapPhase::Releasing) => { @@ -5099,21 +5112,19 @@ impl KubernetesComputeDriver { } Some(SandboxRuntimeBootstrapPhase::Released) | None => {} } - let names = SandboxRuntimeNames::new(&sandbox_id); - let policies = Api::::namespaced(self.client.clone(), namespace); - match self.create_sandbox_runtime_fence(namespace, &names).await { - Ok(()) => {} - Err(KubernetesDriverError::Precondition(error)) => { - warn!(sandbox_id, %error, "sandbox-runtime workload fence is altered; suspending workload"); - self.suspend_sandbox_runtime_after_dependency_failure(&lookup_api, &object) - .await; - continue; - } - Err(error) => { - warn!(sandbox_id, %error, "could not verify sandbox-runtime workload fence; reconciliation will retry"); - continue; - } + if !self + .reconcile_sandbox_runtime_fence( + &lookup_api, + &object, + &sandbox_id, + namespace, + &names, + ) + .await + { + continue; } + let policies = Api::::namespaced(self.client.clone(), namespace); let Ok(Ok(fence)) = tokio::time::timeout(KUBE_API_TIMEOUT, policies.get(&names.workload_policy)).await else { @@ -5499,6 +5510,31 @@ impl KubernetesComputeDriver { } } + /// Create or verify the namespace workload fence, suspending the sandbox + /// if the fence was altered. Returns whether reconciliation may continue. + async fn reconcile_sandbox_runtime_fence( + &self, + lookup_api: &AgentSandboxApi, + object: &DynamicObject, + sandbox_id: &str, + namespace: &str, + names: &SandboxRuntimeNames, + ) -> bool { + match self.create_sandbox_runtime_fence(namespace, names).await { + Ok(()) => true, + Err(KubernetesDriverError::Precondition(error)) => { + warn!(sandbox_id, %error, "sandbox-runtime workload fence is altered; suspending workload"); + self.suspend_sandbox_runtime_after_dependency_failure(lookup_api, object) + .await; + false + } + Err(error) => { + warn!(sandbox_id, %error, "could not verify sandbox-runtime workload fence; reconciliation will retry"); + false + } + } + } + async fn suspend_sandbox_runtime_after_dependency_failure( &self, lookup_api: &AgentSandboxApi, diff --git a/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs b/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs index 6faaa69a86..64a61da733 100644 --- a/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs +++ b/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs @@ -344,7 +344,14 @@ mod lifecycle_reconciliation { version: &'static str, sandbox_reads: Vec, ) -> (KubernetesComputeDriver, RecordedRequests) { - let (workload_policy, supervisor_policy) = labeled_workload_fence(); + other_replica_driver_with_fence(version, sandbox_reads, labeled_workload_fence()) + } + + fn other_replica_driver_with_fence( + version: &'static str, + sandbox_reads: Vec, + (workload_policy, supervisor_policy): (serde_json::Value, serde_json::Value), + ) -> (KubernetesComputeDriver, RecordedRequests) { let sandboxes = format!("/apis/agents.x-k8s.io/{version}/namespaces/openshell/sandboxes"); let sandbox = format!("{sandboxes}/sandbox-cr"); let requests = RecordedRequests::default(); @@ -537,6 +544,29 @@ mod lifecycle_reconciliation { } } + // The namespace fence does not depend on the bootstrap claim, so an + // altered fence suspends the workload even while the claim is fresh. + #[tokio::test] + async fn reconciliation_enforces_the_namespace_fence_during_a_fresh_bootstrap() { + let (mut workload_policy, supervisor_policy) = labeled_workload_fence(); + workload_policy["spec"]["policyTypes"] = serde_json::json!(["Egress"]); + for version in [SANDBOX_VERSION_V1ALPHA1, SANDBOX_VERSION_V1BETA1] { + let sandbox = + format!("/apis/agents.x-k8s.io/{version}/namespaces/openshell/sandboxes/sandbox-cr"); + let (driver, requests) = other_replica_driver_with_fence( + version, + vec![fresh_claim(version, "restart")], + (workload_policy.clone(), supervisor_policy.clone()), + ); + driver.reconcile_sandbox_runtime_resources().await; + assert_eq!( + mutations(&requests), + vec![(http::Method::PATCH, sandbox)], + "{version}" + ); + } + } + // The same claim, abandoned past the grace period, is reaped: a stale // restart is suspended and a stale create is deleted. #[tokio::test] diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index db461f8d66..55ade51a4b 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -118,6 +118,10 @@ variables override TOML values. | `sandbox_attach_request_timeout_seconds` | `[openshell.drivers.kubernetes]`: dedicated supervisor startup | `OPENSHELL_ATTACH_REQUEST_TIMEOUT_SECONDS` | For a 15-minute Kubernetes startup window, set both driver settings to `900`. +`runtime_bootstrap_grace_seconds` also sets how long the Kubernetes driver +waits before it reclaims a start abandoned by a failed gateway replica. Until +then, the workload stays gated, and the driver checks the namespace workload +fence but defers runtime drift checks. On shared supervisor deployments, set `OPENSHELL_ATTACH_REQUEST_TIMEOUT_SECONDS=900` directly; the driver setting does not configure shared hosts. Directly launched supervisors also accept `--attach-request-timeout-seconds`.