diff --git a/crates/ledger-cli/tests/book_open_close.rs b/crates/ledger-cli/tests/book_open_close.rs index 51b796d8..08b358ed 100644 --- a/crates/ledger-cli/tests/book_open_close.rs +++ b/crates/ledger-cli/tests/book_open_close.rs @@ -382,7 +382,10 @@ fn agent( /// replayed and checked: every acknowledged draft is in its book's journal /// exactly once, no refused call left anything, a closed book's journal /// and access log never moved between its close answer and its reopening, -/// and no call on the other book was ever refused. +/// and no call on the other book was ever refused. Meanwhile admin jobs on +/// other books (a third book closed and opened over and over, new books made) +/// are all done and none is ever stopped, refused or told of an error by the +/// closings (local.rs INVARIANT 10). #[test] fn closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing() { const CYCLES: usize = 12; @@ -405,6 +408,7 @@ fn closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing() { ); home.create(A, "USD"); home.create(B, "USD"); + home.create("cedar", "USD"); let disk = home.dir.path().join("disk"); std::fs::create_dir_all(&disk).unwrap(); { @@ -414,6 +418,46 @@ fn closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing() { w.end(); } let stop = Arc::new(AtomicBool::new(false)); + // Admin jobs on other books, while the hammered one is closed and opened: + // a third book closed and opened over and over, and new books made. Every + // one is done as asked; what isn't is said here. + let spared = Arc::new(Mutex::new((0usize, Vec::::new()))); + let maker = { + let (home, stop, spared) = (home.clone(), stop.clone(), spared.clone()); + std::thread::spawn(move || { + let mut made = 0; + while !stop.load(Ordering::SeqCst) { + let mut said = Vec::new(); + if made < 8 { + made += 1; + match home.admin(Request::Create { + id: format!("made-{made}"), + currency: "USD".into(), + }) { + Response::Created { problem: None, .. } => {} + other => said.push(format!("create: {other:?}")), + } + } + match home.admin(Request::CloseBook { id: "cedar".into() }) { + Response::CloseBook { + outcome: CloseOutcome::Closed, + .. + } => {} + other => said.push(format!("close: {other:?}")), + } + match home.admin(Request::OpenBook { id: "cedar".into() }) { + Response::OpenBook { + outcome: OpenOutcome::Opened, + .. + } => {} + other => said.push(format!("open: {other:?}")), + } + let mut spared = spared.lock().unwrap(); + spared.0 += 1; + spared.1.extend(said); + } + }) + }; let done = Arc::new(Mutex::new(Vec::new())); let reads = Arc::new([AtomicUsize::new(0), AtomicUsize::new(0)]); let mut agents = Vec::new(); @@ -488,6 +532,16 @@ fn closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing() { for a in agents.into_iter().chain(refusers) { a.join().unwrap(); } + maker.join().unwrap(); + { + let spared = spared.lock().unwrap(); + assert!(spared.0 > 0, "no admin job ran on the other books"); + assert_eq!( + spared.1, + Vec::::new(), + "a close of {A} stopped or refused a job on another book" + ); + } assert!(server.close().success()); // Every log is a whole chain after all those closings. access_of(&home, A); @@ -2790,6 +2844,140 @@ fn a_close_stops_a_running_verification_and_a_running_package_and_says_so() { assert!(server.close().success()); } +/// How many decisions the journal of `id` holds. +#[cfg(unix)] +fn decisions_of(home: &Home, id: &str) -> usize { + files_of(home, id) + .0 + .iter() + .filter(|l| l.line_type == "decision.recorded") + .count() +} + +/// A package that goes with a decision (a reason to export with drafts open +/// or without an audit) is journaled ahead of its build, because the package +/// counts the decision (its README and every footer carry the journal's +/// event count at the build), so the decision may be on record only for a +/// package that is made: a close that begins before the decision is journaled +/// stops the package, and nothing is journaled; one that begins after it +/// doesn't stop it, and the package is handed over whole (tools/reports.rs +/// `export_cpa_package` INVARIANT 4, local.rs INVARIANT 10). The first call is +/// held as it begins and the second right after its decision is journaled, by +/// the server's test knob (`--timer-hold`), which the close's start releases. +#[cfg(unix)] +#[test] +fn a_close_never_leaves_a_decision_on_record_for_a_package_that_was_not_made() { + let home = Home::new("close-package-decision"); + let server = Server::start_with( + &home, + &[ + "--timer-hold", + "--timers", + "20", + "--backup-quiet", + "3600000", + ], + ); + home.create(A, "USD"); + let run = home.run(); + let args = json!({ + "cash_accounts": ["1000"], + "allow_open_drafts": {"reason": "the CPA wants it before the receipt comes"} + }); + let seen = |name: &str| { + std::fs::read_to_string(run.join("timer-held")) + .unwrap_or_default() + .lines() + .any(|l| l == name) + }; + let mut w = Wire::new(&home, A); + w.initialize("owner"); + let r = w.call( + "books.add_account", + json!({"code": "1000", "name": "Bank", "account_type": "asset"}), + ); + assert_eq!(r["result"]["isError"], json!(false), "{r}"); + draft(&mut w, "still open"); + // 1. The close begins before the decision is journaled. + let at_start = "call:books.export_cpa_package"; + std::fs::write(run.join("timer-hold"), at_start).unwrap(); + let mut package = call_unanswered(&home, &w, 7, "books.export_cpa_package", args.clone()); + wait_for("the package is held", Duration::from_secs(60), || { + seen(at_start) + }); + let started = std::time::Instant::now(); + assert_eq!(decisions_of(&home, A), 0); + let closing = admin_in_thread(&home, Request::CloseBook { id: A.into() }); + let (status, said) = package.answer(); + assert_eq!(status, 200, "{said}"); + assert!( + said.contains("stopped because the books are closing"), + "{said}" + ); + assert_eq!( + finished("the close", closing), + Response::CloseBook { + id: A.into(), + outcome: CloseOutcome::Closed + } + ); + assert!(started.elapsed() < NEVER_LONGER); + assert_eq!( + decisions_of(&home, A), + 0, + "a decision is on record for a package that was stopped" + ); + let stopped = access_of(&home, A) + .into_iter() + .find(|r| r.access.subject == "books.export_cpa_package") + .expect("the call is on record"); + assert_eq!( + stopped.access.result, + ledger_store::access::Outcome::Refused("stopped_by_close".into()) + ); + // 2. The close begins after it: the package is made all the same. + std::fs::remove_file(run.join("timer-hold")).unwrap(); + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + let after = "call:books.export_cpa_package:journaled"; + std::fs::write(run.join("timer-hold"), after).unwrap(); + let mut w = Wire::new(&home, A); + w.initialize("owner"); + let mut package = call_unanswered(&home, &w, 8, "books.export_cpa_package", args); + wait_for( + "the package is held after its decision", + Duration::from_secs(60), + || seen(after), + ); + assert_eq!( + decisions_of(&home, A), + 1, + "the decision isn't journaled yet" + ); + let closing = admin_in_thread(&home, Request::CloseBook { id: A.into() }); + let (status, said) = package.answer(); + assert_eq!(status, 200, "{said}"); + assert!( + !said.contains("stopped because the books are closing") && said.contains("download"), + "a package with its decision journaled was stopped by a close: {said}" + ); + assert_eq!( + finished("the close", closing), + Response::CloseBook { + id: A.into(), + outcome: CloseOutcome::Closed + } + ); + assert_eq!(decisions_of(&home, A), 1); + let made = access_of(&home, A) + .into_iter() + .rev() + .find(|r| r.access.subject == "books.export_cpa_package") + .expect("the call is on record"); + assert_eq!(made.access.result, ledger_store::access::Outcome::Ok); + std::fs::remove_file(run.join("timer-hold")).unwrap(); + assert!(server.close().success()); +} + /// The files of `books/` byte for byte (the staging and scratch folders /// among them), but for the books in `live`: those the server has open and /// works on by itself (its timers write their archives and logs). @@ -2801,88 +2989,255 @@ fn root_without(home: &Home, live: &[&str]) -> BTreeMap { .collect() } -/// A job on the admin socket (restore, adopt, create, open) that is running -/// when a close of another book begins is stopped by it, before its point of -/// no return: it answers that it was stopped because the books are closing, -/// what it wrote is removed, and the root is byte for byte as it was (the -/// job's staging or scratch folder is there while it is held, and gone after; -/// asked again with no close, it goes through). Each job is held inside a -/// phase by the server's test knob (`--timer-hold`, `job:phase`), which the -/// close's start releases; the stop is then at the job's next look. +/// The jobs on the admin socket that can run long (restore, adopt, create, +/// open), each held inside a phase by the server's test knob (`--timer-hold`, +/// `job:phase`) until the name is gone or a stop is asked. Returns, for each, +/// the request, the held name, what it says it didn't do, and whether it +/// leaves a folder of its own in `books/` while it is held. +#[cfg(unix)] +struct Jobs { + /// The backup a restore reads (`acme`'s). + repo: PathBuf, + restore_head: (u64, String), + adopt_head: (u64, String), + data: PathBuf, + toml: String, + /// Keeps the adoption's source alive. + _old: tempfile::TempDir, +} + +#[cfg(unix)] +impl Jobs { + /// Books `A` (backed up to a folder) and `cedar` (closed) exist; the + /// previews of a restore of that backup and of an adoption are taken. + fn new(home: &Home) -> Self { + home.create(A, "USD"); + home.create(CEDAR, "USD"); + assert!(matches!(close_book(home, CEDAR), CloseOutcome::Closed)); + let mut w = Wire::new(home, A); + w.initialize("owner"); + let repo = backed_up_to_folder(home, &mut w, A); + w.end(); + let old = tempfile::Builder::new() + .prefix("wb-close-old-") + .tempdir() + .unwrap(); + let data = old.path().join("books-data"); + drop(ledger_store::Store::create(&data, ledger_core::Currency::USD).unwrap()); + let toml = "[company]\nname = \"Acme Widgets LLC\"\n".to_string(); + let restore_head = match home.admin(Request::Restore { + id: "gamma".into(), + source: repo.display().to_string(), + replace: false, + confirmed: false, + expect_head: None, + }) { + Response::RestorePreview(p) => p.head, + other => panic!("{other:?}"), + }; + let mut jobs = Self { + repo, + restore_head, + adopt_head: (0, String::new()), + data, + toml, + _old: old, + }; + jobs.adopt_head = match home.admin(jobs.adopt(false)) { + Response::Preview(p) => p.source_head, + other => panic!("{other:?}"), + }; + jobs + } + + fn adopt(&self, confirmed: bool) -> Request { + Request::Adopt { + id: "delta".into(), + source: self.data.clone(), + settings_toml: Some(self.toml.clone()), + config_json: None, + vault_dir: None, + vault_key: None, + confirmed, + expect_head: confirmed.then(|| self.adopt_head.clone()), + skip_unknown: true, + } + } + + /// A restore of the backup as books `id`, over the books that exist + /// when `replace`. + fn restore(&self, id: &str, replace: bool) -> Request { + Request::Restore { + id: id.into(), + source: self.repo.display().to_string(), + replace, + confirmed: true, + expect_head: Some(self.restore_head.clone()), + } + } +} + +#[cfg(unix)] +const CEDAR: &str = "cedar"; + +/// How many times the server has said it holds `name` (`run/timer-held`). +#[cfg(unix)] +fn times_held(run: &std::path::Path, name: &str) -> usize { + std::fs::read_to_string(run.join("timer-held")) + .unwrap_or_default() + .lines() + .filter(|l| *l == name) + .count() +} + +/// A job started on its own thread, and waited for until the server holds it +/// inside the phase `name`; the thread that will have its answer. +#[cfg(unix)] +fn job_held_in( + home: &Home, + name: &str, + job: &Request, + hold: &str, +) -> std::thread::JoinHandle { + let run = home.run(); + std::fs::write(run.join("timer-hold"), hold).unwrap(); + let seen = times_held(&run, name); + let running = std::thread::spawn({ + let admin = run.join("admin.sock"); + let job = job.clone(); + move || ledger_mcp::admin::call(&admin, job).unwrap() + }); + wait_for( + &format!("{name} is held inside the job"), + Duration::from_secs(300), + || times_held(&run, name) > seen || running.is_finished(), + ); + if running.is_finished() { + panic!( + "{name}: the job ended before it was held: {:?}", + running.join() + ); + } + running +} + +/// A job on the admin socket (restore, adopt, create, open) is stopped by a +/// close only when the close is of the book the job works on, or is the +/// server's own (local.rs INVARIANT 10). Stopped, it answers that it was +/// stopped because the books are closing, what it wrote is removed, and the +/// root is byte for byte as it was (the job's staging or scratch folder is +/// there while it is held, and gone after; asked again with no close, it +/// goes through). Each job is held inside a phase by the server's test knob +/// (`--timer-hold`, `job:phase`), which the stop releases; the stop is then at +/// the job's next look. +/// +/// A restore over a book, and the opening of a book, are work on that book: a +/// close of it stops them. A create, an adoption and a restore that replaces +/// nothing make a NEW book, which no close of a book is the close of: only the +/// server's stops them (the other test below, of closes that stop nothing). #[cfg(unix)] #[test] -fn a_close_stops_a_running_restore_adopt_create_and_open_leaving_the_root_as_it_was() { - const C: &str = "cedar"; - let home = Home::new("close-stops-jobs"); - let server = Server::start_with( - &home, - &[ - "--timer-hold", - "--timers", - "20", - "--backup-quiet", - "3600000", - "--answer-grace", - "300", - ], - ); - home.create(A, "USD"); - home.create(C, "USD"); - assert!(matches!(close_book(&home, C), CloseOutcome::Closed)); - let mut w = Wire::new(&home, A); - w.initialize("owner"); - let repo = backed_up_to_folder(&home, &mut w, A); - w.end(); - let old = tempfile::Builder::new() - .prefix("wb-close-old-") - .tempdir() - .unwrap(); - let data = old.path().join("books-data"); - drop(ledger_store::Store::create(&data, ledger_core::Currency::USD).unwrap()); - let toml = "[company]\nname = \"Acme Widgets LLC\"\n".to_string(); +fn a_close_stops_the_restore_and_the_open_of_its_own_book_leaving_the_root_as_it_was() { + let home = Home::new("close-stops-own-jobs"); + let server = Server::start_with(&home, &JOB_ARGS); + let jobs = Jobs::new(&home); let run = home.run(); - let restore_head = match home.admin(Request::Restore { - id: "gamma".into(), - source: repo.display().to_string(), - replace: false, - confirmed: false, - expect_head: None, - }) { - Response::RestorePreview(p) => p.head, - other => panic!("{other:?}"), - }; - let adopt = |confirmed: bool, head: Option<(u64, String)>| Request::Adopt { - id: "delta".into(), - source: data.clone(), - settings_toml: Some(toml.clone()), - config_json: None, - vault_dir: None, - vault_key: None, - confirmed, - expect_head: head, - skip_unknown: true, - }; - let adopt_head = match home.admin(adopt(false, None)) { - Response::Preview(p) => p.source_head, - other => panic!("{other:?}"), - }; - let restore = || Request::Restore { - id: "gamma".into(), - source: repo.display().to_string(), - replace: false, - confirmed: true, - expect_head: Some(restore_head.clone()), - }; - // (the held name, the job, what it says it didn't do, whether it leaves - // a folder of its own in `books/` while it is held) - let jobs: Vec<(&str, Request, &str, bool)> = vec![ - ("restore:copy", restore(), "nothing was restored", true), + // (the held name, the job, what it says it didn't do, the book whose + // close stops it, whether it leaves a folder of its own in `books/`) + let table: Vec<(&str, Request, &str, &str, bool)> = vec![ ( - "adopt:open", - adopt(true, Some(adopt_head)), - "nothing was adopted", + "restore:copy", + jobs.restore(A, true), + "nothing was restored", + A, true, ), + ( + "open:start", + Request::OpenBook { id: CEDAR.into() }, + "not opened", + CEDAR, + false, + ), + ]; + // The books open and live while a job is held: not compared (the job's + // own book, not yet there, is). + let live = [A, CEDAR]; + for (name, job, said, closes, leaves_a_folder) in table { + let before = root_without(&home, &live); + let legacy_before = tree_of(&home.root().join("legacy")); + let running = job_held_in(&home, name, &job, name); + if leaves_a_folder { + assert_ne!( + root_without(&home, &live), + before, + "{name}: the job wrote nothing while held" + ); + } + let started = std::time::Instant::now(); + // The close of the book the job works on: it stops the job (it + // waits for the job's turn otherwise), and the test lifts nothing. + let closed = close_book(&home, closes); + assert_eq!(closed, CloseOutcome::WasNotOpen, "{name}"); + assert!(started.elapsed() < NEVER_LONGER, "{name}"); + let answer = running.join().unwrap(); + let text = format!("{answer:?}"); + assert!( + text.contains("stopped because the books are closing") && text.contains(said), + "{name}: {text}" + ); + std::fs::remove_file(run.join("timer-hold")).unwrap(); + assert_eq!( + moved(&before, &root_without(&home, &live)), + Vec::::new(), + "{name}: the root isn't as it was" + ); + assert_eq!( + tree_of(&home.root().join("legacy")), + legacy_before, + "{name}" + ); + // Asked again, with nothing closing, it goes through. + if closes == A { + assert_eq!(open_book(&home, A), OpenOutcome::Opened, "{name}"); + } + match (name, home.admin(job)) { + ("restore:copy", Response::Restored(_)) | ("open:start", Response::OpenBook { .. }) => { + } + (name, other) => panic!("{name}, asked again: {other:?}"), + } + } + for id in [A, CEDAR] { + assert_eq!(listed(&home, id), (true, false, None), "{id}"); + } + assert!(server.close().success()); +} + +/// The server's own close stops every job on the admin socket, as a close of +/// one book stops the work on that book: each held inside its phase, the +/// server is closed, and each answers that it was stopped because the books +/// are closing, with the root byte for byte as it was, and the server +/// exits 0. +#[cfg(unix)] +#[test] +fn the_servers_close_stops_every_running_admin_job_leaving_the_root_as_it_was() { + let home = Home::new("server-close-stops-jobs"); + let mut server = Server::start_with(&home, &JOB_ARGS); + let jobs = Jobs::new(&home); + let table: Vec<(&str, Request, &str, bool)> = vec![ + ( + "restore:copy", + jobs.restore("gamma", false), + "nothing was restored", + true, + ), + ( + "restore:copy", + jobs.restore(A, true), + "nothing was restored", + true, + ), + ("adopt:open", jobs.adopt(true), "nothing was adopted", true), ( "create:start", Request::Create { @@ -2894,42 +3249,18 @@ fn a_close_stops_a_running_restore_adopt_create_and_open_leaving_the_root_as_it_ ), ( "open:start", - Request::OpenBook { id: C.into() }, + Request::OpenBook { id: CEDAR.into() }, "not opened", false, ), ]; - let count = |name: &str| { - std::fs::read_to_string(run.join("timer-held")) - .unwrap_or_default() - .lines() - .filter(|l| *l == name) - .count() - }; - // The books open and live while a job is held: not compared (the job's - // own book, not yet there, is). - let mut live = vec![A]; - for (name, job, said, leaves_a_folder) in jobs { + // The books a server has open when it is closed write to their folders as + // they are let go: `acme`, and `gamma` once the first job is asked again. + let live = [A, "gamma"]; + for (n, (name, job, said, leaves_a_folder)) in table.into_iter().enumerate() { let before = root_without(&home, &live); let legacy_before = tree_of(&home.root().join("legacy")); - std::fs::write(run.join("timer-hold"), name).unwrap(); - let seen = count(name); - let running = std::thread::spawn({ - let admin = home.run().join("admin.sock"); - let job = job.clone(); - move || ledger_mcp::admin::call(&admin, job).unwrap() - }); - wait_for( - &format!("{name} is held inside the job"), - Duration::from_secs(300), - || count(name) > seen || running.is_finished(), - ); - if running.is_finished() { - panic!( - "{name}: the job ended before it was held: {:?}", - running.join() - ); - } + let running = job_held_in(&home, name, &job, name); if leaves_a_folder { assert_ne!( root_without(&home, &live), @@ -2938,21 +3269,17 @@ fn a_close_stops_a_running_restore_adopt_create_and_open_leaving_the_root_as_it_ ); } let started = std::time::Instant::now(); - // The close of another book: it stops the job (it waits for the - // job's lock otherwise), and the test lifts nothing. - let closed = close_book(&home, A); - assert_eq!(closed, CloseOutcome::Closed, "{name}"); + // Nothing lifts the hold but the server's close. + assert!(server.close().success(), "{name}"); assert!(started.elapsed() < NEVER_LONGER, "{name}"); - let answer = running.join().unwrap(); - let text = format!("{answer:?}"); + let text = format!("{:?}", running.join().unwrap()); assert!( text.contains("stopped because the books are closing") && text.contains(said), "{name}: {text}" ); - std::fs::remove_file(run.join("timer-hold")).unwrap(); - let after = root_without(&home, &live); + std::fs::remove_file(home.run().join("timer-hold")).unwrap(); assert_eq!( - moved(&before, &after), + moved(&before, &root_without(&home, &live)), Vec::::new(), "{name}: the root isn't as it was" ); @@ -2961,29 +3288,218 @@ fn a_close_stops_a_running_restore_adopt_create_and_open_leaving_the_root_as_it_ legacy_before, "{name}" ); - assert_eq!(open_book(&home, A), OpenOutcome::Opened, "{name}"); - // Asked again, with nothing closing, it goes through. - match (name, home.admin(job)) { - ("restore:copy", Response::Restored(_)) - | ("adopt:open", Response::Adopted(_)) - | ("create:start", Response::Created { .. }) - | ("open:start", Response::OpenBook { .. }) => {} - (name, other) => panic!("{name}, asked again: {other:?}"), + server = job_server_again(&home); + // Asked again, with nothing closing, it goes through (the first time + // on this server only: the others would change what comes next). + if n == 0 { + match home.admin(job) { + Response::Restored(_) => {} + other => panic!("{name}, asked again: {other:?}"), + } + // Only `acme` is opened again: `cedar` is closed, as the open + // job after this needs it. + assert_eq!(listed(&home, CEDAR), (false, true, None)); } - live.push(match name { - "restore:copy" => "gamma", - "adopt:open" => "delta", - "create:start" => "epsilon", - _ => C, - }); - } - assert_eq!(listed(&home, C), (true, false, None)); - for id in ["gamma", "delta", "epsilon"] { - assert_eq!(listed(&home, id), (true, false, None), "{id}"); } assert!(server.close().success()); } +/// An admin request made on its own thread. +#[cfg(unix)] +fn admin_in_thread(home: &Home, request: Request) -> std::thread::JoinHandle { + let admin = home.run().join("admin.sock"); + std::thread::spawn(move || ledger_mcp::admin::call(&admin, request).unwrap()) +} + +/// Wait for a thread to finish, failing (never hanging) if it doesn't. +#[cfg(unix)] +fn finished(what: &str, thread: std::thread::JoinHandle) -> T { + wait_for(what, Duration::from_secs(120), || thread.is_finished()); + thread.join().unwrap() +} + +/// Closing and opening one book never stops, fails, refuses or delays +/// another book's work (local.rs INVARIANT 10, the first rule of the unit), +/// the work on the admin socket included. A restore over `beta`, a create of +/// `epsilon` and an adoption of `delta` are each held in flight (inside a +/// phase, by the server's test knob; they make books one at a time, so the +/// second and third wait for their turn, not yet held, until the one before +/// is let go), and `acme` is closed and opened again while each is: its +/// close is made slow (its backup's git stalls), and during it another book +/// (`cedar`) is opened and closed and answers at once, while the close of +/// `acme` is still not answered. All three jobs finish correctly, none +/// stopped, none told of any error. +#[cfg(unix)] +#[test] +fn closing_and_opening_one_book_never_stops_waits_for_or_refuses_another_books_jobs() { + let home = Home::new("close-spares-other-jobs"); + let shim = shim_git(&home); + let mut args = JOB_ARGS.to_vec(); + args.extend(["--close-backup", "120000"]); + let server = server_with_shim(&home, &shim, &args); + let jobs = Jobs::new(&home); + home.create(B, "USD"); + let run = home.run(); + let stalled = || { + std::fs::read_to_string(shim.join("stalled")) + .unwrap_or_default() + .lines() + .count() + }; + // One close and reopening of `acme`, while the jobs are held. + let cycle = |why: &str| { + let before = stalled(); + std::fs::write(shim.join("stall"), b"").unwrap(); + let closing = admin_in_thread(&home, Request::CloseBook { id: A.into() }); + wait_for( + &format!("{why}: the close of {A} is in its backup"), + Duration::from_secs(120), + || stalled() > before || closing.is_finished(), + ); + assert!( + !closing.is_finished(), + "{why}: the close of {A} was answered with its backup stalled" + ); + // Another book is opened, and closed, while this close is not + // answered: neither waits for it, nor is refused. + let opening = admin_in_thread(&home, Request::OpenBook { id: CEDAR.into() }); + assert_eq!( + finished( + &format!("{why}: an open of {CEDAR} during the close of {A}"), + opening + ), + Response::OpenBook { + id: CEDAR.into(), + outcome: OpenOutcome::Opened + }, + "{why}" + ); + assert!(!closing.is_finished(), "{why}: the close was answered"); + let shutting = admin_in_thread(&home, Request::CloseBook { id: CEDAR.into() }); + assert_eq!( + finished( + &format!("{why}: a close of {CEDAR} during the close of {A}"), + shutting + ), + Response::CloseBook { + id: CEDAR.into(), + outcome: CloseOutcome::Closed + }, + "{why}" + ); + assert!(!closing.is_finished(), "{why}: the close was answered"); + std::fs::remove_file(shim.join("stall")).unwrap(); + assert_eq!( + finished(&format!("{why}: the close of {A}"), closing), + Response::CloseBook { + id: A.into(), + outcome: CloseOutcome::Closed + }, + "{why}" + ); + assert_eq!(open_book(&home, A), OpenOutcome::Opened, "{why}"); + }; + let hold = |names: &[&str]| std::fs::write(run.join("timer-hold"), names.join(",")).unwrap(); + // The restore holds the turn; the other two are asked, and wait for it. + let restore = jobs.restore(B, true); + let restoring = job_held_in( + &home, + "restore:copy", + &restore, + "restore:copy,create:start,adopt:open", + ); + let create = Request::Create { + id: "epsilon".into(), + currency: "USD".into(), + }; + // (The server says every phase it passes, held or not: the books made + // so far have passed `create:start`.) + let seen = |name: &str| times_held(&run, name); + let base = [ + ("create:start", seen("create:start")), + ("adopt:open", seen("adopt:open")), + ]; + let taken = |name: &str| { + seen(name) + > base + .iter() + .find(|(n, _)| *n == name) + .map(|(_, c)| *c) + .unwrap() + }; + let queued = [ + ("create:start", admin_in_thread(&home, create)), + ("adopt:open", admin_in_thread(&home, jobs.adopt(true))), + ]; + for n in 0..2 { + cycle(&format!("restore over {B}, round {n}")); + assert!(!restoring.is_finished(), "the restore was stopped or ended"); + assert!( + queued.iter().all(|(_, q)| !q.is_finished()), + "a queued job was stopped or ended" + ); + } + assert!( + !taken("create:start") && !taken("adopt:open"), + "a job took the turn from the restore" + ); + // The restore is let go; it finishes. + hold(&["create:start", "adopt:open"]); + match finished("the restore over beta", restoring) { + Response::Restored(r) => assert!(r.problem.is_none(), "{r:?}"), + other => panic!("the restore: {other:?}"), + } + // Then each of the others takes the turn in its time, and is held. + let mut waiting: Vec<(&str, std::thread::JoinHandle)> = queued.into_iter().collect(); + while !waiting.is_empty() { + wait_for( + "a queued job has its turn", + Duration::from_secs(300), + || waiting.iter().any(|(n, _)| taken(n)), + ); + let at = waiting.iter().position(|(n, _)| taken(n)).unwrap(); + let (name, job) = waiting.remove(at); + assert!(!job.is_finished(), "{name} ended while it was held"); + cycle(name); + assert!(!job.is_finished(), "{name} was stopped or ended"); + let names: Vec<&str> = waiting.iter().map(|(n, _)| *n).collect(); + hold(&names); + match (name, finished(name, job)) { + ("create:start", Response::Created { problem, .. }) => { + assert!(problem.is_none(), "{problem:?}"); + } + ("adopt:open", Response::Adopted(a)) => assert!(a.problem.is_none(), "{a:?}"), + (name, other) => panic!("{name}: {other:?}"), + } + } + for id in [A, B, "epsilon", "delta"] { + assert_eq!(listed(&home, id), (true, false, None), "{id}"); + } + assert_eq!(listed(&home, CEDAR), (false, true, None)); + assert!(server.close().success()); +} + +/// The arguments of the servers the job tests start. +#[cfg(unix)] +const JOB_ARGS: [&str; 7] = [ + "--timer-hold", + "--timers", + "20", + "--backup-quiet", + "3600000", + "--answer-grace", + "300", +]; + +/// A server again, on books made by an earlier one: only `acme` open, as it +/// was left (the other books of the root are closed). +#[cfg(unix)] +fn job_server_again(home: &Home) -> Server { + let mut args = JOB_ARGS.to_vec(); + args.extend(["--open", A]); + Server::start_with(home, &args) +} + /// A git that can't end on SIGTERM (its group frozen here, so the signal /// stays pending) is killed once the grace has run out, and the lock it /// leaves in a backup FOLDER is the owner's: the server never removes it. It diff --git a/crates/ledger-mcp/src/local.rs b/crates/ledger-mcp/src/local.rs index 4039dd3c..f721c279 100644 --- a/crates/ledger-mcp/src/local.rs +++ b/crates/ledger-mcp/src/local.rs @@ -82,7 +82,11 @@ //! the books stop. Lapsed uploads and exports are swept every //! SWEEP_EVERY. Nothing comes in or goes out once the books stopped. //! 10. One book opens or closes while the server runs, by admin request, -//! one change at a time (create, adopt and restore among them). Open: +//! one change to a book at a time (create, adopt and restore among +//! them): each book has its own turn (`Books::lives`), so a change to +//! one book waits for no other book's, and a close of one book is +//! never held up by, nor holds up, an open, a restore, an adoption or a +//! create of another. Open: //! a closed (or failed) book of the root is opened and verified as at //! the start. Close: from the moment it begins, a call on that book is //! refused at its door, unrun, and not in its journal; a request not @@ -114,7 +118,8 @@ //! store backup INVARIANT 5; between targets the flag is looked at //! too); `books.verify` (once per journal line replayed and per //! stored file hashed); `books.export_cpa_package` (before it -//! builds, and once per stored file it reads); a drill; and a +//! builds, and once per stored file it reads, unless it has +//! journaled a decision: below); a drill; and a //! format upgrade not yet journaled. A call stopped this way //! answers its caller that it was stopped because the books are //! closing, its access record says `refused: stopped_by_close`, and @@ -132,37 +137,69 @@ //! one that arrives after that look still upgrades and records //! success (safe: the books are in this version's format, proven //! backed up first), and finishes (a line and a database row). -//! - on the admin socket, which hold the one lifecycle lock: restore -//! and its preview, adopt and its preview, create, and open. A -//! close of any book, and the server's close, stops them (a job -//! that starts while a close is under way is refused, and asked -//! again after it). Each is stopped, before its point of no return, -//! at its next look (a phase, a stored file, a journal line, a git -//! command): what it wrote is removed (a clone, a staging folder), -//! and the root is byte for byte as it was. The point of no return -//! of restore and adopt is the rename that puts the books in place; -//! after it they finish, which is a rename or two and the sync of -//! two folders (a restore over books moves them to `legacy/` and -//! renames the copy in, both within the root); then the book is -//! opened, which is itself stopped, left closed (its answer says -//! so). Create's is the making of its folder, after which it makes -//! one empty book. Open has none: it stops anywhere (the book is -//! left closed, intact). +//! And a third: `books.export_cpa_package` that is exporting with +//! a reason (without an audit, with open drafts) journals that +//! decision before it builds, because the package counts it (its +//! README and every footer carry the journal's event count at the +//! build). The close is looked for once, immediately before the first +//! decision is journaled (a stop then journals nothing); from there +//! to the hand-over nothing looks at it, so a decision on record is +//! a package handed over (tools/reports.rs INVARIANT 4). Its build +//! then runs to its end: it is one of the named exceptions below. +//! - on the admin socket: restore and its preview, adopt and its +//! preview, create, and open. A stop is scoped to what it concerns. +//! A close of the book X stops the work on X only: an open of X, and +//! a restore that replaces X (the stoppable calls on X, above, and +//! X's backups and drill, are stopped by the same close). A create, +//! an adoption and a restore that replaces nothing make a NEW book: +//! no close of any book is a close of that, and none stops them; nor +//! does it stop, fail, refuse or delay an open or a close of another +//! book, nor a job queued for its turn at making books (`books.lock` +//! in the root, one at a time across processes: a deliberate rule, +//! ledger_store::root INVARIANT 5, that a queued job leaves at once +//! when it is asked to stop). Only the server's own close stops +//! every job (`Books::stop_every_job`). A job for a book whose close +//! is under way waits for that book's turn, so for the close to end, +//! and is then asked as any other. Each is stopped, before its +//! point of no return, at its next look (a phase, a stored file, a +//! journal line, a git command): what it wrote is removed (a clone, +//! a staging folder, and the lock file an adoption made in the +//! source folder), and the root is byte for byte as it was. The +//! point of no return of restore and adopt is the rename that puts +//! the books in place; after it they finish, which is a rename or +//! two and the sync of two folders (a restore over books moves them +//! to `legacy/` and renames the copy in, both within the root); then +//! the book is opened, which is itself stopped by the server's close +//! (and, for a restore over X, by a close of X), left closed (its +//! answer says so). Create's is the making of its folder, after which +//! it makes one empty book. Open has none: it stops anywhere (the +//! book is left closed, intact). //! Every other call does work bounded by the size of one request: its //! arguments, one entry, one stored file (at most MAX_UPLOAD) read, -//! hashed or extracted, one report or export over the ledger that is -//! already in memory (local CPU, no wait on a client, a disk of -//! another's or the network). A call that is neither stoppable nor -//! bounded by one request's size is a defect to be listed here: -//! `books.import_bank_csv` is one (a file of up to MAX_UPLOAD is -//! rehearsed whole, then written row by row, each row journaled: long -//! for a very large file, and it isn't stopped by a close). +//! hashed or extracted (local CPU, no wait on a client, a disk of +//! another's or the network). Three calls are neither stoppable nor +//! bounded by one request's size, and they are the named exceptions to +//! the close's bound below, each with its worst case, which a close that +//! meets it waits for in full (nothing enforces a bound on them: that is +//! a defect to be closed, not a promise kept): +//! - `books.import_bank_csv`: a file of up to MAX_UPLOAD is rehearsed +//! whole, then written row by row, each row journaled, and a close +//! doesn't stop it. Worst case: a full import of the largest file +//! accepted. +//! - a report or export over the whole journal (`books.verify` apart, +//! which is stoppable): CPU on the ledger already in memory, with no +//! look at a stop. Worst case: one report over the whole book. +//! - `books.export_cpa_package` once it has journaled a decision (above). +//! Worst case: one build of the package over the whole book (every +//! stored file it holds read once). //! The close is bounded, from its start, by the sum of these named //! terms, each enforced by code, and nothing else: //! a. T_calls: the longest ordinary call already running with its //! whole body (bounded by one request, above; none is cut or //! killed; nothing a client does lengthens it), or, for a -//! stoppable call, T_stop; +//! stoppable call, T_stop, or, for a call of the three named +//! exceptions above, its worst case (the bound is these terms, +//! with that term unbounded by code while one of them runs); //! 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 @@ -303,10 +340,24 @@ //! and the book is closed: the call is answered, git still stalled, //! that it was stopped because the books are closing; its record says //! `refused: stopped_by_close`; the close is answered `closed`. -//! 14. A restore of a large backup is running (an admin job) when another -//! book is closed: the restore is stopped, answers that it was stopped -//! because the books are closing, and the root is byte for byte as it -//! was; asked again it goes through. +//! 14. A restore of a large backup over `beta` is running (an admin job) +//! when `beta` is closed: the restore is stopped, answers that it was +//! stopped because the books are closing, and the root is byte for byte +//! as it was; asked again it goes through. The same restore, with +//! another book (`acme`) closed instead, is not stopped. +//! 15. A restore over `beta`, a create of `epsilon` and an adoption of +//! `delta` are in flight (held inside a phase), and `acme`, whose close +//! is made slow, is closed and opened again over and over: all three +//! finish correctly, none is stopped, none is told of an error, an open +//! and a close of `cedar` during a close of `acme` are answered at once, +//! and the close of `acme` is not answered until its own backup is done. +//! 16. The server is closed with a restore, an adoption, a create and an +//! open in flight: each is stopped, and the root is as it was. +//! 17. An adoption of a folder that has no lock file is stopped, fails, or +//! panics: the folder is, name for name and byte for byte, as it was. +//! 18. A package exported with a reason is held as it begins and the book is +//! closed: stopped, no decision journaled. Held right after its decision +//! is journaled and the book closed: the package is made. //! ``` use crate::admin::{self, Request, Response}; @@ -762,16 +813,16 @@ struct Books { /// How long after books are first seen open a drill is first looked /// for (`--drill-first`, for tests; else DRILL_FIRST). drill_first: Duration, - /// Held through every change to which books are open or exist (create, - /// adopt, restore, open, close): one at a time (INVARIANT 10). - lifecycle: Mutex<()>, - /// Set while any close of a book is under way, and for good once the - /// server closes: the admin jobs that can run long (restore, create, - /// adopt, open) look at it and stop, before their point of no return, - /// leaving the books as they were (INVARIANT 10). `closers` counts the - /// closes under way; the flag is clear when none is. - job_stop: Arc, - closers: Mutex, + /// What each book's changes share: the lock they are made under, and + /// the stop a close of that book raises (INVARIANT 10). One book's + /// changes wait for one book's; no change to one book waits for, stops + /// or fails a change to another. + lives: Mutex>>, + /// Set for good when the server closes: the jobs that make a NEW book + /// (a create, an adoption, a restore that replaces nothing) look at it. + /// A close of one book never raises it: those jobs aren't work on that + /// book (INVARIANT 10). + server_stop: Arc, /// How these books are kept from agents (plan 3.8, P9a): what /// `books.start` reports (`--isolation`). isolation: Isolation, @@ -779,16 +830,36 @@ struct Books { timers: Timers, } -/// A close of a book under way (`Books::closing_one`). -struct CloseGuard<'a>(&'a Books); +/// What the changes to ONE book share (`Books::lives`): the lock they are +/// made under, one at a time, and the stop a close of that book raises for +/// the jobs that work on it (INVARIANT 10). +struct Life { + /// Held through every change to this book (open, close, a restore that + /// replaces it; a create or an adoption making it). + lock: Mutex<()>, + /// Set while a close of this book is under way, and for good once the + /// server closes: the admin jobs working on this book (an open, a + /// restore over it) look at it and stop, before their point of no + /// return, leaving the books as they were. `closers` counts the closes + /// under way; the flag is clear when none is (and the server isn't + /// closing). Set and cleared under `closers`. + stop: Arc, + closers: Mutex, +} -impl Drop for CloseGuard<'_> { +/// A close of a book under way (`Books::closing_one`). +struct CloseGuard { + life: Arc, + closing: CancellationToken, +} + +impl Drop for CloseGuard { fn drop(&mut self) { - let mut closers = self.0.closers.lock().unwrap_or_else(|e| e.into_inner()); + let mut closers = self.life.closers.lock().unwrap_or_else(|e| e.into_inner()); *closers -= 1; - if *closers == 0 && !self.0.closing.is_cancelled() { - self.0 - .job_stop + if *closers == 0 && !self.closing.is_cancelled() { + self.life + .stop .store(false, std::sync::atomic::Ordering::SeqCst); } } @@ -815,9 +886,8 @@ impl Books { session_tokens: Mutex::new(BTreeMap::new()), backup_quiet, drill_first, - lifecycle: Mutex::new(()), - job_stop: Arc::default(), - closers: Mutex::new(0), + lives: Mutex::new(BTreeMap::new()), + server_stop: Arc::default(), isolation, timers: Timers::default(), } @@ -829,29 +899,74 @@ impl Books { self } - /// A close of a book begins: the admin jobs that can run long stop - /// (INVARIANT 10) until the returned guard is dropped. - fn closing_one(&self) -> CloseGuard<'_> { - let mut closers = self.closers.lock().unwrap_or_else(|e| e.into_inner()); + /// What the changes to the book `id` share: made once, kept while + /// anything holds it. A book first met after the server began closing + /// is born stopped. + fn life(&self, id: &BookId) -> Arc { + let mut lives = self.lives.lock().unwrap_or_else(|e| e.into_inner()); + // Forget the books nothing is changing or closing. + lives.retain(|_, life| Arc::strong_count(life) > 1); + lives + .entry(id.as_str().to_string()) + .or_insert_with(|| { + Arc::new(Life { + lock: Mutex::new(()), + stop: Arc::new(std::sync::atomic::AtomicBool::new( + self.closing.is_cancelled(), + )), + closers: Mutex::new(0), + }) + }) + .clone() + } + + /// A close of the book `life` belongs to begins: the admin jobs working + /// on THAT book that can run long stop (INVARIANT 10) until the returned + /// guard is dropped. Nothing else is stopped. + fn closing_one(&self, life: &Arc) -> CloseGuard { + let mut closers = life.closers.lock().unwrap_or_else(|e| e.into_inner()); *closers += 1; - self.job_stop + life.stop.store(true, std::sync::atomic::Ordering::SeqCst); + drop(closers); + CloseGuard { + life: life.clone(), + closing: self.closing.clone(), + } + } + + /// The server closes: every stop is raised, for good (INVARIANT 10). + /// `closing` is cancelled first, so a book first met from now is born + /// stopped, and a close of one book ending now clears nothing. + fn stop_every_job(&self) { + self.server_stop .store(true, std::sync::atomic::Ordering::SeqCst); - CloseGuard(self) + let lives = self.lives.lock().unwrap_or_else(|e| e.into_inner()); + for life in lives.values() { + // Under the lock a close's end clears the flag under. + let _closers = life.closers.lock().unwrap_or_else(|e| e.into_inner()); + life.stop.store(true, std::sync::atomic::Ordering::SeqCst); + } } /// What an admin job that can run long is asked as it goes whether to - /// stop (ledger_store::root `JobStop`). With the test knob - /// `--timer-hold` a job is held inside a phase named `job:phase` (in - /// `run/timer-hold`) until the name is gone or a stop is asked. - fn job(&self, job: &'static str) -> ledger_store::root::JobStop { - let stop = ledger_store::root::JobStop::new(self.job_stop.clone()); + /// stop (ledger_store::root `JobStop`): `flag` is the stop of the book + /// it works on, or the server's (`server_stop`) for a job that makes a + /// new book. With the test knob `--timer-hold` a job is held inside a + /// phase named `job:phase` (in `run/timer-hold`) until the name is gone + /// or a stop is asked. + fn job( + &self, + job: &'static str, + flag: &Arc, + ) -> ledger_store::root::JobStop { + let stop = ledger_store::root::JobStop::new(flag.clone()); if !self.timers.timer_hold { return stop; } let Ok(run) = self.root.run_dir() else { return stop; }; - let flag = self.job_stop.clone(); + let flag = flag.clone(); stop.with_phase_watch(Arc::new(move |phase: &str| { let name = format!("{job}:{phase}"); { @@ -1219,16 +1334,20 @@ impl Books { "that isn't a currency: give its three-letter ISO code, such as USD".into(), ); }; - let _one = self.lifecycle.lock().unwrap_or_else(|e| e.into_inner()); + let life = self.life(&id); + let _one = life.lock.lock().unwrap_or_else(|e| e.into_inner()); if self.held().contains_key(id.as_str()) { return refused(RootError::Exists(id.to_string())); } - // Stopped by a close before its folder is made, it makes - // nothing; after that it makes one empty book (INVARIANT 10). - match self - .root - .create_book_stoppable(&id, currency, &self.job("create")) - { + // Stopped by the server's close before its folder is made, it + // makes nothing; after that it makes one empty book. A close + // of another book doesn't stop it: it is no work on that book + // (INVARIANT 10). + match self.root.create_book_stoppable( + &id, + currency, + &self.job("create", &self.server_stop), + ) { Ok(store) => { // Made: kept whether or not it opens (INVARIANT 3). let book = self.serve(store).unwrap_or_else(Book::Failed); @@ -1333,11 +1452,16 @@ impl Books { Ok(id) => id, Err(e) => return refused(e), }; - let _one = self.lifecycle.lock().unwrap_or_else(|e| e.into_inner()); + let life = self.life(&id); + let _one = life.lock.lock().unwrap_or_else(|e| e.into_inner()); if self.held().contains_key(id.as_str()) { return refused(RootError::Exists(id.to_string())); } - let stop = self.job("adopt"); + // Making a new book: stopped by the server's close, never by + // a close of another book (INVARIANT 10). Once placed, it is + // opened, which a close of THIS book (asked of the id it is + // making) stops, as it stops an open. + let stop = self.job("adopt", &self.server_stop); let found = match self.root.adopt_preview_stoppable(&source, &stop) { Ok(found) => found, Err(e) => return refused(e), @@ -1545,7 +1669,10 @@ impl Books { id: id.to_string(), outcome, }; - let _one = self.lifecycle.lock().unwrap_or_else(|e| e.into_inner()); + // This book's turn only: an open of this book waits for a close or a + // restore of THIS book, never for any other book's (INVARIANT 10). + let life = self.life(&id); + let _one = life.lock.lock().unwrap_or_else(|e| e.into_inner()); if self.closing.is_cancelled() { return Response::Refused("the books are closing: nothing was done".into()); } @@ -1564,8 +1691,9 @@ impl Books { Err(e) => return Response::Refused(self.hide(e.to_string())), }, } - // Stopped by a close (INVARIANT 10): the book stays as it was. - let stop = self.job("open"); + // Stopped by a close of this book, or the server's (INVARIANT 10): + // the book stays as it was. + let stop = self.job("open", &life.stop); if stop.look("start") { return said(admin::OpenOutcome::CouldNotOpen(OPEN_STOPPED.into())); } @@ -1598,10 +1726,27 @@ impl Books { id: id.to_string(), outcome, }; - // From now the admin jobs that can run long stop (INVARIANT 10), so - // the lifecycle lock is not held for long by one of them. - let _closing = self.closing_one(); - let _one = self.lifecycle.lock().unwrap_or_else(|e| e.into_inner()); + // From now the admin jobs working on THIS book that can run long + // stop (INVARIANT 10), so this book's turn is not held for long by + // one of them; no other book's job is touched, and no other book's + // change is waited for. + let life = self.life(&id); + let closing = self.closing_one(&life); + let one = life.lock.lock().unwrap_or_else(|e| e.into_inner()); + let answer = self.close_book_held(&id, said); + // The stop is lowered while the turn is still held: an open of this + // book that was waiting for it is not stopped by a close that is over. + drop(closing); + drop(one); + answer + } + + /// [`Self::close_one`], the book's turn held. + fn close_book_held( + &self, + id: &BookId, + said: impl Fn(admin::CloseOutcome) -> Response, + ) -> Response { if self.closing.is_cancelled() { return Response::Refused("the books are closing: nothing was done".into()); } @@ -1622,8 +1767,8 @@ impl Books { let rt = tokio::runtime::Handle::current(); // No new call gets in; the book is listed closed. parts.gate.shut(); - self.hold(&id, Book::Closed); - let backup = rt.block_on(self.release(&id, &parts, true, Instant::now(), None)); + self.hold(id, Book::Closed); + 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, @@ -1844,8 +1989,20 @@ impl Books { Ok(id) => id, Err(e) => return said(e.to_string()), }; - let _one = self.lifecycle.lock().unwrap_or_else(|e| e.into_inner()); - let stop = self.job("restore"); + // This book's turn only (INVARIANT 10). What stops the restore: a + // close of THIS book, if it replaces it (that is work on this book); + // else only the server's close (a preview, or a restore making a new + // book, is no work on any book that is closing). + let life = self.life(&id); + let _one = life.lock.lock().unwrap_or_else(|e| e.into_inner()); + let stop = self.job( + "restore", + if confirmed && replace { + &life.stop + } else { + &self.server_stop + }, + ); let git = match ledger_store::backup::Git::find() { Ok(git) => git, Err(e) => return said(e.to_string()), @@ -3405,9 +3562,7 @@ async fn serve( // The admin jobs that can run long stop at their next look, before // their point of no return (INVARIANT 10): the wait below is for jobs // that are stopping, not for a restore to run its course. - books - .job_stop - .store(true, std::sync::atomic::Ordering::SeqCst); + books.stop_every_job(); let begun = Instant::now(); let cutters: Vec<_> = books .gates() @@ -3435,8 +3590,9 @@ async fn serve( // 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). + // (Every admin job has ended: `admin_jobs.wait()` above. No book's + // changes are in flight to be waited for.) 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() diff --git a/docs/mcp-interface.md b/docs/mcp-interface.md index 03623108..9bc54854 100644 --- a/docs/mcp-interface.md +++ b/docs/mcp-interface.md @@ -398,20 +398,41 @@ didn't open, with why). Protocol version 1: the requests are new, the a commit it had made stands), `books.verify` (once per journal line and per stored file; a heal of a drifted database is begun only if no stop was asked before it, then finishes), `books.export_cpa_package` (once per - stored file), a drill, and a format upgrade not yet at its final look (a + stored file, unless it has journaled a decision, below), a drill, and a + format upgrade not yet at its final look (a stop is honoured up to that look; one that arrives after it still - upgrades and records success). On the admin socket, restore (and its - preview), adopt (and its preview), create and open are stopped by a close - of any book, and by the server's own: before their point of no return - (the rename that puts the books in place; create's making of its folder) - they remove what they wrote and leave the root byte for byte as it was - and answer that they were stopped because the books are closing; after - it they finish (a rename or two and two directory syncs), and the book - is then opened unless that, too, is stopped (it is left closed, and the - answer says so). Every other call does work bounded by the size of one - request and is waited for; `books.import_bank_csv` is the one known - exception (a file of up to 25 MiB is rehearsed whole and then written row - by row, each row journaled: long for a very large file, and not stopped); + upgrades and records success). A stop is scoped to what it concerns. On + the admin socket, a close of the book X stops the work on X only: an open + of X, and a restore that replaces X. A create, an adoption and a restore + that replaces nothing make a new book, which no close of a book is the + close of: a close of one book never stops, fails, refuses or delays them, + nor an open or a close of another book (each book has its own turn; books + are made, adopted and restored one at a time, and a job queued for its + turn leaves at once when asked to stop). The server's own close stops + every job. A stopped job, before its point of no return (the rename that + puts the books in place; create's making of its folder), removes what it + wrote (an adoption also removes the lock file it made in the source + folder, so the original is left as it was) and leaves the root byte for + byte as it was, and answers that it was stopped because the books are + closing; after it the job finishes (a rename or two and two directory + syncs), and the book is then opened unless that, too, is stopped (it is + left closed, and the answer says so). `books.export_cpa_package` with a + reason to export (without an audit, with open drafts) journals that + decision before it builds, because the package counts it (its README and + every footer carry the journal's event count at the build): a close is + looked for once, immediately before the first decision is journaled, and + a stop then journals nothing; after it the package is made whatever a + close does, so no decision is on record for a package that was never + made (every refusal is decided before any decision is journaled). Every + other call does work bounded by the size of one request and is waited + for. Three are the named exceptions to the close's bound, each waited for + in full if a close meets it: `books.import_bank_csv` (a file of up to + 25 MiB is rehearsed whole and then written row by row, each row + journaled; worst case, a full import of the largest file accepted), + a report or export over the whole journal (CPU on the ledger in memory, + not stopped; worst case, one report over the whole book), and a package + after its decision is journaled (worst case, one build over the whole + book). Otherwise 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); diff --git a/docs/testing.md b/docs/testing.md index c9b337f5..dc40485e 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -4084,7 +4084,8 @@ it checks are already theorems. a medium effort, no claim, a lowered bar read retroactively), `a_period_is_attested_on_a_standing_audit`, `cpa_package_refuses_without_a_counted_audit_unless_a_reason_is_given` - (refused, a reason journaled as a decision, an audit alone not enough, a + (refused, a reason journaled as a decision, and none journaled when an open + draft then refuses the same package, an audit alone not enough, a year attested below the whole bar not enough, the whole bar, an entry since, `warn`), `audits_wait_for_the_upgrade` (the fixture over the wire; the package is not held up by an audit it cannot ask for). @@ -4310,7 +4311,7 @@ one book never refuses or holds up a call on another. | `book_open_close::books_left_closed_at_the_start_say_so_and_open_when_asked` | a real server started with `--open BOOK`: the other book is listed closed and says so on the MCP, download, export and upload routes; a name that is no book is 404; opening serves | | `book_open_close::the_open_option_takes_none_and_refuses_a_book_that_doesnt_exist` | `--open none` leaves every book closed; `--open nobody` exits 2 before opening anything | | `book_open_close::the_sessions_request_names_each_connection_and_never_its_token` | over the real socket: two tokens, two clients, an agent's report, neither token's text nor SHA-256 in the answer, an ended session gone, a close ends the book's sessions | -| `book_open_close::closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing` | the hammer: 6 agents on one book (which has a backup target, every timer at 10 ms, and two clients sending bad tokens so refusals are being recorded) and 4 on another make journaled drafts and reads while the first is closed and reopened 12 times; every file of the closed book (journal, access log, every ops log, stored files, the backup's repository) is hashed when the close is answered and compared just before the reopening, every cycle; "the other book progressed" waits on that condition, not a sleep; the logs end as whole chains; both journals are replayed afterwards: every acknowledged draft is in its journal exactly once under the id it was told, no refused call left anything, the closed book's journal and access log never moved between the close answer and the reopening, the other book never refused a call and kept answering while the first was closed, and the books replay with gapless ids | +| `book_open_close::closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing` | the hammer: 6 agents on one book (which has a backup target, every timer at 10 ms, and two clients sending bad tokens so refusals are being recorded) and 4 on another make journaled drafts and reads while the first is closed and reopened 12 times, and a maker thread creates up to eight new books and closes and opens a third over and over (every one must be answered as asked: a close of the first never stops, refuses or fails an admin job on another book; a probabilistic check, the deterministic one is `closing_and_opening_one_book_never_…`); every file of the closed book (journal, access log, every ops log, stored files, the backup's repository) is hashed when the close is answered and compared just before the reopening, every cycle; "the other book progressed" waits on that condition, not a sleep; the logs end as whole chains; both journals are replayed afterwards: every acknowledged draft is in its journal exactly once under the id it was told, no refused call left anything, the closed book's journal and access log never moved between the close answer and the reopening, the other book never refused a call and kept answering while the first was closed, and the books replay with gapless ids | | `book_open_close::a_close_doesnt_wait_for_a_clients_open_event_stream` | a client keeps its standalone event stream (a GET) open (known open: its response head has come; no sleep): closing its book still answers at once, not after the grace for answers on their way out (it took 12 s while the stream was counted as an answer, which stalled the bridge in a hand demonstration) | | `local::tests::a_refusal_being_recorded_keeps_its_place_when_its_client_hangs_up` | a request refused at the door has its access record written by a task that keeps its place inside the book's door: with the only blocking thread held and the request's future dropped, the door stays counted, a close waits, and the record is written before it empties (it was uncounted: the record could land after the close, and after a reopening) | | `local::tests::handles_from_before_a_close_do_nothing_after_the_book_is_open_again` | the access log, uploads, exports and backups taken before a close, used after the same book is opened again (a late record, a sweep, a grant, an export, a run, a drill, a format upgrade), write nothing: the reopened book's tree is byte for byte what its own upgrade left, and its backup record is a whole chain (fails when the backups' shut flag and record close are removed) | @@ -4334,8 +4335,13 @@ one book never refuses or holds up a call on another. | `book_open_close::a_running_call_is_never_cut_when_the_grace_runs_out` | an ordinary call (`books.attach_receipt`, held inside its read of its file, a named pipe) past the grace (body whole) is not cut: it finishes when fed, is answered and recorded `ok`, and then the close is answered (a backup asked for is no longer this call: it is stoppable) | | `book_open_close::a_close_stops_a_running_backup_call_and_says_so` | `books.back_up_now` held in a stalled `git` (never lifted until the call answers): the close stops it, the call is answered that it was stopped because the books are closing, its access record is `refused: stopped_by_close` with no head, the backup record holds `stopped` and no result of its own for the run, git and all it started are gone, the close's last backup is made and the close answers `closed` | | `book_open_close::a_close_stops_a_running_verification_and_a_running_package_and_says_so` | `books.verify` and `books.export_cpa_package` held as they begin by `--timer-hold` (`call:...`), which the close releases: each is stopped at its first look, answers it was stopped, is recorded `refused: stopped_by_close`, the journal is unchanged | -| `book_open_close::a_close_stops_a_running_restore_adopt_create_and_open_leaving_the_root_as_it_was` | each admin job held inside a phase (`restore:copy`, `adopt:open`, `create:start`, `open:start`): its scratch or staging folder is there while held; a close of another book stops it, it answers it was stopped, the root's `books/` and `legacy/` are byte for byte as before; asked again it goes through | +| `book_open_close::a_close_stops_the_restore_and_the_open_of_its_own_book_leaving_the_root_as_it_was` | a restore over a book and the open of a book, each held inside a phase (`restore:copy`, `open:start`): its scratch or staging folder is there while held; a close of THAT book stops it, it answers it was stopped, the root's `books/` and `legacy/` are byte for byte as before; asked again it goes through | +| `book_open_close::the_servers_close_stops_every_running_admin_job_leaving_the_root_as_it_was` | restore (a new book, and over `acme`), adopt, create and open, each held inside a phase, the server closed with nothing lifting the hold: each answers it was stopped, the root as it was, exit 0; asked again on a new server the first goes through | +| `book_open_close::closing_and_opening_one_book_never_stops_waits_for_or_refuses_another_books_jobs` | a restore over `beta`, a create of `epsilon` and an adoption of `delta` in flight (they make books one at a time, so the later two queue for their turn, and each is held in its phase in its time), `acme` closed (its backup's git stalled, so the close is slow) and opened again around each; during each close `cedar` is opened and closed and answers while the close of `acme` is still not answered; all three finish (`Restored`, `Created`, `Adopted`, no problem), none was stopped. Mutations: a close that raises a server-wide stop fails it (a queued job stopped); one global lock around open and close fails it (the open waits for the close) | +| `book_open_close::a_close_never_leaves_a_decision_on_record_for_a_package_that_was_not_made` | `books.export_cpa_package` with `allow_open_drafts`: held as it begins and the book closed, it is stopped and the journal holds no decision; held right after its decision is journaled and the book closed, it is made, handed over (`ok`), one decision. Mutations: no look before the journaling fails the first; a build still stoppable after it fails the second | | `ledger-store` `tests/root.rs::a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_it_was` | create, adopt, restore (over existing books) and the restore preview stopped at each phase they ask: `Stopped`, the root (`books/`, `legacy/`) byte for byte as before; never stopped, `place` is the last phase asked (nothing after the point of no return) | +| `ledger-store` `tests/root.rs::an_adoption_that_does_not_finish_leaves_no_lock_file_in_the_source` | a source with no lock file: the adoption stopped at each of its seven phases, refused after taking the lock (a stale preview head), and panicking in the middle leaves the source folder name for name, byte for byte and mode for mode as it was; a lock file swapped in by someone else during the adoption is not removed; a source that had its lock keeps it (stopped or adopted, `source_lock_created` false); a success of a source with none leaves the one it made and says so. Mutation: no removal fails it | +| `ledger-store` `tests/root.rs::a_job_waiting_for_its_turn_stops_when_asked_and_otherwise_waits_for_it` | the turn at making books held (as another process would): a create that isn't asked to stop waits, and stops within seconds once asked (`Stopped`, nothing made); not asked, it goes through when the turn is let go. Mutation: a blocking wait for the turn fails it | | `book_open_close::a_lock_a_kill_leaves_in_the_backup_folder_is_reported_and_never_removed_by_the_server` | REAL git in a push to a folder with its group frozen, so only the kill after the grace ends it: the lock it leaves is still there after the close, recorded `lock_left` with its whole path, no `lock_removed` for the folder, the close's answer and `books.backup` name the file and say when it may be removed, a lock that was there before is neither touched nor named, a later backup fails by git's words and removes nothing, and once the file is removed the backup goes on, `git fsck --strict` on both | | `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) |