From e757979f1a2afdbe7146066345bb9acd19d3b151 Mon Sep 17 00:00:00 2001 From: aur-build Date: Thu, 19 Nov 2026 17:09:59 +0000 Subject: comments: say why, not what MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every module-level `//!` header is gone, and the comments that remained either re-explained the line below them or had grown into paragraphs. Density went from one comment line per 6.7 lines of code to one per 10. 827 insertions against 2194 deletions across 86 files. What survived: the invariants (I1-I12), the design cross-references into DESIGN.md, and the notes recording a bug that was found and fixed — those are the comments that carry weight, because they answer a question the code cannot answer about itself. What did not: restating a function signature in prose, and narration of the statement underneath. --- tests/approve.rs | 37 +++++++++----------------- tests/common/mod.rs | 53 ++++++++++++++++--------------------- tests/config.rs | 64 ++++++++++++++------------------------------- tests/crash.rs | 24 +++++------------ tests/db.rs | 9 +------ tests/detect.rs | 13 +++------ tests/dispatch.rs | 50 ++++++++++++----------------------- tests/failure_modes.rs | 23 +++++----------- tests/hash.rs | 22 +++++----------- tests/http.rs | 39 +++++++++------------------ tests/invariants.rs | 41 ++++++++--------------------- tests/kata.rs | 37 +++++++------------------- tests/layers.rs | 22 ++++------------ tests/live.rs | 31 ++++++++-------------- tests/notices.rs | 17 +++--------- tests/ops.rs | 50 ++++++++++++----------------------- tests/pipeline.rs | 55 +++++++++++++++----------------------- tests/production_surface.rs | 36 ++++++------------------- tests/remote_agent.rs | 40 +++++++++------------------- tests/schema_ownership.rs | 20 +++----------- tests/shims.rs | 50 ++++++++++++----------------------- tests/staleness.rs | 28 ++++++-------------- tests/state_machine.rs | 51 ++++++++++++++---------------------- tests/surfaces.rs | 5 ---- tests/time.rs | 9 +++---- tests/vcs.rs | 45 ++++++++++++------------------- tests/versions.rs | 60 ++++++++++++------------------------------ tests/world.rs | 25 ++++-------------- 28 files changed, 296 insertions(+), 660 deletions(-) (limited to 'tests') diff --git a/tests/approve.rs b/tests/approve.rs index f1fc762..86dcf46 100644 --- a/tests/approve.rs +++ b/tests/approve.rs @@ -1,9 +1,3 @@ -//! Approval semantics (§7.1, §7.1a, §7.2) and the CLI approval path (P0). -//! -//! The rule these tests exist to protect: **we build exactly what was displayed, -//! or nothing.** An approval that does not match the hashes of what the reviewer -//! was shown is refused, never retargeted. - mod common; use aur_build::db::model::*; @@ -111,13 +105,12 @@ fn approving_twice_is_refused_not_duplicated() { fn a_broken_database_is_not_reported_as_a_stale_review() { // What this pins: every failure inside the approval transaction used to be // mapped into `Stale::NotPending`, so a SQLite error reached the reviewer as - // "review is no longer pending (state: sqlite: …)" — the one message that - // tells them to look again when the truth is that the write failed (§6 M-3). + // "review is no longer pending" — the one message telling them to look again + // when the truth is that the write failed (§6 M-3). let (env, _fx) = env_with_fixture("plain-make"); let (c, dd) = open_review(&env, "plain-make"); - // Make the write impossible halfway through the transaction: the approval - // row and the candidate update succeed, then the audit append has nowhere - // to go. + // Make the write impossible halfway through: the approval row and the + // candidate update succeed, then the audit append has nowhere to go. env.exec("DROP TABLE audit", &[]); let err = approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap_err(); assert!(matches!(err, ApproveError::System(_)), "a broken database was reported as a stale review: {err:?}"); @@ -131,8 +124,7 @@ fn a_broken_database_is_not_reported_as_a_stale_review() { #[test] fn bulk_refusals_are_their_own_reasons() { // Bulk used to bend `Stale::NotPending` into "high risk", "unknown decision" - // and "the database failed", and to hand back a fabricated `Approval { id: 0 }` - // for a rejection that recorded no approval at all (§6 M-3). + // and "the database failed" (§6 M-3). let (env, _fx) = env_with_fixture("plain-make"); let (c, dd) = open_review(&env, "plain-make"); candidates::set_risk(&env.db, c.id, "high", &["new source host".into()]).unwrap(); @@ -168,8 +160,7 @@ fn a_bulk_rejection_hands_back_no_invented_approval() { let (c, dd) = open_review(&env, "plain-make"); let out = bulk(&env.db, "tester", &[(c.id, c.identity_hash.clone(), dd)], "reject", &[]).unwrap(); assert!(matches!(out[0].outcome, BulkOutcome::Rejected), "{:?}", out[0].outcome); - // A rejection records a `rejected` row; there is no approval to return, and - // the old `Approval { id: 0 }` sentinel is gone. + // A rejection records a `rejected` row; there is no approval to return. assert_eq!(env.query_i64("SELECT count(*) FROM approval WHERE decision='rejected'", &[]), Some(1)); assert_eq!(env.query_i64("SELECT count(*) FROM approval WHERE decision='approved'", &[]), Some(0)); } @@ -209,8 +200,8 @@ fn once_viewed_a_new_state_freezes_the_old_one_as_superseded() { assert_ne!(open[0].id, c.id, "a fresh review was opened"); let frozen = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap(); assert_eq!(frozen.state, CandidateState::Superseded); - // The frozen one can no longer be approved: approving it would build a - // version nobody is looking at. + // The frozen one can no longer be approved: approving it would build a version + // nobody is looking at. let err = approve(&env.db, "tester", c.id, &frozen.identity_hash, &frozen.diff_digest, None).unwrap_err(); assert!(matches!(err, ApproveError::Stale(Stale::NotPending { .. })), "{err:?}"); } @@ -246,9 +237,7 @@ fn reject_requires_a_reason_and_records_it() { .unwrap(); assert!(note.contains("license"), "{note}"); - // And the audit row says *which review* was rejected, not only why (§6 m-4): - // the three review actions each hand-built their own `detail`, and two of - // them recorded no identity at all. + // And the audit row says *which review* was rejected, not only why (§6 m-4). let (actor_kind, detail): (String, String) = env .db .read(|c| { @@ -268,8 +257,8 @@ fn reject_requires_a_reason_and_records_it() { // ------------------------------------------------------------- the CLI path -- -/// Drive the real binary the way an operator would. This is the P0 approval -/// path: `init`, `subscribe`, `detect`, `show`, `approve --yes`. +/// Drive the real binary the way an operator would: `init`, `subscribe`, +/// `detect`, `show`, `approve --yes`. #[test] fn cli_end_to_end_approves_and_queues_a_build() { let tmp = tempfile::tempdir().unwrap(); @@ -291,8 +280,8 @@ fn cli_end_to_end_approves_and_queues_a_build() { let out = cli(bin, &root, &["reviews"]); assert!(out.stdout.contains("#1"), "reviews: {}", out.stdout); - // `show` renders the panels and the hashes; `approve` without --yes refuses - // to act, which is the CLI's version of "look before you approve". + // `show` renders the panels and the hashes; `approve` without --yes refuses to + // act. let out = cli(bin, &root, &["show", "1"]); assert!(out.stdout.contains("identity_hash"), "show: {}", out.stdout); let shown = out.stdout.clone(); diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 426f44d..b1a50ac 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -1,6 +1,3 @@ -//! Shared test scaffolding: an isolated server root in a tempdir with a migrated -//! database and a running writer actor. - #![allow(dead_code)] use std::path::{Path, PathBuf}; @@ -78,8 +75,7 @@ impl Env { } /// Stand in for the build+publish path: turn an approved candidate into a - /// published release and move the accepted pointer. The real path lives in - /// `pipeline`; detection tests need an accepted base without a build. + /// published release and move the accepted pointer. pub fn accept_as_release(&self, candidate_id: i64) -> i64 { let at = "2026-01-01T00:00:00Z"; self.db @@ -227,9 +223,9 @@ pub fn shim_dir() -> PathBuf { .to_path_buf() } -/// An environment wired to one corpus fixture: the fixture is committed into a -/// real git repo standing in for AUR, an optional local upstream git repo exists -/// for VCS sources, and the shims are told to obey the fixture manifest. +/// An environment wired to one corpus fixture: the fixture is committed into a real +/// git repo standing in for AUR, an optional local upstream git repo exists for VCS +/// sources, and the shims obey the fixture manifest. pub fn env_with_fixture(name: &str) -> (Env, Fixture) { let tmp = tempfile::tempdir().expect("tempdir"); let fx = materialize_fixture(tmp.path(), name); @@ -252,8 +248,7 @@ pub fn env_with_fixture(name: &str) -> (Env, Fixture) { } /// Two fixtures sharing one server root, so a test can talk about packages that -/// depend on each other. The second fixture's manifest wins for the shim, which -/// is what you want when the second one is the dependent. +/// depend on each other. pub fn env_with_two_fixtures(a: &str, b: &str) -> (Env, Fixture, Fixture) { let tmp = tempfile::tempdir().expect("tempdir"); let fa = materialize_fixture(tmp.path(), a); @@ -277,17 +272,17 @@ pub fn env_with_two_fixtures(a: &str, b: &str) -> (Env, Fixture, Fixture) { (env, fa, fb) } -/// Copy a corpus fixture into a server root: recipe files into a git repo that -/// stands in for AUR, payload files beside it so their bytes can be swapped, -/// and a local upstream repo when the recipe references one. +/// Copy a corpus fixture into a server root: recipe files into a git repo standing +/// in for AUR, payload files beside it so their bytes can be swapped, and a local +/// upstream repo when the recipe references one. pub fn materialize_fixture(root: &Path, name: &str) -> Fixture { let src = corpus_root().join(name); assert!(src.exists(), "no fixture {name} in {}", corpus_root().display()); let manifest = root.join("manifest.json"); std::fs::copy(src.join("manifest.json"), &manifest).expect("copy manifest"); - // Data files that a source URL points at live outside the recipe so a test - // can swap their bytes (the digest-drift case) without touching git. + // Data files a source URL points at live outside the recipe so a test can swap + // their bytes (the digest-drift case) without touching git. let data = root.join(format!("fixture/{name}")); std::fs::create_dir_all(&data).unwrap(); let aur = root.join(format!("aur/{name}.git")); @@ -473,8 +468,8 @@ pub fn git(dir: &Path, args: &[&str]) -> String { // ------------------------------------------------------------- web driver -- -/// A tiny HTTP client for the surface tests: keeps the session cookie and the -/// CSRF token, and hands back status + body. +/// A tiny HTTP client for the surface tests: keeps the session cookie and the CSRF +/// token, and hands back status + body. pub struct Web { pub env: Env, pub fx: Fixture, @@ -526,8 +521,8 @@ impl Web { aur_build::review::candidates::candidate_by_id(&self.env.db, c.id).unwrap().unwrap() } - /// Approve through the library and run the build to publication, so a test - /// can talk about "what the index serves" without re-implementing P0. + /// Approve through the library and run the build to publication, so a test can + /// talk about "what the index serves". pub fn publish(&self, name: &str) { let c = self.open_review(name); aur_build::review::approve::approve(&self.env.db, "test", c.id, &c.identity_hash, &c.diff_digest, None) @@ -550,8 +545,8 @@ impl Web { }; let cookie = r.header("set-cookie").map(|s| s.to_string()).unwrap_or_default(); let mut headers = vec![("set-cookie".to_string(), cookie)]; - // ureq 2 will not hand out the whole header map, but it will answer for a - // named one, which is all the assertions below need. + // ureq 2 will not hand out the whole header map, but it answers for a named + // one, which is all the assertions below need. for name in ["content-type", "content-encoding", "location"] { if let Some(v) = r.header(name) { headers.push((name.to_string(), v.to_string())); @@ -577,10 +572,9 @@ impl Web { self.finish(resp, path) } - /// Send a request over a bare socket: no cookie jar, no redirect following, - /// so the test sees the 303 a browser would have swallowed. The session - /// gate is only meaningful at this level — a client that follows redirects - /// turns "you are not signed in" into the login page's 200. + /// Send a request over a bare socket: no cookie jar, no redirect following, so + /// the test sees the 303 a browser would have swallowed. The session gate is + /// only meaningful at this level. pub fn raw_request(&self, method: &str, path: &str, headers: &[(&str, String)], body: Option<&str>) -> Raw { use std::io::{Read, Write}; let addr = self.server.addr.clone(); @@ -604,9 +598,8 @@ impl Web { Raw::parse(&raw) } - /// Log in and adopt the session cookie the server issued, refreshing the - /// CSRF token with it — the token is derived from the sid, so a login that - /// rotates the session invalidates the one captured before it. + /// Log in and adopt the session cookie the server issued, refreshing the CSRF + /// token with it — the token is derived from the sid. pub fn login(&mut self, password: &str) -> Raw { let raw = self.raw_request("POST", "/login", &[], Some(&format!("password={}", url_encode(password)))); if let Some(cookie) = raw.cookie() { @@ -673,8 +666,8 @@ fn url_encode(s: &str) -> String { .collect() } -/// Pull an attribute or meta value out of rendered HTML and undo the escaping -/// the templates applied — a page is the contract here, so we read it as one. +/// Pull an attribute or meta value out of rendered HTML and undo the escaping the +/// templates applied — a page is the contract here, so we read it as one. pub fn extract(hay: &str, open: &str, close: &str) -> Option { let i = hay.find(open)? + open.len(); let rest = &hay[i..]; diff --git a/tests/config.rs b/tests/config.rs index 20010a7..3737045 100644 --- a/tests/config.rs +++ b/tests/config.rs @@ -1,21 +1,10 @@ -//! The server root: one directory, named once. -//! -//! `--root` selects the directory and `config.json` lives inside it, so the root -//! *is* wherever the config was found; the `root` field in the file is a record -//! of that, not a second knob. Re-joining a relative field onto the config's own -//! directory is what made `--root runtime` become `runtime/runtime/…`: `init` -//! created and migrated one tree, and every command after it ran against a -//! second one with its own empty database. - use std::path::{Path, PathBuf}; use std::process::Command; use aur_build::config::Config; /// The exact shape of the bug: a relative `--root`, saved verbatim, read back by -/// the next command. Relative to the crate root here, which is the cwd cargo -/// gives a test — the same situation as running `--root runtime` from a directory -/// that is not `/`. +/// the next command. #[test] fn a_relative_root_is_absolutized_once_and_never_doubled() { let rel = PathBuf::from("target").join("config-root-test").join("runtime"); @@ -47,8 +36,8 @@ fn a_relative_root_is_absolutized_once_and_never_doubled() { std::fs::remove_dir_all(&rel).unwrap(); } -/// The legacy shape on disk: a config written by an `init` that saved -/// `--root runtime` verbatim. Loading it must not resurrect the doubled tree. +/// The legacy shape on disk: a config written by an `init` that saved `--root +/// runtime` verbatim. Loading it must not resurrect the doubled tree. #[test] fn a_stale_relative_root_in_the_file_is_ignored() { let tmp = tempfile::tempdir().unwrap(); @@ -72,9 +61,8 @@ fn a_root_with_no_config_is_an_error_not_a_fresh_server() { ); } -/// The CLI half of the same rule. The old fallback invented a default config for -/// *any* command, so a typo'd `--root` quietly produced an empty server whose -/// commands reported success against a database with nothing in it. +/// The CLI half of the same rule: the old fallback invented a default config for +/// *any* command, so a typo'd `--root` quietly produced an empty server. #[test] fn the_cli_refuses_a_root_that_was_never_initialized() { let tmp = tempfile::tempdir().unwrap(); @@ -95,8 +83,7 @@ fn the_cli_refuses_a_root_that_was_never_initialized() { assert!(err.contains("init"), "{err}"); } -/// …and `init` is still allowed to run where there is no config yet, which is the -/// only reason the fallback existed. +/// …and `init` is still allowed to run where there is no config yet. #[test] fn init_still_runs_where_there_is_no_config_yet() { let tmp = tempfile::tempdir().unwrap(); @@ -133,15 +120,9 @@ fn an_absolute_root_is_used_verbatim() { assert_eq!(Config::load(dir).unwrap().root, dir); } -// --------------------------------------------------------------------------- -// The sandbox configuration: three kinds, and only three. -// -// This used to be `sandbox_backend: String` matched with a `_ =>` arm that -// produced loopback, so `"kata"` — a real, intended backend — silently meant -// "run the untrusted PKGBUILD as the hub's own user". The kinds are an enum -// now, so the invalid configurations do not parse, and the error says which -// field or which value was wrong. -// --------------------------------------------------------------------------- +// The sandbox configuration: three kinds, and only three. The kinds are an enum +// now, so a configuration that would silently mean "run the untrusted PKGBUILD as +// the hub's own user" does not parse. /// Write a config carrying exactly this `sandbox` value and load it. fn load_sandbox(sandbox: &str) -> Result { @@ -244,7 +225,7 @@ fn an_unknown_kind_names_the_value_and_the_valid_set() { #[test] fn a_config_with_no_sandbox_object_is_the_local_backend() { // The contract with every config.json already on disk: saying nothing means - // loopback, exactly as before. + // loopback. let cfg = load_raw("{\n \"repo_name\": \"aur\"\n}\n").unwrap(); assert!(matches!(cfg.sandbox, aur_build::config::Sandbox::Loopback)); assert_eq!(cfg.repo_name, "aur", "the rest of the config is untouched"); @@ -252,10 +233,8 @@ fn a_config_with_no_sandbox_object_is_the_local_backend() { assert!(cfg.sandbox.shared_workspace(), "loopback shares the filesystem by construction"); } -/// The file an older `aur-build init` wrote, verbatim. It carries the retired -/// keys, but they say `loopback` and three empty strings — which is what the -/// default already means — so it must still load rather than strand a working -/// local deployment on a syntax change. +/// The file an older `aur-build init` wrote, verbatim. It carries the retired keys, +/// but they say what the default already means, so it must still load. #[test] fn a_config_init_wrote_before_the_enum_still_loads() { let cfg = load_raw( @@ -290,9 +269,8 @@ fn a_config_init_wrote_before_the_enum_still_loads() { assert_eq!(cfg.lease_secs, 90); } -/// …but retired keys that *would* have changed behaviour are refused, not -/// quietly reinterpreted. A retired `"remote"` becoming loopback is the exact -/// silent substitution the enum was introduced to make impossible. +/// …but retired keys that *would* have changed behaviour are refused, not quietly +/// reinterpreted. #[test] fn retired_sandbox_keys_that_mean_something_are_refused() { let err = load_raw(r#"{ "sandbox_backend": "remote", "agent_listen": "0.0.0.0:1", "agent_token": "t" }"#) @@ -323,11 +301,9 @@ fn the_rendezvous_secrets_never_reach_debug() { assert!(shown.contains("builds"), "the non-secret fields are still visible: {shown}"); } -// --------------------------------------------------------------------------- -// The startup guard. The enum makes the impossible unrepresentable; this -// refuses what a type cannot see — a field present but empty, and a remote -// backend that was never told the workspace is shared. -// --------------------------------------------------------------------------- +// The startup guard: the enum makes the impossible unrepresentable, this refuses +// what a type cannot see — a field present but empty, and a remote backend that +// was never told the workspace is shared. /// A config that parses but cannot work must be refused by `validate`, not /// discovered at the step that needed the thing it is missing. @@ -362,10 +338,8 @@ fn a_field_that_is_present_but_empty_is_refused() { } } -/// The workspace gap, made impossible to hit by accident. The build workspace -/// is not shipped to a remote sandbox, so "remote" without this assertion would -/// silently build on the hub — the exact substitution this whole enum exists to -/// prevent, one layer down. +/// The workspace gap: the build workspace is not shipped to a remote sandbox, so +/// "remote" without this assertion would silently build on the hub. #[test] fn a_remote_backend_must_assert_the_shared_workspace() { let cfg = load_sandbox(r#"{"kind":"remote","listen":"127.0.0.1:1","token":"t"}"#).unwrap(); diff --git a/tests/crash.rs b/tests/crash.rs index e1f856f..68cac5c 100644 --- a/tests/crash.rs +++ b/tests/crash.rs @@ -1,11 +1,3 @@ -//! Crash, cancellation and the failure UI (§8.2, §8.4, I5). -//! -//! The difference between this file and the in-process fault hooks elsewhere is -//! that here the process actually dies. A shim sends `SIGKILL` to its parent in -//! the middle of the build step: no `Drop`, no unwinding, no chance to clean up. -//! That is the only way to prove the checkpoint story, because every in-process -//! simulation of a crash can be caught and tidied by accident. - mod common; use std::os::unix::process::ExitStatusExt; @@ -78,8 +70,8 @@ fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work ); assert!(db::accepted_release(&env.db, "plain-make").unwrap().is_none(), "nothing was published"); - // Time passes; the lease expires. A fresh process's dispatcher reaps it — - // the same code path as any other expired lease, with no special recovery. + // Time passes; the lease expires. A fresh process's dispatcher reaps it — the + // same code path as any other expired lease. env.exec("UPDATE build SET 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); assert_eq!( @@ -87,8 +79,7 @@ fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work Some(StepState::Interrupted) ); - // Resume. The completed steps are not repeated; only the interrupted one and - // what follows run. + // Resume: the completed steps are not repeated. env.cfg.hooks.shim_kill_parent = None; env.cfg.save().unwrap(); let out = run_cli(&env, &["run", &id]); @@ -117,8 +108,8 @@ fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work #[test] fn a_cancelled_build_stops_at_a_step_boundary_and_publishes_nothing() { - // §8.2: cancellation is cooperative at a step boundary. A worker never kills - // a step halfway through, because that is exactly the state a crash leaves. + // §8.2: cancellation is cooperative at a step boundary. A worker never kills a + // step halfway through, because that is the state a crash leaves. let (env, _fx) = env_with_fixture("plain-make"); let id = queued(&env, "plain-make"); builds::request_cancel(&env.db, &id).unwrap(); @@ -137,7 +128,7 @@ fn a_cancelled_build_stops_at_a_step_boundary_and_publishes_nothing() { fn a_failed_build_leaves_the_index_serving_the_old_version_and_says_so() { // §8.4: "v2 approved, build failed, index still serving v1". The dangerous // failure mode is a package that looks healthy while the new version never - // arrived, so the state has to be visible, not inferable. + // arrived. let (mut env, fx) = env_with_fixture("plain-make"); // Publish v1 for real. let c = approved(&env, "plain-make"); @@ -153,8 +144,7 @@ fn a_failed_build_leaves_the_index_serving_the_old_version_and_says_so() { let out = pipeline::run(&env.cfg, &env.db, &id2).unwrap(); assert!(matches!(out, pipeline::Outcome::Failed { .. }), "{out:?}"); - // The index still serves v1 — that is correct — and the system knows the - // approved v2 never landed. + // The index still serves v1 — correct — and the system knows v2 never landed. assert_eq!(db::index_version(&env.db, "plain-make").unwrap().as_deref(), Some("1.0-1")); let unbuilt = db::approved_but_unbuilt(&env.db).unwrap(); assert_eq!(unbuilt.len(), 1, "the failed approval must be surfaced: {unbuilt:?}"); diff --git a/tests/db.rs b/tests/db.rs index d750b5a..31f4326 100644 --- a/tests/db.rs +++ b/tests/db.rs @@ -1,8 +1,3 @@ -//! Schema and writer-actor tests (DESIGN.md §11, §11a). -//! -//! These are the parts of the §2 invariant set that are database guarantees -//! rather than code conventions. - mod common; use common::{params, Env, P}; @@ -240,9 +235,7 @@ fn i1_query_flags_index_entries_without_approval() { #[test] fn a_setting_that_is_absent_is_the_default_and_one_that_is_nonsense_falls_back() { - // m-9: the policy is now stated — absent means default, nonsense means - // default *and a complaint*, because a typo in a knob that silently does - // nothing is worse than a knob that refuses to apply. + // m-9: absent means default, nonsense means default *and a complaint*. let env = Env::new(); assert_eq!(db::setting_i64(&env.db, "stage_b_cooldown", 86400), 86400); db::set_setting(&env.db.writer, "stage_b_cooldown", "86400x").unwrap(); diff --git a/tests/detect.rs b/tests/detect.rs index e674c8a..6284b31 100644 --- a/tests/detect.rs +++ b/tests/detect.rs @@ -1,8 +1,3 @@ -//! Detection tests (§5.1, §5.1a, §5.3, §7.1) against a local `file://` "AUR". -//! -//! The fixtures are real git repos so the mirror, the pin and `recipe_hash` are -//! exercised for real; only the network is replaced. - mod common; use common::{git_add_commit, make_git_repo, params, Env, P}; @@ -74,8 +69,8 @@ fn git_head(p: &std::path::Path) -> String { aur_build::git::head(p).unwrap() } -/// §3: `recipe_hash` covers the *entire* tree, because a shipped patch is part -/// of the recipe and is a classic silent-change vector. +/// §3: `recipe_hash` covers the *entire* tree, because a shipped patch is part of +/// the recipe and is a classic silent-change vector. #[test] fn recipe_hash_covers_shipped_patches() { let env = Env::new(); @@ -176,8 +171,8 @@ fn i2_diff_base_is_the_last_accepted_version_however_many_detections_arrive() { assert_eq!(c2.base_release_id, Some(rel1), "base is the accepted release"); assert_eq!(c2.version(), "2.0-1"); - // v3 and v4 arrive while nobody is looking: they collapse into the same - // review, and the base is *still* v1. The human sees v1 -> v4. + // v3 and v4 arrive while nobody is looking: they collapse into the same review, + // and the base is *still* v1. for v in ["3.0", "4.0"] { git_add_commit(&aur(&env, "foo"), &[("PKGBUILD", &common::pkgbuild("foo", v, "1", ""))], v); check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); diff --git a/tests/dispatch.rs b/tests/dispatch.rs index 5f65b6f..197d226 100644 --- a/tests/dispatch.rs +++ b/tests/dispatch.rs @@ -1,8 +1,3 @@ -//! 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; @@ -32,8 +27,7 @@ fn pass(env: &Env) -> Vec { #[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. + // §8.2: re-submitting the same intent is an INSERT OR IGNORE no-op. 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); @@ -72,9 +66,7 @@ fn backpressure_admits_no_more_than_max_concurrent_builds() { 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). + // Ask for more free space than any machine has: nothing is admitted (§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"); @@ -89,8 +81,7 @@ fn disk_headroom_is_part_of_backpressure() { 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). + // that back into queued + interrupted (I5). let (env, _fx) = env_with_fixture("plain-make"); let id = queued_build(&env, "plain-make"); assert_eq!(pass(&env), vec![id.clone()]); @@ -117,8 +108,7 @@ fn an_expired_lease_is_requeued_and_its_running_step_marked_interrupted() { #[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. + // cancel_requested; the worker stops at the next boundary. let (env, _fx) = env_with_fixture("plain-make"); let id = queued_build(&env, "plain-make"); pass(&env); @@ -134,9 +124,8 @@ fn a_newer_approval_cancels_an_in_flight_build_at_the_step_boundary() { #[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. + // §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. 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()); @@ -153,10 +142,8 @@ fn a_deterministic_build_failure_is_not_retried() { #[test] fn a_transient_failure_is_retried_up_to_the_cap() { // §8.4: a failure the outside world caused is retried, up to a bound. This - // drives the real path: detection recorded a `SKIP` source's digest, then - // the bytes became unreachable and the cache was dropped, so the build's - // `sources` step has to fetch and gets an `Http` failure — the class a - // flaky mirror produces. + // drives the real path: the build's `sources` step has to fetch and gets an + // `Http` failure — the class a flaky mirror produces. let (mut env, fx) = env_with_fixture("skip-checksum"); let id = queued_build(&env, "skip-checksum"); std::fs::remove_file(fx.data.join("payload.bin")).expect("payload exists"); @@ -178,10 +165,9 @@ fn a_transient_failure_is_retried_up_to_the_cap() { #[test] fn a_missing_toolchain_is_not_retried() { - // m-14: this used to be the transient test. A missing `makepkg` - // surfaces as an `Io` error, and `Io` used to mean "retry" — so a - // misconfigured host or a full disk burned every attempt and then went - // quiet. It is deterministic: the tool is not going to appear. + // m-14: this used to be the transient test. A missing `makepkg` surfaces as + // an `Io` error, and `Io` used to mean "retry". It is deterministic: the tool + // is not going to appear. let (mut env, _fx) = env_with_fixture("plain-make"); let id = queued_build(&env, "plain-make"); env.cfg.makepkg_bin = "/nonexistent/makepkg-for-test".into(); @@ -215,9 +201,8 @@ fn the_pool_takes_a_queued_build_all_the_way_to_publication() { #[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. + // I5 through the dispatcher rather than a direct run(): a build that dies late + // is requeued, re-claimed, and finishes from its checkpoints. 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(); @@ -233,13 +218,10 @@ fn a_reaped_build_resumes_at_the_next_incomplete_step_with_no_duplicate_work() { )); let builds_before = aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makepkg", ""); - // 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. + // The worker "died" at publish: 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.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", diff --git a/tests/failure_modes.rs b/tests/failure_modes.rs index bea00a2..74794b4 100644 --- a/tests/failure_modes.rs +++ b/tests/failure_modes.rs @@ -1,8 +1,3 @@ -//! 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; @@ -106,9 +101,8 @@ fn run_with_fault(env: &Env, id: &str, fault: Fault) -> pipeline::Outcome { #[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. + // I5 across the sandbox boundary: the box vanishes mid-build, the lease + // expires, and a fresh worker resumes from the checkpoints. let (env, _fx) = env_with_fixture("plain-make"); let id = approve_and_enqueue(&env, "plain-make"); @@ -120,8 +114,7 @@ fn a_sandbox_that_dies_mid_run_expires_its_lease_and_the_requeue_finishes_the_bu other => panic!("{other:?}"), } - // The crash shape the dispatcher reaper knows: leased to a worker that is - // gone, with a lease nobody will extend. + // The crash shape the dispatcher reaper knows: leased to a worker that is gone. env.exec( "UPDATE build SET state='leased', lease_owner='dead-worker', lease_expires_at='2000-01-01T00:00:00Z' WHERE id=?1", @@ -129,8 +122,7 @@ fn a_sandbox_that_dies_mid_run_expires_its_lease_and_the_requeue_finishes_the_bu ); 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. + // Requeue and resume on a healthy pool: the completed steps do not re-run. assert!(matches!( pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Succeeded { .. } @@ -179,10 +171,9 @@ fn a_full_pool_blocks_the_build_instead_of_breaking_it() { #[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. + // 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. 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 { .. })); diff --git a/tests/hash.rs b/tests/hash.rs index 427f8ae..46ecdb4 100644 --- a/tests/hash.rs +++ b/tests/hash.rs @@ -1,19 +1,10 @@ -//! The digest helpers (§3, §5.1a). -//! -//! `sha256` hex is the currency of identity and provenance here, and one of -//! those digests — `Identity::hash` — is the value a reviewer's approval echoes -//! back. Everything that guards "we published what we reviewed" rests on that -//! digest being a function of the identity and of nothing else: not of the -//! order fields were declared in, and never of whether serialization happened -//! to fail. - use std::collections::HashMap; use aur_build::db::model::Identity; use aur_build::hash; -/// A value that refuses to be serialized, which is the input the old -/// implementation answered with `"{}"` — a digest every failed value shared. +/// A value that refuses to be serialized — the input the old implementation +/// answered with `"{}"`, a digest every failed value shared. struct Unserializable; impl serde::Serialize for Unserializable { @@ -26,16 +17,15 @@ impl serde::Serialize for Unserializable { fn a_value_that_cannot_be_serialized_is_an_error_not_an_empty_object() { let err = hash::canonical_json(&Unserializable).unwrap_err(); assert!(err.to_string().contains("cannot be serialized"), "the failure was swallowed: {err}"); - // The point of propagating: two different unserializable values now fail - // loudly instead of hashing to the same digest as each other. + // Two different unserializable values now fail loudly instead of hashing to + // the same digest. assert!(hash::canonical_json(&Unserializable).is_err()); } #[test] fn the_rendering_is_canonical_in_fact_not_in_name() { - // Same fields, different declaration order: routed through `Value`, both - // come out with the keys sorted, so the bytes — and any digest of them — - // are the same. + // Same fields, different declaration order: routed through `Value`, both come + // out with the keys sorted. #[derive(serde::Serialize)] struct Ab { alpha: String, diff --git a/tests/http.rs b/tests/http.rs index 0ca8a6b..068f999 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -1,11 +1,3 @@ -//! The web surface (§12, §13): routes render, the CSRF gate holds, and a stale -//! approval comes back as a 409 with the current diff instead of a silent -//! retarget. -//! -//! These drive a real `tiny_http` server on an ephemeral loopback port over a -//! real fixture corpus — no mocked transport, because the transport is part of -//! what we are claiming works. - mod common; use aur_build::review::{candidates, diff}; @@ -37,8 +29,7 @@ fn every_surface_renders() { #[test] fn the_review_detail_shows_the_panels_and_the_hashes() { let web = Web::new("plain-make"); - // Publish a first version so the review has something to diff against; - // every panel compares the accepted release to the candidate (§6). + // Publish a first version so the review has something to diff against. let first = web.open_review("plain-make"); let page = web.get(&format!("/reviews/{}", first.id)); let dd = extract(&page.body, "name=\"diff_digest\" value=\"", "\"").unwrap(); @@ -57,8 +48,7 @@ fn the_review_detail_shows_the_panels_and_the_hashes() { assert!(page.body.contains(want), "missing panel {want}"); } assert!(page.body.contains("previous accepted release"), "no base shown"); - // The approve form carries both hashes (§7.1a) and is a plain POST form, - // so it works with JavaScript switched off. + // The approve form carries both hashes (§7.1a) and works with JavaScript off. assert!(page.body.contains("name=\"identity_hash\"")); assert!(page.body.contains("name=\"diff_digest\"")); assert!(page.body.contains("
Vec { names } -/// I9: build hosts are treated as untrusted — a malicious PKGBUILD must not -/// reach the control plane's data or smuggle foreign bytes into what we publish. +/// I9: build hosts are treated as untrusted — a malicious PKGBUILD must not reach +/// the control plane's data or smuggle foreign bytes into what we publish. /// -/// The real enforcement is the chroot, and that tier is gated. What is *not* -/// gated, and what this pins, is the pipeline's own hygiene: `collect` scans the -/// srcdir for `*.pkg.tar.zst` and `ingest` copies whatever those paths point at -/// into the content-addressed store, from where the bytes are served from our -/// repo and signed with our key. If a build could make one of those paths be a -/// symlink to the signing keyring or the database, isolation would be the only -/// thing standing between a hostile AUR recipe and a signed artifact of our own -/// secret files. It must not be. So the pipeline refuses symlinks and refuses -/// anything that resolves outside the build's own staging directory, and this -/// test acts the attack out rather than arguing it away. +/// `collect` scans the srcdir for `*.pkg.tar.zst` and `ingest` copies whatever those +/// paths point at into the store, from where the bytes are served and signed. So the +/// pipeline refuses symlinks and anything outside the build's own staging directory. #[test] fn i9_a_build_cannot_smuggle_bytes_in_from_outside_its_own_staging_dir() { let (mut env, _fx) = env_with_fixture("plain-make"); diff --git a/tests/kata.rs b/tests/kata.rs index 29a6f29..79bf9d6 100644 --- a/tests/kata.rs +++ b/tests/kata.rs @@ -1,9 +1,3 @@ -//! The kata backend, tested the way every gated tier here is tested: the -//! logic runs for real on a machine with neither root nor `/dev/kvm`, and -//! only the live-orchestrator tier skips — with a printed note, never -//! silently absent (the convention `versions::vercmp_matches_the_system_oracle` -//! set). - mod common; use std::path::Path; @@ -88,14 +82,8 @@ fn the_live_kata_tier_is_recorded_not_silently_absent() { sbx.destroy().unwrap(); } -// --------------------------------------------------------------------------- -// agent-sandbox as a configuration, not a wish. -// -// `sandbox_backend = "kata"` used to fall through to loopback. The kind is -// `agent-sandbox` now, it parses, and it produces a Kata backend — so the path -// from a config file to the CR that would boot a VM is worth asserting end to -// end, starting from parsed JSON rather than a hand-built request. -// --------------------------------------------------------------------------- +// agent-sandbox as a configuration, not a wish: the path from a config file to +// the CR that would boot a VM, asserted end to end from parsed JSON. /// A config file as an operator would write it, parsed by the real loader. fn agent_sandbox_config() -> Config { @@ -176,11 +164,9 @@ fn a_loopback_config_never_becomes_agent_sandbox_or_vice_versa() { assert!(!id.contains("remote@"), "loopback must not report remote: {id}"); } -/// The seam's whole claim, tested as one thing: a real package built and -/// published through the kata lease path — a real `sandbox-agent` process, a -/// real nonce-matched rendezvous, real frames — with a VM being the only thing -/// this host cannot provide. If the lease path and the loopback path disagree -/// about anything, this is where it shows. +/// The seam's whole claim, tested as one thing: a real package built and published +/// through the kata lease path, with a VM being the only thing this host cannot +/// provide. #[test] fn a_fixture_builds_and_publishes_through_the_kata_lease_path() { let (env, _fx) = env_with_fixture("plain-make"); @@ -210,18 +196,15 @@ fn a_fixture_builds_and_publishes_through_the_kata_lease_path() { "the index must serve what the kata build produced: {world:?}" ); - // And it ran inside the leased sandbox: the agent streamed the build output - // over the wire into the same log file the SSE tail reads, and the shim saw - // exactly one makepkg. + // And it ran inside the leased sandbox: the agent streamed the build output over + // the wire into the same log file the SSE tail reads. let log = std::fs::read_to_string(env.cfg.build_log_path(&id)).unwrap(); assert!(log.contains("Making package"), "agent output must reach the log:\n{log}"); let shimlog = env.cfg.hooks.shim_dir.clone().unwrap(); assert_eq!(aur_build::shims::called_with(&shimlog, "makepkg", ""), 1); - // Deliberately no assertion that the sandbox is gone: the pipeline never - // calls `destroy`, and the design says the TTL is the guarantee and destroy - // is courtesy (wire.rs). The lease window bounds how long a box lives, not - // a teardown call — which is worth knowing, because it means a busy hub - // holds up to `steps x builds` sandboxes until their TTL bites. + // Deliberately no assertion that the sandbox is gone: the design says the TTL is + // the guarantee and destroy is courtesy (wire.rs). A busy hub holds up to + // `steps x builds` sandboxes until their TTL bites. } diff --git a/tests/layers.rs b/tests/layers.rs index 548f475..8566584 100644 --- a/tests/layers.rs +++ b/tests/layers.rs @@ -1,12 +1,3 @@ -//! The dependency direction between modules (§6 M-6, M-7). -//! -//! These are not style rules. The review found the persistence layer naming a -//! type from the VCS watcher, and the reviewer's risk scorer calling back into -//! the watcher for a recipe question — two edges pointing up the stack, which -//! makes `db` and `watch` mutually dependent and means any change to one is a -//! change to the other. A layering rule that is only written down gets violated -//! by the next reasonable-looking commit, so it is a test here. - use std::path::{Path, PathBuf}; fn src_root() -> PathBuf { @@ -57,9 +48,8 @@ fn edges(dir: &str, forbidden: &[&str]) -> Vec { #[test] fn persistence_names_nothing_above_itself() { - // M-6: `db::stage_b_cache_get` used to return `watch::upstream::StageB`, so - // the storage layer could not be understood without the watcher. The row - // type is `db::model::StageBCacheRow` now and the watcher converts. + // M-6: `db::stage_b_cache_get` used to return `watch::upstream::StageB`, so the + // storage layer could not be understood without the watcher. let hits = edges("db", &["watch", "review", "pipeline", "http", "ops", "shims"]); assert!(hits.is_empty(), "src/db depends upward on the modules above it:\n{hits:#?}"); } @@ -67,9 +57,8 @@ fn persistence_names_nothing_above_itself() { #[test] fn review_does_not_call_back_into_the_watcher() { // M-7: `review::risk` called `watch::digests::skip_on_non_vcs` while - // `watch::detect` called `review::candidates` — a cycle. Whether a recipe - // skips verification is a recipe question, so `recipe::skip_on_non_vcs` is - // where it lives and both sides look down, not sideways. + // `watch::detect` called `review::candidates` — a cycle. It now lives in + // `recipe`, and both sides look down, not sideways. let hits = edges("review", &["watch", "pipeline", "http"]); assert!(hits.is_empty(), "src/review depends on modules beside or above it:\n{hits:#?}"); } @@ -82,8 +71,7 @@ fn the_watcher_does_not_reach_into_the_pipeline_or_the_ui() { #[test] fn the_recipe_leaf_depends_on_nothing_above_it() { - // `recipe` is a leaf: parsing and recipe-shaped questions. Everything else - // is allowed to ask it; it may ask nothing. + // `recipe` is a leaf: everything else may ask it; it may ask nothing. let text = std::fs::read_to_string(src_root().join("recipe.rs")).expect("read recipe.rs"); for m in ["watch", "review", "pipeline", "http", "ops", "shims"] { assert!( diff --git a/tests/live.rs b/tests/live.rs index 16b68c5..da0f7ec 100644 --- a/tests/live.rs +++ b/tests/live.rs @@ -1,7 +1,3 @@ -//! The live surfaces: the SSE log tail and the htmx-refreshed builds table -//! (§13). The budget matters here — the whole point of "htmx and thirty lines of -//! glue" is that a reviewer can audit everything the browser runs. - mod common; use std::io::Read; @@ -51,9 +47,8 @@ fn the_log_stream_delivers_bytes_as_they_are_appended_and_then_ends() { std::fs::create_dir_all(log.parent().unwrap()).unwrap(); std::fs::write(&log, "==> step materialize\n").unwrap(); - // A producer appends while the stream is open, then finishes the build. If - // the endpoint buffered its response, everything would arrive only after the - // build ended and the "live" claim would be false. + // A producer appends while the stream is open, then finishes the build. If the + // endpoint buffered its response the "live" claim would be false. let db = web.env.db.clone(); let id2 = id.clone(); let log2 = log.clone(); @@ -101,20 +96,17 @@ fn the_builds_table_refreshes_via_htmx_and_still_works_without_js() { let web = Web::attach(env, fx); let base = web.url("/builds"); - // One queued build so the table has a row: the empty state is a paragraph, - // and asserting on it would prove nothing about server rendering. + // One queued build so the table has a row. queued(&web.env, "plain-make"); let page = ureq::get(&base).call().unwrap().into_string().unwrap(); // The refresh is an attribute on the table, not a script we wrote. assert!(page.contains("hx-trigger=\"every 3s\""), "no htmx refresh: {}", &page[..400.min(page.len())]); assert!(page.contains("hx-get=\"/builds?fragment=1\""), "the refresh has no target"); assert!(page.contains("