diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index bb2c4e49fb..a08e7816cc 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -398,6 +398,20 @@ 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. 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 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 +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 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..e8eb3f30e9 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -580,6 +580,54 @@ 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> { + // 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: Some(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.as_deref() != Some(uid.as_str())) { + 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 +2736,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 +3024,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", @@ -4452,33 +4478,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 +4504,43 @@ 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. + // 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()) + }) + .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, @@ -4521,13 +4557,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(), @@ -4559,20 +4591,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,39 +4744,7 @@ 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, - }), - ) - .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() - { - 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; - } + delete_supervisor_pod_and_wait(&pods, pod).await?; } Ok(()) } @@ -5060,47 +5064,67 @@ 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; + 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. 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) => { + 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 => {} } - if sandbox_runtime_bootstrap_phase(&object) - == Some(SandboxRuntimeBootstrapPhase::Suspending) - { - self.reconcile_sandbox_runtime_suspending( + if !self + .reconcile_sandbox_runtime_fence( &lookup_api, &object, &sandbox_id, namespace, - cr_name, + &names, ) - .await; + .await + { continue; } - 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; - } - } let Ok(Ok(fence)) = tokio::time::timeout(KUBE_API_TIMEOUT, policies.get(&names.workload_policy)).await else { @@ -5216,6 +5240,8 @@ impl KubernetesComputeDriver { } match self .reconcile_sandbox_runtime_supervisor( + &api.api, + cr_name, &sandbox_id, namespace, desired_running, @@ -5484,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, @@ -5623,15 +5674,22 @@ impl KubernetesComputeDriver { async fn reconcile_sandbox_runtime_supervisor( &self, + sandbox_api: &Api, + cr_name: &str, sandbox_id: &str, namespace: &str, desired_running: bool, object: &DynamicObject, ) -> Result<(), KubernetesDriverError> { - let generations = sandbox_runtime_generation(object); if !desired_running { return self - .delete_sandbox_runtime_supervisor(sandbox_id, namespace, generations.as_slice()) + .delete_stopped_sandbox_runtime_supervisor( + sandbox_api, + cr_name, + sandbox_id, + namespace, + object, + ) .await; } if let SupervisorPlacement::Shared { .. } = supervisor_placement(object)? { @@ -5661,6 +5719,57 @@ impl KubernetesComputeDriver { Ok(()) } + /// 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. + /// 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. + /// + /// 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, + cr_name: &str, + sandbox_id: &str, + namespace: &str, + object: &DynamicObject, + ) -> Result<(), KubernetesDriverError> { + 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 current = sandbox_api + .get_opt(cr_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(()); + } + delete_supervisor_pod_and_wait(&pods, pod).await?; + } + self.delete_sandbox_runtime_generation_secrets( + sandbox_id, + namespace, + sandbox_runtime_generation(object).as_slice(), + ) + .await + } + fn spawn_sandbox_runtime_periodic_reconcile( &self, tx: mpsc::Sender>, @@ -8802,17 +8911,68 @@ 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, +) -> serde_json::Value { + serde_json::json!({ + "metadata": { + "resourceVersion": resource_version, + "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 afe894fd39..64a61da733 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 { @@ -185,7 +214,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"); @@ -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![ @@ -322,6 +333,298 @@ 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) { + 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(); + 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 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 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(); + 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!(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()) + } + + /// 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() + .unwrap() + .iter() + .filter(|(m, p)| m == method && p == path) + .count() + } + + fn mutations(requests: &RecordedRequests) -> Vec<(http::Method, String)> { + requests + .lock() + .unwrap() + .iter() + .filter(|(method, _)| *method != http::Method::GET) + .cloned() + .collect() + } + + // 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), 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}"); + } + } + + #[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![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}" + ); + } + } + } + + // 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] + async fn reconciliation_reaps_a_stale_bootstrap() { + 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"); + 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] { @@ -338,7 +641,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; @@ -355,7 +658,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(); @@ -364,8 +667,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; 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`.