From 26b42c6d01398d36885093f6d0c4a0b021a1661b Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Fri, 20 Nov 2026 10:30:56 -0700 Subject: [PATCH] fix(mcp): after a close is answered nothing of this process can write to the book, and a close says when its last backup wasn't whole A close ended with the process still alive, so the faults that process exit used to bound now lived on: something of the server's own could still write to a book that was reported closed, or, once the book was opened again (here or by another process), to the new book's files. One rule now: after a close is answered this process holds nothing that writes to the book's folder, and every path that touches the book is either counted by its gate or checks, under the lock of its own write, that the book is still open. The close answers only when that is true. * A refusal's access record is written by a task that carries the request's place inside the door, so a client hanging up no longer leaves the record to land after the close; the access log, uploads, exports and backups are closed under their own locks by the close, so a record, sweep or run still on its way is refused, unwritten. * A restore over an open book lets go as a close does (drain, sessions, backups, closing the logs) before it moves the book to legacy/: an upload half received no longer leaves its part in legacy/ nor writes to the replaced book's log after. * The backup at a close is bounded, and a run past its bound is stopped (git killed with all it started) and waited for to end, instead of its future being dropped while its blocking task went on; the close answers closed_backup_incomplete, with why, when the last backup wasn't whole. The server's own close does the same. * Every timer (the sweep, the look for a backup due, the look for a drill due) works on handles closed with the book; the sweep also takes its place inside the door. They take --timers for tests. * A format upgrade, run, drill and record through a backup handle from before a close do nothing. * A call whose answer isn't read within the grace is the case of a connection dropped at any other moment: its record, written before its answer, says it ran. No journaled call carries a client key or a duplicate check, so a retry isn't made safe; said in INVARIANT 14, and left as an open design point. Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-cli/tests/book_open_close.rs | 1070 +++++++++++++++++++- crates/ledger-cli/tests/common/mod.rs | 17 + crates/ledger-host/src/commands.rs | 9 + crates/ledger-mcp/src/access.rs | 8 + crates/ledger-mcp/src/admin.rs | 12 +- crates/ledger-mcp/src/backup.rs | 136 ++- crates/ledger-mcp/src/local.rs | 559 ++++++++-- docs/mcp-interface.md | 42 +- docs/testing.md | 18 +- 9 files changed, 1723 insertions(+), 148 deletions(-) diff --git a/crates/ledger-cli/tests/book_open_close.rs b/crates/ledger-cli/tests/book_open_close.rs index 9c0227ea..9886f10d 100644 --- a/crates/ledger-cli/tests/book_open_close.rs +++ b/crates/ledger-cli/tests/book_open_close.rs @@ -13,6 +13,7 @@ use common::{Home, Server, Wire}; use ledger_mcp::admin::{CloseOutcome, OpenOutcome, Request, Response}; use serde_json::{Value, json}; use std::collections::{BTreeMap, BTreeSet}; +use std::path::PathBuf; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -376,9 +377,32 @@ fn agent( fn closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing() { const CYCLES: usize = 12; let home = Arc::new(Home::new("open-close-hammer")); - let server = Server::start(&home); + // Every timer of the server runs every few milliseconds, and the + // hammered book has a backup target, which backs it up and drills it + // as it is written: the writers a close must stop are all at work. + let server = Server::start_with( + &home, + &[ + "--timers", + "10", + "--backup-quiet", + "30", + "--drill-first", + "0", + "--answer-grace", + "1500", + ], + ); home.create(A, "USD"); home.create(B, "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); + w.end(); + } let stop = Arc::new(AtomicBool::new(false)); let done = Arc::new(Mutex::new(Vec::new())); let reads = Arc::new([AtomicUsize::new(0), AtomicUsize::new(0)]); @@ -392,6 +416,19 @@ fn closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing() { })); } } + // Refusals at the door of the hammered book, whose records are written + // as the close comes (the late writers the review found). + let refusers: Vec<_> = (0..2) + .map(|n| { + let (home, stop) = (home.clone(), stop.clone()); + std::thread::spawn(move || { + let mut wire = Wire::with_token(&home, A, Some(format!("no-such-token-{n}"))); + while !stop.load(Ordering::SeqCst) { + wire.send(&json!({"jsonrpc": "2.0", "id": 1, "method": "ping"})); + } + }) + }) + .collect(); let mut closed_for = Vec::new(); for cycle in 0..CYCLES { std::thread::sleep(Duration::from_millis(150 + (cycle as u64 * 37) % 100)); @@ -401,30 +438,54 @@ fn closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing() { // opened, so its files stand still (and, the writer lock being // released, another program could open it). let before = files_of(&home, A); + // Every file of the book (the journal, the access log, every ops + // log, stored files, upload parts, the backup's repository) as it + // is when the close is answered. + let tree = tree_of(&home.book_dir(A)); assert_eq!(listed(&home, A), (false, true, None)); closed_on_every_route(&home, A); - std::thread::sleep(Duration::from_millis(70)); + // The other book answers while this one is closed: waited for as a + // condition (while it is closed), not guessed at with a sleep. + wait_for( + &format!("a call on {B} finished while {A} was closed (cycle {cycle})"), + Duration::from_secs(120), + || done.lock().unwrap().iter().filter(|d| d.book == B).count() > beta_before, + ); let after = files_of(&home, A); assert_eq!( (before.0.len(), before.1), (after.0.len(), after.1), "cycle {cycle}: the closed book's journal or access log moved" ); - closed_for.push(before.0.len()); - // The other book answered while this one was closed. - let beta_after = done.lock().unwrap().iter().filter(|d| d.book == B).count(); - assert!( - beta_after > beta_before, - "cycle {cycle}: no call on {B} finished while {A} was closed" + // Still, to the byte, just before it is opened again, however the + // timers and the late refusals tried (a window to catch them in). + stands_still( + &home, + A, + Duration::from_millis(70), + &format!("cycle {cycle}"), ); + assert_eq!( + moved(&tree, &tree_of(&home.book_dir(A))), + Vec::::new(), + "cycle {cycle}: the closed book's folder moved after the close was answered" + ); + closed_for.push(before.0.len()); assert_eq!(open_book(&home, A), OpenOutcome::Opened, "cycle {cycle}"); } std::thread::sleep(Duration::from_millis(200)); stop.store(true, Ordering::SeqCst); - for a in agents { + for a in agents.into_iter().chain(refusers) { a.join().unwrap(); } assert!(server.close().success()); + // Every log is a whole chain after all those closings. + access_of(&home, A); + ledger_store::chain::read( + &home.book_dir(A).join("ops").join("backup.jsonl"), + "wanderbooks-backup-v1", + ) + .expect("the backup record is a whole chain"); let done = done.lock().unwrap().clone(); for book in [A, B] { @@ -508,49 +569,964 @@ fn closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing() { /// A client's standalone event stream (the GET an MCP client keeps open /// for server messages) ends only with its session: a close must not wait /// on it as it waits on answers on their way out (it would sit out the -/// whole grace for every connected assistant). -#[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn a_close_doesnt_wait_for_a_clients_open_event_stream() { - let home = Arc::new( - tokio::task::spawn_blocking(|| Home::new("open-close-stream")) - .await - .unwrap(), +/// whole grace for every connected assistant). The stream is known to be +/// open (its response head has come) before the close begins. +#[test] +fn a_close_doesnt_wait_for_a_clients_open_event_stream() { + let home = Home::new("open-close-stream"); + let server = Server::start(&home); + home.create(A, "USD"); + let mut w = Wire::new(&home, A); + w.initialize("streamer"); + assert_eq!( + w.call("books.chart", json!({}))["result"]["isError"], + json!(false) ); - let server = { - let home = home.clone(); - tokio::task::spawn_blocking(move || { - let server = Server::start(&home); - home.create(A, "USD"); - server - }) - .await - .unwrap() - }; - let client = tokio::task::spawn_blocking({ - let home = home.clone(); - move || home.token(A) - }) - .await - .unwrap(); - let c = common::connect_with(&home, A, Some(client)).await.unwrap(); - common::call(&c, "books.chart", json!({})).await.unwrap(); - // Time for the client to open its stream. - tokio::time::sleep(Duration::from_millis(500)).await; - let started = std::time::Instant::now(); - let closed = { - let home = home.clone(); - tokio::task::spawn_blocking(move || close_book(&home, A)) + // The client's own multi-thread runtime keeps the stream's connection + // going while this thread asks for the close. + let rt = tokio::runtime::Runtime::new().unwrap(); + let http = common::mcp_http(&home); + let stream = rt.block_on(async { + http.get(format!("http://localhost/b/{A}/mcp")) + .bearer_auth(w.token().unwrap()) + .header("accept", "text/event-stream") + .header("mcp-session-id", w.session().unwrap()) + .header("mcp-protocol-version", w.version().unwrap()) + .send() .await - .unwrap() - }; - assert_eq!(closed, CloseOutcome::Closed); + .expect("the stream opens") + }); + // Its response head has come: the stream is open (no sleep guesses it). + assert_eq!(stream.status().as_u16(), 200); + assert!( + stream + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .is_some_and(|t| t.starts_with("text/event-stream")), + "{:?}", + stream.headers() + ); + let started = std::time::Instant::now(); + assert_eq!(close_book(&home, A), CloseOutcome::Closed); assert!( started.elapsed() < Duration::from_secs(5), "the close waited {:?} on a client's open stream", started.elapsed() ); - let _ = c.cancel().await; - tokio::task::spawn_blocking(move || assert!(server.close().success())) - .await - .unwrap(); + drop(stream); + drop(rt); + assert!(server.close().success()); +} + +// --------------------------------------------------------------------- +// After a close is answered, nothing of the server's reaches the book +// (local.rs INVARIANT 10). The tests below misbehave the way a real +// client does (an answer never read, a body never finished) and keep a +// backup target on the book, which the hammer above did not. +// --------------------------------------------------------------------- + +/// Every file of a book's folder, by relative path: its size and SHA-256. +/// What stands still while the book is closed. +fn tree_of(dir: &std::path::Path) -> BTreeMap { + fn walk( + base: &std::path::Path, + at: &std::path::Path, + out: &mut BTreeMap, + ) { + let Ok(entries) = std::fs::read_dir(at) else { + return; + }; + for e in entries.flatten() { + let path = e.path(); + if e.file_type().map(|t| t.is_dir()).unwrap_or(false) { + walk(base, &path, out); + } else if let Ok(bytes) = std::fs::read(&path) { + out.insert( + path.strip_prefix(base).unwrap().display().to_string(), + ( + bytes.len() as u64, + ledger_store::journal::sha256_hex(&bytes), + ), + ); + } + } + } + let mut out = BTreeMap::new(); + walk(dir, dir, &mut out); + out +} + +/// Say what moved between two trees. +fn moved( + before: &BTreeMap, + after: &BTreeMap, +) -> Vec { + let mut out = Vec::new(); + for (k, v) in before { + match after.get(k) { + None => out.push(format!("{k} went")), + Some(a) if a != v => out.push(format!("{k} changed")), + Some(_) => {} + } + } + out.extend( + after + .keys() + .filter(|k| !before.contains_key(*k)) + .map(|k| format!("{k} appeared")), + ); + out +} + +/// Poll `ready` until it holds, or fail after `within`: a test waits on +/// the condition it needs, never on a sleep that guesses how long it takes. +fn wait_for(what: &str, within: Duration, mut ready: impl FnMut() -> bool) { + let by = std::time::Instant::now() + within; + while !ready() { + assert!(std::time::Instant::now() < by, "never: {what}"); + std::thread::sleep(Duration::from_millis(10)); + } +} + +#[cfg(unix)] +mod raw { + use super::*; + use std::io::{Read, Write}; + use std::os::unix::net::UnixStream; + + /// A client that speaks HTTP over the MCP socket by hand, so that a + /// test can leave an answer unread or a body unfinished. + pub struct Raw { + stream: UnixStream, + token: String, + book: String, + /// What `wait_for_bytes` took off the connection to see it. + taken: Vec, + } + + impl Raw { + pub fn connect(home: &Home, book: &str) -> Self { + let endpoint = ledger_mcp::ipc::Endpoint::new(&home.run(), "mcp.sock").unwrap(); + let stream = UnixStream::connect(endpoint.path()).unwrap(); + std::mem::forget(endpoint); + Self { + stream, + token: home.token(book), + book: book.into(), + taken: Vec::new(), + } + } + + /// Write a request whose body is `body`, of which only `sent` + /// bytes go out now (the rest is for [`Raw::finish`]). + pub fn start( + &mut self, + method: &str, + path: &str, + extra: &[(&str, &str)], + body: &[u8], + sent: usize, + ) { + let mut head = format!( + "{method} /b/{}/{path} HTTP/1.1\r\nhost: localhost\r\nauthorization: Bearer {}\r\ncontent-length: {}\r\n", + self.book, + self.token, + body.len() + ); + for (k, v) in extra { + head.push_str(&format!("{k}: {v}\r\n")); + } + head.push_str("\r\n"); + self.stream.write_all(head.as_bytes()).unwrap(); + self.stream.write_all(&body[..sent]).unwrap(); + } + + /// Wait until the server has sent something on this connection + /// (one byte is taken, and kept for [`Raw::head`]). + pub fn wait_for_bytes(&mut self) { + self.stream.set_nonblocking(true).unwrap(); + let mut byte = [0u8; 1]; + let by = std::time::Instant::now() + Duration::from_secs(60); + loop { + match self.stream.read(&mut byte) { + Ok(n) if n > 0 => { + self.taken.push(byte[0]); + break; + } + _ => { + assert!(std::time::Instant::now() < by, "the server sent nothing"); + std::thread::sleep(Duration::from_millis(5)); + } + } + } + self.stream.set_nonblocking(false).unwrap(); + } + + /// The rest of a body begun with [`Raw::start`]. + pub fn finish(&mut self, rest: &[u8]) { + self.stream.write_all(rest).unwrap(); + } + + /// The response's status line and headers (the body is left). + pub fn head(&mut self) -> (u16, String) { + self.stream + .set_read_timeout(Some(Duration::from_secs(60))) + .unwrap(); + let mut seen = std::mem::take(&mut self.taken); + let mut byte = [0u8; 1]; + while !seen.ends_with(b"\r\n\r\n") { + self.stream.read_exact(&mut byte).unwrap(); + seen.push(byte[0]); + } + let text = String::from_utf8_lossy(&seen).to_string(); + let status = text.split(' ').nth(1).unwrap().parse().unwrap(); + (status, text) + } + } +} + +/// Name a folder as the book's backup target, as an agent would. +fn set_backup_folder(w: &mut Wire, folder: &std::path::Path) { + let r = w.call( + "books.set_setting", + json!({"changes": [{"key": "backup.folder", "value": folder.display().to_string()}], + "decided_by": "Test Owner", "note": "Backups."}), + ); + assert_eq!(r["result"]["isError"], json!(false), "{r}"); +} + +/// A draft entry, journaled: its id. +fn draft(w: &mut Wire, tag: &str) -> u64 { + let r = w.call( + "books.draft_entry", + json!({"date": "2026-03-01", "description": tag}), + ); + assert_eq!(r["result"]["isError"], json!(false), "{r}"); + r["result"]["structuredContent"]["entry_id"] + .as_u64() + .unwrap() +} + +/// What the access log of `id` says, whole (read checks its chain). +fn access_of(home: &Home, id: &str) -> Vec { + ledger_store::access::read(&home.book_dir(id)) + .unwrap_or_else(|e| panic!("{id}'s access log isn't whole: {e}")) + .0 +} + +/// The tree of `id` must not move for a while, however long the server's +/// timers (a few milliseconds) and its backups and sweeps have to move it: +/// compared again and again over `window` (a window to catch a late +/// writer in, not a time anything waits for). +fn stands_still(home: &Home, id: &str, window: Duration, what: &str) { + let first = tree_of(&home.book_dir(id)); + let until = std::time::Instant::now() + window; + while std::time::Instant::now() < until { + let now = tree_of(&home.book_dir(id)); + assert_eq!(moved(&first, &now), Vec::::new(), "{what}"); + std::thread::sleep(Duration::from_millis(15)); + } +} + +/// The answer to a call a client never reads is stuck in the server's +/// socket (the tools list is over 500 KB: more than the socket holds), so +/// the book's close is made to wait for it, and may not for ever: it ends +/// the sessions after its grace, answers closed, and then nothing is +/// written to the book, whose access log stays a whole chain through the +/// reopening (local.rs INVARIANT 10; the call that was being answered ran +/// and is on record, as one whose connection dropped at any other moment). +#[cfg(unix)] +#[test] +fn a_client_that_never_reads_its_answer_cannot_hold_a_close_nor_break_the_log() { + let home = Home::new("close-unread"); + let server = Server::start_with(&home, &["--answer-grace", "700", "--timers", "10"]); + home.create(A, "USD"); + let mut w = Wire::new(&home, A); + w.initialize("reader"); + draft(&mut w, "before"); + let mut raw = raw::Raw::connect(&home, A); + let body = + json!({"jsonrpc": "2.0", "id": 77, "method": "tools/list", "params": {}}).to_string(); + raw.start( + "POST", + "mcp", + &[ + ("content-type", "application/json"), + ("accept", "application/json, text/event-stream"), + ("mcp-session-id", w.session().unwrap()), + ("mcp-protocol-version", w.version().unwrap()), + ], + body.as_bytes(), + body.len(), + ); + // The server is answering: it has sent what the socket holds, and the + // rest is stuck behind a client that doesn't read. + raw.wait_for_bytes(); + let started = std::time::Instant::now(); + assert_eq!(close_book(&home, A), CloseOutcome::Closed); + let took = started.elapsed(); + assert!( + took >= Duration::from_millis(600), + "the close didn't wait for the answer on its way out ({took:?})" + ); + assert!( + took < Duration::from_secs(30), + "the close was held by a client that never reads ({took:?})" + ); + let at_close = tree_of(&home.book_dir(A)); + stands_still( + &home, + A, + Duration::from_millis(400), + "after the close was answered", + ); + assert_eq!( + moved(&at_close, &tree_of(&home.book_dir(A))), + Vec::::new() + ); + // Opened again: the log, which the old one wrote into until the close, + // takes records against its own head. + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + let mut again = Wire::new(&home, A); + again.initialize("after"); + draft(&mut again, "after"); + // One record for each of the two drafts, in one chain across the + // close and the reopening. + let log = access_of(&home, A); + assert_eq!( + log.iter().map(|r| r.seq).collect::>(), + vec![1, 2], + "{log:?}" + ); + drop(raw); + assert!(server.close().success()); + access_of(&home, A); +} + +/// A call that journaled, whose client then went without reading the +/// answer, is on record as having run: the access record is written +/// before the answer goes, so a client that retries (nothing in these +/// calls makes a retry safe: local.rs INVARIANT 10) can find out. +#[cfg(unix)] +#[test] +fn a_call_whose_answer_was_never_read_is_on_record_as_having_run() { + let home = Home::new("close-ran"); + let server = Server::start_with(&home, &["--answer-grace", "300"]); + home.create(A, "USD"); + let mut w = Wire::new(&home, A); + w.initialize("reader"); + let mut raw = raw::Raw::connect(&home, A); + let body = json!({"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": { + "name": "books.draft_entry", + "arguments": {"date": "2026-03-01", "description": "unread"}}}) + .to_string(); + raw.start( + "POST", + "mcp", + &[ + ("content-type", "application/json"), + ("accept", "application/json, text/event-stream"), + ("mcp-session-id", w.session().unwrap()), + ("mcp-protocol-version", w.version().unwrap()), + ], + body.as_bytes(), + body.len(), + ); + // It ran (it is in the journal), and the client goes without a word. + wait_for("the draft is journaled", Duration::from_secs(30), || { + files_of(&home, A) + .0 + .iter() + .any(|l| l.payload["description"] == json!("unread")) + }); + drop(raw); + assert_eq!(close_book(&home, A), CloseOutcome::Closed); + let log = access_of(&home, A); + let rec = log + .iter() + .find(|r| r.access.subject == "books.draft_entry") + .expect("the call has a record"); + assert_eq!(rec.access.result, ledger_store::access::Outcome::Ok); + assert!(rec.access.head_after.is_some(), "{rec:?}"); + assert!(server.close().success()); +} + +/// A stand-in `git` for the server's PATH: it runs the real one, unless +/// the test has said otherwise with a file beside it: `stall` (it waits, +/// recording itself in `stalled`, until the file is gone, then in +/// `resumed`), which is how a backup is made slow. +#[cfg(unix)] +fn shim_git(home: &Home) -> PathBuf { + use std::os::unix::fs::PermissionsExt; + let dir = home.dir.path().join("shim"); + std::fs::create_dir_all(&dir).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 exe = dir.join("git"); + std::fs::write( + &exe, + format!( + "#!/bin/sh\ndir=\"$(dirname \"$0\")\"\necho \"$$ $*\" >> \"$dir/calls\"\nif [ -e \"$dir/stall\" ]; then\n echo $$ >> \"$dir/stalled\"\n while [ -e \"$dir/stall\" ]; do sleep 0.05; done\n echo $$ >> \"$dir/resumed\"\nfi\nexec {real} \"$@\"\n" + ), + ) + .unwrap(); + std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap(); + dir +} + +/// Whether process `pid` is still there. +#[cfg(unix)] +fn alive(pid: u32) -> bool { + std::path::Path::new(&format!("/proc/{pid}")).exists() + && std::fs::read_to_string(format!("/proc/{pid}/stat")) + .map(|s| !s.contains(") Z ")) + .unwrap_or(false) +} + +/// The server, with the stand-in git first on its PATH. +#[cfg(unix)] +fn server_with_shim(home: &Home, shim: &std::path::Path, args: &[&str]) -> Server { + let path = std::env::join_paths([ + shim, + std::path::Path::new("/usr/bin"), + std::path::Path::new("/bin"), + ]) + .unwrap(); + let path: PathBuf = path.into(); + Server::start_full(home, &[("PATH", path.as_path())], args) +} + +/// A book with a backup target whose backup is slow: the close is not +/// answered while the backup's work runs. Its bound lapses, git is +/// stopped (with all it started), the close waits for that to be done, +/// and says the backup wasn't whole. Nothing of the backup runs after the +/// answer, though the stall is lifted: a git left running would go on. +#[cfg(unix)] +#[test] +fn a_close_is_not_answered_while_its_backup_still_runs() { + let home = Home::new("close-slow-backup"); + let shim = shim_git(&home); + let server = server_with_shim( + &home, + &shim, + &[ + "--close-backup", + "1200", + "--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, "moves the head past the last backup"); + w.end(); + // From here every git waits. + std::fs::write(shim.join("stall"), b"").unwrap(); + let started = std::time::Instant::now(); + let outcome = close_book(&home, A); + let took = started.elapsed(); + assert!( + took >= Duration::from_millis(1100), + "answered before the backup's bound ({took:?}): {outcome:?}" + ); + assert!(took < Duration::from_secs(30), "{took:?}"); + match &outcome { + CloseOutcome::ClosedBackupIncomplete(why) => { + assert!(why.contains("longer than"), "{why}"); + home.assert_hidden(why); + } + other => panic!("a stopped backup was answered as {other:?}"), + } + // Answered: the git that was stalled is gone, with what it started. + let stalled: Vec = std::fs::read_to_string(shim.join("stalled")) + .unwrap_or_default() + .lines() + .filter_map(|l| l.trim().parse().ok()) + .collect(); + assert!(!stalled.is_empty(), "the backup never reached git"); + for pid in &stalled { + assert!( + !alive(*pid), + "git {pid} still runs after the close was answered" + ); + } + let at_close = tree_of(&home.book_dir(A)); + // The stall is lifted: anything that had survived would go on now. + std::fs::remove_file(shim.join("stall")).unwrap(); + stands_still( + &home, + A, + Duration::from_millis(500), + "after the close was answered", + ); + assert!( + !shim.join("resumed").exists(), + "a git went on after the close was answered" + ); + assert_eq!( + moved(&at_close, &tree_of(&home.book_dir(A))), + Vec::::new() + ); + // Opened again, the book's backup record is a whole chain, and it + // backs up (nothing of the old backups is in its way). + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + let status = home.admin(Request::BackUpNow { + id: A.into(), + new_disk: false, + }); + assert!(matches!(status, Response::BackedUp { .. }), "{status:?}"); + ledger_store::chain::read( + &ledger_store::ops::ops_dir(&home.book_dir(A)).join("backup.jsonl"), + "wanderbooks-backup-v1", + ) + .expect("the backup record is a whole chain"); + assert!(server.close().success()); +} + +/// A backup that fails (its disk isn't there) closes the book all the same, +/// quickly, and says so: never a plain "closed" for a backup that wasn't +/// made; and nothing runs after. +#[cfg(unix)] +#[test] +fn a_close_whose_backup_fails_says_so_and_leaves_nothing_running() { + let home = Home::new("close-failing-backup"); + let shim = shim_git(&home); + let server = server_with_shim( + &home, + &shim, + &["--backup-quiet", "3600000", "--timers", "20"], + ); + home.create(A, "USD"); + let unplugged = home.dir.path().join("elsewhere").join("unplugged"); + std::fs::create_dir_all(unplugged.parent().unwrap()).unwrap(); + let mut w = Wire::new(&home, A); + w.initialize("owner"); + set_backup_folder(&mut w, &unplugged); + draft(&mut w, "unbacked"); + w.end(); + let outcome = close_book(&home, A); + match &outcome { + CloseOutcome::ClosedBackupIncomplete(why) => { + assert!( + why.contains("failed") || why.contains("isn't there"), + "{why}" + ); + home.assert_hidden(why); + } + other => panic!("a backup that failed was answered as {other:?}"), + } + assert_eq!(listed(&home, A), (false, true, None)); + let at_close = tree_of(&home.book_dir(A)); + let calls = std::fs::read_to_string(shim.join("calls")) + .unwrap_or_default() + .lines() + .count(); + stands_still( + &home, + A, + Duration::from_millis(400), + "after the failed backup's close", + ); + assert_eq!( + moved(&at_close, &tree_of(&home.book_dir(A))), + Vec::::new() + ); + assert_eq!( + std::fs::read_to_string(shim.join("calls")) + .unwrap_or_default() + .lines() + .count(), + calls, + "git was run after the close was answered" + ); + // The same book, backed up fine, is answered plainly. + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + std::fs::create_dir(&unplugged).unwrap(); + let mut w = Wire::new(&home, A); + w.initialize("owner"); + draft(&mut w, "backed up"); + w.end(); + assert_eq!(close_book(&home, A), CloseOutcome::Closed); + assert!(server.close().success()); +} + +/// Every `.part` file (an upload being received) under `dir`. +fn parts_under(dir: &std::path::Path) -> Vec { + tree_of(dir) + .into_keys() + .filter(|k| k.ends_with(".part")) + .collect() +} + +/// Begin an upload for `bytes` as `w`, and send the first half of the +/// bytes by hand, leaving the rest for the caller: the id, and the +/// connection, with the server part way through receiving them. +#[cfg(unix)] +fn half_sent_upload(home: &Home, w: &mut Wire, book: &str, bytes: &[u8]) -> (String, raw::Raw) { + let begun = w.call( + "books.begin_upload", + common::upload_args(bytes, "r.bin", "application/octet-stream", "receipt"), + ); + let id = begun["result"]["structuredContent"]["upload_id"] + .as_str() + .unwrap_or_else(|| panic!("{begun}")) + .to_string(); + let mut raw = raw::Raw::connect(home, book); + raw.start("PUT", &format!("u/{id}"), &[], bytes, bytes.len() / 2); + // The server is receiving: its part file is there (the request is + // inside the book's door, its record not yet written). + wait_for("the upload's part file", Duration::from_secs(30), || { + !parts_under(&home.book_dir(book)).is_empty() + }); + (id, raw) +} + +/// An upload part way in when the close begins finishes before the close +/// is answered (nothing is cut, nothing half done): its bytes are kept, +/// its record written, no part file left, and nothing moves afterwards. +#[cfg(unix)] +#[test] +fn an_upload_in_flight_finishes_before_the_close_is_answered() { + let home = Home::new("close-upload"); + let server = Server::start_with(&home, &["--answer-grace", "500", "--timers", "10"]); + home.create(A, "USD"); + let mut w = Wire::new(&home, A); + w.initialize("uploader"); + let bytes: Vec = (0..200_000u32).map(|n| (n % 251) as u8).collect(); + let (id, mut raw) = half_sent_upload(&home, &mut w, A, &bytes); + let closing = std::thread::spawn({ + let home_root = home.run(); + move || { + ledger_mcp::admin::call( + &home_root.join("admin.sock"), + Request::CloseBook { id: A.into() }, + ) + .unwrap() + } + }); + wait_for("the book is listed closed", Duration::from_secs(30), || { + listed(&home, A).1 + }); + std::thread::sleep(Duration::from_millis(300)); + assert!( + !closing.is_finished(), + "the close was answered with an upload half received" + ); + raw.finish(&bytes[bytes.len() / 2..]); + let (status, head) = raw.head(); + assert_eq!(status, 200, "{head}"); + match closing.join().unwrap() { + Response::CloseBook { outcome, .. } => assert_eq!(outcome, CloseOutcome::Closed), + other => panic!("{other:?}"), + } + let tree = tree_of(&home.book_dir(A)); + assert_eq!(parts_under(&home.book_dir(A)), Vec::::new()); + assert!( + tree.keys().any(|k| k.ends_with(&format!("{id}.bin"))), + "the bytes were kept" + ); + let log = access_of(&home, A); + assert!( + log.iter().any(|r| r.access.action == "upload" + && r.access.subject == id + && r.access.result == ledger_store::access::Outcome::Ok), + "the upload's record is written before the answer: {log:?}" + ); + stands_still( + &home, + A, + Duration::from_millis(300), + "after the close was answered", + ); + assert!(server.close().success()); +} + +/// A backup of `id`, taken now to its folder target; the repository. +#[cfg(unix)] +fn backed_up_to_folder(home: &Home, w: &mut Wire, id: &str) -> PathBuf { + let disk = home.dir.path().join("disk"); + std::fs::create_dir_all(&disk).unwrap(); + set_backup_folder(w, &disk); + draft(w, "kept in the backup"); + match home.admin(Request::BackUpNow { + id: id.into(), + new_disk: false, + }) { + Response::BackedUp { targets, .. } => assert!(targets[0].problem.is_none(), "{targets:?}"), + other => panic!("{other:?}"), + } + disk.join(format!("{id}.git")) +} + +/// A restore over an open book lets go of it as a close does: what is +/// inside the book's door finishes first (an upload half received is +/// completed and recorded in the book it was sent to, and no part file is +/// left in `legacy/`), its sessions end, nothing of it moves once the +/// restore is answered. +#[cfg(unix)] +#[test] +fn a_restore_over_an_open_book_waits_for_what_is_inside_it() { + let home = Home::new("restore-drain"); + let server = Server::start_with( + &home, + &[ + "--answer-grace", + "500", + "--timers", + "10", + "--backup-quiet", + "3600000", + ], + ); + home.create(A, "USD"); + let mut w = Wire::new(&home, A); + w.initialize("owner"); + let repo = backed_up_to_folder(&home, &mut w, A); + let bytes: Vec = (0..200_000u32).map(|n| (n % 241) as u8).collect(); + let (id, mut raw) = half_sent_upload(&home, &mut w, A, &bytes); + let source = repo.display().to_string(); + let preview = match home.admin(Request::Restore { + id: A.into(), + source: source.clone(), + replace: true, + confirmed: false, + expect_head: None, + }) { + Response::RestorePreview(p) => p, + other => panic!("{other:?}"), + }; + let restoring = std::thread::spawn({ + let admin = home.run().join("admin.sock"); + move || { + ledger_mcp::admin::call( + &admin, + Request::Restore { + id: A.into(), + source, + replace: true, + confirmed: true, + expect_head: Some(preview.head), + }, + ) + .unwrap() + } + }); + // The books being replaced are no longer served as these. + wait_for( + "the replaced books are let go", + Duration::from_secs(30), + || { + let mut late = Wire::with_token(&home, A, Some(w.token().unwrap().to_string())); + late.send(&json!({"jsonrpc": "2.0", "id": 1, "method": "ping"})); + late.refused + .as_ref() + .is_some_and(|r| r.status == 404 || r.status == 503) + }, + ); + // The restore (a clone and a check of the backup, which take a second + // or so) is not answered while the upload is half received: watched + // for five seconds, in which a restore that doesn't wait would finish. + let watched = std::time::Instant::now() + Duration::from_secs(5); + while std::time::Instant::now() < watched { + assert!( + !restoring.is_finished(), + "the restore was answered with an upload half received" + ); + std::thread::sleep(Duration::from_millis(20)); + } + raw.finish(&bytes[bytes.len() / 2..]); + let (status, head) = raw.head(); + assert_eq!(status, 200, "{head}"); + let restored = match restoring.join().unwrap() { + Response::Restored(r) => r, + other => panic!("{other:?}"), + }; + let legacy = home.root().join("legacy"); + assert!(restored.replaced.is_some(), "{restored:?}"); + // No part file anywhere, and the replaced book's own log, kept in + // legacy/, is whole and holds the upload, which finished in it. + assert_eq!(parts_under(&legacy), Vec::::new()); + let old = std::fs::read_dir(&legacy) + .unwrap() + .next() + .unwrap() + .unwrap() + .path(); + let (records, _) = ledger_store::access::read(&old).expect("the replaced book's log is whole"); + assert!( + records + .iter() + .any(|r| r.access.action == "upload" && r.access.subject == id), + "{records:?}" + ); + let at_answer = tree_of(&legacy); + std::thread::sleep(Duration::from_millis(300)); + assert_eq!(moved(&at_answer, &tree_of(&legacy)), Vec::::new()); + assert!(server.close().success()); +} + +/// Downloads running while a book closes each complete whole, and are on +/// record, or are refused unrun: never cut, never answered from a book +/// after it was closed. +#[cfg(unix)] +#[test] +fn downloads_during_a_close_complete_or_are_refused() { + let home = Arc::new(Home::new("close-download")); + let server = Server::start_with(&home, &["--answer-grace", "500", "--timers", "10"]); + home.create(A, "USD"); + let mut w = Wire::new(&home, A); + w.initialize("reader"); + let bytes: Vec = (0..300_000u32).map(|n| (n % 239) as u8).collect(); + let id = w.upload(&bytes, "big.bin", "application/octet-stream", "receipt"); + let filed = w.call("books.attach_receipt", json!({"upload_id": id})); + let att = filed["result"]["structuredContent"]["attachment_id"] + .as_u64() + .unwrap_or_else(|| panic!("{filed}")); + let stop = Arc::new(AtomicBool::new(false)); + let answers = Arc::new(Mutex::new(Vec::<(u16, usize)>::new())); + let token = w.token().unwrap().to_string(); + let readers: Vec<_> = (0..4) + .map(|_| { + let (home, stop, answers, token) = + (home.clone(), stop.clone(), answers.clone(), token.clone()); + std::thread::spawn(move || { + let mut wire = Wire::with_token(&home, A, Some(token)); + while !stop.load(Ordering::SeqCst) { + let (status, body) = wire.get(&format!("a/{att}")); + answers.lock().unwrap().push((status, body.len())); + } + }) + }) + .collect(); + wait_for( + "downloads are being answered", + Duration::from_secs(30), + || answers.lock().unwrap().len() > 3, + ); + assert_eq!(close_book(&home, A), CloseOutcome::Closed); + let at_close = tree_of(&home.book_dir(A)); + let recorded = access_of(&home, A) + .iter() + .filter(|r| { + r.access.action == "download" && r.access.result == ledger_store::access::Outcome::Ok + }) + .count(); + stands_still( + &home, + A, + Duration::from_millis(300), + "after the close was answered", + ); + stop.store(true, Ordering::SeqCst); + for r in readers { + r.join().unwrap(); + } + let answers = answers.lock().unwrap().clone(); + let ok = answers.iter().filter(|(s, _)| *s == 200).count(); + for (status, len) in &answers { + match *status { + 200 => assert_eq!(*len, bytes.len(), "a download was cut"), + 503 => {} + other => panic!("a download answered {other}"), + } + } + assert_eq!( + ok, recorded, + "every download that was answered is on record, and no other" + ); + assert_eq!( + moved(&at_close, &tree_of(&home.book_dir(A))), + Vec::::new() + ); + assert!(server.close().success()); +} + +/// Every timer of the server (the sweep of lapsed uploads and exports, the +/// look for a backup due, the look for a drill due) runs every few +/// milliseconds, on a book with a backup target, closed and opened over +/// and over: while the book is closed not one file of its folder moves, +/// though files for a sweep to take are planted in it; while it is open +/// the timers work (it is backed up and drilled), and every log, at the +/// end, is a whole chain. +#[cfg(unix)] +#[test] +fn the_timers_never_touch_a_closed_book() { + let home = Home::new("close-timers"); + let server = Server::start_with( + &home, + &[ + "--timers", + "5", + "--backup-quiet", + "0", + "--drill-first", + "0", + "--answer-grace", + "300", + ], + ); + home.create(A, "USD"); + home.create(B, "USD"); + 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(); + let backup_records = |kind: &str| { + std::fs::read_to_string(home.book_dir(A).join("ops").join("backup.jsonl")) + .unwrap_or_default() + .lines() + .filter(|l| l.contains(&format!("\"kind\":\"{kind}\""))) + .count() + }; + let dir = home.book_dir(A); + for cycle in 0..8 { + // Open: the timers are at work on it, a write is backed up soon. + let pushed_before = backup_records("push"); + let mut w = Wire::new(&home, A); + w.initialize("owner"); + draft(&mut w, &format!("cycle {cycle}")); + w.end(); + wait_for("the write is backed up", Duration::from_secs(60), || { + backup_records("push") > pushed_before + }); + wait_for("its backup is drilled", Duration::from_secs(60), || { + backup_records("drill") >= 1 + }); + assert!( + matches!(close_book(&home, A), CloseOutcome::Closed), + "cycle {cycle}" + ); + // Closed: what a sweep would take is planted, and nothing moves. + for folder in ["uploads", "exports"] { + std::fs::write(dir.join(folder).join("stray.bin"), b"x").unwrap(); + } + stands_still( + &home, + A, + Duration::from_millis(150), + &format!("cycle {cycle}, closed"), + ); + assert!(dir.join("uploads").join("stray.bin").exists()); + assert!(dir.join("exports").join("stray.bin").exists()); + assert_eq!(open_book(&home, A), OpenOutcome::Opened, "cycle {cycle}"); + } + 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"); + ledger_store::Store::open(&dir).expect("the journal replays"); } diff --git a/crates/ledger-cli/tests/common/mod.rs b/crates/ledger-cli/tests/common/mod.rs index fed493f8..f735140e 100644 --- a/crates/ledger-cli/tests/common/mod.rs +++ b/crates/ledger-cli/tests/common/mod.rs @@ -187,6 +187,13 @@ impl Server { Self::spawn(home, home.dir.path(), &[], args) } + /// [`Server::start`], with `env` beside the home's own and these + /// arguments after the root (a PATH with a stand-in git first, a + /// shortened timer). + pub fn start_full(home: &Home, env: &[(&str, &Path)], args: &[&str]) -> Self { + Self::spawn(home, home.dir.path(), env, args) + } + /// [`Server::start`], in the folder `cwd`, with `env` beside the /// home's own (INVARIANT 1). pub fn start_in(home: &Home, cwd: &Path, env: &[(&str, &Path)]) -> Self { @@ -352,6 +359,16 @@ impl Wire { } } + /// The MCP session this wire opened (after `initialize`). + pub fn session(&self) -> Option<&str> { + self.session.as_deref() + } + + /// The protocol version this session negotiated. + pub fn version(&self) -> Option<&str> { + self.version.as_deref() + } + /// The token this session sends. pub fn token(&self) -> Option<&str> { self.token.as_deref() diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index 072a4efb..e1b22d2e 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -713,6 +713,15 @@ pub fn books( ); Ok(()) } + admin::CloseOutcome::ClosedBackupIncomplete(why) => { + println!( + "Closed the books \"{id}\": nothing is running on them, their sessions ended, and they are let go." + ); + eprintln!( + "warning: their last backup wasn't whole: {why}. What they hold since the last good backup isn't backed up." + ); + Ok(()) + } admin::CloseOutcome::WasNotOpen => { println!("The books \"{id}\" weren't open."); Ok(()) diff --git a/crates/ledger-mcp/src/access.rs b/crates/ledger-mcp/src/access.rs index 2392ff26..7dd30145 100644 --- a/crates/ledger-mcp/src/access.rs +++ b/crates/ledger-mcp/src/access.rs @@ -21,6 +21,14 @@ //! 4. A record's head is the journal's head after the call's own last //! write (taken under the store's lock as it lets go), whatever the //! call answered; none for a call that wrote nothing. +//! 5. A record is written only while the book is open: the log is closed +//! (ledger_store::access INVARIANT 4) when the book is let go, so a +//! refusal still being written when it was (its client gone, its +//! session ended) is refused, unwritten, and never lands in the log of +//! the book opened again. A refusal at the door is written by a task +//! that keeps the request's place inside the book's door (local.rs +//! INVARIANT 13). A call that ran is written inside its counted run, +//! before its answer goes: it is always on record. //! ``` use ledger_store::access::{Access, AccessLog, Client, Outcome, Principal, digest}; diff --git a/crates/ledger-mcp/src/admin.rs b/crates/ledger-mcp/src/admin.rs index 113d9b9f..f5656c54 100644 --- a/crates/ledger-mcp/src/admin.rs +++ b/crates/ledger-mcp/src/admin.rs @@ -35,7 +35,11 @@ //! admin requests (plan/p15-app-and-relay.md 3.1; D-77, D-78): each //! answers what happened in a word (opened, already open, closed, //! was not open, no such book, could not open with why), and a book -//! that is closed is listed as closed, which is not a problem. +//! that is closed is listed as closed, which is not a problem. A +//! close is answered only when the books are let go and nothing of +//! this process's can write to them; its last backup (a bounded +//! step) that wasn't whole is said, in `closed_backup_incomplete` +//! with why, never as a plain `closed`. //! 9. `sessions` says, for each open book, who is connected: a token's //! NAME (never its text, nor its hash), what the client and the agent //! said of themselves, when it connected, how many of its calls are @@ -367,6 +371,12 @@ pub enum CloseOutcome { /// It was open and is closed now: no call on it is running, its /// sessions ended, and another process could open it. Closed, + /// It was open and is closed as `Closed` says, but its last backup + /// wasn't whole (a target that couldn't be reached, git that failed, or + /// a backup stopped after its time): why, in words. The books on disk + /// are whole; what they hold since the last good backup is not backed + /// up. + ClosedBackupIncomplete(String), /// It was not open (closed already, or it never opened): nothing was /// done. WasNotOpen, diff --git a/crates/ledger-mcp/src/backup.rs b/crates/ledger-mcp/src/backup.rs index b589d7ba..d5e6f4d5 100644 --- a/crates/ledger-mcp/src/backup.rs +++ b/crates/ledger-mcp/src/backup.rs @@ -48,6 +48,17 @@ //! exactly as they are (journal, stored files, vault and keys), all //! under the store's lock, so nothing is written in between; a backup //! that can't be made or proven upgrades nothing. Both are records. +//! 10. These backups can be shut (`shut`), once, for good: git is stopped +//! (every command running, with all it started) and none starts; the +//! call waits for every step that was under way to END (each step's +//! count rides in its own blocking task, so it is not lost when the +//! future that began it is dropped, as a close's 60 s bound drops +//! one), and for the run or drill holding the books' turn; then the +//! backup record is closed under its own lock. After `shut` returns, +//! this holder (a timer's, a request's, any clone from before) runs +//! 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. //! ``` use crate::server::SharedStore; @@ -56,8 +67,31 @@ 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::{Arc, Mutex}; +/// What a call is told when these backups were shut (INVARIANT 10). +pub const SHUT: &str = "the books were closed: nothing was backed up"; + +/// Blocking steps of the backups under way (INVARIANT 10). +#[derive(Default)] +struct Busy { + steps: AtomicUsize, + ended: tokio::sync::Notify, +} + +/// One step under way, counted until it is dropped: it rides in the +/// step's own blocking task, so it ends with the work, not with whatever +/// was waiting for it. +struct Step(Arc); + +impl Drop for Step { + fn drop(&mut self) { + self.0.steps.fetch_sub(1, Ordering::SeqCst); + self.0.ended.notify_waiters(); + } +} + /// The book's backup record, in its `ops/`. pub const LOG_FILE: &str = "backup.jsonl"; /// The record's genesis text. @@ -79,6 +113,10 @@ pub struct Backups { log: Mutex, /// One run at a time. running: tokio::sync::Mutex<()>, + /// Set by `shut` (INVARIANT 10): git stops, nothing starts. + shut: Arc, + /// The blocking steps under way. + busy: Arc, } /// What a format upgrade did ([`Backups::upgrade_format`]). @@ -256,6 +294,8 @@ impl Backups { store, log: Mutex::new(log), running: tokio::sync::Mutex::new(()), + shut: Arc::default(), + busy: Arc::default(), }; for fields in carried { me.record(fields); @@ -284,11 +324,54 @@ impl Backups { *e = hide(e, &self.dir); } let mut log = self.log.lock().unwrap_or_else(|e| e.into_inner()); - if let Err(e) = log.append(map) { - eprintln!("wanderbooks server: the books' backup record couldn't be written: {e}"); + match log.append(map) { + Ok(_) | Err(ledger_store::chain::ChainError::Closed) => {} + Err(e) => { + eprintln!("wanderbooks server: the books' backup record couldn't be written: {e}"); + } } } + /// Whether these backups were shut (INVARIANT 10). + fn is_shut(&self) -> bool { + self.shut.load(Ordering::SeqCst) + } + + /// A step begins: counted before the shut flag is looked at, and + /// `shut` sets the flag before it looks at the count, so a step either + /// sees them shut or is waited for, never neither (INVARIANT 10). + fn begin(&self) -> Result { + self.busy.steps.fetch_add(1, Ordering::SeqCst); + let step = Step(self.busy.clone()); + if self.is_shut() { + return Err(SHUT.to_string()); + } + Ok(step) + } + + /// git, stopped by `shut`. + fn git(&self) -> Result { + Ok(Git::find()?.with_cancel(self.shut.clone())) + } + + /// Shut these backups for good (INVARIANT 10): git stopped, every step + /// ended, the record closed. Call it after the last backup the books + /// will have, and before the books' store is let go. + pub async fn shut(&self) { + self.shut.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; + loop { + let ended = self.busy.ended.notified(); + if self.busy.steps.load(Ordering::SeqCst) == 0 { + break; + } + ended.await; + } + self.log.lock().unwrap_or_else(|e| e.into_inner()).close(); + } + fn records(&self) -> Vec> { ledger_store::chain::read( &ledger_store::ops::ops_dir(&self.dir).join(LOG_FILE), @@ -328,12 +411,6 @@ impl Backups { } } - /// Wait for any run or drill to end, and start none while the guard - /// lives: books being replaced by a restore push nothing more. - pub async fn pause(&self) -> tokio::sync::MutexGuard<'_, ()> { - self.running.lock().await - } - /// The books' head now. pub async fn head(&self) -> Option<(u64, String)> { let store = self.store.clone(); @@ -356,15 +433,21 @@ impl Backups { let _one = self.running.lock().await; // Books let go of (closed, or replaced by a restore) push nothing // more, and leave no record of a run that never began. + if self.is_shut() { + return Err(SHUT.to_string()); + } if self.store.is_stopped() { return Err(crate::server::STOPPED.to_string()); } if self.named().await.is_empty() { return Ok(self.status().await); } + let step = self.begin()?; let (store, dir, book) = (self.store.clone(), self.dir.clone(), self.book.clone()); + let git = self.git(); let made = tokio::task::spawn_blocking(move || { - let git = Git::find()?; + let _step = step; + let git = git?; // The stored files first, outside the lock: they never change. // Only a head start (a file being written can trip it): the // commit stages them all again. @@ -405,10 +488,12 @@ impl Backups { } // Its repository is made only where it never took a backup. let may_create = new_disk || !held_before(&n.key, &records); + let step = self.begin()?; + let git = self.git(); let (dir, book, t) = (self.dir.clone(), self.book.clone(), n.target.clone()); let pushed = tokio::task::spawn_blocking(move || { - let git = Git::find()?; - backup::push(&git, &dir, &book, &t, may_create) + let _step = step; + backup::push(&git?, &dir, &book, &t, may_create) }) .await .unwrap_or(Err(BackupError::Damaged("the push stopped".into()))); @@ -442,8 +527,15 @@ impl Backups { /// the targets take them at the next backup, the books having moved. pub async fn upgrade_format(&self) -> Result { let _one = self.running.lock().await; + // Books let go of, between the request's start and now, upgrade + // nothing and leave no record (a failure written through this + // handle would land in the book's record after it was opened + // 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 done = tokio::task::spawn_blocking(move || { + let _step = step; // Books that wait for nothing are left as they are: not even // their archive is made or staged (asked again under the lock // below; only an upgrade moves the format, one at a time). @@ -459,7 +551,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(); + let git = Git::find().map(|g| g.with_cancel(cancel)); if let Ok(git) = &git { let _ = backup::stage_blobs(git, &dir); } @@ -552,18 +644,21 @@ impl Backups { /// Whether a drill is due (INVARIANT 5). pub async fn drill_due(&self) -> bool { + // Through the store first: books let go name no target, and their + // record isn't read for a timer. + let named = self.named().await; + if named.is_empty() || self.is_shut() { + return false; + } let records = self.records(); let now = chrono::Utc::now(); - self.named() - .await - .iter() - .any(|n| drill_due(&n.key, &records, now)) + named.iter().any(|n| drill_due(&n.key, &records, now)) } /// Drill each target whose drill is due (INVARIANT 5), each recorded. pub async fn drill(&self) { let _one = self.running.lock().await; - if self.store.is_stopped() { + if self.is_shut() || self.store.is_stopped() { return; } let records = self.records(); @@ -572,11 +667,16 @@ impl Backups { if paused(&n.key, &records) || !drill_due(&n.key, &records, now) { continue; } + let Ok(step) = self.begin() else { + return; + }; + let git = self.git(); let (dir, book, t) = (self.dir.clone(), self.book.clone(), n.target.clone()); let drilled = tokio::task::spawn_blocking(move || { + let _step = step; let scratch = ledger_store::ops::ops_dir(&dir).join(format!("drill-{}", t.kind())); let _ = std::fs::remove_dir_all(&scratch); - let git = Git::find()?; + let git = git?; backup::drill( &git, &t, diff --git a/crates/ledger-mcp/src/local.rs b/crates/ledger-mcp/src/local.rs index 39b73d89..6803f500 100644 --- a/crates/ledger-mcp/src/local.rs +++ b/crates/ledger-mcp/src/local.rs @@ -70,12 +70,18 @@ //! 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 call already //! running on it, on any route, finishes (nothing is killed, nothing -//! is half-done); the book's last backup is made as at the server's -//! close; its MCP sessions end; its store is let go, its writer lock -//! released, so another process could open it; and only then is -//! "closed" answered. After that answer no call on that book runs -//! until it is opened again. Every other book keeps serving, and a -//! call on it is never held up by this one's close. +//! is half-done); the answers on their way out are sent, for the +//! answer grace at most; its MCP sessions end; its last backup is +//! made, for BACKUP_AT_CLOSE at most; and the book is let go +//! (INVARIANT 13), its writer lock released, so another process could +//! open it; and only then is a close answered. It is answered +//! `closed`, or `closed_backup_incomplete` with why when its last +//! backup wasn't whole (a target that failed, git that failed, a +//! backup stopped after its time): never a plain `closed` for a backup +//! that wasn't made. After that answer no call on that book runs until +//! it is opened again. Every other book keeps serving, and a call on +//! it is never held up by this one's close. A restore over an open +//! book lets go of it the same way (but for its last backup). //! 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 @@ -86,6 +92,36 @@ //! self-report, when it connected, its calls running now, and its last //! call (sessions.rs); a session that ended is not listed, and a //! book's sessions end with the book. +//! 13. After a close of a book is answered, this process holds nothing +//! that can write to that book's folder (journal, access log, ops +//! logs, stored files, upload parts, the backup's git repository) or +//! read it on a caller's behalf, until the book is opened again; and +//! a handle from before a close can never write after a reopen. Every +//! path that touches a book is either counted by its gate (a request +//! carries its place inside the door until its last write is done, +//! even if its client hangs up and its future is dropped; a timer's +//! sweep takes the place too), or checks, under the same lock as its +//! write, that the book is still open, and refuses if not: the +//! access log, the uploads, the exports and the backups (record, +//! git, drill, upgrade) are each closed under the lock their own +//! writes go in under, by the close, once the gate is empty; the +//! store is let go under its lock. A close waits for the backup's +//! work to END, not only for its future: a run past its bound is +//! stopped (git killed with all it started) and waited for, so the +//! close is never answered while a backup runs. The timers (the +//! sweep, the look for a backup due, the look for a drill due) work +//! on handles that are closed with the book, and so can't act on a +//! book that closed, or was opened again, since they looked. +//! 14. A call whose answer isn't read within the answer grace is the same +//! case as a connection that dropped at any other moment: the close +//! ends the session after the grace, and a call that ran stays run. +//! Its access record, written before its answer goes, says it ran +//! (outcome and the journal head after it), so a client that +//! reconnects can find out whether to ask again. Nothing in the +//! journaled calls makes asking again safe (they carry no client key, +//! and none checks for a duplicate): a draft asked for twice is two +//! drafts. That is an open design point (plan/p15-app-and-relay.md), +//! not something the close hides. //! SCENARIOS: //! 1. Two books open; one is closed while agents call both: the other //! answers throughout, the closed one's calls are refused unrun @@ -99,6 +135,18 @@ //! 4. A book is closed, then another process opens the store and writes //! to it: the lock was released; the server, asked to open it, says //! another program has it open, and opens once that one lets go. +//! 5. A client asks for a large answer and never reads it, and a close +//! begins: the close waits the answer grace, ends the session and +//! answers closed; nothing is written to the book afterwards, and when +//! it is opened again its access log continues one whole chain. +//! 6. A book with a slow backup is closed: not answered while the backup +//! runs; at its bound git is stopped and waited for, and the answer +//! says the last backup wasn't whole; nothing runs after. +//! 7. A restore replaces an open book while an upload is half received: +//! the restore is not answered until the upload is, and no part file +//! is left in `legacy/`. +//! 8. The timers run every few milliseconds on a book that is closed and +//! opened over and over: while it is closed not a file of it moves. //! ``` use crate::admin::{self, Request, Response}; @@ -156,6 +204,34 @@ const DRILL_FIRST: Duration = Duration::from_secs(60); /// The most the last backup at a close may take. const BACKUP_AT_CLOSE: Duration = Duration::from_secs(60); +/// The periods and bounds the server keeps, which tests shorten +/// (`--timers`, `--close-backup`, `--answer-grace`). +#[derive(Clone, Copy, Debug)] +pub(crate) struct Timers { + /// How often each book's lapsed uploads and exports are swept. + sweep_every: Duration, + /// How often the books are looked at for a backup due. + backup_look: Duration, + /// How often each book is looked at for a drill due. + drill_look: Duration, + /// The most the last backup at a book's close may take. + backup_at_close: Duration, + /// How long a close waits for answers on their way out. + answer_grace: Duration, +} + +impl Default for Timers { + fn default() -> Self { + Self { + sweep_every: SWEEP_EVERY, + backup_look: BACKUP_LOOK, + drill_look: DRILL_LOOK, + backup_at_close: BACKUP_AT_CLOSE, + answer_grace: ANSWER_GRACE, + } + } +} + type Service = StreamableHttpService; /// What a call is told for a book that exists but is closed (INVARIANT @@ -212,6 +288,43 @@ impl Book { Book::Failed(why) => Some(why.clone()), } } + + /// What lets go of it, if it is open. + fn parts(&self) -> Option { + match self { + Book::Open { + gate, + store, + access, + uploads, + exports, + backups, + ended, + .. + } => Some(Parts { + gate: gate.clone(), + store: store.clone(), + access: access.clone(), + uploads: uploads.clone(), + exports: exports.clone(), + backups: backups.clone(), + ended: ended.clone(), + }), + Book::Failed(_) | Book::Closed => None, + } + } +} + +/// Everything of an open book that can reach its folder, held so it can +/// be let go of together ([`Books::release`]). +struct Parts { + gate: Arc, + store: Arc, + access: Arc, + uploads: ledger_store::uploads::Uploads, + exports: ledger_store::exports::Exports, + backups: Arc, + ended: CancellationToken, } /// One book's door (INVARIANT 10): requests are counted as they enter, and @@ -384,6 +497,8 @@ struct Books { /// How these books are kept from agents (plan 3.8, P9a): what /// `books.start` reports (`--isolation`). isolation: Isolation, + /// The periods and bounds (tests shorten them). + timers: Timers, } impl Books { @@ -409,9 +524,16 @@ impl Books { drill_first, lifecycle: Mutex::new(()), isolation, + timers: Timers::default(), } } + /// These books, with these periods and bounds. + fn with_timers(mut self, timers: Timers) -> Self { + self.timers = timers; + self + } + /// Take the root's path out of a message (INVARIANT 7). fn hide(&self, text: impl Into) -> String { let mut text = text.into(); @@ -1060,17 +1182,9 @@ impl Books { return Response::Refused("the books are closing: nothing was done".into()); } let held = self.held().get(id.as_str()).cloned(); - let (gate, store, backups, ended) = match held { - Some(Book::Open { - gate, - store, - backups, - ended, - .. - }) => (gate, store, backups, ended), - Some(Book::Failed(_) | Book::Closed) => { - return said(admin::CloseOutcome::WasNotOpen); - } + let parts = match held.as_ref().and_then(Book::parts) { + Some(parts) => parts, + None if held.is_some() => return said(admin::CloseOutcome::WasNotOpen), None => { return match self.root.list_books() { Ok(ids) if ids.iter().any(|i| i.as_str() == id.as_str()) => { @@ -1083,33 +1197,92 @@ impl Books { }; let rt = tokio::runtime::Handle::current(); // No new call gets in; the book is listed closed. - gate.shut(); + parts.gate.shut(); self.hold(&id, Book::Closed); + let backup = self.release(&rt, &id, &parts, true); + eprintln!("wanderbooks server: the books {id} were closed"); + said(match backup { + None => admin::CloseOutcome::Closed, + Some(why) => admin::CloseOutcome::ClosedBackupIncomplete(why), + }) + } + + /// Let go of an open book whose door is shut (INVARIANT 10; a close + /// and a replacing restore are this): its calls finish, its sessions + /// end, its last backup is made (a close's), and then nothing of this + /// process's reaches its folder, however a holder of its handles from + /// before is used. Returns why the last backup wasn't whole, if it + /// wasn't (None: made, or no target to make it to). + /// + /// In this order, each step ending before the next begins: + /// 1. the store's tools finish, and its door empties (every request + /// inside has finished, its record written); + /// 2. the answers on their way out are sent, for ANSWER_GRACE at most: + /// a client that never reads its answer doesn't hold the book + /// open (the call it was answering ran and is in the journal and + /// the access log; the client may retry it: INVARIANT 10); + /// 3. its MCP sessions end; + /// 4. the last backup, for `backup_at_close` at most; the backups are + /// then shut, which stops a run still going (git killed) and waits + /// for it to end, so the answer never comes while it runs; + /// 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( + &self, + rt: &tokio::runtime::Handle, + id: &BookId, + parts: &Parts, + last_backup: bool, + ) -> Option { + let Parts { + gate, + store, + access, + uploads, + exports, + backups, + ended, + } = parts; // No tool starts, and every one that did start has finished. rt.block_on(store.close()); - // Every request inside the door has finished, its record written; - // and the answers on their way out are sent (for a while at most: a - // client that never reads its answer doesn't hold the book open, - // as at the server's close). rt.block_on(gate.emptied()); if rt - .block_on(tokio::time::timeout(ANSWER_GRACE, gate.answered())) + .block_on(tokio::time::timeout( + self.timers.answer_grace, + gate.answered(), + )) .is_err() { eprintln!( "wanderbooks server: a client didn't take its answer; closing the books {id} without it" ); } - // Its sessions end, and are forgotten. - self.end_sessions(&id, &ended); - // The last backup, as at the server's close; then nothing more of - // the backups' reaches the books, and the store is let go. - let _ = rt.block_on(tokio::time::timeout(BACKUP_AT_CLOSE, backups.run("close"))); - let _paused = rt.block_on(backups.pause()); + 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(); + // A run still going is stopped, and waited for: nothing of the + // backups runs once this returns. + rt.block_on(backups.shut()); + access.close(); + uploads.close(); + exports.close(); rt.block_on(store.let_go()); - drop(_paused); - eprintln!("wanderbooks server: the books {id} were closed"); - said(admin::CloseOutcome::Closed) + problem.map(|why| self.hide(why)) } /// End the MCP sessions of the book `id` and forget their bindings. @@ -1249,9 +1422,12 @@ impl Books { id.as_str() )); } - // The books replaced are let go (their writer lock released), - // their backups idle until the restore is done: none of theirs - // reaches a target after the backup is read. + // The books replaced are let go as a close lets go of a book, but + // for its last backup (INVARIANT 10): their door shut, the calls + // inside finished (a download answered or refused, an upload's part + // file gone), their sessions ended, their backups stopped and + // waited for (none of theirs reaches a target after the backup is + // read), their logs and files closed, their writer lock released. let old = if replace { self.held .write() @@ -1260,22 +1436,11 @@ impl Books { } else { None }; - let old_backups = match &old { - Some(Book::Open { backups, .. }) => Some(backups.clone()), - _ => None, - }; - let rt = tokio::runtime::Handle::current(); - // Its requests end first (a books.back_up_now among them waits for - // a run of the loop's), then its last run. - if let Some(Book::Open { - store, gate, ended, .. - }) = &old - { - gate.shut(); - rt.block_on(store.let_go()); - self.end_sessions(&id, ended); + if let Some(parts) = old.as_ref().and_then(Book::parts) { + let rt = tokio::runtime::Handle::current(); + parts.gate.shut(); + self.release(&rt, &id, &parts, false); } - let _paused = old_backups.as_ref().map(|b| rt.block_on(b.pause())); match self.root.restore(&git, &source, &id, &expect_head, replace) { Ok(r) => { // Restored: kept whether or not it opens; its backups told @@ -1524,8 +1689,16 @@ impl Asked { /// A request refused at the door: recorded in the book's access log /// (access.rs INVARIANT 3), then answered with `status` and `why`. +/// +/// The record is written by a blocking task that carries the request's +/// place inside the book's door (`inside`) until the record is on disk, +/// even if the client hangs up and this future is dropped meanwhile: a +/// close of the book waits for it (INVARIANT 10), so it never lands in the +/// access log of a book that was let go, nor, once the book is opened again, +/// against the new log's head. async fn refused_at_door( book: &Book, + inside: Inside, principal: Principal, asked: &Asked, code: &'static str, @@ -1547,7 +1720,11 @@ async fn refused_at_door( head_after: None, agent: None, }; - let written = tokio::task::spawn_blocking(move || access.record(&record)).await; + let written = tokio::task::spawn_blocking(move || { + let _inside = inside; + access.record(&record) + }) + .await; if !matches!(written, Ok(Ok(_))) { store.stop(); return ( @@ -1652,6 +1829,7 @@ async fn door( .map_or_else(|_| Principal::unknown(), principal); return Err(refused_at_door( &held, + inside, who, asked, crate::access::CLOSING, @@ -1666,6 +1844,7 @@ async fn door( Err((code, why)) => { return Err(refused_at_door( &held, + inside, Principal::unknown(), asked, code, @@ -1679,6 +1858,7 @@ async fn door( if token.book != book { return Err(refused_at_door( &held, + inside, principal(&token), asked, "wrong_books", @@ -2081,7 +2261,7 @@ async fn mcp( // Inside the book's door (INVARIANT 10) until the request is answered: // a close of the book waits for it, and its tools are counted by the // store (SharedStore INVARIANT 3). - let (held, token, _inside) = + let (held, token, inside) = match door(&books, &book, &Asked::connect(&method), request.headers()).await { Ok(passed) => passed, Err(refused) => return *refused, @@ -2131,6 +2311,7 @@ async fn mcp( if full { return refused_at_door( &held, + inside, principal(&token), &Asked::connect(&method), "too_many_sessions", @@ -2142,6 +2323,7 @@ async fn mcp( if elsewhere { return refused_at_door( &held, + inside, principal(&token), &Asked::connect(&method), "session_token", @@ -2194,7 +2376,7 @@ async fn mcp( // and for this book's, until its body ends. A standalone event stream // (a GET) is no answer, and ends only with its session, after the close // has waited for the answers. - let answering = (method != axum::http::Method::GET).then(|| _inside.answering()); + let answering = (method != axum::http::Method::GET).then(|| inside.answering()); response.map(|body| { use http_body_util::BodyExt; axum::body::Body::new(body.map_frame(move |frame| { @@ -2322,6 +2504,7 @@ pub fn run( let mut root: Option = None; let mut backup_quiet = BACKUP_QUIET; let mut drill_first = DRILL_FIRST; + let mut timers = Timers::default(); let mut isolation = Isolation::SameUser; let mut tunnel: Option = None; let mut open_at_start = OpenAtStart::All; @@ -2370,6 +2553,33 @@ pub fn run( .ok_or("--drill-first needs milliseconds")?; drill_first = Duration::from_millis(ms); } + // The periods of the sweep, the backup look and the drill look + // (tests: every timer at a few milliseconds). + "--timers" => { + let ms: u64 = args + .next() + .and_then(|v| v.parse().ok()) + .ok_or("--timers needs milliseconds")?; + let every = Duration::from_millis(ms.max(1)); + (timers.sweep_every, timers.backup_look, timers.drill_look) = (every, every, every); + } + // How long a book's last backup may take at its close (tests). + "--close-backup" => { + let ms: u64 = args + .next() + .and_then(|v| v.parse().ok()) + .ok_or("--close-backup needs milliseconds")?; + timers.backup_at_close = Duration::from_millis(ms); + } + // How long a book's close waits for answers on their way out + // (tests). + "--answer-grace" => { + let ms: u64 = args + .next() + .and_then(|v| v.parse().ok()) + .ok_or("--answer-grace needs milliseconds")?; + timers.answer_grace = Duration::from_millis(ms); + } "--help" | "-h" => { print_usage(prog); return Ok(()); @@ -2442,12 +2652,9 @@ pub fn run( ledger_store::winsec::set_owner_only(&lock_path) .map_err(|e| format!("can't make the server lock private: {}", e.kind()))?; } - let books = Arc::new(Books::new( - root.clone(), - backup_quiet, - drill_first, - isolation, - )); + let books = Arc::new( + Books::new(root.clone(), backup_quiet, drill_first, isolation).with_timers(timers), + ); { let loaded = books.load_principals(); if let Err(why) = &loaded { @@ -2554,10 +2761,15 @@ async fn serve( let (backing, backup_stop) = (books.clone(), stop.clone()); let backup_loop = tokio::spawn(async move { keep_backed_up(backing, backup_stop).await }); // Every open book's lapsed uploads go within SWEEP_EVERY of lapsing, - // whatever else the server is doing (uploads.rs INVARIANT 3). + // whatever else the server is doing (uploads.rs INVARIANT 3). A sweep + // of a book is inside its door, as a request is (INVARIANT 10): a close + // waits for it, and a book whose door is shut isn't swept; the book's + // uploads and exports are closed as it is let go, so a sweep that + // took its handles earlier can't touch a book that closed or was + // opened again since. let (sweeping, sweep_stop) = (books.clone(), stop.clone()); tokio::spawn(async move { - let mut tick = tokio::time::interval(SWEEP_EVERY); + let mut tick = tokio::time::interval(sweeping.timers.sweep_every); loop { tokio::select! { () = sweep_stop.cancelled() => break, @@ -2566,15 +2778,15 @@ async fn serve( .held() .values() .filter_map(|b| match b { - Book::Open { uploads, exports, .. } => { - Some((uploads.clone(), exports.clone())) - } + Book::Open { uploads, exports, gate, .. } => gate + .enter() + .map(|inside| (uploads.clone(), exports.clone(), inside)), Book::Failed(_) | Book::Closed => None, }) .collect(); let now = chrono::Utc::now().timestamp(); let _ = tokio::task::spawn_blocking(move || { - for (u, x) in &held { + for (u, x, _inside) in &held { u.sweep(now); x.sweep(now); } @@ -2641,7 +2853,10 @@ async fn serve( }) .collect(); for b in held { - let _ = tokio::time::timeout(BACKUP_AT_CLOSE, b.run("close")).await; + 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. @@ -2829,6 +3044,26 @@ fn every_target_held(status: &crate::backup::Status) -> bool { .all(|t| t.paused || t.last_error.is_none()) } +/// Why the last backup at a close wasn't whole, if it wasn't: a target +/// that failed, or lacks the books' head (a target paused for books +/// restored as a copy of others is no failure). None when there is +/// nothing to say, or no target. +fn backup_incomplete(status: &crate::backup::Status) -> Option { + let lacking: Vec = status + .targets + .iter() + .filter(|t| !t.paused) + .filter_map(|t| match (&t.last_error, t.through_seq) { + (Some(why), _) => Some(format!("{} failed: {why}", t.at)), + (None, through) if through != Some(status.head_seq) => { + Some(format!("{} doesn't hold the books' latest", t.at)) + } + (None, _) => None, + }) + .collect(); + (!lacking.is_empty()).then(|| format!("the backup to {}", lacking.join("; "))) +} + /// Whether to look for a drill due now (then again DRILL_LOOK on). fn drill_look_due(seen: &Watch, now: Instant) -> bool { now >= seen.drill_next @@ -2839,7 +3074,7 @@ fn drill_look_due(seen: &Watch, now: Instant) -> bool { /// Until `stop`. async fn keep_backed_up(books: Arc, stop: CancellationToken) { let mut seen: BTreeMap = BTreeMap::new(); - let mut tick = tokio::time::interval(BACKUP_LOOK); + let mut tick = tokio::time::interval(books.timers.backup_look); loop { tokio::select! { () = stop.cancelled() => return, @@ -2899,7 +3134,7 @@ async fn keep_backed_up(books: Arc, stop: CancellationToken) { } // Drills (backup.rs INVARIANT 5). if drill_look_due(s, now) { - s.drill_next = now + DRILL_LOOK; + s.drill_next = now + books.timers.drill_look; if backups.drill_due().await { backups.drill().await; } @@ -4293,4 +4528,192 @@ mod tests { .await; assert_eq!(answer(r).await.0, 404); } + + /// Everything in a folder, by relative path. + fn digest_of_tree(dir: &Path) -> BTreeMap> { + fn walk(base: &Path, at: &Path, out: &mut BTreeMap>) { + let Ok(entries) = std::fs::read_dir(at) else { + return; + }; + for e in entries.flatten() { + let path = e.path(); + if path.is_dir() { + walk(base, &path, out); + } else if let Ok(bytes) = std::fs::read(&path) { + out.insert( + path.strip_prefix(base).unwrap().display().to_string(), + bytes, + ); + } + } + } + let mut out = BTreeMap::new(); + walk(dir, dir, &mut out); + out + } + + /// A refusal's access record is written by a blocking task that keeps + /// the request's place inside the book's door: when the client hangs up + /// and the request's future is dropped while the record still waits for + /// a thread, a close still waits for it (INVARIANT 10). Before, the + /// place went with the future, and the record could land after the + /// close was answered, and after a reopening against the new log's head. + #[test] + fn a_refusal_being_recorded_keeps_its_place_when_its_client_hangs_up() { + let home = tempfile::tempdir().unwrap(); + // One blocking thread, held: the record can only wait for it. + let rt = tokio::runtime::Builder::new_current_thread() + .max_blocking_threads(1) + .enable_all() + .build() + .unwrap(); + let books = books_in(home.path()); + create(&books, "acme"); + let (gate, access) = match books.held().get("acme") { + Some(Book::Open { gate, access, .. }) => (gate.clone(), access.clone()), + _ => panic!("acme is open"), + }; + rt.block_on(async { + let (release, held) = std::sync::mpsc::channel::<()>(); + let blocker = tokio::task::spawn_blocking(move || { + let _ = held.recv(); + }); + // A request with a token nobody knows: refused at the door; its + // future is dropped while the record waits for the thread. + let gone = tokio::time::timeout( + Duration::from_millis(100), + at_the_door(&books, "acme", "no such token"), + ) + .await; + assert!(gone.is_err(), "the record was written with no thread free"); + assert_eq!( + gate.inside.load(Ordering::SeqCst), + 1, + "the request's place inside the door went with its future" + ); + // A close begun now waits for it. + gate.shut(); + let waiting = tokio::time::timeout(Duration::from_millis(100), gate.emptied()).await; + assert!(waiting.is_err(), "the door emptied with a record pending"); + release.send(()).unwrap(); + blocker.await.unwrap(); + tokio::time::timeout(Duration::from_secs(10), gate.emptied()) + .await + .expect("the door empties once the record is written"); + assert_eq!(access.head().seq, 1, "the record was written"); + }); + } + + /// Whatever of a book this process holds from before its close does + /// nothing after it, though the same book is open again (INVARIANT + /// 10): its access log, uploads, exports and backups write, sweep, run + /// and record nothing, so the reopened book's files, and the chain + /// of its logs, are only what the reopened book wrote. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn handles_from_before_a_close_do_nothing_after_the_book_is_open_again() { + let home = tempfile::tempdir().unwrap(); + let books = books_in(home.path()); + let dir = old_books(&books, "acme"); + let auth = books.root.auth_dir().unwrap(); + ledger_store::passphrase::set(&auth, PASS, None).unwrap(); + let (access, uploads, exports, backups) = match books.held().get("acme") { + Some(Book::Open { + access, + uploads, + exports, + backups, + .. + }) => ( + access.clone(), + uploads.clone(), + exports.clone(), + backups.clone(), + ), + _ => panic!("acme is open"), + }; + assert_eq!( + ask(&books, Request::CloseBook { id: "acme".into() }).await, + closed("acme") + ); + assert_eq!( + ask(&books, Request::OpenBook { id: "acme".into() }).await, + opened("acme", admin::OpenOutcome::Opened) + ); + // The reopened book's own backups write records (its format + // upgrade is a backup and a record), moving the log's head on from + // where the old handle left it: an old handle that appended now + // would break the chain. + match upgrade(&books, "acme", PASS).await { + Response::FormatUpgraded(_) => {} + other => panic!("{other:?}"), + } + let before = digest_of_tree(&dir); + // Stray files a sweep would take, and a grant it would lapse. + let now = chrono::Utc::now().timestamp() + 10_000_000; + let stray = dir + .join(ledger_store::uploads::UPLOADS_DIR) + .join("stray.bin"); + std::fs::write(&stray, b"x").unwrap(); + let before = { + let mut b = before; + b.insert( + format!("{}/stray.bin", ledger_store::uploads::UPLOADS_DIR), + b"x".to_vec(), + ); + b + }; + // The late record of a refused call, a timer's sweep, an upload, an + // export, a run, a drill and an upgrade, all through old handles. + let late = Access { + principal: Principal::unknown(), + client: None, + request_id: None, + action: "connect".into(), + subject: "POST".into(), + args_digest: None, + result: Outcome::Refused("closing".into()), + head_after: None, + agent: None, + }; + assert!(access.record(&late).is_err()); + uploads.sweep(now); + exports.sweep(now); + assert!( + uploads + .grant( + "t", + &ledger_store::journal::sha256_hex(b"b"), + 1, + "text/plain", + "a.txt", + "receipt", + now + ) + .is_err() + ); + assert!(exports.put("t", "a.csv", "text/csv", b"x", now).is_err()); + assert!(backups.run("write").await.is_err()); + assert!(backups.run_with("asked", true).await.is_err()); + backups.drill().await; + assert!(!backups.drill_due().await); + assert!(backups.upgrade_format().await.is_err()); + assert_eq!( + digest_of_tree(&dir), + before, + "an old handle changed the reopened book's files" + ); + // The reopened book's own logs are whole and take records. + ledger_store::access::read(&dir).expect("the access log is whole"); + let new_backups = match books.held().get("acme") { + Some(Book::Open { backups, .. }) => backups.clone(), + _ => panic!("acme is open"), + }; + assert!(!Arc::ptr_eq(&backups, &new_backups)); + ledger_store::chain::read( + &ledger_store::ops::ops_dir(&dir).join(crate::backup::LOG_FILE), + "wanderbooks-backup-v1", + ) + .expect("the backup record is whole"); + let _ = std::fs::remove_file(stray); + } } diff --git a/docs/mcp-interface.md b/docs/mcp-interface.md index 0dc955cd..e423e824 100644 --- a/docs/mcp-interface.md +++ b/docs/mcp-interface.md @@ -355,18 +355,40 @@ didn't open, with why). Protocol version 1: the requests are new, the rebuilt, a format upgrade waited for as at the start). Answers `opened`, `already_open`, `no_such_book`, or `could_not_open` with why (the book stays listed, with that `problem`). -- `close_book { id }` answers `closed`, `was_not_open` or `no_such_book`. +- `close_book { id }` answers `closed`, `closed_backup_incomplete` (with + why), `was_not_open` or `no_such_book`. In this order: new calls on the book are refused (the door is shut and the book listed closed); the calls running on it finish, on every route - (nothing is killed, nothing is half-done); 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; its store is let go, releasing the - writer lock, so another process could open the book. Only then is - "closed" answered. Every other book keeps serving, and none of its - calls waits for this close. For every call, either it ran completely - and is in the journal, or it was refused unrun and nothing of it is; after - the answer, no call on that book runs until it is opened again. + (nothing is killed, nothing is half-done); the answers on their way out + are sent, for 10 seconds at most (a client that never reads its answer + doesn't hold the book open); 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: + 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 + 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 + writer lock, so another process could open the book. Only then is the + close answered: `closed`, or `closed_backup_incomplete` when the last + backup wasn't whole (a target failed, or the backup was stopped after + its time): the book is closed all the same, and what it holds since the + last good backup isn't backed up. Every other book keeps serving, and + none of its calls waits for this close. For every call, either it ran + completely and is in the journal, or it was refused unrun and nothing of + it is; after the answer, no call on that book runs until it is opened + again. **A call whose answer was never read** (the client was slow, or + gone, and the grace ran out) is the same case as a connection dropped at + any other moment: the call ran, and its access record, written before the + answer went, says so (outcome and head). Nothing in the journaled tools + makes asking again safe: they carry no client key and none checks for a + duplicate, so a draft asked for twice is two drafts. A client that + reconnects after a close should read the book's state (or the access + record, `books.audit`) before it repeats a write. A restore over an open + book (`restore --replace`) lets go of the book in the same way (waits for + what is inside the book's door, ends its sessions, stops its backups, + closes its logs) before it moves the book into `legacy/`. - `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 2be2a2fa..165eaff7 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -4310,13 +4310,23 @@ 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 and 4 on another make journaled drafts and reads while the first is closed and reopened 12 times; 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` | an rmcp client keeps its standalone event stream (a GET) open: 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) | +| `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::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) | +| `ledger-store` `access::tests::a_closed_log_writes_nothing_and_a_reopened_one_stays_whole`, `uploads::tests::closed_uploads_change_nothing`, `exports::tests::closed_exports_change_nothing_and_give_nothing`, `backup::tests::a_cancelled_git_stops_what_runs_and_starts_nothing` | the closed state of each handle (under the lock its writes go in under), and git's cancel flag (a running command is stopped with all it started, none starts) | +| `book_open_close::a_client_that_never_reads_its_answer_cannot_hold_a_close_nor_break_the_log` | a client asks for the 500 KB tools list and never reads it (the answer is stuck in the socket): the close waits the answer grace (shortened to 700 ms) and then answers; the folder doesn't move afterwards; after the reopening the access log is one whole chain | +| `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) | +| `book_open_close::a_close_whose_backup_fails_says_so_and_leaves_nothing_running` | a target whose disk isn't there: `closed_backup_incomplete` naming the failure, quickly, no git run afterwards; the same book with its disk back is answered plainly `closed` | +| `book_open_close::an_upload_in_flight_finishes_before_the_close_is_answered` | an upload half received when the close begins: the close isn't answered until it is complete (200), its bytes are kept, its record is written, no `.part` is left, nothing moves afterwards | +| `book_open_close::a_restore_over_an_open_book_waits_for_what_is_inside_it` | a replacing restore over a book with an upload half received isn't answered for five seconds (a restore that doesn't wait takes about one); the upload then completes, the replaced book's log in `legacy/` holds it, is whole, no `.part` is left in `legacy/`, and it stands still (fails when the restore lets the store go without the drain) | +| `book_open_close::downloads_during_a_close_complete_or_are_refused` | four clients download a 300 KB file in a loop while the book closes: each answer is a whole 200 or a refusal, the number of 200s is the number of download records, and nothing moves after the answer | +| `book_open_close::the_timers_never_touch_a_closed_book` | `--timers 5` (sweep, backup look, drill look every 5 ms) on a book with a backup target, closed and opened 8 times: while closed, with strays planted for a sweep to take, not one file moves; open, it is backed up and drilled; the logs end as whole chains | | `commands::tests::doctor_says_who_is_connected` | the doctor's lines for sessions | **For P12 (mutation targets).** `Gate::enter` (count before looking at `shut`), -`Books::close_one`'s order (shut and list closed, `SharedStore::close`, the -gate emptied, sessions ended, the last backup, `let_go`), `door`'s entering +`Books::release`'s order (the store's close, the gate emptied, sessions ended, the last backup, `Backups::shut`, the logs and files closed, `let_go`) and `Backups::begin`'s count-before-flag, `Backups::shut` (the flag, the turn, the steps drained, the record closed), `ChainLog::close`, `refused_at_door` taking the request's place into its task, the sweep taking the gate, `door`'s entering before it touches the book, and the gate's riding in the upload and download tasks.