diff --git a/crates/ledger-cli/tests/agent_surface.rs b/crates/ledger-cli/tests/agent_surface.rs index abf66c19..223bd2af 100644 --- a/crates/ledger-cli/tests/agent_surface.rs +++ b/crates/ledger-cli/tests/agent_surface.rs @@ -123,11 +123,11 @@ fn journal_history_traces_what_the_books_did() { assert_eq!(next["lines"][0]["seq"].as_u64().unwrap(), after + 1); // A bad subject is refused with the shapes; the journal is unchanged. - let before = books.journal(); + let before = books.journal_raw(); let err = answer_of(&w.call("books.journal_history", json!({"subject": "nonsense"}))).unwrap_err(); assert!(err.contains("entry:12"), "{err}"); - assert_eq!(books.journal(), before); + assert_eq!(books.journal_raw(), before); // It is a read: no head in the envelope. assert!(all.get("head").is_none(), "{all}"); } diff --git a/crates/ledger-cli/tests/audit.rs b/crates/ledger-cli/tests/audit.rs index cb5c2cee..1cd9ea1a 100644 --- a/crates/ledger-cli/tests/audit.rs +++ b/crates/ledger-cli/tests/audit.rs @@ -157,13 +157,17 @@ fn audit_is_deterministic() { ); let run = first["run"].clone(); assert_eq!(run["at_current_head"], true); - let journal = books.journal(); + let journal = books.journal_raw(); let again = audit(&mut w, "full", "2026-03-31"); assert_eq!(again["status"], "already_run"); assert_eq!(again["run"]["id"], run["id"]); assert_eq!(again["run"]["findings_sha256"], run["findings_sha256"]); assert_eq!(again["findings"], first["findings"]); - assert_eq!(books.journal(), journal, "asking again journals nothing"); + assert_eq!( + books.journal_raw(), + journal, + "asking again journals nothing" + ); // The workpaper is the same twice, JSON and PDF. let id = run["id"].clone(); let one = answer_of(&w.call("books.workpaper", json!({"id": id}))).unwrap(); @@ -406,7 +410,7 @@ fn audits_wait_for_the_upgrade() { )) .unwrap(); assert_eq!(preview["status"], "preview"); - let journal = books.journal(); + let journal = books.journal_raw(); for (tool, args) in [ ( "books.audit", @@ -425,7 +429,7 @@ fn audits_wait_for_the_upgrade() { let e = answer_of(&w.call(tool, args)).unwrap_err(); assert!(e.starts_with("format_upgrade_pending"), "{tool}: {e}"); } - assert_eq!(books.journal(), journal, "a refusal journals nothing"); + assert_eq!(books.journal_raw(), journal, "a refusal journals nothing"); // The package is held up only by what it always was: an open draft. let args = json!({"as_of": "2026-01-31", "cash_accounts": ["1000"], "include_receipts": false, "include_tins": false}); diff --git a/crates/ledger-cli/tests/call_transactions.rs b/crates/ledger-cli/tests/call_transactions.rs index 20801615..9cf08ecb 100644 --- a/crates/ledger-cli/tests/call_transactions.rs +++ b/crates/ledger-cli/tests/call_transactions.rs @@ -6,7 +6,12 @@ //! answer, across a restart; the same key for another request is refused; //! a write without a key is not run; a failed write leaves its key free //! and the books as they were; a call is framed in the journal and the -//! import is one frame; every tool that can write asks for the key. +//! import is one frame; every tool that can write asks for the key; a call +//! that wrote lines and then failed rolls back, is on the record, and +//! frees its key; a call that wrote nothing leaves no line at all; the +//! same key under two tokens is two calls; a repeat that arrives while its +//! original runs gets its answer; a crash after the closing line is on +//! disk and before SQLite committed leaves the call done, once. use common::{Books, Wire, answer_of}; use serde_json::{Value, json}; @@ -263,3 +268,596 @@ fn every_tool_that_can_write_asks_for_a_key_and_no_other_does() { "{asking} write, {reading} read" ); } + +/// The books' SQLite projection file. +fn projection(books: &Books) -> std::path::PathBuf { + std::fs::read_dir(books.dir()) + .unwrap() + .flatten() + .map(|e| e.path()) + .find(|p| p.extension().is_some_and(|e| e == "db")) + .expect("the projection file") +} + +/// A `books.add_account` request. +fn account(key: &str) -> Value { + json!({"code": "1000", "name": "Bank", "account_type": "asset", "request_key": key}) +} + +/// The raw journal's line types, in order. +fn types(books: &Books) -> Vec { + lines(books) + .iter() + .map(|l| l["type"].as_str().unwrap().to_string()) + .collect() +} + +/// A call that gets as far as writing lines and then fails: its savepoint +/// rolls back, the live books are rebuilt without its lines, a `failed` +/// closing line is on the record, its key is free, and what takes its ids +/// next is a fact of the books (plan P15 2a, SCENARIO 2). +/// +/// The failure is the projection refusing the account's line: a +/// trigger put in the books' SQLite file from outside, as a full disk or a +/// corrupt page would. +#[test] +fn a_call_that_wrote_lines_and_then_failed_leaves_the_books_and_its_key_as_they_were() { + let books = Books::new("calls-failed-lines"); + let mut w = books.session("test"); + let before = types(&books); + let db = rusqlite::Connection::open(projection(&books)).unwrap(); + db.execute_batch( + "CREATE TRIGGER wb_test_refuses BEFORE INSERT ON accounts \ + BEGIN SELECT RAISE(ABORT, 'a test refuses this write'); END;", + ) + .unwrap(); + let failed = call_exactly(&mut w, "books.add_account", account("key-lines-fail-1")); + assert!(answer_of(&failed).is_err(), "{failed}"); + let added: Vec<_> = types(&books)[before.len()..].to_vec(); + assert_eq!( + added.first().map(String::as_str), + Some("call.begun"), + "{added:?}" + ); + assert_eq!(added.last().map(String::as_str), Some("call.closed")); + assert!( + added.len() >= 3, + "it wrote a line before failing: {added:?}" + ); + let all = lines(&books); + let closed = &all.last().unwrap()["payload"]; + assert_eq!(closed["outcome"], "failed"); + assert!(closed["error"].as_str().is_some_and(|e| !e.is_empty())); + assert!(closed.get("answer").is_none()); + // The live books are as they were: no such account, though a line was + // written. + db.execute_batch("DROP TRIGGER wb_test_refuses").unwrap(); + drop(db); + let banks = |w: &mut common::Wire| { + let chart = answer_of(&w.call("books.chart", json!({}))).unwrap(); + chart.to_string().matches("\"Bank\"").count() + }; + assert_eq!(banks(&mut w), 0); + // The key is free: the same request now succeeds, takes the id the dead + // call had, and is the only account. + let fixed = answer_of(&call_exactly( + &mut w, + "books.add_account", + account("key-lines-fail-1"), + )) + .unwrap(); + assert_eq!( + fixed["account_id"], 1, + "the dead call's account id is handed out again: {fixed}" + ); + assert_eq!(banks(&mut w), 1); + // History lists every line and says of the dead ones that they did not + // count; none of the counted lines is a dead one. + let history = answer_of(&w.call("books.journal_history", json!({"limit": 200}))).unwrap(); + let said: Vec<&str> = history["lines"] + .as_array() + .unwrap() + .iter() + .filter_map(|l| l["summary"].as_str()) + .filter(|s| s.contains("not counted")) + .collect(); + assert_eq!(said.len(), added.len() - 2, "{history}"); + // A restart replays the same books: the dead lines build nothing. + books.restart(); + let mut w = books.session("test"); + assert_eq!(banks(&mut w), 1); + answer_of(&w.call("books.verify", json!({}))).unwrap(); +} + +/// A call that wrote no line leaves none (WB-format-9): its answer is kept +/// for the life of the server, so a repeat within the session is answered; +/// after a restart the repeat simply runs again. +#[test] +fn a_call_that_wrote_nothing_leaves_no_line_and_is_answered_again_only_within_the_session() { + let books = Books::new("calls-nothing"); + let mut w = books.session("test"); + let before = books.journal_raw(); + let args = json!({"request_key": "key-nothing-0001", "sha256": "ab".repeat(32), + "size": 5, "mime_type": "text/csv", "file_name": "x.csv", + "purpose": "import"}); + let first = answer_of(&call_exactly(&mut w, "books.begin_upload", args.clone())).unwrap(); + assert_eq!(books.journal_raw(), before, "no frame, no line"); + let again = answer_of(&call_exactly(&mut w, "books.begin_upload", args.clone())).unwrap(); + assert_eq!(again, first, "the same answer within the session"); + assert_eq!(books.journal_raw(), before); + books.restart(); + let mut w = books.session("test"); + let after = answer_of(&call_exactly(&mut w, "books.begin_upload", args)).unwrap(); + assert_ne!(after, first, "after a restart it simply runs again"); + assert_eq!(books.journal_raw(), before, "and still writes nothing"); +} + +/// The same request key under two tokens is two calls: a key belongs to +/// the token that made it. +#[test] +fn the_same_key_under_two_tokens_is_two_calls() { + let books = Books::new("calls-two-tokens"); + let mut one = books.session("test"); + let second = books + .home + .token_with(&books.id, "second", &["read", "write", "post", "admin"]); + let mut two = common::Wire::with_token(&books.home, &books.id, Some(second)); + two.initialize("test"); + let a = answer_of(&call_exactly( + &mut one, + "books.draft_entry", + draft("key-tokens-0001", "Same"), + )) + .unwrap(); + let b = answer_of(&call_exactly( + &mut two, + "books.draft_entry", + draft("key-tokens-0001", "Same"), + )) + .unwrap(); + assert_ne!(a["entry_id"], b["entry_id"], "one draft per token: {a} {b}"); + let drafts = answer_of(&one.call("books.list_drafts", json!({}))).unwrap(); + assert_eq!( + drafts["drafts"].as_array().map(Vec::len), + Some(2), + "{drafts}" + ); + // And each token's repeat finds its own. + let a2 = answer_of(&call_exactly( + &mut one, + "books.draft_entry", + draft("key-tokens-0001", "Same"), + )) + .unwrap(); + assert_eq!(a2, a); +} + +/// A repeat that arrives while its original is still running waits for it +/// (writes take turns) and then gets its answer: the original's effects +/// are made once. Eight identical requests sent at the same moment make +/// one draft and are answered alike. +#[test] +fn a_repeat_arriving_while_its_original_runs_gets_its_answer_and_changes_nothing() { + let books = Books::new("calls-concurrent"); + let before = lines(&books).len(); + let barrier = std::sync::Barrier::new(8); + let (home, id) = (&books.home, books.id.clone()); + let answers: Vec = std::thread::scope(|scope| { + let runs: Vec<_> = (0..8) + .map(|n| { + let (barrier, id) = (&barrier, &id); + scope.spawn(move || { + let mut w = common::Wire::new(home, id); + w.initialize(&format!("racer-{n}")); + barrier.wait(); + call_exactly( + &mut w, + "books.draft_entry", + draft("key-concurrent-1", "Raced"), + ) + }) + }) + .collect(); + runs.into_iter().map(|r| r.join().unwrap()).collect() + }); + let answers: Vec = answers.iter().map(|a| answer_of(a).unwrap()).collect(); + assert!(answers.windows(2).all(|p| p[0] == p[1]), "{answers:?}"); + let all = lines(&books); + assert_eq!( + all[before..] + .iter() + .filter(|l| l["type"] == "entry.created") + .count(), + 1, + "one draft" + ); + assert_eq!( + all[before..] + .iter() + .filter(|l| l["type"] == "call.begun") + .count(), + 1, + "one frame" + ); +} + +/// A call whose answer is too long for the books to keep (above 4 KiB): +/// its closing line keeps the answer's hash and length, and a repeat, even +/// one that arrived while the original ran, is told in words that it was +/// done, with the lines it wrote; nothing is done twice. +#[test] +fn a_repeat_of_a_call_whose_answer_was_too_long_is_told_it_was_done() { + let books = Books::new("calls-long-answer"); + let mut w = books.session("test"); + for (code, name, kind) in [("1000", "Bank", "asset"), ("6000", "Supplies", "expense")] { + answer_of(&w.call( + "books.add_account", + json!({"code": code, "name": name, "account_type": kind}), + )) + .unwrap(); + } + let rows = 300; + let mut csv = String::from("Date,Description,Amount\n"); + for n in 0..rows { + csv.push_str(&format!("2026-01-02,Row {n},-1.{:02}\n", n % 100)); + } + let up = w.upload(csv.as_bytes(), "bank.csv", "text/csv", "import"); + let args = json!({"upload_id": up, "bank_account_code": "1000", + "default_offset_code": "6000", "request_key": "key-long-answer1"}); + let before = lines(&books).len(); + let (home, id) = (&books.home, books.id.clone()); + let (first, second) = std::thread::scope(|scope| { + let original = scope.spawn(|| { + let mut w = common::Wire::new(home, &id); + w.initialize("original"); + call_exactly(&mut w, "books.import_bank_csv", args.clone()) + }); + std::thread::sleep(std::time::Duration::from_millis(30)); + let repeat = scope.spawn(|| { + let mut w = common::Wire::new(home, &id); + w.initialize("repeat"); + call_exactly(&mut w, "books.import_bank_csv", args.clone()) + }); + (original.join().unwrap(), repeat.join().unwrap()) + }); + // One of the two ran; the other was told, in words, that it was done. + let (ran, told) = match (answer_of(&first), answer_of(&second)) { + (Ok(a), Err(why)) | (Err(why), Ok(a)) => (a, why), + other => panic!("one runs and one is told: {other:?}"), + }; + assert_eq!(ran["count"], rows, "{ran}"); + assert!(told.contains("was done"), "{told}"); + assert!(told.contains("nothing more was changed"), "{told}"); + assert!(told.contains("journal lines"), "{told}"); + let all = lines(&books); + assert_eq!( + all[before..] + .iter() + .filter(|l| l["type"] == "entry.created") + .count(), + rows, + "the file was imported once" + ); + let closed = all.last().unwrap(); + assert_eq!(closed["type"], "call.closed"); + assert!( + closed["payload"].get("answer").is_none(), + "no answer kept whole" + ); + assert_eq!( + closed["payload"]["answer_sha256"].as_str().map(str::len), + Some(64) + ); + assert!(closed["payload"]["answer_bytes"].as_u64().unwrap() > 4096); + // Across a restart the same words. + books.restart(); + let mut w = books.session("test"); + let again = call_exactly(&mut w, "books.import_bank_csv", args); + assert!(answer_of(&again).unwrap_err().contains("was done")); + assert_eq!(lines(&books).len(), all.len()); +} + +/// A crash after the closing line is on disk and before SQLite committed: +/// the books are rebuilt from the journal, the call is done, and a repeat +/// of its key answers the first answer and changes nothing. +#[test] +fn a_crash_with_the_ok_close_on_disk_but_sqlite_not_committed_leaves_the_call_done_once() { + let books = Books::new("calls-sqlite-behind"); + let mut w = books.session("test"); + answer_of(&call_exactly( + &mut w, + "books.draft_entry", + draft("key-crash-prior1", "Earlier"), + )) + .unwrap(); + drop(w); + // The projection as it was before the call. + books.stop(); + let db = projection(&books); + let old = std::fs::read(&db).unwrap(); + let side: Vec<_> = ["-wal", "-shm"] + .iter() + .map(|x| std::path::PathBuf::from(format!("{}{x}", db.display()))) + .collect(); + assert!( + side.iter().all(|p| !p.exists()), + "a stopped server leaves no -wal or -shm" + ); + books.start(); + let mut w = books.session("test"); + let first = answer_of(&call_exactly( + &mut w, + "books.draft_entry", + draft("key-crash-0001", "Done once"), + )) + .unwrap(); + drop(w); + let journal = books.journal_raw(); + assert_eq!( + lines(&books).last().unwrap()["payload"]["outcome"], + "ok", + "the ok closing line is on disk" + ); + // Power fails: the journal has it (it was fsynced first), SQLite does not. + books.stop(); + std::fs::write(&db, old).unwrap(); + books.start(); + let mut w = books.session("test"); + // The books are rebuilt from the journal: both drafts are there. + let drafts = answer_of(&w.call("books.list_drafts", json!({}))).unwrap(); + assert_eq!( + drafts["drafts"].as_array().map(Vec::len), + Some(2), + "{drafts}" + ); + // The repeat is answered with the first answer and does nothing. + let again = answer_of(&call_exactly( + &mut w, + "books.draft_entry", + draft("key-crash-0001", "Done once"), + )) + .unwrap(); + assert_eq!(again, first); + assert_eq!(books.journal_raw(), journal, "nothing more was written"); + let drafts = answer_of(&w.call("books.list_drafts", json!({}))).unwrap(); + assert_eq!( + drafts["drafts"].as_array().map(Vec::len), + Some(2), + "{drafts}" + ); + answer_of(&w.call("books.verify", json!({}))).unwrap(); +} + +// ---- The tax-id vault is inside the transaction (BS-partner-2). Obviously +// fake values: a TIN is never written in a journal line, an error, or here +// beyond these two. + +const OLD_TIN: &str = "123-45-6789"; +const NEW_TIN: &str = "765-43-2109"; + +fn digits(tin: &str) -> String { + tin.replace('-', "") +} + +/// Whether `text` holds either fake TIN, hyphenated or not. +fn holds_a_tin(text: &str) -> bool { + [OLD_TIN, NEW_TIN] + .iter() + .any(|t| text.contains(t) || text.contains(&digits(t))) +} + +/// What the vault holds for the party, by the vault's own reader: the +/// TIN's last four, or None. +fn vaulted_last4(books: &Books, party: u64) -> Option { + let book = books.dir(); + let key = book.join("keys").join("legacy.key"); + let vault = ledger_vault::Vault::open(&book.join("vault"), &key, false).ok()?; + vault.tin(party).unwrap().map(|t| t.last4().to_string()) +} + +fn staged_files(books: &Books) -> Vec { + std::fs::read_dir(books.dir().join("vault")) + .map(|d| { + d.flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|n| n.contains(".staged-") || n.contains(".purging-")) + .collect() + }) + .unwrap_or_default() +} + +fn set_tin(key: &str, tin: &str) -> Value { + json!({"party": "Mo", "tin": tin, "tin_type": "ssn", "request_key": key}) +} + +/// A set_tin that fails after it wrote the vault: the vault keeps the old +/// tax id whole and holds nothing of the new one, the journal holds +/// neither, and once the call can run again it is the new one that is kept. +#[test] +fn a_set_tin_that_fails_leaves_the_vault_as_it_was() { + let books = Books::new("calls-vault-fail"); + let mut w = books.session("test"); + let party = answer_of(&w.call( + "books.add_party", + json!({"name": "Mo", "roles": ["member"]}), + )) + .unwrap()["party_id"] + .as_u64() + .unwrap(); + answer_of(&call_exactly( + &mut w, + "books.set_tin", + set_tin("key-vault-first1", OLD_TIN), + )) + .unwrap(); + assert_eq!(vaulted_last4(&books, party).as_deref(), Some("6789")); + // The projection refuses the call's first line (its begin line). + let db = rusqlite::Connection::open(projection(&books)).unwrap(); + db.execute_batch( + "CREATE TRIGGER wb_test_refuses BEFORE UPDATE ON meta \ + BEGIN SELECT RAISE(ABORT, 'a test refuses this write'); END;", + ) + .unwrap(); + let failed = call_exactly( + &mut w, + "books.set_tin", + set_tin("key-vault-fail01", NEW_TIN), + ); + let why = answer_of(&failed).unwrap_err(); + assert!(!holds_a_tin(&why), "an error never holds a tax id"); + db.execute_batch("DROP TRIGGER wb_test_refuses").unwrap(); + drop(db); + // The failure here is one that persists (the projection refuses every + // write, as a full disk would), so the books server stops: the call's + // failed closing line is on disk, and what it staged is settled by what + // the journal says at the next start. + books.restart(); + let mut w = books.session("test"); + let log = books.server_log(); + assert!(log.contains("vault records unsettled"), "{log}"); + assert!(!holds_a_tin(&log), "a log never holds a tax id"); + // The journal's failed frame holds no tax id, and the old one is whole in + // the vault; nothing is left staged. + assert_eq!( + lines(&books)[lines(&books).len() - 1]["payload"]["outcome"], + "failed" + ); + assert!(!holds_a_tin( + &String::from_utf8(books.journal_raw()).unwrap() + )); + assert_eq!(vaulted_last4(&books, party).as_deref(), Some("6789")); + assert_eq!(staged_files(&books), Vec::::new()); + // The party still shows the old last four. + let shown = answer_of(&w.call("books.party", json!({"party": "Mo"}))).unwrap(); + assert!(shown.to_string().contains("6789"), "{shown}"); + assert!(!shown.to_string().contains("2109"), "{shown}"); + // The key is free: the same request now succeeds and the vault holds the new one. + answer_of(&call_exactly( + &mut w, + "books.set_tin", + set_tin("key-vault-fail01", NEW_TIN), + )) + .unwrap(); + assert_eq!(vaulted_last4(&books, party).as_deref(), Some("2109")); + assert_eq!(staged_files(&books), Vec::::new()); + assert!(!holds_a_tin( + &String::from_utf8(books.journal_raw()).unwrap() + )); +} + +/// Two requests that differ only in a tax id are two requests: the same key +/// with another tax id is refused, never answered as a repeat, and nothing +/// of either is in the journal to test a guess against. +#[test] +fn a_key_reused_for_another_tax_id_is_refused_not_repeated() { + let books = Books::new("calls-vault-mask"); + let mut w = books.session("test"); + answer_of(&w.call( + "books.add_party", + json!({"name": "Mo", "roles": ["member"]}), + )) + .unwrap(); + let first = answer_of(&call_exactly( + &mut w, + "books.set_tin", + set_tin("key-mask-000001", OLD_TIN), + )) + .unwrap(); + // The same request again: the first answer, nothing more written. + let journal = books.journal_raw(); + let again = answer_of(&call_exactly( + &mut w, + "books.set_tin", + set_tin("key-mask-000001", OLD_TIN), + )) + .unwrap(); + assert_eq!(again, first); + // Another tax id under the same key: refused in words. + let other = call_exactly(&mut w, "books.set_tin", set_tin("key-mask-000001", NEW_TIN)); + let why = answer_of(&other).unwrap_err(); + assert!(why.contains("already used"), "{why}"); + assert!(!holds_a_tin(&why)); + assert_eq!(books.journal_raw(), journal); + assert!(!holds_a_tin(&String::from_utf8(journal).unwrap())); + // And across a restart, with the digest keyed by the books' own secret. + books.restart(); + let mut w = books.session("test"); + let other = call_exactly(&mut w, "books.set_tin", set_tin("key-mask-000001", NEW_TIN)); + assert!(answer_of(&other).unwrap_err().contains("already used")); + let same = answer_of(&call_exactly( + &mut w, + "books.set_tin", + set_tin("key-mask-000001", OLD_TIN), + )) + .unwrap(); + assert_eq!(same, first); +} + +/// A crash after the closing line is on disk and before the staged vault +/// record was made final: the next start finishes what the journal says +/// was done (the new tax id is the party's), and drops what no committed +/// call staged. +#[test] +fn a_crash_between_the_commit_and_the_vault_settling_is_finished_at_the_next_start() { + let books = Books::new("calls-vault-crash"); + let mut w = books.session("test"); + let party = answer_of(&w.call( + "books.add_party", + json!({"name": "Mo", "roles": ["member"]}), + )) + .unwrap()["party_id"] + .as_u64() + .unwrap(); + answer_of(&call_exactly( + &mut w, + "books.set_tin", + set_tin("key-vcrash-first", OLD_TIN), + )) + .unwrap(); + drop(w); + books.stop(); + let record = books.dir().join("vault").join(format!("tin-{party}.bin")); + let old = std::fs::read(&record).unwrap(); + books.start(); + let mut w = books.session("test"); + answer_of(&call_exactly( + &mut w, + "books.set_tin", + set_tin("key-vcrash-second", NEW_TIN), + )) + .unwrap(); + drop(w); + let closed = lines(&books) + .into_iter() + .rev() + .find(|l| l["type"] == "call.closed") + .unwrap(); + assert_eq!(closed["payload"]["outcome"], "ok"); + let tag = ledger_store::calls::call_tag( + closed["payload"]["token"].as_str().unwrap(), + closed["payload"]["key"].as_str().unwrap(), + ); + books.stop(); + let new = std::fs::read(&record).unwrap(); + assert_ne!(old, new); + // As a crash would have left it: the closing line is on disk, the new + // record is still staged, the old one still final. And a record staged + // by a call the journal never closed. + std::fs::write(&record, &old).unwrap(); + let staged = record.with_file_name(format!("tin-{party}.staged-{tag}")); + std::fs::write(&staged, &new).unwrap(); + let stray = record.with_file_name(format!("tin-99.staged-{}", "0123456789abcdef")); + std::fs::write(&stray, &new).unwrap(); + books.start(); + assert_eq!( + vaulted_last4(&books, party).as_deref(), + Some("2109"), + "finished" + ); + assert!( + !staged.exists() && !stray.exists(), + "{:?}", + staged_files(&books) + ); + assert!(books.server_log().contains("vault records unsettled")); +} diff --git a/crates/ledger-cli/tests/documents.rs b/crates/ledger-cli/tests/documents.rs index 7d274a24..c36455c8 100644 --- a/crates/ledger-cli/tests/documents.rs +++ b/crates/ledger-cli/tests/documents.rs @@ -123,7 +123,7 @@ fn an_invoice_from_issue_to_paid() { // The preview: nothing written, a DRAFT copy handed over, the number // and due date the confirm will take. - let before = books.journal(); + let before = books.journal_raw(); let preview = m.call("books.create_invoice", issue.clone()); assert!( preview["preview"].is_string(), @@ -155,7 +155,7 @@ fn an_invoice_from_issue_to_paid() { let draft = m.handed(&preview["pdf"]); assert!(draft.starts_with(b"%PDF"), "a PDF, not bytes inline"); assert!(draft.len() > 1_000, "the DRAFT copy is a page: {preview}"); - assert_eq!(books.journal(), before, "a preview journals nothing"); + assert_eq!(books.journal_raw(), before, "a preview journals nothing"); assert!(books.journal().len() == before.len()); // The confirm: the same number, the issued copy filed with the invoice. @@ -239,7 +239,7 @@ fn a_bill_with_its_vendor_invoice_and_terms() { "account": "6500"}], }); - let before = books.journal(); + let before = books.journal_raw(); let mut preview = bill.clone(); preview["upload_id"] = json!(file); let p = m.call("books.create_bill", preview.clone()); @@ -248,7 +248,7 @@ fn a_bill_with_its_vendor_invoice_and_terms() { assert_eq!(p["terms"], "2/10 net 30", "{p}"); assert_eq!(p["discount_by"], "2026-02-11", "{p}"); assert_eq!(p["max_discount"], "20.00", "2% of 1,000.00"); - assert_eq!(books.journal(), before, "a preview journals nothing"); + assert_eq!(books.journal_raw(), before, "a preview journals nothing"); let mut confirm = preview; confirm["confirmed"] = json!(true); @@ -321,13 +321,13 @@ fn duplicate_vendor_invoice_refused() { m.call("books.create_bill", bill(&first_file, "2026-02-01")); // The same number (however written) is the same vendor invoice. let second_file = m.upload(b"second copy", "ch-1-again.pdf", "receipt"); - let before = books.journal(); + let before = books.journal_raw(); let refused = m .try_call("books.create_bill", bill(&second_file, "2026-02-02")) .unwrap_err(); assert!(refused.contains("CH-4471"), "{refused}"); assert!(refused.contains("duplicate_reason"), "{refused}"); - assert_eq!(books.journal(), before, "a refusal journals nothing"); + assert_eq!(books.journal_raw(), before, "a refusal journals nothing"); // The upload was given back, not used up (an upload is spent only by // the call that files it). let mut with_reason = bill(&second_file, "2026-02-02"); @@ -377,14 +377,14 @@ fn a_line_account_must_be_allowed() { "lines": [{"description": "Work", "amount": "100.00", "account": account}], "confirmed": true}) }; - let before = books.journal(); + let before = books.journal_raw(); // An invoice line may not post to the receivable control or a role // account. let why = m .try_call("books.create_invoice", invoice("1200")) .unwrap_err(); assert!(why.contains("1200"), "{why}"); - assert_eq!(books.journal(), before, "a refusal journals nothing"); + assert_eq!(books.journal_raw(), before, "a refusal journals nothing"); // Nor to an expense account. let why = m .try_call("books.create_invoice", invoice("6999")) @@ -547,7 +547,7 @@ fn custom_terms_are_due_on_the_date_they_give() { assert_eq!(bill["due_date"], "2026-11-20", "{bill}"); // Dated after the agreed day: refused. - let before = books.journal(); + let before = books.journal_raw(); let late = m .try_call( "books.create_invoice", @@ -555,7 +555,7 @@ fn custom_terms_are_due_on_the_date_they_give() { ) .unwrap_err(); assert!(late.contains("due"), "{late}"); - assert_eq!(books.journal(), before, "a refusal writes nothing"); + assert_eq!(books.journal_raw(), before, "a refusal writes nothing"); } /// A customer given by id and by name is the same record (the old @@ -589,7 +589,7 @@ fn a_customer_by_id_and_by_name_is_one_record() { // ambiguous, and is refused rather than guessed. m.customer("Zeta"); m.customer("2"); - let before = books.journal(); + let before = books.journal_raw(); let why = m .try_call( "books.create_invoice", @@ -598,7 +598,7 @@ fn a_customer_by_id_and_by_name_is_one_record() { ) .unwrap_err(); assert!(why.contains("ambiguous"), "{why}"); - assert_eq!(books.journal(), before, "a refusal journals nothing"); + assert_eq!(books.journal_raw(), before, "a refusal journals nothing"); // Nothing at all names no customer. let why = m .try_call( diff --git a/crates/ledger-cli/tests/drafts.rs b/crates/ledger-cli/tests/drafts.rs index 4bc9ebf9..022fed3f 100644 --- a/crates/ledger-cli/tests/drafts.rs +++ b/crates/ledger-cli/tests/drafts.rs @@ -397,7 +397,7 @@ fn stale_preview_refused() { json!({"entry_id": id, "account": "1000", "side": "credit", "amount": "1.00"}), )) .unwrap(); - let before = books.journal(); + let before = books.journal_raw(); let r = w.call_raw( "books.post_entry", json!({"entry_id": id, "confirmed": true, "preview": digest}), @@ -405,7 +405,11 @@ fn stale_preview_refused() { let err = refusal(&r); assert_eq!(err["code"], "stale_preview"); assert_eq!(err["remedy_tool"], "books.post_entry"); - assert_eq!(books.journal(), before, "a stale confirm writes nothing"); + assert_eq!( + books.journal_raw(), + before, + "a stale confirm writes nothing" + ); // An operation's preview moves with the journal's head: a post by // another session in between forces a re-preview. let other = draft(&mut w, "2026-03-02", "Other", "5.00"); diff --git a/crates/ledger-cli/tests/evidence.rs b/crates/ledger-cli/tests/evidence.rs index addd1031..a80e3864 100644 --- a/crates/ledger-cli/tests/evidence.rs +++ b/crates/ledger-cli/tests/evidence.rs @@ -325,11 +325,11 @@ fn consolidation_never_removes_an_entrys_only_evidence() { let (_root, fixture) = legacy_duplicates("dupes-only", true); let books = Books::placed("p6-dupes-only", &fixture); let mut w = books.session("evidence"); - let before = books.journal(); + let before = books.journal_raw(); let r = w.call("books.consolidate_duplicates", json!({"confirmed": true})); let why = answer_of(&r).unwrap_err(); assert!(why.contains("receipt_required"), "{why}"); - assert_eq!(books.journal(), before, "a refusal journals nothing"); + assert_eq!(books.journal_raw(), before, "a refusal journals nothing"); } /// Plan P6 step 4: the kept file takes every subject the duplicates had; @@ -351,8 +351,8 @@ fn consolidation_links_the_kept_file_to_every_subject() { assert_eq!(preview["status"], "preview"); assert_eq!(preview["groups"][0]["keep"], 1); assert_eq!(preview["groups"][0]["withdraw"], json!([2])); - let before = books.journal(); - assert_eq!(before, books.journal(), "a preview journals nothing"); + let before = books.journal_raw(); + assert_eq!(before, books.journal_raw(), "a preview journals nothing"); let r = w.call("books.consolidate_duplicates", json!({"confirmed": true})); let out = answer_of(&r).unwrap(); assert_eq!(out["status"], "consolidated", "{out}"); @@ -413,7 +413,7 @@ fn the_backfill_reads_an_old_fixtures_files_once() { // Attachment 1 is a PDF (one page with text), 2 a text file, 3 a // Markdown document. for id in 1..=2 { - let before = books.journal(); + let before = books.journal_raw(); let r = w.call("books.get_receipt", json!({"attachment_id": id})); let out = answer_of(&r).unwrap(); assert_eq!(out["text_status"], "not_extracted", "{out}"); @@ -425,7 +425,11 @@ fn the_backfill_reads_an_old_fixtures_files_once() { ledger_mcp::admin::Response::Extracted { status, .. } => assert_eq!(status, "ok"), other => panic!("{other:?}"), } - assert_ne!(books.journal(), before, "the backfill journals a record"); + assert_ne!( + books.journal_raw(), + before, + "the backfill journals a record" + ); } // The PDF's text is readable now, and its pages render. let r = w.call("books.get_receipt", json!({"attachment_id": 1})); @@ -446,18 +450,18 @@ fn the_backfill_reads_an_old_fixtures_files_once() { common::clean_env(&mut extract, books.home.dir.path()); extract.output().unwrap() }; - let before = books.journal(); + let before = books.journal_raw(); let out = run(); assert!(out.status.success(), "{out:?}"); assert!( String::from_utf8_lossy(&out.stdout).contains("Read attachment 3"), "{out:?}" ); - assert_ne!(books.journal(), before, "the command journals a record"); - let after = books.journal(); + assert_ne!(books.journal_raw(), before, "the command journals a record"); + let after = books.journal_raw(); let out = run(); assert!(out.status.success(), "{out:?}"); - assert_eq!(books.journal(), after, "an extract journals once"); + assert_eq!(books.journal_raw(), after, "an extract journals once"); books.start(); let mut w = books.session("evidence"); let r = w.call("books.verify", json!({})); diff --git a/crates/ledger-cli/tests/mcp_journeys.rs b/crates/ledger-cli/tests/mcp_journeys.rs index 6a5450fa..b76932e7 100644 --- a/crates/ledger-cli/tests/mcp_journeys.rs +++ b/crates/ledger-cli/tests/mcp_journeys.rs @@ -787,7 +787,7 @@ fn tin_bearing_files_are_refused_when_given_back_to_be_filed() { let handed_over = [w9_back, mcp.handed(&ws["csv"]), mcp.handed(&pkg["file"])]; // Given back, each is refused by its bytes, by every way a file is // filed. - let journal = books.journal(); + let journal = books.journal_raw(); for (n, bytes) in handed_over.iter().enumerate() { // One upload, refused by each tool and so left for the next. let up = mcp.upload(bytes, "receipt.pdf", "application/pdf", "receipt"); @@ -3314,7 +3314,7 @@ fn files_pass_only_by_handle_in_and_out() { ); mcp.call("books.import_chart_csv", json!({"upload_id": chart})); // In: an inline file is refused as unknown, storing nothing. - let journal = books.journal(); + let journal = books.journal_raw(); for (name, args) in [ ( "books.attach_receipt", @@ -3334,7 +3334,11 @@ fn files_pass_only_by_handle_in_and_out() { "{name}: {resp}" ); } - assert_eq!(books.journal(), journal, "an inline file stored something"); + assert_eq!( + books.journal_raw(), + journal, + "an inline file stored something" + ); // A posted entry with its receipt, and an asset with its tag. let receipt = b"%PDF-1.4 a receipt for the laptop"; let e = mcp.call( diff --git a/crates/ledger-cli/tests/spec_1099.rs b/crates/ledger-cli/tests/spec_1099.rs index 0e7c4440..de5b5d4c 100644 --- a/crates/ledger-cli/tests/spec_1099.rs +++ b/crates/ledger-cli/tests/spec_1099.rs @@ -107,11 +107,15 @@ impl Mcp { mcp } - /// The journal, without the frames of tool calls (D-88). + /// The journal, without the frames of tool calls (D-88): the events. fn journal(&self) -> Vec { - common::without_call_lines( - &std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(), - ) + common::without_call_lines(&self.journal_raw()) + } + + /// The journal, byte for byte: what a check that a refusal or a + /// preview "journaled nothing" compares, so a stray frame line is seen. + fn journal_raw(&self) -> Vec { + std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default() } /// The journal's line types, in order. @@ -154,7 +158,7 @@ impl Mcp { /// Call a tool; a refusal must leave the journal unchanged, a success /// must match the outputSchema. fn tool(&mut self, name: &str, args: Value) -> Out { - let before = self.journal(); + let before = self.journal_raw(); let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone()); let out = if let Some(err) = resp.get("error") { Out::RpcErr(err.clone()) @@ -184,7 +188,7 @@ impl Mcp { }; if out.refused() { assert!( - self.journal() == before, + self.journal_raw() == before, "refused {name} {args} changed the journal ({out:?})" ); } @@ -211,10 +215,10 @@ impl Mcp { /// `ok`, and the journal must not change (read-only tools). fn read_only(&mut self, name: &str, args: Value) -> Value { - let before = self.journal(); + let before = self.journal_raw(); let v = self.ok(name, args); assert!( - self.journal() == before, + self.journal_raw() == before, "read-only {name} changed the journal" ); v diff --git a/crates/ledger-cli/tests/spec_assets.rs b/crates/ledger-cli/tests/spec_assets.rs index 95034e19..d85de8e4 100644 --- a/crates/ledger-cli/tests/spec_assets.rs +++ b/crates/ledger-cli/tests/spec_assets.rs @@ -106,11 +106,15 @@ impl Mcp { mcp } - /// The journal, without the frames of tool calls (D-88). + /// The journal, without the frames of tool calls (D-88): the events. fn journal(&self) -> Vec { - common::without_call_lines( - &std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(), - ) + common::without_call_lines(&self.journal_raw()) + } + + /// The journal, byte for byte: what a check that a refusal or a + /// preview "journaled nothing" compares, so a stray frame line is seen. + fn journal_raw(&self) -> Vec { + std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default() } /// The journal's line types, in order. @@ -153,7 +157,7 @@ impl Mcp { /// Call a tool; a refusal must leave the journal unchanged, a success /// must match the outputSchema. fn tool(&mut self, name: &str, args: Value) -> Out { - let before = self.journal(); + let before = self.journal_raw(); let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone()); let out = if let Some(err) = resp.get("error") { Out::RpcErr(err.clone()) @@ -183,7 +187,7 @@ impl Mcp { }; if out.refused() { assert!( - self.journal() == before, + self.journal_raw() == before, "refused {name} {args} changed the journal ({out:?})" ); } @@ -210,10 +214,10 @@ impl Mcp { /// `ok`, and the journal must not change (read-only tools). fn read_only(&mut self, name: &str, args: Value) -> Value { - let before = self.journal(); + let before = self.journal_raw(); let v = self.ok(name, args); assert!( - self.journal() == before, + self.journal_raw() == before, "read-only {name} changed the journal" ); v @@ -1596,7 +1600,7 @@ fn a_disposal_inside_a_posted_month_takes_back_the_extra_days() { fn run_depreciation_skips_a_month_that_rounds_to_nothing() { let mut m = books("zero-month"); let (a, _) = m.register_ok(json!({"cost": "0.01", "useful_life_months": 3})); - let before = m.journal(); + let before = m.journal_raw(); let r = m.ok("books.run_depreciation", json!({"period": "2026-01"})); assert_eq!(r["runs"], json!([])); let skipped = r["skipped"].as_array().unwrap(); @@ -1609,7 +1613,7 @@ fn run_depreciation_skips_a_month_that_rounds_to_nothing() { .contains("rounds to nothing"), "{r}" ); - assert_eq!(m.journal(), before, "nothing journaled"); + assert_eq!(m.journal_raw(), before, "nothing journaled"); let r = m.ok("books.run_depreciation", json!({"period": "2026-02"})); assert_eq!(canon(r["runs"][0]["amount"].as_str().unwrap()), "0.01"); } diff --git a/crates/ledger-cli/tests/spec_attachments.rs b/crates/ledger-cli/tests/spec_attachments.rs index d2448088..851febd2 100644 --- a/crates/ledger-cli/tests/spec_attachments.rs +++ b/crates/ledger-cli/tests/spec_attachments.rs @@ -110,11 +110,15 @@ impl Mcp { mcp } - /// The journal, without the frames of tool calls (D-88). + /// The journal, without the frames of tool calls (D-88): the events. fn journal(&self) -> Vec { - common::without_call_lines( - &std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(), - ) + common::without_call_lines(&self.journal_raw()) + } + + /// The journal, byte for byte: what a check that a refusal or a + /// preview "journaled nothing" compares, so a stray frame line is seen. + fn journal_raw(&self) -> Vec { + std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default() } /// The journal's line types, in order. @@ -159,7 +163,7 @@ impl Mcp { /// Call a tool; a refusal must leave the journal unchanged, a success /// must match the outputSchema. fn tool(&mut self, name: &str, args: Value) -> Out { - let before = self.journal(); + let before = self.journal_raw(); let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone()); let out = if let Some(err) = resp.get("error") { Out::RpcErr(err.clone()) @@ -189,7 +193,7 @@ impl Mcp { }; if out.refused() { assert!( - self.journal() == before, + self.journal_raw() == before, "refused {name} {args} changed the journal ({out:?})" ); } @@ -216,10 +220,10 @@ impl Mcp { /// `ok`, and the journal must not change (read-only tools). fn read_only(&mut self, name: &str, args: Value) -> Value { - let before = self.journal(); + let before = self.journal_raw(); let v = self.ok(name, args); assert!( - self.journal() == before, + self.journal_raw() == before, "read-only {name} changed the journal" ); v diff --git a/crates/ledger-cli/tests/spec_mcp.rs b/crates/ledger-cli/tests/spec_mcp.rs index de511859..aca43151 100644 --- a/crates/ledger-cli/tests/spec_mcp.rs +++ b/crates/ledger-cli/tests/spec_mcp.rs @@ -224,11 +224,15 @@ impl Mcp { mcp } - /// The journal, without the frames of tool calls (D-88). + /// The journal, without the frames of tool calls (D-88): the events. fn journal(&self) -> Vec { - common::without_call_lines( - &std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(), - ) + common::without_call_lines(&self.journal_raw()) + } + + /// The journal, byte for byte: what a check that a refusal or a + /// preview "journaled nothing" compares, so a stray frame line is seen. + fn journal_raw(&self) -> Vec { + std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default() } /// What a read-only tool must leave as it was: every file of the books @@ -288,7 +292,7 @@ impl Mcp { /// Call a tool and check invariants 1, 2, 3 and 7 on the outcome. fn tool(&mut self, name: &str, args: Value) -> Out { - let before = self.journal(); + let before = self.journal_raw(); let files = self.read_only(name).then(|| self.data_files()); let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone()); let out = if let Some(err) = resp.get("error") { @@ -308,13 +312,13 @@ impl Mcp { }; if out.refused() { assert!( - self.journal() == before, + self.journal_raw() == before, "invariant 2: refused {name} {args} changed the journal ({out:?})" ); } if let Some(files) = files { assert!( - self.journal() == before, + self.journal_raw() == before, "readOnlyHint: {name} {args} changed the journal" ); assert_eq!( @@ -1953,16 +1957,16 @@ fn inv4_post_and_reverse_preview_without_confirmed() { json!({"entry_id": e, "confirmed": false}), json!({"entry_id": e, "confirmed": null}), ] { - let before = m.journal(); + let before = m.journal_raw(); let p = m.ok("books.post_entry", args.clone()); assert_eq!(p["status"], "preview", "{args}: {p}"); - assert!(m.journal() == before, "post_entry preview {args} wrote"); + assert!(m.journal_raw() == before, "post_entry preview {args} wrote"); assert_eq!(m.entry_status(e), "draft"); } - let before = m.journal(); + let before = m.journal_raw(); let posted = m.post(e).ok("confirmed post"); assert_eq!(posted["status"], "posted"); - assert!(m.journal() != before, "confirmed post wrote nothing"); + assert!(m.journal_raw() != before, "confirmed post wrote nothing"); assert_eq!(m.entry_status(e), "posted"); let rev = json!({"entry_id": e, "date": "2026-04-02", "description": "undo"}); @@ -1971,17 +1975,20 @@ fn inv4_post_and_reverse_preview_without_confirmed() { args.as_object_mut() .unwrap() .extend(extra.as_object().unwrap().clone()); - let before = m.journal(); + let before = m.journal_raw(); let p = m.ok("books.reverse_entry", args.clone()); assert_eq!(p["status"], "preview", "{args}: {p}"); - assert!(m.journal() == before, "reverse_entry preview {args} wrote"); + assert!( + m.journal_raw() == before, + "reverse_entry preview {args} wrote" + ); } let mut args = rev; args["confirmed"] = json!(true); - let before = m.journal(); + let before = m.journal_raw(); let r = m.ok("books.reverse_entry", args); assert_eq!(r["status"], "posted", "{r}"); - assert!(m.journal() != before); + assert!(m.journal_raw() != before); let tb = m.ok("books.trial_balance", json!({"as_of": "2026-12-31"})); assert_eq!(tb["balanced"], true); } @@ -2002,7 +2009,7 @@ fn a_reversal_dated_before_its_entry_is_refused_in_preview_and_post() { ); m.attach(Some(e), b"rent receipt"); m.post(e).ok("post"); - let before = m.journal(); + let before = m.journal_raw(); for confirmed in [None, Some(false), Some(true)] { let mut args = json!({"entry_id": e, "date": "2026-05-09", "description": "early"}); if let Some(c) = confirmed { @@ -2014,7 +2021,7 @@ fn a_reversal_dated_before_its_entry_is_refused_in_preview_and_post() { "{why}" ); } - assert!(m.journal() == before, "a refused reversal wrote"); + assert!(m.journal_raw() == before, "a refused reversal wrote"); let p = m.ok( "books.reverse_entry", json!({"entry_id": e, "date": "2026-05-10", "description": "same day"}), @@ -2147,7 +2154,7 @@ fn inv5_bad_threshold_refused_when_set() { let dir = test_dir("inv5-set"); let toml = books_toml(&dir, "25.00", ""); let mut m = Mcp::start(&dir, &toml); - let before = m.journal(); + let before = m.journal_raw(); assert!(!before.is_empty(), "the books keep a journal"); for bad in ["-1", "abc", "-0.01", "", "1,000", "ten"] { m.refuse( @@ -2156,7 +2163,11 @@ fn inv5_bad_threshold_refused_when_set() { "decided_by": "Test Owner"}), ); } - assert_eq!(m.journal(), before, "a refused threshold journals nothing"); + assert_eq!( + m.journal_raw(), + before, + "a refused threshold journals nothing" + ); let rule = m.ok("books.settings", json!({}))["receipt_rule"].clone(); assert!(rule.as_str().unwrap().contains("25.00"), "{rule}"); } diff --git a/crates/ledger-cli/tests/spec_parties.rs b/crates/ledger-cli/tests/spec_parties.rs index 53095287..befb94f1 100644 --- a/crates/ledger-cli/tests/spec_parties.rs +++ b/crates/ledger-cli/tests/spec_parties.rs @@ -107,11 +107,15 @@ impl Mcp { mcp } - /// The journal, without the frames of tool calls (D-88). + /// The journal, without the frames of tool calls (D-88): the events. fn journal(&self) -> Vec { - common::without_call_lines( - &std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(), - ) + common::without_call_lines(&self.journal_raw()) + } + + /// The journal, byte for byte: what a check that a refusal or a + /// preview "journaled nothing" compares, so a stray frame line is seen. + fn journal_raw(&self) -> Vec { + std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default() } /// The journal's line types, in order. @@ -154,7 +158,7 @@ impl Mcp { /// Call a tool; a refusal must leave the journal unchanged, a success /// must match the outputSchema. fn tool(&mut self, name: &str, args: Value) -> Out { - let before = self.journal(); + let before = self.journal_raw(); let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone()); let out = if let Some(err) = resp.get("error") { Out::RpcErr(err.clone()) @@ -184,7 +188,7 @@ impl Mcp { }; if out.refused() { assert!( - self.journal() == before, + self.journal_raw() == before, "refused {name} {args} changed the journal ({out:?})" ); } @@ -211,10 +215,10 @@ impl Mcp { /// `ok`, and the journal must not change (read-only tools). fn read_only(&mut self, name: &str, args: Value) -> Value { - let before = self.journal(); + let before = self.journal_raw(); let v = self.ok(name, args); assert!( - self.journal() == before, + self.journal_raw() == before, "read-only {name} changed the journal" ); v @@ -1227,13 +1231,13 @@ fn require_refuses_until_tagged_or_marked_none() { json!({}), &[("6999", "debit", "5.00"), ("1000", "credit", "5.00")], ); - let before = m.journal(); + let before = m.journal_raw(); let e = m.refuse( "books.post_entry", json!({"entry_id": id, "confirmed": true}), ); assert!(e.contains("party_required"), "{e}"); - assert_eq!(m.journal(), before, "refusal journals nothing"); + assert_eq!(m.journal_raw(), before, "refusal journals nothing"); m.ok( "books.set_entry_party", json!({"entry_id": id, "party": bank.to_string()}), @@ -1611,10 +1615,10 @@ fn under_require_engine_postings_name_their_counterparty() { let sale = json!({"asset_id": sold, "date": "2026-06-30", "proceeds": "500.00", "proceeds_account": "1000", "gain_loss_account": "7100", "confirmed": true}); - let before = m.journal(); + let before = m.journal_raw(); let e = m.refuse("books.dispose_asset", sale.clone()); assert!(e.contains("party_required"), "{e}"); - assert!(m.journal() == before, "refused, nothing journaled"); + assert!(m.journal_raw() == before, "refused, nothing journaled"); let mut with_buyer = sale; with_buyer["buyer"] = json!("Buyer Co"); let d = m.ok("books.dispose_asset", with_buyer); diff --git a/crates/ledger-cli/tests/spec_party_totals.rs b/crates/ledger-cli/tests/spec_party_totals.rs index c6c66970..c27d18a4 100644 --- a/crates/ledger-cli/tests/spec_party_totals.rs +++ b/crates/ledger-cli/tests/spec_party_totals.rs @@ -114,11 +114,15 @@ impl Mcp { mcp } - /// The journal, without the frames of tool calls (D-88). + /// The journal, without the frames of tool calls (D-88): the events. fn journal(&self) -> Vec { - common::without_call_lines( - &std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(), - ) + common::without_call_lines(&self.journal_raw()) + } + + /// The journal, byte for byte: what a check that a refusal or a + /// preview "journaled nothing" compares, so a stray frame line is seen. + fn journal_raw(&self) -> Vec { + std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default() } /// The journal's line types, in order. @@ -161,7 +165,7 @@ impl Mcp { /// Call a tool; a refusal must leave the journal unchanged, a success /// must match the outputSchema. fn tool(&mut self, name: &str, args: Value) -> Out { - let before = self.journal(); + let before = self.journal_raw(); let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone()); let out = if let Some(err) = resp.get("error") { Out::RpcErr(err.clone()) @@ -191,7 +195,7 @@ impl Mcp { }; if out.refused() { assert!( - self.journal() == before, + self.journal_raw() == before, "refused {name} {args} changed the journal ({out:?})" ); } @@ -218,10 +222,10 @@ impl Mcp { /// `ok`, and the journal must not change (read-only tools). fn read_only(&mut self, name: &str, args: Value) -> Value { - let before = self.journal(); + let before = self.journal_raw(); let v = self.ok(name, args); assert!( - self.journal() == before, + self.journal_raw() == before, "read-only {name} changed the journal" ); v @@ -582,12 +586,12 @@ fn defect24_creditor_of_round_trips_and_a_card_fee_is_not_a_payment() { "nothing declared on the way" ); // The same list again changes nothing. - let journal = m.journal(); + let journal = m.journal_raw(); m.ok( "books.update_party", json!({"party": "Harbor Bank", "creditor_of": ["2050"]}), ); - assert!(m.journal() == journal); + assert!(m.journal_raw() == journal); assert_eq!( part(&mut m, fee, "Harbor Bank"), ( diff --git a/crates/ledger-cli/tests/spec_projects.rs b/crates/ledger-cli/tests/spec_projects.rs index ddcd5fed..a0b3f1cf 100644 --- a/crates/ledger-cli/tests/spec_projects.rs +++ b/crates/ledger-cli/tests/spec_projects.rs @@ -113,11 +113,15 @@ impl Mcp { mcp } - /// The journal, without the frames of tool calls (D-88). + /// The journal, without the frames of tool calls (D-88): the events. fn journal(&self) -> Vec { - common::without_call_lines( - &std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(), - ) + common::without_call_lines(&self.journal_raw()) + } + + /// The journal, byte for byte: what a check that a refusal or a + /// preview "journaled nothing" compares, so a stray frame line is seen. + fn journal_raw(&self) -> Vec { + std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default() } /// The journal's line types, in order. @@ -160,7 +164,7 @@ impl Mcp { /// Call a tool; a refusal must leave the journal unchanged, a success /// must match the outputSchema. fn tool(&mut self, name: &str, args: Value) -> Out { - let before = self.journal(); + let before = self.journal_raw(); let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone()); let out = if let Some(err) = resp.get("error") { Out::RpcErr(err.clone()) @@ -190,7 +194,7 @@ impl Mcp { }; if out.refused() { assert!( - self.journal() == before, + self.journal_raw() == before, "refused {name} {args} changed the journal ({out:?})" ); } @@ -217,10 +221,10 @@ impl Mcp { /// `ok`, and the journal must not change (read-only tools). fn read_only(&mut self, name: &str, args: Value) -> Value { - let before = self.journal(); + let before = self.journal_raw(); let v = self.ok(name, args); assert!( - self.journal() == before, + self.journal_raw() == before, "read-only {name} changed the journal" ); v @@ -516,7 +520,7 @@ fn update_project_with_nothing_new_journals_nothing() { "books.add_project", json!({"name": "Harbor", "kind": "client"}), ); - let before = m.journal(); + let before = m.journal_raw(); m.ok( "books.update_project", json!({"project": "Harbor", "kind": "client"}), @@ -525,7 +529,7 @@ fn update_project_with_nothing_new_journals_nothing() { "books.update_project", json!({"project": "harbor", "name": "Harbor"}), ); - assert_eq!(m.journal(), before); + assert_eq!(m.journal_raw(), before); } // ------------------------------------------------- figures @@ -934,7 +938,7 @@ fn show_project_sends_its_target() { #[test] fn project_writes_wait_for_the_format_upgrade() { let mut m = books_in("upgrade", true); - let head = m.journal(); + let head = m.journal_raw(); for (tool, args) in [ ("books.add_project", json!({"name": "Harbor"})), ( @@ -959,7 +963,7 @@ fn project_writes_wait_for_the_format_upgrade() { assert!(why.starts_with("format_upgrade_pending:"), "{tool}: {why}"); assert!(why.contains("nothing can be written"), "{tool}: {why}"); } - assert_eq!(m.journal(), head, "nothing journaled"); + assert_eq!(m.journal_raw(), head, "nothing journaled"); } #[test] @@ -1480,7 +1484,7 @@ fn books_without_the_feature_refuse_a_tagged_document() { ); let cedar = m.ok("books.add_customer", json!({"name": "Cedar"}))["id"].clone(); let v = m.ok("books.add_vendor", json!({"name": "Dana"}))["id"].clone(); - let head = m.journal(); + let head = m.journal_raw(); for (tool, key, party) in [ ("books.create_invoice", "customer", &cedar), ("books.create_bill", "vendor", &v), @@ -1496,7 +1500,7 @@ fn books_without_the_feature_refuse_a_tagged_document() { "{tool}: {why}" ); } - assert_eq!(m.journal(), head, "nothing journaled"); + assert_eq!(m.journal_raw(), head, "nothing journaled"); m.ok( "books.create_invoice", json!({"customer": (cedar).to_string(), "date": "2026-03-02", "due_date": "2026-04-01", "lines": [ diff --git a/crates/ledger-cli/tests/spec_vault.rs b/crates/ledger-cli/tests/spec_vault.rs index 734af91d..0f2f8d7d 100644 --- a/crates/ledger-cli/tests/spec_vault.rs +++ b/crates/ledger-cli/tests/spec_vault.rs @@ -115,11 +115,15 @@ impl Mcp { mcp } - /// The journal, without the frames of tool calls (D-88). + /// The journal, without the frames of tool calls (D-88): the events. fn journal(&self) -> Vec { - common::without_call_lines( - &std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(), - ) + common::without_call_lines(&self.journal_raw()) + } + + /// The journal, byte for byte: what a check that a refusal or a + /// preview "journaled nothing" compares, so a stray frame line is seen. + fn journal_raw(&self) -> Vec { + std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default() } /// The journal's line types, in order. @@ -164,7 +168,7 @@ impl Mcp { /// Call a tool; a refusal must leave the journal unchanged, a success /// must match the outputSchema. fn tool(&mut self, name: &str, args: Value) -> Out { - let before = self.journal(); + let before = self.journal_raw(); let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone()); let out = if let Some(err) = resp.get("error") { Out::RpcErr(err.clone()) @@ -194,7 +198,7 @@ impl Mcp { }; if out.refused() { assert!( - self.journal() == before, + self.journal_raw() == before, "refused {name} {args} changed the journal ({out:?})" ); } @@ -221,10 +225,10 @@ impl Mcp { /// `ok`, and the journal must not change (read-only tools). fn read_only(&mut self, name: &str, args: Value) -> Value { - let before = self.journal(); + let before = self.journal_raw(); let v = self.ok(name, args); assert!( - self.journal() == before, + self.journal_raw() == before, "read-only {name} changed the journal" ); v @@ -1024,7 +1028,7 @@ fn purge_deletes_the_vault_records_and_journals_why() { json!({"party": "Nobody", "reason": "x", "confirmed": true}), ); // A preview changes nothing. - let journal = m.journal(); + let journal = m.journal_raw(); let p = m.ok( "books.purge_tin", json!({"party": "Acme Design", "reason": "retention over"}), @@ -1033,7 +1037,7 @@ fn purge_deletes_the_vault_records_and_journals_why() { assert_eq!(p["tin_in_vault"], true); assert_eq!(p["w9_file_in_vault"], true); assert_eq!(p["tin_last4"], "2846"); - assert!(m.journal() == journal); + assert!(m.journal_raw() == journal); assert!(m.vault().join(format!("tin-{acme}.bin")).exists()); // Without the key, confirmed: gone, and journaled. std::fs::remove_file(m.key()).unwrap(); @@ -2100,7 +2104,7 @@ fn idempotent_tools_change_nothing_when_repeated() { m.ok(name, args.clone()); let (journal, vault) = (m.journal(), vault_bytes(&m)); m.ok(name, args.clone()); - let changed = m.journal() != journal || vault_bytes(&m) != vault; + let changed = m.journal_raw() != journal || vault_bytes(&m) != vault; *repeats_change.entry(name).or_default() |= changed; } let wrong: Vec = repeats_change diff --git a/crates/ledger-mcp/src/calls.rs b/crates/ledger-mcp/src/calls.rs index c4952c47..ca8ef394 100644 --- a/crates/ledger-mcp/src/calls.rs +++ b/crates/ledger-mcp/src/calls.rs @@ -6,7 +6,7 @@ //! GOAL: a write whose answer is lost and which is then retried happens //! once; a call half done is never left looking done; a failed //! write is on the record. -//! SOURCE: WB-format-8, WB-format-9, WB-format-10, WB-format-11; +//! SOURCE: WB-format-8, WB-format-9, WB-format-10, WB-format-11, WB-format-12; //! plan/p15-app-and-relay.md 2a. //! INVARIANTS: //! 1. Every tool that can change anything (no readOnlyHint, but for @@ -19,16 +19,30 @@ //! 2. A write call runs alone among writes: they take turns, so a //! call's lines are one run in the journal, and a repeat that //! arrives while its original still runs waits for it, then gets its -//! answer. +//! answer. Nothing else touches the books while a call that has +//! written a line is open: a read that arrives between the tool's +//! return and its closing line waits for the close +//! (`BooksServer::lock`), so no read ever shows what a call did +//! before the call committed. A call that has written no line has +//! nothing to show, and leaves reads free (a backup can take long). //! 3. A repeat of a (token, key) whose call committed, with the same //! tool and arguments, returns that call's answer as it was given and //! writes nothing; with other arguments (or another tool) it is -//! refused as a misuse of the key. The access log records a repeat -//! as `repeat`. -//! 4. A call that answered ok commits with a closing line holding its -//! answer; one that answered with an error, was stopped by a close or -//! failed by any other means rolls back, is journaled as `failed` -//! when it had written lines, and leaves its key unused. +//! refused as a misuse of the key. "The same arguments" is a keyed +//! digest of them, tax ids included (ledger_store::calls::args_mac), +//! so two requests that differ only in a tax id are two requests. A +//! call whose answer was too long to keep is repeated in words: it +//! was done, its lines are named, nothing is done again. The access +//! log records a repeat as `repeat`. +//! 4. A call that answered ok and wrote lines commits with a closing +//! line holding its answer; one that answered with an error, was +//! stopped by a close or failed by any other means rolls back, is +//! journaled as `failed` when it had written lines, and leaves its +//! key unused. A call that wrote no line leaves no line at all: its +//! key and answer are kept in memory for the life of the server. +//! Nothing a tool writes outside the journal (the tax-id vault) +//! is final before the call commits: it is staged, and settled +//! after the closing line (`vault_stage`). //! 5. Books that haven't declared call_transactions take no write: every //! write call is refused with the upgrade remedy, before it runs. //! Reads are never refused for it. @@ -180,11 +194,136 @@ fn refusal(text: String) -> CallToolResponse { ])) } +thread_local! { + /// The tag of the call open on this thread (`ledger_store::calls:: + /// call_tag`): what its staged vault records are named by. + static CALL_TAG: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + /// Whether this thread runs the call that is open: the only request + /// that may touch the books until its closing line (INVARIANT 2). + static OWNS_CALL: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Whether the request on this thread is the one whose call is open. +pub(crate) fn owns_call() -> bool { + OWNS_CALL.with(std::cell::Cell::get) +} + +/// The tag of the call open on this thread, if one is: a tool that +/// writes outside the journal (the tax-id vault) stages its write under +/// it, and the write is made final or dropped when the call closes +/// (INVARIANT 4). None outside a call: the write is final at once. +pub(crate) fn vault_tag() -> Option { + CALL_TAG.with(|t| t.borrow().clone()) +} + +/// Store a party's TIN for the call open on this thread: staged until the +/// call commits (INVARIANT 4); final at once outside a call. +pub(crate) fn put_tin( + vault: &ledger_vault::Vault, + party: u64, + tin: &ledger_vault::Tin, +) -> Result { + match vault_tag() { + Some(tag) => vault.stage_tin(party, tin, &tag), + None => vault.put_tin(party, tin), + } +} + +/// Store a party's W-9 file for the call open on this thread, as +/// [`put_tin`]. +pub(crate) fn put_w9( + vault: &ledger_vault::Vault, + party: u64, + file: &ledger_vault::W9File, +) -> Result { + match vault_tag() { + Some(tag) => vault.stage_w9(party, file, &tag), + None => vault.put_w9(party, file), + } +} + +/// Purge what the vault in `dir` holds for a party for the call open on +/// this thread: set aside until the call commits, put back if it fails +/// (INVARIANT 4); deleted at once outside a call. +pub(crate) fn purge_records( + dir: &std::path::Path, + party: u64, +) -> Result { + match vault_tag() { + Some(tag) => ledger_vault::stage_purge(dir, party, &tag), + None => ledger_vault::purge_records(dir, party), + } +} + +/// Apply the outcome of the call `tag` to the vault records it staged +/// (`ledger_vault::settle`). +fn settle_vault(store: &ledger_store::Store, tag: &str, committed: bool) -> Result<(), String> { + let dir = store.data_dir().join(ledger_store::root::VAULT_DIR); + ledger_vault::settle(&dir, tag, committed) + .map(|_| ()) + .map_err(|e| format!("the TIN vault's staged records could not be settled: {e}")) +} + +/// At start: the staged vault records a crash left, each settled by what +/// the journal says of its call (INVARIANT 4): final if the call +/// committed, dropped (or a purge undone) if not. Said on stderr, never +/// failing the open. +pub(crate) fn recover_vault(store: &ledger_store::Store) { + let dir = store.data_dir().join(ledger_store::root::VAULT_DIR); + let Ok(tags) = ledger_vault::pending_tags(&dir) else { + return; + }; + for tag in tags { + let committed = store.call_committed(&tag); + match ledger_vault::settle(&dir, &tag, committed) { + Ok(done) => eprintln!( + "wanderbooks: a call left tax-id vault records unsettled; its call {} (made final {}, dropped {}, purged {}, put back {})", + if committed { + "committed" + } else { + "did not commit" + }, + done.promoted, + done.dropped, + done.purged, + done.restored + ), + Err(e) => { + eprintln!("wanderbooks: tax-id vault records of a call could not be settled: {e}") + } + } + } +} + +/// What a repeat of a call whose answer was too long to keep is told. +fn done_in_words(tool: &str, replay: &ledger_store::calls::Replay) -> String { + use ledger_store::calls::Replay; + match replay { + Replay::Answer(_) => String::new(), + Replay::Summary { + first_seq, + last_seq, + closed_seq, + answer_sha256, + answer_bytes, + } => format!( + "this request_key was already used for this very call: {tool} was done, and nothing more was changed. Its answer ({answer_bytes} bytes, SHA-256 {answer_sha256}) was too long for the books to keep, so it can't be given again. What it did is journal lines {first_seq} to {last_seq}, closed by line {closed_seq}: books.journal_history with after_seq {} lists them", + first_seq.saturating_sub(1) + ), + } +} + /// Open a call (INVARIANTS 3, 5): refuse it if the books take no calls; /// answer it from the books if its key already committed; otherwise open /// it. Takes the store's lock for the moment it needs; the caller holds -/// the write turn (`SharedStore::write_turn`). -pub(crate) fn begin(server: &BooksServer, id: CallId) -> Result { +/// the write turn (`SharedStore::write_turn`). `arguments` are the call's, +/// the request key already taken out: their keyed digest is what a repeat +/// is compared by. +pub(crate) fn begin( + server: &BooksServer, + mut id: CallId, + arguments: Option<&Map>, +) -> Result { let mut store = server.lock()?; if let Err(e) = store.ensure_takes_calls() { return Ok(Begun::Answer( @@ -192,21 +331,34 @@ pub(crate) fn begin(server: &BooksServer, id: CallId) -> Result { UPGRADE_PENDING, )); } - if let Some(kept) = store.recorded_call(&id.token, &id.key) { + let args = Value::Object(arguments.cloned().unwrap_or_default()); + id.args = store.args_mac(&args).map_err(|e| e.to_string())?; + if let Some(kept) = store + .recorded_call(&id.token, &id.key) + .map_err(|e| e.to_string())? + { if kept.tool == id.tool && kept.args == id.args { - return match serde_json::from_str::(&kept.answer) { - Ok(answer) => Ok(Begun::Answer( - Box::new(CallToolResponse::Complete(answer)), + return match kept.replay { + ledger_store::calls::Replay::Answer(text) => { + match serde_json::from_str::(&text) { + Ok(answer) => Ok(Begun::Answer( + Box::new(CallToolResponse::Complete(answer)), + REPEAT, + )), + Err(e) => Err(format!( + "the answer kept for this request_key can't be read back: {e}" + )), + } + } + summary => Ok(Begun::Answer( + Box::new(refusal(done_in_words(&id.tool, &summary))), REPEAT, )), - Err(e) => Err(format!( - "the answer kept for this request_key can't be read back: {e}" - )), }; } return Ok(Begun::Answer( Box::new(refusal(format!( - "this request_key was already used for {} with other arguments, so the call was not run and nothing was changed. A key names one action: send this one again with a key of its own", + "this request_key was already used for {} with other arguments (or the books' record of the first can't be matched), so the call was not run and nothing was changed. A key names one action: send this one again with a key of its own", if kept.tool == id.tool { "the same tool".to_string() } else { @@ -216,7 +368,10 @@ pub(crate) fn begin(server: &BooksServer, id: CallId) -> Result { KEY_REUSED, )); } + let tag = ledger_store::calls::call_tag(&id.token, &id.key); store.begin_call(id).map_err(|e| e.to_string())?; + OWNS_CALL.with(|o| o.set(true)); + CALL_TAG.with(|t| *t.borrow_mut() = Some(tag)); Ok(Begun::Run) } @@ -241,16 +396,27 @@ pub(crate) fn answered_ok( && matches!(out, Ok(CallToolResponse::Complete(r)) if r.is_error != Some(true)) } +/// Why a call could not be closed. +pub(crate) enum CloseError { + /// Its closing line could not be written: none of it counts. + NotClosed(String), + /// Its closing line is on disk, so it counts, but the books' working + /// copy could not be brought up to it. + Committed(String), +} + /// Close the open call with how it came out (INVARIANTS 4, 6). An error -/// here means the call could not be closed: the books server stops, and -/// the caller is told so. +/// here means the books server stops, and the caller is told which of the +/// two it is. pub(crate) fn close( server: &BooksServer, out: &Result, ok: bool, -) -> Result<(), String> { +) -> Result<(), CloseError> { use ledger_core::parties::{has_full_tin, redact_full_tins}; - let mut store = server.lock()?; + // The call ends on this thread whatever comes of its closing line. + let _ends = EndsCall(server); + let mut store = server.lock().map_err(CloseError::NotClosed)?; if !store.in_call() { return Ok(()); } @@ -263,12 +429,14 @@ pub(crate) fn close( }; let ended = if ok { let Ok(CallToolResponse::Complete(r)) = out else { - return Err("a call that committed has no answer".into()); + return Err(CloseError::NotClosed( + "a call that committed has no answer".into(), + )); }; // Kept as given: no tool's answer holds a full TIN (the three that // can are no transaction), and a digest of the books' head can hold // nine digits in a row, which masking would spoil on a repeat. - let text = serde_json::to_string(r).map_err(|e| e.to_string())?; + let text = serde_json::to_string(r).map_err(|e| CloseError::NotClosed(e.to_string()))?; store.close_call(CallEnd::Done(&text)) } else { let why = match out { @@ -283,8 +451,43 @@ pub(crate) fn close( }; store.close_call(CallEnd::Failed(&masked(why))) }; - ended.map_err(|e| e.to_string()) + // What the call staged outside the journal follows how it ended: final + // if it committed (it answered ok, or its closing line is on disk), + // dropped if it failed. A call whose closing line could not be written + // is settled at the next start, by what the journal then says. + let tag = CALL_TAG.with(|t| t.borrow_mut().take()); + let committed = match &ended { + Ok(()) => Some(ok), + Err(ledger_store::StoreError::CallCommitted(_)) => Some(true), + Err(_) => None, + }; + let settled = match (tag, committed) { + (Some(tag), Some(committed)) => settle_vault(&store, &tag, committed), + _ => Ok(()), + }; + match (ended, settled) { + (Ok(()), Ok(())) => Ok(()), + (Ok(()), Err(why)) => Err(CloseError::Committed(why)), + (Err(ledger_store::StoreError::CallCommitted(why)), _) => Err(CloseError::Committed(why)), + (Err(other), _) => Err(CloseError::NotClosed(other.to_string())), + } } +/// Ends the open call's claim on this thread, and wakes every request +/// that waited for it (`BooksServer::lock`). +struct EndsCall<'a>(&'a BooksServer); + +impl Drop for EndsCall<'_> { + fn drop(&mut self) { + OWNS_CALL.with(|o| o.set(false)); + CALL_TAG.with(|t| *t.borrow_mut() = None); + self.0.store.call_ended(); + } +} + +/// What a call is told when its closing line is saved but the books' +/// working copy could not be brought up to it. +pub(crate) const COMMITTED_NOT_APPLIED: &str = "this call was completed and counts: its closing line is saved in the books. The books server could not bring its working copy up to date, so it stopped taking requests to protect the books, and rebuilds the copy from the journal when it starts again. Ask the human to restart it. Do not do the work again: sending this call again with the same request_key answers what it answered and changes nothing"; + /// What a call is told when its closing line could not be written. pub(crate) const NOT_CLOSED: &str = "this call could not be completed: its closing line could not be written, so none of it counts, and the books server stopped taking requests to protect the books. Ask the human to restart it, then send the call again with the same request_key"; diff --git a/crates/ledger-mcp/src/server.rs b/crates/ledger-mcp/src/server.rs index d31671d7..6a0e047d 100644 --- a/crates/ledger-mcp/src/server.rs +++ b/crates/ledger-mcp/src/server.rs @@ -227,6 +227,9 @@ pub struct SharedStore { /// for the owner's format upgrade, so a call's lines are one run in /// the journal. writes: tokio::sync::Mutex<()>, + /// Woken when a call's closing line is done (calls.rs INVARIANT 2): + /// the requests that waited for the open call to close. + call_over: (std::sync::Mutex<()>, std::sync::Condvar), /// The books' base currency, fixed at their creation: read without /// the lock (the connect text names it). currency: Currency, @@ -252,6 +255,24 @@ impl SharedStore { self.writes.blocking_lock() } + /// Wake every request that waits for the open call to close. + pub(crate) fn call_ended(&self) { + self.call_over.1.notify_all(); + } + + /// Wait (a moment, then look again) for the open call to close. + fn wait_for_call(&self) { + let held = self + .call_over + .0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let _ = self + .call_over + .1 + .wait_timeout(held, std::time::Duration::from_millis(25)); + } + /// Run `f` on the store under its lock, writing: the owner's format /// upgrade, after its backup (backup.rs). Blocking. Refused once the /// books are closing or the server stopped (INVARIANTS 2, 3), counted @@ -324,6 +345,9 @@ impl SharedStore { /// Share an open store. pub fn new(store: Store) -> Arc { + // Tax-id vault records a crash left staged are settled by what the + // journal says of their call (calls.rs INVARIANT 4). + calls::recover_vault(&store); Arc::new(Self { currency: store.base_currency(), store: tokio::sync::Mutex::new(Some(store)), @@ -333,6 +357,7 @@ impl SharedStore { running: std::sync::atomic::AtomicUsize::new(0), ended: tokio::sync::Notify::new(), writes: tokio::sync::Mutex::new(()), + call_over: (std::sync::Mutex::new(()), std::sync::Condvar::new()), }) } @@ -1029,12 +1054,28 @@ impl BooksServer { if self.store.stopped() { return Err(STOPPED.to_string()); } - let guard = self.store.store.blocking_lock(); - // A request that panicked while this one waited stopped it; books - // let go hold no store. - if self.store.stopped() { - return Err(STOPPED.to_string()); - } + // Nothing but the request whose call is open touches the books + // until the call's closing line is written (calls.rs INVARIANT 2): + // a read never sees what a call did before the call committed. + let guard = loop { + let guard = self.store.store.blocking_lock(); + // A request that panicked while this one waited stopped it; + // books let go hold no store. + if self.store.stopped() { + return Err(STOPPED.to_string()); + } + // Only a call that has written a line has effects to hide: one + // that has written none (a backup, an upload begun) leaves + // reads free. + let open = guard + .as_ref() + .is_some_and(|s| s.in_call() && s.call_has_lines()); + if !open || calls::owns_call() { + break guard; + } + drop(guard); + self.store.wait_for_call(); + }; let Some(store) = guard.as_ref() else { return Err(STOPPED.to_string()); }; @@ -1946,12 +1987,14 @@ impl ServerHandler for BooksServer { .unwrap_or_default(), tool: tool_name.clone(), key: calls::key_text(k), - args: digest.clone().unwrap_or_default(), + // Filled by `calls::begin`: the keyed digest. + args: String::new(), }); let _turn = call_id.as_ref().map(|_| server.store.write_turn()); let early = match &call_id { None => None, - Some(id) => match calls::begin(&server, id.clone()) { + Some(id) => match calls::begin(&server, id.clone(), request.arguments.as_ref()) + { Ok(calls::Begun::Run) => None, Ok(calls::Begun::Answer(answer, code)) => Some((answer, code)), Err(why) => Some((Box::new(tool_error(why)), access::STOPPED)), @@ -2008,10 +2051,20 @@ impl ServerHandler for BooksServer { let mut wrote = wrote; if call_id.is_some() { let ok = calls::answered_ok(&out, stopped); - if let Err(why) = calls::close(&server, &out, ok) { - eprintln!("wanderbooks: a call could not be closed: {why}"); - server.store.stop(); - out = Ok(tool_error(calls::NOT_CLOSED.to_string())); + match calls::close(&server, &out, ok) { + Ok(()) => {} + Err(calls::CloseError::NotClosed(why)) => { + eprintln!("wanderbooks: a call could not be closed: {why}"); + server.store.stop(); + out = Ok(tool_error(calls::NOT_CLOSED.to_string())); + } + Err(calls::CloseError::Committed(why)) => { + eprintln!( + "wanderbooks: a call committed, but the books' working copy could not follow: {why}" + ); + server.store.stop(); + out = Ok(tool_error(calls::COMMITTED_NOT_APPLIED.to_string())); + } } // The closing line is this call's last write. wrote = WROTE diff --git a/crates/ledger-mcp/src/tools/parties.rs b/crates/ledger-mcp/src/tools/parties.rs index 711083a6..bb5f03a1 100644 --- a/crates/ledger-mcp/src/tools/parties.rs +++ b/crates/ledger-mcp/src/tools/parties.rs @@ -921,11 +921,15 @@ impl BooksServer { self.wrote_tins(&store, &w.bytes)?; } let tin_hash = match &tin { - Some(t) => Some(vault.put_tin(id, t).map_err(|e| e.to_string())?), + Some(t) => { + Some(super::calls::put_tin(&vault, id, t).map_err(|e| e.to_string())?) + } None => None, }; let w9_hash = match &w9_file { - Some(w) => Some(vault.put_w9(id, w).map_err(|e| e.to_string())?), + Some(w) => { + Some(super::calls::put_w9(&vault, id, w).map_err(|e| e.to_string())?) + } None => None, }; // The W-9 is in the vault: its upload is used up. @@ -1047,7 +1051,7 @@ impl BooksServer { .map_err(|e| e.to_string())?; } let vault = self.open_vault(&store, true)?; - let hash = vault.put_tin(id, &tin).map_err(|e| e.to_string())?; + let hash = super::calls::put_tin(&vault, id, &tin).map_err(|e| e.to_string())?; store .set_party_tin( id, @@ -1238,7 +1242,7 @@ impl BooksServer { if !p.confirmed.unwrap_or(false) { return Ok(Json(out)); } - ledger_vault::purge_records(&vault_dir, id).map_err(|e| e.to_string())?; + super::calls::purge_records(&vault_dir, id).map_err(|e| e.to_string())?; if let Some(f) = new_facts { store.set_party_w9(id, Some(f)).map_err(|e| e.to_string())?; out.journaled = true; diff --git a/crates/ledger-store/src/calls.rs b/crates/ledger-store/src/calls.rs index 97c20115..207f45f2 100644 --- a/crates/ledger-store/src/calls.rs +++ b/crates/ledger-store/src/calls.rs @@ -612,6 +612,19 @@ pub fn committed(lines: &[JournalLine]) -> Result, StoreError> .collect()) } +/// A call's tag: 16 lowercase hex digits naming it in file names outside +/// the journal (a staged vault record), derived from its token and key, +/// so a later open can ask the journal whether that call committed +/// ([`Store::call_committed`]). +pub fn call_tag(token: &str, key: &str) -> String { + let mut h = Sha256::new(); + h.update(b"wanderbooks-call\0"); + h.update(token.as_bytes()); + h.update(b"\0"); + h.update(key.as_bytes()); + hex::encode(&h.finalize()[..8]) +} + /// HMAC-SHA256 (RFC 2104) of `msg` under `key`, hex. pub(crate) fn hmac_sha256_hex(key: &[u8], msg: &[u8]) -> String { const BLOCK: usize = 64; @@ -773,6 +786,15 @@ impl Store { })) } + /// Whether the call with this tag ([`call_tag`]) committed with lines + /// on the journal: its closing line says `ok`. + pub fn call_committed(&self, tag: &str) -> bool { + self.keys + .by + .keys() + .any(|(token, key)| call_tag(token, key) == tag) + } + /// The table's sizes: calls with lines, and the session's calls that /// wrote none with the bytes of their answers. pub fn call_table(&self) -> (usize, (usize, usize)) { @@ -834,10 +856,14 @@ impl Store { return Ok(()); } let line = self.journal.append(BEGUN, begun_payload(&call.id))?; - apply_line_to_sqlite(&self.conn, &line)?; + // The frame is open from the moment its line is on disk, whatever + // the projection says next: a call that fails here must close it + // (`failed`), or the next call would begin inside it (a corrupt + // journal). if let Some(call) = &mut self.call { call.begun = Some(line.seq); } + apply_line_to_sqlite(&self.conn, &line)?; Ok(()) } diff --git a/crates/ledger-store/tests/calls.rs b/crates/ledger-store/tests/calls.rs index a56fef3c..ee10bc5a 100644 --- a/crates/ledger-store/tests/calls.rs +++ b/crates/ledger-store/tests/calls.rs @@ -596,3 +596,109 @@ fn a_call_that_rebuilds_the_projection_still_commits() { let s = Store::open(tmp.path()).unwrap(); s.verify().unwrap(); } + +/// The closing line is on disk but the projection can't be brought up to +/// it: the call committed, and is not reported as if it hadn't. The store +/// says so in words, takes no more writes, and the next open rebuilds the +/// projection from the journal with the call's effects in it (SCENARIO 4). +#[test] +fn a_closing_line_on_disk_but_sqlite_failing_is_a_call_that_counts() { + let tmp = tempfile::tempdir().unwrap(); + let mut s = books(tmp.path()); + // From the closing line on, the projection refuses every write: the + // call writes a begin line, a draft and two lines (four), then closes. + let closing_seq = lines_of(tmp.path()).last().unwrap().seq + 5; + let db_file = tmp.path().join(s.database_file()); + let db = rusqlite::Connection::open(&db_file).unwrap(); + db.execute_batch(&format!( + "CREATE TRIGGER wb_test_refuses BEFORE UPDATE ON meta \ + WHEN NEW.key = 'last_applied_seq' AND CAST(NEW.value AS INTEGER) >= {closing_seq} \ + BEGIN SELECT RAISE(ABORT, 'a test refuses this write'); END;" + )) + .unwrap(); + drop(db); + s.begin_call(id("key-commit-0001")).unwrap(); + draft(&mut s, "Counts"); + assert_eq!(lines_of(tmp.path()).last().unwrap().seq + 1, closing_seq); + let err = s + .close_call(CallEnd::Done(r#"{"entry_id":1}"#)) + .unwrap_err(); + let StoreError::CallCommitted(why) = &err else { + panic!("expected CallCommitted, got {err:?}"); + }; + assert!(why.contains("counts"), "{why}"); + assert!(!why.contains("none of it counts"), "{why}"); + // The record says ok, and the key is kept: a repeat is the first answer. + let last = lines_of(tmp.path()).into_iter().last().unwrap(); + assert_eq!(closed_of(&last).unwrap().outcome, CallOutcome::Ok); + assert_eq!( + answer_of(&kept(&s, "token-1", "key-commit-0001").unwrap()), + r#"{"entry_id":1}"# + ); + // No more writes until the books are opened again. + assert!(matches!( + s.begin_call(id("key-commit-0002")), + Err(StoreError::CallRefused(_)) + )); + drop(s); + rusqlite::Connection::open(&db_file) + .unwrap() + .execute_batch("DROP TRIGGER wb_test_refuses") + .unwrap(); + let s = Store::open(tmp.path()).unwrap(); + assert_eq!( + s.ledger().get_entry(1).map(|e| e.description()), + Some("Counts") + ); + assert_eq!( + answer_of(&kept(&s, "token-1", "key-commit-0001").unwrap()), + r#"{"entry_id":1}"# + ); + s.verify().unwrap(); +} + +/// The projection refuses a call's begin line itself: the line is on disk, +/// so the frame is open and the call must close it (`failed`). Left open, +/// the next call would begin inside it and the journal would be corrupt. +#[test] +fn a_call_whose_begin_line_the_projection_refuses_still_closes_its_frame() { + let tmp = tempfile::tempdir().unwrap(); + let mut s = books(tmp.path()); + let begin_seq = lines_of(tmp.path()).last().unwrap().seq + 1; + let db_file = tmp.path().join(s.database_file()); + let db = rusqlite::Connection::open(&db_file).unwrap(); + db.execute_batch(&format!( + "CREATE TRIGGER wb_test_refuses BEFORE UPDATE ON meta \ + WHEN NEW.key = 'last_applied_seq' AND CAST(NEW.value AS INTEGER) = {begin_seq} \ + BEGIN SELECT RAISE(ABORT, 'a test refuses this write'); END;" + )) + .unwrap(); + drop(db); + s.begin_call(id("key-begin-0001")).unwrap(); + assert!(s.create_entry(d(2026, 1, 5), "Never").is_err()); + s.close_call(CallEnd::Failed("the projection refused it")) + .ok(); + drop(s); + rusqlite::Connection::open(&db_file) + .unwrap() + .execute_batch("DROP TRIGGER wb_test_refuses") + .unwrap(); + let all = lines_of(tmp.path()); + assert_eq!( + all.last().unwrap().line_type, + "call.closed", + "{:?}", + types_of(tmp.path()) + ); + assert_eq!( + closed_of(all.last().unwrap()).unwrap().outcome, + CallOutcome::Failed + ); + // The books open, and the next call begins on a closed frame. + let mut s = Store::open(tmp.path()).unwrap(); + s.begin_call(id("key-begin-0002")).unwrap(); + draft(&mut s, "Fine"); + s.close_call(CallEnd::Done("{}")).unwrap(); + drop(s); + Store::open(tmp.path()).unwrap().verify().unwrap(); +} diff --git a/crates/ledger-vault/src/lib.rs b/crates/ledger-vault/src/lib.rs index 5c69955d..4a210592 100644 --- a/crates/ledger-vault/src/lib.rs +++ b/crates/ledger-vault/src/lib.rs @@ -25,6 +25,15 @@ //! 5. `record_hash` is the SHA-256 of a record's bytes on disk, so the //! journal can prove a record existed without holding it. //! 6. Purging deletes the record's file; nothing else keeps a copy. +//! 7. A write made for a call that may yet fail is staged, never final: +//! `stage_tin`, `stage_w9` and `stage_purge` write a file of another +//! name (`.staged-TAG`, `.purging-TAG`) that no reader opens, and +//! `settle` makes the call's staged files final, or drops them, +//! once it is known whether the call committed. A record is +//! therefore never replaced, and never destroyed, by a call that did +//! not commit; a crash between the commit and the settle is finished +//! by the next `settle`, which the caller asks of every tag left in +//! `pending_tags`. //! SCENARIOS: //! 1. IF the key file is missing: `open` creates one (mode 0600) only when //! asked to (`create_key`), else the vault is locked (Error::NoKey). @@ -268,6 +277,16 @@ impl Vault { } fn seal(&self, party: u64, kind: Kind, plain: &[u8]) -> Result { + self.seal_to(&self.path(party, kind), party, kind, plain) + } + + fn seal_to( + &self, + target: &Path, + party: u64, + kind: Kind, + plain: &[u8], + ) -> Result { let mut nonce = [0u8; NONCE_LEN]; getrandom::getrandom(&mut nonce).map_err(|e| Error::Io(std::io::Error::other(e)))?; let aad = Self::aad(party, kind); @@ -286,7 +305,7 @@ impl Vault { out.extend_from_slice(&nonce); out.extend_from_slice(&ct); std::fs::create_dir_all(&self.dir)?; - write_private(&self.path(party, kind), &out)?; + write_private(target, &out)?; Ok(hex::encode(Sha256::digest(&out))) } @@ -323,6 +342,30 @@ impl Vault { self.seal(party, Kind::Tin, &plain) } + /// [`Vault::put_tin`] staged for the call `tag` (INVARIANT 7): the + /// record is written, and its hash returned, but under a name no + /// reader opens until [`settle`] makes it final. + pub fn stage_tin(&self, party: u64, tin: &Tin, tag: &str) -> Result { + let plain = Zeroizing::new(serde_json::to_vec(tin).expect("serializes")); + self.seal_to( + &staged_path(&self.dir, party, Kind::Tin, tag)?, + party, + Kind::Tin, + &plain, + ) + } + + /// [`Vault::put_w9`] staged for the call `tag` (INVARIANT 7). + pub fn stage_w9(&self, party: u64, file: &W9File, tag: &str) -> Result { + let plain = Zeroizing::new(serde_json::to_vec(file).expect("serializes")); + self.seal_to( + &staged_path(&self.dir, party, Kind::W9, tag)?, + party, + Kind::W9, + &plain, + ) + } + /// A party's TIN, if the vault holds one. pub fn tin(&self, party: u64) -> Result, Error> { match self.open_record(party, Kind::Tin)? { @@ -369,6 +412,125 @@ fn record_path(dir: &Path, party: u64, kind: Kind) -> PathBuf { dir.join(format!("{}-{party}.bin", kind.name())) } +/// A call's tag: 16 lowercase hex digits (the name of the call in file +/// names, never a path). +fn checked_tag(tag: &str) -> Result<&str, Error> { + if tag.len() == 16 && tag.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) { + Ok(tag) + } else { + Err(Error::Io(std::io::Error::other("not a call tag"))) + } +} + +fn staged_path(dir: &Path, party: u64, kind: Kind, tag: &str) -> Result { + Ok(dir.join(format!( + "{}-{party}.staged-{}", + kind.name(), + checked_tag(tag)? + ))) +} + +fn purging_path(dir: &Path, party: u64, kind: Kind, tag: &str) -> Result { + Ok(dir.join(format!( + "{}-{party}.purging-{}", + kind.name(), + checked_tag(tag)? + ))) +} + +/// Stage the purge of what the vault in `dir` holds for a party, for the +/// call `tag` (INVARIANT 7): each record is set aside under a name no +/// reader opens, and is deleted only when [`settle`] says the call +/// committed (and put back when it didn't). Needs no key. Returns whether +/// anything was there. +pub fn stage_purge(dir: &Path, party: u64, tag: &str) -> Result { + let mut any = false; + for kind in [Kind::Tin, Kind::W9] { + let aside = purging_path(dir, party, kind, tag)?; + match std::fs::rename(record_path(dir, party, kind), aside) { + Ok(()) => any = true, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(Error::Io(e)), + } + } + Ok(any) +} + +/// What a call's staged files came to. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Settled { + /// Staged records made final. + pub promoted: usize, + /// Staged records dropped (the call did not commit). + pub dropped: usize, + /// Purged records deleted (the call committed). + pub purged: usize, + /// Records put back (the call that set them aside did not commit). + pub restored: usize, +} + +/// The tags of every call that left a staged or set-aside file in the +/// vault in `dir` (INVARIANT 7): the calls whose outcome `settle` is +/// still to apply, after a crash. +pub fn pending_tags(dir: &Path) -> Result, Error> { + let mut tags = std::collections::BTreeSet::new(); + let entries = match std::fs::read_dir(dir) { + Ok(e) => e, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(e) => return Err(Error::Io(e)), + }; + for entry in entries { + let name = entry?.file_name().to_string_lossy().into_owned(); + for marker in [".staged-", ".purging-"] { + if let Some((_, tag)) = name.split_once(marker) + && checked_tag(tag).is_ok() + { + tags.insert(tag.to_string()); + } + } + } + Ok(tags.into_iter().collect()) +} + +/// Apply the outcome of the call `tag` to its staged files (INVARIANT 7): +/// if it `committed`, staged records become the party's records and +/// set-aside ones are deleted; if not, staged ones are deleted and +/// set-aside ones are put back. Safe to repeat; needs no key. +pub fn settle(dir: &Path, tag: &str, committed: bool) -> Result { + checked_tag(tag)?; + let mut done = Settled::default(); + let entries = match std::fs::read_dir(dir) { + Ok(e) => e.collect::, _>>()?, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(done), + Err(e) => return Err(Error::Io(e)), + }; + for entry in entries { + let name = entry.file_name().to_string_lossy().into_owned(); + let path = entry.path(); + // `tin-12.staged-TAG`: the record's own name is what's before the + // marker, plus `.bin`. + if let Some(stem) = name.strip_suffix(&format!(".staged-{tag}")) { + if committed { + std::fs::rename(&path, dir.join(format!("{stem}.bin")))?; + done.promoted += 1; + } else { + std::fs::remove_file(&path)?; + done.dropped += 1; + } + } else if let Some(stem) = name.strip_suffix(&format!(".purging-{tag}")) { + let own = dir.join(format!("{stem}.bin")); + if committed || own.exists() { + std::fs::remove_file(&path)?; + done.purged += 1; + } else { + std::fs::rename(&path, own)?; + done.restored += 1; + } + } + } + Ok(done) +} + /// What the vault in `dir` holds for a party, `(TIN, W-9 file)`, without /// the key: whether each record's file exists (nothing is decrypted). pub fn records_held(dir: &Path, party: u64) -> Result<(bool, bool), Error> { diff --git a/crates/ledger-vault/tests/vault.rs b/crates/ledger-vault/tests/vault.rs index de4cecdc..1125b825 100644 --- a/crates/ledger-vault/tests/vault.rs +++ b/crates/ledger-vault/tests/vault.rs @@ -237,3 +237,143 @@ fn purge_and_holdings_need_no_key() { (false, false) ); } + +const TAG: &str = "0123456789abcdef"; +const OTHER: &str = "fedcba9876543210"; + +fn tin_a() -> Tin { + Tin::new("123-45-6789", TinType::Ssn).unwrap() +} + +fn tin_b() -> Tin { + Tin::new("765-43-2109", TinType::Ssn).unwrap() +} + +/// INVARIANT 7: a staged record is not the party's record: a reader sees +/// the old one (or none) until `settle` says the call committed. +#[test] +fn a_staged_record_is_read_by_no_one_until_its_call_commits() { + let d = dir("stage-commit"); + let v = vault(&d); + let old_hash = v.put_tin(7, &tin_a()).unwrap(); + let new_hash = v.stage_tin(7, &tin_b(), TAG).unwrap(); + assert_ne!(old_hash, new_hash); + // Nothing changed for a reader. + assert_eq!(v.tin(7).unwrap().unwrap().last4(), "6789"); + assert_eq!( + v.record_hash(7).unwrap().as_deref(), + Some(old_hash.as_str()) + ); + assert_eq!( + ledger_vault::pending_tags(&d.join("vault")).unwrap(), + [TAG.to_string()] + ); + let done = ledger_vault::settle(&d.join("vault"), TAG, true).unwrap(); + assert_eq!(done.promoted, 1); + assert_eq!(v.tin(7).unwrap().unwrap().last4(), "2109"); + assert_eq!( + v.record_hash(7).unwrap().as_deref(), + Some(new_hash.as_str()) + ); + assert!( + ledger_vault::pending_tags(&d.join("vault")) + .unwrap() + .is_empty() + ); + // Settling again changes nothing. + assert_eq!( + ledger_vault::settle(&d.join("vault"), TAG, true).unwrap(), + Default::default() + ); +} + +/// INVARIANT 7: a call that did not commit leaves the old record whole, +/// and nothing of the new one. +#[test] +fn a_call_that_did_not_commit_leaves_the_old_record_whole() { + let d = dir("stage-drop"); + let v = vault(&d); + let old_hash = v.put_tin(7, &tin_a()).unwrap(); + v.stage_tin(7, &tin_b(), TAG).unwrap(); + // Another call's staged file is not this call's to settle. + v.stage_tin(8, &tin_b(), OTHER).unwrap(); + let done = ledger_vault::settle(&d.join("vault"), TAG, false).unwrap(); + assert_eq!(done.dropped, 1); + assert_eq!(v.tin(7).unwrap().unwrap().last4(), "6789"); + assert_eq!( + v.record_hash(7).unwrap().as_deref(), + Some(old_hash.as_str()) + ); + assert_eq!( + ledger_vault::pending_tags(&d.join("vault")).unwrap(), + [OTHER.to_string()] + ); + assert!(v.tin(8).unwrap().is_none()); +} + +/// INVARIANT 7: a purge is destroyed only when its call commits; if it +/// doesn't, every record is put back, byte for byte. +#[test] +fn a_purge_is_final_only_when_its_call_commits() { + let d = dir("stage-purge"); + let v = vault(&d); + let hash = v.put_tin(7, &tin_a()).unwrap(); + v.put_w9( + 7, + &W9File { + file_name: "w9.pdf".into(), + mime_type: "application/pdf".into(), + bytes: b"%PDF fake".to_vec(), + }, + ) + .unwrap(); + assert!(ledger_vault::stage_purge(&d.join("vault"), 7, TAG).unwrap()); + // Out of sight at once ... + assert_eq!( + ledger_vault::records_held(&d.join("vault"), 7).unwrap(), + (false, false) + ); + // ... and back if the call didn't commit. + let undone = ledger_vault::settle(&d.join("vault"), TAG, false).unwrap(); + assert_eq!(undone.restored, 2); + assert_eq!(v.record_hash(7).unwrap().as_deref(), Some(hash.as_str())); + assert!(v.w9(7).unwrap().is_some()); + // Committed: gone for good. + ledger_vault::stage_purge(&d.join("vault"), 7, TAG).unwrap(); + let gone = ledger_vault::settle(&d.join("vault"), TAG, true).unwrap(); + assert_eq!(gone.purged, 2); + assert_eq!( + ledger_vault::records_held(&d.join("vault"), 7).unwrap(), + (false, false) + ); + assert!( + ledger_vault::pending_tags(&d.join("vault")) + .unwrap() + .is_empty() + ); +} + +/// A tag names a call in a file name: anything else is refused, so it can't +/// name a path. +#[test] +fn a_tag_that_is_not_sixteen_hex_digits_is_refused() { + let d = dir("stage-tag"); + let v = vault(&d); + for bad in [ + "", + "../x", + "0123456789ABCDEF", + "0123456789abcde", + "0123456789abcdefg", + ] { + assert!(v.stage_tin(7, &tin_a(), bad).is_err(), "{bad}"); + assert!( + ledger_vault::stage_purge(&d.join("vault"), 7, bad).is_err(), + "{bad}" + ); + assert!( + ledger_vault::settle(&d.join("vault"), bad, true).is_err(), + "{bad}" + ); + } +}