Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(spaces): remove the job Spaces a daemon restart leaves behind (#6244)

ddupontd0739a8c3fe2
diff --git a/libs/cua/crates/cua-spaces/src/host_jobs.rs b/libs/cua/crates/cua-spaces/src/host_jobs.rs
index 20b34e404b..6ddf11a100 100644
--- a/libs/cua/crates/cua-spaces/src/host_jobs.rs
+++ b/libs/cua/crates/cua-spaces/src/host_jobs.rs
@@ -62,6 +62,10 @@ const MACOS_MIN: (u32, u64) = (4, 8192);
/// Smallest macOS VM a member that asks for an accelerator gets.
const MACOS_GPU_MIN: (u32, u64) = (6, 16384);
+/// How often the Spaces of jobs that are gone are looked for (the first look
+/// is this long after the daemon starts).
+const ORPHAN_SWEEP_EVERY: Duration = Duration::from_secs(30);
+
/// How often a running job's Space is looked at for having stopped on its own.
const SPACE_WATCH_EVERY: Duration = Duration::from_secs(3);
@@ -184,6 +188,13 @@ impl SpacesExecutor {
tokio::time::sleep(Duration::from_secs(3600)).await;
}
});
+ let me = self.clone();
+ rt.spawn(async move {
+ loop {
+ tokio::time::sleep(ORPHAN_SWEEP_EVERY).await;
+ me.sweep_orphans().await;
+ }
+ });
if cfg!(target_os = "macos") {
let others = self.macos_others.clone();
rt.spawn(async move {
@@ -204,6 +215,44 @@ impl SpacesExecutor {
}
}
+ /// Removes the job Spaces nothing here runs in: the ones a restart of the
+ /// daemon left behind (the job runner ends the jobs the ledger says were
+ /// running and removes their Spaces once, at start, when the runtimes may
+ /// not answer yet) and any a failed delete left. A Space a job of this
+ /// process runs in is in `running` before it is created, so it is never
+ /// touched. Returns how many it removed.
+ pub async fn sweep_orphans(&self) -> usize {
+ let Ok(all) = self.spaces.list() else {
+ return 0;
+ };
+ let mut removed = 0;
+ for info in all {
+ if !is_job_space(&info.id) {
+ continue;
+ }
+ let name = info
+ .id
+ .strip_prefix("local:")
+ .unwrap_or(&info.id)
+ .to_string();
+ if self.running.lock().expect("running").contains(&name) {
+ continue;
+ }
+ self.remove_space(&name).await;
+ // Only what is gone counts: a Space a job created meanwhile (it
+ // is in `running` by now) stays, and one still there is retried.
+ if self
+ .spaces
+ .list()
+ .is_ok_and(|l| l.iter().all(|i| i.id != info.id))
+ {
+ tracing::info!(space = %name, "removed a job Space nothing runs in");
+ removed += 1;
+ }
+ }
+ removed
+ }
+
fn is_dedicated(&self) -> bool {
self.machine.is_some() && (self.dedicated)()
}
@@ -818,8 +867,11 @@ impl JobExecutor for SpacesExecutor {
return;
}
let id = format!("local:{space}");
- if self.spaces.delete(&id).await.is_err() {
- let _ = self.spaces.sandboxes().delete_local_instance(space).await;
+ if let Err(first) = self.spaces.delete(&id).await
+ && let Err(e) = self.spaces.sandboxes().delete_local_instance(space).await
+ {
+ // The orphan sweep ([`SpacesExecutor::sweep_orphans`]) tries again.
+ tracing::warn!(space, "removing a job's Space failed: {first}; {e}");
}
}
diff --git a/libs/cua/crates/cua-spaces/tests/host_jobs.rs b/libs/cua/crates/cua-spaces/tests/host_jobs.rs
index 2f76c884de..1afc431442 100644
--- a/libs/cua/crates/cua-spaces/tests/host_jobs.rs
+++ b/libs/cua/crates/cua-spaces/tests/host_jobs.rs
@@ -28,6 +28,8 @@ struct FakeRuntime {
port: u16,
started: Mutex<Vec<LocalStartSpec>>,
deleted: Mutex<Vec<String>>,
+ /// Deletes that fail before one works (a runtime that does not answer yet).
+ fail_deletes: Mutex<u32>,
running: Mutex<BTreeMap<String, bool>>,
/// Instances their engine says stopped on their own (a killed container).
exits: Mutex<BTreeMap<String, cua_sandbox_core::StopReason>>,
@@ -75,6 +77,16 @@ impl LocalRuntime for FakeRuntime {
}
}
async fn delete(&self, name: &str) -> Result<(), RuntimeError> {
+ {
+ let mut n = self.fail_deletes.lock().unwrap();
+ if *n > 0 {
+ *n -= 1;
+ return Err(RuntimeError::Unsupported {
+ backend: "fake".into(),
+ op: format!("delete {name}: runtime not ready"),
+ });
+ }
+ }
self.deleted.lock().unwrap().push(name.into());
self.running.lock().unwrap().remove(name);
Ok(())
@@ -100,6 +112,7 @@ struct Fixture {
home: std::path::PathBuf,
_env: MockServer,
rt: Arc<FakeRuntime>,
+ spaces: Spaces,
server: Arc<HostSpacesServer>,
}
@@ -121,6 +134,7 @@ async fn fixture() -> Fixture {
port: env.addr.port(),
started: Mutex::default(),
deleted: Mutex::default(),
+ fail_deletes: Mutex::default(),
running: Mutex::default(),
exits: Mutex::default(),
});
@@ -134,7 +148,8 @@ async fn fixture() -> Fixture {
)
.build();
Fixture {
- server: HostSpacesServer::new(spaces),
+ server: HostSpacesServer::new(spaces.clone()),
+ spaces,
_dir: dir,
home,
_env: env,
@@ -308,6 +323,59 @@ async fn a_job_whose_space_is_killed_ends_at_once_with_the_reason() {
assert!(f.rt.deleted.lock().unwrap().contains(&name));
}
+/// A daemon that restarts leaves the Space of the job it was running (CUA-2984:
+/// the job runner removes it once at start, when the runtime may not answer
+/// yet, and a durable agent's driver Space then stayed up for ever). The
+/// orphan sweep removes a job Space nothing in this process runs in, retries
+/// when the delete failed, and leaves every other Space alone.
+#[tokio::test]
+async fn a_job_space_nothing_runs_in_is_removed_by_the_sweep() {
+ use cua_spaces::host_jobs::SpacesExecutor;
+ let f = fixture().await;
+ seed_uv(&f.home);
+ let jobs = f.server.jobs_for(&HostCaller::local()).await.unwrap();
+ let mut long = spec("o1-1", &["sleep", "120000"]);
+ long.timeout_secs = 300;
+ let acks = jobs.run_batch(vec![long], "test").await;
+ assert_eq!(acks[0].outcome, "accepted", "{acks:?}");
+ let mut name = String::new();
+ for _ in 0..400 {
+ if let Some(s) = f.rt.started.lock().unwrap().first() {
+ name = s.name.clone();
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ assert!(!name.is_empty(), "the job's Space never started");
+ let id = format!("local:{name}");
+ let listed = |f: &Fixture| f.spaces.list().unwrap().iter().any(|i| i.id == id);
+ for _ in 0..200 {
+ if listed(&f) {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ assert!(listed(&f), "the job's Space is registered while it runs");
+ // The runner that runs it (this process) never sweeps its own: nothing
+ // to do for a sweep through the executor the server opened. A new
+ // executor stands for the daemon after a restart: it knows of no job.
+ let after_restart = SpacesExecutor::local(f.spaces.clone()).await;
+ // The first delete fails (the runtime does not answer yet): the Space is
+ // still there and counted as not removed.
+ *f.rt.fail_deletes.lock().unwrap() = 2;
+ assert_eq!(after_restart.sweep_orphans().await, 0);
+ assert!(
+ listed(&f),
+ "a failed delete leaves the Space for the next sweep"
+ );
+ // The next sweep removes it.
+ assert_eq!(after_restart.sweep_orphans().await, 1);
+ assert!(!listed(&f));
+ assert!(f.rt.deleted.lock().unwrap().contains(&name));
+ // Nothing left to do.
+ assert_eq!(after_restart.sweep_orphans().await, 0);
+}
+
/// What a scheduler reads: `GetHostSpaces` carries the node status.
#[tokio::test]
async fn the_host_reports_its_node_status() {