Skip to content

Commit d763328

Browse files
fix(kubernetes): delete sandboxes by UID, not revision (#5843)
Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>
1 parent f73b853 commit d763328

2 files changed

Lines changed: 158 additions & 65 deletions

File tree

‎crates/openshell-driver-kubernetes/src/driver.rs‎

Lines changed: 57 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -4814,75 +4814,64 @@ impl KubernetesComputeDriver {
48144814
.await?;
48154815
let selector = self.sandbox_lookup_selector(sandbox_id);
48164816
let lp = ListParams::default().labels(&selector);
4817-
let (kube_name, obj_namespace, _workspace, preconditions, pod_name, placement) =
4818-
match tokio::time::timeout(KUBE_API_TIMEOUT, lookup_api.api.list(&lp)).await {
4819-
Ok(Ok(list)) => {
4820-
if let Some(obj) = list.items.into_iter().next() {
4821-
match obj.metadata.name.clone() {
4822-
Some(name) => {
4823-
let ns = obj
4824-
.metadata
4825-
.namespace
4826-
.clone()
4827-
.unwrap_or_else(|| self.config.namespace.clone());
4828-
let ws = obj
4829-
.metadata
4830-
.labels
4831-
.as_ref()
4832-
.and_then(|l| l.get(LABEL_SANDBOX_WORKSPACE).cloned())
4833-
.unwrap_or_default();
4834-
// An unreadable placement leaves any instance to reconciliation.
4835-
let placement = supervisor_placement(&obj).ok();
4836-
let pc = Preconditions {
4837-
uid: obj.metadata.uid,
4838-
resource_version: obj.metadata.resource_version,
4839-
};
4840-
let pod_name = obj
4841-
.metadata
4842-
.annotations
4843-
.as_ref()
4844-
.and_then(|annotations| {
4845-
annotations.get(SANDBOX_POD_NAME_ANNOTATION)
4846-
})
4847-
.cloned()
4848-
.unwrap_or_else(|| name.clone());
4849-
(name, ns, ws, pc, pod_name, placement)
4850-
}
4851-
None => return Ok(false),
4852-
}
4853-
} else {
4854-
debug!(sandbox_id = %sandbox_id, "Sandbox not found in Kubernetes (already deleted)");
4855-
return Ok(false);
4856-
}
4857-
}
4858-
Ok(Err(err)) => {
4859-
warn!(
4860-
sandbox_id = %sandbox_id,
4861-
error = %err,
4862-
"Failed to list sandbox for deletion from Kubernetes"
4863-
);
4864-
return Err(err.to_string());
4865-
}
4866-
Err(_elapsed) => {
4867-
warn!(
4868-
sandbox_id = %sandbox_id,
4869-
timeout_secs = KUBE_API_TIMEOUT.as_secs(),
4870-
"Timed out listing sandbox for deletion from Kubernetes"
4871-
);
4872-
return Err(format!(
4873-
"timed out after {}s waiting for Kubernetes API",
4874-
KUBE_API_TIMEOUT.as_secs()
4875-
));
4876-
}
4877-
};
4817+
let list = match tokio::time::timeout(KUBE_API_TIMEOUT, lookup_api.api.list(&lp)).await {
4818+
Ok(Ok(list)) => list,
4819+
Ok(Err(err)) => {
4820+
warn!(
4821+
sandbox_id = %sandbox_id,
4822+
error = %err,
4823+
"Failed to list sandbox for deletion from Kubernetes"
4824+
);
4825+
return Err(err.to_string());
4826+
}
4827+
Err(_elapsed) => {
4828+
warn!(
4829+
sandbox_id = %sandbox_id,
4830+
timeout_secs = KUBE_API_TIMEOUT.as_secs(),
4831+
"Timed out listing sandbox for deletion from Kubernetes"
4832+
);
4833+
return Err(format!(
4834+
"timed out after {}s waiting for Kubernetes API",
4835+
KUBE_API_TIMEOUT.as_secs()
4836+
));
4837+
}
4838+
};
4839+
let Some(obj) = list.items.into_iter().next() else {
4840+
debug!(sandbox_id = %sandbox_id, "Sandbox not found in Kubernetes (already deleted)");
4841+
return Ok(false);
4842+
};
4843+
// An unreadable placement leaves any instance to reconciliation.
4844+
let placement = supervisor_placement(&obj).ok();
4845+
let kube_name = obj.metadata.name.ok_or("Sandbox CR has no name")?;
4846+
let obj_namespace = obj
4847+
.metadata
4848+
.namespace
4849+
.unwrap_or_else(|| self.config.namespace.clone());
4850+
let uid = obj
4851+
.metadata
4852+
.uid
4853+
.filter(|uid| !uid.is_empty())
4854+
.ok_or_else(|| format!("Sandbox CR {obj_namespace}/{kube_name} has no UID"))?;
4855+
let pod_name = obj
4856+
.metadata
4857+
.annotations
4858+
.as_ref()
4859+
.and_then(|annotations| annotations.get(SANDBOX_POD_NAME_ANNOTATION))
4860+
.cloned()
4861+
.unwrap_or_else(|| kube_name.clone());
48784862

48794863
let delete_api = self
48804864
.supported_agent_sandbox_api(self.client.clone(), &obj_namespace)
48814865
.await?;
4882-
let dp = DeleteParams::default().preconditions(preconditions);
4866+
// Delete this identity, not this revision. A controller status write
4867+
// must not block deletion, and a same-name replacement has another UID.
4868+
let dp = DeleteParams::default().preconditions(Preconditions {
4869+
uid: Some(uid),
4870+
resource_version: None,
4871+
});
48834872
match tokio::time::timeout(KUBE_API_TIMEOUT, delete_api.api.delete(&kube_name, &dp)).await {
48844873
Ok(Ok(_response)) => {
4885-
info!(sandbox_id = %sandbox_id, namespace = %obj_namespace, "Sandbox deleted from Kubernetes");
4874+
info!(sandbox_id = %sandbox_id, namespace = %obj_namespace, "Kubernetes accepted Sandbox CR deletion");
48864875
// The workload is going away, so its sandbox instance cannot
48874876
// stop it gracefully; end the instance without delaying the
48884877
// delete.
@@ -4923,11 +4912,14 @@ impl KubernetesComputeDriver {
49234912
}
49244913
Ok(true)
49254914
}
4926-
Ok(Err(KubeError::Api(err))) if err.code == 404 || err.code == 409 => {
4927-
debug!(sandbox_id = %sandbox_id, "Sandbox not found in Kubernetes (already deleted or replaced)");
4915+
Ok(Err(KubeError::Api(err))) if err.code == 404 => {
4916+
debug!(sandbox_id = %sandbox_id, "Sandbox not found in Kubernetes (already deleted)");
49284917
Ok(false)
49294918
}
49304919
Ok(Err(err)) => {
4920+
// In particular, a 409 is not proof of absence. Returning
4921+
// false would let the gateway release the name without a
4922+
// deletion event or an independent lookup.
49314923
warn!(
49324924
sandbox_id = %sandbox_id,
49334925
error = %err,

‎crates/openshell-driver-kubernetes/src/lifecycle_tests.rs‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,107 @@
11
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
22
// SPDX-License-Identifier: Apache-2.0
33

4+
mod sandbox_deletion {
5+
use super::*;
6+
use http_body_util::BodyExt as _;
7+
8+
async fn delete_after_concurrent_change(current_uid: &'static str) -> Result<bool, String> {
9+
use http::{Method, StatusCode};
10+
use serde_json::json;
11+
12+
const CR: &str = "/apis/agents.x-k8s.io/v1beta1/namespaces/openshell/sandboxes";
13+
const NAMED_CR: &str =
14+
"/apis/agents.x-k8s.io/v1beta1/namespaces/openshell/sandboxes/default--demo";
15+
const POD: &str = "/api/v1/namespaces/openshell/pods/default--demo";
16+
17+
let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0));
18+
let observed_attempts = attempts.clone();
19+
let service = tower::service_fn(move |request: http::Request<kube::client::Body>| {
20+
let attempts = attempts.clone();
21+
async move {
22+
let (code, body) = match (request.method(), request.uri().path()) {
23+
(&Method::GET, CR) => (
24+
StatusCode::OK,
25+
json!({
26+
"apiVersion": "agents.x-k8s.io/v1beta1",
27+
"kind": "SandboxList",
28+
"items": [{
29+
"apiVersion": "agents.x-k8s.io/v1beta1",
30+
"kind": "Sandbox",
31+
"metadata": {
32+
"name": "default--demo",
33+
"namespace": "openshell",
34+
"uid": "original",
35+
"resourceVersion": "41"
36+
}
37+
}]
38+
}),
39+
),
40+
(&Method::DELETE, NAMED_CR) => {
41+
attempts.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
42+
let bytes = request.into_body().collect().await.unwrap().to_bytes();
43+
let params: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
44+
let conditions = &params["preconditions"];
45+
assert_eq!(conditions["uid"], "original");
46+
// The controller wrote version 42 after the list. A
47+
// same-name replacement also has a different UID.
48+
if conditions["uid"] != current_uid
49+
|| (!conditions["resourceVersion"].is_null()
50+
&& conditions["resourceVersion"] != "42")
51+
{
52+
(
53+
StatusCode::CONFLICT,
54+
json!({
55+
"status": "Failure", "reason": "Conflict", "code": 409,
56+
"message": "deletion precondition failed"
57+
}),
58+
)
59+
} else {
60+
(
61+
StatusCode::OK,
62+
json!({
63+
"apiVersion": "v1", "kind": "Status", "status": "Success"
64+
}),
65+
)
66+
}
67+
}
68+
(&Method::GET, POD | NAMED_CR) if current_uid == "original" => (
69+
StatusCode::NOT_FOUND,
70+
json!({"status": "Failure", "reason": "NotFound", "code": 404}),
71+
),
72+
_ => panic!("unexpected Kubernetes request: {request:?}"),
73+
};
74+
Ok::<_, std::convert::Infallible>(kube_test_response(code, body))
75+
}
76+
});
77+
let (mut driver, _, _) = scripted_driver(KubernetesComputeConfig::default(), vec![]);
78+
driver.client = Client::new(service, "openshell");
79+
driver
80+
.sandbox_api_version
81+
.set(SANDBOX_VERSION_V1BETA1)
82+
.expect("set test Sandbox API version");
83+
let result = driver.delete_sandbox("sandbox-id").await;
84+
assert_eq!(
85+
observed_attempts.load(std::sync::atomic::Ordering::Relaxed),
86+
1
87+
);
88+
result
89+
}
90+
91+
#[tokio::test]
92+
async fn delete_sandbox_survives_a_controller_status_update() {
93+
assert!(delete_after_concurrent_change("original").await.unwrap());
94+
}
95+
96+
#[tokio::test]
97+
async fn delete_sandbox_conflict_does_not_delete_replacement_or_claim_absence() {
98+
let error = delete_after_concurrent_change("replacement")
99+
.await
100+
.unwrap_err();
101+
assert!(error.contains("deletion precondition failed"), "{error}");
102+
}
103+
}
104+
4105
mod lifecycle_reconciliation {
5106
use super::*;
6107

0 commit comments

Comments
 (0)