From 181859d8013ca69c885f7dbc77dfd1530679d161 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Fri, 20 Nov 2026 10:08:42 -0700 Subject: [PATCH] fix(store): logs, uploads, exports and git can be closed, so a handle from before a close can never write after it A book closed while the server runs stays a book of the root: another process may open it, or this one may open it again, and a new access log is then opened against the file's own head. Any holder of the old handle that appends (an access record written late), sweeps (a timer) or renames (an upload part, a claim dropped) reaches the new book's files and breaks its chain. Each of these now has a closed state, set under the very lock every change to its files goes in under, so a change whose work began before the close is whole and one after it is refused, unwritten. git also takes a cancel flag: a command running is stopped with all it started, and none starts, so a close can end a backup that is still going instead of leaving it to run against books reported closed. Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-store/src/access.rs | 36 ++++++++++ crates/ledger-store/src/backup.rs | 89 +++++++++++++++++++++++- crates/ledger-store/src/chain.rs | 20 ++++++ crates/ledger-store/src/exports.rs | 55 +++++++++++++-- crates/ledger-store/src/uploads.rs | 106 +++++++++++++++++++++++++---- 5 files changed, 286 insertions(+), 20 deletions(-) diff --git a/crates/ledger-store/src/access.rs b/crates/ledger-store/src/access.rs index ac0282b7..57cf7f95 100644 --- a/crates/ledger-store/src/access.rs +++ b/crates/ledger-store/src/access.rs @@ -19,6 +19,12 @@ //! name and version, a request id, the tool or resource it named) //! has any full TIN masked and is then cut to 64 characters. //! 3. Records go in one at a time, in the order they are made. +//! 4. A log can be closed (`close`, under the lock every record goes in +//! under): a record whose append began before it is whole, one after +//! it is refused (`ChainError::Closed`), unwritten. So a record +//! still on its way when its book is let go (a refusal written late) +//! never reaches the file, nor, once the book is opened again, the +//! new log's chain. //! ``` use crate::chain::{self, ChainError, ChainLog, Head}; @@ -220,6 +226,12 @@ impl AccessLog { log.append(fields).map(|(_, head)| head) } + /// Take no more records, ever (INVARIANT 4): waits for the record + /// being appended, if one is. + pub fn close(&self) { + self.log.lock().unwrap_or_else(|e| e.into_inner()).close(); + } + /// Where the log ends now. pub fn head(&self) -> Head { self.log @@ -289,6 +301,30 @@ mod tests { } } + /// A closed log takes no more records (INVARIANT 4): a handle kept from + /// before a close can't append after the log is opened again, which + /// would break the new log's chain. + #[test] + fn a_closed_log_writes_nothing_and_a_reopened_one_stays_whole() { + let dir = tempfile::tempdir().unwrap(); + let old = AccessLog::open(dir.path()).unwrap(); + old.record(&access(1)).unwrap(); + old.close(); + let file = || std::fs::read(dir.path().join(ACCESS_FILE)).unwrap(); + let at_close = file(); + assert_eq!(old.record(&access(2)), Err(ChainError::Closed)); + assert_eq!(file(), at_close, "a closed log wrote"); + // The book is opened again: a new log, against its own head. + let new = AccessLog::open(dir.path()).unwrap(); + new.record(&access(3)).unwrap(); + // The old handle, used late, writes nothing. + assert_eq!(old.record(&access(4)), Err(ChainError::Closed)); + new.record(&access(5)).unwrap(); + let (back, head) = read(dir.path()).unwrap(); + assert_eq!(back.len(), 3); + assert_eq!(head.seq, 3); + } + #[test] fn records_read_back_as_written() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ledger-store/src/backup.rs b/crates/ledger-store/src/backup.rs index 6117675a..f557e2e1 100644 --- a/crates/ledger-store/src/backup.rs +++ b/crates/ledger-store/src/backup.rs @@ -82,6 +82,10 @@ pub enum BackupError { /// A git command ran past its time limit. #[error("git {0} took too long and was stopped")] TimedOut(String), + /// A git command stopped because the books it served were let go + /// ([`Git::with_cancel`]). + #[error("git {0} was stopped: the books are closing")] + Cancelled(String), /// A folder target that isn't there (an external disk not mounted). #[error("the backup folder isn't there (is its disk connected?)")] NoFolder, @@ -114,6 +118,9 @@ pub struct Git { exe: PathBuf, /// How long it may say nothing before it is stopped (GIT_TIMEOUT). quiet: Duration, + /// Set by whoever serves the books when they are let go: a git + /// command running is stopped, with what it started, and none starts. + cancel: Option>, } impl Git { @@ -145,10 +152,27 @@ impl Git { .map(|exe| Git { exe, quiet: GIT_TIMEOUT, + cancel: None, }) .ok_or(BackupError::NoGit) } + /// This git, stopped (every command running, and any that would + /// start) once `cancel` is set: how the server's close ends a backup + /// that is still going, instead of leaving it to run against books it + /// reported closed. + #[must_use] + pub fn with_cancel(mut self, cancel: std::sync::Arc) -> Self { + self.cancel = Some(cancel); + self + } + + fn cancelled(&self) -> bool { + self.cancel + .as_ref() + .is_some_and(|c| c.load(std::sync::atomic::Ordering::SeqCst)) + } + /// A git command with a clean configuration (INVARIANT 4). fn command(&self) -> Command { let mut c = Command::new(&self.exe); @@ -222,6 +246,9 @@ impl Git { /// (a push or a clone reports its progress as it goes). fn run(&self, what: &str, args: &[&std::ffi::OsStr]) -> Result { use std::sync::atomic::{AtomicU64, Ordering}; + if self.cancelled() { + return Err(BackupError::Cancelled(what.to_string())); + } let mut c = self.command(); // A path made canonical on Windows carries `\\?\`, which git refuses. c.args(args.iter().map(|a| match a.to_str() { @@ -306,6 +333,12 @@ impl Git { let quiet_for = started .elapsed() .saturating_sub(Duration::from_millis(heard.load(Ordering::Relaxed))); + if self.cancelled() { + kill_group(child.id()); + let _ = child.kill(); + let _ = child.wait(); + return Err(BackupError::Cancelled(what.to_string())); + } if quiet_for > self.quiet { kill_group(child.id()); let _ = child.kill(); @@ -1877,6 +1910,7 @@ mod tests { Git { exe: wrapper, quiet: GIT_TIMEOUT, + cancel: None, } } @@ -1928,7 +1962,59 @@ mod tests { let exe = dir.join("fake-git"); std::fs::write(&exe, format!("#!/bin/sh\n{script}\n")).unwrap(); std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap(); - Git { exe, quiet } + Git { + exe, + quiet, + cancel: None, + } + } + + /// Cancelled, a git that is running is stopped at once, with all it + /// started, and one that would start doesn't (the server's close ends + /// a backup instead of leaving it to run against closed books). + #[test] + fn a_cancelled_git_stops_what_runs_and_starts_nothing() { + let dir = tempfile::tempdir().unwrap(); + let pid = dir.path().join("pid"); + let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let slow = fake_git( + dir.path(), + &format!("sleep 30 & echo $! > '{}'; sleep 30", pid.display()), + Duration::from_secs(60), + ) + .with_cancel(cancel.clone()); + let running = { + let slow = slow.clone(); + std::thread::spawn(move || slow.run("slow", &[])) + }; + // It is running (it wrote its child's pid) before it is cancelled. + let by = Instant::now() + Duration::from_secs(10); + while !pid.exists() { + assert!(Instant::now() < by, "the fake git never started"); + std::thread::sleep(Duration::from_millis(10)); + } + let cancelled_at = Instant::now(); + cancel.store(true, std::sync::atomic::Ordering::SeqCst); + assert_eq!( + running.join().unwrap().unwrap_err(), + BackupError::Cancelled("slow".into()) + ); + assert!(cancelled_at.elapsed() < Duration::from_secs(5)); + let child: i32 = std::fs::read_to_string(&pid) + .unwrap() + .trim() + .parse() + .unwrap(); + std::thread::sleep(Duration::from_millis(200)); + // SAFETY: signal 0 only asks whether the process is there. + assert_ne!(unsafe { libc::kill(child, 0) }, 0, "what it started ran on"); + // And none starts now. + std::fs::remove_file(&pid).unwrap(); + assert_eq!( + slow.run("again", &[]).unwrap_err(), + BackupError::Cancelled("again".into()) + ); + assert!(!pid.exists(), "a cancelled git started anyway"); } #[test] @@ -2005,6 +2091,7 @@ mod tests { let odd = Git { exe: quoted.join("git"), quiet: GIT_TIMEOUT, + cancel: None, }; let b = dir.path().join("book"); let s = book(&b); diff --git a/crates/ledger-store/src/chain.rs b/crates/ledger-store/src/chain.rs index b7ce5fbb..3970171a 100644 --- a/crates/ledger-store/src/chain.rs +++ b/crates/ledger-store/src/chain.rs @@ -28,6 +28,11 @@ //! 4. Only an unfinished last line (no newline: an append cut short by //! a crash, never acknowledged) is set aside: open cuts it away, //! read reports it. +//! 5. A log can be closed (`close`), and a closed log takes no more +//! appends, ever: a holder of it from before the book was let go can +//! never write after the book is opened again, when a new log is +//! opened on the file against its own head (an append from the old +//! handle would break the chain there). //! ``` use crate::journal::{canonical_json, sha256_hex}; @@ -60,6 +65,8 @@ pub enum ChainError { Io(std::io::ErrorKind), /// An earlier append failed: the log must be reopened (INVARIANT 2). Broken, + /// The log was closed: its book was let go (INVARIANT 5). + Closed, } impl std::fmt::Display for ChainError { @@ -68,6 +75,7 @@ impl std::fmt::Display for ChainError { ChainError::Damaged { line, why } => write!(f, "record {line} is damaged: {why}"), ChainError::Io(kind) => write!(f, "the disk refused: {kind}"), ChainError::Broken => f.write_str("an earlier record couldn't be written"), + ChainError::Closed => f.write_str("the log was closed: its books are not open"), } } } @@ -168,6 +176,7 @@ pub struct ChainLog { file: File, head: Head, broken: bool, + closed: bool, } impl std::fmt::Debug for ChainLog { @@ -175,6 +184,7 @@ impl std::fmt::Debug for ChainLog { f.debug_struct("ChainLog") .field("head", &self.head) .field("broken", &self.broken) + .field("closed", &self.closed) .finish_non_exhaustive() } } @@ -224,6 +234,7 @@ impl ChainLog { file, head: read.head, broken: false, + closed: false, }, read.records, )) @@ -234,6 +245,11 @@ impl ChainLog { &self.head } + /// Take no more appends, ever (INVARIANT 5). + pub fn close(&mut self) { + self.closed = true; + } + /// The log's file. pub fn path(&self) -> &Path { &self.path @@ -243,6 +259,9 @@ impl ChainLog { /// and `hash` (which `fields` must not hold). Returns the record as /// written and the new head (INVARIANT 2). pub fn append(&mut self, fields: Map) -> Result<(Value, Head), ChainError> { + if self.closed { + return Err(ChainError::Closed); + } if self.broken { return Err(ChainError::Broken); } @@ -600,6 +619,7 @@ mod tests { hash: genesis(G), }, broken: false, + closed: false, }; assert!(matches!(log.append(fields(1)), Err(ChainError::Io(_)))); assert_eq!(log.head().seq, 0, "the head didn't move"); diff --git a/crates/ledger-store/src/exports.rs b/crates/ledger-store/src/exports.rs index 122f08a3..a006e512 100644 --- a/crates/ledger-store/src/exports.rs +++ b/crates/ledger-store/src/exports.rs @@ -21,6 +21,11 @@ //! lapsed ones are swept when the books open, whenever one is made, //! and by the server's sweeper. A token has at most MAX_LIVE. //! 4. No error names a path. +//! 5. Exports can be closed (`close`, under the lock every change to the +//! folder is made under): after it none is made, given or swept by +//! any holder of these exports from before, so a book let go is +//! never touched by a late request or a sweep, whoever has it open +//! by then. //! ``` use crate::journal::sha256_hex; @@ -87,8 +92,9 @@ impl From for ExportError { #[derive(Debug, Clone)] pub struct Exports { dir: PathBuf, - /// Held while exports are made or swept (INVARIANT 3). - lock: std::sync::Arc>, + /// Held while exports are made or swept (INVARIANT 3). True once + /// closed (INVARIANT 5). + lock: std::sync::Arc>, } /// `ex_` and 32 letters `a` to `p`, a letter a nibble (INVARIANT 1). @@ -132,10 +138,16 @@ impl Exports { Ok(exports) } - fn locked(&self) -> std::sync::MutexGuard<'_, ()> { + fn locked(&self) -> std::sync::MutexGuard<'_, bool> { self.lock.lock().unwrap_or_else(|e| e.into_inner()) } + /// Change nothing in these exports, and give none, from now on + /// (INVARIANT 5): waits for the change being made, if one is. + pub fn close(&self) { + *self.locked() = true; + } + fn path(&self, id: &str, ext: &str) -> PathBuf { self.dir.join(format!("{id}.{ext}")) } @@ -152,7 +164,10 @@ impl Exports { if let Some(why) = file_name_problem(file_name).or_else(|| mime_problem(mime)) { return Err(ExportError::Bad(why)); } - let _held = self.locked(); + let held = self.locked(); + if *held { + return Err(ExportError::Bad("the books aren't open".into())); + } self.sweep_held(now); if self.live_for(token, now) >= MAX_LIVE { return Err(ExportError::Bad(format!( @@ -196,6 +211,9 @@ impl Exports { return Err(ExportError::Unknown(id.chars().take(40).collect())); } let unknown = || ExportError::Unknown(id.to_string()); + if *self.locked() { + return Err(ExportError::Bad("the books aren't open".into())); + } let record = std::fs::read(self.path(id, "json")).map_err(|_| unknown())?; let export: Export = serde_json::from_slice(&record).map_err(|_| unknown())?; if export.expires <= now { @@ -228,8 +246,10 @@ impl Exports { /// Sweep away every export that lapsed by `now`, and anything left /// without one (INVARIANT 3). pub fn sweep(&self, now: i64) { - let _held = self.locked(); - self.sweep_held(now); + let held = self.locked(); + if !*held { + self.sweep_held(now); + } } fn sweep_held(&self, now: i64) { @@ -259,6 +279,29 @@ mod tests { const NOW: i64 = 1_800_000_000; + /// Closed, exports are made, given and swept by no one (INVARIANT 5). + #[test] + fn closed_exports_change_nothing_and_give_nothing() { + let dir = tempfile::tempdir().unwrap(); + let x = Exports::open(dir.path(), NOW).unwrap(); + let e = x.put("t", "a.csv", "text/csv", b"x", NOW).unwrap(); + x.close(); + let seen = || { + let mut names: Vec<_> = std::fs::read_dir(dir.path().join(EXPORTS_DIR)) + .unwrap() + .map(|f| f.unwrap().file_name()) + .collect(); + names.sort(); + names + }; + let before = seen(); + assert!(x.put("t", "b.csv", "text/csv", b"y", NOW).is_err()); + assert!(x.get(&e.id, "t", NOW).is_err()); + // A sweep long after everything lapsed removes nothing. + x.sweep(NOW + 10 * EXPORT_TTL); + assert_eq!(seen(), before); + } + #[test] fn an_export_is_kept_fifteen_minutes() { // What its refusal tells the human: kept 15 minutes, then gone. diff --git a/crates/ledger-store/src/uploads.rs b/crates/ledger-store/src/uploads.rs index 9528f3d4..daee4766 100644 --- a/crates/ledger-store/src/uploads.rs +++ b/crates/ledger-store/src/uploads.rs @@ -28,6 +28,12 @@ //! 4. No error names a path. //! 5. A token has at most MAX_LIVE grants under way, so what one agent //! can keep on the disk is bounded. +//! 6. Uploads can be closed (`close`, under the lock every change to +//! the folder is made under): after it nothing is granted, received, +//! taken, swept, given back or forgotten, by any holder of these +//! uploads from before, so a book let go (closed, or replaced by a +//! restore) is never touched by a sweep, a late request or a claim +//! dropped after, whoever has the book open by then. //! ``` use crate::journal::sha256_hex; @@ -36,6 +42,8 @@ use sha2::{Digest, Sha256}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; +/// What an upload is told when its books were let go (INVARIANT 6). +const CLOSED: &str = "the books aren't open"; /// The uploads' folder, in a book's folder. pub const UPLOADS_DIR: &str = "uploads"; /// The largest file taken (plan 4.7). @@ -99,7 +107,10 @@ impl Claim { impl Drop for Claim { fn drop(&mut self) { if !self.spent { - let _held = self.uploads.locked(); + let held = self.uploads.locked(); + if *held { + return; + } let _ = std::fs::rename( self.uploads.path(&self.id, TAKEN), self.uploads.path(&self.id, "bin"), @@ -169,8 +180,8 @@ pub struct Uploads { dir: PathBuf, /// Held while grants are made or swept and while bytes change name /// (INVARIANTS 1, 2, 5): one server serves a book, so this orders - /// every request to its uploads. - lock: std::sync::Arc>, + /// every request to its uploads. True once closed (INVARIANT 6). + lock: std::sync::Arc>, } /// The longest file name taken, in bytes (most file systems' limit). @@ -287,10 +298,25 @@ impl Uploads { Ok(uploads) } - fn locked(&self) -> std::sync::MutexGuard<'_, ()> { + fn locked(&self) -> std::sync::MutexGuard<'_, bool> { self.lock.lock().unwrap_or_else(|e| e.into_inner()) } + /// The lock, if the uploads aren't closed (INVARIANT 6). + fn locked_open(&self) -> Result, UploadError> { + let held = self.locked(); + if *held { + return Err(UploadError::Bad(CLOSED.into())); + } + Ok(held) + } + + /// Change nothing in these uploads from now on (INVARIANT 6): waits + /// for the change being made, if one is. + pub fn close(&self) { + *self.locked() = true; + } + fn path(&self, id: &str, ext: &str) -> PathBuf { self.dir.join(format!("{id}.{ext}")) } @@ -327,7 +353,7 @@ impl Uploads { "purpose is receipt, document, import (a bank or chart CSV) or w9".into(), )); } - let _held = self.locked(); + let _held = self.locked_open()?; self.sweep_held(now); // INVARIANT 5. if self.live_for(token, now) >= MAX_LIVE { @@ -378,6 +404,7 @@ impl Uploads { return Err(UploadError::Unknown(id.chars().take(40).collect())); } let unknown = || UploadError::Unknown(id.to_string()); + drop(self.locked_open()?); let bytes = std::fs::read(self.path(id, "json")).map_err(|_| unknown())?; let grant: Grant = serde_json::from_slice(&bytes).map_err(|_| unknown())?; if grant.expires <= now { @@ -406,7 +433,7 @@ impl Uploads { // One request at a time (INVARIANT 2): no bytes kept or held, and // no `.part` of another request. let mut out = { - let _held = self.locked(); + let _held = self.locked_open()?; if done.exists() || self.path(id, TAKEN).exists() { return Err(UploadError::AlreadySent); } @@ -459,7 +486,11 @@ impl Uploads { Ok(()) => { // Kept only if its grant still stands (it may have lapsed, // or been filed by another request's bytes, meanwhile). - let _held = self.locked(); + let held = self.locked(); + if *held { + let _ = std::fs::remove_file(&part); + return Err(UploadError::Bad(CLOSED.into())); + } let standing = std::fs::read(self.path(id, "json")) .ok() .and_then(|b| serde_json::from_slice::(&b).ok()) @@ -493,7 +524,7 @@ impl Uploads { let taken = self.path(id, TAKEN); // The rename is the hold: of two calls, one gets it. { - let _held = self.locked(); + let _held = self.locked_open()?; if let Err(e) = std::fs::rename(self.path(id, "bin"), &taken) { return Err(match e.kind() { std::io::ErrorKind::NotFound if taken.exists() => UploadError::InUse, @@ -527,14 +558,19 @@ impl Uploads { /// be written): the grant stands, its bytes are to be sent again. pub fn discard(&self, id: &str) { if is_id(id) { - let _held = self.locked(); - let _ = std::fs::remove_file(self.path(id, "bin")); + let held = self.locked(); + if !*held { + let _ = std::fs::remove_file(self.path(id, "bin")); + } } } /// Forget grant `id` and anything kept for it. fn forget(&self, id: &str) { - let _held = self.locked(); + let held = self.locked(); + if *held { + return; + } for ext in ["json", "part", "bin", TAKEN] { let _ = std::fs::remove_file(self.path(id, ext)); } @@ -543,8 +579,10 @@ impl Uploads { /// Sweep away every grant that lapsed by `now`, and anything left /// without one (INVARIANT 3). pub fn sweep(&self, now: i64) { - let _held = self.locked(); - self.sweep_held(now); + let held = self.locked(); + if !*held { + self.sweep_held(now); + } } /// [`Self::sweep`], the lock held. @@ -588,6 +626,48 @@ mod tests { .unwrap() } + /// Closed, uploads are granted, received, taken, swept and given back + /// by no one, and a claim dropped after puts nothing back (INVARIANT 6). + #[test] + fn closed_uploads_change_nothing() { + let dir = tempfile::tempdir().unwrap(); + let u = Uploads::open(dir.path(), NOW).unwrap(); + let bytes = b"%PDF-1.4 a receipt".to_vec(); + let g = grant_for(&u, "tok_a", &bytes); + u.receive(&g.id, "tok_a", &mut &bytes[..], NOW).unwrap(); + let received = u.take(&g.id, "tok_a", NOW).unwrap(); + let seen = || { + let mut names: Vec<_> = std::fs::read_dir(dir.path().join(UPLOADS_DIR)) + .unwrap() + .map(|f| f.unwrap().file_name()) + .collect(); + names.sort(); + names + }; + let held = seen(); + u.close(); + assert!( + u.grant( + "tok_a", + &sha256_hex(&bytes), + bytes.len() as u64, + "application/pdf", + "r.pdf", + "receipt", + NOW + ) + .is_err() + ); + assert!(u.receive(&g.id, "tok_a", &mut &bytes[..], NOW).is_err()); + assert!(u.take(&g.id, "tok_a", NOW).is_err()); + u.discard(&g.id); + u.sweep(NOW + 10 * UPLOAD_TTL); + // The call that held the bytes lets go of them, unspent: nothing + // is put back, nor forgotten, in a folder that is no longer ours. + drop(received); + assert_eq!(seen(), held); + } + #[test] fn bytes_sent_as_declared_are_taken_once() { let dir = tempfile::tempdir().unwrap();