From fa921c26bade47634506b57b32713421f976ae22 Mon Sep 17 00:00:00 2001 From: aur-build Date: Thu, 19 Nov 2026 12:00:46 +0000 Subject: =?UTF-8?q?sandbox:=20failure-mode=20tier=20=E2=80=94=20a=20FakeBa?= =?UTF-8?q?ckend=20that=20breaks=20on=20purpose?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The recovery paths a remote pool makes newly reachable are now executed, not described. A decorator over the loopback backend injects the four faults that matter: a sandbox that vanishes mid-run (the step fails, the lease expires, the reaper requeues, a healthy pool finishes from the checkpoints — I5 across the sandbox boundary); a TTL that bites mid-build (a failed step, not a retry-burned one); a pool at quota (the build blocks on sandbox-pool using the same blocked machinery as missing deps, rather than failing on an infrastructure fact); and a sandbox whose pacman -Q lies about the installed world (provisioning refuses with a dedicated world-mismatch class, so 'the sandbox lied' never reads as 'the sandbox broke'). Two error classes carry that vocabulary: PoolExhausted — capacity, so wait, never retry — and WorldMismatch — fail-closed, never retried. The remote and kata acquire timeouts now speak the first, which is what makes a full pool a queue fact instead of a build failure. --- src/error.rs | 31 ++++++++ src/pipeline/steps.rs | 33 +++++++- src/sandbox/kata.rs | 2 +- tests/failure_modes.rs | 200 +++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 261 insertions(+), 5 deletions(-) create mode 100644 tests/failure_modes.rs diff --git a/src/error.rs b/src/error.rs index cf6e567..342c628 100644 --- a/src/error.rs +++ b/src/error.rs @@ -30,6 +30,17 @@ pub enum Error { Invalid(String), #[error("blocked: {0}")] Blocked(String), + /// The sandbox pool could not fit a lease right now. Not a failure and not + /// a retry: the build waits, the same way it waits for a dependency it + /// publishes (§10.4). A quota is a fact about capacity, not a bug. + #[error("sandbox pool exhausted: {0}")] + PoolExhausted(String), + /// The world inside the sandbox is not the world the plan approved: + /// a pinned dependency did not land, or the closure was incomplete. + /// Fail-closed with its own class so a test (and an operator) can tell + /// "the sandbox lied" apart from "the sandbox broke". + #[error("world mismatch: {0}")] + WorldMismatch(String), /// A failure the outside world caused and a retry may clear: an unreachable /// upstream, a half-written mirror. Distinct from a deterministic failure, /// which must never be retried into a different answer (§8.4). @@ -67,6 +78,19 @@ impl Error { pub fn transient(s: impl fmt::Display) -> Self { Error::Transient(s.to_string()) } + pub fn pool_exhausted(s: impl fmt::Display) -> Self { + Error::PoolExhausted(s.to_string()) + } + pub fn world_mismatch(s: impl fmt::Display) -> Self { + Error::WorldMismatch(s.to_string()) + } + + /// True when the sandbox pool, not the build, is the problem: the build + /// should block and wait, not fail and not be retried into a different + /// answer. + pub fn is_pool_exhausted(&self) -> bool { + matches!(self, Error::PoolExhausted(_)) + } /// True when a retry could plausibly help (§8.4): an unreachable upstream, a /// mirror that 5xx'd, a connection that reset. @@ -79,6 +103,9 @@ impl Error { pub fn is_transient(&self) -> bool { match self { Error::Http(_) | Error::Transient(_) => true, + // A quota is capacity, not a hiccup: retrying a build that has no + // sandbox just burns attempts. It blocks instead. + Error::PoolExhausted(_) | Error::WorldMismatch(_) => false, Error::Io(e) => matches!( e.kind(), std::io::ErrorKind::WouldBlock @@ -119,5 +146,9 @@ mod tests { assert!(Error::Http("connection reset".into()).is_transient()); assert!(!Error::invalid("recipe has no pkgbase").is_transient()); assert!(!Error::fail_closed("identity hash moved").is_transient()); + // A full pool waits; it does not retry. A lying world fails closed. + assert!(!Error::pool_exhausted("at quota").is_transient()); + assert!(!Error::world_mismatch("missing pinned dep").is_transient()); + assert!(Error::pool_exhausted("at quota").is_pool_exhausted()); } } diff --git a/src/pipeline/steps.rs b/src/pipeline/steps.rs index c989476..59c9a64 100644 --- a/src/pipeline/steps.rs +++ b/src/pipeline/steps.rs @@ -130,7 +130,10 @@ fn provision(ctx: &Ctx) -> Result { if lease.is_empty() { return Ok(StepResult::Skipped("no of-our-packages dependencies to install".into())); } - let sbx = ctx.sandbox()?; + let sbx = match sandbox_or_wait(ctx)? { + Some(s) => s, + None => return Ok(StepResult::Blocked(vec!["sandbox-pool".into()])), + }; for e in &lease { let path = ctx.cfg.store_path(&e.digest); // The hub hashes what it sends: store corruption is caught here, not @@ -149,7 +152,10 @@ fn provision(ctx: &Ctx) -> Result { argv.extend(lease.iter().map(|e| format!("blob:{}", e.digest))); let out = sbx.run(&Cmd::new(argv), &mut |_| {})?; if !out.success() { - return Err(Error::fail_closed(format!( + // A refused `-U` is almost always an incomplete closure: the lease set + // cannot satisfy itself. Its own error class, because "the sandbox + // lied about its world" must not look like "the sandbox broke". + return Err(Error::world_mismatch(format!( "{} -U refused the lease set: {}", ctx.cfg.pacman_bin, tail(&out.stderr) @@ -176,7 +182,7 @@ fn provision(ctx: &Ctx) -> Result { .collect(); for e in &lease { if !installed.contains(&(e.name.clone(), e.version.clone())) { - return Err(Error::fail_closed(format!( + return Err(Error::world_mismatch(format!( "sandbox world is missing {}-{} after installing the lease set", e.name, e.version ))); @@ -191,6 +197,22 @@ fn provision(ctx: &Ctx) -> Result { Ok(StepResult::Done(Some(crate::hash::canonical_json(&world)?))) } +/// Lease a sandbox for a step, or report that the pool cannot fit one right +/// now. A full pool is not a broken build: the build blocks and waits, the +/// same way it waits for a dependency it publishes (§10.4). +fn sandbox_or_wait( + ctx: &Ctx, +) -> Result>> { + match ctx.sandbox() { + Ok(s) => Ok(Some(s)), + Err(e) if e.is_pool_exhausted() => { + ctx.log_line(" blocked: no sandbox available in the pool"); + Ok(None) + } + Err(e) => Err(e), + } +} + /// One pinned entry of the lease manifest. #[derive(Debug, Clone)] struct LeasePkg { @@ -307,6 +329,10 @@ fn pkgver(ctx: &Ctx) -> Result { /// ingest signs hub-side. fn build(ctx: &Ctx) -> Result { let argv = vec![ctx.cfg.makepkg_bin.clone(), "-c".into(), "-f".into()]; + let sbx = match sandbox_or_wait(ctx)? { + Some(s) => s, + None => return Ok(StepResult::Blocked(vec!["sandbox-pool".into()])), + }; // Capture the child's output into the build log regardless of outcome — // the sandbox streams it here as it arrives, and the SSE tail reads the // same file. @@ -320,7 +346,6 @@ fn build(ctx: &Ctx) -> Result { let _ = f.write_all(bytes); } }; - let sbx = ctx.sandbox()?; let out = sbx.run(&Cmd::new(argv).in_dir(&ctx.srcdir), &mut on_log)?; drop(on_log); // closes the log file before the outcome is recorded if !out.success() { diff --git a/src/sandbox/kata.rs b/src/sandbox/kata.rs index 7a83f89..9592dca 100644 --- a/src/sandbox/kata.rs +++ b/src/sandbox/kata.rs @@ -324,7 +324,7 @@ impl SandboxBackend for KataBackend { Err(_) => { self.pending.lock().unwrap().remove(&id); let _ = self.provisioner.reclaim(&id); - return Err(Error::other(format!( + return Err(Error::pool_exhausted(format!( "sandbox {id} for profile {} never dialed in within its TTL", spec.profile ))); diff --git a/tests/failure_modes.rs b/tests/failure_modes.rs new file mode 100644 index 0000000..bea00a2 --- /dev/null +++ b/tests/failure_modes.rs @@ -0,0 +1,200 @@ +//! The failure-mode tier: a `FakeBackend` decorator that breaks sandboxes on +//! purpose, so the recovery paths are executed rather than described. Every +//! scenario runs rootless, offline, against the real step machine — the same +//! philosophy as the shims (§16a), one layer up. + +mod common; + +use std::sync::Arc; + +use aur_build::db::{self, builds, model::*}; +use aur_build::error::{Error, Result}; +use aur_build::pipeline::{self, Ctx}; +use aur_build::sandbox::loopback::LoopbackBackend; +use aur_build::sandbox::{Exit, Sandbox, SandboxBackend, SandboxInfo, SandboxSpec}; +use common::*; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Fault { + /// The sandbox vanishes while the build command is running — the shape of + /// a VM pulled out from under a worker. + DieMidRun, + /// The sandbox's own TTL bites mid-build. + TtlMidBuild, + /// The pool is at quota: no lease exists to hand out. + NoCapacity, + /// The sandbox installs the lease but its `pacman -Q` comes back empty — + /// an incomplete closure, or a world that lied. + EmptyWorld, +} + +struct FakeBackend { + cfg: aur_build::config::Config, + fault: Fault, +} + +impl SandboxBackend for FakeBackend { + fn acquire(&self, spec: &SandboxSpec) -> Result> { + if self.fault == Fault::NoCapacity { + return Err(Error::pool_exhausted("fake pool at quota")); + } + let inner = LoopbackBackend::new(&self.cfg).acquire(spec)?; + Ok(Arc::new(FakeSandbox { inner, fault: self.fault })) + } + fn status(&self) -> Result> { + Ok(vec![SandboxInfo { id: "fake".into(), profile: "fake".into(), warm: true }]) + } +} + +struct FakeSandbox { + inner: std::sync::Arc, + fault: Fault, +} + +impl FakeSandbox { + fn is_build(cmd: &aur_build::sandbox::Cmd) -> bool { + cmd.argv.first().is_some_and(|a| a.ends_with("makepkg")) + } + fn is_query(cmd: &aur_build::sandbox::Cmd) -> bool { + cmd.argv.get(1).is_some_and(|a| a == "-Q") + } +} + +impl Sandbox for FakeSandbox { + fn id(&self) -> &str { + self.inner.id() + } + fn run(&self, cmd: &aur_build::sandbox::Cmd, on_log: &mut dyn FnMut(&[u8])) -> Result { + match self.fault { + Fault::DieMidRun if Self::is_build(cmd) => { + Err(Error::other("sandbox vanished mid-run (connection reset)")) + } + Fault::TtlMidBuild if Self::is_build(cmd) => { + Err(Error::other("sandbox ttl expired during build")) + } + Fault::EmptyWorld if Self::is_query(cmd) => { + Ok(Exit { code: Some(0), stdout: Vec::new(), stderr: Vec::new() }) + } + _ => self.inner.run(cmd, on_log), + } + } + fn put(&self, digest: &str, r: &mut dyn std::io::Read) -> Result<()> { + self.inner.put(digest, r) + } + fn get(&self, digest: &str) -> Result> { + self.inner.get(digest) + } + fn destroy(&self) -> Result<()> { + self.inner.destroy() + } +} + +fn approve_and_enqueue(env: &Env, name: &str) -> String { + aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, name).unwrap(); + let c = aur_build::review::candidates::pending_candidates(&env.db).unwrap().remove(0); + let dd = aur_build::review::diff::render_and_store(&env.db, &env.cfg, &c).unwrap(); + aur_build::review::approve::approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap(); + let c = aur_build::review::candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap(); + pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap() +} + +fn run_with_fault(env: &Env, id: &str, fault: Fault) -> pipeline::Outcome { + let mut ctx = Ctx::new(&env.cfg, &env.db, id).unwrap(); + ctx.backend = Arc::new(FakeBackend { cfg: env.cfg.clone(), fault }); + pipeline::run_with(&ctx).unwrap() +} + +#[test] +fn a_sandbox_that_dies_mid_run_expires_its_lease_and_the_requeue_finishes_the_build() { + // I5 across the sandbox boundary: the box vanishes mid-build, the build + // fails its step, the lease expires, and a fresh worker resumes from the + // checkpoints with a healthy pool. + let (env, _fx) = env_with_fixture("plain-make"); + let id = approve_and_enqueue(&env, "plain-make"); + + match run_with_fault(&env, &id, Fault::DieMidRun) { + pipeline::Outcome::Failed { step, error, .. } => { + assert_eq!(step, "build"); + assert!(error.contains("vanished"), "{error}"); + } + other => panic!("{other:?}"), + } + + // The crash shape the dispatcher reaper knows: leased to a worker that is + // gone, with a lease nobody will extend. + env.exec( + "UPDATE build SET state='leased', lease_owner='dead-worker', + lease_expires_at='2000-01-01T00:00:00Z' WHERE id=?1", + ¶ms(vec![id.as_str()]), + ); + assert_eq!(builds::reap_expired(&env.db).unwrap(), 1); + + // Requeue and resume on a healthy pool: the completed steps do not re-run + // and the build lands. + assert!(matches!( + pipeline::run(&env.cfg, &env.db, &id).unwrap(), + pipeline::Outcome::Succeeded { .. } + )); + assert_eq!(db::index_version(&env.db, "plain-make").unwrap().as_deref(), Some("1.0-1")); +} + +#[test] +fn a_ttl_that_bites_mid_build_is_a_failed_step_not_a_lost_build() { + let (env, _fx) = env_with_fixture("plain-make"); + let id = approve_and_enqueue(&env, "plain-make"); + match run_with_fault(&env, &id, Fault::TtlMidBuild) { + pipeline::Outcome::Failed { step, error, transient } => { + assert_eq!(step, "build"); + assert!(error.contains("ttl expired"), "{error}"); + assert!(!transient, "a sandbox TTL is deterministic; do not retry-burn it"); + } + other => panic!("{other:?}"), + } + // Nothing was published, and the approval is still there to resume from. + assert!(db::accepted_release(&env.db, "plain-make").unwrap().is_none()); +} + +#[test] +fn a_full_pool_blocks_the_build_instead_of_breaking_it() { + let (env, _fx) = env_with_fixture("plain-make"); + let id = approve_and_enqueue(&env, "plain-make"); + match run_with_fault(&env, &id, Fault::NoCapacity) { + pipeline::Outcome::Blocked { on } => { + assert_eq!(on, vec!["sandbox-pool".to_string()]); + } + other => panic!("a quota is a wait, not a failure: {other:?}"), + } + let b = builds::get(&env.db, &id).unwrap().unwrap(); + assert_eq!( + b.state, + BuildState::BlockedMissingDep, + "the build waits for capacity on the same blocked machinery it uses for missing deps, unharmed" + ); + assert_eq!( + b.blocked_on_json.as_str(), + r#"["sandbox-pool"]"#, + "the block names what it waits on" + ); +} + +#[test] +fn an_incomplete_closure_fails_closed_as_a_world_mismatch() { + // dep-client's lease pins plain-make; the fake sandbox installs it but + // its `pacman -Q` comes back empty — the world lied. Provisioning must + // refuse with its own error class, not build against a world that is + // not the one the plan approved. + let (env, _plain, _client) = env_with_two_fixtures("plain-make", "dep-client"); + let id = approve_and_enqueue(&env, "plain-make"); + assert!(matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Succeeded { .. })); + + let id2 = approve_and_enqueue(&env, "dep-client"); + match run_with_fault(&env, &id2, Fault::EmptyWorld) { + pipeline::Outcome::Failed { step, error, transient } => { + assert_eq!(step, "chroot", "provisioning is where a lying world gets caught"); + assert!(error.contains("world is missing plain-make"), "{error}"); + assert!(!transient, "a mismatched world is fail-closed, never retried"); + } + other => panic!("{other:?}"), + } + assert!(db::accepted_release(&env.db, "dep-client").unwrap().is_none()); +} -- cgit v1.2.3