diff --git a/crates/ledger-cli/tests/audit.rs b/crates/ledger-cli/tests/audit.rs index cd3935f0..cb5c2cee 100644 --- a/crates/ledger-cli/tests/audit.rs +++ b/crates/ledger-cli/tests/audit.rs @@ -323,6 +323,23 @@ fn cpa_package_refuses_without_a_counted_audit_unless_a_reason_is_given() { before["decisions"].as_array().unwrap().len() + 1 ); assert!(after.to_string().contains("without a counted audit")); + // A refusal that comes after the reason (an open draft, with no reason of + // its own) journals nothing: no decision stands for a package that was + // never made. + let open = post(&mut w, "2026-03-25", "Still open", "3.00"); + let held_off = export( + &mut w, + json!({"without_audit_reason": "the CPA asked for it early"}), + ); + let err: Value = serde_json::from_str(&answer_of(&held_off).unwrap_err()).unwrap(); + assert_eq!(err["code"], "open_drafts", "{err}"); + let still = answer_of(&w.call("books.decisions", json!({}))).unwrap(); + assert_eq!( + still["decisions"].as_array().unwrap().len(), + after["decisions"].as_array().unwrap().len(), + "a decision was journaled for a package that was refused" + ); + confirm_post(&mut w, open); // An audit alone does not open it; nor one attested below the bar. answer_of(&w.call( "books.create_period", diff --git a/crates/ledger-cli/tests/book_open_close.rs b/crates/ledger-cli/tests/book_open_close.rs new file mode 100644 index 00000000..9396f53d --- /dev/null +++ b/crates/ledger-cli/tests/book_open_close.rs @@ -0,0 +1,3755 @@ +//! Opening and closing one book while the books server runs, and who is +//! connected to each book (plan/p15-app-and-relay.md 3.1, D-77, D-78). +//! Oracle: ledger-mcp local.rs INVARIANTS 3 and 10 to 12, admin.rs +//! INVARIANTS 8 and 9, sessions.rs INVARIANTS 1 and 3. +//! +//! The rule the hammer proves: every call either ran completely and is in +//! the book's journal, or was refused and nothing of it is; after a +//! close is answered nothing more runs on that book until it is opened +//! again; and a close of one book never refuses or holds up a call on +//! another. + +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; + +mod common; + +const A: &str = "acme"; +const B: &str = "beta"; + +/// What an agent is told of a book that exists but is closed. +fn closed_words(id: &str) -> String { + format!("The books \"{id}\" aren't open: open them in Wanderbooks.") +} + +/// New books `id` written in `home`'s root by the store itself, before a +/// server opens them. +fn written(home: &Home, id: &str) { + let dir = home.book_dir(id); + drop(ledger_store::Store::create(&dir, ledger_core::Currency::USD).unwrap()); + common::private_folder(&dir); +} + +/// What the server's list says of `id`: (open, closed, problem). +fn listed(home: &Home, id: &str) -> (bool, bool, Option) { + match home.admin(Request::List) { + Response::Books(list) => { + let b = list + .into_iter() + .find(|b| b.id == id) + .unwrap_or_else(|| panic!("{id} isn't listed")); + (b.open, b.closed, b.problem) + } + other => panic!("{other:?}"), + } +} + +fn open_book(home: &Home, id: &str) -> OpenOutcome { + match home.admin(Request::OpenBook { id: id.into() }) { + Response::OpenBook { outcome, .. } => outcome, + other => panic!("{other:?}"), + } +} + +fn close_book(home: &Home, id: &str) -> CloseOutcome { + match home.admin(Request::CloseBook { id: id.into() }) { + Response::CloseBook { outcome, .. } => outcome, + other => panic!("{other:?}"), + } +} + +/// What the book's files hold now: the journal's lines (read and chain +/// checked) and the access log's head. A closed book's must not move. +fn files_of(home: &Home, id: &str) -> (Vec, u64) { + let dir = home.book_dir(id); + let (lines, _) = + ledger_store::journal::read_journal_and_format(&dir.join(ledger_store::JOURNAL_FILE)) + .unwrap(); + let (_, head) = ledger_store::access::read(&dir).unwrap(); + (lines, head.seq) +} + +/// A request the server refuses before it runs, as a closed book's calls +/// are: its status, and its words. +fn refusal_of(wire: &Wire) -> (u16, String) { + let r = wire.refused.clone().expect("a refusal"); + assert!(r.not_run, "refused unrun: {r:?}"); + (r.status, r.body) +} + +/// Every route to a closed book says so, in words an agent can relay, +/// and a book that doesn't exist says that instead. +fn closed_on_every_route(home: &Home, id: &str) { + let mut wire = Wire::new(home, id); + wire.send( + &json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { + "protocolVersion": common::PROTOCOL, "capabilities": {}, + "clientInfo": {"name": "t", "version": "0"}}}), + ); + assert!(wire.recv(common::TIMEOUT).is_none()); + assert_eq!(refusal_of(&wire), (503, closed_words(id))); + for path in ["a/1", "x/e1"] { + let (status, body) = wire.get(path); + assert_eq!( + (status, String::from_utf8(body).unwrap()), + (503, closed_words(id)), + "GET {path}" + ); + } + assert_eq!( + wire.put("u/u1", b"bytes"), + (503, closed_words(id)), + "PUT an upload" + ); +} + +/// The books a server was told to open at the start are open; the others +/// are closed, are listed so, and say so on every route; a name that is no +/// book is told apart; opened on request, a book serves. +#[test] +fn books_left_closed_at_the_start_say_so_and_open_when_asked() { + let home = Home::new("open-close-start"); + written(&home, A); + written(&home, B); + let server = Server::start_with(&home, &["--open", B]); + assert_eq!(listed(&home, A), (false, true, None)); + assert_eq!(listed(&home, B), (true, false, None)); + closed_on_every_route(&home, A); + // Told apart from books that don't exist. + let mut nobody = Wire::with_token(&home, "nobody", Some(home.token(A))); + nobody.send(&json!({"jsonrpc": "2.0", "id": 1, "method": "ping"})); + assert_eq!(nobody.status, 404); + assert!( + nobody + .refused + .as_ref() + .unwrap() + .body + .contains("no books called"), + "{:?}", + nobody.refused + ); + // The other book serves. + let mut beta = Wire::new(&home, B); + beta.initialize("t"); + assert_eq!( + beta.call("books.chart", json!({}))["result"]["isError"], + json!(false) + ); + // Opened on request: once, then already; a name that is no book. + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + assert_eq!(open_book(&home, A), OpenOutcome::AlreadyOpen); + assert_eq!(open_book(&home, "nobody"), OpenOutcome::NoSuchBook); + assert_eq!(listed(&home, A), (true, false, None)); + let mut acme = Wire::new(&home, A); + acme.initialize("t"); + assert_eq!( + acme.call("books.chart", json!({}))["result"]["isError"], + json!(false) + ); + assert!(server.close().success()); +} + +/// `--open none` leaves every book closed; an id that names no book stops +/// the server before it opens anything. +#[test] +fn the_open_option_takes_none_and_refuses_a_book_that_doesnt_exist() { + let home = Home::new("open-close-none"); + written(&home, A); + let server = Server::start_with(&home, &["--open", "none"]); + assert_eq!(listed(&home, A), (false, true, None)); + closed_on_every_route(&home, A); + assert!(server.close().success()); + let mut bad = std::process::Command::new(env!("CARGO_BIN_EXE_wanderbooks")); + bad.args(["server", "--root"]) + .arg(home.root()) + .args(["--open", "nobody"]) + .stdin(std::process::Stdio::null()); + common::clean_env(&mut bad, home.dir.path()); + let out = bad.output().unwrap(); + assert_eq!(out.status.code(), Some(2), "{out:?}"); + assert!( + String::from_utf8_lossy(&out.stderr).contains("don't exist"), + "{out:?}" + ); +} + +/// What the sessions request says: each connection's token NAME, its +/// client, what the agent said of itself, its last call; never a token; +/// a session that ended isn't listed; and a book's sessions end with it. +#[test] +fn the_sessions_request_names_each_connection_and_never_its_token() { + let home = Home::new("open-close-sessions"); + let server = Server::start(&home); + home.create(A, "USD"); + home.create(B, "USD"); + let (one, two) = ( + home.token_with(A, "alpha", &["read", "write"]), + home.token_with(A, "beta", &["read"]), + ); + let mut first = Wire::with_token(&home, A, Some(one.clone())); + first.initialize("claude-code"); + let started = first.call( + "books.start", + json!({"agent": {"model": "m-1", "reasoning_effort": "high", "harness": "h-1"}}), + ); + assert_eq!(started["result"]["isError"], json!(false), "{started}"); + let mut second = Wire::with_token(&home, A, Some(two.clone())); + second.initialize("chatgpt"); + let sessions = |home: &Home| match home.admin(Request::Sessions) { + Response::Sessions(all) => all, + other => panic!("{other:?}"), + }; + // `initialized` is a notification, handled after its 202: each client's + // name is known once the server has (waited for, not guessed). + wait_for("both clients are known", Duration::from_secs(60), || { + sessions(&home) + .iter() + .find(|b| b.book == A) + .is_some_and(|a| { + a.sessions.len() == 2 && a.sessions.iter().all(|s| s.client_name.is_some()) + }) + }); + let all = sessions(&home); + let text = serde_json::to_string(&all).unwrap(); + for token in [&one, &two] { + assert!(!text.contains(token.as_str()), "a token's text was listed"); + assert!(!text.contains(&ledger_store::journal::sha256_hex(token.as_bytes()))); + } + let a = all.iter().find(|b| b.book == A).unwrap(); + assert!( + all.iter() + .find(|b| b.book == B) + .unwrap() + .sessions + .is_empty() + ); + assert_eq!(a.sessions.len(), 2, "{a:?}"); + let alpha = a.sessions.iter().find(|s| s.token == "alpha").unwrap(); + assert_eq!(alpha.client_name.as_deref(), Some("claude-code")); + assert_eq!(alpha.client_version.as_deref(), Some("0.1.0")); + let said = alpha.agent.as_ref().expect("the agent's report"); + assert_eq!(said.model.as_deref(), Some("m-1")); + assert_eq!(said.harness.as_deref(), Some("h-1")); + assert_eq!(alpha.running, 0); + let last = alpha.last.as_ref().expect("a last call"); + assert_eq!( + (last.tool.as_str(), last.outcome.as_str()), + ("books.start", "ok") + ); + let beta = a.sessions.iter().find(|s| s.token == "beta").unwrap(); + assert_eq!(beta.client_name.as_deref(), Some("chatgpt")); + assert!(beta.last.is_none() && beta.agent.is_none(), "{beta:?}"); + + // Ended: not listed. + second.end(); + let a = sessions(&home).into_iter().find(|b| b.book == A).unwrap(); + assert_eq!(a.sessions.len(), 1); + // Closed with the book: its session is gone; the closed book lists none. + assert_eq!(close_book(&home, A), CloseOutcome::Closed); + assert!(sessions(&home).iter().all(|b| b.book != A)); + first.send(&json!({"jsonrpc": "2.0", "id": 9, "method": "tools/list"})); + assert!(first.recv(common::TIMEOUT).is_none()); + assert_eq!(refusal_of(&first), (503, closed_words(A))); + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + assert!( + sessions(&home) + .iter() + .find(|b| b.book == A) + .unwrap() + .sessions + .is_empty() + ); + assert!(server.close().success()); +} + +/// How one call came out. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Said { + /// It ran: the answer says so (with the draft's id, for a draft). + Ran(Option), + /// It was refused, unrun. + Refused, +} + +/// One call's tag (the draft's description) and what came of it. +#[derive(Debug, Clone)] +struct Done { + book: &'static str, + tag: String, + said: Said, +} + +/// Send `tools/call` and read what came of it: it ran, or it was refused +/// unrun (at the book's door, as closing, or as a session the reopened +/// book never knew). Anything else is neither, and fails the test. +fn once(wire: &mut Wire, book: &str, id: u64, tool: &str, args: Value) -> Said { + wire.send(&json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", + "params": {"name": tool, "arguments": args}})); + match wire.recv(common::TIMEOUT) { + Some(resp) => { + if let Some(code) = resp.pointer("/error/code").and_then(Value::as_i64) { + assert_eq!(code, i64::from(ledger_mcp::NOT_RUN_CLOSING_CODE), "{resp}"); + return Said::Refused; + } + assert_eq!(resp["result"]["isError"], json!(false), "{resp}"); + Said::Ran(resp["result"]["structuredContent"]["entry_id"].as_u64()) + } + None => { + let r = wire.refused.clone().expect("an answer or a refusal"); + let closed = r.status == 503 && r.not_run && r.body == closed_words(book); + let unknown_session = r.status == 404 && r.body.contains("Session not found"); + assert!(closed || unknown_session, "neither run nor refused: {r:?}"); + Said::Refused + } + } +} + +/// An agent: keeps a session with `book`, draft entries (journaled +/// writes) and chart reads, until told to stop; a refused call ends its +/// session, and it opens another when it can. +fn agent( + home: Arc, + book: &'static str, + n: usize, + stop: Arc, + done: Arc>>, + reads: Arc<[AtomicUsize; 2]>, +) { + let token = home.token(book); + let mut wire: Option = None; + let mut k = 0u64; + while !stop.load(Ordering::SeqCst) { + if wire.is_none() { + let mut w = Wire::with_token(&home, book, Some(token.clone())); + w.send( + &json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { + "protocolVersion": common::PROTOCOL, "capabilities": {}, + "clientInfo": {"name": format!("agent-{n}"), "version": "1"}}}), + ); + match w.recv(common::TIMEOUT) { + Some(r) if r.get("result").is_some() => { + w.send(&json!({"jsonrpc": "2.0", "method": "notifications/initialized"})); + wire = Some(w); + } + _ => { + let r = w.refused.clone().expect("a refusal"); + assert!(r.not_run && r.status == 503, "{r:?}"); + std::thread::sleep(Duration::from_millis(3)); + continue; + } + } + } + let w = wire.as_mut().unwrap(); + k += 1; + let said = if k.is_multiple_of(3) { + let said = once(w, book, k + 10, "books.chart", json!({})); + let which = usize::from(said == Said::Refused); + if book == B { + reads[which].fetch_add(1, Ordering::SeqCst); + } + said + } else { + let tag = format!("{book}-agent{n}-call{k}"); + let said = once( + w, + book, + k + 10, + "books.draft_entry", + json!({"date": "2026-03-01", "description": tag}), + ); + done.lock().unwrap().push(Done { + book, + tag, + said: said.clone(), + }); + said + }; + if said == Said::Refused { + wire = None; + } + } +} + +/// Many agents call two books (journaled drafts and reads) while one book +/// is closed and opened again, over and over. Afterwards both journals are +/// replayed and checked: every acknowledged draft is in its book's journal +/// exactly once, no refused call left anything, a closed book's journal +/// and access log never moved between its close answer and its reopening, +/// and no call on the other book was ever refused. Meanwhile admin jobs on +/// other books (a third book closed and opened over and over, new books made) +/// are all done and none is ever stopped, refused or told of an error by the +/// closings (local.rs INVARIANT 10). +#[test] +fn closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing() { + const CYCLES: usize = 12; + let home = Arc::new(Home::new("open-close-hammer")); + // 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"); + home.create("cedar", "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)); + // Admin jobs on other books, while the hammered one is closed and opened: + // a third book closed and opened over and over, and new books made. Every + // one is done as asked; what isn't is said here. + let spared = Arc::new(Mutex::new((0usize, Vec::::new()))); + let maker = { + let (home, stop, spared) = (home.clone(), stop.clone(), spared.clone()); + std::thread::spawn(move || { + let mut made = 0; + while !stop.load(Ordering::SeqCst) { + let mut said = Vec::new(); + if made < 8 { + made += 1; + match home.admin(Request::Create { + id: format!("made-{made}"), + currency: "USD".into(), + }) { + Response::Created { problem: None, .. } => {} + other => said.push(format!("create: {other:?}")), + } + } + match home.admin(Request::CloseBook { id: "cedar".into() }) { + Response::CloseBook { + outcome: CloseOutcome::Closed, + .. + } => {} + other => said.push(format!("close: {other:?}")), + } + match home.admin(Request::OpenBook { id: "cedar".into() }) { + Response::OpenBook { + outcome: OpenOutcome::Opened, + .. + } => {} + other => said.push(format!("open: {other:?}")), + } + let mut spared = spared.lock().unwrap(); + spared.0 += 1; + spared.1.extend(said); + } + }) + }; + let done = Arc::new(Mutex::new(Vec::new())); + let reads = Arc::new([AtomicUsize::new(0), AtomicUsize::new(0)]); + let mut agents = Vec::new(); + for (book, how_many) in [(A, 6), (B, 4)] { + for n in 0..how_many { + let (home, stop, done, reads) = + (home.clone(), stop.clone(), done.clone(), reads.clone()); + agents.push(std::thread::spawn(move || { + agent(home, book, n, stop, done, reads) + })); + } + } + // 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)); + let beta_before = done.lock().unwrap().iter().filter(|d| d.book == B).count(); + assert_eq!(close_book(&home, A), CloseOutcome::Closed, "cycle {cycle}"); + // Answered closed: from here nothing runs on the book until it is + // 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); + // 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" + ); + // 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.into_iter().chain(refusers) { + a.join().unwrap(); + } + maker.join().unwrap(); + { + let spared = spared.lock().unwrap(); + assert!(spared.0 > 0, "no admin job ran on the other books"); + assert_eq!( + spared.1, + Vec::::new(), + "a close of {A} stopped or refused a job on another book" + ); + } + assert!(server.close().success()); + // Every log is a whole chain after all those closings. + access_of(&home, A); + 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] { + let (lines, _) = files_of(&home, book); + let mut journaled: BTreeMap> = BTreeMap::new(); + for l in lines.iter().filter(|l| l.line_type == "entry.created") { + journaled + .entry(l.payload["description"].as_str().unwrap().to_string()) + .or_default() + .push(l.payload["id"].as_u64().unwrap()); + } + let ran: BTreeMap<&str, Option> = done + .iter() + .filter(|d| d.book == book) + .filter_map(|d| match &d.said { + Said::Ran(id) => Some((d.tag.as_str(), *id)), + Said::Refused => None, + }) + .collect(); + let refused: BTreeSet<&str> = done + .iter() + .filter(|d| d.book == book && d.said == Said::Refused) + .map(|d| d.tag.as_str()) + .collect(); + // Every acknowledged write is there exactly once, under the id it + // was acknowledged with. + for (tag, id) in &ran { + assert_eq!( + journaled.get(*tag), + Some(&vec![id.expect("a draft's id")]), + "{book}: {tag} was acknowledged" + ); + } + // A refused call left nothing; nothing is in the journal that + // wasn't acknowledged. + for tag in &refused { + assert!(!journaled.contains_key(*tag), "{book}: {tag} was refused"); + } + let in_journal: BTreeSet<&str> = journaled.keys().map(String::as_str).collect(); + assert_eq!( + in_journal, + ran.keys().copied().collect::>(), + "{book}: the journal holds what was acknowledged and nothing else" + ); + // The journal replays: the books open, and the ids run on without + // a gap. + let store = ledger_store::Store::open(&home.book_dir(book)).unwrap(); + assert_eq!( + store.ledger().next_entry_id(), + ran.len() as u64 + 1, + "{book}: replayed ids" + ); + eprintln!( + "{book}: {} acknowledged, {} refused", + ran.len(), + refused.len() + ); + match book { + A => { + assert!(!ran.is_empty() && !refused.is_empty(), "the hammer hit {A}"); + } + _ => { + assert!(refused.is_empty(), "{B} was never closed: no call refused"); + assert!(!ran.is_empty()); + } + } + } + assert_eq!( + reads[1].load(Ordering::SeqCst), + 0, + "no read of {B} was refused" + ); + assert!(reads[0].load(Ordering::SeqCst) > 0); + // Between closings the journal only grew. + assert!( + closed_for.windows(2).all(|w| w[0] <= w[1]), + "{closed_for:?}" + ); +} + +/// 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). 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) + ); + // 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 + .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() + ); + 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(); + } + + /// [`Raw::start`] for a request that sends its body only once the + /// server has asked for it (`Expect: 100-continue`): the server asks + /// when its handler first reads the body, which it does inside the + /// book's door. So once this returns the request is known to be + /// inside, with `sent` bytes of its body written: a condition, not a + /// guess at how long the server takes to read a head. + pub fn start_inside( + &mut self, + method: &str, + path: &str, + extra: &[(&str, &str)], + body: &[u8], + sent: usize, + ) { + let mut extra = extra.to_vec(); + extra.push(("expect", "100-continue")); + self.start(method, path, &extra, body, 0); + self.stream + .set_read_timeout(Some(Duration::from_secs(120))) + .unwrap(); + let mut seen = Vec::new(); + let mut byte = [0u8; 1]; + while !seen.ends_with(b"\r\n\r\n") { + self.stream + .read_exact(&mut byte) + .expect("the server never asked for the body"); + seen.push(byte[0]); + } + let said = String::from_utf8_lossy(&seen).to_string(); + assert!(said.starts_with("HTTP/1.1 100"), "{said}"); + 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(); + } + + /// A piece of the rest of a body; false once the server has closed + /// the connection (nothing more can be sent). + pub fn try_finish(&mut self, piece: &[u8]) -> bool { + self.stream.write_all(piece).is_ok() + } + + /// Everything the server sends until it closes the connection, + /// which it must do within `within`. + pub fn until_closed(&mut self, within: Duration) -> String { + self.stream.set_read_timeout(Some(within)).unwrap(); + let mut seen = std::mem::take(&mut self.taken); + let mut buf = [0u8; 4096]; + loop { + match self.stream.read(&mut buf) { + Ok(0) => break, + Ok(n) => seen.extend_from_slice(&buf[..n]), + Err(e) + if matches!( + e.kind(), + std::io::ErrorKind::ConnectionReset | std::io::ErrorKind::BrokenPipe + ) => + { + break; + } + Err(e) => panic!("the connection was left open: {e}"), + } + } + String::from_utf8_lossy(&seen).to_string() + } + + /// The whole response: its status, and its body (as long as its + /// `content-length` says). + pub fn answer(&mut self) -> (u16, String) { + let (status, head) = self.head(); + let lower = head.to_ascii_lowercase(); + let mut body = Vec::new(); + if lower.contains("transfer-encoding: chunked") { + // Chunks, each a hex size line, its bytes and a line end. + loop { + let mut size = String::new(); + let mut byte = [0u8; 1]; + while !size.ends_with("\r\n") { + self.stream.read_exact(&mut byte).unwrap(); + size.push(byte[0] as char); + } + let n = usize::from_str_radix(size.trim(), 16).unwrap(); + let mut chunk = vec![0u8; n + 2]; + self.stream.read_exact(&mut chunk).unwrap(); + if n == 0 { + break; + } + body.extend_from_slice(&chunk[..n]); + } + } else { + let length: usize = lower + .lines() + .find_map(|l| { + l.strip_prefix("content-length:") + .map(|v| v.trim().parse().unwrap()) + }) + .unwrap_or(0); + body = vec![0u8; length]; + self.stream.read_exact(&mut body).unwrap(); + } + (status, String::from_utf8_lossy(&body).to_string()) + } + + /// 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); + // The timers look once an hour, so none runs a backup of its own: the + // first look is at the server's start, before any book is made here. A + // timer's backup that a close hurried could have its git miss the + // terminate grace under heavy load, be killed, and leave a lock in the + // target's folder, which the close's own backup would then truthfully + // fail against (`ClosedBackupIncomplete`): the plain `Closed` asserted + // below is of the close's backup alone. + let server = server_with_shim( + &home, + &shim, + &["--backup-quiet", "3600000", "--timers", "3600000"], + ); + 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(); + // A backup asked for, to see the target works now (no timer makes one + // here: above). + match home.admin(Request::BackUpNow { + id: A.into(), + new_disk: false, + }) { + Response::BackedUp { targets, .. } => { + assert!(targets.iter().all(|t| t.problem.is_none()), "{targets:?}"); + } + other => panic!("{other:?}"), + } + let mut w = Wire::new(&home, A); + w.initialize("owner"); + draft(&mut w, "backed up"); + w.end(); + let outcome = close_book(&home, A); + assert_eq!( + outcome, + CloseOutcome::Closed, + "{}", + std::fs::read_to_string(home.book_dir(A).join("ops").join("backup.jsonl")) + .unwrap_or_default() + ); + 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 + }); + // A negative window: it can only fail if the close was answered, never + // because the machine was slow. + 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()); +} + +/// Whether the access log of `id` holds a record of `action` on `subject` +/// that the close cut (never a record of it having run). +fn cut_records(home: &Home, id: &str, action: &str) -> Vec { + access_of(home, id) + .into_iter() + .filter(|r| { + r.access.action == action + && r.access.result + == ledger_store::access::Outcome::Refused("cut_by_close".to_string()) + }) + .collect() +} + +/// An upload whose body stalls half way (the client neither sends the rest +/// nor hangs up) is inside the book's door, and would hold the close for +/// ever. The close waits the grace, cuts it: its connection is closed, its +/// part file is gone, its record says the close cut it, nothing was +/// kept. The close is answered, and the log is a whole chain through a +/// reopening (local.rs INVARIANT 10, the cut). +#[cfg(unix)] +#[test] +fn a_stalled_upload_body_cannot_hold_a_close_and_leaves_no_part_file() { + let home = Home::new("close-stalled-upload"); + let server = Server::start_with(&home, &["--answer-grace", "600", "--timers", "10"]); + home.create(A, "USD"); + let mut w = Wire::new(&home, A); + w.initialize("uploader"); + let bytes: Vec = (0..200_000u32).map(|n| (n % 251) as u8).collect(); + let (id, mut raw) = half_sent_upload(&home, &mut w, A, &bytes); + let started = std::time::Instant::now(); + assert_eq!(close_book(&home, A), CloseOutcome::Closed); + let took = started.elapsed(); + assert!( + took >= Duration::from_millis(500), + "the upload was cut before the grace ran out ({took:?})" + ); + assert!( + took < Duration::from_secs(20), + "a stalled upload held the close ({took:?})" + ); + assert_eq!(parts_under(&home.book_dir(A)), Vec::::new()); + assert!( + !tree_of(&home.book_dir(A)) + .keys() + .any(|k| k.contains(&id) && k.ends_with(".bin")), + "bytes of a cut upload were kept" + ); + let said = raw.until_closed(Duration::from_secs(10)); + assert!(said.contains("cut_by_close"), "{said}"); + assert_eq!(cut_records(&home, A, "upload").len(), 1); + stands_still( + &home, + A, + Duration::from_millis(300), + "after the close was answered", + ); + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + let mut again = Wire::new(&home, A); + again.initialize("after"); + draft(&mut again, "after"); + access_of(&home, A); + assert!(server.close().success()); + access_of(&home, A); +} + +/// The same for an MCP call whose body never finishes arriving: no tool saw +/// it, so nothing is in the journal; the close is not held; the record says +/// the close cut it. +#[cfg(unix)] +#[test] +fn a_stalled_mcp_body_cannot_hold_a_close_and_nothing_of_it_is_journaled() { + let home = Home::new("close-stalled-mcp"); + let server = Server::start_with(&home, &["--answer-grace", "600", "--timers", "10"]); + home.create(A, "USD"); + let mut w = Wire::new(&home, A); + w.initialize("caller"); + draft(&mut w, "before"); + let mut raw = raw::Raw::connect(&home, A); + let body = json!({"jsonrpc": "2.0", "id": 9, "method": "tools/call", "params": { + "name": "books.draft_entry", + "arguments": {"date": "2026-03-01", "description": "never finished"}}}) + .to_string(); + raw.start_inside( + "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() / 2, + ); + let started = std::time::Instant::now(); + assert_eq!(close_book(&home, A), CloseOutcome::Closed); + let took = started.elapsed(); + assert!( + took >= Duration::from_millis(500), + "cut too early ({took:?})" + ); + assert!(took < Duration::from_secs(20), "held by a stall ({took:?})"); + let said = raw.until_closed(Duration::from_secs(10)); + assert!(said.contains("cut_by_close"), "{said}"); + assert!( + !files_of(&home, A) + .0 + .iter() + .any(|l| l.payload["description"] == json!("never finished")), + "a call whose body never arrived was journaled" + ); + assert_eq!(cut_records(&home, A, "connect").len(), 1); + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + let mut again = Wire::new(&home, A); + again.initialize("after"); + draft(&mut again, "after"); + access_of(&home, A); + assert!(server.close().success()); +} + +/// A slow upload that is still arriving, and finishes within the grace, is +/// not cut: it is kept and answered, as without a close. Driven by +/// conditions, not by time: the grace (a minute) is far past anything the +/// test does, and the rest of the bytes are sent only after the close has +/// begun (the book is listed closed), so the one thing this proves is that +/// the cut waits for the grace, never firing at the start of the close (it +/// fails with the cut set to fire at once). Its mirror, that the cut does +/// fire when the grace is out, is +/// `an_upload_still_arriving_when_the_grace_runs_out_is_cut_however_active_it_is`. +#[cfg(unix)] +#[test] +fn a_slow_upload_that_finishes_within_the_grace_is_not_cut() { + let home = Home::new("close-slow-upload"); + let server = Server::start_with(&home, &["--answer-grace", "60000", "--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 % 247) as u8).collect(); + let (id, mut raw) = half_sent_upload(&home, &mut w, A, &bytes); + let closing = std::thread::spawn({ + let admin = home.run().join("admin.sock"); + move || ledger_mcp::admin::call(&admin, Request::CloseBook { id: A.into() }).unwrap() + }); + wait_for("the book is listed closed", Duration::from_secs(30), || { + listed(&home, A).1 + }); + for chunk in bytes[bytes.len() / 2..].chunks(25_000) { + std::thread::sleep(Duration::from_millis(150)); + raw.finish(chunk); + } + 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:?}"), + } + assert!(cut_records(&home, A, "upload").is_empty()); + assert!( + tree_of(&home.book_dir(A)) + .keys() + .any(|k| k.ends_with(&format!("{id}.bin"))), + "the bytes were kept" + ); + assert!(server.close().success()); +} + +/// A call whose body is whole and that is running when the grace runs out +/// is not cut: it ends, is answered and recorded as having run, and only +/// then is the close answered. The call is an ordinary one (`books.attach_ +/// receipt`, which reads its upload: bounded by one request, so a close waits +/// for it instead of stopping it), held inside its read of the file, which +/// is a named pipe nothing writes to yet. What this proves is that the close +/// waits for such a call and does not kill it; that a body read to its end +/// is never cut (the line of INVARIANT 15) is proved at its seat, by +/// `local::tests::a_body_read_to_its_end_is_never_cut_and_one_not_yet_is`: +/// this test passes even with a cut that marks every request inside (the +/// call runs in the session's task, past the handler's own check for a cut). +/// (A backup asked for is no longer this call: it is stoppable, and a close +/// stops it: `a_close_stops_a_running_backup_call_and_says_so`.) +#[cfg(unix)] +#[test] +fn a_running_call_is_never_cut_when_the_grace_runs_out() { + use std::os::unix::fs::OpenOptionsExt; + let home = Home::new("close-running-call"); + let server = Server::start_with(&home, &["--answer-grace", "400", "--timers", "20"]); + home.create(A, "USD"); + let mut w = Wire::new(&home, A); + w.initialize("owner"); + let bytes = b"%PDF-1.4 a receipt, read by a call that is held".to_vec(); + let up = w.upload(&bytes, "r.pdf", "application/pdf", "receipt"); + // The call takes its file (renaming it to `.taken`) and reads it: make + // what it reads a named pipe, so it waits there for a writer. + let uploads = home.book_dir(A).join("uploads"); + let bin = uploads.join(format!("{up}.bin")); + std::fs::remove_file(&bin).unwrap(); + assert!( + std::process::Command::new("mkfifo") + .arg(&bin) + .status() + .unwrap() + .success() + ); + let mut raw = raw::Raw::connect(&home, A); + let body = json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": { + "name": "books.attach_receipt", "arguments": {"upload_id": up}}}) + .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(), + ); + // Inside its read: a writer can open the pipe without blocking only + // once a reader has it open. (The writer is kept, to feed it later.) + let taken = uploads.join(format!("{up}.taken")); + let mut feed = None; + wait_for( + "the call is reading its file", + Duration::from_secs(60), + || match std::fs::OpenOptions::new() + .write(true) + .custom_flags(libc::O_NONBLOCK) + .open(&taken) + { + Ok(f) => { + feed = Some(f); + true + } + Err(_) => false, + }, + ); + let closing = std::thread::spawn({ + let admin = home.run().join("admin.sock"); + move || ledger_mcp::admin::call(&admin, Request::CloseBook { id: A.into() }).unwrap() + }); + wait_for("the book is listed closed", Duration::from_secs(30), || { + listed(&home, A).1 + }); + // A negative window well past the grace (400 ms): the call is still + // running, and not cut. It can only fail if the close was answered, never + // because the machine was slow. + std::thread::sleep(Duration::from_millis(1200)); + assert!( + !closing.is_finished(), + "the close didn't wait for a running call" + ); + { + use std::io::Write; + let mut feed = feed.take().unwrap(); + feed.write_all(&bytes).unwrap(); + } + let (status, said) = raw.answer(); + assert_eq!(status, 200, "{said}"); + let _ = closing.join().unwrap(); + assert!(cut_records(&home, A, "books.attach_receipt").is_empty()); + assert!(cut_records(&home, A, "connect").is_empty()); + assert!( + access_of(&home, A) + .iter() + .any(|r| r.access.subject == "books.attach_receipt" + && r.access.result == ledger_store::access::Outcome::Ok), + "the call that ran is on record as having run: {said}" + ); + drop(raw); + 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", + "15000", + "--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(); + // (The grace is longer than the 5 seconds watched below: an upload + // that finishes within it is waited for, never cut.) + 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() + } + }); + // A call for the books being replaced is told they aren't open (503, + // the words, the closed header), as in a close; never that there are + // no such books (404), which they would be told if they were taken + // out of the list while the restore waits (INVARIANT 10). + let late_call = || { + 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.clone().map(|r| (r.status, r.body)) + }; + wait_for( + "the replaced books are let go", + Duration::from_secs(30), + || match late_call() { + Some((404, body)) => panic!("books being restored were `no such books`: {body}"), + Some((503, body)) => { + assert_eq!(body, closed_words(A)); + true + } + _ => false, + }, + ); + // 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. + // Every call meanwhile gets the same answer. + 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" + ); + assert_eq!( + late_call(), + Some((503, closed_words(A))), + "a call while the books were being restored" + ); + 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); + // A negative window (it can only fail if something moved). + std::thread::sleep(Duration::from_millis(300)); + assert_eq!(moved(&at_answer, &tree_of(&legacy)), Vec::::new()); + assert!(server.close().success()); +} + +/// A restore over an open book is held by an upload that stalls no longer +/// than the grace: the upload is cut (no part file in `legacy/`, its record +/// in the replaced book's log says so), and the restore is answered. +#[cfg(unix)] +#[test] +fn a_restore_over_an_open_book_is_not_held_by_a_stalled_upload() { + let home = Home::new("restore-stalled"); + let server = Server::start_with( + &home, + &[ + "--answer-grace", + "600", + "--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 % 239) 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 started = std::time::Instant::now(); + let restored = match home.admin(Request::Restore { + id: A.into(), + source, + replace: true, + confirmed: true, + expect_head: Some(preview.head), + }) { + Response::Restored(r) => r, + other => panic!("{other:?}"), + }; + assert!(started.elapsed() < Duration::from_secs(30)); + assert!(restored.replaced.is_some(), "{restored:?}"); + let said = raw.until_closed(Duration::from_secs(10)); + assert!(said.contains("cut_by_close"), "{said}"); + let legacy = home.root().join("legacy"); + 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 + && r.access.result + == ledger_store::access::Outcome::Refused("cut_by_close".to_string())), + "{records:?}" + ); + 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"); +} + +/// The mirror of `a_slow_upload_that_finishes_within_the_grace_is_not_cut`: +/// an upload whose client is not stalled at all, sending steadily, is cut +/// the moment the grace has run out, because its body isn't whole then (the +/// line is the body's end, INVARIANT 15). Driven by conditions: the client +/// sends until the server closes the connection, and the body is far too +/// large to be whole within the grace (the test fails if the upload is +/// let finish: with the cut removed it is kept, answered 200, and the close +/// answered ten seconds late). +#[cfg(unix)] +#[test] +fn an_upload_still_arriving_when_the_grace_runs_out_is_cut_however_active_it_is() { + let home = Home::new("close-active-upload"); + let server = Server::start_with(&home, &["--answer-grace", "600", "--timers", "10"]); + home.create(A, "USD"); + let mut w = Wire::new(&home, A); + w.initialize("uploader"); + let bytes: Vec = (0..3_000_000u32).map(|n| (n % 241) as u8).collect(); + let (id, mut raw) = half_sent_upload(&home, &mut w, A, &bytes); + let closing = std::thread::spawn({ + let admin = home.run().join("admin.sock"); + move || ledger_mcp::admin::call(&admin, Request::CloseBook { id: A.into() }).unwrap() + }); + wait_for("the book is listed closed", Duration::from_secs(30), || { + listed(&home, A).1 + }); + // Steady: 8 KB every 25 ms (about 320 KB/s: the rest takes ten seconds). + let begun = std::time::Instant::now(); + let mut sent = bytes.len() / 2; + while sent < bytes.len() { + let piece = &bytes[sent..(sent + 8192).min(bytes.len())]; + if !raw.try_finish(piece) { + break; + } + sent += piece.len(); + std::thread::sleep(Duration::from_millis(25)); + assert!( + begun.elapsed() < Duration::from_secs(8), + "an upload that was still arriving was never cut" + ); + } + assert!( + sent < bytes.len(), + "the whole upload went in before the cut" + ); + assert!( + begun.elapsed() >= Duration::from_millis(400), + "cut before the grace ran out ({:?})", + begun.elapsed() + ); + let said = raw.until_closed(Duration::from_secs(10)); + assert!(said.contains("cut_by_close"), "{said}"); + match closing.join().unwrap() { + Response::CloseBook { outcome, .. } => assert_eq!(outcome, CloseOutcome::Closed), + other => panic!("{other:?}"), + } + assert_eq!(parts_under(&home.book_dir(A)), Vec::::new()); + assert!( + !tree_of(&home.book_dir(A)) + .keys() + .any(|k| k.contains(&id) && k.ends_with(".bin")), + "bytes of a cut upload were kept" + ); + assert_eq!(cut_records(&home, A, "upload").len(), 1); + assert!(server.close().success()); +} + +/// The server's own close is the book's close, all books together +/// (local.rs INVARIANT 15): with an upload stalled half way on one book and +/// an MCP call's body stalled half way on another, the server told to close +/// (its standard input ends) cuts both one grace after the close began, +/// exits 0 within a bound, leaves no part file, journals nothing of the +/// call, and its records say `cut_by_close`. +#[cfg(unix)] +#[test] +fn the_servers_own_close_cuts_stalled_requests_and_exits_zero_in_time() { + let home = Home::new("server-close-stalled"); + let server = Server::start_with(&home, &["--answer-grace", "600", "--timers", "10"]); + home.create(A, "USD"); + home.create(B, "USD"); + let mut wa = Wire::new(&home, A); + wa.initialize("uploader"); + let bytes: Vec = (0..200_000u32).map(|n| (n % 251) as u8).collect(); + let (id, mut raw_upload) = half_sent_upload(&home, &mut wa, A, &bytes); + let mut wb = Wire::new(&home, B); + wb.initialize("caller"); + draft(&mut wb, "before"); + let mut raw_call = raw::Raw::connect(&home, B); + let body = json!({"jsonrpc": "2.0", "id": 9, "method": "tools/call", "params": { + "name": "books.draft_entry", + "arguments": {"date": "2026-03-01", "description": "never finished"}}}) + .to_string(); + raw_call.start_inside( + "POST", + "mcp", + &[ + ("content-type", "application/json"), + ("accept", "application/json, text/event-stream"), + ("mcp-session-id", wb.session().unwrap()), + ("mcp-protocol-version", wb.version().unwrap()), + ], + body.as_bytes(), + body.len() / 2, + ); + let started = std::time::Instant::now(); + let status = server.close(); + let took = started.elapsed(); + assert_eq!(status.code(), Some(0), "{status:?}"); + assert!( + took >= Duration::from_millis(500), + "cut before the grace ran out ({took:?})" + ); + // The bound: the grace (600 ms, the cut), the answers' grace (600 ms), + // and the linger and the HTTP side's end (3 s and 5 s at most). + assert!(took < Duration::from_secs(12), "{took:?}"); + assert!( + raw_upload + .until_closed(Duration::from_secs(10)) + .contains("cut_by_close") + ); + assert!( + raw_call + .until_closed(Duration::from_secs(10)) + .contains("cut_by_close") + ); + assert_eq!(parts_under(&home.book_dir(A)), Vec::::new()); + assert!( + !tree_of(&home.book_dir(A)) + .keys() + .any(|k| k.contains(&id) && k.ends_with(".bin")), + "bytes of a cut upload were kept" + ); + assert_eq!(cut_records(&home, A, "upload").len(), 1); + assert_eq!(cut_records(&home, B, "connect").len(), 1); + assert!( + !files_of(&home, B) + .0 + .iter() + .any(|l| l.payload["description"] == json!("never finished")), + "a call whose body never arrived was journaled" + ); + // Every log is whole, and the books open again. + access_of(&home, A); + access_of(&home, B); + ledger_store::Store::open(&home.book_dir(A)).expect("the books open again"); + ledger_store::Store::open(&home.book_dir(B)).expect("the books open again"); +} + +/// A timer that took a book's handles before the close and acts on them +/// after it does nothing to the book (local.rs INVARIANT 13). The knob +/// `--timer-hold` holds a timer between its taking the handles and its +/// acting on them; the test closes the book meanwhile, plants what a sweep +/// would take, lets the timer go on, and the tree of the closed book must +/// not move. `held` names the timers held: the sweep, and the backup or the +/// drill (the backup loop is one task: the drill is held only once the +/// write is backed up). +#[cfg(unix)] +fn a_late_timer_does_nothing(name: &str, held_timers: &str) { + let home = Home::new(name); + let server = Server::start_with( + &home, + &[ + "--timers", + "5", + "--timer-hold", + "--backup-quiet", + "0", + "--drill-first", + "0", + "--answer-grace", + "300", + ], + ); + home.create(A, "USD"); + let run = home.run(); + let seen = || std::fs::read_to_string(run.join("timer-held")).unwrap_or_default(); + let all_held = || { + held_timers + .split(',') + .all(|t| seen().lines().any(|l| l == t)) + }; + // From the start of the book's work: the timers hold what they take. + std::fs::write(run.join("timer-hold"), held_timers).unwrap(); + let mut w = Wire::new(&home, A); + w.initialize("owner"); + let disk = home.dir.path().join("disk"); + std::fs::create_dir_all(&disk).unwrap(); + set_backup_folder(&mut w, &disk); + w.end(); + wait_for( + "the timers hold their handles", + Duration::from_secs(60), + all_held, + ); + let dir = home.book_dir(A); + assert!(matches!(close_book(&home, A), CloseOutcome::Closed)); + for folder in ["uploads", "exports"] { + std::fs::write(dir.join(folder).join("stray.bin"), b"x").unwrap(); + } + let at_close = tree_of(&dir); + // The timers go on, with what they took before the close. + std::fs::remove_file(run.join("timer-hold")).unwrap(); + // (A window in which nothing may move, begun at the release: no wait + // before it for the timers to get going, which proved nothing.) + stands_still(&home, A, Duration::from_millis(800), "a late timer"); + assert_eq!(moved(&at_close, &tree_of(&dir)), Vec::::new()); + assert!(dir.join("uploads").join("stray.bin").exists()); + assert!(dir.join("exports").join("stray.bin").exists()); + // Opened again, the timers work on it again. + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + wait_for( + "the sweep takes the stray files", + Duration::from_secs(30), + || !dir.join("uploads").join("stray.bin").exists(), + ); + assert!(server.close().success()); + access_of(&home, A); + ledger_store::chain::read( + &dir.join("ops").join("backup.jsonl"), + "wanderbooks-backup-v1", + ) + .expect("the backup record is a whole chain"); +} + +/// The sweep and the backup, each holding its handles across a close. +#[cfg(unix)] +#[test] +fn a_backup_and_a_sweep_that_took_their_handles_before_a_close_do_nothing_after_it() { + a_late_timer_does_nothing("close-late-backup", "sweep,backup"); +} + +/// The sweep and the drill, each holding its handles across a close. +#[cfg(unix)] +#[test] +fn a_drill_and_a_sweep_that_took_their_handles_before_a_close_do_nothing_after_it() { + a_late_timer_does_nothing("close-late-drill", "sweep,drill"); +} + +/// A close does not wait for a drill, however long the book makes it: the +/// drill is stopped at its next look (a cancel flag), its scratch clone is +/// removed, and the close is answered within its stated bound (local.rs +/// INVARIANT 10: the grace for what hasn't arrived, the grace for the +/// answers, the last backup's bound, the stop of a step, which for a +/// folder target includes the lock settling time), with the last backup +/// made. `--slow-steps` makes each phase of the drill wait a minute, as a +/// book of a million events would make its replay; without the hurry the +/// last backup waits behind the drill and the close says it wasn't whole. +#[cfg(unix)] +#[test] +fn a_close_stops_a_slow_drill_instead_of_waiting_for_it() { + let home = Home::new("close-slow-drill"); + let (grace, last_backup) = (500u64, 3000u64); + let server = Server::start_with( + &home, + &[ + "--slow-steps", + "60000", + "--timers", + "20", + "--backup-quiet", + "0", + "--drill-first", + "0", + "--answer-grace", + &grace.to_string(), + "--close-backup", + &last_backup.to_string(), + ], + ); + home.create(A, "USD"); + let disk = home.dir.path().join("disk"); + std::fs::create_dir_all(&disk).unwrap(); + let mut w = Wire::new(&home, A); + w.initialize("owner"); + set_backup_folder(&mut w, &disk); + draft(&mut w, "backed up first"); + w.end(); + // The write is backed up, then its first drill begins and sits in its + // wait: the clone is made, its scratch folder is there. + let scratch = home.book_dir(A).join("ops").join("drill-folder"); + wait_for("a drill is under way", Duration::from_secs(60), || { + scratch.exists() + }); + // A write the close's last backup has to make. + let mut w = Wire::new(&home, A); + w.initialize("owner"); + draft(&mut w, "after the drill began"); + w.end(); + let started = std::time::Instant::now(); + let outcome = close_book(&home, A); + let took = started.elapsed(); + assert_eq!( + outcome, + CloseOutcome::Closed, + "the last backup waited behind the drill" + ); + // The stated bound, as a sum of its parts: the grace, the answers' + // grace, the last backup's bound, and the stop of a step (git's kill + // and its group's end, 2 s; its pipes, 10 s; the lock settling, 1.5 s). + let bound = Duration::from_millis(2 * grace + last_backup) + Duration::from_millis(13_500); + assert!(took < bound, "{took:?} past the stated bound {bound:?}"); + assert!(took < Duration::from_secs(8), "{took:?}: the drill ran on"); + assert!(!scratch.exists(), "the stopped drill's clone was left"); + // The last backup took the write. + let records = std::fs::read_to_string(home.book_dir(A).join("ops").join("backup.jsonl")) + .unwrap_or_default(); + assert!( + records.matches("\"why\":\"close\"").count() >= 1, + "no backup at the close: {records}" + ); + stands_still( + &home, + A, + Duration::from_millis(400), + "after the close was answered", + ); + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + assert!(server.close().success()); + ledger_store::chain::read( + &home.book_dir(A).join("ops").join("backup.jsonl"), + "wanderbooks-backup-v1", + ) + .expect("the backup record is a whole chain"); +} + +/// A stand-in `git` that is the real one with a hooks folder of its own +/// (every `core.hooksPath=/dev/null` it is given, in its arguments and in +/// the `--receive-pack` command of a push to a folder, names it instead), +/// where a `reference-transaction` hook waits, while `slow-commit` (for the +/// book's archive) or `slow-push` (for any other repository) exists in the +/// shim folder, at the point where git holds its ref locks. `hooked` has a +/// line per hook that waited. A real git, killed inside real work. +#[cfg(unix)] +fn slow_real_git(home: &Home) -> PathBuf { + use std::os::unix::fs::PermissionsExt; + let dir = home.dir.path().join("slow-shim"); + let hooks = dir.join("hooks"); + std::fs::create_dir_all(&hooks).unwrap(); + let real = ["/usr/bin/git", "/bin/git", "/usr/local/bin/git"] + .into_iter() + .find(|p| std::path::Path::new(p).is_file()) + .expect("git is installed"); + let hook = hooks.join("reference-transaction"); + std::fs::write( + &hook, + "#!/bin/sh\ncat >/dev/null\n[ \"$1\" = prepared ] || exit 0\nd=\"$(dirname \"$0\")/..\"\ncase \"$GIT_DIR $PWD\" in *archive.git*) f=slow-commit ;; *) f=slow-push ;; esac\nif [ -e \"$d/$f\" ]; then\n echo $$ >> \"$d/hooked\"\n while [ -e \"$d/$f\" ]; do sleep 0.05; done\nfi\nexit 0\n", + ) + .unwrap(); + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + let exe = dir.join("git"); + std::fs::write( + &exe, + format!( + "#!/bin/sh\nn=$#\nwhile [ $n -gt 0 ]; do\n a=\"$1\"; shift\n case \"$a\" in\n *core.hooksPath=/dev/null*) a=$(printf '%s' \"$a\" | sed 's|core.hooksPath=/dev/null|core.hooksPath={}|g') ;;\n esac\n set -- \"$@\" \"$a\"\n n=$((n-1))\ndone\nexec {real} \"$@\"\n", + hooks.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap(); + dir +} + +/// Every `*.lock` file under a bare repository. +#[cfg(unix)] +fn locks_under(repo: &std::path::Path) -> Vec { + tree_of(repo) + .into_keys() + .filter(|k| k.ends_with(".lock")) + .collect() +} + +#[cfg(unix)] +fn fsck_of(repo: &std::path::Path) { + let out = std::process::Command::new("git") + .arg(format!("--git-dir={}", repo.display())) + .args(["fsck", "--strict"]) + .output() + .unwrap(); + assert!( + out.status.success(), + "{} isn't whole: {}", + repo.display(), + String::from_utf8_lossy(&out.stderr) + ); +} + +/// A close that stops real git inside a commit, and inside a push to a +/// folder, leaves no lock for anyone to remove: git is sent SIGTERM and +/// removes its own locks, so there is nothing for the server to clean up +/// (the backup's record holds no `lock_removed` or `lock_left`), the book +/// opened again at once backs up with no step by hand, and both +/// repositories pass `git fsck` (ledger_store::backup INVARIANT 5). +#[cfg(unix)] +#[test] +fn a_close_that_stops_git_in_a_commit_or_a_push_leaves_no_lock_and_the_next_backup_succeeds() { + let home = Home::new("close-git-locks"); + let shim = slow_real_git(&home); + let server = server_with_shim( + &home, + &shim, + &[ + "--close-backup", + "1500", + "--backup-quiet", + "3600000", + "--timers", + "20", + ], + ); + home.create(A, "USD"); + let disk = home.dir.path().join("disk"); + std::fs::create_dir_all(&disk).unwrap(); + let mut w = Wire::new(&home, A); + w.initialize("owner"); + set_backup_folder(&mut w, &disk); + draft(&mut w, "to be backed up inside a commit"); + w.end(); + let archive = home.book_dir(A).join("archive.git"); + let target = disk.join(format!("{A}.git")); + let record = || { + std::fs::read_to_string(home.book_dir(A).join("ops").join("backup.jsonl")) + .unwrap_or_default() + }; + // 0. Inside the making of the archive itself (`git init`): a lock in + // a repository that isn't one yet stops every later `init`. + std::fs::write(shim.join("slow-commit"), b"").unwrap(); + let outcome = close_book(&home, A); + assert!( + matches!(outcome, CloseOutcome::ClosedBackupIncomplete(_)), + "{outcome:?}" + ); + assert!( + shim.join("hooked").exists(), + "git never reached its ref update" + ); + assert_eq!(locks_under(&archive), Vec::::new()); + assert!( + !record().contains("lock_removed") && !record().contains("lock_left"), + "git removed its own locks: nothing was cleaned up here: {}", + record() + ); + std::fs::remove_file(shim.join("slow-commit")).unwrap(); + std::fs::remove_file(shim.join("hooked")).unwrap(); + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + let mut w = Wire::new(&home, A); + w.initialize("owner"); + draft(&mut w, "to be backed up inside a commit"); + w.end(); + match home.admin(Request::BackUpNow { + id: A.into(), + new_disk: false, + }) { + Response::BackedUp { targets, .. } => { + assert!(targets.iter().all(|t| t.problem.is_none()), "{targets:?}"); + } + other => panic!("{other:?}"), + } + let mut w = Wire::new(&home, A); + w.initialize("owner"); + draft(&mut w, "to be committed inside a commit"); + w.end(); + // 1. Inside the commit's ref update. + std::fs::write(shim.join("slow-commit"), b"").unwrap(); + let outcome = close_book(&home, A); + assert!( + matches!(outcome, CloseOutcome::ClosedBackupIncomplete(_)), + "{outcome:?}" + ); + assert!( + shim.join("hooked").exists(), + "git never reached its ref update" + ); + assert_eq!(locks_under(&archive), Vec::::new()); + assert!( + !record().contains("lock_removed") && !record().contains("lock_left"), + "git removed its own locks: nothing was cleaned up here: {}", + record() + ); + std::fs::remove_file(shim.join("slow-commit")).unwrap(); + std::fs::remove_file(shim.join("hooked")).unwrap(); + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + let status = home.admin(Request::BackUpNow { + id: A.into(), + new_disk: false, + }); + match &status { + Response::BackedUp { targets, .. } => { + assert!(targets.iter().all(|t| t.problem.is_none()), "{status:?}"); + } + other => panic!("{other:?}"), + } + fsck_of(&archive); + fsck_of(&target); + // 2. Inside the push's ref update at the folder. + let mut w = Wire::new(&home, A); + w.initialize("owner"); + draft(&mut w, "to be pushed inside a push"); + w.end(); + std::fs::write(shim.join("slow-push"), b"").unwrap(); + let outcome = close_book(&home, A); + assert!( + matches!(outcome, CloseOutcome::ClosedBackupIncomplete(_)), + "{outcome:?}" + ); + assert!( + shim.join("hooked").exists(), + "git never reached its ref update" + ); + assert_eq!(locks_under(&target), Vec::::new()); + assert_eq!(locks_under(&archive), Vec::::new()); + assert!( + !record().contains("lock_removed") && !record().contains("lock_left"), + "git removed its own locks: nothing was cleaned up here: {}", + record() + ); + std::fs::remove_file(shim.join("slow-push")).unwrap(); + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + let status = home.admin(Request::BackUpNow { + id: A.into(), + new_disk: false, + }); + match &status { + Response::BackedUp { targets, .. } => { + assert!(targets.iter().all(|t| t.problem.is_none()), "{status:?}"); + } + other => panic!("{other:?}"), + } + fsck_of(&archive); + fsck_of(&target); + ledger_store::chain::read( + &home.book_dir(A).join("ops").join("backup.jsonl"), + "wanderbooks-backup-v1", + ) + .expect("the backup record is a whole chain"); + assert!(server.close().success()); +} + +/// A tool call sent on `w`'s session, its whole body written and its answer +/// not yet read: the connection it went out on. +#[cfg(unix)] +fn call_unanswered(home: &Home, w: &Wire, id: u64, tool: &str, args: Value) -> raw::Raw { + let mut raw = raw::Raw::connect(home, A); + let body = json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": { + "name": tool, "arguments": args}}) + .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(), + ); + raw +} + +/// Hold every process of the group `pid` leads still (SIGSTOP): a SIGTERM +/// sent to it then stays pending, git can't end on it, and only the kill +/// after the grace ends it (how a git that can't end on SIGTERM, holding +/// its locks, is made on purpose). +#[cfg(unix)] +fn freeze_group_of(pid: u32) { + let out = std::process::Command::new("ps") + .args(["-o", "pgid=", "-p", &pid.to_string()]) + .output() + .unwrap(); + let group: i32 = String::from_utf8_lossy(&out.stdout) + .trim() + .parse() + .expect("ps names the group"); + // SAFETY: stopping the group of a git this test's server started. + assert_eq!(unsafe { libc::kill(-group, libc::SIGSTOP) }, 0); +} + +/// The most a close may take in these tests where what it stops would +/// otherwise run for ever (a stall that is never lifted): a guard against a +/// hang, not a measure of speed. That the close ends at all, with the stall +/// still in place, is what proves it stopped the call or job. +#[cfg(unix)] +const NEVER_LONGER: Duration = Duration::from_secs(120); + +/// The backup record of `id`, whole. +#[cfg(unix)] +fn backup_record_of(home: &Home, id: &str) -> Vec> { + ledger_store::chain::read( + &ledger_store::ops::ops_dir(&home.book_dir(id)).join("backup.jsonl"), + "wanderbooks-backup-v1", + ) + .expect("the backup record is a whole chain") + .records +} + +/// A backup call that is running (git stalled) when a close begins is +/// STOPPED by it, not waited for: the call is answered, while git is still +/// stalled, that it was stopped because the books are closing; its access +/// record says `refused: stopped_by_close`; the backup records `stopped` +/// and no result of the run's own (nothing it was doing is recorded as +/// done); git and all it started are gone; and the close's own last +/// backup is made as always (local.rs INVARIANT 10). +#[cfg(unix)] +#[test] +fn a_close_stops_a_running_backup_call_and_says_so() { + let home = Home::new("close-stops-backup-call"); + let shim = shim_git(&home); + let server = server_with_shim( + &home, + &shim, + &[ + "--close-backup", + "20000", + "--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"); + std::fs::write(shim.join("stall"), b"").unwrap(); + let mut call = call_unanswered(&home, &w, 4, "books.back_up_now", json!({})); + wait_for("the call reached git", Duration::from_secs(60), || { + shim.join("stalled").exists() + }); + let started = std::time::Instant::now(); + let closing = std::thread::spawn({ + let admin = home.run().join("admin.sock"); + move || ledger_mcp::admin::call(&admin, Request::CloseBook { id: A.into() }).unwrap() + }); + // Answered with git still stalled: stopped by the close, not let go. + let (status, said) = call.answer(); + assert_eq!(status, 200, "{said}"); + assert!( + said.contains("stopped because the books are closing") + && said.contains("nothing it was doing is recorded as done"), + "{said}" + ); + assert!(shim.join("stall").exists(), "the stall was lifted first"); + // Lifted now, so the close's own last backup can run. + std::fs::remove_file(shim.join("stall")).unwrap(); + match closing.join().unwrap() { + Response::CloseBook { outcome, .. } => assert_eq!(outcome, CloseOutcome::Closed), + other => panic!("{other:?}"), + } + assert!(started.elapsed() < NEVER_LONGER); + let stalled: Vec = std::fs::read_to_string(shim.join("stalled")) + .unwrap_or_default() + .lines() + .filter_map(|l| l.trim().parse().ok()) + .collect(); + for pid in &stalled { + assert!(!alive(*pid), "git {pid} still runs"); + } + let records = access_of(&home, A); + let mine = records + .iter() + .find(|r| r.access.subject == "books.back_up_now") + .expect("the call is on record"); + assert_eq!( + mine.access.result, + ledger_store::access::Outcome::Refused("stopped_by_close".into()) + ); + assert!(mine.access.head_after.is_none()); + let record = backup_record_of(&home, A); + assert!( + record + .iter() + .any(|r| r.get("kind") == Some(&json!("stopped")) + && r.get("why") == Some(&json!("asked"))), + "{record:?}" + ); + assert!( + !record + .iter() + .any(|r| r.get("why") == Some(&json!("asked")) + && r.get("kind") != Some(&json!("stopped"))), + "the stopped run recorded a result of its own: {record:?}" + ); + assert!(server.close().success()); +} + +/// A verification and a package that are running when a close begins are +/// stopped by it, each answering that it was stopped because the books are +/// closing, each on record as `refused: stopped_by_close`, and the journal +/// untouched. Each is held as it begins by the server's test knob +/// (`--timer-hold`: `call:books.verify`, `call:books.export_cpa_package`), +/// which the close's start releases; the stop is then at the call's first +/// look. +#[cfg(unix)] +#[test] +fn a_close_stops_a_running_verification_and_a_running_package_and_says_so() { + let home = Home::new("close-stops-verify-package"); + let server = Server::start_with( + &home, + &[ + "--timer-hold", + "--timers", + "20", + "--backup-quiet", + "3600000", + ], + ); + home.create(A, "USD"); + let run = home.run(); + let mut w = Wire::new(&home, A); + w.initialize("owner"); + let mut other = Wire::new(&home, A); + other.initialize("packager"); + let held = ["call:books.verify", "call:books.export_cpa_package"]; + std::fs::write(run.join("timer-hold"), held.join(",")).unwrap(); + let mut verify = call_unanswered(&home, &w, 4, "books.verify", json!({})); + let mut package = call_unanswered( + &home, + &other, + 5, + "books.export_cpa_package", + json!({"cash_accounts": ["1000"]}), + ); + let seen = || std::fs::read_to_string(run.join("timer-held")).unwrap_or_default(); + wait_for("both calls are held", Duration::from_secs(60), || { + held.iter().all(|h| seen().lines().any(|l| l == *h)) + }); + let before = files_of(&home, A); + let started = std::time::Instant::now(); + // The hold is never lifted by the test: the close does it (it is the + // close that releases the calls, which then stop at their first look). + let closing = std::thread::spawn({ + let admin = home.run().join("admin.sock"); + move || ledger_mcp::admin::call(&admin, Request::CloseBook { id: A.into() }).unwrap() + }); + for (what, call) in [("verify", &mut verify), ("package", &mut package)] { + let (status, said) = call.answer(); + assert_eq!(status, 200, "{what}: {said}"); + assert!( + said.contains("stopped because the books are closing"), + "{what}: {said}" + ); + } + match closing.join().unwrap() { + Response::CloseBook { outcome, .. } => assert_eq!(outcome, CloseOutcome::Closed), + other => panic!("{other:?}"), + } + assert!(started.elapsed() < NEVER_LONGER); + assert_eq!(files_of(&home, A).0.len(), before.0.len()); + let records = access_of(&home, A); + for tool in ["books.verify", "books.export_cpa_package"] { + let mine = records + .iter() + .find(|r| r.access.subject == tool) + .unwrap_or_else(|| panic!("{tool} isn't on record")); + assert_eq!( + mine.access.result, + ledger_store::access::Outcome::Refused("stopped_by_close".into()), + "{tool}" + ); + assert!(mine.access.head_after.is_none(), "{tool}"); + } + std::fs::remove_file(run.join("timer-hold")).unwrap(); + assert!(server.close().success()); +} + +/// How many decisions the journal of `id` holds. +#[cfg(unix)] +fn decisions_of(home: &Home, id: &str) -> usize { + files_of(home, id) + .0 + .iter() + .filter(|l| l.line_type == "decision.recorded") + .count() +} + +/// A package that goes with a decision (a reason to export with drafts open +/// or without an audit) is journaled ahead of its build, because the package +/// counts the decision (its README and every footer carry the journal's +/// event count at the build), so the decision may be on record only for a +/// package that is made: a close that begins before the decision is journaled +/// stops the package, and nothing is journaled; one that begins after it +/// doesn't stop it, and the package is handed over whole (tools/reports.rs +/// `export_cpa_package` INVARIANT 4, local.rs INVARIANT 10). The first call is +/// held as it begins and the second right after its decision is journaled, by +/// the server's test knob (`--timer-hold`), which the close's start releases. +#[cfg(unix)] +#[test] +fn a_close_never_leaves_a_decision_on_record_for_a_package_that_was_not_made() { + let home = Home::new("close-package-decision"); + let server = Server::start_with( + &home, + &[ + "--timer-hold", + "--timers", + "20", + "--backup-quiet", + "3600000", + ], + ); + home.create(A, "USD"); + let run = home.run(); + let args = json!({ + "cash_accounts": ["1000"], + "allow_open_drafts": {"reason": "the CPA wants it before the receipt comes"} + }); + let seen = |name: &str| { + std::fs::read_to_string(run.join("timer-held")) + .unwrap_or_default() + .lines() + .any(|l| l == name) + }; + let mut w = Wire::new(&home, A); + w.initialize("owner"); + let r = w.call( + "books.add_account", + json!({"code": "1000", "name": "Bank", "account_type": "asset"}), + ); + assert_eq!(r["result"]["isError"], json!(false), "{r}"); + draft(&mut w, "still open"); + // 1. The close begins before the decision is journaled. + let at_start = "call:books.export_cpa_package"; + std::fs::write(run.join("timer-hold"), at_start).unwrap(); + let mut package = call_unanswered(&home, &w, 7, "books.export_cpa_package", args.clone()); + wait_for("the package is held", Duration::from_secs(60), || { + seen(at_start) + }); + let started = std::time::Instant::now(); + assert_eq!(decisions_of(&home, A), 0); + let closing = admin_in_thread(&home, Request::CloseBook { id: A.into() }); + let (status, said) = package.answer(); + assert_eq!(status, 200, "{said}"); + assert!( + said.contains("stopped because the books are closing"), + "{said}" + ); + assert_eq!( + finished("the close", closing), + Response::CloseBook { + id: A.into(), + outcome: CloseOutcome::Closed + } + ); + assert!(started.elapsed() < NEVER_LONGER); + assert_eq!( + decisions_of(&home, A), + 0, + "a decision is on record for a package that was stopped" + ); + let stopped = access_of(&home, A) + .into_iter() + .find(|r| r.access.subject == "books.export_cpa_package") + .expect("the call is on record"); + assert_eq!( + stopped.access.result, + ledger_store::access::Outcome::Refused("stopped_by_close".into()) + ); + // 2. The close begins after it: the package is made all the same. + std::fs::remove_file(run.join("timer-hold")).unwrap(); + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + let after = "call:books.export_cpa_package:journaled"; + std::fs::write(run.join("timer-hold"), after).unwrap(); + let mut w = Wire::new(&home, A); + w.initialize("owner"); + let mut package = call_unanswered(&home, &w, 8, "books.export_cpa_package", args); + wait_for( + "the package is held after its decision", + Duration::from_secs(60), + || seen(after), + ); + assert_eq!( + decisions_of(&home, A), + 1, + "the decision isn't journaled yet" + ); + let closing = admin_in_thread(&home, Request::CloseBook { id: A.into() }); + let (status, said) = package.answer(); + assert_eq!(status, 200, "{said}"); + assert!( + !said.contains("stopped because the books are closing") && said.contains("download"), + "a package with its decision journaled was stopped by a close: {said}" + ); + assert_eq!( + finished("the close", closing), + Response::CloseBook { + id: A.into(), + outcome: CloseOutcome::Closed + } + ); + assert_eq!(decisions_of(&home, A), 1); + let made = access_of(&home, A) + .into_iter() + .rev() + .find(|r| r.access.subject == "books.export_cpa_package") + .expect("the call is on record"); + assert_eq!(made.access.result, ledger_store::access::Outcome::Ok); + std::fs::remove_file(run.join("timer-hold")).unwrap(); + assert!(server.close().success()); +} + +/// The files of `books/` byte for byte (the staging and scratch folders +/// among them), but for the books in `live`: those the server has open and +/// works on by itself (its timers write their archives and logs). +#[cfg(unix)] +fn root_without(home: &Home, live: &[&str]) -> BTreeMap { + tree_of(&home.root().join("books")) + .into_iter() + .filter(|(k, _)| !live.iter().any(|b| k.starts_with(&format!("{b}/")))) + .collect() +} + +/// The jobs on the admin socket that can run long (restore, adopt, create, +/// open), each held inside a phase by the server's test knob (`--timer-hold`, +/// `job:phase`) until the name is gone or a stop is asked. Returns, for each, +/// the request, the held name, what it says it didn't do, and whether it +/// leaves a folder of its own in `books/` while it is held. +#[cfg(unix)] +struct Jobs { + /// The backup a restore reads (`acme`'s). + repo: PathBuf, + restore_head: (u64, String), + adopt_head: (u64, String), + data: PathBuf, + toml: String, + /// Keeps the adoption's source alive. + _old: tempfile::TempDir, +} + +#[cfg(unix)] +impl Jobs { + /// Books `A` (backed up to a folder) and `cedar` (closed) exist; the + /// previews of a restore of that backup and of an adoption are taken. + fn new(home: &Home) -> Self { + home.create(A, "USD"); + home.create(CEDAR, "USD"); + assert!(matches!(close_book(home, CEDAR), CloseOutcome::Closed)); + let mut w = Wire::new(home, A); + w.initialize("owner"); + let repo = backed_up_to_folder(home, &mut w, A); + w.end(); + let old = tempfile::Builder::new() + .prefix("wb-close-old-") + .tempdir() + .unwrap(); + let data = old.path().join("books-data"); + drop(ledger_store::Store::create(&data, ledger_core::Currency::USD).unwrap()); + let toml = "[company]\nname = \"Acme Widgets LLC\"\n".to_string(); + let restore_head = match home.admin(Request::Restore { + id: "gamma".into(), + source: repo.display().to_string(), + replace: false, + confirmed: false, + expect_head: None, + }) { + Response::RestorePreview(p) => p.head, + other => panic!("{other:?}"), + }; + let mut jobs = Self { + repo, + restore_head, + adopt_head: (0, String::new()), + data, + toml, + _old: old, + }; + jobs.adopt_head = match home.admin(jobs.adopt(false)) { + Response::Preview(p) => p.source_head, + other => panic!("{other:?}"), + }; + jobs + } + + fn adopt(&self, confirmed: bool) -> Request { + Request::Adopt { + id: "delta".into(), + source: self.data.clone(), + settings_toml: Some(self.toml.clone()), + config_json: None, + vault_dir: None, + vault_key: None, + confirmed, + expect_head: confirmed.then(|| self.adopt_head.clone()), + skip_unknown: true, + } + } + + /// A restore of the backup as books `id`, over the books that exist + /// when `replace`. + fn restore(&self, id: &str, replace: bool) -> Request { + Request::Restore { + id: id.into(), + source: self.repo.display().to_string(), + replace, + confirmed: true, + expect_head: Some(self.restore_head.clone()), + } + } +} + +#[cfg(unix)] +const CEDAR: &str = "cedar"; + +/// How many times the server has said it holds `name` (`run/timer-held`). +#[cfg(unix)] +fn times_held(run: &std::path::Path, name: &str) -> usize { + std::fs::read_to_string(run.join("timer-held")) + .unwrap_or_default() + .lines() + .filter(|l| *l == name) + .count() +} + +/// A job started on its own thread, and waited for until the server holds it +/// inside the phase `name`; the thread that will have its answer. +#[cfg(unix)] +fn job_held_in( + home: &Home, + name: &str, + job: &Request, + hold: &str, +) -> std::thread::JoinHandle { + let run = home.run(); + std::fs::write(run.join("timer-hold"), hold).unwrap(); + let seen = times_held(&run, name); + let running = std::thread::spawn({ + let admin = run.join("admin.sock"); + let job = job.clone(); + move || ledger_mcp::admin::call(&admin, job).unwrap() + }); + wait_for( + &format!("{name} is held inside the job"), + Duration::from_secs(300), + || times_held(&run, name) > seen || running.is_finished(), + ); + if running.is_finished() { + panic!( + "{name}: the job ended before it was held: {:?}", + running.join() + ); + } + running +} + +/// A job on the admin socket (restore, adopt, create, open) is stopped by a +/// close only when the close is of the book the job works on, or is the +/// server's own (local.rs INVARIANT 10). Stopped, it answers that it was +/// stopped because the books are closing, what it wrote is removed, and the +/// root is byte for byte as it was (the job's staging or scratch folder is +/// there while it is held, and gone after; asked again with no close, it +/// goes through). Each job is held inside a phase by the server's test knob +/// (`--timer-hold`, `job:phase`), which the stop releases; the stop is then at +/// the job's next look. +/// +/// A restore over a book, and the opening of a book, are work on that book: a +/// close of it stops them. A create, an adoption and a restore that replaces +/// nothing make a NEW book, which no close of a book is the close of: only the +/// server's stops them (the other test below, of closes that stop nothing). +#[cfg(unix)] +#[test] +fn a_close_stops_the_restore_and_the_open_of_its_own_book_leaving_the_root_as_it_was() { + let home = Home::new("close-stops-own-jobs"); + let server = Server::start_with(&home, &JOB_ARGS); + let jobs = Jobs::new(&home); + let run = home.run(); + // (the held name, the job, what it says it didn't do, the book whose + // close stops it, whether it leaves a folder of its own in `books/`) + let table: Vec<(&str, Request, &str, &str, bool)> = vec![ + ( + "restore:copy", + jobs.restore(A, true), + "nothing was restored", + A, + true, + ), + ( + "open:start", + Request::OpenBook { id: CEDAR.into() }, + "not opened", + CEDAR, + false, + ), + ]; + // The books open and live while a job is held: not compared (the job's + // own book, not yet there, is). + let live = [A, CEDAR]; + for (name, job, said, closes, leaves_a_folder) in table { + let before = root_without(&home, &live); + let legacy_before = tree_of(&home.root().join("legacy")); + let running = job_held_in(&home, name, &job, name); + if leaves_a_folder { + assert_ne!( + root_without(&home, &live), + before, + "{name}: the job wrote nothing while held" + ); + } + let started = std::time::Instant::now(); + // The close of the book the job works on: it stops the job (it + // waits for the job's turn otherwise), and the test lifts nothing. + let closed = close_book(&home, closes); + assert_eq!(closed, CloseOutcome::WasNotOpen, "{name}"); + assert!(started.elapsed() < NEVER_LONGER, "{name}"); + let answer = running.join().unwrap(); + let text = format!("{answer:?}"); + assert!( + text.contains("stopped because the books are closing") && text.contains(said), + "{name}: {text}" + ); + std::fs::remove_file(run.join("timer-hold")).unwrap(); + assert_eq!( + moved(&before, &root_without(&home, &live)), + Vec::::new(), + "{name}: the root isn't as it was" + ); + assert_eq!( + tree_of(&home.root().join("legacy")), + legacy_before, + "{name}" + ); + // Asked again, with nothing closing, it goes through. + if closes == A { + assert_eq!(open_book(&home, A), OpenOutcome::Opened, "{name}"); + } + match (name, home.admin(job)) { + ("restore:copy", Response::Restored(_)) | ("open:start", Response::OpenBook { .. }) => { + } + (name, other) => panic!("{name}, asked again: {other:?}"), + } + } + for id in [A, CEDAR] { + assert_eq!(listed(&home, id), (true, false, None), "{id}"); + } + assert!(server.close().success()); +} + +/// The server's own close stops every job on the admin socket, as a close of +/// one book stops the work on that book: each held inside its phase, the +/// server is closed, and each answers that it was stopped because the books +/// are closing, with the root byte for byte as it was, and the server +/// exits 0. +#[cfg(unix)] +#[test] +fn the_servers_close_stops_every_running_admin_job_leaving_the_root_as_it_was() { + let home = Home::new("server-close-stops-jobs"); + let mut server = Server::start_with(&home, &JOB_ARGS); + let jobs = Jobs::new(&home); + let table: Vec<(&str, Request, &str, bool)> = vec![ + ( + "restore:copy", + jobs.restore("gamma", false), + "nothing was restored", + true, + ), + ( + "restore:copy", + jobs.restore(A, true), + "nothing was restored", + true, + ), + ("adopt:open", jobs.adopt(true), "nothing was adopted", true), + ( + "create:start", + Request::Create { + id: "epsilon".into(), + currency: "USD".into(), + }, + "nothing was created", + false, + ), + ( + "open:start", + Request::OpenBook { id: CEDAR.into() }, + "not opened", + false, + ), + ]; + // The books a server has open when it is closed write to their folders as + // they are let go: `acme`, and `gamma` once the first job is asked again. + let live = [A, "gamma"]; + for (n, (name, job, said, leaves_a_folder)) in table.into_iter().enumerate() { + let before = root_without(&home, &live); + let legacy_before = tree_of(&home.root().join("legacy")); + let running = job_held_in(&home, name, &job, name); + if leaves_a_folder { + assert_ne!( + root_without(&home, &live), + before, + "{name}: the job wrote nothing while held" + ); + } + let started = std::time::Instant::now(); + // Nothing lifts the hold but the server's close. + assert!(server.close().success(), "{name}"); + assert!(started.elapsed() < NEVER_LONGER, "{name}"); + let text = format!("{:?}", running.join().unwrap()); + assert!( + text.contains("stopped because the books are closing") && text.contains(said), + "{name}: {text}" + ); + std::fs::remove_file(home.run().join("timer-hold")).unwrap(); + assert_eq!( + moved(&before, &root_without(&home, &live)), + Vec::::new(), + "{name}: the root isn't as it was" + ); + assert_eq!( + tree_of(&home.root().join("legacy")), + legacy_before, + "{name}" + ); + server = job_server_again(&home); + // Asked again, with nothing closing, it goes through (the first time + // on this server only: the others would change what comes next). + if n == 0 { + match home.admin(job) { + Response::Restored(_) => {} + other => panic!("{name}, asked again: {other:?}"), + } + // Only `acme` is opened again: `cedar` is closed, as the open + // job after this needs it. + assert_eq!(listed(&home, CEDAR), (false, true, None)); + } + } + assert!(server.close().success()); +} + +/// An admin request made on its own thread. +#[cfg(unix)] +fn admin_in_thread(home: &Home, request: Request) -> std::thread::JoinHandle { + let admin = home.run().join("admin.sock"); + std::thread::spawn(move || ledger_mcp::admin::call(&admin, request).unwrap()) +} + +/// Wait for a thread to finish, failing (never hanging) if it doesn't. +#[cfg(unix)] +fn finished(what: &str, thread: std::thread::JoinHandle) -> T { + wait_for(what, Duration::from_secs(120), || thread.is_finished()); + thread.join().unwrap() +} + +/// Closing and opening one book never stops, fails, refuses or delays +/// another book's work (local.rs INVARIANT 10, the first rule of the unit), +/// the work on the admin socket included. A restore over `beta`, a create of +/// `epsilon` and an adoption of `delta` are each held in flight (inside a +/// phase, by the server's test knob; they make books one at a time, so the +/// second and third wait for their turn, not yet held, until the one before +/// is let go), and `acme` is closed and opened again while each is: its +/// close is made slow (its backup's git stalls), and during it another book +/// (`cedar`) is opened and closed and answers at once, while the close of +/// `acme` is still not answered. All three jobs finish correctly, none +/// stopped, none told of any error. +#[cfg(unix)] +#[test] +fn closing_and_opening_one_book_never_stops_waits_for_or_refuses_another_books_jobs() { + let home = Home::new("close-spares-other-jobs"); + let shim = shim_git(&home); + let mut args = JOB_ARGS.to_vec(); + args.extend(["--close-backup", "120000"]); + let server = server_with_shim(&home, &shim, &args); + let jobs = Jobs::new(&home); + home.create(B, "USD"); + let run = home.run(); + let stalled = || { + std::fs::read_to_string(shim.join("stalled")) + .unwrap_or_default() + .lines() + .count() + }; + // One close and reopening of `acme`, while the jobs are held. + let cycle = |why: &str| { + let before = stalled(); + std::fs::write(shim.join("stall"), b"").unwrap(); + let closing = admin_in_thread(&home, Request::CloseBook { id: A.into() }); + wait_for( + &format!("{why}: the close of {A} is in its backup"), + Duration::from_secs(120), + || stalled() > before || closing.is_finished(), + ); + assert!( + !closing.is_finished(), + "{why}: the close of {A} was answered with its backup stalled" + ); + // Another book is opened, and closed, while this close is not + // answered: neither waits for it, nor is refused. + let opening = admin_in_thread(&home, Request::OpenBook { id: CEDAR.into() }); + assert_eq!( + finished( + &format!("{why}: an open of {CEDAR} during the close of {A}"), + opening + ), + Response::OpenBook { + id: CEDAR.into(), + outcome: OpenOutcome::Opened + }, + "{why}" + ); + assert!(!closing.is_finished(), "{why}: the close was answered"); + let shutting = admin_in_thread(&home, Request::CloseBook { id: CEDAR.into() }); + assert_eq!( + finished( + &format!("{why}: a close of {CEDAR} during the close of {A}"), + shutting + ), + Response::CloseBook { + id: CEDAR.into(), + outcome: CloseOutcome::Closed + }, + "{why}" + ); + assert!(!closing.is_finished(), "{why}: the close was answered"); + std::fs::remove_file(shim.join("stall")).unwrap(); + assert_eq!( + finished(&format!("{why}: the close of {A}"), closing), + Response::CloseBook { + id: A.into(), + outcome: CloseOutcome::Closed + }, + "{why}" + ); + assert_eq!(open_book(&home, A), OpenOutcome::Opened, "{why}"); + }; + let hold = |names: &[&str]| std::fs::write(run.join("timer-hold"), names.join(",")).unwrap(); + // The restore holds the turn; the other two are asked, and wait for it. + let restore = jobs.restore(B, true); + let restoring = job_held_in( + &home, + "restore:copy", + &restore, + "restore:copy,create:start,adopt:open", + ); + let create = Request::Create { + id: "epsilon".into(), + currency: "USD".into(), + }; + // (The server says every phase it passes, held or not: the books made + // so far have passed `create:start`.) + let seen = |name: &str| times_held(&run, name); + let base = [ + ("create:start", seen("create:start")), + ("adopt:open", seen("adopt:open")), + ]; + let taken = |name: &str| { + seen(name) + > base + .iter() + .find(|(n, _)| *n == name) + .map(|(_, c)| *c) + .unwrap() + }; + let queued = [ + ("create:start", admin_in_thread(&home, create)), + ("adopt:open", admin_in_thread(&home, jobs.adopt(true))), + ]; + for n in 0..2 { + cycle(&format!("restore over {B}, round {n}")); + assert!(!restoring.is_finished(), "the restore was stopped or ended"); + assert!( + queued.iter().all(|(_, q)| !q.is_finished()), + "a queued job was stopped or ended" + ); + } + assert!( + !taken("create:start") && !taken("adopt:open"), + "a job took the turn from the restore" + ); + // The restore is let go; it finishes. + hold(&["create:start", "adopt:open"]); + match finished("the restore over beta", restoring) { + Response::Restored(r) => assert!(r.problem.is_none(), "{r:?}"), + other => panic!("the restore: {other:?}"), + } + // Then each of the others takes the turn in its time, and is held. + let mut waiting: Vec<(&str, std::thread::JoinHandle)> = queued.into_iter().collect(); + while !waiting.is_empty() { + wait_for( + "a queued job has its turn", + Duration::from_secs(300), + || waiting.iter().any(|(n, _)| taken(n)), + ); + let at = waiting.iter().position(|(n, _)| taken(n)).unwrap(); + let (name, job) = waiting.remove(at); + assert!(!job.is_finished(), "{name} ended while it was held"); + cycle(name); + assert!(!job.is_finished(), "{name} was stopped or ended"); + let names: Vec<&str> = waiting.iter().map(|(n, _)| *n).collect(); + hold(&names); + match (name, finished(name, job)) { + ("create:start", Response::Created { problem, .. }) => { + assert!(problem.is_none(), "{problem:?}"); + } + ("adopt:open", Response::Adopted(a)) => assert!(a.problem.is_none(), "{a:?}"), + (name, other) => panic!("{name}: {other:?}"), + } + } + for id in [A, B, "epsilon", "delta"] { + assert_eq!(listed(&home, id), (true, false, None), "{id}"); + } + assert_eq!(listed(&home, CEDAR), (false, true, None)); + assert!(server.close().success()); +} + +/// The arguments of the servers the job tests start. +#[cfg(unix)] +const JOB_ARGS: [&str; 7] = [ + "--timer-hold", + "--timers", + "20", + "--backup-quiet", + "3600000", + "--answer-grace", + "300", +]; + +/// A server again, on books made by an earlier one: only `acme` open, as it +/// was left (the other books of the root are closed). +#[cfg(unix)] +fn job_server_again(home: &Home) -> Server { + let mut args = JOB_ARGS.to_vec(); + args.extend(["--open", A]); + Server::start_with(home, &args) +} + +/// A git that can't end on SIGTERM (its group frozen here, so the signal +/// stays pending) is killed once the grace has run out, and the lock it +/// leaves in a backup FOLDER is the owner's: the server never removes it. It +/// is recorded with its whole path, the target's backup is marked failed with +/// words naming the file and saying when it may be removed, the close says +/// its last backup wasn't whole, and the status (`books.backup`) says the +/// same after the book is opened again. The next backup, meeting the lock, +/// fails by git's own words and leaves the file; once the owner removes it +/// the backup goes on, and both repositories pass `git fsck`. +#[cfg(unix)] +#[test] +fn a_lock_a_kill_leaves_in_the_backup_folder_is_reported_and_never_removed_by_the_server() { + let home = Home::new("close-lock-left"); + let shim = slow_real_git(&home); + // A bound long enough that the test freezes git before the close's own + // bound runs out: the freeze is made on the condition that git is + // inside the push, not on a guess at how long that takes. + let server = server_with_shim( + &home, + &shim, + &[ + "--close-backup", + "8000", + "--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, "the first backup"); + match home.admin(Request::BackUpNow { + id: A.into(), + new_disk: false, + }) { + Response::BackedUp { targets, .. } => { + assert!(targets.iter().all(|t| t.problem.is_none()), "{targets:?}"); + } + other => panic!("{other:?}"), + } + draft(&mut w, "to be pushed inside a push"); + let target = disk.join(format!("{A}.git")); + let lock = target.join("refs").join("heads").join("main.lock"); + // Another writer's lock, there before our push: never touched, never + // named. + let another = target.join("refs").join("heads").join("another.lock"); + std::fs::write(&another, b"").unwrap(); + std::fs::write(shim.join("slow-push"), b"").unwrap(); + let closing = std::thread::spawn({ + let admin = home.run().join("admin.sock"); + move || ledger_mcp::admin::call(&admin, Request::CloseBook { id: A.into() }).unwrap() + }); + wait_for("git is inside the push", Duration::from_secs(60), || { + shim.join("hooked").exists() && lock.exists() + }); + let hooked: u32 = std::fs::read_to_string(shim.join("hooked")) + .unwrap() + .lines() + .next() + .unwrap() + .trim() + .parse() + .unwrap(); + freeze_group_of(hooked); + let outcome = match closing.join().unwrap() { + Response::CloseBook { outcome, .. } => outcome, + other => panic!("{other:?}"), + }; + let why = match outcome { + CloseOutcome::ClosedBackupIncomplete(why) => why, + other => panic!("a backup that left a lock was answered as {other:?}"), + }; + let lock_text = lock.display().to_string(); + assert!(why.contains(&lock_text), "{why}"); + assert!( + why.contains("nothing else is using the backup folder"), + "{why}" + ); + assert!(!why.contains("another.lock"), "{why}"); + assert!(!why.contains(&home.root().display().to_string()), "{why}"); + // Left where it was: the server deleted nothing in the owner's folder. + assert!(lock.exists(), "a file in the owner's folder was deleted"); + assert!(another.exists()); + let record = backup_record_of(&home, A); + assert!( + record + .iter() + .any(|r| r.get("kind") == Some(&json!("lock_left")) + && r.get("repo") == Some(&json!("folder")) + && r.get("path") == Some(&json!(lock_text))), + "{record:?}" + ); + assert!( + !record + .iter() + .any(|r| r.get("kind") == Some(&json!("lock_removed")) + && r.get("repo") == Some(&json!("folder"))), + "{record:?}" + ); + // Opened again, the status says it, in words that name the file. + std::fs::remove_file(shim.join("slow-push")).unwrap(); + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + let mut w = Wire::new(&home, A); + w.initialize("owner"); + let status = w.call("books.backup", json!({})); + let shown = status["result"]["structuredContent"]["targets"][0]["last_error"] + .as_str() + .unwrap_or_else(|| panic!("the status names no failure: {status}")) + .to_string(); + assert!(shown.contains(&lock_text), "{shown}"); + assert!( + shown.contains("nothing else is using the backup folder"), + "{shown}" + ); + // With the lock still there the next backup fails (git's own words) and + // the file stays; once the owner removes it, it goes on. + match home.admin(Request::BackUpNow { + id: A.into(), + new_disk: false, + }) { + Response::BackedUp { targets, .. } => { + assert!(targets.iter().any(|t| t.problem.is_some()), "{targets:?}"); + } + other => panic!("{other:?}"), + } + assert!(lock.exists(), "a later backup removed it"); + std::fs::remove_file(&lock).unwrap(); + match home.admin(Request::BackUpNow { + id: A.into(), + new_disk: false, + }) { + Response::BackedUp { targets, .. } => { + assert!(targets.iter().all(|t| t.problem.is_none()), "{targets:?}"); + } + other => panic!("{other:?}"), + } + assert!(another.exists()); + fsck_of(&home.book_dir(A).join("archive.git")); + fsck_of(&target); + assert!(server.close().success()); +} + +/// Whether `thread` finished within `within`, never hanging the test. +#[cfg(unix)] +fn finishes_within(thread: &std::thread::JoinHandle, within: Duration) -> bool { + let by = std::time::Instant::now() + within; + while !thread.is_finished() { + if std::time::Instant::now() >= by { + return false; + } + std::thread::sleep(Duration::from_millis(10)); + } + true +} + +/// A restore PREVIEW changes nothing, so it holds no book's turn: a close of +/// the book it is about is answered while the preview is still running (held +/// inside its fetch by the test knob, which only the test lifts), and the +/// preview then finishes and answers as it would have (local.rs INVARIANT +/// 10: a close never waits behind a preview, however long its clone or its +/// queue for `books.lock`). +#[cfg(unix)] +#[test] +fn a_close_is_answered_while_a_restore_preview_of_its_book_is_still_running() { + let home = Home::new("close-not-held-by-preview"); + let server = Server::start_with(&home, &JOB_ARGS); + let jobs = Jobs::new(&home); + let preview = Request::Restore { + id: A.into(), + source: jobs.repo.display().to_string(), + replace: false, + confirmed: false, + expect_head: None, + }; + let previewing = job_held_in(&home, "restore:fetch", &preview, "restore:fetch"); + let closing = admin_in_thread(&home, Request::CloseBook { id: A.to_string() }); + let answered = finishes_within(&closing, Duration::from_secs(20)); + // Lifted before anything is asserted, so a failure never hangs. + std::fs::remove_file(home.run().join("timer-hold")).unwrap(); + assert!(answered, "the close waited for the preview of its own book"); + match closing.join().unwrap() { + Response::CloseBook { + outcome: CloseOutcome::Closed, + .. + } => {} + other => panic!("{other:?}"), + } + match previewing.join().unwrap() { + Response::RestorePreview(p) => assert!(p.exists, "{p:?}"), + other => panic!("{other:?}"), + } + assert!(server.close().success()); +} + +/// A close of an id stops an adoption that is making that id, before its +/// point of no return: the adoption (held in its opening of the copy by the +/// test knob, which only the stop lifts) answers that it was stopped and +/// that nothing was adopted, the root is as it was, and the close, which +/// waited for the adoption's turn, is answered at once after: there is no +/// such book (local.rs INVARIANT 10). +#[cfg(unix)] +#[test] +fn a_close_of_an_id_stops_the_adoption_that_is_making_it() { + let home = Home::new("close-stops-adoption-of-its-id"); + let server = Server::start_with(&home, &JOB_ARGS); + let jobs = Jobs::new(&home); + let live = [A, CEDAR]; + let before = root_without(&home, &live); + let adopting = job_held_in(&home, "adopt:open", &jobs.adopt(true), "adopt:open"); + let closing = admin_in_thread( + &home, + Request::CloseBook { + id: "delta".to_string(), + }, + ); + let answered = finishes_within(&closing, Duration::from_secs(20)); + // Lifted before anything is asserted, so a failure never hangs. + std::fs::remove_file(home.run().join("timer-hold")).unwrap(); + assert!( + answered, + "the close of an id waited for the adoption making it" + ); + let text = format!("{:?}", adopting.join().unwrap()); + assert!( + text.contains("stopped because the books are closing") + && text.contains("nothing was adopted"), + "{text}" + ); + match closing.join().unwrap() { + Response::CloseBook { + outcome: CloseOutcome::NoSuchBook, + .. + } => {} + other => panic!("{other:?}"), + } + assert_eq!( + moved(&before, &root_without(&home, &live)), + Vec::::new(), + "the root isn't as it was" + ); + assert!(server.close().success()); +} diff --git a/crates/ledger-cli/tests/common/mod.rs b/crates/ledger-cli/tests/common/mod.rs index e3990eb8..f735140e 100644 --- a/crates/ledger-cli/tests/common/mod.rs +++ b/crates/ledger-cli/tests/common/mod.rs @@ -182,9 +182,25 @@ impl Server { Self::start_in(home, home.dir.path(), &[]) } + /// [`Server::start`], with these arguments after the root (`--open`). + pub fn start_with(home: &Home, args: &[&str]) -> Self { + 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 { + Self::spawn(home, cwd, env, &[]) + } + + fn spawn(home: &Home, cwd: &Path, env: &[(&str, &Path)], args: &[&str]) -> Self { let log = std::fs::OpenOptions::new() .create(true) .append(true) @@ -195,6 +211,7 @@ impl Server { .arg("server") .arg("--root") .arg(home.root()) + .args(args) .current_dir(cwd); clean_env(&mut command, home.dir.path()); let mut child = command @@ -342,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-cli/tests/drafts.rs b/crates/ledger-cli/tests/drafts.rs index 438c62d0..4bc9ebf9 100644 --- a/crates/ledger-cli/tests/drafts.rs +++ b/crates/ledger-cli/tests/drafts.rs @@ -333,6 +333,40 @@ fn cpa_package_refuses_open_draft() { assert!(journal.contains("the CPA wants it before the receipt comes")); } +/// A package the build will refuse is refused before any decision is +/// journaled (tools/reports.rs INVARIANT 4): the books name a member whose +/// capital account isn't in the chart, so the build can never succeed, and +/// an override (the reason for an open draft) must not leave "was exported" +/// on record, once or on a retry, with no package. The journal does not move. +#[test] +fn a_package_the_build_refuses_journals_no_decision_even_with_a_reason() { + let settings = format!( + "{SETTINGS}[[company.members]]\nname = \"Mo\"\nshare = \"100%\"\ncapital_account = \"3999\"\n" + ); + let books = Books::with("p4-cpa-refused", "USD", Some(&settings)); + let mut w = books.session("p4"); + chart(&mut w); + draft(&mut w, "2026-03-10", "Open", "40.00"); + let mut args = json!({"as_of": "2026-03-31", "cash_accounts": ["1000"]}); + args["allow_open_drafts"] = json!({"reason": "the CPA wants it before the receipt comes"}); + let before = books.journal().len(); + for _ in 0..2 { + let why = answer_of(&w.call("books.export_cpa_package", args.clone())) + .expect_err("the build refuses an unknown capital account"); + assert!(why.contains("unknown capital account 3999"), "{why}"); + assert_eq!( + books.journal().len(), + before, + "a decision was journaled for a package that was refused" + ); + } + assert!( + !String::from_utf8(books.journal()) + .unwrap() + .contains("decision.recorded") + ); +} + /// D-50: a confirm takes the preview it was shown; without it, or after a /// changed argument or a write by another session, it is refused with /// `stale_preview` before anything is written. diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index 98741675..e1b22d2e 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -474,10 +474,18 @@ fn books_usage(prog: &str) { eprintln!(" {prog} back-up ID [--new-disk]"); eprintln!(" {prog} upgrade ID"); eprintln!(" {prog} extract BOOK ATTACHMENT"); + eprintln!(" {prog} open ID"); + eprintln!(" {prog} close ID"); eprintln!( " {prog} put-aside ID DATA-DIR [--vault DIR --vault-key FILE] [PATH...] [--yes]" ); - eprintln!(" list the books, and whether each is open"); + eprintln!(" list the books, and whether each is open or closed"); + eprintln!( + " open open one closed book while the server runs, checked as at its start (agents can reach it from then)" + ); + eprintln!( + " close close one book while the server runs: its running calls finish, its sessions end, it is backed up and let go; the others keep serving" + ); eprintln!(" create start new, empty books (base currency USD unless given)"); eprintln!(" adopt copy existing books in, verified; the original is left as it was"); eprintln!( @@ -604,6 +612,18 @@ pub fn books( }; return put_aside(&common, book, old, yes); } + ["open", book] => with_server( + &common, + Request::OpenBook { + id: (*book).to_string(), + }, + ), + ["close", book] => with_server( + &common, + Request::CloseBook { + id: (*book).to_string(), + }, + ), ["back-up", book] => { return match back_up_now(&common, book, new_disk) { Ok(lines) => { @@ -666,6 +686,53 @@ pub fn books( } Ok(()) } + Ok(Response::OpenBook { id, outcome }) => match outcome { + admin::OpenOutcome::Opened => { + println!("Opened the books \"{id}\": agents can reach them now."); + Ok(()) + } + admin::OpenOutcome::AlreadyOpen => { + println!("The books \"{id}\" are open already."); + Ok(()) + } + admin::OpenOutcome::NoSuchBook => { + eprintln!( + "error: there are no books called \"{id}\": `wanderbooks books list` lists them" + ); + Err(exit(1)) + } + admin::OpenOutcome::CouldNotOpen(why) => { + eprintln!("error: the books \"{id}\" couldn't be opened: {why}"); + Err(exit(1)) + } + }, + Ok(Response::CloseBook { id, outcome }) => match outcome { + admin::CloseOutcome::Closed => { + println!( + "Closed the books \"{id}\": nothing is running on them, their sessions ended, and they are let go." + ); + 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(()) + } + admin::CloseOutcome::NoSuchBook => { + eprintln!( + "error: there are no books called \"{id}\": `wanderbooks books list` lists them" + ); + Err(exit(1)) + } + }, Ok(Response::Refused(why)) | Err(why) => { eprintln!("error: {why}"); Err(exit(1)) @@ -679,6 +746,12 @@ pub fn books( /// One book, as `books list` and `doctor` show it. fn book_line(b: &admin::BookStatus) -> String { + if b.closed { + return format!( + "{} closed (`wanderbooks books open {}` opens it)", + b.id, b.id + ); + } match (&b.problem, &b.format_upgrade) { (Some(why), _) => format!("{} didn't open: {why}", b.id), (None, Some(_)) => format!( @@ -689,6 +762,54 @@ fn book_line(b: &admin::BookStatus) -> String { } } +/// `doctor`'s lines for who is connected to each open book: the token's +/// name, the client and agent as they said, when it connected, the calls +/// running and the last call. +fn session_lines(open: &[admin::BookSessions]) -> Vec { + let mut lines = Vec::new(); + if open.iter().all(|b| b.sessions.is_empty()) { + lines.push("Assistants connected: none.".to_string()); + return lines; + } + lines.push("Assistants connected:".to_string()); + for b in open { + if b.sessions.is_empty() { + lines.push(format!(" {}: none", b.book)); + continue; + } + lines.push(format!(" {}:", b.book)); + for s in &b.sessions { + let client = match (&s.client_name, &s.client_version) { + (Some(n), Some(v)) => format!("{n} {v}"), + (Some(n), None) => n.clone(), + _ => "a client that hasn't said who it is".to_string(), + }; + let mut line = format!(" token {:?}, {client}", s.token); + if let Some(a) = &s.agent { + let said: Vec<&str> = [&a.model, &a.reasoning_effort, &a.harness] + .into_iter() + .filter_map(|v| v.as_deref()) + .collect(); + if !said.is_empty() { + line.push_str(&format!(" (says: {})", said.join(", "))); + } + } + line.push_str(&format!(", connected {}", s.connected_at)); + line.push_str(&match s.running { + 0 => ", no call running".to_string(), + 1 => ", 1 call running".to_string(), + n => format!(", {n} calls running"), + }); + match &s.last { + Some(l) => line.push_str(&format!(", last {} ({}) at {}", l.tool, l.outcome, l.at)), + None => line.push_str(", no call yet"), + } + lines.push(line); + } + } + lines +} + /// The projection database a book uses, and the other schemas' files /// beside it (left as they are for the versions that wrote them, never /// deleted), as `doctor` says them; None when it didn't open. @@ -2499,6 +2620,18 @@ pub fn doctor( Ok(admin::Response::Refused(why)) => println!("Agents' tokens: {why}"), Ok(_) | Err(_) => {} } + // Who is connected to each open book, and what it is doing. + match admin::call_within(&socket, Request::Sessions, Some(DOCTOR_WAIT)) { + Ok(admin::Response::Sessions(open)) => { + for line in session_lines(&open) { + println!("{line}"); + } + } + Ok(admin::Response::Refused(why)) => { + println!("Assistants connected: {why}") + } + Ok(_) | Err(_) => {} + } } } else { println!("The books are opening (the books server isn't ready yet)."); @@ -3516,6 +3649,7 @@ mod tests { |problem: Option<&str>, waiting: Option| admin::BookStatus { id: "acme".into(), open: problem.is_none(), + closed: false, problem: problem.map(str::to_string), format_upgrade: waiting, database: None, @@ -3558,6 +3692,78 @@ mod tests { ); } + /// `doctor` says who is connected to each open book: the token's name, + /// the client and what the agent said, when, the calls running, the + /// last call; and that none is when none is. + #[test] + fn doctor_says_who_is_connected() { + let none = [admin::BookSessions { + book: "acme".into(), + sessions: Vec::new(), + }]; + assert_eq!(session_lines(&none), ["Assistants connected: none."]); + let open = [ + admin::BookSessions { + book: "acme".into(), + sessions: vec![ + admin::SessionInfo { + token: "agent".into(), + client_name: Some("claude-code".into()), + client_version: Some("2.1".into()), + agent: Some(admin::SessionAgent { + model: Some("m-1".into()), + reasoning_effort: None, + harness: Some("h-1".into()), + }), + connected_at: "2026-11-20T10:00:00Z".into(), + running: 2, + last: Some(admin::LastCall { + tool: "books.chart".into(), + outcome: "ok".into(), + at: "2026-11-20T10:01:00Z".into(), + }), + }, + admin::SessionInfo { + token: "web".into(), + client_name: None, + client_version: None, + agent: None, + connected_at: "2026-11-20T10:02:00Z".into(), + running: 0, + last: None, + }, + ], + }, + admin::BookSessions { + book: "beta".into(), + sessions: Vec::new(), + }, + ]; + assert_eq!( + session_lines(&open), + [ + "Assistants connected:", + " acme:", + " token \"agent\", claude-code 2.1 (says: m-1, h-1), connected 2026-11-20T10:00:00Z, 2 calls running, last books.chart (ok) at 2026-11-20T10:01:00Z", + " token \"web\", a client that hasn't said who it is, connected 2026-11-20T10:02:00Z, no call running, no call yet", + " beta: none", + ] + ); + let closed = admin::BookStatus { + id: "acme".into(), + open: false, + closed: true, + problem: None, + format_upgrade: None, + database: None, + other_databases: Vec::new(), + }; + assert_eq!( + book_line(&closed), + "acme closed (`wanderbooks books open acme` opens it)" + ); + } + /// `doctor` names the database file a book uses, and any other /// schema's beside it as left alone; nothing for books that didn't /// open. @@ -3566,6 +3772,7 @@ mod tests { let mut b = admin::BookStatus { id: "acme".into(), open: true, + closed: false, problem: None, format_upgrade: None, database: Some("wanderbooks.v13.db".into()), diff --git a/crates/ledger-mcp/src/access.rs b/crates/ledger-mcp/src/access.rs index 31915e29..a06c1d3c 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}; @@ -61,6 +69,17 @@ pub fn caller(context: &RequestContext) -> Option { .cloned() } +/// The MCP session a request belongs to (its `mcp-session-id`), as the +/// door left the request's parts in `extensions`; None for a request that +/// came another way. +pub(crate) fn session_of(extensions: &rmcp::model::Extensions) -> Option { + extensions + .get::() + .and_then(|parts| parts.headers.get(crate::local::SESSION_HEADER)) + .and_then(|v| v.to_str().ok()) + .map(str::to_string) +} + /// The client program, as it named itself at `initialize`. fn client(context: &RequestContext) -> Option { context.peer.peer_info().map(|info| Client { @@ -87,6 +106,12 @@ pub(crate) struct Call { subject: String, args_digest: Option, agent: Option, + /// The book's board of live sessions, and the session this call is + /// in: it counts as running there until the call ends, and is what + /// the session last did once recorded (sessions.rs). + board: Arc, + session: Option, + _live: Option>, } /// Why a call wasn't run, for its record and its answer. @@ -95,8 +120,13 @@ pub(crate) const UNAUTHORIZED: &str = "unauthorized"; pub(crate) const INSUFFICIENT_SCOPE: &str = "insufficient_scope"; /// The books were closing. pub(crate) const CLOSING: &str = "closing"; +/// A close cut the request while its body was still arriving. +pub(crate) const CUT: &str = "cut_by_close"; /// The server had stopped. pub(crate) const STOPPED: &str = "stopped"; +/// A call that was running when a close began, stopped by it: it answered +/// that it was stopped, and nothing it was doing is recorded as done. +pub(crate) const STOPPED_BY_CLOSE: &str = "stopped_by_close"; /// A file's bytes or text came as an argument (D-46). pub(crate) const INLINE_FILE: &str = "inline_file"; @@ -113,11 +143,16 @@ impl Call { /// close beginning meanwhile waits for it. pub(crate) fn new( log: &Arc, + board: &Arc, context: &RequestContext, action: &'static str, subject: &str, ) -> Self { + let session = session_of(&context.extensions); Self { + board: board.clone(), + _live: session.as_deref().map(|sid| Arc::new(board.begin(sid))), + session, log: log.clone(), caller: caller(context), client: client(context), @@ -187,7 +222,19 @@ impl Call { agent: self.agent.clone(), }; match self.log.record(&access) { - Ok(_) => Ok(()), + Ok(_) => { + if let Some(sid) = &self.session { + self.board.finished( + sid, + &access.subject, + &access.result, + access.client.as_ref(), + access.agent.as_ref(), + chrono::Utc::now().timestamp(), + ); + } + Ok(()) + } Err(e) => { eprintln!("wanderbooks server: an access record couldn't be written: {e}"); Err(()) diff --git a/crates/ledger-mcp/src/admin.rs b/crates/ledger-mcp/src/admin.rs index 696db438..f5656c54 100644 --- a/crates/ledger-mcp/src/admin.rs +++ b/crates/ledger-mcp/src/admin.rs @@ -8,7 +8,8 @@ //! the data root itself: the server, its sole writer, does it. //! SOURCE: plan/served.md 3.1 (the CLI "talks to run/admin.sock ... it can //! create or adopt books"), 5.5 (adoption), 3.9 (protocol versions -//! N and N-1). +//! N and N-1); plan/p15-app-and-relay.md 3.1 (open and close one +//! book at run time; who is connected), D-77, D-78. //! INVARIANTS: //! 1. One request per connection, one JSON line each way, at most //! MAX_LINE bytes; anything else is refused with a plain reason. @@ -30,6 +31,19 @@ //! 7. A format upgrade is asked with the owner passphrase, which the //! server checks before anything is done (plan 3.9, D-39); no answer //! carries it, and Debug never shows it. +//! 8. Opening and closing ONE book (`open_book`, `close_book`) are +//! 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. 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 +//! running, and its last call. A session that ended is not listed. //! ``` use serde::{Deserialize, Serialize}; @@ -174,6 +188,22 @@ pub enum Request { /// The attachment to read. attachment_id: u64, }, + /// Open one book that is not open (INVARIANT 8): checked and verified + /// exactly as at the server's start. + OpenBook { + /// The books. + id: String, + }, + /// Close one book while the server runs (INVARIANT 8): new calls on it + /// are refused from the moment this begins, the calls running on it + /// finish, its sessions end, and it is let go of as at the server's + /// close (a last backup, its writer lock released). + CloseBook { + /// The books. + id: String, + }, + /// Who is connected to each open book (INVARIANT 9). + Sessions, /// End a token. TokenRevoke { /// Its books. @@ -298,6 +328,11 @@ pub struct BookStatus { pub id: String, /// Whether it is open and served. pub open: bool, + /// Whether it was closed (at the server's start, or by `close_book`): + /// not open, and no problem. A book that failed to open is not closed: + /// it has a `problem`. + #[serde(default)] + pub closed: bool, /// Why it couldn't be opened, if it couldn't. #[serde(default, skip_serializing_if = "Option::is_none")] pub problem: Option, @@ -314,6 +349,99 @@ pub struct BookStatus { pub other_databases: Vec, } +/// What `open_book` came to. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum OpenOutcome { + /// It was closed (or had failed to open) and is open now. + Opened, + /// It was open already: nothing was done. + AlreadyOpen, + /// There are no such books in the data root. + NoSuchBook, + /// It could not be opened, and why (it stays listed, with this + /// `problem`). + CouldNotOpen(String), +} + +/// What `close_book` came to. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +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, + /// There are no such books in the data root. + NoSuchBook, +} + +/// What an agent said about itself (`books.start`'s `agent`): asserted, +/// never checked. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct SessionAgent { + /// The model's name. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub model: Option, + /// The reasoning effort it ran at. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reasoning_effort: Option, + /// The program driving it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub harness: Option, +} + +/// A session's last call. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct LastCall { + /// The tool (or the resource's address). + pub tool: String, + /// "ok", "error", or "refused: CODE". + pub outcome: String, + /// When it finished (UTC, RFC 3339). + pub at: String, +} + +/// One live MCP session (INVARIANT 9). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct SessionInfo { + /// The NAME of the token it was opened with: never the token. + pub token: String, + /// The client program's name, as it said at `initialize`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_name: Option, + /// Its version. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_version: Option, + /// What the agent said about itself, if it has. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub agent: Option, + /// When it connected (UTC, RFC 3339). + pub connected_at: String, + /// Calls of it running now. + pub running: u32, + /// The last call it made, if it has made one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last: Option, +} + +/// An open book's live sessions. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct BookSessions { + /// The books. + pub book: String, + /// Its live sessions, the longest connected first. + pub sessions: Vec, +} + /// A setting an adoption would move in. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct SettingChange { @@ -486,6 +614,22 @@ pub enum Response { }, /// A format upgrade made (or none needed). FormatUpgraded(FormatUpgraded), + /// What `open_book` came to. + OpenBook { + /// The books. + id: String, + /// What happened. + outcome: OpenOutcome, + }, + /// What `close_book` came to. + CloseBook { + /// The books. + id: String, + /// What happened. + outcome: CloseOutcome, + }, + /// Who is connected, for each open book (INVARIANT 9). + Sessions(Vec), /// An attachment's text read and journaled (plan P6 step 2). Extracted { /// The attachment. @@ -536,7 +680,10 @@ pub fn call_within( let not_sent = |why: String| CallError::NotSent(why); // A list changes nothing: its only question is whether it answered. let look = match request { - Request::List | Request::TokenList | Request::TokenCheck { .. } => None, + Request::List | Request::TokenList | Request::TokenCheck { .. } | Request::Sessions => None, + Request::OpenBook { .. } | Request::CloseBook { .. } => { + Some("`wanderbooks books list` says whether the books are open") + } Request::Create { .. } | Request::Adopt { .. } | Request::Restore { .. } => { Some("`wanderbooks books list` shows the books there are") } @@ -699,6 +846,7 @@ mod tests { for r in [ Response::Books(vec![ BookStatus { + closed: false, id: "acme".into(), open: false, problem: Some("damaged".into()), @@ -707,6 +855,7 @@ mod tests { other_databases: Vec::new(), }, BookStatus { + closed: false, id: "beta".into(), open: true, problem: None, diff --git a/crates/ledger-mcp/src/backup.rs b/crates/ledger-mcp/src/backup.rs index 899b71a7..fa529c03 100644 --- a/crates/ledger-mcp/src/backup.rs +++ b/crates/ledger-mcp/src/backup.rs @@ -48,16 +48,96 @@ //! 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. +//! 11. A close is not held by a step it doesn't wait for. When a close +//! begins (`hurry`, before its last backup), these stop at their next +//! look: a drill, a format upgrade that has not yet reached its final +//! look, and a backup a call or a timer asked for (`run_with` for any +//! `why` but `close`), looking between git commands and phases, once +//! per journal line, file or 64 KiB chunk (ledger_store::backup +//! INVARIANT 6), and between targets. A drill's scratch clone is +//! removed and nothing is said of its target (neither a pass nor a +//! failure: it is due again when the books next open). A run stopped +//! this way records `stopped` (what it was doing: `commit` or `push`) +//! and no result of its own for the step it didn't finish: a commit it +//! had made stands in the archive and is recorded as made, a target it +//! hadn't pushed to is said nothing of, and its caller is told it was +//! stopped because the books are closing (tools/backup.rs, which marks +//! the call's access record `stopped_by_close`). The one thing a stop is +//! a failure for is a lock git left in the owner's folder (INVARIANT 12). +//! An upgrade is reported not done, the books unchanged, and its backup +//! (a commit it made on the way) recorded, if the close's stop reaches +//! it before its final look, which is made once everything it needs is +//! proven and just before the `journal.format_set` line is appended: a +//! stop is honoured up to that look. One that arrives between it and the +//! append does not undo the upgrade: the line is appended, the database's +//! row is written and the upgrade is recorded as made (safe: the books +//! are in this version's format and proven backed up, and the close that +//! asked for the stop is waiting for the books lock). The last backup of +//! the close, and the stop `shut` makes of what is left of it, are not +//! hurried: only `shut` stops them. The close's whole bound is the sum +//! written in the books server's INVARIANT 10 (local.rs). +//! 12. A lock file a stopped git left is dealt with by the step that +//! stopped it (ledger_store::backup INVARIANT 5) and recorded: a +//! record `lock_removed` (the archive's own, made by the git just +//! stopped) or `lock_left`, with `repo` (`archive`, `folder` or +//! `repository`), `lock` (a path in that repository), `why`, and for a +//! lock left in the owner's folder, `path`, its whole path. Git is sent +//! SIGTERM first and removes its own locks, so these records are the +//! rare case. A lock left in the owner's folder is never removed by +//! this program: it marks that target's backup failed, in a `push` +//! record whose error names the files and says to remove them only when +//! nothing else is using the backup folder; that error is the target's +//! `last_error` in `books.backup` and in the server's backup status, and +//! what a close that couldn't finish its last backup says. (A run whose +//! future was dropped at its bound has that record written by `shut`.) +//! The archive's locks found when the books open are dealt with the +//! same way (the store is open, and its lock is ours): only those older +//! than ten minutes are removed. A close is not answered before these +//! are recorded, the backup record being closed after them. //! ``` use crate::server::SharedStore; -use ledger_store::backup::{self, BackupError, Git, Target}; +use ledger_store::backup::{self, BackupError, Git, LockNotes, Target}; use ledger_store::chain::ChainLog; use serde::Serialize; use serde_json::{Map, Value, json}; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, 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. @@ -71,6 +151,9 @@ pub const RETRY_AFTER: std::time::Duration = std::time::Duration::from_secs(15 * /// The most of an error kept. const ERROR_MAX: usize = 500; +/// The test knob that holds a stoppable call as it begins ([`Backups::set_hold`]). +type CallHold = Arc; + /// A book's backups. pub struct Backups { book: String, @@ -79,6 +162,30 @@ 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, + /// Set when a close begins, before its last backup (INVARIANT 11): the + /// steps a close doesn't wait for (a drill, a format upgrade not yet + /// journaled, a backup a call or a timer asked for) stop, and `shut` + /// sets it too. It is the book's store's flag (`SharedStore::hurry`), so + /// the book's calls that can run long see it too. The close's own last + /// backup is stopped by `shut` alone, so it can run. + hurry: Arc, + /// The lock files a stopped git left, as they were dealt with + /// (ledger_store::backup INVARIANT 5), until they are recorded. + locks: LockNotes, + /// A test knob (`--slow-steps`): how long a drill or a format upgrade + /// waits, in milliseconds, at each phase, giving up when hurried. + slow_ms: AtomicU64, + /// Phases that began their wait (the test knob), for a test to see + /// that a step is inside one. + paused: Arc, + /// A test knob (`--timer-hold`): told the name of a call that can be + /// stopped by a close as it begins (`books.verify`, ...); it may wait, + /// and gives up when the close begins (`hurry`). Nothing without it. + hold: Mutex>, } /// What a format upgrade did ([`Backups::upgrade_format`]). @@ -250,16 +357,31 @@ impl Backups { } Err(e) => return Err(format!("its backup record can't be used: {e}")), }; + let hurry = store.hurry_flag(); let me = Self { book: book.to_string(), dir: dir.to_path_buf(), store, log: Mutex::new(log), running: tokio::sync::Mutex::new(()), + shut: Arc::default(), + busy: Arc::default(), + hurry, + locks: LockNotes::default(), + slow_ms: AtomicU64::new(0), + paused: Arc::default(), + hold: Mutex::new(None), }; for fields in carried { me.record(fields); } + // The store is open, so its lock is ours: no other wanderbooks + // process runs git on this archive, and none of this process's does + // yet. A lock in it older than ten minutes is a dead git's; a + // younger one is left (store INVARIANT 5a). + for note in backup::clear_archive_locks(dir) { + me.record_lock(¬e); + } // Books just restored: whose they were (INVARIANTS 6, 7). let marker = ledger_store::ops::ops_dir(dir).join(ledger_store::root::RESTORED_FROM); if let Ok(origin) = std::fs::read_to_string(&marker) { @@ -284,11 +406,182 @@ 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`: the close's own last backup (INVARIANT 10). + fn git(&self) -> Result { + Ok(Git::find()? + .with_cancel(self.shut.clone()) + .with_lock_notes(self.locks.clone())) + } + + /// git for a backup a call or a timer asked for: stopped as soon as a + /// close begins (INVARIANT 11), so it can't hold the close. + fn git_for(&self, why: &str) -> Result { + if why == "close" { + self.git() + } else { + Ok(Git::find()? + .with_cancel(self.hurry.clone()) + .with_lock_notes(self.locks.clone())) + } + } + + /// git for a step a close hurries (a drill, a format upgrade): stopped + /// as soon as the close begins (INVARIANT 11). + fn hurried_git(&self) -> Result { + let git = Git::find()? + .with_cancel(self.hurry.clone()) + .with_lock_notes(self.locks.clone()); + let ms = self.slow_ms.load(Ordering::SeqCst); + if ms == 0 { + return Ok(git); + } + let (hurry, paused) = (self.hurry.clone(), self.paused.clone()); + Ok(git.with_phase_watch(Arc::new(move |phase: &str| { + // From the second phase on (the first is the clone, before + // there is anything of the step's own to see). + if phase == "clone" { + return; + } + paused.fetch_add(1, Ordering::SeqCst); + let by = std::time::Instant::now() + std::time::Duration::from_millis(ms); + while std::time::Instant::now() < by && !hurry.load(Ordering::SeqCst) { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + }))) + } + + /// Make each phase of a drill or format upgrade wait `by` (a test + /// knob: a book large enough for these to take long). + pub(crate) fn slow_steps(&self, by: std::time::Duration) { + self.slow_ms.store(by.as_millis() as u64, Ordering::SeqCst); + } + + /// Install the test knob that holds a stoppable call as it begins. + pub(crate) fn set_hold(&self, hold: CallHold) { + *self.hold.lock().unwrap_or_else(|e| e.into_inner()) = Some(hold); + } + + /// A call that a close can stop has begun (the test knob's seam). + pub(crate) fn hold(&self, call: &str) { + let hold = self.hold.lock().unwrap_or_else(|e| e.into_inner()).clone(); + if let Some(hold) = hold { + hold(call); + } + } + + /// How many waits of the test knob have begun. + #[cfg(test)] + pub(crate) fn pauses_begun(&self) -> usize { + self.paused.load(Ordering::SeqCst) + } + + /// A close begins (INVARIANT 11): the steps it doesn't wait for stop at + /// their next look. The close's last backup, and what `shut` stops, are + /// not affected until `shut`. + pub fn hurry(&self) { + self.hurry.store(true, Ordering::SeqCst); + } + + fn hurried(&self) -> bool { + self.hurry.load(Ordering::SeqCst) + } + + /// A lock a stopped git left, as it was dealt with: a record of the + /// backup (INVARIANT 12). + fn record_lock(&self, note: &backup::LockNote) { + let mut fields = json!({ + "kind": if note.removed { "lock_removed" } else { "lock_left" }, + "repo": note.repo, "lock": note.lock, "why": note.why, + }); + // A lock left in the owner's folder is named by its whole path. + if let (Some(path), Value::Object(map)) = (¬e.path, &mut fields) { + map.insert("path".into(), json!(path)); + } + self.record(fields); + } + + /// Record the locks dealt with since the last look; the notes. + fn note_locks(&self) -> Vec { + let notes = self.locks.take(); + for note in ¬es { + self.record_lock(note); + } + notes + } + + /// 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) -> Vec { + self.shut.store(true, Ordering::SeqCst); + self.hurry.store(true, Ordering::SeqCst); + // The run or drill holding the books' turn ends (its git was just + // stopped), and none begins after. + let _turn = self.running.lock().await; + loop { + let ended = self.busy.ended.notified(); + if self.busy.steps.load(Ordering::SeqCst) == 0 { + break; + } + ended.await; + } + let notes = self.note_locks(); + // A run whose future was dropped at its bound (a close's last + // backup) never recorded its push: a lock its stopped git left in the + // owner's folder is that target's failure all the same, named, in the + // standing the owner reads (ledger_store::backup INVARIANT 5b). Locks + // a run took in hand itself were recorded by it, and aren't here. + let left: Vec<&backup::LockNote> = notes + .iter() + .filter(|n| !n.removed && n.path.is_some()) + .collect(); + let mut said = Vec::new(); + if !left.is_empty() { + for n in self.named().await { + let paths: Vec<&str> = left + .iter() + .filter(|l| l.repo == n.target.kind()) + .filter_map(|l| l.path.as_deref()) + .collect(); + if !paths.is_empty() { + let error = BackupError::LockLeft(paths.join(", ")).to_string(); + self.record( + json!({"kind": "push", "why": "close", "target": n.target.kind(), + "at": n.at, "key": n.key, "ok": false, "error": error}), + ); + said.push(error); + } + } + } + self.log.lock().unwrap_or_else(|e| e.into_inner()).close(); + said + } + fn records(&self) -> Vec> { ledger_store::chain::read( &ledger_store::ops::ops_dir(&self.dir).join(LOG_FILE), @@ -328,12 +621,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(); @@ -354,12 +641,29 @@ impl Backups { /// says it is a new disk). pub async fn run_with(&self, why: &str, new_disk: bool) -> Result { 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()); + } + // A run a call or a timer asked for is stopped by a close + // (INVARIANT 11); the close's own last backup is not. + let stoppable = why != "close"; + if stoppable && self.hurried() { + return Err(self.stopped_words(None)); + } 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_for(why); 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. @@ -375,12 +679,26 @@ impl Backups { }) .await .unwrap_or(Err(BackupError::Damaged("the backup stopped".into()))); + let _ = self.note_locks(); let (made, named, head) = match made { Ok(m) => m, + // Stopped by a close: neither a success nor a failure of the + // backup, so nothing is said of any target (INVARIANT 11); what + // was committed before it stands in the archive, and the close + // makes its own last backup. + Err(BackupError::Cancelled(_)) if stoppable => { + self.record(json!({"kind": "stopped", "why": why, "during": "commit"})); + return Err(self.stopped_words(None)); + } Err(e) => { + let lock_left = matches!(e, BackupError::LockLeft(_)); let e = hide(&e.to_string(), &self.dir); self.record(json!({"kind": "commit", "why": why, "ok": false, "error": e})); - return Err(e); + return Err(if stoppable && self.hurried() && lock_left { + self.stopped_words(Some(&e)) + } else { + e + }); } }; if let Some(m) = &made { @@ -398,30 +716,62 @@ impl Backups { { continue; } + if stoppable && self.hurried() { + self.record(json!({"kind": "stopped", "why": why, "during": "push"})); + return Err(self.stopped_words(None)); + } // 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_for(why); 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()))); + let _ = self.note_locks(); match pushed { Ok(commit) => self.record( json!({"kind": "push", "why": why, "target": n.target.kind(), "at": n.at, "key": n.key, "ok": true, "commit": commit, "head": {"seq": head.0, "hash": head.1}}), ), - Err(e) => self.record( - json!({"kind": "push", "why": why, "target": n.target.kind(), - "at": n.at, "key": n.key, "ok": false, "error": e.to_string()}), - ), + // Stopped by a close: not a failure of the target, and not + // a success: said once, of the run (INVARIANT 11). + Err(BackupError::Cancelled(_)) if stoppable => { + self.record(json!({"kind": "stopped", "why": why, "during": "push", + "target": n.target.kind(), "key": n.key})); + return Err(self.stopped_words(None)); + } + Err(e) => { + let lock_left = matches!(e, BackupError::LockLeft(_)); + self.record( + json!({"kind": "push", "why": why, "target": n.target.kind(), + "at": n.at, "key": n.key, "ok": false, "error": e.to_string()}), + ); + // A stop that left a lock is a failure the owner must + // hear of, and the call is told both. + if stoppable && self.hurried() && lock_left { + return Err(self.stopped_words(Some(&hide(&e.to_string(), &self.dir)))); + } + } } } Ok(self.status().await) } + /// What a run a close stopped answers: that it was stopped because the + /// books are closing (the call's access record says so), and, if it left + /// a lock in the owner's folder, that too. + fn stopped_words(&self, also: Option<&str>) -> String { + match also { + None => crate::server::STOPPED_BY_CLOSE_WORDS.to_string(), + Some(more) => format!("{} Also: {more}", crate::server::STOPPED_BY_CLOSE_WORDS), + } + } + /// The format upgrade, after a verified local backup with the keys /// (plan/served.md 3.9, D-39; INVARIANT 9). The caller has the owner's /// go-ahead (the passphrase, checked by the server). @@ -437,8 +787,16 @@ 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 git_for_upgrade = self.hurried_git(); + let cancel = self.hurry.clone(); let done = tokio::task::spawn_blocking(move || { + let _step = step; // Books that wait for nothing are left as they are: not even // their archive is made or staged (asked again under the lock // below; only an upgrade moves the format, one at a time). @@ -454,7 +812,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_for_upgrade; if let Ok(git) = &git { let _ = backup::stage_blobs(git, &dir); } @@ -483,6 +841,16 @@ impl Backups { }) .map_err(|e| UpgradeFailed::proof(made.clone(), e))?; let commit = proven.commit; + // The last look for a close (INVARIANT 11): once the + // `journal.format_set` line is appended the upgrade + // finishes, which is quick; before it, it is stopped, + // the books unchanged. + if cancel.load(Ordering::SeqCst) { + return Err(UpgradeFailed { + made: made.clone(), + why: "the books are closing: nothing was upgraded".into(), + }); + } let upgrade = match s.upgrade_format() { Ok(upgrade) => upgrade, // Journaled, and what follows the line failed (its @@ -514,6 +882,7 @@ impl Backups { }) .await .unwrap_or_else(|_| Err(UpgradeFailed::stopped("the upgrade stopped".into()))); + let _ = self.note_locks(); match done { Ok(u) => { if let (Some(b), Some(up)) = (&u.backup, &u.upgrade) { @@ -547,28 +916,42 @@ 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.is_shut() || self.store.is_stopped() { + return; + } let records = self.records(); let now = chrono::Utc::now(); for n in self.named().await { if paused(&n.key, &records) || !drill_due(&n.key, &records, now) { continue; } + if self.hurried() { + return; + } + let Ok(step) = self.begin() else { + return; + }; + let git = self.hurried_git(); let (dir, book, t) = (self.dir.clone(), self.book.clone(), n.target.clone()); let drilled = tokio::task::spawn_blocking(move || { + let _step = step; 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, @@ -579,7 +962,12 @@ impl Backups { }) .await .unwrap_or(Err(BackupError::Damaged("the drill stopped".into()))); + let _ = self.note_locks(); match drilled { + // Stopped by a close (INVARIANT 11): neither a pass nor a + // failure, so nothing is said of the target; the drill is + // due again when the books next open. + Err(BackupError::Cancelled(_)) => {} Ok(head) => { self.record(json!({"kind": "drill", "target": n.target.kind(), "at": n.at, "key": n.key, "ok": true, "head": {"seq": head.0, "hash": head.1}})) diff --git a/crates/ledger-mcp/src/lib.rs b/crates/ledger-mcp/src/lib.rs index 42f92784..a12ee161 100644 --- a/crates/ledger-mcp/src/lib.rs +++ b/crates/ledger-mcp/src/lib.rs @@ -15,6 +15,7 @@ pub mod opening; mod policy; pub mod scopes; mod server; +mod sessions; mod settings; mod tin_files; mod types; diff --git a/crates/ledger-mcp/src/local.rs b/crates/ledger-mcp/src/local.rs index 7200c340..d767ab6f 100644 --- a/crates/ledger-mcp/src/local.rs +++ b/crates/ledger-mcp/src/local.rs @@ -1,5 +1,7 @@ -//! `wanderbooks server`: every book in the data root, served on local -//! sockets (plan 3.1, 3.9). The host starts it; nothing else should. +//! `wanderbooks server`: the books of the data root, served on local +//! sockets (plan 3.1, 3.9), every one open at the start unless told +//! otherwise, and any one opened or closed while it runs (plan/p15-app-and-relay.md 3.1). +//! The host starts it; nothing else should. //! //! ```text //! GOAL: one process, the books' sole writer, serves every book in the @@ -11,7 +13,10 @@ //! layout, run/books.lock), 3.9 (local channels, peer checks, //! closing: "no new requests, the one in progress finishes, every //! writer lock is released"), D-21 and D-23 (no service: the host -//! starts and stops this process). +//! starts and stops this process); plan/p15-app-and-relay.md 3.1 +//! (open and close one book while the server runs; who is +//! connected), D-77 (the app is the host: a company is reachable +//! exactly while the app has it open), D-78 (one tab per company). //! INVARIANTS: //! 1. One server per root: it holds `run/server.lock` from before it //! opens anything until it exits; a second server waits for the lock @@ -20,10 +25,12 @@ //! replaced only under that lock. //! 2. Only this account: a connection to either socket whose peer is //! another user ID is dropped before a byte is read. -//! 3. Every book is opened and verified (rebuilding a drifted database) -//! before the server says it is ready; one that won't open is -//! reported with why, on its route and in the list, and the others -//! are served. +//! 3. Every book chosen to be open (`--open`: all unless said) is opened +//! and verified (rebuilding a drifted database) before the server +//! says it is ready; one that won't open is reported with why, on its +//! route and in the list, and the others are served. The books not +//! chosen are closed (listed so), and open when asked (INVARIANT 10), +//! by the same checks. //! 4. Each book has one store, shared by every session: one writer. //! 5. The ready line (stdout, once) comes only after both sockets are //! bound and every book has been tried. @@ -35,9 +42,24 @@ //! 8. An MCP request reaches a book only with a bearer token that is //! live for that book (auth/principals.jsonl; refused 401 without //! one, 403 with another book's), and a session only with the token -//! that opened it (403). A request refused at the door is recorded -//! in that book's access log; the token rides with the request to -//! the book's tools, which check its scopes (access.rs). A session is +//! that opened it (403). A request that has entered an open book's +//! door and is then refused (no token, another book's, a revoked +//! one, the server closing), and a request cut by a close (INVARIANT +//! 15), are recorded in that book's access log. A request for a book +//! that is listed closed or failed, or that doesn't exist, and one +//! that loses the race at the door (the door shut by a close of the +//! book, a restore over it, or the server's close, between the lookup +//! and the entry), is refused before it is dispatched and is NOT +//! recorded: a closed book's log isn't written (it isn't open), and a +//! shut door belongs to a close that is waiting for the log. None of +//! these ran, and an unrecorded refusal can never be a call that +//! ran: the only way to a book's tools is through its door; a request +//! is counted inside it before anything of the book is touched, and +//! a call that ran is recorded before its answer goes (INVARIANT 14; +//! if it can't be, the server stops taking requests); a request +//! refused outside the door never reached the tools. The token rides +//! with the request to the book's tools, which check its scopes +//! (access.rs). A session is //! bound to its token when opened, and forgotten when it ends, is //! found gone, or its token is revoked or replaced; past MAX_SESSIONS //! bindings a new session is refused (an initialize), never a binding @@ -50,13 +72,314 @@ //! request: an upload only from the token that began it, a download //! only with books:read, an export only to the token it was made for //! (whose tool passed its own scope check; no other is asked). Each, -//! refused at the door or not, is recorded in the book's access log -//! as `upload`, `download` or `export` with its id, and the +//! once inside the door, ran or was refused there, is recorded in the +//! book's access log as `upload`, `download` or `export` with its id +//! (one refused outside the door is not recorded, and did not run: +//! INVARIANT 8), and the //! bytes (kept, or read) and their record are one task that runs to //! its end if the client hangs up (a process killed in that task //! excepted); bytes whose record can't be written aren't kept, and //! the books stop. Lapsed uploads and exports are swept every //! SWEEP_EVERY. Nothing comes in or goes out once the books stopped. +//! 10. One book opens or closes while the server runs, by admin request, +//! one change to a book at a time (create, adopt and restore among +//! them): each book has its own turn (`Books::lives`), so a change to +//! one book waits for no other book's, and a close of one book is +//! never held up by, nor holds up, an open, a restore, an adoption or a +//! create of another. Open: +//! a closed (or failed) book of the root is opened and verified as at +//! the start. Close: from the moment it begins, a call on that book is +//! refused at its door, unrun, and not in its journal; a request not +//! yet whole when the grace runs out is cut (INVARIANT 15); a call +//! already running on it, on any route, either finishes (an ordinary +//! call: nothing is killed, nothing is half-done) or, if it is one of +//! the stoppable calls below, is stopped at its next look; 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), its door shut and the book listed closed from the start: a +//! call that comes while the restore runs is told the books aren't +//! open (503, INVARIANT 11), never that there are no such books. +//! +//! What can run long, and what stops it. A close calls `hurry` at its +//! start, before it waits for anything. The calls and jobs that can do +//! long I/O or loop over a book's whole journal or files are exactly +//! these, and each is stoppable: +//! - on the book: `books.back_up_now`, and a backup a timer asked for +//! (git is sent SIGTERM and killed only after TERM_GRACE: ledger_ +//! store backup INVARIANT 5; between targets the flag is looked at +//! too); `books.verify` (once per journal line replayed and per +//! stored file hashed); `books.export_cpa_package` (before it +//! builds, and once per stored file it reads, unless it has +//! journaled a decision: below); a drill; and a +//! format upgrade not yet journaled. A call stopped this way +//! answers its caller that it was stopped because the books are +//! closing, its access record says `refused: stopped_by_close`, and +//! nothing it was doing is recorded as done: a stopped backup +//! records `stopped` and no push or commit outcome for the step it +//! didn't finish (a commit made before it stands in the archive, and +//! is recorded as made); a stopped verification changed nothing. +//! Two points of no return: `books.verify` heals a drifted database +//! by rebuilding it from the journal, begun only if no stop was +//! asked before it (the look comes before the database is copied +//! aside, so a stopped heal leaves no `.mismatch` copy and no +//! rebuild), and then run to its end (stopped half way it would +//! leave the live ledger part replayed; it is the fourth named +//! exception below, and only after a drift); and a format upgrade: a +//! stop is honoured up to its final look (made once the archive is +//! proven, just before the `journal.format_set` line is appended); +//! one that arrives after that look still upgrades and records +//! success (safe: the books are in this version's format, proven +//! backed up first), and finishes (a line and a database row). +//! And a third: `books.export_cpa_package` that is exporting with +//! a reason (without an audit, with open drafts) journals that +//! decision before it builds, because the package counts it (its +//! README and every footer carry the journal's event count at the +//! build). The close is looked for once, immediately before the first +//! decision is journaled (a stop then journals nothing); from there +//! to the hand-over nothing looks at it, so a decision on record is +//! a package handed over (tools/reports.rs INVARIANT 4). Its build +//! then runs to its end: it is one of the named exceptions below. +//! - on the admin socket: restore and its preview, adopt and its +//! preview, create, and open. A stop is scoped to what it concerns. +//! A job that changes books holds the turn of the id it works on +//! (an open, a close, a create, an adoption, a restore: one at a +//! time per id), and listens to the stop of THAT id, which a close +//! of the id raises before it waits for the turn, and to the +//! server's (the id's stop is raised by the server's close too): +//! so a close of X stops an open of X, an adoption or a create +//! making X, and a restore of X (over it, or making it), before +//! their point of no return, and never waits behind one. A +//! PREVIEW (of a restore, of an adoption) changes nothing, and +//! holds no book's turn at all: a close never waits for one, +//! however long its clone or its queue for `books.lock`; only the +//! server's close stops it. No close of any other book stops, fails, +//! refuses or delays an open, a close or a job of X, nor a job +//! queued for its turn at making books (`books.lock` in the root, +//! one at a time across processes: a deliberate rule, ledger_store:: +//! root INVARIANT 5, that a queued job leaves at once when it is +//! asked to stop). Only the server's own close stops every job +//! (`Books::stop_every_job`). A job for a book whose close is under +//! way waits for that book's turn, so for the close to end, and is +//! then asked as any other. Each is stopped, before its +//! point of no return, at its next look (a phase, a stored file, a +//! journal line, a git command): what it wrote is removed (a clone, +//! a staging folder, and the lock file an adoption made in the +//! source folder), and the root is byte for byte as it was. The +//! point of no return of restore and adopt is the rename that puts +//! the books in place; after it they finish, which is a rename or +//! two and the sync of two folders (a restore over books moves them +//! to `legacy/` and renames the copy in, both within the root); then +//! the book is opened, which is itself stopped by the server's close +//! and by a close of its id (the same stop the job held), left closed +//! (its answer says so). Create's is the making of its folder, after which +//! it makes one empty book. Open stops at every look of its +//! verification (the book is left closed, intact), but for one +//! place: once it has begun to heal a drifted database it finishes +//! the heal (the fourth named exception below); a stop asked before +//! the heal begins leaves no copy of the database either. +//! Every other call does work bounded by the size of one request: its +//! arguments, one entry, one stored file (at most MAX_UPLOAD) read, +//! hashed or extracted (local CPU, no wait on a client, a disk of +//! another's or the network). Three calls, and one step inside two +//! stoppable ones, are neither stoppable nor bounded by one request's +//! size, and they are the named exceptions to the close's bound below, +//! each with its worst case, which a close that meets it waits for in +//! full (nothing enforces a bound on them: that is a defect to be +//! closed, not a promise kept): +//! - `books.import_bank_csv`: a file of up to MAX_UPLOAD is rehearsed +//! whole, then written row by row, each row journaled, and a close +//! doesn't stop it. Worst case: a full import of the largest file +//! accepted. +//! - a report or export over the whole journal (`books.verify` apart, +//! which is stoppable): CPU on the ledger already in memory, with no +//! look at a stop. Worst case: one report over the whole book. +//! - `books.export_cpa_package` once it has journaled a decision (above). +//! Worst case: one build of the package over the whole book (every +//! stored file it holds read once). +//! - the heal of a drifted database, once begun, in `books.verify` and +//! in an open (ledger_store `verify_and_heal`, cancel INVARIANT 4): +//! the rebuild and its verification are shielded from the stop, and +//! met only after a drift. Worst case: the copy of the database, +//! and about six passes over the journal (three by the rebuild: +//! read and chain-checked, applied to the database, replayed; +//! three by the verification: read and chain-checked, replayed, +//! applied to a fresh projection), and each stored file read and +//! hashed once. +//! The close is bounded, from its start, by the sum of these named +//! terms, each enforced by code, and nothing else: +//! a. T_calls: the longest ordinary call already running with its +//! whole body (bounded by one request, above; none is cut or +//! killed; nothing a client does lengthens it), or, for a +//! stoppable call, T_stop, or, for a call or step of the four named +//! exceptions above, its worst case (the bound is these terms, +//! with that term unbounded by code while one of them runs); +//! b. ANSWER_GRACE for the answers on their way out, counted from +//! when the door is empty (the cut of a body not yet whole is at +//! ANSWER_GRACE from the START of the close, inside (a): a +//! stalled client adds nothing); +//! c. T_stop: the longest between two looks of what is stopped, one +//! of: a git command's stop (SIGTERM and up to TERM_GRACE, 5 s; +//! then a kill and GROUP_GONE_WAIT, 2 s, and its pipes, 10 s at +//! most), one journal line, one stored file, one 64 KiB chunk, one +//! phase of a job; and the removal of what a stopped job or drill +//! wrote (its scratch clone or staging folder: a local deletion of +//! the job's own output, as long as that is large, waiting on no +//! one); +//! d. BACKUP_AT_CLOSE for the last backup; +//! e. T_stop again for what is left of that backup at its bound +//! (`Backups::shut`: git stopped, every step awaited); +//! f. closing the logs and letting go of the store (instant). +//! A drill (or a format upgrade) that took the backups' turn never +//! costs the last backup its time. +//! 11. A call for a book that exists but is closed is told apart from one +//! that does not exist, on the MCP, upload, download and export +//! routes: 503, `x-wanderbooks-refused: closed`, and the words `The +//! books "ID" aren't open: open them in Wanderbooks.` (the access log +//! of a closed book is not written: it is not open). +//! 12. A book's live MCP sessions are known: for each, its token's NAME +//! (never the token), the client's name and version, the agent's +//! 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. +//! 15. A request that has begun and never finishes arriving can't hold a +//! close: when the answer grace (counted from the start of the close, +//! or of the server's) has run out, every request inside the door +//! whose body has not yet been read to its end is cut. The line is +//! the body's end, and no later: a body read to its end is whole, +//! whatever the request does after (a call running, its answer being +//! sent), and is never cut; a body not yet read to its end, however +//! slowly or quickly it is coming, is cut at that moment. A cut +//! request's connection is closed (`Connection: close`, 503, +//! `x-wanderbooks-refused: cut_by_close`), what it had written is +//! removed (an upload's part file, by `receive` on its read error), +//! and its access record, written before its answer, says +//! `cut_by_close`. Nothing of an MCP call can have been journaled: +//! the service reads the whole body before it gives any message to a +//! session or a tool (rmcp `expect_json`, which answers a body that +//! fails with an error before anything else), and the handler checks +//! for the cut again before it binds a session. This holds for a +//! book's close, for a restore over an open book (both are +//! `Books::release`) and for the server's close, which is the same +//! path: at the start of the server's close (not after its admin +//! jobs, store closes or backups) every open book's door is shut and +//! its cut set for one grace from that moment, then every book still +//! open is released as a close of one book releases it, together +//! (so one book's slow backup holds no other's, each book's bound +//! being INVARIANT 10's), its gate, sessions, logs, uploads, exports, +//! backups and store all closed; only the HTTP side's end and the +//! linger (a request that set out before its client heard of the +//! close still meets a refusal, LINGER, 3 s at most) come after. A +//! request that arrives once the server is closing and finds a book's +//! door shut is refused as closing (503, `closing`), not recorded: +//! the door is shut (INVARIANT 11), as in a close of one book. +//! SCENARIOS: +//! 1. Two books open; one is closed while agents call both: the other +//! answers throughout, the closed one's calls are refused unrun +//! (never half-done), its journal holds exactly the calls that were +//! acknowledged; it is opened again and serves again. +//! 2. The server starts with `--open none`: every book is listed closed, +//! a call to one says it isn't open, a call to a name that isn't a +//! book says there is no such book; one is opened by request. +//! 3. A book is closed twice: the second answer is "was not open". A +//! name that is no book: "no such book". +//! 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. +//! 9. An upload stops sending half way, and another call's body stops +//! half way, and the book is closed: the close waits the grace, cuts +//! both (no part file, nothing journaled, the records say cut), and +//! answers closed. An upload still coming within the grace, and a +//! call running past it, are not cut; an upload that keeps coming, +//! steadily, past the grace is cut. +//! 10. A drill is slow (a large book): the book is closed, the drill is +//! stopped at its next look and its clone removed, the last backup is +//! made, and the close is answered within INVARIANT 10's bound. A +//! format upgrade not yet journaled is stopped the same way, the books +//! unchanged. +//! 11. A backup's git is stopped inside a commit or a push: it is sent +//! SIGTERM and removes its own locks (nothing is left, nothing is +//! recorded), the book opened again backs up at once. A git that can't +//! end on SIGTERM and has to be killed after TERM_GRACE leaves locks +//! that this process removes from the book's own archive only, and +//! leaves in the owner's backup folder, recorded with their whole path +//! and said in the close's answer and in the backup's status, until the +//! owner removes them. +//! 12. The server is closed (standard input ends) with an upload stalled +//! on one book and a call's body stalled on another: both are cut one +//! grace after the close began, the server exits 0 within its bound. +//! 13. A backup asked for (`books.back_up_now`) is running, git stalled, +//! and the book is closed: the call is answered, git still stalled, +//! that it was stopped because the books are closing; its record says +//! `refused: stopped_by_close`; the close is answered `closed`. +//! 14. A restore of a large backup over `beta` is running (an admin job) +//! when `beta` is closed: the restore is stopped, answers that it was +//! stopped because the books are closing, and the root is byte for byte +//! as it was; asked again it goes through. The same restore, with +//! another book (`acme`) closed instead, is not stopped. +//! 15. A restore over `beta`, a create of `epsilon` and an adoption of +//! `delta` are in flight (held inside a phase), and `acme`, whose close +//! is made slow, is closed and opened again over and over: all three +//! finish correctly, none is stopped, none is told of an error, an open +//! and a close of `cedar` during a close of `acme` are answered at once, +//! and the close of `acme` is not answered until its own backup is done. +//! 16. The server is closed with a restore, an adoption, a create and an +//! open in flight: each is stopped, and the root is as it was. +//! 17. An adoption of a folder that has no lock file is stopped, fails, or +//! panics: the folder is, name for name and byte for byte, as it was. +//! 18. A package exported with a reason is held as it begins and the book is +//! closed: stopped, no decision journaled. Held right after its decision +//! is journaled and the book closed: the package is made. //! ``` use crate::admin::{self, Request, Response}; @@ -77,6 +400,12 @@ use std::time::{Duration, Instant}; use tokio_util::sync::CancellationToken; use tokio_util::task::TaskTracker; +/// What a restore or adoption that a close stopped after its point of no +/// return says of the books it put in place (INVARIANT 10). +const STOPPED_AFTER_PLACED: &str = "they are in place, but were not opened: the books server is closing. Open them when it runs again"; +/// Why a book's opening was stopped (by a close, INVARIANT 10): the book is +/// intact and stays closed. +const OPEN_STOPPED: &str = "stopped because the books are closing: they were not opened"; /// The server's MCP socket, in the root's `run/`. pub const MCP_SOCKET: &str = "mcp.sock"; /// The server's admin socket, in the root's `run/`. @@ -114,8 +443,53 @@ 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, + /// A test knob (`--slow-steps`): each phase of a drill or format + /// upgrade waits this long, so these can be long (backup.rs). + slow_steps: Duration, + /// A test knob (`--timer-hold`): a timer that has taken a book's + /// handles waits, before it acts on them, while the file `timer-hold` + /// in the root's `run/` names it (`sweep`, `backup`, `drill`), saying + /// which timer it is in `run/timer-held` as it comes to wait (see + /// [`Books::timer_hold`]). + timer_hold: bool, +} + +impl Default for Timers { + 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, + slow_steps: Duration::ZERO, + timer_hold: false, + } + } +} + type Service = StreamableHttpService; +/// What a call is told for a book that exists but is closed (INVARIANT +/// 11): words an agent can relay to the person. +fn closed_words(book: &str) -> String { + format!("The books \"{book}\" aren't open: open them in Wanderbooks.") +} + /// A book the server holds. #[derive(Clone)] enum Book { @@ -141,19 +515,295 @@ enum Book { /// Its projection database's file, and other schemas' beside it, /// by name, as it opened (`wanderbooks doctor` says them). database: (String, Vec), + /// Its door: every request on it enters here, and a close shuts it + /// and waits for those inside (INVARIANT 10). + gate: Arc, + /// Ends its MCP sessions (a child of the server's own). + ended: CancellationToken, + /// Who is connected to it (sessions.rs, INVARIANT 12). + board: Arc, }, /// Not opened, with why (INVARIANT 3). Failed(String), + /// Not open, by choice: left closed at the start (`--open`), or closed + /// since (INVARIANT 10). Not a problem. + Closed, } impl Book { /// Why it isn't open, if it isn't. fn problem(&self) -> Option { match self { - Book::Open { .. } => None, + Book::Open { .. } | Book::Closed => None, 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, +} + +/// `wait`, or None once `hurry` (a second signal to close: stop waiting) +/// is cancelled; without a `hurry`, `wait` alone. +async fn unless_hurried( + hurry: Option<&CancellationToken>, + wait: impl std::future::Future, +) -> Option { + match hurry { + Some(hurry) => tokio::select! { + out = wait => Some(out), + () = hurry.cancelled() => None, + }, + None => Some(wait.await), + } +} + +/// One book's door (INVARIANT 10): requests are counted as they enter, and +/// once shut none enters. A close shuts it, then waits for the count to +/// reach zero: every request that got in has finished, its record written. +/// +/// Entering adds to the count before it looks at `shut`, and shutting sets +/// `shut` before it looks at the count (both sequentially consistent), so +/// a request either sees the door shut, or is counted where the close will +/// wait for it: never neither. +/// +/// An MCP request's answer may still be on its way after its handler is +/// done (the tool runs in the session's own task, its answer streamed back): +/// the handler takes an [`Answering`] before it leaves, which rides in the +/// answer's body until the body ends, so a close can wait for the answers +/// (as the server's own close does) before it ends the sessions. +#[derive(Default)] +pub(crate) struct Gate { + shut: std::sync::atomic::AtomicBool, + inside: AtomicUsize, + answering: AtomicUsize, + left: tokio::sync::Notify, + /// Cancelled when the close's grace has run out: a request inside + /// whose body hasn't finished arriving is cut (see [`Arrival`]). + cut: CancellationToken, +} + +/// Where a request's body is: still coming, whole, or cut by a close. +/// The body of a request inside a book's door is wrapped by +/// [`Inside::arriving`], which changes this state in one place only (its +/// own poll), so a body is never both whole and cut. +pub(crate) struct Arrival(std::sync::atomic::AtomicU8); + +const ARRIVING: u8 = 0; +const ARRIVED: u8 = 1; +const CUT: u8 = 2; + +impl Arrival { + /// Whether a close cut this request's body before it was whole. + fn was_cut(&self) -> bool { + self.0.load(Ordering::SeqCst) == CUT + } +} + +/// A request inside a book's door, counted until dropped. +struct Inside(Arc); + +impl Drop for Inside { + fn drop(&mut self) { + self.0.inside.fetch_sub(1, Ordering::SeqCst); + self.0.left.notify_waiters(); + } +} + +impl Inside { + /// An answer on its way out, for a request still inside: counted until + /// the answer is sent. + fn answering(&self) -> Answering { + self.0.answering.fetch_add(1, Ordering::SeqCst); + Answering(self.0.clone()) + } + + /// The request, its body watched: it is whole once the body's end has + /// been read (a request with no body is whole at once), and until + /// then a close whose grace ran out cuts it: the body fails, as a + /// connection that dropped would, and the returned [`Arrival`] says + /// so. A body already whole is never cut, whatever runs after it. + fn arriving(&self, request: axum::extract::Request) -> (axum::extract::Request, Arc) { + use axum::body::HttpBody as _; + use futures_util::StreamExt; + use std::task::Poll; + let arrival = Arc::new(Arrival(std::sync::atomic::AtomicU8::new(ARRIVING))); + let (parts, body) = request.into_parts(); + if body.is_end_stream() { + arrival.0.store(ARRIVED, Ordering::SeqCst); + return (axum::extract::Request::from_parts(parts, body), arrival); + } + let mut data = body.into_data_stream(); + let mut cut = Box::pin(self.0.cut.clone().cancelled_owned()); + let seen = arrival.clone(); + let stream = futures_util::stream::poll_fn(move |cx| { + match seen.0.load(Ordering::SeqCst) { + ARRIVED => return Poll::Ready(None), + CUT => return Poll::Ready(Some(Err(cut_error()))), + _ => {} + } + // Checked before the data: a body that keeps coming past the + // grace is cut too, not only one that stalled. + if cut.as_mut().poll(cx).is_ready() { + seen.0.store(CUT, Ordering::SeqCst); + return Poll::Ready(Some(Err(cut_error()))); + } + match data.poll_next_unpin(cx) { + Poll::Ready(None) => { + seen.0.store(ARRIVED, Ordering::SeqCst); + Poll::Ready(None) + } + Poll::Ready(Some(r)) => Poll::Ready(Some(r.map_err(std::io::Error::other))), + Poll::Pending => Poll::Pending, + } + }); + ( + axum::extract::Request::from_parts(parts, axum::body::Body::from_stream(stream)), + arrival, + ) + } +} + +fn cut_error() -> std::io::Error { + std::io::Error::new( + std::io::ErrorKind::ConnectionAborted, + "the request wasn't finished when the books closed", + ) +} + +/// An answer on its way out of a book's door (see [`Gate`]). +struct Answering(Arc); + +impl Drop for Answering { + fn drop(&mut self) { + self.0.answering.fetch_sub(1, Ordering::SeqCst); + self.0.left.notify_waiters(); + } +} + +impl Gate { + /// Let a request in, if the door is open. + fn enter(self: &Arc) -> Option { + self.inside.fetch_add(1, Ordering::SeqCst); + let inside = Inside(self.clone()); + (!self.shut.load(Ordering::SeqCst)).then_some(inside) + } + + /// Cut every request inside whose body isn't whole (see + /// [`Inside::arriving`]); the ones whose body is whole are left to + /// finish. + fn cut_unfinished(&self) { + self.cut.cancel(); + } + + /// Let no request in from now on. + fn shut(&self) { + self.shut.store(true, Ordering::SeqCst); + } + + /// Wait until every request inside has left. + async fn emptied(&self) { + loop { + let left = self.left.notified(); + if self.inside.load(Ordering::SeqCst) == 0 { + return; + } + left.await; + } + } + + /// Wait until every answer on its way out has been sent. Call after + /// [`Self::emptied`]: no request is inside to start another. + async fn answered(&self) { + loop { + let left = self.left.notified(); + if self.answering.load(Ordering::SeqCst) == 0 { + return; + } + left.await; + } + } +} + +/// A session bound to the token that opened it (INVARIANT 8). +struct Bound { + /// The token's id. + token: String, + /// The token's name (listed by `sessions`: never the token). + name: String, + /// The book it is a session of. + book: String, + /// When it connected (seconds since the epoch, UTC). + at: i64, +} + +/// Which books are open at the server's start (`--open`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum OpenAtStart { + /// Every book of the root (the default). + All, + /// Only these (none: an empty list). + Only(Vec), +} + +impl OpenAtStart { + /// `--open`'s value: `all`, `none`, or books' ids separated by commas. + pub fn parse(text: &str) -> Result { + match text.trim() { + "all" => Ok(Self::All), + "none" => Ok(Self::Only(Vec::new())), + list => list + .split(',') + .map(|id| { + BookId::parse(id.trim()) + .map(|id| id.to_string()) + .map_err(|e| format!("--open takes all, none, or books' ids: {e}")) + }) + .collect::, _>>() + .map(Self::Only), + } + } + + fn wants(&self, id: &BookId) -> bool { + match self { + Self::All => true, + Self::Only(ids) => ids.iter().any(|i| i == id.as_str()), + } + } } /// Every book the server holds, and what serving them needs. @@ -178,21 +828,220 @@ struct Books { principals: RwLock>, /// Which token opened each MCP session: a session is used only with /// the token that opened it (INVARIANT 8). - session_tokens: Mutex>, + session_tokens: Mutex>, /// How long the books stay unwritten before a backup is made /// (`--backup-quiet`, for tests; else BACKUP_QUIET). backup_quiet: Duration, /// How long after books are first seen open a drill is first looked /// for (`--drill-first`, for tests; else DRILL_FIRST). drill_first: Duration, - /// Held through a restore: one at a time. - restoring: Mutex<()>, + /// What each book's changes share: the lock they are made under, and + /// the stop a close of that book raises (INVARIANT 10). One book's + /// changes wait for one book's; no change to one book waits for, stops + /// or fails a change to another. + lives: Mutex>>, + /// Set for good when the server closes: the jobs that make a NEW book + /// (a create, an adoption, a restore that replaces nothing) look at it. + /// A close of one book never raises it: those jobs aren't work on that + /// book (INVARIANT 10). + server_stop: Arc, /// How these books are kept from agents (plan 3.8, P9a): what /// `books.start` reports (`--isolation`). isolation: Isolation, + /// The periods and bounds (tests shorten them). + timers: Timers, +} + +/// What the changes to ONE book share (`Books::lives`): the lock they are +/// made under, one at a time, and the stop a close of that book raises for +/// the jobs that work on it (INVARIANT 10). +struct Life { + /// Held through every change to this book (open, close, a restore that + /// replaces it; a create or an adoption making it). + lock: Mutex<()>, + /// Set while a close of this book is under way, and for good once the + /// server closes: the admin jobs working on this book (an open, a + /// restore over it) look at it and stop, before their point of no + /// return, leaving the books as they were. `closers` counts the closes + /// under way; the flag is clear when none is (and the server isn't + /// closing). Set and cleared under `closers`. + stop: Arc, + closers: Mutex, +} + +/// A close of a book under way (`Books::closing_one`). +struct CloseGuard { + life: Arc, + closing: CancellationToken, +} + +impl Drop for CloseGuard { + fn drop(&mut self) { + let mut closers = self.life.closers.lock().unwrap_or_else(|e| e.into_inner()); + *closers -= 1; + if *closers == 0 && !self.closing.is_cancelled() { + self.life + .stop + .store(false, std::sync::atomic::Ordering::SeqCst); + } + } } impl Books { + /// A server's books for `root`, none held yet. + fn new( + root: Root, + backup_quiet: Duration, + drill_first: Duration, + isolation: Isolation, + ) -> Self { + Self { + root, + held: RwLock::new(BTreeMap::new()), + sessions: CancellationToken::new(), + closing: CancellationToken::new(), + in_flight: AtomicUsize::new(0), + finished: tokio::sync::Notify::new(), + last_arrival: std::sync::atomic::AtomicU64::new(0), + started: Instant::now(), + principals: RwLock::new(Err(String::new())), + session_tokens: Mutex::new(BTreeMap::new()), + backup_quiet, + drill_first, + lives: Mutex::new(BTreeMap::new()), + server_stop: Arc::default(), + isolation, + timers: Timers::default(), + } + } + + /// These books, with these periods and bounds. + fn with_timers(mut self, timers: Timers) -> Self { + self.timers = timers; + self + } + + /// What the changes to the book `id` share: made once, kept while + /// anything holds it. A book first met after the server began closing + /// is born stopped. + fn life(&self, id: &BookId) -> Arc { + let mut lives = self.lives.lock().unwrap_or_else(|e| e.into_inner()); + // Forget the books nothing is changing or closing. + lives.retain(|_, life| Arc::strong_count(life) > 1); + lives + .entry(id.as_str().to_string()) + .or_insert_with(|| { + Arc::new(Life { + lock: Mutex::new(()), + stop: Arc::new(std::sync::atomic::AtomicBool::new( + self.closing.is_cancelled(), + )), + closers: Mutex::new(0), + }) + }) + .clone() + } + + /// A close of the book `life` belongs to begins: the admin jobs working + /// on THAT book that can run long stop (INVARIANT 10) until the returned + /// guard is dropped. Nothing else is stopped. + fn closing_one(&self, life: &Arc) -> CloseGuard { + let mut closers = life.closers.lock().unwrap_or_else(|e| e.into_inner()); + *closers += 1; + life.stop.store(true, std::sync::atomic::Ordering::SeqCst); + drop(closers); + CloseGuard { + life: life.clone(), + closing: self.closing.clone(), + } + } + + /// The server closes: every stop is raised, for good (INVARIANT 10). + /// `closing` is cancelled first, so a book first met from now is born + /// stopped, and a close of one book ending now clears nothing. + fn stop_every_job(&self) { + self.server_stop + .store(true, std::sync::atomic::Ordering::SeqCst); + let lives = self.lives.lock().unwrap_or_else(|e| e.into_inner()); + for life in lives.values() { + // Under the lock a close's end clears the flag under. + let _closers = life.closers.lock().unwrap_or_else(|e| e.into_inner()); + life.stop.store(true, std::sync::atomic::Ordering::SeqCst); + } + } + + /// What an admin job that can run long is asked as it goes whether to + /// stop (ledger_store::root `JobStop`): `flag` is the stop of the book + /// it works on, or the server's (`server_stop`) for a job that makes a + /// new book. With the test knob `--timer-hold` a job is held inside a + /// phase named `job:phase` (in `run/timer-hold`) until the name is gone + /// or a stop is asked. + fn job( + &self, + job: &'static str, + flag: &Arc, + ) -> ledger_store::root::JobStop { + let stop = ledger_store::root::JobStop::new(flag.clone()); + if !self.timers.timer_hold { + return stop; + } + let Ok(run) = self.root.run_dir() else { + return stop; + }; + let flag = flag.clone(); + stop.with_phase_watch(Arc::new(move |phase: &str| { + let name = format!("{job}:{phase}"); + { + use std::io::Write; + if let Ok(mut said) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(run.join("timer-held")) + { + let _ = writeln!(said, "{name}"); + } + } + let held = || { + std::fs::read_to_string(run.join("timer-hold")) + .is_ok_and(|names| names.split(',').any(|n| n.trim() == name)) + }; + while held() && !flag.load(std::sync::atomic::Ordering::SeqCst) { + std::thread::sleep(Duration::from_millis(10)); + } + })) + } + + /// The test knob `--timer-hold`: `timer` has taken the handles of a + /// book and is about to act on them. It says so (a line in + /// `run/timer-held`) and waits until `run/timer-hold` is gone, so a + /// test can close the book in between. Nothing without the knob. + async fn timer_hold(&self, timer: &str) { + if !self.timers.timer_hold { + return; + } + let Ok(run) = self.root.run_dir() else { + return; + }; + { + use std::io::Write; + if let Ok(mut said) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(run.join("timer-held")) + { + let _ = writeln!(said, "{timer}"); + } + } + // Held while the file names this timer (a list, comma-separated). + let held = || { + std::fs::read_to_string(run.join("timer-hold")) + .is_ok_and(|names| names.split(',').any(|n| n.trim() == timer)) + }; + while held() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + } + /// Take the root's path out of a message (INVARIANT 7). fn hide(&self, text: impl Into) -> String { let mut text = text.into(); @@ -232,7 +1081,7 @@ impl Books { self.session_tokens .lock() .unwrap_or_else(|e| e.into_inner()) - .retain(|_, owner| owner != token_id); + .retain(|_, bound| bound.token != token_id); } /// Read the principals from the root's `auth/`. @@ -269,6 +1118,18 @@ impl Books { } } + /// [`Self::open`] for an admin job that can be stopped: the store's + /// replay and verification look at the stop, and a book whose opening + /// was stopped is closed, not failed (it is intact: it opens when asked). + fn open_stoppable(&self, id: &BookId, stop: &ledger_store::root::JobStop) -> Book { + let _scope = ledger_store::cancel::scope(stop.flag()); + let book = self.open(id); + match &book { + Book::Failed(why) if why == OPEN_STOPPED => Book::Closed, + _ => book, + } + } + /// Open the book `id` from disk: served, or failed with why. fn open(&self, id: &BookId) -> Book { let opened = match Store::open(&self.root.book_dir(id)) { @@ -276,6 +1137,7 @@ impl Books { Err(ledger_store::StoreError::Locked(_)) => { Err("another program has these books open".to_string()) } + Err(ledger_store::StoreError::Cancelled) => Err(OPEN_STOPPED.to_string()), Err(e) => Err(self.hide(e.to_string())), }; opened.unwrap_or_else(|why| { @@ -286,9 +1148,10 @@ impl Books { /// Verify an open store and build its service (INVARIANTS 3, 4). fn serve(&self, mut store: Store) -> Result { - let report = store - .verify_and_heal() - .map_err(|e| format!("they don't verify: {}", self.hide(e.to_string())))?; + let report = store.verify_and_heal().map_err(|e| match e { + ledger_store::StoreError::Cancelled => OPEN_STOPPED.to_string(), + e => format!("they don't verify: {}", self.hide(e.to_string())), + })?; if let Some(why) = &report.healed { eprintln!( "wanderbooks server: rebuilt a database from its journal ({})", @@ -298,12 +1161,13 @@ impl Books { let waiting = Arc::new(Mutex::new(store.journal_format().upgrade())); let database = (store.database_file(), store.other_databases()); let served = Served::open_with(store, self.isolation).map_err(|e| self.hide(e))?; + let ended = self.sessions.child_token(); let config = StreamableHttpServerConfig::default() .with_json_response(true) .with_legacy_session_mode(true) .with_max_request_body_bytes(MAX_BODY) .enforce_origin_validation() - .with_cancellation_token(self.sessions.child_token()); + .with_cancellation_token(ended.clone()); let parts = served.clone(); // Every session's server is made the one way (server.rs Served). let service = StreamableHttpService::new( @@ -317,9 +1181,42 @@ impl Books { uploads, exports, backups, + board, .. } = served; + backups.slow_steps(self.timers.slow_steps); + // The test knob `--timer-hold`: a call a close can stop is held as + // it begins, named `call:` in `run/timer-hold`, until the + // name is gone or the close begins. + if self.timers.timer_hold + && let Ok(run) = self.root.run_dir() + { + let flag = shared.hurry_flag(); + backups.set_hold(Arc::new(move |call: &str| { + let name = format!("call:{call}"); + { + use std::io::Write; + if let Ok(mut said) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(run.join("timer-held")) + { + let _ = writeln!(said, "{name}"); + } + } + let held = || { + std::fs::read_to_string(run.join("timer-hold")) + .is_ok_and(|names| names.split(',').any(|n| n.trim() == name)) + }; + while held() && !flag.load(std::sync::atomic::Ordering::SeqCst) { + std::thread::sleep(Duration::from_millis(10)); + } + })); + } Ok(Book::Open { + gate: Arc::default(), + ended, + board, service: Box::new(service), store: shared, access, @@ -331,17 +1228,6 @@ impl Books { }) } - /// Every open book's store. - fn stores(&self) -> Vec> { - self.held() - .values() - .filter_map(|b| match b { - Book::Open { store, .. } => Some(store.clone()), - Book::Failed(_) => None, - }) - .collect() - } - fn held(&self) -> std::sync::RwLockReadGuard<'_, BTreeMap> { self.held.read().unwrap_or_else(|e| e.into_inner()) } @@ -363,25 +1249,23 @@ impl Books { .map(|(id, book)| admin::BookStatus { id: id.clone(), open: matches!(book, Book::Open { .. }), - problem: match book { - Book::Open { .. } => None, - Book::Failed(why) => Some(why.clone()), - }, + closed: matches!(book, Book::Closed), + problem: book.problem(), format_upgrade: match book { Book::Open { waiting, .. } => waiting .lock() .unwrap_or_else(|e| e.into_inner()) .as_ref() .map(admin::FormatWaiting::from), - Book::Failed(_) => None, + Book::Failed(_) | Book::Closed => None, }, database: match book { Book::Open { database, .. } => Some(database.0.clone()), - Book::Failed(_) => None, + Book::Failed(_) | Book::Closed => None, }, other_databases: match book { Book::Open { database, .. } => database.1.clone(), - Book::Failed(_) => Vec::new(), + Book::Failed(_) | Book::Closed => Vec::new(), }, }) .collect(), @@ -472,10 +1356,20 @@ impl Books { "that isn't a currency: give its three-letter ISO code, such as USD".into(), ); }; + let life = self.life(&id); + let _one = life.lock.lock().unwrap_or_else(|e| e.into_inner()); if self.held().contains_key(id.as_str()) { return refused(RootError::Exists(id.to_string())); } - match self.root.create_book(&id, currency) { + // Stopped by the server's close, or by a close of this id + // (which waits for the turn held here), before its folder is + // made, it makes nothing; after that it makes one empty book. + // A close of another book doesn't stop it (INVARIANT 10). + match self.root.create_book_stoppable( + &id, + currency, + &self.job("create", &life.stop), + ) { Ok(store) => { // Made: kept whether or not it opens (INVARIANT 3). let book = self.serve(store).unwrap_or_else(Book::Failed); @@ -497,6 +1391,9 @@ impl Books { expect_head, } => self.restore(id, source, replace, confirmed, expect_head), Request::UpgradeFormat { id, passphrase } => self.upgrade_format(id, &passphrase), + Request::OpenBook { id } => self.open_one(id), + Request::CloseBook { id } => self.close_one(id), + Request::Sessions => self.sessions_listed(), Request::Extract { id, attachment_id } => { let id = match BookId::parse(&id) { Ok(id) => id, @@ -507,6 +1404,7 @@ impl Books { Some(Book::Failed(why)) => { return Response::Refused(format!("those books didn't open: {why}")); } + Some(Book::Closed) => return Response::Refused(self.not_open(&id)), None => { return Response::Refused(format!( "there are no books called {:?}", @@ -535,6 +1433,7 @@ impl Books { Some(Book::Failed(why)) => { return Response::Refused(format!("those books didn't open: {why}")); } + Some(Book::Closed) => return Response::Refused(self.not_open(&id)), None => { return Response::Refused(format!( "there are no books called {:?}", @@ -575,10 +1474,27 @@ impl Books { Ok(id) => id, Err(e) => return refused(e), }; + let life = self.life(&id); + // A preview changes nothing, so it takes no book's turn: a + // close of this id never waits behind it (INVARIANT 10). An + // adoption takes the turn, and with it the stop of THIS id + // (and the server's): a close of the id, which waits for the + // turn, stops the adoption before its point of no return, and + // stops the opening that follows its placing, as it stops an + // open. A close of another book stops nothing of it. + let _one = confirmed.then(|| life.lock.lock().unwrap_or_else(|e| e.into_inner())); if self.held().contains_key(id.as_str()) { return refused(RootError::Exists(id.to_string())); } - let found = match self.root.adopt_preview(&source) { + let stop = self.job( + "adopt", + if confirmed { + &life.stop + } else { + &self.server_stop + }, + ); + let found = match self.root.adopt_preview_stoppable(&source, &stop) { Ok(found) => found, Err(e) => return refused(e), }; @@ -671,11 +1587,14 @@ impl Books { vault_key, expect_head, }; - match self.root.adopt(&source, &id, &options) { + match self.root.adopt_stoppable(&source, &id, &options, &stop) { Ok(r) => { - // Adopted: kept whether or not it opens. - let book = self.open(&id); - let problem = book.problem(); + // Adopted: kept whether or not it opens (not opened, + // if a close began: it is in place all the same). + let book = self.open_stoppable(&id, &stop); + let problem = book.problem().or_else(|| { + matches!(book, Book::Closed).then(|| STOPPED_AFTER_PLACED.to_string()) + }); self.hold(&id, book); Response::Adopted(admin::Adopted { id: r.id.to_string(), @@ -720,6 +1639,7 @@ impl Books { Some(Book::Failed(why)) => { return Response::Refused(format!("those books didn't open: {why}")); } + Some(Book::Closed) => return Response::Refused(self.not_open(&id)), None => { return Response::Refused(format!( "there are no books called {:?}: `wanderbooks books list` lists them", @@ -770,6 +1690,313 @@ impl Books { } } + /// Open the one book `id` (INVARIANT 10): a closed or failed book of + /// the root is opened and verified as at the start, and says so. + fn open_one(&self, id: String) -> Response { + let id = match BookId::parse(&id) { + Ok(id) => id, + Err(e) => return Response::Refused(self.hide(e.to_string())), + }; + let said = |outcome| Response::OpenBook { + id: id.to_string(), + outcome, + }; + // This book's turn only: an open of this book waits for a close or a + // restore of THIS book, never for any other book's (INVARIANT 10). + let life = self.life(&id); + let _one = life.lock.lock().unwrap_or_else(|e| e.into_inner()); + if self.closing.is_cancelled() { + return Response::Refused("the books are closing: nothing was done".into()); + } + let is_open = self + .held() + .get(id.as_str()) + .map(|b| matches!(b, Book::Open { .. })); + match is_open { + Some(true) => return said(admin::OpenOutcome::AlreadyOpen), + Some(false) => {} + // Not held: a book of the root this server didn't take up, or + // none at all. + None => match self.root.list_books() { + Ok(ids) if ids.iter().any(|i| i.as_str() == id.as_str()) => {} + Ok(_) => return said(admin::OpenOutcome::NoSuchBook), + Err(e) => return Response::Refused(self.hide(e.to_string())), + }, + } + // Stopped by a close of this book, or the server's (INVARIANT 10): + // the book stays as it was. + let stop = self.job("open", &life.stop); + if stop.look("start") { + return said(admin::OpenOutcome::CouldNotOpen(OPEN_STOPPED.into())); + } + let book = self.open_stoppable(&id, &stop); + if matches!(book, Book::Closed) { + self.hold(&id, book); + return said(admin::OpenOutcome::CouldNotOpen(OPEN_STOPPED.into())); + } + let problem = book.problem(); + self.hold(&id, book); + said(match problem { + None => admin::OpenOutcome::Opened, + Some(why) => admin::OpenOutcome::CouldNotOpen(why), + }) + } + + /// Close the one book `id` while the server runs (INVARIANT 10). In + /// this order: its door is shut and the book is listed closed, so a + /// call on it is refused from here on; the calls running on it finish, + /// on every route (SharedStore INVARIANT 3, and the gate); its MCP + /// sessions end; its last backup is made, as at the server's close; + /// and its store is let go, releasing its writer lock. Only then is it + /// answered closed. Other books are never waited on, nor refused. + fn close_one(&self, id: String) -> Response { + let id = match BookId::parse(&id) { + Ok(id) => id, + Err(e) => return Response::Refused(self.hide(e.to_string())), + }; + let said = |outcome| Response::CloseBook { + id: id.to_string(), + outcome, + }; + // From now the admin jobs working on THIS book that can run long + // stop (INVARIANT 10), so this book's turn is not held for long by + // one of them; no other book's job is touched, and no other book's + // change is waited for. + let life = self.life(&id); + let closing = self.closing_one(&life); + let one = life.lock.lock().unwrap_or_else(|e| e.into_inner()); + let answer = self.close_book_held(&id, said); + // The stop is lowered while the turn is still held: an open of this + // book that was waiting for it is not stopped by a close that is over. + drop(closing); + drop(one); + answer + } + + /// [`Self::close_one`], the book's turn held. + fn close_book_held( + &self, + id: &BookId, + said: impl Fn(admin::CloseOutcome) -> Response, + ) -> Response { + if self.closing.is_cancelled() { + return Response::Refused("the books are closing: nothing was done".into()); + } + let held = self.held().get(id.as_str()).cloned(); + 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()) => { + said(admin::CloseOutcome::WasNotOpen) + } + Ok(_) => said(admin::CloseOutcome::NoSuchBook), + Err(e) => Response::Refused(self.hide(e.to_string())), + }; + } + }; + let rt = tokio::runtime::Handle::current(); + // No new call gets in; the book is listed closed. + parts.gate.shut(); + self.hold(id, Book::Closed); + let backup = rt.block_on(self.release(id, &parts, true, Instant::now(), None)); + 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); a request whose body + /// isn't whole when ANSWER_GRACE has run out is cut (its + /// connection closed, what it wrote removed, its record saying the + /// close cut it), a running call is not; + /// 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. + async fn release( + &self, + id: &BookId, + parts: &Parts, + last_backup: bool, + begun: Instant, + hurry: Option<&CancellationToken>, + ) -> Option { + let Parts { + gate, + store, + access, + uploads, + exports, + backups, + ended, + } = parts; + // The steps of the backups a close doesn't wait for (a drill, a + // format upgrade not yet journaled) stop now, so none holds the + // store's tools or the backups' turn while the close waits for + // what it does wait for (INVARIANT 10). + backups.hurry(); + // No tool starts, and every one that did start has finished. A + // request that has begun and isn't whole when the grace runs out + // (counted from `begun`, the start of the close) is cut, so one + // that never finishes sending can't hold the book; a call whose + // body is whole and that is running is left to end. + let cutter = { + let (gate, at) = (gate.clone(), begun + self.timers.answer_grace); + tokio::spawn(async move { + tokio::time::sleep_until(at.into()).await; + gate.cut_unfinished(); + }) + }; + store.close().await; + unless_hurried(hurry, gate.emptied()).await; + cutter.abort(); + let answered = unless_hurried( + hurry, + tokio::time::timeout(self.timers.answer_grace, gate.answered()), + ) + .await; + if matches!(answered, Some(Err(_))) { + eprintln!( + "wanderbooks server: a client didn't take its answer; closing the books {id} without it" + ); + } + self.end_sessions(id, ended); + let problem = if last_backup && !hurry.is_some_and(CancellationToken::is_cancelled) { + let made = tokio::time::timeout(self.timers.backup_at_close, backups.run("close")); + match unless_hurried(hurry, made).await { + Some(Ok(Ok(status))) => backup_incomplete(&status), + Some(Ok(Err(why))) => Some(why), + Some(Err(_)) => Some(format!( + "it took longer than {} seconds, and was stopped", + self.timers.backup_at_close.as_secs().max(1) + )), + None => None, + } + } else { + None + }; + // A run still going is stopped, and waited for: nothing of the + // backups runs once this returns. + let left = backups.shut().await; + access.close(); + uploads.close(); + exports.close(); + store.let_go().await; + // A git stopped at its bound that left locks in the owner's folder: + // said with the file, as the standing says it (ledger_store backup + // INVARIANT 5b), not only that the backup took too long. + let problem = match (problem, left.is_empty()) { + (problem, true) => problem, + (None, false) => Some(left.join("; ")), + (Some(why), false) => Some(format!("{why}; {}", left.join("; "))), + }; + problem.map(|why| self.hide(why)) + } + + /// The door of every open book. + fn gates(&self) -> Vec> { + self.held() + .values() + .filter_map(|b| b.parts().map(|p| p.gate)) + .collect() + } + + /// End the MCP sessions of the book `id` and forget their bindings. + fn end_sessions(&self, id: &BookId, ended: &CancellationToken) { + ended.cancel(); + self.session_tokens + .lock() + .unwrap_or_else(|e| e.into_inner()) + .retain(|_, bound| bound.book != id.as_str()); + } + + /// Who is connected to each open book (INVARIANT 12). + fn sessions_listed(&self) -> Response { + let bound: Vec<(String, String, String, i64)> = self + .session_tokens + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .map(|(sid, b)| (sid.clone(), b.name.clone(), b.book.clone(), b.at)) + .collect(); + let open: Vec<(String, Arc)> = self + .held() + .iter() + .filter_map(|(id, b)| match b { + Book::Open { board, .. } => Some((id.clone(), board.clone())), + Book::Failed(_) | Book::Closed => None, + }) + .collect(); + let when = |at: i64| { + chrono::DateTime::from_timestamp(at, 0) + .map(|t| t.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)) + .unwrap_or_default() + }; + Response::Sessions( + open.into_iter() + .map(|(book, board)| { + let mut mine: Vec<_> = bound.iter().filter(|(_, _, b, _)| *b == book).collect(); + mine.sort_by(|a, b| (a.3, &a.0).cmp(&(b.3, &b.0))); + let live: Vec = mine.iter().map(|(sid, ..)| sid.clone()).collect(); + let mut notes = board.snapshot(&live); + let sessions = mine + .into_iter() + .map(|(sid, name, _, at)| { + let note = notes.remove(sid).unwrap_or_default(); + admin::SessionInfo { + token: name.clone(), + client_name: note.client.as_ref().map(|c| c.name.clone()), + client_version: note.client.as_ref().map(|c| c.version.clone()), + agent: note.agent.map(|a| admin::SessionAgent { + model: a.model, + reasoning_effort: a.reasoning_effort, + harness: a.harness, + }), + connected_at: when(*at), + running: u32::try_from(note.running).unwrap_or(u32::MAX), + last: note.last.map(|l| admin::LastCall { + tool: l.subject, + outcome: match l.outcome { + Outcome::Ok => "ok".to_string(), + Outcome::Error => "error".to_string(), + Outcome::Refused(code) => format!("refused: {code}"), + }, + at: when(l.at), + }), + } + }) + .collect(); + admin::BookSessions { book, sessions } + }) + .collect(), + ) + } + + /// What is said of a book that exists but isn't open, to an admin + /// request that needs it open. + fn not_open(&self, id: &BookId) -> String { + closed_words(id.as_str()) + } + /// Restore a backup (admin INVARIANT 4; ledger_store::root INVARIANT /// 7): a preview, or the books restored and opened. Books it replaces /// are let go first, and opened again if the restore fails. @@ -794,16 +2021,20 @@ impl Books { Ok(id) => id, Err(e) => return said(e.to_string()), }; - let _one = self.restoring.lock().unwrap_or_else(|e| e.into_inner()); let git = match ledger_store::backup::Git::find() { Ok(git) => git, Err(e) => return said(e.to_string()), }; // A preview only reports (whether books of that id exist among - // what it says): the restore itself is refused over books, or - // replacing none. + // what it says), so it changes nothing and takes no book's turn: a + // close of this id never waits behind its clone and its queue for + // the books lock (INVARIANT 10). Only the server's close stops it. if !confirmed { - return match self.root.restore_preview(&git, &source, &id) { + let stop = self.job("restore", &self.server_stop); + return match self + .root + .restore_preview_stoppable(&git, &source, &id, &stop) + { Ok(p) => Response::RestorePreview(admin::RestorePreview { head: p.head, blobs: p.blobs, @@ -814,9 +2045,20 @@ impl Books { Err(e) => said(e.to_string()), }; } + // A restore takes this book's turn only (INVARIANT 10), and with it + // the stop of THIS id (and the server's): a close of the id, which + // waits for the turn, stops the restore before its point of no + // return, whether it replaces the books or makes new ones. + let life = self.life(&id); + let _one = life.lock.lock().unwrap_or_else(|e| e.into_inner()); + let stop = self.job("restore", &life.stop); let Some(expect_head) = expect_head else { return said("a restore is confirmed against the preview's head: preview first".into()); }; + // Stopped by a close before anything is let go (INVARIANT 10). + if stop.look("begin") { + return said("stopped because the books are closing: nothing was restored".into()); + } let held = self.held().contains_key(id.as_str()); if replace && !held { return said(format!( @@ -830,34 +2072,40 @@ 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. + // The door is shut first and the book listed closed (never taken + // out of the list: a call that comes while the restore runs is + // told the books aren't open, as in a close, never that there are + // no such books). let old = if replace { - self.held - .write() - .unwrap_or_else(|e| e.into_inner()) - .remove(id.as_str()) + self.held().get(id.as_str()).cloned() } 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, .. }) = &old { - rt.block_on(store.let_go()); + if let Some(parts) = old.as_ref().and_then(Book::parts) { + let rt = tokio::runtime::Handle::current(); + parts.gate.shut(); + self.hold(&id, Book::Closed); + rt.block_on(self.release(&id, &parts, false, Instant::now(), None)); } - let _paused = old_backups.as_ref().map(|b| rt.block_on(b.pause())); - match self.root.restore(&git, &source, &id, &expect_head, replace) { + match self + .root + .restore_stoppable(&git, &source, &id, &expect_head, replace, &stop) + { Ok(r) => { // Restored: kept whether or not it opens; its backups told - // whose books these were (backup.rs INVARIANTS 6, 7). - let book = self.open(&id); - let problem = book.problem(); + // whose books these were (backup.rs INVARIANTS 6, 7). Past its + // point of no return a stop doesn't undo it: the books are + // in place, and not opened if the server is closing. + let book = self.open_stoppable(&id, &stop); + let problem = book.problem().or_else(|| { + matches!(book, Book::Closed).then(|| STOPPED_AFTER_PLACED.to_string()) + }); self.hold(&id, book); Response::Restored(admin::Restored { id: r.id.to_string(), @@ -872,8 +2120,8 @@ impl Books { Err(e) => { // The books it would have replaced, let go above, open // again (only this restore runs, so nothing else holds them). - if replace && !self.held().contains_key(id.as_str()) { - let book = self.open(&id); + if replace { + let book = self.open_stoppable(&id, &stop); self.hold(&id, book); } said(e.to_string()) @@ -1073,7 +2321,7 @@ impl Drop for InFlight { } /// The MCP session header. -const SESSION_HEADER: &str = "mcp-session-id"; +pub(crate) const SESSION_HEADER: &str = "mcp-session-id"; /// The most sessions open at once (each bound to its token): past it a /// new session is refused until one ends, never a binding forgotten @@ -1100,8 +2348,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, @@ -1123,7 +2379,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 ( @@ -1144,20 +2404,75 @@ async fn refused_at_door( response } +/// The answer to a request a close cut while its body was still arriving +/// (INVARIANT 10): recorded in the access log as cut by the close, and the +/// connection ends with it. +async fn cut_by_the_close( + book: &Book, + inside: Inside, + principal: Principal, + asked: &Asked, +) -> axum::response::Response { + let mut response = refused_at_door( + book, + inside, + principal, + asked, + crate::access::CUT, + axum::http::StatusCode::SERVICE_UNAVAILABLE, + "the books closed before this request was all sent: it wasn't run".into(), + ) + .await; + close_connection(&mut response); + response +} + +fn close_connection(response: &mut axum::response::Response) { + response.headers_mut().insert( + axum::http::header::CONNECTION, + axum::http::HeaderValue::from_static("close"), + ); +} + /// The door to `book` (INVARIANT 8): the books held open, the server not /// closing, and a live token for those books; else the answer refusing /// the request (recorded in the books' access log, where there is one). +/// A request let through is inside the book's door (INVARIANT 10) until +/// the returned [`Inside`] is dropped: a close of the book waits for it, +/// so it must live as long as the request touches the book. async fn door( books: &Arc, book: &str, asked: &Asked, headers: &axum::http::HeaderMap, -) -> Result<(Book, Token), Box> { +) -> Result<(Book, Token, Inside), Box> { use axum::http::StatusCode; use axum::response::IntoResponse; let closing = books.closing.is_cancelled(); let found = books.held().get(book).cloned(); + // Inside the book's door before anything of the book is touched, its + // access log included; a door that has shut (the book is closing, or + // closed) is the same refusal as a book listed closed. + let entered = match &found { + Some(Book::Open { gate, .. }) => Some(gate.enter()), + _ => None, + }; + let shut_door = matches!(entered, Some(None)); + let (found, inside) = match entered { + Some(Some(inside)) => (found, Some(inside)), + Some(None) => (Some(Book::Closed), None), + None => (found, None), + }; let held = match found { + Some(Book::Closed) if !closing => { + return Err(( + StatusCode::SERVICE_UNAVAILABLE, + [(REFUSED_HEADER, "closed")], + closed_words(book), + ) + .into_response() + .into()); + } Some(Book::Failed(why)) if !closing => { return Err(( StatusCode::SERVICE_UNAVAILABLE, @@ -1181,14 +2496,26 @@ async fn door( } Some(b @ Book::Open { .. }) => b, _ => { - return Err(( + let mut response = ( StatusCode::SERVICE_UNAVAILABLE, "the books are closing: this request wasn't run", ) - .into_response() - .into()); + .into_response(); + // The server is closing and this book's door is already shut + // (INVARIANT 15): the same refusal, as a client knows it, as + // one at an open door (not recorded: the door is shut). + if shut_door { + response.headers_mut().insert( + REFUSED_HEADER, + axum::http::HeaderValue::from_static(crate::access::CLOSING), + ); + } + return Err(response.into()); } }; + let Some(inside) = inside else { + unreachable!("an open book was entered above") + }; let token = books.bearer(headers); let principal = |t: &Token| Principal { id: t.id.clone(), @@ -1201,6 +2528,7 @@ async fn door( .map_or_else(|_| Principal::unknown(), principal); return Err(refused_at_door( &held, + inside, who, asked, crate::access::CLOSING, @@ -1215,6 +2543,7 @@ async fn door( Err((code, why)) => { return Err(refused_at_door( &held, + inside, Principal::unknown(), asked, code, @@ -1228,6 +2557,7 @@ async fn door( if token.book != book { return Err(refused_at_door( &held, + inside, principal(&token), asked, "wrong_books", @@ -1237,7 +2567,7 @@ async fn door( .await .into()); } - Ok((held, token)) + Ok((held, token, inside)) } /// `PUT /b/{book}/u/{upload}`: the bytes of an upload begun with @@ -1260,7 +2590,7 @@ async fn upload( action: "upload", subject: id.clone(), }; - let (held, token) = match door(&books, &book, &asked, request.headers()).await { + let (held, token, inside) = match door(&books, &book, &asked, request.headers()).await { Ok(passed) => passed, Err(refused) => { // What was sent is read and dropped (up to the most an upload @@ -1287,6 +2617,10 @@ async fn upload( else { unreachable!("the door lets only open books through") }; + // Its body watched: a close whose grace ran out cuts it while it is + // still arriving, which ends `receive` with its part file removed. + let (request, arrival) = inside.arriving(request); + let cut_seen = arrival.clone(); // Streamed to the disk as it comes, never held whole; `receive` reads // no more than the size declared and one byte. The bytes and their // record are one blocking task, which runs to its end even if the @@ -1301,6 +2635,9 @@ async fn upload( let (uploads, access, stopped) = (uploads.clone(), access.clone(), store.is_stopped()); let task = tokio::task::spawn_blocking(move || { let _counted = _counted; + // Inside the book's door until its bytes and record are done: a + // close of the book waits for them (INVARIANT 10). + let _inside = inside; // The books server stopped after an internal error: nothing more // comes in (SharedStore INVARIANT 2). let received = if stopped { @@ -1317,6 +2654,12 @@ async fn upload( let _ = std::io::copy(&mut (&mut body).take(rest), &mut std::io::sink()); } let (status, outcome, text) = match &received { + _ if cut_seen.was_cut() => ( + StatusCode::SERVICE_UNAVAILABLE, + Outcome::Refused(crate::access::CUT.into()), + "the books closed before this upload was all sent: send it again once they are open" + .to_string(), + ), Ok(g) => ( StatusCode::OK, Outcome::Ok, @@ -1369,10 +2712,14 @@ async fn upload( ) .into_response(); }; - match outcome { + let mut response = match outcome { Outcome::Refused(code) => (status, [(REFUSED_HEADER, code)], text).into_response(), _ => (status, text).into_response(), + }; + if arrival.was_cut() { + close_connection(&mut response); } + response } /// `GET /b/{book}/a/{attachment}`: a stored file's bytes, for a token @@ -1437,7 +2784,7 @@ async fn fetch( action, subject: subject.clone(), }; - let (held, token) = match door(&books, &book, &asked, request.headers()).await { + let (held, token, inside) = match door(&books, &book, &asked, request.headers()).await { Ok(passed) => passed, Err(refused) => return *refused, }; @@ -1455,6 +2802,9 @@ async fn fetch( let (access, store_for, exports) = (access.clone(), store.clone(), exports.clone()); let task = tokio::task::spawn_blocking(move || { let _counted = _counted; + // Inside the book's door until the read and its record are done + // (INVARIANT 10). + let _inside = inside; use ledger_store::exports::ExportError; let not_found = |code, what: &str| { ( @@ -1621,20 +2971,28 @@ async fn mcp( .last_arrival .store(books.started.elapsed().as_millis() as u64, Ordering::SeqCst); let method = request.method().clone(); - let (held, token) = match door(&books, &book, &Asked::connect(&method), request.headers()).await - { - Ok(passed) => passed, - Err(refused) => return *refused, - }; - let Book::Open { service, .. } = &held else { + // 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) = + match door(&books, &book, &Asked::connect(&method), request.headers()).await { + Ok(passed) => passed, + Err(refused) => return *refused, + }; + let Book::Open { service, board, .. } = &held else { unreachable!("the door lets only open books through") }; - let service = (**service).clone(); + let (service, board) = ((**service).clone(), board.clone()); let principal = |t: &Token| Principal { id: t.id.clone(), kind: "agent".into(), label: t.name.clone(), }; + // Its body watched: a close whose grace ran out cuts it while it is + // still arriving (never once whole), before any tool has seen it. + let (rewatched, arrival) = inside.arriving(request); + request = rewatched; + let who = principal(&token); let session = request .headers() .get(SESSION_HEADER) @@ -1652,7 +3010,7 @@ async fn mcp( let elsewhere = session .as_ref() .and_then(|sid| bound.get(sid)) - .is_some_and(|owner| *owner != token.id); + .is_some_and(|owner| owner.token != token.id); (elsewhere, session.is_none() && bound.len() >= MAX_SESSIONS) }; // The cap is on opening sessions: a request opens one only if it is an @@ -1668,9 +3026,13 @@ async fn mcp( request = axum::extract::Request::from_parts(parts, axum::body::Body::from(bytes)); opens }; + if arrival.was_cut() { + return cut_by_the_close(&held, inside, who, &Asked::connect(&method)).await; + } if full { return refused_at_door( &held, + inside, principal(&token), &Asked::connect(&method), "too_many_sessions", @@ -1682,6 +3044,7 @@ async fn mcp( if elsewhere { return refused_at_door( &held, + inside, principal(&token), &Asked::connect(&method), "session_token", @@ -1690,7 +3053,7 @@ async fn mcp( ) .await; } - let token_id = token.id.clone(); + let (token_id, token_name) = (token.id.clone(), token.name.clone()); request .extensions_mut() .insert(crate::access::Caller { token }); @@ -1698,6 +3061,14 @@ async fn mcp( Ok(response) => response, Err(never) => match never {}, }; + // The service reads a whole body before it hands any message to a + // session or a tool (rmcp's `expect_json`, which ends in an error + // answer on a body that fails), so a body cut here reached nothing: + // no call ran, nothing is in the journal. + if arrival.was_cut() { + drop(response); + return cut_by_the_close(&held, inside, who, &Asked::connect(&method)).await; + } // A session the answer opened is bound to the token that opened it; // one ended, or found gone, is forgotten. { @@ -1711,7 +3082,15 @@ async fn mcp( .get(SESSION_HEADER) .and_then(|v| v.to_str().ok()) { - bound.insert(sid.to_string(), token_id); + bound.insert( + sid.to_string(), + Bound { + token: token_id, + name: token_name, + book: book.clone(), + at: chrono::Utc::now().timestamp(), + }, + ); } let ended = method == axum::http::Method::DELETE && response.status().is_success(); let gone = response.status() == StatusCode::NOT_FOUND; @@ -1719,12 +3098,18 @@ async fn mcp( && let Some(sid) = &session { bound.remove(sid); + board.forget(sid); } } + // The answer may still be on its way: it counts, for the server's close + // 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()); response.map(|body| { use http_body_util::BodyExt; axum::body::Body::new(body.map_frame(move |frame| { - let _held = &counted; + let _held = (&counted, &answering); frame })) }) @@ -1827,7 +3212,7 @@ pub fn tunnel_address(text: &str) -> Result { } fn print_usage(prog: &str) { - eprintln!("usage: {prog} [--root DIR] [--isolation LEVEL] [--http [ADDR]]"); + eprintln!("usage: {prog} [--root DIR] [--isolation LEVEL] [--http [ADDR]] [--open BOOKS]"); eprintln!(" The books server for the data root: started by the host, not by hand."); eprintln!(" It runs until its standard input ends, or SIGTERM, SIGINT or SIGHUP."); eprintln!(" --isolation same_user | enforced: what books.start says of how these books"); @@ -1835,6 +3220,8 @@ fn print_usage(prog: &str) { eprintln!(" --http [ADDR]: also serve the MCP door on loopback only (default"); eprintln!(" 127.0.0.1:7411), for a TLS proxy or a tunnel in front of it. Off unless"); eprintln!(" given; any other address is refused."); + eprintln!(" --open all | none | ID[,ID...]: which books are open at the start (default"); + eprintln!(" all). A book left closed opens when asked (`wanderbooks books open ID`)."); } /// `wanderbooks server`: serve every book in the data root until told to @@ -1846,8 +3233,10 @@ 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; let mut args = args.into_iter().peekable(); while let Some(arg) = args.next() { match arg.as_str() { @@ -1871,6 +3260,12 @@ pub fn run( }; tunnel = Some(tunnel_address(&addr)?); } + // Which books are open at the start (plan/p15-app-and-relay.md + // 3.1): the app opens a company as its tab opens. + "--open" => { + open_at_start = + OpenAtStart::parse(&args.next().ok_or("--open needs all, none, or ids")?)?; + } // How long the books stay unwritten before a backup (tests). "--backup-quiet" => { let ms: u64 = args @@ -1887,6 +3282,46 @@ 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); + } + // Make a drill or a format upgrade slow, as a large book makes + // them (tests): each phase waits this long, or until the close + // hurries it. + "--slow-steps" => { + let ms: u64 = args + .next() + .and_then(|v| v.parse().ok()) + .ok_or("--slow-steps needs milliseconds")?; + timers.slow_steps = Duration::from_millis(ms); + } + // A timer waits between taking a book's handles and acting on + // them, while `run/timer-hold` exists (tests). + "--timer-hold" => timers.timer_hold = true, "--help" | "-h" => { print_usage(prog); return Ok(()); @@ -1959,22 +3394,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 { - root: root.clone(), - held: RwLock::new(BTreeMap::new()), - sessions: CancellationToken::new(), - closing: CancellationToken::new(), - in_flight: AtomicUsize::new(0), - finished: tokio::sync::Notify::new(), - last_arrival: std::sync::atomic::AtomicU64::new(0), - started: std::time::Instant::now(), - principals: RwLock::new(Err(String::new())), - session_tokens: Mutex::new(BTreeMap::new()), - backup_quiet, - drill_first, - restoring: Mutex::new(()), - 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 { @@ -1982,9 +3404,25 @@ pub fn run( } *books.principals.write().unwrap_or_else(|e| e.into_inner()) = loaded; } - // INVARIANT 3: every book tried before ready. - for id in root.list_books().map_err(|e| e.to_string())? { - let book = books.open(&id); + // INVARIANT 3: every book chosen to be open is tried before ready; the + // others are held closed. + let ids = root.list_books().map_err(|e| e.to_string())?; + if let OpenAtStart::Only(wanted) = &open_at_start + && let Some(unknown) = wanted + .iter() + .find(|w| !ids.iter().any(|i| i.as_str() == w.as_str())) + { + eprintln!( + "wanderbooks server: --open names books that don't exist: {unknown:?} (`wanderbooks books list` lists them)" + ); + return Err(Box::new(crate::Exit(2))); + } + for id in ids { + let book = if open_at_start.wants(&id) { + books.open(&id) + } else { + Book::Closed + }; books.hold(&id, book); } let served = if stops.close.is_cancelled() { @@ -2065,27 +3503,42 @@ 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, _ = tick.tick() => { - let held: Vec<_> = sweeping + let handles: Vec<_> = sweeping .held() .values() .filter_map(|b| match b { - Book::Open { uploads, exports, .. } => { - Some((uploads.clone(), exports.clone())) + Book::Open { uploads, exports, gate, .. } => { + Some((uploads.clone(), exports.clone(), gate.clone())) } - Book::Failed(_) => None, + Book::Failed(_) | Book::Closed => None, }) .collect(); + if !handles.is_empty() { + sweeping.timer_hold("sweep").await; + } + // Inside each book's door, entered only now: a book + // that closed since the handles were taken is skipped + // (and its handles are closed, whatever this does). + let held: Vec<_> = handles + .into_iter() + .filter_map(|(u, x, gate)| gate.enter().map(|inside| (u, x, inside))) + .collect(); let now = chrono::Utc::now().timestamp(); let _ = tokio::task::spawn_blocking(move || { - for (u, x) in &held { + for (u, x, _inside) in &held { u.sweep(now); x.sweep(now); } @@ -2127,50 +3580,68 @@ async fn serve( } drop(admin_listener); eprintln!("wanderbooks server: closing"); - // INVARIANT 6. New requests are refused from here on. + // INVARIANT 6. New requests are refused from here on, and (INVARIANT + // 15) every book's door is shut and the cut of what hasn't finished + // arriving is set for one grace from now, at the start: the one thing + // a stalled client may not do is hold the close, whatever else the + // close is waiting for (an admin job, a slow backup of another book). books.closing.cancel(); - // Admin work under way (a create, an adoption) finishes. - admin_jobs.close(); - admin_jobs.wait().await; - // Every request already running finishes its work, however long it - // takes and whether or not its client is still there: a store is - // never let go of mid-write (SharedStore INVARIANT 3). - for store in books.stores() { - store.close().await; - } - // A last backup of what was written since the last one, for a while - // at most: the books are closing, nothing more is written. The loop - // stops at its next step (`stop`); a run of its still under way - // finishes first (each book runs one at a time). - drop(backup_loop); - let held: Vec> = books - .held() - .values() - .filter_map(|b| match b { - Book::Open { backups, .. } => Some(backups.clone()), - Book::Failed(_) => None, + // The admin jobs that can run long stop at their next look, before + // their point of no return (INVARIANT 10): the wait below is for jobs + // that are stopping, not for a restore to run its course. + books.stop_every_job(); + let begun = Instant::now(); + let cutters: Vec<_> = books + .gates() + .into_iter() + .map(|gate| { + gate.shut(); + let at = begun + books.timers.answer_grace; + tokio::spawn(async move { + tokio::time::sleep_until(at.into()).await; + gate.cut_unfinished(); + }) }) .collect(); - for b in held { - let _ = tokio::time::timeout(BACKUP_AT_CLOSE, b.run("close")).await; - } - // Answers on their way out are sent, for a while: a client sending - // a request it never finishes doesn't hold the books open. - let answers = async { - loop { - let notified = books.finished.notified(); - if books.in_flight.load(Ordering::SeqCst) == 0 { - break; - } - notified.await; + // Admin work under way (a create, an adoption, a close of one book) + // finishes. + admin_jobs.close(); + admin_jobs.wait().await; + drop(backup_loop); + // Every book still open is let go the way a close of one book lets go + // of it (`Books::release`: INVARIANT 10, the one closing path): its + // tools finish, however long they take and whether or not their client + // is still there (a store is never let go of mid-write, SharedStore + // INVARIANT 3), the answers on their way out are sent, a request not + // whole at the grace is cut, its sessions end, its last backup is made + // for BACKUP_AT_CLOSE at most, and its logs, uploads, exports, backups + // and store are closed. The books are let go together: one slow + // backup doesn't hold the others' (each book's own bound is the same). + // (Every admin job has ended: `admin_jobs.wait()` above. No book's + // changes are in flight to be waited for.) + let open: Vec<(BookId, Parts)> = { + let open: Vec<(BookId, Parts)> = books + .held() + .iter() + .filter_map(|(id, b)| Some((BookId::parse(id).ok()?, b.parts()?))) + .collect(); + for (id, _) in &open { + books.hold(id, Book::Closed); } + open }; - tokio::select! { - () = answers => {} - () = tokio::time::sleep(ANSWER_GRACE) => { - eprintln!("wanderbooks server: a client didn't finish its request; closing without it"); + let released = futures_util::future::join_all( + open.iter() + .map(|(id, parts)| books.release(id, parts, true, begun, Some(&stops.hurry))), + ) + .await; + for ((id, _), problem) in open.iter().zip(released) { + if let Some(why) = problem { + eprintln!("wanderbooks server: the last backup of the books {id} wasn't whole: {why}"); } - () = stops.hurry.cancelled() => {} + } + for cutter in cutters { + cutter.abort(); } books.sessions.cancel(); // A call that set out just before its client heard of the close still @@ -2340,6 +3811,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 @@ -2350,7 +3841,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, @@ -2361,7 +3852,7 @@ async fn keep_backed_up(books: Arc, stop: CancellationToken) { .iter() .filter_map(|(id, b)| match b { Book::Open { backups, .. } => Some((id.clone(), backups.clone())), - Book::Failed(_) => None, + Book::Failed(_) | Book::Closed => None, }) .collect(); seen.retain(|id, _| open.iter().any(|(o, _)| o == id)); @@ -2398,6 +3889,7 @@ async fn keep_backed_up(books: Arc, stop: CancellationToken) { s.moved_at = now; } if let Some(why) = due { + books.timer_hold("backup").await; let outcome = backups .run(why) .await @@ -2410,8 +3902,9 @@ 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 { + books.timer_hold("drill").await; backups.drill().await; } } @@ -2620,22 +4113,12 @@ mod tests { /// without its sockets: each test drives the handlers itself. fn books_in(home: &Path) -> Arc { let (root, _) = Root::setup(home, Some(&home.join("root")), None).unwrap(); - let books = Arc::new(Books { + let books = Arc::new(Books::new( root, - held: RwLock::new(BTreeMap::new()), - sessions: CancellationToken::new(), - closing: CancellationToken::new(), - in_flight: AtomicUsize::new(0), - finished: tokio::sync::Notify::new(), - last_arrival: std::sync::atomic::AtomicU64::new(0), - started: Instant::now(), - principals: RwLock::new(Err(String::new())), - session_tokens: Mutex::new(BTreeMap::new()), - backup_quiet: BACKUP_QUIET, - drill_first: DRILL_FIRST, - restoring: Mutex::new(()), - isolation: Isolation::SameUser, - }); + BACKUP_QUIET, + DRILL_FIRST, + Isolation::SameUser, + )); let loaded = books.load_principals(); *books.principals.write().unwrap() = loaded; books @@ -2668,6 +4151,16 @@ mod tests { } } + /// A session of `book` bound to the token `token`. + fn bound_to(token: &str, book: &str) -> Bound { + Bound { + token: token.into(), + name: "test".into(), + book: book.into(), + at: 0, + } + } + /// The sessions bound, by id. fn bound(books: &Books) -> Vec { books @@ -2948,7 +4441,7 @@ mod tests { { let mut bound = books.session_tokens.lock().unwrap(); for (sid, owner) in [("s-beta", &beta), ("s-other", &other), ("s-agent", &agent)] { - bound.insert(sid.into(), owner.clone()); + bound.insert(sid.into(), bound_to(owner, "acme")); } } token(&books, "acme", "agent"); @@ -3054,7 +4547,12 @@ mod tests { let (status, _, said) = answer(r).await; assert!((200..300).contains(&status), "{status}: {said}"); assert_eq!( - books.session_tokens.lock().unwrap().get(&sid), + books + .session_tokens + .lock() + .unwrap() + .get(&sid) + .map(|b| &b.token), Some(&agent_id) ); } @@ -3085,7 +4583,7 @@ mod tests { { let mut bound = books.session_tokens.lock().unwrap(); for n in 0..MAX_SESSIONS { - bound.insert(format!("s-{n}"), agent_id.clone()); + bound.insert(format!("s-{n}"), bound_to(&agent_id, "acme")); } } let r = send_mcp( @@ -3343,6 +4841,7 @@ mod tests { let store = match &books.held()["acme"] { Book::Open { store, .. } => store.clone(), Book::Failed(why) => panic!("{why}"), + Book::Closed => panic!("closed"), }; let (d, s) = (dir.clone(), store.clone()); let first = tokio::task::spawn_blocking(move || { @@ -3428,4 +4927,671 @@ mod tests { "{record}" ); } + + /// An admin request, on a thread of its own (an admin request blocks). + async fn ask(books: &Arc, request: Request) -> Response { + let books = books.clone(); + tokio::task::spawn_blocking(move || books.admin(request)) + .await + .unwrap() + } + + fn closed(id: &str) -> Response { + Response::CloseBook { + id: id.into(), + outcome: admin::CloseOutcome::Closed, + } + } + + fn opened(id: &str, outcome: admin::OpenOutcome) -> Response { + Response::OpenBook { + id: id.into(), + outcome, + } + } + + /// Headers carrying `bearer`. + fn bearing(bearer: &str) -> axum::http::HeaderMap { + let mut h = axum::http::HeaderMap::new(); + h.insert("authorization", format!("Bearer {bearer}").parse().unwrap()); + h + } + + /// What the door says of `book`, for a request bearing `bearer`: let + /// through (None), or its status, refusal code and words. + async fn at_the_door( + books: &Arc, + book: &str, + bearer: &str, + ) -> Option<(u16, Option, String)> { + let asked = Asked::connect(&axum::http::Method::POST); + match door(books, book, &asked, &bearing(bearer)).await { + Ok(_) => None, + Err(r) => Some(answer(*r).await), + } + } + + /// INVARIANT 10, 11: a closed book's calls are refused as "closed" (not + /// as a book that doesn't exist), with words an agent can relay; the + /// other book never notices; the book is listed closed, with no + /// problem; it opens again, and serves again. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_closed_book_is_refused_as_closed_and_the_other_still_serves() { + let home = tempfile::tempdir().unwrap(); + let books = books_in(home.path()); + create(&books, "acme"); + create(&books, "beta"); + let (_, acme) = token(&books, "acme", "agent"); + let (_, beta) = token(&books, "beta", "agent"); + assert_eq!(at_the_door(&books, "acme", &acme).await, None); + + assert_eq!( + ask(&books, Request::CloseBook { id: "acme".into() }).await, + closed("acme") + ); + let (status, code, said) = at_the_door(&books, "acme", &acme).await.unwrap(); + assert_eq!((status, code.as_deref()), (503, Some("closed"))); + assert_eq!( + said, + "The books \"acme\" aren't open: open them in Wanderbooks." + ); + // Told apart from books that don't exist. + let (status, code, _) = at_the_door(&books, "nobody", &acme).await.unwrap(); + assert_eq!((status, code.as_deref()), (404, Some("no-such-books"))); + // The other book is untouched. + assert_eq!(at_the_door(&books, "beta", &beta).await, None); + let listed = books.held()["acme"].problem(); + assert_eq!(listed, None, "closed is not a problem"); + match ask(&books, Request::List).await { + Response::Books(list) => { + let a = list.iter().find(|b| b.id == "acme").unwrap(); + assert!(!a.open && a.closed && a.problem.is_none(), "{a:?}"); + let b = list.iter().find(|b| b.id == "beta").unwrap(); + assert!(b.open && !b.closed, "{b:?}"); + } + other => panic!("{other:?}"), + } + + // Closed twice; and a name that is no book. + assert_eq!( + ask(&books, Request::CloseBook { id: "acme".into() }).await, + Response::CloseBook { + id: "acme".into(), + outcome: admin::CloseOutcome::WasNotOpen + } + ); + assert_eq!( + ask( + &books, + Request::CloseBook { + id: "nobody".into() + } + ) + .await, + Response::CloseBook { + id: "nobody".into(), + outcome: admin::CloseOutcome::NoSuchBook + } + ); + + // Open: once; again; a name that is no book. + assert_eq!( + ask(&books, Request::OpenBook { id: "acme".into() }).await, + opened("acme", admin::OpenOutcome::Opened) + ); + assert_eq!( + ask(&books, Request::OpenBook { id: "acme".into() }).await, + opened("acme", admin::OpenOutcome::AlreadyOpen) + ); + assert_eq!( + ask( + &books, + Request::OpenBook { + id: "nobody".into() + } + ) + .await, + opened("nobody", admin::OpenOutcome::NoSuchBook) + ); + assert_eq!(at_the_door(&books, "acme", &acme).await, None); + } + + /// INVARIANT 10: a close lets go of the store, releasing its writer + /// lock, so another process could open the book; and while another + /// holds it, opening says so, as at the start. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_closed_book_can_be_opened_by_another_program_and_not_by_two() { + let home = tempfile::tempdir().unwrap(); + let books = books_in(home.path()); + create(&books, "acme"); + let dir = books.root.book_dir(&BookId::parse("acme").unwrap()); + // Held: the same program can't open the store a second time. + assert!(Store::open(&dir).is_err(), "the server holds the books"); + assert_eq!( + ask(&books, Request::CloseBook { id: "acme".into() }).await, + closed("acme") + ); + // Let go: another opens, writes (an account), and holds it. + let other = Store::open(&dir).expect("the lock was released"); + match ask(&books, Request::OpenBook { id: "acme".into() }).await { + Response::OpenBook { + outcome: admin::OpenOutcome::CouldNotOpen(why), + .. + } => assert!( + why.contains("another program has these books open"), + "{why}" + ), + other => panic!("{other:?}"), + } + match ask(&books, Request::List).await { + Response::Books(list) => { + let a = list.iter().find(|b| b.id == "acme").unwrap(); + assert!(!a.open && !a.closed && a.problem.is_some(), "{a:?}"); + } + other => panic!("{other:?}"), + } + // Closing a book that didn't open: it was not open. + assert_eq!( + ask(&books, Request::CloseBook { id: "acme".into() }).await, + Response::CloseBook { + id: "acme".into(), + outcome: admin::CloseOutcome::WasNotOpen + } + ); + drop(other); + assert_eq!( + ask(&books, Request::OpenBook { id: "acme".into() }).await, + opened("acme", admin::OpenOutcome::Opened) + ); + } + + /// INVARIANT 10: a close answers only once the requests already inside + /// the book's door have left; a request arriving meanwhile is + /// refused at once (as closed), and another book is not held up. + /// INVARIANT 10: a close stops a format upgrade that has not yet + /// journaled its `journal.format_set` line, instead of waiting for it + /// (the upgrade is counted by the store's close): the upgrade says it + /// was not done, the books are byte for byte as they were, and the + /// close is answered. The upgrade is held in its backup's proof by the + /// test knob that makes each phase wait a minute. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_close_stops_a_format_upgrade_before_it_is_journaled() { + let home = tempfile::tempdir().unwrap(); + let (root, _) = Root::setup(home.path(), Some(&home.path().join("root")), None).unwrap(); + let books = Arc::new( + Books::new(root, BACKUP_QUIET, DRILL_FIRST, Isolation::SameUser).with_timers(Timers { + slow_steps: Duration::from_secs(60), + answer_grace: Duration::from_millis(300), + ..Timers::default() + }), + ); + let loaded = books.load_principals(); + *books.principals.write().unwrap() = loaded; + let dir = old_books(&books, "acme"); + let auth = books.root.auth_dir().unwrap(); + ledger_store::passphrase::set(&auth, PASS, None).unwrap(); + let journal = || std::fs::read(dir.join(ledger_store::JOURNAL_FILE)).unwrap(); + let before = journal(); + let backups = match books.held().get("acme") { + Some(Book::Open { backups, .. }) => backups.clone(), + _ => panic!("acme isn't open"), + }; + let upgrading = tokio::spawn({ + let books = books.clone(); + async move { upgrade(&books, "acme", PASS).await } + }); + // It is inside the proof of its backup, waiting. + let by = Instant::now() + Duration::from_secs(60); + while backups.pauses_begun() == 0 { + assert!(Instant::now() < by, "the upgrade never reached its proof"); + tokio::time::sleep(Duration::from_millis(20)).await; + } + let started = Instant::now(); + let closed = ask(&books, Request::CloseBook { id: "acme".into() }).await; + assert!( + started.elapsed() < Duration::from_secs(20), + "held by the upgrade" + ); + assert!( + matches!( + closed, + Response::CloseBook { + outcome: admin::CloseOutcome::Closed + | admin::CloseOutcome::ClosedBackupIncomplete(_), + .. + } + ), + "{closed:?}" + ); + match upgrading.await.unwrap() { + Response::Refused(why) => assert!(why.contains("nothing was upgraded"), "{why}"), + other => panic!("{other:?}"), + } + assert_eq!( + journal(), + before, + "an upgrade stopped by a close changed the books" + ); + } + + /// INVARIANT 15: a body read to its end is whole and never cut, + /// whatever follows (the cut firing, the body polled again); one not + /// read to its end when the cut fires is cut at once, however much of + /// it has come. + #[tokio::test] + async fn a_body_read_to_its_end_is_never_cut_and_one_not_yet_is() { + use futures_util::StreamExt; + let gate = Arc::new(Gate::default()); + // Whole: every byte read to the end, then the cut. + let inside = gate.enter().unwrap(); + let (tx, body) = fed(); + let (request, whole) = inside.arriving(axum::extract::Request::new(body)); + let mut data = request.into_body().into_data_stream(); + tx.send(vec![1, 2, 3]).await.unwrap(); + assert_eq!(data.next().await.unwrap().unwrap().len(), 3); + drop(tx); + assert!(data.next().await.is_none()); + gate.cut_unfinished(); + assert!(!whole.was_cut(), "a body read to its end was cut"); + // Asked again after the cut: still the end, not a cut. + assert!(data.next().await.is_none()); + assert!(!whole.was_cut()); + drop(inside); + // Not whole: part of it came, the cut fires, the next read fails + // (a gate's cut is for good: this is another book's). + let gate = Arc::new(Gate::default()); + let inside = gate.enter().unwrap(); + let (tx, body) = fed(); + let (request, partial) = inside.arriving(axum::extract::Request::new(body)); + let mut data = request.into_body().into_data_stream(); + tx.send(vec![1, 2, 3]).await.unwrap(); + assert!(data.next().await.unwrap().is_ok()); + assert!(!partial.was_cut()); + gate.cut_unfinished(); + // More bytes are on their way, however quickly: cut all the same. + let _ = tx.try_send(vec![4, 5, 6]); + assert!(data.next().await.unwrap().is_err()); + assert!(partial.was_cut()); + drop(inside); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_close_waits_for_the_requests_inside_and_refuses_the_next() { + let home = tempfile::tempdir().unwrap(); + let books = books_in(home.path()); + create(&books, "acme"); + create(&books, "beta"); + let (_, acme) = token(&books, "acme", "agent"); + let (_, beta) = token(&books, "beta", "agent"); + let gate = match books.held().get("acme") { + Some(Book::Open { gate, .. }) => gate.clone(), + _ => panic!("acme isn't open"), + }; + let inside = gate.enter().expect("the door is open"); + let closing = tokio::spawn({ + let books = books.clone(); + async move { ask(&books, Request::CloseBook { id: "acme".into() }).await } + }); + // The door shuts as the close begins. + while gate.enter().is_some() { + tokio::time::sleep(Duration::from_millis(5)).await; + } + let (status, code, _) = at_the_door(&books, "acme", &acme).await.unwrap(); + assert_eq!((status, code.as_deref()), (503, Some("closed"))); + assert_eq!(at_the_door(&books, "beta", &beta).await, None); + // A negative window: it can only fail if the close was answered, + // never because the machine was slow. + tokio::time::sleep(Duration::from_millis(300)).await; + assert!(!closing.is_finished(), "closed with a request still inside"); + drop(inside); + assert_eq!(closing.await.unwrap(), closed("acme")); + } + + /// INVARIANT 3, 10: books left closed at the start are listed closed + /// and open when asked; the option takes all, none, or ids. + #[test] + fn the_books_open_at_the_start_are_chosen_by_option() { + assert_eq!(OpenAtStart::parse("all"), Ok(OpenAtStart::All)); + assert_eq!(OpenAtStart::parse("none"), Ok(OpenAtStart::Only(vec![]))); + assert_eq!( + OpenAtStart::parse("acme, beta"), + Ok(OpenAtStart::Only(vec!["acme".into(), "beta".into()])) + ); + assert!(OpenAtStart::parse("acme,../etc").is_err()); + assert!(OpenAtStart::parse("").is_err()); + let acme = BookId::parse("acme").unwrap(); + assert!(OpenAtStart::All.wants(&acme)); + assert!(!OpenAtStart::Only(vec![]).wants(&acme)); + assert!(OpenAtStart::Only(vec!["acme".into()]).wants(&acme)); + } + + /// INVARIANT 12: the live sessions of each open book, as the server + /// knows them: the token's NAME, the client, the agent's report, the + /// calls, the last call; never the token; one that ended isn't listed; + /// and a book's sessions end with the book. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn the_sessions_request_says_who_is_connected_and_never_their_token() { + use axum::http::Method; + let home = tempfile::tempdir().unwrap(); + let books = books_in(home.path()); + create(&books, "acme"); + create(&books, "beta"); + let (_, agent) = token(&books, "acme", "agent"); + let sessions_of = |r: Response, book: &str| match r { + Response::Sessions(all) => { + all.into_iter() + .find(|b| b.book == book) + .unwrap_or_else(|| panic!("{book} isn't listed")) + .sessions + } + other => panic!("{other:?}"), + }; + assert!(sessions_of(ask(&books, Request::Sessions).await, "acme").is_empty()); + let r = send_mcp( + &books, + mcp_request(Method::POST, &agent, None, initialize()), + ) + .await; + let sid = r.headers()[SESSION_HEADER].to_str().unwrap().to_string(); + let (status, _, said) = answer(r).await; + assert_eq!(status, 200, "{said}"); + let r = send_mcp( + &books, + mcp_request( + Method::POST, + &agent, + Some(&sid), + serde_json::json!({"jsonrpc": "2.0", "method": "notifications/initialized"}), + ), + ) + .await; + assert!(answer(r).await.0 < 300); + // Who the client is, from `initialize`, before it has made a call. + // (The notification is handled by the session's task, a moment + // after it was accepted.) + let mut early = sessions_of(ask(&books, Request::Sessions).await, "acme"); + for _ in 0..100 { + if early.iter().all(|s| s.client_name.is_some()) { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + early = sessions_of(ask(&books, Request::Sessions).await, "acme"); + } + assert_eq!(early.len(), 1, "{early:?}"); + assert_eq!(early[0].client_name.as_deref(), Some("test"), "{early:?}"); + assert!(early[0].last.is_none() && early[0].agent.is_none()); + for body in [ + serde_json::json!({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { + "name": "books.start", + "arguments": {"agent": {"model": "m-1", "harness": "h-1"}}}}), + ] { + let r = send_mcp(&books, mcp_request(Method::POST, &agent, Some(&sid), body)).await; + let (status, _, said) = answer(r).await; + assert!((200..300).contains(&status), "{status}: {said}"); + } + let listed = ask(&books, Request::Sessions).await; + let text = serde_json::to_string(&listed).unwrap(); + assert!(!text.contains(&agent), "a token's text is never listed"); + let sessions = sessions_of(listed, "acme"); + assert_eq!(sessions.len(), 1, "{sessions:?}"); + let s = &sessions[0]; + assert_eq!(s.token, "agent"); + assert_eq!( + (s.client_name.as_deref(), s.client_version.as_deref()), + (Some("test"), Some("0")) + ); + let said = s.agent.as_ref().expect("the agent's self-report"); + assert_eq!( + (said.model.as_deref(), said.harness.as_deref()), + (Some("m-1"), Some("h-1")) + ); + assert_eq!(s.running, 0); + let last = s.last.as_ref().expect("a last call"); + assert_eq!( + (last.tool.as_str(), last.outcome.as_str()), + ("books.start", "ok") + ); + assert!(s.connected_at.ends_with('Z'), "{}", s.connected_at); + assert!(sessions_of(ask(&books, Request::Sessions).await, "beta").is_empty()); + + // Ended: not listed. + let r = send_mcp( + &books, + mcp_request(Method::DELETE, &agent, Some(&sid), serde_json::json!({})), + ) + .await; + assert!(answer(r).await.0 < 300); + assert!(sessions_of(ask(&books, Request::Sessions).await, "acme").is_empty()); + + // Closed with the book: a session that was open is gone, and the + // reopened book has none. + let r = send_mcp( + &books, + mcp_request(Method::POST, &agent, None, initialize()), + ) + .await; + let again = r.headers()[SESSION_HEADER].to_str().unwrap().to_string(); + assert_eq!(answer(r).await.0, 200); + assert_eq!(bound(&books), std::slice::from_ref(&again)); + assert_eq!( + ask(&books, Request::CloseBook { id: "acme".into() }).await, + closed("acme") + ); + assert!(bound(&books).is_empty()); + let list = Request::Sessions; + match ask(&books, list).await { + Response::Sessions(all) => { + assert!( + all.iter().all(|b| b.book != "acme"), + "closed books list none" + ) + } + other => panic!("{other:?}"), + } + assert_eq!( + ask(&books, Request::OpenBook { id: "acme".into() }).await, + opened("acme", admin::OpenOutcome::Opened) + ); + assert!(sessions_of(ask(&books, Request::Sessions).await, "acme").is_empty()); + // The old session id isn't one of the reopened book's. + let r = send_mcp( + &books, + mcp_request( + Method::POST, + &agent, + Some(&again), + serde_json::json!({"jsonrpc": "2.0", "id": 9, "method": "tools/list"}), + ), + ) + .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/crates/ledger-mcp/src/local/fuzz_door.rs b/crates/ledger-mcp/src/local/fuzz_door.rs index ffa2b344..30e7e98d 100644 --- a/crates/ledger-mcp/src/local/fuzz_door.rs +++ b/crates/ledger-mcp/src/local/fuzz_door.rs @@ -28,22 +28,12 @@ impl FuzzDoor { let home = tempfile::tempdir().expect("a folder"); let (root, _) = Root::setup(home.path(), Some(&home.path().join("root")), None).expect("a data root"); - let books = Arc::new(Books { + let books = Arc::new(Books::new( root, - held: RwLock::new(BTreeMap::new()), - sessions: CancellationToken::new(), - closing: CancellationToken::new(), - in_flight: AtomicUsize::new(0), - finished: tokio::sync::Notify::new(), - last_arrival: std::sync::atomic::AtomicU64::new(0), - started: Instant::now(), - principals: RwLock::new(Err(String::new())), - session_tokens: Mutex::new(BTreeMap::new()), - backup_quiet: BACKUP_QUIET, - drill_first: DRILL_FIRST, - restoring: Mutex::new(()), - isolation: Isolation::SameUser, - }); + BACKUP_QUIET, + DRILL_FIRST, + Isolation::SameUser, + )); let loaded = books.load_principals(); *books.principals.write().unwrap() = loaded; match books.admin(Request::Create { diff --git a/crates/ledger-mcp/src/server.rs b/crates/ledger-mcp/src/server.rs index 7e2d51f5..50018111 100644 --- a/crates/ledger-mcp/src/server.rs +++ b/crates/ledger-mcp/src/server.rs @@ -74,6 +74,8 @@ pub struct BooksServer { exports: ledger_store::exports::Exports, /// The books' backups (backup.rs). backups: Arc, + /// Who is connected, and what each is doing (sessions.rs). + board: Arc, /// How these books are kept from agents (plan 3.8, P9a): what /// `books.start` reports. isolation: Isolation, @@ -128,6 +130,8 @@ pub(crate) struct Served { pub(crate) uploads: ledger_store::uploads::Uploads, pub(crate) exports: ledger_store::exports::Exports, pub(crate) backups: Arc, + /// Its live sessions' board (sessions.rs), read by the admin socket. + pub(crate) board: Arc, pub(crate) isolation: Isolation, } @@ -178,6 +182,7 @@ impl Served { uploads, exports, backups, + board: Arc::default(), isolation, }) } @@ -208,6 +213,11 @@ pub struct SharedStore { stopped: std::sync::atomic::AtomicBool, /// Closing: no new request runs (INVARIANT 3). closing: std::sync::atomic::AtomicBool, + /// A close of these books has begun (`hurry`): a call that can run + /// long (a verification, a backup asked for, a package of every stored + /// file) stops at its next look, answering that it was stopped. Shared + /// with the books' backups (backup.rs), whose git it stops. + hurry: Arc, /// Requests running (from before their blocking task to its end). running: std::sync::atomic::AtomicUsize, /// Woken whenever one ends. @@ -305,6 +315,7 @@ impl SharedStore { store: tokio::sync::Mutex::new(Some(store)), stopped: std::sync::atomic::AtomicBool::new(false), closing: std::sync::atomic::AtomicBool::new(false), + hurry: Arc::default(), running: std::sync::atomic::AtomicUsize::new(0), ended: tokio::sync::Notify::new(), }) @@ -329,6 +340,23 @@ impl SharedStore { self.closing.load(std::sync::atomic::Ordering::SeqCst) } + /// A close of these books begins: every call and job that can run long + /// stops at its next look (local.rs INVARIANT 10). + pub fn hurry(&self) { + self.hurry.store(true, std::sync::atomic::Ordering::SeqCst); + } + + /// Whether a close of these books has begun. + pub fn hurried(&self) -> bool { + self.hurry.load(std::sync::atomic::Ordering::SeqCst) + } + + /// The stop flag itself, for what looks at it from another thread or + /// hands it to git (ledger_store `cancel`, `Git::with_cancel`). + pub fn hurry_flag(&self) -> Arc { + self.hurry.clone() + } + fn stopped(&self) -> bool { self.stopped.load(std::sync::atomic::Ordering::SeqCst) } @@ -352,6 +380,18 @@ impl SharedStore { /// What every request gets after an internal error (SharedStore /// INVARIANT 2). +/// What a call that a close stopped is told (local.rs INVARIANT 10): it +/// was stopped, because the books are closing, and nothing it was doing +/// is recorded as done. +pub(crate) const STOPPED_BY_CLOSE_WORDS: &str = "this call was stopped because the books are closing: nothing it was doing is recorded as done. Open the books again, then ask again"; + +/// The words of a call a close stopped, and the mark that its access record +/// says so (`refused: stopped_by_close`): returned as the call's error. +pub(crate) fn stopped_by_close() -> String { + STOPPED_BY_CLOSE.with(|s| s.set(true)); + STOPPED_BY_CLOSE_WORDS.to_string() +} + pub(crate) const STOPPED: &str = "the books server stopped taking requests after an internal error, to protect the books: ask the human to restart the books server (the books are checked again when it starts)"; /// The store, locked for one stretch of synchronous work. Not `Send`, so @@ -547,6 +587,7 @@ impl BooksServer { uploads: served.uploads.clone(), exports: served.exports.clone(), backups: served.backups.clone(), + board: served.board.clone(), isolation: served.isolation, } } @@ -1379,6 +1420,9 @@ thread_local! { /// The journal's head after the last write made by the request /// running on this thread (StoreGuard's drop), for its access record. static WROTE: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + /// Whether the request running on this thread was stopped by a close + /// (`stopped_by_close`), for its access record. + static STOPPED_BY_CLOSE: std::cell::Cell = const { std::cell::Cell::new(false) }; /// Who the request running on this thread is, as `books.start` shows /// it: `{principal, kind, scopes, client_id}`. The token's own facts /// and the client's name; set at the start of the request. @@ -1744,7 +1788,7 @@ impl ServerHandler for BooksServer { ) -> Result { use crate::access::{self, Call}; use ledger_store::access::Outcome; - let mut call = Call::new(&self.access, &context, "tool", &request.name); + let mut call = Call::new(&self.access, &self.board, &context, "tool", &request.name); let outcome_of = |out: &Result| match out { Ok(rmcp::model::CallToolResponse::Complete(r)) if r.is_error != Some(true) => { Outcome::Ok @@ -1837,6 +1881,7 @@ impl ServerHandler for BooksServer { let result = run_blocking(&self.store, move || { Box::pin(async move { WROTE.with(|w| w.borrow_mut().take()); + STOPPED_BY_CLOSE.with(|s| s.set(false)); ARGS.with(|a| *a.borrow_mut() = request.arguments.clone()); let caller = running_call .caller() @@ -1889,7 +1934,14 @@ impl ServerHandler for BooksServer { let mut c = running_call; c.digested(digest); c.with_agent(AGENT_NOTE.with(|a| a.borrow_mut().take())); - let recorded = c.record_blocking(outcome_of(&out), wrote); + // A call a close stopped is on record as stopped, not as an + // answer it gave (local.rs INVARIANT 10). + let outcome = if STOPPED_BY_CLOSE.with(|s| s.replace(false)) { + Outcome::Refused(access::STOPPED_BY_CLOSE.into()) + } else { + outcome_of(&out) + }; + let recorded = c.record_blocking(outcome, wrote); (out, recorded) }) }) @@ -1944,6 +1996,23 @@ impl ServerHandler for BooksServer { }) } + /// The client has said who it is: the session's board (sessions.rs) + /// knows it before the session's first call. + async fn on_initialized(&self, context: rmcp::service::NotificationContext) { + if let (Some(sid), Some(info)) = ( + crate::access::session_of(&context.extensions), + context.peer.peer_info(), + ) { + self.board.initialized( + &sid, + ledger_store::access::Client { + name: info.client_info.name.clone(), + version: info.client_info.version.clone(), + }, + ); + } + } + fn get_info(&self) -> ServerConfig { // A client connecting after a settings change sees the change // (never waiting for the books here; a request holding them syncs @@ -2011,7 +2080,13 @@ impl ServerHandler for BooksServer { use ledger_store::access::Outcome; // Reading a resource is reading the books: books:read, recorded // (access.rs). - let call = Call::new(&self.access, &context, "resource", &request.uri); + let call = Call::new( + &self.access, + &self.board, + &context, + "resource", + &request.uri, + ); let result = self.resource(request, &call).await; { let outcome = match &result { diff --git a/crates/ledger-mcp/src/server_tests.rs b/crates/ledger-mcp/src/server_tests.rs index 28b6a973..c5faa94a 100644 --- a/crates/ledger-mcp/src/server_tests.rs +++ b/crates/ledger-mcp/src/server_tests.rs @@ -1454,6 +1454,7 @@ fn an_access_record_that_cant_be_written_stops_the_books_and_says_so() { let (server, _books) = unwritable("unrecorded-refusal"); let call = crate::access::Call::new( &server.access, + &server.board, &context(&s.peer, Some(ALL)), "tool", "books.chart", diff --git a/crates/ledger-mcp/src/sessions.rs b/crates/ledger-mcp/src/sessions.rs new file mode 100644 index 00000000..58959997 --- /dev/null +++ b/crates/ledger-mcp/src/sessions.rs @@ -0,0 +1,224 @@ +//! Who is connected to a book right now: the in-memory board of one +//! book's live MCP sessions (plan/p15-app-and-relay.md 3.1, D-77). +//! +//! ```text +//! GOAL: the app can say, for each open book, which assistants are +//! connected and what each is doing, without reading the access log +//! back and without ever holding a token. +//! SOURCE: plan/p15-app-and-relay.md 3.1 (the sessions request: client name +//! and version, the token's name, in-flight calls, the last tool +//! and when); D-77 (the app is the host); D-78 (one tab per +//! company: a connection names its company). +//! INVARIANTS: +//! 1. The board holds what the client and the agent SAID of themselves +//! (asserted, never checked), each masked of any full TIN and cut to +//! the access log's own limit (ledger_store::access::asserted); never +//! a token, its text or its hash. +//! 2. A call is counted as running from the moment it is made until its +//! blocking work and its record are done, even if its client hung +//! up (the count rides in the call, as the store's own does). +//! 3. A session that ended is not listed: the board is read only for +//! the sessions the server still binds (local.rs `session_tokens`), +//! and a note for another is dropped. +//! 4. Nothing here is durable: a restarted server knows no session, as +//! its clients know theirs ended. +//! ``` + +use ledger_store::access::{Agent, Client, Outcome, asserted}; +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +/// What one session has said and done. +#[derive(Clone, Debug, Default)] +pub(crate) struct Note { + /// The client program, as it named itself at `initialize`. + pub client: Option, + /// What the agent said about itself, the latest time it did. + pub agent: Option, + /// Calls running now (INVARIANT 2). + pub running: usize, + /// The last call that finished: its tool (or resource), what came of + /// it, and when (seconds since the epoch, UTC). + pub last: Option, +} + +/// A call that finished. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Last { + /// The tool's name, or the resource's address. + pub subject: String, + /// What came of it. + pub outcome: Outcome, + /// When (seconds since the epoch, UTC). + pub at: i64, +} + +/// One book's live sessions' notes, by MCP session id. +#[derive(Default)] +pub(crate) struct Board { + notes: Mutex>, +} + +/// A call running (INVARIANT 2): counted while it lives. +pub(crate) struct Live { + board: Arc, + sid: String, +} + +impl Drop for Live { + fn drop(&mut self) { + let mut notes = self.board.notes(); + if let Some(note) = notes.get_mut(&self.sid) { + note.running = note.running.saturating_sub(1); + } + } +} + +fn client_of(client: Client) -> Client { + Client { + name: asserted(&client.name), + version: asserted(&client.version), + } +} + +fn agent_of(agent: Agent) -> Agent { + Agent { + model: agent.model.as_deref().map(asserted), + reasoning_effort: agent.reasoning_effort.as_deref().map(asserted), + harness: agent.harness.as_deref().map(asserted), + } +} + +impl Board { + fn notes(&self) -> std::sync::MutexGuard<'_, HashMap> { + self.notes.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// The session `sid` said who its client is (`initialize`). + pub fn initialized(&self, sid: &str, client: Client) { + self.notes().entry(sid.to_string()).or_default().client = Some(client_of(client)); + } + + /// A call of `sid` began (INVARIANT 2). + pub fn begin(self: &Arc, sid: &str) -> Live { + self.notes().entry(sid.to_string()).or_default().running += 1; + Live { + board: self.clone(), + sid: sid.to_string(), + } + } + + /// A call of `sid` is done and recorded: what it was, what came of + /// it, and what its client and agent said, if they did. + pub fn finished( + &self, + sid: &str, + subject: &str, + outcome: &Outcome, + client: Option<&Client>, + agent: Option<&Agent>, + at: i64, + ) { + let mut notes = self.notes(); + let note = notes.entry(sid.to_string()).or_default(); + if let Some(client) = client { + note.client = Some(client_of(client.clone())); + } + if let Some(agent) = agent { + note.agent = Some(agent_of(agent.clone())); + } + note.last = Some(Last { + subject: asserted(subject), + outcome: outcome.clone(), + at, + }); + } + + /// The session `sid` ended. + pub fn forget(&self, sid: &str) { + self.notes().remove(sid); + } + + /// The notes of the sessions `live` still names, and no other + /// (INVARIANT 3): the others are dropped. + pub fn snapshot(&self, live: &[String]) -> HashMap { + let mut notes = self.notes(); + notes.retain(|sid, note| note.running > 0 || live.contains(sid)); + live.iter() + .map(|sid| (sid.clone(), notes.get(sid).cloned().unwrap_or_default())) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn client(name: &str) -> Client { + Client { + name: name.into(), + version: "1.2".into(), + } + } + + #[test] + fn a_call_counts_as_running_until_its_guard_is_dropped() { + let board = Arc::new(Board::default()); + let (a, b) = (board.begin("s1"), board.begin("s1")); + assert_eq!(board.snapshot(&["s1".into()])["s1"].running, 2); + drop(a); + assert_eq!(board.snapshot(&["s1".into()])["s1"].running, 1); + drop(b); + assert_eq!(board.snapshot(&["s1".into()])["s1"].running, 0); + } + + #[test] + fn the_last_call_and_what_the_client_said_are_kept_and_masked() { + let board = Board::default(); + board.initialized("s1", client("Claude Code")); + board.finished( + "s1", + "books.chart", + &Outcome::Ok, + Some(&client("Claude Code 123-45-6789")), + Some(&Agent { + model: Some("m".into()), + reasoning_effort: None, + harness: Some("h".into()), + }), + 100, + ); + board.finished( + "s1", + "books.trial_balance", + &Outcome::Error, + None, + None, + 200, + ); + let note = &board.snapshot(&["s1".into()])["s1"]; + let said = note.client.as_ref().unwrap(); + assert!(!said.name.contains("6789"), "a TIN is masked: {said:?}"); + assert_eq!(note.agent.as_ref().unwrap().model.as_deref(), Some("m")); + assert_eq!( + note.last, + Some(Last { + subject: "books.trial_balance".into(), + outcome: Outcome::Error, + at: 200 + }) + ); + } + + #[test] + fn a_session_that_ended_is_not_listed_and_its_note_is_dropped() { + let board = Board::default(); + board.initialized("gone", client("x")); + board.initialized("kept", client("y")); + let listed = board.snapshot(&["kept".into()]); + assert_eq!(listed.keys().collect::>(), vec!["kept"]); + assert!(board.notes().get("gone").is_none()); + board.forget("kept"); + assert!(board.notes().is_empty()); + } +} diff --git a/crates/ledger-mcp/src/tools/backup.rs b/crates/ledger-mcp/src/tools/backup.rs index d4bce093..28a6b2f5 100644 --- a/crates/ledger-mcp/src/tools/backup.rs +++ b/crates/ledger-mcp/src/tools/backup.rs @@ -111,11 +111,15 @@ impl BooksServer { &self, params: Parameters, ) -> Result, String> { - Ok(Json( - self.backups - .run_with("asked", params.0.new_disk) - .await? - .into(), - )) + // Stopped by a close (backup.rs INVARIANT 11): said so, and on + // record as stopped, not as an answer it gave. + match self.backups.run_with("asked", params.0.new_disk).await { + Ok(status) => Ok(Json(status.into())), + Err(why) if why.starts_with(crate::server::STOPPED_BY_CLOSE_WORDS) => { + crate::server::stopped_by_close(); + Err(why) + } + Err(why) => Err(why), + } } } diff --git a/crates/ledger-mcp/src/tools/reports.rs b/crates/ledger-mcp/src/tools/reports.rs index 8e411d63..2a3bb2f0 100644 --- a/crates/ledger-mcp/src/tools/reports.rs +++ b/crates/ledger-mcp/src/tools/reports.rs @@ -266,6 +266,16 @@ fn cash_flow_csv(stmt: &ledger_core::CashFlowStatement) -> String { csv } +/// A store error as a call's answer: one that is a close's stop is said so, +/// and marks the call's access record (server.rs `stopped_by_close`). +fn stoppable(e: ledger_store::StoreError) -> String { + if matches!(e, ledger_store::StoreError::Cancelled) { + crate::server::stopped_by_close() + } else { + e.to_string() + } +} + #[tool_router(router = reports_router, vis = "pub(super)")] impl BooksServer { #[tool( @@ -707,10 +717,16 @@ impl BooksServer { ) )] async fn verify(&self, params: Parameters) -> Result, String> { + self.backups.hold("books.verify"); let mut store = self.lock()?; - let report = store.verify_and_heal().map_err(|e| e.to_string())?; + // The replay and the hashing of every stored file are looked at + // once per journal line and per file: a close stops them + // (local.rs INVARIANT 10). Healing a drifted database is begun only + // if no stop was asked for before it, and then finishes. + let _stop = ledger_store::cancel::scope(self.store.hurry_flag()); + let report = store.verify_and_heal().map_err(stoppable)?; let blobs = if params.0.blobs { - Some(store.verify_blobs().map_err(|e| e.to_string())?) + Some(store.verify_blobs().map_err(stoppable)?) } else { None }; @@ -1126,7 +1142,32 @@ impl BooksServer { /// 3. A locked vault or a missing TIN never fails the package: the /// row says why (vault_tin), the README lists it, and so does /// tin_gaps (members, and 1099 payees that are reportable). - /// 4. Read-only: nothing is journaled. + /// 4. Nothing is journaled but the decisions an override records (a + /// reason for exporting without an audit, a reason for exporting + /// with open drafts), and only once the package is certain to be + /// made. Every refusal that can be known from the books as they + /// stand is decided first: the two named ones (the audit, the open + /// drafts) and every one the build itself can make (a member's + /// unknown capital account, a report that can't be built), by + /// running the build once, read-only and in memory, before the + /// decision is journaled (without the stored files and the vault, + /// which a machine fails at, not the books). So a package refused + /// for what the books say journals nothing, on every retry. What + /// can still fail after a decision is journaled is only a failure + /// of the machine (the disk reading a stored file, memory, the + /// hand-over); the decision is then on record, with the reason in + /// the access log, and a later export that succeeds records its + /// own. The decisions stay ahead of the build because the + /// package describes the books it is made from, itself included: + /// its README and every report's footer carry the journal's event + /// count at the build (ledger_package::package, report_meta), which + /// counts the decisions. A close that has begun is looked for once, + /// immediately before the first decision is journaled: it refuses + /// then, journaling nothing. From the journaling to the hand-over + /// nothing looks at the close's stop (the build is no longer + /// stoppable, local.rs INVARIANT 10), so a decision on record is a + /// package handed over, unless the machine fails, which a close + /// cannot make it do. /// ``` #[tool( name = "books.export_cpa_package", @@ -1144,7 +1185,11 @@ impl BooksServer { ) -> Result, String> { let p = params.0; let as_of = self.as_of(p.as_of.as_deref())?; + self.backups.hold("books.export_cpa_package"); let mut store = self.lock()?; + // The decisions an override records, journaled below only once every + // refusal has been decided (INVARIANT 4). + let mut decisions: Vec = Vec::new(); // A package no counted audit stands behind is not final either // (plan P8, D-9): on books that declared `audits`, refused under // policy.cpa_package_requires_audit = refuse unless a reason is @@ -1174,20 +1219,18 @@ impl BooksServer { let by = CALLER .with(|c| c.borrow().as_ref().map(|(_, name)| name.clone())) .unwrap_or_else(|| ledger_store::auth::DEFAULT_NAME.to_string()); - store - .record_decision(&ledger_core::conventions::NewDecision { - subject: format!("CPA package as of {as_of} without a counted audit"), - decision_md: format!( - "The CPA package as of {as_of} was exported without an audit at the books' current head attested at the bar. Reason: {reason}" - ), - decided_by: vec![by], - decided_on: today(), - evidence_attachment: None, - supersedes: None, - citation: None, - projects: Vec::new(), - }) - .map_err(|e| e.to_string())?; + decisions.push(ledger_core::conventions::NewDecision { + subject: format!("CPA package as of {as_of} without a counted audit"), + decision_md: format!( + "The CPA package as of {as_of} was exported without an audit at the books' current head attested at the bar. Reason: {reason}" + ), + decided_by: vec![by], + decided_on: today(), + evidence_attachment: None, + supersedes: None, + citation: None, + projects: Vec::new(), + }); } else { audit_warning = Some(format!( "No counted audit stands behind this package: {why}." @@ -1224,23 +1267,71 @@ impl BooksServer { let by = CALLER .with(|c| c.borrow().as_ref().map(|(_, name)| name.clone())) .unwrap_or_else(|| ledger_store::auth::DEFAULT_NAME.to_string()); - store - .record_decision(&ledger_core::conventions::NewDecision { - subject: format!("CPA package as of {as_of} with open drafts"), - decision_md: format!( - "The CPA package as of {as_of} was exported with {} draft(s) open: {}. Reason: {}", - open_drafts.len(), - named.join("; "), - allow.reason.trim() - ), - decided_by: vec![by], - decided_on: today(), - evidence_attachment: None, - supersedes: None, - citation: None, - projects: Vec::new(), - }) - .map_err(|e| e.to_string())?; + decisions.push(ledger_core::conventions::NewDecision { + subject: format!("CPA package as of {as_of} with open drafts"), + decision_md: format!( + "The CPA package as of {as_of} was exported with {} draft(s) open: {}. Reason: {}", + open_drafts.len(), + named.join("; "), + allow.reason.trim() + ), + decided_by: vec![by], + decided_on: today(), + evidence_attachment: None, + supersedes: None, + citation: None, + projects: Vec::new(), + }); + } + // Every refusal the build can make from the books as they stand is + // decided before a decision goes on record (INVARIANT 4): the build + // is run once, in memory, to see that it will succeed. It is + // read-only (ledger_package INVARIANT 5: it takes the books by + // shared reference and writes nowhere, and it leaves its result to + // be dropped), so it changes nothing. It leaves out what only the + // machine can fail at: the stored files (include_receipts false) and + // the vault (no TIN source: a TIN it can't give never fails a + // package, ledger_package INVARIANT 3). A close that begins during + // it stops it, before anything is journaled. + if !decisions.is_empty() { + let _stop = ledger_store::cancel::scope(self.store.hurry_flag()); + ledger_package::build_package( + &*store, + &package_settings(&self.settings()), + &ledger_package::PackageRequest { + as_of, + prepared_on: today(), + cash_accounts: &p.cash_accounts, + financing_accounts: &p.financing_accounts, + investing_accounts: &p.investing_accounts, + include_receipts: false, + tins: None, + }, + ) + .map_err(|e| { + if e == ledger_store::StoreError::Cancelled.to_string() { + crate::server::stopped_by_close() + } else { + e + } + })?; + } + // The decisions go on record now, ahead of the build (the package + // counts them: INVARIANT 4), and the close is looked for once more, + // immediately before the first: past it the package is made + // whatever a close does. + let journaled = !decisions.is_empty(); + if journaled { + if self.store.hurried() { + return Err(crate::server::stopped_by_close()); + } + for decision in &decisions { + store.record_decision(decision).map_err(|e| e.to_string())?; + } + // The test knob's seam (`--timer-hold`, `call:books.export_cpa_ + // package:journaled`): a close that begins here must not stop + // the build. + self.backups.hold("books.export_cpa_package:journaled"); } let book = book_name(&store); // The vault, opened once and never creating a key: locked, each @@ -1251,7 +1342,13 @@ impl BooksServer { .as_ref() .map(|vault| move |id| vault_tin(ledger, vault, id)); // Built from the books under the lock, written nowhere - // (ledger_package INVARIANT 1). + // (ledger_package INVARIANT 1). Every stored file it holds is read + // one at a time, and a close stops it between two (local.rs + // INVARIANT 10). + // Not once a decision is journaled for it (INVARIANT 4): then it runs + // to the hand-over, which local.rs INVARIANT 10 names as a call a + // close does not stop. + let _stop = (!journaled).then(|| ledger_store::cancel::scope(self.store.hurry_flag())); let package = ledger_package::build_package( &*store, &package_settings(&self.settings()), @@ -1264,7 +1361,15 @@ impl BooksServer { include_receipts: p.include_receipts, tins: tins.as_ref().map(|f| f as ledger_package::TinSource<'_>), }, - )?; + ) + .map_err(|e| { + if e == ledger_store::StoreError::Cancelled.to_string() { + crate::server::stopped_by_close() + } else { + e + } + })?; + drop(_stop); let vault_dir = if p.include_tins { self.tin_record_dir(&store)? } else { diff --git a/crates/ledger-package/src/package.rs b/crates/ledger-package/src/package.rs index 00307d67..11d1eefc 100644 --- a/crates/ledger-package/src/package.rs +++ b/crates/ledger-package/src/package.rs @@ -126,6 +126,8 @@ pub fn build_package( req: &PackageRequest<'_>, ) -> Result { use ledger_import::{XlsxReport, report, report_to_xlsx, statement_pdf}; + // A stop asked for before any of the work (the books server's close). + ledger_store::cancel::check().map_err(|e| e.to_string())?; let company = settings.company; let (as_of, today) = (req.as_of, req.prepared_on); let meta = report_meta(company, req.prepared_on, books.journal_seq()); @@ -490,6 +492,10 @@ pub fn build_package( }; let mut index = String::from("entry_id,date,description,amount,file,sha256\n"); for a in books.all_attachments().map_err(|e| e.to_string())? { + // A stop asked for (the books server's close) is looked at once + // per stored file read: a package of many files isn't held to + // its end by it (ledger_store::cancel). + ledger_store::cancel::check().map_err(|e| e.to_string())?; if a.withdrawn_at.is_some() { continue; } diff --git a/crates/ledger-store/src/access.rs b/crates/ledger-store/src/access.rs index ac0282b7..57cf7f95 100644 --- a/crates/ledger-store/src/access.rs +++ b/crates/ledger-store/src/access.rs @@ -19,6 +19,12 @@ //! name and version, a request id, the tool or resource it named) //! has any full TIN masked and is then cut to 64 characters. //! 3. Records go in one at a time, in the order they are made. +//! 4. A log can be closed (`close`, under the lock every record goes in +//! under): a record whose append began before it is whole, one after +//! it is refused (`ChainError::Closed`), unwritten. So a record +//! still on its way when its book is let go (a refusal written late) +//! never reaches the file, nor, once the book is opened again, the +//! new log's chain. //! ``` use crate::chain::{self, ChainError, ChainLog, Head}; @@ -220,6 +226,12 @@ impl AccessLog { log.append(fields).map(|(_, head)| head) } + /// Take no more records, ever (INVARIANT 4): waits for the record + /// being appended, if one is. + pub fn close(&self) { + self.log.lock().unwrap_or_else(|e| e.into_inner()).close(); + } + /// Where the log ends now. pub fn head(&self) -> Head { self.log @@ -289,6 +301,30 @@ mod tests { } } + /// A closed log takes no more records (INVARIANT 4): a handle kept from + /// before a close can't append after the log is opened again, which + /// would break the new log's chain. + #[test] + fn a_closed_log_writes_nothing_and_a_reopened_one_stays_whole() { + let dir = tempfile::tempdir().unwrap(); + let old = AccessLog::open(dir.path()).unwrap(); + old.record(&access(1)).unwrap(); + old.close(); + let file = || std::fs::read(dir.path().join(ACCESS_FILE)).unwrap(); + let at_close = file(); + assert_eq!(old.record(&access(2)), Err(ChainError::Closed)); + assert_eq!(file(), at_close, "a closed log wrote"); + // The book is opened again: a new log, against its own head. + let new = AccessLog::open(dir.path()).unwrap(); + new.record(&access(3)).unwrap(); + // The old handle, used late, writes nothing. + assert_eq!(old.record(&access(4)), Err(ChainError::Closed)); + new.record(&access(5)).unwrap(); + let (back, head) = read(dir.path()).unwrap(); + assert_eq!(back.len(), 3); + assert_eq!(head.seq, 3); + } + #[test] fn records_read_back_as_written() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ledger-store/src/backup.rs b/crates/ledger-store/src/backup.rs index 6117675a..f1a83e7b 100644 --- a/crates/ledger-store/src/backup.rs +++ b/crates/ledger-store/src/backup.rs @@ -48,7 +48,76 @@ //! that says nothing for GIT_TIMEOUT is stopped with all it started. //! What git said of itself is kept in whole lines; callers hide the //! paths in it before an agent sees it (ledger-mcp backup.rs, -//! root.rs). +//! root.rs). None of ours starts another git to go on after it ends +//! (`gc.auto=0`, `maintenance.auto=false`): when a git of ours has +//! ended, nothing it began is still working. +//! 5. A git that is stopped (cancelled, or silent for GIT_TIMEOUT) is +//! stopped gently: SIGTERM to its whole process group first (git +//! removes the lock files it holds when it is sent one, and a push's +//! receiving end the objects it had not yet kept), up to TERM_GRACE +//! (5 s: git's handler takes milliseconds, so the grace is only for a +//! machine too loaded to schedule it) for the group to end, and only +//! then SIGKILL. So a lock left behind is the rare case, and there is +//! nothing to clean up in the usual one. (Windows has no signal to +//! send a group: the nearest thing the code has, `taskkill /T /F`, +//! ends the tree at once, and the rules below cover what is left.) +//! Once the stopped command is reaped AND every process it started is +//! gone (a killed process can still take a lock in its last +//! instructions, so the process group is waited for, GROUP_GONE_WAIT, +//! and nothing is looked at as left over while it isn't), the locks in +//! the repositories that command could write are dealt with, each +//! noted ([`LockNote`], for the caller's record). Each repository is +//! looked at as the command begins (its folder opened once, the locks +//! already there listed); "ours" is a lock that wasn't there then. +//! (A stopped `init` of the archive, or of a folder target's new +//! repository, is such a command too: its HEAD lock is dealt with +//! the same way.) +//! a. The book's own archive (`archive.git` in the book's folder, +//! private to this program): the locks of ours are removed once +//! the group is gone, each noted. Nothing else is removed from +//! it in a stop. At open (`clear_archive_locks`), and when a +//! backup begins, only a lock older than ARCHIVE_STALE (10 +//! minutes) is removed, each removal noted; a younger one is +//! left (the next backup tries again, and removes it once it is +//! old). Running git by hand inside the archive is unsupported: +//! only the store lock keeps another wanderbooks process out, and +//! what protects the archive from one that doesn't is that this +//! code never removes a lock younger than ARCHIVE_STALE except +//! one that its own stopped git made (a lock a person's git +//! holds that long is the person's to deal with). +//! b. A target on this computer (a folder, or a repository named by +//! a path): its git is our `receive-pack`, a child of the one +//! stopped. This program NEVER writes to, or deletes from, a +//! folder that is the owner's (an external disk, a synced folder +//! such as Syncthing's, shared with other computers and other +//! gits): only git itself does. A lock git left there when it +//! had to be killed, that wasn't there when the push began, is +//! left in place and reported with its whole path: a note +//! (`lock_left`), and [`BackupError::LockLeft`], which marks the +//! target's backup failed and names the files and what the owner +//! may do (remove them, only when nothing else is using the +//! backup folder). A lock that was there when the push began is +//! another's: untouched, and not named. A later backup that finds +//! the lock gone goes on normally. A repository far away (ssh, +//! https) is never looked at: its receiving end cleans up when +//! the connection ends. +//! c. No removal follows a path. A removal goes through the folder +//! handle opened and verified once, when the command began (it is +//! the archive in the book's folder, not a link; git_locks), never +//! follows a link, and removes only a regular file named as git +//! names its locks, in the places git puts them. +//! 6. A step that has to end when the books are let go (the caller's +//! cancel flag, [`Git::with_cancel`]) ends promptly, wherever it is, +//! and leaves nothing half-made: it looks for the flag between every +//! git command and phase of a verification (`clone`, `tree`, +//! `checkout`, `replay`, `verify`, `blobs`, `vault`, `prefix`), once +//! per file listed or hashed, once per chunk of the journal compared +//! and once per journal line replayed (cancel.rs); a git command +//! running is killed. A stopped drill or proof removes its scratch +//! clone (the one removal that is not itself stopped: it is as long +//! as the clone is big). The longest between two looks is one git +//! command's stop (SIGTERM and up to TERM_GRACE, then a kill, GROUP_GONE_WAIT, +//! and up to 10 s for its pipes), one journal line, one file, or one 64 KiB chunk. //! ``` use std::path::{Path, PathBuf}; @@ -65,8 +134,19 @@ pub const BACKED_UP: [&str; 5] = [ crate::root::KEYS_DIR, crate::access::ACCESS_FILE, ]; -/// The longest a git command may take before it is stopped. +/// The longest a git command may say nothing before it is stopped. pub const GIT_TIMEOUT: Duration = Duration::from_secs(300); +/// How long a git that is to be stopped is given, after SIGTERM, to end +/// (and so remove its own lock files) before its whole process group is +/// killed (INVARIANT 5). Git's handler takes milliseconds; the grace is for +/// a machine so loaded that the handler is slow to be scheduled. It is +/// generous on purpose: a lock left in the owner's folder costs the owner a +/// step by hand, while a longer grace costs only a git that ignores SIGTERM. +pub const TERM_GRACE: Duration = Duration::from_secs(5); +/// How old a lock in the book's own archive must be, at open and when a +/// backup begins, before it is taken for a dead git's (INVARIANT 5a): a +/// younger one is left, and the next backup tries again. +pub const ARCHIVE_STALE: Duration = Duration::from_secs(600); /// Why a backup couldn't be made, pushed or trusted. Never names a path of /// the data root (INVARIANT 4). @@ -82,6 +162,18 @@ pub enum BackupError { /// A git command ran past its time limit. #[error("git {0} took too long and was stopped")] TimedOut(String), + /// A git command stopped because the books it served were let go + /// ([`Git::with_cancel`]). + #[error("git {0} was stopped: the books are closing")] + Cancelled(String), + /// A git of ours was stopped while it was writing a backup folder (or a + /// repository on this computer), and left lock files there (every one + /// named, whole paths, separated by `, `), which this program never + /// removes from a place that is the owner's (INVARIANT 5b). + #[error( + "git was stopped while it was writing the backup, and left lock files in your backup folder: {0}. This program doesn't remove files from your backup folder. Remove those files (only those), and only when nothing else is using the backup folder (another computer, a sync program, git run by hand); the next backup then goes on" + )] + LockLeft(String), /// A folder target that isn't there (an external disk not mounted). #[error("the backup folder isn't there (is its disk connected?)")] NoFolder, @@ -108,12 +200,58 @@ impl From for BackupError { } } +/// A lock file a git left, as it was dealt with (INVARIANT 5): for the +/// caller's own record of the backup (never names a path of the data root: +/// the repository is `archive`, or the target's kind, and the lock is +/// named from the repository's own folder). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LockNote { + /// `archive`, `folder` or `repository`. + pub repo: &'static str, + /// The lock, as a path in the repository (`index.lock`, + /// `refs/heads/main.lock`). + pub lock: String, + /// Removed (the archive's, made by the git just stopped), or left. + pub removed: bool, + /// Why: what ended the git that made it, or why it was left. + pub why: &'static str, + /// For a lock left in a folder that is the owner's: its whole path, the + /// file the owner is told to remove (INVARIANT 5b). + pub path: Option, +} + +/// A watcher of a verification's phases ([`Git::with_phase_watch`]). +pub type PhaseWatch = std::sync::Arc; + +/// What a caller may watch of a git's work, and look at after it (tests, +/// and the server's record of a backup). +#[derive(Clone, Default)] +struct Watch { + /// Told the name of each phase of a verification as it begins. + phase: Option, + /// The lock files dealt with since the caller last took them. + notes: std::sync::Arc>>, +} + +impl std::fmt::Debug for Watch { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Watch") + } +} + /// The git program, found once. #[derive(Debug, Clone)] pub struct Git { exe: PathBuf, /// How long it may say nothing before it is stopped (GIT_TIMEOUT). quiet: Duration, + /// Set by whoever serves the books when they are let go: a git + /// command running is stopped, with what it started, and none starts. + cancel: Option>, + /// How long a git that is to be stopped has to end after SIGTERM + /// before it is killed (TERM_GRACE). + term_grace: Duration, + watch: Watch, } impl Git { @@ -145,10 +283,87 @@ impl Git { .map(|exe| Git { exe, quiet: GIT_TIMEOUT, + cancel: None, + term_grace: TERM_GRACE, + watch: Watch::default(), }) .ok_or(BackupError::NoGit) } + /// This git, given `grace` (not TERM_GRACE) to end after SIGTERM before + /// it is killed (a seam for tests). + #[must_use] + pub fn with_term_grace(mut self, grace: Duration) -> Self { + self.term_grace = grace; + self + } + + /// This git, stopped (every command running, and any that would + /// start) once `cancel` is set: how the server's close ends a backup + /// that is still going, instead of leaving it to run against books it + /// reported closed. + #[must_use] + pub fn with_cancel(mut self, cancel: std::sync::Arc) -> Self { + self.cancel = Some(cancel); + self + } + + fn cancelled(&self) -> bool { + self.cancel + .as_ref() + .is_some_and(|c| c.load(std::sync::atomic::Ordering::SeqCst)) + } + + /// Ok, or `Cancelled(what)` once this git was cancelled: looked at + /// between a step's phases and inside its loops over files, so a step + /// that is not running a git command ends as promptly as one that is + /// (INVARIANT 6). + fn check(&self, what: &str) -> Result<(), BackupError> { + if self.cancelled() { + Err(BackupError::Cancelled(what.to_string())) + } else { + Ok(()) + } + } + + /// This git, telling `watch` the name of each phase of a verification + /// as it begins (a seam for tests and for the server's own test knob + /// that makes a drill slow: `watch` may wait, but must give up when + /// the cancel flag is set). + #[must_use] + pub fn with_phase_watch(mut self, watch: PhaseWatch) -> Self { + self.watch.phase = Some(watch); + self + } + + /// This git, sharing `sink` for the lock files it deals with + /// (INVARIANT 5), which the caller takes with [`take_lock_notes`]: + /// every git made from the same sink reports into it. + #[must_use] + pub fn with_lock_notes(mut self, sink: LockNotes) -> Self { + self.watch.notes = sink.0; + self + } + + /// The lock files dealt with since this was last called. + pub fn take_lock_notes(&self) -> Vec { + std::mem::take(&mut *self.watch.notes.lock().unwrap_or_else(|e| e.into_inner())) + } + + fn note(&self, note: LockNote) { + self.watch + .notes + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(note); + } + + fn phase(&self, name: &str) { + if let Some(watch) = &self.watch.phase { + watch(name); + } + } + /// A git command with a clean configuration (INVARIANT 4). fn command(&self) -> Command { let mut c = Command::new(&self.exe); @@ -191,6 +406,13 @@ impl Git { "log.showSignature=false", "-c", "push.gpgSign=false", + // No git of ours starts another to go on after it ends + // (a detached `gc` would outlive a stopped backup and hold + // locks: INVARIANT 5). + "-c", + "gc.auto=0", + "-c", + "maintenance.auto=false", // A link is never made from a backup's tree (verify // refuses one before checkout, too). "-c", @@ -221,7 +443,60 @@ impl Git { /// process it started, once it has said nothing for GIT_TIMEOUT /// (a push or a clone reports its progress as it goes). fn run(&self, what: &str, args: &[&std::ffi::OsStr]) -> Result { + self.run_killed(what, args).0 + } + + /// [`Self::run`], and whether the command had to be killed (cancelled + /// or gone quiet) and what became of everything it started. + fn run_killed( + &self, + what: &str, + args: &[&std::ffi::OsStr], + ) -> (Result, Killed) { + let killed = std::cell::Cell::new(Killed::No); + let result = self.run_with(what, args, &killed); + (result, killed.get()) + } + + /// [`Self::run`] where every repository the command may write (its + /// `guards`) is looked at as the command begins, and has the locks it + /// left dealt with if the command was stopped, once all it started is + /// gone (INVARIANT 5). A stop that left a lock in the owner's folder is + /// said so: [`BackupError::LockLeft`]. + fn run_in( + &self, + what: &str, + args: &[&std::ffi::OsStr], + guards: &[&Watched], + ) -> Result { + let snaps: Vec = guards.iter().map(|g| g.snapshot()).collect(); + let (result, killed) = self.run_killed(what, args); + if killed != Killed::No { + let mut left = Vec::new(); + for (guard, snap) in guards.iter().zip(&snaps) { + left.extend(guard.after_kill(self, snap, killed == Killed::Gone)); + } + if matches!( + result, + Err(BackupError::Cancelled(_) | BackupError::TimedOut(_)) + ) && !left.is_empty() + { + return Err(BackupError::LockLeft(left.join(", "))); + } + } + result + } + + fn run_with( + &self, + what: &str, + args: &[&std::ffi::OsStr], + killed: &std::cell::Cell, + ) -> Result { use std::sync::atomic::{AtomicU64, Ordering}; + if self.cancelled() { + return Err(BackupError::Cancelled(what.to_string())); + } let mut c = self.command(); // A path made canonical on Windows carries `\\?\`, which git refuses. c.args(args.iter().map(|a| match a.to_str() { @@ -274,29 +549,18 @@ impl Git { // says of itself, in part. let stdout = drain(child.stdout.take().map(|p| Box::new(p) as _), usize::MAX); let stderr = drain(child.stderr.take().map(|p| Box::new(p) as _), OUTPUT_MAX); - // Git and every process it started (its own group, above). + // Once git has ended normally, what it started is stopped (Unix: + // its group; Windows has no group to signal, and nothing is looked + // for: a process spawned per git call would cost more than the + // leftovers it could find). #[cfg(unix)] - // SAFETY: kill has no preconditions; the group is git's own - // (process_group(0) above), so this stops it and what it started. - let kill_group = |pid: u32| unsafe { - libc::kill(-(pid as libc::pid_t), libc::SIGKILL); + let kill_leftovers = |pid: u32| { + // SAFETY: kill has no preconditions; the group is git's own + // (process_group(0) above). + unsafe { + libc::kill(-(pid as libc::pid_t), libc::SIGKILL); + } }; - // Windows has no process group to signal: a git that has gone quiet - // is stopped with the tree of processes it started (`taskkill /T`). - // Once git has ended normally nothing is looked for (a process - // spawned per git call would cost more than the leftovers it could - // find). - #[cfg(windows)] - let kill_group = |pid: u32| { - let _ = std::process::Command::new("taskkill") - .args(["/T", "/F", "/PID", &pid.to_string()]) - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status(); - }; - #[cfg(unix)] - let kill_leftovers = kill_group; #[cfg(windows)] let kill_leftovers = |_: u32| {}; let status = loop { @@ -306,10 +570,12 @@ impl Git { let quiet_for = started .elapsed() .saturating_sub(Duration::from_millis(heard.load(Ordering::Relaxed))); + if self.cancelled() { + killed.set(self.stop(&mut child)); + return Err(BackupError::Cancelled(what.to_string())); + } if quiet_for > self.quiet { - kill_group(child.id()); - let _ = child.kill(); - let _ = child.wait(); + killed.set(self.stop(&mut child)); return Err(BackupError::TimedOut(what.to_string())); } std::thread::sleep(Duration::from_millis(20)); @@ -328,9 +594,308 @@ impl Git { } } +impl Git { + /// Stop a git that is running, and everything it started (INVARIANT 5): + /// SIGTERM to its process group first (git removes the lock files it + /// holds when it is sent one, and a push's receiving end the objects it + /// had not yet kept), then up to `term_grace` for the group to end, and + /// only then SIGKILL. The leader is reaped as the group is waited for + /// (a zombie is still in its group). What became of the group. + /// + /// Windows has no signal to send a group: the nearest thing the code has + /// is `taskkill /T /F`, which ends the tree at once, so there is no + /// grace there, and no reliance on git's own clean-up: the lock rules + /// (INVARIANT 5) cover what is left. + fn stop(&self, child: &mut std::process::Child) -> Killed { + #[cfg(unix)] + { + let pid = child.id(); + // SAFETY: kill has no preconditions; the group is git's own + // (process_group(0) when it was started). + unsafe { + libc::kill(-(pid as libc::pid_t), libc::SIGTERM); + } + let by = Instant::now() + self.term_grace; + loop { + let _ = child.try_wait(); + if group_empty(pid) { + return Killed::Gone; + } + if Instant::now() >= by { + break; + } + std::thread::sleep(Duration::from_millis(5)); + } + // SAFETY: as above. + unsafe { + libc::kill(-(pid as libc::pid_t), libc::SIGKILL); + } + let _ = child.kill(); + let _ = child.wait(); + group_gone(pid) + } + #[cfg(windows)] + { + let _ = std::process::Command::new("taskkill") + .args(["/T", "/F", "/PID", &child.id().to_string()]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + let _ = child.kill(); + let _ = child.wait(); + Killed::Gone + } + } +} + /// The most kept of what a git says of itself. const OUTPUT_MAX: usize = 1 << 20; +/// What became of a git command that was killed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Killed { + /// It ended by itself. + No, + /// Killed, and it and everything it started is gone. + Gone, + /// Killed, but something it started was still there when we stopped + /// looking (GROUP_GONE_WAIT). + Lingering, +} + +/// How long, after a git was killed, to wait for everything it started to +/// be gone. +pub const GROUP_GONE_WAIT: Duration = Duration::from_secs(2); + +/// Whether the process group `pid` led has no process left. +#[cfg(unix)] +fn group_empty(pid: u32) -> bool { + // SAFETY: signal 0 only asks whether a process is in the group. + let found = unsafe { libc::kill(-(pid as libc::pid_t), 0) }; + found != 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) +} + +/// Wait until the process group `pid` led has no process left, for +/// GROUP_GONE_WAIT at most: a killed process can run a few more +/// instructions before the kernel takes it, and could take a lock in them. +fn group_gone(pid: u32) -> Killed { + #[cfg(unix)] + { + let by = Instant::now() + GROUP_GONE_WAIT; + loop { + if group_empty(pid) { + return Killed::Gone; + } + if Instant::now() >= by { + return Killed::Lingering; + } + std::thread::sleep(Duration::from_millis(5)); + } + } + #[cfg(windows)] + { + // taskkill /T /F ended the tree before it returned. + let _ = pid; + Killed::Gone + } +} + +/// A shared place for the lock files dealt with (see +/// [`Git::with_lock_notes`]). +#[derive(Clone, Default)] +pub struct LockNotes(std::sync::Arc>>); + +impl LockNotes { + /// What was dealt with since this was last called. + pub fn take(&self) -> Vec { + std::mem::take(&mut *self.0.lock().unwrap_or_else(|e| e.into_inner())) + } +} + +/// A repository a git command may leave locks in when it is stopped. +pub struct Watched { + dir: PathBuf, + /// `archive`, `folder` or `repository`. + kind: &'static str, +} + +/// A repository as it was when a command began: its folder opened once +/// (never again by its path: INVARIANT 5), and the locks already in it. +struct Snapshot { + handle: Option, + before: std::collections::BTreeSet, +} + +impl Watched { + /// The book's own archive, `dir` (`/archive.git`): private to + /// this program, one git of ours at a time. + fn archive(dir: &Path) -> Self { + Self { + dir: dir.to_path_buf(), + kind: "archive", + } + } + + /// A target repository on this computer, the owner's. + fn target(dir: &Path, kind: &'static str) -> Self { + Self { + dir: dir.to_path_buf(), + kind, + } + } + + fn is_archive(&self) -> bool { + self.kind == "archive" + } + + fn open(&self) -> std::io::Result { + if self.is_archive() { + match ( + self.dir.parent(), + self.dir.file_name().and_then(|n| n.to_str()), + ) { + (Some(book), Some(name)) => crate::git_locks::RepoDir::open_in(book, name), + _ => Err(std::io::ErrorKind::InvalidInput.into()), + } + } else { + crate::git_locks::RepoDir::open(&self.dir) + } + } + + /// Looked at as a command begins. + fn snapshot(&self) -> Snapshot { + let handle = self.open().ok(); + let before = handle + .as_ref() + .map(|h| h.locks().into_iter().map(|f| f.lock).collect()) + .unwrap_or_default(); + Snapshot { handle, before } + } + + /// The command was stopped. Once all it started is `gone`, deal with + /// the locks it left (INVARIANT 5): in the archive, remove those that + /// were not there when the command began; in the owner's folder remove + /// nothing, and say so. The whole paths of the locks left there. + fn after_kill(&self, git: &Git, snap: &Snapshot, gone: bool) -> Vec { + // A repository that didn't exist when the command began (a new + // target's, made by an `init` that was stopped) is looked at, never + // changed. The archive is only ever touched through the handle + // opened before the command. + let fresh; + let handle = match (&snap.handle, self.is_archive()) { + (Some(h), _) => h, + (None, true) => return Vec::new(), + (None, false) => match self.open() { + Ok(h) => { + fresh = h; + &fresh + } + Err(_) => return Vec::new(), + }, + }; + let mut left = Vec::new(); + for found in handle.locks() { + if snap.before.contains(&found.lock) { + continue; + } + let lock = found.lock; + if self.is_archive() { + if !gone { + git.note(LockNote { + repo: self.kind, + lock, + removed: false, + why: "what git started was still running", + path: None, + }); + } else if handle.remove(&lock).unwrap_or(false) { + git.note(LockNote { + repo: self.kind, + lock, + removed: true, + why: "git was stopped", + path: None, + }); + } + } else { + let path = handle.path().join(&lock).display().to_string(); + git.note(LockNote { + repo: self.kind, + lock, + removed: false, + why: if gone { + "git was stopped while it held it: the owner's folder is never changed by this program" + } else { + "what git started was still running" + }, + path: Some(path.clone()), + }); + left.push(path); + } + } + left + } +} + +/// The locks of the book's archive in `book_dir` that are older than +/// ARCHIVE_STALE, removed, each noted in `notes`; and, when `say_young`, +/// each younger one noted as left. The archive is opened once and only +/// regular files named as git names its locks are touched (INVARIANT 5a). +fn clear_stale_archive_locks( + book_dir: &Path, + removed_why: &'static str, + young: Option<&'static str>, + notes: &mut Vec, +) { + let Ok(handle) = crate::git_locks::RepoDir::open_in(book_dir, ARCHIVE_DIR) else { + return; + }; + let now = std::time::SystemTime::now(); + for found in handle.locks() { + let old = found + .modified + .and_then(|t| now.duration_since(t).ok()) + .is_some_and(|age| age >= ARCHIVE_STALE); + if old { + if handle.remove(&found.lock).unwrap_or(false) { + notes.push(LockNote { + repo: "archive", + lock: found.lock, + removed: true, + why: removed_why, + path: None, + }); + } + } else if let Some(why) = young { + notes.push(LockNote { + repo: "archive", + lock: found.lock, + removed: false, + why, + path: None, + }); + } + } +} + +/// The locks a git of ours left in the book's archive at an earlier time +/// (killed with the server, a power cut), for the caller to say it removed +/// them: those older than ARCHIVE_STALE are removed, younger ones are left +/// and noted as left (the next backup tries again, and removes them once +/// they are old). Call it while this process holds the book's store lock: +/// no other wanderbooks process runs git on the archive (INVARIANT 5a). +pub fn clear_archive_locks(book_dir: &Path) -> Vec { + let mut notes = Vec::new(); + clear_stale_archive_locks( + book_dir, + "found when the books opened, older than ten minutes", + Some("younger than ten minutes when the books opened: left, the next backup tries again"), + &mut notes, + ); + notes +} + /// What git said when it failed: its messages without its progress, the /// last whole lines of it (never a line cut part way, which could hide a /// path from those who hide paths, INVARIANT 4); `cut` when only the last @@ -381,9 +946,12 @@ fn archive(git: &Git, book_dir: &Path) -> Result { if !dir.join("HEAD").is_file() { crate::root::private_book_folder(book_dir, ARCHIVE_DIR) .map_err(|e| BackupError::Damaged(e.to_string()))?; - git.run( + // A git killed in the middle of making it leaves HEAD's lock, which + // would stop every later `init` (INVARIANT 5). + git.run_in( "init", &[os("init"), os("--bare"), os("-q"), dir.as_os_str()], + &[&Watched::archive(&dir)], )?; } let _ = std::fs::remove_file(dir.join("info").join("attributes")); @@ -406,7 +974,8 @@ pub fn commit( head: (u64, String), ) -> Result, BackupError> { let archive = archive(git, book_dir)?; - clear_old_locks(&archive); + clear_old_locks(git, book_dir); + let guard = Watched::archive(&archive); let git_dir = format!("--git-dir={}", archive.display()); let work_tree = format!("--work-tree={}", book_dir.display()); let paths: Vec<&str> = BACKED_UP @@ -424,7 +993,7 @@ pub fn commit( os("--"), ]; add.extend(paths.iter().map(|p| os(p))); - git.run("add", &add)?; + git.run_in("add", &add, &[&guard])?; } // What was backed up and is now gone altogether (a vault purged to // nothing) goes from the next commit too. @@ -445,7 +1014,7 @@ pub fn commit( os("--"), ]; rm.extend(gone.iter().map(|p| os(p))); - git.run("rm", &rm)?; + git.run_in("rm", &rm, &[&guard])?; } // Every file there is in it, nothing else (INVARIANT 1). let listed = git.run( @@ -460,7 +1029,7 @@ pub fn commit( indexed.sort(); let mut on_disk = Vec::new(); for p in &paths { - files_under(book_dir, Path::new(p), &mut on_disk)?; + files_under(git, book_dir, Path::new(p), &mut on_disk)?; } on_disk.sort(); if on_disk @@ -506,7 +1075,7 @@ pub fn commit( // The books it holds by name too (a restore tells their own from // others'). let message = format!("seq {} head {}\n\nbook {book}", head.0, head.1); - git.run( + git.run_in( "commit", &[ os(&git_dir), @@ -518,6 +1087,7 @@ pub fn commit( os("-m"), os(&message), ], + &[&guard], )?; let commit = git.run("rev-parse", &[os(&git_dir), os("rev-parse"), os("HEAD")])?; Ok(Some(Made { commit, head })) @@ -532,10 +1102,11 @@ pub fn stage_blobs(git: &Git, book_dir: &Path) -> Result<(), BackupError> { return Ok(()); } let archive = archive(git, book_dir)?; - clear_old_locks(&archive); + clear_old_locks(git, book_dir); + let guard = Watched::archive(&archive); let git_dir = format!("--git-dir={}", archive.display()); let work_tree = format!("--work-tree={}", book_dir.display()); - git.run( + git.run_in( "add", &[ os(&git_dir), @@ -546,33 +1117,43 @@ pub fn stage_blobs(git: &Git, book_dir: &Path) -> Result<(), BackupError> { os("--"), os(blobs), ], + &[&guard], )?; Ok(()) } -/// The locks a git left behind (stopped, the server killed) would refuse -/// every later backup: cleared once older than any git may run quiet, -/// so never one a git still at work holds. -fn clear_old_locks(archive: &Path) { - for lock in ["index.lock", "HEAD.lock", "refs/heads/main.lock"] { - let path = archive.join(lock); - let old = std::fs::metadata(&path) - .and_then(|m| m.modified()) - .is_ok_and(|t| t.elapsed().is_ok_and(|e| e > GIT_TIMEOUT)); - if old { - let _ = std::fs::remove_file(path); - } +/// The locks a git left behind (the server killed, a power cut) would +/// refuse every later backup: those older than ARCHIVE_STALE are removed, +/// each noted, so none a git still at work holds is touched (INVARIANT 5a). +fn clear_old_locks(git: &Git, book_dir: &Path) { + let mut notes = Vec::new(); + clear_stale_archive_locks( + book_dir, + "older than ten minutes when a backup began", + None, + &mut notes, + ); + for note in notes { + git.note(note); } } /// Every file under `rel` in `base` (or `rel` itself), as paths relative to /// `base` with `/` between their parts. -fn files_under(base: &Path, rel: &Path, out: &mut Vec) -> Result<(), BackupError> { +fn files_under( + git: &Git, + base: &Path, + rel: &Path, + out: &mut Vec, +) -> Result<(), BackupError> { + // Looked at once per entry: a folder of any size is left promptly + // (INVARIANT 6). + git.check("listing the files")?; let full = base.join(rel); let meta = std::fs::symlink_metadata(&full)?; if meta.is_dir() { for entry in std::fs::read_dir(&full)? { - files_under(base, &rel.join(entry?.file_name()), out)?; + files_under(git, base, &rel.join(entry?.file_name()), out)?; } } else { let parts: Vec = rel @@ -768,9 +1349,12 @@ pub fn push( if !may_create { return Err(BackupError::NoBackupThere); } - git.run( + // The repository is new: any lock in it is ours, by the + // same rules as a push's (INVARIANT 5b). + git.run_in( "init", &[os("init"), os("--bare"), os("-q"), repo.as_os_str()], + &[&Watched::target(&repo, target.kind())], )?; } repo.display().to_string() @@ -800,7 +1384,19 @@ pub fn push( args.push(os(&receive)); } args.extend([os(&to), os("HEAD:refs/heads/main")]); - match git.run("push", &args) { + // The repositories this push may leave a lock in if it is killed: the + // archive, and the target if it is on this computer (one far away + // cleans up after its own connection's end, and isn't ours to touch). + let mine = Watched::archive(&archive); + let theirs = (matches!(target, Target::Folder(_)) || is_local(&to)).then(|| { + Watched::target( + Path::new(to.strip_prefix("file://").unwrap_or(&to)), + target.kind(), + ) + }); + let mut guards = vec![&mine]; + guards.extend(theirs.as_ref()); + match git.run_in("push", &args, &guards) { Ok(_) => {} Err(BackupError::Git(_, said)) if said.contains("non-fast-forward") @@ -843,6 +1439,15 @@ pub fn verify(git: &Git, source: &str, scratch: &Path) -> Result BackupError::Cancelled("verifying".into()), + e => BackupError::Damaged(e.to_string()), + }; + git.phase("clone"); + git.check("clone")?; git.run( "clone", &[ @@ -857,6 +1462,7 @@ pub fn verify(git: &Git, source: &str, scratch: &Path) -> Result Result Result Result Result Ok(v.head), Ok(false) => Err(BackupError::Damaged( "its journal isn't this book's history".into(), )), - Err(e) => Err(e.into()), + Err(e) => Err(e), } }); let _ = std::fs::remove_dir_all(scratch); @@ -1028,8 +1640,10 @@ pub fn prove_archive( "its journal isn't the books' own, byte for byte".into(), )); } + git.phase("compare"); + git.check("comparing")?; for kept in [crate::root::VAULT_DIR, crate::root::KEYS_DIR] { - if held_files(book_dir, kept)? != held_files(&v.tree, kept)? { + if held_files(git, book_dir, kept)? != held_files(git, &v.tree, kept)? { return Err(BackupError::Damaged(format!( "its {} isn't the books' own, file for file", if kept == crate::root::KEYS_DIR { @@ -1065,16 +1679,17 @@ pub struct Proven { /// Every file under `rel` in `base`, by its path there, with its bytes /// (none when `rel` isn't there). -fn held_files(base: &Path, rel: &str) -> Result)>, BackupError> { +fn held_files(git: &Git, base: &Path, rel: &str) -> Result)>, BackupError> { if std::fs::symlink_metadata(base.join(rel)).is_err() { return Ok(Vec::new()); } let mut names = Vec::new(); - files_under(base, Path::new(rel), &mut names)?; + files_under(git, base, Path::new(rel), &mut names)?; names.sort(); names .into_iter() .map(|n| { + git.check("reading the files")?; let bytes = std::fs::read(base.join(&n))?; Ok((n, bytes)) }) @@ -1084,11 +1699,25 @@ fn held_files(base: &Path, rel: &str) -> Result)>, BackupEr /// Whether the journal at `backup` is a byte prefix of the one at `live` /// (a drill: the backup holds the book's history, nothing else). pub fn is_prefix(live: &Path, backup: &Path) -> std::io::Result { + is_prefix_with(live, backup, || Ok(())).map_err(|e| match e { + BackupError::Io(kind) => std::io::Error::from(kind), + other => std::io::Error::other(other.to_string()), + }) +} + +/// [`is_prefix`], asking `each` before every chunk read (a step that has +/// to stop looks for its stop there, INVARIANT 6). +fn is_prefix_with( + live: &Path, + backup: &Path, + mut each: impl FnMut() -> Result<(), BackupError>, +) -> Result { use std::io::Read; let mut a = std::fs::File::open(live)?; let mut b = std::fs::File::open(backup)?; let (mut x, mut y) = (vec![0u8; 64 * 1024], vec![0u8; 64 * 1024]); loop { + each()?; let n = b.read(&mut y)?; if n == 0 { return Ok(true); @@ -1458,7 +2087,7 @@ mod tests { s.add_account("6000", "Supplies", AccountType::Expense, None, false) .unwrap(); assert!(commit(&git, &b, "acme", s.head()).is_err()); - let then = std::time::SystemTime::now() - GIT_TIMEOUT - Duration::from_secs(1); + let then = std::time::SystemTime::now() - ARCHIVE_STALE - Duration::from_secs(1); for lock in locks { std::fs::File::options() .write(true) @@ -1877,6 +2506,9 @@ mod tests { Git { exe: wrapper, quiet: GIT_TIMEOUT, + cancel: None, + term_grace: TERM_GRACE, + watch: Watch::default(), } } @@ -1922,13 +2554,840 @@ mod tests { ); } + /// A git that is the real one with the hooks folder of its own: each + /// `core.hooksPath=/dev/null` it is given (in its own arguments, and in + /// the `--receive-pack` command a push to this computer runs) names + /// `hooks` instead, where a `reference-transaction` hook waits, while + /// `hooks/slow` exists, at the point where git holds its ref locks (and + /// a commit its index lock): how a real git is made slow enough to be + /// killed inside the work. `hooks/hooked` has a line per hook that waited. + fn slow_git(dir: &Path, real: &Git) -> (Git, PathBuf) { + use std::os::unix::fs::PermissionsExt; + let hooks = dir.join("slow-hooks"); + std::fs::create_dir_all(&hooks).unwrap(); + let hook = hooks.join("reference-transaction"); + std::fs::write( + &hook, + "#!/bin/sh\ncat >/dev/null\n[ \"$1\" = prepared ] || exit 0\nd=\"$(dirname \"$0\")\"\nif [ -e \"$d/slow\" ]; then\n echo $$ >> \"$d/hooked\"\n while [ -e \"$d/slow\" ]; do sleep 0.05; done\nfi\nexit 0\n", + ) + .unwrap(); + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + // The receiving end's `pre-receive`: waits while `slow-pack` exists, + // after the pack has been received into the quarantine. + let pre = hooks.join("pre-receive"); + std::fs::write( + &pre, + "#!/bin/sh\ncat >/dev/null\nd=\"$(dirname \"$0\")\"\nif [ -e \"$d/slow-pack\" ]; then\n echo $$ >> \"$d/hooked-pack\"\n while [ -e \"$d/slow-pack\" ]; do sleep 0.05; done\nfi\nexit 0\n", + ) + .unwrap(); + std::fs::set_permissions(&pre, std::fs::Permissions::from_mode(0o755)).unwrap(); + let wrapper = dir.join("slow-git"); + std::fs::write( + &wrapper, + format!( + "#!/bin/sh\nn=$#\nwhile [ $n -gt 0 ]; do\n a=\"$1\"; shift\n case \"$a\" in\n *core.hooksPath=/dev/null*) a=$(printf '%s' \"$a\" | sed 's|core.hooksPath=/dev/null|core.hooksPath={}|g') ;;\n esac\n set -- \"$@\" \"$a\"\n n=$((n-1))\ndone\nexec '{}' \"$@\"\n", + hooks.display(), + real.exe.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap(); + ( + Git { + exe: wrapper, + quiet: GIT_TIMEOUT, + cancel: None, + term_grace: TERM_GRACE, + watch: Watch::default(), + }, + hooks, + ) + } + + /// Wait until a hook of `slow_git` is waiting. + fn wait_hooked(hooks: &Path) { + let by = Instant::now() + Duration::from_secs(30); + while !hooks.join("hooked").exists() { + assert!(Instant::now() < by, "git never reached its ref update"); + std::thread::sleep(Duration::from_millis(10)); + } + } + + fn fsck(git: &Git, repo: &Path) { + git.run( + "fsck", + &[ + os(&format!("--git-dir={}", repo.display())), + os("fsck"), + os("--strict"), + ], + ) + .unwrap_or_else(|e| panic!("the repository isn't whole: {e}")); + } + + /// The locks in `repo`, as paths in it. + fn locks_in(repo: &Path) -> Vec { + crate::git_locks::RepoDir::open(repo) + .unwrap() + .locks() + .into_iter() + .map(|f| f.lock) + .collect() + } + + /// Hold every process of the group `pid` leads still (SIGSTOP): a + /// SIGTERM sent to it then stays pending, git can't run its handler, + /// and only the kill after the grace ends it. This is how a git that + /// can't end on SIGTERM, with the locks it holds, is made on purpose. + fn freeze_group_of(pid: u32) { + let out = std::process::Command::new("ps") + .args(["-o", "pgid=", "-p", &pid.to_string()]) + .output() + .unwrap(); + let group: i32 = String::from_utf8_lossy(&out.stdout) + .trim() + .parse() + .expect("ps names the group"); + // SAFETY: stopping the group this test's own git started. + assert_eq!(unsafe { libc::kill(-group, libc::SIGSTOP) }, 0); + } + + /// The pid of the first hook of `slow_git` that waited, in `file`. + fn hooked_pid(hooks: &Path, file: &str) -> u32 { + std::fs::read_to_string(hooks.join(file)) + .unwrap() + .lines() + .next() + .unwrap() + .trim() + .parse() + .unwrap() + } + + /// INVARIANT 5, the archive, told to stop: a real git in the middle of a + /// commit, holding the ref locks, ends on SIGTERM and removes them + /// itself. Nothing is left, and nothing was cleaned up here (no note): + /// the grace is long, so a git that needed the kill would show. + #[test] + fn a_git_stopped_by_sigterm_mid_commit_leaves_no_lock_and_needs_no_cleanup() { + let real = Git::find().expect("git is installed"); + let dir = tempfile::tempdir().unwrap(); + let (slow, hooks) = slow_git(dir.path(), &real); + let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let cancelled = slow + .clone() + .with_cancel(flag.clone()) + .with_term_grace(Duration::from_secs(120)); + let b = dir.path().join("book"); + let mut s = book(&b); + commit(&slow, &b, "acme", s.head()).unwrap().unwrap(); + s.add_account("6000", "Supplies", AccountType::Expense, None, false) + .unwrap(); + let archive = b.join(ARCHIVE_DIR); + std::fs::write(hooks.join("slow"), b"").unwrap(); + let running = { + let (git, b, head) = (cancelled.clone(), b.clone(), s.head()); + std::thread::spawn(move || commit(&git, &b, "acme", head)) + }; + wait_hooked(&hooks); + // Inside the commit's ref update it holds the ref locks. + let held = locks_in(&archive); + assert!(held.contains(&"HEAD.lock".to_string()), "{held:?}"); + assert!( + held.contains(&"refs/heads/main.lock".to_string()), + "{held:?}" + ); + flag.store(true, std::sync::atomic::Ordering::SeqCst); + assert_eq!( + running.join().unwrap().unwrap_err(), + BackupError::Cancelled("commit".into()) + ); + assert_eq!(locks_in(&archive), Vec::::new()); + assert_eq!( + cancelled.take_lock_notes(), + Vec::new(), + "git removed its own locks: there was nothing for this program to clean up" + ); + // The next backup, with no one to remove anything by hand. + std::fs::remove_file(hooks.join("slow")).unwrap(); + let made = commit(&slow, &b, "acme", s.head()) + .unwrap() + .expect("the next backup is made"); + assert_eq!(made.head, s.head()); + fsck(&real, &archive); + } + + /// INVARIANT 5, the archive, a git that can't end on SIGTERM: killed + /// only after the grace; once its group is gone the locks it left, none + /// of which was there when the command began, are removed through the + /// archive's own handle, each noted; the next backup needs no hand. + #[test] + fn a_git_that_cannot_end_on_sigterm_is_killed_after_the_grace_and_its_archive_locks_go() { + let real = Git::find().expect("git is installed"); + let dir = tempfile::tempdir().unwrap(); + let (slow, hooks) = slow_git(dir.path(), &real); + let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let grace = Duration::from_millis(400); + let cancelled = slow + .clone() + .with_cancel(flag.clone()) + .with_term_grace(grace); + let b = dir.path().join("book"); + let mut s = book(&b); + commit(&slow, &b, "acme", s.head()).unwrap().unwrap(); + s.add_account("6000", "Supplies", AccountType::Expense, None, false) + .unwrap(); + let archive = b.join(ARCHIVE_DIR); + std::fs::write(hooks.join("slow"), b"").unwrap(); + let running = { + let (git, b, head) = (cancelled.clone(), b.clone(), s.head()); + std::thread::spawn(move || commit(&git, &b, "acme", head)) + }; + wait_hooked(&hooks); + let held = locks_in(&archive); + assert!(!held.is_empty(), "git held no lock inside its ref update"); + freeze_group_of(hooked_pid(&hooks, "hooked")); + let stopped = Instant::now(); + flag.store(true, std::sync::atomic::Ordering::SeqCst); + assert_eq!( + running.join().unwrap().unwrap_err(), + BackupError::Cancelled("commit".into()) + ); + assert!( + stopped.elapsed() >= grace, + "killed before the grace had run out" + ); + assert_eq!(locks_in(&archive), Vec::::new()); + let notes = cancelled.take_lock_notes(); + for lock in &held { + assert!( + notes.iter().any(|n| n.repo == "archive" + && &n.lock == lock + && n.removed + && n.why == "git was stopped" + && n.path.is_none()), + "{lock} wasn't noted: {notes:?}" + ); + } + std::fs::remove_file(hooks.join("slow")).unwrap(); + let made = commit(&slow, &b, "acme", s.head()) + .unwrap() + .expect("the next backup is made"); + assert_eq!(made.head, s.head()); + fsck(&real, &archive); + } + + /// INVARIANT 5, the index lock: a real git stopped inside `add` (here + /// hashing a very large, empty, stored file) holds the index lock, and + /// removes it itself on SIGTERM; the next backup needs no hand. + #[test] + fn a_git_stopped_mid_add_leaves_no_index_lock() { + let real = Git::find().expect("git is installed"); + let dir = tempfile::tempdir().unwrap(); + let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let git = real + .clone() + .with_cancel(flag.clone()) + .with_term_grace(Duration::from_secs(120)); + let b = dir.path().join("book"); + let s = book(&b); + commit(&real, &b, "acme", s.head()).unwrap().unwrap(); + let big = b.join("blobs").join("big-and-empty"); + std::fs::File::create(&big) + .unwrap() + .set_len(64 << 30) + .unwrap(); + let archive = b.join(ARCHIVE_DIR); + let running = { + let (git, b) = (git.clone(), b.clone()); + std::thread::spawn(move || stage_blobs(&git, &b)) + }; + // The lock is taken as `add` begins and held until it ends, which + // for a file this size is minutes: seeing it is being inside. + let by = Instant::now() + Duration::from_secs(60); + while !archive.join("index.lock").exists() { + assert!(Instant::now() < by, "git never took the index lock"); + std::thread::sleep(Duration::from_millis(5)); + } + flag.store(true, std::sync::atomic::Ordering::SeqCst); + assert_eq!( + running.join().unwrap().unwrap_err(), + BackupError::Cancelled("add".into()) + ); + assert_eq!(locks_in(&archive), Vec::::new()); + assert_eq!(git.take_lock_notes(), Vec::new()); + std::fs::remove_file(&big).unwrap(); + stage_blobs(&real, &b).unwrap(); + fsck(&real, &archive); + } + + /// A book backed up once to a folder target, then changed and + /// committed again, ready for a push: (git, hooks, book folder, target + /// repository, the target, the store). + fn ready_to_push( + dir: &Path, + real: &Git, + ) -> (Git, PathBuf, PathBuf, PathBuf, Target, crate::Store) { + let (slow, hooks) = slow_git(dir, real); + let b = dir.join("book"); + let mut s = book(&b); + commit(&slow, &b, "acme", s.head()).unwrap().unwrap(); + let folder = dir.join("disk"); + std::fs::create_dir(&folder).unwrap(); + let target = Target::Folder(folder.clone()); + push(&slow, &b, "acme", &target, true).unwrap(); + s.add_account("6000", "Supplies", AccountType::Expense, None, false) + .unwrap(); + commit(&slow, &b, "acme", s.head()).unwrap().unwrap(); + (slow, hooks, b, folder.join("acme.git"), target, s) + } + + fn main_of(real: &Git, repo: &Path) -> String { + real.run( + "rev-parse", + &[ + os(&format!("--git-dir={}", repo.display())), + os("rev-parse"), + os("refs/heads/main"), + ], + ) + .unwrap() + } + + /// INVARIANT 5b, told to stop: a real git in the middle of a push (its + /// receive-pack holding the target's ref lock) ends on SIGTERM and its + /// receiving end removes the lock itself. Nothing was removed here, a + /// lock that was there before the push is untouched, the next push + /// succeeds, and both repositories pass git's check. + #[test] + fn a_push_stopped_by_sigterm_leaves_no_lock_in_the_target_and_removes_nothing_there() { + let real = Git::find().expect("git is installed"); + let dir = tempfile::tempdir().unwrap(); + let (slow, hooks, b, repo, target, _s) = ready_to_push(dir.path(), &real); + // Another writer's lock, held before our push begins. + std::fs::write(repo.join("refs/heads/another.lock"), b"").unwrap(); + let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let cancelled = slow + .clone() + .with_cancel(flag.clone()) + .with_term_grace(Duration::from_secs(120)); + std::fs::write(hooks.join("slow"), b"").unwrap(); + let running = { + let (git, b, target) = (cancelled.clone(), b.clone(), target.clone()); + std::thread::spawn(move || push(&git, &b, "acme", &target, true)) + }; + wait_hooked(&hooks); + assert!(repo.join("refs/heads/main.lock").exists()); + flag.store(true, std::sync::atomic::Ordering::SeqCst); + assert_eq!( + running.join().unwrap().unwrap_err(), + BackupError::Cancelled("push".into()) + ); + assert!(!repo.join("refs/heads/main.lock").exists()); + assert!( + repo.join("refs/heads/another.lock").exists(), + "a lock that was there before the push was removed" + ); + assert_eq!(cancelled.take_lock_notes(), Vec::new()); + // The next push, nobody's hand in it. + std::fs::remove_file(hooks.join("slow")).unwrap(); + std::fs::remove_file(hooks.join("hooked")).unwrap(); + let commit_id = push(&slow, &b, "acme", &target, true).unwrap(); + assert_eq!(main_of(&real, &repo), commit_id); + fsck(&real, &repo); + fsck(&real, &b.join(ARCHIVE_DIR)); + } + + /// INVARIANT 5b, a git that can't end on SIGTERM: killed after the + /// grace, it leaves the target's ref lock, and nothing in the owner's + /// folder is deleted by us, whatever the lock's age. The push is + /// reported as failed, naming the file and what the owner may do. A + /// lock that was there before the push began is not named, and is + /// untouched. Once the owner (here, the test) removes the file the next + /// push succeeds, and both repositories pass git's check. + #[test] + fn a_lock_left_in_a_folder_target_by_a_kill_is_never_removed_but_reported() { + let real = Git::find().expect("git is installed"); + let dir = tempfile::tempdir().unwrap(); + let (slow, hooks, b, repo, target, _s) = ready_to_push(dir.path(), &real); + std::fs::write(repo.join("refs/heads/another.lock"), b"").unwrap(); + let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let grace = Duration::from_millis(400); + let cancelled = slow + .clone() + .with_cancel(flag.clone()) + .with_term_grace(grace); + std::fs::write(hooks.join("slow"), b"").unwrap(); + let running = { + let (git, b, target) = (cancelled.clone(), b.clone(), target.clone()); + std::thread::spawn(move || push(&git, &b, "acme", &target, true)) + }; + wait_hooked(&hooks); + let lock = repo.join("refs/heads/main.lock"); + assert!(lock.exists()); + freeze_group_of(hooked_pid(&hooks, "hooked")); + let stopped = Instant::now(); + flag.store(true, std::sync::atomic::Ordering::SeqCst); + let said = running.join().unwrap().unwrap_err(); + assert!(stopped.elapsed() >= grace); + let BackupError::LockLeft(named) = &said else { + panic!("{said:?}"); + }; + assert!( + named.split(", ").any(|p| p == lock.display().to_string()), + "{said}" + ); + // Every lock it left is named, by its whole path, and each is there. + for path in named.split(", ") { + assert!(Path::new(path).exists(), "{path}"); + } + let words = said.to_string(); + assert!( + words.contains("nothing else is using the backup folder"), + "{words}" + ); + assert!(!words.contains("another.lock"), "{words}"); + // Left where it was, and the one before our push untouched. + assert!(lock.exists(), "a file in the owner's folder was deleted"); + assert!(repo.join("refs/heads/another.lock").exists()); + let notes = cancelled.take_lock_notes(); + assert!( + notes.iter().all(|n| n.repo == "folder" + && !n.removed + && n.path.as_deref() == Some(repo.join(&n.lock).display().to_string().as_str())), + "{notes:?}" + ); + assert!( + notes.iter().any(|n| n.lock == "refs/heads/main.lock"), + "{notes:?}" + ); + assert!( + !notes.iter().any(|n| n.lock.contains("another")), + "{notes:?}" + ); + // Still there, a later push fails by git's own words, and the file + // stays. + std::fs::remove_file(hooks.join("slow")).unwrap(); + assert!(push(&slow, &b, "acme", &target, true).is_err()); + assert!(lock.exists(), "a later push removed it"); + // The owner removes it; the next backup goes on. + std::fs::remove_file(&lock).unwrap(); + let commit_id = push(&slow, &b, "acme", &target, true).unwrap(); + assert_eq!(main_of(&real, &repo), commit_id); + fsck(&real, &repo); + fsck(&real, &b.join(ARCHIVE_DIR)); + } + + /// A book whose next push carries a large object (about 48 MiB that + /// doesn't compress), with a `pre-receive` hook on the receiving side + /// that waits while `slow-pack` exists: the pack has been received into + /// the target's quarantine by then, and the push is held inside the + /// transfer's receiving end. + fn large_push_ready(dir: &Path, real: &Git) -> (Git, PathBuf, PathBuf, PathBuf, Target) { + let (slow, hooks, b, repo, target, _s) = ready_to_push(dir, real); + let mut bytes = vec![0u8; 48 << 20]; + let mut x: u64 = 0x9E37_79B9_7F4A_7C15; + for chunk in bytes.chunks_mut(8) { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + chunk.copy_from_slice(&x.to_le_bytes()[..chunk.len()]); + } + std::fs::write(b.join("blobs").join("large-and-random"), &bytes).unwrap(); + commit(&slow, &b, "acme", (1, "x".into())) + .map(|_| ()) + .unwrap(); + (slow, hooks, b, repo, target) + } + + /// INVARIANT 5, 6: a push stopped while its pack is being received (a + /// large object, the receiving end held up by a hook) leaves both + /// repositories whole, however it was ended: git's own check is run on + /// both at once, with nothing cleaned up between. + #[test] + fn a_push_stopped_during_the_pack_transfer_leaves_both_repositories_whole() { + let real = Git::find().expect("git is installed"); + for (name, frozen) in [("by SIGTERM", false), ("by the kill after the grace", true)] { + let dir = tempfile::tempdir().unwrap(); + let (slow, hooks, b, repo, target) = large_push_ready(dir.path(), &real); + let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let cancelled = slow + .clone() + .with_cancel(flag.clone()) + .with_term_grace(Duration::from_millis(if frozen { 400 } else { 120_000 })); + std::fs::write(hooks.join("slow-pack"), b"").unwrap(); + let running = { + let (git, b, target) = (cancelled.clone(), b.clone(), target.clone()); + std::thread::spawn(move || push(&git, &b, "acme", &target, true)) + }; + let by = Instant::now() + Duration::from_secs(300); + while !hooks.join("hooked-pack").exists() { + assert!( + Instant::now() < by, + "{name}: the push never reached the receiving end's hook" + ); + std::thread::sleep(Duration::from_millis(10)); + } + // The pack is in the target's quarantine: a stop is in the + // transfer's receiving end. + let incoming = std::fs::read_dir(repo.join("objects")) + .unwrap() + .flatten() + .filter(|e| e.file_name().to_string_lossy().contains("incoming-")) + .count(); + assert!(incoming > 0, "{name}: nothing was being received"); + if frozen { + freeze_group_of(hooked_pid(&hooks, "hooked-pack")); + } + flag.store(true, std::sync::atomic::Ordering::SeqCst); + let said = running.join().unwrap().unwrap_err(); + assert!( + matches!(said, BackupError::Cancelled(_) | BackupError::LockLeft(_)), + "{name}: {said:?}" + ); + // At once: nothing cleaned up, nothing waited for. + fsck(&real, &repo); + fsck(&real, &b.join(ARCHIVE_DIR)); + // And the target still takes the next push, after the owner's + // own removal of a lock a kill left (none, when SIGTERM ended + // git). + std::fs::remove_file(hooks.join("slow-pack")).unwrap(); + std::fs::remove_file(hooks.join("hooked-pack")).unwrap(); + if let BackupError::LockLeft(path) = said { + assert!(frozen, "{name}: SIGTERM left a lock"); + std::fs::remove_file(path).unwrap(); + } + let commit_id = push(&slow, &b, "acme", &target, true).unwrap(); + assert_eq!(main_of(&real, &repo), commit_id, "{name}"); + fsck(&real, &repo); + } + } + + /// INVARIANT 5a: at open, a lock in the archive is removed only if it + /// is older than ARCHIVE_STALE, each removal noted; a younger one is + /// left (and said so), nothing that isn't a lock's name is touched, and + /// the next backup removes a lock once it has grown old. + #[test] + fn the_archives_age_rule_at_open() { + let git = Git::find().expect("git is installed"); + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let mut s = book(&b); + commit(&git, &b, "acme", s.head()).unwrap().unwrap(); + let archive = b.join(ARCHIVE_DIR); + let old_enough = std::time::SystemTime::now() - ARCHIVE_STALE - Duration::from_secs(5); + let age = |path: &Path, to: std::time::SystemTime| { + std::fs::File::options() + .write(true) + .open(path) + .unwrap() + .set_modified(to) + .unwrap(); + }; + let old = ["index.lock", "refs/heads/main.lock"]; + let young = ["HEAD.lock", "packed-refs.lock"]; + for lock in old.iter().chain(&young) { + std::fs::write(archive.join(lock), b"").unwrap(); + } + for lock in old { + age(&archive.join(lock), old_enough); + } + // Not locks, however old: a file of git's own, a folder named like + // one, and a link. + std::fs::write(archive.join("description.lock-not"), b"").unwrap(); + age(&archive.join("description.lock-not"), old_enough); + std::fs::create_dir(archive.join("shallow.lock")).unwrap(); + let notes = clear_archive_locks(&b); + let removed: Vec<&str> = notes + .iter() + .filter(|n| n.removed) + .map(|n| n.lock.as_str()) + .collect(); + let mut removed_sorted = removed.clone(); + removed_sorted.sort(); + assert_eq!(removed_sorted, ["index.lock", "refs/heads/main.lock"]); + let mut left: Vec<&str> = notes + .iter() + .filter(|n| !n.removed) + .map(|n| n.lock.as_str()) + .collect(); + left.sort(); + assert_eq!(left, ["HEAD.lock", "packed-refs.lock"]); + assert!(notes.iter().all(|n| n.repo == "archive")); + assert_eq!(locks_in(&archive), ["HEAD.lock", "packed-refs.lock"]); + assert!(archive.join("description.lock-not").exists()); + assert!(archive.join("shallow.lock").is_dir()); + // The next backup meets a young lock: it fails by git's words, and + // the lock stays. Once old it is removed, noted, and the backup goes. + s.add_account("6000", "Supplies", AccountType::Expense, None, false) + .unwrap(); + assert!(commit(&git, &b, "acme", s.head()).is_err()); + assert!(archive.join("HEAD.lock").exists()); + for lock in young { + age(&archive.join(lock), old_enough); + } + let git = git.with_lock_notes(LockNotes::default()); + let made = commit(&git, &b, "acme", s.head()) + .unwrap() + .expect("backed up"); + assert_eq!(made.head, s.head()); + let notes = git.take_lock_notes(); + let mut removed: Vec<&str> = notes.iter().map(|n| n.lock.as_str()).collect(); + removed.sort(); + assert_eq!(removed, ["HEAD.lock", "packed-refs.lock"]); + assert!(notes.iter().all(|n| n.removed && n.repo == "archive")); + assert_eq!(locks_in(&archive), Vec::::new()); + } + + /// INVARIANT 5a and git_locks INVARIANT 1: what is removed after a stop + /// is removed through the archive's folder as it was opened when the + /// command began. A `refs` folder swapped for a link, or the archive's + /// own path swapped for one, in the meantime, touches nothing outside. + #[test] + fn removal_after_a_stop_goes_through_the_handle_opened_before_the_command() { + let git = Git::find().expect("git is installed"); + let dir = tempfile::tempdir().unwrap(); + let outside = dir.path().join("outside"); + std::fs::create_dir_all(outside.join("refs/heads")).unwrap(); + for lock in ["index.lock", "HEAD.lock", "refs/heads/main.lock"] { + std::fs::write(outside.join(lock), b"theirs").unwrap(); + } + let untouched = |what: &str| { + for lock in ["index.lock", "HEAD.lock", "refs/heads/main.lock"] { + assert_eq!( + std::fs::read(outside.join(lock)).unwrap(), + b"theirs", + "{what}: {lock} outside was touched" + ); + } + }; + // 1. `refs` swapped for a link. + let b = dir.path().join("book"); + let s = book(&b); + commit(&git, &b, "acme", s.head()).unwrap().unwrap(); + let archive = b.join(ARCHIVE_DIR); + let watched = Watched::archive(&archive); + let snap = watched.snapshot(); + std::fs::write(archive.join("index.lock"), b"ours").unwrap(); + std::fs::write(archive.join("refs/heads/main.lock"), b"ours").unwrap(); + std::fs::rename(archive.join("refs"), dir.path().join("refs-moved")).unwrap(); + std::os::unix::fs::symlink(outside.join("refs"), archive.join("refs")).unwrap(); + let left = watched.after_kill(&git, &snap, true); + assert!(left.is_empty()); + assert!(!archive.join("index.lock").exists(), "its own lock stays"); + assert!( + dir.path().join("refs-moved/heads/main.lock").exists(), + "the folder moved aside was reached through the link" + ); + untouched("refs swapped"); + let notes = git.take_lock_notes(); + assert_eq!( + notes.iter().map(|n| n.lock.as_str()).collect::>(), + ["index.lock"] + ); + // 2. The archive's own path swapped for a link. + std::fs::remove_file(archive.join("refs")).unwrap(); + std::fs::rename(dir.path().join("refs-moved"), archive.join("refs")).unwrap(); + std::fs::remove_file(archive.join("refs/heads/main.lock")).unwrap(); + let snap = watched.snapshot(); + std::fs::write(archive.join("index.lock"), b"ours").unwrap(); + let moved = b.join("archive-moved.git"); + std::fs::rename(&archive, &moved).unwrap(); + std::os::unix::fs::symlink(&outside, &archive).unwrap(); + let left = watched.after_kill(&git, &snap, true); + assert!(left.is_empty()); + assert!(!moved.join("index.lock").exists()); + untouched("archive path swapped"); + // 3. A command that began when the archive path was already a link + // has no handle, and nothing is removed anywhere. + std::fs::write(outside.join("new.lock"), b"theirs").unwrap(); + let snap = watched.snapshot(); + assert!(snap.handle.is_none()); + std::fs::write(outside.join("index.lock"), b"theirs").unwrap(); + assert!(watched.after_kill(&git, &snap, true).is_empty()); + untouched("path a link from the start"); + } + + /// INVARIANT 6: a drill stops inside whichever phase it is told to stop + /// in, never going on to the next, and leaves nothing (its scratch + /// folder is removed). The stop is set as the phase begins; each case + /// fails when the stop is no longer looked at inside that phase. + #[test] + fn a_drill_stops_inside_the_phase_it_is_told_to_stop_in() { + let real = Git::find().expect("git is installed"); + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let s = book(&b); + commit(&real, &b, "acme", s.head()).unwrap().unwrap(); + let folder = dir.path().join("disk"); + std::fs::create_dir(&folder).unwrap(); + let target = Target::Folder(folder); + push(&real, &b, "acme", &target, true).unwrap(); + let order = [ + "clone", "tree", "checkout", "replay", "verify", "blobs", "vault", "prefix", + ]; + for stop_in in ["clone", "replay", "verify", "blobs", "prefix"] { + let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let git = real.clone().with_cancel(flag.clone()).with_phase_watch({ + let (flag, seen) = (flag.clone(), seen.clone()); + std::sync::Arc::new(move |phase: &str| { + seen.lock().unwrap().push(phase.to_string()); + if phase == stop_in { + flag.store(true, std::sync::atomic::Ordering::SeqCst); + } + }) + }); + let scratch = dir.path().join(format!("scratch-{stop_in}")); + let drilled = drill( + &git, + &target, + "acme", + &b.join(crate::JOURNAL_FILE), + &scratch, + ); + assert!( + matches!(drilled, Err(BackupError::Cancelled(_))), + "{stop_in}: {drilled:?}" + ); + let seen = seen.lock().unwrap().clone(); + let last = order + .iter() + .position(|p| *p == seen.last().unwrap()) + .unwrap(); + let at = order.iter().position(|p| *p == stop_in).unwrap(); + assert_eq!(last, at, "{stop_in}: went on to {seen:?}"); + assert!(!scratch.exists(), "{stop_in}: its scratch folder was left"); + } + // Not stopped, it goes through every phase. + let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let git = real.clone().with_phase_watch({ + let seen = seen.clone(); + std::sync::Arc::new(move |phase: &str| seen.lock().unwrap().push(phase.to_string())) + }); + drill( + &git, + &target, + "acme", + &b.join(crate::JOURNAL_FILE), + &dir.path().join("whole"), + ) + .unwrap(); + assert_eq!(*seen.lock().unwrap(), order.map(String::from)); + } + /// A stand-in for git: a script. fn fake_git(dir: &Path, script: &str, quiet: Duration) -> Git { use std::os::unix::fs::PermissionsExt; let exe = dir.join("fake-git"); std::fs::write(&exe, format!("#!/bin/sh\n{script}\n")).unwrap(); std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap(); - Git { exe, quiet } + Git { + exe, + quiet, + cancel: None, + term_grace: TERM_GRACE, + watch: Watch::default(), + } + } + + /// Cancelled, a git that is running is stopped at once, with all it + /// started, and one that would start doesn't (the server's close ends + /// a backup instead of leaving it to run against closed books). + #[test] + fn a_cancelled_git_stops_what_runs_and_starts_nothing() { + let dir = tempfile::tempdir().unwrap(); + let pid = dir.path().join("pid"); + let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let slow = fake_git( + dir.path(), + &format!("sleep 30 & echo $! > '{}'; sleep 30", pid.display()), + Duration::from_secs(60), + ) + .with_cancel(cancel.clone()); + let running = { + let slow = slow.clone(); + std::thread::spawn(move || slow.run("slow", &[])) + }; + // It is running (it wrote its child's pid) before it is cancelled. + let by = Instant::now() + Duration::from_secs(10); + while !pid.exists() { + assert!(Instant::now() < by, "the fake git never started"); + std::thread::sleep(Duration::from_millis(10)); + } + let cancelled_at = Instant::now(); + cancel.store(true, std::sync::atomic::Ordering::SeqCst); + assert_eq!( + running.join().unwrap().unwrap_err(), + BackupError::Cancelled("slow".into()) + ); + assert!(cancelled_at.elapsed() < Duration::from_secs(5)); + let child: i32 = std::fs::read_to_string(&pid) + .unwrap() + .trim() + .parse() + .unwrap(); + // `run` returned: the group was waited for, so what it started is + // gone now, not at some later moment. + // SAFETY: signal 0 only asks whether the process is there. + assert_ne!(unsafe { libc::kill(child, 0) }, 0, "what it started ran on"); + // And none starts now. + std::fs::remove_file(&pid).unwrap(); + assert_eq!( + slow.run("again", &[]).unwrap_err(), + BackupError::Cancelled("again".into()) + ); + assert!(!pid.exists(), "a cancelled git started anyway"); + } + + /// INVARIANT 5: a git is told to end (SIGTERM, to its whole group) + /// before it is killed, and killed only once the grace has run out: one + /// that ignores the signal (a trap, as a hook may set) is waited for the + /// whole grace, then killed with all it started. + #[test] + fn a_git_that_ignores_sigterm_is_killed_after_the_grace_with_all_it_started() { + let dir = tempfile::tempdir().unwrap(); + let (started, termed) = (dir.path().join("started"), dir.path().join("termed")); + let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let grace = Duration::from_millis(500); + let stubborn = fake_git( + dir.path(), + &format!( + "trap 'echo term >> \"{}\"' TERM\necho $$ > '{}'\nwhile :; do sleep 0.05; done", + termed.display(), + started.display() + ), + Duration::from_secs(60), + ) + .with_cancel(cancel.clone()) + .with_term_grace(grace); + let running = { + let stubborn = stubborn.clone(); + std::thread::spawn(move || stubborn.run("stubborn", &[])) + }; + let by = Instant::now() + Duration::from_secs(30); + while !started.exists() { + assert!(Instant::now() < by, "the fake git never started"); + std::thread::sleep(Duration::from_millis(10)); + } + let stopped = Instant::now(); + cancel.store(true, std::sync::atomic::Ordering::SeqCst); + assert_eq!( + running.join().unwrap().unwrap_err(), + BackupError::Cancelled("stubborn".into()) + ); + assert!( + stopped.elapsed() >= grace, + "killed before the grace had run out" + ); + assert!(termed.exists(), "it was never sent SIGTERM first"); + let shell: i32 = std::fs::read_to_string(&started) + .unwrap() + .trim() + .parse() + .unwrap(); + // SAFETY: signal 0 only asks whether the process is there. + assert_ne!(unsafe { libc::kill(shell, 0) }, 0, "it ran on"); } #[test] @@ -2005,6 +3464,9 @@ mod tests { let odd = Git { exe: quoted.join("git"), quiet: GIT_TIMEOUT, + cancel: None, + term_grace: TERM_GRACE, + watch: Watch::default(), }; let b = dir.path().join("book"); let s = book(&b); diff --git a/crates/ledger-store/src/cancel.rs b/crates/ledger-store/src/cancel.rs new file mode 100644 index 00000000..f9bb0a45 --- /dev/null +++ b/crates/ledger-store/src/cancel.rs @@ -0,0 +1,84 @@ +//! A stop request the long loops over a book's journal and files look at +//! (a backup's drill or proof, ledger-store `backup`): a step that has to +//! end when the books are let go (a close) can't wait for a replay of a +//! journal of any length to come to its end. +//! +//! ```text +//! GOAL: a verification over a book's journal or files that was asked to +//! stop stops promptly, at its next step, and leaves nothing of its +//! own half-made, however large the book. +//! SOURCE: the books server's close (ledger-mcp local.rs INVARIANT 10 and +//! 13: a close is answered only when nothing of its backups still +//! runs, and is bounded). +//! INVARIANTS: +//! 1. A request is scoped to the thread that made it (`scope`), for as +//! long as the scope lives; code on other threads, and code outside a +//! scope, never sees one. Nothing is shared, so no other work of the +//! process can be stopped by it. +//! 2. `check` is looked at once per journal line (verifying, replaying, +//! applying to the projection), once per stored file hashed, and at +//! the boundaries between a verification's phases: the longest it +//! goes without looking is one line or one file. +//! 3. A stop is an error (`StoreError::Cancelled`), never a partial +//! success: what a stopped verification had made is the caller's to +//! remove (the books it was opened on are a scratch folder's). +//! 4. A step that can't be left half-made is shielded (`shielded`): the +//! stop is looked at before it begins, never inside it. The database's +//! rebuild from the journal (`verify_and_heal`, healing a drift) is +//! one: stopped part way it would leave the live ledger part replayed. +//! The look comes before ANYTHING is done for the heal (the database +//! copied aside included), so a stopped heal leaves nothing behind. +//! ``` + +use crate::error::StoreError; +use std::cell::RefCell; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +thread_local! { + static FLAG: RefCell>> = const { RefCell::new(None) }; +} + +/// A stop request in force on this thread, until dropped. +pub struct Scope(Option>); + +impl Drop for Scope { + fn drop(&mut self) { + FLAG.with(|f| *f.borrow_mut() = self.0.take()); + } +} + +/// Look for `flag` (INVARIANT 1) on this thread, until the returned scope +/// is dropped (the request in force before it comes back). +#[must_use] +pub fn scope(flag: Arc) -> Scope { + Scope(FLAG.with(|f| f.borrow_mut().replace(flag))) +} + +/// Run `f` with no stop in force on this thread (the request in force +/// before comes back after): for the one step that can't be left half-made, +/// such as rebuilding the database from the journal, which would leave the +/// live ledger part replayed. +pub fn shielded(f: impl FnOnce() -> R) -> R { + let outer = FLAG.with(|flag| flag.borrow_mut().take()); + let _restore = Scope(outer); + f() +} + +/// Whether a stop was asked for. +pub fn requested() -> bool { + FLAG.with(|f| { + f.borrow() + .as_ref() + .is_some_and(|c| c.load(Ordering::SeqCst)) + }) +} + +/// Ok, or `StoreError::Cancelled` when a stop was asked for (INVARIANT 2). +pub fn check() -> Result<(), StoreError> { + if requested() { + Err(StoreError::Cancelled) + } else { + Ok(()) + } +} diff --git a/crates/ledger-store/src/chain.rs b/crates/ledger-store/src/chain.rs index b7ce5fbb..3970171a 100644 --- a/crates/ledger-store/src/chain.rs +++ b/crates/ledger-store/src/chain.rs @@ -28,6 +28,11 @@ //! 4. Only an unfinished last line (no newline: an append cut short by //! a crash, never acknowledged) is set aside: open cuts it away, //! read reports it. +//! 5. A log can be closed (`close`), and a closed log takes no more +//! appends, ever: a holder of it from before the book was let go can +//! never write after the book is opened again, when a new log is +//! opened on the file against its own head (an append from the old +//! handle would break the chain there). //! ``` use crate::journal::{canonical_json, sha256_hex}; @@ -60,6 +65,8 @@ pub enum ChainError { Io(std::io::ErrorKind), /// An earlier append failed: the log must be reopened (INVARIANT 2). Broken, + /// The log was closed: its book was let go (INVARIANT 5). + Closed, } impl std::fmt::Display for ChainError { @@ -68,6 +75,7 @@ impl std::fmt::Display for ChainError { ChainError::Damaged { line, why } => write!(f, "record {line} is damaged: {why}"), ChainError::Io(kind) => write!(f, "the disk refused: {kind}"), ChainError::Broken => f.write_str("an earlier record couldn't be written"), + ChainError::Closed => f.write_str("the log was closed: its books are not open"), } } } @@ -168,6 +176,7 @@ pub struct ChainLog { file: File, head: Head, broken: bool, + closed: bool, } impl std::fmt::Debug for ChainLog { @@ -175,6 +184,7 @@ impl std::fmt::Debug for ChainLog { f.debug_struct("ChainLog") .field("head", &self.head) .field("broken", &self.broken) + .field("closed", &self.closed) .finish_non_exhaustive() } } @@ -224,6 +234,7 @@ impl ChainLog { file, head: read.head, broken: false, + closed: false, }, read.records, )) @@ -234,6 +245,11 @@ impl ChainLog { &self.head } + /// Take no more appends, ever (INVARIANT 5). + pub fn close(&mut self) { + self.closed = true; + } + /// The log's file. pub fn path(&self) -> &Path { &self.path @@ -243,6 +259,9 @@ impl ChainLog { /// and `hash` (which `fields` must not hold). Returns the record as /// written and the new head (INVARIANT 2). pub fn append(&mut self, fields: Map) -> Result<(Value, Head), ChainError> { + if self.closed { + return Err(ChainError::Closed); + } if self.broken { return Err(ChainError::Broken); } @@ -600,6 +619,7 @@ mod tests { hash: genesis(G), }, broken: false, + closed: false, }; assert!(matches!(log.append(fields(1)), Err(ChainError::Io(_)))); assert_eq!(log.head().seq, 0, "the head didn't move"); diff --git a/crates/ledger-store/src/error.rs b/crates/ledger-store/src/error.rs index e8c253d8..95716935 100644 --- a/crates/ledger-store/src/error.rs +++ b/crates/ledger-store/src/error.rs @@ -5,6 +5,10 @@ use thiserror::Error; /// Every way a store operation can fail. #[derive(Debug, Error)] pub enum StoreError { + /// A verification was told to stop ([`crate::cancel`]): the books it + /// was reading are being let go. + #[error("stopped: the books are closing")] + Cancelled, /// An attachment link names a subject that doesn't exist. #[error("no {0} to link to")] UnknownSubject(String), diff --git a/crates/ledger-store/src/exports.rs b/crates/ledger-store/src/exports.rs index 122f08a3..8986d41d 100644 --- a/crates/ledger-store/src/exports.rs +++ b/crates/ledger-store/src/exports.rs @@ -21,6 +21,13 @@ //! lapsed ones are swept when the books open, whenever one is made, //! and by the server's sweeper. A token has at most MAX_LIVE. //! 4. No error names a path. +//! 5. Exports can be closed (`close`, under the lock every change to the +//! folder is made under): after it none is made, given or swept by +//! any holder of these exports from before, so a book let go is +//! never touched by a late request or a sweep, whoever has it open +//! by then. A fetch (`get`) reads under that lock: `close` waits for +//! one under way, so no byte of a closed book's folder is read for a +//! caller after `close` has returned. //! ``` use crate::journal::sha256_hex; @@ -87,8 +94,9 @@ impl From for ExportError { #[derive(Debug, Clone)] pub struct Exports { dir: PathBuf, - /// Held while exports are made or swept (INVARIANT 3). - lock: std::sync::Arc>, + /// Held while exports are made or swept (INVARIANT 3). True once + /// closed (INVARIANT 5). + lock: std::sync::Arc>, } /// `ex_` and 32 letters `a` to `p`, a letter a nibble (INVARIANT 1). @@ -132,10 +140,16 @@ impl Exports { Ok(exports) } - fn locked(&self) -> std::sync::MutexGuard<'_, ()> { + fn locked(&self) -> std::sync::MutexGuard<'_, bool> { self.lock.lock().unwrap_or_else(|e| e.into_inner()) } + /// Change nothing in these exports, and give none, from now on + /// (INVARIANT 5): waits for the change being made, if one is. + pub fn close(&self) { + *self.locked() = true; + } + fn path(&self, id: &str, ext: &str) -> PathBuf { self.dir.join(format!("{id}.{ext}")) } @@ -152,7 +166,10 @@ impl Exports { if let Some(why) = file_name_problem(file_name).or_else(|| mime_problem(mime)) { return Err(ExportError::Bad(why)); } - let _held = self.locked(); + let held = self.locked(); + if *held { + return Err(ExportError::Bad("the books aren't open".into())); + } self.sweep_held(now); if self.live_for(token, now) >= MAX_LIVE { return Err(ExportError::Bad(format!( @@ -196,6 +213,12 @@ impl Exports { return Err(ExportError::Unknown(id.chars().take(40).collect())); } let unknown = || ExportError::Unknown(id.to_string()); + // Read under the lock a close takes (INVARIANT 5): `close` waits + // for a fetch under way, and none begins after it. + let held = self.locked(); + if *held { + return Err(ExportError::Bad("the books aren't open".into())); + } let record = std::fs::read(self.path(id, "json")).map_err(|_| unknown())?; let export: Export = serde_json::from_slice(&record).map_err(|_| unknown())?; if export.expires <= now { @@ -205,6 +228,7 @@ impl Exports { return Err(ExportError::NotYours); } let bytes = std::fs::read(self.path(id, "bin")).map_err(|_| unknown())?; + drop(held); if bytes.len() as u64 != export.size || sha256_hex(&bytes) != export.sha256 { return Err(ExportError::Damaged); } @@ -228,8 +252,10 @@ impl Exports { /// Sweep away every export that lapsed by `now`, and anything left /// without one (INVARIANT 3). pub fn sweep(&self, now: i64) { - let _held = self.locked(); - self.sweep_held(now); + let held = self.locked(); + if !*held { + self.sweep_held(now); + } } fn sweep_held(&self, now: i64) { @@ -259,6 +285,99 @@ mod tests { const NOW: i64 = 1_800_000_000; + /// Closed, exports are made, given and swept by no one (INVARIANT 5). + #[test] + fn closed_exports_change_nothing_and_give_nothing() { + let dir = tempfile::tempdir().unwrap(); + let x = Exports::open(dir.path(), NOW).unwrap(); + let e = x.put("t", "a.csv", "text/csv", b"x", NOW).unwrap(); + x.close(); + let seen = || { + let mut names: Vec<_> = std::fs::read_dir(dir.path().join(EXPORTS_DIR)) + .unwrap() + .map(|f| f.unwrap().file_name()) + .collect(); + names.sort(); + names + }; + let before = seen(); + assert!(x.put("t", "b.csv", "text/csv", b"y", NOW).is_err()); + assert!(x.get(&e.id, "t", NOW).is_err()); + // A sweep long after everything lapsed removes nothing. + x.sweep(NOW + 10 * EXPORT_TTL); + assert_eq!(seen(), before); + } + + /// INVARIANT 5: a fetch reads under the lock a close takes, so a close + /// waits for the fetch under way instead of returning while bytes of + /// the folder are still being read for a caller. The fetch is held + /// inside its read (the export's file is a named pipe nothing writes + /// to yet), and `close` must not return until it is let go. + #[cfg(unix)] + #[test] + fn a_close_waits_for_a_fetch_that_is_reading() { + let dir = tempfile::tempdir().unwrap(); + let x = Exports::open(dir.path(), NOW).unwrap(); + let e = x.put("t", "a.csv", "text/csv", b"x", NOW).unwrap(); + let bin = x.path(&e.id, "bin"); + std::fs::remove_file(&bin).unwrap(); + let made = std::process::Command::new("mkfifo").arg(&bin).status(); + assert!(made.unwrap().success()); + let fetching = { + let (x, id) = (x.clone(), e.id.clone()); + std::thread::spawn(move || x.get(&id, "t", NOW)) + }; + // The fetch holds the lock, blocked opening the pipe for reading (no + // writer yet). A writer can be opened without blocking only once a + // reader has the pipe open, so that is the condition waited for (the + // writer, kept, is the one that lets the read end later). + use std::os::unix::fs::OpenOptionsExt; + let by = std::time::Instant::now() + std::time::Duration::from_secs(60); + let writer = loop { + match std::fs::OpenOptions::new() + .write(true) + .custom_flags(libc::O_NONBLOCK) + .open(&bin) + { + Ok(w) => break w, + Err(_) => { + assert!( + std::time::Instant::now() < by, + "the fetch never reached the pipe" + ); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + } + }; + let (begun, started) = std::sync::mpsc::channel(); + let (done, closed) = std::sync::mpsc::channel(); + let closing = { + let x = x.clone(); + std::thread::spawn(move || { + let _ = begun.send(()); + x.close(); + let _ = done.send(()); + }) + }; + started.recv().unwrap(); + // A negative window: it can only fail if the close returned, never + // because the machine was slow. + assert!( + closed + .recv_timeout(std::time::Duration::from_millis(500)) + .is_err(), + "the close returned while a fetch was reading the folder" + ); + // A writer that sends nothing lets the read end (an empty file, + // not the size kept: the fetch is refused). + drop(writer); + assert!(fetching.join().unwrap().is_err()); + closed + .recv_timeout(std::time::Duration::from_secs(5)) + .expect("the close returns once the fetch has ended"); + closing.join().unwrap(); + } + #[test] fn an_export_is_kept_fifteen_minutes() { // What its refusal tells the human: kept 15 minutes, then gone. diff --git a/crates/ledger-store/src/git_locks.rs b/crates/ledger-store/src/git_locks.rs new file mode 100644 index 00000000..65d90af9 --- /dev/null +++ b/crates/ledger-store/src/git_locks.rs @@ -0,0 +1,554 @@ +//! The lock files a git leaves in a repository, found and (only where it +//! is ours to) removed through a directory handle (ledger-store `backup` +//! INVARIANT 5). +//! +//! ```text +//! GOAL: a lock file a stopped git left can be seen, and removed from the +//! one repository this program owns, without ever touching anything +//! a swapped folder or link points to. +//! SOURCE: the books server's close (ledger-mcp local.rs INVARIANT 10, 13: +//! a close is answered with no git of ours still working, and +//! leaves nothing a person must clean up); git's own lock files +//! (git-config, gitrepository-layout: `HEAD.lock`, `index.lock`, +//! `.lock`, `packed-refs.lock`, `shallow.lock`, +//! `config.lock`). +//! INVARIANTS: +//! 1. A repository is opened once (`RepoDir::open`, `open_in`): a +//! directory that is not a link, the folder it was found in kept as +//! the book's own. Every look and every removal after that goes +//! through that handle: the folders below it (`refs/`, and those +//! under it) are each opened from the one above with links refused, +//! so a folder swapped for a link, or the repository's own path swapped +//! for one, after the handle was opened, sends nothing anywhere: the +//! handle still names the folder that was opened. +//! 2. Only a regular file is ever removed (never a link, never a folder, +//! never a file whose type changed), and only one named as git names +//! its locks, in the places git puts them (`is_lock`). A name that +//! isn't one is refused. +//! 3. Where there is no directory handle to be had (not Unix) each step +//! looks at the path itself and refuses a link: the same rules, +//! without the guarantee against a swap in between. Nothing else +//! about the platform's behaviour is designed here. +//! ``` + +use std::io; +use std::path::{Path, PathBuf}; +use std::time::SystemTime; + +/// Locks git makes in a repository's own folder. +const TOP: [&str; 5] = [ + "HEAD.lock", + "index.lock", + "config.lock", + "packed-refs.lock", + "shallow.lock", +]; +/// Locks git makes below it, outside `refs/`. +const BELOW: [&str; 2] = [ + "objects/info/commit-graph.lock", + "objects/pack/multi-pack-index.lock", +]; +/// How deep under `refs/` a lock is looked for. +const REFS_DEPTH: usize = 12; + +/// Whether `rel` (a path in a repository, with `/` between its parts) is +/// named as git names a lock, in a place git puts one (INVARIANT 2). +pub fn is_lock(rel: &str) -> bool { + if TOP.contains(&rel) || BELOW.contains(&rel) { + return true; + } + let Some(under) = rel.strip_prefix("refs/") else { + return false; + }; + let parts: Vec<&str> = under.split('/').collect(); + parts.len() <= REFS_DEPTH + && parts + .iter() + .all(|p| !p.is_empty() && *p != "." && *p != "..") + && parts + .last() + .is_some_and(|name| name.len() > ".lock".len() && name.ends_with(".lock")) +} + +/// A lock found: its path in the repository, and when it was last written. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Found { + /// `index.lock`, `refs/heads/main.lock`. + pub lock: String, + /// Its modification time, when the system said. + pub modified: Option, +} + +/// A repository's folder, opened once (INVARIANT 1). +#[derive(Debug)] +pub struct RepoDir { + path: PathBuf, + inner: imp::Dir, +} + +impl RepoDir { + /// The folder at `path`, which must not itself be a link. + pub fn open(path: &Path) -> io::Result { + Ok(RepoDir { + path: path.to_path_buf(), + inner: imp::open(path)?, + }) + } + + /// The folder `name` inside the folder `parent` (the book's own folder + /// holding its archive): `name` must not be a link. + pub fn open_in(parent: &Path, name: &str) -> io::Result { + Ok(RepoDir { + path: parent.join(name), + inner: imp::open_in(parent, name)?, + }) + } + + /// The path it was opened by (for words, never for an operation). + pub fn path(&self) -> &Path { + &self.path + } + + /// The locks in it, sorted: regular files named as git names its locks. + pub fn locks(&self) -> Vec { + let mut out = Vec::new(); + for rel in TOP.iter().chain(BELOW.iter()) { + if let Some(modified) = self.inner.regular(rel) { + out.push(Found { + lock: (*rel).to_string(), + modified, + }); + } + } + self.inner.refs(&mut out, REFS_DEPTH); + out.sort_by(|a, b| a.lock.cmp(&b.lock)); + out + } + + /// Remove the lock `rel` (INVARIANTS 1, 2): Ok(true) if a regular file + /// of that name was removed, Ok(false) if there was none (or it was + /// not a regular file: nothing was done), Err if the name isn't a + /// lock's or the system refused. + pub fn remove(&self, rel: &str) -> io::Result { + if !is_lock(rel) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "not a name git gives a lock", + )); + } + self.inner.remove(rel) + } +} + +#[cfg(unix)] +mod imp { + use super::{Found, SystemTime}; + use std::ffi::{CStr, CString, OsStr}; + use std::io; + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; + use std::os::unix::ffi::OsStrExt; + use std::path::Path; + + #[derive(Debug)] + pub struct Dir(OwnedFd); + + const FLAGS: libc::c_int = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC; + + fn c(text: &OsStr) -> io::Result { + CString::new(text.as_bytes()) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "a name with a NUL")) + } + + fn owned(fd: libc::c_int) -> io::Result { + if fd < 0 { + Err(io::Error::last_os_error()) + } else { + // SAFETY: a file descriptor just returned by the system, owned + // by no one else. + Ok(unsafe { OwnedFd::from_raw_fd(fd) }) + } + } + + pub fn open(path: &Path) -> io::Result { + let path = c(path.as_os_str())?; + // SAFETY: a NUL-ended path; the flags refuse a link at its end. + owned(unsafe { libc::open(path.as_ptr(), FLAGS | libc::O_NOFOLLOW) }).map(Dir) + } + + pub fn open_in(parent: &Path, name: &str) -> io::Result { + let parent = c(parent.as_os_str())?; + // SAFETY: as in `open`; the parent may be reached through links (it + // is the book's own folder), only `name` may not be one. + let parent = owned(unsafe { libc::open(parent.as_ptr(), FLAGS) })?; + sub(parent.as_raw_fd(), name).map(Dir) + } + + /// The folder `name` of `dir`, a link refused. + fn sub(dir: RawFd, name: &str) -> io::Result { + let name = c(OsStr::new(name))?; + // SAFETY: `dir` is open for the call; the name is NUL-ended. + owned(unsafe { libc::openat(dir, name.as_ptr(), FLAGS | libc::O_NOFOLLOW) }) + } + + /// `name` in `dir` as it is (a link is not followed): its stat. + fn stat(dir: RawFd, name: &str) -> io::Result { + let name = c(OsStr::new(name))?; + // SAFETY: zeroed stat is a valid out-parameter; `dir` is open. + let mut st: libc::stat = unsafe { std::mem::zeroed() }; + let found = + unsafe { libc::fstatat(dir, name.as_ptr(), &mut st, libc::AT_SYMLINK_NOFOLLOW) }; + if found == 0 { + Ok(st) + } else { + Err(io::Error::last_os_error()) + } + } + + fn is_regular(st: &libc::stat) -> bool { + (st.st_mode & libc::S_IFMT) == libc::S_IFREG + } + + fn is_dir(st: &libc::stat) -> bool { + (st.st_mode & libc::S_IFMT) == libc::S_IFDIR + } + + fn modified(st: &libc::stat) -> Option { + let secs = u64::try_from(st.st_mtime).ok()?; + let nanos = u32::try_from(st.st_mtime_nsec).ok()?; + Some(SystemTime::UNIX_EPOCH + std::time::Duration::new(secs, nanos)) + } + + /// The names in the folder `dir` (a fresh look each time). + fn names(dir: RawFd) -> Vec { + // SAFETY: a duplicate of an open descriptor, handed to fdopendir, + // which owns it from then on (closedir closes it). + let copy = unsafe { libc::dup(dir) }; + if copy < 0 { + return Vec::new(); + } + let stream = unsafe { libc::fdopendir(copy) }; + if stream.is_null() { + // SAFETY: fdopendir didn't take it. + unsafe { libc::close(copy) }; + return Vec::new(); + } + let mut out = Vec::new(); + // SAFETY: `stream` is a live directory stream until closedir; each + // entry's name is a NUL-ended string valid until the next readdir. + unsafe { + libc::rewinddir(stream); + loop { + let entry = libc::readdir(stream); + if entry.is_null() { + break; + } + let name = CStr::from_ptr((*entry).d_name.as_ptr()); + if let Ok(name) = name.to_str() + && name != "." + && name != ".." + { + out.push(name.to_string()); + } + } + libc::closedir(stream); + } + out + } + + impl Dir { + /// The folder holding `rel`, opened step by step from this one + /// with a link refused at each, and `rel`'s last part. + fn parent_of<'a>(&self, rel: &'a str) -> io::Result<(OwnedFd, &'a str)> { + let mut parts: Vec<&str> = rel.split('/').collect(); + let last = parts.pop().ok_or(io::ErrorKind::InvalidInput)?; + // SAFETY: a duplicate of the open descriptor, owned here. + let mut here = owned(unsafe { libc::dup(self.0.as_raw_fd()) })?; + for part in parts { + here = sub(here.as_raw_fd(), part)?; + } + Ok((here, last)) + } + + /// A regular file at `rel`: its modification time (when known). + pub fn regular(&self, rel: &str) -> Option> { + let (parent, name) = self.parent_of(rel).ok()?; + let st = stat(parent.as_raw_fd(), name).ok()?; + is_regular(&st).then(|| modified(&st)) + } + + /// The locks under `refs/`, in `out`. + pub fn refs(&self, out: &mut Vec, depth: usize) { + let Ok(refs) = sub(self.0.as_raw_fd(), "refs") else { + return; + }; + fn walk(dir: RawFd, prefix: &str, depth: usize, out: &mut Vec) { + for name in names(dir) { + let Ok(st) = stat(dir, &name) else { continue }; + let rel = format!("{prefix}{name}"); + if is_regular(&st) { + if super::is_lock(&rel) { + out.push(Found { + lock: rel, + modified: modified(&st), + }); + } + } else if is_dir(&st) + && depth > 0 + && let Ok(inner) = sub(dir, &name) + { + walk(inner.as_raw_fd(), &format!("{rel}/"), depth - 1, out); + } + } + } + walk(refs.as_raw_fd(), "refs/", depth, out); + } + + pub fn remove(&self, rel: &str) -> io::Result { + let (parent, name) = match self.parent_of(rel) { + Ok(found) => found, + // A folder that isn't there (or is a link): nothing to remove. + Err(_) => return Ok(false), + }; + match stat(parent.as_raw_fd(), name) { + Ok(st) if is_regular(&st) => {} + _ => return Ok(false), + } + let name = c(OsStr::new(name))?; + // SAFETY: the parent is open; the name is NUL-ended and relative + // to it, and names a regular file just looked at. + let removed = unsafe { libc::unlinkat(parent.as_raw_fd(), name.as_ptr(), 0) }; + if removed == 0 { + Ok(true) + } else { + let e = io::Error::last_os_error(); + if e.kind() == io::ErrorKind::NotFound { + Ok(false) + } else { + Err(e) + } + } + } + } +} + +#[cfg(not(unix))] +mod imp { + use super::{Found, SystemTime}; + use std::io; + use std::path::{Path, PathBuf}; + + #[derive(Debug)] + pub struct Dir(PathBuf); + + fn plain(path: &Path) -> io::Result<()> { + let meta = std::fs::symlink_metadata(path)?; + if meta.file_type().is_symlink() || !meta.is_dir() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "not a plain folder", + )); + } + Ok(()) + } + + pub fn open(path: &Path) -> io::Result { + plain(path)?; + Ok(Dir(path.to_path_buf())) + } + + pub fn open_in(parent: &Path, name: &str) -> io::Result { + open(&parent.join(name)) + } + + impl Dir { + fn at(&self, rel: &str) -> io::Result { + let mut path = self.0.clone(); + let mut parts: Vec<&str> = rel.split('/').collect(); + let last = parts.pop().ok_or(io::ErrorKind::InvalidInput)?; + for part in parts { + path.push(part); + plain(&path)?; + } + path.push(last); + Ok(path) + } + + pub fn regular(&self, rel: &str) -> Option> { + let path = self.at(rel).ok()?; + let meta = std::fs::symlink_metadata(path).ok()?; + meta.file_type().is_file().then(|| meta.modified().ok()) + } + + pub fn refs(&self, out: &mut Vec, depth: usize) { + fn walk(dir: &Path, prefix: &str, depth: usize, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for e in entries.flatten() { + let Ok(meta) = std::fs::symlink_metadata(e.path()) else { + continue; + }; + let rel = format!("{prefix}{}", e.file_name().to_string_lossy()); + if meta.file_type().is_file() { + if super::is_lock(&rel) { + out.push(Found { + lock: rel, + modified: meta.modified().ok(), + }); + } + } else if meta.is_dir() && !meta.file_type().is_symlink() && depth > 0 { + walk(&e.path(), &format!("{rel}/"), depth - 1, out); + } + } + } + let refs = self.0.join("refs"); + if plain(&refs).is_ok() { + walk(&refs, "refs/", depth, out); + } + } + + pub fn remove(&self, rel: &str) -> io::Result { + let Ok(path) = self.at(rel) else { + return Ok(false); + }; + match std::fs::symlink_metadata(&path) { + Ok(meta) if meta.file_type().is_file() => std::fs::remove_file(path).map(|()| true), + _ => Ok(false), + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn repo(dir: &Path) -> PathBuf { + let repo = dir.join("repo.git"); + std::fs::create_dir_all(repo.join("refs/heads")).unwrap(); + std::fs::create_dir_all(repo.join("objects/pack")).unwrap(); + std::fs::create_dir_all(repo.join("objects/info")).unwrap(); + repo + } + + #[test] + fn only_the_names_git_gives_its_locks_are_locks() { + for yes in [ + "HEAD.lock", + "index.lock", + "config.lock", + "packed-refs.lock", + "shallow.lock", + "refs/heads/main.lock", + "refs/heads/feature/x.lock", + "refs/tags/v1.lock", + "objects/info/commit-graph.lock", + "objects/pack/multi-pack-index.lock", + ] { + assert!(is_lock(yes), "{yes}"); + } + for no in [ + "", + ".lock", + "refs/.lock", + "refs/heads/", + "refs/heads/main", + "refs/heads/../../x.lock", + "refs//x.lock", + "refs/heads/./x.lock", + "other.lock", + "objects/pack/pack-1.pack", + "objects/other.lock", + "../index.lock", + "/etc/x.lock", + "hooks/pre-commit.lock", + "refs", + ] { + assert!(!is_lock(no), "{no:?}"); + } + } + + #[test] + fn locks_are_found_and_only_regular_files_are_removed() { + let dir = tempfile::tempdir().unwrap(); + let repo = repo(dir.path()); + std::fs::write(repo.join("index.lock"), b"").unwrap(); + std::fs::write(repo.join("refs/heads/main.lock"), b"").unwrap(); + // Named like locks, but not files: neither is listed nor removed. + std::fs::create_dir(repo.join("HEAD.lock")).unwrap(); + std::fs::write(dir.path().join("elsewhere"), b"").unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink(dir.path().join("elsewhere"), repo.join("config.lock")).unwrap(); + // Not a lock's name. + std::fs::write(repo.join("refs/heads/main"), b"").unwrap(); + let handle = RepoDir::open(&repo).unwrap(); + let found: Vec = handle.locks().into_iter().map(|f| f.lock).collect(); + assert_eq!(found, ["index.lock", "refs/heads/main.lock"]); + assert!(handle.locks().iter().all(|f| f.modified.is_some())); + assert!(handle.remove("index.lock").unwrap()); + assert!(!handle.remove("index.lock").unwrap(), "already gone"); + assert!(!handle.remove("HEAD.lock").unwrap(), "a folder stays"); + assert!(repo.join("HEAD.lock").is_dir()); + #[cfg(unix)] + { + assert!(!handle.remove("config.lock").unwrap(), "a link stays"); + assert!(repo.join("config.lock").is_symlink()); + assert!(dir.path().join("elsewhere").exists()); + } + assert!(handle.remove("refs/heads/main").is_err(), "not a lock"); + assert!(repo.join("refs/heads/main").exists()); + assert!(handle.remove("../elsewhere.lock").is_err()); + } + + /// INVARIANT 1: a folder (or the repository's own path) swapped for a + /// link after the handle was opened sends nothing anywhere. + #[cfg(unix)] + #[test] + fn a_folder_swapped_for_a_link_after_the_handle_was_opened_touches_nothing_outside() { + let dir = tempfile::tempdir().unwrap(); + let outside = dir.path().join("outside"); + std::fs::create_dir_all(outside.join("refs/heads")).unwrap(); + for lock in ["index.lock", "HEAD.lock", "refs/heads/main.lock"] { + std::fs::write(outside.join(lock), b"theirs").unwrap(); + } + // `refs` swapped for a link to a folder holding a lock of that name. + let repo_path = repo(dir.path()); + std::fs::write(repo_path.join("refs/heads/main.lock"), b"ours").unwrap(); + let handle = RepoDir::open(&repo_path).unwrap(); + std::fs::rename(repo_path.join("refs"), dir.path().join("refs-moved")).unwrap(); + std::os::unix::fs::symlink(outside.join("refs"), repo_path.join("refs")).unwrap(); + assert!(!handle.remove("refs/heads/main.lock").unwrap()); + assert!(handle.locks().is_empty(), "a link is not looked through"); + assert_eq!( + std::fs::read(outside.join("refs/heads/main.lock")).unwrap(), + b"theirs" + ); + assert_eq!( + std::fs::read(dir.path().join("refs-moved/heads/main.lock")).unwrap(), + b"ours", + "nor was the folder it moved to touched through the link" + ); + // The repository's own path swapped for a link: the handle still + // names the folder it opened (moved aside), and the link's target + // is never touched. + let second = dir.path().join("second.git"); + std::fs::create_dir_all(second.join("refs")).unwrap(); + std::fs::write(second.join("index.lock"), b"ours").unwrap(); + let handle = RepoDir::open(&second).unwrap(); + std::fs::rename(&second, dir.path().join("second-moved.git")).unwrap(); + std::os::unix::fs::symlink(&outside, &second).unwrap(); + assert!(handle.remove("index.lock").unwrap()); + assert!(!dir.path().join("second-moved.git/index.lock").exists()); + assert_eq!( + std::fs::read(outside.join("index.lock")).unwrap(), + b"theirs", + "the link's target was touched" + ); + assert_eq!(std::fs::read(outside.join("HEAD.lock")).unwrap(), b"theirs"); + // And a repository that is a link when the handle is opened is + // refused, with the archive's own `open_in` too. + assert!(RepoDir::open(&second).is_err()); + assert!(RepoDir::open_in(dir.path(), "second.git").is_err()); + assert!(RepoDir::open_in(dir.path(), "second-moved.git").is_ok()); + } +} diff --git a/crates/ledger-store/src/journal.rs b/crates/ledger-store/src/journal.rs index 43bb4058..48cfda14 100644 --- a/crates/ledger-store/src/journal.rs +++ b/crates/ledger-store/src/journal.rs @@ -317,6 +317,7 @@ fn verify_lines( let mut expected_prev = GENESIS_PREV.to_string(); let mut raws = body.split(|&b| b == b'\n').enumerate().peekable(); while let Some((i, raw)) = raws.next() { + crate::cancel::check()?; let read = read_line(raw).map_err(|e| { StoreError::JournalCorrupt(format!("seq {}: unparseable line: {e}", i + 1)) })?; diff --git a/crates/ledger-store/src/lib.rs b/crates/ledger-store/src/lib.rs index 0ba779d1..eb3477cb 100644 --- a/crates/ledger-store/src/lib.rs +++ b/crates/ledger-store/src/lib.rs @@ -22,12 +22,14 @@ pub mod access; pub mod auth; pub mod backup; pub mod blob; +pub mod cancel; pub mod chain; pub mod describe; pub mod error; pub mod exports; pub mod form1099; pub mod format; +pub mod git_locks; pub mod journal; pub mod lock; pub mod meta; diff --git a/crates/ledger-store/src/root.rs b/crates/ledger-store/src/root.rs index c318ec5e..ca4347e8 100644 --- a/crates/ledger-store/src/root.rs +++ b/crates/ledger-store/src/root.rs @@ -29,7 +29,16 @@ //! file if the source never had one), and a new book appears in the //! root only whole: every stored file re-hashed against its name, //! every file the books name present, verified end to end, synced to -//! disk, and its head equal to the source's. +//! disk, and its head equal to the source's. The original is left as it +//! was: a lock file the adoption made in the source is removed again, +//! exactly that file and no other, on every way out but its success +//! (stopped by the books server's close, refused, or a panic); one the +//! source already had is never removed. A success leaves the one it +//! made, and says so (`source_lock_created`). Books are made, adopted +//! and restored one at a time across processes (`run/books.lock`), and +//! a job waiting for its turn looks at its stop every few milliseconds +//! and leaves at once when asked, so a close of the books is never held +//! up by a job that is only queued. //! 6. No error names the root or a path inside it: nothing an agent is //! shown names the books' folder. //! 7. Restoring a backup (plan 3.7) is proven before use, as an adoption @@ -116,6 +125,10 @@ pub enum RootError { /// Adopting was refused, with why. #[error("{0}")] Adopt(String), + /// A job was stopped because the books are closing, before its point of + /// no return ([`JobStop`]): nothing it did is left. + #[error("{0}")] + Stopped(String), /// The store refused (its message with the root's path taken out). #[error("{0}")] Store(String, #[source] StoreError), @@ -146,6 +159,87 @@ impl From for RootError { } } +/// What a job that changes which books the root holds (create, adopt, +/// restore) is asked, as it goes, whether it must stop (the books server's +/// close): looked at as each phase begins and once per stored file copied; +/// a job stops, removes what it made, and leaves the books exactly as they +/// were. Each job has a point of no return (the rename that puts its books +/// in place), after which nothing is asked and the job finishes: a few +/// renames and directory syncs, so short and bounded. +#[derive(Clone)] +pub struct JobStop { + flag: std::sync::Arc, + phase: Option, +} + +/// What is told the name of each phase of a job as it begins +/// ([`JobStop::with_phase_watch`]). +pub type JobPhaseWatch = std::sync::Arc; + +impl JobStop { + /// Stop when `flag` is set. + pub fn new(flag: std::sync::Arc) -> Self { + Self { flag, phase: None } + } + + /// Never asked to stop (a command run on its own, not in the server). + pub fn never() -> Self { + Self::new(std::sync::Arc::default()) + } + + /// Told the name of each phase as it begins, before the stop is looked + /// at (a seam for tests, and the server's test knob that holds a job + /// inside a phase: it may wait, but must give up when the flag is set). + #[must_use] + pub fn with_phase_watch(mut self, watch: JobPhaseWatch) -> Self { + self.phase = Some(watch); + self + } + + /// The flag: what git and the store's loops are handed to look at. + pub fn flag(&self) -> std::sync::Arc { + self.flag.clone() + } + + /// Whether a stop was asked for. + pub fn requested(&self) -> bool { + self.flag.load(std::sync::atomic::Ordering::SeqCst) + } + + /// A phase begins, for a caller that decides for itself what to do about + /// a stop: whether one was asked for (the phase watch is told first). + pub fn look(&self, phase: &str) -> bool { + if let Some(watch) = &self.phase { + watch(phase); + } + self.requested() + } + + /// A phase begins: Ok, or `Stopped` (naming what was not done). + fn at(&self, phase: &str, undone: &str) -> Result<(), RootError> { + if let Some(watch) = &self.phase { + watch(phase); + } + if self.requested() { + Err(RootError::Stopped(format!( + "stopped because the books are closing: nothing was {undone}" + ))) + } else { + Ok(()) + } + } + + /// A stop that reached the store's own loops or git, said as a job's. + fn said(&self, e: RootError, undone: &str) -> RootError { + match e { + RootError::Store(_, StoreError::Cancelled) => RootError::Stopped(format!( + "stopped because the books are closing: nothing was {undone}" + )), + other => other, + } + } +} + /// A book's id within the root: its folder name under `books/`. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct BookId(String); @@ -731,8 +825,11 @@ impl Root { } /// Take the lock under which books are made: one at a time, across - /// processes. - fn books_lock(&self) -> Result { + /// processes. A job that has to wait for another's turn looks at `stop` + /// while it waits (every few milliseconds), and gives up with `Stopped` + /// if asked: a close of the books can't be held up by a job that is + /// only waiting its turn behind another. + fn books_lock(&self, stop: &JobStop, undone: &str) -> Result { let (run, _) = self.private_subdir(RUN_DIR, false)?; let path = run.join(BOOKS_LOCK); let file = std::fs::OpenOptions::new() @@ -741,24 +838,56 @@ impl Root { .write(true) .open(&path)?; set_mode(&path, 0o600)?; - file.lock()?; - Ok(file) + loop { + match file.try_lock() { + Ok(()) => return Ok(file), + Err(std::fs::TryLockError::WouldBlock) => { + // The flag alone: the phase watch is told of phases, not + // of every turn of this wait. + if stop.requested() { + return Err(RootError::Stopped(format!( + "stopped because the books are closing: nothing was {undone}" + ))); + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + Err(std::fs::TryLockError::Error(e)) => return Err(e.into()), + } + } } /// Start new, empty books called `id` in `base_currency`. Refused if /// books of that id exist. Returns the open store. pub fn create_book(&self, id: &BookId, base_currency: Currency) -> Result { - self.create_book_inner(id, base_currency) + self.create_book_stoppable(id, base_currency, &JobStop::never()) + } + + /// [`Self::create_book`], stopped if `stop` asks before its folder is + /// made (its point of no return); after that it makes one empty book, + /// the same few files and syncs whatever else is in the root. + pub fn create_book_stoppable( + &self, + id: &BookId, + base_currency: Currency, + stop: &JobStop, + ) -> Result { + self.create_book_inner(id, base_currency, stop) .map_err(|e| self.hide(e)) } - fn create_book_inner(&self, id: &BookId, base_currency: Currency) -> Result { - let _lock = self.books_lock()?; + fn create_book_inner( + &self, + id: &BookId, + base_currency: Currency, + stop: &JobStop, + ) -> Result { + let _lock = self.books_lock(stop, "created")?; let (books, _) = self.private_subdir(BOOKS_DIR, false)?; let dir = books.join(id.as_str()); if std::fs::symlink_metadata(&dir).is_ok() { return Err(RootError::Exists(id.to_string())); } + stop.at("start", "created")?; make_private_dir(&dir)?; match Store::create(&dir, base_currency) { Ok(store) => { @@ -793,7 +922,21 @@ impl Root { id: &BookId, options: &AdoptOptions, ) -> Result { - self.adopt_inner(source, id, options) + self.adopt_stoppable(source, id, options, &JobStop::never()) + } + + /// [`Self::adopt`], stopped if `stop` asks at any phase before the + /// rename that puts the books in place (its point of no return): the + /// staging folder is removed and the root is as it was. After the + /// rename it finishes, which is a directory sync. + pub fn adopt_stoppable( + &self, + source: &Path, + id: &BookId, + options: &AdoptOptions, + stop: &JobStop, + ) -> Result { + self.adopt_inner(source, id, options, stop) .map_err(|e| self.hide(e)) } @@ -802,13 +945,15 @@ impl Root { source: &Path, id: &BookId, options: &AdoptOptions, + stop: &JobStop, ) -> Result { - let _lock = self.books_lock()?; + let _lock = self.books_lock(stop, "adopted")?; let (books, _) = self.private_subdir(BOOKS_DIR, false)?; let dest = books.join(id.as_str()); if std::fs::symlink_metadata(&dest).is_ok() { return Err(RootError::Exists(id.to_string())); } + stop.at("start", "adopted")?; let source = self.adoptable(source)?; for (what, path) in [ ("vault folder", &options.vault_dir), @@ -824,9 +969,14 @@ impl Root { } // Step 1: the source's writer lock, held to the end, so nothing // writes it while it is copied. - let (_source_lock, source_lock_created) = lock_source(&source)?; - // Step 2: verify the chain and record the head. - let (raw, lines) = read_source_journal(&source)?; + let mut source_lock = lock_source(&source)?; + let source_lock_created = source_lock.created(); + // Step 2: verify the chain and record the head. (The chain's check + // looks at the stop once per journal line.) + let scope = crate::cancel::scope(stop.flag()); + let (raw, lines) = read_source_journal(&source).map_err(|e| stop.said(e, "adopted"))?; + drop(scope); + stop.at("journal", "adopted")?; let head = head_of(&lines); if let Some(expected) = &options.expect_head && *expected != head @@ -859,11 +1009,19 @@ impl Root { } let staging = books.join(format!("{STAGING_PREFIX}{id}-{}", std::process::id())); make_private_dir(&staging)?; + // The store's own loops (opening, verifying) look at the stop too. + let scope = crate::cancel::scope(stop.flag()); let built = (|| -> Result { + stop.at("copy", "adopted")?; // Step 3: the journal as read, then every stored file. write_private_file(&staging.join(JOURNAL_FILE), &raw)?; let blob_dir = crate::store::BLOBS_DIR; - let copied = copy_blobs(&source.join(blob_dir), &staging.join(blob_dir))?; + let copied = copy_blobs( + &source.join(blob_dir), + &staging.join(blob_dir), + stop, + "adopted", + )?; // Step 5: the vault's records and the v1 key. let vault_files = match &options.vault_dir { Some(dir) => copy_flat_private(dir, &staging.join(VAULT_DIR))?, @@ -879,6 +1037,7 @@ impl Root { } None => false, }; + stop.at("open", "adopted")?; let mut store = Store::open(&staging)?; if store.head() != head { return Err(RootError::Adopt(format!( @@ -899,6 +1058,7 @@ impl Root { .join(", ") ))); } + stop.at("verify", "adopted")?; store.verify_and_heal()?; let blobs_verified = store.verify_blobs()?; // The copy is new books of this version, in its journal format @@ -936,13 +1096,22 @@ impl Root { format_upgraded, }) })(); - let renamed = built.and_then(|report| { - std::fs::rename(&staging, &dest)?; - sync_dir(&books)?; - Ok(report) - }); + drop(scope); + let renamed = built + .map_err(|e| stop.said(e, "adopted")) + .and_then(|report| { + // The last look: from the rename on, the job finishes. + stop.at("place", "adopted")?; + std::fs::rename(&staging, &dest)?; + sync_dir(&books)?; + Ok(report) + }); if renamed.is_err() { let _ = std::fs::remove_dir_all(&staging); + } else { + // Adopted: a lock file made in the source stays and is reported + // (`source_lock_created`). Any other way out, it goes. + source_lock.keep(); } renamed } @@ -991,7 +1160,11 @@ impl Root { source: &str, books: &Path, id: &BookId, + stop: &JobStop, ) -> Result<(PathBuf, crate::backup::Verified), RootError> { + stop.at("fetch", "restored")?; + // git, and the verification's own phases and loops, look at the stop. + let git = git.clone().with_cancel(stop.flag()); // Anything left from one that never finished goes first: none is // in progress (each holds the books lock). for entry in std::fs::read_dir(books)? { @@ -1005,13 +1178,18 @@ impl Root { } } let scratch = books.join(format!("{RESTORE_PREFIX}{id}-{}", std::process::id())); - match crate::backup::verify(git, source, &scratch) { + match crate::backup::verify(&git, source, &scratch) { Ok(v) => Ok((scratch, v)), Err(e) => { + // What the verification wrote goes with it (a stop leaves the + // root as it was). let _ = std::fs::remove_dir_all(&scratch); - Err(RootError::Adopt(format!( - "that backup can't be restored: {e}" - ))) + Err(match e { + crate::backup::BackupError::Cancelled(_) => RootError::Stopped( + "stopped because the books are closing: nothing was restored".into(), + ), + e => RootError::Adopt(format!("that backup can't be restored: {e}")), + }) } } } @@ -1024,10 +1202,23 @@ impl Root { source: &str, id: &BookId, ) -> Result { + self.restore_preview_stoppable(git, source, id, &JobStop::never()) + } + + /// [`Self::restore_preview`], stopped if `stop` asks: the clone is + /// removed and nothing is left. + pub fn restore_preview_stoppable( + &self, + git: &crate::backup::Git, + source: &str, + id: &BookId, + stop: &JobStop, + ) -> Result { + let _scope = crate::cancel::scope(stop.flag()); (|| { - let _lock = self.books_lock()?; + let _lock = self.books_lock(stop, "restored")?; let (books, _) = self.private_subdir(BOOKS_DIR, false)?; - let (scratch, v) = self.fetch_backup(git, source, &books, id)?; + let (scratch, v) = self.fetch_backup(git, source, &books, id, stop)?; let vault = scratch.join(VAULT_DIR); let vault_files = if vault.is_dir() { std::fs::read_dir(&vault) @@ -1063,7 +1254,24 @@ impl Root { expect_head: &(u64, String), replace: bool, ) -> Result { - self.restore_inner(git, source, id, expect_head, replace) + self.restore_stoppable(git, source, id, expect_head, replace, &JobStop::never()) + } + + /// [`Self::restore`], stopped if `stop` asks at any phase before the + /// renames that put the books in place (its point of no return): the + /// clone and the staging folder are removed and the root is as it was, + /// books that were to be replaced untouched. From the first rename on it + /// finishes: two renames and two directory syncs. + pub fn restore_stoppable( + &self, + git: &crate::backup::Git, + source: &str, + id: &BookId, + expect_head: &(u64, String), + replace: bool, + stop: &JobStop, + ) -> Result { + self.restore_inner(git, source, id, expect_head, replace, stop) .map_err(|e| match e { // The copy's checks are the adoption's: said as a restore. RootError::Adopt(text) => { @@ -1081,8 +1289,9 @@ impl Root { id: &BookId, expect_head: &(u64, String), replace: bool, + stop: &JobStop, ) -> Result { - let _lock = self.books_lock()?; + let _lock = self.books_lock(stop, "restored")?; let (books, _) = self.private_subdir(BOOKS_DIR, false)?; let dest = books.join(id.as_str()); let exists = std::fs::symlink_metadata(&dest).is_ok(); @@ -1097,18 +1306,25 @@ impl Root { } // Books being replaced are moved only while nothing holds them. let _held = if exists { - Some(lock_source(&dest).map_err(|_| { + let mut held = lock_source(&dest).map_err(|_| { RootError::Adopt(format!( "the books called {:?} are open: close them first; nothing was restored", id.as_str() )) - })?) + })?; + // The root's own folder: its lock file is the books', whoever + // made it. + held.keep(); + Some(held) } else { None }; - let (scratch, v) = self.fetch_backup(git, source, &books, id)?; + stop.at("start", "restored")?; + let _scope = crate::cancel::scope(stop.flag()); + let (scratch, v) = self.fetch_backup(git, source, &books, id, stop)?; let staging = books.join(format!("{RESTORE_PREFIX}{id}-{}-book", std::process::id())); let built = (|| -> Result { + stop.at("copy", "restored")?; if v.head != *expect_head { return Err(RootError::Adopt(format!( "that backup isn't the one previewed (it is now at event {}): nothing was restored; preview it again", @@ -1124,7 +1340,12 @@ impl Root { make_private_dir(&staging)?; write_private_file(&staging.join(JOURNAL_FILE), &raw)?; let blob_dir = crate::store::BLOBS_DIR; - let copied = copy_blobs(&scratch.join(blob_dir), &staging.join(blob_dir))?; + let copied = copy_blobs( + &scratch.join(blob_dir), + &staging.join(blob_dir), + stop, + "restored", + )?; let vault_files = if scratch.join(VAULT_DIR).is_dir() { copy_flat_private(&scratch.join(VAULT_DIR), &staging.join(VAULT_DIR))? } else { @@ -1151,6 +1372,7 @@ impl Root { &crate::ops::ops_dir(&staging).join(RESTORED_FROM), v.book.as_deref().unwrap_or("").as_bytes(), )?; + stop.at("open", "restored")?; let mut store = Store::open(&staging)?; if store.head() != v.head { return Err(RootError::Adopt(format!( @@ -1165,6 +1387,7 @@ impl Root { "the backup lacks stored files its books name: nothing was restored".into(), )); } + stop.at("verify", "restored")?; store.verify_and_heal()?; let blobs_verified = store.verify_blobs()?; let head = store.head(); @@ -1180,38 +1403,42 @@ impl Root { }) })(); let _ = std::fs::remove_dir_all(&scratch); - let placed = built.and_then(|mut report| { - if exists { - let (legacy, _) = self.private_subdir(LEGACY_DIR, false)?; - let stamp = chrono::Utc::now().format("%Y%m%d-%H%M%S"); - let mut name = format!("{id}-{stamp}"); - let mut n = 1; - while std::fs::symlink_metadata(legacy.join(&name)).is_ok() { - n += 1; - name = format!("{id}-{stamp}-{n}"); - } - std::fs::rename(&dest, legacy.join(&name))?; - if let Err(e) = std::fs::rename(&staging, &dest) { - // The books it would replace go back where they were. - if std::fs::rename(legacy.join(&name), &dest).is_err() { - return Err(RootError::Adopt(format!( - "the backup couldn't be put in place ({}), and the books it would \ - replace are in the legacy folder as {name}: nothing was restored", - e.kind() - ))); + let placed = built + .map_err(|e| stop.said(e, "restored")) + .and_then(|mut report| { + // The last look: from the first rename on, the job finishes. + stop.at("place", "restored")?; + if exists { + let (legacy, _) = self.private_subdir(LEGACY_DIR, false)?; + let stamp = chrono::Utc::now().format("%Y%m%d-%H%M%S"); + let mut name = format!("{id}-{stamp}"); + let mut n = 1; + while std::fs::symlink_metadata(legacy.join(&name)).is_ok() { + n += 1; + name = format!("{id}-{stamp}-{n}"); } - return Err(e.into()); + std::fs::rename(&dest, legacy.join(&name))?; + if let Err(e) = std::fs::rename(&staging, &dest) { + // The books it would replace go back where they were. + if std::fs::rename(legacy.join(&name), &dest).is_err() { + return Err(RootError::Adopt(format!( + "the backup couldn't be put in place ({}), and the books it would \ + replace are in the legacy folder as {name}: nothing was restored", + e.kind() + ))); + } + return Err(e.into()); + } + // In place: a folder that won't sync now is said no more + // than any later write's would be. + let _ = sync_dir(&legacy); + report.replaced = Some(name); + } else { + std::fs::rename(&staging, &dest)?; } - // In place: a folder that won't sync now is said no more - // than any later write's would be. - let _ = sync_dir(&legacy); - report.replaced = Some(name); - } else { - std::fs::rename(&staging, &dest)?; - } - let _ = sync_dir(&books); - Ok(report) - }); + let _ = sync_dir(&books); + Ok(report) + }); if placed.is_err() { let _ = std::fs::remove_dir_all(&staging); } @@ -1242,7 +1469,19 @@ impl Root { /// checks [`Self::adopt`] makes, writing nothing (not even a lock /// file). The adoption itself reads it all again under the lock. pub fn adopt_preview(&self, source: &Path) -> Result { + self.adopt_preview_stoppable(source, &JobStop::never()) + } + + /// [`Self::adopt_preview`], stopped if `stop` asks (the read of the + /// source's journal looks once per line). + pub fn adopt_preview_stoppable( + &self, + source: &Path, + stop: &JobStop, + ) -> Result { + let _scope = crate::cancel::scope(stop.flag()); (|| { + stop.at("preview", "read")?; let source = self.adoptable(source)?; // Held for writing now: adoption would be refused, so is this. if let Ok(lock) = std::fs::File::open(source.join(crate::store::LOCK_FILE)) @@ -1254,7 +1493,7 @@ impl Root { .into(), ))); } - let (_, lines) = read_source_journal(&source)?; + let (_, lines) = read_source_journal(&source).map_err(|e| stop.said(e, "read"))?; Ok(SourcePreview { head: head_of(&lines), currency: crate::store::journal_currency(&lines)?, @@ -1381,7 +1620,10 @@ impl Root { // Held for writing: nothing is moved from under it. A preview // only looks; the move holds the lock to the end. let _lock = if confirm { - Some(lock_source(source)?.0) + let mut lock = lock_source(source)?; + // The old copy is moved whole, lock file and all. + lock.keep(); + Some(lock) } else { if let Ok(lock) = std::fs::File::open(source.join(crate::store::LOCK_FILE)) && let Err(std::fs::TryLockError::WouldBlock) = lock.try_lock_shared() @@ -1830,9 +2072,63 @@ pub struct AdoptReport { /// The source's writer lock: its lock file opened read-only (so a /// read-only source can be adopted and nothing in it changes), or, for -/// books that never had one, created. Returns the lock and whether the -/// file was made. -fn lock_source(source: &Path) -> Result<(std::fs::File, bool), RootError> { +/// books that never had one, created. +/// +/// A lock file this made is the adoption's own, not the source's: unless +/// the adoption succeeds (the caller says so with [`SourceLock::keep`]), +/// it is removed when this is dropped, whatever way out the adoption took +/// (stopped by a close, failed, or a panic): the original is left as it +/// was. A lock file that was there already is never removed, nor is a +/// file this didn't make: the path must still name the very file this +/// holds, on systems that can tell. +struct SourceLock { + file: Option, + path: PathBuf, + created: bool, + keep: bool, +} + +impl SourceLock { + /// The source had no lock file, so taking its lock made one. + fn created(&self) -> bool { + self.created + } + + /// The lock file stays, whatever this made: the adoption is done (and + /// reports it), or the folder is the root's own. + fn keep(&mut self) { + self.keep = true; + } +} + +impl Drop for SourceLock { + fn drop(&mut self) { + if !self.created || self.keep { + return; + } + let Some(file) = self.file.take() else { + return; + }; + // Still the file this made? (Never one another process put there.) + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let same = match (file.metadata(), std::fs::symlink_metadata(&self.path)) { + (Ok(mine), Ok(there)) => mine.dev() == there.dev() && mine.ino() == there.ino(), + _ => false, + }; + if !same { + return; + } + } + // Let go of the lock first (a file that is open can't be removed on + // every system), then remove exactly that file. + drop(file); + let _ = std::fs::remove_file(&self.path); + } +} + +fn lock_source(source: &Path) -> Result { let path = source.join(crate::store::LOCK_FILE); let (file, created) = match std::fs::File::open(&path) { Ok(file) => (file, false), @@ -1841,7 +2137,15 @@ fn lock_source(source: &Path) -> Result<(std::fs::File, bool), RootError> { } Err(e) => return Err(e.into()), }; - if !created { + // From here the guard owns the file this may have made, so a refusal + // below removes it too. + let held = SourceLock { + file: Some(file), + path, + created, + keep: false, + }; + if !created && let Some(file) = &held.file { match file.try_lock() { Ok(()) => {} Err(std::fs::TryLockError::WouldBlock) => { @@ -1854,7 +2158,7 @@ fn lock_source(source: &Path) -> Result<(std::fs::File, bool), RootError> { Err(std::fs::TryLockError::Error(e)) => return Err(e.into()), } } - Ok((file, created)) + Ok(held) } /// The head of a verified journal: the last line's seq and the hash the @@ -2183,7 +2487,12 @@ struct CopiedBlobs { /// its name; an unfinished write (`.tmp`, a put that never finished) /// is left behind and counted; anything else (a link, a stray file) is /// refused. Folders 0700, files 0600, every folder synced. -fn copy_blobs(from: &Path, to: &Path) -> Result { +fn copy_blobs( + from: &Path, + to: &Path, + stop: &JobStop, + undone: &str, +) -> Result { use sha2::{Digest, Sha256}; let mut copied = CopiedBlobs { shas: BTreeSet::new(), @@ -2251,6 +2560,8 @@ fn copy_blobs(from: &Path, to: &Path) -> Result { } return Err(stray(&f.path())); } + // Once per stored file (one read, one hash, one write). + stop.at("file", undone)?; let bytes = std::fs::read(f.path())?; if hex::encode(Sha256::digest(&bytes)) != name.to_lowercase() { return Err(RootError::Adopt(format!( diff --git a/crates/ledger-store/src/store.rs b/crates/ledger-store/src/store.rs index 02dd939d..ec6ae4b5 100644 --- a/crates/ledger-store/src/store.rs +++ b/crates/ledger-store/src/store.rs @@ -669,6 +669,7 @@ impl Store { // open with the journal and the database as they were. let mut ledger = Ledger::new(base_currency); for line in &lines { + crate::cancel::check()?; replay_line_into_ledger(&mut ledger, line, base_currency)?; } // Only then is an append cut off mid-line (never acknowledged) set @@ -845,6 +846,7 @@ impl Store { // The ledger is already their replay (Store::open): only the // projection is caught up here. for line in lines.iter().filter(|l| l.seq > last_applied) { + crate::cancel::check()?; apply_line_to_sqlite(&self.conn, line)?; } Ok(()) @@ -6273,8 +6275,10 @@ impl Store { let lines = read_and_verify_journal(self.journal.path())?; let mut replayed = Ledger::new(self.base_currency); for line in &lines { + crate::cancel::check()?; replay_line_into_ledger(&mut replayed, line, self.base_currency)?; } + crate::cancel::check()?; let a = reports::snapshot(&replayed).map_err(StoreError::Ledger)?; let b = reports::snapshot(&self.ledger).map_err(StoreError::Ledger)?; if a != b { @@ -6371,25 +6375,15 @@ impl Store { /// healed: none. /// 2. IF the projection or ledger diverged (VerifyMismatch): SHOULD copy /// the database aside, rebuild from the journal, verify again, and - /// report why it healed. + /// report why it healed. A stop asked before the copy leaves no + /// copy and no rebuild; from the copy on none is looked at. /// 3. IF the journal itself fails: SHOULD refuse /// - NEVER touch the journal. /// ``` pub fn verify_and_heal(&mut self) -> Result { let healed = match self.verify() { Ok(()) => None, - Err(StoreError::VerifyMismatch(why)) => { - let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string(); - let keep = self.db_path.with_extension(format!("mismatch.{stamp}")); - std::fs::copy(&self.db_path, &keep)?; - eprintln!( - "wanderbooks: {why}; kept the old database as {} beside it and rebuilt from the journal", - keep.file_name().unwrap_or_default().to_string_lossy() - ); - self.rebuild()?; - self.verify()?; - Some(why) - } + Err(StoreError::VerifyMismatch(why)) => Some(self.heal_drift(why)?), Err(e) => return Err(e), }; let lines = read_and_verify_journal(self.journal.path())?; @@ -6405,6 +6399,37 @@ impl Store { }) } + /// The healing of a drifted projection (`verify_and_heal`), `why` being + /// what verification found. A stop is looked at FIRST, before the + /// database is copied aside or anything is touched: a stopped heal + /// leaves no `.mismatch` copy and no rebuild (cancel INVARIANT 4). From + /// the copy on, nothing looks at a stop: the rebuild and its second + /// verification are shielded, because stopped part way the live ledger + /// would be left part replayed. Their cost is the copy of the database + /// and about six passes over the journal (the rebuild reads and + /// chain-checks it, applies it to the database and replays it into the + /// ledger; the verification reads and chain-checks it, replays it and + /// applies it to a fresh projection), and each stored file read and + /// hashed once by the verification: a named term of the books server's + /// close bound (ledger-mcp local.rs INVARIANT 10), met only after a + /// drift. + #[doc(hidden)] + pub fn heal_drift(&mut self, why: String) -> Result { + crate::cancel::check()?; + let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string(); + let keep = self.db_path.with_extension(format!("mismatch.{stamp}")); + std::fs::copy(&self.db_path, &keep)?; + eprintln!( + "wanderbooks: {why}; kept the old database as {} beside it and rebuilt from the journal", + keep.file_name().unwrap_or_default().to_string_lossy() + ); + crate::cancel::shielded(|| -> Result<(), StoreError> { + self.rebuild()?; + self.verify() + })?; + Ok(why) + } + /// The SHA-256 of every stored file the books name (receipts and /// documents, withdrawn ones included). pub fn stored_blob_shas(&self) -> Result, StoreError> { @@ -6426,6 +6451,7 @@ impl Store { .collect::>()?; let mut n = 0u64; for sha in shas { + crate::cancel::check()?; self.blobs.get(&sha)?; n += 1; } @@ -6449,10 +6475,12 @@ impl Store { Self::write_meta(&self.conn, "last_applied_seq", "0")?; let lines = read_and_verify_journal(self.journal.path())?; for line in &lines { + crate::cancel::check()?; apply_line_to_sqlite(&self.conn, line)?; } self.ledger = Ledger::new(self.base_currency); for line in &lines { + crate::cancel::check()?; replay_line_into_ledger(&mut self.ledger, line, self.base_currency)?; } Ok(()) diff --git a/crates/ledger-store/src/uploads.rs b/crates/ledger-store/src/uploads.rs index 9528f3d4..3a7ceb02 100644 --- a/crates/ledger-store/src/uploads.rs +++ b/crates/ledger-store/src/uploads.rs @@ -28,6 +28,24 @@ //! 4. No error names a path. //! 5. A token has at most MAX_LIVE grants under way, so what one agent //! can keep on the disk is bounded. +//! 6. Uploads can be closed (`close`, under the lock every change to +//! the folder is made under): after it nothing is granted, taken, +//! swept, given back or forgotten, by any holder of these uploads +//! from before, so a book let go (closed, or replaced by a restore) +//! is never touched by a sweep, a late request or a claim dropped +//! after, whoever has the book open by then. A file coming in +//! (`receive`) is the one change that spans time: each chunk is +//! written under that lock, and the rename that keeps the bytes is +//! made under it, so once `close` has returned no byte is written +//! and none is kept; what the request had written (its `.part`) is +//! removed by the request, when it next looks (its next chunk, or +//! its end), which is the only thing a request begun before the +//! close does to the folder after it, and the removal of a file +//! only that request made. A request that is still waiting for its +//! next bytes when the close returns is not woken by the type: a +//! caller that must not leave that part behind waits for the +//! request (the books server's gate does, and cuts one that never +//! finishes arriving). //! ``` use crate::journal::sha256_hex; @@ -36,6 +54,8 @@ use sha2::{Digest, Sha256}; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; +/// What an upload is told when its books were let go (INVARIANT 6). +const CLOSED: &str = "the books aren't open"; /// The uploads' folder, in a book's folder. pub const UPLOADS_DIR: &str = "uploads"; /// The largest file taken (plan 4.7). @@ -99,7 +119,10 @@ impl Claim { impl Drop for Claim { fn drop(&mut self) { if !self.spent { - let _held = self.uploads.locked(); + let held = self.uploads.locked(); + if *held { + return; + } let _ = std::fs::rename( self.uploads.path(&self.id, TAKEN), self.uploads.path(&self.id, "bin"), @@ -169,8 +192,8 @@ pub struct Uploads { dir: PathBuf, /// Held while grants are made or swept and while bytes change name /// (INVARIANTS 1, 2, 5): one server serves a book, so this orders - /// every request to its uploads. - lock: std::sync::Arc>, + /// every request to its uploads. True once closed (INVARIANT 6). + lock: std::sync::Arc>, } /// The longest file name taken, in bytes (most file systems' limit). @@ -287,10 +310,25 @@ impl Uploads { Ok(uploads) } - fn locked(&self) -> std::sync::MutexGuard<'_, ()> { + fn locked(&self) -> std::sync::MutexGuard<'_, bool> { self.lock.lock().unwrap_or_else(|e| e.into_inner()) } + /// The lock, if the uploads aren't closed (INVARIANT 6). + fn locked_open(&self) -> Result, UploadError> { + let held = self.locked(); + if *held { + return Err(UploadError::Bad(CLOSED.into())); + } + Ok(held) + } + + /// Change nothing in these uploads from now on (INVARIANT 6): waits + /// for the change being made, if one is. + pub fn close(&self) { + *self.locked() = true; + } + fn path(&self, id: &str, ext: &str) -> PathBuf { self.dir.join(format!("{id}.{ext}")) } @@ -327,7 +365,7 @@ impl Uploads { "purpose is receipt, document, import (a bank or chart CSV) or w9".into(), )); } - let _held = self.locked(); + let _held = self.locked_open()?; self.sweep_held(now); // INVARIANT 5. if self.live_for(token, now) >= MAX_LIVE { @@ -378,6 +416,7 @@ impl Uploads { return Err(UploadError::Unknown(id.chars().take(40).collect())); } let unknown = || UploadError::Unknown(id.to_string()); + drop(self.locked_open()?); let bytes = std::fs::read(self.path(id, "json")).map_err(|_| unknown())?; let grant: Grant = serde_json::from_slice(&bytes).map_err(|_| unknown())?; if grant.expires <= now { @@ -406,7 +445,7 @@ impl Uploads { // One request at a time (INVARIANT 2): no bytes kept or held, and // no `.part` of another request. let mut out = { - let _held = self.locked(); + let _held = self.locked_open()?; if done.exists() || self.path(id, TAKEN).exists() { return Err(UploadError::AlreadySent); } @@ -434,6 +473,13 @@ impl Uploads { break Ok(()); } hasher.update(&buf[..n]); + // Each chunk is written under the lock a close takes + // (INVARIANT 6): once the uploads are closed no more bytes go + // into the part, which is removed below. + let held = self.locked(); + if *held { + break Err(UploadError::Bad(CLOSED.into())); + } if let Err(e) = out.write_all(&buf[..n]) { break Err(e.into()); } @@ -459,7 +505,11 @@ impl Uploads { Ok(()) => { // Kept only if its grant still stands (it may have lapsed, // or been filed by another request's bytes, meanwhile). - let _held = self.locked(); + let held = self.locked(); + if *held { + let _ = std::fs::remove_file(&part); + return Err(UploadError::Bad(CLOSED.into())); + } let standing = std::fs::read(self.path(id, "json")) .ok() .and_then(|b| serde_json::from_slice::(&b).ok()) @@ -493,7 +543,7 @@ impl Uploads { let taken = self.path(id, TAKEN); // The rename is the hold: of two calls, one gets it. { - let _held = self.locked(); + let _held = self.locked_open()?; if let Err(e) = std::fs::rename(self.path(id, "bin"), &taken) { return Err(match e.kind() { std::io::ErrorKind::NotFound if taken.exists() => UploadError::InUse, @@ -527,14 +577,19 @@ impl Uploads { /// be written): the grant stands, its bytes are to be sent again. pub fn discard(&self, id: &str) { if is_id(id) { - let _held = self.locked(); - let _ = std::fs::remove_file(self.path(id, "bin")); + let held = self.locked(); + if !*held { + let _ = std::fs::remove_file(self.path(id, "bin")); + } } } /// Forget grant `id` and anything kept for it. fn forget(&self, id: &str) { - let _held = self.locked(); + let held = self.locked(); + if *held { + return; + } for ext in ["json", "part", "bin", TAKEN] { let _ = std::fs::remove_file(self.path(id, ext)); } @@ -543,8 +598,10 @@ impl Uploads { /// Sweep away every grant that lapsed by `now`, and anything left /// without one (INVARIANT 3). pub fn sweep(&self, now: i64) { - let _held = self.locked(); - self.sweep_held(now); + let held = self.locked(); + if !*held { + self.sweep_held(now); + } } /// [`Self::sweep`], the lock held. @@ -588,6 +645,141 @@ mod tests { .unwrap() } + /// Closed, uploads are granted, received, taken, swept and given back + /// by no one, and a claim dropped after puts nothing back (INVARIANT 6). + #[test] + fn closed_uploads_change_nothing() { + let dir = tempfile::tempdir().unwrap(); + let u = Uploads::open(dir.path(), NOW).unwrap(); + let bytes = b"%PDF-1.4 a receipt".to_vec(); + let g = grant_for(&u, "tok_a", &bytes); + u.receive(&g.id, "tok_a", &mut &bytes[..], NOW).unwrap(); + let received = u.take(&g.id, "tok_a", NOW).unwrap(); + let seen = || { + let mut names: Vec<_> = std::fs::read_dir(dir.path().join(UPLOADS_DIR)) + .unwrap() + .map(|f| f.unwrap().file_name()) + .collect(); + names.sort(); + names + }; + let held = seen(); + u.close(); + assert!( + u.grant( + "tok_a", + &sha256_hex(&bytes), + bytes.len() as u64, + "application/pdf", + "r.pdf", + "receipt", + NOW + ) + .is_err() + ); + assert!(u.receive(&g.id, "tok_a", &mut &bytes[..], NOW).is_err()); + assert!(u.take(&g.id, "tok_a", NOW).is_err()); + u.discard(&g.id); + u.sweep(NOW + 10 * UPLOAD_TTL); + // The call that held the bytes lets go of them, unspent: nothing + // is put back, nor forgotten, in a folder that is no longer ours. + drop(received); + assert_eq!(seen(), held); + } + + /// A body that hands out `chunks`, one per read, and tells the test + /// before each read (its number, from 1) so it can act at an exact + /// point of the transfer. + struct Feed<'a> { + chunks: std::collections::VecDeque>, + reads: usize, + before: Box, + } + + impl std::io::Read for Feed<'_> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + self.reads += 1; + (self.before)(self.reads); + match self.chunks.pop_front() { + Some(c) => { + buf[..c.len()].copy_from_slice(&c); + Ok(c.len()) + } + None => Ok(0), + } + } + } + + fn names_in(dir: &Path) -> Vec { + let mut names: Vec<_> = std::fs::read_dir(dir.join(UPLOADS_DIR)) + .unwrap() + .map(|f| f.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + names + } + + /// INVARIANT 6, per chunk: a close that comes while a file is coming + /// in stops the request at the chunk that follows it. Not one more + /// read is made, no byte is written after the close, and the part the + /// request had written is removed. + #[test] + fn a_close_in_the_middle_of_a_file_stops_it_at_the_next_chunk() { + let dir = tempfile::tempdir().unwrap(); + let u = Uploads::open(dir.path(), NOW).unwrap(); + let bytes: Vec = (0..3000u32).map(|n| (n % 251) as u8).collect(); + let g = grant_for(&u, "tok_a", &bytes); + let mut feed = Feed { + chunks: bytes.chunks(1000).map(<[u8]>::to_vec).collect(), + reads: 0, + before: Box::new(|read| { + if read == 2 { + u.close(); + } + }), + }; + let refused = u.receive(&g.id, "tok_a", &mut feed, NOW).unwrap_err(); + assert!(refused.to_string().contains("aren't open"), "{refused}"); + assert_eq!(feed.reads, 2, "the body was read after the close"); + let left = names_in(dir.path()); + assert!( + !left + .iter() + .any(|n| n.ends_with(".part") || n.ends_with(".bin")), + "{left:?}" + ); + } + + /// INVARIANT 6, the last step: a close that comes after the last byte + /// and before the bytes are kept keeps nothing (the rename that makes + /// them the upload is under the lock a close takes). + #[test] + fn a_close_between_the_last_byte_and_the_rename_keeps_nothing() { + let dir = tempfile::tempdir().unwrap(); + let u = Uploads::open(dir.path(), NOW).unwrap(); + let bytes = b"%PDF-1.4 a receipt".to_vec(); + let g = grant_for(&u, "tok_a", &bytes); + let mut feed = Feed { + chunks: [bytes.clone()].into(), + reads: 0, + // The second read is the one that finds the end. + before: Box::new(|read| { + if read == 2 { + u.close(); + } + }), + }; + let refused = u.receive(&g.id, "tok_a", &mut feed, NOW).unwrap_err(); + assert!(refused.to_string().contains("aren't open"), "{refused}"); + let left = names_in(dir.path()); + assert!( + !left + .iter() + .any(|n| n.ends_with(".part") || n.ends_with(".bin")), + "{left:?}" + ); + } + #[test] fn bytes_sent_as_declared_are_taken_once() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ledger-store/tests/root.rs b/crates/ledger-store/tests/root.rs index ea46e95e..dc220c7f 100644 --- a/crates/ledger-store/tests/root.rs +++ b/crates/ledger-store/tests/root.rs @@ -1734,3 +1734,343 @@ fn a_registry_rewritten_or_a_vault_given_unchecked_is_refused() { } assert!(p.vault.is_dir() && p.key.is_file()); } + +/// A stop that is asked at `phase` (and the phases a job has asked, in +/// order): the job's own look at its phases, raised from the watcher. +fn stopping_at( + phase: &'static str, +) -> ( + ledger_store::root::JobStop, + std::sync::Arc>>, +) { + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Arc, Mutex}; + let flag = Arc::new(AtomicBool::new(false)); + let seen = Arc::new(Mutex::new(Vec::::new())); + let stop = ledger_store::root::JobStop::new(flag.clone()).with_phase_watch({ + let (flag, seen) = (flag.clone(), seen.clone()); + Arc::new(move |p: &str| { + seen.lock().unwrap().push(p.to_string()); + if p == phase { + flag.store(true, Ordering::SeqCst); + } + }) + }); + (stop, seen) +} + +/// What a job leaves of the root, byte for byte. +fn root_files(root: &Root) -> Vec<(PathBuf, Vec)> { + let mut out = snapshot_files(&root.path().join("books")); + if root.path().join("legacy").exists() { + out.extend(snapshot_files(&root.path().join("legacy"))); + } + out +} + +/// A job that changes which books the root holds (create, adopt, restore) is +/// asked at each of its phases whether it must stop (the books server's +/// close), and stopped at any of them leaves the root byte for byte as it +/// was: the staging and scratch folders are gone, books it would have +/// replaced untouched, `legacy/` as it was. The last phase it asks is the +/// look before its point of no return (the renames that put the books in +/// place): nothing is asked after, so a stop that comes then is not heeded +/// and the job finishes. +#[test] +fn a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_it_was() { + use ledger_store::root::JobStop; + let home = tmp("job-stop"); + let (root, _) = Root::setup(home.path(), None, None).unwrap(); + // create + let before = root_files(&root); + let (stop, seen) = stopping_at("start"); + let e = refused( + root.create_book_stoppable(&id("new"), Currency::USD, &stop) + .map(|_| ()), + ); + assert!(matches!(e, RootError::Stopped(_)), "{e:?}"); + assert!(e.to_string().contains("nothing was created"), "{e}"); + assert_eq!(root_files(&root), before); + assert!(root.list_books().unwrap().is_empty()); + assert!(!root.book_dir(&id("new")).exists(), "its folder was made"); + assert_eq!(*seen.lock().unwrap(), ["start"]); + // adopt + let old = tmp("job-stop-old"); + drop(source_books(old.path(), true)); + let options = AdoptOptions::default(); + let phases = [ + "start", "journal", "copy", "file", "open", "verify", "place", + ]; + for phase in phases { + let before = root_files(&root); + let (stop, seen) = stopping_at(phase); + let e = refused(root.adopt_stoppable(old.path(), &id("adopted"), &options, &stop)); + assert!(matches!(e, RootError::Stopped(_)), "{phase}: {e:?}"); + assert!( + e.to_string().contains("nothing was adopted"), + "{phase}: {e}" + ); + assert_eq!(root_files(&root), before, "adopt stopped at {phase}"); + assert!(root.list_books().unwrap().is_empty(), "{phase}"); + assert_eq!(seen.lock().unwrap().last().map(String::as_str), Some(phase)); + } + // Never stopped: every phase is asked, in this order, `place` the last. + let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let stop = JobStop::new(flag).with_phase_watch({ + let seen = seen.clone(); + std::sync::Arc::new(move |p: &str| seen.lock().unwrap().push(p.to_string())) + }); + root.adopt_stoppable(old.path(), &id("adopted"), &options, &stop) + .unwrap(); + let asked = seen.lock().unwrap().clone(); + let mut distinct = asked.clone(); + distinct.dedup(); + assert_eq!(distinct, phases, "{asked:?}"); + assert_eq!(asked.last().map(String::as_str), Some("place"), "{asked:?}"); + // restore, over books that exist: they stay as they are. + let dir = root.book_dir(&id("adopted")); + let store = Store::open(&dir).unwrap(); + let source = backed_up(home.path(), &dir, &store).expect("git is installed"); + drop(store); + let git = ledger_store::backup::Git::find().unwrap(); + let preview = root.restore_preview(&git, &source, &id("adopted")).unwrap(); + let phases = ["start", "fetch", "copy", "file", "open", "verify", "place"]; + for phase in phases { + let before = root_files(&root); + let (stop, seen) = stopping_at(phase); + let e = refused(root.restore_stoppable( + &git, + &source, + &id("adopted"), + &preview.head, + true, + &stop, + )); + assert!(matches!(e, RootError::Stopped(_)), "{phase}: {e:?}"); + assert!( + e.to_string().contains("nothing was restored"), + "{phase}: {e}" + ); + assert_eq!(root_files(&root), before, "restore stopped at {phase}"); + assert_eq!(seen.lock().unwrap().last().map(String::as_str), Some(phase)); + } + // The preview too: stopped, nothing left of its clone. + let before = root_files(&root); + let (stop, _) = stopping_at("fetch"); + let e = refused(root.restore_preview_stoppable(&git, &source, &id("adopted"), &stop)); + assert!(matches!(e, RootError::Stopped(_)), "{e:?}"); + assert_eq!(root_files(&root), before); + // Never stopped, a restore asks `place` last and goes through. + let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::::new())); + let stop = JobStop::new(std::sync::Arc::default()).with_phase_watch({ + let seen = seen.clone(); + std::sync::Arc::new(move |p: &str| seen.lock().unwrap().push(p.to_string())) + }); + let r = root + .restore_stoppable(&git, &source, &id("adopted"), &preview.head, true, &stop) + .unwrap(); + assert!(r.replaced.is_some()); + assert_eq!( + seen.lock().unwrap().last().map(String::as_str), + Some("place") + ); +} + +/// A folder, name for name and byte for byte: every file and every folder +/// in it, with its bytes and its mode. +fn tree_exact(dir: &Path) -> Vec<(PathBuf, Option>, u32)> { + let mut out = Vec::new(); + let mut stack = vec![dir.to_path_buf()]; + while let Some(d) = stack.pop() { + for e in std::fs::read_dir(&d).unwrap() { + let p = e.unwrap().path(); + let is_dir = std::fs::symlink_metadata(&p).unwrap().is_dir(); + out.push(( + p.strip_prefix(dir).unwrap().to_path_buf(), + (!is_dir).then(|| std::fs::read(&p).unwrap()), + mode(&p), + )); + if is_dir { + stack.push(p); + } + } + } + out.sort(); + out +} + +/// An adoption makes the source's lock file when the source has none (INVARIANT +/// 5), and the original is to be left as it was: so a lock file the adoption +/// itself made is removed on every way out but its success (stopped by a close +/// at any phase, refused, or a panic), exactly that file and nothing else; one +/// the source already had is never removed, and a success leaves the one it +/// made and says so. +#[test] +fn an_adoption_that_does_not_finish_leaves_no_lock_file_in_the_source() { + use std::sync::Arc; + use std::sync::atomic::AtomicBool; + let home = tmp("adopt-lock"); + let (root, _) = Root::setup(home.path(), None, None).unwrap(); + let old = tmp("adopt-lock-src"); + drop(source_books(old.path(), true)); + let lock = old.path().join(ledger_store::LOCK_FILE); + std::fs::remove_file(&lock).unwrap(); + let before = tree_exact(old.path()); + assert!( + before + .iter() + .all(|(n, ..)| n != Path::new(ledger_store::LOCK_FILE)) + ); + let options = AdoptOptions::default(); + // Stopped at every phase, before the lock is taken and after. + for phase in [ + "start", "journal", "copy", "file", "open", "verify", "place", + ] { + let (stop, _) = stopping_at(phase); + let e = refused(root.adopt_stoppable(old.path(), &id("adopted"), &options, &stop)); + assert!(matches!(e, RootError::Stopped(_)), "{phase}: {e:?}"); + assert_eq!( + tree_exact(old.path()), + before, + "the source after an adoption stopped at {phase}" + ); + } + // Refused after the lock: the books changed since the preview. + let wrong = AdoptOptions { + expect_head: Some((999, "not the head".into())), + ..AdoptOptions::default() + }; + let e = refused(root.adopt(old.path(), &id("adopted"), &wrong)); + assert!(e.to_string().contains("changed since the preview"), "{e}"); + assert_eq!(tree_exact(old.path()), before, "after a refusal"); + // A panic, in the middle of the copy. + let flag = Arc::new(AtomicBool::new(false)); + let stop = ledger_store::root::JobStop::new(flag).with_phase_watch(Arc::new(|p: &str| { + if p == "verify" { + panic!("a panic in the middle of an adoption"); + } + })); + let gone = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + root.adopt_stoppable(old.path(), &id("adopted"), &options, &stop) + .map(|_| ()) + })); + assert!(gone.is_err(), "the adoption panicked"); + assert_eq!(tree_exact(old.path()), before, "after a panic"); + assert!(root.list_books().unwrap().is_empty()); + // The lock held while the adoption runs is gone with it: the source can + // be taken for writing at once. + drop(Store::open(old.path()).unwrap()); + std::fs::remove_file(&lock).unwrap(); + // Not removed when it isn't the file the adoption made: a lock file put + // there by someone else while the adoption ran (it was swapped at the + // last phase) stays. + let flag = Arc::new(AtomicBool::new(false)); + let swap = lock.clone(); + let stop = ledger_store::root::JobStop::new(flag).with_phase_watch(Arc::new(move |p: &str| { + if p == "verify" { + std::fs::remove_file(&swap).unwrap(); + std::fs::write(&swap, b"someone else's").unwrap(); + panic!("stopped after the swap"); + } + })); + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + root.adopt_stoppable(old.path(), &id("adopted"), &options, &stop) + .map(|_| ()) + })); + assert_eq!( + std::fs::read(&lock).unwrap(), + b"someone else's", + "a lock file the adoption did not make was removed" + ); + std::fs::remove_file(&lock).unwrap(); + assert_eq!(tree_exact(old.path()), before); + // A source that had its lock file keeps it, stopped or not: the folder + // is as it was, and the adoption reports it made none. + drop(Store::open(old.path()).unwrap()); + let had = tree_exact(old.path()); + assert!( + had.iter() + .any(|(n, ..)| n == Path::new(ledger_store::LOCK_FILE)) + ); + for phase in ["copy", "verify", "place"] { + let (stop, _) = stopping_at(phase); + let e = refused(root.adopt_stoppable(old.path(), &id("adopted"), &options, &stop)); + assert!(matches!(e, RootError::Stopped(_)), "{phase}: {e:?}"); + assert_eq!(tree_exact(old.path()), had, "a lock it had, at {phase}"); + } + let report = root.adopt(old.path(), &id("adopted"), &options).unwrap(); + assert!(!report.source_lock_created); + assert_eq!(tree_exact(old.path()), had); + // And a success of a source with none leaves the one it made, as before. + let fresh = tmp("adopt-lock-src2"); + drop(source_books(fresh.path(), true)); + std::fs::remove_file(fresh.path().join(ledger_store::LOCK_FILE)).unwrap(); + let report = root.adopt(fresh.path(), &id("second"), &options).unwrap(); + assert!(report.source_lock_created); + assert!(fresh.path().join(ledger_store::LOCK_FILE).is_file()); +} + +/// A job waiting for another's turn at making books (they are made one at a +/// time, across processes) gives up when it is asked to stop, whatever the +/// job holding the turn does: a close can't be held up by a job that is only +/// queued. A job that isn't asked to stop waits its turn, and goes through +/// when it comes. +#[test] +fn a_job_waiting_for_its_turn_stops_when_asked_and_otherwise_waits_for_it() { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + let home = tmp("turn"); + let (root, _) = Root::setup(home.path(), None, None).unwrap(); + // Another process's turn: the lock file is held. + let turn = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(root.path().join("run/books.lock")) + .unwrap(); + turn.lock().unwrap(); + let flag = Arc::new(AtomicBool::new(false)); + let waiting = { + let flag = flag.clone(); + let root = root.clone(); + std::thread::spawn(move || { + root.create_book_stoppable( + &id("queued"), + Currency::USD, + &ledger_store::root::JobStop::new(flag), + ) + .map(|_| ()) + }) + }; + // Queued: it has not made its folder, nor stopped, while the turn is + // held and nothing asks it to. + let by = std::time::Instant::now() + std::time::Duration::from_millis(400); + while std::time::Instant::now() < by { + assert!(!waiting.is_finished(), "it didn't wait for its turn"); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + flag.store(true, Ordering::SeqCst); + let by = std::time::Instant::now() + std::time::Duration::from_secs(60); + while !waiting.is_finished() { + assert!( + std::time::Instant::now() < by, + "a job waiting for its turn didn't stop when asked" + ); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + let e = refused(waiting.join().unwrap()); + assert!(matches!(e, RootError::Stopped(_)), "{e:?}"); + assert!(e.to_string().contains("nothing was created"), "{e}"); + assert!(!root.book_dir(&id("queued")).exists()); + // Not asked: it waits, and goes through when the turn is let go. + let other = { + let root = root.clone(); + std::thread::spawn(move || root.create_book(&id("patient"), Currency::USD).map(|_| ())) + }; + std::thread::sleep(std::time::Duration::from_millis(150)); + assert!(!other.is_finished()); + drop(turn); + other.join().unwrap().unwrap(); + assert_eq!(root.list_books().unwrap(), vec![id("patient")]); +} diff --git a/crates/ledger-store/tests/store.rs b/crates/ledger-store/tests/store.rs index befd3ddd..b2fa05e8 100644 --- a/crates/ledger-store/tests/store.rs +++ b/crates/ledger-store/tests/store.rs @@ -883,6 +883,72 @@ fn vendor_1099_tags_replay_and_project() { } } +/// A stop asked before a heal begins leaves nothing behind (cancel INVARIANT +/// 4, store.rs `heal_drift`): no `.mismatch` copy of the database and no +/// rebuild, the database exactly as it was (still drifted), and the stop is +/// the answer. Healed with no stop, the same drift heals. +#[test] +fn a_stop_before_a_heal_leaves_no_copy_and_no_rebuild() { + let dir = test_dir("heal-stopped"); + let mut store = build_books(&dir); + let e = store + .ledger() + .posted_entries() + .next() + .map(|e| e.id()) + .unwrap(); + store + .attach_receipt(Some(e), "r.png", "image/png", b"receipt", None) + .unwrap(); + drop(store); + let db = dir.join(ledger_store::db_file()); + let conn = rusqlite::Connection::open(&db).unwrap(); + conn.execute("UPDATE attachments SET entry_id = NULL", []) + .unwrap(); + drop(conn); + let mut store = Store::open(&dir).unwrap(); + let Err(StoreError::VerifyMismatch(why)) = store.verify() else { + panic!("the drift wasn't found"); + }; + let files = |dir: &std::path::Path| { + let mut names: Vec = std::fs::read_dir(dir) + .unwrap() + .filter_map(|d| d.ok()) + .map(|d| d.file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + names + }; + let (names, db_bytes) = (files(&dir), std::fs::read(&db).unwrap()); + { + // The stop arrives after the drift was found, before the heal. + let _stop = ledger_store::cancel::scope(std::sync::Arc::new( + std::sync::atomic::AtomicBool::new(true), + )); + assert!(matches!( + store.heal_drift(why.clone()), + Err(StoreError::Cancelled) + )); + } + assert_eq!(files(&dir), names, "a stopped heal left a copy behind"); + assert_eq!( + std::fs::read(&db).unwrap(), + db_bytes, + "a stopped heal rebuilt the database" + ); + assert!( + matches!(store.verify(), Err(StoreError::VerifyMismatch(_))), + "still drifted: nothing was rebuilt" + ); + // Not stopped, the same drift heals, keeping its copy. + let report = store.verify_and_heal().unwrap(); + assert!(report.healed.is_some()); + assert!( + files(&dir).iter().any(|n| n.contains(".mismatch.")), + "the divergent database is kept for forensics" + ); +} + #[test] fn the_whole_projection_is_checked_and_healed() { let dir = test_dir("heal"); diff --git a/docs/architecture.md b/docs/architecture.md index 05a2a279..fbfb02fc 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -287,6 +287,15 @@ re-verifies the journal. ## The local transport and the Windows arms (`ledger-mcp::ipc`, `ledger-store::winsec`, P11c, D-62) +The books server opens the books of the data root at its start (all, or the +ones `--open` names), and opens or closes **one** while it runs (admin +requests `open_book` and `close_book`, `ledger-mcp/src/local.rs` +INVARIANT 10; plan/p15-app-and-relay.md 3.1): each open book has a gate +every request enters before it touches the book, which a close shuts and +waits empty, so the app's tab for a company can be its book's open state. +`sessions.rs` keeps the per-book board of who is connected (the admin +`sessions` request). + The books server, the host and everything that talks to them meet on channels only this account can open (plan 3.9). `ledger_mcp::ipc` is the one seam: `Endpoint` (a socket in the root's `run/` on Unix; the pipe diff --git a/docs/mcp-interface.md b/docs/mcp-interface.md index c8e8a0f7..9bc54854 100644 --- a/docs/mcp-interface.md +++ b/docs/mcp-interface.md @@ -267,7 +267,10 @@ reach through the bridge. - **Served books** (`wanderbooks server`, started by the host; an agent connects with `wanderbooks mcp --book ID`, the bridge: stdio to the agent, the server's socket upstream): every book - in the data root, on a socket in the root's private `run/` folder that + in the data root that is open (all of them at the start, unless + `wanderbooks server --open none|ID[,ID…]` says otherwise; one is opened + or closed while the server runs, "Opening and closing one book" below), + on a socket in the root's private `run/` folder that only this account can connect to. Every request carries a bearer token live for that book (refused 401 without one, 403 with another book's). Refusals at the door, tool calls, uploads, downloads and exports are @@ -275,6 +278,12 @@ reach through the bridge. book stops taking requests (an upload, download or export is then refused, 503). - `/b/{book}/mcp`: the book's MCP service. A request is at most 1 MiB. + - A book that exists but is **closed** is refused on every route below + and on this one: 503 with `x-wanderbooks-refused: closed` and the words + `The books "ID" aren't open: open them in Wanderbooks.` (the bridge + hands them to the agent as they are). A book that doesn't exist is 404 + `no-such-books`; one that failed to open is 503 `not-open` with why. + Nothing of a closed book is written, its access log included. - `PUT /b/{book}/u/{upload}`: an upload's bytes (`books.begin_upload`), from the token that began it; what `wanderbooks upload --book B [--token NAME] UPLOAD FILE` sends. Streamed to the disk, kept only if @@ -331,6 +340,143 @@ reach through the bridge. hidden file and hard-linked in: never a partial file under the real name, never over another file. +### Opening and closing one book (plan/p15-app-and-relay.md 3.1, D-77, D-78) + +The desktop app has one tab per company, and a company is reachable by +agents exactly while its tab is open, so the books server opens and closes +**one** book while it runs. These are requests on the admin socket (the +command line sends them: `wanderbooks books open ID`, `wanderbooks books +close ID`; `books list` and `doctor` show each book as open, closed, or +didn't open, with why). Protocol version 1: the requests are new, the +`closed` flag of a listed book defaults to false. + +- `open_book { id }` opens a closed (or failed) book of the data root with + exactly the checks of the server's start (verified, a drifted database + 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`, `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 + (an ordinary call: nothing is killed, nothing is half-done; the calls + that can run long are stopped instead, see below); 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); a request whose body has not been read + to its end when that time runs out (counted from the start of the + close: an upload or a call that began and stopped sending) is cut: its + connection is closed, an upload's part file is removed, nothing of an + MCP call reached the journal, and the access log says `cut_by_close`; + a call whose body arrived whole and is running is never cut, it + finishes; its MCP sessions end (an agent's next + request on one gets the "isn't open" words above, and after a reopening + a 404 "Session not found", which a client takes as "open a new one"); its + last backup is made, as at the server's close, for 60 seconds at most + (a drill, or a format upgrade not yet journaled, is stopped when the + close begins, at its next look, so it never takes the last backup's + turn; its scratch clone is removed and the books are unchanged): + a backup still running after that is stopped (git is sent SIGTERM, which + makes it remove its own lock files, and killed with all it started only + if it hasn't ended after 5 seconds) and waited for to end. The program + never writes to or deletes from a backup folder (it is the owner's, and + may be shared with other computers or a sync program): a lock git left + there when it had to be killed is left in place, recorded in + `ops/backup.jsonl` as `lock_left` with its whole path, and the target's + backup is marked failed with words naming the file and saying to remove + it only when nothing else is using the backup folder (`books.backup` + and the close's answer say the same; the next backup that finds the + lock gone goes on). In the book's own archive (`archive.git`, private to + the program; running git by hand inside it is unsupported) it removes + only the locks its own stopped git made, and, at open and when a backup + begins, locks older than ten minutes, each recorded `lock_removed`; + **What a close stops, and what it waits for.** At its start a close + stops the calls and jobs that can do long I/O or loop over a book's + whole journal or files, each at its next look: `books.back_up_now` and + a backup a timer asked for (git is stopped; the call answers that it was + stopped because the books are closing, its access record says + `refused: stopped_by_close`, and nothing it was doing is recorded as done; + a commit it had made stands), `books.verify` (once per journal line and + per stored file; a heal of a drifted database is begun only if no stop + was asked before it, then finishes), `books.export_cpa_package` (once per + stored file, unless it has journaled a decision, below), a drill, and a + format upgrade not yet at its final look (a + stop is honoured up to that look; one that arrives after it still + upgrades and records success). A stop is scoped to what it concerns. On + the admin socket, a close of the book X stops the work on X only: an open + of X, and a restore that replaces X. A create, an adoption and a restore + that replaces nothing make a new book, which no close of a book is the + close of: a close of one book never stops, fails, refuses or delays them, + nor an open or a close of another book (each book has its own turn; books + are made, adopted and restored one at a time, and a job queued for its + turn leaves at once when asked to stop). The server's own close stops + every job. A stopped job, before its point of no return (the rename that + puts the books in place; create's making of its folder), removes what it + wrote (an adoption also removes the lock file it made in the source + folder, so the original is left as it was) and leaves the root byte for + byte as it was, and answers that it was stopped because the books are + closing; after it the job finishes (a rename or two and two directory + syncs), and the book is then opened unless that, too, is stopped (it is + left closed, and the answer says so). `books.export_cpa_package` with a + reason to export (without an audit, with open drafts) journals that + decision before it builds, because the package counts it (its README and + every footer carry the journal's event count at the build): a close is + looked for once, immediately before the first decision is journaled, and + a stop then journals nothing; after it the package is made whatever a + close does, so no decision is on record for a package that was never + made (every refusal is decided before any decision is journaled). Every + other call does work bounded by the size of one request and is waited + for. Three are the named exceptions to the close's bound, each waited for + in full if a close meets it: `books.import_bank_csv` (a file of up to + 25 MiB is rehearsed whole and then written row by row, each row + journaled; worst case, a full import of the largest file accepted), + a report or export over the whole journal (CPU on the ledger in memory, + not stopped; worst case, one report over the whole book), and a package + after its decision is journaled (worst case, one build over the whole + book). Otherwise + the close is bounded by the sum written in the server's INVARIANT 10 + (`local.rs`: running calls, the grace, the answers' grace, the stop of a + hurried step, the last backup's 60 s, the stop of what is left of it); + 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/`; the book is + listed closed from the moment the restore begins, so a call that comes + meanwhile is told the books aren't open (503, as in a close), never that + there are no such books (404). +- **The server's own close** (its standard input ends, or SIGTERM) is the + same path for every open book at once: at its start every book's door + is shut and the cut (above) is set for 10 seconds from that moment; each + book is then released as `close_book` releases it. The server exits 0 + once they are all closed (and the HTTP side has ended); a request that + arrives meanwhile is refused as closing (503) and not recorded, the + door being shut. +- `sessions` lists, for each open book, its live MCP sessions: the token's + **name** (never the token, its text or its hash), the client's name and + version from `initialize`, the agent's self-report (`books.start`'s + `agent`, if it made one), when it connected, how many of its calls are + running now, and its last tool with its outcome and time. A session + that ended is not listed; nothing is kept across a server restart. + `wanderbooks doctor` prints these lines under "Assistants connected". + ## Server instructions The MCP `initialize` response carries an `instructions` string, the diff --git a/docs/receipt-store.md b/docs/receipt-store.md index fe4c47c6..f3d7a7e3 100644 --- a/docs/receipt-store.md +++ b/docs/receipt-store.md @@ -33,7 +33,14 @@ easily backupable, journable": ahead, the commit under the store's lock) and pushes it to the owner's private repository and backup folder, versioned and deduplicated, with full history (docs/mcp-interface.md, "Tools — - backups"). + backups"). The program stops its git gently (SIGTERM first, so git + removes its own lock files, and a kill only after 5 seconds), and never + writes to or deletes from a backup folder, which is the owner's (shared, + perhaps, with another computer or a sync program): a lock git left + there after a kill is reported with its path, never removed. The book's + own archive (`archive.git`) is private to the program; there it removes + only the locks its own stopped git made, and locks older than ten + minutes found when the books open or a backup begins. - **Journable.** It literally is a journal: `{seq, ts, type, payload, prev}`. Greppable, diffable, replayable. The audit trail isn't a feature bolted on — it's the storage format. diff --git a/docs/testing.md b/docs/testing.md index e4c1e3e0..dc40485e 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -4084,7 +4084,8 @@ it checks are already theorems. a medium effort, no claim, a lowered bar read retroactively), `a_period_is_attested_on_a_standing_audit`, `cpa_package_refuses_without_a_counted_audit_unless_a_reason_is_given` - (refused, a reason journaled as a decision, an audit alone not enough, a + (refused, a reason journaled as a decision, and none journaled when an open + draft then refuses the same package, an audit alone not enough, a year attested below the whole bar not enough, the whole bar, an entry since, `warn`), `audits_wait_for_the_upgrade` (the fixture over the wire; the package is not held up by an audit it cannot ask for). @@ -4290,6 +4291,91 @@ that make a group, the reversal skip, the `total > threshold` end), `audit::check_split` (`> unit`, not `>=`), `AttestationBar::parse`'s range (1..=64), `reconcilable::reconciliation_due` (`<=` through, `<` reconciled). +## P15 A1: open and close one book, and who is connected (2026-11-20) + +The server opens and closes one book while it runs (`ledger-mcp/src/local.rs` +INVARIANTS 3, 10 to 12; `admin.rs` INVARIANTS 8 and 9; `sessions.rs`). The +rule the tests prove: for every call, either it ran completely and is in +the journal, or it was refused and nothing of it is; after a close is +answered no call on that book runs until it is opened again; and a close of +one book never refuses or holds up a call on another. + +| Test | What it proves | +|---|---| +| `local::tests::a_closed_book_is_refused_as_closed_and_the_other_still_serves` | a closed book's door says `closed` with the words an agent can relay, a name that is no book says `no-such-books`, the other book still passes the door, the list shows closed (not a problem), closing twice is `was_not_open`, opening is `opened` then `already_open`, a name that is no book is `no_such_book` | +| `local::tests::a_closed_book_can_be_opened_by_another_program_and_not_by_two` | a close releases the store's writer lock (another `Store::open` succeeds); while another holds it, opening says `another program has these books open` and the book is listed with that problem; once it lets go it opens | +| `local::tests::a_close_waits_for_the_requests_inside_and_refuses_the_next` | a close answers only after a request already inside the book's gate has left; a request arriving meanwhile is refused as closed at once; another book's door is not held up | +| `local::tests::the_books_open_at_the_start_are_chosen_by_option` | `--open` takes `all`, `none`, or ids, and refuses a bad id | +| `local::tests::the_sessions_request_says_who_is_connected_and_never_their_token` | the sessions list: the token's name, the client from `initialize` (known before any call), the agent's self-report, the last call; no token text; an ended session is not listed; a book's sessions end with it and a reopened book has none | +| `sessions::tests` (3) | the running count rides in the call's guard; the last call, the client and the agent are kept, masked of any full TIN; a note for an ended session is dropped | +| `book_open_close::books_left_closed_at_the_start_say_so_and_open_when_asked` | a real server started with `--open BOOK`: the other book is listed closed and says so on the MCP, download, export and upload routes; a name that is no book is 404; opening serves | +| `book_open_close::the_open_option_takes_none_and_refuses_a_book_that_doesnt_exist` | `--open none` leaves every book closed; `--open nobody` exits 2 before opening anything | +| `book_open_close::the_sessions_request_names_each_connection_and_never_its_token` | over the real socket: two tokens, two clients, an agent's report, neither token's text nor SHA-256 in the answer, an ended session gone, a close ends the book's sessions | +| `book_open_close::closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing` | the hammer: 6 agents on one book (which has a backup target, every timer at 10 ms, and two clients sending bad tokens so refusals are being recorded) and 4 on another make journaled drafts and reads while the first is closed and reopened 12 times, and a maker thread creates up to eight new books and closes and opens a third over and over (every one must be answered as asked: a close of the first never stops, refuses or fails an admin job on another book; a probabilistic check, the deterministic one is `closing_and_opening_one_book_never_…`); every file of the closed book (journal, access log, every ops log, stored files, the backup's repository) is hashed when the close is answered and compared just before the reopening, every cycle; "the other book progressed" waits on that condition, not a sleep; the logs end as whole chains; both journals are replayed afterwards: every acknowledged draft is in its journal exactly once under the id it was told, no refused call left anything, the closed book's journal and access log never moved between the close answer and the reopening, the other book never refused a call and kept answering while the first was closed, and the books replay with gapless ids | +| `book_open_close::a_close_doesnt_wait_for_a_clients_open_event_stream` | a client keeps its standalone event stream (a GET) open (known open: its response head has come; no sleep): closing its book still answers at once, not after the grace for answers on their way out (it took 12 s while the stream was counted as an answer, which stalled the bridge in a hand demonstration) | +| `local::tests::a_refusal_being_recorded_keeps_its_place_when_its_client_hangs_up` | a request refused at the door has its access record written by a task that keeps its place inside the book's door: with the only blocking thread held and the request's future dropped, the door stays counted, a close waits, and the record is written before it empties (it was uncounted: the record could land after the close, and after a reopening) | +| `local::tests::handles_from_before_a_close_do_nothing_after_the_book_is_open_again` | the access log, uploads, exports and backups taken before a close, used after the same book is opened again (a late record, a sweep, a grant, an export, a run, a drill, a format upgrade), write nothing: the reopened book's tree is byte for byte what its own upgrade left, and its backup record is a whole chain (fails when the backups' shut flag and record close are removed) | +| `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_stalled_upload_body_cannot_hold_a_close_and_leaves_no_part_file` | an upload stops sending half way: the close waits the grace (600 ms), cuts it (connection closed, no part file, no bytes kept, record `cut_by_close`) and answers; the folder stands still; one whole access chain across the reopening (hung before the change) | +| `book_open_close::a_stalled_mcp_body_cannot_hold_a_close_and_nothing_of_it_is_journaled` | a `tools/call` whose body stops half way is cut by the close: connection closed, the call is not in the journal, record `cut_by_close` (hung before the change) | +| `book_open_close::a_restore_over_an_open_book_is_not_held_by_a_stalled_upload` | a restore over an open book with an upload stalled half way: the upload is cut after the grace, no part file in `legacy/`, the replaced book's log records `cut_by_close`, the restore is answered | +| `book_open_close::a_restore_over_an_open_book_waits_for_what_is_inside_it` | (extended) every call while the restore waits for a half-received upload gets 503 and the closed words, never 404 `no such books` (fails when the restore takes the book out of the list before it shuts the door) | +| `ledger-store` `uploads::tests::a_close_in_the_middle_of_a_file_stops_it_at_the_next_chunk`, `uploads::tests::a_close_between_the_last_byte_and_the_rename_keeps_nothing`, `exports::tests::a_close_waits_for_a_fetch_that_is_reading` | the types' own claims (INVARIANT 6 of uploads, 5 of exports): a close in the middle of a file stops it at the next chunk (no read after, no part left), a close between the last byte and the rename keeps nothing, and a fetch reads under the lock a close takes (a named pipe holds it inside its read; `close` must not return); each fails with its guard removed | +| `book_open_close::a_slow_upload_that_finishes_within_the_grace_is_not_cut` | (made deterministic) the grace is a minute and the rest of the bytes go only after the book is listed closed: the cut waits for the grace (fails with the cut set to fire at once) | +| `book_open_close::an_upload_still_arriving_when_the_grace_runs_out_is_cut_however_active_it_is` | the mirror: a client sending 8 KB every 25 ms (not stalled) of a 3 MB body with a 600 ms grace is cut (`cut_by_close`, no part, no bytes kept) and the close answered; driven by the client's condition (it sends until the connection is closed), fails with the cut removed | +| `book_open_close::the_servers_own_close_cuts_stalled_requests_and_exits_zero_in_time` | one upload stalled on one book and one MCP body stalled on another, the server's stdin closed: exit code 0 within the bound, both cut after the grace, no part file, nothing journaled, two `cut_by_close` records, every log whole | +| `book_open_close::a_backup_and_a_sweep_that_took_their_handles_before_a_close_do_nothing_after_it`, `…a_drill_and_a_sweep…` | `--timer-hold` holds a timer between taking a book's handles and acting; the book is closed meanwhile, stray files planted, the timers go on: the closed book's tree doesn't move; opened again the sweep works (fail with the handles' closed state, the gate's check and the backups' shut flag removed) | +| `book_open_close::a_close_stops_a_slow_drill_instead_of_waiting_for_it` | `--slow-steps` makes each phase of a drill wait a minute: the close answers plain `closed` (the last backup was made), within the stated sum, with the drill's scratch clone removed (fails without `hurry`: `closed_backup_incomplete`) | +| `book_open_close::a_close_that_stops_git_in_a_commit_or_a_push_leaves_no_lock_and_the_next_backup_succeeds` | REAL git (a wrapper that points git's hooks at a `reference-transaction` hook that waits) stopped inside `init`, a commit and a push to a folder by a close: git is sent SIGTERM and removes its own locks, so none is left in the archive or the folder and the backup's record holds no `lock_removed` or `lock_left` (nothing for the server to clean up), the reopened book backs up with no step by hand, `git fsck --strict` passes on both | +| `local::tests::a_close_stops_a_format_upgrade_before_it_is_journaled` | an upgrade held in its backup's proof: the close stops it, it says nothing was upgraded, the journal is byte for byte as before | +| `local::tests::a_body_read_to_its_end_is_never_cut_and_one_not_yet_is` | the line of the cut: a body read to its end is never cut (the cut firing, the body asked again), one not read to its end is cut even with bytes on the way | +| `ledger-store` `backup::tests::a_git_stopped_by_sigterm_mid_commit_…`, `…_stopped_mid_add_…`, `a_push_stopped_by_sigterm_…`, `a_git_that_ignores_sigterm_…`, `a_git_that_cannot_end_on_sigterm_…`, `a_lock_left_in_a_folder_target_…`, `a_push_stopped_during_the_pack_transfer_…`, `the_archives_age_rule_at_open`, `removal_after_a_stop_goes_through_the_handle_…`, `git_locks::tests` (3) | REAL git stopped inside a commit (HEAD and ref locks), an add (the index lock) and a push to a folder (the target's ref lock): on SIGTERM it removes its own locks and nothing is noted (the grace is long, so a git that needed the kill would show); a git whose group is frozen (SIGSTOP, so SIGTERM stays pending) is killed only after the grace, and the archive's locks it left (not there when the command began) are removed, noted; the folder target's lock is NEVER removed, reported with its whole path (`LockLeft`, `lock_left` with `path`), a lock that was there before the push is untouched and not named, a later push fails by git's words and removes nothing, the next one passes once the test removes the file; a fake git that traps SIGTERM is sent it first (marker) and killed after the grace with all it started; a 48 MiB pack held in the receiving end's `pre-receive` hook (the target's `incoming-` quarantine present) stopped by SIGTERM and by the kill, `git fsck --strict` on both repositories at once; the archive's locks at open: older than ten minutes removed and noted, younger left and said, non-lock names, folders and links untouched; a swapped `refs` folder or archive path after the handle was opened touches nothing outside; the handle module: exact lock names only, regular files only, no link followed | +| `ledger-store` `backup::tests::a_drill_stops_inside_the_phase_it_is_told_to_stop_in` | for each phase (clone, replay, verify, blobs, prefix) a stop set as the phase begins ends the drill inside it (the observer sees no later phase), scratch removed; each case fails when the loop's looks inside that phase are removed | +| `book_open_close::a_running_call_is_never_cut_when_the_grace_runs_out` | an ordinary call (`books.attach_receipt`, held inside its read of its file, a named pipe) past the grace (body whole) is not cut: it finishes when fed, is answered and recorded `ok`, and then the close is answered (a backup asked for is no longer this call: it is stoppable) | +| `book_open_close::a_close_stops_a_running_backup_call_and_says_so` | `books.back_up_now` held in a stalled `git` (never lifted until the call answers): the close stops it, the call is answered that it was stopped because the books are closing, its access record is `refused: stopped_by_close` with no head, the backup record holds `stopped` and no result of its own for the run, git and all it started are gone, the close's last backup is made and the close answers `closed` | +| `book_open_close::a_close_stops_a_running_verification_and_a_running_package_and_says_so` | `books.verify` and `books.export_cpa_package` held as they begin by `--timer-hold` (`call:...`), which the close releases: each is stopped at its first look, answers it was stopped, is recorded `refused: stopped_by_close`, the journal is unchanged | +| `book_open_close::a_close_stops_the_restore_and_the_open_of_its_own_book_leaving_the_root_as_it_was` | a restore over a book and the open of a book, each held inside a phase (`restore:copy`, `open:start`): its scratch or staging folder is there while held; a close of THAT book stops it, it answers it was stopped, the root's `books/` and `legacy/` are byte for byte as before; asked again it goes through | +| `book_open_close::the_servers_close_stops_every_running_admin_job_leaving_the_root_as_it_was` | restore (a new book, and over `acme`), adopt, create and open, each held inside a phase, the server closed with nothing lifting the hold: each answers it was stopped, the root as it was, exit 0; asked again on a new server the first goes through | +| `book_open_close::closing_and_opening_one_book_never_stops_waits_for_or_refuses_another_books_jobs` | a restore over `beta`, a create of `epsilon` and an adoption of `delta` in flight (they make books one at a time, so the later two queue for their turn, and each is held in its phase in its time), `acme` closed (its backup's git stalled, so the close is slow) and opened again around each; during each close `cedar` is opened and closed and answers while the close of `acme` is still not answered; all three finish (`Restored`, `Created`, `Adopted`, no problem), none was stopped. Mutations: a close that raises a server-wide stop fails it (a queued job stopped); one global lock around open and close fails it (the open waits for the close) | +| `book_open_close::a_close_never_leaves_a_decision_on_record_for_a_package_that_was_not_made` | `books.export_cpa_package` with `allow_open_drafts`: held as it begins and the book closed, it is stopped and the journal holds no decision; held right after its decision is journaled and the book closed, it is made, handed over (`ok`), one decision. Mutations: no look before the journaling fails the first; a build still stoppable after it fails the second | +| `ledger-store` `tests/root.rs::a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_it_was` | create, adopt, restore (over existing books) and the restore preview stopped at each phase they ask: `Stopped`, the root (`books/`, `legacy/`) byte for byte as before; never stopped, `place` is the last phase asked (nothing after the point of no return) | +| `ledger-store` `tests/root.rs::an_adoption_that_does_not_finish_leaves_no_lock_file_in_the_source` | a source with no lock file: the adoption stopped at each of its seven phases, refused after taking the lock (a stale preview head), and panicking in the middle leaves the source folder name for name, byte for byte and mode for mode as it was; a lock file swapped in by someone else during the adoption is not removed; a source that had its lock keeps it (stopped or adopted, `source_lock_created` false); a success of a source with none leaves the one it made and says so. Mutation: no removal fails it | +| `ledger-store` `tests/root.rs::a_job_waiting_for_its_turn_stops_when_asked_and_otherwise_waits_for_it` | the turn at making books held (as another process would): a create that isn't asked to stop waits, and stops within seconds once asked (`Stopped`, nothing made); not asked, it goes through when the turn is let go. Mutation: a blocking wait for the turn fails it | +| `book_open_close::a_lock_a_kill_leaves_in_the_backup_folder_is_reported_and_never_removed_by_the_server` | REAL git in a push to a folder with its group frozen, so only the kill after the grace ends it: the lock it leaves is still there after the close, recorded `lock_left` with its whole path, no `lock_removed` for the folder, the close's answer and `books.backup` name the file and say when it may be removed, a lock that was there before is neither touched nor named, a later backup fails by git's words and removes nothing, and once the file is removed the backup goes on, `git fsck --strict` on both | +| `book_open_close::a_call_whose_answer_was_never_read_is_on_record_as_having_run` | a journaled draft whose client goes without reading: after the close the access log has its record, outcome `ok`, with the head it wrote (INVARIANT 14: a retry isn't made safe by anything; the record says it ran) | +| `book_open_close::a_close_is_not_answered_while_its_backup_still_runs` | a book with a folder target and a stand-in `git` on the server's PATH that waits: the close isn't answered before its backup bound (1.2 s), then answers `closed_backup_incomplete`, git and all it started are gone, and lifting the stall makes nothing resume; the reopened book's backup record is a whole chain and it backs up (fails when `shut` is removed: git still runs after the answer) | +| `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 | + +**Waiting on conditions, not on guesses (review of 2026-11-20).** A test of +this branch that slept for a fixed time to let "the other side get there" +now waits on the condition: `exports::tests::a_close_waits_for_a_fetch_that_is_reading` +(it slept 300 ms assuming its thread had reached the named pipe; it now +opens a non-blocking writer on the pipe, which succeeds only once a reader +has it open); the two MCP bodies that stop half way +(`a_stalled_mcp_body_cannot_hold_a_close_…`, the server's-own-close test, the +second of which slept 200 ms and the first nothing at all) send their head +with `Expect: 100-continue` and their body only on the server's `100 +Continue`, which the server sends when its handler first reads the body, +inside the book's door (`raw::Raw::start_inside`); the late-timer test no +longer sleeps 300 ms before its 800 ms window in which nothing may move; +`a_close_whose_backup_fails_…` waits out the backup the opening makes by +asking for one itself (it could be stopped by the close and leave a lock). The +sleeps that remain are negative windows (a close must NOT have been answered; +nothing must move), which can only fail when the property is broken, never +because the machine is slow, and pacing of a stimulus (the hammer's jitter, +a client trickling an upload on purpose). + +**For P12 (mutation targets).** `Gate::enter` (count before looking at `shut`), +`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. + ## P12: the checklists The **For P12** paragraphs above (kept where they were written, with their