Skip to content

Commit 9f60f55

Browse files
authored
fix(server): retry transient sandbox CAS conflicts (ai-openshell#3501)
Signed-off-by: Drew Newberry <anewberry@nvidia.com>
1 parent 0c29d8e commit 9f60f55

2 files changed

Lines changed: 142 additions & 62 deletions

File tree

‎architecture/gateway.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -858,8 +858,9 @@ with it.
858858
fetches the current object, applies a mutation closure, and writes with a
859859
`MatchResourceVersion` condition. On conflict the persistence layer returns a
860860
`Conflict` error, which gRPC handlers map to `ABORTED` status so the client
861-
(or the next watch/reconcile event) can retry with fresh state. There is no
862-
automatic retry loop.
861+
(or the next watch/reconcile event) can retry with fresh state. Provider
862+
attach/detach handlers retry bounded server-driven conflicts around this helper;
863+
an explicit client version still fails on its first conflict.
863864

864865
The helper accepts an `expected_version` parameter that selects between two
865866
modes:

‎crates/openshell-server/src/grpc/sandbox.rs‎

Lines changed: 139 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ const TCP_FORWARD_CHUNK_SIZE: usize = 64 * 1024;
7878
const NO_LOGIN_SHELL_ENV: (&str, &str) = ("OPENSHELL_NO_LOGIN_SHELL", "1");
7979
const MAX_TEMPLATES_PER_WORKSPACE: u32 = 1000;
8080
const MAX_CREATE_SERVICE_EXPOSURES: usize = 32;
81+
const SANDBOX_CAS_RETRY_LIMIT: usize = 16;
8182

8283
#[cfg(test)]
8384
#[path = "interactive_exec_tests.rs"]
@@ -1381,38 +1382,37 @@ pub(super) async fn handle_attach_sandbox_provider(
13811382
let attached_clone = attached.clone();
13821383
let mutation_id = uuid::Uuid::new_v4().to_string();
13831384

1384-
let sandbox = state
1385-
.store
1386-
.update_message_cas::<Sandbox, _>(
1387-
&sandbox_id,
1388-
request.expected_resource_version,
1389-
|sandbox| {
1390-
attached_clone.store(false, Ordering::Relaxed);
1391-
let Some(ref mut spec) = sandbox.spec else {
1392-
// Spec should always exist post-creation; if missing, fail CAS to surface error
1393-
return;
1394-
};
1385+
let sandbox = update_sandbox_cas(
1386+
state,
1387+
&sandbox_id,
1388+
request.expected_resource_version,
1389+
|sandbox| {
1390+
attached_clone.store(false, Ordering::Relaxed);
1391+
let Some(ref mut spec) = sandbox.spec else {
1392+
// Spec should always exist post-creation; if missing, fail CAS to surface error
1393+
return;
1394+
};
13951395

1396-
if spec.provider_attachment_epoch.is_empty() {
1397-
spec.provider_attachment_epoch.clone_from(&mutation_id);
1398-
}
1396+
if spec.provider_attachment_epoch.is_empty() {
1397+
spec.provider_attachment_epoch.clone_from(&mutation_id);
1398+
}
13991399

1400-
dedupe_provider_names(&mut spec.providers);
1401-
if !spec.providers.iter().any(|name| name == &provider_name)
1402-
&& spec.providers.len() < MAX_PROVIDERS
1403-
{
1404-
spec.providers.push(provider_name.clone());
1405-
spec.provider_attachment_epoch.clone_from(&mutation_id);
1406-
attached_clone.store(true, Ordering::Relaxed);
1407-
crate::compute::provisioning_deadline::attachments_changed(
1408-
sandbox,
1409-
current_time_ms(),
1410-
);
1411-
}
1412-
},
1413-
)
1414-
.await
1415-
.map_err(|e| super::persistence_error_to_status(e, "attach sandbox provider"))?;
1400+
dedupe_provider_names(&mut spec.providers);
1401+
if !spec.providers.iter().any(|name| name == &provider_name)
1402+
&& spec.providers.len() < MAX_PROVIDERS
1403+
{
1404+
spec.providers.push(provider_name.clone());
1405+
spec.provider_attachment_epoch.clone_from(&mutation_id);
1406+
attached_clone.store(true, Ordering::Relaxed);
1407+
crate::compute::provisioning_deadline::attachments_changed(
1408+
sandbox,
1409+
current_time_ms(),
1410+
);
1411+
}
1412+
},
1413+
)
1414+
.await
1415+
.map_err(|e| super::persistence_error_to_status(e, "attach sandbox provider"))?;
14161416

14171417
let attached = attached.load(Ordering::Relaxed);
14181418
let receipt = super::provider_readiness::record_provider_mutation(
@@ -1505,38 +1505,37 @@ pub(super) async fn handle_detach_sandbox_provider(
15051505
let detached_clone = detached.clone();
15061506
let mutation_id = uuid::Uuid::new_v4().to_string();
15071507

1508-
let sandbox = state
1509-
.store
1510-
.update_message_cas::<Sandbox, _>(
1511-
&sandbox_id,
1512-
request.expected_resource_version,
1513-
|sandbox| {
1514-
detached_clone.store(false, Ordering::Relaxed);
1515-
let Some(ref mut spec) = sandbox.spec else {
1516-
// Spec should always exist post-creation; if missing, fail CAS to surface error
1517-
return;
1518-
};
1508+
let sandbox = update_sandbox_cas(
1509+
state,
1510+
&sandbox_id,
1511+
request.expected_resource_version,
1512+
|sandbox| {
1513+
detached_clone.store(false, Ordering::Relaxed);
1514+
let Some(ref mut spec) = sandbox.spec else {
1515+
// Spec should always exist post-creation; if missing, fail CAS to surface error
1516+
return;
1517+
};
15191518

1520-
if spec.provider_attachment_epoch.is_empty() {
1521-
spec.provider_attachment_epoch.clone_from(&mutation_id);
1522-
}
1519+
if spec.provider_attachment_epoch.is_empty() {
1520+
spec.provider_attachment_epoch.clone_from(&mutation_id);
1521+
}
15231522

1524-
let before_len = spec.providers.len();
1525-
spec.providers.retain(|name| name != &provider_name);
1526-
if spec.providers.len() != before_len {
1527-
spec.provider_attachment_epoch.clone_from(&mutation_id);
1528-
detached_clone.store(true, Ordering::Relaxed);
1529-
// Only dedupe after making a change
1530-
dedupe_provider_names(&mut spec.providers);
1531-
crate::compute::provisioning_deadline::attachments_changed(
1532-
sandbox,
1533-
current_time_ms(),
1534-
);
1535-
}
1536-
},
1537-
)
1538-
.await
1539-
.map_err(|e| super::persistence_error_to_status(e, "detach sandbox provider"))?;
1523+
let before_len = spec.providers.len();
1524+
spec.providers.retain(|name| name != &provider_name);
1525+
if spec.providers.len() != before_len {
1526+
spec.provider_attachment_epoch.clone_from(&mutation_id);
1527+
detached_clone.store(true, Ordering::Relaxed);
1528+
// Only dedupe after making a change
1529+
dedupe_provider_names(&mut spec.providers);
1530+
crate::compute::provisioning_deadline::attachments_changed(
1531+
sandbox,
1532+
current_time_ms(),
1533+
);
1534+
}
1535+
},
1536+
)
1537+
.await
1538+
.map_err(|e| super::persistence_error_to_status(e, "detach sandbox provider"))?;
15401539

15411540
let detached = detached.load(Ordering::Relaxed);
15421541
let receipt = super::provider_readiness::record_provider_mutation(
@@ -1764,6 +1763,33 @@ async fn providers_for_sandbox(
17641763
Ok(providers)
17651764
}
17661765

1766+
/// Retry a pure server-owned mutation on a fresh resource version. Explicit
1767+
/// client versions still fail on conflict so clients retain their CAS contract.
1768+
async fn update_sandbox_cas<F>(
1769+
state: &ServerState,
1770+
sandbox_id: &str,
1771+
expected_resource_version: u64,
1772+
mut mutate: F,
1773+
) -> crate::persistence::PersistenceResult<Sandbox>
1774+
where
1775+
F: FnMut(&mut Sandbox),
1776+
{
1777+
for attempt in 1..=SANDBOX_CAS_RETRY_LIMIT {
1778+
match state
1779+
.store
1780+
.update_message_cas::<Sandbox, _>(sandbox_id, expected_resource_version, &mut mutate)
1781+
.await
1782+
{
1783+
Ok(sandbox) => return Ok(sandbox),
1784+
Err(crate::persistence::PersistenceError::Conflict { .. })
1785+
if expected_resource_version == 0 && attempt < SANDBOX_CAS_RETRY_LIMIT => {}
1786+
Err(error) => return Err(error),
1787+
}
1788+
}
1789+
1790+
unreachable!("sandbox CAS retry loop always returns on its final attempt")
1791+
}
1792+
17671793
fn dedupe_provider_names(provider_names: &mut Vec<String>) {
17681794
let mut index = 0;
17691795
while index < provider_names.len() {
@@ -8422,6 +8448,59 @@ mod tests {
84228448

84238449
// ---- CAS (Client-driven optimistic concurrency) tests ----
84248450

8451+
#[tokio::test(flavor = "multi_thread", worker_threads = 6)]
8452+
async fn server_managed_sandbox_cas_retries_concurrent_updates() {
8453+
use std::sync::Barrier;
8454+
8455+
const WRITERS: usize = 5;
8456+
8457+
let state = Arc::new(test_server_state().await);
8458+
let sandbox = test_sandbox("server-cas-retry", Vec::new());
8459+
let sandbox_id = sandbox.object_id().to_string();
8460+
state.store.put_message(&sandbox).await.unwrap();
8461+
8462+
let barrier = Arc::new(Barrier::new(WRITERS));
8463+
let mut handles = Vec::with_capacity(WRITERS);
8464+
for _ in 0..WRITERS {
8465+
let state = Arc::clone(&state);
8466+
let barrier = Arc::clone(&barrier);
8467+
let sandbox_id = sandbox_id.clone();
8468+
handles.push(tokio::spawn(async move {
8469+
let mut first_attempt = true;
8470+
update_sandbox_cas(&state, &sandbox_id, 0, |sandbox| {
8471+
if first_attempt {
8472+
first_attempt = false;
8473+
barrier.wait();
8474+
}
8475+
let annotations = &mut sandbox.metadata.as_mut().unwrap().annotations;
8476+
let count = annotations
8477+
.get("internal-update-count")
8478+
.and_then(|value| value.parse::<usize>().ok())
8479+
.unwrap_or_default();
8480+
annotations
8481+
.insert("internal-update-count".to_string(), (count + 1).to_string());
8482+
})
8483+
.await
8484+
}));
8485+
}
8486+
8487+
for result in future::join_all(handles).await {
8488+
result.unwrap().unwrap();
8489+
}
8490+
8491+
let updated = state
8492+
.store
8493+
.get_message::<Sandbox>(&sandbox_id)
8494+
.await
8495+
.unwrap()
8496+
.unwrap();
8497+
assert_eq!(
8498+
updated.metadata.as_ref().unwrap().annotations["internal-update-count"],
8499+
WRITERS.to_string()
8500+
);
8501+
assert_eq!(updated.get_resource_version(), WRITERS as u64 + 1);
8502+
}
8503+
84258504
#[tokio::test]
84268505
async fn attach_sandbox_provider_client_driven_cas_succeeds_with_correct_version() {
84278506
let state = test_server_state().await;

0 commit comments

Comments
 (0)