@@ -5595,6 +5595,7 @@ impl ComputeRuntime {
55955595 }
55965596 }
55975597 Some(watch_sandboxes_event::Payload::Deleted(deleted)) => {
5598+ info!(sandbox_id = %deleted.sandbox_id, "Compute driver reported sandbox deleted");
55985599 self.apply_deleted(&deleted.sandbox_id).await?;
55995600 }
56005601 Some(watch_sandboxes_event::Payload::PlatformEvent(platform_event)) => {
@@ -6314,24 +6315,43 @@ impl ComputeRuntime {
63146315 }
63156316
63166317 async fn apply_deleted_locked(&self, sandbox_id: &str) -> Result<(), String> {
6317- let sandbox = self
6318- .store
6319- .get_message::<Sandbox>(sandbox_id)
6320- .await
6321- .map_err(|e| e.to_string())?;
6322- if let Some(sandbox) = sandbox.as_ref() {
6318+ // This event is the only signal that removes the record after a
6319+ // driver-confirmed delete; the orphan sweep waits out its grace
6320+ // period. Other replicas keep writing the record until it is gone,
6321+ // e.g. the endpoint-status reset when the supervisor session ends, so
6322+ // retry the removal against a fresh snapshot after such a write.
6323+ for attempt in 1..=DELETE_PHASE_CAS_RETRY_LIMIT {
6324+ let Some(sandbox) = self
6325+ .store
6326+ .get_message::<Sandbox>(sandbox_id)
6327+ .await
6328+ .map_err(|e| e.to_string())?
6329+ else {
6330+ let _ = self
6331+ .store
6332+ .delete(Sandbox::object_type(), sandbox_id)
6333+ .await
6334+ .map_err(|e| e.to_string())?;
6335+ self.cleanup_removed_sandbox_state(sandbox_id);
6336+ return Ok(());
6337+ };
63236338 // Timeout cleanup can emit Deleted before an explicit stop exposes
63246339 // Stopped for repair. A delayed (or repeated) event must retain that
63256340 // recovery record too; explicit deletion still transitions to Deleting.
63266341 if self
6327- .pending_driver_operation_blocks_cleanup(sandbox)
6342+ .pending_driver_operation_blocks_cleanup(& sandbox)
63286343 .await?
6329- || (provisioning_deadline::timed_out(sandbox)
6344+ || (provisioning_deadline::timed_out(& sandbox)
63306345 && matches!(
63316346 SandboxPhase::try_from(sandbox.phase()),
63326347 Ok(SandboxPhase::Error | SandboxPhase::Stopped)
63336348 ))
63346349 {
6350+ info!(
6351+ sandbox_id,
6352+ phase = ?SandboxPhase::try_from(sandbox.phase()).unwrap_or(SandboxPhase::Unknown),
6353+ "Retaining sandbox record after driver deletion for pending recovery"
6354+ );
63356355 return Ok(());
63366356 }
63376357 // The watcher told us this sandbox's compute resource is gone, so
@@ -6343,21 +6363,27 @@ impl ComputeRuntime {
63436363 if self
63446364 .remove_sandbox_record_if_version_locked(
63456365 sandbox_id,
6346- sandbox_resource_version(sandbox),
6366+ sandbox_resource_version(& sandbox),
63476367 )
63486368 .await?
63496369 {
63506370 self.spawn_driver_sandbox_cleanup(sandbox.object_id(), sandbox.object_name());
6371+ return Ok(());
6372+ }
6373+ if attempt < DELETE_PHASE_CAS_RETRY_LIMIT {
6374+ info!(
6375+ sandbox_id,
6376+ attempt,
6377+ expected_resource_version = sandbox_resource_version(&sandbox),
6378+ "Sandbox removal after driver deletion did not complete; retrying"
6379+ );
6380+ tokio::task::yield_now().await;
63516381 }
6352- return Ok(());
63536382 }
6354-
6355- let _ = self
6356- .store
6357- .delete(Sandbox::object_type(), sandbox_id)
6358- .await
6359- .map_err(|e| e.to_string())?;
6360- self.cleanup_removed_sandbox_state(sandbox_id);
6383+ warn!(
6384+ sandbox_id,
6385+ "Sandbox removal after driver deletion did not complete; leaving it to reconciliation"
6386+ );
63616387 Ok(())
63626388 }
63636389
@@ -6808,6 +6834,7 @@ impl ComputeRuntime {
68086834 sandbox_id = %sandbox_id,
68096835 sandbox_name = %sandbox_name,
68106836 age_secs = age_ms / 1000,
6837+ phase = ?phase,
68116838 "Removing sandbox from store after it disappeared from the compute driver snapshot"
68126839 );
68136840 // The driver's own snapshot never reported this sandbox, so no
@@ -17274,6 +17301,70 @@ mod tests {
1727417301 }));
1727517302 }
1727617303
17304+ /// Another replica can write a deleting sandbox while the watch deletion
17305+ /// removes it, e.g. when the supervisor session ends. The removal must
17306+ /// retry, not wait for the orphan grace period.
17307+ #[tokio::test]
17308+ async fn watch_deletion_retries_after_concurrent_replica_write() {
17309+ let directory = tempfile::tempdir().expect("temporary database directory");
17310+ let database_url = format!("sqlite://{}", directory.path().join("gateway.db").display());
17311+ let store = Arc::new(Store::connect(&database_url).await.expect("connect store"));
17312+ let pool = sqlx::SqlitePool::connect(&database_url)
17313+ .await
17314+ .expect("connect conflict injector");
17315+ sqlx::query("CREATE TABLE injected_conflicts (id TEXT PRIMARY KEY)")
17316+ .execute(&pool)
17317+ .await
17318+ .expect("create conflict marker table");
17319+ // Another replica writes the sandbox between the removal's version
17320+ // check and its delete, once.
17321+ sqlx::query(
17322+ "CREATE TRIGGER inject_replica_write \
17323+ AFTER DELETE ON objects \
17324+ WHEN OLD.object_type = 'sandbox_settings' \
17325+ AND NOT EXISTS (SELECT 1 FROM injected_conflicts) \
17326+ BEGIN \
17327+ INSERT INTO injected_conflicts (id) VALUES (OLD.id); \
17328+ UPDATE objects SET resource_version = resource_version + 1 \
17329+ WHERE object_type = 'sandbox' AND id = 'sb-race'; \
17330+ END",
17331+ )
17332+ .execute(&pool)
17333+ .await
17334+ .expect("install conflict trigger");
17335+
17336+ let driver = ControlledDriver::new();
17337+ let mut runtime = test_runtime(driver.clone()).await;
17338+ runtime.store = store;
17339+ let sandbox = sandbox_record("sb-race", "race", SandboxPhase::Deleting);
17340+ runtime.store.put_message(&sandbox).await.unwrap();
17341+ seed_sandbox_owned_records(&runtime, &sandbox).await;
17342+
17343+ runtime.apply_deleted("sb-race").await.unwrap();
17344+
17345+ let injected = sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM injected_conflicts")
17346+ .fetch_one(&pool)
17347+ .await
17348+ .unwrap();
17349+ assert_eq!(injected, 1, "the removal must hit the injected write");
17350+ pool.close().await;
17351+ assert!(
17352+ runtime
17353+ .store
17354+ .get_message::<Sandbox>("sb-race")
17355+ .await
17356+ .unwrap()
17357+ .is_none()
17358+ );
17359+ tokio::time::timeout(Duration::from_secs(1), async {
17360+ while driver.delete_calls() == 0 {
17361+ tokio::task::yield_now().await;
17362+ }
17363+ })
17364+ .await
17365+ .expect("the successful retry must reclaim driver-owned resources");
17366+ }
17367+
1727717368 /// Driver watch events arrive on a background stream, so the store writes
1727817369 /// they trigger land outside the request that caused them.
1727917370 #[tokio::test]
0 commit comments