diff options
Diffstat (limited to 'src/pipeline')
| -rw-r--r-- | src/pipeline/dispatch.rs | 39 | ||||
| -rw-r--r-- | src/pipeline/mod.rs | 49 | ||||
| -rw-r--r-- | src/pipeline/publish.rs | 138 | ||||
| -rw-r--r-- | src/pipeline/steps.rs | 93 |
4 files changed, 98 insertions, 221 deletions
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 { |
