From 89403a715977bb91a1598f56375fc81982aa5aed Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Fri, 20 Nov 2026 09:23:39 -0700 Subject: [PATCH] fix(mcp): a close waits for the answers on their way out, and test it under a hammer The first run of the hammer (agents calling two books while one is closed and reopened over and over) found a real race: an MCP request's handler returns as soon as the session's task has the request, and the tool's answer streams back afterwards. A close that waited only for handlers and running tools could end the sessions while an answer was still on its way, so a call that did not run (refused as closing) reached its client as neither answered nor refused. The gate now also counts answers on their way out (Answering, carried in the response body as the server's own close counts them), and a close waits for them, for ANSWER_GRACE at most, before it ends the sessions. The hammer (tests/book_open_close.rs) replays both journals afterwards: every acknowledged draft is there 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 its reopening, the other book never refused a call and kept answering while the first was closed. Beside it: a server started with --open, the sessions request over the real socket, the doctor's lines, and the docs (mcp-interface, architecture, testing). Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-cli/tests/book_open_close.rs | 506 +++++++++++++++++++++ crates/ledger-cli/tests/common/mod.rs | 10 + crates/ledger-host/src/commands.rs | 72 +++ crates/ledger-mcp/src/admin.rs | 5 +- crates/ledger-mcp/src/local.rs | 142 ++++-- crates/ledger-mcp/src/server.rs | 8 +- crates/ledger-mcp/src/sessions.rs | 9 +- docs/architecture.md | 9 + docs/mcp-interface.md | 46 +- docs/testing.md | 29 ++ 10 files changed, 802 insertions(+), 34 deletions(-) create mode 100644 crates/ledger-cli/tests/book_open_close.rs 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..09b73b42 --- /dev/null +++ b/crates/ledger-cli/tests/book_open_close.rs @@ -0,0 +1,506 @@ +//! 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::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:?}"), + }; + 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. +#[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")); + let server = Server::start(&home); + home.create(A, "USD"); + home.create(B, "USD"); + let stop = Arc::new(AtomicBool::new(false)); + let done = Arc::new(Mutex::new(Vec::new())); + let reads = Arc::new([AtomicUsize::new(0), AtomicUsize::new(0)]); + 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) + })); + } + } + 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); + assert_eq!(listed(&home, A), (false, true, None)); + closed_on_every_route(&home, A); + std::thread::sleep(Duration::from_millis(70)); + let after = files_of(&home, A); + assert_eq!( + (before.0.len(), before.1), + (after.0.len(), after.1), + "cycle {cycle}: the closed book's journal or access log moved" + ); + closed_for.push(before.0.len()); + // The other book answered while this one was closed. + let beta_after = done.lock().unwrap().iter().filter(|d| d.book == B).count(); + assert!( + beta_after > beta_before, + "cycle {cycle}: no call on {B} finished while {A} was closed" + ); + 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 { + a.join().unwrap(); + } + assert!(server.close().success()); + + 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:?}" + ); +} diff --git a/crates/ledger-cli/tests/common/mod.rs b/crates/ledger-cli/tests/common/mod.rs index e3990eb8..fed493f8 100644 --- a/crates/ledger-cli/tests/common/mod.rs +++ b/crates/ledger-cli/tests/common/mod.rs @@ -182,9 +182,18 @@ 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`], 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 +204,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 diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index 466a1496..072a4efb 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -3683,6 +3683,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. diff --git a/crates/ledger-mcp/src/admin.rs b/crates/ledger-mcp/src/admin.rs index 41a5cb0b..113d9b9f 100644 --- a/crates/ledger-mcp/src/admin.rs +++ b/crates/ledger-mcp/src/admin.rs @@ -670,10 +670,7 @@ 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 { .. } - | Request::Sessions => None, + Request::List | Request::TokenList | Request::TokenCheck { .. } | Request::Sessions => None, Request::OpenBook { .. } | Request::CloseBook { .. } => { Some("`wanderbooks books list` says whether the books are open") } diff --git a/crates/ledger-mcp/src/local.rs b/crates/ledger-mcp/src/local.rs index 5146a658..3005a0c5 100644 --- a/crates/ledger-mcp/src/local.rs +++ b/crates/ledger-mcp/src/local.rs @@ -222,10 +222,17 @@ impl Book { /// `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, } @@ -239,6 +246,25 @@ impl Drop for Inside { } } +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()) + } +} + +/// 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 { @@ -262,6 +288,18 @@ impl Gate { 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). @@ -1049,8 +1087,19 @@ impl Books { self.hold(&id, Book::Closed); // No tool starts, and every one that did start has finished. rt.block_on(store.close()); - // Every request inside the door has finished, its record written. + // Every request inside the door has finished, its record written; + // and the answers on their way out are sent (for a while at most: a + // client that never reads its answer doesn't hold the book open, + // as at the server's close). rt.block_on(gate.emptied()); + if rt + .block_on(tokio::time::timeout(ANSWER_GRACE, gate.answered())) + .is_err() + { + eprintln!( + "wanderbooks server: a client didn't take its answer; closing the books {id} without it" + ); + } // Its sessions end, and are forgotten. self.end_sessions(&id, &ended); // The last backup, as at the server's close; then nothing more of @@ -1219,10 +1268,7 @@ impl Books { // Its requests end first (a books.back_up_now among them waits for // a run of the loop's), then its last run. if let Some(Book::Open { - store, - gate, - ended, - .. + store, gate, ended, .. }) = &old { gate.shut(); @@ -2144,10 +2190,13 @@ async fn mcp( 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. + let answering = _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 })) }) @@ -3898,10 +3947,7 @@ mod tests { /// 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.insert("authorization", format!("Bearer {bearer}").parse().unwrap()); h } @@ -3933,10 +3979,16 @@ mod tests { 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")); + 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."); + 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"))); @@ -3963,7 +4015,13 @@ mod tests { } ); assert_eq!( - ask(&books, Request::CloseBook { id: "nobody".into() }).await, + ask( + &books, + Request::CloseBook { + id: "nobody".into() + } + ) + .await, Response::CloseBook { id: "nobody".into(), outcome: admin::CloseOutcome::NoSuchBook @@ -3980,7 +4038,13 @@ mod tests { opened("acme", admin::OpenOutcome::AlreadyOpen) ); assert_eq!( - ask(&books, Request::OpenBook { id: "nobody".into() }).await, + ask( + &books, + Request::OpenBook { + id: "nobody".into() + } + ) + .await, opened("nobody", admin::OpenOutcome::NoSuchBook) ); assert_eq!(at_the_door(&books, "acme", &acme).await, None); @@ -3997,14 +4061,20 @@ mod tests { 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")); + 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}"), + } => assert!( + why.contains("another program has these books open"), + "{why}" + ), other => panic!("{other:?}"), } match ask(&books, Request::List).await { @@ -4093,15 +4163,20 @@ mod tests { 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, + 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 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}"); @@ -4157,7 +4232,10 @@ mod tests { ); 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_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()); @@ -4172,16 +4250,26 @@ mod tests { // 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 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), [again.clone()]); - assert_eq!(ask(&books, Request::CloseBook { id: "acme".into() }).await, closed("acme")); + 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") + assert!( + all.iter().all(|b| b.book != "acme"), + "closed books list none" + ) } other => panic!("{other:?}"), } diff --git a/crates/ledger-mcp/src/server.rs b/crates/ledger-mcp/src/server.rs index d8f529a8..1c67c02a 100644 --- a/crates/ledger-mcp/src/server.rs +++ b/crates/ledger-mcp/src/server.rs @@ -2034,7 +2034,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, &self.board, &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/sessions.rs b/crates/ledger-mcp/src/sessions.rs index 6f537a14..58959997 100644 --- a/crates/ledger-mcp/src/sessions.rs +++ b/crates/ledger-mcp/src/sessions.rs @@ -188,7 +188,14 @@ mod tests { }), 100, ); - board.finished("s1", "books.trial_balance", &Outcome::Error, None, None, 200); + 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:?}"); 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..0dc955cd 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,41 @@ 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`, `was_not_open` or `no_such_book`. + In this order: new calls on the book are refused (the door is shut and + the book listed closed); the calls running on it finish, on every route + (nothing is killed, nothing is half-done); its MCP sessions end (an agent's next request on one + gets the "isn't open" words above, and after a reopening a 404 "Session + not found", which a client takes as "open a new one"); its last backup is + made, as at the server's close; its store is let go, releasing the + writer lock, so another process could open the book. Only then is + "closed" answered. Every other book keeps serving, and none of its + calls waits for this close. For every call, either it ran completely + and is in the journal, or it was refused unrun and nothing of it is; after + the answer, no call on that book runs until it is opened again. +- `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/testing.md b/docs/testing.md index e4c1e3e0..65f818dd 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -4290,6 +4290,35 @@ 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 and 4 on another make journaled drafts and reads while the first is closed and reopened 12 times; both journals are replayed afterwards: every acknowledged draft is in its journal exactly once under the id it was told, no refused call left anything, the closed book's journal and access log never moved between the close answer and the reopening, the other book never refused a call and kept answering while the first was closed, and the books replay with gapless ids | +| `commands::tests::doctor_says_who_is_connected` | the doctor's lines for sessions | + +**For P12 (mutation targets).** `Gate::enter` (count before looking at `shut`), +`Books::close_one`'s order (shut and list closed, `SharedStore::close`, the +gate emptied, sessions ended, the last backup, `let_go`), `door`'s entering +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