diff options
| author | aur-build <aur-build@localhost> | 2026-11-19 17:09:59 +0000 |
|---|---|---|
| committer | aur-build <aur-build@localhost> | 2026-11-19 17:09:59 +0000 |
| commit | e757979f1a2afdbe7146066345bb9acd19d3b151 (patch) | |
| tree | 30d5f5fbccd25ea7bf01c5202684af463b74e7d3 | |
| parent | 94c318f13264bb3c00a9f3057ba2e1aafb57c9e4 (diff) | |
| download | aur-build-e757979f1a2afdbe7146066345bb9acd19d3b151.tar.gz aur-build-e757979f1a2afdbe7146066345bb9acd19d3b151.zip | |
comments: say why, not what
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.
86 files changed, 827 insertions, 2194 deletions
diff --git a/src/bin/gpg.rs b/src/bin/gpg.rs index e9df5e3..da8c3db 100644 --- a/src/bin/gpg.rs +++ b/src/bin/gpg.rs @@ -1,5 +1,3 @@ -//! Toolchain shim: `gpg` (§16a). See `aur_build::shims`. - fn main() { std::process::exit(aur_build::shims::run("gpg")); } diff --git a/src/bin/makechrootpkg.rs b/src/bin/makechrootpkg.rs index 00569fb..c190e8b 100644 --- a/src/bin/makechrootpkg.rs +++ b/src/bin/makechrootpkg.rs @@ -1,5 +1,3 @@ -//! Toolchain shim: `makechrootpkg` (§16a). See `aur_build::shims`. - fn main() { std::process::exit(aur_build::shims::run("makechrootpkg")); } diff --git a/src/bin/makepkg.rs b/src/bin/makepkg.rs index 1c5cd7f..3398f5d 100644 --- a/src/bin/makepkg.rs +++ b/src/bin/makepkg.rs @@ -1,5 +1,3 @@ -//! Toolchain shim: `makepkg` (§16a). See `aur_build::shims`. - fn main() { std::process::exit(aur_build::shims::run("makepkg")); } diff --git a/src/bin/mkarchroot.rs b/src/bin/mkarchroot.rs index a4be6eb..33f2577 100644 --- a/src/bin/mkarchroot.rs +++ b/src/bin/mkarchroot.rs @@ -1,5 +1,3 @@ -//! Toolchain shim: `mkarchroot` (§16a). See `aur_build::shims`. - fn main() { std::process::exit(aur_build::shims::run("mkarchroot")); } diff --git a/src/bin/pacman.rs b/src/bin/pacman.rs index 5f7a357..e42b50b 100644 --- a/src/bin/pacman.rs +++ b/src/bin/pacman.rs @@ -1,5 +1,3 @@ -//! Toolchain shim: `pacman` (§16a). See `aur_build::shims`. - fn main() { std::process::exit(aur_build::shims::run("pacman")); } diff --git a/src/bin/repo-add.rs b/src/bin/repo-add.rs index 6714de6..ce74b24 100644 --- a/src/bin/repo-add.rs +++ b/src/bin/repo-add.rs @@ -1,5 +1,3 @@ -//! Toolchain shim: `repo-add` (§16a). See `aur_build::shims`. - fn main() { std::process::exit(aur_build::shims::run("repo-add")); } diff --git a/src/bin/sandbox-agent.rs b/src/bin/sandbox-agent.rs index 4e959a9..ce34d50 100644 --- a/src/bin/sandbox-agent.rs +++ b/src/bin/sandbox-agent.rs @@ -1,9 +1,3 @@ -//! The ephemeral sandbox agent — see `aur_build::sandbox::agent`. -//! -//! This is the piece that runs *inside* the disposable sandbox (a Kata -//! container, a throwaway VM, a test's temp process). It dials the hub, -//! serves exactly one lease, and dies with it. - use std::time::Duration; fn main() { diff --git a/src/config.rs b/src/config.rs index d583b05..f8fe51a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,72 +1,43 @@ -//! Filesystem layout and runtime configuration. -//! -//! Everything the server owns lives under one root directory so a test can point -//! the whole application at a `tempdir` and get an isolated instance. The heavy -//! bytes (packages, logs, mirrors) live on the filesystem and are referenced by -//! path from the DB (DESIGN.md §11a). - use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; -/// The tag a provisioned sandbox image gets when the configuration names a -/// provisioning kind but the caller has no image of its own (tests, mostly). +/// Fallback tag for a provisioning backend when the caller has no image of its own. pub const DEFAULT_SANDBOX_IMAGE: &str = "aur-build-sandbox:latest"; /// Where build code runs (§8, the sandbox seam). /// -/// Three kinds, and only three. This is an enum with required fields rather -/// than a string plus a `validate()` that has to be remembered, because the -/// failure mode of the string was silent: `sandbox_backend = "kata"` fell -/// through to loopback and a build that was supposed to run inside a VM ran -/// as the hub's own user. Here an unknown kind is a parse error naming the -/// valid set, and a kind is missing a field it needs is a parse error naming -/// the field. -/// -/// Secrets are redacted in `Debug` on purpose: a config that ends up in a log -/// line or a panic message must not carry the rendezvous token. +/// An enum with required fields rather than a string plus a `validate()`: the +/// string version silently fell through to loopback. #[derive(Clone, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)] pub enum Sandbox { - /// Subprocesses of this process — tests, and the single-machine deployment - /// where §14's sudo rules are the boundary. The default, and the only kind - /// that needs no configuration, which is what keeps an existing - /// `config.json` valid without edits. - /// - /// Isolation is *none*: the sandbox is the hub's own user. + /// Subprocesses of this process; isolation is *none* (§14's sudo rules are + /// the boundary). The default, and the only kind needing no configuration. Loopback, - /// Sandboxes that dial in over the agent protocol (§8a). The hub never - /// provisions them; it waits for an agent carrying the token to connect. + /// Sandboxes that dial in over the agent protocol (§8a); the hub never + /// provisions them. Remote { - /// Address the hub listens on for agent dial-ins. Port 0 is allowed - /// and resolves at bind. + /// Agent dial-in listener; port 0 resolves at bind. listen: String, - /// Shared secret an agent presents at rendezvous. A sandbox is - /// untrusted the moment it boots; this is the only thing saying "you - /// belong to me". Deploy it like a credential. + /// Rendezvous secret. Deploy it like a credential. token: String, - /// Asserts that hub and sandbox see the same filesystem. The workspace - /// is not yet shipped to a remote sandbox (§8a), so a remote build only - /// works where the srcdir is shared; saying so explicitly is what - /// turns a silent misconfiguration into a refusal. See `Config`'s - /// startup guard. + /// Asserts hub and sandbox see the same filesystem — required, because + /// the workspace is not shipped to a remote sandbox (§8a). See + /// `Config`'s startup guard. #[serde(default)] shared_workspace: bool, }, - /// agent-sandbox: disposable Kata VMs provisioned by a Kubernetes CRD, so - /// the orchestrator enforces the TTL even if the hub dies (§8a). + /// Disposable Kata VMs provisioned by a Kubernetes CRD, so the orchestrator + /// enforces the TTL even if the hub dies (§8a). AgentSandbox { - /// Kubernetes API server serving the agent-sandbox CRD. api: String, - /// Namespace the sandboxes are created in. namespace: String, - /// Bearer token for the API. A credential; never logged. + /// Never logged. bearer: String, - /// Image a provisioned sandbox boots — the `sandbox-agent` entrypoint. + /// The `sandbox-agent` entrypoint. image: String, - /// Address the hub listens on for agent dial-ins. listen: String, - /// Shared secret an agent presents at rendezvous. token: String, /// As [`Sandbox::Remote`]. #[serde(default)] @@ -75,16 +46,14 @@ pub enum Sandbox { } impl Default for Sandbox { - /// The fully local option, so a config that says nothing still builds. fn default() -> Self { Sandbox::Loopback } } impl std::fmt::Debug for Sandbox { - /// Hand-written so the secrets cannot ride along: a config that ends up in - /// a log line, a panic message, or an audit payload must not carry the - /// rendezvous token or the cluster bearer. + // Hand-written so the rendezvous token and cluster bearer cannot ride into + // a log line, a panic message, or an audit payload. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Sandbox::Loopback => f.write_str("Sandbox::Loopback"), @@ -109,7 +78,6 @@ impl std::fmt::Debug for Sandbox { } impl Sandbox { - /// The kind name, for error messages and the UI. pub fn kind(&self) -> &'static str { match self { Sandbox::Loopback => "loopback", @@ -118,7 +86,6 @@ impl Sandbox { } } - /// The rendezvous listener address, for the kinds that have one. pub fn listen(&self) -> Option<&str> { match self { Sandbox::Remote { listen, .. } => Some(listen), @@ -127,7 +94,7 @@ impl Sandbox { } } - /// The rendezvous token, for the kinds that have one. Never log this. + /// Never log this. pub fn token(&self) -> Option<&str> { match self { Sandbox::Remote { token, .. } => Some(token), @@ -136,9 +103,7 @@ impl Sandbox { } } - /// The image a provisioning backend boots. `None` for kinds that - /// provision nothing — there is no honest default for loopback, and a - /// field that is never consulted is a field that lies. + /// `None` for kinds that provision nothing. pub fn image(&self) -> Option<&str> { match self { Sandbox::AgentSandbox { image, .. } => Some(image), @@ -146,8 +111,6 @@ impl Sandbox { } } - /// Whether the operator has asserted that hub and sandbox share a - /// filesystem. Loopback shares it by construction. pub fn shared_workspace(&self) -> bool { match self { Sandbox::Loopback => true, @@ -156,7 +119,6 @@ impl Sandbox { } } - /// The valid kind names, for the error that names them. pub const KINDS: [&'static str; 3] = ["loopback", "remote", "agent-sandbox"]; } @@ -164,101 +126,63 @@ impl Sandbox { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] pub struct Config { - /// Root directory holding db, mirrors, caches, store, repo and logs. + /// Holds db, mirrors, caches, store, repo and logs. pub root: PathBuf, - /// Name of the single pacman repo we publish (DESIGN.md §9, decision 4). pub repo_name: String, - /// Architecture, fixed to x86_64 by decision 17. pub arch: String, - /// GPG key id used to sign packages *and* the database (decision 22). + /// Signs packages *and* the database (decision 22). pub signing_key_id: String, - /// Address the HTTP UI binds to. Default is loopback only (§14). + /// Loopback only by default (§14). pub bind: String, - /// Shared credential for the UI. Single user, one credential, no user table. + /// One credential, no user table. pub password: String, - /// Public base URL used in consumer-facing snippets. pub base_url: String, - /// devtools build profile (§8.3). pub build_profile: String, - /// Path to the git executable. pub git_bin: String, - /// Path to the makepkg executable. pub makepkg_bin: String, - /// Path to pacman. The provisioning step installs the pinned lease set - /// with `pacman -U` inside the sandbox (§8); nothing resolves against a - /// live mirror at build time. + /// The lease set is installed with `pacman -U` inside the sandbox (§8). pub pacman_bin: String, - /// Path to repo-add. pub repo_add_bin: String, - /// Path to gpg. pub gpg_bin: String, - /// Unprivileged user that runs PKGBUILD code (§14). Empty = current user. + /// Unprivileged user running PKGBUILD code (§14). Empty = current user. pub build_user: String, - /// Where build code runs (§8). A tagged enum rather than a free-form string - /// plus a validation pass: the configurations that cannot work are not - /// representable, so there is no input that silently becomes "loopback". - /// See [`Sandbox`]. pub sandbox: Sandbox, - /// Test-only hooks (§16a). Not part of the production configuration at all - /// unless the crate is built with `test-support` — see [`TestHooks`]. + /// Absent unless built with `test-support` (§16a). #[cfg(feature = "test-support")] #[serde(default, skip_serializing_if = "TestHooks::is_empty")] pub hooks: TestHooks, - /// How many builds may run at once (§8.2 backpressure). Default 1, which - /// also means the chroot pool only needs one warm root. + /// Default 1, so the chroot pool needs only one warm root. pub max_concurrent_builds: usize, - /// Seconds of lease a worker takes when it claims a build (§8.2). pub lease_secs: i64, - /// A build is not admitted unless at least this much free space remains - /// on the filesystem holding `root` (§8.2 disk headroom). pub min_free_disk_mb: u64, - /// Transient step failures are retried up to this many attempts; a - /// deterministic build failure is never retried (§8.4). + /// Transient step failures only (§8.4). pub max_transient_attempts: i64, - /// Seconds between dispatcher passes. pub dispatch_tick_secs: u64, } -/// The test harness's handles on a real pipeline (§16a), grouped into one -/// submodule so the production configuration says what it is. -/// -/// Each of these exists because a *fake* pipeline would test something else: -/// I4 (atomic publish) needs a process that really dies between the tmp write -/// and the rename; I5 needs a step that really dies mid-child; I9 needs a -/// PKGBUILD that really reaches outside its staging dir. The alternative was a -/// mock that asserts the mock's own behaviour. +/// The test harness's handles on a real pipeline (§16a). /// -/// They are compiled out entirely unless the crate is built with the -/// `test-support` feature (the same feature that gates the shims, §6 M-4), so a -/// production binary has no fault-injection branch in its publish path and no -/// shim protocol in its child environment. The test suite enables the feature -/// through a dev-dependency on this crate, and nothing else does. +/// Each exists because a *fake* pipeline would test something else: I4 needs a +/// process that really dies between the tmp write and the rename, I5 needs a step +/// that really dies mid-child, I9 needs a PKGBUILD that really reaches outside its +/// staging dir. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(default)] pub struct TestHooks { - /// Directory prepended to PATH for child processes: the toolchain shims. pub path_prepend: Option<PathBuf>, - /// Fixture manifest the shims should obey, exported as `AUR_SHIM_MANIFEST`. pub shim_manifest: Option<PathBuf>, - /// Where shims record their invocations, exported as `AUR_SHIM_DIR`. pub shim_dir: Option<PathBuf>, - /// Abort publish at a named point so I4 (atomic publish) can be exercised - /// for real: `before-rename` or `after-rename`. + /// `before-rename` or `after-rename`, for I4. pub publish_fault: Option<String>, /// The named shim must fail, e.g. `makepkg`. pub shim_fail: Option<String>, - /// The named shim SIGKILLs its parent — the process running the pipeline — - /// mid-step. This is how a real crash is reproduced for I5: not a caught - /// error, an uncatchable death. + /// The named shim SIGKILLs the pipeline process mid-step (I5). pub shim_kill_parent: Option<String>, - /// Make the build shim plant a symlink to this path in its srcdir, so a test - /// can act out the I9 attack: an untrusted PKGBUILD smuggling bytes in from - /// outside its own staging dir. + /// The build shim plants a symlink to this path in its srcdir (I9). pub shim_plant_link: Option<String>, } impl TestHooks { - /// True when nothing is hooked — the state every real process runs in. pub fn is_empty(&self) -> bool { self.path_prepend.is_none() && self.shim_manifest.is_none() @@ -300,10 +224,6 @@ impl Default for Config { } impl Config { - /// The image a provisioning sandbox boots, when this configuration - /// provisions anything. Falls back to the conventional tag so a test that - /// builds a `KataBackend` over a default config still gets a name to hand - /// an agent. pub fn sandbox_image(&self) -> String { self.sandbox .image() @@ -313,12 +233,8 @@ impl Config { /// Refuse a configuration that cannot work, before anything builds with it. /// - /// The enum already makes the impossible unrepresentable; this catches what - /// a type cannot see — a field that is present but empty, and the one - /// assertion the type deliberately leaves defaulted so the refusal can - /// explain itself instead of arriving as a parse error. Called at startup - /// (so the operator hears about it now, not at the first build) and again - /// where a backend is constructed (so a hand-built `Config` cannot skip it). + /// The enum makes the impossible unrepresentable; this catches what a type cannot + /// see — empty-but-present fields, and the assertion the type leaves defaulted. pub fn validate(&self) -> crate::error::Result<()> { let require = |field: &str, value: &str| -> crate::error::Result<()> { if value.trim().is_empty() { @@ -351,10 +267,7 @@ impl Config { if self.sandbox.shared_workspace() { return Ok(()); } - // The one gap a remote configuration cannot be trusted to notice by - // itself: the workspace is not shipped to the sandbox, so a remote - // build only works where hub and sandbox see the same path. Refusing - // here is what stops "remote" from silently meaning "on the hub". + // A remote build only works where hub and sandbox see the same path. Err(crate::error::Error::invalid(format!( concat!( "sandbox kind \"{}\" was not told that hub and sandbox share a filesystem: ", @@ -370,20 +283,10 @@ impl Config { /// Read `<root>/config.json`. /// - /// The crate's own error type, like everything else that can fail (m-15): - /// `anyhow::Result` here meant two error vocabularies in one crate, and the - /// one thing a caller can actually branch on — "there is no config yet, run - /// init" — arrived as an opaque string. - /// - /// **The root is the directory the config file was found in.** The `root` - /// field inside the file is written for whoever is looking at the tree, not - /// as a second source of truth: `load` is only ever handed the directory it - /// then reads the config from, so a field that disagreed with its own - /// location could only ever contradict it. Honouring a relative field by - /// re-joining it onto the config's directory is what turned `--root runtime` - /// (which `init` used to save verbatim) into `runtime/runtime/…` — every - /// command after `init` ran against a second tree with its own database, - /// while `init` had created and migrated the first one. + /// **The root is the directory the config file was found in.** The `root` field + /// inside the file is documentation, not a second source of truth; honouring a + /// relative field by re-joining it onto the config's directory is what turned + /// `--root runtime` into `runtime/runtime/…`. pub fn load(root: &Path) -> crate::error::Result<Self> { let dir = absolute(root)?; let p = dir.join("config.json"); @@ -404,9 +307,8 @@ impl Config { pub fn save(&self) -> crate::error::Result<()> { std::fs::create_dir_all(&self.root)?; let mut out = self.clone(); - // Absolutize on the way out, so a config written by a process that was - // handed a relative `--root` can never be misread — by the next command, - // or by a person editing it by hand. + // Absolutize on the way out, so a config written from a relative + // `--root` can never be misread. out.root = absolute(&self.root)?; std::fs::write( self.root.join("config.json"), @@ -415,17 +317,12 @@ impl Config { Ok(()) } - /// Environment for a child process: PATH with the shims in front, plus the - /// shim protocol variables (§16a). The pairs form is what the remote - /// backend puts on the wire, so a remote child sees exactly what a local - /// one would. + /// Child environment as pairs — the form the remote backend puts on the + /// wire, so a remote child sees what a local one would. #[cfg_attr(not(feature = "test-support"), allow(unused_variables))] pub fn child_env_pairs(&self) -> Vec<(String, String)> { #[cfg_attr(not(feature = "test-support"), allow(unused_mut))] let mut pairs = Vec::new(); - // Without `test-support` there is no shim protocol to export and no - // PATH to rewrite: the child inherits the real environment, which is - // what a real build needs (§16a). #[cfg(feature = "test-support")] { let h = &self.hooks; @@ -452,9 +349,6 @@ impl Config { pairs } - /// Environment for a child process: PATH with the shims in front, plus the - /// shim protocol variables (§16a). - #[cfg_attr(not(feature = "test-support"), allow(unused_variables))] pub fn child_env(&self, cmd: &mut std::process::Command) { for (k, v) in self.child_env_pairs() { cmd.env(k, v); @@ -482,15 +376,12 @@ impl Config { pub fn db_path(&self) -> PathBuf { self.root.join("aur-build.db") } - /// Local AUR git mirrors, one clone per pkgbase (§5.1). Load-bearing, not a - /// cache: it is what makes historical releases rebuildable (§5.1a). pub fn mirrors_dir(&self) -> PathBuf { self.root.join("mirrors") } pub fn mirror_path(&self, pkgbase: &str) -> PathBuf { self.mirrors_dir().join(format!("{pkgbase}.git")) } - /// Persistent upstream VCS clones (§5.2 cost control). pub fn vcs_cache_dir(&self) -> PathBuf { self.root.join("vcs_cache") } @@ -498,21 +389,18 @@ impl Config { let h = crate::hash::short(url.as_bytes(), 16); self.vcs_cache_dir().join(format!("{}-{}.git", slug(url), h)) } - /// Content-addressed download cache reused by the build (§5.3). pub fn source_cache_dir(&self) -> PathBuf { self.root.join("source_cache") } pub fn source_cache_path(&self, digest: &str) -> PathBuf { self.source_cache_dir().join(&digest[..2.min(digest.len())]).join(digest) } - /// Disposable per-build workspace (§8.2). pub fn staging_dir(&self) -> PathBuf { self.root.join("staging") } pub fn staging_build_dir(&self, build_id: &str) -> PathBuf { self.staging_dir().join(build_id) } - /// Content-addressed artifact store. pub fn store_dir(&self) -> PathBuf { self.root.join("store") } @@ -525,7 +413,6 @@ impl Config { pub fn build_log_path(&self, build_id: &str) -> PathBuf { self.log_dir().join(format!("{build_id}.log")) } - /// The served repo tree: `<repo>/<name>/os/<arch>/` (§9). pub fn repo_dir(&self) -> PathBuf { self.root.join("repo") } @@ -540,11 +427,9 @@ impl Config { } } -/// Whether a retired key holds exactly the value `init` used to write for a -/// local deployment. Such a value states nothing the default does not already -/// state, so it is noise from an old file rather than an intent that could be -/// lost — which is what lets a working local config keep loading across the -/// change. Anything else is refused. +/// A retired key holding exactly what `init` used to write for a local +/// deployment states nothing the default does not already state, so it is noise +/// from an old file rather than lost intent. Anything else is refused. fn retired_key_is_inert(key: &str, value: &str) -> bool { match key { "sandbox_backend" => value == "loopback", @@ -554,14 +439,9 @@ fn retired_key_is_inert(key: &str, value: &str) -> bool { } /// The sandbox configuration moved from four flat keys to one tagged object -/// ([`Sandbox`]). A retired key is refused rather than quietly ignored — but -/// only when it would have changed behaviour. -/// -/// `init` used to write `sandbox_backend: "loopback"` alongside three empty -/// strings, and a config carrying exactly that says nothing the default does -/// not already say, so it keeps loading untouched. Anything else is an error: -/// silently turning a retired `sandbox_backend: "remote"` into loopback is -/// precisely the failure the enum exists to make impossible. +/// ([`Sandbox`]). A retired key is refused only when it would have changed +/// behaviour: `init` used to write `sandbox_backend: "loopback"` alongside three +/// empty strings, and a config carrying exactly that keeps loading untouched. fn check_retired_sandbox_keys(v: &serde_json::Value) -> crate::error::Result<()> { const RETIRED: [&str; 4] = ["sandbox_backend", "agent_listen", "agent_token", "sandbox_image"]; let named: Vec<String> = RETIRED @@ -591,14 +471,13 @@ fn check_retired_sandbox_keys(v: &serde_json::Value) -> crate::error::Result<()> ))) } -/// Absolutize a path without resolving symlinks and without requiring it to +/// Absolutize without resolving symlinks and without requiring the path to /// exist, both of which `canonicalize` insists on — and `init` saves its config /// before the tree under it is complete. fn absolute(p: &Path) -> crate::error::Result<PathBuf> { Ok(std::path::absolute(p)?) } -/// Filesystem-safe slug for a URL, used in cache filenames. pub fn slug(url: &str) -> String { url.chars() .map(|c| { diff --git a/src/db/approvals.rs b/src/db/approvals.rs index f04d641..b5a9b59 100644 --- a/src/db/approvals.rs +++ b/src/db/approvals.rs @@ -1,11 +1,3 @@ -//! The approval table: the record of a human decision, and the only thing that -//! makes a candidate publishable (§7.1a, I1). -//! -//! An approval row is what an index entry must trace back to. The rules about -//! *when* one may be written — same identity, same diff, same base — are domain -//! logic in `review::approve`; what lives here is the SQL, so the schema has one -//! owner (§6 M-1). - use rusqlite::{params, OptionalExtension, Transaction}; use crate::db::Db; diff --git a/src/db/builds.rs b/src/db/builds.rs index 072836b..8598dd3 100644 --- a/src/db/builds.rs +++ b/src/db/builds.rs @@ -1,5 +1,3 @@ -//! Build queue rows: deterministic ids, leases, step checkpoints (§8.1, §8.2). - use rusqlite::{params, Connection, OptionalExtension}; use crate::db::{BuildState, Db, StepState}; @@ -160,12 +158,10 @@ pub fn extend_lease(db: &Db, id: &str, lease_secs: i64) -> Result<()> { }) } -/// Reaper pass (§8.2): expired leases go back to the queue and their in-flight -/// step is marked interrupted, so the checkpoint decides where it resumes. +/// Reaper pass (§8.2): expired leases go back to the queue and their in-flight step +/// is marked interrupted, so the checkpoint decides where it resumes. /// -/// Both `leased` and `running` are reaped: a worker sets `running` as soon as it -/// starts a step, so a process that dies mid-step leaves a `running` row, not a -/// `leased` one. Reaping only `leased` would strand every real crash. +/// Both `leased` and `running` are reaped: a mid-step death leaves a `running` row. pub fn reap_expired(db: &Db) -> Result<usize> { let now = time::now(); db.writer.tx(move |tx| { @@ -195,10 +191,8 @@ pub fn reap_expired(db: &Db) -> Result<usize> { /// The one way a build changes state, usable inside a transaction. /// -/// The write is a compare-and-swap: only a row currently in one of `to`'s legal -/// predecessor states is updated, so two workers cannot both land a terminal -/// state, and a zombie worker whose lease was reaped gets an error instead of -/// silently rewriting a build that has since been handed to somebody else. +/// The write is a compare-and-swap: only a row in one of `to`'s legal predecessor +/// states is updated, so a zombie worker whose lease was reaped gets an error. fn transition_in_tx( tx: &mut rusqlite::Transaction<'_>, id: &str, @@ -248,13 +242,10 @@ pub fn block_on(db: &Db, id: &str, blocked_on: &[String]) -> Result<()> { }) } -/// Re-check blocked builds whenever a publish lands (§10.4). /// Requeue blocked builds whose blocking packages have since arrived (§10.4). /// -/// Not "requeue everything that is blocked": the dispatcher calls this every -/// pass, and requeueing a build that will immediately block again is a busy loop -/// that burns a claim and a plan step each tick. A build only goes back on the -/// queue when every name it is waiting for is actually in the index now. +/// Not "requeue everything that is blocked": the dispatcher calls this every pass, +/// and requeueing a build that will immediately block again burns a claim each tick. pub fn requeue_blocked(db: &Db) -> Result<usize> { let now = time::now(); db.writer.tx(move |tx| { @@ -265,9 +256,8 @@ pub fn requeue_blocked(db: &Db) -> Result<usize> { .collect::<rusqlite::Result<Vec<(String, String)>>>()?; out }; - // The index membership check is one query for the whole pass, not one - // per dependency of every blocked build (m-17): the old shape was an N+1 - // whose N grew with the backlog, and it ran on the dispatcher's hot loop. + // The index membership check is one query for the whole pass, not one per + // dependency of every blocked build (m-17), on the dispatcher's hot loop. let in_index: std::collections::HashSet<String> = { let mut stmt = tx.prepare("SELECT name FROM package WHERE state='in_index'")?; let names = stmt @@ -544,8 +534,7 @@ pub fn current_state(c: &Connection, id: &str) -> Result<Option<BuildState>> { /// Claim up to `limit` queued builds in one `BEGIN IMMEDIATE` transaction and /// hand them to workers (§8.2). SQLite has no `SKIP LOCKED`, but with exactly one -/// writer the claim cannot race: the SELECT and the UPDATE are the same -/// transaction, so no other claimer can see a row in between. +/// writer the claim cannot race: the SELECT and the UPDATE are one transaction. pub fn claim_batch(db: &Db, owner: &str, limit: usize, lease_secs: i64) -> Result<Vec<String>> { if limit == 0 { return Ok(Vec::new()); @@ -597,9 +586,9 @@ pub fn requeue_transient(db: &Db, id: &str) -> Result<()> { .tx(move |tx| transition_in_tx(tx, &id, BuildState::Queued, None)) } -/// Explicitly retry a failed build (§8.4). This is a human decision, not a -/// policy: the failed step is put back to pending so it runs again, everything -/// that succeeded stays checkpointed, and the attempt counter keeps counting. +/// Explicitly retry a failed build (§8.4): the failed step goes back to pending, +/// everything that succeeded stays checkpointed, and the attempt counter keeps +/// counting. pub fn retry(db: &Db, id: &str) -> Result<()> { let id = id.to_string(); db.writer.tx(move |tx| { @@ -609,8 +598,7 @@ pub fn retry(db: &Db, id: &str) -> Result<()> { params![id], )?; // The move itself goes through the machine, so requeueing a build that - // already published is refused with a reason instead of silently - // re-queueing a row whose every step is checkpointed as done. + // already published is refused with a reason. transition_in_tx(tx, &id, BuildState::Queued, None)?; tx.execute("UPDATE build SET cancel_requested=0 WHERE id=?1", params![id])?; Ok(()) diff --git a/src/db/candidates.rs b/src/db/candidates.rs index 63c089f..631bf42 100644 --- a/src/db/candidates.rs +++ b/src/db/candidates.rs @@ -1,22 +1,10 @@ -//! The candidate table: its row shape, its column list, and every statement -//! that touches it (§7.1). -//! -//! The *rules* about candidates — collapse into the open review, supersede once -//! a human has looked, never re-raise a rejection — are domain logic and live -//! in `review::candidates`. What lives here is SQL, so that the schema has one -//! owner (§6 M-1). The `_in` functions take a transaction handle so a caller -//! can compose several of them into one atomic decision; the decision itself -//! stays with the caller. - use rusqlite::{params, OptionalExtension, Row, Transaction}; use crate::db::{CandidateRow, CandidateState, Db}; use crate::error::{Error, Result}; use crate::time; -/// The columns `row_to_candidate` reads, spelled once. Every other table in -/// this module already works this way; the candidate select was simply copied -/// four times for long enough to be noticed (§6 m-3). +/// The columns `row_to_candidate` reads, spelled once (§6 m-3). const CANDIDATE_COLS: &str = "c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver, \ c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash, c.diff_digest, \ c.revision, c.viewed_at, c.risk_level, c.risk_signals_json, c.missing_deps_json, c.state, \ @@ -130,10 +118,8 @@ pub fn review_subject_in(tx: &Transaction<'_>, candidate_id: i64) -> Result<Opti /// Take a candidate out of the open state: approved, rejected or superseded. /// -/// The write is a compare-and-swap on [`CandidateState`]: a decided review is -/// never re-decided, so an approval racing a rejection — or a stale worker -/// resolving a review that has since been superseded — fails instead of -/// silently overwriting what a human did. +/// The write is a compare-and-swap on [`CandidateState`]: a decided review is never +/// re-decided, so an approval racing a rejection fails instead of overwriting. pub fn resolve_in(tx: &Transaction<'_>, id: i64, to: CandidateState, at: &str) -> Result<()> { let froms = CandidateState::predecessors(to); let placeholders = froms.iter().map(|_| "?").collect::<Vec<_>>().join(","); @@ -233,7 +219,7 @@ pub fn supersede_in(tx: &Transaction<'_>, id: i64) -> Result<()> { } /// Has this exact identity been rejected before? If so the watcher stays quiet -/// until a human re-opens it (§7.1: "do not nag"). +/// until a human re-opens it (§7.1). pub fn rejected_before_in(tx: &Transaction<'_>, pkgbase_id: i64, identity_hash: &str) -> Result<bool> { Ok(tx .query_row( @@ -362,7 +348,7 @@ pub fn mark_viewed(db: &Db, id: i64) -> Result<()> { }) } -/// §7.1: a rejection can be re-opened. We retire the rejected row so it stops +/// §7.1: a rejection can be re-opened. The rejected row is retired so it stops /// suppressing the identity, and the next detection opens a fresh review. pub fn reopen_rejected(db: &Db, id: i64) -> Result<()> { let at = time::now(); diff --git a/src/db/migrations.rs b/src/db/migrations.rs index 9e60132..b1954ab 100644 --- a/src/db/migrations.rs +++ b/src/db/migrations.rs @@ -1,9 +1,3 @@ -//! Hand-rolled `user_version` migration stepper (DESIGN.md §4, "Migrations"). -//! -//! Each entry is applied inside its own transaction and bumps -//! `PRAGMA user_version`. Migrations must never be edited after they ship; add -//! a new one instead. - /// One migration: version number + SQL body. pub struct Migration { pub version: u32, @@ -300,9 +294,8 @@ END; "#; /// Stage B results, keyed on `(pkgbase, recipe_hash, upstream_tip)` (§5.2). -/// Re-resolving means cloning an upstream repo and running makepkg, so the -/// answer is worth keeping; the same key also implements the per-pkgbase -/// cooldown, because a fresh tip inside the window reuses the old answer. +/// Re-resolving means cloning an upstream repo and running makepkg, so the answer +/// is worth keeping; the same key also implements the per-pkgbase cooldown. const M_0007_STAGE_B_CACHE: &str = r#" CREATE TABLE stage_b_cache ( pkgbase_id INTEGER NOT NULL REFERENCES pkgbase(id), @@ -319,14 +312,10 @@ CREATE TABLE stage_b_cache ( CREATE INDEX stage_b_cache_by_pkgbase ON stage_b_cache (pkgbase_id, resolved_at); "#; -/// Retention (§15, open question 21). The rows are never compacted — the whole -/// point of the schema is that "which bytes produced this installed package" -/// stays answerable — but the bytes on disk cannot be kept forever. So eviction -/// is recorded rather than implied: the artifact row keeps its digest, size and -/// provenance and gains a `purged_at`, which says "these bytes existed, and were -/// dropped from the store at T" instead of silently pretending they are still -/// there. A `cp` of the store and a database that disagrees about what is on disk -/// is the failure mode this avoids. +/// Retention (§15). The rows are never compacted — the schema exists so "which +/// bytes produced this installed package" stays answerable — but the bytes on disk +/// cannot be kept forever. So eviction is recorded rather than implied: the +/// artifact row keeps its digest, size and provenance and gains a `purged_at`. const M_0008_RETENTION: &str = r#" ALTER TABLE artifact ADD COLUMN purged_at TEXT; diff --git a/src/db/mod.rs b/src/db/mod.rs index 403ced2..c271fe7 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -1,13 +1,3 @@ -//! SQLite access (DESIGN.md §11a). -//! -//! The app is multi-threaded and SQLite has one writer at a time, so there is -//! exactly **one writer thread** owning the write connection. Everything that -//! mutates is sent to it over a channel as a closure and answered with a -//! `Result`. That makes "who can write" a compile-time fact (only [`Writer`] -//! hands out `&mut`-equivalent access) and removes `SQLITE_BUSY` from the -//! design entirely. Readers are thread-local, read-only connections; WAL lets -//! them proceed concurrently with the writer. - pub mod approvals; pub mod builds; pub mod candidates; @@ -18,11 +8,8 @@ pub mod queries; pub use migrations::MIGRATIONS; pub use model::*; -/// Parse a state column into one of the state enums. -/// -/// A value the code does not recognise fails the row instead of becoming a -/// default: a build in a state we cannot name must not be listed, claimed, or -/// rendered as if it were in one we could. +/// Parse a state column into one of the state enums. A value the code does not +/// recognise fails the row instead of becoming a default. pub(crate) fn state_col<T: StateEnum>(col: usize, text: &str) -> rusqlite::Result<T> { T::parse(text).ok_or_else(|| { rusqlite::Error::FromSqlConversionFailure( @@ -158,17 +145,13 @@ impl Writer { self.alive.load(Ordering::SeqCst) } - /// Run `f` on the write connection and wait for its result. - /// - /// No transaction may span a build step: `f` should be short. - /// Use [`Writer::tx`] for atomic multi-statement mutations. + /// Run `f` on the write connection and wait for its result. No transaction + /// may span a build step: `f` should be short. /// - /// `pub(crate)`, not `pub`: the schema is the system's most protected asset - /// and it has one owner, this module (§6 M-1). Code outside `db/` asks for a - /// typed query instead of writing SQL. `pub(crate)` is what keeps the - /// *crate's* users (the integration tests, the shim binaries) out; inside - /// the crate the convention is enforced by `tests/schema_ownership.rs`, - /// which fails the build if a SQL statement appears outside `src/db/`. + /// `pub(crate)`, not `pub`: the schema has one owner, this module (§6 M-1). + /// Inside the crate the convention is enforced by + /// `tests/schema_ownership.rs`, which fails the build if a SQL statement + /// appears outside `src/db/`. pub(crate) fn call<T>(&self, f: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static) -> Result<T> where T: Send + 'static, @@ -182,8 +165,7 @@ impl Writer { .map_err(|_| Error::db("writer actor gone"))? } - /// Run `f` inside a single `BEGIN IMMEDIATE` transaction on the write - /// connection. This is how every multi-statement mutation is expressed. + /// Run `f` inside a single `BEGIN IMMEDIATE` transaction. pub(crate) fn tx<T>( &self, f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result<T> + Send + 'static, @@ -216,17 +198,12 @@ impl Writer { } } -/// The raw-SQL door, open only for the test harness (§6 M-9). -/// -/// A fixture sometimes has to put the database in a state the typed API only -/// reaches through several steps — a release published without a build, a -/// pointer moved out from under a review. That is a reason to have a door, not -/// a reason to leave it unlocked in the binary an operator runs, so it exists -/// only under the `test-support` feature, which nothing but this crate's own -/// dev-dependency enables. +/// The raw-SQL door, open only for the test harness (§6 M-9). A fixture +/// sometimes has to reach a state the typed API only reaches through several +/// steps, but that is not a reason to leave the door unlocked in the binary an +/// operator runs. #[cfg(feature = "test-support")] impl Writer { - /// Run `f` in a transaction. Test fixtures only. pub fn tx_for_tests<T>( &self, f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result<T> + Send + 'static, @@ -237,7 +214,6 @@ impl Writer { self.tx(f) } - /// Run `f` on the write connection. Test fixtures only. pub fn call_for_tests<T>(&self, f: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static) -> Result<T> where T: Send + 'static, @@ -246,10 +222,9 @@ impl Writer { } } -/// Thread-local read-only connection pool. -/// -/// One connection per thread per database file, opened read-only. HTTP handlers -/// and watchers use this; they never touch the write connection. +/// Thread-local read-only connection pool: one connection per thread per +/// database file. HTTP handlers and watchers use this; they never touch the +/// write connection. pub struct Readers { path: PathBuf, } @@ -275,9 +250,8 @@ impl Readers { .iter() .position(|(p, _)| p == &path) .ok_or_else(|| Error::db("reader pool lost entry"))?; - // Safety of the borrow: we only ever use one connection at a time - // per thread and `f` cannot re-enter this function for the same pool - // (it receives &Connection, not &Readers). + // We only ever use one connection at a time per thread, and `f` + // receives &Connection rather than &Readers, so it cannot re-enter. let conn = &pool[idx].1; f(conn) }) @@ -321,13 +295,11 @@ pub fn backup_to(writer: &Writer, dest: &Path) -> Result<()> { }) } -/// The schema version a database file reports. A backup that does not open and -/// answer with a migrated schema is a file, not a backup, and the only way to -/// find that out is to ask it. +/// The schema version a database file reports. A backup that does not answer +/// with a migrated schema is a file, not a backup. /// -/// Opened read-write and untouched by the connection pragmas: the point is to -/// read one number from a file we are not going to modify, and a WAL database -/// cannot even be opened read-only (it needs its sidecar). +/// Opened read-write and untouched by the connection pragmas: a WAL database +/// cannot even be opened read-only. pub fn schema_version(path: &Path) -> Result<i64> { let conn = rusqlite::Connection::open(path) .map_err(|e| Error::db(format!("{} does not open: {e}", path.display())))?; @@ -335,7 +307,6 @@ pub fn schema_version(path: &Path) -> Result<i64> { .map_err(|e| Error::db(format!("{} has no schema version: {e}", path.display()))) } -/// WAL size + checkpoint lag, surfaced on the Ops page and in metrics. pub fn wal_stats(db: &Db) -> (u64, u64) { let db_file = std::fs::metadata(db.writer.path()).map(|m| m.len()).unwrap_or(0); let mut wal = db.writer.path().as_os_str().to_os_string(); diff --git a/src/db/model.rs b/src/db/model.rs index 3fa2840..84701d1 100644 --- a/src/db/model.rs +++ b/src/db/model.rs @@ -1,35 +1,25 @@ -//! Row types and small value objects that appear in JSON columns. - use serde::{Deserialize, Serialize}; use crate::hash; -/// One resolved upstream VCS source (DESIGN.md §3, "Three things to pin"). -/// -/// The commit SHA alone is sufficient: a git commit transitively commits to its -/// tree, and a gitlink in that tree commits to any submodule's commit. +/// One resolved upstream VCS source (DESIGN.md §3). The commit SHA alone is +/// sufficient: a git commit transitively commits to its tree, and a gitlink in +/// that tree commits to any submodule's commit. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct UpstreamPin { - /// Index into the PKGBUILD `source=()` array. pub index: usize, pub url: String, /// The ref we asked for: `HEAD`, a tag, or an explicit commit. pub ref_: String, - /// Branch the ref resolved to, when known. pub branch: Option<String>, - /// Resolved commit SHA. This is the pin. + /// The pin. pub commit: String, } -/// A row of the Stage B cache (§5.2): the version that resolution produced, -/// with the pins it was computed from. -/// -/// This lives with the schema because the table lives here — the persistence -/// layer must not name a type from the module that owns VCS probing, which is -/// the dependency pointing the wrong way (§6 M-6). `watch::upstream::StageB` -/// is this plus `cached`, and that extra field is the reason the two are not -/// the same type: "was this answer a cache hit?" is a fact about the resolution -/// that just happened, not a column. +/// A row of the Stage B cache (§5.2): the version resolution produced, with the +/// pins it was computed from. This lives with the schema because the table does — +/// the persistence layer must not name a type from the module that owns VCS +/// probing (§6 M-6). #[derive(Debug, Clone)] pub struct StageBCacheRow { pub epoch: String, @@ -55,20 +45,16 @@ pub struct SourceDigest { /// sha256, or the resolved VCS commit for vcs sources. pub digest: String, pub size: u64, - /// True when the PKGBUILD gave us no checksum to trust for this source — - /// `SKIP`, a malformed digest, or nothing at all. - /// - /// It means that and nothing else (m-19). It used to be hardcoded `true` for - /// VCS entries, where it reads as a warning the recipe never earned: a - /// `-git` source has no checksum by design because the *pin* is the - /// integrity. Ask [`SourceDigest::is_vcs`] when you need to know which of - /// the two mechanisms protects an entry. + /// True when the PKGBUILD gave us no checksum to trust — `SKIP`, a malformed + /// digest, or nothing at all. It means that and nothing else (m-19): a `-git` + /// source has no checksum by design because the *pin* is the integrity. Ask + /// [`SourceDigest::is_vcs`] which mechanism protects an entry. pub skip_declared: bool, } impl SourceDigest { - /// True when this entry's integrity comes from a resolved commit rather than - /// a content hash. + /// True when this entry's integrity comes from a resolved commit rather than a + /// content hash. pub fn is_vcs(&self) -> bool { matches!(self.kind.as_str(), "vcs" | "git" | "svn" | "hg" | "bzr") } @@ -93,35 +79,28 @@ pub struct Identity { } impl Identity { - /// The hash that makes I3 a fact: two byte-identical inputs never produce - /// two candidates, and any change to what becomes a byte in the artifact - /// produces a new one. - /// - /// A digest of the canonical JSON of the identity tuple. This is the value - /// an approval must echo: two candidates share an `identity_hash` only if - /// every pin, digest and version in them is identical. A value that cannot - /// be serialized is an error rather than a digest — a shared fallback digest - /// would be the one way two identities could collide by accident. + /// The hash that makes I3 a fact: two byte-identical inputs never produce two + /// candidates, and any change to what becomes a byte in the artifact produces a + /// new one. This is the value an approval must echo; a value that cannot be + /// serialized is an error rather than a digest, because a shared fallback + /// digest would be the one way two identities could collide by accident. pub fn hash(&self) -> crate::error::Result<String> { Ok(format!("sha256:{}", hash::hex(hash::canonical_json(self)?.as_bytes()))) } } -/// The review state machine (§7.1). -/// -/// A candidate is what a human decides on, and the decision is the one thing in -/// this system that must never be overwritten by accident: an approval that -/// silently replaced a rejection, or a superseded review resurrected, would -/// break I2 and I3 without any symptom. So the states are an enum, and +/// The review state machine (§7.1). A decision must never be overwritten by +/// accident — an approval that silently replaced a rejection would break I2 and +/// I3 without any symptom — so the states are an enum and /// [`crate::db::candidates::resolve_in`] refuses a move the machine forbids. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum CandidateState { - /// Open: nobody has decided yet. The only state a reviewer can act on. + /// The only state a reviewer can act on. PendingReview, Approved, Rejected, - /// Frozen: a newer review of the same pkgbase took its place (§7.1). + /// A newer review of the same pkgbase took its place (§7.1). Superseded, /// Not approved because something it needs is missing (§10.4). Blocked, @@ -150,13 +129,11 @@ impl CandidateState { CandidateState::ALL.iter().copied().find(|c| c.as_str() == s) } - /// The state a reviewer can still act on. pub fn is_open(&self) -> bool { *self == CandidateState::PendingReview } - /// May a candidate in this state be written to `to`? Re-writing the state it - /// already has is a no-op, not a move. + /// Re-writing the state a row already has is a no-op, not a move. pub fn can_transition(&self, to: CandidateState) -> bool { use CandidateState::*; if *self == to { @@ -195,7 +172,6 @@ pub mod candidate_kind { #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ReleaseState { - /// In the served index. Published, /// Taken out of the index (§9 withdrawal); the row stays (§15). Withdrawn, @@ -222,8 +198,7 @@ impl ReleaseState { ReleaseState::ALL.iter().copied().find(|r| r.as_str() == s) } - /// Withdrawal is the only move a release makes on its own; a failed-unbuilt - /// release is a record of an attempt, and a published one is live. + /// Withdrawal is the only move a release makes on its own. pub fn can_transition(&self, to: ReleaseState) -> bool { use ReleaseState::*; if *self == to { @@ -243,8 +218,8 @@ impl std::fmt::Display for ReleaseState { } /// What the state enums below have in common: a closed set of column values, -/// parsed where a row is read. `db::state_col` uses this to fail a row whose -/// state the code does not know instead of defaulting it. +/// parsed where a row is read, so `db::state_col` can fail an unknown state +/// instead of defaulting it. pub trait StateEnum: Copy + Sized { /// The name of the machine, for the error message. const KIND: &'static str; @@ -272,17 +247,11 @@ impl_state_enum!(StepState, "build step"); impl_state_enum!(ReleaseState, "release"); impl_state_enum!(SubscriptionState, "subscription"); -/// The build state machine (§7.1, §8.2). -/// -/// This used to be seven `&str` constants and a `set_state(&str)` that wrote any -/// string a caller invented, so the machine existed only as `WHERE state IN -/// (...)` clauses scattered across six modules — nothing could tell you that -/// `succeeded → running` is nonsense. The enum is the machine: a state is one -/// of these seven, it is parsed where a row is read, and `can_transition` is -/// the only way a write happens. +/// The build state machine (§7.1, §8.2). A state is one of these seven, it is +/// parsed where a row is read, and `can_transition` is the only way a write +/// happens. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum BuildState { - /// Approved and waiting for a worker. Queued, /// Claimed by a worker with a lease (§8.2). Leased, @@ -306,8 +275,8 @@ impl BuildState { BuildState::Cancelled, ]; - /// The text in the `state` column. The spelling is part of the schema: the - /// reaper, the dispatcher and the UI all speak it. + /// The text in the `state` column — a spelling the reaper, dispatcher and UI + /// all speak. pub fn as_str(&self) -> &'static str { match self { BuildState::Queued => "queued", @@ -320,17 +289,14 @@ impl BuildState { } } - /// The only way in from the database text. An unrecognised state is `None`, - /// and the row boundary turns that into an error rather than a silent - /// fallback: a state we cannot name is a state we must not act on. + /// An unrecognised state is `None`, and the row boundary turns that into an + /// error: a state we cannot name is one we must not act on. pub fn parse(s: &str) -> Option<BuildState> { BuildState::ALL.iter().copied().find(|b| b.as_str() == s) } - /// Nothing happens to a finished build by itself. `Succeeded` is final — - /// the release is published and the row is history (§15). `Failed` and - /// `Cancelled` end a worker's involvement, and only an explicit human - /// requeue or resume moves them again ([`BuildState::can_transition`]). + /// Nothing happens to a finished build by itself; only an explicit human + /// requeue or resume moves it again. pub fn is_terminal(&self) -> bool { matches!( self, @@ -338,17 +304,11 @@ impl BuildState { ) } - /// May a row in this state be written to `to`? - /// - /// Writing the state a row already has is always allowed: it is a no-op, not - /// a move. The step loop re-asserts `Running` at every step boundary (§8.3), - /// and re-running a finished build must stay harmless rather than turn into - /// an error. - /// - /// Everything else is refused by [`crate::db::builds::set_state`], and the - /// refusals are the point: nothing revives a `Succeeded` build, and a build - /// reaped back to `Queued` cannot be completed by the zombie worker that - /// lost its lease — that refusal is the alarm. + /// Writing the state a row already has is always allowed: the step loop + /// re-asserts `Running` at every step boundary (§8.3). Everything else is + /// refused by [`crate::db::builds::set_state`], and the refusals are the point: + /// nothing revives a `Succeeded` build, and a build reaped back to `Queued` + /// cannot be completed by the zombie worker that lost its lease. pub fn can_transition(&self, to: BuildState) -> bool { use BuildState::*; if *self == to { @@ -356,16 +316,13 @@ impl BuildState { } match self { // The dispatcher claims queued builds; `aur-build run <id>` runs one - // in the foreground without a lease, so `Running` is legal from here - // too. A dependency can be discovered before a worker ever starts. + // in the foreground without a lease. Queued => matches!(to, Leased | Running | BlockedMissingDep | Cancelled), Leased => matches!(to, Running | Queued | BlockedMissingDep | Succeeded | Failed | Cancelled), Running => matches!(to, Queued | BlockedMissingDep | Succeeded | Failed | Cancelled), BlockedMissingDep => matches!(to, Queued | Cancelled), - // A failed build is resumed on the same row — that is I5 (the step - // checkpoints say where to continue) and §8.4's human requeue. + // A failed build is resumed on the same row — that is I5 (§8.4). Failed => matches!(to, Queued | Running), - // §8.4: requeue is a human decision, not a policy. Cancelled => to == Queued, Succeeded => false, } @@ -381,7 +338,6 @@ impl BuildState { .collect() } - /// The states the queue considers "in flight" for metrics and the index. pub fn active() -> &'static [BuildState] { &[ BuildState::Queued, @@ -398,11 +354,9 @@ impl std::fmt::Display for BuildState { } } -/// The step checkpoint state machine (§8.3, I5). -/// -/// The checkpoint row is what a resumed build reads to decide what not to redo, -/// so the rule that matters is that a completed checkpoint is frozen: a step -/// recorded `succeeded` or `skipped` is never re-run and never rewritten. +/// The step checkpoint state machine (§8.3, I5). The checkpoint row is what a +/// resumed build reads to decide what not to redo, so a completed checkpoint is +/// frozen. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum StepState { @@ -441,7 +395,7 @@ impl StepState { } /// I5: the resume skips a step in one of these two states, so nothing may - /// move it again — a checkpoint that can be rewritten is not a checkpoint. + /// move it again. pub fn is_done(&self) -> bool { matches!(self, StepState::Succeeded | StepState::Skipped) } @@ -565,13 +519,10 @@ pub struct SourceEntry { pub url: String, /// Explicit filename (`::name` / `::` prefix handling). pub filename: Option<String>, - /// `#commit=` fragment. pub commit: Option<String>, - /// `#tag=` fragment. pub tag: Option<String>, - /// `#branch=` fragment. pub branch: Option<String>, - /// VCS kind if the url is prefixed `git+`, `svn+`, `hg+`, `bzr+`. + /// Set when the url is prefixed `git+`, `svn+`, `hg+`, `bzr+`. pub vcs: Option<String>, /// True for files shipped inside the AUR repo (no scheme). pub local: bool, @@ -610,21 +561,18 @@ pub struct Recipe { pub install: Option<String>, /// Names of the binary packages this pkgbase emits (split pkgbases have N). pub pkgnames: Vec<String>, - /// Per-package depends, for split pkgbases. pub pkg_depends: Vec<(String, Vec<String>)>, /// Raw PKGBUILD text, for display and diffing. pub pkgbuild: String, - /// Raw .SRCINFO text when it was present. pub srcinfo: Option<String>, /// True if `--skippgpcheck` appears in the PKGBUILD. pub skipgpcheck: bool, - /// Parsed `source=()` entries. Derived from `source`, so not serialized. + /// Derived from `source`, so not serialized. #[serde(skip, default)] pub source_entries: Vec<SourceEntry>, } impl Recipe { - /// `epoch:pkgver-pkgrel` as displayed to consumers. pub fn full_version(&self) -> String { crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) } diff --git a/src/db/queries.rs b/src/db/queries.rs index fe0518f..924051d 100644 --- a/src/db/queries.rs +++ b/src/db/queries.rs @@ -1,6 +1,3 @@ -//! Typed query helpers. Everything that mutates goes through the writer actor; -//! everything that reads takes a `&Connection` from the reader pool. - use rusqlite::{params, params_from_iter, OptionalExtension, Row}; use crate::db::*; @@ -12,9 +9,7 @@ use crate::time; /// Every setting, for the settings page. /// /// Row-error policy, applied everywhere in `db` (m-9): a row that cannot be read -/// fails the query. `filter_map(|r| r.ok())` used to drop such rows silently, -/// which is fine for a page that merely looks incomplete and fatal for the -/// callers that decide what to reap, what to claim, and what is stale. +/// fails the query rather than being dropped silently. pub fn all_settings(db: &Db) -> Result<Vec<(String, String)>> { db.read(|c| { let mut st = c.prepare("SELECT key, value FROM settings ORDER BY key")?; @@ -34,12 +29,10 @@ pub fn setting(db: &Db, key: &str) -> Result<Option<String>> { /// An integer setting, or `default`. /// /// The policy, stated once (m-9): a *missing* setting is normal — the default is -/// the answer, and every knob in `settings` has one. A setting that is present -/// but unparseable, or a read that failed outright, is not normal, and silently -/// returning the default would hide an operator's typo behind a config that -/// looks applied. Both still fall back — these are tuning knobs, and refusing to -/// start over `stage_b_cooldown = 86400x` is worse than using the default — but -/// they fall back out loud. +/// the answer. A setting present but unparseable, or a read that failed, is not, +/// and silently returning the default would hide an operator's typo. Both still +/// fall back, because refusing to start over a tuning knob is worse — but they +/// fall back out loud. pub fn setting_i64(db: &Db, key: &str, default: i64) -> i64 { match setting(db, key) { Ok(None) => default, @@ -101,14 +94,9 @@ pub fn audit( }) } -/// An audit row to append inside someone else's transaction. -/// -/// Build one with [`AuditEntry::human`] or [`AuditEntry::system`] rather than -/// by writing the literal: `actor_kind` is a closed set and the timestamp is -/// not the caller's to improvise (§6 m-4). Three review sites had each -/// hand-built this struct, and their `detail` shapes drifted until the log -/// could not answer, for two of the three, which candidate bytes the decision -/// was about. +/// An audit row to append inside someone else's transaction. Build one with +/// [`AuditEntry::human`] or [`AuditEntry::system`]: `actor_kind` is a closed set +/// and the timestamp is not the caller's to improvise (§6 m-4). #[derive(Debug)] pub struct AuditEntry<'a> { pub at: &'a str, @@ -145,10 +133,8 @@ impl<'a> AuditEntry<'a> { } } -/// Append an audit row inside a caller's transaction (I10). This is the variant -/// every multi-statement mutation uses: the record of a decision commits with -/// the decision or not at all, so there is no window where an audit row -/// describes a change that was rolled back. +/// Append an audit row inside a caller's transaction (I10), so the record of a +/// decision commits with the decision or not at all. pub fn audit_in(tx: &rusqlite::Transaction<'_>, e: &AuditEntry<'_>) -> Result<()> { tx.execute( "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json) @@ -523,16 +509,12 @@ const RELEASE_COLS_R: &str = "r.id, r.pkgbase_id, r.candidate_id, r.approval_id, r.recipe_hash, r.upstream_pins_json, r.source_digests_json, r.epoch, r.pkgver, r.pkgrel, \ r.world_snapshot_id, r.state, r.published_at"; -/// Withdraw a published release and remove the packages it served (§9 -/// `repo-remove`, decision 23). Runs in the caller's transaction so the removal -/// and the audit row that explains it are one fact. -/// Take a release out of the served index (§9, decision 23). +/// Take a release out of the served index (§9, decision 23), in the caller's +/// transaction so the removal and the audit row explaining it are one fact. /// /// Refuses a release that is not currently published (m-10): re-withdrawing used -/// to report success and rewrite nothing, so an operator who clicked twice — or -/// withdrew a release that had never been live — got a green result and no -/// explanation. The write is a compare-and-swap on `state='published'`, and the -/// refusal names the state that was actually there. +/// to report success and rewrite nothing. The write is a compare-and-swap on +/// `state='published'`, and the refusal names the state that was actually there. pub fn withdraw_release_in(tx: &rusqlite::Transaction<'_>, release_id: i64) -> Result<()> { let n = tx.execute( "UPDATE release SET state='withdrawn' WHERE id=?1 AND state='published'", @@ -679,10 +661,9 @@ pub fn index_version(db: &Db, name: &str) -> Result<Option<String>> { }) } -/// The exact artifact we serve for a package name: `(version, digest)` of the -/// in-index row's artifact. This is what a build's lease manifest pins — the -/// dependency arrives as these bytes or the build fails closed (§8, -/// provisioning); nothing about it is re-resolved at build time. +/// The exact artifact we serve for a package name: `(version, digest)`. This is +/// what a build's lease manifest pins — the dependency arrives as these bytes or +/// the build fails closed (§8). pub fn index_artifact(db: &Db, name: &str) -> Result<Option<(String, String)>> { db.read(|c| { c.query_row( @@ -766,9 +747,7 @@ pub fn builds_for_pkgbase(db: &Db, pkgbase_id: i64, limit: i64) -> Result<Vec<cr // ------------------------------------------------------------ publish writes -- // // Publishing is the one externally visible step, so every statement it needs is -// here and the *decision* stays in `pipeline::publish`: the caller opens the -// transaction, calls these in order, and bails if the compare-and-swap says the -// world moved (I4). +// here and the *decision* stays in `pipeline::publish` (I4). /// The on-disk path of an artifact, by id. pub fn artifact_path(db: &Db, id: i64) -> Result<Option<String>> { @@ -899,9 +878,8 @@ pub fn insert_package_in( // ------------------------------------------------------------ staleness reads -- // -// Staleness is derived on read (§10.2), and these are the reads it is derived -// from. They return plain tuples: the *meaning* ("this dependency moved") is -// `watch::staleness`'s business, the SQL is this module's. +// Staleness is derived on read (§10.2). These return plain tuples: the *meaning* +// is `watch::staleness`'s business, the SQL is this module's. /// `(pkgbase, world members JSON)` for every published release, taken from the /// world snapshot its build recorded (§10.1). @@ -944,13 +922,12 @@ pub fn served_vs_offered_pkgvers(db: &Db) -> Result<Vec<(String, String, String) }) } -/// The `srcinfo_json` of the recipe the index's copy of a package was built -/// from — what its dependency list actually said. -/// Every in-index package's recipe JSON, as (name, srcinfo_json). +/// Every in-index package's recipe JSON, as (name, srcinfo_json) — what each +/// dependency list actually said. /// -/// One query, not one per package (m-17). `watch::staleness::dependents_of` -/// wants the whole table: asking for each package by name was an N+1 whose N is -/// the size of the index, on a code path that runs after every publish. +/// One query, not one per package (m-17): `watch::staleness::dependents_of` +/// wants the whole table, and asking per name was an N+1 on a path that runs +/// after every publish. pub fn index_recipes(db: &Db) -> Result<Vec<(String, String)>> { db.read(|c| { let mut stmt = c.prepare( @@ -1314,10 +1291,7 @@ pub fn list_audit(db: &Db, limit: i64) -> Result<Vec<AuditRow>> { // -------------------------------------------------------------- metrics reads -- // -// The metrics surface is derived from live state, never stored (§10.3: a -// counter that is written is a counter that can drift out of truth). These are -// the reads that derivation is made of, and they live here because the schema -// they read lives here. +// The metrics surface is derived from live state, never stored (§10.3). /// The `count(*)` idiom in one place, so a metric cannot accidentally become a /// `count(*)` of a join. @@ -1412,9 +1386,8 @@ pub fn last_gc_age_secs(db: &Db, now: &str) -> Result<Option<i64>> { Ok(at.and_then(|t| time::delta_secs(now, &t))) } -/// Seconds since the last successful poll of any source, if there has been one. -/// This is the metric that catches a watcher that stopped, which no log line -/// will tell you about. +/// Seconds since the last successful poll of any source. This is the metric that +/// catches a watcher that stopped. pub fn last_poll_age_secs(db: &Db, now: &str) -> Result<Option<i64>> { let at = db.read(|c| { c.query_row("SELECT max(last_checked_at) FROM subscription", [], |r| r.get::<_, Option<String>>(0)) @@ -1575,10 +1548,9 @@ pub fn index_pkgbase_drift(db: &Db) -> Result<(Vec<String>, Vec<String>)> { }) } -/// An approved change whose build failed and which therefore never reached the -/// index (§8.4). This is the state that must never look healthy: a human said -/// yes, the build died, and the index is quietly still serving the previous -/// version. Surfacing it is the whole point of `approved_but_unbuilt`. +/// An approved change whose build failed and never reached the index (§8.4). A +/// human said yes, the build died, and the index is quietly still serving the +/// previous version; surfacing that is the whole point. #[derive(Debug, Clone)] pub struct Unbuilt { pub pkgbase: String, @@ -1593,9 +1565,8 @@ pub struct Unbuilt { pub fn approved_but_unbuilt(db: &Db) -> Result<Vec<Unbuilt>> { db.read(|c| { // The version strings are assembled in Rust by `pkgver::full_version`, - // not by a CASE expression here (m-18): the epoch-omitted form is a rule - // of ours, and a second copy of it in SQL is a second rule that can - // disagree with the first. + // not by a CASE expression here (m-18): a second copy of the + // epoch-omission rule in SQL is a second rule that can disagree. let mut stmt = c.prepare( "SELECT p.name, cnd.epoch, cnd.pkgver, cnd.pkgrel, diff --git a/src/error.rs b/src/error.rs index 342c628..f849f83 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,5 +1,3 @@ -//! Error type shared across the application. - use std::fmt; #[derive(Debug, thiserror::Error)] @@ -30,20 +28,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. + /// The sandbox pool could not fit a lease right now. Not a failure and not a + /// retry: the build waits, as 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". + /// The world inside the sandbox is not the world the plan approved: a pinned + /// dependency did not land, or the closure was incomplete. Its own class so + /// a test can tell "the sandbox lied" 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). + /// A failure the outside world caused and a retry may clear (§8.4). #[error("transient: {0}")] Transient(String), #[error("{0}")] @@ -86,25 +81,19 @@ impl Error { } /// 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. + /// blocks and waits rather than failing. 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. + /// True when a retry could plausibly help (§8.4). /// - /// `Error::Io` is *not* automatically transient (m-14). `ENOSPC` and - /// `EACCES` are `Io`, and treating them as retryable meant a full disk or a - /// misconfigured root turned into three identical failures, a shrug, and a - /// build that never got the operator's attention. Only the kinds that mean - /// "the same call might work in a moment" are retried. + /// `Error::Io` is *not* automatically transient (m-14): `ENOSPC` and `EACCES` + /// are `Io`, and retrying them burns attempts while a full disk goes unnoticed. 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. + // A quota is capacity, not a hiccup; the build blocks instead. Error::PoolExhausted(_) | Error::WorldMismatch(_) => false, Error::Io(e) => matches!( e.kind(), @@ -129,9 +118,6 @@ mod tests { #[test] fn a_full_disk_is_not_a_retryable_failure() { - // m-14: `Error::Io` used to mean "retry", so ENOSPC and EACCES — both - // plain `Io` — turned into three identical failures and a build that - // never announced itself as broken. let enospc = Error::Io(std::io::Error::from_raw_os_error(28)); let eacces = Error::Io(std::io::Error::from_raw_os_error(13)); assert!(!enospc.is_transient(), "a full disk does not clear itself between retries"); @@ -146,7 +132,6 @@ 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/fetch.rs b/src/fetch.rs index c1c4575..c802339 100644 --- a/src/fetch.rs +++ b/src/fetch.rs @@ -1,9 +1,3 @@ -//! Outbound HTTP. `ureq` is blocking, which is the whole point of this stack -//! (DESIGN.md §4: "`reqwest` pulls in tokio even in blocking mode — avoid"). -//! -//! `file://` is supported as a first-class scheme so the test corpus can serve -//! sources from disk with no network (§16a). - use std::io::{Read, Write}; use std::path::PathBuf; @@ -1,9 +1,3 @@ -//! Shelling out to `git` (DESIGN.md §4: "shell out to git ... avoids libgit2 -//! build pain"). -//! -//! Every git operation the system performs goes through here so the subprocess -//! surface is auditable in one place. - use std::path::Path; use std::process::{Command, Output}; @@ -40,8 +34,8 @@ pub fn git_ok(cwd: Option<&Path>, args: &[&str]) -> bool { git(cwd, args).is_ok() } -/// `git ls-remote <url> HEAD` — the cheap poll (§5.1). Returns the remote HEAD -/// SHA, or `None` when the remote is gone (deletion / orphan handling). +/// `git ls-remote <url> HEAD` — the cheap poll (§5.1). `None` when the remote is +/// gone. pub fn ls_remote_head(url: &str) -> Result<Option<String>> { match git(None, &["ls-remote", url, "HEAD"]) { Ok(out) => { @@ -91,10 +85,9 @@ fn is_missing_remote(e: &Error) -> bool { || s.contains("404") } -/// Clone an AUR mirror. `--mirror` so that `git fetch` actually moves our refs -/// (a plain clone would leave HEAD on the original commit), and **never** -/// `--filter=blob:none`: a partial clone can lazily drop blobs and we must be -/// able to materialize any historical commit forever (§5.1). +/// Clone an AUR mirror. `--mirror` so that `git fetch` actually moves our refs, +/// and **never** `--filter=blob:none`: a partial clone can lazily drop blobs and +/// we must be able to materialize any historical commit forever (§5.1). pub fn clone(url: &str, dest: &Path) -> Result<()> { if dest.exists() { return Ok(()); @@ -132,8 +125,8 @@ pub fn head(mirror: &Path) -> Result<String> { Ok(git(Some(mirror), &["rev-parse", "HEAD"])?.trim().to_string()) } -/// True if `commit` exists in the local mirror. Guards against a force-pushed -/// AUR history making a pin vanish (§16 mirror divergence). +/// True if `commit` exists in the local mirror. Guards against a force-pushed AUR +/// history making a pin vanish (§16 mirror divergence). pub fn has_commit(mirror: &Path, commit: &str) -> bool { git_ok(Some(mirror), &["cat-file", "-e", &format!("{commit}^{{commit}}")]) } @@ -192,8 +185,7 @@ pub fn materialize(mirror: &Path, commit: &str, dest: &Path) -> Result<()> { Ok(()) } -/// `git log --oneline range` — review context (§5.1) and the upstream delta -/// panel (§6). +/// `git log --oneline range` — review context (§5.1) and the upstream delta panel. pub fn log_oneline(mirror: &Path, range: &str) -> Result<Vec<String>> { let out = git(Some(mirror), &["log", "--oneline", range])?; Ok(out.lines().map(|l| l.to_string()).collect()) diff --git a/src/hash.rs b/src/hash.rs index 0321437..70c3791 100644 --- a/src/hash.rs +++ b/src/hash.rs @@ -1,6 +1,3 @@ -//! Hashing helpers. `sha256` hex strings are the currency of identity and -//! provenance throughout the system (DESIGN.md §3, §5.3). - use sha2::{Digest, Sha256}; use std::io::{self, Read, Write}; @@ -22,10 +19,9 @@ pub fn short(bytes: &[u8], n: usize) -> String { h[..n.min(h.len())].to_string() } -/// Stream-hash a reader, optionally teeing every byte into `sink`. -/// -/// Used to hash a download while writing it into the source cache, so the -/// bandwidth is paid for once (§5.3 "stream-hash, don't buffer"). +/// Stream-hash a reader, optionally teeing every byte into `sink` — so a +/// download can be hashed into the source cache without paying for the +/// bandwidth twice (§5.3). pub fn digest_reader<R: Read>(mut r: R, mut sink: Option<&mut dyn Write>) -> io::Result<(String, u64)> { let mut h = Sha256::new(); let mut buf = vec![0u8; 64 * 1024]; @@ -50,11 +46,8 @@ pub fn digest_file(path: &std::path::Path) -> io::Result<(String, u64)> { digest_reader(&mut br, None) } -/// Hash of a canonical, sorted list of `(path, blob_hash)` pairs. -/// /// This is `recipe_hash` (DESIGN.md §3): a digest over *every* file in the AUR -/// snapshot tree — PKGBUILD, .SRCINFO, *.install and any shipped patches or -/// assets — because a patch file shipped in the AUR repo is part of the recipe +/// snapshot tree, because a patch shipped in the AUR repo is part of the recipe /// and is a classic silent-change vector. pub fn recipe_hash(entries: &[(String, String)]) -> String { let mut sorted: Vec<&(String, String)> = entries.iter().collect(); @@ -69,17 +62,12 @@ pub fn recipe_hash(entries: &[(String, String)]) -> String { hex::encode(h.finalize()) } -/// Serialize a value to canonical JSON: compact, with every object's keys in -/// sorted order, so equal values always produce equal bytes. -/// -/// The ordering is not free in `serde_json` — a struct serializes in field -/// declaration order and a map in whatever order it happens to hold — so the -/// value is routed through `serde_json::Value`, whose map is a `BTreeMap`. -/// That makes the name true rather than aspirational. +/// Serialize to canonical JSON: compact, object keys sorted, so equal values always +/// produce equal bytes. The value is routed through `serde_json::Value` because a +/// struct otherwise serializes in field declaration order. /// -/// A serialization failure is an error. It used to be `"{}"`, which meant every -/// value that failed to serialize hashed to the same digest — and this is the -/// function behind `Identity::hash`, the value an approval echoes (§6 M-2). +/// A serialization failure is an error, not `"{}"`: this is the function behind +/// `Identity::hash` (M-2). pub fn canonical_json<T: serde::Serialize>(v: &T) -> Result<String, serde_json::Error> { serde_json::to_string(&serde_json::to_value(v)?) } diff --git a/src/http/auth.rs b/src/http/auth.rs index 8c56c1f..9689fd8 100644 --- a/src/http/auth.rs +++ b/src/http/auth.rs @@ -1,26 +1,11 @@ -//! Session and CSRF (§12: "form posts are plain `<form method=post>` with a -//! CSRF token"). -//! -//! One operator, one shared credential, no user table (§14). A session is an -//! opaque random id held in memory; the CSRF token is derived from it, so a -//! cross-site form cannot produce one it has not seen, and there is no token -//! table to keep in step with the sessions. -//! -//! **The sid is the credential.** A sid is minted for anonymous visitors too, -//! because the CSRF token has to be derivable before anyone has typed a -//! password; what the password buys is the `authenticated` flag on one sid. -//! Nothing else in the request proves who you are, which is why there is no -//! separate "logged in" cookie to forge. - use std::collections::HashMap; use std::sync::Mutex; use std::sync::OnceLock; use crate::hash; -/// Live sids and whether each has passed the password gate. One map, so the -/// two facts cannot drift apart: dropping a session removes its authentication -/// with it. +/// Live sids and whether each has passed the password gate. One map, so +/// dropping a session removes its authentication with it. static SESSIONS: OnceLock<Mutex<HashMap<String, bool>>> = OnceLock::new(); fn sessions() -> &'static Mutex<HashMap<String, bool>> { @@ -28,19 +13,14 @@ fn sessions() -> &'static Mutex<HashMap<String, bool>> { } /// Random hex token from the system RNG, or `None` when there is no usable one. -/// -/// The old version read `/dev/urandom` into a zeroed buffer, ignored every -/// error, and hashed the result anyway (§6 m-13): a failed read produced a -/// session id derived from a buffer of zeros plus the clock and a counter, -/// which is guessable by anyone who can guess roughly when the process started -/// — and nothing anywhere said the RNG had failed. A session id is the whole -/// credential now (C-1), so "no RNG" is a refusal, not a weaker token. +/// A session id is the whole credential (C-1), so "no RNG" is a refusal rather +/// than a weaker, guessable token. fn random_hex() -> Option<String> { use std::io::Read; let mut buf = [0u8; 32]; let mut f = std::fs::File::open("/dev/urandom").ok()?; f.read_exact(&mut buf).ok()?; - // Mixed in regardless, so two calls in the same instant still differ. + // Mixed in so two calls in the same instant still differ. let nanos = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_nanos()) @@ -68,8 +48,7 @@ pub fn is_valid_session(sid: &str) -> bool { sessions().lock().map(|s| s.contains_key(sid)).unwrap_or(false) } -/// Mark a session as having passed the password gate. Only ever called with a -/// sid this process minted, and it cannot mint one: an unknown sid stays +/// Mark a session as having passed the password gate. An unknown sid stays /// unknown rather than being inserted as a side effect of a login attempt. pub fn authenticate(sid: &str) { if let Ok(mut s) = sessions().lock() { @@ -79,8 +58,8 @@ pub fn authenticate(sid: &str) { } } -/// The gate's whole question: is this sid one we issued *and* did someone type -/// the password into a form on this session? +/// The gate's whole question: is this sid one we issued, and did someone type +/// the password into a form on it? pub fn is_authenticated(sid: &str) -> bool { sessions().lock().map(|s| s.get(sid).copied().unwrap_or(false)).unwrap_or(false) } @@ -91,8 +70,8 @@ pub fn drop_session(sid: &str) { } } -/// The CSRF token for a session. Derived rather than stored: it cannot drift -/// out of sync with the session, and it is cheap to recompute per request. +/// The CSRF token for a session. Derived rather than stored, so it cannot drift +/// out of sync with the session. pub fn csrf_token(sid: &str) -> String { hash::hex(format!("csrf|{sid}").as_bytes())[..32].to_string() } @@ -125,8 +104,8 @@ pub fn parse_cookies(header: &str) -> Vec<(String, String)> { .collect() } -/// Check the shared password. Empty password means the UI is open, which is the -// default on loopback; the CSRF gate still applies. +/// An empty password means the UI is open, which is the default on loopback; +/// the CSRF gate still applies. pub fn password_ok(cfg: &crate::config::Config, given: &str) -> bool { cfg.password.is_empty() || constant_time_eq(&cfg.password, given) } diff --git a/src/http/forms.rs b/src/http/forms.rs index 6e36e38..03da7b8 100644 --- a/src/http/forms.rs +++ b/src/http/forms.rs @@ -1,8 +1,3 @@ -//! `application/x-www-form-urlencoded` parsing and HTML escaping. -//! -//! Deliberately tiny: the only forms in this application are ours, so we need -//! decoding for names, versions and hashes — not a general MIME parser. - /// Percent-decode one token (`+` means space in a form body). pub fn decode(s: &str) -> String { let bytes = s.as_bytes(); diff --git a/src/http/mod.rs b/src/http/mod.rs index 81c526c..11ea107 100644 --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -1,16 +1,3 @@ -//! The web surface (§12). -//! -//! `tiny_http`, thread-per-connection, blocking. Handlers **read** through the -//! thread-local read-only connections and never touch the write connection; -//! mutations are handed to the writer actor as a transaction request. That is -//! what keeps a slow browser from ever holding the database lock. -//! -//! Two guards on every POST: a session id, and a CSRF token that must match -//! it. The session id is the only credential the browser holds, and it counts -//! as authentication only if someone typed the password into a form on that -//! exact session (§12). Forms are plain `<form method=post>`, so the whole -//! approval flow works with JavaScript switched off. - mod auth; mod forms; mod render; @@ -36,10 +23,8 @@ pub struct Req { pub body: String, pub cookies: Vec<(String, String)>, pub query_pairs: Vec<(String, String)>, - /// The body's form pairs, parsed once when the request is decoded (n-3). - /// `form_get` used to re-parse the whole body on every call, and a single - /// handler — approve, with its two hashes, its note and its CSRF token — - /// asks five times. + /// The body's form pairs, parsed once when the request is decoded (n-3) — a + /// single handler asks for five of them. pub form_pairs: Vec<(String, String)>, /// Whether the client said it can take gzip. Used to decide whether to hand /// out the precompressed static asset. @@ -67,9 +52,9 @@ pub struct Res { pub content_type: String, pub body: Vec<u8>, pub headers: Vec<(String, String)>, - /// When set, the response body is produced by reading this to EOF instead of - /// `body`. Used for the log tail (§13), which must stream bytes as a build - /// appends them rather than buffering a response that never finishes. + /// When set, the body is produced by reading this to EOF instead of `body`. + /// Used for the log tail (§13), which must stream bytes as a build appends + /// them rather than buffering a response that never finishes. pub stream: Option<Box<dyn std::io::Read + Send>>, /// Length of `stream` when it is known up front, so the response can carry a /// Content-Length instead of chunked transfer encoding. @@ -84,8 +69,8 @@ impl Res { Self { status, content_type: "text/plain; charset=utf-8".into(), body: body.into_bytes(), headers: Vec::new(), stream: None, stream_len: None } } /// A streamed response. `known_len` lets a static file be sent with a - /// Content-Length instead of chunked, which is what a browser wants for a - /// file it already knows the size of. + /// Content-Length, which is what a browser wants for a file whose size it + /// already knows. pub fn stream(content_type: &str, reader: impl std::io::Read + Send + 'static, known_len: Option<usize>) -> Self { Self { status: 200, @@ -221,8 +206,8 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result< request.respond(builder) } -/// Route table (§12). Everything is one flat match: there is no middleware -/// stack, just the session gate and then a path. +/// Route table (§12). One flat match: no middleware stack, just the session gate +/// and then a path. fn dispatch(state: &State, req: &Req) -> Res { let seg: Vec<&str> = req.path.trim_matches('/').split('/').filter(|s| !s.is_empty()).collect(); let is_get = req.method == "GET"; @@ -233,17 +218,16 @@ fn dispatch(state: &State, req: &Req) -> Res { ("GET", ["login"]) => return routes::login_form(state, req), ("POST", ["login"]) => return routes::login(state, req), ("GET", ["healthz"]) => return Res::text(200, "ok\n".into()), - // Metrics are counts only — no package names, no versions, no audit - // detail — and a Prometheus scraper has no session to present. Serving - // them unauthenticated is what makes them scrapeable at all; the bind - // address is loopback by default, which is where that is safe. + // Metrics are counts only — no package names, versions, or audit detail + // — and a Prometheus scraper has no session to present. The bind address + // is loopback by default, which is where this is safe. ("GET", ["metrics"]) => return routes::metrics(state), _ => {} } // Session gate: mint a session for anonymous visitors so the CSRF token - // exists even before anyone logs in. It is not a login — `gate` only lets - // through a sid that a successful login marked authenticated. + // exists before anyone logs in. It is not a login — `gate` only lets through + // a sid that a successful login marked authenticated. let (sid, new_session) = match req.cookie("sid") { Some(s) if auth::is_valid_session(&s) => (s, false), _ => match auth::new_session() { diff --git a/src/http/render.rs b/src/http/render.rs index ca3ba51..f049a25 100644 --- a/src/http/render.rs +++ b/src/http/render.rs @@ -1,9 +1,3 @@ -//! Template contexts (§12, §13). -//! -//! Askama compiles every template into Rust at build time, so a missing field -//! is a compile error rather than a blank page at 2am. Contexts are built from -//! live DB state; nothing here writes. - use askama::Template; /// Everything the shared chrome needs. Embedded in each page context because @@ -293,8 +287,7 @@ pub struct Builds { pub recent: Vec<BuildRow>, } -/// The same table on its own, for the htmx fragment refresh. Same fields, so -/// the include in builds.html and this standalone render cannot drift apart. +/// The same table on its own, for the htmx fragment refresh. #[derive(Template)] #[template(path = "builds_table.html")] pub struct BuildsTable { @@ -386,13 +379,10 @@ pub struct SettingRow { pub value: String, } -/// Vendored static assets. htmx arrives in P3; until then this serves the -/// favicon and refuses everything else rather than walking the filesystem. /// Static assets. Two files, both vendored, both served from `include_bytes!` /// so the binary is self-contained and there is no install step and no bundler /// (§13). htmx is the only JavaScript this app ships; it is served precompressed -/// because the raw file is 48 KB and the gzip is 15 KB, and the budget that -/// matters is what a browser actually downloads. +/// because the budget that matters is what a browser actually downloads. pub fn static_asset(name: &str, accept_gzip: bool) -> crate::http::Res { use crate::http::Res; match name { diff --git a/src/http/routes/mod.rs b/src/http/routes/mod.rs index e78cc74..0dfed52 100644 --- a/src/http/routes/mod.rs +++ b/src/http/routes/mod.rs @@ -1,9 +1,3 @@ -//! Route handlers (§12). -//! -//! Every handler reads through `db.read` — the thread-local read-only -//! connection — and hands mutations to the writer actor. A slow client can -//! therefore never hold the write lock, which is the whole point of the split. - use crate::db::{self, builds, model::*}; use crate::review::candidates; use crate::time; diff --git a/src/http/routes/mutations.rs b/src/http/routes/mutations.rs index 133d491..79089b2 100644 --- a/src/http/routes/mutations.rs +++ b/src/http/routes/mutations.rs @@ -1,6 +1,3 @@ -//! The write side of the UI: every handler that changes something, and the flash -//! it answers with. - use crate::db::{self, builds}; use crate::review::{approve as ap, candidates}; use crate::pipeline; diff --git a/src/http/routes/pages.rs b/src/http/routes/pages.rs index dea7de0..f1f3ef8 100644 --- a/src/http/routes/pages.rs +++ b/src/http/routes/pages.rs @@ -1,5 +1,3 @@ -//! The read side of the UI: pages that only ever go through `db.read`. - use crate::db::{self, builds, Db}; use crate::review::{candidates, diff, risk}; use crate::ops; @@ -554,10 +552,9 @@ pub(crate) fn audit(state: &State, req: &Req) -> Res { /// `GET /metrics` in Prometheus text exposition format (§12, §15). /// -/// Everything here is computed from live state on every scrape. There are no -/// counters incremented at event sites, because a counter that has to be -/// maintained by every code path is a counter that quietly drifts the first time -/// a path is added; a query cannot drift. +/// Everything here is computed from live state on every scrape. There are no counters +/// incremented at event sites: a counter every code path has to maintain quietly +/// drifts the first time a path is added; a query cannot drift. pub fn metrics(state: &State) -> Res { match ops::metrics(&state.cfg, &state.db) { Ok(m) => { diff --git a/src/http/sse.rs b/src/http/sse.rs index 5bfb75b..561de33 100644 --- a/src/http/sse.rs +++ b/src/http/sse.rs @@ -1,15 +1,3 @@ -//! The live log tail (§13): `GET /builds/:id/log.stream` as server-sent events. -//! -//! This is a blocking `std::io::Read` polled by the connection's thread, which is -//! exactly the shape §14 asks for — no async runtime, no timer wheel. The -//! pipeline appends to a plain file, so "streaming the log" means noticing that -//! the file grew and forwarding the new bytes. Nothing in the build path knows -//! this reader exists, which is what makes it safe to have at all: a client that -//! disconnects, hangs or never connects cannot slow a build by a microsecond. -//! -//! The stream ends when the build reaches a terminal state and the file has no -//! more bytes, so a browser tab does not hold a connection open forever. - use std::io::{self, Read}; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; @@ -1,10 +1,3 @@ -//! AUR Build Server — see DESIGN.md. -//! -//! One process, many threads, no async. The write path is: watcher detects a -//! change → candidate → human approval → build pipeline → atomic publish into a -//! signed pacman repo. Nothing reaches a consumer without an approval row -//! behind it (I1). - pub mod config; pub mod db; pub mod error; @@ -20,13 +13,9 @@ pub mod recipe; pub mod review; pub mod sandbox; /// The §16a fake toolchain: stand-ins for `makepkg`, `mkarchroot`, `gpg`, -/// `repo-add` and `pacman` so the whole step machine runs without root, network -/// or an Arch chroot. -/// -/// Test-only, and compiled out of a production build (§6 M-4): the module exists -/// only under the `test-support` feature, which nothing but this crate's own -/// dev-dependency enables, and the shim binaries declare the same feature. A -/// binary an operator runs cannot fake a build tool it cannot see. +/// `repo-add` and `pacman`, so the whole step machine runs without root, network +/// or an Arch chroot. Compiled out of a production build (§6 M-4): a binary an +/// operator runs cannot fake a build tool it cannot see. #[cfg(feature = "test-support")] pub mod shims; pub mod time; diff --git a/src/main.rs b/src/main.rs index ccd20a2..edfcd44 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,11 +1,3 @@ -//! `aur-build` — the operator's command line (§7.2, §12). -//! -//! P0 ships the approval path as a CLI subcommand: the same code the web UI -//! will call in P2, so the invariant "we build exactly what was displayed, or -//! nothing" is enforced here too. `approve` renders the review, prints it, and -//! then approves with the hashes it just displayed — it cannot approve a diff it -//! did not show you. - use std::path::PathBuf; use clap::{Parser, Subcommand}; @@ -119,10 +111,9 @@ enum Cmd { fn main() -> anyhow::Result<()> { let cli = Cli::parse(); // `init` is the only command that runs before a config exists. For everything - // else a missing config is the error it sounds like, not a reason to invent - // one: the old unconditional fallback turned a typo'd `--root` into a fresh - // empty server at the wrong path, whose commands then "succeeded" against a - // database with no subscriptions and no releases in it. + // else a missing config is an error, not a reason to invent one: the old + // unconditional fallback turned a typo'd `--root` into a fresh empty server + // at the wrong path. let root = cli.root.clone().unwrap_or_else(|| Config::default().root); let cfg = if matches!(cli.cmd, Cmd::Init { .. }) { Config::load(&root).unwrap_or_else(|_| Config { @@ -156,9 +147,8 @@ fn main() -> anyhow::Result<()> { let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); aur_build::watch::scheduler::spawn_scheduler(std::sync::Arc::new(cfg.clone()), db.clone(), stop.clone()); let _server = aur_build::http::spawn(cfg.clone(), db.clone())?; - // The dispatcher reaps expired leases before its first claim, so a - // restart recovers whatever a crash left leased without any special - // startup routine (§8.2). + // The dispatcher reaps expired leases before its first claim, so a restart + // recovers whatever a crash left leased (§8.2). let _pool = aur_build::pipeline::dispatch::Pool::spawn(std::sync::Arc::new(cfg.clone()), db.clone()); println!("serving on http://{} — ctrl-c to stop", cfg.bind); // Single process, thread per connection: the main thread has nothing to @@ -259,7 +249,7 @@ fn main() -> anyhow::Result<()> { } Cmd::Approve { candidate, yes, note, identity, diff: diff_arg } => { let c = need_candidate(&ctx.db, candidate)?; - // Render first, always. The hashes we send are the hashes of what we + // Render first, always: the hashes we send are the hashes of what we // just rendered, unless the operator explicitly names older ones. let (text, digest) = diff::render_current(&ctx.db, &cfg, &c)?; candidates::set_diff_digest(&ctx.db, c.id, &digest)?; @@ -1,20 +1,3 @@ -//! Retention, metrics and backups (§15). -//! -//! Three separate jobs that share one premise: the database is the thing that -//! must survive, and the bytes on disk are the thing that cannot be kept forever. -//! -//! *Retention* evicts files for releases beyond the last N of a pkgbase. It never -//! deletes a row. The artifact keeps its digest, size and provenance and gains a -//! `purged_at`, so the record says "these bytes existed and were dropped at T" -//! rather than continuing to claim a file that is no longer there. -//! -//! *Metrics* are computed on read, like staleness. A counter that has to be -//! incremented on every state change is a counter that drifts. -//! -//! *Backups* use `VACUUM INTO`. Copying a live WAL database with `cp` produces a -//! main file plus a WAL that may or may not belong to it, which is to say a backup -//! that is only sometimes restorable. - use std::path::{Path, PathBuf}; use crate::config::Config; @@ -37,7 +20,7 @@ pub struct RetentionReport { /// Everything a metrics scrape reports, computed in one pass over the database. /// /// Kept as a struct rather than a string builder so the HTTP handler, the CLI and -/// the tests all read the same numbers from the same source. +/// the tests read the same numbers from the same source. #[derive(Debug, Default, Clone)] pub struct Metrics { pub builds: Vec<(String, i64)>, @@ -67,8 +50,8 @@ pub struct Metrics { impl Metrics { /// Share of recorded builds that published. Reported as 1.0 when nothing has - /// run yet: a fresh install is not a failing install, and an alert rule that - /// reads 0% success on an empty system pages someone for no reason. + /// run yet: an alert rule reading 0% success on an empty system pages someone + /// for no reason. pub fn build_success_rate(&self) -> f64 { match self.succeeded + self.failed { 0 => 1.0, @@ -76,10 +59,9 @@ impl Metrics { } } - /// Render in Prometheus text exposition format. - /// - /// Every family is declared with `# HELP` and `# TYPE` because a scrape that - /// fails validation silently drops the whole payload, not just the bad line. + /// Render in Prometheus text exposition format. Every family is declared with + /// `# HELP` and `# TYPE`, because a scrape that fails validation drops the + /// whole payload. pub fn to_prometheus(&self) -> String { let mut o = String::new(); @@ -97,8 +79,7 @@ impl Metrics { o.push_str(&header("aurbuild_pending_review_candidates", "Reviews waiting on a human — the review debt.")); o.push_str(&format!("aurbuild_pending_review_candidates {}\n", self.pending_review)); - // The debt number nobody asks for until it is weeks old: not how many - // reviews are pending, but how stale the pending ones are. + // Not how many reviews are pending, but how stale the pending ones are. o.push_str("# HELP aurbuild_pending_review_age_seconds Histogram of how long pending reviews have waited.\n# TYPE aurbuild_pending_review_age_seconds histogram\n"); for le in [3600i64, 21600, 86400, 259200, 604800] { let n = self.review_ages.iter().filter(|a| **a <= le).count(); @@ -214,8 +195,7 @@ pub fn metrics(cfg: &Config, db: &Db) -> Result<Metrics> { Ok(m) } -/// A Prometheus family header. Kept as a function rather than a closure over the -/// output buffer so the borrow checker does not object to interleaving. +/// A Prometheus family header. fn header(name: &str, help: &str) -> String { format!("# HELP {name} {help}\n# TYPE {name} gauge\n") } @@ -254,12 +234,7 @@ fn dir_bytes(path: &Path) -> u64 { /// Which releases of a pkgbase keep their files, and which lose them. /// -/// The rule is "newest N, plus anything that would be a lie to evict": the -/// currently accepted release and any release still backing an `in_index` -/// package are kept regardless of how far down the list they sit. Evicting those -/// would delete the bytes the index is actively pointing at, which is the one -/// thing retention must never do — a rollback target is worth disk, a served -/// package is not optional. +/// The rule is "newest N, plus anything that would be a lie to evict". pub fn plan_retention(db: &Db, keep: usize) -> Result<(Vec<i64>, Vec<EvictPlan>)> { let keep = keep.max(1); let pkgbases = db::pkgbase_release_pointers(db)?; @@ -268,8 +243,7 @@ pub fn plan_retention(db: &Db, keep: usize) -> Result<(Vec<i64>, Vec<EvictPlan>) let mut evict = Vec::new(); for (pb_id, accepted) in pkgbases { let releases = db::published_release_ids(db, pb_id)?; - // Still in the index? Then it is being served and is not a candidate for - // eviction no matter how old it is. + // Still in the index? Then it is being served, whatever its age. let serving = db::serving_release_ids(db, pb_id)?; let mut keep_set: std::collections::BTreeSet<i64> = serving.iter().cloned().collect(); @@ -298,10 +272,8 @@ pub struct EvictPlan { /// Run retention: evict files for releases beyond the keep window, then sweep /// abandoned staging directories. /// -/// Files are only removed when no *retained* release still references them. The -/// store is content-addressed, so two releases built from the same source share -/// one cached archive; deleting it because one release aged out would corrupt a -/// release that is still current. +/// Files are only removed when no *retained* release still references them: the store +/// is content-addressed. pub fn retention(cfg: &Config, db: &Db, keep: Option<usize>) -> Result<RetentionReport> { let keep = keep.unwrap_or_else(|| db::setting_i64(db, "retention_versions", DEFAULT_KEEP as i64) as usize); let (kept, evict) = plan_retention(db, keep)?; @@ -366,13 +338,11 @@ pub fn retention(cfg: &Config, db: &Db, keep: Option<usize>) -> Result<Retention /// belong to a build that is still running right now. pub const STAGING_GRACE_SECS: i64 = 3600; -/// The files a release holds on disk: package, signature, build log, and the -/// cached sources it was built from. +/// The files a release holds on disk: package, signature, build log, and the cached +/// sources it was built from. /// -/// These are returned as a unit because that is how they must be treated. A -/// package without its build log is a byte nobody can explain, and a package -/// without its sources cannot be rebuilt — keeping one and dropping the others -/// is how a store ends up full of orphans and empty of answers. +/// Returned as a unit because that is how they must be treated: keeping one and +/// dropping the others is how a store ends up full of orphans. pub fn release_files(cfg: &Config, db: &Db, release_id: i64) -> Result<Vec<PathBuf>> { let mut out = Vec::new(); for (path, sig, log) in db::release_artifact_paths(db, release_id)? { @@ -380,8 +350,8 @@ pub fn release_files(cfg: &Config, db: &Db, release_id: i64) -> Result<Vec<PathB out.push(PathBuf::from(p)); } } - // Cached sources, by content digest (§5.1a: the mirror and the source cache - // are what make an old release rebuildable). + // Cached sources, by content digest (§5.1a: these are what make an old + // release rebuildable). let digests = db::release_by_id(db, release_id)? .map(|r| r.source_digests_json) .unwrap_or_else(|| "[]".into()); @@ -395,13 +365,10 @@ pub fn release_files(cfg: &Config, db: &Db, release_id: i64) -> Result<Vec<PathB Ok(out) } -/// Remove staging directories whose build is finished or unknown (§8.2: staging -/// is disposable, and a GC pass sweeps what was abandoned). +/// Remove staging directories whose build is finished or unknown (§8.2). /// -/// "Abandoned" is derived, not guessed: a dir is swept when its build row is in a -/// terminal state, or when no build row exists at all, and the dir is older than -/// the grace period. A dir belonging to a live build is left alone no matter how -/// old it looks, because a long build is not an abandoned one. +/// "Abandoned" is derived, not guessed: a dir is swept when its build row is terminal +/// or absent and the dir is older than the grace period. pub fn sweep_staging(cfg: &Config, db: &Db, grace_secs: i64) -> Result<(usize, u64)> { let root = cfg.staging_dir(); let Ok(entries) = std::fs::read_dir(&root) else { return Ok((0, 0)) }; @@ -419,7 +386,7 @@ pub fn sweep_staging(cfg: &Config, db: &Db, grace_secs: i64) -> Result<(usize, u let state = db::builds::get(db, &build_id)?.map(|b| b.state); let abandonable = match &state { // No build row: staging left over from a crash before the row was - // written, or from a build id that no longer exists. + // written. None => true, Some(s) => matches!(s.as_str(), "succeeded" | "failed" | "cancelled"), }; @@ -461,11 +428,9 @@ fn record_run(db: &Db, r: &RetentionReport) -> Result<()> { /// A consistent snapshot of the database, written to `dest`. /// -/// `VACUUM INTO` runs on the writer connection so the snapshot cannot interleave -/// with a write, and it produces a compacted single file with no WAL — which is -/// what you want to be holding at 3am when the main file is gone. A `cp` of a -/// live WAL database gives you a main file and a sidecar log that may or may not -/// belong to it, and you find out which during the restore. +/// `VACUUM INTO` runs on the writer connection so the snapshot cannot interleave with +/// a write, and produces a compacted single file with no WAL. A `cp` of a live WAL +/// database gives a main file and a sidecar log that may not belong to it. pub fn backup(db: &Db, dest: &Path) -> Result<PathBuf> { let dest = dest.to_path_buf(); if dest.exists() { diff --git a/src/pipeline/dispatch.rs b/src/pipeline/dispatch.rs index 62052fd..d9891c2 100644 --- a/src/pipeline/dispatch.rs +++ b/src/pipeline/dispatch.rs @@ -1,21 +1,3 @@ -//! The dispatcher actor, the worker pool and the reaper (§8.2). -//! -//! Shape: one dispatcher thread, N worker threads, one crossbeam channel -//! between them. The dispatcher's loop is -//! -//! ```text -//! reaper: expired leases -> queued, in-flight step -> interrupted -//! cancel: superseded in-flight builds -> cancel_requested -//! claim: BEGIN IMMEDIATE { SELECT queued LIMIT admissible; UPDATE leased } -//! send: build_tx.send(id) for each -//! ``` -//! -//! Nothing lives only in a worker's memory. If the process is killed, the lease -//! expires and the next dispatcher pass puts the build back; the step -//! checkpoint decides where it resumes (I5). That is the whole crash-recovery -//! story, and it is why there is no separate "recover on startup" routine — the -//! reaper pass *is* the recovery, and it runs first in every loop. - use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread::JoinHandle; @@ -83,9 +65,8 @@ impl Pool { } fn dispatcher(cfg: Arc<Config>, db: Db, stop: Arc<AtomicBool>, tx: Sender<String>) { - // The reaper pass runs first on every loop, including the very first one, so - // "recover from a crash" and "notice an expired lease" are the same code - // path. There is no special startup recovery to get wrong. + // The reaper runs first on every loop, including the first, so "recover from + // a crash" and "notice an expired lease" are the same code path. while !stop.load(Ordering::SeqCst) { dispatch_once(&cfg, &db, &tx); let mut slept = 0u64; @@ -112,7 +93,6 @@ pub fn dispatch_once(cfg: &Config, db: &Db, tx: &Sender<String>) -> Vec<String> } // Blocked builds become eligible again when the blocking package arrives. let _ = builds::requeue_blocked(db); - // A newer approval makes an in-flight build pointless (§8.2). let _ = builds::cancel_superseded(db); let room = admissible(cfg, db); @@ -131,10 +111,9 @@ pub fn dispatch_once(cfg: &Config, db: &Db, tx: &Sender<String>) -> Vec<String> ids } -/// How many builds may be admitted right now (§8.2 backpressure): -/// `min(max_concurrent - in_flight, disk headroom)`. A build that cannot fit on -/// disk is not admitted — it stays queued rather than filling the filesystem -/// halfway through a compile. +/// How many builds may be admitted right now (§8.2 backpressure). A build that +/// cannot fit on disk stays queued rather than filling the filesystem halfway +/// through a compile. pub fn admissible(cfg: &Config, db: &Db) -> usize { let in_flight = builds::in_flight(db).unwrap_or(0) as usize; let slots = cfg.max_concurrent_builds.saturating_sub(in_flight); @@ -176,11 +155,9 @@ fn worker(cfg: Arc<Config>, db: Db, rx: crossbeam_channel::Receiver<String>, sto let attempt = builds::get(&db, &id).ok().flatten().map(|b| b.attempt).unwrap_or(1); match pipeline::run(&cfg, &db, &id) { Ok(Outcome::Failed { transient, .. }) => { - // §8.4: transient failures (network, mirror 5xx) retry with a - // bounded number of attempts. A deterministic build failure - // does NOT retry — the release stays approved_but_unbuilt and - // the UI says "index still serving v1". Retrying that would burn - // a chroot to produce the same failure. + // §8.4: transient failures retry with a bounded number of + // attempts; a deterministic failure does not, because it would + // produce the same answer. if transient && attempt < cfg.max_transient_attempts { let _ = builds::requeue_transient(&db, &id); db::audit_system( diff --git a/src/pipeline/mod.rs b/src/pipeline/mod.rs index 6729605..308f2a8 100644 --- a/src/pipeline/mod.rs +++ b/src/pipeline/mod.rs @@ -1,10 +1,3 @@ -//! The build pipeline (§8). -//! -//! Ten steps, each idempotent and checkpointed in `build_step`. A worker can die -//! at any instant and the pipeline resumes at the next incomplete step with no -//! duplicate side effects (I5). Only the last step is externally visible, and it -//! is serialized per repo (I4). - pub mod publish; pub mod dispatch; mod steps; @@ -37,15 +30,10 @@ pub struct SourceIdentity { } impl SourceIdentity { - /// The identity of a build's source, complete on construction (n-1). - /// - /// This used to return a value with `aur_commit` and `recipe_hash` left - /// empty, which `Ctx::new` filled in afterwards if it happened to find the - /// snapshot row — so a `SourceIdentity` was a type whose empty strings could - /// mean either "not filled in yet" or "genuinely unknown", and a new call - /// site that forgot the second half produced a build that silently recorded - /// an empty provenance. The snapshot is an argument now: you cannot build one - /// without it. + /// The identity of a build's source, complete on construction (n-1). The + /// snapshot is an argument because an `aur_commit` that could mean either + /// "not filled in yet" or "genuinely unknown" records empty provenance + /// silently. pub fn from_candidate(c: &CandidateRow, snapshot: &SnapshotRow) -> Self { Self { aur_commit: snapshot.aur_commit.clone(), @@ -175,12 +163,9 @@ impl Ctx { }) } - /// Lease a sandbox for this build's profile. Today every step acquires and - /// releases around itself; a remote backend will hold one sandbox across - /// the sandbox-bearing steps of a build, and steps stay idempotent either - /// way (I5). The TTL is the lease window: a sandbox that outlives it is - /// assumed dead, which is exactly what the reaper already concludes about - /// an expired build lease. + /// Lease a sandbox for this build's profile. The TTL is the lease window: a + /// sandbox that outlives it is assumed dead, which is what the reaper already + /// concludes about an expired build lease. pub fn sandbox(&self) -> Result<Arc<dyn Sandbox>> { let spec = crate::sandbox::SandboxSpec { profile: self.profile.clone(), @@ -265,10 +250,9 @@ pub fn run_with(ctx: &Ctx) -> Result<Outcome> { )?; ctx.log_line(&format!("!! {step} failed: {e}")); // A failed build must not leave the old version looking healthy. - // Nothing has to *do* that: the accepted pointer was never moved, - // so "approved, build failed, index still serving the old - // version" is what the derived query reads back (§8.4). There is - // deliberately no state to set here — see `approved_but_unbuilt`. + // Nothing has to do that: the accepted pointer was never moved, + // so the derived query reads it back (§8.4). There is + // deliberately no state to set here. return Ok(Outcome::Failed { step: step.to_string(), error: e.to_string(), transient }); } } @@ -314,15 +298,10 @@ pub fn enqueue_manual_rebuild(cfg: &Config, db: &Db, pkgbase: &str) -> Result<St let rel = db::accepted_release(db, pkgbase)? .ok_or_else(|| Error::invalid(format!("{pkgbase} has no accepted release")))?; // A manual rebuild is the accepted release asked for again, so its identity - // is derived from what that release actually is — commit, recipe, pins, - // digests — through the same canonical-JSON hash every other identity uses - // (n-5). The old version was an ad-hoc `commit|hash|manual` string: a - // different format for the same concept, with a delimiter that could appear - // inside the values, and no pins or digests at all, so two releases with the - // same recipe but different upstream commits... were distinguished only by - // luck. `requested` is what keeps a rebuild a *distinct* build from the one - // that produced the release, while staying deterministic (§8.2): clicking - // rebuild twice is one build, not two. + // is derived from what that release actually is, through the same + // canonical-JSON hash every other identity uses (n-5). `requested` is what + // keeps a rebuild a *distinct* build while staying deterministic (§8.2): + // clicking rebuild twice is one build, not two. let identity = format!( "sha256:{}", crate::hash::hex(crate::hash::canonical_json(&serde_json::json!({ diff --git a/src/pipeline/publish.rs b/src/pipeline/publish.rs index f8efeff..7340e53 100644 --- a/src/pipeline/publish.rs +++ b/src/pipeline/publish.rs @@ -1,11 +1,3 @@ -//! Publishing and serving the index (§9). -//! -//! Publishing is the only externally visible step, and it is atomic and -//! serialized per repo (I4). The served database is a materialized view of the -//! DB: we render it in scratch space beside the live file, fsync, commit the DB, -//! then `rename` over the real one. A crash anywhere in there leaves the *old* -//! index intact, and [`reconcile`] re-materializes from the DB on startup. - use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use std::process::Command; @@ -17,27 +9,15 @@ use crate::error::{Error, Result}; use crate::pipeline::{Collect, Ctx}; use crate::time; -/// One writer to the served repo at a time. -/// -/// This is *the* serialization guarantee for the index (§8.2, §9, I4): a publish -/// renders a new pacman database in scratch space, commits the DB, then renames -/// over the live one, and a second writer interleaving anywhere in that sequence -/// would produce an index that matches neither DB state. It is held by -/// [`publish`] for the whole of it — staging, render, DB commit, rename, sign — -/// and by [`withdraw_package`] for the same reason. With -/// `max_concurrent_builds > 1` it is what stops two workers racing on one file. -/// -/// It is a process-local mutex, which is exactly the guarantee the design asks -/// for: one `aur-build` process owns one repo directory. Two processes sharing -/// a directory is not a configuration this system supports. +/// One writer to the served repo at a time — *the* serialization guarantee for +/// the index (§8.2, §9, I4). A publish renders a new database in scratch space, +/// commits the DB, then renames over the live one; a second writer interleaving +/// anywhere in that sequence produces an index matching neither DB state. Held by +/// [`publish`] and [`withdraw_package`] for the whole sequence; [`reconcile`] skips +/// it because it runs before the dispatcher exists. /// -/// [`reconcile`] rewrites the index without it because it runs at startup, -/// before the dispatcher exists, when there is nothing to race with. -/// -/// A panic while holding it is recovered from rather than propagated: atomic -/// publish means a poisoned lock cannot have left a half-written database — the -/// live file is whatever was last renamed into place — so clearing the poison -/// continues instead of wedging the queue forever. +/// A panic while holding it is recovered rather than propagated: atomic publish +/// means a poisoned lock cannot have left a half-written database. static REPO_LOCK: Mutex<()> = Mutex::new(()); fn lock_repo() -> std::sync::MutexGuard<'static, ()> { @@ -61,7 +41,7 @@ pub fn index_world(db: &Db) -> Result<Vec<WorldMember>> { } /// Package files that belong in the served index right now, plus the extra ones -/// being published (which are not in the DB yet when the new index is rendered). +/// being published (not in the DB yet when the new index is rendered). fn index_artifacts(db: &Db, extra: &[PathBuf]) -> Result<Vec<PathBuf>> { let mut out: Vec<PathBuf> = Vec::new(); for p in db::index_packages(db)? { @@ -77,8 +57,7 @@ fn index_artifacts(db: &Db, extra: &[PathBuf]) -> Result<Vec<PathBuf>> { /// Publish the collected artifacts of a build. Returns the new release id. /// -/// Serialized against every other writer of the index by [`REPO_LOCK`], which -/// is held for the whole function. +/// Serialized against every other writer of the index by [`REPO_LOCK`]. pub fn publish(ctx: &Ctx) -> Result<i64> { let _guard = lock_repo(); let collect = Collect::load(&ctx.collect_path)?; @@ -91,13 +70,11 @@ pub fn publish(ctx: &Ctx) -> Result<i64> { // Artifacts are copied into the served tree under their real filenames. let mut staged: Vec<(PathBuf, PathBuf)> = Vec::new(); - // Set once the render starts, so the failure path below can sweep the scratch - // directory even when the publish died after repo-add returned. + // Set once the render starts, so the failure path can sweep the scratch + // directory even if the publish died after repo-add returned. let mut scratch_dir: Option<PathBuf> = None; - // Files this publish created that were not there before. If the publish does - // not land, they are orphans: no index names them and no consumer will ever - // ask for them (§6 m-16). A file that already existed belongs to the release - // that is still live, so it is never on this list. + // Files this publish created that were not there before: if the publish does + // not land they are orphans no index names (§6 m-16). let mut fresh: Vec<PathBuf> = Vec::new(); for p in &collect.packages { let from = PathBuf::from(&p.path); @@ -122,25 +99,21 @@ pub fn publish(ctx: &Ctx) -> Result<i64> { } let outcome = (|| -> Result<i64> { - // 1. render the new database and fsync it. The live one is untouched - // until step 3's rename. + // 1. render the new database; the live one is untouched until step 3. let db_name = ctx.cfg.repo_db_name(); let final_db = arch_dir.join(format!("{db_name}.tar.gz")); let mut pkgs = index_artifacts(&ctx.db, &staged.iter().map(|(d, _)| d.clone()).collect::<Vec<_>>())?; - // Deduplicate: the same package name must appear once, newest wins. pkgs = dedupe_by_name(pkgs); let rendered = render_db(&ctx.cfg, &arch_dir, "publish", &pkgs, &mut scratch_dir)?; - // Fault injection so I4 can be tested for real: die between the render - // and the rename, and the old index must still be what consumers get. - // Compiled out of a production build (§6 M-9). + // Fault injection so I4 can be tested for real (§6 M-9). #[cfg(feature = "test-support")] if ctx.cfg.hooks.publish_fault.as_deref() == Some("before-rename") { return Err(Error::other("injected fault: before-rename")); } - // 2. commit the DB: release + package rows + the accepted pointer, in one - // transaction, with the pointer moved by compare-and-swap. + // 2. commit the DB: release + package rows + the accepted pointer, in + // one transaction, with the pointer moved by compare-and-swap. let release_id = commit_release(ctx, &collect)?; // 3. atomic swap: rename over the real database, then sign the new bytes. @@ -168,9 +141,8 @@ pub fn publish(ctx: &Ctx) -> Result<i64> { })(); if outcome.is_err() { - // The publish did not land, so nothing in the served tree may look like it - // did: the bytes this call copied in are removed again (m-16). Files that - // were already there belong to the release still being served and stay. + // Nothing in the served tree may look like a publish that did not land + // (m-16); files already there belong to the release still served. for p in &fresh { let _ = std::fs::remove_file(p); } @@ -222,9 +194,7 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> { .and_then(|b| b.world_snapshot_id); let repo_id = db::repo_id(&ctx.db)?; // The compare-and-swap baseline is the release the *approval* was taken - // against, not whatever the pointer happens to say now. If they differ, - // someone accepted a newer version while we were building, and publishing - // this one would roll it back. + // against, not whatever the pointer says now. let expected_base: Option<i64> = match ctx.build.kind.as_str() { "manual_rebuild" => ctx.build.release_id, _ => ctx @@ -235,16 +205,15 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> { }; ctx.db.writer.tx(move |tx| { - // Compare-and-swap on the accepted pointer, inside the write - // transaction: two publishes cannot both land (I4). + // Compare-and-swap inside the write transaction (I4). let actual_base = db::accepted_pointer_in(tx, pkgbase_id)?; if actual_base != expected_base { return Err(Error::conflict( "accepted pointer moved while this build was running; refusing to publish", )); } - // Retire whatever the index held for these names *before* inserting the - // new rows: the index holds exactly the accepted pointer, nothing else. + // The index holds exactly the accepted pointer, so what it held for these + // names goes before the new rows go in. db::remove_index_packages_in(tx, &names)?; let release_id = db::insert_release_in( tx, @@ -280,10 +249,8 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> { }) } -/// Remove scratch directories a crash left behind. [`render_db`] cleans up after -/// itself on every path it controls; these are the ones it did not get to, and -/// they are unambiguous — the leading dot means nothing a consumer asks for, and -/// only a render creates one. +/// Remove scratch directories a crash left behind: the leading dot means nothing +/// a consumer asks for, and only a render creates one. pub fn sweep_render_dirs(arch_dir: &Path) { let Ok(entries) = std::fs::read_dir(arch_dir) else { return; @@ -303,9 +270,8 @@ struct Rendered { } impl Rendered { - /// The publish point: rename the rendered database over the live one, fsync - /// the directory entry, then drop the scratch directory. Before the rename a - /// consumer still gets the old index; after it, the new one. + /// The publish point: rename over the live database, fsync the directory + /// entry, then drop the scratch directory. fn swap_into(self, final_db: &Path) -> Result<()> { std::fs::rename(&self.db, final_db)?; fsync_dir(&self.arch_dir)?; @@ -317,18 +283,12 @@ impl Rendered { /// Render a fresh database with repo-add, ready to be renamed into place. /// /// repo-add refuses any database argument that is not a name pacman itself would -/// accept (`<repo>.db.tar.gz` and friends) — a `.tmp` suffix is a usage error to -/// it, not a convention. So the render cannot happen at `<db>.tar.gz.tmp` beside -/// the live file, which is what this code used to do: every publish of a real -/// package failed the moment it met a real repo-add, while 200+ tests stayed -/// green because the shim accepted any filename. It renders instead into a -/// scratch directory *under* the served directory, under the exact name a -/// consumer will download. Same filesystem, so the caller's `rename` is still the -/// atomic swap I4 requires, and the live database is never the file repo-add is -/// writing into. +/// accept, so the render happens in a scratch directory *under* the served +/// directory, under the exact name a consumer will download. Same filesystem, so +/// the caller's `rename` is still the atomic swap I4 requires. /// -/// `scratch` is filled in as soon as the directory exists, so the caller can -/// sweep it even if this function is never reached again. +/// `scratch` is filled in as soon as the directory exists, so the caller can sweep +/// it even if this function is never reached again. fn render_db( cfg: &Config, arch_dir: &Path, @@ -343,8 +303,6 @@ fn render_db( *scratch = Some(dir.clone()); let db = dir.join(format!("{}.tar.gz", cfg.repo_db_name())); let rendered = Rendered { db, dir, arch_dir: arch_dir.to_path_buf() }; - // Anything that can still fail lives here, so the scratch directory does not - // outlive the attempt on the error path. let attempt = (|| -> Result<()> { run_repo_add(cfg, &rendered.db, pkgs)?; fsync_file(&rendered.db)?; @@ -358,12 +316,8 @@ fn render_db( Ok(rendered) } -/// `repo-add -R <db> <pkgs...>`. -/// -/// Deliberately *not* `-s`: repo-add would sign the database into whatever -/// directory it was rendered in, which is scratch space that gets deleted, and -/// the hub signs the live file itself in [`sign`] — one key, one code path, and -/// the signature is always over the bytes that were renamed into place (§9). +/// `repo-add -R <db> <pkgs...>`, deliberately *not* `-s`: repo-add would sign into +/// scratch space that gets deleted. The hub signs the live file itself in [`sign`]. fn run_repo_add(cfg: &Config, db_path: &Path, pkgs: &[PathBuf]) -> Result<()> { let mut cmd = Command::new(&cfg.repo_add_bin); cmd.arg("-R"); @@ -390,10 +344,8 @@ fn sign(cfg: &Config, path: &Path) -> Result<()> { sign_to(cfg, path, Path::new(&sig)) } -/// `gpg --detach-sign` over `path`, written to `sig_out` atomically. Shared by -/// publish (the database) and ingest (the packages): one key, one code path, -/// and the key never leaves the hub — a build sandbox signs nothing (§8, -/// remote-builder design). +/// `gpg --detach-sign` over `path`, written to `sig_out` atomically. The key never +/// leaves the hub — a build sandbox signs nothing (§8). pub(crate) fn sign_to(cfg: &Config, path: &Path, sig_out: &Path) -> Result<()> { if cfg.signing_key_id.is_empty() { return Ok(()); @@ -416,11 +368,8 @@ pub(crate) fn sign_to(cfg: &Config, path: &Path, sig_out: &Path) -> Result<()> { Ok(()) } -/// fsync, and *say so* when it fails (m-7). The whole point of writing to a -/// scratch file, fsyncing, and renaming is the promise that a consumer never -/// sees a half-written database; swallowing the error made that a comment rather -/// than a guarantee — on a filesystem that refuses `fsync` (full, read-only, a -/// network mount that dropped), the rename still "succeeded". +/// fsync, and *say so* when it fails (m-7). Swallowing the error would make the +/// write-scratch-fsync-rename promise a comment rather than a guarantee. fn fsync_file(p: &Path) -> Result<()> { let f = std::fs::File::open(p) .map_err(|e| Error::other(format!("open {} for fsync: {e}", p.display())))?; @@ -439,8 +388,7 @@ fn fsync_dir(p: &Path) -> Result<()> { /// Keep one entry per package name; the newest file wins. The name comes from -/// `.PKGINFO` inside the tarball, not from the filename, because package names -/// contain dashes. +/// `.PKGINFO`, not the filename, because package names contain dashes. fn dedupe_by_name(paths: Vec<PathBuf>) -> Vec<PathBuf> { let mut seen: BTreeSet<String> = BTreeSet::new(); let mut out: Vec<PathBuf> = Vec::new(); @@ -460,10 +408,8 @@ fn dedupe_by_name(paths: Vec<PathBuf>) -> Vec<PathBuf> { /// The package name a built artifact declares, read from its own `.PKGINFO`. /// -/// This is the real parser in `crate::pkginfo`, not the shim harness's: the -/// name that goes into the index must come from the same read of the bytes that -/// the pipeline signs, and a second parser in the test scaffolding is one -/// refactor away from disagreeing about what a package calls itself (§6 M-4). +/// The name that goes into the index must come from the same read of the bytes the +/// pipeline signs, so this uses the real parser (§6 M-4). fn package_name(path: &Path) -> Option<String> { let bytes = std::fs::read(path).ok()?; let info = crate::pkginfo::pkginfo_text(&bytes).ok()?; diff --git a/src/pipeline/steps.rs b/src/pipeline/steps.rs index 59c9a64..c19ac6b 100644 --- a/src/pipeline/steps.rs +++ b/src/pipeline/steps.rs @@ -1,8 +1,3 @@ -//! The ten pipeline steps (§8.1). -//! -//! Every step is idempotent and records its result in one short transaction; -//! the long-running child process happens outside any transaction (§11a). - use std::path::Path; use crate::db::{self, builds, model::*}; @@ -115,16 +110,14 @@ fn plan(ctx: &Ctx) -> Result<StepResult> { /// Step 2 — provision the sandbox with the pinned lease set. /// -/// The devtools chroot is gone: the sandbox boots from a base that already -/// carries the official packages, and everything *we* publish that this build -/// needs arrives as content-addressed blobs installed with `pacman -U`. The -/// step id stays `chroot` in the checkpoint table — the DB does not care what -/// the string means, and renaming would strand every existing checkpoint row. +/// The devtools chroot is gone: the sandbox boots from a base that already carries +/// the official packages, and everything *we* publish arrives as blobs installed +/// with `pacman -U`. The step id stays `chroot` so existing checkpoint rows are +/// not stranded. /// -/// Nothing is resolved at build time: the lease manifest is the plan, every -/// blob is re-hashed before it is staged, and the sandbox's own `pacman -Q` -/// must confirm the pinned world actually landed. A byte that hashes to -/// something else, or a world that drifted, fails the build closed. +/// Nothing is resolved at build time: the lease manifest is the plan, every blob +/// is re-hashed before it is staged, and the sandbox's own `pacman -Q` must confirm +/// the pinned world landed. fn provision(ctx: &Ctx) -> Result<StepResult> { let lease = lease_manifest(ctx)?; if lease.is_empty() { @@ -152,18 +145,15 @@ fn provision(ctx: &Ctx) -> Result<StepResult> { argv.extend(lease.iter().map(|e| format!("blob:{}", e.digest))); let out = sbx.run(&Cmd::new(argv), &mut |_| {})?; if !out.success() { - // 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". + // A refused `-U` is almost always an incomplete closure — "the sandbox lied + // about its world", not "the sandbox broke". return Err(Error::world_mismatch(format!( "{} -U refused the lease set: {}", ctx.cfg.pacman_bin, tail(&out.stderr) ))); } - // Fail-closed world check: every pinned entry must be present in the - // sandbox at exactly the pinned version. The world we approved is the - // world we build in, or nothing. + // Fail-closed world check: the world we approved is the world we build in. let q = sbx.run(&Cmd::new(vec![ctx.cfg.pacman_bin.clone(), "-Q".into()]), &mut |_| {})?; if !q.success() { return Err(Error::fail_closed(format!( @@ -197,9 +187,8 @@ fn provision(ctx: &Ctx) -> Result<StepResult> { 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). +/// Lease a sandbox for a step, or report that the pool cannot fit one. A full +/// pool blocks the build rather than failing it (§10.4). fn sandbox_or_wait( ctx: &Ctx, ) -> Result<Option<std::sync::Arc<dyn crate::sandbox::Sandbox>>> { @@ -223,9 +212,8 @@ struct LeasePkg { /// The lease manifest: every dependency this build needs that we publish, /// pinned to the exact version and digest of the artifact we serve. Official -/// packages are the base image's business — they arrive with the sandbox, and -/// pinning them is the hub's official-repo cache, not this step. Anything -/// unresolvable here would have been `plan()`'s problem (blocked, not built). +/// packages arrive with the sandbox; anything unresolvable here would have been +/// `plan()`'s problem. fn lease_manifest(ctx: &Ctx) -> Result<Vec<LeasePkg>> { let recipe = recipe_at(&ctx.srcdir)?; let mut wanted: Vec<String> = Vec::new(); @@ -248,8 +236,7 @@ fn lease_manifest(ctx: &Ctx) -> Result<Vec<LeasePkg>> { /// Step 3 — make sure every source we reviewed is on disk and hashes to what the /// candidate recorded. For a `SKIP` source this is the only verification that -/// exists, and it closes the window between "we hashed it at review time" and -/// "makepkg downloaded something else just now" (§8.1). +/// exists (§8.1). fn sources(ctx: &Ctx) -> Result<StepResult> { let digests: Vec<SourceDigest> = serde_json::from_str(&ctx.src.source_digests_json).unwrap_or_default(); let mut verified = 0; @@ -281,9 +268,8 @@ fn sources(ctx: &Ctx) -> Result<StepResult> { )))) } -/// Step 4 — the belt-and-braces assertion that what we build is what was -/// approved. If upstream moved between approval and build, fail with both -/// versions instead of silently shipping the new one (§8.1). +/// Step 4 — the belt-and-braces assertion that what we build is what was approved. +/// If upstream moved between approval and build, fail with both versions (§8.1). fn pkgver(ctx: &Ctx) -> Result<StepResult> { let recipe = recipe_at(&ctx.srcdir)?; let has_vcs = recipe.source_entries.iter().any(|s| s.is_vcs()); @@ -323,19 +309,17 @@ fn pkgver(ctx: &Ctx) -> Result<StepResult> { } /// Step 5 — `makepkg -c -f` in the provisioned sandbox, with the log going to -/// the file the SSE tail reads. No `-s`: the lease set is already installed, -/// and a build that resolves dependencies at build time is exactly what the -/// pinning model forbids. No `-si`: the sandbox never holds the signing key; -/// ingest signs hub-side. +/// the file the SSE tail reads. No `-s`: the lease set is already installed, and +/// resolving dependencies at build time is what the pinning model forbids. No +/// `-si`: the sandbox never holds the signing key. fn build(ctx: &Ctx) -> Result<StepResult> { 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. + // The sandbox streams the child's output here as it arrives; the SSE tail + // reads the same file. if let Some(parent) = ctx.log.parent() { let _ = std::fs::create_dir_all(parent); } @@ -376,16 +360,12 @@ fn collect(ctx: &Ctx) -> Result<StepResult> { .filter(|p| p.to_string_lossy().ends_with(".pkg.tar.zst")) .collect(); entries.sort(); - // I9: the build is untrusted. In production it runs in a chroot, but the - // control plane must not *depend* on that for its own safety. Everything - // below takes a path that a PKGBUILD could have arranged to exist in the - // srcdir, and the next step copies whatever that path points at into the - // content-addressed store — from where it is served from our repo and signed - // with our key. A symlink to the signing keyring, the database, or anyone's - // home directory would otherwise become a signed artifact we publish. So: - // no symlinks, and the resolved target must live inside this build's own - // staging directory. Anything else fails the build closed. - let staging_root = ctx.staging.canonicalize()?; + // I9: the build is untrusted, and the control plane must not *depend* on the + // sandbox for its own safety. Everything below takes a path a PKGBUILD could + // have arranged to exist in the srcdir, and the next step copies whatever it + // points at into the store, from where we serve and sign it. So: no symlinks, + // and the resolved target must live inside this build's staging directory. + let staging_root = ctx.staging.canonicalize()?;; for path in entries { if std::fs::symlink_metadata(&path).map(|m| m.file_type().is_symlink()).unwrap_or(true) { return Err(Error::fail_closed(format!( @@ -409,8 +389,7 @@ fn collect(ctx: &Ctx) -> Result<StepResult> { .map_err(|e| Error::invalid(format!("{}: {e}", path.display())))?; let meta = crate::pkginfo::parse_pkginfo(&pkginfo); // `.BUILDINFO` is what the world snapshot is built from. Absent is not - // fatal — the snapshot is then simply empty for this package — but a - // present-but-unparseable one would be a lie we should not swallow. + // fatal; present-but-unparseable would be a lie we should not swallow. let buildinfo = crate::pkginfo::buildinfo_text(&bytes).unwrap_or_default(); let sig = path.with_extension("pkg.tar.zst.sig"); pkgs.push(CollectedPkg { @@ -436,14 +415,12 @@ fn collect(ctx: &Ctx) -> Result<StepResult> { } let collect = Collect { packages: pkgs.clone() }; collect.save(&ctx.collect_path)?; - // A split pkgbase is one approval and N index entries (§3). ctx.log_line(&format!(" collected {}", pkgs.iter().map(|p| format!("{}-{}", p.name, p.version)).collect::<Vec<_>>().join(", "))); Ok(StepResult::Done(Some(crate::hash::hex_str(&serde_json::to_string(&pkgs)?)))) } /// Step 7 — dependencies satisfiable, no downgrade. Signature checking is not -/// here: the build no longer signs (the sandbox never sees the key), so the -/// signature is made at ingest, after these checks pass. +/// here: the sandbox never sees the key, so the signature is made at ingest. fn verify(ctx: &Ctx) -> Result<StepResult> { let collect = Collect::load(&ctx.collect_path)?; let ours = db::our_package_names(&ctx.db)?; @@ -486,10 +463,8 @@ fn ingest(ctx: &Ctx) -> Result<StepResult> { std::fs::copy(from, &dest)?; } p.path = dest.display().to_string(); - // Hub-side signing: the build environment never holds the key, so the - // signature is made here, over the exact bytes that just entered the - // store, by the same key that signs the database. A gpg failure fails - // the build closed — an unsigned artifact never reaches the repo. + // Hub-side signing: over the exact bytes that just entered the store. A + // gpg failure fails the build closed. if !ctx.cfg.signing_key_id.is_empty() { let sigdest = ctx.cfg.store_path(&format!("{}-sig", p.digest)); if !sigdest.exists() { @@ -524,8 +499,8 @@ fn ingest(ctx: &Ctx) -> Result<StepResult> { })?; // §10.1: the world snapshot is the build's installed set INTERSECTED with our - // own packages, filtered at ingest time, not at query time. Left unfiltered, - // every package would be permanently stale because Arch never stops moving. + // own packages, filtered at ingest time. Left unfiltered, every package would + // be permanently stale because Arch never stops moving. let ours = db::our_package_names(&ctx.db)?; let mut members: Vec<WorldMember> = Vec::new(); for p in &collect.packages { diff --git a/src/pkginfo.rs b/src/pkginfo.rs index 7ec8b83..be0aeb6 100644 --- a/src/pkginfo.rs +++ b/src/pkginfo.rs @@ -1,17 +1,3 @@ -//! Reading `.PKGINFO` and `.BUILDINFO` out of a package archive (§10.1). -//! -//! A `.pkg.tar.zst` is a zstd-compressed tar with two plain-text metadata files -//! inside it. pacman reads these through libalpm; we do not link libalpm (no -//! FFI, no C toolchain dependency, §14), so this module parses the tar and the -//! text directly. That is not a shortcut — the format is a `key = value` file -//! with repeated keys, and a `.BUILDINFO` `installed =` block of -//! `name version arch signature` lines. Both are stable and documented, and -//! parsing them here is roughly eighty lines. -//! -//! This is production code, not harness code: the ingest step decides what the -//! index claims about a package, and what the world snapshot records, by reading -//! these two files. - use std::io::Read; /// A package's own metadata, as `.PKGINFO` states it. @@ -97,9 +83,7 @@ pub fn parse_pkginfo(text: &str) -> PkgInfo { /// Parse the `.BUILDINFO` `installed` block. /// /// The first entry shares the line with the key — `installed = glibc 2.39-1 -/// x86_64 -` — and the rest are indented under it, so the header line has to be -/// parsed as well as skipped. Dropping it would silently lose one dependency from -/// every snapshot, which is exactly the kind of gap that makes staleness lie. +/// x86_64 -` — so the header line has to be parsed as well as skipped. pub fn parse_installed(text: &str) -> Vec<Installed> { let mut out = Vec::new(); let mut in_block = false; diff --git a/src/pkgver/mod.rs b/src/pkgver/mod.rs index e968256..bd77a01 100644 --- a/src/pkgver/mod.rs +++ b/src/pkgver/mod.rs @@ -1,12 +1,3 @@ -//! Version comparison and dependency-string parsing. -//! -//! Hand-written rather than bound to libalpm (DESIGN.md §4). The algorithm is -//! the ALPM one and is fully specified: compare epoch numerically, then compare -//! `pkgver` chunk-wise, then `pkgrel` chunk-wise. A chunk is a maximal run of -//! digits or a maximal run of non-digits; non-alphanumeric characters are -//! ignored. A numeric chunk always sorts before an alphabetic chunk, so `1.5` -//! < `1.5a` and `1.1` < `1.a`. - use std::cmp::Ordering; use std::fmt; @@ -127,25 +118,19 @@ fn preceded_by_separator(s: &[u8], k: usize) -> bool { k > 0 && !is_alnum(s[k - 1]) } -/// ALPM's `vercmp`, character-wise. -/// -/// Three rules do all the work, and each one is surprising the first time: +/// ALPM's `vercmp`, character-wise. Three rules do all the work: /// /// 1. A numeric chunk is newer than an alphabetic chunk at the same position, so /// `1.0.1` > `1.0.a`. /// 2. When one string runs out, the other side decides by its *next raw /// character*: a letter there makes the exhausted string newer (`1.0` > -/// `1.0a`, the `1.0rc1 < 1.0` rule), anything else makes it older -/// (`1.0` < `1.0.1`). -/// 3. Separators are not merely skipped. An alphabetic chunk that follows a -/// separator is newer than one glued to the previous chunk, whatever the -/// letters are: `1.0.a` > `1.0z`. Two versions that differ only in where the -/// dot sits are *not* equal, which is the part a chunk-splitting -/// implementation gets wrong. +/// `1.0a`), anything else makes it older (`1.0` < `1.0.1`). +/// 3. An alphabetic chunk following a separator is newer than one glued to the +/// previous chunk, whatever the letters are: `1.0.a` > `1.0z`. Versions +/// differing only in where the dot sits are *not* equal. /// /// The cross-product test in `tests/versions.rs` checks this against pacman's own -/// `vercmp` over ~1100 pairs, which is the only reason anyone can be confident -/// about rule 3. +/// `vercmp` over ~1100 pairs. pub fn vercmp_string(a: &str, b: &str) -> Ordering { let (a, b) = (a.as_bytes(), b.as_bytes()); let (mut i, mut j) = (0usize, 0usize); diff --git a/src/recipe.rs b/src/recipe.rs index 4ba6a6f..cfdb4c6 100644 --- a/src/recipe.rs +++ b/src/recipe.rs @@ -1,9 +1,3 @@ -//! Recipe parsing: `.SRCINFO` (authoritative, present in every AUR repo) with a -//! `PKGBUILD` fallback, plus `source=()` parsing. -//! -//! The recipe is what a human reviews, so parsing failures are loud: a recipe we -//! cannot read must never silently produce a candidate with an empty source list. - use std::collections::BTreeMap; use crate::db::model::{Recipe, SourceEntry}; @@ -92,8 +86,8 @@ fn push_field(r: &mut Recipe, in_pkg: bool, pkg: Option<&str>, k: &str, v: &str) /// Minimal `PKGBUILD` variable reader: top-level `var=value` and `var=(...)` /// assignments, including arrays spanning several lines and quoted elements. /// -/// This is a fallback for recipes without `.SRCINFO`; it deliberately does not -/// try to evaluate bash. Anything it cannot read is reported, not guessed. +/// A fallback for recipes without `.SRCINFO`; it deliberately does not evaluate +/// bash. Anything it cannot read is reported, not guessed. pub fn parse_pkgbuild(text: &str) -> Result<Recipe> { let vars = pkgbuild_vars(text); let mut r = Recipe::default(); @@ -357,13 +351,9 @@ pub fn is_diffable(path: &str) -> bool { /// The executable part of a `PKGBUILD`: everything from the first function /// definition onward. /// -/// The variable assignments above the functions are metadata — a new version -/// string, another dependency. The functions are code that runs on this machine -/// and, through the package, on every machine that installs it. Reviewers and -/// the risk scorer both need that line drawn in the same place, so it is drawn -/// once here (§6 m-2): two copies had drifted, and the diff panel's version -/// compared only the function *header* lines, so a rewritten `build()` body -/// with the same function names showed the reviewer nothing. +/// The assignments above the functions are metadata; the functions are code that runs +/// here and, through the package, everywhere it installs. +/// scorer need that line drawn in the same place (§6 m-2). pub fn pkgbuild_bodies(text: &str) -> String { let mut out = String::new(); let mut inside = false; diff --git a/src/review/approve.rs b/src/review/approve.rs index e5f446f..c8cd99d 100644 --- a/src/review/approve.rs +++ b/src/review/approve.rs @@ -1,10 +1,3 @@ -//! Approval semantics (§7.1, §7.1a, §7.2, §7.4). -//! -//! Rule of the system: **we build exactly what was displayed, or nothing.** -//! The approve POST carries the `identity_hash` and `diff_digest` that were -//! rendered; if either has moved under the reviewer, the approval is refused -//! with a conflict (HTTP 409) and a re-render, never silently retargeted. - use crate::db::{self, approvals, candidates, CandidateState, *}; use crate::error::{Error, Result}; use crate::time; @@ -36,20 +29,16 @@ pub struct Approval { /// Why a decision did not happen (§7.1a, §6 M-3). /// -/// Two families, and the difference is the whole point. `Stale` means the -/// reviewer's screen no longer matches the database: the answer is to look -/// again, and the UI says so with a 409 and a fresh diff. `System` means the -/// database itself refused: looking again changes nothing, and the operator has -/// a broken thing to fix. They used to be the same variant — every failure, -/// SQLite included, arrived as "review is no longer pending (state: sqlite: -/// …)", which told a reviewer their eyes were wrong when the truth was that -/// the write failed. +/// Two families, and the difference is the whole point: `Stale` means the +/// reviewer's screen no longer matches the database, so the answer is to look +/// again; `System` means the database itself refused, and looking again changes +/// nothing. #[derive(Debug, thiserror::Error)] pub enum ApproveError { /// What is stored is not what was displayed. #[error(transparent)] Stale(#[from] Stale), - /// The write itself failed. Nothing about the review is at fault. + /// The write itself failed; nothing about the review is at fault. #[error("the decision could not be recorded: {0}")] System(#[from] Error), } @@ -77,19 +66,16 @@ pub fn approve( let base = subject.base_release_id; let current_base = subject.current_base_release_id; - // 1. still open if !subject.state.is_open() { return Ok(Err(ApproveError::Stale(Stale::NotPending { state: subject.state.to_string() }))); } - // 2. same candidate bytes if subject.identity_hash != ih { return Ok(Err(ApproveError::Stale(Stale::Identity { expected: ih.clone(), actual: subject.identity_hash }))); } - // 3. same rendered diff if subject.diff_digest != dd { return Ok(Err(ApproveError::Stale(Stale::Diff { expected: dd.clone(), actual: subject.diff_digest }))); } - // 4. base is still the accepted release (I2, end to end) + // Base is still the accepted release (I2, end to end). if base != current_base { return Ok(Err(ApproveError::Stale(Stale::Base { expected: base, actual: current_base }))); } @@ -128,7 +114,7 @@ pub fn approve( identity_hash: ih, })) }) - // A failure of the transaction is a system failure, never a stale review. + // A failed transaction is a system failure, never a stale review. .map_err(ApproveError::System)? } @@ -156,9 +142,6 @@ pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()> "reject", "candidate", &candidate_id.to_string(), - // The identity hash, not only the note: "why was this rejected" - // is unanswerable if the row does not say which bytes were on - // screen (§11). serde_json::json!({"identity": identity, "note": note}), ), )?; @@ -169,15 +152,13 @@ pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()> /// One item of a bulk decision, and what happened to it (§7.4). #[derive(Debug)] pub struct BulkItem { - /// The review this outcome is about; `None` when the id matched nothing — - /// which is exactly the case a caller must be able to report, so the row - /// cannot be the key. + /// `None` when the id matched nothing — which a caller must be able to + /// report, so the row cannot be the key. pub candidate: Option<CandidateRow>, pub outcome: BulkOutcome, } impl BulkItem { - /// The pkgbase to name in a summary line. pub fn pkgbase(&self) -> &str { self.candidate.as_ref().map(|c| c.pkgbase.as_str()).unwrap_or("(gone)") } @@ -188,21 +169,14 @@ impl BulkItem { pub enum BulkOutcome { /// Approved; the approval row is here so the caller can queue the build. Approved(Approval), - /// Rejected. A rejection records no approval, so there is no row to hand - /// back — the old code fabricated `Approval { id: 0 }`, which a caller - /// could not tell from a real one (§6 M-3). + /// A rejection records no approval, so there is no row to hand back. Rejected, /// Not decided, and why. Refused(BulkRefusal), } -/// Why a bulk decision skipped one of its items (§7.4). -/// -/// Each reason is its own variant because they are different answers to give a -/// human: one wants a confirmation click, one is a form bug, one means the -/// review moved while the page was open, one means the database is broken. They -/// used to all be `Stale::NotPending`, which made the flash message the only -/// place the truth survived. +/// Why a bulk decision skipped one of its items (§7.4). Each reason is its own +/// variant because they are different answers to give a human. #[derive(Debug, thiserror::Error)] pub enum BulkRefusal { /// High-risk items need their own confirmation, per item (§7.4). @@ -222,11 +196,11 @@ pub enum BulkRefusal { System(Error), } -/// §7.4 bulk decision. High-risk items are refused unless confirmed individually, -/// and one refused item never rolls back the ones that were decided. -/// -/// `items` carries the identity and diff each review was displayed with, so the -/// approval-echo rule applies to bulk exactly as it does to a single approval. +/// §7.4 bulk decision. High-risk items are refused unless confirmed +/// individually, and one refused item never rolls back the ones that were +/// decided. `items` carries the identity and diff each review was displayed +/// with, so the approval-echo rule applies to bulk exactly as to a single +/// approval. pub fn bulk( db: &Db, actor: &str, @@ -262,7 +236,6 @@ pub fn bulk( Ok(out) } -/// The approval behind a candidate, if any. pub fn approval_for(db: &Db, candidate_id: i64) -> Result<Option<(i64, String)>> { approvals::for_candidate(db, candidate_id) } @@ -290,7 +263,6 @@ pub fn withdraw(db: &Db, actor: &str, release_id: i64, reason: &str) -> Result<( }) } -/// The pkgbase's accepted release pointer, exposed for callers that need it. pub fn current_accepted(db: &Db, pkgbase: &str) -> Result<Option<ReleaseRow>> { db::accepted_release(db, pkgbase) } diff --git a/src/review/candidates.rs b/src/review/candidates.rs index 7cedf4b..d4c49e8 100644 --- a/src/review/candidates.rs +++ b/src/review/candidates.rs @@ -1,15 +1,3 @@ -//! Candidate creation and the collapse-in-place rule (§7.1). -//! -//! One review object per pkgbase at a time. A newer detection **collapses into** -//! the open review rather than queueing beside it, and the review's `base` is -//! fixed at creation to the pkgbase's `current_accepted_release` — that is what -//! makes "diff against the last accepted version, never the last seen one" (I2) -//! true no matter how many detections arrive while nobody is looking. -//! -//! This module is the *rule*, not the SQL: every statement it needs lives in -//! `db::candidates` and is called through the transaction handle, so the whole -//! decision is atomic and the schema still has one owner. - use crate::db::{self, candidates as sql, Db, Pkgbase, ReleaseRow}; use crate::error::Result; @@ -49,22 +37,20 @@ pub fn upsert_candidate(db: &Db, pb: &Pkgbase, accepted: Option<&ReleaseRow>, nc return Ok(Upsert::Unchanged); } if !open.viewed() { - // Collapse in place: same base, no new row, revision bumped. let revision = sql::collapse_in(tx, &open, &nc)?; return Ok(Upsert::Collapsed { id: open.id, revision }); } - // A human saw the old diff: freeze it for the audit trail and open a - // fresh review against the same base. + // A human saw the old diff: freeze it for the audit trail and open + // a fresh review against the same base. sql::supersede_in(tx, open.id)?; let new_id = sql::insert_in(tx, pkgbase_id, base, kind, &nc)?; return Ok(Upsert::Superseded { old: open.id, new: new_id }); } - // No open review. A previously rejected identity must not be re-raised. + // A previously rejected identity must not be re-raised. if sql::rejected_before_in(tx, pkgbase_id, &nc.identity_hash)? { return Ok(Upsert::PreviouslyRejected); } - // Same identity already approved/recorded: nothing to do. if sql::recorded_before_in(tx, pkgbase_id, &nc.identity_hash)? { return Ok(Upsert::Unchanged); } @@ -73,7 +59,6 @@ pub fn upsert_candidate(db: &Db, pb: &Pkgbase, accepted: Option<&ReleaseRow>, nc }) } -/// Convenience used by the watcher: the accepted release of a pkgbase row. pub fn accepted_for(db: &Db, pb: &Pkgbase) -> Result<Option<ReleaseRow>> { match pb.current_accepted_release_id { Some(id) => db::release_by_id(db, id), diff --git a/src/review/diff.rs b/src/review/diff.rs index 3eecc4e..519d9ae 100644 --- a/src/review/diff.rs +++ b/src/review/diff.rs @@ -1,10 +1,3 @@ -//! Diff rendering (§6). -//! -//! A review is not one diff, it is a panel set, and **every** panel compares what -//! the accepted release recorded against what the candidate records now — never -//! "last seen". The rendered text is hashed into `diff_digest`, which is what -//! makes "we build exactly what was displayed, or nothing" (§7.1a) provable. - use crate::config::Config; use crate::db::{self, *}; use crate::error::Result; diff --git a/src/review/mod.rs b/src/review/mod.rs index c8b2f50..eb78b3a 100644 --- a/src/review/mod.rs +++ b/src/review/mod.rs @@ -1,6 +1,3 @@ -//! Review lifecycle: candidate creation and collapse-in-place (§7.1), the -//! approval record (§7.2), diffing (§6) and risk scoring (§6). - pub mod approve; pub mod candidates; pub mod diff; diff --git a/src/review/risk.rs b/src/review/risk.rs index cf7069d..3b483cf 100644 --- a/src/review/risk.rs +++ b/src/review/risk.rs @@ -1,15 +1,3 @@ -//! Advisory risk scoring (§6). -//! -//! The reviewer's attention is the scarcest resource in this system, so every -//! candidate gets a computed level that orders and colours the inbox. It is -//! **advisory only**: there is no auto-approval in v1 (§7.3), so nothing is -//! gated on a score and no heuristic can let something through. A wrong score -//! costs attention, never safety. -//! -//! Every signal is computed from what the accepted release recorded against -//! what the candidate records now — the same "never last seen" rule that makes -//! I2 true for the diff panels. - use crate::db::{self, model::*, Db}; use crate::error::Result; use crate::pkgver; diff --git a/src/sandbox/agent.rs b/src/sandbox/agent.rs index 09a6f93..d7b841c 100644 --- a/src/sandbox/agent.rs +++ b/src/sandbox/agent.rs @@ -1,18 +1,3 @@ -//! The ephemeral sandbox agent: what runs *inside* the sandbox. -//! -//! One connection, one lease, one life: the agent dials the hub (outbound -//! rendezvous — the hub never needs a route into an untrusted box), accepts -//! `Run`/`Put`/`Get` frames for as long as the hub keeps the connection alive, -//! and dies — taking its child processes with it — when the connection drops -//! or its TTL expires. There is no state between leases by design: the sandbox -//! is disposable, the TTL is the guarantee, and a leaked sandbox is a bug in -//! the TTL watchdog, not a lifecycle question. -//! -//! The TTL watchdog is the backstop under every failure mode: hub crashes, -//! network partition, a hub bug that forgets `Destroy`. The hub keeps it fed -//! with `Ping` frames while a run is in flight; silence longer than the TTL -//! means nobody is coming, so the agent kills its child and exits. - use std::io::BufReader; use std::net::TcpStream; use std::path::{Path, PathBuf}; diff --git a/src/sandbox/kata.rs b/src/sandbox/kata.rs index c7d717f..9169f9f 100644 --- a/src/sandbox/kata.rs +++ b/src/sandbox/kata.rs @@ -1,25 +1,3 @@ -//! The kata backend: ad-hoc, TTL-bounded sandboxes provisioned by an -//! orchestrator, leased over the same agent protocol as everything else. -//! -//! This is composition, not a new protocol: a kata sandbox is a small VM that -//! boots the `sandbox-agent` image pointed at this hub, and `acquire` is -//! "ask the provisioner for a box, then wait for *that specific box* to dial -//! in". The nonce each lease generates is handed to the provisioner and comes -//! back as the agent's `agent_id`, so a stray sandbox can never be leased to -//! the wrong build, and a sandbox that never dials in is a TTL expiry — the -//! same vocabulary every other failure in this system speaks (I5). -//! -//! The payload is an agent-sandbox-style Kubernetes CR (`runtimeClass: kata`, -//! `activeDeadlineSeconds` as the TTL the orchestrator enforces). It is a pure -//! function, unit-tested; the network call that sends it is exercised only by -//! the gated live tier, which skips — with a printed note, never a silent -//! pass — wherever a cluster is absent. -//! -//! The `LocalAgentProvisioner` is the shape this tier is tested with: a real -//! `sandbox-agent` process, real rendezvous, no VM. It is to kata what the -//! loopback backend is to a clean machine — the honest stand-in that keeps -//! the interface itself under test. - use std::collections::HashMap; use std::io::BufReader; use std::net::{TcpListener, TcpStream}; @@ -218,16 +196,12 @@ impl KataBackend { /// /// A Kata backend cannot share only its listener the way the plain remote /// backend does: it routes every dial-in by the nonce in its `Hello` into a - /// map that belongs to it, so two backends on one address would each see - /// half the dial-ins and neither could complete a rendezvous. So the whole - /// backend is shared, not just the socket — which is also what makes - /// "one listener per process" true here, since binding happens exactly once - /// per distinct configuration. + /// map that belongs to it, so two backends on one address would each see half + /// the dial-ins. The whole backend is therefore shared, and binding happens + /// exactly once per distinct configuration. /// /// The key is a digest of everything that distinguishes one backend from - /// another, so the rendezvous token and the cluster bearer are not sitting - /// around in a second place, and two configurations that differ only in - /// unrelated hub settings still get their own backend. + /// another, so the tokens are not sitting around in a second place. pub fn shared_for(cfg: &Config) -> Result<Arc<KataBackend>> { let crate::config::Sandbox::AgentSandbox { api, namespace, bearer, image, listen, token, .. } = &cfg.sandbox diff --git a/src/sandbox/loopback.rs b/src/sandbox/loopback.rs index 8e9f52d..8a3c229 100644 --- a/src/sandbox/loopback.rs +++ b/src/sandbox/loopback.rs @@ -1,16 +1,3 @@ -//! The loopback backend: run sandbox commands as local subprocesses. -//! -//! This is today's behavior wearing the new interface — same `Config::child_env` -//! shim protocol (§16a), same captured output, same process as the hub. It is -//! what `cargo test` exercises and what a single machine with devtools runs; -//! the shim suite passing unchanged through this file is what makes the seam a -//! pure refactor rather than a re-architecture. -//! -//! Isolation here is *none*: the "sandbox" is the hub's own user. That is -//! honest — the loopback backend is for development, tests, and the local -//! chroot deployment where §14's sudo rules are the boundary — and the Kata -//! backend is where the machine boundary lives. - use std::fs; use std::io::Read; use std::path::PathBuf; diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs index 13cf282..ea3e126 100644 --- a/src/sandbox/mod.rs +++ b/src/sandbox/mod.rs @@ -1,29 +1,3 @@ -//! The sandbox seam: where build code actually runs (§8, remote-builder design). -//! -//! The pipeline executes untrusted recipe code, and the security boundary around -//! it has so far been "a chroot on this machine, with sudo rules" (§14). That -//! boundary is a *deployment* fact, not a pipeline fact: the step machine should -//! not know whether it is talking to a local process, a Kata container on a -//! cluster, or a loopback harness. So every subprocess the pipeline runs goes -//! through this interface instead of spawning one itself. -//! -//! Two implementations exist: -//! -//! * [`loopback::LoopbackBackend`] — today's behavior: commands run as local -//! subprocesses of the hub process, with the §16a shim protocol applied -//! through [`Config::child_env`]. This is what `cargo test` and a single -//! machine with devtools use. -//! * (planned) a Kata/agent-sandbox backend that leases disposable, TTL-bounded -//! sandboxes and speaks the wire protocol; the pipeline cannot tell the -//! difference, which is the entire point of the seam. -//! -//! The unit of isolation is a *sandbox lease*: [`SandboxBackend::acquire`] -//! hands out a handle, steps run commands on it, and the handle is destroyable -//! at any time. Nothing may assume a sandbox outlives its TTL, and nothing may -//! assume two tasks share one. Blob transfer is content-addressed by design: -//! there is no "path on the sandbox" concept in the interface at all, which -//! removes a class of hostile-write bugs that a path-based API would invite. - use std::collections::HashMap; use std::io::Read; use std::net::{TcpListener, TcpStream}; @@ -42,15 +16,14 @@ pub mod loopback; pub mod remote; pub mod wire; -/// A command to run inside a sandbox. Deliberately argv-shaped, not -/// `Command`-shaped: a remote sandbox must never be handed a shell string, and -/// the environment is the backend's business (see `Config::child_env`), not the -/// caller's. +/// A command to run inside a sandbox. Deliberately argv-shaped, never +/// shell-shaped: a remote sandbox must not be handed a shell string. The +/// environment is the backend's business (see `Config::child_env`). /// -/// An argv element of the form `blob:<digest>` names a content-addressed blob -/// staged with [`Sandbox::put`]: the backend expands it to wherever that blob -/// materializes inside the sandbox. Callers never name sandbox-local paths — -/// that is what keeps a loopback step byte-identical to a remote one. +/// An argv element of the form `blob:<digest>` names a blob staged with +/// [`Sandbox::put`]; the backend expands it to wherever the blob materializes +/// inside the sandbox. Callers never name sandbox-local paths, which is what +/// keeps a loopback step byte-identical to a remote one. #[derive(Debug, Clone)] pub struct Cmd { pub argv: Vec<String>, @@ -69,15 +42,12 @@ impl Cmd { self.cwd = Some(dir.into()); self } - /// The program name, for error messages. pub fn name(&self) -> &str { self.argv.first().map(String::as_str).unwrap_or("") } } -/// A finished command: exit status plus captured output. `code` is `None` when -/// the child died by signal — `success()` is false either way, matching what -/// `ExitStatus::success` would have said before the seam existed. +/// A finished command. `code` is `None` when the child died by signal. #[derive(Debug)] pub struct Exit { pub code: Option<i32>, @@ -92,11 +62,9 @@ impl Exit { } /// What a caller asks the pool for. `profile` is the only affinity key warm -/// pools need today (one warm root per build profile, §8.3); `task` is for -/// attribution and rendezvous, `ttl` is the guarantee that the sandbox is dead -/// no matter what this process then does, and `disk_mb` is the admission hint -/// that replaces the hub's local disk-headroom check (§8.2) once builds leave -/// the hub's filesystem. +/// pools need today (§8.3); `ttl` is the guarantee that the sandbox is dead no +/// matter what this process then does; `disk_mb` replaces the hub's local +/// disk-headroom check (§8.2) once builds leave the hub's filesystem. #[derive(Debug, Clone)] pub struct SandboxSpec { pub profile: String, @@ -111,7 +79,7 @@ impl SandboxSpec { } } -/// Pool state for the UI and notices: who is warm, who is busy, what profile. +/// Pool state for the UI and notices. #[derive(Debug, Clone)] pub struct SandboxInfo { pub id: String, @@ -121,37 +89,30 @@ pub struct SandboxInfo { /// A leased sandbox. `run` streams output through `on_log` as it arrives and /// also returns it captured, so a step can parse stdout while the build log -/// stays complete. `put`/`get` move content-addressed blobs in and out — the -/// hub pulls artifacts by digest and never accepts a destination path from a -/// sandbox, which is the same I9 posture the local staging-containment checks -/// already enforce. +/// stays complete. `put`/`get` move content-addressed blobs and never accept a +/// destination path from a sandbox — the same I9 posture the local staging +/// containment checks enforce. pub trait Sandbox: Send + Sync { fn id(&self) -> &str; fn run(&self, cmd: &Cmd, on_log: &mut dyn FnMut(&[u8])) -> Result<Exit>; fn put(&self, digest: &str, r: &mut dyn Read) -> Result<()>; fn get(&self, digest: &str) -> Result<Box<dyn Read>>; - /// Idempotent, and also happens by itself when the TTL bites. Destroying a - /// sandbox must never be the only thing standing between untrusted code and - /// the world. + /// Idempotent, and also happens by itself when the TTL bites. fn destroy(&self) -> Result<()>; } /// The pool. `acquire` may return a pre-warmed sandbox, cold-start one, or fail -/// when at quota; callers treat a failed acquire like a blocked build, not a -/// broken one. +/// when at quota; a failed acquire is a blocked build, not a broken one. pub trait SandboxBackend: Send + Sync { fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>>; fn status(&self) -> Result<Vec<SandboxInfo>>; } -/// Turn a configuration into the backend it names — the only place that does, -/// so "which backend" has exactly one answer. +/// Turn a configuration into the backend it names — the only place that does. /// /// `Config::validate` runs here as well as at startup: a guard that only exists -/// in the CLI is a guard a test, a tool, or a future daemon can walk past. -/// And an unknown or unwired kind is an error, never a fallthrough — a build -/// configured for a Kata VM that quietly ran as the hub's own user is the -/// failure this function used to have. +/// in the CLI is a guard a test or a future daemon can walk past. An unknown or +/// unwired kind is an error, never a fallthrough. pub fn backend_for(cfg: &Config) -> Result<Arc<dyn SandboxBackend>> { cfg.validate()?; match &cfg.sandbox { @@ -175,23 +136,17 @@ pub(crate) struct Bound { /// One bound listener per `(address, token)` per process. /// -/// The listener is a property of the *process*, not of a build. Binding it per -/// build — which is what happened while `Ctx::new` constructed a backend for -/// every build — meant a second concurrent build hit `EADDRINUSE` on a fixed -/// `listen` and failed for a reason that had nothing to do with its package. -/// Sharing the queue is also exactly the semantics the agent protocol has: an -/// agent dials in when it is booted, and whichever build is waiting takes it. -/// -/// The token is part of the key on purpose. Two different tokens cannot share a -/// listener, and reusing the first one's listener for a second, different token -/// would be a fail-open surprise; forcing a real bind makes the mistake loud. +/// The listener belongs to the process, not to a build: binding it per build +/// meant a second concurrent build hit `EADDRINUSE` for a reason unrelated to +/// its package. The token is part of the key because two different tokens +/// cannot share a listener, and silently reusing the first one's listener would +/// be a fail-open surprise. pub(crate) fn bound_listener(addr: &str, token: &str) -> Result<Bound> { static REGISTRY: OnceLock<Mutex<HashMap<(String, String), Bound>>> = OnceLock::new(); let registry = REGISTRY.get_or_init(|| Mutex::new(HashMap::new())); let key = (addr.to_string(), token.to_string()); - // A poisoned registry means a panic in some other thread's bind; the map - // itself is still sound, so recover rather than wedge every later build — - // the same posture as the publish lock. + // A poisoned registry means a panic in another thread's bind; the map is + // still sound, so recover rather than wedge every later build. let mut reg = registry.lock().unwrap_or_else(|p| p.into_inner()); if let Some(b) = reg.get(&key) { return Ok(b.clone()); diff --git a/src/sandbox/remote.rs b/src/sandbox/remote.rs index d02335c..1f9514f 100644 --- a/src/sandbox/remote.rs +++ b/src/sandbox/remote.rs @@ -1,24 +1,3 @@ -//! The hub side of the agent protocol: a [`SandboxBackend`] that leases -//! sandboxes which dial in from outside. -//! -//! The rendezvous is outbound-only: `acquire` waits for an agent to connect -//! and present the shared token, and every command since then is a frame on -//! the connection *the agent initiated*. A sandbox that vanishes mid-run is -//! not an error this code invents — a closed connection reads as a failed -//! step, which reads as an expired lease, which the reaper already turns into -//! a requeue (I5). The remote backend adds no new failure vocabulary. -//! -//! One connection is one lease: after `destroy` (or a drop of the hub side), -//! the agent dies and the next `acquire` waits for a fresh one. That matches -//! the disposable-sandbox model — warm pooling across steps of one build is -//! a backend optimization, not an interface requirement. -//! -//! Workspace note: `Run` frames carry a hub-side `cwd`, which is honest for -//! loopback-shaped deployments and the test tier where hub and sandbox share -//! a filesystem. A remote-over-the-network deployment needs the workspace -//! manifest/tar sync from the design sketch; that is deliberately not here -//! yet, and nothing should pretend otherwise. - use std::io::BufReader; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; diff --git a/src/sandbox/wire.rs b/src/sandbox/wire.rs index 4ea1c74..8f03063 100644 --- a/src/sandbox/wire.rs +++ b/src/sandbox/wire.rs @@ -1,19 +1,3 @@ -//! The hub↔sandbox wire protocol: length-prefixed JSON frames over a plain -//! socket, payloads hex-encoded. -//! -//! Deliberately boring, and deliberately dependency-free: one frame is a 4-byte -//! big-endian length followed by one JSON object. Binary payloads ride inside -//! the JSON as hex — twice the bytes of base64, but `hex` is already a -//! dependency and blobs (recipes, pinned packages) are small. A frame is -//! self-delimiting, so a reader that times out mid-frame cannot silently -//! desynchronize: the connection is dead, and a dead sandbox is a lease -//! expiry, which the reaper already knows how to handle (I5). -//! -//! The direction of connection matters: the *agent dials the hub*, never the -//! reverse. A sandbox is untrusted the moment it boots; the hub must never need -//! a route into it. Everything the hub wants — runs, blobs, teardown — is a -//! frame on the connection the agent initiated (outbound rendezvous). - use std::io::{self, BufRead, Write}; use serde::{Deserialize, Serialize}; @@ -33,18 +17,16 @@ pub enum Frame { /// hub → agent: rendezvous accepted; `ttl_secs` arms the agent's watchdog. HelloAck { ttl_secs: u64 }, /// hub → agent: run argv. `blob:<digest>` argv elements name blobs the - /// agent must have received via `Put`. `env` is the hub's child - /// environment (the §16a shim protocol rides on it in tests). + /// agent must already have via `Put`; `env` is the hub's child environment. Run { req: u64, argv: Vec<String>, cwd: Option<String>, env: Vec<(String, String)> }, /// agent → hub: a chunk of the running child's output, hex-encoded. Log { req: u64, stream: String, data: String }, /// agent → hub: the child finished. `code` is None when it died by signal. Exit { req: u64, code: Option<i32> }, - /// hub → agent: stage this content-addressed blob. The agent verifies - /// `data` hashes to `digest` before writing — the same posture the local - /// pacman fake enforces. + /// hub → agent: stage this blob. The agent verifies `data` hashes to + /// `digest` before writing. Put { req: u64, digest: String, data: String }, - /// hub → agent: pull this blob back out (artifacts come home by digest). + /// hub → agent: pull this blob back out. Get { req: u64, digest: String }, /// agent → hub: reply to `Get`. Blob { req: u64, data: String }, @@ -54,8 +36,7 @@ pub enum Frame { Err { req: u64, msg: String }, /// hub → agent: keepalive; resets the agent's TTL watchdog. Ping {}, - /// hub → agent: tear down now. The agent would also die on its own when - /// the connection drops — destroy is courtesy, TTL is the guarantee. + /// hub → agent: tear down now. TTL is the guarantee, this is courtesy. Destroy {}, } @@ -70,9 +51,8 @@ pub fn write_frame(w: &mut impl Write, f: &Frame) -> io::Result<()> { w.flush() } -/// Read one frame. `Ok(None)` means the peer closed the connection cleanly — -/// which, for a sandbox, is indistinguishable from "the sandbox is gone" and -/// therefore means the same thing to the hub: lease expired, requeue. +/// Read one frame. `Ok(None)` means a clean close, which for a sandbox means +/// the lease expired and the build should requeue. pub fn read_frame(r: &mut impl BufRead) -> io::Result<Option<Frame>> { let mut len = [0u8; 4]; match r.read_exact(&mut len) { @@ -130,8 +110,6 @@ mod tests { #[test] fn a_truncated_frame_is_an_error_not_a_silent_none() { - // Half a frame on the wire must read as a dead connection through an - // error path, never as a parsed frame. let mut buf = Vec::new(); write_frame(&mut buf, &Frame::Ping {}).unwrap(); buf.truncate(3); diff --git a/src/shims/mod.rs b/src/shims/mod.rs index 7118283..818d28d 100644 --- a/src/shims/mod.rs +++ b/src/shims/mod.rs @@ -1,26 +1,3 @@ -//! Toolchain shims (§16a). -//! -//! The pipeline shells out to `makepkg`, `pacman`, `repo-add` and `gpg` inside -//! a sandbox, and `git` outside it. In test mode the harness prepends a -//! directory of fakes to `PATH`; each fake records its invocation, obeys a -//! scripted outcome from the fixture manifest, and emits plausible -//! `.PKGINFO`/`.BUILDINFO`/`.sig` output. The `mkarchroot` and `makechrootpkg` -//! fakes remain as stand-ins for the real devtools — the pipeline stopped -//! calling them when builds moved to the provisioning model — so the shim -//! protocol itself stays exercised end to end. -//! -//! That is what makes the full step machine, checkpointing, lease/reaper -//! recovery, publishing and index regeneration runnable in milliseconds on any -//! machine — no Arch host, no root, no network. -//! -//! Protocol, all via environment so the pipeline needs no test-only code paths: -//! -//! | var | meaning | -//! |---|---| -//! | `AUR_SHIM_DIR` | where invocations are recorded (`invocations.jsonl`) | -//! | `AUR_SHIM_MANIFEST` | fixture manifest describing the scripted outcome | -//! | `AUR_SHIM_FAIL` | optional step name that must fail, e.g. `build` | - use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; @@ -150,15 +127,11 @@ pub fn record(tool: &str, args: &[String]) { } } -/// Test hook: kill the process that invoked us, mid-step, with a signal it -/// cannot catch. This is how the crash-resume invariant (I5) is tested for real: -/// the pipeline process dies while a step is running, with no chance to clean -/// up, and the next process must pick up from the checkpoints. +/// Test hook: kill the process that invoked us, mid-step, with a signal it cannot +/// catch. This is how the crash-resume invariant (I5) is tested for real. fn kill_parent_if_asked(tool: &str) { let want = std::env::var("AUR_SHIM_KILL_PARENT").unwrap_or_default(); if want == tool { - // Flush the invocation log first (record() already closed the file), - // then murder the parent. No cleanup, no unwinding, no atexit. unsafe { libc::kill(libc::getppid(), libc::SIGKILL); } @@ -250,20 +223,17 @@ pub fn mkarchroot(args: &[String]) -> Result<i32, String> { Ok(0) } -/// `makechrootpkg -c -r <chroot> -- ...`: the real tool's contract, kept as a -/// stand-in for direct shim tests. The pipeline no longer calls it — the build -/// step runs `makepkg` in the provisioned sandbox — so the package-emitting -/// logic lives in [`emit_packages`], shared with the `makepkg` shim. +/// `makechrootpkg -c -r <chroot> -- ...`: kept as a stand-in for direct shim +/// tests. The pipeline no longer calls it; the package-emitting logic lives in +/// [`emit_packages`], shared with the `makepkg` shim. pub fn makechrootpkg(args: &[String], m: &Manifest) -> Result<i32, String> { // The real tool reads a chroot root; asserting it keeps the fake honest // about the real tool's contract. if !args.iter().any(|a| a == "-r") { return Err("makechrootpkg: expected -r <chroot>".into()); } - // Sign only when the caller asked for it, like the real tool: signing is - // `-si<key>`/`-i`, and the pipeline stopped passing it when signing moved - // hub-side to ingest. A shim that signed anyway would hide that move from - // every test in the suite. + // Sign only when the caller asked, like the real tool. A shim that signed + // anyway would hide the move of signing hub-side from every test. let wants_sig = args.iter().any(|a| a.starts_with("-si") || a == "-i" || a == "--sign"); emit_packages(m, "makechrootpkg", wants_sig) } @@ -283,8 +253,8 @@ pub fn emit_packages(m: &Manifest, tool: &str, wants_sig: bool) -> Result<i32, S return Ok(1); } let startdir = std::env::current_dir().map_err(|e| e.to_string())?; - // The real tool reads the PKGBUILD it was handed; we assert it is there so - // a broken materialize step cannot pass silently. + // Assert the PKGBUILD is there so a broken materialize step cannot pass + // silently. if !startdir.join("PKGBUILD").exists() { let found = std::fs::read_dir(&startdir) .map(|rd| rd.filter_map(|e| e.ok()).map(|e| e.file_name().to_string_lossy().into_owned()).collect::<Vec<_>>()) @@ -309,9 +279,9 @@ pub fn emit_packages(m: &Manifest, tool: &str, wants_sig: bool) -> Result<i32, S Ok(0) } -/// I9 test hook: drop a symlink into the srcdir pointing wherever the test names, -/// standing in for a PKGBUILD that tries to smuggle outside bytes into the -/// artifact store. The pipeline must refuse it; see `collect` in steps.rs. +/// I9 test hook: drop a symlink into the srcdir standing in for a PKGBUILD that +/// tries to smuggle outside bytes into the artifact store. The pipeline must +/// refuse it; see `collect` in steps.rs. fn plant_link_if_asked(startdir: &Path) { let target = match std::env::var("AUR_SHIM_PLANT_LINK") { Ok(t) if !t.is_empty() => t, @@ -498,23 +468,19 @@ pub fn makepkg(args: &[String], m: &Manifest) -> Result<i32, String> { } } } else { - // `makepkg -c -f` style: the pipeline's build step, running in the - // provisioned sandbox. No `-s` and no `-si` reach this shim, and the - // emulation does not care: dependencies and signatures are the hub's - // business now. + // `makepkg -c -f`: the pipeline's build step in the provisioned sandbox. + // No `-s` and no `-si` reach this shim. emit_packages(m, "makepkg", false) } } -/// `pacman -U <blobs...>` / `pacman -Q`: a fake installed database living in -/// the shim dir, so the provisioning step's world check runs against something -/// that behaves. +/// `pacman -U <blobs...>` / `pacman -Q`: a fake installed database living in the +/// shim dir, so the provisioning step's world check runs against something that +/// behaves. /// -/// `-U` refuses any file that does not hash to the digest its filename claims -/// — the same trust posture as the real signature check — and records each -/// package from its `.PKGINFO`. `-Q` then reports exactly what was installed, -/// which is what makes the pipeline's fail-closed world assertion a real test -/// rather than a no-op. +/// `-U` refuses any file that does not hash to the digest its filename claims and +/// records each package from its `.PKGINFO`; `-Q` reports exactly what was +/// installed, which makes the pipeline's fail-closed world assertion a real test. pub fn pacman(args: &[String]) -> Result<i32, String> { if args.iter().any(|a| a == "-U") { for path in args.iter().filter(|a| !a.starts_with('-')) { @@ -556,24 +522,18 @@ fn installed_db() -> Option<std::path::PathBuf> { std::env::var("AUR_SHIM_DIR").ok().map(|d| std::path::Path::new(&d).join("installed.txt")) } -/// `repo-add [-s -p key -R] <db.tar.{gz,zst}> <pkg...>`: rebuild the database -/// from the packages handed to it. -/// -/// The real tool appends; `-R` replaces an existing entry. We rebuild the whole -/// db from the packages given, which is what our publish step does anyway (it -/// passes exactly the packages that belong in the index). -/// The database filenames pacman's repo-add accepts — and therefore the ones -/// this shim must accept, and no others. -/// -/// A shim that is more permissive than the tool it stands in for is worse than no -/// shim: the pipeline used to render its database to `<db>.tar.gz.tmp` and rename -/// it into place, real repo-add rejects that filename as a usage error, and every -/// publish test in the suite passed because the shim would write anywhere. That -/// is how the first real package anyone tried to publish died at the last step. -/// This list is the accepted set as measured against `repo-add (pacman) 7.1.0`: -/// the `.db.tar` forms with or without a compression suffix, and nothing else — -/// not `aur.db`, not `aur.db.gz`, and not the `.files.*` forms, which belong to -/// `repo-files`. +// `repo-add [-s -p key -R] <db.tar.{gz,zst}> <pkg...>`: rebuild the database +// from the packages handed to it. The real tool appends and `-R` replaces an +// existing entry; we rebuild the whole db, which is what our publish step does +// anyway. + +/// The database filenames pacman's repo-add accepts — and therefore the ones this +/// shim must accept, and no others. A shim more permissive than the tool it +/// stands in for is worse than no shim: the pipeline used to render its database +/// to `<db>.tar.gz.tmp`, real repo-add rejects that as a usage error, and every +/// publish test passed because the shim would write anywhere. Measured against +/// `repo-add (pacman) 7.1.0`: the `.db.tar` forms with or without a compression +/// suffix, and nothing else. pub const DB_SUFFIXES: [&str; 5] = [ ".db.tar", ".db.tar.gz", @@ -669,14 +629,11 @@ pub fn repo_add(args: &[String], _m: &Manifest) -> Result<i32, String> { Ok(0) } -/// Pull `.PKGINFO` out of a `.pkg.tar.zst` and render the `DESC` fields a -/// pacman database carries beyond the fixed ones. -/// -/// Both halves come from `crate::pkginfo`, the parser the production pipeline -/// uses (§6 M-4). The shim used to carry its own copy of the field parser, and -/// two parsers that can drift is a supply-chain-shaped foot-gun in a system -/// whose whole job is provenance: a test that passed because the shim read a -/// package one way would not have meant the pipeline read it that way. +/// Pull `.PKGINFO` out of a `.pkg.tar.zst` and render the `DESC` fields a pacman +/// database carries beyond the fixed ones. Both halves come from +/// `crate::pkginfo`, the parser the production pipeline uses — two parsers that +/// can drift is a supply-chain-shaped foot-gun in a system whose whole job is +/// provenance (§6 M-4). fn pkginfo_fields(pkg_bytes: &[u8]) -> Result<(String, String, String, String), String> { let text = crate::pkginfo::pkginfo_text(pkg_bytes)?; let info = crate::pkginfo::parse_pkginfo(&text); diff --git a/src/time.rs b/src/time.rs index 88a27c7..b5f077e 100644 --- a/src/time.rs +++ b/src/time.rs @@ -1,29 +1,17 @@ -//! Clock helpers. -//! -//! DESIGN.md §16: "use DB time (`strftime` at write) for all ordering and audit -//! stamps". We store timestamps as UTC ISO-8601 with second resolution so that -//! lexicographic ordering equals chronological ordering, and every write path -//! funnels through [`now`] so a test can pin the clock. - use chrono::{DateTime, SecondsFormat, TimeZone, Utc}; /// Current time as a canonical DB timestamp: `2026-11-17T20:43:24Z`. pub fn now() -> String { - // A test may pin the clock (see `pin`); production reads the real clock. match pinned() { Some(pinned) => pinned, None => fmt(Utc::now()), } } -/// The instant relative arithmetic should use. -/// -/// This is what makes `secs_ago` and `secs_ahead` honest under a pinned clock -/// (§6 m-1): a test that pins the clock and then asks for a 90-second lease -/// means a lease expiring 90 seconds after *the pinned instant*, not after the -/// real one. Reading the wall clock here instead would hand a pinned test a -/// lease that had already expired — or would not expire for a century — and the -/// test would pass while proving nothing about expiry at all. +/// The instant relative arithmetic should use, which is what makes `secs_ago` +/// and `secs_ahead` honest under a pinned clock (§6 m-1): a pinned test asking +/// for a 90-second lease means 90 seconds after *the pinned instant*, not after +/// the real one. fn base() -> DateTime<Utc> { match pinned().and_then(|p| parse(&p)) { Some(t) => t, @@ -51,12 +39,10 @@ pub fn pin(ts: &str) -> Option<String> { }) } -/// Unpin the clock for the current thread. pub fn unpin() { CLOCK.with(|c| *c.borrow_mut() = None); } -/// Parse a DB timestamp back into a `DateTime<Utc>`. pub fn parse(ts: &str) -> Option<DateTime<Utc>> { DateTime::parse_from_rfc3339(ts) .ok() @@ -68,19 +54,15 @@ pub fn parse(ts: &str) -> Option<DateTime<Utc>> { }) } -/// Whole seconds between two timestamps (`b - a`), or `None` if unparseable. pub fn delta_secs(a: &str, b: &str) -> Option<i64> { Some(parse(b)?.signed_duration_since(parse(a)?).num_seconds()) } -/// A timestamp `secs` seconds in the past, canonical format. Honors the pinned -/// clock — see [`base`]. +/// A timestamp `secs` from [`base`], canonical format. pub fn secs_ago(secs: i64) -> String { fmt(base() - chrono::Duration::seconds(secs)) } -/// A timestamp `secs` seconds in the future, canonical format. Honors the -/// pinned clock — see [`base`]. pub fn secs_ahead(secs: i64) -> String { fmt(base() + chrono::Duration::seconds(secs)) } diff --git a/src/urlutil.rs b/src/urlutil.rs index 75b52b9..51def16 100644 --- a/src/urlutil.rs +++ b/src/urlutil.rs @@ -1,17 +1,10 @@ -//! Source-URL questions that more than one module asks (§6 m-2). -//! -//! `review::diff` and `review::risk` each carried a verbatim copy of `hosts`, -//! which is the kind of duplication that stays harmless until one copy is fixed -//! and the other is not: the diff panel would tell a reviewer a host appeared -//! while the risk scorer stayed quiet about the same host. - use std::collections::BTreeSet; /// The host of one `source=()` entry, or `None` when it names no host — a local /// file, a relative path, or a `file://` URL. /// -/// Handles the two prefixes a PKGBUILD puts in front of a URL: a `custom::` -/// filename prefix, and the `git+`/`svn+`/`npm+` VCS scheme prefix. +/// Handles the `custom::` and `git+`/`svn+`/`npm+` prefixes a PKGBUILD puts before a +/// URL. pub fn host_of(source: &str) -> Option<String> { let s = source.rsplit("::").next().unwrap_or(source); let s = s.rsplit('+').next().unwrap_or(s); diff --git a/src/watch/detect.rs b/src/watch/detect.rs index 6271dae..de1285e 100644 --- a/src/watch/detect.rs +++ b/src/watch/detect.rs @@ -1,11 +1,3 @@ -//! Detection: the recipe watcher pass for one pkgbase (§5.1, §5.2, §5.3). -//! -//! The decision that matters is *what counts as a change*. A candidate exists -//! only if something **publishable** changed — if the version string is -//! unchanged, `pacman` cannot offer an upgrade, so there is nothing to approve. -//! Those events become `notice` rows instead, and are never silently dropped -//! (I11). - use crate::config::Config; use crate::db::{self, *}; use crate::error::Result; @@ -18,19 +10,10 @@ use crate::watch::mirror::{read_tree, sync_mirror, Sync}; /// What one check of one pkgbase resulted in. /// -/// Four variants mirror [`Upsert`], and that is deliberate rather than lazy -/// duplication (n-2). `Upsert` answers a storage question — what did the -/// candidate write do — and belongs to `review::candidates`; `Outcome` answers -/// the watcher's question — what should happen next, including the cases that -/// never reach the candidate table at all (paused, gone, blocked, a -/// non-publishable notice). Folding them into one enum would put -/// `Paused`/`Blocked` next to `Collapsed` in the review module, where they mean -/// nothing, and would make every caller in the scheduler match on storage -/// vocabulary. `outcome_of` is the total, compiler-checked translation between -/// the two, and it is the only place that knows both. +/// Four variants mirror [`Upsert`] deliberately (n-2): `Upsert` answers the storage +/// question, `Outcome` the watcher's. `outcome_of` is the only place that knows both. #[derive(Debug, Clone)] pub enum Outcome { - /// Nothing moved at all. NoChange, /// The subscription is paused: we look at nothing and change nothing. Paused, @@ -61,11 +44,9 @@ pub struct CheckReport { pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result<CheckReport> { let pb = get_pkgbase(db, name)? .ok_or_else(|| crate::error::Error::not_found(format!("pkgbase {name}")))?; - // A paused subscription is not observed at all. Pausing because a package is - // broken must not keep opening reviews nobody is going to act on, and it - // must not keep polling AUR either. The pause lives on the subscription, so - // that is what we consult. - let sub = db::get_subscription(db, name)?; + // A paused subscription is not observed at all: pausing must not keep opening + // reviews nobody will act on, nor keep polling AUR. + let sub = db::get_subscription(db, name)?;; let paused = sub.as_ref().map(|s| s.state == SubscriptionState::Paused).unwrap_or(false); if paused { return Ok(CheckReport { pkgbase: name.into(), head: String::new(), outcome: Outcome::Paused }); @@ -83,9 +64,8 @@ pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result<CheckReport> { db::set_subscription_state(&db.writer, name, SubscriptionState::Orphaned)?; return Ok(CheckReport { pkgbase: name.into(), head: String::new(), outcome: Outcome::Gone }); } - // The cheap poll saved us a fetch, but we still have to look: a source - // can change its bytes without the recipe moving at all, and that is the - // digest-drift case §5.3 calls the single most valuable detection. + // The cheap poll saved a fetch, but we still have to look: a source can + // change its bytes without the recipe moving (§5.3). Sync::Unchanged { head } => head.clone(), Sync::Fetched { head, .. } | Sync::Cloned { head } => head.clone(), }; @@ -95,18 +75,13 @@ pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result<CheckReport> { } /// When to look at this pkgbase again: its own interval if the subscription -/// carries one, otherwise the global default. -/// -/// The interval arrives as an argument because the caller read the subscription -/// row a moment ago to decide whether this pkgbase is paused (m-11); going back -/// to the database for a number the caller was holding was both a second query -/// and a second, possibly different, answer. +/// carries one, otherwise the global default. The interval is an argument because +/// the caller already read the subscription row (m-11). fn schedule_next(db: &Db, name: &str, poll_interval: Option<i64>) { let interval = poll_interval.unwrap_or_else(|| crate::db::setting_i64(db, "poll_interval", 86400)); let next = time::secs_ahead(interval); - // Best-effort: a missed "next check" stamp means the scheduler looks again - // a tick early, not that a change goes unnoticed — the tick re-selects by - // `next_check_at` and a NULL is due immediately. + // Best-effort: a missed stamp means the scheduler looks again a tick early, + // not that a change goes unnoticed. let _ = db::note_check(&db.writer, name, &next, None); } @@ -139,12 +114,11 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor let recipe_hash = tree.recipe_hash(); // §5.2, the two-stage funnel. Stage A is one `ls-remote` per VCS source and - // costs no clone; if the tip set is what the accepted release was built - // from, nothing can have changed and Stage B never runs. + // costs no clone; if the tip set is what the accepted release was built from, + // nothing can have changed and Stage B never runs. let has_vcs = recipe.source_entries.iter().any(|e| e.is_vcs()); let accepted_pins: Vec<UpstreamPin> = accepted.as_ref().map(|a| a.pins()).unwrap_or_default(); - // A recipe with no VCS sources states its own version; there is nothing to - // probe and nothing to resolve. + // A recipe with no VCS sources states its own version. let stage_a = if has_vcs { Some(crate::watch::upstream::probe(&recipe, &accepted_pins)?) } else { @@ -155,8 +129,8 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor } else if stage_a.as_ref().unwrap().needs_stage_b() { crate::watch::upstream::resolve(cfg, db, pb, &recipe, &recipe_hash, stage_a.as_ref().unwrap())? } else { - // Upstream has not moved. The version we serve is still the answer, and - // reusing its pins is what makes the next pass cheap too. + // Upstream has not moved; reusing the accepted pins keeps the next pass + // cheap too. accepted.as_ref().map(|a| crate::watch::upstream::StageB { epoch: a.epoch.clone(), pkgver: a.pkgver.clone(), @@ -166,7 +140,7 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor }) }; // For a VCS package the literal `pkgver=` is frozen; the resolved one is the - // only version a consumer could actually install. + // only version a consumer could install. let (epoch, pkgver, pkgrel, pins) = match &resolved { Some(r) => (r.epoch.clone(), r.pkgver.clone(), r.pkgrel.clone(), r.pins.clone()), None => (recipe.epoch.clone(), recipe.pkgver.clone(), recipe.pkgrel.clone(), Vec::new()), @@ -266,9 +240,7 @@ fn score( let _ = crate::review::candidates::set_risk(db, id, &a.level, &a.signals); } // Record now what would block the build later, using the same rule the plan - // step uses. A reviewer approving a package whose dependencies we have not - // published yet should see that before they approve it, not as a blocked - // build afterwards (§10.4). + // step uses, so a reviewer sees it before approving (§10.4). let missing = missing_deps(db, pb, recipe); let _ = crate::review::candidates::set_missing_deps(db, id, &missing); } @@ -306,9 +278,8 @@ fn outcome_of(up: Upsert) -> Outcome { } } -/// The version string did not move, so there is no review to open — but the -/// change is recorded, because a silently drifting tarball is exactly the kind -/// of thing that must not be invisible (§5.3). +/// The version string did not move, so there is no review to open — but the change +/// is recorded, because a silently drifting tarball must not be invisible (§5.3). fn non_publishable( db: &Db, pb: &Pkgbase, @@ -319,12 +290,8 @@ fn non_publishable( let old_digests: Vec<SourceDigest> = base.digests(); let new_digests: Vec<SourceDigest> = serde_json::from_str(&nc.source_digests_json).unwrap_or_default(); // A local source is part of the recipe: when its bytes move, that *is* the - // recipe drift, not an integrity event. The integrity alert is specifically - // "the bytes upstream serves no longer match what we built" (§5.3). - // A VCS source's digest *is* its pin, so upstream moving shows up there too - // — but that is ordinary drift, handled by the pin check below, not an - // integrity event. Integrity means "the bytes we built are gone and the - // version says nothing moved", which only applies to fixed downloads. + // recipe drift. A VCS source's digest is its pin, so upstream moving shows up + // there too, but that is ordinary drift (§5.3). let vcs_indices: std::collections::BTreeSet<usize> = recipe .source_entries .iter() @@ -346,9 +313,8 @@ fn non_publishable( if digest_changed { // The single most valuable detection in the system: the artifact in the - // index was built from bytes upstream no longer serves, and the version - // string is unchanged. An approval would be useless (approving it would - // not let us publish anything), so this is an alert, not a review. + // index was built from bytes upstream no longer serves, and the version is + // unchanged. An approval would be useless, so this is an alert. let changed: Vec<serde_json::Value> = changed_remote .iter() .map(|n| { diff --git a/src/watch/digests.rs b/src/watch/digests.rs index 8136850..d3119eb 100644 --- a/src/watch/digests.rs +++ b/src/watch/digests.rs @@ -1,15 +1,3 @@ -//! Source digest resolution (§5.3). -//! -//! `sha256sums=('SKIP')` is the hole in the integrity story. We resolve and -//! record the digest of *every* source ourselves, at detection time, regardless -//! of what the PKGBUILD declares — which turns a silent artifact swap into a -//! reviewable (or at least alertable) event. -//! -//! Cost control: only `SKIP`-declared static sources cost bandwidth. Declared -//! checksums are trusted-as-declared for identity because makepkg enforces them -//! at build time; VCS digests come free from the pin we already resolved; local -//! files are already in the mirror. - use crate::config::Config; use crate::db::{self, *}; use crate::error::Result; @@ -49,10 +37,9 @@ pub fn resolve_sources( digest, size: 0, // Computed from the recipe like every other entry (m-19), not - // hardcoded: the field answers "did the recipe give us a - // checksum?", and for a VCS source the answer is usually yes-by- - // absence — which is why renderers must ask `is_vcs` before - // calling it a missing checksum. + // hardcoded: for a VCS source the answer is usually + // yes-by-absence, so renderers must ask `is_vcs` before calling + // it a missing checksum. skip_declared: match declared_sums(recipe, entry.index) { Some(d) => d == SKIP || !is_hex_digest(&d), None => true, @@ -120,11 +107,8 @@ pub fn resolve_sources( /// Download `url`, hashing as we go, and record it in `source_cache`. /// -/// This always goes to the network. That is deliberate: the whole point of §5.3 -/// is to notice that the bytes behind a `SKIP` source changed while the version -/// did not, and answering from our own cache would make that impossible. The -/// cache exists so the *build* can reuse the bytes it was reviewed against -/// ([`cached_path`]), not so detection can skip looking. +/// This always goes to the network: the point of .5.3 is to notice that the bytes +/// behind a `SKIP` source changed while the version did not. pub fn download_and_cache(cfg: &Config, db: &Db, url: &str) -> Result<(String, u64)> { let tmp = cfg.source_cache_dir().join(format!("tmp-{}", crate::hash::short(url.as_bytes(), 16))); let (digest, size) = crate::fetch::fetch_to(url, &tmp)?; diff --git a/src/watch/mirror.rs b/src/watch/mirror.rs index 989b968..b6f9c47 100644 --- a/src/watch/mirror.rs +++ b/src/watch/mirror.rs @@ -1,10 +1,3 @@ -//! The local AUR git mirror (§5.1). -//! -//! Clone, don't scrape. The mirror is load-bearing rather than a cache: every -//! build materializes its recipe from it at the pinned commit and never asks -//! the network for a recipe (§5.1a), so losing it would mean losing the ability -//! to reproduce any historical release. - use std::collections::BTreeMap; use std::path::Path; @@ -64,11 +57,10 @@ fn record(db: &Db, name: &str, head: &str, mirror: &Path) -> Result<()> { #[derive(Debug, Clone)] pub struct Tree { /// `(path, git blob id)` for every file in the tree — the input to - /// `recipe_hash`. Covers PKGBUILD, .SRCINFO, *.install and shipped patches - /// (§3): a patch file is part of the recipe. + /// `recipe_hash`, which covers shipped patches too (§3). pub blobs: Vec<(String, String)>, - /// Text bodies, keyed by path. Binary files are omitted from this map but - /// still counted in `blobs`. + /// Text bodies, keyed by path. Binary files are omitted here but still + /// counted in `blobs`. pub files: BTreeMap<String, String>, } diff --git a/src/watch/mod.rs b/src/watch/mod.rs index 87df3f3..8c7604f 100644 --- a/src/watch/mod.rs +++ b/src/watch/mod.rs @@ -1,6 +1,3 @@ -//! Watchers: AUR recipe mirror (§5.1), upstream VCS probe (§5.2), source digest -//! resolution (§5.3), and the scheduler tick. - pub mod detect; pub mod digests; pub mod mirror; diff --git a/src/watch/scheduler.rs b/src/watch/scheduler.rs index ca42e32..837a51a 100644 --- a/src/watch/scheduler.rs +++ b/src/watch/scheduler.rs @@ -1,8 +1,3 @@ -//! The scheduler tick (§4: "one tick thread + sweep over `next_check_at`"). -//! -//! Blocking is the right shape here: the tick sleeps between sweeps and each -//! sweep is a sequence of blocking git and HTTP calls. - use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread::JoinHandle; diff --git a/src/watch/staleness.rs b/src/watch/staleness.rs index e052b26..2631769 100644 --- a/src/watch/staleness.rs +++ b/src/watch/staleness.rs @@ -1,14 +1,3 @@ -//! Staleness (§10.2): "would rebuilding this change what a consumer gets?" -//! -//! Computed **on read**, never stored. A stored staleness flag goes wrong the -//! moment anything else is published, and there is always something else being -//! published; deriving it from the world snapshots and the current index means -//! it can never lie. -//! -//! The pair comes from §10.1: each build recorded the versions of *our* -//! packages it was built against. If any of those differ from what the index -//! holds now, the artifact was built against a world that no longer exists. - use crate::db::{self, Db}; use crate::error::Result; @@ -73,12 +62,10 @@ pub fn stale_for(db: &Db, pkgbase: &str) -> Result<Vec<Stale>> { Ok(stale_rows(db)?.into_iter().filter(|s| s.pkgbase == pkgbase).collect()) } -/// AUR now offers a **lower** version than we serve (§10.2). This is not a -/// build request; it is an announcement that the mirror and the upstream have -/// disagreed, and someone has to decide which one consumers follow. +/// AUR now offers a **lower** version than we serve (§10.2). This is not a build +/// request; it is an announcement that the mirror and upstream have disagreed. /// -/// Derived on read from the newest candidate per pkgbase against the accepted -/// release, so it disappears the moment either side moves. +/// Derived on read, so it disappears the moment either side moves. pub fn downgrades(db: &Db) -> Result<Vec<Stale>> { let rows = db::served_vs_offered_pkgvers(db)?; let mut out = Vec::new(); diff --git a/src/watch/upstream.rs b/src/watch/upstream.rs index c2772a2..507d734 100644 --- a/src/watch/upstream.rs +++ b/src/watch/upstream.rs @@ -1,20 +1,3 @@ -//! The two-stage VCS watcher (§5.2) — the expensive path, made cheap. -//! -//! For a `-git` package the `pkgver=` field is frozen and the real version is -//! computed by `pkgver()` at build time, so detection cannot read it off the -//! recipe. Running the real thing every poll would be absurd, so: -//! -//! **Stage A** asks each upstream where its tip is now (`git ls-remote`, which -//! costs one network round trip and no clone). If the set of tips is identical -//! to the set recorded on the accepted release, *nothing can have changed* and -//! we stop. This is the common case: most days, nothing moves. -//! -//! **Stage B** runs only when Stage A saw movement: clone/fetch into the -//! persistent cache, run `makepkg --vercheck` against the recipe, and read back -//! the computed `epoch:pkgver-pkgrel` — the only correct answer, because -//! `pkgver()` can do arbitrary things. The clone is already there, so this is -//! also where the pins are captured. - use std::collections::BTreeSet; use std::path::PathBuf; use std::process::Command; @@ -148,9 +131,8 @@ impl StageB { } } -/// A process-wide cap on concurrent Stage B resolutions (§5.2 "a global -/// concurrency cap"). Each one clones repositories and runs a chroot-less -/// makepkg; letting twenty run at once would be silly. +/// A process-wide cap on concurrent Stage B resolutions (§5.2). Each one clones +/// repositories and runs a chroot-less makepkg. static RUNNING: AtomicUsize = AtomicUsize::new(0); static SLOT_FREE: Condvar = Condvar::new(); static SLOT_LOCK: Mutex<()> = Mutex::new(()); @@ -205,9 +187,9 @@ pub fn resolve( return Ok(Some(StageB::from_cache(hit))); } - // Per-pkgbase cooldown: even if the tips moved again, we do not re-resolve - // the same pkgbase more than once per cooldown window. The previous answer - // is reused, so a chatty upstream cannot turn detection into a build loop. + // Per-pkgbase cooldown: even if the tips moved again, we do not re-resolve the + // same pkgbase more than once per window, so a chatty upstream cannot turn + // detection into a build loop. let cooldown = db::setting_i64(db, "stage_b_cooldown", 86400); if let Some(recent) = db::stage_b_recent(db, pb.id, cooldown)? { return Ok(Some(StageB::from_cache(recent))); 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<String> { 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<Config, String> { @@ -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<String> { #[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("<form method=\"post\"")); @@ -148,8 +138,8 @@ fn a_stale_approval_is_a_409_that_renders_the_current_diff() { ); assert_eq!(res.status, 409, "a stale approval must come back as 409"); assert!(res.body.contains("refused"), "no explanation: {}", &res.body[..200.min(res.body.len())]); - // Either way the reviewer is told the ground moved under them, and shown - // the review as it is NOW rather than the one they asked to approve. + // Either way the reviewer is told the ground moved, and shown the review as it + // is NOW rather than the one they asked to approve. assert!( res.body.contains("while you were looking") || res.body.contains("no longer pending"), "not a §7.1a explanation: {}", @@ -191,8 +181,7 @@ fn bulk_approve_refuses_high_risk_without_individual_confirmation() { assert!(res.body.contains("refused"), "bulk approve accepted a high-risk item: {}", &res.body[..300.min(res.body.len())]); assert_eq!(web.env.query_i64("SELECT count(*) FROM approval", &[]), Some(0)); - // Confirming it individually lets it through — bulk is per-item, never - // "approve everything forever" (§7.4). + // Confirming it individually lets it through — bulk is per-item (§7.4). let res = web.post( "/reviews/bulk", &[("csrf", &web.csrf), ("decision", "approve"), ("ids", &id), ("confirm", &id)], @@ -221,19 +210,16 @@ fn a_password_gate_redirects_anonymous_visitors() { #[test] fn a_forged_auth_cookie_is_not_a_session() { - // What this pins: the gate used to read `Cookie: auth=1`, a value login - // merely echoed, so any client that typed the cookie itself could read the - // reviews, the audit log and the build output without ever supplying the - // password. The session id is the credential now, and only this process - // can mint one. + // What this pins: the gate used to read `Cookie: auth=1`, a value login merely + // echoed, so any client that typed the cookie could read the reviews without + // ever supplying the password. The session id is the credential now. let web = Web::with_password("plain-make", "s3cret"); for path in ["/", "/reviews", "/audit", "/settings", "/builds", "/packages"] { let res = web.raw_request("GET", path, &[("Cookie", "auth=1".into())], None); assert_eq!(res.status, 303, "{path} let a forged cookie through ({}): {}", res.status, &res.body[..120.min(res.body.len())]); assert_eq!(res.header("location"), Some("/login"), "{path} did not redirect to the login page"); } - // A POST with the forged cookie is turned away at the gate too, before the - // CSRF step ever gets a chance to mint the attacker a session of their own. + // A POST with the forged cookie is turned away at the gate too. let res = web.raw_request("POST", "/logout", &[("Cookie", "auth=1".into())], Some("")); assert_eq!(res.status, 303, "a forged cookie reached a mutating route"); // And the word "auth" is not a cookie the server recognises anywhere. @@ -257,8 +243,7 @@ fn login_rotates_the_session_and_logout_ends_it() { if !anon.is_empty() { assert_eq!(web.raw_request("GET", "/reviews", &[("Cookie", anon)], None).status, 303, "the pre-login sid still worked"); } - // Logout drops the sid server-side, which invalidates its CSRF token with - // it, so the same cookie is an anonymous visitor again. + // Logout drops the sid server-side, which invalidates its CSRF token with it. let out = web.raw_request("POST", "/logout", &[("Cookie", session.clone()), ("Content-Type", "application/x-www-form-urlencoded".into())], Some(&format!("csrf={}", web.csrf))); assert_eq!(out.status, 303, "logout did not redirect: {}", out.status); assert_eq!(web.raw_request("GET", "/reviews", &[("Cookie", session)], None).status, 303, "the logged-out sid still worked"); @@ -266,8 +251,8 @@ fn login_rotates_the_session_and_logout_ends_it() { #[test] fn handlers_read_on_a_read_only_connection() { - // The claim under test: a handler can never take the write lock, because - // the connection it reads through is read-only at the SQLite level. + // The claim under test: a handler can never take the write lock, because the + // connection it reads through is read-only at the SQLite level. let web = Web::new("plain-make"); let err = web .env diff --git a/tests/invariants.rs b/tests/invariants.rs index 770966f..35f5b1a 100644 --- a/tests/invariants.rs +++ b/tests/invariants.rs @@ -1,13 +1,3 @@ -//! The §2 invariant index. -//! -//! Every invariant in DESIGN.md §2 gets a named test here, asserted as a -//! **post-condition on a real end-to-end run** rather than as a unit test of the -//! function that happens to maintain it. If one of these ever fails, the -//! property the whole design rests on is broken, not just some helper. -//! -//! Invariants whose mechanism lands in a later phase are named at the bottom -//! with the test that covers them once it does. - mod common; use aur_build::db::{self, builds, model::*}; @@ -72,8 +62,8 @@ fn i1_every_index_entry_traces_back_to_an_approval() { } /// **I2 — the diff base is the last accepted version, never the last seen one.** -/// Many detections arrive while nobody is looking; the review still compares -/// against the accepted release, not against whatever was polled last. +/// Many detections arrive while nobody is looking; the review still compares against +/// the accepted release. #[test] fn i2_base_is_the_last_accepted_version_after_many_detections() { let (env, fx) = env_with_fixture("plain-make"); @@ -175,8 +165,8 @@ fn i5_resume_after_a_crash_repeats_no_completed_step() { ); // No duplicate side effects: one release row for the version, one artifact. assert_eq!(count(&env, "SELECT count(*) FROM release WHERE pkgver='2.0'"), 1); - // Artifacts are content-addressed and persist across builds; what must not - // happen is the same bytes recorded twice. + // Artifacts are content-addressed; what must not happen is the same bytes + // recorded twice. assert_eq!( count(&env, "SELECT count(*) FROM artifact"), count(&env, "SELECT count(DISTINCT digest) FROM artifact"), @@ -224,8 +214,7 @@ fn i7_the_schema_refuses_a_second_open_review() { } /// **I8 — the served index is exactly the set of accepted pointers.** Not a -/// superset (nothing stale lingers) and not a subset (nothing published is -/// missing). Checked against the files on disk as well as the rows. +/// superset and not a subset. Checked against the files on disk as well as the rows. #[test] fn i8_index_equals_the_accepted_pointers() { let (env, fx) = env_with_fixture("plain-make"); @@ -304,8 +293,7 @@ fn i6_manual_rebuild_publishes_the_same_version_without_a_new_approval() { /// n-5: a manual rebuild's identity used to be a hand-rolled /// `format!("{commit}|{hash}|manual}")` — a second, incompatible format for the /// same concept, with a delimiter that can occur inside the values. It is now -/// derived through the same canonical-JSON hash as every other identity, and -/// what the change must not disturb is the two properties the queue depends on. +/// derived through the same canonical-JSON hash as every other identity. #[test] fn a_manual_rebuild_is_deterministic_and_its_own_build() { let (env, _fx) = env_with_fixture("plain-make"); @@ -418,19 +406,12 @@ fn index_db_names(path: &std::path::Path) -> Vec<String> { 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<String> { #[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("<script src=\"/static/htmx.min.js\""), "htmx is not loaded"); - // And with JavaScript switched off the same HTML already contains the table: - // the refresh is an enhancement, not a requirement. + // And with JavaScript off the same HTML already contains the table. assert!(page.contains("<table>"), "no server-rendered table"); - // The fragment endpoint returns the table on its own, so htmx can swap it in - // without dragging the whole document along. + // The fragment endpoint returns the table on its own, so htmx can swap it in. let frag = ureq::get(&format!("{base}?fragment=1")).call().unwrap().into_string().unwrap(); assert!(frag.starts_with("<div id=\"builds\""), "fragment is not the table: {}", &frag[..120.min(frag.len())]); assert!(!frag.contains("<!doctype"), "the fragment is a whole page"); @@ -126,9 +118,8 @@ fn htmx_is_the_only_javascript_and_what_is_shipped_fits_the_budget() { let (env, fx) = env_with_fixture("plain-make"); let web = Web::attach(env, fx); // Served bytes are what a browser actually downloads, and that is the budget - // with any meaning: the file on disk is 48 KB, the wire copy is not. - // Read the wire bytes directly: an HTTP client would transparently - // decompress, which is exactly the thing this budget is about. + // with any meaning. An HTTP client would transparently decompress, which is + // exactly what this budget is about, so read the wire directly. let (headers, served) = raw_get(&web, "/static/htmx.min.js", true); assert!(headers.to_lowercase().contains("content-encoding: gzip"), "the vendored js is not compressed: {headers}"); assert!( @@ -159,13 +150,13 @@ fn the_stylesheet_is_served_and_the_review_surface_needs_no_javascript() { assert!(css.contains("body"), "app.css is a placeholder"); let page = web.get("/reviews").body; assert!(page.contains("<link rel=\"stylesheet\" href=\"/static/app.css\">"), "the page does not load it"); - // The review flow is the one that must work with scripting disabled, so it - // deliberately does not load htmx at all. + // The review flow is the one that must work with scripting disabled, so it does + // not load htmx at all. assert!(!page.contains("<script"), "the review surface ships JavaScript"); } -/// Ask for a path over a bare socket so the response is seen as it goes over the -/// wire, before any client-side content negotiation undoes it. +/// Ask for a path over a bare socket so the response is seen before any client-side +/// content negotiation undoes it. fn raw_get(web: &Web, path: &str, gzip: bool) -> (String, Vec<u8>) { use std::io::{BufRead, BufReader, Write}; let addr = web.server.addr.clone(); diff --git a/tests/notices.rs b/tests/notices.rs index 7051acf..1f2852e 100644 --- a/tests/notices.rs +++ b/tests/notices.rs @@ -1,11 +1,3 @@ -//! Non-publishable change handling (§5.2, §5.3) and advisory risk scoring (§6). -//! -//! I11 is the invariant here: **a change that cannot be published is still -//! recorded.** The tempting failure mode is "nothing to approve, so nothing to -//! say" — which is exactly how a silently swapped tarball becomes invisible. -//! Every non-publishable change becomes a `notice` row, and the index keeps -//! serving the artifact it has. - mod common; use aur_build::db::{self, model::*}; @@ -125,8 +117,8 @@ fn risk_scoring_compares_against_the_accepted_release() { assert_eq!(c.risk_level, risk::level::LOW, "signals: {:?}", c.risk_signals()); assert!(!c.risk_signals().iter().any(|s| s.starts_with("recipe-code-changed"))); - // Now change the build body and add a fetching makedep: that is the shape of - // a real supply-chain edit and it must say so. + // Now change the build body and add a fetching makedep: the shape of a real + // supply-chain edit. let path = fx.aur.join("PKGBUILD"); let text = std::fs::read_to_string(&path).unwrap(); std::fs::write( @@ -158,9 +150,8 @@ fn a_first_introduction_is_flagged_as_its_own_kind_of_review() { #[test] fn i11_nothing_publishable_is_ever_silently_dropped() { - // Sweep every fixture through detection and assert the outcome is always - // one of: a review, a notice, an explicit no-change, or a recorded failure. - // There is no path where something moved and we said nothing. + // Sweep every fixture through detection and assert the outcome is always a + // review, a notice, an explicit no-change, or a recorded failure. let fixtures = [ "plain-make", "with-patch", "skip-checksum", "split-pkgbase", "epoch-bump", "pkgrel-reset", "downgrade", "git-sourced", "pin-drift", "digest-drift", "missing-dep", "build-fails", diff --git a/tests/ops.rs b/tests/ops.rs index 305976e..8fc6308 100644 --- a/tests/ops.rs +++ b/tests/ops.rs @@ -1,12 +1,3 @@ -//! Retention, metrics and backups (§15). -//! -//! These are the features that only get tested when something goes wrong, which -//! is why they are specified here as behaviour rather than as functions that -//! exist. The load-bearing claims: retention never evicts a byte the index is -//! serving, it treats a package and its log and its sources as one unit, and it -//! never deletes the history that explains the bytes. Metrics are computed from -//! live state, so they cannot drift. Backups are `VACUUM INTO`, so they restore. - mod common; use std::path::{Path, PathBuf}; @@ -85,9 +76,8 @@ fn retention_keeps_the_newest_n_versions_and_never_deletes_a_row() { assert!(!p.exists(), "an evicted artifact should be gone: {}", p.display()); } - // Nothing was forgotten: the rows are all still there, marked as purged - // rather than removed, so "which bytes produced this" stays answerable as - // history even once the bytes are gone. + // Nothing was forgotten: the rows are all still there, marked as purged rather + // than removed (§15). assert_eq!(env.query_i64("SELECT count(*) FROM release", &[]), Some(5)); assert_eq!(env.query_i64("SELECT count(*) FROM artifact", &[]), Some(5)); assert_eq!( @@ -118,10 +108,9 @@ fn retention_keeps_a_package_with_its_log_and_sources_as_one_unit() { }) .unwrap(); let files = ops::release_files(&env.cfg, &env.db, oldest).unwrap(); - // Compare against what the database says the release holds, rather than - // guessing from filename shapes: the store is content-addressed, so the - // package file is a bare hex name and "does it look like a package" is not - // a question the path can answer. + // Compare against what the database says the release holds: the store is + // content-addressed, so "does it look like a package" is not a question the + // path can answer. let held: Vec<(Option<String>, Option<String>, Option<String>)> = env .db .read(|c| { @@ -150,8 +139,8 @@ fn retention_keeps_a_package_with_its_log_and_sources_as_one_unit() { assert!(Path::new(p).exists(), "the {what} should exist before eviction"); } - // Eviction removes them together. A package whose log is gone but whose bytes - // remain is the worst outcome: full price, no explanation. + // Eviction removes them together: a package whose log is gone but whose bytes + // remain is full price for no explanation. ops::retention(&env.cfg, &env.db, Some(1)).unwrap(); let still_there: Vec<&PathBuf> = files.iter().filter(|f| f.exists()).collect(); assert!( @@ -162,9 +151,8 @@ fn retention_keeps_a_package_with_its_log_and_sources_as_one_unit() { #[test] fn retention_never_evicts_the_version_the_index_is_serving() { - // The interesting case: the accepted release is *not* the newest one, because - // the newest build has not happened yet. A naive "keep the newest N" would - // delete the bytes the index is pointing at. + // The accepted release is *not* the newest one here; a naive "keep the newest + // N" would delete the bytes the index points at. let (env, fx) = env_with_fixture("plain-make"); publish_versions(&env, &fx, "plain-make", 2); let served = env @@ -248,8 +236,7 @@ fn metrics_reports_the_operating_numbers_in_prometheus_format() { let m = ops::metrics(&env.cfg, &env.db).unwrap(); let text = m.to_prometheus(); - // Every family the contract names, and each one parseable as a Prometheus - // sample: `name{labels} value`, preceded by its TYPE line. + // Every family the contract names, each parseable as a Prometheus sample. for family in [ "aurbuild_queue_depth", "aurbuild_pending_review_candidates", @@ -294,8 +281,8 @@ fn metrics_reports_the_operating_numbers_in_prometheus_format() { #[test] fn a_fresh_install_reports_a_clean_sheet_not_a_division_by_zero() { - // A brand-new install has no builds at all. Success rate has to be something - // an alert rule can read, not NaN and not 0% (which would page). + // A brand-new install has no builds at all: success rate has to be something an + // alert rule can read, not NaN and not 0%. let env = Env::new(); let m = ops::metrics(&env.cfg, &env.db).unwrap(); assert_eq!(m.succeeded + m.failed, 0); @@ -329,8 +316,7 @@ fn backup_is_a_consistent_single_file_that_reopens_and_matches() { let out = ops::backup(&env.db, &dest).unwrap(); assert_eq!(out, dest); - // A single file: `VACUUM INTO` produces a compacted database with no WAL, so - // the backup is one object that can be copied while the server keeps running. + // A single file: `VACUUM INTO` produces a compacted database with no WAL. assert!(dest.exists()); assert!(!Path::new(&format!("{}-wal", dest.display())).exists(), "a backup must not need a sidecar"); assert!(!Path::new(&format!("{}-shm", dest.display())).exists()); @@ -346,8 +332,7 @@ fn backup_is_a_consistent_single_file_that_reopens_and_matches() { assert_eq!(releases, 1); drop(probe); - // The live database is untouched and still in WAL mode — the backup did not - // checkpoint it out from under the running server. + // The live database is untouched and still in WAL mode. let mode: String = env .db .read(|c| Ok(c.query_row("PRAGMA journal_mode", [], |r| r.get::<_, String>(0))?)) @@ -358,8 +343,8 @@ fn backup_is_a_consistent_single_file_that_reopens_and_matches() { #[test] fn backup_refuses_to_overwrite_an_existing_snapshot() { - // A backup that silently replaces last week's backup is not a backup; it is a - // way of losing the only copy on the day you need it. + // A backup that silently replaces last week's backup is a way of losing the + // only copy on the day you need it. let (env, _fx) = env_with_fixture("plain-make"); approve_and_build(&env, "plain-make"); let dest = env.root().join("snap.db"); @@ -370,8 +355,7 @@ fn backup_refuses_to_overwrite_an_existing_snapshot() { assert!(std::fs::metadata(&dest).unwrap().len() > 0); } -/// Set a directory's mtime into the past, so the grace period can be exercised -/// without sleeping for an hour. +/// Set a directory's mtime into the past, so the grace period can be exercised. fn backdate(path: &Path, secs: u64) { let old = std::time::SystemTime::now() - std::time::Duration::from_secs(secs); for f in std::fs::read_dir(path).into_iter().flatten().flatten() { diff --git a/tests/pipeline.rs b/tests/pipeline.rs index d4ef724..6dd1df5 100644 --- a/tests/pipeline.rs +++ b/tests/pipeline.rs @@ -1,6 +1,3 @@ -//! End-to-end pipeline tests driven entirely by the toolchain shims (§16a): -//! no root, no network, no real chroot — but the *real* step machine runs. - mod common; use aur_build::db::{self, builds, model::*}; @@ -86,11 +83,9 @@ fn end_to_end_publishes_a_signed_index() { #[test] fn the_build_never_signs_ingest_does() { - // Signing moved hub-side: the build environment is a sandbox that must - // never hold the key, so the build command carries no `-si` and the - // signature over each artifact is made at ingest by the hub's own gpg. - // This is the property that makes a remote build sandbox safe to run at - // all — worst the sandbox ever returns is unsigned bytes. + // Signing moved hub-side: the build command carries no `-si` and the signature + // over each artifact is made at ingest by the hub's own gpg. Worst the sandbox + // ever returns is unsigned bytes. let (env, _fx) = env_with_fixture("plain-make"); let c = approve_fixture(&env, "plain-make"); assert!(matches!(run_for(&env, &c), pipeline::Outcome::Succeeded { .. })); @@ -119,10 +114,8 @@ fn the_build_never_signs_ingest_does() { #[test] fn a_tampered_store_artifact_fails_the_lease_closed() { - // dep-client depends on plain-make, so its lease pins plain-make's exact - // artifact. Corrupt the store bytes after publication: provisioning - // re-hashes everything it stages and must refuse, not build against bytes - // that are not what the index — and the review behind it — approved. + // Corrupt the store bytes after publication: provisioning re-hashes everything + // it stages and must refuse, not build against bytes the index never approved. let (env, _plain, _client) = env_with_two_fixtures("plain-make", "dep-client"); let c = approve_fixture(&env, "plain-make"); assert!(matches!(run_for(&env, &c), pipeline::Outcome::Succeeded { .. })); @@ -152,9 +145,8 @@ fn a_tampered_store_artifact_fails_the_lease_closed() { other => panic!("{other:?}"), } - // Restore the bytes and resume: the lease verifies, the sandbox's own - // `pacman -Q` confirms the pinned world landed, and the build completes — - // which is the happy provisioning path proven end to end as well. + // Restore the bytes and resume: the lease verifies, the sandbox's `pacman -Q` + // confirms the pinned world landed, and the build completes. std::fs::write(&path, &original).unwrap(); assert!( matches!(pipeline::run(&env.cfg, &env.db, &id2).unwrap(), pipeline::Outcome::Succeeded { .. }), @@ -281,9 +273,8 @@ fn i4_kill_mid_publish_leaves_the_old_index_intact() { let out = run_for(&env, &c2); assert!(matches!(out, pipeline::Outcome::Failed { .. }), "{out:?}"); - // The served database is byte-for-byte the old one, and the DB never - // recorded the new release: consumers saw either the old world or the new - // one, never a half-written index (I4). + // The served database is byte-for-byte the old one, and the DB never recorded + // the new release: consumers saw either the old world or the new one (I4). assert_eq!(std::fs::read(&v1).unwrap(), before); assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]); assert_eq!( @@ -310,8 +301,8 @@ fn i5_a_restarted_build_resumes_at_the_next_incomplete_step() { aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makepkg", ""); assert_eq!(builds_after_crash, 2, "one real build before the crash"); - // "Restart": same build row, no fault. Steps 0-8 are checkpointed as - // succeeded, so only publish re-runs — the expensive step is not repeated. + // "Restart": same build row, no fault. Only publish re-runs; the expensive + // steps are checkpointed. env.clear_publish_fault(); match pipeline::run(&env.cfg, &env.db, &id).unwrap() { pipeline::Outcome::Succeeded { release_id } => assert!(release_id > 0), @@ -373,8 +364,8 @@ fn a_failed_build_leaves_the_previous_version_serving() { #[test] fn an_unresolvable_dependency_blocks_instead_of_failing() { let (env, _fx) = env_with_fixture("missing-dep"); - // We subscribe to `dep-partner` but have never published it: that is exactly - // "unresolvable" in §10.4, and the answer is to wait, not to fail. + // We subscribe to `dep-partner` but have never published it: "unresolvable" in + // §10.4 means wait, not fail. env.subscribe("dep-partner"); let c = approve_fixture(&env, "missing-dep"); let out = run_for(&env, &c); @@ -397,9 +388,8 @@ fn a_blocked_build_waits_until_its_dependency_actually_arrives() { let c = approve_fixture(&env, "missing-dep"); assert!(matches!(run_for(&env, &c), pipeline::Outcome::Blocked { .. })); assert_eq!(builds::blocked_builds(&env.db).unwrap().len(), 1); - // The dispatcher sweeps blocked builds every pass. Requeueing one whose - // blocker is still missing would block again immediately — a busy loop that - // burns a claim and a plan step each tick — so it must stay put. + // The dispatcher sweeps blocked builds every pass. Requeueing one whose blocker + // is still missing would block again immediately, so it must stay put. let _ = publish::reconcile(&env.cfg, &env.db); assert_eq!(builds::requeue_blocked(&env.db).unwrap(), 0, "requeued while still blocked"); assert_eq!(builds::blocked_builds(&env.db).unwrap().len(), 1); @@ -489,9 +479,8 @@ fn publish_refuses_without_an_approval_behind_it() { let (env, _fx) = env_with_fixture("plain-make"); let c = approve_fixture(&env, "plain-make"); run_for(&env, &c); - // Approval rows are immutable (I10 / §7.2), so we build the bad state from - // the other side: a release with nothing behind it. A rebuild of it must - // still refuse to publish — the guard is on publishing, not on noticing. + // Approval rows are immutable (I10 / §7.2), so the bad state is built from the + // other side: a release with nothing behind it. let rid = db::accepted_release(&env.db, "plain-make").unwrap().unwrap().id; env.exec("UPDATE release SET approval_id=NULL WHERE id=?1", ¶ms(vec![rid])); let id = pipeline::enqueue_manual_rebuild(&env.cfg, &env.db, "plain-make").unwrap(); @@ -531,8 +520,7 @@ fn a_stale_accepted_pointer_refuses_to_publish() { #[test] fn withdrawing_a_release_twice_is_refused_the_second_time() { - // m-10: the second withdraw used to report success while rewriting nothing, - // so an operator who clicked twice got a green result and no explanation. + // m-10: the second withdraw used to report success while rewriting nothing. let (env, _fx) = env_with_fixture("plain-make"); let c = approve_fixture(&env, "plain-make"); run_for(&env, &c); @@ -549,8 +537,7 @@ fn withdrawing_a_release_twice_is_refused_the_second_time() { #[test] fn a_publish_that_does_not_land_leaves_no_orphan_files_in_the_served_tree() { // m-16: the artifacts are copied into the served tree before the DB commit, - // and when the commit refused, those bytes used to stay — files no index - // names, sitting in the directory consumers download from. + // and when the commit refused those bytes used to stay. let (mut env, _fx) = env_with_fixture("plain-make"); let c = approve_fixture(&env, "plain-make"); env.set_publish_fault("before-rename"); @@ -567,8 +554,8 @@ fn a_publish_that_does_not_land_leaves_no_orphan_files_in_the_served_tree() { .collect(); assert!(stray.is_empty(), "a publish that did not land left files behind: {stray:?}"); - // And the retry still works: the artifacts come from the collect dir, not - // from the served tree, so cleaning up costs nothing but the copy. + // And the retry still works: the artifacts come from the collect dir, not the + // served tree. env.clear_publish_fault(); assert!( matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Succeeded { .. }), diff --git a/tests/production_surface.rs b/tests/production_surface.rs index e978a2c..e4e1346 100644 --- a/tests/production_surface.rs +++ b/tests/production_surface.rs @@ -1,17 +1,3 @@ -//! The production surface cannot see the test scaffolding (§6 M-4, M-9). -//! -//! The shim harness is load-bearing: the whole step machine is tested by driving -//! the real binaries with fakes for `makepkg`, `mkarchroot`, `gpg` and friends. -//! That is fine. What is not fine is production code reaching into it — the -//! publish path once read a package's name through the shim module's copy of the -//! `.PKGINFO` parser, which meant the bytes we signed and the bytes the tests -//! believed were parsed by two pieces of code that could drift apart. -//! -//! The compile-time half of this rule is real: `shims` is compiled out unless the -//! `test-support` feature is on, and only this crate's own dev-dependency turns -//! it on. This test covers the half the compiler cannot: a module in `src/` -//! naming the scaffolding directly. - use std::path::{Path, PathBuf}; fn read(rel: &str) -> String { @@ -64,9 +50,7 @@ fn no_production_module_references_the_shim_harness() { #[test] fn the_served_index_has_exactly_one_serialization_lock() { // §6 M-5: two mutexes in `publish.rs`, each documented as *the* "one publish - // per repo" guarantee, with `withdraw_package` taking only one of them, is - // worse than either answer — a reader cannot tell whether the guarantee is - // redundant or incomplete. There is one lock now, and this keeps it that way. + // per repo" guarantee, is worse than either answer. There is one lock now. let src = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("src/pipeline/publish.rs")) .expect("read publish.rs"); let mutexes = src @@ -104,10 +88,8 @@ fn the_shim_binaries_are_test_only() { #[test] fn the_test_hooks_are_a_gated_submodule_not_config_fields() { - // §6 M-9: fault injection in the publish hot path, shim environment - // variables and clock pinning were part of the production API surface — - // `Config` advertised `publish_fault` next to `signing_key_id`, and the - // branch that reads it sat in the middle of every real publish. + // §6 M-9: fault injection in the publish hot path, shim environment variables + // and clock pinning were part of the production API surface. let cfg_src = read("src/config.rs"); for field in [ "pub path_prepend", @@ -131,8 +113,8 @@ fn the_test_hooks_are_a_gated_submodule_not_config_fields() { #[test] fn the_publish_hot_path_has_no_ungated_test_branch() { - // The two fault-injection points in `publish()` are the ones that ran on - // every real publish. Each must sit behind the feature gate. + // The two fault-injection points in `publish()` must sit behind the feature + // gate. let src = read("src/pipeline/publish.rs"); let lines: Vec<&str> = src.lines().collect(); let mut gated = 0; @@ -162,10 +144,8 @@ fn a_default_config_has_no_hooks_attached() { #[test] fn the_review_modules_do_not_keep_private_copies_of_the_rules() { - // §6 m-2: `hosts` existed twice, verbatim, and the "did the executable part - // of the recipe change" rule existed twice with *different* semantics — the - // diff panel compared function header lines, the risk scorer compared the - // bodies. One question, one answer, in the module that owns the subject. + // §6 m-2: `hosts` existed twice, verbatim, and the "did the executable part of + // the recipe change" rule existed twice with *different* semantics. for (file, forbidden) in [ ("src/review/diff.rs", ["fn hosts(", "fn body_changed("]), ("src/review/risk.rs", ["fn hosts(", "fn body_changed("]), @@ -184,7 +164,7 @@ fn the_review_modules_do_not_keep_private_copies_of_the_rules() { #[test] fn audit_rows_are_built_by_the_constructors_not_by_hand() { // §6 m-4: three review sites hand-built `AuditEntry` literals, each with its - // own `detail` shape and its own spelling of `actor_kind`. + // own `detail` shape. let src = read("src/review/approve.rs"); assert!(!src.contains("db::AuditEntry {"), "audit rows must be built by AuditEntry::human/system"); assert_eq!(src.matches("AuditEntry::human(").count(), 3, "approve, reject and withdraw"); diff --git a/tests/remote_agent.rs b/tests/remote_agent.rs index 24e259e..af4ac60 100644 --- a/tests/remote_agent.rs +++ b/tests/remote_agent.rs @@ -1,8 +1,3 @@ -//! The remote-builder path, end to end: a real build driven over the real -//! agent protocol against the §16a shims. No root, no network beyond a -//! loopback socket, no container — but the frames, the rendezvous, the log -//! streaming and the blob transfer are the production ones. - mod common; use std::io::Read; @@ -44,8 +39,7 @@ fn a_full_build_runs_over_the_agent_protocol() { .expect("spawn sandbox-agent"); let out = pipeline::run_with(&ctx).unwrap(); - // Kill *and* reap: an unreaped child is a zombie the next test inherits, and - // clippy is right that a spawn nobody waits on is unfinished business. + // Kill *and* reap: an unreaped child is a zombie the next test inherits. let _ = agent.kill(); let _ = agent.wait(); assert!(matches!(out, pipeline::Outcome::Succeeded { .. }), "{out:?}"); @@ -57,8 +51,8 @@ fn a_full_build_runs_over_the_agent_protocol() { "agent-streamed output must reach the build log:\n{log}" ); - // The build really ran as the agent's child, with the shim protocol - // applied from the Run frame's environment. + // The build really ran as the agent's child, with the shim protocol applied + // from the Run frame's environment. let shimlog = env.cfg.hooks.shim_dir.clone().unwrap(); assert_eq!(aur_build::shims::called_with(&shimlog, "makepkg", ""), 1); } @@ -98,14 +92,9 @@ fn blobs_round_trip_over_the_wire_and_a_bad_token_is_refused() { let _ = bad.wait(); } -// --------------------------------------------------------------------------- -// One listener per process. -// -// `Ctx::new` used to construct a backend for every build, and constructing a -// remote backend bound the agent listener. So a second concurrent build on a -// fixed `listen` died of EADDRINUSE — a build failing for a reason that had -// nothing to do with its package. The listener is a property of the process now. -// --------------------------------------------------------------------------- +// One listener per process. Constructing a remote backend bound the agent +// listener, so a second concurrent build on a fixed `listen` died of EADDRINUSE +// for a reason that had nothing to do with its package. fn remote_cfg(listen: &str, token: &str) -> aur_build::config::Config { aur_build::config::Config { @@ -119,7 +108,7 @@ fn remote_cfg(listen: &str, token: &str) -> aur_build::config::Config { } /// A port nothing is holding, so two backends can be asked for the *same* fixed -/// address — which is the only case where double-binding shows up. +/// address — the only case where double-binding shows up. fn free_port() -> u16 { let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let port = l.local_addr().unwrap().port(); @@ -136,19 +125,17 @@ fn two_builds_share_one_agent_listener() { let (sa, sb) = (&a.status().unwrap()[0].id, &b.status().unwrap()[0].id); assert_eq!(sa, sb, "both must report the one listener: {sa} vs {sb}"); assert!(sa.contains(&addr), "and it must be the configured address: {sa}"); - // Why the sharing matters, asserted rather than assumed: a raw second bind - // on a listening address is EADDRINUSE (Rust binds and listens together, so - // SO_REUSEADDR does not rescue it). If this ever passes, the test above is - // vacuous and the regression it guards is back. + // Why the sharing matters, asserted rather than assumed: a raw second bind on a + // listening address is EADDRINUSE. If this ever passes, the test above is + // vacuous. assert!( std::net::TcpListener::bind(&addr).is_err(), "a second bind on {addr} must fail, or nothing here proves anything" ); } -/// Sharing the listener means sharing the queue of dial-ins, which is exactly -/// the semantics `remote` already has: an agent dials in when the operator -/// boots one, and whichever build is waiting takes it. +/// Sharing the listener means sharing the queue of dial-ins: an agent dials in when +/// the operator boots one, and whichever build is waiting takes it. #[test] fn a_dial_in_goes_to_whichever_backend_is_waiting() { let addr = format!("127.0.0.1:{}", free_port()); @@ -179,9 +166,6 @@ fn a_different_token_on_the_same_address_is_refused_not_shared() { } /// The contract in its literal shape: two workers, two builds, one listener. -/// Each worker builds a `Ctx`, and building a `Ctx` used to bind the listener — -/// so the second worker's build died of EADDRINUSE before it looked at its -/// package at all. #[test] fn two_concurrent_builds_do_not_fight_over_the_listener() { let addr = format!("127.0.0.1:{}", free_port()); diff --git a/tests/schema_ownership.rs b/tests/schema_ownership.rs index dac93d6..07345dd 100644 --- a/tests/schema_ownership.rs +++ b/tests/schema_ownership.rs @@ -1,15 +1,3 @@ -//! The schema has one owner (§6 M-1). -//! -//! `db/` is a boundary, not a directory, only if SQL cannot land anywhere else. -//! Part of that is a compile-time fact: `Writer::call`, `tx` and `send` are -//! `pub(crate)`, and the raw door the test harness uses exists only under the -//! `test-support` feature. What the compiler cannot express is the other half — -//! that no module *inside* this crate writes a statement of its own. This does. -//! -//! The rule it enforces: a SQL statement, or a rusqlite statement call, appears -//! in `src/db/` and nowhere else. A module that needs the database asks `db/` -//! for a typed query; if the query does not exist, that is the change to make. - use std::path::{Path, PathBuf}; /// String literals that begin a statement. Matched on the quote so a prose @@ -73,11 +61,9 @@ fn no_sql_statements_outside_the_db_module() { } /// m-18: the version a human reads is `pkgver::full_version`'s to produce — -/// `epoch:pkgver-pkgrel`, with the epoch omitted when it is `0` or empty. That -/// rule used to exist twice, once in Rust and once as a `CASE WHEN epoch='0'` -/// inside `approved_but_unbuilt`, where a change to one would silently make the -/// Attention page disagree with every other page about what a version looks -/// like. SQL selects the parts; Rust formats them. +/// `epoch:pkgver-pkgrel`, with the epoch omitted when it is `0` or empty. That rule +/// used to exist twice, once in Rust and once in SQL. SQL selects the parts; Rust +/// formats them. #[test] fn only_rust_formats_a_version() { let root = Path::new(env!("CARGO_MANIFEST_DIR")); diff --git a/tests/shims.rs b/tests/shims.rs index d512bd7..d06a81e 100644 --- a/tests/shims.rs +++ b/tests/shims.rs @@ -1,7 +1,3 @@ -//! The §16a test harness itself: toolchain shims and the fake-package corpus. -//! -//! If these tests fail, nothing above the harness can be trusted. - mod common; use std::path::{Path, PathBuf}; @@ -62,9 +58,7 @@ fn makechrootpkg_emits_pkginfo_buildinfo_and_sig() { let pkg = build.join("plain-make-1.0-1-x86_64.pkg.tar.zst"); assert!(pkg.exists(), "artifact left in the build dir like the real tool does"); let bytes = std::fs::read(&pkg).unwrap(); - // Read the artifact with the production parser, not a shim-only one: the - // harness is only a faithful stand-in if it reads a package the way the - // pipeline will (§6 M-4). + // Read the artifact with the production parser, not a shim-only one (§6 M-4). let pkginfo = aur_build::pkginfo::pkginfo_text(&bytes).unwrap(); assert!(pkginfo.contains("pkgname = plain-make")); assert!(pkginfo.contains("pkgver = 1.0-1")); @@ -86,8 +80,8 @@ fn makechrootpkg_emits_pkginfo_buildinfo_and_sig() { #[test] fn makechrootpkg_refuses_a_missing_pkgbuild() { - // Step 0 materializes from the mirror; if that silently produced nothing, - // the fake tool must notice rather than build an empty package. + // Step 0 materializes from the mirror; if that silently produced nothing, the + // fake tool must notice rather than build an empty package. let tmp = tempfile::tempdir().unwrap(); let build = tmp.path().join("build"); std::fs::create_dir_all(&build).unwrap(); @@ -176,9 +170,8 @@ fn repo_add_writes_a_pacman_database() { #[test] fn pacman_u_verifies_digests_and_q_reports_the_world() { - // The provisioning step's fail-closed world check runs against this fake: - // `-U` must refuse bytes that do not hash to the digest their name claims, - // and `-Q` must report exactly what landed. + // The provisioning step's fail-closed world check runs against this fake: `-U` + // must refuse bytes that do not hash to the digest their name claims. let tmp = tempfile::tempdir().unwrap(); let log = tmp.path().join("shimlog"); std::fs::create_dir_all(&log).unwrap(); @@ -208,8 +201,8 @@ fn pacman_u_verifies_digests_and_q_reports_the_world() { assert_eq!(code, 0); assert!(out.contains("plain-make 1.0-1"), "the world check reads -Q: {out}"); - // A blob whose bytes do not match the digest its name claims is refused - // like a bad signature: name it with some other digest's hex. + // A blob whose bytes do not match the digest its name claims is refused like a + // bad signature. let bad = tmp.path().join(aur_build::hash::hex(b"some other artifact")); std::fs::write(&bad, b"tampered").unwrap(); let (code, _, err) = shim( @@ -251,8 +244,8 @@ fn mkarchroot_creates_a_warm_root() { assert!(root.join("SHIM-ROOT").exists()); } -/// Every fixture in the corpus must be drivable through the shims. This is the -/// executable documentation of the §16 edge cases. +/// Every fixture in the corpus must be drivable through the shims: the executable +/// documentation of the §16 edge cases. #[test] fn every_fixture_is_drivable_through_the_shims() { let mut names = Vec::new(); @@ -359,16 +352,10 @@ fn shim_environment_reaches_child_processes_through_the_config() { assert!(s.contains("manifest.json"), "{s}"); } -// --------------------------------------------------------------------------- -// repo-add's database filename. -// -// The shim used to write the database wherever it was told to, and the pipeline -// took that literally: it rendered the index to `<db>.tar.gz.tmp` and renamed it -// into place. Real repo-add rejects that filename as a usage error, so every -// publish test in this suite passed while the first real package anyone tried to -// publish died at the last step. A shim must be as strict as the tool it stands -// in for, or it is not a test of the tool. -// --------------------------------------------------------------------------- +// repo-add's database filename. A shim must be as strict as the tool it stands in +// for: the pipeline used to render the index to `<db>.tar.gz.tmp`, real repo-add +// rejects that as a usage error, and every publish test passed while the first +// real package died at the last step. /// Names pacman's repo-add accepts as its database argument, measured against /// `repo-add (pacman) 7.1.0` rather than guessed from its docs. @@ -407,8 +394,7 @@ fn repo_add_shim_refuses_a_database_name_repo_add_refuses() { } /// The oracle, when the host has one: the shim's verdict must be the real tool's -/// verdict, name for name. Gated and noted rather than skipped silently, in the -/// shape of `versions::vercmp_matches_the_system_oracle`. +/// verdict, name for name. #[test] fn repo_add_db_names_match_the_real_repo_add() { if Command::new("repo-add").arg("--version").output().is_err() { @@ -431,8 +417,7 @@ fn repo_add_db_names_match_the_real_repo_add() { } /// The regression itself, asserted on the pipeline rather than on the shim: what -/// filename does publish actually hand repo-add, and does it clean up after -/// itself while doing it? +/// filename does publish actually hand repo-add? #[test] fn publish_hands_repo_add_a_database_name_the_real_tool_accepts() { let web = Web::new("plain-make"); @@ -458,9 +443,8 @@ fn publish_hands_repo_add_a_database_name_the_real_tool_accepts() { "publish passed {db}, which repo-add would refuse" ); - // The render happens in a scratch directory beside the live database, under - // the name a consumer will download, and is gone once the rename lands. A - // leftover would mean a publish that died on a path that never cleaned up. + // The render happens in a scratch directory beside the live database, under the + // name a consumer will download, and is gone once the rename lands. let arch = web.env.cfg.repo_arch_dir(); let leftovers: Vec<String> = std::fs::read_dir(&arch) .unwrap() diff --git a/tests/staleness.rs b/tests/staleness.rs index bebceb4..cadfc69 100644 --- a/tests/staleness.rs +++ b/tests/staleness.rs @@ -1,11 +1,3 @@ -//! Staleness, blocked builds and the dependents question (§10). -//! -//! The design's position is that staleness is a fact to be shown, not a state to -//! be stored: there is no automatic rebuild engine, and no `stale` column, because -//! a stored flag goes wrong the moment anything else is published and something -//! else always is. These tests pin that down — including the part that is easy to -//! fake, which is that the derivation is real and not a cached answer. - mod common; use aur_build::db::{builds, model::*}; @@ -46,8 +38,7 @@ fn staleness_is_derived_on_read_and_nothing_stores_it() { assert_eq!(stale[0].built_with, "1.0-1"); assert_eq!(stale[0].now, "2.0-1"); - // "Derived purely on read" has to mean there is nowhere for a stale answer to - // hide. No column on any table stores it. + // "Derived purely on read" means there is nowhere for a stale answer to hide. let cols: Vec<String> = env .db .read(|c| { @@ -62,7 +53,7 @@ fn staleness_is_derived_on_read_and_nothing_stores_it() { assert!(cols.is_empty(), "staleness must not be persisted anywhere: {cols:?}"); // The answer tracks the index, not any stored flag: withdrawing plain-make - // changes what is true about dep-client without touching dep-client at all. + // changes what is true about dep-client without touching it. pipeline::publish::withdraw_package(&env.cfg, &env.db, "plain-make").unwrap(); let after = staleness::stale_rows(&env.db).unwrap(); assert!( @@ -82,7 +73,7 @@ fn staleness_is_derived_on_read_and_nothing_stores_it() { fn a_missing_dependency_blocks_the_build_and_names_the_blocker_everywhere() { let (env, fx, _partner) = env_with_two_fixtures("missing-dep", "dep-partner"); // dep-partner is a package we intend to publish but have not yet: the build - // cannot run, and that is a fact to report rather than a failure to retry. + // cannot run, and that is a fact to report (§10.4). let c = approved(&env, "missing-dep"); assert_eq!(c.missing_deps(), vec!["dep-partner".to_string()], "the review must warn before approving"); let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); @@ -118,16 +109,14 @@ fn a_blocked_build_waits_and_is_requeued_only_when_the_blocker_arrives() { assert_eq!(builds::requeue_blocked(&env.db).unwrap(), 0, "requeued while still blocked"); assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::BlockedMissingDep); - // Publishing dep-partner is what unblocks it. A build that was blocked and - // can now run is not a new decision — a human already approved it (§10). + // Publishing dep-partner is what unblocks it: a human already approved it. publish(&env, "dep-partner"); assert!( aur_build::db::our_package_names(&env.db).unwrap().contains("dep-partner"), "dep-partner should be in the index now: {:?}", aur_build::db::our_package_names(&env.db) ); - // Publishing the blocker requeues what was waiting on it — the publish path - // sweeps blocked builds itself, so an explicit call afterwards is a no-op. + // Publishing the blocker requeues what was waiting on it. assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Queued, "the blocker arrived and the build stayed blocked"); assert_eq!(builds::requeue_blocked(&env.db).unwrap(), 0, "nothing left to requeue"); @@ -152,8 +141,7 @@ fn the_review_page_warns_about_missing_deps_before_approval() { #[test] fn the_review_page_answers_what_approving_this_would_disturb() { - // §10.3: "approving this marks N packages stale". A reviewer approving a - // plain-make bump needs to know that dep-client is about to need a rebuild. + // §10.3: "approving this marks N packages stale". let (env, plain, _client) = env_with_two_fixtures("plain-make", "dep-client"); publish(&env, "plain-make"); publish(&env, "dep-client"); @@ -182,8 +170,8 @@ fn a_dependency_we_stopped_publishing_shows_as_missing_not_outdated() { let (env, _plain, client) = env_with_two_fixtures("plain-make", "dep-client"); publish(&env, "plain-make"); publish(&env, "dep-client"); - // Withdraw plain-make from the index: dep-client was built against it and now - // depends on something we no longer serve. + // Withdraw plain-make from the index: dep-client now depends on something we + // no longer serve. pipeline::publish::withdraw_package(&env.cfg, &env.db, "plain-make").unwrap(); let stale = staleness::stale_rows(&env.db).unwrap(); diff --git a/tests/state_machine.rs b/tests/state_machine.rs index 1c05fff..a8d9b35 100644 --- a/tests/state_machine.rs +++ b/tests/state_machine.rs @@ -1,9 +1,3 @@ -//! The build state machine (§6 M-8). -//! -//! Before this was an enum, `set_state(&str)` wrote any string a caller -//! invented and the machine lived only in `WHERE state IN (...)` clauses. These -//! tests are the ones that would have failed then. - mod common; use aur_build::db::{builds, model::{BuildState, CandidateState, StepState}}; @@ -38,8 +32,7 @@ fn the_machine_refuses_a_transition_it_does_not_define() { let id = build(&env, "b1"); assert_eq!(state(&env, "b1"), BuildState::Queued); - // Queued → Succeeded: a build cannot finish without running. Before the - // enum this wrote happily and produced a succeeded build that never built. + // Queued → Succeeded: a build cannot finish without running. let err = builds::set_state(&env.db, &id, BuildState::Succeeded, None).unwrap_err(); assert!(err.to_string().contains("illegal build transition"), "{err}"); assert_eq!(state(&env, "b1"), BuildState::Queued, "a refused transition writes nothing"); @@ -73,9 +66,9 @@ fn a_terminal_build_is_history_and_does_not_move() { #[test] fn a_zombie_worker_cannot_finish_a_build_it_no_longer_owns() { // The failure this pins: a worker's lease expires mid-step, the reaper hands - // the build back to the queue, and the original worker — still running — - // comes back and writes `succeeded` over whatever the new owner did. The - // compare-and-swap in `set_state` is what makes that an error. + // the build back, and the original worker comes back and writes `succeeded` + // over whatever the new owner did. The compare-and-swap in `set_state` makes + // that an error. let env = Env::new(); let id = build(&env, "b1"); builds::claim(&env.db, "worker-1", &id, 90).unwrap(); @@ -92,25 +85,23 @@ fn a_zombie_worker_cannot_finish_a_build_it_no_longer_owns() { #[test] fn a_state_the_code_does_not_know_is_an_error_not_an_empty_string() { - // A row written by an older binary, a hand-edit, or a future migration the - // code has not caught up with must stop the process, not render as a build - // in no state at all. + // A row written by an older binary, a hand-edit, or a future migration must + // stop the process, not render as a build in no state at all. let env = Env::new(); let id = build(&env, "b1"); env.exec("UPDATE build SET state='exploded' WHERE id=?1", &[common::P::S(id.clone())]); let err = builds::get(&env.db, &id).unwrap_err(); assert!(err.to_string().contains("outside the state machine"), "{err}"); // The package page lists a pkgbase's builds with no state filter: an - // unreadable row must fail the query, not vanish from the list. + // unreadable row must fail the query, not vanish. let pb = env.query_i64("SELECT id FROM pkgbase WHERE name='x'", &[]).unwrap(); assert!(aur_build::db::builds_for_pkgbase(&env.db, pb, 10).is_err()); } #[test] fn the_transition_table_is_the_machine_the_code_actually_uses() { - // Every state may be re-written with its own name — that is a no-op, not a - // move (the step loop re-asserts Running at each boundary). What matters is - // what else is reachable, and this table is the whole machine. + // Every state may be re-written with its own name — a no-op, not a move. What + // matters is what else is reachable, and this table is the whole machine. let reachable = |from: BuildState| -> Vec<&'static str> { BuildState::ALL .iter() @@ -131,16 +122,14 @@ fn the_transition_table_is_the_machine_the_code_actually_uses() { // A failed build is resumed on its own row (I5) or requeued by a human (§8.4). assert_eq!(reachable(BuildState::Failed), ["queued", "running", "failed"]); assert_eq!(reachable(BuildState::Cancelled), ["queued", "cancelled"]); - // A published build is history. Nothing revives it; a new version is a new - // build id (§8.1), not a resurrection. + // A published build is history: a new version is a new build id (§8.1). assert_eq!(reachable(BuildState::Succeeded), ["succeeded"]); } #[test] fn requeueing_a_succeeded_build_is_refused_not_silently_requeued() { - // `builds::retry` resets the failed steps and moves the row back to the - // queue. On a build that already published there is nothing to retry, and - // the old unconditional UPDATE happily requeued it anyway. + // `builds::retry` resets the failed steps and moves the row back to the queue. + // On a build that already published there is nothing to retry. let env = Env::new(); let id = build(&env, "b1"); builds::claim(&env.db, "worker-1", &id, 90).unwrap(); @@ -154,7 +143,7 @@ fn requeueing_a_succeeded_build_is_refused_not_silently_requeued() { #[test] fn a_failed_build_is_resumed_on_its_own_row() { // I5: the resume happens on the same row, because the step checkpoints say - // where to continue. The machine has to know that, or the resume is a bug. + // where to continue. let env = Env::new(); let id = build(&env, "b1"); builds::claim(&env.db, "worker-1", &id, 90).unwrap(); @@ -171,8 +160,8 @@ fn a_failed_build_is_resumed_on_its_own_row() { // ---------------------------------------------------------- the other machines -- -/// A candidate row in `state`, inserted directly: these tests are about the -/// state column, not about how a candidate is discovered. +/// A candidate row in `state`, inserted directly: these tests are about the state +/// column, not about how a candidate is discovered. fn candidate(env: &Env, state: &str) -> i64 { env.exec( "INSERT OR IGNORE INTO pkgbase (name, aur_url, created_at) VALUES ('x', 'u', '2026-01-01T00:00:00Z')", @@ -210,8 +199,7 @@ fn a_decided_review_is_never_re_decided() { assert!(err.to_string().contains("illegal candidate transition approved"), "{err}"); assert_eq!(candidate_state(&env, id), CandidateState::Approved); - // Superseding a decided review is the one move it makes (§7.1), and a - // superseded review is history. + // Superseding a decided review is the one move it makes (§7.1). resolve(&env, id, CandidateState::Superseded).unwrap(); assert_eq!(candidate_state(&env, id), CandidateState::Superseded); assert!(resolve(&env, id, CandidateState::Approved).is_err()); @@ -229,8 +217,7 @@ fn only_an_open_review_can_be_approved() { #[test] fn a_completed_step_checkpoint_is_frozen() { - // I5: a resumed build reads these rows to decide what not to redo. A - // checkpoint that can be rewritten is not a checkpoint. + // I5: a resumed build reads these rows to decide what not to redo. let env = Env::new(); let id = build(&env, "b1"); builds::begin_step(&env.db, &id, "build", 1).unwrap(); @@ -261,8 +248,8 @@ fn an_interrupted_step_resumes_and_a_blocked_step_waits() { #[test] fn an_unnamed_state_in_any_row_is_an_error() { - // Every state column is parsed through `db::state_col`, so a value the code - // does not know stops the read instead of rendering as some other state. + // Every state column is parsed through `db::state_col`, so an unknown value + // stops the read instead of rendering as some other state. let env = Env::new(); let cid = candidate(&env, "approved"); env.exec( diff --git a/tests/surfaces.rs b/tests/surfaces.rs index b13cc9d..1df9f40 100644 --- a/tests/surfaces.rs +++ b/tests/surfaces.rs @@ -1,8 +1,3 @@ -//! The §13 surfaces driven by live state, not fixtures of HTML: Attention must -//! name outdated dependencies, downgrades and blocked builds; the package page -//! must answer "what does this depend on and what depends on it"; and a manual -//! rebuild must reuse the approved source identity without asking again (I6). - mod common; use aur_build::db::{self, builds, model::*}; diff --git a/tests/time.rs b/tests/time.rs index 281d78a..6ab0665 100644 --- a/tests/time.rs +++ b/tests/time.rs @@ -1,5 +1,3 @@ -//! The clock helpers (§16) and the pinned clock the lease tests depend on (§6 m-1). - mod common; use aur_build::db::{builds, BuildState}; @@ -8,10 +6,9 @@ use common::Env; #[test] fn a_pinned_clock_moves_relative_arithmetic_with_it() { - // The finding: `now()` honored the pinned clock but `secs_ago` and - // `secs_ahead` read the wall clock, so a pinned test computed real-clock - // lease expiries and deadlines while comparing them against the pinned - // "now" — the two never met, and the test proved nothing about expiry. + // The finding: `now()` honored the pinned clock but `secs_ago` and `secs_ahead` + // read the wall clock, so a pinned test computed real-clock expiries while + // comparing them against the pinned "now". time::pin("2026-01-01T00:00:00Z"); assert_eq!(time::now(), "2026-01-01T00:00:00Z"); assert_eq!(time::secs_ahead(90), "2026-01-01T00:01:30Z"); diff --git a/tests/vcs.rs b/tests/vcs.rs index b1edd51..62efe5f 100644 --- a/tests/vcs.rs +++ b/tests/vcs.rs @@ -1,10 +1,3 @@ -//! Stage A / Stage B: the VCS watcher (§5.2). -//! -//! The whole point of the two-stage funnel is that the expensive thing (clone + -//! run `pkgver()`) happens only when the cheap thing (`git ls-remote`) says -//! something moved. These tests assert both halves: that the answer is right, -//! and that it was paid for only once. - mod common; use aur_build::db::{self, model::*}; @@ -30,8 +23,7 @@ fn makepkg_calls(env: &Env) -> usize { #[test] fn stage_a_probes_every_vcs_source_not_just_the_first() { let (env, fx) = env_with_fixture("git-multi"); - // Two upstream repos, two pins — a pkgbase that builds from more than one - // upstream can have either one move alone (§5.2). + // Two upstream repos, two pins: either one can move alone (§5.2). let (outcome, c) = detect_and_take(&env, "git-multi"); assert!(matches!(outcome, detect::Outcome::Candidate { .. }), "{outcome:?}"); let c = c.unwrap(); @@ -74,8 +66,8 @@ fn stage_a_short_circuits_before_stage_b_when_nothing_moved() { let id = aur_build::pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); aur_build::pipeline::run(&env.cfg, &env.db, &id).unwrap(); - // Now poll again with nothing changed. Stage A finds the same tip set, so - // Stage B must not run at all — this is the common case, every day. + // Now poll again with nothing changed. Stage A finds the same tip set, so Stage + // B must not run at all — the common case, every day. let before = makepkg_calls(&env); let cache_before = stage_b_rows(&env); let r = detect::check_pkgbase(&env.cfg, &env.db, "git-sourced").unwrap(); @@ -93,12 +85,12 @@ fn stage_b_resolves_pkgver_and_captures_the_pins() { // The candidate's version is what `pkgver()` computed, not the frozen field. assert_eq!(c.pkgver, "r1.0"); assert_eq!(c.pkgrel, "1"); - // And the pins it will be built from are recorded now, while the clone is - // already there — not later, which would mean cloning again. + // The pins it will be built from are recorded now, while the clone is already + // there. let pins: Vec<UpstreamPin> = serde_json::from_str(&c.upstream_pins_json).unwrap(); assert_eq!(pins[0].commit, head); - // The pins are part of the identity: a different commit is a different - // thing to approve, even under the same version string. + // The pins are part of the identity: a different commit is a different thing to + // approve. let with_pins = Identity { aur_commit: "x".into(), epoch: "0".into(), @@ -124,9 +116,8 @@ fn stage_b_is_cached_on_pkgbase_recipe_and_tip() { assert_eq!(makepkg_calls(&env), calls, "cache miss on an unchanged key"); assert_eq!(stage_b_rows(&env), 1); - // A new tip is a new key, so it resolves again — but the cooldown window - // holds it back, which is what keeps a chatty upstream from turning - // detection into a build loop. + // A new tip is a new key, so it resolves again — but the cooldown window holds + // it back. fx.upstream_commit("upstream: new tip\n"); detect::check_pkgbase(&env.cfg, &env.db, "git-sourced").unwrap(); assert_eq!(stage_b_rows(&env), 1, "cooldown should suppress the re-resolve"); @@ -139,9 +130,8 @@ fn stage_b_is_cached_on_pkgbase_recipe_and_tip() { #[test] fn stage_b_concurrency_cap_is_enforced() { - // The cap is a process-wide guard; with the default of 1 a second caller - // waits for the first. Two threads, one slot: the second must not enter - // until the first releases. + // The cap is a process-wide guard; with the default of 1 a second caller waits + // for the first. let (env, _fx) = env_with_fixture("git-sourced"); let slots = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); let s1 = slots.clone(); @@ -164,9 +154,8 @@ fn stage_b_concurrency_cap_is_enforced() { #[test] fn an_unprobeable_source_forces_stage_b_instead_of_claiming_no_change() { - // svn/hg have no cheap universal probe. The honest answer is "we do not - // know", which means Stage B runs; claiming "nothing moved" would be a lie - // that silently stops detection. + // svn/hg have no cheap universal probe. The honest answer is "we do not know", + // which means Stage B runs. let recipe = aur_build::recipe::parse_pkgbuild( &std::fs::read_to_string(corpus_root().join("git-sourced/PKGBUILD")).unwrap(), ) @@ -189,8 +178,8 @@ fn an_unprobeable_source_forces_stage_b_instead_of_claiming_no_change() { #[test] fn a_moved_tip_with_an_unchanged_pkgver_is_a_notice_not_a_candidate() { - // §5.2: pins moved, version frozen — pacman cannot offer an upgrade, so - // there is nothing to approve. It becomes a notice, and is never dropped. + // §5.2: pins moved, version frozen — pacman cannot offer an upgrade, so it + // becomes a notice and is never dropped. let (env, fx) = env_with_fixture("pin-drift"); let (_outcome, c) = detect_and_take(&env, "pin-drift"); let c = c.unwrap(); @@ -199,8 +188,8 @@ fn a_moved_tip_with_an_unchanged_pkgver_is_a_notice_not_a_candidate() { let id = aur_build::pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); aur_build::pipeline::run(&env.cfg, &env.db, &id).unwrap(); - // Upstream moves. The shim still reports the same pkgver (that is what a - // degenerate `pkgver()` does), so nothing is publishable. + // Upstream moves. The shim still reports the same pkgver, as a degenerate + // `pkgver()` does, so nothing is publishable. fx.upstream_commit("upstream: 14 more commits\n"); env.exec("UPDATE stage_b_cache SET resolved_at='2000-01-01T00:00:00Z'", &[]); let (outcome, new_candidate) = detect_and_take(&env, "pin-drift"); diff --git a/tests/versions.rs b/tests/versions.rs index 04866d0..ae6e877 100644 --- a/tests/versions.rs +++ b/tests/versions.rs @@ -1,15 +1,3 @@ -//! `vercmp` and the dependency-string grammar (§4, §6). -//! -//! Version comparison is the one place where a subtle bug is invisible until it -//! publishes the wrong thing: a downgrade that reads as an upgrade gets served to -//! every consumer, and an epoch bump that reads as a downgrade gets refused. So -//! this is a table, not a story — the vectors are the ones pacman's own test -//! suite uses, plus the shapes that only appear in AUR recipes (epoch on one side -//! only, `pkgrel` reset to 1 under a new `pkgver`, alpha/numeric boundaries like -//! `1.0a` vs `1.0.1`). -//! -//! The hand-written implementation is deliberate (§14): no libalpm, no FFI. - mod common; use std::cmp::Ordering; @@ -20,13 +8,9 @@ use aur_build::pkgver::{self, Dep, DepOp}; use aur_build::review::{candidates, diff}; use common::*; -/// Ordering pairs, each `a` strictly older than `b`. -/// -/// These are not hand-derived: every pair was checked against pacman's own -/// `vercmp` on this machine, because the interesting cases (alpha suffixes, -/// alpha-vs-numeric at the same position, a shorter version beating a longer one) -/// are exactly the ones that are easy to misremember. `vercmp_matches_the_system_oracle` -/// below re-checks them whenever the binary is present. +/// Ordering pairs, each `a` strictly older than `b`. Every pair was checked +/// against pacman's own `vercmp`, because the interesting cases are exactly the +/// ones that are easy to misremember. const ORDERED: &[(&str, &str)] = &[ ("v1.2.3", "v1.2.4"), ("1.0", "1.1"), @@ -94,10 +78,8 @@ fn vercmp_orders_the_canonical_vectors() { } /// The strongest version of this test: compare the hand-written implementation -/// against pacman's own `vercmp` over a cross-product of the shapes that appear -/// in real recipes. It is skipped with a note when the binary is absent, so the -/// suite still runs on a machine without pacman — but on a real host this is the -/// test that would catch a chunking bug a hand-typed table would miss. +/// against pacman's own `vercmp` over a cross-product of the shapes that appear in +/// real recipes. Skipped with a note when the binary is absent. #[test] fn vercmp_matches_the_system_oracle() { if std::process::Command::new("vercmp").arg("1").arg("2").output().is_err() { @@ -105,8 +87,7 @@ fn vercmp_matches_the_system_oracle() { return; } // No `-` here: pacman's `vercmp` binary compares two raw version strings and - // does not split an epoch/pkgrel triple out of them, so the EVR-aware - // `vercmp` is not the right side of this comparison. `vercmp_string` is. + // does not split an epoch/pkgrel triple, so `vercmp_string` is the right side. let fragments = [ "1", "1.0", "1.0.0", "1.0.1", "1.1", "2", "2.0", "1.0a", "1.0rc1", "1.0.2a", "1.0.2.1", "1.0.2.a", "1.0.2.aa", "1.0.2.b", "1.0.2z", "1.0z", "1.0.z", "0.9", "10", "2.24", "2.5", @@ -170,13 +151,11 @@ fn a_pkgrel_reset_under_a_newer_pkgver_is_still_an_upgrade() { #[test] fn alpha_numeric_boundaries_follow_the_chunk_rule() { - // A numeric chunk is always NEWER than an alphabetic one at the same - // position — the rule that reads backwards and that this project got wrong - // until it was checked against pacman's own binary. + // A numeric chunk is always newer than an alphabetic one at the same position. assert_eq!(pkgver::vercmp("1.0.1", "1.0.a"), Ordering::Greater); assert_eq!(pkgver::vercmp("1.0.a", "1.0.1"), Ordering::Less); - // A shorter version is newer when the extra chunk is numeric, older when it - // is alphabetic — the part everyone gets wrong. + // A shorter version is newer when the extra chunk is numeric, older when it is + // alphabetic. assert_eq!(pkgver::vercmp("1.0", "1.0.1"), Ordering::Less); assert_eq!(pkgver::vercmp("1.0", "1.0a"), Ordering::Greater); assert_eq!(pkgver::vercmp("1.0rc1", "1.0"), Ordering::Less); @@ -203,8 +182,7 @@ fn dependency_strings_parse_with_their_constraints() { assert_eq!(d.op, op, "{src:?} operator"); assert_eq!(d.version.as_deref(), ver, "{src:?} version"); } - // Malformed input is dropped, not fatal: one odd optdepends line must not - // break detection for the whole recipe. + // Malformed input is dropped, not fatal. assert!(Dep::parse("").is_none()); assert!(Dep::parse(">=1.0").is_none()); assert_eq!(pkgver::dep_names(&["python>=3.11".into(), "gcc".into()]), vec!["python", "gcc"]); @@ -227,8 +205,7 @@ fn version_constraints_are_satisfied_by_the_right_versions() { #[test] fn provides_and_conflicts_use_the_same_grammar() { - // provides/conflicts entries carry versions with the same syntax; the - // dependency delta panel compares them by name. + // provides/conflicts entries carry versions with the same syntax. for src in ["aur-build", "aur-build=0.1-1", "virtual-thing>=1.0"] { let d = Dep::parse(src).expect(src); assert!(!d.name().is_empty()); @@ -243,7 +220,7 @@ fn provides_and_conflicts_use_the_same_grammar() { #[test] fn a_downgrade_in_the_aur_is_flagged_not_silently_served() { // A maintainer reverting a version is a mistake far more often than a - // deliberate rollback, and a naive string compare would not notice at all. + // deliberate rollback. let (env, fx) = env_with_fixture("plain-make"); publish(&env, "plain-make"); fx.bump(&[("pkgver", "0.9")]); @@ -258,15 +235,13 @@ fn a_downgrade_in_the_aur_is_flagged_not_silently_served() { ); assert!(version.body.contains("1.0-1 -> 0.9-1"), "{:?}", version.body); assert!(pkgver::is_downgrade("1.0-1", "0.9-1")); - // A downgrade is a decision, not an automatic rebuild: it is shown, and the - // index keeps serving the higher version until a human says otherwise. + // A downgrade is a decision, not an automatic rebuild. assert_eq!(aur_build::db::index_version(&env.db, "plain-make").unwrap().unwrap(), "1.0-1"); } #[test] fn an_epoch_bump_is_an_upgrade_even_though_the_version_went_down() { - // The classic "reset the version, add an epoch" move. String comparison - // calls 0.9 older than 1.0 and would refuse it; vercmp must not. + // The classic "reset the version, add an epoch" move. let (env, fx) = env_with_fixture("epoch-bump"); publish(&env, "epoch-bump"); append_line(&fx, "epoch=1"); @@ -301,7 +276,7 @@ fn full_version_round_trips_through_split() { // --- helpers ------------------------------------------------------------- /// Detect, render the diff, approve and build, so the next candidate has a real -/// accepted release behind it (§2 I1: nothing is published without approval). +/// accepted release behind it (I1). fn publish(env: &Env, name: &str) { let c = detect_raw(env, name); let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap(); @@ -336,9 +311,8 @@ fn panel<'a>(panels: &'a [diff::Panel], name: &str) -> &'a diff::Panel { } /// Add a top-level declaration the fixture did not ship with (an `epoch=` line) -/// and commit it, so detection sees a recipe that genuinely gained an epoch. -/// It has to go with the other top-level assignments: after a `package_*()` -/// function it would be inside the function body and mean nothing. +/// and commit it. It has to go with the other top-level assignments: after a +/// `package_*()` function it would be inside the function body and mean nothing. fn append_line(fx: &Fixture, line: &str) { let path = fx.aur.join("PKGBUILD"); let text = std::fs::read_to_string(&path).unwrap(); diff --git a/tests/world.rs b/tests/world.rs index 8229d62..3a7dd54 100644 --- a/tests/world.rs +++ b/tests/world.rs @@ -1,14 +1,3 @@ -//! `.PKGINFO` / `.BUILDINFO` parsing and the world snapshot (§10.1, I12). -//! -//! The world snapshot is the whole basis of staleness: "would rebuilding this -//! change what a consumer gets?" only means something if we recorded, at build -//! time, the exact set of our packages the build saw. Two properties matter and -//! are tested here — that the record comes from the archive rather than from -//! anything the build asserted about itself, and that it is intersected with our -//! own index **at ingest time**, because an unfiltered `.BUILDINFO` would make -//! every package permanently stale (Arch never stops moving) and the Attention -//! page would be noise forever. - mod common; use aur_build::db; @@ -17,8 +6,7 @@ use aur_build::pkginfo; use common::*; /// Build a real `.pkg.tar.zst`: zstd-compressed tar with the two metadata files -/// inside, exactly as makepkg lays them out. `None` for either means the file is -/// absent from the archive. +/// inside, as makepkg lays them out. `None` means the file is absent. fn make_archive(dir: &std::path::Path, name: &str, pkginfo: Option<&str>, buildinfo: Option<&str>) -> std::path::PathBuf { let path = dir.join(format!("{name}.pkg.tar.zst")); let enc = std::io::BufWriter::new(std::fs::File::create(&path).unwrap()); @@ -132,15 +120,13 @@ fn the_world_snapshot_is_intersected_with_our_index_at_ingest_time() { // §10.1 / I12. The fixture's build root contains glibc, pacman, binutils and // plain-make; only plain-make is ours, and only plain-make may be recorded. let (env, fx) = env_with_fixture("plain-make"); - // The first build has no world of ours to record — nothing we publish exists - // yet. That is the honest answer, not an empty lie about glibc. + // The first build has no world of ours to record — the honest answer, not an + // empty lie about glibc. publish(&env, "plain-make"); let first = world_of_last_build(&env); assert!(first.is_empty(), "nothing of ours existed for the first build: {first:?}"); - // Now plain-make is in the index, so a later build records it and nothing - // else. A real chroot with our repo enabled has the previous version of the - // package installed; the manifest says the same. + // Now plain-make is in the index, so a later build records it and nothing else. let mut manifest = fx.manifest_json(); manifest["installed"] = serde_json::json!([ { "name": "glibc", "version": "2.39-1", "arch": "x86_64" }, @@ -169,8 +155,7 @@ fn the_world_snapshot_is_intersected_with_our_index_at_ingest_time() { #[test] fn a_split_pkgbase_is_one_approval_and_many_index_rows() { - // §3: one recipe, several packages, one human decision. Every package the - // build produced gets its own index entry and its own artifact. + // §3: one recipe, several packages, one human decision. let (env, _fx) = env_with_fixture("split-pkgbase"); publish(&env, "split-pkgbase"); let rows: Vec<String> = env |
