From b2812158da19af863d3e53a4a135a3a11e4b1be0 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 30 Nov 2026 15:14:02 -0800 Subject: [PATCH 1/5] fix(kubernetes): compare-and-swap lifecycle writes on the bootstrap claim Create and restart patches to the Sandbox CR reread it on a conflict and reapplied the patch whatever its state, so a restart on one replica could overwrite a suspension the lease holder started. - The patch builder now receives the current Sandbox and may refuse. - A restart claims the Sandbox only if it is stopped and no other transition is in progress. - The Running, fence-binding and Released writes of create and restart require their claim (operation, generation, Preparing) to still hold; otherwise the request fails and rolls back. - Type bootstrap operations with an enum. - Return an error instead of using an empty name when a Pod or Sandbox has no name. Signed-off-by: Matthew Grossman --- crates/openshell-driver-kubernetes/README.md | 17 +- .../openshell-driver-kubernetes/src/driver.rs | 261 ++++++++++++++---- .../src/lifecycle_tests.rs | 147 +++++++++- 3 files changed, 355 insertions(+), 70 deletions(-) diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index 1f39befca6..37ccac7e7e 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -399,14 +399,15 @@ 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. 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. 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. +replica can serve a lifecycle RPC. A restart claims the CR, marking it +`Preparing`, before it creates the supervisor Pod. The claim succeeds only if +the CR is stopped and no other transition is in progress, and reconciliation +respects it until the bootstrap grace period expires, then reaps it: a stale +restart is suspended and a stale create is deleted. Each later create or restart +write to the CR checks that its claim still holds; if another replica started a +transition such as a suspension, the request fails and rolls back. 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 diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index da7786eeca..ef98a0c5f3 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -347,6 +347,94 @@ impl SandboxRuntimeBootstrapPhase { } } +/// The lifecycle request that started a bootstrap transition. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SandboxRuntimeBootstrapOperation { + Create, + Restart, + Stop, +} + +impl SandboxRuntimeBootstrapOperation { + const fn as_str(self) -> &'static str { + match self { + Self::Create => "create", + Self::Restart => "restart", + Self::Stop => "stop", + } + } + + fn parse(value: &str) -> Option { + match value { + "create" => Some(Self::Create), + "restart" => Some(Self::Restart), + "stop" => Some(Self::Stop), + _ => None, + } + } +} + +/// A create or restart request's claim on a Sandbox's bootstrap. +/// +/// Any gateway replica may serve the request, so its writes to the Sandbox +/// compare the stored claim with this one and refuse to overwrite a +/// transition another replica started, such as a suspension. +#[derive(Clone, Copy, Debug)] +struct SandboxRuntimeBootstrapClaim<'a> { + cr_uid: &'a str, + operation: SandboxRuntimeBootstrapOperation, + generation: &'a str, +} + +impl SandboxRuntimeBootstrapClaim<'_> { + /// Fail unless `current` still carries this claim, still `Preparing`. + fn ensure_held(&self, current: &DynamicObject) -> Result<(), KubernetesDriverError> { + let held = current.metadata.uid.as_deref() == Some(self.cr_uid) + && sandbox_runtime_bootstrap_in_progress(current) + && sandbox_runtime_bootstrap_phase(current) + == Some(SandboxRuntimeBootstrapPhase::Preparing) + && sandbox_runtime_bootstrap_operation(current) == Some(self.operation) + && sandbox_runtime_generation(current) == Some(self.generation); + if held { + Ok(()) + } else { + Err(KubernetesDriverError::Precondition(format!( + "sandbox {} of generation {} was superseded by another lifecycle transition", + self.operation.as_str(), + self.generation + ))) + } + } + + /// Claim a stopped Sandbox that no other transition has claimed. + fn begin_patch( + &self, + current: &DynamicObject, + ) -> Result { + if current.metadata.uid.as_deref() != Some(self.cr_uid) { + return Err(KubernetesDriverError::Precondition( + "the Sandbox resource was replaced".to_string(), + )); + } + if sandbox_runtime_bootstrap_in_progress(current) || sandbox_runtime_should_run(current) { + return Err(KubernetesDriverError::Precondition( + "another lifecycle transition claimed the sandbox; retry after it completes" + .to_string(), + )); + } + Ok(serde_json::json!({ + "metadata": { + "resourceVersion": resource_version(current), + "annotations": sandbox_runtime_bootstrap_claim( + self.operation, + SandboxRuntimeBootstrapPhase::Preparing, + Some(self.generation), + ), + }, + })) + } +} + fn boundary_service_authority( namespace: &str, names: &SandboxRuntimeNames, @@ -543,20 +631,30 @@ fn is_kube_resource_version_conflict(error: &KubeError) -> bool { matches!(error, KubeError::Api(api) if api.code == 409 && api.reason == "Conflict") } -async fn patch_dynamic_object_with_resource_version_retry( +fn resource_version(object: &DynamicObject) -> &str { + object + .metadata + .resource_version + .as_deref() + .unwrap_or_default() +} + +/// Read `name` and apply the merge patch `patch_for` builds from it, retrying +/// with a fresh read on a resourceVersion conflict. `patch_for` sees the +/// current object each time and may refuse the write; the patch must pin the +/// current resourceVersion for the comparison to hold. +async fn compare_and_patch_dynamic_object( api: &Api, name: &str, - mut patch_for_resource_version: impl FnMut(&str) -> serde_json::Value, + mut patch_for: impl FnMut(&DynamicObject) -> Result, ) -> Result { let operation = async { loop { - let current = api.get(name).await?; - let resource_version = current - .metadata - .resource_version - .as_deref() - .unwrap_or_default(); - let patch = patch_for_resource_version(resource_version); + let current = api + .get(name) + .await + .map_err(KubernetesDriverError::from_kube)?; + let patch = patch_for(¤t)?; match api .patch(name, &PatchParams::default(), &Patch::Merge(&patch)) .await @@ -565,7 +663,7 @@ async fn patch_dynamic_object_with_resource_version_retry( Err(error) if is_kube_resource_version_conflict(&error) => { tokio::task::yield_now().await; } - Err(error) => return Err(error), + Err(error) => return Err(KubernetesDriverError::from_kube(error)), } } }; @@ -577,7 +675,34 @@ async fn patch_dynamic_object_with_resource_version_retry( KUBE_API_TIMEOUT.as_secs() )) })? - .map_err(KubernetesDriverError::from_kube) +} + +/// Apply a patch whatever the current state of the object, retrying +/// resourceVersion conflicts. Use [`compare_and_patch_dynamic_object`] when +/// another writer's transition must not be overwritten. +async fn patch_dynamic_object_with_resource_version_retry( + api: &Api, + name: &str, + mut patch_for_resource_version: impl FnMut(&str) -> serde_json::Value, +) -> Result { + compare_and_patch_dynamic_object(api, name, |current| { + Ok(patch_for_resource_version(resource_version(current))) + }) + .await +} + +/// Apply a patch while `claim` still holds the Sandbox's bootstrap. +async fn patch_claimed_sandbox( + api: &Api, + name: &str, + claim: SandboxRuntimeBootstrapClaim<'_>, + mut patch_for_resource_version: impl FnMut(&str) -> serde_json::Value, +) -> Result { + compare_and_patch_dynamic_object(api, name, |current| { + claim.ensure_held(current)?; + Ok(patch_for_resource_version(resource_version(current))) + }) + .await } /// Delete `pod` by UID and wait until it is gone. A Pod that has since been @@ -587,7 +712,10 @@ async fn delete_supervisor_pod_and_wait( pods: &Api, pod: Pod, ) -> Result<(), KubernetesDriverError> { - let name = pod.metadata.name.clone().unwrap_or_default(); + let name = + pod.metadata.name.clone().ok_or_else(|| { + KubernetesDriverError::Message("supervisor Pod has no name".to_string()) + })?; let uid = pod.metadata.uid.clone(); let deletion_timeout = kubernetes_pod_termination_timeout(&pod); match pods @@ -2732,7 +2860,7 @@ impl KubernetesComputeDriver { ); add_trace_context_annotation(&mut annotations); annotations.extend(sandbox_runtime_bootstrap_claim( - "create", + SandboxRuntimeBootstrapOperation::Create, SandboxRuntimeBootstrapPhase::Preparing, Some(&generation), )); @@ -3362,6 +3490,13 @@ impl KubernetesComputeDriver { let cr_uid = sandbox_cr.metadata.uid.as_deref().ok_or_else(|| { KubernetesDriverError::Message("created Sandbox CR has no UID".to_string()) })?; + let claim = SandboxRuntimeBootstrapClaim { + cr_uid, + operation: SandboxRuntimeBootstrapOperation::Create, + generation: sandbox_runtime_generation(sandbox_cr).ok_or_else(|| { + KubernetesDriverError::Message("created Sandbox CR has no generation".to_string()) + })?, + }; let dependent_owner = sandbox_runtime_sandbox_owner_reference( cr_name, cr_uid, @@ -3415,7 +3550,7 @@ impl KubernetesComputeDriver { // the workload Pod. The Pod remains unschedulable because its template // carries the OpenShell scheduling gate and references a Secret that // does not exist yet. - patch_dynamic_object_with_resource_version_retry(&sandbox_api.api, cr_name, |version| { + patch_claimed_sandbox(&sandbox_api.api, cr_name, claim, |version| { sandbox_operating_state_patch(&sandbox_api.resource.version, version, true) }) .await?; @@ -3436,7 +3571,7 @@ impl KubernetesComputeDriver { cr_name, sandbox_api, &sandbox.id, - cr_uid, + claim, names, &supervisor, agent_uid, @@ -3794,7 +3929,7 @@ impl KubernetesComputeDriver { cr_name: &str, sandbox_api: &AgentSandboxApi, sandbox_id: &str, - cr_uid: &str, + claim: SandboxRuntimeBootstrapClaim<'_>, names: &SandboxRuntimeNames, supervisor: &GenerationSupervisor, agent_uid: u32, @@ -3803,6 +3938,7 @@ impl KubernetesComputeDriver { launch_authentication: &openshell_core::jwt::SandboxLaunchAuthentication, staged: StagedBootstrapMaterial, ) -> Result<(), KubernetesDriverError> { + let cr_uid = claim.cr_uid; let namespace_uid = Api::::all(self.client.clone()) .get(namespace) .await @@ -3883,7 +4019,7 @@ impl KubernetesComputeDriver { annotations[ANNOTATION_SANDBOX_RUNTIME_CONTROL_POLICY_GENERATION] = policy.generation.to_string().into(); } - patch_dynamic_object_with_resource_version_retry(&sandbox_api.api, cr_name, |version| { + patch_claimed_sandbox(&sandbox_api.api, cr_name, claim, |version| { serde_json::json!({ "metadata": {"resourceVersion": version, "annotations": annotations.clone()} }) @@ -4099,7 +4235,7 @@ impl KubernetesComputeDriver { ) .await .map_err(KubernetesDriverError::from_kube)?; - patch_dynamic_object_with_resource_version_retry(&sandbox_api.api, cr_name, |version| { + patch_claimed_sandbox(&sandbox_api.api, cr_name, claim, |version| { sandbox_runtime_bootstrap_phase_patch(version, SandboxRuntimeBootstrapPhase::Released) }) .await?; @@ -4282,7 +4418,8 @@ impl KubernetesComputeDriver { if sandbox_runtime_bootstrap_in_progress(&object) { let phase = sandbox_runtime_bootstrap_phase(&object); if phase != Some(SandboxRuntimeBootstrapPhase::Suspending) - && sandbox_runtime_bootstrap_operation(&object) != Some("restart") + && sandbox_runtime_bootstrap_operation(&object) + != Some(SandboxRuntimeBootstrapOperation::Restart) { return Err(KubernetesDriverError::Precondition( "initial sandbox bootstrap has not completed; wait for reconciliation" @@ -4498,13 +4635,18 @@ impl KubernetesComputeDriver { })?; sandbox_secret["secretName"] = serde_json::json!(names.sandbox_secret); let image_pull_secrets = self.generation_image_pull_secret_names(&names); + let claim = SandboxRuntimeBootstrapClaim { + cr_uid, + operation: SandboxRuntimeBootstrapOperation::Restart, + generation: generation.as_str(), + }; 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()) + // not cover requests served by other replicas. Claim the Sandbox + // before creating the supervisor Pod so reconciliation that + // refreshed the stopped Sandbox cannot delete the new Pod. + compare_and_patch_dynamic_object(&sandbox_api.api, cr_name, |current| { + claim.begin_patch(current) }) .await?; let supervisor = match &placement { @@ -4534,9 +4676,10 @@ impl KubernetesComputeDriver { route: route.clone(), }, }; - patch_dynamic_object_with_resource_version_retry( + patch_claimed_sandbox( &sandbox_api.api, cr_name, + claim, |version| { let mut running_patch = sandbox_operating_state_patch(&sandbox_api.resource.version, version, true); @@ -4575,7 +4718,7 @@ impl KubernetesComputeDriver { cr_name, &sandbox_api, sandbox_id, - cr_uid, + claim, &names, &supervisor, agent_uid, @@ -5544,7 +5687,9 @@ impl KubernetesComputeDriver { ) { return; } - if sandbox_runtime_bootstrap_operation(object) != Some("create") { + if sandbox_runtime_bootstrap_operation(object) + != Some(SandboxRuntimeBootstrapOperation::Create) + { warn!( sandbox = object.metadata.name.as_deref().unwrap_or(""), "suspending stale sandbox-runtime restart bootstrap" @@ -6130,13 +6275,15 @@ fn sandbox_runtime_bootstrap_in_progress(object: &DynamicObject) -> bool { .is_some_and(|value| value == "true") } -fn sandbox_runtime_bootstrap_operation(object: &DynamicObject) -> Option<&str> { +fn sandbox_runtime_bootstrap_operation( + object: &DynamicObject, +) -> Option { object .metadata .annotations .as_ref() .and_then(|annotations| annotations.get(ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION)) - .map(String::as_str) + .and_then(|value| SandboxRuntimeBootstrapOperation::parse(value)) } fn sandbox_runtime_bootstrap_is_ready_to_complete(object: &DynamicObject) -> bool { @@ -6144,7 +6291,10 @@ fn sandbox_runtime_bootstrap_is_ready_to_complete(object: &DynamicObject) -> boo && sandbox_runtime_bootstrap_phase(object) == Some(SandboxRuntimeBootstrapPhase::Released) && matches!( sandbox_runtime_bootstrap_operation(object), - Some("create" | "restart") + Some( + SandboxRuntimeBootstrapOperation::Create + | SandboxRuntimeBootstrapOperation::Restart + ) ) && sandbox_runtime_runtime_is_ready(object) } @@ -7226,7 +7376,8 @@ fn sandbox_from_object_with_bootstrap_state( ) -> Result<(String, Sandbox), String> { let (name, mut sandbox) = sandbox_from_object(namespace, obj.clone())?; if sandbox_runtime_bootstrap_in_progress(obj) { - if sandbox_runtime_bootstrap_operation(obj) == Some("stop") { + if sandbox_runtime_bootstrap_operation(obj) == Some(SandboxRuntimeBootstrapOperation::Stop) + { mark_sandbox_runtime_stopping(&mut sandbox); } else { mark_sandbox_runtime_bootstrapping(&mut sandbox); @@ -8865,7 +9016,7 @@ fn sandbox_operating_state_patch( /// Annotations that start a bootstrap transition and its grace period. fn sandbox_runtime_bootstrap_claim( - operation: &str, + operation: SandboxRuntimeBootstrapOperation, phase: SandboxRuntimeBootstrapPhase, generation: Option<&str>, ) -> BTreeMap { @@ -8880,7 +9031,7 @@ fn sandbox_runtime_bootstrap_claim( ), ( ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION.to_string(), - operation.to_string(), + operation.as_str().to_string(), ), ( ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE.to_string(), @@ -8897,8 +9048,11 @@ fn sandbox_runtime_bootstrap_claim( } fn sandbox_runtime_stop_begin_patch(resource_version: &str) -> serde_json::Value { - let mut annotations = - sandbox_runtime_bootstrap_claim("stop", SandboxRuntimeBootstrapPhase::Releasing, None); + let mut annotations = sandbox_runtime_bootstrap_claim( + SandboxRuntimeBootstrapOperation::Stop, + SandboxRuntimeBootstrapPhase::Releasing, + None, + ); annotations.insert( ANNOTATION_SANDBOX_RUNTIME_READINESS.to_string(), "unavailable".to_string(), @@ -8911,24 +9065,6 @@ fn sandbox_runtime_stop_begin_patch(resource_version: &str) -> serde_json::Value }) } -/// 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, -) -> serde_json::Value { - serde_json::json!({ - "metadata": { - "resourceVersion": resource_version, - "annotations": sandbox_runtime_bootstrap_claim( - "restart", - SandboxRuntimeBootstrapPhase::Preparing, - Some(generation), - ), - }, - }) -} - fn sandbox_runtime_suspension_patch( api_version: &str, resource_version: &str, @@ -8938,16 +9074,19 @@ fn sandbox_runtime_suspension_patch( } else { serde_json::json!({"replicas": 0}) }; + let mut annotations = sandbox_runtime_bootstrap_claim( + SandboxRuntimeBootstrapOperation::Stop, + SandboxRuntimeBootstrapPhase::Suspending, + 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::Suspending.as_str(), - ANNOTATION_SANDBOX_RUNTIME_READINESS: "unavailable", - }, + "annotations": annotations, }, "spec": desired_state, }) @@ -10631,7 +10770,7 @@ mod tests { assert!(sandbox_runtime_bootstrap_in_progress(&object)); assert_eq!( sandbox_runtime_bootstrap_operation(&object), - Some("restart") + Some(SandboxRuntimeBootstrapOperation::Restart) ); let started_at = SystemTime::UNIX_EPOCH + started; assert!(!sandbox_runtime_bootstrap_is_stale( diff --git a/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs b/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs index dc8a601330..a07abe06dc 100644 --- a/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs +++ b/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs @@ -476,7 +476,10 @@ mod lifecycle_reconciliation { // 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!( + requests_to(&requests, &http::Method::GET, &sandbox) >= 2, + "{version}" + ); assert_eq!(mutations(&requests), vec![], "{version}"); } } @@ -538,6 +541,148 @@ mod lifecycle_reconciliation { } } + /// A Sandbox API whose reads return the next of `reads`, repeating the + /// last, and whose first patch conflicts when `conflict_first` is set. + fn claimed_sandbox_api( + reads: Vec, + conflict_first: bool, + ) -> (Api, RecordedRequests) { + let requests = RecordedRequests::default(); + let recorded = requests.clone(); + let reads = Arc::new(std::sync::Mutex::new(VecDeque::from(reads))); + let conflict = Arc::new(std::sync::atomic::AtomicBool::new(conflict_first)); + let service = tower::service_fn(move |request: http::Request| { + let method = request.method().clone(); + recorded + .lock() + .unwrap() + .push((method.clone(), request.uri().path().to_string())); + let mut reads = reads.lock().unwrap(); + let current = if reads.len() > 1 { + reads.pop_front().unwrap() + } else { + reads.front().unwrap().clone() + }; + let (status, body) = if method == http::Method::PATCH + && conflict.swap(false, std::sync::atomic::Ordering::SeqCst) + { + ( + http::StatusCode::CONFLICT, + serde_json::json!({ + "apiVersion": "v1", "kind": "Status", "status": "Failure", + "reason": "Conflict", "code": 409, "message": "object was modified" + }), + ) + } else { + (http::StatusCode::OK, current) + }; + async move { Ok::<_, std::convert::Infallible>(kube_test_response(status, body)) } + }); + let api = KubernetesComputeDriver::agent_sandbox_api( + Client::new(service, "openshell"), + SANDBOX_VERSION_V1BETA1, + "openshell", + ) + .api; + (api, requests) + } + + fn restart_claim() -> SandboxRuntimeBootstrapClaim<'static> { + SandboxRuntimeBootstrapClaim { + cr_uid: "cr-uid", + operation: SandboxRuntimeBootstrapOperation::Restart, + generation: "gen2", + } + } + + fn our_restart_claim() -> serde_json::Value { + let mut object = fresh_claim(SANDBOX_VERSION_V1BETA1, "restart"); + object["metadata"]["annotations"][ANNOTATION_SANDBOX_RUNTIME_GENERATION] = + serde_json::json!("gen2"); + object + } + + fn patches(requests: &RecordedRequests) -> usize { + requests + .lock() + .unwrap() + .iter() + .filter(|(method, _)| *method == http::Method::PATCH) + .count() + } + + // The lease holder suspends a Sandbox, for example after an admission + // failure, while a restart on another replica holds its claim. The + // restart's next write conflicts, rereads the suspension, and must fail + // so the restart rolls back instead of releasing the workload again. + #[tokio::test] + async fn claimed_writes_do_not_overwrite_another_transition() { + let suspended = snapshot( + SANDBOX_VERSION_V1BETA1, + Some(SandboxRuntimeBootstrapPhase::Suspending), + ); + let (api, requests) = claimed_sandbox_api(vec![our_restart_claim(), suspended], true); + let error = patch_claimed_sandbox(&api, "sandbox-cr", restart_claim(), |version| { + sandbox_operating_state_patch(SANDBOX_VERSION_V1BETA1, version, true) + }) + .await + .unwrap_err(); + assert!( + matches!(error, KubernetesDriverError::Precondition(_)), + "{error}" + ); + assert_eq!(patches(&requests), 1, "only the conflicting write was sent"); + + let (api, requests) = claimed_sandbox_api(vec![our_restart_claim()], true); + patch_claimed_sandbox(&api, "sandbox-cr", restart_claim(), |version| { + sandbox_runtime_bootstrap_phase_patch(version, SandboxRuntimeBootstrapPhase::Released) + }) + .await + .unwrap(); + assert_eq!(patches(&requests), 2, "a held claim retries the conflict"); + } + + #[tokio::test] + async fn restart_claims_only_an_unclaimed_stopped_sandbox() { + let mut other_generation = our_restart_claim(); + other_generation["metadata"]["annotations"][ANNOTATION_SANDBOX_RUNTIME_GENERATION] = + serde_json::json!("gen3"); + let mut running = snapshot(SANDBOX_VERSION_V1BETA1, None); + running["spec"]["operatingMode"] = serde_json::json!("Running"); + for (name, current) in [ + ("another restart", other_generation), + ("our own claim", our_restart_claim()), + ( + "a stop", + snapshot( + SANDBOX_VERSION_V1BETA1, + Some(SandboxRuntimeBootstrapPhase::Releasing), + ), + ), + ("a running sandbox", running), + ] { + let (api, requests) = claimed_sandbox_api(vec![current], false); + let error = compare_and_patch_dynamic_object(&api, "sandbox-cr", |current| { + restart_claim().begin_patch(current) + }) + .await + .unwrap_err(); + assert!( + matches!(error, KubernetesDriverError::Precondition(_)), + "{name}: {error}" + ); + assert_eq!(patches(&requests), 0, "{name}"); + } + + let (api, requests) = claimed_sandbox_api(vec![snapshot(SANDBOX_VERSION_V1BETA1, None)], true); + compare_and_patch_dynamic_object(&api, "sandbox-cr", |current| { + restart_claim().begin_patch(current) + }) + .await + .unwrap(); + assert_eq!(patches(&requests), 2); + } + #[tokio::test] async fn supervisor_deletion_does_not_wait_for_a_replacement_pod() { let pod = |uid: &str| { From f17d2b2349d7cff998e64e8322cd194734a67dcf Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 30 Nov 2026 16:31:48 -0800 Subject: [PATCH 2/5] fix(kubernetes): roll back a restart only while it holds its claim A restart whose claimed write failed rolled back with a full stop, which deleted the supervisor Pod by name and wrote the suspension blindly. If another replica's restart had taken over the claim, the rollback tore that restart down. The rollback now writes the suspension as a claimed write. If the claim no longer holds, it leaves the Sandbox to the transition that replaced it and deletes only the supervisor Pod this request created, by UID. A claim in the Released phase still counts as held, so a rollback after a Released write that timed out but landed still stops the sandbox. Signed-off-by: Matthew Grossman --- .../openshell-driver-kubernetes/src/driver.rs | 85 +++++++++++++++++-- .../src/lifecycle_tests.rs | 37 ++++++++ 2 files changed, 113 insertions(+), 9 deletions(-) diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index ef98a0c5f3..d019041448 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -387,12 +387,18 @@ struct SandboxRuntimeBootstrapClaim<'a> { } impl SandboxRuntimeBootstrapClaim<'_> { - /// Fail unless `current` still carries this claim, still `Preparing`. + /// Fail unless `current` still carries this claim. `Released` counts, so + /// a rollback after a write that timed out but landed still holds it. fn ensure_held(&self, current: &DynamicObject) -> Result<(), KubernetesDriverError> { let held = current.metadata.uid.as_deref() == Some(self.cr_uid) && sandbox_runtime_bootstrap_in_progress(current) - && sandbox_runtime_bootstrap_phase(current) - == Some(SandboxRuntimeBootstrapPhase::Preparing) + && matches!( + sandbox_runtime_bootstrap_phase(current), + Some( + SandboxRuntimeBootstrapPhase::Preparing + | SandboxRuntimeBootstrapPhase::Released + ) + ) && sandbox_runtime_bootstrap_operation(current) == Some(self.operation) && sandbox_runtime_generation(current) == Some(self.generation); if held { @@ -4640,6 +4646,7 @@ impl KubernetesComputeDriver { operation: SandboxRuntimeBootstrapOperation::Restart, generation: generation.as_str(), }; + let mut created_supervisor_pod = None; let restart = async { // Only the lease holder reconciles, and its lifecycle gate does // not cover requests served by other replicas. Claim the Sandbox @@ -4650,8 +4657,8 @@ impl KubernetesComputeDriver { }) .await?; let supervisor = match &placement { - SupervisorPlacement::Dedicated => GenerationSupervisor::Dedicated { - pod_uid: self + SupervisorPlacement::Dedicated => { + let pod_uid = self .create_sandbox_runtime_supervisor( &namespace, &names, @@ -4669,9 +4676,13 @@ impl KubernetesComputeDriver { &log_level, staged.upstream_proxy_ca_bundle.is_some(), ) - .await?, - connection: control_connection, - }, + .await?; + created_supervisor_pod = Some(pod_uid.clone()); + GenerationSupervisor::Dedicated { + pod_uid, + connection: control_connection, + } + } SupervisorPlacement::Shared { route } => GenerationSupervisor::Shared { route: route.clone(), }, @@ -4737,7 +4748,17 @@ impl KubernetesComputeDriver { 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 { + if let Err(rollback_error) = self + .roll_back_restart( + &sandbox_api, + cr_name, + claim, + &namespace, + sandbox_id, + created_supervisor_pod.as_deref(), + ) + .await + { return Err(KubernetesDriverError::Message(format!( "restart failed: {error}; rollback remains pending: {rollback_error}" ))); @@ -4868,6 +4889,52 @@ impl KubernetesComputeDriver { } } + /// Roll back a failed restart. A restart that still holds its claim + /// suspends the Sandbox and stops it. One whose claim was superseded, + /// for example by another replica's restart or the lease holder's + /// suspension, leaves the Sandbox to that transition and deletes only + /// the supervisor Pod it created, by UID. + async fn roll_back_restart( + &self, + sandbox_api: &AgentSandboxApi, + cr_name: &str, + claim: SandboxRuntimeBootstrapClaim<'_>, + namespace: &str, + sandbox_id: &str, + created_supervisor_pod: Option<&str>, + ) -> Result<(), KubernetesDriverError> { + // The suspension is a claimed write, so no other transition can + // start between the claim check and the rollback taking over. The + // stop that follows is not claim-aware: if another start finishes + // the same stop and claims the Sandbox before this stop's final + // poll, this stop can still remove that start's supervisor Pod, as + // with any two concurrent stops. + let held = match patch_claimed_sandbox(&sandbox_api.api, cr_name, claim, |version| { + sandbox_runtime_suspension_patch(&sandbox_api.resource.version, version) + }) + .await + { + Ok(_) => true, + Err(KubernetesDriverError::Precondition(_) | KubernetesDriverError::NotFound) => false, + Err(error) => return Err(error), + }; + if let Some(uid) = created_supervisor_pod { + let pods = Api::::namespaced(self.client.clone(), namespace); + if let Some(pod) = pods + .get_opt(&SandboxRuntimeNames::new(sandbox_id).supervisor_pod) + .await + .map_err(KubernetesDriverError::from_kube)? + && pod.metadata.uid.as_deref() == Some(uid) + { + delete_supervisor_pod_and_wait(&pods, pod).await?; + } + } + if held { + self.stop_sandbox_inner(sandbox_id).await?; + } + Ok(()) + } + async fn delete_sandbox_runtime_supervisor_pod( &self, sandbox_id: &str, diff --git a/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs b/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs index a07abe06dc..7db14ed400 100644 --- a/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs +++ b/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs @@ -683,6 +683,43 @@ mod lifecycle_reconciliation { assert_eq!(patches(&requests), 2); } + // A slow restart's claim (gen2) was taken over by a restart on another + // replica (gen3), which created its own supervisor Pod under the same + // name. The superseded restart's rollback must leave both alone. + #[tokio::test] + async fn superseded_restart_rollback_spares_the_other_restart() { + let mut other_restart = our_restart_claim(); + other_restart["metadata"]["annotations"][ANNOTATION_SANDBOX_RUNTIME_GENERATION] = + serde_json::json!("gen3"); + let (driver, requests) = other_replica_driver(SANDBOX_VERSION_V1BETA1, vec![other_restart]); + let sandbox_api = KubernetesComputeDriver::agent_sandbox_api( + driver.client.clone(), + SANDBOX_VERSION_V1BETA1, + "openshell", + ); + driver + .roll_back_restart( + &sandbox_api, + "sandbox-cr", + restart_claim(), + "openshell", + "sandbox-1", + Some("our-supervisor-uid"), + ) + .await + .unwrap(); + // It looked for its own Pod, found the other restart's, and kept it. + assert_eq!( + requests_to( + &requests, + &http::Method::GET, + "/api/v1/namespaces/openshell/pods/os-supervisor-sandbox-1" + ), + 1 + ); + assert_eq!(mutations(&requests), vec![]); + } + #[tokio::test] async fn supervisor_deletion_does_not_wait_for_a_replacement_pod() { let pod = |uid: &str| { From fd6c000179348c72ce6fec9627a8e63220e9ad78 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 30 Nov 2026 16:32:19 -0800 Subject: [PATCH 3/5] docs(kubernetes): describe how a superseded restart rolls back Signed-off-by: Matthew Grossman --- crates/openshell-driver-kubernetes/README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index 37ccac7e7e..82eb0a483c 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -405,9 +405,11 @@ the CR is stopped and no other transition is in progress, and reconciliation respects it until the bootstrap grace period expires, then reaps it: a stale restart is suspended and a stale create is deleted. Each later create or restart write to the CR checks that its claim still holds; if another replica started a -transition such as a suspension, the request fails and rolls back. 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. +transition such as a suspension, the request fails. A failed create deletes its +CR. A failed restart that lost its claim leaves the CR to the other transition +and deletes only the supervisor Pod it created. 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 From 9237e66d85d80083ef5eced7c5a19186dd3357a0 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 30 Nov 2026 16:47:23 -0800 Subject: [PATCH 4/5] docs(kubernetes): state the bootstrap claim rule Signed-off-by: Matthew Grossman --- crates/openshell-driver-kubernetes/README.md | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index 82eb0a483c..fb178b5a2d 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -403,13 +403,16 @@ replica can serve a lifecycle RPC. A restart claims the CR, marking it `Preparing`, before it creates the supervisor Pod. The claim succeeds only if the CR is stopped and no other transition is in progress, and reconciliation respects it until the bootstrap grace period expires, then reaps it: a stale -restart is suspended and a stale create is deleted. Each later create or restart -write to the CR checks that its claim still holds; if another replica started a -transition such as a suspension, the request fails. A failed create deletes its -CR. A failed restart that lost its claim leaves the CR to the other transition -and deletes only the supervisor Pod it created. 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. +restart is suspended and a stale create is deleted. Every create or restart +write to the CR is a compare-and-swap against the request's claim (CR UID, +operation, and generation), and supervisor Pods are deleted by UID. If another +replica started a transition such as a suspension, the request fails. A failed +create deletes its CR. A failed restart that lost its claim leaves the CR to the +other transition and deletes only the supervisor Pod it created. Stop and +suspend writes don't check a claim yet +([#6110](https://github.com/ai-openshell/openshell/issues/6110)). 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 From dd4adce36f3e21a98f8cbb8ae0fc148d5ff2f1fa Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 30 Nov 2026 17:07:36 -0800 Subject: [PATCH 5/5] refactor(kubernetes): move the bootstrap claim into its own module The claim types, annotation accessors, compare-and-swap patch, and by-UID supervisor deletion move from driver.rs to bootstrap_claim.rs. The claim is now the only write path for create and restart: begin, patch, and release. Writes without a claim call compare_and_patch_dynamic_object directly, so the resourceVersion retry wrapper and patch_claimed_sandbox are gone. A missing resourceVersion is now an error instead of an unconditional write. A failed restart now returns the supervisor Pod it created with its error instead of setting a captured variable, and the rollback is split into suspend_if_claimed and delete_created_supervisor_pod. Create builds its claim from the generation it already has. The README states the remaining concurrent-stop window. Signed-off-by: Matthew Grossman --- crates/openshell-driver-kubernetes/README.md | 4 +- .../src/bootstrap_claim.rs | 368 +++++++++++ .../openshell-driver-kubernetes/src/driver.rs | 611 +++++------------- .../src/lifecycle_tests.rs | 42 +- 4 files changed, 547 insertions(+), 478 deletions(-) create mode 100644 crates/openshell-driver-kubernetes/src/bootstrap_claim.rs diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index fb178b5a2d..5a059dbd7f 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -410,7 +410,9 @@ replica started a transition such as a suspension, the request fails. A failed create deletes its CR. A failed restart that lost its claim leaves the CR to the other transition and deletes only the supervisor Pod it created. Stop and suspend writes don't check a claim yet -([#6110](https://github.com/ai-openshell/openshell/issues/6110)). Before it +([#6110](https://github.com/ai-openshell/openshell/issues/6110)), so a stop, +including a failed restart's rollback, can remove the supervisor Pod of a start +that claimed the CR while the stop was finishing. 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/bootstrap_claim.rs b/crates/openshell-driver-kubernetes/src/bootstrap_claim.rs new file mode 100644 index 0000000000..b51a2792e8 --- /dev/null +++ b/crates/openshell-driver-kubernetes/src/bootstrap_claim.rs @@ -0,0 +1,368 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Bootstrap claims on a Sandbox CR and the compare-and-swap writes that +//! respect them. +//! +//! A create or restart claims a Sandbox by recording its operation, phase, +//! and generation in annotations. Any gateway replica may serve the request, +//! so each later write compares the stored claim with the request's own and +//! refuses to overwrite a transition another replica started. + +use super::{ + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION, ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE, + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_STARTED_AT, ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAPPING, + ANNOTATION_SANDBOX_RUNTIME_GENERATION, ANNOTATION_SANDBOX_RUNTIME_READINESS, KUBE_API_TIMEOUT, + KubernetesDriverError, is_kube_resource_version_conflict, kubernetes_pod_termination_timeout, + sandbox_runtime_generation, sandbox_runtime_should_run, +}; +use k8s_openapi::api::core::v1::Pod; +use kube::Api; +use kube::Error as KubeError; +use kube::api::{DeleteParams, Patch, PatchParams, Preconditions}; +use kube::core::DynamicObject; +use std::collections::BTreeMap; +use std::time::Duration; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum SandboxRuntimeBootstrapPhase { + Preparing, + Released, + Releasing, + Suspending, +} + +impl SandboxRuntimeBootstrapPhase { + pub(super) const fn as_str(self) -> &'static str { + match self { + Self::Preparing => "preparing", + Self::Released => "released", + Self::Releasing => "releasing", + Self::Suspending => "suspending", + } + } + + pub(super) fn parse(value: &str) -> Option { + match value { + "preparing" => Some(Self::Preparing), + "released" => Some(Self::Released), + "releasing" => Some(Self::Releasing), + "suspending" => Some(Self::Suspending), + _ => None, + } + } + + /// Whether a create or restart claim in this phase still belongs to the + /// request that made it. `Released` does, so a request whose `Released` + /// write timed out but landed can still roll back. + const fn held_by_claimant(self) -> bool { + matches!(self, Self::Preparing | Self::Released) + } +} + +/// The lifecycle request that started a bootstrap transition. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum SandboxRuntimeBootstrapOperation { + Create, + Restart, + Stop, +} + +impl SandboxRuntimeBootstrapOperation { + const fn as_str(self) -> &'static str { + match self { + Self::Create => "create", + Self::Restart => "restart", + Self::Stop => "stop", + } + } + + fn parse(value: &str) -> Option { + [Self::Create, Self::Restart, Self::Stop] + .into_iter() + .find(|operation| operation.as_str() == value) + } +} + +fn annotation<'a>(object: &'a DynamicObject, key: &str) -> Option<&'a str> { + object + .metadata + .annotations + .as_ref() + .and_then(|annotations| annotations.get(key)) + .map(String::as_str) +} + +pub(super) fn sandbox_runtime_bootstrap_in_progress(object: &DynamicObject) -> bool { + annotation(object, ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAPPING) == Some("true") +} + +pub(super) fn sandbox_runtime_bootstrap_operation( + object: &DynamicObject, +) -> Option { + annotation(object, ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION) + .and_then(SandboxRuntimeBootstrapOperation::parse) +} + +pub(super) fn sandbox_runtime_bootstrap_phase( + object: &DynamicObject, +) -> Option { + annotation(object, ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE) + .and_then(SandboxRuntimeBootstrapPhase::parse) +} + +/// Annotations that start a bootstrap transition and its grace period. +fn bootstrap_annotations( + operation: SandboxRuntimeBootstrapOperation, + phase: SandboxRuntimeBootstrapPhase, +) -> BTreeMap { + 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.as_str().to_string(), + ), + ( + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE.to_string(), + phase.as_str().to_string(), + ), + ]) +} + +/// Annotations that start a stop in `phase` and mark the runtime unavailable. +pub(super) fn stop_annotations(phase: SandboxRuntimeBootstrapPhase) -> BTreeMap { + let mut annotations = bootstrap_annotations(SandboxRuntimeBootstrapOperation::Stop, phase); + annotations.insert( + ANNOTATION_SANDBOX_RUNTIME_READINESS.to_string(), + "unavailable".to_string(), + ); + annotations +} + +/// The resourceVersion a compare-and-swap patch pins. An object without one +/// would turn the patch into an unconditional write, so it is an error. +pub(super) fn resource_version(object: &DynamicObject) -> Result<&str, KubernetesDriverError> { + object.metadata.resource_version.as_deref().ok_or_else(|| { + KubernetesDriverError::Message(format!( + "Kubernetes resource {} has no resourceVersion", + object.metadata.name.as_deref().unwrap_or("") + )) + }) +} + +/// Read `name` and apply the merge patch `patch_for` builds from it, retrying +/// with a fresh read on a resourceVersion conflict. `patch_for` sees the +/// current object each time and may refuse the write; the patch must pin +/// [`resource_version`] for the comparison to hold. +pub(super) async fn compare_and_patch_dynamic_object( + api: &Api, + name: &str, + mut patch_for: impl FnMut(&DynamicObject) -> Result, +) -> Result { + let operation = async { + loop { + let current = api + .get(name) + .await + .map_err(KubernetesDriverError::from_kube)?; + let patch = patch_for(¤t)?; + match api + .patch(name, &PatchParams::default(), &Patch::Merge(&patch)) + .await + { + Ok(updated) => return Ok(updated), + Err(error) if is_kube_resource_version_conflict(&error) => { + tokio::task::yield_now().await; + } + Err(error) => return Err(KubernetesDriverError::from_kube(error)), + } + } + }; + tokio::time::timeout(KUBE_API_TIMEOUT, operation) + .await + .map_err(|_| { + KubernetesDriverError::Message(format!( + "timed out after {}s updating Kubernetes resource {name}", + KUBE_API_TIMEOUT.as_secs() + )) + })? +} + +/// A create or restart request's claim on a Sandbox's bootstrap. +#[derive(Clone, Copy, Debug)] +pub(super) struct SandboxRuntimeBootstrapClaim<'a> { + cr_uid: &'a str, + operation: SandboxRuntimeBootstrapOperation, + generation: &'a str, +} + +impl<'a> SandboxRuntimeBootstrapClaim<'a> { + pub(super) const fn new( + cr_uid: &'a str, + operation: SandboxRuntimeBootstrapOperation, + generation: &'a str, + ) -> Self { + Self { + cr_uid, + operation, + generation, + } + } + + pub(super) const fn cr_uid(&self) -> &'a str { + self.cr_uid + } + + /// Annotations that record a claim for `operation` and `generation`. A + /// create writes them when it creates the CR, before its UID exists. + pub(super) fn annotations( + operation: SandboxRuntimeBootstrapOperation, + generation: &str, + ) -> BTreeMap { + let mut annotations = + bootstrap_annotations(operation, SandboxRuntimeBootstrapPhase::Preparing); + annotations.insert( + ANNOTATION_SANDBOX_RUNTIME_GENERATION.to_string(), + generation.to_string(), + ); + annotations + } + + /// Claim a stopped Sandbox that no other transition has claimed. + pub(super) async fn begin( + &self, + api: &Api, + name: &str, + ) -> Result<(), KubernetesDriverError> { + compare_and_patch_dynamic_object(api, name, |current| { + if current.metadata.uid.as_deref() != Some(self.cr_uid) { + return Err(KubernetesDriverError::Precondition( + "the Sandbox resource was replaced".to_string(), + )); + } + if sandbox_runtime_bootstrap_in_progress(current) || sandbox_runtime_should_run(current) + { + return Err(KubernetesDriverError::Precondition( + "another lifecycle transition claimed the sandbox; retry after it completes" + .to_string(), + )); + } + Ok(serde_json::json!({ + "metadata": { + "resourceVersion": resource_version(current)?, + "annotations": Self::annotations(self.operation, self.generation), + }, + })) + }) + .await?; + Ok(()) + } + + /// Apply the patch `patch_for` builds from the current resourceVersion, + /// but only while this claim still holds. Fails with `Precondition` once + /// another transition has replaced it. + pub(super) async fn patch( + &self, + api: &Api, + name: &str, + mut patch_for: impl FnMut(&str) -> serde_json::Value, + ) -> Result { + compare_and_patch_dynamic_object(api, name, |current| { + self.ensure_held(current)?; + Ok(patch_for(resource_version(current)?)) + }) + .await + } + + /// Mark the generation installed so reconciliation may complete it. + pub(super) async fn release( + &self, + api: &Api, + name: &str, + ) -> Result<(), KubernetesDriverError> { + self.patch(api, name, |version| { + serde_json::json!({ + "metadata": { + "resourceVersion": version, + "annotations": { + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE: + SandboxRuntimeBootstrapPhase::Released.as_str(), + } + } + }) + }) + .await?; + Ok(()) + } + + fn ensure_held(&self, current: &DynamicObject) -> Result<(), KubernetesDriverError> { + let held = current.metadata.uid.as_deref() == Some(self.cr_uid) + && sandbox_runtime_bootstrap_in_progress(current) + && sandbox_runtime_bootstrap_phase(current) + .is_some_and(SandboxRuntimeBootstrapPhase::held_by_claimant) + && sandbox_runtime_bootstrap_operation(current) == Some(self.operation) + && sandbox_runtime_generation(current) == Some(self.generation); + if held { + Ok(()) + } else { + Err(KubernetesDriverError::Precondition(format!( + "sandbox {} of generation {} was superseded by another lifecycle transition", + self.operation.as_str(), + self.generation + ))) + } + } +} + +/// 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. +pub(super) async fn delete_supervisor_pod_and_wait( + pods: &Api, + pod: Pod, +) -> Result<(), KubernetesDriverError> { + let name = + pod.metadata.name.clone().ok_or_else(|| { + KubernetesDriverError::Message("supervisor Pod has no name".to_string()) + })?; + 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; + } +} diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index d019041448..d57887ae40 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -90,9 +90,18 @@ use tokio::sync::{OnceCell, mpsc}; use tokio_stream::wrappers::ReceiverStream; use tracing::{debug, info, warn}; +#[path = "bootstrap_claim.rs"] +mod bootstrap_claim; #[path = "image_update.rs"] mod image_update; +use bootstrap_claim::{ + SandboxRuntimeBootstrapClaim, SandboxRuntimeBootstrapOperation, SandboxRuntimeBootstrapPhase, + compare_and_patch_dynamic_object, delete_supervisor_pod_and_wait, resource_version, + sandbox_runtime_bootstrap_in_progress, sandbox_runtime_bootstrap_operation, + sandbox_runtime_bootstrap_phase, stop_annotations, +}; + pub type WatchStream = Pin> + Send>>; @@ -318,129 +327,6 @@ async fn create_or_validate_network_additional_ca_config_map( } } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum SandboxRuntimeBootstrapPhase { - Preparing, - Released, - Releasing, - Suspending, -} - -impl SandboxRuntimeBootstrapPhase { - const fn as_str(self) -> &'static str { - match self { - Self::Preparing => "preparing", - Self::Released => "released", - Self::Releasing => "releasing", - Self::Suspending => "suspending", - } - } - - fn parse(value: &str) -> Option { - match value { - "preparing" => Some(Self::Preparing), - "released" => Some(Self::Released), - "releasing" => Some(Self::Releasing), - "suspending" => Some(Self::Suspending), - _ => None, - } - } -} - -/// The lifecycle request that started a bootstrap transition. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum SandboxRuntimeBootstrapOperation { - Create, - Restart, - Stop, -} - -impl SandboxRuntimeBootstrapOperation { - const fn as_str(self) -> &'static str { - match self { - Self::Create => "create", - Self::Restart => "restart", - Self::Stop => "stop", - } - } - - fn parse(value: &str) -> Option { - match value { - "create" => Some(Self::Create), - "restart" => Some(Self::Restart), - "stop" => Some(Self::Stop), - _ => None, - } - } -} - -/// A create or restart request's claim on a Sandbox's bootstrap. -/// -/// Any gateway replica may serve the request, so its writes to the Sandbox -/// compare the stored claim with this one and refuse to overwrite a -/// transition another replica started, such as a suspension. -#[derive(Clone, Copy, Debug)] -struct SandboxRuntimeBootstrapClaim<'a> { - cr_uid: &'a str, - operation: SandboxRuntimeBootstrapOperation, - generation: &'a str, -} - -impl SandboxRuntimeBootstrapClaim<'_> { - /// Fail unless `current` still carries this claim. `Released` counts, so - /// a rollback after a write that timed out but landed still holds it. - fn ensure_held(&self, current: &DynamicObject) -> Result<(), KubernetesDriverError> { - let held = current.metadata.uid.as_deref() == Some(self.cr_uid) - && sandbox_runtime_bootstrap_in_progress(current) - && matches!( - sandbox_runtime_bootstrap_phase(current), - Some( - SandboxRuntimeBootstrapPhase::Preparing - | SandboxRuntimeBootstrapPhase::Released - ) - ) - && sandbox_runtime_bootstrap_operation(current) == Some(self.operation) - && sandbox_runtime_generation(current) == Some(self.generation); - if held { - Ok(()) - } else { - Err(KubernetesDriverError::Precondition(format!( - "sandbox {} of generation {} was superseded by another lifecycle transition", - self.operation.as_str(), - self.generation - ))) - } - } - - /// Claim a stopped Sandbox that no other transition has claimed. - fn begin_patch( - &self, - current: &DynamicObject, - ) -> Result { - if current.metadata.uid.as_deref() != Some(self.cr_uid) { - return Err(KubernetesDriverError::Precondition( - "the Sandbox resource was replaced".to_string(), - )); - } - if sandbox_runtime_bootstrap_in_progress(current) || sandbox_runtime_should_run(current) { - return Err(KubernetesDriverError::Precondition( - "another lifecycle transition claimed the sandbox; retry after it completes" - .to_string(), - )); - } - Ok(serde_json::json!({ - "metadata": { - "resourceVersion": resource_version(current), - "annotations": sandbox_runtime_bootstrap_claim( - self.operation, - SandboxRuntimeBootstrapPhase::Preparing, - Some(self.generation), - ), - }, - })) - } -} - fn boundary_service_authority( namespace: &str, names: &SandboxRuntimeNames, @@ -483,6 +369,32 @@ struct StagedBootstrapMaterial { client_tls: Option, } +/// A failed restart and the supervisor Pod it created, if it got that far. +struct RestartFailure { + source: KubernetesDriverError, + created_supervisor_pod: Option, +} + +/// Suspend the Sandbox in one write if `claim` still holds it. Returns +/// `false`, writing nothing, once another transition has replaced the claim +/// or the Sandbox is gone. +async fn suspend_if_claimed( + sandbox_api: &AgentSandboxApi, + cr_name: &str, + claim: SandboxRuntimeBootstrapClaim<'_>, +) -> Result { + match claim + .patch(&sandbox_api.api, cr_name, |version| { + sandbox_runtime_suspension_patch(&sandbox_api.resource.version, version) + }) + .await + { + Ok(_) => Ok(true), + Err(KubernetesDriverError::Precondition(_) | KubernetesDriverError::NotFound) => Ok(false), + Err(error) => Err(error), + } +} + /// The supervisor a generation is installed with. enum GenerationSupervisor { /// A supervisor Pod paired with this generation's workload Pod. @@ -637,126 +549,6 @@ fn is_kube_resource_version_conflict(error: &KubeError) -> bool { matches!(error, KubeError::Api(api) if api.code == 409 && api.reason == "Conflict") } -fn resource_version(object: &DynamicObject) -> &str { - object - .metadata - .resource_version - .as_deref() - .unwrap_or_default() -} - -/// Read `name` and apply the merge patch `patch_for` builds from it, retrying -/// with a fresh read on a resourceVersion conflict. `patch_for` sees the -/// current object each time and may refuse the write; the patch must pin the -/// current resourceVersion for the comparison to hold. -async fn compare_and_patch_dynamic_object( - api: &Api, - name: &str, - mut patch_for: impl FnMut(&DynamicObject) -> Result, -) -> Result { - let operation = async { - loop { - let current = api - .get(name) - .await - .map_err(KubernetesDriverError::from_kube)?; - let patch = patch_for(¤t)?; - match api - .patch(name, &PatchParams::default(), &Patch::Merge(&patch)) - .await - { - Ok(updated) => return Ok(updated), - Err(error) if is_kube_resource_version_conflict(&error) => { - tokio::task::yield_now().await; - } - Err(error) => return Err(KubernetesDriverError::from_kube(error)), - } - } - }; - tokio::time::timeout(KUBE_API_TIMEOUT, operation) - .await - .map_err(|_| { - KubernetesDriverError::Message(format!( - "timed out after {}s updating Kubernetes resource {name}", - KUBE_API_TIMEOUT.as_secs() - )) - })? -} - -/// Apply a patch whatever the current state of the object, retrying -/// resourceVersion conflicts. Use [`compare_and_patch_dynamic_object`] when -/// another writer's transition must not be overwritten. -async fn patch_dynamic_object_with_resource_version_retry( - api: &Api, - name: &str, - mut patch_for_resource_version: impl FnMut(&str) -> serde_json::Value, -) -> Result { - compare_and_patch_dynamic_object(api, name, |current| { - Ok(patch_for_resource_version(resource_version(current))) - }) - .await -} - -/// Apply a patch while `claim` still holds the Sandbox's bootstrap. -async fn patch_claimed_sandbox( - api: &Api, - name: &str, - claim: SandboxRuntimeBootstrapClaim<'_>, - mut patch_for_resource_version: impl FnMut(&str) -> serde_json::Value, -) -> Result { - compare_and_patch_dynamic_object(api, name, |current| { - claim.ensure_held(current)?; - Ok(patch_for_resource_version(resource_version(current))) - }) - .await -} - -/// 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().ok_or_else(|| { - KubernetesDriverError::Message("supervisor Pod has no name".to_string()) - })?; - 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 { @@ -2865,10 +2657,9 @@ impl KubernetesComputeDriver { .to_string(), ); add_trace_context_annotation(&mut annotations); - annotations.extend(sandbox_runtime_bootstrap_claim( + annotations.extend(SandboxRuntimeBootstrapClaim::annotations( SandboxRuntimeBootstrapOperation::Create, - SandboxRuntimeBootstrapPhase::Preparing, - Some(&generation), + &generation, )); annotations.insert( ANNOTATION_SANDBOX_RUNTIME_MAIN_PROCESS_SPEC.to_string(), @@ -2954,6 +2745,7 @@ impl KubernetesComputeDriver { &kube_name, &agent_sandbox_api, &created, + &generation, &proxy_names, control_connection, &placement, @@ -3474,6 +3266,7 @@ impl KubernetesComputeDriver { cr_name: &str, sandbox_api: &AgentSandboxApi, sandbox_cr: &DynamicObject, + generation: &str, names: &SandboxRuntimeNames, control_connection: KubernetesControlConnection, placement: &SupervisorPlacement, @@ -3496,13 +3289,11 @@ impl KubernetesComputeDriver { let cr_uid = sandbox_cr.metadata.uid.as_deref().ok_or_else(|| { KubernetesDriverError::Message("created Sandbox CR has no UID".to_string()) })?; - let claim = SandboxRuntimeBootstrapClaim { + let claim = SandboxRuntimeBootstrapClaim::new( cr_uid, - operation: SandboxRuntimeBootstrapOperation::Create, - generation: sandbox_runtime_generation(sandbox_cr).ok_or_else(|| { - KubernetesDriverError::Message("created Sandbox CR has no generation".to_string()) - })?, - }; + SandboxRuntimeBootstrapOperation::Create, + generation, + ); let dependent_owner = sandbox_runtime_sandbox_owner_reference( cr_name, cr_uid, @@ -3556,10 +3347,11 @@ impl KubernetesComputeDriver { // the workload Pod. The Pod remains unschedulable because its template // carries the OpenShell scheduling gate and references a Secret that // does not exist yet. - patch_claimed_sandbox(&sandbox_api.api, cr_name, claim, |version| { - sandbox_operating_state_patch(&sandbox_api.resource.version, version, true) - }) - .await?; + claim + .patch(&sandbox_api.api, cr_name, |version| { + sandbox_operating_state_patch(&sandbox_api.resource.version, version, true) + }) + .await?; let mut child_env = sandbox .spec @@ -3944,7 +3736,7 @@ impl KubernetesComputeDriver { launch_authentication: &openshell_core::jwt::SandboxLaunchAuthentication, staged: StagedBootstrapMaterial, ) -> Result<(), KubernetesDriverError> { - let cr_uid = claim.cr_uid; + let cr_uid = claim.cr_uid(); let namespace_uid = Api::::all(self.client.clone()) .get(namespace) .await @@ -4025,12 +3817,13 @@ impl KubernetesComputeDriver { annotations[ANNOTATION_SANDBOX_RUNTIME_CONTROL_POLICY_GENERATION] = policy.generation.to_string().into(); } - patch_claimed_sandbox(&sandbox_api.api, cr_name, claim, |version| { - serde_json::json!({ - "metadata": {"resourceVersion": version, "annotations": annotations.clone()} + claim + .patch(&sandbox_api.api, cr_name, |version| { + serde_json::json!({ + "metadata": {"resourceVersion": version, "annotations": annotations.clone()} + }) }) - }) - .await?; + .await?; let session_id = launch_authentication.supervisor.session_id; let tls = generate_sandbox_tls_material(session_id) @@ -4241,10 +4034,7 @@ impl KubernetesComputeDriver { ) .await .map_err(KubernetesDriverError::from_kube)?; - patch_claimed_sandbox(&sandbox_api.api, cr_name, claim, |version| { - sandbox_runtime_bootstrap_phase_patch(version, SandboxRuntimeBootstrapPhase::Released) - }) - .await?; + claim.release(&sandbox_api.api, cr_name).await?; let control = match target { GenerationLaunchTarget::Dedicated { .. } => BootstrapControl::SupervisorPod { pods, @@ -4290,13 +4080,12 @@ impl KubernetesComputeDriver { if phase != Some(SandboxRuntimeBootstrapPhase::Suspending) { self.release_generation_supervisor(sandbox_id, &namespace, &placement) .await?; - patch_dynamic_object_with_resource_version_retry( - &agent_sandbox_api.api, - &kube_name, - |version| { - sandbox_runtime_suspension_patch(&agent_sandbox_api.resource.version, version) - }, - ) + compare_and_patch_dynamic_object(&agent_sandbox_api.api, &kube_name, |current| { + Ok(sandbox_runtime_suspension_patch( + &agent_sandbox_api.resource.version, + resource_version(current)?, + )) + }) .await?; } let pod_api = Api::::namespaced(self.client.clone(), &namespace); @@ -4342,11 +4131,11 @@ impl KubernetesComputeDriver { sandbox_runtime_generation(&object).as_slice(), ) .await?; - patch_dynamic_object_with_resource_version_retry( - &agent_sandbox_api.api, - &kube_name, - sandbox_runtime_suspension_completion_patch, - ) + compare_and_patch_dynamic_object(&agent_sandbox_api.api, &kube_name, |current| { + Ok(sandbox_runtime_suspension_completion_patch( + resource_version(current)?, + )) + }) .await?; return Ok(()); } @@ -4641,24 +4430,27 @@ impl KubernetesComputeDriver { })?; sandbox_secret["secretName"] = serde_json::json!(names.sandbox_secret); let image_pull_secrets = self.generation_image_pull_secret_names(&names); - let claim = SandboxRuntimeBootstrapClaim { + let claim = SandboxRuntimeBootstrapClaim::new( cr_uid, - operation: SandboxRuntimeBootstrapOperation::Restart, - generation: generation.as_str(), - }; - let mut created_supervisor_pod = None; + SandboxRuntimeBootstrapOperation::Restart, + generation.as_str(), + ); let restart = async { + let before_supervisor = |source| RestartFailure { + source, + created_supervisor_pod: None, + }; // Only the lease holder reconciles, and its lifecycle gate does // not cover requests served by other replicas. Claim the Sandbox // before creating the supervisor Pod so reconciliation that // refreshed the stopped Sandbox cannot delete the new Pod. - compare_and_patch_dynamic_object(&sandbox_api.api, cr_name, |current| { - claim.begin_patch(current) - }) - .await?; + claim + .begin(&sandbox_api.api, cr_name) + .await + .map_err(before_supervisor)?; let supervisor = match &placement { - SupervisorPlacement::Dedicated => { - let pod_uid = self + SupervisorPlacement::Dedicated => GenerationSupervisor::Dedicated { + pod_uid: self .create_sandbox_runtime_supervisor( &namespace, &names, @@ -4676,22 +4468,20 @@ impl KubernetesComputeDriver { &log_level, staged.upstream_proxy_ca_bundle.is_some(), ) - .await?; - created_supervisor_pod = Some(pod_uid.clone()); - GenerationSupervisor::Dedicated { - pod_uid, - connection: control_connection, - } - } + .await + .map_err(before_supervisor)?, + connection: control_connection, + }, SupervisorPlacement::Shared { route } => GenerationSupervisor::Shared { route: route.clone(), }, }; - patch_claimed_sandbox( - &sandbox_api.api, - cr_name, - claim, - |version| { + let created_supervisor_pod = match &supervisor { + GenerationSupervisor::Dedicated { pod_uid, .. } => Some(pod_uid.clone()), + GenerationSupervisor::Shared { .. } => None, + }; + let finish = async { + claim.patch(&sandbox_api.api, cr_name, |version| { let mut running_patch = sandbox_operating_state_patch(&sandbox_api.resource.version, version, true); let (supervisor_uid, topology, instance_route) = match &supervisor { @@ -4719,33 +4509,41 @@ impl KubernetesComputeDriver { &image_pull_secrets, ); running_patch - }, - ) - .await?; + }) + .await?; - let child_env = child_environment_from_sandbox_object(&object); - self.install_sandbox_runtime_generation( - &namespace, - cr_name, - &sandbox_api, - sandbox_id, - claim, - &names, - &supervisor, - agent_uid, - agent_gid, - child_env, - &launch_authentication, - staged, - ) - .await?; + let child_env = child_environment_from_sandbox_object(&object); + self.install_sandbox_runtime_generation( + &namespace, + cr_name, + &sandbox_api, + sandbox_id, + claim, + &names, + &supervisor, + agent_uid, + agent_gid, + child_env, + &launch_authentication, + staged, + ) + .await + } + .await; + finish.map_err(|source| RestartFailure { + source, + created_supervisor_pod, + })?; Ok(supervisor) } .await; let supervisor = match restart { Ok(supervisor) => supervisor, - Err(error) => { + Err(RestartFailure { + source, + created_supervisor_pod, + }) => { // The restart patch may not have recorded the sandbox instance yet. self.remove_shared_instance(&placement); if let Err(rollback_error) = self @@ -4760,10 +4558,10 @@ impl KubernetesComputeDriver { .await { return Err(KubernetesDriverError::Message(format!( - "restart failed: {error}; rollback remains pending: {rollback_error}" + "restart failed: {source}; rollback remains pending: {rollback_error}" ))); } - return Err(error); + return Err(source); } }; Ok(kubernetes_runtime_identity( @@ -4841,11 +4639,9 @@ impl KubernetesComputeDriver { SandboxRuntimeBootstrapPhase::Releasing | SandboxRuntimeBootstrapPhase::Suspending ) ) { - patch_dynamic_object_with_resource_version_retry( - &agent_sandbox_api.api, - &kube_name, - sandbox_runtime_stop_begin_patch, - ) + compare_and_patch_dynamic_object(&agent_sandbox_api.api, &kube_name, |current| { + Ok(sandbox_runtime_stop_begin_patch(resource_version(current)?)) + }) .await?; } @@ -4889,11 +4685,15 @@ impl KubernetesComputeDriver { } } - /// Roll back a failed restart. A restart that still holds its claim - /// suspends the Sandbox and stops it. One whose claim was superseded, - /// for example by another replica's restart or the lease holder's - /// suspension, leaves the Sandbox to that transition and deletes only - /// the supervisor Pod it created, by UID. + /// Roll back a failed restart. While the claim holds, suspend the + /// Sandbox, delete the supervisor Pod this request created, and stop the + /// sandbox. Once another transition has replaced the claim, such as + /// another replica's restart or the lease holder's suspension, leave the + /// Sandbox to it and delete only the created Pod. + /// + /// The stop is not claim-aware yet (#6110): if another start completes the + /// same stop and claims the Sandbox before this stop's last poll, this + /// stop can still remove that start's supervisor Pod. async fn roll_back_restart( &self, sandbox_api: &AgentSandboxApi, @@ -4903,38 +4703,37 @@ impl KubernetesComputeDriver { sandbox_id: &str, created_supervisor_pod: Option<&str>, ) -> Result<(), KubernetesDriverError> { - // The suspension is a claimed write, so no other transition can - // start between the claim check and the rollback taking over. The - // stop that follows is not claim-aware: if another start finishes - // the same stop and claims the Sandbox before this stop's final - // poll, this stop can still remove that start's supervisor Pod, as - // with any two concurrent stops. - let held = match patch_claimed_sandbox(&sandbox_api.api, cr_name, claim, |version| { - sandbox_runtime_suspension_patch(&sandbox_api.resource.version, version) - }) - .await - { - Ok(_) => true, - Err(KubernetesDriverError::Precondition(_) | KubernetesDriverError::NotFound) => false, - Err(error) => return Err(error), - }; + let suspended = suspend_if_claimed(sandbox_api, cr_name, claim).await?; if let Some(uid) = created_supervisor_pod { - let pods = Api::::namespaced(self.client.clone(), namespace); - if let Some(pod) = pods - .get_opt(&SandboxRuntimeNames::new(sandbox_id).supervisor_pod) - .await - .map_err(KubernetesDriverError::from_kube)? - && pod.metadata.uid.as_deref() == Some(uid) - { - delete_supervisor_pod_and_wait(&pods, pod).await?; - } + self.delete_created_supervisor_pod(namespace, sandbox_id, uid) + .await?; } - if held { + if suspended { self.stop_sandbox_inner(sandbox_id).await?; } Ok(()) } + /// Delete this sandbox's supervisor Pod only if it is still the Pod with + /// `uid`, leaving one another request created under the same name. + async fn delete_created_supervisor_pod( + &self, + namespace: &str, + sandbox_id: &str, + uid: &str, + ) -> Result<(), KubernetesDriverError> { + let pods = Api::::namespaced(self.client.clone(), namespace); + if let Some(pod) = pods + .get_opt(&SandboxRuntimeNames::new(sandbox_id).supervisor_pod) + .await + .map_err(KubernetesDriverError::from_kube)? + && pod.metadata.uid.as_deref() == Some(uid) + { + delete_supervisor_pod_and_wait(&pods, pod).await?; + } + Ok(()) + } + async fn delete_sandbox_runtime_supervisor_pod( &self, sandbox_id: &str, @@ -6333,26 +6132,6 @@ fn sandbox_runtime_runtime_is_ready(object: &DynamicObject) -> bool { ready && !suspended } -fn sandbox_runtime_bootstrap_in_progress(object: &DynamicObject) -> bool { - object - .metadata - .annotations - .as_ref() - .and_then(|annotations| annotations.get(ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAPPING)) - .is_some_and(|value| value == "true") -} - -fn sandbox_runtime_bootstrap_operation( - object: &DynamicObject, -) -> Option { - object - .metadata - .annotations - .as_ref() - .and_then(|annotations| annotations.get(ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION)) - .and_then(|value| SandboxRuntimeBootstrapOperation::parse(value)) -} - fn sandbox_runtime_bootstrap_is_ready_to_complete(object: &DynamicObject) -> bool { sandbox_runtime_bootstrap_in_progress(object) && sandbox_runtime_bootstrap_phase(object) == Some(SandboxRuntimeBootstrapPhase::Released) @@ -6366,15 +6145,6 @@ fn sandbox_runtime_bootstrap_is_ready_to_complete(object: &DynamicObject) -> boo && sandbox_runtime_runtime_is_ready(object) } -fn sandbox_runtime_bootstrap_phase(object: &DynamicObject) -> Option { - object - .metadata - .annotations - .as_ref() - .and_then(|annotations| annotations.get(ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE)) - .and_then(|value| SandboxRuntimeBootstrapPhase::parse(value)) -} - fn sandbox_runtime_generation(object: &DynamicObject) -> Option<&str> { object .metadata @@ -6384,20 +6154,6 @@ fn sandbox_runtime_generation(object: &DynamicObject) -> Option<&str> { .map(String::as_str) } -fn sandbox_runtime_bootstrap_phase_patch( - resource_version: &str, - phase: SandboxRuntimeBootstrapPhase, -) -> serde_json::Value { - serde_json::json!({ - "metadata": { - "resourceVersion": resource_version, - "annotations": { - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE: phase.as_str(), - } - } - }) -} - fn sandbox_runtime_bootstrap_is_stale( object: &DynamicObject, now: SystemTime, @@ -9081,49 +8837,8 @@ fn sandbox_operating_state_patch( } } -/// Annotations that start a bootstrap transition and its grace period. -fn sandbox_runtime_bootstrap_claim( - operation: SandboxRuntimeBootstrapOperation, - 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.as_str().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( - SandboxRuntimeBootstrapOperation::Stop, - SandboxRuntimeBootstrapPhase::Releasing, - None, - ); - annotations.insert( - ANNOTATION_SANDBOX_RUNTIME_READINESS.to_string(), - "unavailable".to_string(), - ); + let annotations = stop_annotations(SandboxRuntimeBootstrapPhase::Releasing); serde_json::json!({ "metadata": { "resourceVersion": resource_version, @@ -9141,15 +8856,7 @@ fn sandbox_runtime_suspension_patch( } else { serde_json::json!({"replicas": 0}) }; - let mut annotations = sandbox_runtime_bootstrap_claim( - SandboxRuntimeBootstrapOperation::Stop, - SandboxRuntimeBootstrapPhase::Suspending, - None, - ); - annotations.insert( - ANNOTATION_SANDBOX_RUNTIME_READINESS.to_string(), - "unavailable".to_string(), - ); + let annotations = stop_annotations(SandboxRuntimeBootstrapPhase::Suspending); serde_json::json!({ "metadata": { "resourceVersion": resource_version, diff --git a/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs b/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs index 7db14ed400..1db9895955 100644 --- a/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs +++ b/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs @@ -588,11 +588,11 @@ mod lifecycle_reconciliation { } fn restart_claim() -> SandboxRuntimeBootstrapClaim<'static> { - SandboxRuntimeBootstrapClaim { - cr_uid: "cr-uid", - operation: SandboxRuntimeBootstrapOperation::Restart, - generation: "gen2", - } + SandboxRuntimeBootstrapClaim::new( + "cr-uid", + SandboxRuntimeBootstrapOperation::Restart, + "gen2", + ) } fn our_restart_claim() -> serde_json::Value { @@ -622,11 +622,12 @@ mod lifecycle_reconciliation { Some(SandboxRuntimeBootstrapPhase::Suspending), ); let (api, requests) = claimed_sandbox_api(vec![our_restart_claim(), suspended], true); - let error = patch_claimed_sandbox(&api, "sandbox-cr", restart_claim(), |version| { - sandbox_operating_state_patch(SANDBOX_VERSION_V1BETA1, version, true) - }) - .await - .unwrap_err(); + let error = restart_claim() + .patch(&api, "sandbox-cr", |version| { + sandbox_operating_state_patch(SANDBOX_VERSION_V1BETA1, version, true) + }) + .await + .unwrap_err(); assert!( matches!(error, KubernetesDriverError::Precondition(_)), "{error}" @@ -634,11 +635,7 @@ mod lifecycle_reconciliation { assert_eq!(patches(&requests), 1, "only the conflicting write was sent"); let (api, requests) = claimed_sandbox_api(vec![our_restart_claim()], true); - patch_claimed_sandbox(&api, "sandbox-cr", restart_claim(), |version| { - sandbox_runtime_bootstrap_phase_patch(version, SandboxRuntimeBootstrapPhase::Released) - }) - .await - .unwrap(); + restart_claim().release(&api, "sandbox-cr").await.unwrap(); assert_eq!(patches(&requests), 2, "a held claim retries the conflict"); } @@ -662,11 +659,10 @@ mod lifecycle_reconciliation { ("a running sandbox", running), ] { let (api, requests) = claimed_sandbox_api(vec![current], false); - let error = compare_and_patch_dynamic_object(&api, "sandbox-cr", |current| { - restart_claim().begin_patch(current) - }) - .await - .unwrap_err(); + let error = restart_claim() + .begin(&api, "sandbox-cr") + .await + .unwrap_err(); assert!( matches!(error, KubernetesDriverError::Precondition(_)), "{name}: {error}" @@ -675,11 +671,7 @@ mod lifecycle_reconciliation { } let (api, requests) = claimed_sandbox_api(vec![snapshot(SANDBOX_VERSION_V1BETA1, None)], true); - compare_and_patch_dynamic_object(&api, "sandbox-cr", |current| { - restart_claim().begin_patch(current) - }) - .await - .unwrap(); + restart_claim().begin(&api, "sandbox-cr").await.unwrap(); assert_eq!(patches(&requests), 2); }