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: preserve borrowed sandboxes and remove speculative cleanup

Dillon Duponta597517d8077
diff --git a/libs/cua/crates/cua-daemon/src/maintenance.rs b/libs/cua/crates/cua-daemon/src/maintenance.rs
index 0ea4e656ec..fd65fc3f52 100644
--- a/libs/cua/crates/cua-daemon/src/maintenance.rs
+++ b/libs/cua/crates/cua-daemon/src/maintenance.rs
@@ -6,21 +6,15 @@
//! `sandboxes/.ephemeral/` names a process that no longer exists; after
//! `CUA_ORPHAN_REAP_MINUTES` (default 10) the daemon, `cua cache prune` or
//! the next `cua` run deletes the instance (container, VM disk, Lume clone)
-//! and the lease. Ephemeral instances with no lease at all (an SDK older
-//! than leases) are reaped after 24 hours, abandoned build VMs and build
-//! containers after 6 hours. Named sandboxes are never reaped.
+//! and the lease. Unleased ephemeral and build instances require explicit
+//! cleanup; their name, kind and age do not authorize deletion.
use std::time::{Duration, SystemTime, UNIX_EPOCH};
-use cua_disk::{CacheConfig, Category, GcOptions, GcReport, Layout, Scanner};
+use cua_disk::{CacheConfig, GcOptions, GcReport, Layout, Scanner};
use cua_sandbox_core::{LocalRuntime, RuntimeError, StateStore};
use serde::Serialize;
-/// Ephemeral instances without a lease are reaped after this long.
-pub const UNLEASED_REAP_AFTER: Duration = Duration::from_secs(24 * 3600);
-/// Build VMs and build containers left by a crashed build are removed after
-/// this long.
-pub const BUILD_LEFTOVER_AFTER: Duration = Duration::from_secs(6 * 3600);
/// `CUA_DAEMON_MAINTENANCE=0` turns the daemon's periodic maintenance off.
pub const ENV_DAEMON_MAINTENANCE: &str = "CUA_DAEMON_MAINTENANCE";
@@ -98,51 +92,17 @@ pub async fn reap_leases(
out
}
-/// [`reap_leases`] plus instances the scan found: ephemeral ones without a
-/// lease (after 24 h) and abandoned build VMs and containers (after 6 h).
+/// Compatibility entry point for lease reaping; inventory does not authorize deletion.
pub async fn reap_orphans(
local: &dyn LocalRuntime,
state: &StateStore,
- items: &[cua_disk::Item],
+ _items: &[cua_disk::Item],
reap_after: Duration,
now: SystemTime,
dry_run: bool,
alive: &(dyn Fn(u32) -> bool + Sync),
) -> Vec<Reaped> {
- let leases: Vec<String> = state.leases().into_iter().map(|l| l.name).collect();
- let mut out = reap_leases(local, state, reap_after, now, dry_run, alive).await;
- let age = |i: &cua_disk::Item| i.created.map(|c| secs(now).saturating_sub(c));
- for i in items {
- let running = i.status.as_deref() == Some("running");
- let reason = if i.category == Category::Sandboxes
- && i.ephemeral
- && !leases.contains(&i.name)
- && age(i).is_some_and(|a| a >= UNLEASED_REAP_AFTER.as_secs())
- {
- "ephemeral sandbox without an owner for over 24 hours"
- } else if matches!(i.kind.as_str(), "build-vm" | "container-build")
- && age(i).is_some_and(|a| a >= BUILD_LEFTOVER_AFTER.as_secs())
- && !(running && i.kind == "build-vm")
- {
- "build instance left by an interrupted build"
- } else {
- continue;
- };
- if out.iter().any(|r| r.name == i.name) {
- continue;
- }
- let error = if dry_run {
- None
- } else {
- delete(local, &i.name).await
- };
- out.push(Reaped {
- name: i.name.clone(),
- reason: reason.into(),
- error,
- });
- }
- out
+ reap_leases(local, state, reap_after, now, dry_run, alive).await
}
/// One full pass: reap orphans, collect the cache (budget and orphans; the
@@ -155,13 +115,10 @@ pub async fn run(
dry_run: bool,
) -> MaintenanceReport {
let config = CacheConfig::load();
- let scanner = Scanner::system(layout.clone()).await;
let now = SystemTime::now();
- let report = scanner.scan_at(now).await;
- let reaped = reap_orphans(
+ let reaped = reap_leases(
local,
state,
- &report.items,
config.orphan_reap_after,
now,
dry_run,
@@ -170,6 +127,7 @@ pub async fn run(
.await;
let gc = match gc {
Some(mut o) => {
+ let scanner = Scanner::system(layout.clone()).await;
o.dry_run = dry_run;
Some(cua_disk::collect(&scanner, o).await)
}
@@ -206,6 +164,7 @@ pub fn spawn_auto_gc(reason: &'static str) {
mod tests {
use super::*;
use async_trait::async_trait;
+ use cua_disk::Category;
use cua_sandbox_core::{
InstanceStatus, LocalEndpoints, LocalInstance, LocalStartSpec, LocalSummary, RuntimeResult,
};
@@ -301,7 +260,7 @@ mod tests {
}
#[tokio::test]
- async fn unleased_ephemerals_and_build_leftovers_age_out_named_never() {
+ async fn unleased_inventory_is_not_authority_to_reap() {
let d = tempfile::tempdir().unwrap();
let state = StateStore::new(d.path());
let now = UNIX_EPOCH + Duration::from_secs(NOW);
@@ -318,13 +277,16 @@ mod tests {
status: Some("running".into()),
..Default::default()
};
- let items = vec![
+ let mut items = vec![
item("cua-eph-ancient", "container-sandbox", true, 2 * 86_400),
item("cua-eph-recent", "qemu", true, 3600),
item("my-named-box", "qemu", false, 90 * 86_400),
item("cua-build-ctr-9", "container-build", false, 7 * 3600),
item("cua-build-1f", "build-vm", false, 7 * 3600),
];
+ let mut stopped = item("cua-build-stopped", "build-vm", false, 7 * 3600);
+ stopped.status = Some("stopped".into());
+ items.push(stopped);
let fake = Fake::default();
let r = reap_orphans(
&fake,
@@ -336,15 +298,35 @@ mod tests {
&|_| false,
)
.await;
- let names: Vec<&str> = r.iter().map(|x| x.name.as_str()).collect();
- // A running build VM is still building; the container is reaped.
- assert_eq!(names, vec!["cua-eph-ancient", "cua-build-ctr-9"]);
- assert!(
- !fake
- .deleted
- .lock()
- .unwrap()
- .contains(&"my-named-box".to_string())
- );
+ assert!(r.is_empty(), "{r:?}");
+ assert!(fake.deleted.lock().unwrap().is_empty());
+ lease(&state, "cua-eph-ancient", 111, NOW - 3600);
+ lease(&state, "my-named-box", 222, NOW - 3600);
+ let r = reap_orphans(
+ &fake,
+ &state,
+ &items,
+ Duration::from_secs(600),
+ now,
+ true,
+ &|p| p == 222,
+ )
+ .await;
+ assert_eq!(r.len(), 1);
+ assert!(fake.deleted.lock().unwrap().is_empty());
+ assert_eq!(state.leases().len(), 2);
+ let r = reap_orphans(
+ &fake,
+ &state,
+ &items,
+ Duration::from_secs(600),
+ now,
+ false,
+ &|p| p == 222,
+ )
+ .await;
+ assert_eq!(r.len(), 1);
+ assert_eq!(fake.deleted.lock().unwrap().as_slice(), ["cua-eph-ancient"]);
+ assert_eq!(state.leases().len(), 1);
}
}
diff --git a/libs/cua/crates/cua-sandbox-core/src/sandbox.rs b/libs/cua/crates/cua-sandbox-core/src/sandbox.rs
index 37d13c9268..b0577a51f5 100644
--- a/libs/cua/crates/cua-sandbox-core/src/sandbox.rs
+++ b/libs/cua/crates/cua-sandbox-core/src/sandbox.rs
@@ -1036,6 +1036,12 @@ impl Sandboxes {
}
let options = self.resolve_fleet_template(options).await?;
let options = self.build_image(options).await?;
+ let preexisting = match (&options.provider, options.name.as_deref()) {
+ (ProviderKind::Local, Some(name)) if !name.is_empty() => {
+ self.local_name_in_use(name).await
+ }
+ _ => false,
+ };
let sandbox = match options.provider {
ProviderKind::Fleet => self.create_fleet(&options).await?,
ProviderKind::Local => self.create_local(&options).await?,
@@ -1064,7 +1070,9 @@ impl Sandboxes {
if let Err(e) = ready {
// A failed create releases what it made (a named sandbox's claim
// too), unless the caller keeps it to debug.
- if sandbox.ephemeral || !options.keep_on_failure {
+ if preexisting {
+ tracing::warn!(sandbox = %sandbox.id(), "readiness failed; pre-existing sandbox retained");
+ } else if sandbox.ephemeral || !options.keep_on_failure {
let id = sandbox.id();
if let Err(d) = sandbox.clone().delete().await {
tracing::warn!(sandbox = %id, error = %d, "could not delete a sandbox that failed readiness");
diff --git a/libs/cua/crates/cua-sandbox-core/tests/providers.rs b/libs/cua/crates/cua-sandbox-core/tests/providers.rs
index 1c775ca15b..b7ee2ae364 100644
--- a/libs/cua/crates/cua-sandbox-core/tests/providers.rs
+++ b/libs/cua/crates/cua-sandbox-core/tests/providers.rs
@@ -1809,3 +1809,32 @@ async fn a_cancelled_local_create_deletes_only_what_it_made() {
assert!(matches!(r, Err(Error::Cancelled(m)) if m.contains("existed before")));
assert!(rt.instances.lock().unwrap().contains_key("theirs"));
}
+
+/// Readiness failure preserves an observed existing VM, while a newly created
+/// VM still receives baseline cleanup. Both state and backend effects are local.
+#[tokio::test]
+async fn local_readiness_cleanup_distinguishes_existing_from_new() {
+ for existing in [true, false] {
+ let state = tempfile::tempdir().unwrap();
+ let rt = Arc::new(FakeRuntime::default());
+ let name = "cua-e2e-readiness";
+ if existing {
+ rt.instances
+ .lock()
+ .unwrap()
+ .insert(name.into(), InstanceStatus::Running);
+ }
+ let sbx = Sandboxes::builder()
+ .local(rt.clone())
+ .state_dir(state.path())
+ .build();
+ let mut opts = CreateOptions::new(ProviderKind::Local, IMAGE)
+ .name(name)
+ .wait_for(Probe::Tcp(45678));
+ opts.ready_timeout = Duration::from_millis(20);
+ let err = sbx.create(opts).await.unwrap_err();
+ assert!(matches!(err, Error::Timeout(_)), "{err:?}");
+ assert_eq!(rt.instances.lock().unwrap().contains_key(name), existing);
+ assert_eq!(sbx.state().load(name).is_some(), existing);
+ }
+}
diff --git a/libs/cua/crates/cua-spaces/src/creating.rs b/libs/cua/crates/cua-spaces/src/creating.rs
index 737a8f5423..72b2ae9513 100644
--- a/libs/cua/crates/cua-spaces/src/creating.rs
+++ b/libs/cua/crates/cua-spaces/src/creating.rs
@@ -607,7 +607,11 @@ impl Spaces {
},
}
}
- if !j.id.is_empty() {
+ let borrowed = j
+ .made
+ .iter()
+ .any(|m| matches!(m, Made::LocalSandbox { fresh: false, .. }));
+ if !j.id.is_empty() && !borrowed {
let _ = self.inner.registry.remove(&j.id);
}
let mut msg = format!("Cancelled {}", display(&j.id, &j.name));
diff --git a/libs/cua/crates/cua-spaces/src/spaces.rs b/libs/cua/crates/cua-spaces/src/spaces.rs
index 2a5ad088e7..e41e531511 100644
--- a/libs/cua/crates/cua-spaces/src/spaces.rs
+++ b/libs/cua/crates/cua-spaces/src/spaces.rs
@@ -2137,7 +2137,7 @@ impl Spaces {
// Until the Space is registered, the create's journal holds its
// token and what it made: a process that dies mid-create (a daemon
// crash, a quit) leaves it, and [`Spaces::recover_interrupted_creates`]
- // then registers the sandbox or deletes it, never a hidden one; a
+ // then recovers it or retains it for manual cleanup; an explicit
// cancel removes what it made. Only a name nothing used before is
// this create's to delete.
let fresh = !self.inner.sandboxes.local_name_in_use(&name).await;
@@ -2214,7 +2214,7 @@ impl Spaces {
{
Ok(s) => s,
Err(e) => {
- if let Ok(sb) = self.inner.sandboxes.connect(&name).await {
+ if fresh && let Ok(sb) = self.inner.sandboxes.connect(&name).await {
let _ = sb.delete().await;
}
return Err(e);
@@ -2231,17 +2231,11 @@ impl Spaces {
self.info(&id)
}
- /// Local creates a process that died left half done (its daemon
- /// crashed or was killed between starting the sandbox and registering
- /// the Space): each such sandbox is registered when its cua-spacesd
- /// answers within `budget`, else deleted, so nothing keeps running
- /// that no Space lists. Creates of live processes are left alone. The
- /// daemon runs this when it starts.
- ///
- /// A create someone cancelled (its `.cancel` marker), a cloud or host
- /// create, and one under a name that was in use before are not
- /// registered: what they made is removed ([`Spaces::cancel_create`]'s
- /// undo), and a sandbox that existed before is left as it was.
+ /// Recovers local creates left by a dead process when their cua-spacesd
+ /// authenticates within `budget`. Failed, cancelled or borrowed local
+ /// attempts retain their resources and journals for explicit cleanup.
+ /// Live processes are left alone; nonlocal creates retain cancellation
+ /// cleanup. The daemon runs this at startup.
pub async fn recover_interrupted_creates(&self, budget: Duration) -> Vec<RecoveredCreate> {
use crate::creating::Made;
let mut out = Vec::new();
@@ -2254,7 +2248,7 @@ impl Spaces {
Made::LocalSandbox { fresh, .. } => Some(*fresh),
_ => None,
});
- if crate::creating::cancel_marked(&home, &stem) || j.kind != "local" {
+ if j.kind != "local" {
let message = self.undo(&j).await;
tracing::info!(create = %stem, message, "interrupted create undone");
crate::creating::remove(&home, &stem);
@@ -2271,12 +2265,15 @@ impl Spaces {
let id = SpaceId::Local {
name: j.name.clone(),
};
- // Nothing made yet (cut off while resolving the image), or a
- // name that was someone else's: nothing of this create's to
- // delete.
- let untouchable =
- (j.token.is_empty() && j.made.is_empty()) || local_made == Some(false);
- let outcome = if self
+ let outcome = if crate::creating::cancel_marked(&home, &stem)
+ || local_made == Some(false)
+ || j.token.trim().is_empty()
+ || !j.spacesd
+ {
+ RecoveryOutcome::Failed(
+ "local attempt retained; inspect and clean up manually".into(),
+ )
+ } else if self
.inner
.registry
.get(&id.to_string())
@@ -2285,18 +2282,6 @@ impl Spaces {
.is_some()
{
RecoveryOutcome::AlreadyRegistered
- } else if untouchable && self.inner.sandboxes.connect(&j.name).await.is_err() {
- RecoveryOutcome::NothingLeft
- } else if self.inner.sandboxes.connect(&j.name).await.is_err() {
- // Cut off before the sandbox was recorded: an instance the
- // runtime started is deleted, never left running unlisted.
- match self.inner.sandboxes.delete_local_instance(&j.name).await {
- Ok(true) => RecoveryOutcome::Deleted(
- "the create was cut off before the sandbox was recorded".into(),
- ),
- Ok(false) => RecoveryOutcome::NothingLeft,
- Err(e) => RecoveryOutcome::Failed(format!("delete: {e}")),
- }
} else {
let credential = Credential {
token: Some(j.token.clone()),
@@ -2317,15 +2302,19 @@ impl Spaces {
self.notify_connected(&id);
RecoveryOutcome::Registered
}
- Err(e) if untouchable => RecoveryOutcome::Failed(e.to_string()),
- Err(e) => self.discard_interrupted(&j.name, e.to_string()).await,
+ Err(e) => RecoveryOutcome::Failed(format!(
+ "{e}; local attempt retained for manual cleanup"
+ )),
},
- Err(e) if untouchable => RecoveryOutcome::Failed(e.to_string()),
- Err(e) => self.discard_interrupted(&j.name, e.to_string()).await,
+ Err(e) => RecoveryOutcome::Failed(format!(
+ "{e}; local attempt retained for manual cleanup"
+ )),
}
};
tracing::info!(space = %id, ?outcome, "interrupted create");
- crate::creating::remove(&home, &stem);
+ if !matches!(outcome, RecoveryOutcome::Failed(_)) {
+ crate::creating::remove(&home, &stem);
+ }
out.push(RecoveredCreate {
id: id.to_string(),
outcome,
@@ -2334,23 +2323,6 @@ impl Spaces {
out
}
- async fn discard_interrupted(&self, name: &str, why: String) -> RecoveryOutcome {
- let deleted = match self.inner.sandboxes.connect(name).await {
- Ok(sb) => sb.delete().await.map(|_| ()).map_err(Error::from),
- Err(_) => self
- .inner
- .sandboxes
- .delete_local_instance(name)
- .await
- .map(|_| ())
- .map_err(Error::from),
- };
- match deleted {
- Ok(()) => RecoveryOutcome::Deleted(why),
- Err(e) => RecoveryOutcome::Failed(format!("{why}; delete: {e}")),
- }
- }
-
/// Deletes a Space's sandbox and forgets it: a cloud Space's sandbox is
/// deleted (metering stops), a local one's instance is deleted. A Space
/// added by address (`direct:`, `relay:`) is only forgotten: cua did not
@@ -2794,7 +2766,7 @@ pub enum RecoveryOutcome {
Registered,
/// It never became a Space (why): its sandbox was deleted.
Deleted(String),
- /// Its sandbox could not be deleted (why).
+ /// Recovery failed (why); a local attempt and its journal are retained.
Failed(String),
/// It had been registered after all.
AlreadyRegistered,
diff --git a/libs/cua/crates/cua-spaces/tests/cancel.rs b/libs/cua/crates/cua-spaces/tests/cancel.rs
index 2b840ff3a2..78dfdab8dd 100644
--- a/libs/cua/crates/cua-spaces/tests/cancel.rs
+++ b/libs/cua/crates/cua-spaces/tests/cancel.rs
@@ -211,6 +211,16 @@ async fn a_cancelled_local_create_removes_what_it_made_once() {
async fn a_cancel_never_removes_what_existed_and_a_drop_cleans_up() {
let e = env();
e.rt.running.lock().unwrap().insert("theirs".into(), true);
+ e.spaces
+ .registry()
+ .upsert(
+ cua_proto::daemon::v1::Space {
+ id: "local:theirs".into(),
+ ..Default::default()
+ },
+ Default::default(),
+ )
+ .unwrap();
let spaces = e.spaces.clone();
let create = tokio::spawn(async move { spaces.create(local(Some("theirs"), "p2")).await });
until("the create runs", || e.rt.specs.lock().unwrap().len() == 1).await;
@@ -219,6 +229,8 @@ async fn a_cancel_never_removes_what_existed_and_a_drop_cleans_up() {
assert!(o.message.contains("existed before"), "{}", o.message);
assert!(create.await.unwrap().is_err());
assert!(e.rt.running.lock().unwrap().contains_key("theirs"));
+ assert!(e.spaces.registry().get("local:theirs").unwrap().is_some());
+
assert!(e.rt.deleted.lock().unwrap().is_empty());
// Dropped: the future goes away without a cancel.
@@ -268,7 +280,7 @@ async fn a_cancel_after_a_restart_undoes_the_journal() {
assert!(!e.rt.running.lock().unwrap().contains_key("orphan"));
assert!(!dir.join("orphan.json").exists());
// A cancel marker left for a process that then died: the recovery
- // removes instead of registering; a name that was in use stays.
+ // preserves both resources and evidence instead of replaying cancellation.
journal("marked", true);
std::fs::write(dir.join("marked.cancel"), b"cancel\n").unwrap();
journal("borrowed", false);
@@ -278,9 +290,17 @@ async fn a_cancel_after_a_restart_undoes_the_journal() {
.recover_interrupted_creates(Duration::from_secs(1))
.await;
assert_eq!(got.len(), 2, "{got:?}");
- assert!(!e.rt.running.lock().unwrap().contains_key("marked"));
+ assert!(e.rt.running.lock().unwrap().contains_key("marked"));
assert!(e.rt.running.lock().unwrap().contains_key("borrowed"));
- assert_eq!(journals(&e.spaces), 0);
+ assert!(
+ got.iter()
+ .all(|r| matches!(r.outcome, cua_spaces::RecoveryOutcome::Failed(_)))
+ );
+ for name in ["marked", "borrowed"] {
+ assert!(dir.join(format!("{name}.json")).exists());
+ assert!(dir.join(format!("{name}.cancel")).exists());
+ }
+ assert_eq!(e.rt.deleted.lock().unwrap().as_slice(), ["orphan"]);
}
/// A cloud create cancelled while its claim waits to bind releases the
@@ -365,3 +385,93 @@ async fn a_cancel_while_connecting_removes_the_running_instance() {
assert!(!e.rt.running.lock().unwrap().contains_key("connecting"));
assert_eq!(journals(&e.spaces), 0);
}
+
+/// A create given the name of a Space that already runs (its cua-spacesd
+/// answers another token, so readiness and the handshake fail) never
+/// deletes it: only what a create made is its to remove.
+#[tokio::test]
+async fn a_failed_create_never_deletes_an_existing_space_of_that_name() {
+ let e = env();
+ e.rt.boots.store(true, std::sync::atomic::Ordering::SeqCst);
+ let mute = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ e.rt.port.store(
+ mute.local_addr().unwrap().port(),
+ std::sync::atomic::Ordering::SeqCst,
+ );
+ tokio::spawn(async move {
+ let mut held = Vec::new();
+ while let Ok((sock, _)) = mute.accept().await {
+ held.push(sock);
+ }
+ });
+ let name = "space-0123456789";
+ e.rt.running.lock().unwrap().insert(name.into(), true);
+ e.spaces
+ .registry()
+ .upsert(
+ cua_proto::daemon::v1::Space {
+ id: format!("local:{name}"),
+ ..Default::default()
+ },
+ Default::default(),
+ )
+ .unwrap();
+ let mut opts = local(Some(name), "p5");
+ opts.timeout = Some(Duration::from_secs(3));
+ let err = e.spaces.create(opts).await.unwrap_err();
+ assert_eq!(err.tag(), "timeout", "{err}");
+ assert!(
+ e.spaces
+ .registry()
+ .get(&format!("local:{name}"))
+ .unwrap()
+ .is_some()
+ );
+ assert!(e.rt.running.lock().unwrap().contains_key(name));
+ assert!(
+ e.rt.deleted.lock().unwrap().is_empty(),
+ "{:?}",
+ e.rt.deleted.lock().unwrap()
+ );
+}
+
+#[tokio::test]
+async fn interrupted_nonlocal_recovery_still_releases_its_claim() {
+ let reg = tempfile::tempdir().unwrap();
+ let fake = FakeFleet::new();
+ let spaces = Spaces::builder()
+ .home(reg.path())
+ .fleet(fake.client())
+ .build();
+ fake.put_object(
+ "claim",
+ "test-pool",
+ "claim",
+ serde_json::json!({
+ "metadata": {"name": "claim", "namespace": "test-pool"}, "spec": {}
+ }),
+ );
+ let dir = reg.path().join("creating");
+ std::fs::create_dir_all(&dir).unwrap();
+ let mut child = std::process::Command::new("true").spawn().unwrap();
+ let pid = child.id();
+ child.wait().unwrap();
+ std::fs::write(
+ dir.join("claim.json"),
+ serde_json::json!({
+ "kind": "cloud", "name": "claim", "id": "cloud:claim", "pid": pid, "started": 0,
+ "made": [{"type": "fleet_claim", "namespace": "test-pool", "name": "claim"}],
+ })
+ .to_string(),
+ )
+ .unwrap();
+ let got = spaces
+ .recover_interrupted_creates(Duration::from_millis(20))
+ .await;
+ assert!(
+ matches!(got.as_slice(), [r] if matches!(r.outcome, cua_spaces::RecoveryOutcome::Deleted(_))),
+ "{got:?}"
+ );
+ assert!(!fake.exists("claim", "test-pool", "claim"));
+ assert!(!dir.join("claim.json").exists());
+}
diff --git a/libs/cua/crates/cua-spaces/tests/providers.rs b/libs/cua/crates/cua-spaces/tests/providers.rs
index 2365252264..8a3e55ede1 100644
--- a/libs/cua/crates/cua-spaces/tests/providers.rs
+++ b/libs/cua/crates/cua-spaces/tests/providers.rs
@@ -413,11 +413,10 @@ async fn a_local_create_resolves_an_image_alias_to_its_canonical_image() {
/// A daemon killed mid-create leaves a started sandbox that no Space
/// lists. The next daemon's `recover_interrupted_creates` registers it when
-/// its cua-spacesd answers and deletes it when it does not; creates of live
-/// processes and journals with nothing behind them are handled without
-/// touching anything else. A finished create leaves no journal.
+/// its cua-spacesd answers; otherwise its resource and journal remain.
+/// A live owner's journal is untouched. Successful recovery retires its journal.
#[tokio::test]
-async fn an_interrupted_local_create_is_registered_or_deleted_never_hidden() {
+async fn an_interrupted_local_create_is_registered_or_preserved() {
use cua_sandbox_core::{CreateOptions, ProviderKind};
use cua_spaces::RecoveryOutcome;
let srv = MockServer::start(MockAuth::default()).await;
@@ -518,9 +517,12 @@ async fn an_interrupted_local_create_is_registered_or_deleted_never_hidden() {
Some(RecoveryOutcome::Registered),
"{got:?}"
);
- assert_eq!(outcome("local:early"), Some(RecoveryOutcome::NothingLeft));
+ assert!(matches!(
+ outcome("local:early"),
+ Some(RecoveryOutcome::Failed(_))
+ ));
assert!(
- matches!(outcome("local:cut"), Some(RecoveryOutcome::Deleted(_))),
+ matches!(outcome("local:cut"), Some(RecoveryOutcome::Failed(_))),
"{got:?}"
);
assert_eq!(
@@ -538,10 +540,15 @@ async fn an_interrupted_local_create_is_registered_or_deleted_never_hidden() {
"back\n"
);
assert!(creating.join("busy.json").exists());
- assert!(!creating.join("half.json").exists() && !creating.join("early.json").exists());
- assert_eq!(good.deleted.lock().unwrap().as_slice(), ["cut"]);
+ assert!(!creating.join("half.json").exists());
+ for name in ["early", "cut"] {
+ assert!(creating.join(format!("{name}.json")).exists());
+ std::fs::remove_file(creating.join(format!("{name}.json"))).unwrap();
+ }
+ assert_eq!(good.running.lock().unwrap().get("cut"), Some(&true));
+ assert!(good.deleted.lock().unwrap().is_empty());
- // A sandbox whose cua-spacesd never answers is deleted, not left running.
+ // A sandbox whose cua-spacesd never answers retains its resource and journal.
let spaces2 = spaces_on(&bad, s2.path());
spaces2
.sandboxes()
@@ -560,12 +567,13 @@ async fn an_interrupted_local_create_is_registered_or_deleted_never_hidden() {
.recover_interrupted_creates(Duration::from_secs(2))
.await;
assert!(
- matches!(got.as_slice(), [r] if r.id == "local:mute" && matches!(r.outcome, RecoveryOutcome::Deleted(_))),
+ matches!(got.as_slice(), [r] if r.id == "local:mute" && matches!(r.outcome, RecoveryOutcome::Failed(_))),
"{got:?}"
);
- assert_eq!(bad.deleted.lock().unwrap().as_slice(), ["mute"]);
+ assert!(bad.deleted.lock().unwrap().is_empty());
+ assert_eq!(bad.running.lock().unwrap().get("mute"), Some(&true));
assert!(!spaces2.list().unwrap().iter().any(|s| s.id == "local:mute"));
- assert_eq!(std::fs::read_dir(&creating).unwrap().count(), 0);
+ assert!(creating.join("mute.json").exists());
}
/// A create reports what it is doing, in order, ending with `ready`: the
@@ -1048,3 +1056,156 @@ impl LocalRuntime for SlowBootRuntime {
})
}
}
+
+#[tokio::test]
+async fn recovery_requires_authenticated_evidence_and_preserves_failed_attempts() {
+ use cua_sandbox_core::{CreateOptions, ProviderKind};
+ use cua_spaces::RecoveryOutcome;
+ let srv = MockServer::start(MockAuth {
+ token: Some("recovery-token".into()),
+ ..Default::default()
+ })
+ .await;
+ let unprotected = MockServer::start(MockAuth::default()).await;
+ let dead_port = std::net::TcpListener::bind("127.0.0.1:0")
+ .unwrap()
+ .local_addr()
+ .unwrap()
+ .port();
+ let mut child = std::process::Command::new("true").spawn().unwrap();
+ let pid = child.id();
+ child.wait().unwrap();
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs();
+ for age in [60, 25 * 3600] {
+ for case in [
+ "good",
+ "missing",
+ "auth",
+ "store",
+ "services",
+ "empty-token",
+ "borrowed",
+ "marked-registered",
+ "registered",
+ ] {
+ let reg = tempfile::tempdir().unwrap();
+ let state = tempfile::tempdir().unwrap();
+ let rt = Arc::new(FakeRuntime {
+ port: if case == "services" {
+ dead_port
+ } else if case == "empty-token" {
+ unprotected.addr.port()
+ } else {
+ srv.addr.port()
+ },
+ started: Mutex::new(vec![]),
+ deleted: Mutex::new(vec![]),
+ running: Mutex::new(BTreeMap::new()),
+ });
+ let spaces = Spaces::builder()
+ .home(reg.path())
+ .sandboxes(
+ cua_sandbox_core::Sandboxes::builder()
+ .local(rt.clone())
+ .state_dir(state.path())
+ .build(),
+ )
+ .build();
+ let name = "recover-me";
+ spaces
+ .sandboxes()
+ .create(
+ CreateOptions::new(
+ ProviderKind::Local,
+ "cua-e2e-local/linux:docker-local-arm64",
+ )
+ .name(name),
+ )
+ .await
+ .unwrap();
+ if case == "missing" {
+ spaces.sandboxes().state().delete(name).unwrap();
+ }
+ if case.ends_with("registered") {
+ spaces
+ .registry()
+ .upsert(
+ cua_proto::daemon::v1::Space {
+ id: format!("local:{name}"),
+ ..Default::default()
+ },
+ Default::default(),
+ )
+ .unwrap();
+ }
+ if case == "store" {
+ std::fs::create_dir(reg.path().join("spaces.json")).unwrap();
+ }
+ let dir = reg.path().join("creating");
+ std::fs::create_dir_all(&dir).unwrap();
+ let journal = dir.join(format!("{name}.json"));
+ let marker = dir.join(format!("{name}.cancel"));
+ let token = match case {
+ "auth" => "wrong",
+ "empty-token" => "",
+ _ => "recovery-token",
+ };
+ std::fs::write(
+ &journal,
+ serde_json::json!({
+ "kind": "local", "id": format!("local:{name}"), "name": name, "pid": pid,
+ "token": token, "spacesd": case != "services", "started": now - age,
+ "made": [{"type": "local_sandbox", "name": name, "fresh": case != "borrowed"}],
+ })
+ .to_string(),
+ )
+ .unwrap();
+ if case == "marked-registered" {
+ std::fs::write(&marker, b"cancel").unwrap();
+ }
+ let got = spaces
+ .recover_interrupted_creates(Duration::from_millis(20))
+ .await;
+ assert_eq!(got.len(), 1, "{case}: {got:?}");
+ match case {
+ "good" => {
+ assert_eq!(got[0].outcome, RecoveryOutcome::Registered);
+ assert!(
+ spaces
+ .space(&format!("local:{name}"))
+ .await
+ .unwrap()
+ .has_spacesd()
+ );
+ }
+ "registered" => assert_eq!(got[0].outcome, RecoveryOutcome::AlreadyRegistered),
+ _ => assert!(
+ matches!(&got[0].outcome, RecoveryOutcome::Failed(message) if message.contains("retained")),
+ "{case}: {got:?}"
+ ),
+ }
+ assert_eq!(
+ journal.exists(),
+ !matches!(case, "good" | "registered"),
+ "{case}"
+ );
+ assert_eq!(marker.exists(), case == "marked-registered", "{case}");
+ assert_eq!(rt.running.lock().unwrap().get(name), Some(&true), "{case}");
+ assert!(rt.deleted.lock().unwrap().is_empty(), "{case}");
+ if case != "store" {
+ assert_eq!(
+ spaces
+ .registry()
+ .get(&format!("local:{name}"))
+ .unwrap()
+ .is_some(),
+ matches!(case, "good" | "registered" | "marked-registered"),
+ "{case}"
+ );
+ }
+ }
+ }
+}