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(cua-spaces): fail a macOS create within seconds when its image download stops (#5214)

ddupont0bd9d113fe84
diff --git a/libs/cua/crates/cua-spaces-app-core/src/spaces/creating.rs b/libs/cua/crates/cua-spaces-app-core/src/spaces/creating.rs
index e233798860..b3ac0d9932 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/spaces/creating.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/spaces/creating.rs
@@ -761,6 +761,9 @@ pub enum FailureCause {
ServiceTimeout,
/// The image download did not finish in time.
PullTimeout,
+ /// The image download stopped partway: Lume's pull failed or was
+ /// cancelled, or Lume stopped. Another try resumes it.
+ PullStopped,
}
impl FailureCause {
@@ -775,10 +778,15 @@ impl FailureCause {
Self::Gpu => "Unsupported",
Self::Unauthenticated => "Unauthenticated",
Self::ServiceTimeout | Self::PullTimeout => "Timeout",
+ Self::PullStopped => "ImagePull",
}
}
}
+/// The SDK's words for an image download that stopped partway
+/// (`VmmError::PullStopped`), lowercased.
+const PULL_STOPPED: &str = "the image download stopped before it finished";
+
/// Which known cause the SDK's `raw` error is, if any. `phase` is where it
/// failed and `gpu` whether GPU acceleration was asked for, when known.
pub fn failure_cause(raw: &str, phase: Option<&str>, gpu: bool) -> Option<FailureCause> {
@@ -816,6 +824,9 @@ pub fn failure_cause(raw: &str, phase: Option<&str>, gpu: bool) -> Option<Failur
if l.contains("unauthenticated") {
return Some(FailureCause::Unauthenticated);
}
+ if l.contains(PULL_STOPPED) {
+ return Some(FailureCause::PullStopped);
+ }
let timed_out =
l.contains("timed out") || l.contains("timeout") || l.contains("not ready after");
if l.contains("cua-spacesd did not answer within ") {
@@ -906,6 +917,29 @@ pub fn failure_text_on(
.into(),
}
}
+ Some(FailureCause::PullStopped) => {
+ // The SDK's "The image download stopped before it finished
+ // (<cause>). Try again; ..." with its cause.
+ let at = l.find(PULL_STOPPED).unwrap_or(0) + PULL_STOPPED.len();
+ let cause = plain[at..]
+ .trim_start()
+ .strip_prefix('(')
+ .and_then(|r| r.rsplit_once(')'))
+ .map(|(c, _)| c.trim())
+ .filter(|c| !c.is_empty());
+ let cause = cause.map(|c| format!(" ({c})")).unwrap_or_default();
+ let place = match host_name.map(str::trim).filter(|n| !n.is_empty()) {
+ Some(name) => format!(" on {name}"),
+ None if matches!(provider, Some(SpaceProvider::Relay | SpaceProvider::Direct)) => {
+ " on the Mac running this Space".into()
+ }
+ None => String::new(),
+ };
+ format!(
+ "The image download{place} stopped before it finished{cause}. Try again; it \
+ picks up where it stopped."
+ )
+ }
Some(FailureCause::PullTimeout) => "The image download did not finish in the time \
allowed. Check your internet connection, then try again."
.into(),
@@ -2410,6 +2444,30 @@ mod tests {
"The image download did not finish in the time allowed. Check your internet \
connection, then try again."
);
+ // A download that stopped partway says why, also on another Mac.
+ let stopped = "local runtime: [local] The image download stopped before it finished \
+ (The network connection was lost). Try again; it picks up where it stopped.";
+ assert_eq!(
+ failure_text(stopped, Some("pulling"), Some(SpaceProvider::Local), false),
+ "The image download stopped before it finished (The network connection was lost). \
+ Try again; it picks up where it stopped."
+ );
+ assert_eq!(
+ failure_text_on(
+ "host: create failed: The image download stopped before it finished (Lume \
+ stopped running). Try again; it picks up where it stopped.",
+ Some("pulling"),
+ Some(SpaceProvider::Relay),
+ Some("Studio"),
+ false
+ ),
+ "The image download on Studio stopped before it finished (Lume stopped running). \
+ Try again; it picks up where it stopped."
+ );
+ assert_eq!(
+ failure_variant(stopped, Some("pulling"), false, "Runtime"),
+ "ImagePull"
+ );
// Local Network privacy on the Mac that runs the VM.
let sdk = "Local Network access is not available: cua cannot reach the VM at \
192.168.64.45:3211 (No route to host (os error 65)). macOS blocks an app's \
diff --git a/libs/cua/crates/cua-spaces/tests/host_spaces.rs b/libs/cua/crates/cua-spaces/tests/host_spaces.rs
index ccffd867d5..7e6ef8864a 100644
--- a/libs/cua/crates/cua-spaces/tests/host_spaces.rs
+++ b/libs/cua/crates/cua-spaces/tests/host_spaces.rs
@@ -39,6 +39,9 @@ struct FakeRuntime {
/// Starts first download an image of this many bytes, slowly,
/// reporting it as create progress (as Lume's pull does).
pull_bytes: Mutex<Option<u64>>,
+ /// The download stops at this step of 30 with this error (Lume's pull
+ /// failed, or Lume died under it).
+ pull_stops: Mutex<Option<(u64, String)>>,
}
#[async_trait]
@@ -53,7 +56,11 @@ impl LocalRuntime for FakeRuntime {
let pull = *self.pull_bytes.lock().unwrap();
if let Some(total) = pull {
use cua_sandbox_core::progress::{Phase, Progress, Transfer, report};
+ let stops = self.pull_stops.lock().unwrap().clone();
for i in 0..=30u64 {
+ if let Some((_, e)) = stops.as_ref().filter(|(at, _)| *at == i) {
+ return Err(RuntimeError::Other(e.clone()));
+ }
let done = total * i / 30;
report(
Progress::phase(Phase::Pulling)
@@ -198,6 +205,7 @@ async fn runtime_fixture(
paused: Mutex::default(),
hang: Default::default(),
fail: Mutex::default(),
+ pull_stops: Mutex::default(),
pull_bytes: Mutex::default(),
});
let spaces = Spaces::builder()
@@ -1398,6 +1406,43 @@ async fn a_create_on_a_host_reports_the_hosts_progress() {
}
}
+/// A host whose image download stops partway fails the caller's create
+/// right then, with the host's reason, after showing the download; the
+/// host stops listing the create and no Space is left on the relay.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn a_download_that_stops_on_the_host_fails_the_create_with_its_reason() {
+ let f = fixture(HostProfile::Spare).await;
+ let (_host, spaces, _other) = client_fixture(&f).await;
+ *f.rt.pull_bytes.lock().unwrap() = Some(TOTAL);
+ let why = "The image download stopped before it finished (Lume stopped running). Try \
+ again; it picks up where it stopped.";
+ *f.rt.pull_stops.lock().unwrap() = Some((10, why.into()));
+ let seen = Arc::new(Mutex::new(Vec::<cua_spaces::CreateProgress>::new()));
+ let s = seen.clone();
+ let mut create = on_host("Mac mini (spare)");
+ create.progress = Some(cua_spaces::ProgressSink::new(move |p| {
+ s.lock().unwrap().push(p.clone())
+ }));
+ let t = std::time::Instant::now();
+ let e = spaces.create(create).await.unwrap_err().to_string();
+ assert!(
+ t.elapsed() < std::time::Duration::from_secs(10),
+ "failed after {:?}",
+ t.elapsed()
+ );
+ assert!(e.contains(why), "the host's reason: {e}");
+ assert!(
+ seen.lock()
+ .unwrap()
+ .iter()
+ .any(|p| p.phase == cua_spaces::CreatePhase::Pulling),
+ "the download showed before it stopped"
+ );
+ assert!(provided_machines(&f).await.is_empty(), "no ghost Space");
+ let creating = f.server.get(&ada()).await.unwrap().creating;
+ assert!(creating.is_empty(), "{creating:?}");
+}
+
/// A host that predates listing its creates still creates the Space; the
/// client reports what it does itself (as before: no download to show).
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
diff --git a/libs/cua/crates/cua-vmm/src/error.rs b/libs/cua/crates/cua-vmm/src/error.rs
index 11dc664428..c606102a52 100644
--- a/libs/cua/crates/cua-vmm/src/error.rs
+++ b/libs/cua/crates/cua-vmm/src/error.rs
@@ -59,6 +59,14 @@ pub enum VmmError {
detail: String,
},
+ /// An image download ended before it finished: Lume's pull failed, was
+ /// cancelled outside the SDK, or `lume serve` stopped under it. Lume
+ /// keeps the layers it finished, so another try picks up from there.
+ #[error(
+ "The image download stopped before it finished ({reason}). Try again; it picks up where it stopped."
+ )]
+ PullStopped { name: String, reason: String },
+
/// A spawned host command failed.
#[error("`{cmd}` failed (exit {code:?}): {stderr}")]
Command {
@@ -108,6 +116,7 @@ pub fn failure_kind(message: &str) -> Option<&'static str> {
|| m.contains("manifest unknown")
|| m.contains("pull access denied")
|| m.contains("toomanyrequests")
+ || m.contains("the image download stopped before it finished")
{
Some("image_pull")
} else if m.contains("permission denied") {
@@ -165,6 +174,11 @@ mod tests {
assert_eq!(failure_kind(&wrap(pull)), Some("image_pull"));
let denied_pull = VmmError::Engine("pull x: pull access denied for x".into());
assert_eq!(failure_kind(&denied_pull.to_string()), Some("image_pull"));
+ let stopped = VmmError::PullStopped {
+ name: "cua-base-x".into(),
+ reason: "Lume stopped running".into(),
+ };
+ assert_eq!(failure_kind(&wrap(stopped)), Some("image_pull"));
assert_eq!(failure_kind(&VmmError::other("boom").to_string()), None);
let lan = VmmError::missing("Local Network access", "click Allow");
assert_eq!(failure_kind(&lan.to_string()), None);
diff --git a/libs/cua/crates/cua-vmm/src/lume/client.rs b/libs/cua/crates/cua-vmm/src/lume/client.rs
index e55ec93542..bd268df462 100644
--- a/libs/cua/crates/cua-vmm/src/lume/client.rs
+++ b/libs/cua/crates/cua-vmm/src/lume/client.rs
@@ -524,15 +524,22 @@ impl LumeClient {
/// Waits for the async pull of `name` to end, reporting its progress.
/// It fails after `idle` without movement (a new percent or new bytes),
- /// never because a slow download that still moves takes long. Dropping
- /// the wait (a cancelled create) cancels the pull on a Lume that can
- /// ([`LumeClient::cancel_pull`]), once no other wait in this process
- /// still needs it.
+ /// never because a slow download that still moves takes long. It fails
+ /// within [`PULL_GONE_GRACE`] when the pull is gone: Lume reports it
+ /// failed, Lume no longer knows the VM (the pull was cancelled outside
+ /// this wait), or `lume serve` stopped answering (the pull ran inside
+ /// it). Dropping the wait (a cancelled create) cancels the pull on a
+ /// Lume that can ([`LumeClient::cancel_pull`]), once no other wait in
+ /// this process still needs it.
async fn wait_pulled(&self, name: &str, idle: Duration) -> Result<()> {
let mut guard = PullGuard::new(self.clone(), name);
let mut moved_at = tokio::time::Instant::now();
let mut last: Option<(Option<f64>, Option<u64>)> = None;
let mut meter = crate::progress::Meter::new();
+ // Since when the pull has looked gone, and whether `lume serve`
+ // stopped answering meanwhile.
+ let mut gone_since: Option<tokio::time::Instant> = None;
+ let mut serve_lost = false;
loop {
// A Lume that counts bytes shows a stall much sooner.
let budget = if guard.cancellable {
@@ -547,8 +554,10 @@ impl LumeClient {
detail: "lume pull made no progress".into(),
});
}
+ let mut gone = false;
match self.get(name).await {
Ok(Some(vm)) => {
+ gone_since = None;
let now = (vm.download_progress, vm.downloaded_bytes);
if last != Some(now) {
moved_at = tokio::time::Instant::now();
@@ -565,9 +574,9 @@ impl LumeClient {
}
s if s.to_ascii_lowercase().contains("error") => {
guard.done();
- return Err(VmmError::Lume {
- status: 500,
- message: format!("pull of '{name}' failed: {s}"),
+ return Err(VmmError::PullStopped {
+ name: name.into(),
+ reason: format!("Lume reported {s}"),
});
}
_ => {
@@ -582,12 +591,36 @@ impl LumeClient {
message,
}) if message.contains("Pull failed") => {
guard.done();
- return Err(VmmError::Lume {
- status: 500,
- message,
+ return Err(VmmError::PullStopped {
+ name: name.into(),
+ reason: pull_failed_reason(&message),
+ });
+ }
+ // The pull ended without making the VM: cancelled outside
+ // this wait, or lost with a `lume serve` that restarted.
+ Ok(None) => gone = true,
+ // `lume serve` is gone, and the pull that ran inside it.
+ Err(VmmError::Missing { .. }) => {
+ gone = true;
+ serve_lost = true;
+ }
+ Err(_) => {}
+ }
+ if gone {
+ let since = *gone_since.get_or_insert_with(tokio::time::Instant::now);
+ if since.elapsed() >= PULL_GONE_GRACE {
+ guard.done();
+ let reason = if serve_lost {
+ "Lume stopped running"
+ } else {
+ "it was cancelled outside Cua"
+ };
+ tracing::warn!(vm = name, reason, "lume pull ended without the image");
+ return Err(VmmError::PullStopped {
+ name: name.into(),
+ reason: reason.into(),
});
}
- _ => {}
}
tokio::time::sleep(PULL_POLL).await;
}
@@ -615,6 +648,26 @@ impl LumeClient {
/// How often an async pull is polled (Lume answers from memory).
const PULL_POLL: Duration = Duration::from_millis(250);
+/// How long an async pull may look gone (its VM unknown to Lume, or
+/// `lume serve` not answering) before the wait fails: a few polls, so one
+/// missed answer never fails a pull that still runs.
+const PULL_GONE_GRACE: Duration = Duration::from_secs(3);
+
+/// The cause in Lume's "Pull failed for 'vm': <cause>" answer.
+fn pull_failed_reason(message: &str) -> String {
+ let cause = message
+ .split_once("': ")
+ .map(|(_, c)| c)
+ .unwrap_or(message)
+ .trim()
+ .trim_end_matches('.');
+ if cause.is_empty() {
+ "Lume's download failed".into()
+ } else {
+ cause.into()
+ }
+}
+
/// How long a pull whose bytes Lume counts may go without a new byte.
const PULL_IDLE_WITH_BYTES: Duration = Duration::from_secs(10 * 60);
diff --git a/libs/cua/crates/cua-vmm/src/lume/mod.rs b/libs/cua/crates/cua-vmm/src/lume/mod.rs
index a00c59fdb1..ac077b8147 100644
--- a/libs/cua/crates/cua-vmm/src/lume/mod.rs
+++ b/libs/cua/crates/cua-vmm/src/lume/mod.rs
@@ -444,6 +444,9 @@ impl LumeRuntime {
);
*self.old_lume.lock().unwrap_or_else(|e| e.into_inner()) = Some(v);
}
+ // No `lume serve` answers, so none of its pulls runs: a pull a
+ // killed serve left half-made in its temp dir is only taking space.
+ sweep_stale_pull_dirs(&lume_temp_dir(), STALE_PULL_DIR_IDLE);
std::fs::create_dir_all(&self.cfg.root)?;
let log = std::fs::File::create(self.cfg.root.join("serve.log"))?;
let mut cmd = std::process::Command::new(&bin);
@@ -478,7 +481,8 @@ impl LumeRuntime {
/// leases and ARP table ([`lease`]); `lume serve` can lag the lease by
/// many seconds or miss it. Polls back off from 0.5 s to 3 s. A VM that
/// never reaches `running`, or stops after it did, fails fast with the
- /// tail of its run log instead of waiting out the timeout.
+ /// tail of its run log instead of waiting out the timeout; one Lume no
+ /// longer knows (deleted outside the SDK) fails within a few seconds.
async fn wait_for_ip(&self, name: &str) -> Result<VmDetails> {
let start = tokio::time::Instant::now();
let deadline = start + self.cfg.ip_timeout;
@@ -488,9 +492,20 @@ impl LumeRuntime {
let mut last_state = String::new();
let leases_path = std::path::PathBuf::from(&self.cfg.leases_path);
let before = lease::read_leases(&leases_path).await;
+ let mut missing_since: Option<tokio::time::Instant> = None;
// Bounded by the deadline; at most ip_timeout / 0.5 s iterations.
while tokio::time::Instant::now() < deadline {
let vm = self.client.get(name).await?;
+ if vm.is_none() {
+ let since = *missing_since.get_or_insert_with(tokio::time::Instant::now);
+ if since.elapsed() >= VM_GONE_GRACE {
+ return Err(VmmError::other(format!(
+ "lume VM '{name}' disappeared while booting (it was deleted outside Cua)"
+ )));
+ }
+ } else {
+ missing_since = None;
+ }
if let Some(mut vm) = vm {
let state = format!(
"status={} api_ip={:?} mac={:?}",
@@ -1007,6 +1022,75 @@ pub async fn cli_pull(
/// Host-side marker: this VM got a workload environment from cua-vmm (so a
/// later start without one clears it).
const MACOS_ENV_MARKER: &str = "env-applied";
+/// How long a pull's temp dir must have gone unwritten before
+/// [`sweep_stale_pull_dirs`] removes it: a pull that still runs (a `lume
+/// pull` in another process) writes to it all the time.
+const STALE_PULL_DIR_IDLE: Duration = Duration::from_secs(30);
+
+/// Where Lume pulls an image before moving the VM into place
+/// (`FileManager.temporaryDirectory`: the per-user temp dir on macOS).
+fn lume_temp_dir() -> PathBuf {
+ #[cfg(target_os = "macos")]
+ {
+ let mut buf = vec![0u8; 1024];
+ // SAFETY: `buf` is writable for its length; confstr writes at most
+ // that many bytes, NUL-terminated.
+ let n = unsafe {
+ libc::confstr(
+ libc::_CS_DARWIN_USER_TEMP_DIR,
+ buf.as_mut_ptr().cast(),
+ buf.len(),
+ )
+ };
+ if n > 0 && n <= buf.len() {
+ buf.truncate(n - 1);
+ if let Ok(s) = String::from_utf8(buf) {
+ return PathBuf::from(s);
+ }
+ }
+ }
+ std::env::temp_dir()
+}
+
+/// Removes the `lume_vm_*` dirs in `temp` (a pull's half-made VM, left by a
+/// `lume serve` that was killed mid-pull: it cleans up only when it can)
+/// that nothing wrote for `idle`. Returns how many it removed.
+fn sweep_stale_pull_dirs(temp: &std::path::Path, idle: Duration) -> usize {
+ fn newest(path: &std::path::Path, depth: u8) -> Option<std::time::SystemTime> {
+ let mut t = std::fs::symlink_metadata(path).ok()?.modified().ok()?;
+ if depth > 0
+ && let Ok(entries) = std::fs::read_dir(path)
+ {
+ for e in entries.flatten() {
+ if let Some(m) = newest(&e.path(), depth - 1) {
+ t = t.max(m);
+ }
+ }
+ }
+ Some(t)
+ }
+ let Ok(entries) = std::fs::read_dir(temp) else {
+ return 0;
+ };
+ let mut removed = 0;
+ for e in entries.flatten() {
+ let path = e.path();
+ let ours = e.file_name().to_string_lossy().starts_with("lume_vm_")
+ && e.file_type().is_ok_and(|t| t.is_dir());
+ let stale = newest(&path, 3)
+ .and_then(|t| t.elapsed().ok())
+ .is_some_and(|age| age >= idle);
+ if ours && stale && std::fs::remove_dir_all(&path).is_ok() {
+ tracing::info!(dir = %path.display(), "removed a pull a stopped lume serve left");
+ removed += 1;
+ }
+ }
+ removed
+}
+
+/// How long a booting VM may be unknown to Lume before the wait fails.
+const VM_GONE_GRACE: Duration = Duration::from_secs(3);
+
/// How long to keep retrying the environment write while the guest's sshd
/// comes up after boot.
const MACOS_ENV_BUDGET: Duration = Duration::from_secs(180);
@@ -1679,6 +1763,27 @@ impl Runtime for LumeRuntime {
mod tests {
use super::*;
+ /// A killed serve's half-made pull is removed; a pull still being
+ /// written, and anything not Lume's, stays.
+ #[test]
+ fn a_stale_pull_dir_is_swept_and_a_live_one_stays() {
+ let t = tempfile::tempdir().unwrap();
+ for d in ["lume_vm_dead", "lume_vm_live", "other"] {
+ std::fs::create_dir_all(t.path().join(d).join("sub")).unwrap();
+ std::fs::write(t.path().join(d).join("sub/disk.img"), b"x").unwrap();
+ }
+ std::fs::write(t.path().join("lume_vm_file"), b"x").unwrap();
+ assert_eq!(
+ sweep_stale_pull_dirs(t.path(), Duration::from_secs(3600)),
+ 0,
+ "written just now: still pulling"
+ );
+ assert_eq!(sweep_stale_pull_dirs(t.path(), Duration::ZERO), 2);
+ assert!(!t.path().join("lume_vm_dead").exists());
+ assert!(t.path().join("other").exists());
+ assert!(t.path().join("lume_vm_file").exists());
+ }
+
#[test]
fn cli_get_reads_the_status_lume_reports() {
let stopped = r#"[{"name":"cua-box","status":"stopped","os":"macOS"}]"#;
diff --git a/libs/cua/crates/cua-vmm/tests/lume_pull_fail.rs b/libs/cua/crates/cua-vmm/tests/lume_pull_fail.rs
new file mode 100644
index 0000000000..6c7489e798
--- /dev/null
+++ b/libs/cua/crates/cua-vmm/tests/lume_pull_fail.rs
@@ -0,0 +1,153 @@
+//! A macOS create whose base image download stops partway fails within
+//! seconds, with the reason, and leaves nothing behind; the next try pulls
+//! again and finishes.
+//!
+//! Hermetic: a fake `lume serve` runs the async pull (`POST
+//! /lume/pull/start`, then `GET /lume/vms/:name` while it pulls) and ends it
+//! one of three ways: Lume reports the pull failed, the pull is cancelled
+//! outside the SDK (Lume no longer knows the VM), or `lume serve` dies with
+//! the pull inside it. Without the fix each waited out the pull's idle
+//! timeout (10 minutes in the daemon, 10 s here).
+
+#![cfg(feature = "lume")]
+
+#[allow(dead_code)]
+#[path = "support/fake_lume.rs"]
+mod fake_lume;
+
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use cua_vmm::lume::base_vm_name;
+use cua_vmm::{GuestOs, ImageSource, Runtime, StartSpec, VmmError};
+use fake_lume::{FakeLume, FakePull, PullEnd, serve, temp_home};
+
+/// One image per test: tests run in parallel and share the owned-VM records.
+const REF_FAILED: &str = "registry.example/test/macos:failed";
+const REF_VANISHED: &str = "registry.example/test/macos:vanished";
+const REF_DIED: &str = "registry.example/test/macos:died";
+
+/// Plenty of free disk, so the pull's disk guard never decides the test.
+struct Roomy;
+impl cua_vmm::disk::SpaceProbe for Roomy {
+ fn space(&self, _: &std::path::Path) -> std::io::Result<cua_vmm::disk::Space> {
+ Ok(cua_vmm::disk::Space {
+ available: 1 << 50,
+ total: 1 << 50,
+ })
+ }
+}
+
+fn spec(name: &str, reference: &str) -> StartSpec {
+ StartSpec::new(
+ name,
+ ImageSource::Oci {
+ reference: reference.into(),
+ },
+ )
+ .os(GuestOs::Macos)
+ .cpus(2)
+ .memory_mb(4096)
+}
+
+fn pull(end: PullEnd) -> FakePull {
+ FakePull {
+ polls: 4,
+ step: 1 << 30,
+ total: 30 << 30,
+ end,
+ }
+}
+
+async fn fake(end: PullEnd) -> (Arc<Mutex<FakeLume>>, String) {
+ temp_home();
+ cua_vmm::disk::set_probe(Some(Arc::new(Roomy)));
+ let state = Arc::new(Mutex::new(FakeLume {
+ pull: Some(pull(end)),
+ ..Default::default()
+ }));
+ let url = serve(state.clone()).await;
+ (state, url)
+}
+
+fn owns(name: &str) -> bool {
+ cua_vmm::lume::OwnedVms::default()
+ .list()
+ .iter()
+ .any(|r| r.name == name)
+}
+
+/// Starts `name`, expecting the pull to stop: the error, and how long the
+/// create took to fail.
+async fn failed_create(url: String, name: &str, reference: &str) -> (VmmError, Duration) {
+ let rt = fake_lume::runtime(url);
+ let t = Instant::now();
+ let err = rt.start(&spec(name, reference)).await.unwrap_err();
+ (err, t.elapsed())
+}
+
+#[tokio::test]
+async fn a_pull_lume_reports_failed_says_why_and_leaves_nothing() {
+ let (state, url) = fake(PullEnd::Fails("The network connection was lost.".into())).await;
+ let (err, took) = failed_create(url, "cua-pf-failed", REF_FAILED).await;
+ assert!(took < Duration::from_secs(5), "failed after {took:?}");
+ assert!(matches!(err, VmmError::PullStopped { .. }), "{err}");
+ assert!(
+ err.to_string()
+ .contains("stopped before it finished (The network connection was lost)"),
+ "{err}"
+ );
+ let st = state.lock().unwrap();
+ assert!(st.vms.is_empty(), "no VM is left: {:?}", st.vms.keys());
+ assert!(!owns(&base_vm_name(REF_FAILED)), "no base record is left");
+}
+
+#[tokio::test]
+async fn a_pull_cancelled_outside_fails_within_seconds() {
+ let (state, url) = fake(PullEnd::Vanishes).await;
+ let (err, took) = failed_create(url, "cua-pf-vanished", REF_VANISHED).await;
+ assert!(took < Duration::from_secs(6), "failed after {took:?}");
+ assert!(
+ err.to_string().contains("(it was cancelled outside Cua)"),
+ "{err}"
+ );
+ assert!(state.lock().unwrap().vms.is_empty());
+ assert!(!owns(&base_vm_name(REF_VANISHED)));
+}
+
+/// `lume serve` dies mid-pull: the create fails within seconds saying so,
+/// nothing is left, and the next try (a restarted serve) pulls again from
+/// the start of the request and boots the Space.
+#[tokio::test]
+async fn a_serve_that_dies_mid_pull_fails_fast_and_try_again_finishes() {
+ let (state, url) = fake(PullEnd::ServeDies).await;
+ let (err, took) = failed_create(url, "cua-pf-died", REF_DIED).await;
+ assert!(took < Duration::from_secs(6), "failed after {took:?}");
+ assert!(err.to_string().contains("(Lume stopped running)"), "{err}");
+ assert!(state.lock().unwrap().dead, "the fake serve died mid-pull");
+ assert!(state.lock().unwrap().vms.is_empty());
+ assert!(!owns("cua-pf-died"));
+ assert!(!owns(&base_vm_name(REF_DIED)));
+
+ // Try again: Lume is serving again and this pull finishes.
+ let again = {
+ let mut st = state.lock().unwrap();
+ st.dead = false;
+ st.pull = Some(pull(PullEnd::Completes));
+ st.calls.clear();
+ state.clone()
+ };
+ let url = serve(again).await;
+ let rt = fake_lume::runtime(url);
+ rt.start(&spec("cua-pf-died", REF_DIED)).await.unwrap();
+ let st = state.lock().unwrap();
+ let base = base_vm_name(REF_DIED);
+ let starts = st
+ .calls
+ .iter()
+ .filter(|(m, p, _)| m == "POST" && p == "/lume/pull/start")
+ .count();
+ assert_eq!(starts, 1, "the retry asks Lume to pull again");
+ assert!(st.vms.contains_key(&base), "the base is pulled");
+ assert_eq!(st.vms["cua-pf-died"]["status"], "running");
+}
diff --git a/libs/cua/crates/cua-vmm/tests/support/fake_lume.rs b/libs/cua/crates/cua-vmm/tests/support/fake_lume.rs
index 68f03b0dfa..d5604f47da 100644
--- a/libs/cua/crates/cua-vmm/tests/support/fake_lume.rs
+++ b/libs/cua/crates/cua-vmm/tests/support/fake_lume.rs
@@ -39,8 +39,39 @@ pub struct FakeLume {
/// A booted VM stops on its own before it gets an address (the guest
/// crashed: "stopped while booting").
pub boot_fails: bool,
+ /// How `POST /lume/pull/start` pulls go; `None` refuses them.
+ pub pull: Option<FakePull>,
+ /// Polls each async pull has had so far, by VM name.
+ pub pulling: BTreeMap<String, u64>,
+ /// The server stopped (a killed `lume serve`): it accepts nothing more.
+ pub dead: bool,
}
+/// An async pull: it reports `step` more bytes of `total` on each
+/// `GET /lume/vms/:name`, then after `polls` polls ends as `end` says.
+#[derive(Clone)]
+pub struct FakePull {
+ pub polls: u64,
+ pub step: u64,
+ pub total: u64,
+ pub end: PullEnd,
+}
+
+#[derive(Clone, PartialEq)]
+pub enum PullEnd {
+ /// The pull finishes: a stopped VM of that name.
+ Completes,
+ /// Lume reports the pull failed with this cause.
+ Fails(String),
+ /// The pull is gone and no VM was made (cancelled outside the SDK).
+ Vanishes,
+ /// `lume serve`, and the pull inside it, die.
+ ServeDies,
+}
+
+/// What [`handle`] answers when the fake's serve just died: no response.
+const DIE: u16 = 0;
+
fn not_found(name: &str) -> (u16, Value) {
(
404,
@@ -54,6 +85,56 @@ fn handle(st: &mut FakeLume, method: &str, path: &str, body: Value) -> (u16, Val
let name = path.strip_prefix("/lume/vms/").unwrap_or("");
match (method, path) {
("GET", "/lume/host/status") => (200, json!({ "status": "ok" })),
+ ("POST", "/lume/pull/start") => {
+ let Some(_) = st.pull else {
+ return (404, json!({ "message": "no route" }));
+ };
+ let vm = body["name"].as_str().unwrap().to_string();
+ st.pulling.insert(vm.clone(), 0);
+ (202, json!({ "message": "Pull started", "name": vm }))
+ }
+ ("GET", _) if st.pulling.contains_key(name) => {
+ let pull = st.pull.clone().unwrap();
+ let n = st.pulling.get_mut(name).unwrap();
+ *n += 1;
+ if *n <= pull.polls {
+ let done = (*n * pull.step).min(pull.total);
+ return (
+ 200,
+ json!({
+ "name": name, "status": "pulling",
+ "downloadProgress": done as f64 * 100.0 / pull.total as f64,
+ "downloadedBytes": done, "totalBytes": pull.total,
+ "bytesPerSecond": 1000.0
+ }),
+ );
+ }
+ match pull.end {
+ PullEnd::Completes => {
+ st.pulling.remove(name);
+ let vm = json!({
+ "name": name, "os": "macOS", "cpuCount": 4, "memorySize": 8u64 << 30,
+ "diskSize": { "allocated": 1u64 << 30, "total": 150u64 << 30 },
+ "display": "1024x768", "status": "stopped"
+ });
+ st.vms.insert(name.to_string(), vm.clone());
+ (200, vm)
+ }
+ PullEnd::Fails(cause) => (
+ 400,
+ json!({ "message": format!("Pull failed for '{name}': {cause}") }),
+ ),
+ PullEnd::Vanishes => {
+ st.pulling.remove(name);
+ not_found(name)
+ }
+ PullEnd::ServeDies => {
+ st.pulling.clear();
+ st.dead = true;
+ (DIE, Value::Null)
+ }
+ }
+ }
("POST", "/lume/vms/clone") => {
let src = body["name"].as_str().unwrap();
let new = body["newName"].as_str().unwrap().to_string();
@@ -131,12 +212,17 @@ fn handle(st: &mut FakeLume, method: &str, path: &str, body: Value) -> (u16, Val
/// Minimal HTTP/1.1 server (one request per connection, like lume).
pub async fn serve(state: Arc<Mutex<FakeLume>>) -> String {
let l = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let url = format!("http://{}", l.local_addr().unwrap());
+ let addr = l.local_addr().unwrap();
+ let url = format!("http://{addr}");
tokio::spawn(async move {
loop {
let Ok((mut s, _)) = l.accept().await else {
return;
};
+ // A dead serve closes its socket: later connects are refused.
+ if state.lock().unwrap().dead {
+ return;
+ }
let state = state.clone();
tokio::spawn(async move {
let mut buf = Vec::new();
@@ -181,6 +267,11 @@ pub async fn serve(state: Arc<Mutex<FakeLume>>) -> String {
return;
}
let (code, resp) = handle(&mut state.lock().unwrap(), method, path, body);
+ if code == DIE {
+ // Wake the accept loop so it sees the serve died.
+ let _ = tokio::net::TcpStream::connect(addr).await;
+ return;
+ }
let resp = resp.to_string();
let out = format!(
"HTTP/1.1 {code} X\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{resp}",