diff --git a/crates/ledger-cli/tests/book_open_close.rs b/crates/ledger-cli/tests/book_open_close.rs index 18555ceb..933d73fc 100644 --- a/crates/ledger-cli/tests/book_open_close.rs +++ b/crates/ledger-cli/tests/book_open_close.rs @@ -778,6 +778,12 @@ mod raw { self.stream.write_all(rest).unwrap(); } + /// A piece of the rest of a body; false once the server has closed + /// the connection (nothing more can be sent). + pub fn try_finish(&mut self, piece: &[u8]) -> bool { + self.stream.write_all(piece).is_ok() + } + /// Everything the server sends until it closes the connection, /// which it must do within `within`. pub fn until_closed(&mut self, within: Duration) -> String { @@ -1406,12 +1412,19 @@ fn a_stalled_mcp_body_cannot_hold_a_close_and_nothing_of_it_is_journaled() { } /// A slow upload that is still arriving, and finishes within the grace, is -/// not cut: it is kept and answered, as without a close. +/// not cut: it is kept and answered, as without a close. Driven by +/// conditions, not by time: the grace (a minute) is far past anything the +/// test does, and the rest of the bytes are sent only after the close has +/// begun (the book is listed closed), so the one thing this proves is that +/// the cut waits for the grace, never firing at the start of the close (it +/// fails with the cut set to fire at once). Its mirror, that the cut does +/// fire when the grace is out, is +/// `an_upload_still_arriving_when_the_grace_runs_out_is_cut_however_active_it_is`. #[cfg(unix)] #[test] fn a_slow_upload_that_finishes_within_the_grace_is_not_cut() { let home = Home::new("close-slow-upload"); - let server = Server::start_with(&home, &["--answer-grace", "2500", "--timers", "10"]); + let server = Server::start_with(&home, &["--answer-grace", "60000", "--timers", "10"]); home.create(A, "USD"); let mut w = Wire::new(&home, A); w.initialize("uploader"); @@ -1886,3 +1899,534 @@ fn the_timers_never_touch_a_closed_book() { .expect("the backup record is a whole chain"); ledger_store::Store::open(&dir).expect("the journal replays"); } + +/// The mirror of `a_slow_upload_that_finishes_within_the_grace_is_not_cut`: +/// an upload whose client is not stalled at all, sending steadily, is cut +/// the moment the grace has run out, because its body isn't whole then (the +/// line is the body's end, INVARIANT 15). Driven by conditions: the client +/// sends until the server closes the connection, and the body is far too +/// large to be whole within the grace (the test fails if the upload is +/// let finish: with the cut removed it is kept, answered 200, and the close +/// answered ten seconds late). +#[cfg(unix)] +#[test] +fn an_upload_still_arriving_when_the_grace_runs_out_is_cut_however_active_it_is() { + let home = Home::new("close-active-upload"); + let server = Server::start_with(&home, &["--answer-grace", "600", "--timers", "10"]); + home.create(A, "USD"); + let mut w = Wire::new(&home, A); + w.initialize("uploader"); + let bytes: Vec = (0..3_000_000u32).map(|n| (n % 241) as u8).collect(); + let (id, mut raw) = half_sent_upload(&home, &mut w, A, &bytes); + let closing = std::thread::spawn({ + let admin = home.run().join("admin.sock"); + move || ledger_mcp::admin::call(&admin, Request::CloseBook { id: A.into() }).unwrap() + }); + wait_for("the book is listed closed", Duration::from_secs(30), || { + listed(&home, A).1 + }); + // Steady: 8 KB every 25 ms (about 320 KB/s: the rest takes ten seconds). + let begun = std::time::Instant::now(); + let mut sent = bytes.len() / 2; + while sent < bytes.len() { + let piece = &bytes[sent..(sent + 8192).min(bytes.len())]; + if !raw.try_finish(piece) { + break; + } + sent += piece.len(); + std::thread::sleep(Duration::from_millis(25)); + assert!( + begun.elapsed() < Duration::from_secs(8), + "an upload that was still arriving was never cut" + ); + } + assert!( + sent < bytes.len(), + "the whole upload went in before the cut" + ); + assert!( + begun.elapsed() >= Duration::from_millis(400), + "cut before the grace ran out ({:?})", + begun.elapsed() + ); + let said = raw.until_closed(Duration::from_secs(10)); + assert!(said.contains("cut_by_close"), "{said}"); + match closing.join().unwrap() { + Response::CloseBook { outcome, .. } => assert_eq!(outcome, CloseOutcome::Closed), + other => panic!("{other:?}"), + } + assert_eq!(parts_under(&home.book_dir(A)), Vec::::new()); + assert!( + !tree_of(&home.book_dir(A)) + .keys() + .any(|k| k.contains(&id) && k.ends_with(".bin")), + "bytes of a cut upload were kept" + ); + assert_eq!(cut_records(&home, A, "upload").len(), 1); + assert!(server.close().success()); +} + +/// The server's own close is the book's close, all books together +/// (local.rs INVARIANT 15): with an upload stalled half way on one book and +/// an MCP call's body stalled half way on another, the server told to close +/// (its standard input ends) cuts both one grace after the close began, +/// exits 0 within a bound, leaves no part file, journals nothing of the +/// call, and its records say `cut_by_close`. +#[cfg(unix)] +#[test] +fn the_servers_own_close_cuts_stalled_requests_and_exits_zero_in_time() { + let home = Home::new("server-close-stalled"); + let server = Server::start_with(&home, &["--answer-grace", "600", "--timers", "10"]); + home.create(A, "USD"); + home.create(B, "USD"); + let mut wa = Wire::new(&home, A); + wa.initialize("uploader"); + let bytes: Vec = (0..200_000u32).map(|n| (n % 251) as u8).collect(); + let (id, mut raw_upload) = half_sent_upload(&home, &mut wa, A, &bytes); + let mut wb = Wire::new(&home, B); + wb.initialize("caller"); + draft(&mut wb, "before"); + let mut raw_call = raw::Raw::connect(&home, B); + let body = json!({"jsonrpc": "2.0", "id": 9, "method": "tools/call", "params": { + "name": "books.draft_entry", + "arguments": {"date": "2026-03-01", "description": "never finished"}}}) + .to_string(); + raw_call.start( + "POST", + "mcp", + &[ + ("content-type", "application/json"), + ("accept", "application/json, text/event-stream"), + ("mcp-session-id", wb.session().unwrap()), + ("mcp-protocol-version", wb.version().unwrap()), + ], + body.as_bytes(), + body.len() / 2, + ); + std::thread::sleep(Duration::from_millis(200)); + let started = std::time::Instant::now(); + let status = server.close(); + let took = started.elapsed(); + assert_eq!(status.code(), Some(0), "{status:?}"); + assert!( + took >= Duration::from_millis(500), + "cut before the grace ran out ({took:?})" + ); + // The bound: the grace (600 ms, the cut), the answers' grace (600 ms), + // and the linger and the HTTP side's end (3 s and 5 s at most). + assert!(took < Duration::from_secs(12), "{took:?}"); + assert!( + raw_upload + .until_closed(Duration::from_secs(10)) + .contains("cut_by_close") + ); + assert!( + raw_call + .until_closed(Duration::from_secs(10)) + .contains("cut_by_close") + ); + assert_eq!(parts_under(&home.book_dir(A)), Vec::::new()); + assert!( + !tree_of(&home.book_dir(A)) + .keys() + .any(|k| k.contains(&id) && k.ends_with(".bin")), + "bytes of a cut upload were kept" + ); + assert_eq!(cut_records(&home, A, "upload").len(), 1); + assert_eq!(cut_records(&home, B, "connect").len(), 1); + assert!( + !files_of(&home, B) + .0 + .iter() + .any(|l| l.payload["description"] == json!("never finished")), + "a call whose body never arrived was journaled" + ); + // Every log is whole, and the books open again. + access_of(&home, A); + access_of(&home, B); + ledger_store::Store::open(&home.book_dir(A)).expect("the books open again"); + ledger_store::Store::open(&home.book_dir(B)).expect("the books open again"); +} + +/// A timer that took a book's handles before the close and acts on them +/// after it does nothing to the book (local.rs INVARIANT 13). The knob +/// `--timer-hold` holds a timer between its taking the handles and its +/// acting on them; the test closes the book meanwhile, plants what a sweep +/// would take, lets the timer go on, and the tree of the closed book must +/// not move. `held` names the timers held: the sweep, and the backup or the +/// drill (the backup loop is one task: the drill is held only once the +/// write is backed up). +#[cfg(unix)] +fn a_late_timer_does_nothing(name: &str, held_timers: &str) { + let home = Home::new(name); + let server = Server::start_with( + &home, + &[ + "--timers", + "5", + "--timer-hold", + "--backup-quiet", + "0", + "--drill-first", + "0", + "--answer-grace", + "300", + ], + ); + home.create(A, "USD"); + let run = home.run(); + let seen = || std::fs::read_to_string(run.join("timer-held")).unwrap_or_default(); + let all_held = || { + held_timers + .split(',') + .all(|t| seen().lines().any(|l| l == t)) + }; + // From the start of the book's work: the timers hold what they take. + std::fs::write(run.join("timer-hold"), held_timers).unwrap(); + let mut w = Wire::new(&home, A); + w.initialize("owner"); + let disk = home.dir.path().join("disk"); + std::fs::create_dir_all(&disk).unwrap(); + set_backup_folder(&mut w, &disk); + w.end(); + wait_for( + "the timers hold their handles", + Duration::from_secs(60), + all_held, + ); + let dir = home.book_dir(A); + assert!(matches!(close_book(&home, A), CloseOutcome::Closed)); + for folder in ["uploads", "exports"] { + std::fs::write(dir.join(folder).join("stray.bin"), b"x").unwrap(); + } + let at_close = tree_of(&dir); + // The timers go on, with what they took before the close. + std::fs::remove_file(run.join("timer-hold")).unwrap(); + std::thread::sleep(Duration::from_millis(300)); + stands_still(&home, A, Duration::from_millis(500), "a late timer"); + assert_eq!(moved(&at_close, &tree_of(&dir)), Vec::::new()); + assert!(dir.join("uploads").join("stray.bin").exists()); + assert!(dir.join("exports").join("stray.bin").exists()); + // Opened again, the timers work on it again. + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + wait_for( + "the sweep takes the stray files", + Duration::from_secs(30), + || !dir.join("uploads").join("stray.bin").exists(), + ); + assert!(server.close().success()); + access_of(&home, A); + ledger_store::chain::read( + &dir.join("ops").join("backup.jsonl"), + "wanderbooks-backup-v1", + ) + .expect("the backup record is a whole chain"); +} + +/// The sweep and the backup, each holding its handles across a close. +#[cfg(unix)] +#[test] +fn a_backup_and_a_sweep_that_took_their_handles_before_a_close_do_nothing_after_it() { + a_late_timer_does_nothing("close-late-backup", "sweep,backup"); +} + +/// The sweep and the drill, each holding its handles across a close. +#[cfg(unix)] +#[test] +fn a_drill_and_a_sweep_that_took_their_handles_before_a_close_do_nothing_after_it() { + a_late_timer_does_nothing("close-late-drill", "sweep,drill"); +} + +/// A close does not wait for a drill, however long the book makes it: the +/// drill is stopped at its next look (a cancel flag), its scratch clone is +/// removed, and the close is answered within its stated bound (local.rs +/// INVARIANT 10: the grace for what hasn't arrived, the grace for the +/// answers, the last backup's bound, the stop of a step, which for a +/// folder target includes the lock settling time), with the last backup +/// made. `--slow-steps` makes each phase of the drill wait a minute, as a +/// book of a million events would make its replay; without the hurry the +/// last backup waits behind the drill and the close says it wasn't whole. +#[cfg(unix)] +#[test] +fn a_close_stops_a_slow_drill_instead_of_waiting_for_it() { + let home = Home::new("close-slow-drill"); + let (grace, last_backup) = (500u64, 3000u64); + let server = Server::start_with( + &home, + &[ + "--slow-steps", + "60000", + "--timers", + "20", + "--backup-quiet", + "0", + "--drill-first", + "0", + "--answer-grace", + &grace.to_string(), + "--close-backup", + &last_backup.to_string(), + ], + ); + home.create(A, "USD"); + let disk = home.dir.path().join("disk"); + std::fs::create_dir_all(&disk).unwrap(); + let mut w = Wire::new(&home, A); + w.initialize("owner"); + set_backup_folder(&mut w, &disk); + draft(&mut w, "backed up first"); + w.end(); + // The write is backed up, then its first drill begins and sits in its + // wait: the clone is made, its scratch folder is there. + let scratch = home.book_dir(A).join("ops").join("drill-folder"); + wait_for("a drill is under way", Duration::from_secs(60), || { + scratch.exists() + }); + // A write the close's last backup has to make. + let mut w = Wire::new(&home, A); + w.initialize("owner"); + draft(&mut w, "after the drill began"); + w.end(); + let started = std::time::Instant::now(); + let outcome = close_book(&home, A); + let took = started.elapsed(); + assert_eq!( + outcome, + CloseOutcome::Closed, + "the last backup waited behind the drill" + ); + // The stated bound, as a sum of its parts: the grace, the answers' + // grace, the last backup's bound, and the stop of a step (git's kill + // and its group's end, 2 s; its pipes, 10 s; the lock settling, 1.5 s). + let bound = Duration::from_millis(2 * grace + last_backup) + Duration::from_millis(13_500); + assert!(took < bound, "{took:?} past the stated bound {bound:?}"); + assert!(took < Duration::from_secs(8), "{took:?}: the drill ran on"); + assert!(!scratch.exists(), "the stopped drill's clone was left"); + // The last backup took the write. + let records = std::fs::read_to_string(home.book_dir(A).join("ops").join("backup.jsonl")) + .unwrap_or_default(); + assert!( + records.matches("\"why\":\"close\"").count() >= 1, + "no backup at the close: {records}" + ); + stands_still( + &home, + A, + Duration::from_millis(400), + "after the close was answered", + ); + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + assert!(server.close().success()); + ledger_store::chain::read( + &home.book_dir(A).join("ops").join("backup.jsonl"), + "wanderbooks-backup-v1", + ) + .expect("the backup record is a whole chain"); +} + +/// A stand-in `git` that is the real one with a hooks folder of its own +/// (every `core.hooksPath=/dev/null` it is given, in its arguments and in +/// the `--receive-pack` command of a push to a folder, names it instead), +/// where a `reference-transaction` hook waits, while `slow-commit` (for the +/// book's archive) or `slow-push` (for any other repository) exists in the +/// shim folder, at the point where git holds its ref locks. `hooked` has a +/// line per hook that waited. A real git, killed inside real work. +#[cfg(unix)] +fn slow_real_git(home: &Home) -> PathBuf { + use std::os::unix::fs::PermissionsExt; + let dir = home.dir.path().join("slow-shim"); + let hooks = dir.join("hooks"); + std::fs::create_dir_all(&hooks).unwrap(); + let real = ["/usr/bin/git", "/bin/git", "/usr/local/bin/git"] + .into_iter() + .find(|p| std::path::Path::new(p).is_file()) + .expect("git is installed"); + let hook = hooks.join("reference-transaction"); + std::fs::write( + &hook, + "#!/bin/sh\ncat >/dev/null\n[ \"$1\" = prepared ] || exit 0\nd=\"$(dirname \"$0\")/..\"\ncase \"$GIT_DIR $PWD\" in *archive.git*) f=slow-commit ;; *) f=slow-push ;; esac\nif [ -e \"$d/$f\" ]; then\n echo $$ >> \"$d/hooked\"\n while [ -e \"$d/$f\" ]; do sleep 0.05; done\nfi\nexit 0\n", + ) + .unwrap(); + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + let exe = dir.join("git"); + std::fs::write( + &exe, + format!( + "#!/bin/sh\nn=$#\nwhile [ $n -gt 0 ]; do\n a=\"$1\"; shift\n case \"$a\" in\n *core.hooksPath=/dev/null*) a=$(printf '%s' \"$a\" | sed 's|core.hooksPath=/dev/null|core.hooksPath={}|g') ;;\n esac\n set -- \"$@\" \"$a\"\n n=$((n-1))\ndone\nexec {real} \"$@\"\n", + hooks.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap(); + dir +} + +/// Every `*.lock` file under a bare repository. +#[cfg(unix)] +fn locks_under(repo: &std::path::Path) -> Vec { + tree_of(repo) + .into_keys() + .filter(|k| k.ends_with(".lock")) + .collect() +} + +#[cfg(unix)] +fn fsck_of(repo: &std::path::Path) { + let out = std::process::Command::new("git") + .arg(format!("--git-dir={}", repo.display())) + .args(["fsck", "--strict"]) + .output() + .unwrap(); + assert!( + out.status.success(), + "{} isn't whole: {}", + repo.display(), + String::from_utf8_lossy(&out.stderr) + ); +} + +/// A close that stops real git inside a commit, and inside a push to a +/// folder, leaves no lock for anyone to remove: each is gone before the +/// close is answered and noted in the backup's record, the book opened +/// again at once backs up with no step by hand, and both repositories pass +/// `git fsck` (ledger_store::backup INVARIANT 5). +#[cfg(unix)] +#[test] +fn a_close_that_stops_git_in_a_commit_or_a_push_leaves_no_lock_and_the_next_backup_succeeds() { + let home = Home::new("close-git-locks"); + let shim = slow_real_git(&home); + let server = server_with_shim( + &home, + &shim, + &[ + "--close-backup", + "1500", + "--backup-quiet", + "3600000", + "--timers", + "20", + ], + ); + home.create(A, "USD"); + let disk = home.dir.path().join("disk"); + std::fs::create_dir_all(&disk).unwrap(); + let mut w = Wire::new(&home, A); + w.initialize("owner"); + set_backup_folder(&mut w, &disk); + draft(&mut w, "to be backed up inside a commit"); + w.end(); + let archive = home.book_dir(A).join("archive.git"); + let target = disk.join(format!("{A}.git")); + let record = || { + std::fs::read_to_string(home.book_dir(A).join("ops").join("backup.jsonl")) + .unwrap_or_default() + }; + // 0. Inside the making of the archive itself (`git init`): a lock in + // a repository that isn't one yet stops every later `init`. + std::fs::write(shim.join("slow-commit"), b"").unwrap(); + let outcome = close_book(&home, A); + assert!( + matches!(outcome, CloseOutcome::ClosedBackupIncomplete(_)), + "{outcome:?}" + ); + assert!( + shim.join("hooked").exists(), + "git never reached its ref update" + ); + assert_eq!(locks_under(&archive), Vec::::new()); + assert!(record().contains("HEAD.lock"), "{}", record()); + std::fs::remove_file(shim.join("slow-commit")).unwrap(); + std::fs::remove_file(shim.join("hooked")).unwrap(); + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + let mut w = Wire::new(&home, A); + w.initialize("owner"); + draft(&mut w, "to be backed up inside a commit"); + w.end(); + match home.admin(Request::BackUpNow { + id: A.into(), + new_disk: false, + }) { + Response::BackedUp { targets, .. } => { + assert!(targets.iter().all(|t| t.problem.is_none()), "{targets:?}"); + } + other => panic!("{other:?}"), + } + let mut w = Wire::new(&home, A); + w.initialize("owner"); + draft(&mut w, "to be committed inside a commit"); + w.end(); + // 1. Inside the commit's ref update. + std::fs::write(shim.join("slow-commit"), b"").unwrap(); + let outcome = close_book(&home, A); + assert!( + matches!(outcome, CloseOutcome::ClosedBackupIncomplete(_)), + "{outcome:?}" + ); + assert!( + shim.join("hooked").exists(), + "git never reached its ref update" + ); + assert_eq!(locks_under(&archive), Vec::::new()); + assert!( + record().contains("\"kind\":\"lock_removed\"") && record().contains("refs/heads/main.lock"), + "the removal wasn't recorded: {}", + record() + ); + std::fs::remove_file(shim.join("slow-commit")).unwrap(); + std::fs::remove_file(shim.join("hooked")).unwrap(); + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + let status = home.admin(Request::BackUpNow { + id: A.into(), + new_disk: false, + }); + match &status { + Response::BackedUp { targets, .. } => { + assert!(targets.iter().all(|t| t.problem.is_none()), "{status:?}"); + } + other => panic!("{other:?}"), + } + fsck_of(&archive); + fsck_of(&target); + // 2. Inside the push's ref update at the folder. + let mut w = Wire::new(&home, A); + w.initialize("owner"); + draft(&mut w, "to be pushed inside a push"); + w.end(); + std::fs::write(shim.join("slow-push"), b"").unwrap(); + let outcome = close_book(&home, A); + assert!( + matches!(outcome, CloseOutcome::ClosedBackupIncomplete(_)), + "{outcome:?}" + ); + assert!( + shim.join("hooked").exists(), + "git never reached its ref update" + ); + assert_eq!(locks_under(&target), Vec::::new()); + assert_eq!(locks_under(&archive), Vec::::new()); + assert!( + record().contains("\"repo\":\"folder\""), + "the folder's lock wasn't recorded: {}", + record() + ); + std::fs::remove_file(shim.join("slow-push")).unwrap(); + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + let status = home.admin(Request::BackUpNow { + id: A.into(), + new_disk: false, + }); + match &status { + Response::BackedUp { targets, .. } => { + assert!(targets.iter().all(|t| t.problem.is_none()), "{status:?}"); + } + other => panic!("{other:?}"), + } + fsck_of(&archive); + fsck_of(&target); + ledger_store::chain::read( + &home.book_dir(A).join("ops").join("backup.jsonl"), + "wanderbooks-backup-v1", + ) + .expect("the backup record is a whole chain"); + assert!(server.close().success()); +} diff --git a/crates/ledger-mcp/src/backup.rs b/crates/ledger-mcp/src/backup.rs index d5e6f4d5..1b70a112 100644 --- a/crates/ledger-mcp/src/backup.rs +++ b/crates/ledger-mcp/src/backup.rs @@ -59,15 +59,38 @@ //! nothing, spawns no process, and writes nothing, whatever the books //! are doing: not in this process's later opening of the same books, //! whose own backups are another object with another record handle. +//! 11. A close is not held by a step it doesn't wait for. When a close +//! begins (`hurry`, before its last backup), a drill, and a format +//! upgrade that has not yet appended its `journal.format_set` line, +//! stop at their next look (ledger_store::backup INVARIANT 6: between +//! git commands and phases, once per journal line, file or 64 KiB +//! chunk): a drill's scratch clone is removed and nothing is said of +//! its target (neither a pass nor a failure: it is due again when the +//! books next open); an upgrade is reported not done, the books +//! unchanged, and its backup (a commit it made on the way) recorded. +//! Once the `journal.format_set` line is appended the upgrade +//! finishes, which is quick (the line, the database's row). The last +//! backup of the close, and the stop `shut` makes of what is left of +//! it, are not hurried: only `shut` stops them. The close's whole +//! bound is the sum written in the books server's INVARIANT 10 +//! (local.rs). +//! 12. A lock file a stopped git left is dealt with by the step that +//! stopped it (ledger_store::backup INVARIANT 5) and recorded: a +//! record `lock_removed` (or `lock_left`, for one it must not touch) +//! with `repo` (`archive`, `folder` or `repository`), `lock` (a path +//! in that repository) and `why`; so are the locks found in the +//! archive when the books open (the store is open, and its lock is +//! ours). A close is not answered before these are recorded, the +//! backup record being closed after them. //! ``` use crate::server::SharedStore; -use ledger_store::backup::{self, BackupError, Git, Target}; +use ledger_store::backup::{self, BackupError, Git, LockNotes, Target}; use ledger_store::chain::ChainLog; use serde::Serialize; use serde_json::{Map, Value, json}; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; /// What a call is told when these backups were shut (INVARIANT 10). @@ -117,6 +140,20 @@ pub struct Backups { shut: Arc, /// The blocking steps under way. busy: Arc, + /// Set when a close begins, before its last backup (INVARIANT 11): the + /// steps a close doesn't wait for (a drill, a format upgrade not yet + /// journaled) stop, and `shut` sets it too. A backup's own git is + /// stopped by `shut` alone, so the close's last backup can run. + hurry: Arc, + /// The lock files a stopped git left, as they were dealt with + /// (ledger_store::backup INVARIANT 5), until they are recorded. + locks: LockNotes, + /// A test knob (`--slow-steps`): how long a drill or a format upgrade + /// waits, in milliseconds, at each phase, giving up when hurried. + slow_ms: AtomicU64, + /// Phases that began their wait (the test knob), for a test to see + /// that a step is inside one. + paused: Arc, } /// What a format upgrade did ([`Backups::upgrade_format`]). @@ -296,10 +333,20 @@ impl Backups { running: tokio::sync::Mutex::new(()), shut: Arc::default(), busy: Arc::default(), + hurry: Arc::default(), + locks: LockNotes::default(), + slow_ms: AtomicU64::new(0), + paused: Arc::default(), }; for fields in carried { me.record(fields); } + // The store is open, so its lock is ours: no other wanderbooks + // process runs git on this archive, and none of this process's does + // yet, so a lock in it is a dead git's (store INVARIANT 5a). + for note in backup::clear_archive_locks(dir) { + me.record_lock(¬e); + } // Books just restored: whose they were (INVARIANTS 6, 7). let marker = ledger_store::ops::ops_dir(dir).join(ledger_store::root::RESTORED_FROM); if let Ok(origin) = std::fs::read_to_string(&marker) { @@ -351,7 +398,73 @@ impl Backups { /// git, stopped by `shut`. fn git(&self) -> Result { - Ok(Git::find()?.with_cancel(self.shut.clone())) + Ok(Git::find()? + .with_cancel(self.shut.clone()) + .with_lock_notes(self.locks.clone())) + } + + /// git for a step a close hurries (a drill, a format upgrade): stopped + /// as soon as the close begins (INVARIANT 11). + fn hurried_git(&self) -> Result { + let git = Git::find()? + .with_cancel(self.hurry.clone()) + .with_lock_notes(self.locks.clone()); + let ms = self.slow_ms.load(Ordering::SeqCst); + if ms == 0 { + return Ok(git); + } + let (hurry, paused) = (self.hurry.clone(), self.paused.clone()); + Ok(git.with_phase_watch(Arc::new(move |phase: &str| { + // From the second phase on (the first is the clone, before + // there is anything of the step's own to see). + if phase == "clone" { + return; + } + paused.fetch_add(1, Ordering::SeqCst); + let by = std::time::Instant::now() + std::time::Duration::from_millis(ms); + while std::time::Instant::now() < by && !hurry.load(Ordering::SeqCst) { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + }))) + } + + /// Make each phase of a drill or format upgrade wait `by` (a test + /// knob: a book large enough for these to take long). + pub(crate) fn slow_steps(&self, by: std::time::Duration) { + self.slow_ms.store(by.as_millis() as u64, Ordering::SeqCst); + } + + /// How many waits of the test knob have begun. + #[cfg(test)] + pub(crate) fn pauses_begun(&self) -> usize { + self.paused.load(Ordering::SeqCst) + } + + /// A close begins (INVARIANT 11): the steps it doesn't wait for stop at + /// their next look. The close's last backup, and what `shut` stops, are + /// not affected until `shut`. + pub fn hurry(&self) { + self.hurry.store(true, Ordering::SeqCst); + } + + fn hurried(&self) -> bool { + self.hurry.load(Ordering::SeqCst) + } + + /// A lock a stopped git left, as it was dealt with: a record of the + /// backup (INVARIANT 12). + fn record_lock(&self, note: &backup::LockNote) { + self.record(json!({ + "kind": if note.removed { "lock_removed" } else { "lock_left" }, + "repo": note.repo, "lock": note.lock, "why": note.why, + })); + } + + /// Record the locks dealt with since the last look. + fn note_locks(&self) { + for note in self.locks.take() { + self.record_lock(¬e); + } } /// Shut these backups for good (INVARIANT 10): git stopped, every step @@ -359,6 +472,7 @@ impl Backups { /// will have, and before the books' store is let go. pub async fn shut(&self) { self.shut.store(true, Ordering::SeqCst); + self.hurry.store(true, Ordering::SeqCst); // The run or drill holding the books' turn ends (its git was just // stopped), and none begins after. let _turn = self.running.lock().await; @@ -369,6 +483,7 @@ impl Backups { } ended.await; } + self.note_locks(); self.log.lock().unwrap_or_else(|e| e.into_inner()).close(); } @@ -463,6 +578,7 @@ impl Backups { }) .await .unwrap_or(Err(BackupError::Damaged("the backup stopped".into()))); + self.note_locks(); let (made, named, head) = match made { Ok(m) => m, Err(e) => { @@ -497,6 +613,7 @@ impl Backups { }) .await .unwrap_or(Err(BackupError::Damaged("the push stopped".into()))); + self.note_locks(); match pushed { Ok(commit) => self.record( json!({"kind": "push", "why": why, "target": n.target.kind(), @@ -533,7 +650,8 @@ impl Backups { // again): INVARIANT 10. let step = self.begin()?; let (store, dir, book) = (self.store.clone(), self.dir.clone(), self.book.clone()); - let cancel = self.shut.clone(); + let git_for_upgrade = self.hurried_git(); + let cancel = self.hurry.clone(); let done = tokio::task::spawn_blocking(move || { let _step = step; // Books that wait for nothing are left as they are: not even @@ -551,7 +669,7 @@ impl Backups { Err(why) => return Err(UpgradeFailed::stopped(why)), } // Stored files staged ahead, outside the lock (as a backup's). - let git = Git::find().map(|g| g.with_cancel(cancel)); + let git = git_for_upgrade; if let Ok(git) = &git { let _ = backup::stage_blobs(git, &dir); } @@ -580,6 +698,16 @@ impl Backups { }) .map_err(|e| UpgradeFailed::proof(made.clone(), e))?; let commit = proven.commit; + // The last look for a close (INVARIANT 11): once the + // `journal.format_set` line is appended the upgrade + // finishes, which is quick; before it, it is stopped, + // the books unchanged. + if cancel.load(Ordering::SeqCst) { + return Err(UpgradeFailed { + made: made.clone(), + why: "the books are closing: nothing was upgraded".into(), + }); + } let upgrade = match s.upgrade_format() { Ok(upgrade) => upgrade, // Journaled, and what follows the line failed (its @@ -611,6 +739,7 @@ impl Backups { }) .await .unwrap_or_else(|_| Err(UpgradeFailed::stopped("the upgrade stopped".into()))); + self.note_locks(); match done { Ok(u) => { if let (Some(b), Some(up)) = (&u.backup, &u.upgrade) { @@ -667,10 +796,13 @@ impl Backups { if paused(&n.key, &records) || !drill_due(&n.key, &records, now) { continue; } + if self.hurried() { + return; + } let Ok(step) = self.begin() else { return; }; - let git = self.git(); + let git = self.hurried_git(); let (dir, book, t) = (self.dir.clone(), self.book.clone(), n.target.clone()); let drilled = tokio::task::spawn_blocking(move || { let _step = step; @@ -687,7 +819,12 @@ impl Backups { }) .await .unwrap_or(Err(BackupError::Damaged("the drill stopped".into()))); + self.note_locks(); match drilled { + // Stopped by a close (INVARIANT 11): neither a pass nor a + // failure, so nothing is said of the target; the drill is + // due again when the books next open. + Err(BackupError::Cancelled(_)) => {} Ok(head) => { self.record(json!({"kind": "drill", "target": n.target.kind(), "at": n.at, "key": n.key, "ok": true, "head": {"seq": head.0, "hash": head.1}})) diff --git a/crates/ledger-mcp/src/local.rs b/crates/ledger-mcp/src/local.rs index 082beb2a..0008bb71 100644 --- a/crates/ledger-mcp/src/local.rs +++ b/crates/ledger-mcp/src/local.rs @@ -86,6 +86,31 @@ //! door shut and the book listed closed from the start: a call that //! comes while the restore runs is told the books aren't open (503, //! INVARIANT 11), never that there are no such books. +//! The close is bounded, from its start, by the sum of these named, +//! finite parts and nothing else: +//! a. T_calls: the longest of the calls already running with their +//! whole body (none is cut or killed; each is local work on the +//! book, and nothing a client does lengthens it); +//! b. ANSWER_GRACE for the answers on their way out, counted from +//! when the door is empty (the cut of a body not yet whole is at +//! ANSWER_GRACE from the START of the close, inside (a): a +//! stalled client adds nothing); +//! c. T_stop for each step the close doesn't wait for, a drill or a +//! format upgrade not yet journaled, which are hurried at the +//! start (`Backups::hurry`) and stop at their next look: one git +//! kill (GROUP_GONE_WAIT, 2 s, and its pipes, 10 s at most, and +//! for a target on this computer LOCK_SETTLE, 1.5 s), or one +//! journal line, one file or one 64 KiB chunk, and the removal +//! of the step's scratch clone (as long as the clone is big); +//! a format upgrade whose `journal.format_set` line has been +//! appended is not stopped, it finishes (a line and a database +//! row: part of (a)); +//! d. BACKUP_AT_CLOSE for the last backup; +//! e. T_stop again for what is left of that backup at its bound +//! (`Backups::shut`: git killed, every step awaited); +//! f. closing the logs and letting go of the store (instant). +//! A drill (or a format upgrade) that took the backups' turn never +//! costs the last backup its time. //! 11. A call for a book that exists but is closed is told apart from one //! that does not exist, on the MCP, upload, download and export //! routes: 503, `x-wanderbooks-refused: closed`, and the words `The @@ -144,7 +169,19 @@ //! fails with an error before anything else), and the handler checks //! for the cut again before it binds a session. This holds for a //! book's close, for a restore over an open book (both are -//! `Books::release`) and for the server's close. +//! `Books::release`) and for the server's close, which is the same +//! path: at the start of the server's close (not after its admin +//! jobs, store closes or backups) every open book's door is shut and +//! its cut set for one grace from that moment, then every book still +//! open is released as a close of one book releases it, together +//! (so one book's slow backup holds no other's, each book's bound +//! being INVARIANT 10's), its gate, sessions, logs, uploads, exports, +//! backups and store all closed; only the HTTP side's end and the +//! linger (a request that set out before its client heard of the +//! close still meets a refusal, LINGER, 3 s at most) come after. A +//! request that arrives once the server is closing and finds a book's +//! door shut is refused as closing (503, `closing`), not recorded: +//! the door is shut (INVARIANT 11), as in a close of one book. //! SCENARIOS: //! 1. Two books open; one is closed while agents call both: the other //! answers throughout, the closed one's calls are refused unrun @@ -174,7 +211,19 @@ //! half way, and the book is closed: the close waits the grace, cuts //! both (no part file, nothing journaled, the records say cut), and //! answers closed. An upload still coming within the grace, and a -//! call running past it, are not cut. +//! call running past it, are not cut; an upload that keeps coming, +//! steadily, past the grace is cut. +//! 10. A drill is slow (a large book): the book is closed, the drill is +//! stopped at its next look and its clone removed, the last backup is +//! made, and the close is answered within INVARIANT 10's bound. A +//! format upgrade not yet journaled is stopped the same way, the books +//! unchanged. +//! 11. A backup's git is killed inside a commit or a push: the locks it +//! left are removed before the close is answered, each recorded; the +//! book opened again backs up at once. +//! 12. The server is closed (standard input ends) with an upload stalled +//! on one book and a call's body stalled on another: both are cut one +//! grace after the close began, the server exits 0 within its bound. //! ``` use crate::admin::{self, Request, Response}; @@ -246,6 +295,15 @@ pub(crate) struct Timers { backup_at_close: Duration, /// How long a close waits for answers on their way out. answer_grace: Duration, + /// A test knob (`--slow-steps`): each phase of a drill or format + /// upgrade waits this long, so these can be long (backup.rs). + slow_steps: Duration, + /// A test knob (`--timer-hold`): a timer that has taken a book's + /// handles waits, before it acts on them, while the file `timer-hold` + /// in the root's `run/` names it (`sweep`, `backup`, `drill`), saying + /// which timer it is in `run/timer-held` as it comes to wait (see + /// [`Books::timer_hold`]). + timer_hold: bool, } impl Default for Timers { @@ -256,6 +314,8 @@ impl Default for Timers { drill_look: DRILL_LOOK, backup_at_close: BACKUP_AT_CLOSE, answer_grace: ANSWER_GRACE, + slow_steps: Duration::ZERO, + timer_hold: false, } } } @@ -355,6 +415,21 @@ struct Parts { ended: CancellationToken, } +/// `wait`, or None once `hurry` (a second signal to close: stop waiting) +/// is cancelled; without a `hurry`, `wait` alone. +async fn unless_hurried( + hurry: Option<&CancellationToken>, + wait: impl std::future::Future, +) -> Option { + match hurry { + Some(hurry) => tokio::select! { + out = wait => Some(out), + () = hurry.cancelled() => None, + }, + None => Some(wait.await), + } +} + /// One book's door (INVARIANT 10): requests are counted as they enter, and /// once shut none enters. A close shuts it, then waits for the count to /// reach zero: every request that got in has finished, its record written. @@ -641,6 +716,37 @@ impl Books { self } + /// The test knob `--timer-hold`: `timer` has taken the handles of a + /// book and is about to act on them. It says so (a line in + /// `run/timer-held`) and waits until `run/timer-hold` is gone, so a + /// test can close the book in between. Nothing without the knob. + async fn timer_hold(&self, timer: &str) { + if !self.timers.timer_hold { + return; + } + let Ok(run) = self.root.run_dir() else { + return; + }; + { + use std::io::Write; + if let Ok(mut said) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(run.join("timer-held")) + { + let _ = writeln!(said, "{timer}"); + } + } + // Held while the file names this timer (a list, comma-separated). + let held = || { + std::fs::read_to_string(run.join("timer-hold")) + .is_ok_and(|names| names.split(',').any(|n| n.trim() == timer)) + }; + while held() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + } + /// Take the root's path out of a message (INVARIANT 7). fn hide(&self, text: impl Into) -> String { let mut text = text.into(); @@ -769,6 +875,7 @@ impl Books { board, .. } = served; + backups.slow_steps(self.timers.slow_steps); Ok(Book::Open { gate: Arc::default(), ended, @@ -784,17 +891,6 @@ impl Books { }) } - /// Every open book's store. - fn stores(&self) -> Vec> { - self.held() - .values() - .filter_map(|b| match b { - Book::Open { store, .. } => Some(store.clone()), - Book::Failed(_) | Book::Closed => None, - }) - .collect() - } - fn held(&self) -> std::sync::RwLockReadGuard<'_, BTreeMap> { self.held.read().unwrap_or_else(|e| e.into_inner()) } @@ -1306,7 +1402,7 @@ impl Books { // No new call gets in; the book is listed closed. parts.gate.shut(); self.hold(&id, Book::Closed); - let backup = self.release(&rt, &id, &parts, true); + let backup = rt.block_on(self.release(&id, &parts, true, Instant::now(), None)); eprintln!("wanderbooks server: the books {id} were closed"); said(match backup { None => admin::CloseOutcome::Closed, @@ -1338,12 +1434,13 @@ impl Books { /// 5. the access log, uploads and exports close, each under the lock /// its own writes go in under, so a late writer is refused; /// 6. the store is let go, its writer lock released. - fn release( + async fn release( &self, - rt: &tokio::runtime::Handle, id: &BookId, parts: &Parts, last_backup: bool, + begun: Instant, + hurry: Option<&CancellationToken>, ) -> Option { let Parts { gate, @@ -1354,57 +1451,58 @@ impl Books { backups, ended, } = parts; + // The steps of the backups a close doesn't wait for (a drill, a + // format upgrade not yet journaled) stop now, so none holds the + // store's tools or the backups' turn while the close waits for + // what it does wait for (INVARIANT 10). + backups.hurry(); // No tool starts, and every one that did start has finished. A // request that has begun and isn't whole when the grace runs out - // is cut, so one that never finishes sending can't hold the book; - // a call whose body is whole and that is running is left to end. - rt.block_on(async { - let cutter = { - let (gate, grace) = (gate.clone(), self.timers.answer_grace); - tokio::spawn(async move { - tokio::time::sleep(grace).await; - gate.cut_unfinished(); - }) - }; - store.close().await; - gate.emptied().await; - cutter.abort(); - }); - if rt - .block_on(tokio::time::timeout( - self.timers.answer_grace, - gate.answered(), - )) - .is_err() - { + // (counted from `begun`, the start of the close) is cut, so one + // that never finishes sending can't hold the book; a call whose + // body is whole and that is running is left to end. + let cutter = { + let (gate, at) = (gate.clone(), begun + self.timers.answer_grace); + tokio::spawn(async move { + tokio::time::sleep_until(at.into()).await; + gate.cut_unfinished(); + }) + }; + store.close().await; + unless_hurried(hurry, gate.emptied()).await; + cutter.abort(); + let answered = unless_hurried( + hurry, + tokio::time::timeout(self.timers.answer_grace, gate.answered()), + ) + .await; + if matches!(answered, Some(Err(_))) { eprintln!( "wanderbooks server: a client didn't take its answer; closing the books {id} without it" ); } self.end_sessions(id, ended); - let problem = last_backup - .then(|| { - let made = rt.block_on(tokio::time::timeout( - self.timers.backup_at_close, - backups.run("close"), - )); - match made { - Ok(Ok(status)) => backup_incomplete(&status), - Ok(Err(why)) => Some(why), - Err(_) => Some(format!( - "it took longer than {} seconds, and was stopped", - self.timers.backup_at_close.as_secs().max(1) - )), - } - }) - .flatten(); + let problem = if last_backup && !hurry.is_some_and(CancellationToken::is_cancelled) { + let made = tokio::time::timeout(self.timers.backup_at_close, backups.run("close")); + match unless_hurried(hurry, made).await { + Some(Ok(Ok(status))) => backup_incomplete(&status), + Some(Ok(Err(why))) => Some(why), + Some(Err(_)) => Some(format!( + "it took longer than {} seconds, and was stopped", + self.timers.backup_at_close.as_secs().max(1) + )), + None => None, + } + } else { + None + }; // A run still going is stopped, and waited for: nothing of the // backups runs once this returns. - rt.block_on(backups.shut()); + backups.shut().await; access.close(); uploads.close(); exports.close(); - rt.block_on(store.let_go()); + store.let_go().await; problem.map(|why| self.hide(why)) } @@ -1572,7 +1670,7 @@ impl Books { let rt = tokio::runtime::Handle::current(); parts.gate.shut(); self.hold(&id, Book::Closed); - self.release(&rt, &id, &parts, false); + rt.block_on(self.release(&id, &parts, false, Instant::now(), None)); } match self.root.restore(&git, &source, &id, &expect_head, replace) { Ok(r) => { @@ -1931,6 +2029,7 @@ async fn door( Some(Book::Open { gate, .. }) => Some(gate.enter()), _ => None, }; + let shut_door = matches!(entered, Some(None)); let (found, inside) = match entered { Some(Some(inside)) => (found, Some(inside)), Some(None) => (Some(Book::Closed), None), @@ -1969,12 +2068,21 @@ async fn door( } Some(b @ Book::Open { .. }) => b, _ => { - return Err(( + let mut response = ( StatusCode::SERVICE_UNAVAILABLE, "the books are closing: this request wasn't run", ) - .into_response() - .into()); + .into_response(); + // The server is closing and this book's door is already shut + // (INVARIANT 15): the same refusal, as a client knows it, as + // one at an open door (not recorded: the door is shut). + if shut_door { + response.headers_mut().insert( + REFUSED_HEADER, + axum::http::HeaderValue::from_static(crate::access::CLOSING), + ); + } + return Err(response.into()); } }; let Some(inside) = inside else { @@ -2773,6 +2881,19 @@ pub fn run( .ok_or("--answer-grace needs milliseconds")?; timers.answer_grace = Duration::from_millis(ms); } + // Make a drill or a format upgrade slow, as a large book makes + // them (tests): each phase waits this long, or until the close + // hurries it. + "--slow-steps" => { + let ms: u64 = args + .next() + .and_then(|v| v.parse().ok()) + .ok_or("--slow-steps needs milliseconds")?; + timers.slow_steps = Duration::from_millis(ms); + } + // A timer waits between taking a book's handles and acting on + // them, while `run/timer-hold` exists (tests). + "--timer-hold" => timers.timer_hold = true, "--help" | "-h" => { print_usage(prog); return Ok(()); @@ -2967,16 +3088,26 @@ async fn serve( tokio::select! { () = sweep_stop.cancelled() => break, _ = tick.tick() => { - let held: Vec<_> = sweeping + let handles: Vec<_> = sweeping .held() .values() .filter_map(|b| match b { - Book::Open { uploads, exports, gate, .. } => gate - .enter() - .map(|inside| (uploads.clone(), exports.clone(), inside)), + Book::Open { uploads, exports, gate, .. } => { + Some((uploads.clone(), exports.clone(), gate.clone())) + } Book::Failed(_) | Book::Closed => None, }) .collect(); + if !handles.is_empty() { + sweeping.timer_hold("sweep").await; + } + // Inside each book's door, entered only now: a book + // that closed since the handles were taken is skipped + // (and its handles are closed, whatever this does). + let held: Vec<_> = handles + .into_iter() + .filter_map(|(u, x, gate)| gate.enter().map(|inside| (u, x, inside))) + .collect(); let now = chrono::Utc::now().timestamp(); let _ = tokio::task::spawn_blocking(move || { for (u, x, _inside) in &held { @@ -3021,65 +3152,63 @@ async fn serve( } drop(admin_listener); eprintln!("wanderbooks server: closing"); - // INVARIANT 6. New requests are refused from here on. + // INVARIANT 6. New requests are refused from here on, and (INVARIANT + // 15) every book's door is shut and the cut of what hasn't finished + // arriving is set for one grace from now, at the start: the one thing + // a stalled client may not do is hold the close, whatever else the + // close is waiting for (an admin job, a slow backup of another book). books.closing.cancel(); - // Admin work under way (a create, an adoption) finishes. - admin_jobs.close(); - admin_jobs.wait().await; - // Every request already running finishes its work, however long it - // takes and whether or not its client is still there: a store is - // never let go of mid-write (SharedStore INVARIANT 3). - for store in books.stores() { - store.close().await; - } - // A last backup of what was written since the last one, for a while - // at most: the books are closing, nothing more is written. The loop - // stops at its next step (`stop`); a run of its still under way - // finishes first (each book runs one at a time). - drop(backup_loop); - let held: Vec> = books - .held() - .values() - .filter_map(|b| match b { - Book::Open { backups, .. } => Some(backups.clone()), - Book::Failed(_) | Book::Closed => None, + let begun = Instant::now(); + let cutters: Vec<_> = books + .gates() + .into_iter() + .map(|gate| { + gate.shut(); + let at = begun + books.timers.answer_grace; + tokio::spawn(async move { + tokio::time::sleep_until(at.into()).await; + gate.cut_unfinished(); + }) }) .collect(); - for b in held { - let _ = tokio::time::timeout(books.timers.backup_at_close, b.run("close")).await; - // A run that didn't end in time is stopped, not left to outlive - // the server (git keeps its own process group): and waited for. - b.shut().await; - } - // Answers on their way out are sent, for a while: a client sending - // a request it never finishes doesn't hold the books open. - let answers = async { - loop { - let notified = books.finished.notified(); - if books.in_flight.load(Ordering::SeqCst) == 0 { - break; - } - notified.await; + // Admin work under way (a create, an adoption, a close of one book) + // finishes. + admin_jobs.close(); + admin_jobs.wait().await; + drop(backup_loop); + // Every book still open is let go the way a close of one book lets go + // of it (`Books::release`: INVARIANT 10, the one closing path): its + // tools finish, however long they take and whether or not their client + // is still there (a store is never let go of mid-write, SharedStore + // INVARIANT 3), the answers on their way out are sent, a request not + // whole at the grace is cut, its sessions end, its last backup is made + // for BACKUP_AT_CLOSE at most, and its logs, uploads, exports, backups + // and store are closed. The books are let go together: one slow + // backup doesn't hold the others' (each book's own bound is the same). + let open: Vec<(BookId, Parts)> = { + let _one = books.lifecycle.lock().unwrap_or_else(|e| e.into_inner()); + let open: Vec<(BookId, Parts)> = books + .held() + .iter() + .filter_map(|(id, b)| Some((BookId::parse(id).ok()?, b.parts()?))) + .collect(); + for (id, _) in &open { + books.hold(id, Book::Closed); } + open }; - tokio::select! { - () = answers => {} - () = tokio::time::sleep(books.timers.answer_grace) => { - eprintln!("wanderbooks server: a client didn't finish its request; closing without it"); + let released = futures_util::future::join_all( + open.iter() + .map(|(id, parts)| books.release(id, parts, true, begun, Some(&stops.hurry))), + ) + .await; + for ((id, _), problem) in open.iter().zip(released) { + if let Some(why) = problem { + eprintln!("wanderbooks server: the last backup of the books {id} wasn't whole: {why}"); } - () = stops.hurry.cancelled() => {} } - // A request that began and still isn't whole is cut, whatever it had - // written removed and its record saying so; a call whose body is whole - // has finished already (the stores were closed above). - let gates = books.gates(); - for gate in &gates { - gate.cut_unfinished(); - } - tokio::select! { - () = async { for gate in &gates { gate.emptied().await } } => {} - () = tokio::time::sleep(HTTP_GRACE) => {} - () = stops.hurry.cancelled() => {} + for cutter in cutters { + cutter.abort(); } books.sessions.cancel(); // A call that set out just before its client heard of the close still @@ -3327,6 +3456,7 @@ async fn keep_backed_up(books: Arc, stop: CancellationToken) { s.moved_at = now; } if let Some(why) = due { + books.timer_hold("backup").await; let outcome = backups .run(why) .await @@ -3341,6 +3471,7 @@ async fn keep_backed_up(books: Arc, stop: CancellationToken) { if drill_look_due(s, now) { s.drill_next = now + books.timers.drill_look; if backups.drill_due().await { + books.timer_hold("drill").await; backups.drill().await; } } @@ -4544,6 +4675,113 @@ mod tests { /// INVARIANT 10: a close answers only once the requests already inside /// the book's door have left; a request arriving meanwhile is /// refused at once (as closed), and another book is not held up. + /// INVARIANT 10: a close stops a format upgrade that has not yet + /// journaled its `journal.format_set` line, instead of waiting for it + /// (the upgrade is counted by the store's close): the upgrade says it + /// was not done, the books are byte for byte as they were, and the + /// close is answered. The upgrade is held in its backup's proof by the + /// test knob that makes each phase wait a minute. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_close_stops_a_format_upgrade_before_it_is_journaled() { + let home = tempfile::tempdir().unwrap(); + let (root, _) = Root::setup(home.path(), Some(&home.path().join("root")), None).unwrap(); + let books = Arc::new( + Books::new(root, BACKUP_QUIET, DRILL_FIRST, Isolation::SameUser).with_timers(Timers { + slow_steps: Duration::from_secs(60), + answer_grace: Duration::from_millis(300), + ..Timers::default() + }), + ); + let loaded = books.load_principals(); + *books.principals.write().unwrap() = loaded; + let dir = old_books(&books, "acme"); + let auth = books.root.auth_dir().unwrap(); + ledger_store::passphrase::set(&auth, PASS, None).unwrap(); + let journal = || std::fs::read(dir.join(ledger_store::JOURNAL_FILE)).unwrap(); + let before = journal(); + let backups = match books.held().get("acme") { + Some(Book::Open { backups, .. }) => backups.clone(), + _ => panic!("acme isn't open"), + }; + let upgrading = tokio::spawn({ + let books = books.clone(); + async move { upgrade(&books, "acme", PASS).await } + }); + // It is inside the proof of its backup, waiting. + let by = Instant::now() + Duration::from_secs(60); + while backups.pauses_begun() == 0 { + assert!(Instant::now() < by, "the upgrade never reached its proof"); + tokio::time::sleep(Duration::from_millis(20)).await; + } + let started = Instant::now(); + let closed = ask(&books, Request::CloseBook { id: "acme".into() }).await; + assert!( + started.elapsed() < Duration::from_secs(20), + "held by the upgrade" + ); + assert!( + matches!( + closed, + Response::CloseBook { + outcome: admin::CloseOutcome::Closed + | admin::CloseOutcome::ClosedBackupIncomplete(_), + .. + } + ), + "{closed:?}" + ); + match upgrading.await.unwrap() { + Response::Refused(why) => assert!(why.contains("nothing was upgraded"), "{why}"), + other => panic!("{other:?}"), + } + assert_eq!( + journal(), + before, + "an upgrade stopped by a close changed the books" + ); + } + + /// INVARIANT 15: a body read to its end is whole and never cut, + /// whatever follows (the cut firing, the body polled again); one not + /// read to its end when the cut fires is cut at once, however much of + /// it has come. + #[tokio::test] + async fn a_body_read_to_its_end_is_never_cut_and_one_not_yet_is() { + use futures_util::StreamExt; + let gate = Arc::new(Gate::default()); + // Whole: every byte read to the end, then the cut. + let inside = gate.enter().unwrap(); + let (tx, body) = fed(); + let (request, whole) = inside.arriving(axum::extract::Request::new(body)); + let mut data = request.into_body().into_data_stream(); + tx.send(vec![1, 2, 3]).await.unwrap(); + assert_eq!(data.next().await.unwrap().unwrap().len(), 3); + drop(tx); + assert!(data.next().await.is_none()); + gate.cut_unfinished(); + assert!(!whole.was_cut(), "a body read to its end was cut"); + // Asked again after the cut: still the end, not a cut. + assert!(data.next().await.is_none()); + assert!(!whole.was_cut()); + drop(inside); + // Not whole: part of it came, the cut fires, the next read fails + // (a gate's cut is for good: this is another book's). + let gate = Arc::new(Gate::default()); + let inside = gate.enter().unwrap(); + let (tx, body) = fed(); + let (request, partial) = inside.arriving(axum::extract::Request::new(body)); + let mut data = request.into_body().into_data_stream(); + tx.send(vec![1, 2, 3]).await.unwrap(); + assert!(data.next().await.unwrap().is_ok()); + assert!(!partial.was_cut()); + gate.cut_unfinished(); + // More bytes are on their way, however quickly: cut all the same. + let _ = tx.try_send(vec![4, 5, 6]); + assert!(data.next().await.unwrap().is_err()); + assert!(partial.was_cut()); + drop(inside); + } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_close_waits_for_the_requests_inside_and_refuses_the_next() { let home = tempfile::tempdir().unwrap(); diff --git a/docs/mcp-interface.md b/docs/mcp-interface.md index 7f7f5cce..d0c7c943 100644 --- a/docs/mcp-interface.md +++ b/docs/mcp-interface.md @@ -370,9 +370,19 @@ didn't open, with why). Protocol version 1: the requests are new, the finishes; its MCP sessions end (an agent's next request on one gets the "isn't open" words above, and after a reopening a 404 "Session not found", which a client takes as "open a new one"); its - last backup is made, as at the server's close, for 60 seconds at most: + last backup is made, as at the server's close, for 60 seconds at most + (a drill, or a format upgrade not yet journaled, is stopped when the + close begins, at its next look, so it never takes the last backup's + turn; its scratch clone is removed and the books are unchanged): a backup still running after that is stopped (git is killed with all it - started) and waited for to end; then nothing of the server's can write + started, and any lock file it left, in the book's archive and in a + folder target on this computer, is removed and recorded in + `ops/backup.jsonl` as `lock_removed`; a lock that was there before the + push began is never touched, `lock_left`) and waited for to end; + the close is bounded by the sum written in the server's INVARIANT 10 + (`local.rs`: running calls, the grace, the answers' grace, the stop of a + hurried step, the last backup's 60 s, the stop of what is left of it); + then nothing of the server's can write to the book: its access log, uploads, exports and backups are closed under the locks their writes go in under, so a handle held from before can never write after a reopening; its store is let go, releasing the @@ -398,6 +408,13 @@ didn't open, with why). Protocol version 1: the requests are new, the listed closed from the moment the restore begins, so a call that comes meanwhile is told the books aren't open (503, as in a close), never that there are no such books (404). +- **The server's own close** (its standard input ends, or SIGTERM) is the + same path for every open book at once: at its start every book's door + is shut and the cut (above) is set for 10 seconds from that moment; each + book is then released as `close_book` releases it. The server exits 0 + once they are all closed (and the HTTP side has ended); a request that + arrives meanwhile is refused as closing (503) and not recorded, the + door being shut. - `sessions` lists, for each open book, its live MCP sessions: the token's **name** (never the token, its text or its hash), the client's name and version from `initialize`, the agent's self-report (`books.start`'s diff --git a/docs/testing.md b/docs/testing.md index 63d31609..64839b72 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -4321,7 +4321,16 @@ one book never refuses or holds up a call on another. | `book_open_close::a_restore_over_an_open_book_is_not_held_by_a_stalled_upload` | a restore over an open book with an upload stalled half way: the upload is cut after the grace, no part file in `legacy/`, the replaced book's log records `cut_by_close`, the restore is answered | | `book_open_close::a_restore_over_an_open_book_waits_for_what_is_inside_it` | (extended) every call while the restore waits for a half-received upload gets 503 and the closed words, never 404 `no such books` (fails when the restore takes the book out of the list before it shuts the door) | | `ledger-store` `uploads::tests::a_close_in_the_middle_of_a_file_stops_it_at_the_next_chunk`, `uploads::tests::a_close_between_the_last_byte_and_the_rename_keeps_nothing`, `exports::tests::a_close_waits_for_a_fetch_that_is_reading` | the types' own claims (INVARIANT 6 of uploads, 5 of exports): a close in the middle of a file stops it at the next chunk (no read after, no part left), a close between the last byte and the rename keeps nothing, and a fetch reads under the lock a close takes (a named pipe holds it inside its read; `close` must not return); each fails with its guard removed | -| `book_open_close::a_slow_upload_that_finishes_within_the_grace_is_not_cut` | an upload dripping in over ~600 ms with a 2.5 s grace is kept and answered 200, nothing cut | +| `book_open_close::a_slow_upload_that_finishes_within_the_grace_is_not_cut` | (made deterministic) the grace is a minute and the rest of the bytes go only after the book is listed closed: the cut waits for the grace (fails with the cut set to fire at once) | +| `book_open_close::an_upload_still_arriving_when_the_grace_runs_out_is_cut_however_active_it_is` | the mirror: a client sending 8 KB every 25 ms (not stalled) of a 3 MB body with a 600 ms grace is cut (`cut_by_close`, no part, no bytes kept) and the close answered; driven by the client's condition (it sends until the connection is closed), fails with the cut removed | +| `book_open_close::the_servers_own_close_cuts_stalled_requests_and_exits_zero_in_time` | one upload stalled on one book and one MCP body stalled on another, the server's stdin closed: exit code 0 within the bound, both cut after the grace, no part file, nothing journaled, two `cut_by_close` records, every log whole | +| `book_open_close::a_backup_and_a_sweep_that_took_their_handles_before_a_close_do_nothing_after_it`, `…a_drill_and_a_sweep…` | `--timer-hold` holds a timer between taking a book's handles and acting; the book is closed meanwhile, stray files planted, the timers go on: the closed book's tree doesn't move; opened again the sweep works (fail with the handles' closed state, the gate's check and the backups' shut flag removed) | +| `book_open_close::a_close_stops_a_slow_drill_instead_of_waiting_for_it` | `--slow-steps` makes each phase of a drill wait a minute: the close answers plain `closed` (the last backup was made), within the stated sum, with the drill's scratch clone removed (fails without `hurry`: `closed_backup_incomplete`) | +| `book_open_close::a_close_that_stops_git_in_a_commit_or_a_push_leaves_no_lock_and_the_next_backup_succeeds` | REAL git (a wrapper that points git's hooks at a `reference-transaction` hook that waits) killed inside `init`, a commit and a push to a folder by a close: no lock left in the archive or the folder before the close is answered, each recorded, the reopened book backs up with no step by hand, `git fsck --strict` passes on both | +| `local::tests::a_close_stops_a_format_upgrade_before_it_is_journaled` | an upgrade held in its backup's proof: the close stops it, it says nothing was upgraded, the journal is byte for byte as before | +| `local::tests::a_body_read_to_its_end_is_never_cut_and_one_not_yet_is` | the line of the cut: a body read to its end is never cut (the cut firing, the body asked again), one not read to its end is cut even with bytes on the way | +| `ledger-store` `backup::tests::a_git_killed_mid_commit_…`, `…_mid_add_…`, `…_mid_push_…`, `locks_found_in_the_archive_when_the_books_open_…` | real git killed inside a commit (HEAD and ref locks), an add (the index lock) and a push to a folder (the target's ref lock): locks removed once the group is gone, noted; a lock that was in the target before the push is never removed, and the target's lock is removed only after LOCK_SETTLE; next backup succeeds, `git fsck` passes; the archive's locks are cleared at open | +| `ledger-store` `backup::tests::a_drill_stops_inside_the_phase_it_is_told_to_stop_in` | for each phase (clone, replay, verify, blobs, prefix) a stop set as the phase begins ends the drill inside it (the observer sees no later phase), scratch removed; each case fails when the loop's looks inside that phase are removed | | `book_open_close::a_running_call_is_never_cut_when_the_grace_runs_out` | `books.back_up_now` held in a stalled `git` past the grace (body whole) is not cut: it finishes, is answered and recorded `ok`, and then the close is answered | | `book_open_close::a_call_whose_answer_was_never_read_is_on_record_as_having_run` | a journaled draft whose client goes without reading: after the close the access log has its record, outcome `ok`, with the head it wrote (INVARIANT 14: a retry isn't made safe by anything; the record says it ran) | | `book_open_close::a_close_is_not_answered_while_its_backup_still_runs` | a book with a folder target and a stand-in `git` on the server's PATH that waits: the close isn't answered before its backup bound (1.2 s), then answers `closed_backup_incomplete`, git and all it started are gone, and lifting the stall makes nothing resume; the reopened book's backup record is a whole chain and it backs up (fails when `shut` is removed: git still runs after the answer) |