From 153e72cc797c1e45a60f4896d00163fb4bdf3056 Mon Sep 17 00:00:00 2001 From: aur-build Date: Thu, 19 Nov 2026 14:15:16 +0000 Subject: publish: repo-add decides the database filename MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Publishing renders the index before the DB commits and renames it into place after, so a crash between the two leaves the old index serving (I4). The way that was written did it at `.tar.gz.tmp` beside the live file — a filename real repo-add refuses, because its database argument has to be a name pacman would accept. Every publish test passed; the first real package anyone tried to publish died at the last step with the release already committed. `render_db` now renders into a scratch directory under the served directory, under the name a consumer will download. Same filesystem, so the rename is still the atomic swap, and the live database is never the file repo-add is writing into. `publish`, `reconcile` and `withdraw_package` all had the bug and all share the helper now; `reconcile` sweeps scratch directories a crash left behind. `run_repo_add` drops `-s` too: repo-add would sign into scratch space that is about to be deleted, and `publish::sign` already signs the renamed file. The reason 238 tests missed this is that the shim would write the database anywhere it was told. It now enforces the accepted set — measured against `repo-add (pacman) 7.1.0`, not read out of its docs — with the real tool's wording and exit status, and a gated test re-derives the set against the installed tool, in the shape of the vercmp oracle. A shim that is more permissive than its tool is not a test of the tool. --- src/pipeline/publish.rs | 147 +++++++++++++++++++++++++++++++++++++----------- 1 file changed, 113 insertions(+), 34 deletions(-) (limited to 'src/pipeline') diff --git a/src/pipeline/publish.rs b/src/pipeline/publish.rs index fd2fdd1..f8efeff 100644 --- a/src/pipeline/publish.rs +++ b/src/pipeline/publish.rs @@ -2,9 +2,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 to `.tmp`, 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. +//! 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}; @@ -20,8 +20,8 @@ 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 to `.tmp`, commits the DB, then renames over -/// the live one, and a second writer interleaving anywhere in that sequence +/// 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 @@ -61,7 +61,7 @@ pub fn index_world(db: &Db) -> Result> { } /// Package files that belong in the served index right now, plus the extra ones -/// being published (which are not in the DB yet when we render `.tmp`). +/// being published (which are not in the DB yet when the new index is rendered). fn index_artifacts(db: &Db, extra: &[PathBuf]) -> Result> { let mut out: Vec = Vec::new(); for p in db::index_packages(db)? { @@ -91,6 +91,9 @@ pub fn publish(ctx: &Ctx) -> Result { // 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. + let mut scratch_dir: Option = 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 @@ -119,17 +122,16 @@ pub fn publish(ctx: &Ctx) -> Result { } let outcome = (|| -> Result { - // 1. render the new database to .tmp and fsync it. The old one is untouched. + // 1. render the new database and fsync it. The live one is untouched + // until step 3's rename. let db_name = ctx.cfg.repo_db_name(); let final_db = arch_dir.join(format!("{db_name}.tar.gz")); - let tmp_db = arch_dir.join(format!("{db_name}.tar.gz.tmp")); let mut pkgs = index_artifacts(&ctx.db, &staged.iter().map(|(d, _)| d.clone()).collect::>())?; // Deduplicate: the same package name must appear once, newest wins. pkgs = dedupe_by_name(pkgs); - run_repo_add(&ctx.cfg, &tmp_db, &pkgs)?; - fsync_file(&tmp_db)?; + 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 tmp write + // 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). #[cfg(feature = "test-support")] @@ -141,15 +143,9 @@ pub fn publish(ctx: &Ctx) -> Result { // 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 and swap the sig. - std::fs::rename(&tmp_db, &final_db)?; - fsync_dir(&arch_dir)?; + // 3. atomic swap: rename over the real database, then sign the new bytes. + rendered.swap_into(&final_db)?; sign(&ctx.cfg, &final_db)?; - let sig = arch_dir.join(format!("{db_name}.tar.gz.sig")); - let tmp_sig = arch_dir.join(format!("{db_name}.tar.gz.sig.tmp")); - if tmp_sig.exists() { - std::fs::rename(&tmp_sig, &sig)?; - } // 4. a publish can unblock builds waiting on a dependency we just added. let unblocked = builds::requeue_blocked(&ctx.db)?; @@ -178,6 +174,9 @@ pub fn publish(ctx: &Ctx) -> Result { for p in &fresh { let _ = std::fs::remove_file(p); } + if let Some(s) = &scratch_dir { + let _ = std::fs::remove_dir_all(s); + } } outcome } @@ -281,14 +280,93 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result { }) } -/// `repo-add -s -p -R ` (§9: both packages and the database -/// are signed so consumers can run `SigLevel = Required`). +/// 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. +pub fn sweep_render_dirs(arch_dir: &Path) { + let Ok(entries) = std::fs::read_dir(arch_dir) else { + return; + }; + for entry in entries.flatten() { + if entry.file_name().to_string_lossy().starts_with(".render-") { + let _ = std::fs::remove_dir_all(entry.path()); + } + } +} + +/// A database repo-add has rendered, and the scratch directory it rendered into. +struct Rendered { + db: PathBuf, + dir: PathBuf, + arch_dir: PathBuf, +} + +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. + fn swap_into(self, final_db: &Path) -> Result<()> { + std::fs::rename(&self.db, final_db)?; + fsync_dir(&self.arch_dir)?; + let _ = std::fs::remove_dir_all(&self.dir); + Ok(()) + } +} + +/// 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 (`.db.tar.gz` and friends) — a `.tmp` suffix is a usage error to +/// it, not a convention. So the render cannot happen at `.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. +/// +/// `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, + tag: &str, + pkgs: &[PathBuf], + scratch: &mut Option, +) -> Result { + static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = arch_dir.join(format!(".render-{}-{n}-{tag}", std::process::id())); + std::fs::create_dir_all(&dir)?; + *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)?; + Ok(()) + })(); + if let Err(e) = attempt { + let _ = std::fs::remove_dir_all(&rendered.dir); + *scratch = None; + return Err(e); + } + Ok(rendered) +} + +/// `repo-add -R `. +/// +/// 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). fn run_repo_add(cfg: &Config, db_path: &Path, pkgs: &[PathBuf]) -> Result<()> { let mut cmd = Command::new(&cfg.repo_add_bin); cmd.arg("-R"); - if !cfg.signing_key_id.is_empty() { - cmd.args(["-s", "-p", &cfg.signing_key_id]); - } cmd.arg(db_path); for p in pkgs { cmd.arg(p); @@ -338,10 +416,10 @@ 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 -/// `.tmp`, 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 +/// 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". fn fsync_file(p: &Path) -> Result<()> { let f = std::fs::File::open(p) @@ -419,9 +497,10 @@ pub fn reconcile(cfg: &Config, db: &Db) -> Result { return Ok(0); } let arch_dir = cfg.repo_arch_dir(); - let tmp = arch_dir.join(format!("{}.tar.gz.tmp", cfg.repo_db_name())); - run_repo_add(cfg, &tmp, &dedupe_by_name(files.clone()))?; - std::fs::rename(&tmp, arch_dir.join(format!("{}.tar.gz", cfg.repo_db_name())))?; + sweep_render_dirs(&arch_dir); + let mut scratch = None; + let rendered = render_db(cfg, &arch_dir, "reconcile", &dedupe_by_name(files.clone()), &mut scratch)?; + rendered.swap_into(&arch_dir.join(format!("{}.tar.gz", cfg.repo_db_name())))?; Ok(files.len()) } @@ -432,10 +511,10 @@ pub fn withdraw_package(cfg: &Config, db: &Db, name: &str) -> Result<()> { let n = name.to_string(); db.writer.tx(move |tx| db::remove_package_by_name_in(tx, rid, &n))?; let arch_dir = cfg.repo_arch_dir(); - let tmp = arch_dir.join(format!("{}.tar.gz.tmp", cfg.repo_db_name())); + let mut scratch = None; let files = index_artifacts(db, &[])?; - run_repo_add(cfg, &tmp, &dedupe_by_name(files))?; - std::fs::rename(&tmp, arch_dir.join(format!("{}.tar.gz", cfg.repo_db_name())))?; + let rendered = render_db(cfg, &arch_dir, "withdraw", &dedupe_by_name(files), &mut scratch)?; + rendered.swap_into(&arch_dir.join(format!("{}.tar.gz", cfg.repo_db_name())))?; db::audit(&db.writer, "human", "cli", "withdraw.publish", "package", name, serde_json::json!({}))?; Ok(()) } -- cgit v1.2.3