summaryrefslogtreecommitdiffstats
path: root/tests/dispatch.rs
diff options
context:
space:
mode:
Diffstat (limited to 'tests/dispatch.rs')
-rw-r--r--tests/dispatch.rs281
1 files changed, 281 insertions, 0 deletions
diff --git a/tests/dispatch.rs b/tests/dispatch.rs
new file mode 100644
index 0000000..c70dd6b
--- /dev/null
+++ b/tests/dispatch.rs
@@ -0,0 +1,281 @@
+//! The dispatcher, the worker pool and the reaper (§8.2), plus the retry policy
+//! (§8.4). These drive the real threads and the real claim transaction — the
+//! crash-recovery claims in §2 are only worth anything if the lease machinery is
+//! actually exercised, not asserted in a comment.
+
+mod common;
+
+use std::sync::atomic::AtomicBool;
+use std::sync::Arc;
+
+use aur_build::config::Config;
+use aur_build::db::{self, builds, model::*};
+use aur_build::pipeline::{self, dispatch};
+use aur_build::review::{candidates, diff};
+use common::*;
+
+/// Approve a fixture's candidate and enqueue its build without running it.
+fn queued_build(env: &Env, name: &str) -> String {
+ aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, name).unwrap();
+ let c = candidates::pending_candidates(&env.db).unwrap().remove(0);
+ let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap();
+ let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
+ aur_build::review::approve::approve(&env.db, "t", c.id, &c.identity_hash, &dd, None).unwrap();
+ let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
+ pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap()
+}
+
+fn pass(env: &Env) -> Vec<String> {
+ let (tx, _rx) = crossbeam_channel::bounded::<String>(8);
+ dispatch::dispatch_once(&env.cfg, &env.db, &tx)
+}
+
+#[test]
+fn the_deterministic_build_id_makes_re_enqueue_a_noop() {
+ // §8.2: re-submitting the same intent is an INSERT OR IGNORE no-op, which is
+ // what makes a careless "rebuild that again" harmless.
+ let (env, _fx) = env_with_fixture("plain-make");
+ aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap();
+ let c = candidates::pending_candidates(&env.db).unwrap().remove(0);
+ let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap();
+ let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
+ aur_build::review::approve::approve(&env.db, "t", c.id, &c.identity_hash, &dd, None).unwrap();
+ let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
+ let first = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
+ let again = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
+ assert_eq!(first, again, "the same intent produced two build ids");
+ assert_eq!(env.query_i64("SELECT count(*) FROM build", &[]), Some(1));
+}
+
+#[test]
+fn backpressure_admits_no_more_than_max_concurrent_builds() {
+ let (mut env, _plain, _client) = env_with_two_fixtures("plain-make", "dep-client");
+ env.cfg.max_concurrent_builds = 1;
+ let a = queued_build(&env, "plain-make");
+ let b = queued_build(&env, "dep-client");
+ assert_ne!(a, b);
+
+ let claimed = pass(&env);
+ assert_eq!(claimed.len(), 1, "one slot must admit exactly one build");
+ // The dispatcher will not run ahead into the second slot while the first is
+ // still in flight.
+ assert_eq!(pass(&env).len(), 0, "admitted a second build while one is in flight");
+ assert_eq!(env.query_i64("SELECT count(*) FROM build WHERE state='leased'", &[]), Some(1));
+ assert_eq!(env.query_i64("SELECT count(*) FROM build WHERE state='queued'", &[]), Some(1));
+
+ // Widen the pool and the second one goes.
+ env.cfg.max_concurrent_builds = 2;
+ assert_eq!(pass(&env).len(), 1);
+}
+
+#[test]
+fn disk_headroom_is_part_of_backpressure() {
+ let (mut env, _fx) = env_with_fixture("plain-make");
+ queued_build(&env, "plain-make");
+ // Ask for more free space than any machine has: nothing is admitted. A build
+ // that cannot fit on disk stays queued instead of filling the filesystem
+ // halfway through a compile (§8.2).
+ env.cfg.min_free_disk_mb = u64::MAX / 2;
+ assert_eq!(dispatch::admissible(&env.cfg, &env.db), 0);
+ assert!(pass(&env).is_empty(), "claimed a build with no disk headroom");
+ assert_eq!(env.query_i64("SELECT count(*) FROM build WHERE state='queued'", &[]), Some(1));
+ // And the measurement itself is real, not a stub returning zero.
+ env.cfg.min_free_disk_mb = 1;
+ assert!(dispatch::free_disk_mb(&env.cfg.root) > 0, "free_disk_mb never measures anything");
+ assert_eq!(dispatch::admissible(&env.cfg, &env.db), 1);
+}
+
+#[test]
+fn an_expired_lease_is_requeued_and_its_running_step_marked_interrupted() {
+ // The reaper pass is the whole crash-recovery story: a worker that died
+ // mid-step leaves a leased row and a running step, and the next pass turns
+ // that back into queued + interrupted so the checkpoint decides where it
+ // resumes (I5).
+ let (env, _fx) = env_with_fixture("plain-make");
+ let id = queued_build(&env, "plain-make");
+ assert_eq!(pass(&env), vec![id.clone()]);
+ builds::begin_step(&env.db, &id, "build", 1).unwrap();
+ assert_eq!(builds::step_status(&env.db, &id, "build").unwrap().as_deref(), Some("running"));
+
+ // Time passes — the lease expires, as it would if the process were killed.
+ env.exec("UPDATE build SET lease_expires_at='2000-01-01T00:00:00Z'", &[]);
+
+ // A fresh dispatcher (as after a restart) reaps it before claiming anything.
+ let reaped = builds::reap_expired(&env.db).unwrap();
+ assert_eq!(reaped, 1, "the expired lease was not requeued");
+ assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, build_state::QUEUED);
+ assert_eq!(
+ builds::step_status(&env.db, &id, "build").unwrap().as_deref(),
+ Some("interrupted"),
+ "the in-flight step was not marked interrupted"
+ );
+ // And it is claimable again.
+ assert_eq!(pass(&env), vec![id.clone()]);
+ assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().attempt, 2, "the retry was not counted");
+}
+
+#[test]
+fn a_newer_approval_cancels_an_in_flight_build_at_the_step_boundary() {
+ // §8.2 cancellation: a superseded candidate marks the running build
+ // cancel_requested; the worker stops at the next boundary rather than
+ // finishing work nobody asked for.
+ let (env, _fx) = env_with_fixture("plain-make");
+ let id = queued_build(&env, "plain-make");
+ pass(&env);
+ assert!(!builds::cancel_requested(&env.db, &id).unwrap());
+ env.exec("UPDATE candidate SET state='superseded' WHERE id=(SELECT candidate_id FROM build WHERE id=?1)", &params(vec![id.as_str()]));
+ assert_eq!(builds::cancel_superseded(&env.db).unwrap(), 1);
+ assert!(builds::cancel_requested(&env.db, &id).unwrap());
+ // run() honours it at the step boundary rather than mid-step.
+ let out = pipeline::run(&env.cfg, &env.db, &id).unwrap();
+ assert!(matches!(out, pipeline::Outcome::Cancelled), "run ignored the cancellation");
+ assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, build_state::CANCELLED);
+}
+
+#[test]
+fn a_deterministic_build_failure_is_not_retried() {
+ // §8.4: a build that fails for a deterministic reason stays failed at
+ // attempt 1. Burning another chroot to reproduce the same failure helps
+ // nobody; the release stays approved_but_unbuilt and the UI says so.
+ let (env, _fx) = env_with_fixture("build-fails");
+ let id = queued_build(&env, "build-fails");
+ let pool = dispatch::Pool::spawn(Arc::new(env.cfg.clone()), env.db.clone());
+ let state = wait_for(&env, &id, &["failed", "succeeded"]);
+ pool.shutdown();
+ assert_eq!(state, build_state::FAILED, "a deterministic failure should not succeed");
+ let b = builds::get(&env.db, &id).unwrap().unwrap();
+ assert_eq!(b.attempt, 1, "a deterministic failure must not be retried");
+ assert!(b.error.unwrap_or_default().contains("build"), "no step named in the error");
+ // And the old version keeps looking served: nothing was published.
+ assert_eq!(db::index_version(&env.db, "build-fails").unwrap(), None);
+}
+
+#[test]
+fn a_transient_failure_is_retried_up_to_the_cap() {
+ // §8.4: transient failures (network, mirror 5xx) retry with a bounded
+ // number of attempts. Here the toolchain itself is missing, which surfaces
+ // as an IO error — the same class as a flaky mirror.
+ let (mut env, _fx) = env_with_fixture("plain-make");
+ let id = queued_build(&env, "plain-make");
+ env.cfg.makechrootpkg_bin = "/nonexistent/makechrootpkg-for-test".into();
+ env.cfg.max_transient_attempts = 3;
+ env.cfg.dispatch_tick_secs = 0;
+ let pool = dispatch::Pool::spawn(Arc::new(env.cfg.clone()), env.db.clone());
+ // The state flickers to 'failed' between retries; what settles is the
+ // attempt count reaching the cap with the build left failed.
+ let b = wait_attempt(&env, &id, 3);
+ pool.shutdown();
+ assert_eq!(b.state, build_state::FAILED);
+ assert_eq!(b.attempt, 3, "a transient failure should retry up to the cap");
+}
+
+#[test]
+fn the_pool_takes_a_queued_build_all_the_way_to_publication() {
+ // The threads, not a test calling run() directly: dispatcher claims, worker
+ // runs the ten steps, publish lands the release.
+ let (env, _fx) = env_with_fixture("plain-make");
+ let id = queued_build(&env, "plain-make");
+ let cfg = Arc::new(env.cfg.clone());
+ let pool = dispatch::Pool::spawn(cfg, env.db.clone());
+ let state = wait_for(&env, &id, &["succeeded", "failed"]);
+ pool.shutdown();
+ assert_eq!(state, build_state::SUCCEEDED, "the pool did not finish the build");
+ assert!(db::accepted_release(&env.db, "plain-make").unwrap().is_some(), "nothing was published");
+ assert_eq!(db::index_version(&env.db, "plain-make").unwrap().as_deref(), Some("1.0-1"));
+}
+
+#[test]
+fn a_reaped_build_resumes_at_the_next_incomplete_step_with_no_duplicate_work() {
+ // I5 through the dispatcher rather than a direct run(): a build that dies
+ // late is requeued, re-claimed, and finishes from its checkpoints — the
+ // expensive steps are not done again.
+ let (mut env, fx) = env_with_fixture("plain-make");
+ let c = queued_candidate(&env, "plain-make");
+ let first = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap();
+ pipeline::run(&env.cfg, &env.db, &first).unwrap();
+
+ fx.bump(&[("pkgver", "1.0.1")]);
+ let c2 = queued_candidate(&env, "plain-make");
+ let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c2).unwrap();
+ env.set_publish_fault("before-rename");
+ assert!(matches!(
+ pipeline::run(&env.cfg, &env.db, &id).unwrap(),
+ pipeline::Outcome::Failed { .. }
+ ));
+ let builds_before = aur_build::shims::called_with(&env.cfg.shim_dir.clone().unwrap(), "makechrootpkg", "");
+
+ // The worker "died" at publish: the row is leased with a lease nobody will
+ // extend. A fresh dispatcher reaps it and a worker finishes from the
+ // checkpoints.
+ env.clear_publish_fault();
+ // The crash shape: the row is leased to a worker that is no longer running,
+ // with a lease nobody will extend. A fresh dispatcher reaps it and a worker
+ // finishes from the checkpoints.
+ env.exec(
+ "UPDATE build SET state='leased', lease_owner='dead-worker',
+ lease_expires_at='2000-01-01T00:00:00Z' WHERE id=?1",
+ &params(vec![id.as_str()]),
+ );
+
+ let pool = dispatch::Pool::spawn(Arc::new(env.cfg.clone()), env.db.clone());
+ let state = wait_for(&env, &id, &["succeeded", "failed"]);
+ pool.shutdown();
+ assert_eq!(state, build_state::SUCCEEDED, "the resumed build did not finish");
+
+ assert_eq!(
+ aur_build::shims::called_with(&env.cfg.shim_dir.clone().unwrap(), "makechrootpkg", ""),
+ builds_before,
+ "I5: resuming must not rebuild"
+ );
+ let steps = builds::steps(&env.db, &id).unwrap();
+ let done = steps
+ .iter()
+ .filter(|s| s.status == step_state::SUCCEEDED || s.status == step_state::SKIPPED)
+ .count();
+ assert_eq!(done, BUILD_STEPS.len(), "not every step ended succeeded or skipped: {steps:?}");
+ assert_eq!(
+ env.query_i64("SELECT count(*) FROM release WHERE pkgver='1.0.1'", &[]),
+ Some(1),
+ "the resume published twice"
+ );
+ assert_eq!(db::index_version(&env.db, "plain-make").unwrap().as_deref(), Some("1.0.1-1"));
+}
+
+/// Approve a fixture's candidate and hand back the approved row.
+fn queued_candidate(env: &Env, name: &str) -> CandidateRow {
+ aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, name).unwrap();
+ let c = candidates::pending_candidates(&env.db).unwrap().remove(0);
+ let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap();
+ let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap();
+ aur_build::review::approve::approve(&env.db, "t", c.id, &c.identity_hash, &dd, None).unwrap();
+ candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap()
+}
+
+/// Poll until the build has been attempted `n` times and settled.
+fn wait_attempt(env: &Env, id: &str, n: i64) -> builds::BuildRow {
+ for _ in 0..600 {
+ if let Some(b) = builds::get(&env.db, id).unwrap() {
+ if b.attempt >= n && b.state == build_state::FAILED {
+ return b;
+ }
+ }
+ std::thread::sleep(std::time::Duration::from_millis(50));
+ }
+ panic!("build {id} never reached {n} attempts in state failed");
+}
+
+/// Poll until the build reaches one of `want` (or the test gives up).
+fn wait_for(env: &Env, id: &str, want: &[&str]) -> String {
+ for _ in 0..600 {
+ if let Some(b) = builds::get(&env.db, id).unwrap() {
+ if want.contains(&b.state.as_str()) {
+ return b.state;
+ }
+ }
+ std::thread::sleep(std::time::Duration::from_millis(50));
+ }
+ panic!("build {id} never reached {want:?}");
+}
+
+#[allow(dead_code)]
+fn unused(_: AtomicBool, _: Config) {}