From 2633109d55012dc1a7f0fc261ec22abe8694ec31 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 09:16:03 -0700 Subject: [PATCH 1/6] feat(store): a tool call is one journal transaction (P15 T1, D-88) Accounting reasoning: a write that is retried after a lost answer must happen once, and a call that dies between its journal lines must never be replayed as if whole. The journal feature `call_transactions` frames a call's lines with `call.begun` and `call.closed`; the lines between count only when the closing line says `ok`. Every replay (open, the viewer, verify, rebuild, the projection's catch-up) goes through one gate (`CallGate`), so no state is built from half a call and a replay of any prefix ending inside a call equals the replay of the prefix before it. A call that never closed is closed `unfinished` at the next open; a call that fails after writing lines is closed `failed`, its SQLite changes (one transaction per call) rolled back and the live ledger rebuilt without them. The closing line keeps the answer given, so a repeat of a request key returns it; the key table is rebuilt from the journal alone. The envelope is untouched. Lines outside a frame apply as ever, so every journal written before the feature replays as it was. Books get a unique id (`books_id`) at creation, and older books at the format upgrade, in the `journal.format_set` that declares the feature. The frame lines never move the audit's figure head. The upgrade's declaration now also carries the id, so the three tests that pinned its exact payload compare it without the id. No figure and no golden moved. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-gui/src/pages/journal.rs | 12 + crates/ledger-store/src/audit.rs | 2 + crates/ledger-store/src/calls.rs | 606 ++++++++++++++++++++ crates/ledger-store/src/describe.rs | 9 + crates/ledger-store/src/error.rs | 18 +- crates/ledger-store/src/format.rs | 56 ++ crates/ledger-store/src/lib.rs | 1 + crates/ledger-store/src/snapshot.rs | 23 +- crates/ledger-store/src/store.rs | 128 ++++- crates/ledger-store/tests/calls.rs | 416 ++++++++++++++ crates/ledger-store/tests/format.rs | 12 +- crates/ledger-store/tests/format_upgrade.rs | 6 +- docs/receipt-store.md | 14 + docs/spec/claims/format.md | 99 +++- fuzz/fuzz_targets/fuzz_store_replay.rs | 2 + 15 files changed, 1375 insertions(+), 29 deletions(-) create mode 100644 crates/ledger-store/src/calls.rs create mode 100644 crates/ledger-store/tests/calls.rs diff --git a/crates/ledger-gui/src/pages/journal.rs b/crates/ledger-gui/src/pages/journal.rs index b75865dd..2bb8d345 100644 --- a/crates/ledger-gui/src/pages/journal.rs +++ b/crates/ledger-gui/src/pages/journal.rs @@ -1098,6 +1098,18 @@ pub fn describe(b: &Books, line: &JournalLine) -> Option { format!("Recurring: {}", s(p, "description")), Some(Route::Company), ), + // A call's frame (ledger-store calls.rs): the call's own lines are + // listed between them. + "call.begun" => ev( + icon::FILE_TEXT, + format!("Call begun: {}", s(p, "tool")), + None, + ), + "call.closed" => ev( + icon::FILE_TEXT, + format!("Call closed ({}): {}", s(p, "outcome"), s(p, "tool")), + None, + ), "journal.tail_repaired" => ev( icon::WARNING, format!("Cut-off journal line set aside ({} bytes)", p["bytes"]), diff --git a/crates/ledger-store/src/audit.rs b/crates/ledger-store/src/audit.rs index c15b890d..90f6757b 100644 --- a/crates/ledger-store/src/audit.rs +++ b/crates/ledger-store/src/audit.rs @@ -60,6 +60,8 @@ pub const NOT_FIGURES: &[&str] = &[ "store.created", "journal.format_set", "journal.tail_repaired", + "call.begun", + "call.closed", "attachment.linked", "attachment.unlinked", "attachment.withdrawn", diff --git a/crates/ledger-store/src/calls.rs b/crates/ledger-store/src/calls.rs new file mode 100644 index 00000000..e8882bc1 --- /dev/null +++ b/crates/ledger-store/src/calls.rs @@ -0,0 +1,606 @@ +//! Calls: every write a tool makes is one transaction that happens once +//! (plan P15 2a, D-88, D-89). +//! +//! A call that writes frames its journal lines with two line types, and +//! a call that wrote nothing is just a closing line: +//! +//! * `call.begun { tool, token, key, args }`, written lazily, just before +//! the call's first line; +//! * `call.closed { tool, token, key, args, outcome, first_seq, last_seq, +//! answer | error }`, written when the call is over. `outcome` is `ok` +//! (the answer the caller was given is `answer`, kept as text so a +//! repeat returns it byte for byte), `failed` (the call got as far as +//! writing lines and then failed: `error` says how), or `unfinished` +//! (written by the next open of books whose last call never closed). +//! +//! The lines between a begin and its close count only if the close says +//! `ok`: that is how a reader tells a complete call from an incomplete +//! one, and the one rule every replay uses ([`CallGate`]). The envelope +//! `{seq, ts, type, payload, prev}` is untouched. +//! +//! ```text +//! GOAL: a call's lines commit together or not at all, a failed call is +//! on the record, and a repeated request key answers what the first +//! call answered and writes nothing. +//! SOURCE: WB-format-8, WB-format-9, WB-format-10, WB-format-11, WB-format-12; +//! plan/p15-app-and-relay.md 2a (D-88, D-89). +//! INVARIANTS: +//! 1. Replay applies a call's lines only at its `ok` closing line, in +//! order, and never any line of a call that closed `failed` or +//! `unfinished`, or that never closed: no state is ever built from +//! half a call. A replay of any prefix that ends inside a call +//! equals the replay of the prefix before that call's begin line. +//! 2. Lines outside a begin..close frame (every line written before the +//! books declared the feature, and the owner's own acts: the format +//! declaration, a repaired tail) apply as ever. +//! 3. A close names the frame it ends: its `first_seq` is the begin +//! line's seq and its `last_seq` the line before it, or both are +//! absent when the call wrote no lines. A begin inside a frame, a +//! mismatched close, or an `unfinished` close with no frame is a +//! corrupt journal. +//! 4. The projection never holds a line of a call that did not commit: +//! the call's SQLite changes live in one transaction that is released +//! only after the `ok` closing line is on disk. +//! 5. The key table (token, key) -> answer is built from `ok` closing +//! lines alone, so a restart rebuilds it from the journal. +//! 6. Books that haven't declared `call_transactions` take no call: a +//! begin is refused (FormatUpgradePending), journaling nothing. +//! SCENARIOS: +//! 1. IF the process dies between a call's lines and its closing line: +//! SHOULD, at the next open, apply none of them, write an +//! `unfinished` close, and rebuild the projection if it holds them. +//! 2. IF a call fails after writing lines: SHOULD journal a `failed` +//! close, roll its SQLite changes back, and replay the journal +//! without its lines. +//! 3. IF a call fails before writing a line: SHOULD journal nothing. +//! ``` + +use std::collections::HashMap; + +use serde_json::{Value, json}; + +use super::{Store, apply_line_to_sqlite, get_str, get_u64}; +use crate::error::StoreError; +use crate::format::{self, CALL_TRANSACTIONS}; +use crate::journal::JournalLine; + +/// The line type that opens a call's frame. +pub const BEGUN: &str = "call.begun"; +/// The line type that closes it. +pub const CLOSED: &str = "call.closed"; + +/// A request key is at least this many characters. +pub const MIN_KEY_LEN: usize = 8; +/// A request key is at most this many characters. +pub const MAX_KEY_LEN: usize = 128; + +/// Who made a call, what it is, and what it asked for. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CallId { + /// The token the call came with (a key is scoped to its token). + pub token: String, + /// The tool's name. + pub tool: String, + /// The request key. + pub key: String, + /// The digest of the call's arguments, without the key. + pub args: String, +} + +/// How a call ended. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CallOutcome { + /// It committed: its lines count. + Ok, + /// It failed after writing lines: none of them count. + Failed, + /// It never closed: written by the open that found it. + Unfinished, +} + +impl CallOutcome { + fn as_str(self) -> &'static str { + match self { + Self::Ok => "ok", + Self::Failed => "failed", + Self::Unfinished => "unfinished", + } + } +} + +/// A closing line, read. +#[derive(Clone, Debug)] +pub struct Closed { + /// The call. + pub id: CallId, + /// How it ended. + pub outcome: CallOutcome, + /// The seq of the begin line, when the call wrote lines. + pub first_seq: Option, + /// The seq of the call's last line, when it wrote lines. + pub last_seq: Option, + /// The answer it gave (an `ok` call): JSON text. + pub answer: Option, + /// How it failed (a `failed` call). + pub error: Option, +} + +/// What the books kept of a call that committed. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Recorded { + /// The tool. + pub tool: String, + /// The digest of its arguments, without the key. + pub args: String, + /// The answer it gave, as JSON text. + pub answer: String, + /// The seq of its closing line. + pub seq: u64, +} + +/// The keys of every call that committed, by (token, key). +#[derive(Clone, Debug, Default)] +pub struct Keys { + by: HashMap<(String, String), Recorded>, +} + +impl Keys { + /// Every `ok` closing line of `lines`, oldest first (INVARIANT 5). The + /// first call with a key wins, as it did when it ran. + pub(crate) fn from_lines(lines: &[JournalLine]) -> Result { + let mut keys = Self::default(); + for line in lines.iter().filter(|l| l.line_type == CLOSED) { + let closed = closed_of(line)?; + if closed.outcome == CallOutcome::Ok { + keys.note(&closed, line.seq); + } + } + Ok(keys) + } + + fn note(&mut self, closed: &Closed, seq: u64) { + let Some(answer) = closed.answer.clone() else { + return; + }; + self.by + .entry((closed.id.token.clone(), closed.id.key.clone())) + .or_insert(Recorded { + tool: closed.id.tool.clone(), + args: closed.id.args.clone(), + answer, + seq, + }); + } + + fn get(&self, token: &str, key: &str) -> Option<&Recorded> { + self.by.get(&(token.to_string(), key.to_string())) + } +} + +fn corrupt(line: &JournalLine, what: &str) -> StoreError { + StoreError::JournalCorrupt(format!("seq {}: {} {what}", line.seq, line.line_type)) +} + +fn call_id_of(line: &JournalLine) -> Result { + let p = &line.payload; + let field = |k: &str| { + get_str(p, k) + .map(str::to_string) + .map_err(|_| corrupt(line, k)) + }; + Ok(CallId { + token: field("token")?, + tool: field("tool")?, + key: field("key")?, + args: field("args")?, + }) +} + +/// A `call.begun` line's call: a missing or mistyped key is corrupt. +pub fn begun_of(line: &JournalLine) -> Result { + call_id_of(line) +} + +/// A `call.closed` line, read: a missing or mistyped key is corrupt, an +/// outcome this version doesn't know is newer (BS-format-1). +pub fn closed_of(line: &JournalLine) -> Result { + let p = &line.payload; + let id = call_id_of(line)?; + let outcome = match get_str(p, "outcome").map_err(|_| corrupt(line, "outcome"))? { + "ok" => CallOutcome::Ok, + "failed" => CallOutcome::Failed, + "unfinished" => CallOutcome::Unfinished, + other => { + return Err(format::newer_content( + line, + format!("call outcome {other:?}"), + )); + } + }; + let seq_of = |k: &str| match p.get(k) { + None | Some(Value::Null) => Ok(None), + Some(_) => get_u64(p, k).map(Some).map_err(|_| corrupt(line, k)), + }; + let text_of = |k: &str| match p.get(k) { + None | Some(Value::Null) => Ok(None), + Some(v) => v + .as_str() + .map(|s| Some(s.to_string())) + .ok_or_else(|| corrupt(line, k)), + }; + let answer = text_of("answer")?; + if outcome == CallOutcome::Ok && answer.is_none() { + return Err(corrupt(line, "answer")); + } + Ok(Closed { + id, + outcome, + first_seq: seq_of("first_seq")?, + last_seq: seq_of("last_seq")?, + answer, + error: text_of("error")?, + }) +} + +fn begun_payload(id: &CallId) -> Value { + json!({ "tool": id.tool, "token": id.token, "key": id.key, "args": id.args }) +} + +fn closed_payload( + id: &CallId, + outcome: CallOutcome, + range: Option<(u64, u64)>, + answer: Option<&str>, + error: Option<&str>, +) -> Value { + let mut p = begun_payload(id); + p["outcome"] = json!(outcome.as_str()); + if let Some((first, last)) = range { + p["first_seq"] = json!(first); + p["last_seq"] = json!(last); + } + if let Some(a) = answer { + p["answer"] = json!(a); + } + if let Some(e) = error { + p["error"] = json!(e); + } + p +} + +/// A frame that never closed, at the end of a journal. +#[derive(Clone, Debug)] +pub(crate) struct Unfinished { + pub(crate) id: CallId, + pub(crate) first_seq: u64, + pub(crate) last_seq: u64, +} + +struct Pending { + id: CallId, + begun_seq: u64, + events: Vec, + last_seq: u64, +} + +/// The one rule every replay applies (INVARIANTS 1 to 3): fed the lines +/// in order, it says which of them to apply, now. +/// +/// A line outside a frame applies at once; the begin line applies at once +/// (it changes nothing); the lines inside a frame wait, and are released +/// with the closing line when it says `ok`, and dropped when it says +/// anything else. +#[derive(Default)] +pub(crate) struct CallGate { + pending: Option, + skipped: Vec<(u64, u64)>, +} + +impl CallGate { + /// Take the line at `index`; the indices (into the caller's lines) to + /// apply now, in order. + pub(crate) fn push( + &mut self, + index: usize, + line: &JournalLine, + ) -> Result, StoreError> { + match line.line_type.as_str() { + BEGUN => { + if self.pending.is_some() { + return Err(corrupt(line, "begins inside a call that never closed")); + } + self.pending = Some(Pending { + id: begun_of(line)?, + begun_seq: line.seq, + events: Vec::new(), + last_seq: line.seq, + }); + Ok(vec![index]) + } + CLOSED => { + let closed = closed_of(line)?; + let Some(call) = self.pending.take() else { + if closed.first_seq.is_some() + || closed.last_seq.is_some() + || closed.outcome == CallOutcome::Unfinished + { + return Err(corrupt(line, "closes a call that never began")); + } + return Ok(vec![index]); + }; + if closed.id != call.id + || closed.first_seq != Some(call.begun_seq) + || closed.last_seq != Some(line.seq.saturating_sub(1)) + { + return Err(corrupt(line, "doesn't close the call it follows")); + } + if closed.outcome == CallOutcome::Ok { + let mut out = call.events; + out.push(index); + Ok(out) + } else { + if !call.events.is_empty() { + self.skipped.push((call.begun_seq + 1, call.last_seq)); + } + Ok(vec![index]) + } + } + _ => match &mut self.pending { + Some(call) => { + call.events.push(index); + call.last_seq = line.seq; + Ok(Vec::new()) + } + None => Ok(vec![index]), + }, + } + } + + /// The frame that has not closed yet, if any. + pub(crate) fn unfinished(&self) -> Option { + self.pending.as_ref().map(|c| Unfinished { + id: c.id.clone(), + first_seq: c.begun_seq, + last_seq: c.last_seq, + }) + } + + /// Whether `seq` is a line of a call that did not commit: closed + /// `failed` or `unfinished`, or not closed yet (the begin line apart). + pub(crate) fn is_uncommitted(&self, seq: u64) -> bool { + self.skipped.iter().any(|&(a, b)| (a..=b).contains(&seq)) + || self + .pending + .as_ref() + .is_some_and(|c| seq > c.begun_seq && seq <= c.last_seq) + } +} + +/// [`CallGate`] over a whole journal: the indices to apply, in order, the +/// frame left open at the end, and the gate (for what it knows of the +/// lines that did not commit). +pub(crate) fn gate_all(lines: &[JournalLine]) -> Result<(Vec, CallGate), StoreError> { + let mut gate = CallGate::default(); + let mut released = Vec::with_capacity(lines.len()); + for (i, line) in lines.iter().enumerate() { + released.extend(gate.push(i, line)?); + } + Ok((released, gate)) +} + +/// The books' id: the one `store.created` carries (books made since +/// `call_transactions`), else the one the format upgrade added to its +/// `journal.format_set`. None for books that have had neither yet. +pub fn books_id_of(lines: &[JournalLine]) -> Option { + lines + .iter() + .filter(|l| l.line_type == "store.created" || l.line_type == format::FORMAT_SET) + .find_map(|l| l.payload.get("books_id").and_then(Value::as_str)) + .map(str::to_string) +} + +/// A fresh books id: 128 random bits, in hex. +pub(crate) fn new_books_id() -> Result { + let mut bytes = [0u8; 16]; + getrandom::getrandom(&mut bytes).map_err(|e| { + StoreError::Io(std::io::Error::other(format!( + "no randomness for the books' id: {e}" + ))) + })?; + Ok(hex::encode(bytes)) +} + +/// The call a store is in, between [`Store::begin_call`] and +/// [`Store::close_call`]. +pub(crate) struct ActiveCall { + id: CallId, + /// The seq of its begin line once it has written one. + begun: Option, +} + +/// How a call ended, as [`Store::close_call`] is told. +pub enum CallEnd<'a> { + /// It answered; this is the answer (JSON text). + Done(&'a str), + /// It failed; this is how. + Failed(&'a str), +} + +impl Store { + /// The books' id, if they have one (see [`books_id_of`]). + pub fn books_id(&self) -> Option<&str> { + self.books_id.as_deref() + } + + /// Whether these books declared `call_transactions`: they take calls. + pub fn takes_calls(&self) -> bool { + self.format.has_feature(CALL_TRANSACTIONS) + } + + /// Refuse unless the books take calls (D-89), journaling nothing: the + /// refusal says what the owner does. + pub fn ensure_takes_calls(&self) -> Result<(), StoreError> { + self.ensure_feature(CALL_TRANSACTIONS) + } + + /// What the books kept of the call that ran under this token and key, + /// if one committed. + pub fn recorded_call(&self, token: &str, key: &str) -> Option<&Recorded> { + self.keys.get(token, key) + } + + /// Whether a call is open. + pub fn in_call(&self) -> bool { + self.call.is_some() + } + + /// Open a call: from here every line this store journals belongs to + /// it, until [`Self::close_call`]. Journals nothing yet (the begin + /// line comes with the first line); the projection's changes are held + /// in one transaction. + /// + /// ```text + /// SCENARIOS: + /// 1. IF the books haven't declared call_transactions: SHOULD + /// refuse (FormatUpgradePending), journaling nothing. + /// 2. IF a call is already open, or an earlier call's closing line + /// couldn't be written: SHOULD refuse (CallRefused). + /// ``` + pub fn begin_call(&mut self, id: CallId) -> Result<(), StoreError> { + self.ensure_takes_calls()?; + if self.dangling { + return Err(StoreError::CallRefused( + "an earlier call's closing line couldn't be written: the books must be opened again before they take another".into(), + )); + } + if self.call.is_some() { + return Err(StoreError::CallRefused( + "a call is already open in these books".into(), + )); + } + self.conn.execute_batch("SAVEPOINT call_tx")?; + self.call = Some(ActiveCall { id, begun: None }); + Ok(()) + } + + /// Write the begin line of the open call, if it has none yet. Every + /// append comes through here (`append_journal`). + pub(super) fn begin_frame(&mut self) -> Result<(), StoreError> { + if self.dangling { + return Err(StoreError::CallRefused( + "an earlier call's closing line couldn't be written: the books must be opened again before they take another".into(), + )); + } + let Some(call) = &self.call else { + return Ok(()); + }; + if call.begun.is_some() { + return Ok(()); + } + let line = self.journal.append(BEGUN, begun_payload(&call.id))?; + apply_line_to_sqlite(&self.conn, &line)?; + if let Some(call) = &mut self.call { + call.begun = Some(line.seq); + } + Ok(()) + } + + /// Close the open call. `Done`: journal its closing line with the + /// answer, and release the projection's transaction: the call + /// committed. `Failed`: if the call wrote lines, journal a `failed` + /// closing line, roll the projection back and rebuild the live ledger + /// without those lines; if it wrote none, journal nothing. + /// + /// If the closing line cannot be written, the call has not committed + /// (it will close `unfinished` at the next open), the store refuses + /// every further write, and the error is returned: the caller stops + /// taking requests. + pub fn close_call(&mut self, end: CallEnd<'_>) -> Result<(), StoreError> { + let call = self + .call + .take() + .ok_or_else(|| StoreError::CallRefused("no call is open".into()))?; + let range = call.begun.map(|first| (first, self.journal.head().0)); + match end { + CallEnd::Done(answer) => { + let payload = closed_payload(&call.id, CallOutcome::Ok, range, Some(answer), None); + let line = self + .journal + .append(CLOSED, payload) + .map_err(|e| self.dangle(e))?; + // The projection commits with the line: released only + // once the closing line is on disk (INVARIANT 4). + apply_line_to_sqlite(&self.conn, &line) + .and_then(|()| Ok(self.conn.execute_batch("RELEASE call_tx")?)) + .map_err(|e| self.dangle(e))?; + let closed = closed_of(&line)?; + self.keys.note(&closed, line.seq); + Ok(()) + } + CallEnd::Failed(error) => { + if range.is_none() { + self.conn + .execute_batch("ROLLBACK TO call_tx; RELEASE call_tx")?; + return Ok(()); + } + let payload = + closed_payload(&call.id, CallOutcome::Failed, range, None, Some(error)); + self.journal + .append(CLOSED, payload) + .map_err(|e| self.dangle(e))?; + self.conn + .execute_batch("ROLLBACK TO call_tx; RELEASE call_tx") + .map_err(StoreError::from) + .and_then(|()| self.reload()) + .map_err(|e| self.dangle(e))?; + Ok(()) + } + } + } + + /// An open call that can't be finished (its closing line can't be + /// written, or what follows it fails): the call stays unfinished in the + /// journal or its effects are unsure, the projection's changes are dropped, + /// and the store takes nothing more. + fn dangle(&mut self, e: StoreError) -> StoreError { + self.dangling = true; + let _ = self + .conn + .execute_batch("ROLLBACK TO call_tx; RELEASE call_tx"); + e + } + + /// The live ledger and the projection, brought to what a restart + /// would build: the journal read through the gate, the ledger replayed + /// from it, and the projection (rolled back to before the call) caught + /// up with the lines that count. After a call failed with lines + /// written. + fn reload(&mut self) -> Result<(), StoreError> { + let lines = crate::journal::read_and_verify_journal(self.journal.path())?; + let (released, _) = gate_all(&lines)?; + let mut ledger = ledger_core::Ledger::new(self.base_currency); + for &i in &released { + super::replay_line_into_ledger(&mut ledger, &lines[i], self.base_currency)?; + } + self.ledger = ledger; + self.catch_up(&lines, &released) + } + + /// At open: the journal's last call never closed. Journal an + /// `unfinished` close for it, so the record says what became of the + /// lines and the next call begins on a closed frame. + pub(super) fn close_unfinished(&mut self, u: &Unfinished) -> Result<(), StoreError> { + let payload = closed_payload( + &u.id, + CallOutcome::Unfinished, + Some((u.first_seq, u.last_seq)), + None, + Some( + "the call never finished: the books were closed or the program stopped before its closing line was written", + ), + ); + let line = self.journal.append(CLOSED, payload)?; + apply_line_to_sqlite(&self.conn, &line)?; + Ok(()) + } +} diff --git a/crates/ledger-store/src/describe.rs b/crates/ledger-store/src/describe.rs index 51b5e04e..9f538c99 100644 --- a/crates/ledger-store/src/describe.rs +++ b/crates/ledger-store/src/describe.rs @@ -204,6 +204,15 @@ pub fn describe(line: &JournalLine) -> String { if let Some(d) = p.get("date").and_then(Value::as_str) { parts.push(d.to_string()); } + // A call's frame: which tool, and how it ended; never the key, the + // arguments or the answer. + if ty.starts_with("call.") { + for k in ["tool", "outcome"] { + if let Some(t) = p.get(k).and_then(Value::as_str) { + parts.push(quote(t)); + } + } + } // Settings: which keys, never their values. if ty == "settings.set" && let Some(changes) = p.get("changes").and_then(Value::as_array) diff --git a/crates/ledger-store/src/error.rs b/crates/ledger-store/src/error.rs index 95716935..b99ecc3f 100644 --- a/crates/ledger-store/src/error.rs +++ b/crates/ledger-store/src/error.rs @@ -106,6 +106,11 @@ pub enum StoreError { need: String, }, + /// A call (plan P15 2a) was begun or closed when it can't be: one is + /// already open, none is, or an earlier call could not be finished. + #[error("{0}")] + CallRefused(String), + /// Replay produced different ids than the journal recorded. #[error("replay mismatch: {0}")] ReplayMismatch(String), @@ -185,13 +190,22 @@ pub const FORMAT_UPGRADE_PENDING: &str = "format_upgrade_pending"; /// that nothing was changed, that only the owner can give the go-ahead /// (and where), and that the rest still works. fn format_upgrade_text(need: &str) -> String { + // D-89: books that haven't declared call_transactions take no writes + // at all, so for them the old promise ("everything that needs nothing + // new works") is not made. + let until = if need == format!("the journal feature {}", crate::format::CALL_TRANSACTIONS) { + "Until then these books can be read as ever, but nothing can be written to them: \ + every write is one transaction that happens exactly once, and books written by an \ + older version can't keep that until they are upgraded" + } else { + "Until then everything that needs nothing new works as before" + }; format!( "{FORMAT_UPGRADE_PENDING}: this needs {need}, and these books are still in the journal \ format an older version of wanderbooks wrote: they are waiting for the owner's \ go-ahead to upgrade to this version's format. Nothing was changed. Only the owner can \ give it, with the owner passphrase: in the app (it asks when it opens the books) or \ - with `wanderbooks books upgrade ID` at a terminal; no tool can. Until then everything \ - that needs nothing new works as before" + with `wanderbooks books upgrade ID` at a terminal; no tool can. {until}" ) } diff --git a/crates/ledger-store/src/format.rs b/crates/ledger-store/src/format.rs index 79ac76f5..764d9c37 100644 --- a/crates/ledger-store/src/format.rs +++ b/crates/ledger-store/src/format.rs @@ -68,6 +68,7 @@ pub const KNOWN_FEATURES: &[&str] = &[ DRAFTS_V2, SOURCE_REVISIONS, AUDITS, + CALL_TRANSACTIONS, ]; /// Feature: `period.closed` closes to members with `"rounding": @@ -256,6 +257,17 @@ pub const SOURCE_REVISIONS: &str = "source_revisions"; /// (BS-format-1, BS-ledger-13). pub const AUDITS: &str = "audits"; +/// Feature: `call_transactions` (plan P15 2a, D-88, D-89): every write a +/// tool makes is one transaction. A call's lines are framed by +/// `call.begun` and `call.closed`; the lines between them count only when +/// the closing line says `ok`, and a call that never closed, or closed +/// `failed`, builds no state. An older version doesn't know the two line +/// types and would refuse them as unknown, but a version that skipped +/// them would replay every line of a half-done or failed call as if it +/// were whole; it stops at the declaration instead (BS-format-1). The +/// books also take no tool write until they declare it (D-89). +pub const CALL_TRANSACTIONS: &str = "call_transactions"; + /// The line type that declares the journal format. pub const FORMAT_SET: &str = "journal.format_set"; @@ -284,6 +296,8 @@ pub const EVENT_TYPES: &[&str] = &[ "audit.run", "bill.created", "bill.paid", + "call.begun", + "call.closed", "class.added", "convention.retired", "convention.set", @@ -1101,6 +1115,48 @@ mod tests { assert_eq!(up.adds(), vec!["the journal feature audits"]); } + /// The version before D-88 (every feature but `call_transactions`) + /// stops at the declaration as newer: it would refuse a call's frame + /// as an unknown type, or, skipping the frame, replay every line of a + /// call that failed or never closed as if it were whole. Books that + /// declared every earlier feature still wait for it, and take no tool + /// write until they have it (D-89). + #[test] + fn call_transactions_is_its_own_feature() { + assert!(KNOWN_FEATURES.contains(&CALL_TRANSACTIONS)); + let before: Vec<&str> = KNOWN_FEATURES + .iter() + .copied() + .filter(|f| *f != CALL_TRANSACTIONS) + .collect(); + let l = line( + FORMAT_SET, + json!({"format": 2, "features": [AUDITS, CALL_TRANSACTIONS]}), + ); + match declared_knowing(&l, &before) { + Err(StoreError::NewerJournal { need, .. }) => { + assert_eq!(need, "journal features call_transactions") + } + other => panic!("expected NewerJournal, got {other:?}"), + } + let older = JournalFormat { + format: 2, + features: before.iter().map(|f| f.to_string()).collect(), + }; + let refused = older.require_feature(CALL_TRANSACTIONS); + assert!(matches!( + refused, + Err(StoreError::FormatUpgradePending { .. }) + )); + // The refusal tells the owner what is true of these books: no + // write at all, not "everything else works". + let words = refused.unwrap_err().to_string(); + assert!(words.contains("nothing can be written"), "{words}"); + assert!(words.contains("wanderbooks books upgrade"), "{words}"); + let up = older.upgrade().expect("waits for it"); + assert_eq!(up.adds(), vec!["the journal feature call_transactions"]); + } + /// The version before K-U5 (every feature but `schedule_minor_unit`) /// stops at the declaration as newer, so it never reads a ¥33,333 /// month under the cent rule (and refuses, or posts ¥33,333.33 where diff --git a/crates/ledger-store/src/lib.rs b/crates/ledger-store/src/lib.rs index eb3477cb..52cdfa2f 100644 --- a/crates/ledger-store/src/lib.rs +++ b/crates/ledger-store/src/lib.rs @@ -53,6 +53,7 @@ pub use format::{FormatUpgrade, JournalFormat, SUPPORTED_JOURNAL_FORMAT}; pub use journal::{GENESIS_PREV, JournalLine, JournalWriter}; pub use snapshot::{DiskCheck, Snapshot}; pub use store::audit; +pub use store::calls; pub use store::{ Attachment, BillPreview, DepreciationRun, DisposalPreview, EntryRow, EventRow, Extraction, ExtractionStatus, InvoicePreview, JOURNAL_FILE, LEGACY_DB_FILE, LOCK_FILE, MAX_RECURRING_RUN, diff --git a/crates/ledger-store/src/snapshot.rs b/crates/ledger-store/src/snapshot.rs index 2c977a5e..f150656b 100644 --- a/crates/ledger-store/src/snapshot.rs +++ b/crates/ledger-store/src/snapshot.rs @@ -74,6 +74,10 @@ pub struct Snapshot { head: String, /// The journal format in force (the format gate's record). format: JournalFormat, + /// Which lines count (calls.rs): the lines of a call wait here until + /// its closing line is read, and a call that failed or never closed + /// is never applied. + gate: crate::calls::CallGate, } impl Snapshot { @@ -95,6 +99,7 @@ impl Snapshot { offset: 0, head: GENESIS_PREV.to_string(), format: JournalFormat::default(), + gate: crate::calls::CallGate::default(), }; snap.read_new()?; Ok(snap) @@ -209,10 +214,17 @@ impl Snapshot { self.ledger = Ledger::new(self.base_currency); } self.format.admit(&line)?; - replay_line_into_ledger(&mut self.ledger, &line, self.base_currency)?; - apply_line_to_sqlite(&self.conn, &line)?; - self.head = hash; + // Only what the call gate releases is applied (calls.rs): a + // call's lines wait for its closing line. + let index = self.lines.len(); + let released = self.gate.push(index, &line)?; self.lines.push(line); + for i in released { + let line = &self.lines[i]; + replay_line_into_ledger(&mut self.ledger, line, self.base_currency)?; + apply_line_to_sqlite(&self.conn, line)?; + } + self.head = hash; self.offset += len; } Ok(added) @@ -234,6 +246,11 @@ impl Snapshot { &self.format } + /// The books' id, if they have one ([`crate::calls::books_id_of`]). + pub fn books_id(&self) -> Option { + crate::calls::books_id_of(&self.lines) + } + /// The data directory. pub fn data_dir(&self) -> &Path { &self.data_dir diff --git a/crates/ledger-store/src/store.rs b/crates/ledger-store/src/store.rs index 451a5007..5880a531 100644 --- a/crates/ledger-store/src/store.rs +++ b/crates/ledger-store/src/store.rs @@ -54,6 +54,9 @@ use std::path::{Path, PathBuf}; #[path = "audit.rs"] pub mod audit; +#[path = "calls.rs"] +pub mod calls; + /// File names inside the data directory. pub const JOURNAL_FILE: &str = "journal.jsonl"; @@ -493,6 +496,16 @@ pub struct Store { base_currency: Currency, /// The journal format in force (the format gate's record). format: JournalFormat, + /// The call open now, if any (calls.rs): every line journaled while it + /// is open belongs to it. + call: Option, + /// The keys of every call that committed (calls.rs). + keys: calls::Keys, + /// The books' id (calls::books_id_of), if they have one. + books_id: Option, + /// A call could not be finished: no write is taken until the books + /// are opened again (calls.rs, close_call). + dangling: bool, } /// One filing of bytes into the blob store and journal. @@ -591,11 +604,20 @@ impl Store { ledger: Ledger::new(base_currency), base_currency, format: JournalFormat::default(), + call: None, + keys: calls::Keys::default(), + books_id: None, + dangling: false, }; - let line = store.journal.append( - "store.created", - json!({ "base_currency": base_currency.code() }), - )?; + // Books that take calls are born with their id; older books are + // given one at their format upgrade (declare_journal_format). + let mut created = json!({ "base_currency": base_currency.code() }); + if format.has_feature(crate::format::CALL_TRANSACTIONS) { + let id = calls::new_books_id()?; + created["books_id"] = json!(id); + store.books_id = Some(id); + } + let line = store.journal.append("store.created", created)?; apply_line_to_sqlite(&store.conn, &line)?; if *format != JournalFormat::default() { let features: Vec<&str> = format.features.iter().map(String::as_str).collect(); @@ -667,11 +689,16 @@ impl Store { // Every complete line replayed, in memory, before anything on disk // changes (SCENARIO 3): a line the books can't apply refuses the // open with the journal and the database as they were. + // Through the call gate (calls.rs): only the lines of calls that + // committed, and every line outside a call, build the books. + let (released, gate) = calls::gate_all(&lines)?; let mut ledger = Ledger::new(base_currency); - for line in &lines { + for &i in &released { crate::cancel::check()?; - replay_line_into_ledger(&mut ledger, line, base_currency)?; + replay_line_into_ledger(&mut ledger, &lines[i], base_currency)?; } + let keys = calls::Keys::from_lines(&lines)?; + let books_id = calls::books_id_of(&lines); // Only then is an append cut off mid-line (never acknowledged) set // aside, and journaled below. let torn = if complete < raw.len() { @@ -691,6 +718,8 @@ impl Store { Some("failed integrity_check".to_string()) } else if let Some(other) = schema_of(&db_path).filter(|v| *v != schema) { Some(format!("holds schema {other}, not this version's {schema}")) + } else if Self::db_applied_seq(&db_path).is_some_and(|n| gate.is_uncommitted(n)) { + Some("holds lines of a call that never committed".to_string()) } else { match Self::db_currency(&db_path) { Some(c) if c == base_currency => None, @@ -733,8 +762,23 @@ impl Store { ledger, base_currency, format, + call: None, + keys, + books_id, + dangling: false, }; - store.catch_up(&lines)?; + store.catch_up(&lines, &released)?; + // A call that never closed (calls.rs, SCENARIO 1): on the record + // before anything else is written, so the next call's lines are + // never inside its frame. + if let Some(u) = gate.unfinished() { + store.close_unfinished(&u)?; + eprintln!( + "wanderbooks: the last call to the books ({}) never finished; none of its {} lines count, and it is closed as unfinished in the journal", + u.id.tool, + u.last_seq - u.first_seq + ); + } if let Some(t) = torn { // On the record, so the repair is part of the audit trail. let line = store.append_journal( @@ -755,6 +799,20 @@ impl Store { Ok(store) } + /// The last journal line an existing database says it applied. + fn db_applied_seq(db_path: &Path) -> Option { + let conn = Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) + .ok()?; + let seq: String = conn + .query_row( + "SELECT value FROM meta WHERE key='last_applied_seq'", + [], + |r| r.get(0), + ) + .ok()?; + seq.parse().ok() + } + /// The base currency an existing database records, if it can say. fn db_currency(db_path: &Path) -> Option { let conn = Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) @@ -832,7 +890,7 @@ impl Store { /// Catch the projection up: apply to SQLite every line past /// `last_applied_seq` (the ledger is already the replay of every line, /// done in memory by [`Store::open`] before anything changed). - fn catch_up(&mut self, lines: &[JournalLine]) -> Result<(), StoreError> { + fn catch_up(&mut self, lines: &[JournalLine], released: &[usize]) -> Result<(), StoreError> { let last_applied: u64 = self .conn .query_row( @@ -845,7 +903,13 @@ impl Store { .unwrap_or(0); // The ledger is already their replay (Store::open): only the // projection is caught up here. - for line in lines.iter().filter(|l| l.seq > last_applied) { + // Only the lines that count (calls.rs): a call that didn't commit + // never reaches the projection. + for line in released + .iter() + .map(|&i| &lines[i]) + .filter(|l| l.seq > last_applied) + { crate::cancel::check()?; apply_line_to_sqlite(&self.conn, line)?; } @@ -927,9 +991,23 @@ impl Store { format: u32, features: &[&str], ) -> Result<(), StoreError> { - let payload = self.format.declaration(format, features)?; + let mut payload = self.format.declaration(format, features)?; + // Older books get their id with the declaration that gives them + // call_transactions (calls.rs; plan 6a): new books had one at + // creation. + let new_id = + if self.books_id.is_none() && features.contains(&crate::format::CALL_TRANSACTIONS) { + let id = calls::new_books_id()?; + payload["books_id"] = json!(id); + Some(id) + } else { + None + }; let line = self.append_journal(crate::format::FORMAT_SET, payload)?; self.format = crate::format::declared(&line)?; + if new_id.is_some() { + self.books_id = new_id; + } apply_line_to_sqlite(&self.conn, &line)?; Ok(()) } @@ -1327,6 +1405,8 @@ impl Store { line_type: &str, payload: Value, ) -> Result { + // The first line of a call opens its frame (calls.rs). + self.begin_frame()?; let line = self.journal.append(line_type, payload)?; // The command that posts the entry runs after its line is // journaled: tell the ledger which line that is (plan P4). @@ -6273,10 +6353,11 @@ impl Store { /// ``` pub fn verify(&self) -> Result<(), StoreError> { let lines = read_and_verify_journal(self.journal.path())?; + let (released, _) = calls::gate_all(&lines)?; let mut replayed = Ledger::new(self.base_currency); - for line in &lines { + for &i in &released { crate::cancel::check()?; - replay_line_into_ledger(&mut replayed, line, self.base_currency)?; + replay_line_into_ledger(&mut replayed, &lines[i], self.base_currency)?; } crate::cancel::check()?; let a = reports::snapshot(&replayed).map_err(StoreError::Ledger)?; @@ -6474,14 +6555,15 @@ impl Store { Self::write_meta(&self.conn, "base_currency", self.base_currency.code())?; Self::write_meta(&self.conn, "last_applied_seq", "0")?; let lines = read_and_verify_journal(self.journal.path())?; - for line in &lines { + let (released, _) = calls::gate_all(&lines)?; + for &i in &released { crate::cancel::check()?; - apply_line_to_sqlite(&self.conn, line)?; + apply_line_to_sqlite(&self.conn, &lines[i])?; } self.ledger = Ledger::new(self.base_currency); - for line in &lines { + for &i in &released { crate::cancel::check()?; - replay_line_into_ledger(&mut self.ledger, line, self.base_currency)?; + replay_line_into_ledger(&mut self.ledger, &lines[i], self.base_currency)?; } Ok(()) } @@ -7348,6 +7430,10 @@ fn replay_line( )); } } + // A call's frame (calls.rs): the gate decides which lines inside + // it reach here; the frame itself changes nothing. + "call.begun" => {} + "call.closed" => {} "account.added" => { let want = get_u64(p, "id")?; let account_type: AccountType = serde_json::from_value(p["account_type"].clone())?; @@ -8394,6 +8480,10 @@ fn apply_line_rows(conn: &Connection, line: &JournalLine) -> Result<(), StoreErr let p = &line.payload; match line.line_type.as_str() { "store.created" | "journal.tail_repaired" | "journal.format_set" => {} + // A call's frame (calls.rs): the replay gate decides which lines + // inside it count; the frame itself changes nothing. + "call.begun" => {} + "call.closed" => {} "account.added" => { conn.execute( "INSERT INTO accounts(id, code, name, type, parent, placeholder, currency) VALUES (?,?,?,?,?,?,?)", @@ -9388,8 +9478,10 @@ fn file_name_of(path: &Path) -> String { pub(crate) fn fresh_projection(lines: &[JournalLine]) -> Result { let conn = Connection::open_in_memory()?; Store::migrate(&conn)?; - for line in lines { - apply_line_to_sqlite(&conn, line)?; + // Only the lines that count (calls.rs). + let (released, _) = calls::gate_all(lines)?; + for &i in &released { + apply_line_to_sqlite(&conn, &lines[i])?; } Ok(conn) } diff --git a/crates/ledger-store/tests/calls.rs b/crates/ledger-store/tests/calls.rs new file mode 100644 index 00000000..58f340d6 --- /dev/null +++ b/crates/ledger-store/tests/calls.rs @@ -0,0 +1,416 @@ +//! Every write a tool makes is one transaction that happens once (plan +//! P15 2a, D-88, D-89; WB-format-8 to WB-format-12): a call's lines are +//! framed by `call.begun` and `call.closed`, count only when the closing +//! line says `ok`, and a call that failed or never closed builds nothing. +//! +//! The tests encode the law: a crash at any point of a call leaves the +//! whole call or none of it, in the ledger and in the projection; a +//! failed call is on the record and builds nothing; a replay of any +//! prefix that ends inside a call equals the replay of the prefix before +//! it; a repeated key finds the first answer; books that have not +//! declared the feature take no call and still read. + +use chrono::NaiveDate; +use ledger_core::{AccountType, Currency, Ledger, Money, Side}; +use ledger_store::calls::{CallEnd, CallId, CallOutcome, begun_of, closed_of}; +use ledger_store::{JOURNAL_FILE, JournalFormat, Snapshot, Store, StoreError}; +use rust_decimal::Decimal; +use serde_json::Value; +use std::path::Path; + +fn d(y: i32, m: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(y, m, day).unwrap() +} + +fn money(units: i64) -> Money { + Money::new(Decimal::from(units), Currency::USD) +} + +fn id(key: &str) -> CallId { + CallId { + token: "token-1".into(), + tool: "books.draft_entry".into(), + key: key.into(), + args: "a".repeat(64), + } +} + +fn lines_of(dir: &Path) -> Vec { + ledger_store::journal::read_and_verify_journal(&dir.join(JOURNAL_FILE)).unwrap() +} + +fn types_of(dir: &Path) -> Vec { + lines_of(dir).into_iter().map(|l| l.line_type).collect() +} + +/// Books with a chart, in this version's format, and the number of lines +/// their journal holds. +fn books(dir: &Path) -> Store { + let mut s = Store::create(dir, Currency::USD).unwrap(); + s.add_account("1000", "Bank", AccountType::Asset, None, false) + .unwrap(); + s.add_account("3000", "Capital", AccountType::Equity, None, false) + .unwrap(); + s +} + +/// One step of a call: a draft with two lines. +fn draft(s: &mut Store, what: &str) { + let e = s.create_entry(d(2026, 1, 5), what).unwrap(); + let bank = s.ledger().chart().find_by_code("1000").unwrap().id; + let capital = s.ledger().chart().find_by_code("3000").unwrap().id; + s.add_line(e, bank, Side::Debit, money(10)).unwrap(); + s.add_line(e, capital, Side::Credit, money(10)).unwrap(); +} + +fn same_books(a: &Ledger, b: &Ledger) { + assert_eq!(a.differs_from(b), Vec::<&str>::new()); +} + +#[test] +fn a_call_is_framed_and_its_answer_kept_by_key() { + let tmp = tempfile::tempdir().unwrap(); + let mut s = books(tmp.path()); + let before = lines_of(tmp.path()).len(); + s.begin_call(id("key-aaaa-1")).unwrap(); + draft(&mut s, "Rent"); + s.close_call(CallEnd::Done(r#"{"entry_id":1}"#)).unwrap(); + let lines = lines_of(tmp.path()); + // begun, entry.created, two lines, closed. + assert_eq!(lines.len(), before + 5); + assert_eq!(lines[before].line_type, "call.begun"); + assert_eq!(begun_of(&lines[before]).unwrap().key, "key-aaaa-1"); + let closed = closed_of(lines.last().unwrap()).unwrap(); + assert_eq!(closed.outcome, CallOutcome::Ok); + assert_eq!(closed.first_seq, Some(lines[before].seq)); + assert_eq!(closed.last_seq, Some(lines.last().unwrap().seq - 1)); + assert_eq!(closed.answer.as_deref(), Some(r#"{"entry_id":1}"#)); + let kept = s.recorded_call("token-1", "key-aaaa-1").unwrap(); + assert_eq!(kept.answer, r#"{"entry_id":1}"#); + assert_eq!(kept.args, "a".repeat(64)); + // Scoped to the token: another token has not used this key. + assert!(s.recorded_call("token-2", "key-aaaa-1").is_none()); + s.verify().unwrap(); + // A restart rebuilds the table from the journal alone. + drop(s); + let s = Store::open(tmp.path()).unwrap(); + assert_eq!( + s.recorded_call("token-1", "key-aaaa-1").unwrap().answer, + r#"{"entry_id":1}"# + ); + s.verify().unwrap(); +} + +#[test] +fn a_call_that_wrote_nothing_is_only_a_closing_line() { + let tmp = tempfile::tempdir().unwrap(); + let mut s = books(tmp.path()); + let before = lines_of(tmp.path()).len(); + s.begin_call(id("key-aaaa-2")).unwrap(); + s.close_call(CallEnd::Done(r#"{"ok":true}"#)).unwrap(); + let lines = lines_of(tmp.path()); + assert_eq!(lines.len(), before + 1); + let closed = closed_of(&lines[before]).unwrap(); + assert_eq!((closed.first_seq, closed.last_seq), (None, None)); + assert!(s.recorded_call("token-1", "key-aaaa-2").is_some()); + // A failed call that wrote nothing leaves no line at all. + s.begin_call(id("key-aaaa-3")).unwrap(); + s.close_call(CallEnd::Failed("refused")).unwrap(); + assert_eq!(lines_of(tmp.path()).len(), before + 1); + assert!(s.recorded_call("token-1", "key-aaaa-3").is_none()); +} + +#[test] +fn a_failed_call_is_on_the_record_and_builds_nothing() { + let tmp = tempfile::tempdir().unwrap(); + let mut s = books(tmp.path()); + let committed = s.ledger().clone(); + s.begin_call(id("key-aaaa-4")).unwrap(); + draft(&mut s, "Half"); + // What the call can see while it runs. + assert_ne!(s.ledger().differs_from(&committed), Vec::<&str>::new()); + s.close_call(CallEnd::Failed("it went wrong")).unwrap(); + // Live: the lines did not count, in memory or in the projection. + same_books(s.ledger(), &committed); + s.verify().unwrap(); + // On the record: the lines, then a closing line that says failed. + let lines = lines_of(tmp.path()); + let closed = closed_of(lines.last().unwrap()).unwrap(); + assert_eq!(closed.outcome, CallOutcome::Failed); + assert_eq!(closed.error.as_deref(), Some("it went wrong")); + assert!(lines.iter().any(|l| l.line_type == "entry.created")); + // A failed key is free again: nothing happened under it. + assert!(s.recorded_call("token-1", "key-aaaa-4").is_none()); + // Books go on: the next call's ids do not collide with the failed one's. + s.begin_call(id("key-aaaa-5")).unwrap(); + draft(&mut s, "Whole"); + s.close_call(CallEnd::Done("{}")).unwrap(); + s.verify().unwrap(); + // A restart builds the same books. + let live = s.ledger().clone(); + drop(s); + let s = Store::open(tmp.path()).unwrap(); + same_books(s.ledger(), &live); + s.verify().unwrap(); +} + +/// A call of every kind of step, by how far it got. +fn steps() -> Vec> { + vec![ + Box::new(|s| { + s.create_entry(d(2026, 1, 5), "One").unwrap(); + }), + Box::new(|s| { + let bank = s.ledger().chart().find_by_code("1000").unwrap().id; + s.add_line(1, bank, Side::Debit, money(10)).unwrap(); + }), + Box::new(|s| { + let capital = s.ledger().chart().find_by_code("3000").unwrap().id; + s.add_line(1, capital, Side::Credit, money(10)).unwrap(); + }), + Box::new(|s| { + s.add_account("4000", "Sales", AccountType::Revenue, None, false) + .unwrap(); + }), + ] +} + +#[test] +fn a_crash_at_each_point_of_a_call_leaves_the_whole_call_or_none_of_it() { + let n = steps().len(); + for k in 0..=n { + let tmp = tempfile::tempdir().unwrap(); + let mut s = books(tmp.path()); + let committed = s.ledger().clone(); + let seq_before = s.head().0; + s.begin_call(id("key-crash-01")).unwrap(); + for step in steps().iter().take(k) { + step(&mut s); + } + // The process dies here: no closing line, no clean shutdown. + drop(s); + let reopened = Store::open(tmp.path()).unwrap(); + same_books(reopened.ledger(), &committed); + reopened.verify().unwrap(); + assert!(reopened.recorded_call("token-1", "key-crash-01").is_none()); + let types = types_of(tmp.path()); + if k == 0 { + // It had written nothing: there is nothing to close. + assert_eq!(reopened.head().0, seq_before); + } else { + // The record says what became of its lines. + let last = lines_of(tmp.path()).pop().unwrap(); + let closed = closed_of(&last).unwrap(); + assert_eq!(closed.outcome, CallOutcome::Unfinished, "{types:?}"); + assert_eq!(closed.first_seq, Some(seq_before + 1)); + } + // And the books take the next call as if nothing had happened. + let mut s = reopened; + s.begin_call(id("key-crash-02")).unwrap(); + for step in steps().iter().take(1) { + step(&mut s); + } + s.close_call(CallEnd::Done("{}")).unwrap(); + s.verify().unwrap(); + let live = s.ledger().clone(); + drop(s); + let s = Store::open(tmp.path()).unwrap(); + same_books(s.ledger(), &live); + } + // And a call that closed is whole, however the process ends after. + let tmp = tempfile::tempdir().unwrap(); + let mut s = books(tmp.path()); + s.begin_call(id("key-crash-03")).unwrap(); + for step in steps().iter() { + step(&mut s); + } + s.close_call(CallEnd::Done("{}")).unwrap(); + let live = s.ledger().clone(); + drop(s); + let s = Store::open(tmp.path()).unwrap(); + same_books(s.ledger(), &live); + assert!(s.ledger().chart().find_by_code("4000").is_some()); +} + +#[test] +fn a_replay_of_any_prefix_inside_a_call_is_the_replay_of_the_prefix_before_it() { + let tmp = tempfile::tempdir().unwrap(); + let mut s = books(tmp.path()); + s.begin_call(id("key-prefix-1")).unwrap(); + for step in steps().iter() { + step(&mut s); + } + s.close_call(CallEnd::Done("{}")).unwrap(); + s.begin_call(id("key-prefix-2")).unwrap(); + draft(&mut s, "Second"); + s.close_call(CallEnd::Failed("no")).unwrap(); + s.begin_call(id("key-prefix-3")).unwrap(); + draft(&mut s, "Third"); + s.close_call(CallEnd::Done("{}")).unwrap(); + drop(s); + let raw = std::fs::read(tmp.path().join(JOURNAL_FILE)).unwrap(); + let lines = lines_of(tmp.path()); + let mut ends = Vec::new(); + let mut at = 0usize; + for line in raw.split_inclusive(|&b| b == b'\n') { + at += line.len(); + ends.push(at); + } + // The books as the viewer reads the journal cut after line `i`. + let work = tempfile::tempdir().unwrap(); + let books_after = |i: usize| { + std::fs::write(work.path().join(JOURNAL_FILE), &raw[..ends[i]]).unwrap(); + Snapshot::load(work.path()).unwrap().ledger().clone() + }; + let mut begun: Option = None; + let mut inside = 0; + for (i, l) in lines.iter().enumerate() { + match l.line_type.as_str() { + "call.begun" => begun = Some(i), + "call.closed" => { + let first = begun.take().expect("a close follows its begin"); + let after = books_after(i); + let before = books_after(first); + let closed = closed_of(l).unwrap(); + if closed.outcome == CallOutcome::Ok { + // Committed: the call's lines count, all at once. + assert_ne!(after.differs_from(&before), Vec::<&str>::new()); + } else { + // Failed: on the record, and not one of its lines counts. + same_books(&after, &before); + } + } + _ => { + if let Some(first) = begun { + // Any prefix that ends inside a call. + inside += 1; + same_books(&books_after(i), &books_after(first)); + } + } + } + } + assert!(inside >= 8, "the cuts inside a call were tried: {inside}"); +} + +#[test] +fn books_that_have_not_declared_the_feature_take_no_call_and_still_read() { + let tmp = tempfile::tempdir().unwrap(); + { + // Books as an older version made them: format 1, no feature. + let mut s = + Store::create_in_format(tmp.path(), Currency::USD, &JournalFormat::default()).unwrap(); + s.add_account("1000", "Bank", AccountType::Asset, None, false) + .unwrap(); + s.add_account("3000", "Capital", AccountType::Equity, None, false) + .unwrap(); + } + let mut s = Store::open(tmp.path()).unwrap(); + let before = s.head(); + assert!(!s.takes_calls()); + assert!(s.books_id().is_none()); + let refused = s.begin_call(id("key-old-0001")).unwrap_err(); + assert!(matches!(refused, StoreError::FormatUpgradePending { .. })); + let words = refused.to_string(); + assert!(words.contains("nothing can be written"), "{words}"); + // Nothing was written, and the books read as ever. + assert_eq!(s.head(), before); + assert!(s.ledger().chart().find_by_code("1000").is_some()); + s.verify().unwrap(); + // The owner's go-ahead: the format upgrade. After it, calls are taken, + // and the books have the id the upgrade gave them. + s.upgrade_format().unwrap().expect("waited for an upgrade"); + assert!(s.takes_calls()); + let given = s.books_id().expect("the upgrade gives an id").to_string(); + assert_eq!(given.len(), 32); + s.begin_call(id("key-old-0002")).unwrap(); + draft(&mut s, "After"); + s.close_call(CallEnd::Done("{}")).unwrap(); + drop(s); + // The id is in the journal, so it is the same after a restart and for + // a viewer. + let s = Store::open(tmp.path()).unwrap(); + assert_eq!(s.books_id(), Some(given.as_str())); + assert_eq!(Snapshot::load(tmp.path()).unwrap().books_id(), Some(given)); +} + +#[test] +fn new_books_are_born_with_an_id_and_no_two_share_one() { + let a = tempfile::tempdir().unwrap(); + let b = tempfile::tempdir().unwrap(); + let sa = Store::create(a.path(), Currency::USD).unwrap(); + let sb = Store::create(b.path(), Currency::USD).unwrap(); + let (ia, ib) = ( + sa.books_id().unwrap().to_string(), + sb.books_id().unwrap().to_string(), + ); + assert_ne!(ia, ib); + assert_eq!( + lines_of(a.path())[0].payload["books_id"].as_str(), + Some(ia.as_str()) + ); + // Upgrading books that have one gives them no second. + drop(sa); + let mut sa = Store::open(a.path()).unwrap(); + assert!(sa.upgrade_format().unwrap().is_none()); + assert_eq!(sa.books_id(), Some(ia.as_str())); +} + +#[test] +fn a_viewer_applies_a_call_only_when_it_closes() { + let tmp = tempfile::tempdir().unwrap(); + let mut s = books(tmp.path()); + let mut snap = Snapshot::load(tmp.path()).unwrap(); + let committed = snap.ledger().clone(); + s.begin_call(id("key-view-01")).unwrap(); + draft(&mut s, "Viewed"); + // Lines are on disk, the call is not closed: the viewer holds none. + assert!(snap.refresh().unwrap() > 0); + same_books(snap.ledger(), &committed); + s.close_call(CallEnd::Done("{}")).unwrap(); + snap.refresh().unwrap(); + assert_ne!(snap.ledger().differs_from(&committed), Vec::<&str>::new()); + same_books(snap.ledger(), s.ledger()); +} + +#[test] +fn a_frame_that_does_not_close_what_it_follows_is_corrupt() { + let tmp = tempfile::tempdir().unwrap(); + let mut s = books(tmp.path()); + s.begin_call(id("key-bad-0001")).unwrap(); + draft(&mut s, "Framed"); + s.close_call(CallEnd::Done("{}")).unwrap(); + drop(s); + // A closing line whose range is not the frame's: rewritten with a + // valid chain, so only the frame rule can refuse it. + let mut lines = lines_of(tmp.path()); + let last = lines.len() - 1; + lines[last].payload["last_seq"] = Value::from(1); + let mut prev = lines[last - 1].clone(); + let _ = &mut prev; + let bad = tempfile::tempdir().unwrap(); + let mut w = ledger_store::JournalWriter::open(&bad.path().join(JOURNAL_FILE)).unwrap(); + for l in &lines { + w.append(&l.line_type, l.payload.clone()).unwrap(); + } + let err = Store::open(bad.path()).err().expect("refused"); + assert!( + matches!(err, StoreError::JournalCorrupt(_)), + "{err} should be corrupt" + ); +} + +#[test] +fn a_call_cannot_begin_inside_another_or_after_a_failed_close() { + let tmp = tempfile::tempdir().unwrap(); + let mut s = books(tmp.path()); + s.begin_call(id("key-twice-01")).unwrap(); + assert!(matches!( + s.begin_call(id("key-twice-02")), + Err(StoreError::CallRefused(_)) + )); + s.close_call(CallEnd::Failed("x")).unwrap(); + assert!(matches!( + s.close_call(CallEnd::Done("{}")), + Err(StoreError::CallRefused(_)) + )); +} diff --git a/crates/ledger-store/tests/format.rs b/crates/ledger-store/tests/format.rs index c78d79d4..97587e28 100644 --- a/crates/ledger-store/tests/format.rs +++ b/crates/ledger-store/tests/format.rs @@ -994,8 +994,12 @@ fn p3_features_wait_for_the_upgrade_and_are_declared_once() { .collect(); let current = ledger_store::format::current(); assert_eq!(kinds[0].0, FORMAT_SET); + // The upgrade of older books also gives them their id (calls.rs). + let mut declared = kinds[0].1.clone(); + let books_id = declared.as_object_mut().unwrap().remove("books_id"); + assert_eq!(books_id.and_then(|v| v.as_str().map(str::len)), Some(32)); assert_eq!( - kinds[0].1, + declared, json!({"format": current.format, "features": current.features}) ); assert_eq!(kinds[1].0, "account.renamed"); @@ -1122,8 +1126,12 @@ fn a_daily_schedule_waits_for_its_feature_and_an_older_reader_stops_there() { assert_eq!(journal[n - 1]["payload"]["convention"], "daily"); assert_eq!(journal[n - 2]["type"], FORMAT_SET); let current = ledger_store::format::current(); + // The upgrade of older books also gives them their id (calls.rs). + let mut declared = journal[n - 2]["payload"].clone(); + let books_id = declared.as_object_mut().unwrap().remove("books_id"); + assert_eq!(books_id.and_then(|v| v.as_str().map(str::len)), Some(32)); assert_eq!( - journal[n - 2]["payload"], + declared, json!({"format": current.format, "features": current.features}) ); store.run_schedules(day(2026, 5, 31)).unwrap(); diff --git a/crates/ledger-store/tests/format_upgrade.rs b/crates/ledger-store/tests/format_upgrade.rs index 2613226b..fba96168 100644 --- a/crates/ledger-store/tests/format_upgrade.rs +++ b/crates/ledger-store/tests/format_upgrade.rs @@ -211,7 +211,11 @@ fn a_change_needing_the_new_format_waits_for_the_upgrade() { let after = lines(&dir); assert_eq!(after.len(), n + 1, "one line"); assert_eq!(after[n]["type"], FORMAT_SET); - assert_eq!(after[n]["payload"], this_versions_declaration()); + // The declaration also gives older books their id (calls.rs, plan 6a). + let mut declared = after[n]["payload"].clone(); + let books_id = declared.as_object_mut().unwrap().remove("books_id"); + assert_eq!(books_id.and_then(|v| v.as_str().map(str::len)), Some(32)); + assert_eq!(declared, this_versions_declaration()); assert!(journal(&dir).starts_with(&mid), "nothing before it changed"); assert_eq!( ledger_core::reports::snapshot(s.ledger()).unwrap(), diff --git a/docs/receipt-store.md b/docs/receipt-store.md index f3d7a7e3..d9ce4134 100644 --- a/docs/receipt-store.md +++ b/docs/receipt-store.md @@ -196,6 +196,20 @@ a backup is then proven where it lands, by a drill (docs/mcp-interface.md, `method` ({model?, reasoning_effort?, adversarial?, verifier_agents?}) is that client's own word. Whether a claim counts is never journaled: it is derived against `policy.attestation_bar` when asked. +- **A tool call is a frame, not a record** (plan P15 2a, D-88, feature + `call_transactions`): a call that writes lines is framed by + `call.begun {tool, token, key, args}` before its first line and + `call.closed {tool, token, key, args, outcome, first_seq?, last_seq?, + answer?, error?}` after its last. The lines between count only when + `outcome` is `ok` (then `answer` is the text of the answer given, kept + so a repeat of `key` returns it); `failed` and `unfinished` (written by + the open that finds a call that never closed) say the lines in the frame + never count, in any replay. A call that wrote no line is a closing line + alone. A line outside a frame applies as ever, so every journal written + before the feature replays as it was. `store.created` carries + `books_id` (the books' own unique id) in books made since the feature; + older books are given one in the `journal.format_set` of their upgrade. + Neither frame line moves the audit's figure head. - The store is policy-free: it records attachments faithfully. Whether a posting *requires* a receipt is decided by the MCP layer's receipt policy (`docs/mcp-interface.md`), which reads the `attachments` table. diff --git a/docs/spec/claims/format.md b/docs/spec/claims/format.md index eddf0fdf..e3091de0 100644 --- a/docs/spec/claims/format.md +++ b/docs/spec/claims/format.md @@ -171,9 +171,10 @@ in their second line, so they wait for nothing. Books an older version wrote declare less (format 1, written before the gate, declares nothing): they *wait for a format upgrade*, which is a fact of their journal alone (`JournalFormat::upgrade`). They open and replay as they are, byte for byte; -everything that needs nothing new is written as ever; a write that would need -the newer format or a feature they haven't declared is refused before anything -is journaled (`StoreError::FormatUpgradePending`, guard +everything that needs nothing new is written as ever, except that since D-88 +and D-89 they take no tool write at all (WB-format-11); a write that would +need the newer format or a feature they haven't declared is refused before +anything is journaled (`StoreError::FormatUpgradePending`, guard `format_upgrade_pending`), never declared on the way. Every setting key and tax category an earlier version didn't read needs a feature (`format::setting_feature`, `format::tax_category_feature`: the P3 data-safety @@ -219,6 +220,98 @@ others are there; none is deleted for being stale. --- +**WB-format-8 Every write a tool makes is one transaction in the journal.** +(The owner, 2026-11-20, D-88: "Writes have to be TRANSACTIONAL ALWAYS! You +can record a failed transaction.") A tool call that writes frames its journal +lines: `call.begun { tool, token, key, args }` just before its first line, and +`call.closed { tool, token, key, args, outcome, first_seq, last_seq, answer | +error }` when it is over, `outcome` being `ok` (the answer given is `answer`, +kept as text so a repeat returns it byte for byte), `failed`, or `unfinished`. +A call that wrote no line is only its closing line. The lines between a begin +and its close count only when the close says `ok`: that is how a reader tells +a complete call from an incomplete one. Every replay (opening the books, the +viewer, verify, rebuild, the projection a restart catches up) goes through +one rule (`CallGate`): a line outside a frame applies at once (every line +before the books declared `call_transactions`, and the owner's own acts: the +format declaration, a repaired tail); a line inside a frame waits, and is +applied with its closing line when that says `ok`, and never when it says +`failed` or `unfinished` or when no closing line follows. So no state is built +from half a call, and a replay of any prefix that ends inside a call equals the +replay of the prefix before it. A close must name the frame it ends (its +`first_seq` is the begin line's, its `last_seq` the line before it); a frame +that begins inside another, a close with no frame, or a close that does not +match is a corrupt journal. The projection keeps a call's changes in one +SQLite transaction, released only after the `ok` closing line is on disk. When +the books are opened and the journal's last call never closed, its lines are +not applied, it is closed `unfinished` before anything else is written, and a +projection that holds its lines is rebuilt. The envelope `{seq, ts, type, +payload, prev}` is untouched: the feature adds two line types +(`call_transactions`, WB-format-2) and nothing else. Calls take turns: the +server runs one write call at a time, so a call's lines are one run in the +journal. `books.import_bank_csv` is one transaction like every other write +(plan P15 6a). The reader's view: a viewer reads a call's lines only once its +closing line is read; a reader of the memory sees a call's lines for the +moment between its tool finishing and its closing line (never after a +restart). +*Enforced:* `ledger_store::calls` (`CallGate`, `gate_all`, `closed_of`, `begun_of`, `Store::begin_call`, `Store::close_call`), `Store::open`, `Store::verify`, `Store::rebuild`, `Snapshot::refresh`, `format::CALL_TRANSACTIONS`, ledger-mcp `SharedStore::write_turn`. +*Checked:* `ledger-store` `tests/calls.rs` (`a_call_is_framed_and_its_answer_kept_by_key`, `a_call_that_wrote_nothing_is_only_a_closing_line`, `a_crash_at_each_point_of_a_call_leaves_the_whole_call_or_none_of_it`, `a_replay_of_any_prefix_inside_a_call_is_the_replay_of_the_prefix_before_it`, `a_viewer_applies_a_call_only_when_it_closes`, `a_frame_that_does_not_close_what_it_follows_is_corrupt`, `a_call_cannot_begin_inside_another_or_after_a_failed_close`), the unit test `call_transactions_is_its_own_feature` in `format.rs`, `tests/format.rs` (`every_event_the_store_replays_passes_the_gate`); `ledger-cli` `tests/call_transactions.rs` (`a_call_is_one_frame_in_the_journal_closed_with_its_answer`, `the_import_is_one_transaction`). + +**WB-format-9 Every write call carries a request key, and a repeat of it +writes nothing.** Every tool that can change the books (no `readOnlyHint`; +86 of the 140) takes a required `request_key`, 8 to 128 characters of plain +text, which the agent makes up, new for each action. A write without a usable +key is refused in words before it runs; a preview (a confirmed tool called +without `confirmed: true`) writes nothing and needs none. The key is taken out +of the arguments before the tool sees them. A repeat of a (token, key) whose +call committed, with the same tool and arguments, returns that call's answer +as it was given, writes nothing, and is recorded in the access log as +`repeat`; with other arguments or another tool it is refused in words as a +misuse of the key, and nothing is changed. A key is the token's own: two +tokens with one key are two keys. The key table is rebuilt at every open from +the `ok` closing lines alone. A repeat that arrives while its original is +still running waits for it (calls take turns) and gets its answer. An answer +that holds a full TIN is kept masked, so its repeat returns it masked +(BS-partner-2: no journal line holds one). +*Enforced:* ledger-mcp `calls::is_write_call`, `calls::key_problem`, `calls::begin`, `calls::close`, `calls::add_key_to_schema`, `Store::recorded_call`, `Keys`. +*Checked:* `ledger-cli` `tests/call_transactions.rs` (`a_repeat_of_a_key_returns_the_first_answer_and_writes_nothing`, `the_same_key_for_another_request_is_refused_in_words`, `a_write_without_a_usable_key_is_not_run`, `every_tool_that_can_write_asks_for_a_key_and_no_other_does`); `ledger-store` `tests/calls.rs` (`a_call_is_framed_and_its_answer_kept_by_key`). + +**WB-format-10 A failed write is on the record, and builds nothing.** A call +that answers with an error, is stopped by a close, or fails any other way +rolls back: if it had written lines, its closing line says `failed` with how, +its lines are never applied, the projection's changes are rolled back and the +live ledger is rebuilt from the journal without them; if it had written none, +the access log has it (as every call has) and the journal has nothing. A +failed call leaves its key unused: nothing happened under it, so the corrected +call may use it. A call whose closing line cannot be written has not +committed; the store takes no further write, and the books server stops, as +it does when an access record cannot be written. +*Enforced:* `Store::close_call`, ledger-mcp `calls::answered_ok`, `calls::close`. +*Checked:* `ledger-store` `tests/calls.rs` (`a_failed_call_is_on_the_record_and_builds_nothing`, `a_call_that_wrote_nothing_is_only_a_closing_line`); `ledger-cli` `tests/call_transactions.rs` (`a_failed_write_leaves_the_books_and_its_key_as_they_were`). + +**WB-format-11 Books that have not declared `call_transactions` take no +write.** (The owner, 2026-11-20, D-89.) This replaces WB-format-3's "everything +that needs nothing new is written as ever" for writes: from the release that +carries the feature, books an older version wrote are opened and read as +ever, and every write call is refused, before it runs, with the upgrade remedy +and the words "nothing can be written", until the owner's go-ahead (the format +upgrade, WB-format-3). So there is one way a write can happen, the one that is +proved. The Store's own commands, which the owner's acts and the tests call +directly outside a call, are unchanged; `Store::begin_call` refuses. +*Enforced:* `Store::ensure_takes_calls`, `Store::begin_call`, `StoreError::FormatUpgradePending`, ledger-mcp `calls::begin`. +*Checked:* `ledger-store` `tests/calls.rs` (`books_that_have_not_declared_the_feature_take_no_call_and_still_read`), the unit test `call_transactions_is_its_own_feature` in `format.rs`; `ledger-cli` `tests/format_upgrade.rs` (`books_p2_served_cut_over_whole`, `format_upgrade_waits_for_consent`, `documents_v2_refused_until_consent`). + +**WB-format-12 Every set of books has a unique id.** (Plan P15 6a: the hash of +the journal's first line, which carries a currency and a time to the second, +told two sets of books apart badly.) Books made since `call_transactions` are +born with `books_id`, 128 random bits in hex, in their `store.created` line. +Older books get one with the format upgrade: the `journal.format_set` that +declares `call_transactions` carries `books_id` when the books have none. The +id is read from the journal alone (`books_id_of`), so it is the same after a +restart and for the viewer, and a restored backup keeps it. Books that have +had neither yet have no id (`Store::books_id` is None). +*Enforced:* `Store::create`, `Store::declare_journal_format`, `Store::books_id`, `Snapshot::books_id`, `books_id_of`. +*Checked:* `ledger-store` `tests/calls.rs` (`new_books_are_born_with_an_id_and_no_two_share_one`, `books_that_have_not_declared_the_feature_take_no_call_and_still_read`), `tests/format.rs` and `tests/format_upgrade.rs` (the upgrade's declaration holds the id). + ## B-34 The QuickBooks Desktop file (IIF): plain ASCII, every entry through as_of, closes left out, classes carried **bookspec:** `BS-format-2` diff --git a/fuzz/fuzz_targets/fuzz_store_replay.rs b/fuzz/fuzz_targets/fuzz_store_replay.rs index 28693260..37baad7a 100644 --- a/fuzz/fuzz_targets/fuzz_store_replay.rs +++ b/fuzz/fuzz_targets/fuzz_store_replay.rs @@ -47,6 +47,7 @@ const TYPES: &[&str] = &[ "entry.draft_state_set", "entry.draft_discarded", "convention.source_revised", "decision.source_revised", "open_item.source_revised", "audit.run", "receipt.attested", "entry.reviewed", "period.attested", + "call.begun", "call.closed", // Merged 2026-10-28 (S7, P6): every type EVENT_TYPES names. ]; @@ -69,6 +70,7 @@ const FIELDS: &[&str] = &[ "tax_basis_723", "depreciable_basis", "built_in_gain_704c", "on", "convention", "status", "party_id", "started_on", "ended_on", "links", "notes", "projects", "via", "by", "to", "reference", "note", "state", + "tool", "token", "args", "outcome", "first_seq", "last_seq", "answer", "error", "books_id", "through", "through_seq", "scope", "program_version", "tb_hash", "findings_sha256", "workpaper_attachment", "workpaper_pdf", "at", "amount_checked", "date_checked", "disagrees", "audit_run_id", "period_id", "verifier_agents", "reasoning_effort", From e542319e63020b47028282eac2a329dbddb6621e Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 09:43:52 -0700 Subject: [PATCH 2/6] feat(mcp): every write call is one transaction with a request key (P15 T1, D-88, D-89) Accounting reasoning: these are financial books reached over the internet, where a request is retried. A write whose answer is lost and then sent again must not post twice, a call half done must not be left looking done, and a failed write must be on the record. Every tool that can change the books (83 of the 140: three that only read what is sealed and may answer with a TIN are reads) takes a required `request_key`, added to its schema in tools/list and taken out of the arguments before the tool runs, so no tool, preview digest or check changes. A write without a usable key is refused in words. Write calls take turns, and each runs as one transaction of the store: opened (or answered from the books if its key committed: the same tool and arguments return the first answer and write nothing; other arguments are refused as a misuse of the key; the access log says `repeat`), then closed with its answer if it answered ok, or rolled back and closed `failed` if it errored, failed or was stopped by a close. Books an older version wrote take no write at all until the owner's go-ahead (D-89): every write is refused with the upgrade remedy; reads work as ever. `books.import_bank_csv` is one transaction like the rest. The handbook, docs/mcp-interface.md, the claims (WB-format-8 to 12, and WB-format-3 amended for D-89) and docs/parity.md say so. Tests that wrote to old books through the tools now assert the refusal and write after the upgrade; the shared wire helpers add a fresh key to every tool call (the journal helpers leave the call frames out, as they left out nothing before), so no other test changed. The store-level `_waits_for_` tests still check each feature's own gate. No figure and no golden moved. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/tests/backups.rs | 8 +- crates/ledger-cli/tests/book_open_close.rs | 20 +- crates/ledger-cli/tests/call_transactions.rs | 265 +++++++++++++++++ crates/ledger-cli/tests/common/mod.rs | 67 ++++- crates/ledger-cli/tests/format_upgrade.rs | 210 ++++++++------ crates/ledger-cli/tests/local_server.rs | 6 +- crates/ledger-cli/tests/mcp_journeys.rs | 84 +++--- crates/ledger-cli/tests/open_while_held.rs | 5 +- crates/ledger-cli/tests/spec_1099.rs | 33 ++- crates/ledger-cli/tests/spec_assets.rs | 5 +- crates/ledger-cli/tests/spec_attachments.rs | 5 +- crates/ledger-cli/tests/spec_mcp.rs | 5 +- crates/ledger-cli/tests/spec_parties.rs | 5 +- crates/ledger-cli/tests/spec_party_totals.rs | 29 +- crates/ledger-cli/tests/spec_projects.rs | 42 +-- crates/ledger-cli/tests/spec_vault.rs | 5 +- crates/ledger-mcp/handbook/format-upgrade.md | 8 +- crates/ledger-mcp/src/calls.rs | 290 +++++++++++++++++++ crates/ledger-mcp/src/local.rs | 6 +- crates/ledger-mcp/src/server.rs | 102 ++++++- crates/ledger-store/src/store.rs | 7 + crates/ledger-store/tests/calls.rs | 20 +- docs/mcp-interface.md | 28 ++ docs/parity.md | 8 + docs/spec/claims/format.md | 7 +- 25 files changed, 1084 insertions(+), 186 deletions(-) create mode 100644 crates/ledger-cli/tests/call_transactions.rs create mode 100644 crates/ledger-mcp/src/calls.rs diff --git a/crates/ledger-cli/tests/backups.rs b/crates/ledger-cli/tests/backups.rs index 4928fa11..0d71ead9 100644 --- a/crates/ledger-cli/tests/backups.rs +++ b/crates/ledger-cli/tests/backups.rs @@ -248,7 +248,13 @@ async fn call(c: &Client, tool: &str, mut args: Value) -> Result } async fn call_once(c: &Client, tool: &str, args: Value) -> Result { - let args = args.as_object().cloned().unwrap_or_default(); + let mut args = args.as_object().cloned().unwrap_or_default(); + // The key every write call carries (D-88). + static NEXT_KEY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + args.entry("request_key").or_insert_with(|| { + let n = NEXT_KEY.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + json!(format!("backups-key-{}-{n}", std::process::id())) + }); let r = tokio::time::timeout( Duration::from_secs(60), c.call_tool(CallToolRequestParams::new(tool.to_string()).with_arguments(args)), diff --git a/crates/ledger-cli/tests/book_open_close.rs b/crates/ledger-cli/tests/book_open_close.rs index 9396f53d..74b392da 100644 --- a/crates/ledger-cli/tests/book_open_close.rs +++ b/crates/ledger-cli/tests/book_open_close.rs @@ -1083,7 +1083,8 @@ fn a_call_whose_answer_was_never_read_is_on_record_as_having_run() { let mut raw = raw::Raw::connect(&home, A); let body = json!({"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": { "name": "books.draft_entry", - "arguments": {"date": "2026-03-01", "description": "unread"}}}) + "arguments": {"date": "2026-03-01", "description": "unread", + "request_key": common::fresh_request_key()}}}) .to_string(); raw.start( "POST", @@ -1521,7 +1522,8 @@ fn a_stalled_mcp_body_cannot_hold_a_close_and_nothing_of_it_is_journaled() { let mut raw = raw::Raw::connect(&home, A); let body = json!({"jsonrpc": "2.0", "id": 9, "method": "tools/call", "params": { "name": "books.draft_entry", - "arguments": {"date": "2026-03-01", "description": "never finished"}}}) + "arguments": {"date": "2026-03-01", "description": "never finished", + "request_key": common::fresh_request_key()}}}) .to_string(); raw.start_inside( "POST", @@ -1645,7 +1647,8 @@ fn a_running_call_is_never_cut_when_the_grace_runs_out() { ); let mut raw = raw::Raw::connect(&home, A); let body = json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": { - "name": "books.attach_receipt", "arguments": {"upload_id": up}}}) + "name": "books.attach_receipt", + "arguments": {"upload_id": up, "request_key": common::fresh_request_key()}}}) .to_string(); raw.start( "POST", @@ -2171,7 +2174,8 @@ fn the_servers_own_close_cuts_stalled_requests_and_exits_zero_in_time() { let mut raw_call = raw::Raw::connect(&home, B); let body = json!({"jsonrpc": "2.0", "id": 9, "method": "tools/call", "params": { "name": "books.draft_entry", - "arguments": {"date": "2026-03-01", "description": "never finished"}}}) + "arguments": {"date": "2026-03-01", "description": "never finished", + "request_key": common::fresh_request_key()}}}) .to_string(); raw_call.start_inside( "POST", @@ -2623,9 +2627,11 @@ fn a_close_that_stops_git_in_a_commit_or_a_push_leaves_no_lock_and_the_next_back #[cfg(unix)] fn call_unanswered(home: &Home, w: &Wire, id: u64, tool: &str, args: Value) -> raw::Raw { let mut raw = raw::Raw::connect(home, A); - let body = json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": { - "name": tool, "arguments": args}}) - .to_string(); + let body = common::with_request_key( + &json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": { + "name": tool, "arguments": args}}) + .to_string(), + ); raw.start( "POST", "mcp", diff --git a/crates/ledger-cli/tests/call_transactions.rs b/crates/ledger-cli/tests/call_transactions.rs new file mode 100644 index 00000000..20801615 --- /dev/null +++ b/crates/ledger-cli/tests/call_transactions.rs @@ -0,0 +1,265 @@ +//! Every write through the tools is one transaction that happens exactly +//! once (plan P15 2a, D-88; WB-format-8 to WB-format-12), through the real +//! server as an agent reaches it. +//! +//! The law: a repeat of a request key posts nothing and returns the first +//! 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. + +use common::{Books, Wire, answer_of}; +use serde_json::{Value, json}; + +mod common; + +/// The journal's lines, parsed. +fn lines(books: &Books) -> Vec { + String::from_utf8(books.journal_raw()) + .unwrap() + .lines() + .map(|l| serde_json::from_str(l).unwrap()) + .collect() +} + +/// A `tools/call` with exactly these arguments, key or none. +fn call_exactly(w: &mut Wire, tool: &str, args: Value) -> Value { + let msg = json!({"jsonrpc": "2.0", "id": 4242, "method": "tools/call", + "params": {"name": tool, "arguments": args}}); + w.send_exactly(&msg.to_string()); + w.recv(common::TIMEOUT).expect("an answer") +} + +fn draft(key: &str, what: &str) -> Value { + json!({"date": "2026-03-01", "description": what, "no_party_reason": "test", + "request_key": key}) +} + +#[test] +fn a_repeat_of_a_key_returns_the_first_answer_and_writes_nothing() { + let books = Books::new("calls-repeat"); + let mut w = books.session("test"); + let first = call_exactly( + &mut w, + "books.draft_entry", + draft("key-repeat-0001", "Rent"), + ); + let first = answer_of(&first).unwrap(); + let after_first = books.journal_raw(); + // The answer was lost; the agent asks again, the same call, the same key. + let again = call_exactly( + &mut w, + "books.draft_entry", + draft("key-repeat-0001", "Rent"), + ); + assert_eq!(answer_of(&again).unwrap(), first); + assert_eq!(books.journal_raw(), after_first, "a repeat writes nothing"); + let drafts = answer_of(&w.call("books.list_drafts", json!({}))).unwrap(); + assert_eq!( + drafts["drafts"].as_array().map(Vec::len), + Some(1), + "{drafts}" + ); + // Across a restart: the key is in the journal. + books.restart(); + let mut w = books.session("test"); + let later = call_exactly( + &mut w, + "books.draft_entry", + draft("key-repeat-0001", "Rent"), + ); + assert_eq!(answer_of(&later).unwrap(), first); + assert_eq!(books.journal_raw(), after_first, "nor after a restart"); +} + +#[test] +fn the_same_key_for_another_request_is_refused_in_words() { + let books = Books::new("calls-misuse"); + let mut w = books.session("test"); + answer_of(&call_exactly( + &mut w, + "books.draft_entry", + draft("key-misuse-0001", "Rent"), + )) + .unwrap(); + let before = books.journal_raw(); + let refused = call_exactly( + &mut w, + "books.draft_entry", + draft("key-misuse-0001", "Something else"), + ); + let why = answer_of(&refused).unwrap_err(); + assert!(why.contains("already used"), "{why}"); + assert!(why.contains("nothing was changed"), "{why}"); + assert_eq!(books.journal_raw(), before); +} + +#[test] +fn a_write_without_a_usable_key_is_not_run() { + let books = Books::new("calls-nokey"); + let mut w = books.session("test"); + let before = books.journal_raw(); + let mut bare = draft("x", "No key"); + bare.as_object_mut().unwrap().remove("request_key"); + for (what, args) in [ + ("no key", bare), + ("a short key", draft("short", "No key")), + ("a key that isn't text", { + let mut a = draft("x", "No key"); + a["request_key"] = json!(12345678); + a + }), + ] { + let r = call_exactly(&mut w, "books.draft_entry", args); + let why = answer_of(&r).unwrap_err(); + assert!(why.contains("request_key"), "{what}: {why}"); + assert!(why.contains("not run"), "{what}: {why}"); + } + assert_eq!(books.journal_raw(), before, "a refusal journals nothing"); + // A read needs none, and a preview (a confirmed tool, not confirmed) + // writes nothing and needs none. + answer_of(&call_exactly(&mut w, "books.chart", json!({}))).unwrap(); + let r = call_exactly(&mut w, "books.post_entry", json!({"entry_id": 1})); + let text = serde_json::to_string(&r).unwrap(); + assert!(!text.contains("request_key"), "{text}"); +} + +#[test] +fn a_failed_write_leaves_the_books_and_its_key_as_they_were() { + let books = Books::new("calls-failed"); + let mut w = books.session("test"); + let before = books.journal_raw(); + let mut bad = draft("key-failed-0001", "Bad date"); + bad["date"] = json!("not a date"); + let failed = call_exactly(&mut w, "books.draft_entry", bad); + assert!(answer_of(&failed).is_err(), "{failed}"); + assert_eq!( + books.journal_raw(), + before, + "a call that wrote nothing leaves no line" + ); + // Nothing happened under the key, so the corrected call may use it. + let fixed = call_exactly( + &mut w, + "books.draft_entry", + draft("key-failed-0001", "Good date"), + ); + answer_of(&fixed).unwrap(); +} + +#[test] +fn a_call_is_one_frame_in_the_journal_closed_with_its_answer() { + let books = Books::new("calls-frame"); + let mut w = books.session("test"); + let before = lines(&books).len(); + let out = call_exactly( + &mut w, + "books.draft_entry", + draft("key-frame-00001", "Framed"), + ); + let answer = answer_of(&out).unwrap(); + let all = lines(&books); + let call = &all[before..]; + assert_eq!(call.first().unwrap()["type"], "call.begun", "{call:?}"); + let closed = call.last().unwrap(); + assert_eq!(closed["type"], "call.closed"); + let p = &closed["payload"]; + assert_eq!(p["outcome"], "ok"); + assert_eq!(p["tool"], "books.draft_entry"); + assert_eq!(p["key"], "key-frame-00001"); + assert_eq!(p["first_seq"], call.first().unwrap()["seq"]); + assert_eq!( + p["last_seq"].as_u64().unwrap() + 1, + closed["seq"].as_u64().unwrap() + ); + // The answer kept is the answer given. + let kept: Value = serde_json::from_str(p["answer"].as_str().unwrap()).unwrap(); + assert_eq!(kept["structuredContent"], answer); +} + +#[test] +fn the_import_is_one_transaction() { + let books = Books::new("calls-import"); + 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 csv = b"Date,Description,Amount\n2026-01-02,Paper,-12.50\n2026-01-03,Pens,-3.25\n2026-01-04,Ink,-40.00\n"; + let up = w.upload(csv, "bank.csv", "text/csv", "import"); + let before = lines(&books).len(); + let args = json!({"upload_id": up, "bank_account_code": "1000", + "default_offset_code": "6000", "request_key": "key-import-0001"}); + let out = answer_of(&call_exactly(&mut w, "books.import_bank_csv", args.clone())).unwrap(); + assert_eq!(out["count"], 3, "{out}"); + let all = lines(&books); + let call = &all[before..]; + assert_eq!(call.first().unwrap()["type"], "call.begun"); + assert_eq!(call.last().unwrap()["type"], "call.closed"); + // Every row of the file is inside the one frame. + let inside = call.iter().filter(|l| l["type"] == "entry.created").count(); + assert_eq!(inside, 3); + assert_eq!( + all.iter().filter(|l| l["type"] == "call.begun").count(), + all.iter() + .filter(|l| l["type"] == "call.closed" && l["payload"]["first_seq"].is_u64()) + .count(), + "every frame that began closed" + ); + // The answer lost: the repeat gives the first answer, imports nothing. + let journal = books.journal_raw(); + let again = answer_of(&call_exactly(&mut w, "books.import_bank_csv", args)).unwrap(); + assert_eq!(again, out); + assert_eq!(books.journal_raw(), journal); + // A file the books refuse whole writes none of it. + let bad = b"Date,Description,Amount\n2026-02-02,Ok row,-1.00\nnot a date,Bad row,-2.00\n"; + let up = w.upload(bad, "bad.csv", "text/csv", "import"); + let before = books.journal_raw(); + let refused = call_exactly( + &mut w, + "books.import_bank_csv", + json!({"upload_id": up, "bank_account_code": "1000", + "default_offset_code": "6000", "request_key": "key-import-0002"}), + ); + assert!(answer_of(&refused).is_err(), "{refused}"); + assert_eq!(books.journal_raw(), before, "all or nothing"); +} + +#[test] +fn every_tool_that_can_write_asks_for_a_key_and_no_other_does() { + let books = Books::new("calls-schema"); + let mut w = books.session("test"); + let listed = w.rpc("tools/list", json!({})); + let tools = listed["result"]["tools"].as_array().unwrap(); + let (mut asking, mut reading) = (0, 0); + for t in tools { + let name = t["name"].as_str().unwrap(); + // Three tools only read what is sealed (and may answer with a TIN): + // annotated as writes, they are reads and take no key. + let read_only = t["annotations"]["readOnlyHint"] == json!(true) + || [ + "books.vendor_1099", + "books.get_w9", + "books.export_cpa_package", + ] + .contains(&name); + let required = t["inputSchema"]["required"] + .as_array() + .is_some_and(|r| r.contains(&json!("request_key"))); + let property = t["inputSchema"]["properties"].get("request_key").is_some(); + if read_only { + assert!(!required && !property, "{name} reads and asks for a key"); + reading += 1; + } else { + assert!(required && property, "{name} can write and asks for no key"); + asking += 1; + } + } + assert!( + asking > 50 && reading > 20, + "{asking} write, {reading} read" + ); +} diff --git a/crates/ledger-cli/tests/common/mod.rs b/crates/ledger-cli/tests/common/mod.rs index f735140e..f646a9aa 100644 --- a/crates/ledger-cli/tests/common/mod.rs +++ b/crates/ledger-cli/tests/common/mod.rs @@ -434,8 +434,18 @@ impl Wire { } /// Send `text` as one message's body, as it is (a test's own bytes, - /// malformed ones included). + /// malformed ones included), except that a tool call that carries no + /// `request_key` is given a fresh one (D-88: every write needs one; a + /// read ignores it), so a test of what a tool does needn't make one up. + /// [`Self::send_exactly`] sends the bytes untouched. pub fn send_line(&mut self, text: &str) { + let text = with_request_key(text); + self.send_exactly(&text); + } + + /// [`Self::send_line`] without the request key: these bytes only + /// (the tests of what a call without a key is told). + pub fn send_exactly(&mut self, text: &str) { let parsed: Option = serde_json::from_str(text).ok(); let method = parsed .as_ref() @@ -761,8 +771,15 @@ impl Books { self.home.book_dir(&self.id) } - /// The books' journal, as it is on disk. + /// The books' journal as it is on disk, without the frames of tool + /// calls (`call.begun`, `call.closed`: D-88): what the books hold, so + /// a test that a call "journaled nothing" says so of the events. pub fn journal(&self) -> Vec { + without_call_lines(&self.journal_raw()) + } + + /// The books' journal, byte for byte. + pub fn journal_raw(&self) -> Vec { std::fs::read(self.dir().join("journal.jsonl")).unwrap_or_default() } @@ -1113,6 +1130,48 @@ pub async fn connect_at(run: &Path, book: &str, token: Option) -> Result .map_err(|e| e.to_string()) } +/// A journal's bytes without its call frames (`call.begun`, `call.closed`). +pub fn without_call_lines(journal: &[u8]) -> Vec { + journal + .split_inclusive(|&b| b == b'\n') + .filter(|l| { + let l = String::from_utf8_lossy(l); + !l.contains(r#""type":"call.begun""#) && !l.contains(r#""type":"call.closed""#) + }) + .flatten() + .copied() + .collect() +} + +/// A request key no other call in this process has used. +pub fn fresh_request_key() -> String { + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: AtomicU64 = AtomicU64::new(1); + format!( + "test-key-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::SeqCst) + ) +} + +/// `message`, a JSON-RPC message as text: if it is a `tools/call` whose +/// arguments are an object with no `request_key`, with a fresh one added +/// (the key the books ask of every write, D-88); anything else as it is. +pub fn with_request_key(message: &str) -> String { + let Ok(mut v) = serde_json::from_str::(message) else { + return message.to_string(); + }; + let keyed = v.get("method") == Some(&json!("tools/call")) + && v.pointer("/params/arguments") + .and_then(Value::as_object) + .is_some_and(|a| !a.contains_key("request_key")); + if !keyed { + return message.to_string(); + } + v["params"]["arguments"]["request_key"] = json!(fresh_request_key()); + v.to_string() +} + /// Call a tool: Ok(structured result) or Err(the error text). /// Call a tool the way an agent confirms (plan P4, D-50): a call with /// `confirmed: true` and no `preview` is made first without `confirmed`, @@ -1131,7 +1190,9 @@ pub async fn call(c: &Client, tool: &str, mut args: Value) -> Result Result { use rmcp::model::CallToolRequestParams; - let args = args.as_object().cloned().unwrap_or_default(); + let mut args = args.as_object().cloned().unwrap_or_default(); + args.entry("request_key") + .or_insert_with(|| json!(fresh_request_key())); // A client whose server went away may wait forever: a call that // takes this long counts as refused. let r = tokio::time::timeout( diff --git a/crates/ledger-cli/tests/format_upgrade.rs b/crates/ledger-cli/tests/format_upgrade.rs index 1ade8a9c..bfa8aff0 100644 --- a/crates/ledger-cli/tests/format_upgrade.rs +++ b/crates/ledger-cli/tests/format_upgrade.rs @@ -309,6 +309,8 @@ impl Agent { } fn send(&mut self, message: Value) { + // A tool call carries the request key every write needs (D-88). + let message = common::with_request_key(&message.to_string()); let stdin = self.run.child.stdin.as_mut().unwrap(); writeln!(stdin, "{message}").unwrap(); stdin.flush().unwrap(); @@ -483,12 +485,19 @@ fn format_upgrade_waits_for_consent() { assert!(refused.contains("format_upgrade_pending"), "{refused}"); assert!(refused.contains("no tool can"), "{refused}"); assert_eq!(journal(&dir), before, "a refusal journals nothing"); - // What needs nothing new is made. - a.call( - "books.add_account", - json!({"code": "6000", "name": "Supplies", "account_type": "expense"}), - ) - .unwrap(); + // Nothing is written, whatever it is (D-89): a write that needs + // nothing new is refused the same, with the same remedy; reads work. + let refused = a + .call( + "books.add_account", + json!({"code": "6000", "name": "Supplies", "account_type": "expense"}), + ) + .unwrap_err(); + assert!(refused.starts_with("format_upgrade_pending"), "{refused}"); + assert!(refused.contains("nothing can be written"), "{refused}"); + assert!(refused.contains("wanderbooks books upgrade"), "{refused}"); + assert_eq!(journal(&dir), before, "a refusal journals nothing"); + a.call("books.chart", json!({})).unwrap(); let tools = a.request("tools/list", json!({}), 30); let names: Vec<&str> = tools["result"]["tools"] .as_array() @@ -614,11 +623,11 @@ fn format_upgrade_waits_for_consent() { assert_eq!(format_lines(&dir), 1); } -/// plan P4b S4.4 (R-A step 4, 8.0.6 item 3): on books that haven't -/// declared `documents_v2`, an invoice carrying a new field (terms) is -/// refused with the upgrade remedy and journals nothing, while one -/// carrying none posts as before; after the owner's go-ahead the same call -/// is made, and takes the first number. +/// plan P4b S4.4 (R-A step 4, 8.0.6 item 3), under D-89: on books that +/// haven't declared the journal's call transactions, no write is taken, an +/// invoice carrying a new field (terms) no more than any other, and it +/// journals nothing; after the owner's go-ahead the same call is made, and +/// takes the first number. #[test] fn documents_v2_refused_until_consent() { let home = Home::new("documents-v2"); @@ -632,31 +641,25 @@ fn documents_v2_refused_until_consent() { .unwrap(); assert!(out.status.success(), "{out:?}"); let mut a = Agent::start(&home, "acme"); - let customer = a - .call("books.add_customer", json!({"name": "Harbor Coffee"})) - .unwrap()["id"] - .clone(); let line = json!([{"description": "Design", "amount": "500.00"}]); - let with_terms = json!({"customer": customer.to_string(), "date": "2026-02-10", + let with_terms = json!({"customer": "1", "date": "2026-02-10", "terms": "Net 30", "lines": line, "confirmed": true}); let before = journal(&dir); - let refused = a - .call("books.create_invoice", with_terms.clone()) - .unwrap_err(); - assert!(refused.starts_with("format_upgrade_pending"), "{refused}"); - assert!(refused.contains("documents_v2"), "{refused}"); + // (An invoice's preview, which writes nothing, is made as ever; its + // post is the write that waits: it is asked for after the go-ahead.) + for (tool, args) in [ + ("books.add_customer", json!({"name": "Harbor Coffee"})), + ( + "books.draft_entry", + json!({"date": "2026-02-10", "description": "Waiting", + "no_party_reason": "test"}), + ), + ] { + let refused = a.call(tool, args).unwrap_err(); + assert!(refused.starts_with("format_upgrade_pending"), "{refused}"); + assert!(refused.contains("nothing can be written"), "{refused}"); + } assert_eq!(journal(&dir), before, "a refusal journals nothing"); - // A document carrying none of the new fields posts as before, and - // files its copy; it takes no number (an older version reads it). - let plain = a - .call( - "books.create_invoice", - json!({"customer": customer.to_string(), "date": "2026-02-10", "due_date": "2026-03-12", - "lines": line, "confirmed": true}), - ) - .unwrap(); - assert!(plain.get("number").is_none(), "{plain}"); - assert_eq!(plain["total"], "500.00"); // The go-ahead. let mut words = home.words("books"); @@ -664,6 +667,12 @@ fn documents_v2_refused_until_consent() { let (code, shown) = home.at_terminal(&words, &[PASS]); assert_eq!(code, 0, "{shown}"); assert_eq!(format_lines(&dir), 1, "the format moved once"); + let customer = a + .call("books.add_customer", json!({"name": "Harbor Coffee"})) + .unwrap()["id"] + .clone(); + let mut with_terms = with_terms; + with_terms["customer"] = json!(customer.to_string()); let made = a.call("books.create_invoice", with_terms).unwrap(); assert_eq!(made["number"], "INV-0001", "{made}"); assert_eq!(made["terms"], "Net 30", "{made}"); @@ -700,15 +709,17 @@ fn copy_private(from: &Path, to: &Path) { /// ```text /// INVARIANTS: /// 1. Before consent: the books open and are served, waiting; P2's -/// database is never written; what P2 can read is written, and every -/// write P2 would refuse or misread is refused, journaling nothing -/// (a setting key, a tax category, a depreciation catch-up, a members -/// close counted from the count's start, an invoice's or bill's line -/// naming its project). +/// database is never written; they are read as ever and take no +/// write at all (D-89, WB-format-11: every write is one transaction, +/// and books written before that can't keep it), every one refused +/// with the upgrade remedy, journaling nothing. /// 2. The consent backup holds the books exactly as they were, keys and /// vault too; the upgrade is one line after P2's, byte for byte. -/// 3. After it: the same figures, and every refused write is made; the -/// books verify; P2's database is still byte for byte. +/// 3. After it: the same figures, and every write is made, those P2 +/// would have refused or misread among them (a setting key, a tax +/// category, a depreciation catch-up, a members close counted from +/// the count's start, an invoice's or bill's line naming its +/// project); the books verify; P2's database is still byte for byte. /// ``` #[test] fn books_p2_served_cut_over_whole() { @@ -729,11 +740,9 @@ fn books_p2_served_cut_over_whole() { let mut a = Agent::start(&home, "acme"); let start = a.call("books.start", json!({})).unwrap(); assert_eq!(start["format_upgrade"]["format"], 2, "{start}"); - let verified = a.call("books.verify", json!({})).unwrap(); - assert_eq!(verified["status"], "ok", "{verified}"); - assert_eq!(verified["events"], 470); - assert_eq!(verified["database"], ledger_store::db_file()); - assert_eq!(verified["other_databases"], json!(["wanderbooks.db"])); + // (books.verify can rebuild the projection: a write, so it waits for + // the go-ahead like every other, and is asked after it, below.) + assert_eq!(journal(&dir).iter().filter(|b| **b == b'\n').count(), 470); let figures = |a: &mut Agent| { [ a.call("books.trial_balance", json!({"as_of": "2025-12-31"})), @@ -747,7 +756,68 @@ fn books_p2_served_cut_over_whole() { }; let before = figures(&mut a); - // INVARIANT 1: what P2 reads is written; the rest waits. + // INVARIANT 1 (D-89): the books take no write before the go-ahead, + // whatever the write, and journal nothing for the refusal. + let waiting = journal(&dir); + for (tool, args) in [ + ( + "books.add_account", + json!({"code": "6600", "name": "Travel", "account_type": "expense"}), + ), + ( + "books.create_period", + json!({"name": "2025-Q2", "start": "2025-04-01", "end": "2025-06-30"}), + ), + ("books.add_project", json!({"name": "Lighthouse"})), + ("books.add_customer", json!({"name": "Ridgeway Co"})), + ( + "books.draft_entry", + json!({"date": "2026-02-12", "description": "Waiting for the go-ahead", + "no_party_reason": "test"}), + ), + ( + "books.raise_item", + json!({"title": "Ask the CPA", "decided_by": "Avery Quill"}), + ), + ] { + let e = a.call(tool, args).unwrap_err(); + assert!(e.starts_with("format_upgrade_pending"), "{tool}: {e}"); + assert!(e.contains("nothing can be written"), "{tool}: {e}"); + } + assert_eq!(journal(&dir), waiting, "a refusal journals nothing"); + assert!(journal(&dir).starts_with(&p2_journal)); + // The books are read as ever. + assert_eq!(figures(&mut a), before); + + // INVARIANT 2: the go-ahead. + let mut words = home.words("books"); + words.extend(["upgrade".into(), "acme".into()]); + let (code, shown) = home.at_terminal(&words, &[PASS]); + assert_eq!(code, 0, "{shown}"); + let after = journal(&dir); + assert!(after.starts_with(&waiting)); + assert_eq!( + format_lines(&dir), + 2, + "P2's declaration, then the upgrade's" + ); + let backup = archive_git(&dir, &["rev-parse", "HEAD"]); + assert_eq!( + archive_git(&dir, &["show", &format!("{}:journal.jsonl", backup.trim())]).as_bytes(), + waiting.as_slice(), + "the backup holds the books as they were" + ); + for kept in ["keys/legacy.key", "vault/tin-1.bin", "vault/tin-3.bin"] { + let out = Command::new("git") + .arg(format!("--git-dir={}", dir.join("archive.git").display())) + .args(["show", &format!("{}:{kept}", backup.trim())]) + .output() + .unwrap(); + assert_eq!(out.stdout, std::fs::read(dir.join(kept)).unwrap(), "{kept}"); + } + assert_eq!(figures(&mut a), before, "the upgrade moves no figure"); + + // INVARIANT 3: every write is taken now: first what P2 could read. a.call( "books.add_account", json!({"code": "6600", "name": "Travel", "account_type": "expense"}), @@ -822,7 +892,6 @@ fn books_p2_served_cut_over_whole() { ) .unwrap()["id"] .clone(); - let waiting = journal(&dir); let refused: Vec<(&str, Value)> = vec![ // A source correction (source_revisions, P5): an older version // refuses the type. @@ -921,53 +990,20 @@ fn books_p2_served_cut_over_whole() { json!({"entry_id": 1, "method": {"reasoning_effort": "high"}}), ), ]; - for (tool, args) in &refused { - let e = a.call(tool, args.clone()).unwrap_err(); - assert!(e.starts_with("format_upgrade_pending"), "{tool}: {e}"); - } - assert_eq!(journal(&dir), waiting, "a refusal journals nothing"); - assert!(journal(&dir).starts_with(&p2_journal)); - assert_eq!( - std::fs::read(dir.join(ledger_store::LEGACY_DB_FILE)).unwrap(), - p2_db, - "P2's database is never written" - ); - - // INVARIANT 2: the go-ahead. - let mut words = home.words("books"); - words.extend(["upgrade".into(), "acme".into()]); - let (code, shown) = home.at_terminal(&words, &[PASS]); - assert_eq!(code, 0, "{shown}"); - let after = journal(&dir); - assert!(after.starts_with(&waiting)); - assert_eq!( - format_lines(&dir), - 2, - "P2's declaration, then the upgrade's" - ); - let backup = archive_git(&dir, &["rev-parse", "HEAD"]); - assert_eq!( - archive_git(&dir, &["show", &format!("{}:journal.jsonl", backup.trim())]).as_bytes(), - waiting.as_slice(), - "the backup holds the books as they were" - ); - for kept in ["keys/legacy.key", "vault/tin-1.bin", "vault/tin-3.bin"] { - let out = Command::new("git") - .arg(format!("--git-dir={}", dir.join("archive.git").display())) - .args(["show", &format!("{}:{kept}", backup.trim())]) - .output() - .unwrap(); - assert_eq!(out.stdout, std::fs::read(dir.join(kept)).unwrap(), "{kept}"); - } - - // INVARIANT 3. - assert_eq!(figures(&mut a), before, "the upgrade moves no figure"); + // The writes P2 would have refused or misread, made now. for (tool, args) in refused { a.call(tool, args.clone()) .unwrap_or_else(|e| panic!("{tool} after the upgrade: {e}")); } let verified = a.call("books.verify", json!({})).unwrap(); assert_eq!(verified["status"], "ok", "{verified}"); + // It counts the lines there were when it ran: the call's own closing + // line comes after its answer. + let events = verified["events"].as_u64().unwrap(); + let on_disk = journal(&dir).iter().filter(|b| **b == b'\n').count() as u64; + assert!(events > 470 && events < on_disk, "{events} of {on_disk}"); + assert_eq!(verified["database"], ledger_store::db_file()); + assert_eq!(verified["other_databases"], json!(["wanderbooks.db"])); assert_eq!( std::fs::read(dir.join(ledger_store::LEGACY_DB_FILE)).unwrap(), p2_db, diff --git a/crates/ledger-cli/tests/local_server.rs b/crates/ledger-cli/tests/local_server.rs index 288349cb..f1e93193 100644 --- a/crates/ledger-cli/tests/local_server.rs +++ b/crates/ledger-cli/tests/local_server.rs @@ -623,7 +623,8 @@ async fn raw_upload(http: &reqwest::Client, session: &str, bytes: &[u8], name: & let begin = json!({"jsonrpc": "2.0", "id": 9, "method": "tools/call", "params": { "name": "books.begin_upload", "arguments": { "sha256": ledger_store::journal::sha256_hex(bytes), "size": bytes.len(), - "mime_type": "application/pdf", "file_name": name, "purpose": "document"}}}); + "mime_type": "application/pdf", "file_name": name, "purpose": "document", + "request_key": common::fresh_request_key()}}}); let r = http .post("http://localhost/b/acme/mcp") .header("content-type", "application/json") @@ -681,7 +682,8 @@ async fn a_call_whose_client_hung_up_finishes_before_the_close() { let upload = raw_upload(&http, &session, &bytes, "big.pdf").await; let call = json!({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "books.file_document", "arguments": { - "category": "formation", "upload_id": upload}}}); + "category": "formation", "upload_id": upload, + "request_key": common::fresh_request_key()}}}); let response = http .post("http://localhost/b/acme/mcp") .header("content-type", "application/json") diff --git a/crates/ledger-cli/tests/mcp_journeys.rs b/crates/ledger-cli/tests/mcp_journeys.rs index 07b0b415..6a5450fa 100644 --- a/crates/ledger-cli/tests/mcp_journeys.rs +++ b/crates/ledger-cli/tests/mcp_journeys.rs @@ -805,7 +805,20 @@ fn tin_bearing_files_are_refused_when_given_back_to_be_filed() { ); } } - assert_eq!(books.journal(), journal, "a refusal stored something"); + // (Each upload begun is a call, with its closing line: those only.) + let calls_only = |j: Vec| -> Vec { + String::from_utf8(j) + .unwrap() + .lines() + .filter(|l| !l.contains(r#""type":"call.closed""#)) + .map(str::to_string) + .collect() + }; + assert_eq!( + calls_only(books.journal()), + calls_only(journal), + "a refusal stored something" + ); // Without TINs, the 1099 worksheet is an ordinary file: it may be // filed like any other. let plain = mcp.call("books.vendor_1099", json!({"year": 2026, "csv": true})); @@ -1765,7 +1778,8 @@ fn close_period_shows_each_members_running_split() { fn old_books_name_each_closes_rule_and_true_up_at_the_next_close() { // Books P1 kept, which P2 moved to its journal format (format 2, none // of the features since), left in a data root, with their members set - // as an agent sets them: books waiting for their format upgrade. + // as an agent sets them once they are upgraded: books waiting for + // their format upgrade, which (D-89) take no write until then. let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) .join("../ledger-store/tests/fixtures/old-books/x_member_closes"); let books = Books::placed("members-old", &fixture); @@ -1775,13 +1789,6 @@ fn old_books_name_each_closes_rule_and_true_up_at_the_next_close() { .declare_journal_format(2, &[]) .unwrap(); books.start(); - books.settle( - "[company]\ntax_form = \"1065\"\n\n\ - [[company.members]]\nname = \"Ann\"\nshare = \"50%\"\ncapital_account = \"3000\"\n\ - distribution_account = \"3100\"\n\n\ - [[company.members]]\nname = \"Bo\"\nshare = \"50%\"\ncapital_account = \"3001\"\n\n\ - [books]\nreceipt_threshold = \"10000\"\n", - ); let mut mcp = Mcp::spawn(&books); init(&mut mcp); let rules = |mcp: &mut Mcp| -> Vec { @@ -1805,6 +1812,32 @@ fn old_books_name_each_closes_rule_and_true_up_at_the_next_close() { let mut want: Vec = old.iter().map(|r| json!(r)).collect(); want.extend([Value::Null, json!("members_run"), json!("members_run")]); assert_eq!(rules(&mut mcp), want); + // Read as ever; no write is taken (D-89), whatever it is. + let refused = mcp.call_err( + "books.draft_entry", + json!({"date": "2026-12-10", "description": "two cents"}), + ); + assert!(refused.starts_with("format_upgrade_pending:"), "{refused}"); + // The owner's go-ahead, as the app gives it (ledger-gui owner.rs, after + // the passphrase and a verified backup): the server stopped, the books + // moved to this version's format, and served again. + drop(mcp); + books.stop(); + ledger_store::Store::open(&books.dir()) + .unwrap() + .upgrade_format() + .unwrap() + .expect("old books wait for the upgrade"); + books.start(); + books.settle( + "[company]\ntax_form = \"1065\"\n\n\ + [[company.members]]\nname = \"Ann\"\nshare = \"50%\"\ncapital_account = \"3000\"\n\ + distribution_account = \"3100\"\n\n\ + [[company.members]]\nname = \"Bo\"\nshare = \"50%\"\ncapital_account = \"3001\"\n\n\ + [books]\nreceipt_threshold = \"10000\"\n", + ); + let mut mcp = Mcp::spawn(&books); + init(&mut mcp); let e = mcp.call( "books.draft_entry", @@ -1844,29 +1877,6 @@ fn old_books_name_each_closes_rule_and_true_up_at_the_next_close() { preview["lines"], json!(["Debit 4000 0.02", "Credit 3001 0.02"]) ); - // Books an older version wrote: the close counted from its regime's - // start waits for the owner's go-ahead (D-39), which no tool gives. - let refused = mcp.call_err( - "books.close_period", - json!({"period_id": dec["period_id"], "confirmed": true}), - ); - assert!( - refused.starts_with("format_upgrade_pending:") && refused.contains("members_cumulative"), - "{refused}" - ); - // The owner's go-ahead, as the app gives it (ledger-gui owner.rs, after - // the passphrase and a verified backup): the server stopped, the books - // moved to this version's format, and served again. - drop(mcp); - books.stop(); - ledger_store::Store::open(&books.dir()) - .unwrap() - .upgrade_format() - .unwrap() - .expect("old books wait for the upgrade"); - books.start(); - let mut mcp = Mcp::spawn(&books); - init(&mut mcp); let closed = mcp.call( "books.close_period", json!({"period_id": dec["period_id"], "confirmed": true}), @@ -2988,9 +2998,11 @@ fn rename_account_end_to_end_defect_15() { ); assert!(err.contains(says), "{name:?}: {err}"); } + // (The first verify is a call too: its own closing line is the one + // line the second counts more; the refusals wrote none.) assert_eq!( mcp.call("books.verify", json!({"blobs": false}))["events"], - json!(events), + json!(events + 1), "refusals write nothing" ); let out = mcp.call( @@ -3009,8 +3021,10 @@ fn rename_account_end_to_end_defect_15() { let after = mcp.call("books.verify", json!({"blobs": false})); assert_eq!(after["status"], "ok"); // New books declare account_renamed (with the rest of this version's - // format) as they are created: the rename journals only itself. - assert_eq!(after["events"], json!(events + 1), "the rename"); + // format) as they are created: the rename journals only itself, in + // its frame (begun, the rename, closed), after the two verifies' + // closing lines. + assert_eq!(after["events"], json!(events + 1 + 1 + 3), "the rename"); let chart = mcp.call("books.chart", json!({})); let acct = chart["accounts"] .as_array() diff --git a/crates/ledger-cli/tests/open_while_held.rs b/crates/ledger-cli/tests/open_while_held.rs index 42a08604..b505d5d6 100644 --- a/crates/ledger-cli/tests/open_while_held.rs +++ b/crates/ledger-cli/tests/open_while_held.rs @@ -372,6 +372,8 @@ impl Agent { } fn send(&mut self, message: Value) { + // A tool call carries the request key every write needs (D-88). + let message = common::with_request_key(&message.to_string()); let stdin = self.run.child.stdin.as_mut().unwrap(); writeln!(stdin, "{message}").unwrap(); stdin.flush().unwrap(); @@ -1383,7 +1385,8 @@ fn a_call_cancelled_at_once_is_never_made() { json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": { "name": "books.add_account", "arguments": {"code": format!("{}", 1000 + k), "name": format!("A{k}"), - "account_type": "asset"}}}), + "account_type": "asset", + "request_key": common::fresh_request_key()}}}), json!({"jsonrpc": "2.0", "method": "notifications/cancelled", "params": {"requestId": id}}) ) diff --git a/crates/ledger-cli/tests/spec_1099.rs b/crates/ledger-cli/tests/spec_1099.rs index 7d4c3247..0e7c4440 100644 --- a/crates/ledger-cli/tests/spec_1099.rs +++ b/crates/ledger-cli/tests/spec_1099.rs @@ -71,7 +71,13 @@ fn books_toml(dir: &Path, company: &str, books_extra: &str) -> PathBuf { impl Mcp { fn start(dir: &TestDir, toml: &Path) -> Self { - let wire = dir.start(Some(&std::fs::read_to_string(toml).unwrap())); + Self::start_settings(dir, Some(&std::fs::read_to_string(toml).unwrap())) + } + + /// [`Mcp::start`] with these settings, or none (books that take no + /// write, D-89, can't be given any). + fn start_settings(dir: &TestDir, settings: Option<&str>) -> Self { + let wire = dir.start(settings); let mut mcp = Self { books_dir: None, wire, @@ -101,8 +107,11 @@ impl Mcp { mcp } + /// The journal, without the frames of tool calls (D-88). fn journal(&self) -> Vec { - std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default() + common::without_call_lines( + &std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(), + ) } /// The journal's line types, in order. @@ -300,6 +309,12 @@ fn books_in(name: &str, p2: bool) -> Mcp { .unwrap(); } let toml = books_toml(&dir, "Spec Co", "financing_accounts = [\"2100\"]\n"); + if p2 { + // Books that take no write (D-89): no settings, no chart. + let mut m = Mcp::start_settings(&dir, None); + m.books_dir = Some(dir); + return m; + } let mut m = Mcp::start(&dir, &toml); m.accounts(CHART); m.books_dir = Some(dir); @@ -321,6 +336,7 @@ impl Mcp { .unwrap() .expect("P2's books wait for the upgrade"); let mut m = Mcp::start(&dir, &dir.join("wanderbooks.toml")); + m.accounts(CHART); m.books_dir = Some(dir); m } @@ -623,18 +639,17 @@ fn set_w9_asks_for_the_w9_flags_feature_before_its_first_line() { let w9 = json!({"party": "Harbor Design LLC", "received_on": "2026-03-02", "entity_type": "LLC (partnership)", "tin_last4": "4321", "kept_at": "CPA portal"}); let mut m = books_in("set-w9-feature", true); + let why = m.refuse("books.set_w9", w9.clone()); + assert!(why.starts_with("format_upgrade_pending:"), "{why}"); + assert!(why.contains("nothing can be written"), "{why}"); + assert_eq!(m.count("party.w9_set"), 0, "nothing half done"); + let mut m = m.upgraded(); m.add_party("Harbor Design LLC", &["contractor"]); m.ok("books.add_vendor", json!({"name": "Harbor Design LLC"})); - let why = m.refuse("books.set_w9", w9.clone()); - assert!( - why.starts_with("format_upgrade_pending:") && why.contains("vendor_1099_decisions"), - "{why}" - ); - assert_eq!(m.count("party.w9_set"), 0, "nothing half done"); let mut fresh = books("set-w9-feature-new"); fresh.add_party("Harbor Design LLC", &["contractor"]); fresh.ok("books.add_vendor", json!({"name": "Harbor Design LLC"})); - for mut m in [m.upgraded(), fresh] { + for mut m in [m, fresh] { let before = m.journal_types().len(); m.ok("books.set_w9", w9.clone()); let added = m.journal_types()[before..].to_vec(); diff --git a/crates/ledger-cli/tests/spec_assets.rs b/crates/ledger-cli/tests/spec_assets.rs index 1ed3e3ca..95034e19 100644 --- a/crates/ledger-cli/tests/spec_assets.rs +++ b/crates/ledger-cli/tests/spec_assets.rs @@ -106,8 +106,11 @@ impl Mcp { mcp } + /// The journal, without the frames of tool calls (D-88). fn journal(&self) -> Vec { - std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default() + common::without_call_lines( + &std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(), + ) } /// The journal's line types, in order. diff --git a/crates/ledger-cli/tests/spec_attachments.rs b/crates/ledger-cli/tests/spec_attachments.rs index d826849e..d2448088 100644 --- a/crates/ledger-cli/tests/spec_attachments.rs +++ b/crates/ledger-cli/tests/spec_attachments.rs @@ -110,8 +110,11 @@ impl Mcp { mcp } + /// The journal, without the frames of tool calls (D-88). fn journal(&self) -> Vec { - std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default() + common::without_call_lines( + &std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(), + ) } /// The journal's line types, in order. diff --git a/crates/ledger-cli/tests/spec_mcp.rs b/crates/ledger-cli/tests/spec_mcp.rs index 816f3ddc..de511859 100644 --- a/crates/ledger-cli/tests/spec_mcp.rs +++ b/crates/ledger-cli/tests/spec_mcp.rs @@ -224,8 +224,11 @@ impl Mcp { mcp } + /// The journal, without the frames of tool calls (D-88). fn journal(&self) -> Vec { - std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default() + common::without_call_lines( + &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 diff --git a/crates/ledger-cli/tests/spec_parties.rs b/crates/ledger-cli/tests/spec_parties.rs index 6b54728d..53095287 100644 --- a/crates/ledger-cli/tests/spec_parties.rs +++ b/crates/ledger-cli/tests/spec_parties.rs @@ -107,8 +107,11 @@ impl Mcp { mcp } + /// The journal, without the frames of tool calls (D-88). fn journal(&self) -> Vec { - std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default() + common::without_call_lines( + &std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(), + ) } /// The journal's line types, in order. diff --git a/crates/ledger-cli/tests/spec_party_totals.rs b/crates/ledger-cli/tests/spec_party_totals.rs index ee31f4b5..c6c66970 100644 --- a/crates/ledger-cli/tests/spec_party_totals.rs +++ b/crates/ledger-cli/tests/spec_party_totals.rs @@ -78,7 +78,13 @@ fn books_toml(dir: &Path, company: &str, books_extra: &str) -> PathBuf { impl Mcp { fn start(dir: &TestDir, toml: &Path) -> Self { - let wire = dir.start(Some(&std::fs::read_to_string(toml).unwrap())); + Self::start_settings(dir, Some(&std::fs::read_to_string(toml).unwrap())) + } + + /// [`Mcp::start`] with these settings, or none (books that take no + /// write, D-89, can't be given any). + fn start_settings(dir: &TestDir, settings: Option<&str>) -> Self { + let wire = dir.start(settings); let mut mcp = Self { books_dir: None, wire, @@ -108,8 +114,11 @@ impl Mcp { mcp } + /// The journal, without the frames of tool calls (D-88). fn journal(&self) -> Vec { - std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default() + common::without_call_lines( + &std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(), + ) } /// The journal's line types, in order. @@ -312,6 +321,12 @@ fn books_in(name: &str, p2: bool) -> Mcp { [[company.members]]\nname = \"Tobin Harlow\"\nshare = \"50%\"\ncapital_account = \"3000\"\n\ [[company.members]]\nname = \"Morgan Ellis\"\nshare = \"50%\"\ncapital_account = \"3001\"\n", ); + if p2 { + // Books that take no write (D-89): no settings, no chart. + let mut m = Mcp::start_settings(&dir, None); + m.books_dir = Some(dir); + return m; + } let mut m = Mcp::start(&dir, &toml); m.accounts(CHART); m.add_party("Tobin Harlow", &["member"]); @@ -336,6 +351,10 @@ impl Mcp { .unwrap() .expect("P2's books wait for the upgrade"); let mut m = Mcp::start(&dir, &dir.join("wanderbooks.toml")); + m.accounts(CHART); + m.add_party("Tobin Harlow", &["member"]); + m.add_party("Morgan Ellis", &["member"]); + m.add_party("Harbor Bank", &["financial_institution"]); m.books_dir = Some(dir); m } @@ -616,10 +635,8 @@ fn update_party_asks_for_the_creditor_feature_before_its_first_line() { json!({"party": "Harbor Bank", "notes": "the card's issuer", "creditor_of": ["2050"]}); let mut m = books_in("feature-first", true); let why = m.refuse("books.update_party", change.clone()); - assert!( - why.starts_with("format_upgrade_pending:") && why.contains("party_creditors"), - "{why}" - ); + assert!(why.starts_with("format_upgrade_pending:"), "{why}"); + assert!(why.contains("nothing can be written"), "{why}"); assert_eq!(m.count("party.updated"), 0, "nothing half done"); for mut m in [m.upgraded(), books("feature-first-new")] { let start = m.journal_types().len(); diff --git a/crates/ledger-cli/tests/spec_projects.rs b/crates/ledger-cli/tests/spec_projects.rs index e25e5f32..ddcd5fed 100644 --- a/crates/ledger-cli/tests/spec_projects.rs +++ b/crates/ledger-cli/tests/spec_projects.rs @@ -77,7 +77,13 @@ fn books_toml(dir: &Path, company: &str, books_extra: &str) -> PathBuf { impl Mcp { fn start(dir: &TestDir, toml: &Path) -> Self { - let wire = dir.start(Some(&std::fs::read_to_string(toml).unwrap())); + Self::start_settings(dir, Some(&std::fs::read_to_string(toml).unwrap())) + } + + /// [`Mcp::start`] with these settings, or none (books that take no + /// write, D-89, can't be given any). + fn start_settings(dir: &TestDir, settings: Option<&str>) -> Self { + let wire = dir.start(settings); let mut mcp = Self { books_dir: None, wire, @@ -107,8 +113,11 @@ impl Mcp { mcp } + /// The journal, without the frames of tool calls (D-88). fn journal(&self) -> Vec { - std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default() + common::without_call_lines( + &std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(), + ) } /// The journal's line types, in order. @@ -253,6 +262,7 @@ fn books(name: &str) -> Mcp { /// for their format upgrade. fn books_in(name: &str, p2: bool) -> Mcp { let dir = test_dir(name); + let toml = books_toml(&dir, "Spec Co", ""); if p2 { ledger_store::Store::create_in_format( &dir.books_data(), @@ -263,8 +273,11 @@ fn books_in(name: &str, p2: bool) -> Mcp { }, ) .unwrap(); + // Books that take no write (D-89): no settings, no chart. + let mut m = Mcp::start_settings(&dir, None); + m.books_dir = Some(dir); + return m; } - let toml = books_toml(&dir, "Spec Co", ""); let mut m = Mcp::start(&dir, &toml); m.accounts(CHART); m.books_dir = Some(dir); @@ -914,17 +927,16 @@ fn show_project_sends_its_target() { ); } +/// Books an older version wrote take no write at all (D-89): not a +/// project, not a link to one, nothing, and the refusal journals nothing. +/// (The feature `projects` itself waiting is the store's: +/// `ledger-store` `tests/projects.rs`.) #[test] fn project_writes_wait_for_the_format_upgrade() { let mut m = books_in("upgrade", true); - // A name alone: a plain class, accepted. - m.ok("books.add_project", json!({"name": "Harbor"})); - let a = match m.doc(b"%PDF c", json!([])) { - Out::Ok(v) => v["attachment_id"].as_u64().unwrap(), - o => panic!("{o:?}"), - }; let head = m.journal(); for (tool, args) in [ + ("books.add_project", json!({"name": "Harbor"})), ( "books.add_project", json!({"name": "Dock", "kind": "client"}), @@ -935,7 +947,7 @@ fn project_writes_wait_for_the_format_upgrade() { ), ( "books.link_attachment", - json!({"attachment_id": a, "subject": {"kind": "project", "id": "Harbor"}}), + json!({"attachment_id": 1, "subject": {"kind": "project", "id": "Harbor"}}), ), ( "books.record_decision", @@ -944,15 +956,9 @@ fn project_writes_wait_for_the_format_upgrade() { ), ] { let why = m.refuse(tool, args); - assert!( - why.starts_with("format_upgrade_pending:") && why.contains("projects"), - "{tool}: {why}" - ); + assert!(why.starts_with("format_upgrade_pending:"), "{tool}: {why}"); + assert!(why.contains("nothing can be written"), "{tool}: {why}"); } - // Filing with a link to a project is refused before the file is filed. - let out = m.doc(b"%PDF d", json!([{"kind": "project", "id": "Harbor"}])); - assert!(out.refused()); - assert!(out.err_text().contains("projects"), "{out:?}"); assert_eq!(m.journal(), head, "nothing journaled"); } diff --git a/crates/ledger-cli/tests/spec_vault.rs b/crates/ledger-cli/tests/spec_vault.rs index 7bde0319..734af91d 100644 --- a/crates/ledger-cli/tests/spec_vault.rs +++ b/crates/ledger-cli/tests/spec_vault.rs @@ -115,8 +115,11 @@ impl Mcp { mcp } + /// The journal, without the frames of tool calls (D-88). fn journal(&self) -> Vec { - std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default() + common::without_call_lines( + &std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default(), + ) } /// The journal's line types, in order. diff --git a/crates/ledger-mcp/handbook/format-upgrade.md b/crates/ledger-mcp/handbook/format-upgrade.md index 5eeef693..88b560cf 100644 --- a/crates/ledger-mcp/handbook/format-upgrade.md +++ b/crates/ledger-mcp/handbook/format-upgrade.md @@ -1,11 +1,11 @@ # The format upgrade - A new version of wanderbooks can keep the books in a newer journal format than the version that wrote them. Books an older version wrote wait for a format upgrade: books.start says so (format_upgrade) and puts it first among its next steps, in every session until it is done. -- Until then they work on their old format: everything that needs nothing new works as before, and whatever would need the new format is refused with format_upgrade_pending, changing nothing. Never retry it, work around it, or post it another way. +- Until then they can be read as ever, but nothing can be written to them: every write is one transaction that happens exactly once, and books an older version wrote can't keep that until they are upgraded. Every write is refused with format_upgrade_pending, changing nothing. Never retry it, work around it, or post it another way. - An invoice's or bill's number, payment terms, seller and bill-to, references and memo, a line's account, quantity and unit price, the copy of an invoice kept exactly as it was issued, a party's email, default terms and contact details (phone, contact person, billing and shipping addresses, billing email), and the invoicing and bills settings all wait for the documents_v2 upgrade. A document that names none of them is written exactly as before and is never refused; the work that needs one waits, and the books say so. -- Only the owner can agree to the upgrade, with the owner passphrase: in the app, which asks each time it opens the books, or with `wanderbooks books upgrade ID` in a terminal. No tool can, and you never ask for, take or type the passphrase. Tell the human, in plain words: the books wait for their go-ahead, what was refused, and that saying no keeps the books working as they are. +- Only the owner can agree to the upgrade, with the owner passphrase: in the app, which asks each time it opens the books, or with `wanderbooks books upgrade ID` in a terminal. No tool can, and you never ask for, take or type the passphrase. Tell the human, in plain words: the books wait for their go-ahead, what was refused, and that until they give it the books can be read but not changed. - Before it upgrades, the server makes a backup of the books, their vault and keys included, and proves it whole; a backup that can't be made or proven upgrades nothing. Then the books move to the new format in one step, on the record. - After the upgrade an older version of wanderbooks can't open these books; the backup made first keeps them as they were. Going back is the owner's choice, never yours. -- This upgrade is `documents_v2`: invoice numbers, terms and line accounts (S4), sent records (S5), payments that settle several documents with early-payment discounts and a processor's fee (S6), and write-offs (S7). Until it is given, those writes are refused and everything else works as before. +- This upgrade is `documents_v2`: invoice numbers, terms and line accounts (S4), sent records (S5), payments that settle several documents with early-payment discounts and a processor's fee (S6), and write-offs (S7). Until it is given, every write is refused (the books can be read). -- The journal features an upgrade can add: `members_cumulative`, `account_renamed`, `require_tax_category`, `tax_categories_gain_exempt`, `disposal_before_service`, `depreciation_catch_up`, `party_creditors`, `payment_instruments`, `vendor_1099_decisions`, `schedule_convention`, `schedule_minor_unit` (K-U5: a new equal-months schedule's months are whole units of its currency, whole yen or thousandths of a dinar, where the cent rule gave two places for every currency; schedules written before keep their rule), `month_reposting`, `asset_basis`, `projects`, `document_line_projects`, `document_standing`, `documents_v2`, `attachment_text` (P6: a filed file's extracted text, what a human annotated of it, and the entries a payment settles), `drafts_v2` (P4: a draft's state, awaiting its evidence, and a discarded draft), and `source_revisions` (P5: correcting who decided a convention, a decision or an open item, and when). All are declared at once; a version that doesn't know one stops at the declaration instead of misreading the books. +- The journal features an upgrade can add: `members_cumulative`, `account_renamed`, `require_tax_category`, `tax_categories_gain_exempt`, `disposal_before_service`, `depreciation_catch_up`, `party_creditors`, `payment_instruments`, `vendor_1099_decisions`, `schedule_convention`, `schedule_minor_unit` (K-U5: a new equal-months schedule's months are whole units of its currency, whole yen or thousandths of a dinar, where the cent rule gave two places for every currency; schedules written before keep their rule), `month_reposting`, `asset_basis`, `projects`, `document_line_projects`, `document_standing`, `documents_v2`, `attachment_text` (P6: a filed file's extracted text, what a human annotated of it, and the entries a payment settles), `drafts_v2` (P4: a draft's state, awaiting its evidence, and a discarded draft), `source_revisions` (P5: correcting who decided a convention, a decision or an open item, and when), and `call_transactions` (D-88: every write one transaction, with the request key each write carries, and the books' own unique id). All are declared at once; a version that doesn't know one stops at the declaration instead of misreading the books. diff --git a/crates/ledger-mcp/src/calls.rs b/crates/ledger-mcp/src/calls.rs new file mode 100644 index 00000000..c4952c47 --- /dev/null +++ b/crates/ledger-mcp/src/calls.rs @@ -0,0 +1,290 @@ +//! Every write a tool makes is one transaction that happens once (plan +//! P15 2a, D-88, D-89): the request key, the repeat, and the frame around +//! a call. The journal's side is `ledger_store::calls`. +//! +//! ```text +//! 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; +//! plan/p15-app-and-relay.md 2a. +//! INVARIANTS: +//! 1. Every tool that can change anything (no readOnlyHint, but for +//! READS_THAT_SEAL, which write nothing and may answer with a TIN) takes a +//! required `request_key` in its schema; a call that writes without +//! one is refused in words, before it runs. A preview (a confirmed +//! tool called without confirmed: true) writes nothing and needs +//! none. The key is taken out of the arguments before the tool sees +//! them, so a tool's own checks and previews are unchanged. +//! 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. +//! 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. +//! 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. +//! 6. No full TIN is kept in the journal (BS-partner-2): no answer holds +//! one (READS_THAT_SEAL, the three that can, are no transaction), and +//! an error text that holds one is kept masked. +//! SCENARIOS: +//! 1. IF a write is called again with the same key after its answer was +//! lost: SHOULD return the first answer, and the books hold one of +//! its effects. +//! 2. IF the same key comes with a different request: SHOULD refuse, +//! saying so and that nothing was changed. +//! 3. IF the process dies between the call's lines: SHOULD leave none +//! of them in the books (ledger_store::calls). +//! ``` + +use ledger_store::calls::{CallEnd, CallId, MAX_KEY_LEN, MIN_KEY_LEN}; +use rmcp::model::{CallToolResponse, CallToolResult}; +use serde_json::{Map, Value, json}; + +use super::BooksServer; +use crate::scopes::{Needs, TABLE}; + +/// The argument every write call carries. +pub const KEY_FIELD: &str = "request_key"; + +/// Why a write was refused before it ran, for its access record. +pub(crate) const MISSING_KEY: &str = "request_key_missing"; +/// The key was used for another request. +pub(crate) const KEY_REUSED: &str = "request_key_reused"; +/// The books are waiting for the owner's format upgrade (D-89). +pub(crate) const UPGRADE_PENDING: &str = "format_upgrade_pending"; +/// The call repeated one that committed: its answer was returned. +pub(crate) const REPEAT: &str = "repeat"; + +/// The words that tell a model what the key is, whenever it is asked for. +const KEY_WORDS: &str = "request_key: any text you make up, 8 to 128 characters (a UUID is fine), new for each different action and never reused for another. If a call's answer is lost, send the same call again with the same key: the books will not do it twice, and will answer what they answered the first time"; + +/// The tools that are not read-only by their annotation but write nothing +/// to the books: they read what is sealed or put it into a file, and the +/// answer of each may hold a full TIN, which no journal line may (BS-partner-2). +/// They take no request key and are no transaction; they are read as any +/// read is (INVARIANT 1). +pub(crate) const READS_THAT_SEAL: [&str; 3] = [ + "books.vendor_1099", + "books.get_w9", + "books.export_cpa_package", +]; + +/// The tools whose calls can write: no readOnlyHint (`next_steps:: +/// mutating_tools`), except [`READS_THAT_SEAL`] (83 of the 86). +pub(crate) fn writes(tool: &str) -> bool { + super::next_steps::mutating_tools().contains(tool) && !READS_THAT_SEAL.contains(&tool) +} + +/// Whether a call to `tool` with `args` writes: a write tool, except a +/// confirmed tool called as a preview (INVARIANT 1). +pub(crate) fn is_write_call(tool: &str, args: Option<&Map>) -> bool { + if !writes(tool) { + return false; + } + let previews = TABLE + .iter() + .any(|(n, needs)| *n == tool && *needs == Needs::PostWhenConfirmed); + !(previews + && !args + .and_then(|a| a.get("confirmed")) + .and_then(Value::as_bool) + .unwrap_or(false)) +} + +/// Take the request key out of the arguments (INVARIANT 1). +pub(crate) fn take_key(args: &mut Option>) -> Option { + args.as_mut().and_then(|a| a.remove(KEY_FIELD)) +} + +/// What is wrong with a call's key, in words; None when it will do. +pub(crate) fn key_problem(key: Option<&Value>) -> Option { + match key { + None | Some(Value::Null) => Some(format!( + "this call changes the books and carries no request_key, so it was not run and nothing was changed. Send it again with a {KEY_WORDS}." + )), + Some(Value::String(k)) => { + let n = k.chars().count(); + if k != k.trim() || k.chars().any(char::is_control) { + Some("the request_key has spaces at its ends or control characters in it, so the call was not run and nothing was changed. Send it again with a key of plain text".into()) + } else if !(MIN_KEY_LEN..=MAX_KEY_LEN).contains(&n) { + Some(format!( + "the request_key is {n} characters; it must be {MIN_KEY_LEN} to {MAX_KEY_LEN}, so the call was not run and nothing was changed. Send it again with a {KEY_WORDS}." + )) + } else { + None + } + } + Some(_) => Some(format!( + "the request_key must be text, so the call was not run and nothing was changed. Send it again with a {KEY_WORDS}." + )), + } +} + +/// The key as text, once it has passed [`key_problem`]. +pub(crate) fn key_text(key: &Value) -> String { + key.as_str().unwrap_or_default().to_string() +} + +/// The tool list's schema for a write tool: `request_key` is a required +/// property (INVARIANT 1). A read-only tool's is left as it is. +pub(crate) fn add_key_to_schema(tool: &mut rmcp::model::Tool) { + if !writes(&tool.name) { + return; + } + let mut schema: Map = (*tool.input_schema).clone(); + let props = schema + .entry("properties") + .or_insert_with(|| Value::Object(Map::new())); + if let Value::Object(props) = props { + props.insert( + KEY_FIELD.into(), + json!({ + "type": "string", + "minLength": MIN_KEY_LEN, + "maxLength": MAX_KEY_LEN, + "description": KEY_WORDS, + }), + ); + } + let required = schema + .entry("required") + .or_insert_with(|| Value::Array(Vec::new())); + if let Value::Array(required) = required + && !required.iter().any(|r| r == KEY_FIELD) + { + required.push(json!(KEY_FIELD)); + } + tool.input_schema = std::sync::Arc::new(schema); +} + +/// What opening a call came to. +pub(crate) enum Begun { + /// The call is open: run the tool. + Run, + /// Not run: this is the answer, and the access record's code. + Answer(Box, &'static str), +} + +fn refusal(text: String) -> CallToolResponse { + CallToolResponse::Complete(CallToolResult::error(vec![ + rmcp::model::ContentBlock::text(text), + ])) +} + +/// 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 { + let mut store = server.lock()?; + if let Err(e) = store.ensure_takes_calls() { + return Ok(Begun::Answer( + Box::new(refusal(e.to_string())), + UPGRADE_PENDING, + )); + } + if let Some(kept) = store.recorded_call(&id.token, &id.key) { + 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)), + 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", + if kept.tool == id.tool { + "the same tool".to_string() + } else { + kept.tool.clone() + } + ))), + KEY_REUSED, + )); + } + store.begin_call(id).map_err(|e| e.to_string())?; + Ok(Begun::Run) +} + +/// The text of the first text block, or "". +fn first_text(r: &CallToolResult) -> &str { + r.content + .iter() + .find_map(|c| match c { + rmcp::model::ContentBlock::Text(t) => Some(t.text.as_str()), + _ => None, + }) + .unwrap_or("") +} + +/// Whether a tool's final answer is one that committed: a result that is +/// not an error, and the call not stopped by a close (INVARIANT 4). +pub(crate) fn answered_ok( + out: &Result, + stopped_by_close: bool, +) -> bool { + !stopped_by_close + && matches!(out, Ok(CallToolResponse::Complete(r)) if r.is_error != Some(true)) +} + +/// 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. +pub(crate) fn close( + server: &BooksServer, + out: &Result, + ok: bool, +) -> Result<(), String> { + use ledger_core::parties::{has_full_tin, redact_full_tins}; + let mut store = server.lock()?; + if !store.in_call() { + return Ok(()); + } + let masked = |text: String| { + if has_full_tin(&text) { + redact_full_tins(&text).into_owned() + } else { + text + } + }; + let ended = if ok { + let Ok(CallToolResponse::Complete(r)) = out else { + return Err("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())?; + store.close_call(CallEnd::Done(&text)) + } else { + let why = match out { + Ok(CallToolResponse::Complete(r)) => first_text(r).to_string(), + Ok(_) => "the call did not complete".to_string(), + Err(e) => e.message.to_string(), + }; + let why = if why.is_empty() { + "the call failed".to_string() + } else { + why + }; + store.close_call(CallEnd::Failed(&masked(why))) + }; + ended.map_err(|e| e.to_string()) +} + +/// 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/local.rs b/crates/ledger-mcp/src/local.rs index d767ab6f..78943734 100644 --- a/crates/ledger-mcp/src/local.rs +++ b/crates/ledger-mcp/src/local.rs @@ -4769,8 +4769,12 @@ mod tests { assert_eq!(added.len(), 1, "one line"); assert_eq!(added[0]["type"], "journal.format_set"); let c = ledger_store::format::current(); + // The declaration also gives older books their id (plan P15 6a). + let mut declared = added[0]["payload"].clone(); + let books_id = declared.as_object_mut().unwrap().remove("books_id"); + assert_eq!(books_id.and_then(|v| v.as_str().map(str::len)), Some(32)); assert_eq!( - added[0]["payload"], + declared, serde_json::json!({"format": c.format, "features": c.features}) ); assert_eq!(done.head.0, backup.head.0 + 1); diff --git a/crates/ledger-mcp/src/server.rs b/crates/ledger-mcp/src/server.rs index 50018111..d31671d7 100644 --- a/crates/ledger-mcp/src/server.rs +++ b/crates/ledger-mcp/src/server.rs @@ -222,6 +222,11 @@ pub struct SharedStore { running: std::sync::atomic::AtomicUsize, /// Woken whenever one ends. ended: tokio::sync::Notify, + /// The write turn (calls.rs INVARIANT 2): held for a write call's + /// whole run, from its key being looked up to its closing line, and + /// for the owner's format upgrade, so a call's lines are one run in + /// the journal. + writes: tokio::sync::Mutex<()>, /// The books' base currency, fixed at their creation: read without /// the lock (the connect text names it). currency: Currency, @@ -240,6 +245,13 @@ impl SharedStore { Ok(f(store)) } + /// Wait for the write turn (calls.rs INVARIANT 2). Blocking, on a + /// blocking thread, as the store's lock is; unlike it, the turn is + /// held across a call's awaits, so its guard is `Send`. + pub(crate) fn write_turn(&self) -> tokio::sync::MutexGuard<'_, ()> { + self.writes.blocking_lock() + } + /// 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 @@ -257,6 +269,8 @@ impl SharedStore { if self.closing() { return Err("the books are closing".into()); } + // Not inside a tool's call: its lines are a run of their own. + let _turn = self.write_turn(); let mut store = self.store.blocking_lock(); if self.stopped() { return Err(STOPPED.to_string()); @@ -318,6 +332,7 @@ impl SharedStore { hurry: Arc::default(), running: std::sync::atomic::AtomicUsize::new(0), ended: tokio::sync::Notify::new(), + writes: tokio::sync::Mutex::new(()), }) } @@ -1514,6 +1529,8 @@ enum ShownDates { mod access_tools; #[path = "tools/backup.rs"] mod backup_tools; +#[path = "calls.rs"] +mod calls; #[path = "tools/files.rs"] mod files; #[path = "guards.rs"] @@ -1783,11 +1800,17 @@ impl BooksServer { impl ServerHandler for BooksServer { async fn call_tool( &self, - request: rmcp::model::CallToolRequestParams, + mut request: rmcp::model::CallToolRequestParams, context: RequestContext, ) -> Result { use crate::access::{self, Call}; use ledger_store::access::Outcome; + // The request key is the call's own, not the tool's: out of the + // arguments here, so no tool, preview digest or record sees it as + // an argument (calls.rs INVARIANT 1). A call writes when its tool + // can change the books and it is not a preview. + let request_key = calls::take_key(&mut request.arguments); + let writing = calls::is_write_call(&request.name, request.arguments.as_ref()); let mut call = Call::new(&self.access, &self.board, &context, "tool", &request.name); let outcome_of = |out: &Result| match out { Ok(rmcp::model::CallToolResponse::Complete(r)) if r.is_error != Some(true) => { @@ -1861,7 +1884,16 @@ impl ServerHandler for BooksServer { Err(rmcp::ErrorData::invalid_params(why, None)), ) }), - }; + } + // A write without a usable request key isn't run (calls.rs + // INVARIANT 1). + .or_else(|| { + if !writing { + return None; + } + calls::key_problem(request_key.as_ref()) + .map(|why| (calls::MISSING_KEY, Ok(tool_error(why)))) + }); if let Some((code, answer)) = refusal { call.digested(refused_digest(request.arguments.clone()).await); return self.refuse(&call, code, answer).await; @@ -1900,6 +1932,46 @@ impl ServerHandler for BooksServer { }); // Counted as running by now (run_blocking): hashed here. let digest = Call::digest_of(request.arguments.as_ref()); + // A write call is one transaction (calls.rs): it takes its + // turn among writes, and is opened, or answered from its + // key, before the tool runs. + let call_id = + request_key + .as_ref() + .filter(|_| writing) + .map(|k| ledger_store::calls::CallId { + token: running_call + .caller() + .map(|c| c.token.id.clone()) + .unwrap_or_default(), + tool: tool_name.clone(), + key: calls::key_text(k), + args: digest.clone().unwrap_or_default(), + }); + 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()) { + Ok(calls::Begun::Run) => None, + Ok(calls::Begun::Answer(answer, code)) => Some((answer, code)), + Err(why) => Some((Box::new(tool_error(why)), access::STOPPED)), + }, + }; + if let Some((answer, code)) = early { + // Not run: refused (with the guards a refusal carries), + // or answered again from the books as it was first + // answered. + let answer = if code == calls::REPEAT { + Ok(*answer) + } else { + next_steps::apply(&server, &tool_name, envelope_args.as_ref(), Ok(*answer)) + }; + YOU.with(|y| y.borrow_mut().take()); + let mut c = running_call; + c.digested(digest); + let recorded = c.record_blocking(Outcome::Refused(code.into()), None); + return (answer, recorded); + } let tcc = rmcp::handler::server::tool::ToolCallContext::new(&server, request, context); let router = Self::tool_router(); @@ -1927,7 +1999,26 @@ impl ServerHandler for BooksServer { } }; // The result envelope (next_steps.rs INVARIANT 1). - let out = next_steps::apply(&server, &tool_name, envelope_args.as_ref(), out); + let mut out = next_steps::apply(&server, &tool_name, envelope_args.as_ref(), out); + let stopped = STOPPED_BY_CLOSE.with(|s| s.replace(false)); + // The call is over: its closing line, holding the answer + // the caller is given, commits it (or, for a call that + // failed or was stopped, rolls it back). Only then does it + // count as done (calls.rs INVARIANT 4). + 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())); + } + // The closing line is this call's last write. + wrote = WROTE + .with(|w| w.borrow_mut().take()) + .map(|(seq, hash)| ledger_store::chain::Head { seq, hash }) + .or(wrote); + } // Who asked is the request's alone: a later request on this // thread (a resource read) must not see it. YOU.with(|y| y.borrow_mut().take()); @@ -1936,7 +2027,7 @@ impl ServerHandler for BooksServer { c.with_agent(AGENT_NOTE.with(|a| a.borrow_mut().take())); // A call a close stopped is on record as stopped, not as an // answer it gave (local.rs INVARIANT 10). - let outcome = if STOPPED_BY_CLOSE.with(|s| s.replace(false)) { + let outcome = if stopped { Outcome::Refused(access::STOPPED_BY_CLOSE.into()) } else { outcome_of(&out) @@ -1977,6 +2068,9 @@ impl ServerHandler for BooksServer { context: RequestContext, ) -> Result { let mut tools = Self::tool_router().list_all(); + // Every tool that can change the books takes a request key + // (calls.rs INVARIANT 1). + tools.iter_mut().for_each(calls::add_key_to_schema); // A token is shown what it can call (scopes.rs); the list then // differs by caller, so it may be cached only for this one. let scopes = crate::access::caller(&context) diff --git a/crates/ledger-store/src/store.rs b/crates/ledger-store/src/store.rs index 5880a531..cb171003 100644 --- a/crates/ledger-store/src/store.rs +++ b/crates/ledger-store/src/store.rs @@ -6565,6 +6565,13 @@ impl Store { crate::cancel::check()?; replay_line_into_ledger(&mut self.ledger, &lines[i], self.base_currency)?; } + // A call open now (the verification that heals is itself a call) + // keeps its projection transaction, on the new connection + // (calls.rs). It has written no line a rebuild would lose: it + // reads and rebuilds, nothing more. + if self.call.is_some() { + self.conn.execute_batch("SAVEPOINT call_tx")?; + } Ok(()) } diff --git a/crates/ledger-store/tests/calls.rs b/crates/ledger-store/tests/calls.rs index 58f340d6..54e46081 100644 --- a/crates/ledger-store/tests/calls.rs +++ b/crates/ledger-store/tests/calls.rs @@ -154,8 +154,10 @@ fn a_failed_call_is_on_the_record_and_builds_nothing() { s.verify().unwrap(); } +type Step = Box; + /// A call of every kind of step, by how far it got. -fn steps() -> Vec> { +fn steps() -> Vec { vec![ Box::new(|s| { s.create_entry(d(2026, 1, 5), "One").unwrap(); @@ -414,3 +416,19 @@ fn a_call_cannot_begin_inside_another_or_after_a_failed_close() { Err(StoreError::CallRefused(_)) )); } + +#[test] +fn a_call_that_rebuilds_the_projection_still_commits() { + // books.verify heals a drifted projection by rebuilding it, and is a + // call like any other: its transaction moves to the new database. + let tmp = tempfile::tempdir().unwrap(); + let mut s = books(tmp.path()); + s.begin_call(id("key-heal-0001")).unwrap(); + s.rebuild().unwrap(); + s.close_call(CallEnd::Done("{}")).unwrap(); + s.verify().unwrap(); + assert!(s.recorded_call("token-1", "key-heal-0001").is_some()); + drop(s); + let s = Store::open(tmp.path()).unwrap(); + s.verify().unwrap(); +} diff --git a/docs/mcp-interface.md b/docs/mcp-interface.md index 9bc54854..d2a4f266 100644 --- a/docs/mcp-interface.md +++ b/docs/mcp-interface.md @@ -611,6 +611,34 @@ with generated URIs, checks after each call that the server still serves, restarts it after them to check the books reopen, and drives every tool over every book in ledger-store's `tests/fixtures/old-books`. +## Writes: one transaction, one request key (plan P15 2a, D-88) + +Every tool that can change the books (no `readOnlyHint`; 83 of the 140: the +three that read what is sealed and put it in a file, `books.vendor_1099`, +`books.get_w9` and `books.export_cpa_package`, are annotated so but write +nothing and may answer with a full TIN, so they are read like any read) +takes one more argument than its own, `request_key`, and its schema says it +is required: 8 to 128 characters of plain text the agent makes up, new for +each different action and never reused for another. The agent sends the same +call again with the same key when its answer is lost; the books do not do it +twice, and answer what they answered the first time (a repeat is recorded in +the access log as `repeat`, and writes nothing, even after the books were +closed and opened). The same key with other arguments, or another tool, is +refused in words and changes nothing. A key is the token's own. A write +without a usable key is refused in words before it runs. A preview (a tool +with `confirmed`, called without `confirmed: true`) writes nothing and needs +no key. A failed write changes nothing and leaves its key free: the corrected +call may use it; where the call got as far as writing journal lines, the +journal says it failed (`call.closed`, outcome `failed`) and none of them +count. Every write call is one transaction: its lines commit together with +its closing line or not at all, and after a crash a call without its closing +line is not treated as done (WB-format-8 to WB-format-10). + +Books an older version wrote take no write at all until the owner gives the +format upgrade its go-ahead (D-89, WB-format-11): every write is refused, +before it runs, with `format_upgrade_pending` and the words "nothing can be +written"; every read works as ever. No tool can give the go-ahead. + ## Tool design principles - **Narrow tools, explicit arguments.** No "do what I mean" tools. The agent diff --git a/docs/parity.md b/docs/parity.md index 93440f2e..12662de6 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -256,3 +256,11 @@ Three new rows, none above changed status, and the floor stands. | Books home: a visible folder per book, `/Wanderbooks/`, holding `AGENTS.md`, `CLAUDE.md`, `.mcp.json` and `.claude/settings.json` and nothing of the books | A QBO/Xero company has no counterpart; the point is the agent's workplace (D-27) | partial | `books_home_holds_no_books_data`, `a_books_home_made_again_keeps_what_a_person_kept` (`crates/ledger-host/tests/books_home.rs`); `partial` until the macOS home is tried | | Agent dock: Claude Code or Codex in a terminal along the bottom of the viewer, started in the books home; never required | QBO's assistant panel is a cross-check only | partial | `dock_runs_the_chosen_agent`, `agent_missing_offers_the_installer` (`crates/ledger-gui/tests/dock.rs`); Linux checked; macOS by the CI run; Windows not offered (ConPTY unchecked) | | First run with no terminal: the viewer sets up the private folder, the owner passphrase, the first books and an agent | QBO's "set up your company" flow | partial | `first_run_onboards_with_no_terminal` (`crates/ledger-gui/tests/welcome.rs`); the AppImage's whole path is the EM's to try on a clean machine | + +## P15 T1: every write is one transaction, exactly once (2026-11-21, D-88, D-89) + +| Area | Counterpart (a cross-check, not the spec) | Status | Notes | +|---|---|---|---| +| A tool call's lines commit together with a closing line or not at all; a call that never closed, or failed, builds nothing in any replay; a failed call is on the record | A database transaction; QBO and Xero make a write all or nothing and say so on failure | partial | WB-format-8, WB-format-10; `ledger-store` `tests/calls.rs` (`a_crash_at_each_point_of_a_call_leaves_the_whole_call_or_none_of_it`, `a_replay_of_any_prefix_inside_a_call_is_the_replay_of_the_prefix_before_it`, `a_failed_call_is_on_the_record_and_builds_nothing`); partial until the Lean law is in bookspec and a `done` needs a golden | +| Every write carries a request key; a repeat returns the first answer and writes nothing, across a restart; the same key for another request is refused | An idempotency key (a payments API's `Idempotency-Key`); QBO's `requestid` | partial | WB-format-9; `ledger-cli` `tests/call_transactions.rs` (`a_repeat_of_a_key_returns_the_first_answer_and_writes_nothing`, `the_same_key_for_another_request_is_refused_in_words`, `every_tool_that_can_write_asks_for_a_key_and_no_other_does`); `books.import_bank_csv` is one transaction (`the_import_is_one_transaction`) | +| Books that haven't declared the feature take no write and still read; every set of books has a unique id | No counterpart; the owner's rule (D-89) | partial | WB-format-11, WB-format-12; `ledger-store` `tests/calls.rs` (`books_that_have_not_declared_the_feature_take_no_call_and_still_read`, `new_books_are_born_with_an_id_and_no_two_share_one`); `ledger-cli` `tests/format_upgrade.rs` (`books_p2_served_cut_over_whole`) | diff --git a/docs/spec/claims/format.md b/docs/spec/claims/format.md index e3091de0..8bb193a3 100644 --- a/docs/spec/claims/format.md +++ b/docs/spec/claims/format.md @@ -258,7 +258,9 @@ restart). **WB-format-9 Every write call carries a request key, and a repeat of it writes nothing.** Every tool that can change the books (no `readOnlyHint`; -86 of the 140) takes a required `request_key`, 8 to 128 characters of plain +83 of the 140: the three that only read what is sealed, `books.vendor_1099`, +`books.get_w9` and `books.export_cpa_package`, write nothing and may answer with +a full TIN, so they are reads) takes a required `request_key`, 8 to 128 characters of plain text, which the agent makes up, new for each action. A write without a usable key is refused in words before it runs; a preview (a confirmed tool called without `confirmed: true`) writes nothing and needs none. The key is taken out @@ -270,7 +272,8 @@ misuse of the key, and nothing is changed. A key is the token's own: two tokens with one key are two keys. The key table is rebuilt at every open from the `ok` closing lines alone. A repeat that arrives while its original is still running waits for it (calls take turns) and gets its answer. An answer -that holds a full TIN is kept masked, so its repeat returns it masked +is kept as given: no tool answer holds a full TIN, and the three tools that +can are no transaction; an error text that holds one is kept masked (BS-partner-2: no journal line holds one). *Enforced:* ledger-mcp `calls::is_write_call`, `calls::key_problem`, `calls::begin`, `calls::close`, `calls::add_key_to_schema`, `Store::recorded_call`, `Keys`. *Checked:* `ledger-cli` `tests/call_transactions.rs` (`a_repeat_of_a_key_returns_the_first_answer_and_writes_nothing`, `the_same_key_for_another_request_is_refused_in_words`, `a_write_without_a_usable_key_is_not_run`, `every_tool_that_can_write_asks_for_a_key_and_no_other_does`); `ledger-store` `tests/calls.rs` (`a_call_is_framed_and_its_answer_kept_by_key`). From d4c0036599602da5f7e50bf4e0231f3be4904dce Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 10:09:17 -0700 Subject: [PATCH 3/6] fix(store,gui,package): every reader that derives facts reads the committed journal (P15 T1 review) A failed call's ids are handed out again (nothing it wrote counted), so a reader of the raw journal pins dead lines on whatever takes the id next: a failed books.create_bill for entry 42 then a manual entry 42 showed as a Bill. One accessor, calls::committed (lines outside a call and of calls that closed ok, the frame left out), now feeds the viewer's books (entry events and origin, asset trails, party events), the package feed attention reads, and the adopt preview's settings check. The journal page and journal_history keep every line and say in words of each line of a call that failed, never finished or is still running that it did not count. A call's closing line is now bounded (ANSWER_CAP 4 KiB: above it, the answer's SHA-256 and length), a call that wrote no line leaves no line (its key and answer live in a bounded in-memory table), and the journaled argument digest is an HMAC under the books' own call key, so two requests that differ only in a tax id are two requests and nothing journaled lets a guess of one be tested. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-gui/src/attention.rs | 2 +- crates/ledger-gui/src/books.rs | 28 +- crates/ledger-gui/src/pages/journal.rs | 43 +- crates/ledger-gui/tests/view_model.rs | 114 +++++ crates/ledger-package/src/books.rs | 17 +- crates/ledger-store/src/calls.rs | 584 +++++++++++++++++++++---- crates/ledger-store/src/describe.rs | 34 +- crates/ledger-store/src/error.rs | 6 + crates/ledger-store/src/root.rs | 23 +- crates/ledger-store/src/snapshot.rs | 19 +- crates/ledger-store/tests/calls.rs | 200 ++++++++- 11 files changed, 950 insertions(+), 120 deletions(-) diff --git a/crates/ledger-gui/src/attention.rs b/crates/ledger-gui/src/attention.rs index ea0b1741..148228f0 100644 --- a/crates/ledger-gui/src/attention.rs +++ b/crates/ledger-gui/src/attention.rs @@ -89,7 +89,7 @@ impl ledger_package::PackageBooks for View<'_> { } fn journal_seq(&self) -> u64 { - self.0.journal.len() as u64 + self.0.head_seq } fn journal(&self) -> Result, StoreError> { diff --git a/crates/ledger-gui/src/books.rs b/crates/ledger-gui/src/books.rs index badf7e37..2399bfc2 100644 --- a/crates/ledger-gui/src/books.rs +++ b/crates/ledger-gui/src/books.rs @@ -274,7 +274,20 @@ pub struct Books { pub settings: BooksSettings, pub data_dir: PathBuf, pub attachments: Vec, + /// The committed journal: the lines that are facts of the books (those + /// outside any call and those of calls that closed `ok`), the frame + /// lines left out. Every fact the viewer derives from the journal + /// (an entry's events and origin, an asset's trail, a party's events) + /// comes from here, never from [`Books::history`]: ids are handed out + /// again after a failed call, so a dead line would be pinned on + /// whatever takes the id next (ledger_store::calls). pub journal: Vec, + /// Every line of the journal, in order (seq = index + 1), and each + /// line's standing: for the journal page, which shows history and + /// says of a line that did not count that it did not. + pub history: Vec<(JournalLine, ledger_store::calls::Standing)>, + /// The seq of the journal's last line. + pub head_seq: u64, pub head: String, pub today: NaiveDate, pub loaded_at: chrono::DateTime, @@ -605,7 +618,14 @@ impl Books { ) -> Result { let ledger = snap.ledger().clone(); let attachments = snap.attachments(None).map_err(|e| e.to_string())?; - let journal = snap.journal().to_vec(); + let journal = snap.committed_journal().map_err(|e| e.to_string())?; + let history: Vec<_> = snap + .journal() + .iter() + .cloned() + .zip(snap.journal_standings().map_err(|e| e.to_string())?) + .collect(); + let head_seq = snap.journal_seq(); // The server's own rule, so the viewer flags exactly what the // server would refuse: the books' settings. let policy = ledger_config::codec::receipt_policy(ledger.settings()); @@ -676,7 +696,7 @@ impl Books { let statements = snap.statements(None).map_err(|e| e.to_string())?; let reconciliations = snap.reconciliations(None).map_err(|e| e.to_string())?; let extractions = snap.extractions().map_err(|e| e.to_string())?; - let fresh_from_seq = prev_seq.unwrap_or(journal.len() as u64); + let fresh_from_seq = prev_seq.unwrap_or(head_seq); let mut fresh = HashSet::new(); let closings = ledger.closing_entry_ids(); let mut entries = Vec::new(); @@ -817,6 +837,8 @@ impl Books { data_dir: snap.data_dir().to_path_buf(), attachments, journal, + history, + head_seq, head: snap.head_hash().to_string(), today, loaded_at: chrono::Utc::now(), @@ -864,7 +886,7 @@ impl Books { } pub fn seq(&self) -> u64 { - self.journal.len() as u64 + self.head_seq } pub fn entry(&self, id: EntryId) -> Option<&EntryInfo> { diff --git a/crates/ledger-gui/src/pages/journal.rs b/crates/ledger-gui/src/pages/journal.rs index 2bb8d345..a2ddbf0c 100644 --- a/crates/ledger-gui/src/pages/journal.rs +++ b/crates/ledger-gui/src/pages/journal.rs @@ -1270,6 +1270,24 @@ pub fn describe(b: &Books, line: &JournalLine) -> Option { } } +/// A journal line's event for the journal page: the sentence the books +/// give it when it counts; for a line of a call that did not count, its +/// plain description from the journal's own words and the note that it did +/// not count, never a sentence built from the books' present state (ids +/// are handed out again after a failed call, so "Posted #42" would name +/// whatever took 42 next), and no link. +pub fn event_for(b: &Books, line: &JournalLine, standing: ledger_store::calls::Standing) -> Event { + match standing.note() { + None => describe_any(b, line), + Some(note) => Event { + icon: icon::WARNING, + text: format!("{} ({note})", ledger_store::describe::describe(line)), + route: None, + also: None, + }, + } +} + /// Like [`describe`], but every event gets a sentence. pub fn describe_any(b: &Books, line: &JournalLine) -> Event { if let Some(e) = describe(b, line) { @@ -1342,7 +1360,7 @@ pub fn describe_any(b: &Books, line: &JournalLine) -> Event { pub fn show(ui: &mut Ui, b: &Books, selected: Option, shell: &mut Shell<'_>) { if let Some(seq) = selected - && let Some(line) = b.journal.get(seq.saturating_sub(1) as usize) + && let Some((line, standing)) = b.history.get(seq.saturating_sub(1) as usize) { super::split( ui, @@ -1350,7 +1368,7 @@ pub fn show(ui: &mut Ui, b: &Books, selected: Option, shell: &mut Shell<'_> 480.0, shell, |ui, shell| list(ui, b, selected, shell), - |ui, shell| detail(ui, b, line, shell), + |ui, shell| detail(ui, b, line, *standing, shell), ); } else { list(ui, b, None, shell); @@ -1365,7 +1383,7 @@ fn list(ui: &mut Ui, b: &Books, selected: Option, shell: &mut Shell<'_>) { "Journal", &format!( "Every change to the books, in order: {} events, each hash-chained to the one before. Nothing is ever edited or deleted; corrections are new events.", - b.journal.len() + b.history.len() ), ); let st = &mut shell.state.journal; @@ -1381,11 +1399,11 @@ fn list(ui: &mut Ui, b: &Books, selected: Option, shell: &mut Shell<'_>) { let q = st.query.to_lowercase(); let hide = st.hide_steps; let rows: Vec<(&JournalLine, Event)> = b - .journal + .history .iter() .rev() - .filter(|l| !(hide && describe(b, l).is_none())) - .map(|l| (l, describe_any(b, l))) + .filter(|(l, st)| !(hide && st.counts() && describe(b, l).is_none())) + .map(|(l, st)| (l, event_for(b, l, *st))) .filter(|(l, e)| { q.is_empty() || e.text.to_lowercase().contains(&q) || l.line_type.contains(&q) }) @@ -1461,9 +1479,15 @@ fn list(ui: &mut Ui, b: &Books, selected: Option, shell: &mut Shell<'_>) { }); } -fn detail(ui: &mut Ui, b: &Books, line: &JournalLine, shell: &mut Shell<'_>) { +fn detail( + ui: &mut Ui, + b: &Books, + line: &JournalLine, + standing: ledger_store::calls::Standing, + shell: &mut Shell<'_>, +) { let p = pal(ui.ctx()); - let ev = describe_any(b, line); + let ev = event_for(b, line, standing); egui::ScrollArea::vertical() .id_salt("event_detail") .show(ui, |ui| { @@ -1485,6 +1509,9 @@ fn detail(ui: &mut Ui, b: &Books, line: &JournalLine, shell: &mut Shell<'_>) { ui.add(egui::Label::new(RichText::new(v).font(theme::regular(12.5))).wrap()); }); }; + if let Some(note) = standing.note() { + fact(ui, "Counts", note); + } fact(ui, "Type", &line.line_type); fact(ui, "Recorded", &fmt::timestamp(&line.ts)); fact(ui, "Previous", &line.prev); diff --git a/crates/ledger-gui/tests/view_model.rs b/crates/ledger-gui/tests/view_model.rs index c72801d7..bda7f7c7 100644 --- a/crates/ledger-gui/tests/view_model.rs +++ b/crates/ledger-gui/tests/view_model.rs @@ -986,3 +986,117 @@ fn the_viewer_holds_a_numbered_invoice_as_the_store_does() { assert_eq!(shown.terms.as_ref().unwrap().describe(), "2/10 net 30"); assert_eq!(shown.lines[0].quantity, Some(Decimal::new(3, 0))); } + +/// A call that failed after writing lines, followed by a call that takes +/// the ids it handed out again (nothing it wrote counted): the viewer's +/// books, the package feed that attention reads, and the history all say +/// the dead lines are not facts, and nothing of the dead call is pinned on +/// what took its ids (WB-format-12). +#[test] +fn a_failed_calls_lines_are_not_facts_when_its_ids_are_used_again() { + use ledger_store::calls::{CallEnd, CallId, Standing}; + let (d, mut s) = store_at("failed-call"); + let today = NaiveDate::from_ymd_opt(2026, 5, 20).unwrap(); + let cash = s + .add_account("1000", "Checking", AccountType::Asset, None, false) + .unwrap(); + let cap = s + .add_account("3000", "Capital", AccountType::Equity, None, false) + .unwrap(); + let id = |key: &str, tool: &str| CallId { + token: "t".into(), + tool: tool.into(), + key: key.into(), + args: "a".repeat(64), + }; + let lines = |amount: i64| { + vec![DocumentLine { + description: "x".into(), + amount: Decimal::new(amount, 2), + class_id: None, + account: None, + quantity: None, + unit_price: None, + }] + }; + let before = s.journal_seq(); + // A failed books.create_bill: a vendor, a bill, an entry (id 1). + s.begin_call(id("key-dead-0001", "books.create_bill")) + .unwrap(); + let dead_vendor = s.add_vendor("Dead Vendor").unwrap(); + s.create_bill(dead_vendor, today, today + Days::new(30), lines(5_000)) + .unwrap(); + s.close_call(CallEnd::Failed("the call failed after its lines")) + .unwrap(); + let dead_end = s.journal_seq(); + assert!(dead_end > before + 3); + // A manual entry, which takes entry id 1 again, and a vendor, which + // takes party id 1 again. + let e = s.create_entry(today, "Opening deposit").unwrap(); + assert_eq!(e, 1, "the failed call's entry id is handed out again"); + let m = Money::new(Decimal::new(100_000, 2), Currency::USD); + s.add_line(e, cash, Side::Debit, m).unwrap(); + s.add_line(e, cap, Side::Credit, m).unwrap(); + s.post_entry(e).unwrap(); + let live_vendor = s.add_vendor("Real Vendor").unwrap(); + assert_eq!(live_vendor, dead_vendor); + drop(s); + let source = Source { + data_dir: d.join("books-data"), + today: Some(today), + }; + let b = data::load_once(&source).unwrap(); + // The entry is a manual one: not a "Bill", which is what the dead + // bill.created line (for entry 1) would have made of it. + let entry = b.entry(e).unwrap(); + assert_eq!(entry.origin, "Journal entry"); + assert!( + entry + .events + .iter() + .all(|&i| !(before + 1..=dead_end).contains(&b.journal[i].seq)), + "an entry's events include a dead line" + ); + // No fact the viewer derives holds a dead line: the committed journal + // has none of them, and none of the frame. + assert!( + b.journal + .iter() + .all(|l| !(before + 1..=dead_end).contains(&l.seq) && !l.line_type.starts_with("call.")) + ); + // The party that took the id again has none of the dead vendor's events. + let party = &b.parties[&live_vendor]; + assert!( + party + .events + .iter() + .all(|&i| !(before + 1..=dead_end).contains(&b.journal[i].seq)) + ); + // The package feed attention reads is the same committed journal. + let snap = ledger_store::Snapshot::load(&d.join("books-data")).unwrap(); + let fed = ledger_package::PackageBooks::journal(&snap).unwrap(); + assert_eq!(fed.len(), b.journal.len()); + assert!( + fed.iter() + .all(|l| !(before + 1..=dead_end).contains(&l.seq)) + ); + let store = Store::open(&d.join("books-data")).unwrap(); + let fed = ledger_package::PackageBooks::journal(&store).unwrap(); + assert_eq!(fed.len(), b.journal.len()); + // The viewer's seq is the journal's head, frame lines counted. + assert_eq!(b.seq(), b.history.len() as u64); + // History shows every line, and says of the dead ones in words that + // they did not count; the viewer never names a dead line by the live + // entry that took its id. + let dead: Vec<_> = b + .history + .iter() + .filter(|(_, st)| *st == Standing::Failed) + .collect(); + assert!(dead.len() >= 3); + for (line, st) in dead { + let ev = ledger_gui::pages::journal::event_for(&b, line, *st); + assert!(ev.text.contains("not counted"), "{}", ev.text); + assert!(ev.route.is_none()); + } +} diff --git a/crates/ledger-package/src/books.rs b/crates/ledger-package/src/books.rs index d35e7bf0..c3dcc5a9 100644 --- a/crates/ledger-package/src/books.rs +++ b/crates/ledger-package/src/books.rs @@ -9,7 +9,7 @@ //! INVARIANTS: //! 1. Every method only reads. //! 2. A Store and a Snapshot of the same journal answer every method -//! alike: the same ledger, settings, journal, journal seq, +//! alike: the same ledger, settings, committed journal, journal seq, //! attachments (withdrawn ones included), bytes, statements, and //! reconciliations, and the same entry links once the filing entry //! is added (a store lists it in `links_of`; a snapshot only lists @@ -39,8 +39,12 @@ pub trait PackageBooks { /// package reflects. fn journal_seq(&self) -> u64; - /// Every journal line, in order: what an entry's origin and its events - /// are read from. + /// The committed journal, in order: what an entry's origin and its + /// events are read from. Only the lines that are facts of the books + /// (ledger_store::calls::committed): the lines of a call that failed or + /// never finished are not here, because ids are handed out again after + /// a failed call and a reader that took them would pin dead lines on + /// whatever takes the id next (WB-format-12). fn journal(&self) -> Result, StoreError>; /// Every attachment (receipts and documents), withdrawn ones @@ -83,9 +87,10 @@ impl PackageBooks for Store { } fn journal(&self) -> Result, StoreError> { - ledger_store::journal::read_and_verify_journal( + let lines = ledger_store::journal::read_and_verify_journal( &Store::data_dir(self).join(ledger_store::JOURNAL_FILE), - ) + )?; + ledger_store::calls::committed(&lines) } fn all_attachments(&self) -> Result, StoreError> { @@ -134,7 +139,7 @@ impl PackageBooks for Snapshot { } fn journal(&self) -> Result, StoreError> { - Ok(Snapshot::journal(self).to_vec()) + Snapshot::committed_journal(self) } fn all_attachments(&self) -> Result, StoreError> { diff --git a/crates/ledger-store/src/calls.rs b/crates/ledger-store/src/calls.rs index e8882bc1..97c20115 100644 --- a/crates/ledger-store/src/calls.rs +++ b/crates/ledger-store/src/calls.rs @@ -1,21 +1,33 @@ //! Calls: every write a tool makes is one transaction that happens once //! (plan P15 2a, D-88, D-89). //! -//! A call that writes frames its journal lines with two line types, and -//! a call that wrote nothing is just a closing line: +//! A call that writes journal lines frames them with two line types; a +//! call that wrote none leaves nothing in the journal at all: //! //! * `call.begun { tool, token, key, args }`, written lazily, just before //! the call's first line; //! * `call.closed { tool, token, key, args, outcome, first_seq, last_seq, -//! answer | error }`, written when the call is over. `outcome` is `ok` -//! (the answer the caller was given is `answer`, kept as text so a -//! repeat returns it byte for byte), `failed` (the call got as far as -//! writing lines and then failed: `error` says how), or `unfinished` -//! (written by the next open of books whose last call never closed). +//! answer | answer_sha256 + answer_bytes | error }`, written when the +//! call is over. `outcome` is `ok` (the answer the caller was given is +//! `answer`, kept as text so a repeat returns it byte for byte; above +//! [`ANSWER_CAP`] bytes the closing line keeps `answer_sha256` and +//! `answer_bytes` instead, and a repeat is told in words that the call +//! was done), `failed` (the call got as far as writing lines and then +//! failed: `error` says how), or `unfinished` (written by the next open +//! of books whose last call never closed). +//! +//! `args` is a keyed digest of the call's arguments (HMAC-SHA256 under +//! the books' own call key, `keys/calls.key`, never journaled): the +//! arguments themselves, and any tax id in them, are not recoverable or +//! testable from the journal. //! //! The lines between a begin and its close count only if the close says //! `ok`: that is how a reader tells a complete call from an incomplete -//! one, and the one rule every replay uses ([`CallGate`]). The envelope +//! one, and the one rule every reader applies ([`CallGate`], [`standings`], +//! [`committed`]). Ids are handed out again after a failed call (nothing +//! it wrote counted), so a reader that takes the journal raw would pin the +//! dead lines of a failed call on whatever takes the id next: every reader +//! that derives a fact reads [`committed`]. The envelope //! `{seq, ts, type, payload, prev}` is untouched. //! //! ```text @@ -34,17 +46,28 @@ //! books declared the feature, and the owner's own acts: the format //! declaration, a repaired tail) apply as ever. //! 3. A close names the frame it ends: its `first_seq` is the begin -//! line's seq and its `last_seq` the line before it, or both are -//! absent when the call wrote no lines. A begin inside a frame, a -//! mismatched close, or an `unfinished` close with no frame is a -//! corrupt journal. +//! line's seq and its `last_seq` the line before it. A close with no +//! frame, a begin inside a frame, a mismatched close, or an +//! `unfinished` close with no frame is a corrupt journal. //! 4. The projection never holds a line of a call that did not commit: //! the call's SQLite changes live in one transaction that is released //! only after the `ok` closing line is on disk. -//! 5. The key table (token, key) -> answer is built from `ok` closing -//! lines alone, so a restart rebuilds it from the journal. +//! 5. The key table (token, key) -> call is built from `ok` closing +//! lines alone, so a restart rebuilds it from the journal. A call +//! that wrote no line has no closing line: its key and answer are +//! kept in memory for the life of the store only, in a table bounded +//! in count and bytes, and a repeat after a restart runs again (it +//! wrote nothing, so nothing is done twice). //! 6. Books that haven't declared `call_transactions` take no call: a //! begin is refused (FormatUpgradePending), journaling nothing. +//! 7. Every reader that derives a fact (an entry's origin, an asset's +//! trail, a party's events, an attention item, a preview of what +//! adopting would keep) reads [`committed`], never the raw lines; a +//! reader that shows history shows every line and says in words of +//! each line of a call that did not count that it did not ([`Standing`]). +//! 8. A closing line's answer is at most [`ANSWER_CAP`] bytes; above +//! that the line keeps the answer's SHA-256 and length, and a repeat +//! says in words that the call was done and writes nothing. //! SCENARIOS: //! 1. IF the process dies between a call's lines and its closing line: //! SHOULD, at the next open, apply none of them, write an @@ -53,11 +76,16 @@ //! close, roll its SQLite changes back, and replay the journal //! without its lines. //! 3. IF a call fails before writing a line: SHOULD journal nothing. +//! 4. IF a call's closing line is on disk but its SQLite changes can't +//! be committed: SHOULD say so (the call counts), heal from the +//! journal, and refuse more writes until it has. //! ``` -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; +use std::path::Path; use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; use super::{Store, apply_line_to_sqlite, get_str, get_u64}; use crate::error::StoreError; @@ -74,6 +102,21 @@ pub const MIN_KEY_LEN: usize = 8; /// A request key is at most this many characters. pub const MAX_KEY_LEN: usize = 128; +/// The longest answer (its JSON text, in bytes) a closing line keeps +/// whole: 4 KiB. Above it the line keeps the answer's SHA-256 and length +/// (INVARIANT 8). +pub const ANSWER_CAP: usize = 4096; + +/// The most calls that wrote no line whose key and answer are kept in +/// memory (INVARIANT 5); the oldest go first. +pub const SESSION_KEYS_MAX: usize = 512; +/// The most bytes of answers kept for them: 2 MiB. +pub const SESSION_BYTES_MAX: usize = 2 * 1024 * 1024; + +/// The file, in the books' `keys/` folder, holding the secret the +/// journal's argument digests are keyed with. +pub const CALLS_KEY_FILE: &str = "calls.key"; + /// Who made a call, what it is, and what it asked for. #[derive(Clone, Debug, PartialEq, Eq)] pub struct CallId { @@ -119,29 +162,99 @@ pub struct Closed { pub first_seq: Option, /// The seq of the call's last line, when it wrote lines. pub last_seq: Option, - /// The answer it gave (an `ok` call): JSON text. + /// The answer it gave (an `ok` call), when short enough to keep: + /// JSON text. pub answer: Option, + /// The SHA-256 of the answer, hex, when it was too long to keep. + pub answer_sha256: Option, + /// The length of that answer in bytes. + pub answer_bytes: Option, /// How it failed (a `failed` call). pub error: Option, } +/// What a repeat of a call that committed is answered with. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Replay { + /// The answer it gave, as JSON text, byte for byte. + Answer(String), + /// Its answer was too long to keep: what the closing line says of it. + Summary { + /// The seq of its begin line. + first_seq: u64, + /// The seq of its last line before the closing line. + last_seq: u64, + /// The seq of the closing line. + closed_seq: u64, + /// The SHA-256 of the answer it gave, hex. + answer_sha256: String, + /// The answer's length in bytes. + answer_bytes: u64, + }, +} + /// What the books kept of a call that committed. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Recorded { /// The tool. pub tool: String, - /// The digest of its arguments, without the key. + /// The keyed digest of its arguments. pub args: String, - /// The answer it gave, as JSON text. - pub answer: String, - /// The seq of its closing line. - pub seq: u64, + /// What a repeat is answered with. + pub replay: Replay, +} + +/// What the table keeps of a call with lines: no answer (a repeat reads +/// it from the closing line), so the table's size is one small entry per +/// committed call, whatever the answers' sizes. +#[derive(Clone, Debug)] +struct Entry { + tool: String, + args: String, + /// The seq of the closing line. + seq: u64, +} + +/// The calls that wrote no line, kept for the life of the store: bounded +/// by count and by bytes of answers, oldest first out (INVARIANT 5). +#[derive(Clone, Debug, Default)] +struct Session { + by: HashMap<(String, String), (String, String, String)>, + order: VecDeque<(String, String)>, + bytes: usize, +} + +impl Session { + fn note(&mut self, id: &CallId, answer: &str) { + if answer.len() > ANSWER_CAP { + // Not kept: a repeat of a call that wrote nothing just runs + // again. + return; + } + let k = (id.token.clone(), id.key.clone()); + if self.by.contains_key(&k) { + return; + } + self.bytes += answer.len(); + self.order.push_back(k.clone()); + self.by + .insert(k, (id.tool.clone(), id.args.clone(), answer.to_string())); + while self.order.len() > SESSION_KEYS_MAX || self.bytes > SESSION_BYTES_MAX { + let Some(old) = self.order.pop_front() else { + break; + }; + if let Some((_, _, a)) = self.by.remove(&old) { + self.bytes -= a.len(); + } + } + } } /// The keys of every call that committed, by (token, key). #[derive(Clone, Debug, Default)] pub struct Keys { - by: HashMap<(String, String), Recorded>, + by: HashMap<(String, String), Entry>, + session: Session, } impl Keys { @@ -159,21 +272,24 @@ impl Keys { } fn note(&mut self, closed: &Closed, seq: u64) { - let Some(answer) = closed.answer.clone() else { - return; - }; self.by .entry((closed.id.token.clone(), closed.id.key.clone())) - .or_insert(Recorded { + .or_insert(Entry { tool: closed.id.tool.clone(), args: closed.id.args.clone(), - answer, seq, }); } - fn get(&self, token: &str, key: &str) -> Option<&Recorded> { - self.by.get(&(token.to_string(), key.to_string())) + /// How many calls with lines the table knows (a test's question). + pub fn journaled(&self) -> usize { + self.by.len() + } + + /// How many calls that wrote nothing it holds, and the bytes of their + /// answers. + pub fn session_size(&self) -> (usize, usize) { + (self.session.order.len(), self.session.bytes) } } @@ -229,15 +345,34 @@ pub fn closed_of(line: &JournalLine) -> Result { .ok_or_else(|| corrupt(line, k)), }; let answer = text_of("answer")?; - if outcome == CallOutcome::Ok && answer.is_none() { - return Err(corrupt(line, "answer")); + let answer_sha256 = text_of("answer_sha256")?; + let answer_bytes = seq_of("answer_bytes")?; + if outcome == CallOutcome::Ok { + let kept_whole = answer.is_some() && answer_sha256.is_none() && answer_bytes.is_none(); + let kept_hash = answer.is_none() + && answer_bytes.is_some_and(|n| n > ANSWER_CAP as u64) + && answer_sha256 + .as_deref() + .is_some_and(|h| h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit())); + if !(kept_whole || kept_hash) { + return Err(corrupt(line, "answer")); + } + if answer.as_ref().is_some_and(|a| a.len() > ANSWER_CAP) { + return Err(corrupt(line, "answer (longer than the cap)")); + } + } + let (first_seq, last_seq) = (seq_of("first_seq")?, seq_of("last_seq")?); + if first_seq.is_none() || last_seq.is_none() { + return Err(corrupt(line, "first_seq and last_seq")); } Ok(Closed { id, outcome, - first_seq: seq_of("first_seq")?, - last_seq: seq_of("last_seq")?, + first_seq, + last_seq, answer, + answer_sha256, + answer_bytes, error: text_of("error")?, }) } @@ -246,21 +381,31 @@ fn begun_payload(id: &CallId) -> Value { json!({ "tool": id.tool, "token": id.token, "key": id.key, "args": id.args }) } +/// What a closing line says of the answer: the answer itself, or, above +/// [`ANSWER_CAP`], its hash and length. +enum Kept<'a> { + Answer(&'a str), + Nothing, +} + fn closed_payload( id: &CallId, outcome: CallOutcome, - range: Option<(u64, u64)>, - answer: Option<&str>, + range: (u64, u64), + answer: Kept<'_>, error: Option<&str>, ) -> Value { let mut p = begun_payload(id); p["outcome"] = json!(outcome.as_str()); - if let Some((first, last)) = range { - p["first_seq"] = json!(first); - p["last_seq"] = json!(last); - } - if let Some(a) = answer { - p["answer"] = json!(a); + p["first_seq"] = json!(range.0); + p["last_seq"] = json!(range.1); + if let Kept::Answer(a) = answer { + if a.len() <= ANSWER_CAP { + p["answer"] = json!(a); + } else { + p["answer_sha256"] = json!(hex::encode(Sha256::digest(a.as_bytes()))); + p["answer_bytes"] = json!(a.len()); + } } if let Some(e) = error { p["error"] = json!(e); @@ -320,13 +465,7 @@ impl CallGate { CLOSED => { let closed = closed_of(line)?; let Some(call) = self.pending.take() else { - if closed.first_seq.is_some() - || closed.last_seq.is_some() - || closed.outcome == CallOutcome::Unfinished - { - return Err(corrupt(line, "closes a call that never began")); - } - return Ok(vec![index]); + return Err(corrupt(line, "closes a call that never began")); }; if closed.id != call.id || closed.first_seq != Some(call.begun_seq) @@ -388,6 +527,153 @@ pub(crate) fn gate_all(lines: &[JournalLine]) -> Result<(Vec, CallGate), Ok((released, gate)) } +/// Whether a journal line counts, and if not, why (INVARIANT 7). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Standing { + /// It counts: outside any call, or inside one that closed `ok`. + Counts, + /// A `call.begun` or `call.closed` line: the frame, which says what + /// became of the lines between and is no fact of the books itself. + Frame, + /// Inside a call that closed `failed`: it did not count. + Failed, + /// Inside a call that closed `unfinished`: it did not count. + Unfinished, + /// Inside a call that has not closed yet: it does not count yet. + Pending, +} + +impl Standing { + /// Whether the line is a fact of the books. + pub fn counts(self) -> bool { + self == Self::Counts + } + + /// In words, why the line does not count; None for a line that + /// counts and for a frame line. + pub fn note(self) -> Option<&'static str> { + match self { + Self::Counts | Self::Frame => None, + Self::Failed => Some("not counted: the call that wrote it failed"), + Self::Unfinished => Some("not counted: the call that wrote it never finished"), + Self::Pending => Some("not counted yet: the call that wrote it is still running"), + } + } +} + +/// The standing of every line of `lines`, in order: the one question +/// every reader asks of the journal (INVARIANTS 1, 7). A journal that is +/// not a sound sequence of frames is corrupt. +pub fn standings(lines: &[JournalLine]) -> Result, StoreError> { + let mut gate = CallGate::default(); + let mut out = Vec::with_capacity(lines.len()); + let mut frame: Option = None; + for (i, line) in lines.iter().enumerate() { + gate.push(i, line)?; + match line.line_type.as_str() { + BEGUN => { + frame = Some(i); + out.push(Standing::Frame); + } + CLOSED => { + out.push(Standing::Frame); + if let Some(begun) = frame.take() { + let settled = match closed_of(line)?.outcome { + CallOutcome::Ok => Standing::Counts, + CallOutcome::Failed => Standing::Failed, + CallOutcome::Unfinished => Standing::Unfinished, + }; + for s in &mut out[begun + 1..i] { + *s = settled; + } + } + } + _ => out.push(if frame.is_some() { + Standing::Pending + } else { + Standing::Counts + }), + } + } + Ok(out) +} + +/// The committed journal: the lines that are facts of the books, in +/// order: those outside any call and those of calls that closed `ok`, +/// the frame lines themselves left out (INVARIANT 7). What every reader +/// that derives a fact from the journal's lines reads. +pub fn committed(lines: &[JournalLine]) -> Result, StoreError> { + let standing = standings(lines)?; + Ok(lines + .iter() + .zip(standing) + .filter(|(_, s)| s.counts()) + .map(|(l, _)| l.clone()) + .collect()) +} + +/// HMAC-SHA256 (RFC 2104) of `msg` under `key`, hex. +pub(crate) fn hmac_sha256_hex(key: &[u8], msg: &[u8]) -> String { + const BLOCK: usize = 64; + let mut k = [0u8; BLOCK]; + if key.len() > BLOCK { + k[..32].copy_from_slice(&Sha256::digest(key)); + } else { + k[..key.len()].copy_from_slice(key); + } + let mut inner = Sha256::new(); + inner.update(k.map(|b| b ^ 0x36)); + inner.update(msg); + let mut outer = Sha256::new(); + outer.update(k.map(|b| b ^ 0x5c)); + outer.update(inner.finalize()); + hex::encode(outer.finalize()) +} + +/// The secret a book's call arguments are keyed with: 32 random bytes in +/// `keys/calls.key` of its folder (mode 0600, the folder 0700), made on +/// first need and never written to the journal, a log or an answer. The +/// error names no path. +fn calls_key(data_dir: &Path) -> Result, StoreError> { + let unsure = |what: &str| { + StoreError::CallRefused(format!( + "the books' call key can't be {what}, so the call was not run and nothing was changed" + )) + }; + let file = data_dir.join(crate::root::KEYS_DIR).join(CALLS_KEY_FILE); + match std::fs::read_to_string(&file) { + Ok(text) => hex::decode(text.trim()) + .ok() + .filter(|b| b.len() == 32) + .ok_or_else(|| unsure("read: its file isn't a key")), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + crate::root::private_book_folder(data_dir, crate::root::KEYS_DIR) + .map_err(|_| unsure("kept: the keys folder isn't usable"))?; + let mut key = [0u8; 32]; + getrandom::getrandom(&mut key).map_err(|_| unsure("made: no randomness"))?; + match crate::root::write_new_private_file(&file, hex::encode(key).as_bytes()) { + Ok(()) => Ok(key.to_vec()), + // Another process made it first: use theirs. + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => calls_key(data_dir), + Err(_) => Err(unsure("kept: it can't be written")), + } + } + Err(_) => Err(unsure("read")), + } +} + +/// The keyed digest of a call's arguments: HMAC-SHA256 over their +/// canonical JSON, unmasked, under the books' call key. Two requests that +/// differ only in a tax id differ here; nothing in it lets anyone recover +/// or test a guess of one without the key, which is never journaled. +pub fn args_mac(data_dir: &Path, args: &Value) -> Result { + let key = calls_key(data_dir)?; + Ok(hmac_sha256_hex( + &key, + crate::journal::canonical_json(args).as_bytes(), + )) +} + /// The books' id: the one `store.created` carries (books made since /// `call_transactions`), else the one the format upgrade added to its /// `journal.format_set`. None for books that have had neither yet. @@ -443,10 +729,54 @@ impl Store { self.ensure_feature(CALL_TRANSACTIONS) } + /// The keyed digest of a call's arguments ([`args_mac`]), under this + /// book's call key. + pub fn args_mac(&self, args: &Value) -> Result { + args_mac(&self.data_dir, args) + } + /// What the books kept of the call that ran under this token and key, - /// if one committed. - pub fn recorded_call(&self, token: &str, key: &str) -> Option<&Recorded> { - self.keys.get(token, key) + /// if one committed: from the session's table for a call that wrote + /// nothing, else from the journal's closing line. + pub fn recorded_call(&self, token: &str, key: &str) -> Result, StoreError> { + let k = (token.to_string(), key.to_string()); + if let Some((tool, args, answer)) = self.keys.session.by.get(&k) { + return Ok(Some(Recorded { + tool: tool.clone(), + args: args.clone(), + replay: Replay::Answer(answer.clone()), + })); + } + let Some(entry) = self.keys.by.get(&k) else { + return Ok(None); + }; + // Read from the closing line: the table holds no answers. + let lines = crate::journal::read_and_verify_journal(self.journal.path())?; + let line = lines.iter().find(|l| l.seq == entry.seq).ok_or_else(|| { + StoreError::JournalCorrupt(format!("seq {}: no closing line", entry.seq)) + })?; + let closed = closed_of(line)?; + let replay = match closed.answer { + Some(answer) => Replay::Answer(answer), + None => Replay::Summary { + first_seq: closed.first_seq.unwrap_or_default(), + last_seq: closed.last_seq.unwrap_or_default(), + closed_seq: line.seq, + answer_sha256: closed.answer_sha256.unwrap_or_default(), + answer_bytes: closed.answer_bytes.unwrap_or_default(), + }, + }; + Ok(Some(Recorded { + tool: entry.tool.clone(), + args: entry.args.clone(), + replay, + })) + } + + /// 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)) { + (self.keys.journaled(), self.keys.session_size()) } /// Whether a call is open. @@ -454,6 +784,12 @@ impl Store { self.call.is_some() } + /// Whether the open call has written a line (its begin line is on + /// disk). + pub fn call_has_lines(&self) -> bool { + self.call.as_ref().is_some_and(|c| c.begun.is_some()) + } + /// Open a call: from here every line this store journals belongs to /// it, until [`Self::close_call`]. Journals nothing yet (the begin /// line comes with the first line); the projection's changes are held @@ -505,46 +841,78 @@ impl Store { Ok(()) } - /// Close the open call. `Done`: journal its closing line with the - /// answer, and release the projection's transaction: the call - /// committed. `Failed`: if the call wrote lines, journal a `failed` - /// closing line, roll the projection back and rebuild the live ledger - /// without those lines; if it wrote none, journal nothing. + /// Close the open call. + /// + /// `Done`, with lines written: journal its closing line with the + /// answer (or, above [`ANSWER_CAP`], the answer's hash and length), + /// and release the projection's transaction: the call committed. With + /// none written: journal nothing, release the transaction, and keep + /// the key and answer in memory (INVARIANT 5). + /// + /// `Failed`: if the call wrote lines, journal a `failed` closing + /// line, roll the projection back and rebuild the live ledger without + /// those lines; if it wrote none, journal nothing. /// /// If the closing line cannot be written, the call has not committed /// (it will close `unfinished` at the next open), the store refuses - /// every further write, and the error is returned: the caller stops - /// taking requests. + /// every further write, and the error is returned. If it is on disk + /// but the projection can't be brought up to it, the call *has* + /// committed: the store heals from the journal where it can, and + /// where it can't refuses every further write and returns + /// [`StoreError::CallCommitted`] (SCENARIO 4). pub fn close_call(&mut self, end: CallEnd<'_>) -> Result<(), StoreError> { let call = self .call .take() .ok_or_else(|| StoreError::CallRefused("no call is open".into()))?; let range = call.begun.map(|first| (first, self.journal.head().0)); - match end { - CallEnd::Done(answer) => { - let payload = closed_payload(&call.id, CallOutcome::Ok, range, Some(answer), None); + match (end, range) { + (CallEnd::Done(answer), None) => { + self.conn.execute_batch("RELEASE call_tx")?; + self.keys.session.note(&call.id, answer); + Ok(()) + } + (CallEnd::Done(answer), Some(range)) => { + let payload = + closed_payload(&call.id, CallOutcome::Ok, range, Kept::Answer(answer), None); let line = self .journal .append(CLOSED, payload) .map_err(|e| self.dangle(e))?; - // The projection commits with the line: released only - // once the closing line is on disk (INVARIANT 4). - apply_line_to_sqlite(&self.conn, &line) - .and_then(|()| Ok(self.conn.execute_batch("RELEASE call_tx")?)) - .map_err(|e| self.dangle(e))?; + // The closing line is on disk: the call committed, whatever + // becomes of the projection (INVARIANT 4). let closed = closed_of(&line)?; self.keys.note(&closed, line.seq); + let applied = apply_line_to_sqlite(&self.conn, &line) + .and_then(|()| Ok(self.conn.execute_batch("RELEASE call_tx")?)); + if let Err(e) = applied { + // Roll back what the transaction held, then bring the + // projection up from the journal, as an open would. + let _ = self + .conn + .execute_batch("ROLLBACK TO call_tx; RELEASE call_tx"); + if self.reload().is_err() { + self.dangling = true; + return Err(StoreError::CallCommitted(format!( + "the call's closing line is saved, so it counts, but the books' working copy could not be brought up to it ({e}); it is rebuilt from the journal when the books are opened again" + ))); + } + } Ok(()) } - CallEnd::Failed(error) => { - if range.is_none() { - self.conn - .execute_batch("ROLLBACK TO call_tx; RELEASE call_tx")?; - return Ok(()); - } - let payload = - closed_payload(&call.id, CallOutcome::Failed, range, None, Some(error)); + (CallEnd::Failed(_), None) => { + self.conn + .execute_batch("ROLLBACK TO call_tx; RELEASE call_tx")?; + Ok(()) + } + (CallEnd::Failed(error), Some(range)) => { + let payload = closed_payload( + &call.id, + CallOutcome::Failed, + range, + Kept::Nothing, + Some(error), + ); self.journal .append(CLOSED, payload) .map_err(|e| self.dangle(e))?; @@ -574,7 +942,8 @@ impl Store { /// would build: the journal read through the gate, the ledger replayed /// from it, and the projection (rolled back to before the call) caught /// up with the lines that count. After a call failed with lines - /// written. + /// written, or when a committed call's projection could not be + /// released. fn reload(&mut self) -> Result<(), StoreError> { let lines = crate::journal::read_and_verify_journal(self.journal.path())?; let (released, _) = gate_all(&lines)?; @@ -593,8 +962,8 @@ impl Store { let payload = closed_payload( &u.id, CallOutcome::Unfinished, - Some((u.first_seq, u.last_seq)), - None, + (u.first_seq, u.last_seq), + Kept::Nothing, Some( "the call never finished: the books were closed or the program stopped before its closing line was written", ), @@ -604,3 +973,64 @@ impl Store { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + + /// RFC 4231, test cases 1 and 2 (and 6, a key longer than the block). + #[test] + fn hmac_sha256_matches_rfc_4231() { + assert_eq!( + hmac_sha256_hex(&[0x0b; 20], b"Hi There"), + "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7" + ); + assert_eq!( + hmac_sha256_hex(b"Jefe", b"what do ya want for nothing?"), + "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843" + ); + assert_eq!( + hmac_sha256_hex( + &[0xaa; 131], + b"Test Using Larger Than Block-Size Key - Hash Key First" + ), + "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54" + ); + } + + /// Two requests that differ only in a tax id differ in their digests; + /// the digest holds neither, and is the same for the same request. + #[test] + fn args_mac_tells_tax_ids_apart_and_holds_none() { + let tmp = tempfile::tempdir().unwrap(); + let a = json!({"party": 1, "tin": "111-22-3333"}); + let b = json!({"party": 1, "tin": "111-22-3334"}); + let (ma, mb) = ( + args_mac(tmp.path(), &a).unwrap(), + args_mac(tmp.path(), &b).unwrap(), + ); + assert_ne!(ma, mb); + assert_eq!(ma, args_mac(tmp.path(), &a).unwrap()); + // Not the plain hash of the arguments: a guess can't be tested + // without the books' key. + assert_ne!( + ma, + hex::encode(Sha256::digest(journal_canonical(&a).as_bytes())) + ); + assert_eq!(ma.len(), 64); + // Another book has another key. + let other = tempfile::tempdir().unwrap(); + assert_ne!(ma, args_mac(other.path(), &a).unwrap()); + // The key is a file of its own, not the vault's. + assert!( + tmp.path() + .join(crate::root::KEYS_DIR) + .join(CALLS_KEY_FILE) + .is_file() + ); + } + + fn journal_canonical(v: &Value) -> String { + crate::journal::canonical_json(v) + } +} diff --git a/crates/ledger-store/src/describe.rs b/crates/ledger-store/src/describe.rs index 9f538c99..175366d9 100644 --- a/crates/ledger-store/src/describe.rs +++ b/crates/ledger-store/src/describe.rs @@ -43,6 +43,9 @@ pub struct Described { pub subjects: Vec, /// The entry it belongs to, if it is about one. pub entry_id: Option, + /// Whether the line counts (calls.rs): a line of a call that failed or + /// never finished is listed, and its summary says it did not count. + pub standing: crate::calls::Standing, } /// Which lines to list (INVARIANT 3). @@ -245,12 +248,29 @@ pub fn describe_line(line: &JournalLine) -> Described { summary: describe(line), subjects, entry_id, + standing: crate::calls::Standing::Counts, } } /// The lines `filter` asks for, described, in journal order (INVARIANT 3), -/// and whether more match after the last one returned. +/// and whether more match after the last one returned. Every line counts +/// (use [`history_standing`] where some may not). pub fn history(lines: &[JournalLine], filter: &HistoryFilter) -> (Vec, bool) { + history_standing( + lines, + &vec![crate::calls::Standing::Counts; lines.len()], + filter, + ) +} + +/// [`history`] with each line's standing (calls.rs INVARIANT 7): a line +/// of a call that failed, never finished or is still running is listed, +/// as history is, and its summary says in words that it does not count. +pub fn history_standing( + lines: &[JournalLine], + standing: &[crate::calls::Standing], + filter: &HistoryFilter, +) -> (Vec, bool) { let wanted = |l: &JournalLine| { l.seq > filter.after_seq && (filter.types.is_empty() @@ -268,12 +288,17 @@ pub fn history(lines: &[JournalLine], filter: &HistoryFilter) -> (Vec }; let mut out = Vec::new(); let mut more = false; - for l in lines.iter().filter(|l| wanted(l)) { + for (l, st) in lines.iter().zip(standing).filter(|(l, _)| wanted(l)) { if out.len() == filter.limit { more = true; break; } - out.push(describe_line(l)); + let mut d = describe_line(l); + d.standing = *st; + if let Some(note) = st.note() { + d.summary = format!("{} ({note})", d.summary); + } + out.push(d); } (out, more) } @@ -299,7 +324,8 @@ impl crate::Store { let (lines, _format) = crate::journal::read_journal_and_format( &self.data_dir().join(crate::store::JOURNAL_FILE), )?; - let (described, more) = history(&lines, filter); + let standing = crate::calls::standings(&lines)?; + let (described, more) = history_standing(&lines, &standing, filter); let tail_repairs = self .tail_repairs()? .into_iter() diff --git a/crates/ledger-store/src/error.rs b/crates/ledger-store/src/error.rs index b99ecc3f..a7f526b4 100644 --- a/crates/ledger-store/src/error.rs +++ b/crates/ledger-store/src/error.rs @@ -111,6 +111,12 @@ pub enum StoreError { #[error("{0}")] CallRefused(String), + /// A call's closing line is on disk, so the call committed and counts, + /// but the store could not bring its working copy up to it: the store + /// takes nothing more until the books are opened again, which does. + #[error("{0}")] + CallCommitted(String), + /// Replay produced different ids than the journal recorded. #[error("replay mismatch: {0}")] ReplayMismatch(String), diff --git a/crates/ledger-store/src/root.rs b/crates/ledger-store/src/root.rs index ca4347e8..19f81ef1 100644 --- a/crates/ledger-store/src/root.rs +++ b/crates/ledger-store/src/root.rs @@ -987,7 +987,11 @@ impl Root { head.0 ))); } - let keeps_settings = lines.iter().any(|l| l.line_type == "settings.set"); + // Facts of the books only: a failed call's settings line never counted + // (calls.rs INVARIANT 7). + let keeps_settings = crate::calls::committed(&lines)? + .iter() + .any(|l| l.line_type == "settings.set"); if !keeps_settings && options.settings.is_none() { return Err(RootError::Adopt( "these books keep no settings of their own yet: give their settings file \ @@ -1497,7 +1501,9 @@ impl Root { Ok(SourcePreview { head: head_of(&lines), currency: crate::store::journal_currency(&lines)?, - keeps_settings: lines.iter().any(|l| l.line_type == "settings.set"), + keeps_settings: crate::calls::committed(&lines)? + .iter() + .any(|l| l.line_type == "settings.set"), }) })() .map_err(|e| self.hide(e)) @@ -2290,6 +2296,19 @@ fn write_private_file(path: &Path, bytes: &[u8]) -> Result<(), RootError> { Ok(()) } +/// Write a new file, mode 0600 set explicitly, synced, as `io::Result` +/// (the call key, calls.rs): an existing file is `AlreadyExists`. +pub(crate) fn write_new_private_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + use std::io::Write; + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path)?; + set_mode(path, 0o600)?; + file.write_all(bytes)?; + file.sync_all() +} + /// Make a folder's entries durable (Unix; NTFS journals its own). fn sync_dir(path: &Path) -> Result<(), RootError> { #[cfg(unix)] diff --git a/crates/ledger-store/src/snapshot.rs b/crates/ledger-store/src/snapshot.rs index f150656b..c311b851 100644 --- a/crates/ledger-store/src/snapshot.rs +++ b/crates/ledger-store/src/snapshot.rs @@ -257,11 +257,28 @@ impl Snapshot { } /// Every journal line read so far, in order: the complete history, - /// with timestamps and hashes. + /// with timestamps and hashes, the lines of calls that failed or never + /// finished among them. For showing history only: a reader that + /// derives a fact reads [`Snapshot::committed_journal`] (calls.rs + /// INVARIANT 7), and labels each line here with + /// [`Snapshot::journal_standings`]. pub fn journal(&self) -> &[JournalLine] { &self.lines } + /// The standing of each line of [`Snapshot::journal`], in the same + /// order (calls.rs [`crate::calls::standings`]). + pub fn journal_standings(&self) -> Result, StoreError> { + crate::calls::standings(&self.lines) + } + + /// The committed journal: the lines that are facts of the books, the + /// frame lines left out ([`crate::calls::committed`]). What every + /// reader that derives facts from the journal reads. + pub fn committed_journal(&self) -> Result, StoreError> { + crate::calls::committed(&self.lines) + } + /// Sequence number of the last journal line read. pub fn journal_seq(&self) -> u64 { self.lines.len() as u64 diff --git a/crates/ledger-store/tests/calls.rs b/crates/ledger-store/tests/calls.rs index 54e46081..a56fef3c 100644 --- a/crates/ledger-store/tests/calls.rs +++ b/crates/ledger-store/tests/calls.rs @@ -12,7 +12,10 @@ use chrono::NaiveDate; use ledger_core::{AccountType, Currency, Ledger, Money, Side}; -use ledger_store::calls::{CallEnd, CallId, CallOutcome, begun_of, closed_of}; +use ledger_store::calls::{ + ANSWER_CAP, CallEnd, CallId, CallOutcome, Recorded, Replay, SESSION_KEYS_MAX, Standing, + begun_of, closed_of, +}; use ledger_store::{JOURNAL_FILE, JournalFormat, Snapshot, Store, StoreError}; use rust_decimal::Decimal; use serde_json::Value; @@ -35,6 +38,18 @@ fn id(key: &str) -> CallId { } } +/// What the store kept of a call, if anything. +fn kept(s: &Store, token: &str, key: &str) -> Option { + s.recorded_call(token, key).unwrap() +} + +fn answer_of(r: &Recorded) -> &str { + match &r.replay { + Replay::Answer(a) => a, + other => panic!("kept no whole answer: {other:?}"), + } +} + fn lines_of(dir: &Path) -> Vec { ledger_store::journal::read_and_verify_journal(&dir.join(JOURNAL_FILE)).unwrap() } @@ -85,39 +100,188 @@ fn a_call_is_framed_and_its_answer_kept_by_key() { assert_eq!(closed.first_seq, Some(lines[before].seq)); assert_eq!(closed.last_seq, Some(lines.last().unwrap().seq - 1)); assert_eq!(closed.answer.as_deref(), Some(r#"{"entry_id":1}"#)); - let kept = s.recorded_call("token-1", "key-aaaa-1").unwrap(); - assert_eq!(kept.answer, r#"{"entry_id":1}"#); - assert_eq!(kept.args, "a".repeat(64)); + let was = kept(&s, "token-1", "key-aaaa-1").unwrap(); + assert_eq!(answer_of(&was), r#"{"entry_id":1}"#); + assert_eq!(was.args, "a".repeat(64)); // Scoped to the token: another token has not used this key. - assert!(s.recorded_call("token-2", "key-aaaa-1").is_none()); + assert!(kept(&s, "token-2", "key-aaaa-1").is_none()); s.verify().unwrap(); // A restart rebuilds the table from the journal alone. drop(s); let s = Store::open(tmp.path()).unwrap(); assert_eq!( - s.recorded_call("token-1", "key-aaaa-1").unwrap().answer, + answer_of(&kept(&s, "token-1", "key-aaaa-1").unwrap()), r#"{"entry_id":1}"# ); s.verify().unwrap(); } #[test] -fn a_call_that_wrote_nothing_is_only_a_closing_line() { +fn a_call_that_wrote_nothing_leaves_no_line_and_is_remembered_for_the_session() { let tmp = tempfile::tempdir().unwrap(); let mut s = books(tmp.path()); let before = lines_of(tmp.path()).len(); s.begin_call(id("key-aaaa-2")).unwrap(); s.close_call(CallEnd::Done(r#"{"ok":true}"#)).unwrap(); - let lines = lines_of(tmp.path()); - assert_eq!(lines.len(), before + 1); - let closed = closed_of(&lines[before]).unwrap(); - assert_eq!((closed.first_seq, closed.last_seq), (None, None)); - assert!(s.recorded_call("token-1", "key-aaaa-2").is_some()); - // A failed call that wrote nothing leaves no line at all. + // No line at all: a call that wrote nothing has nothing to frame. + assert_eq!(lines_of(tmp.path()).len(), before); + // But a repeat within the session is answered as the first was. + assert_eq!( + answer_of(&kept(&s, "token-1", "key-aaaa-2").unwrap()), + r#"{"ok":true}"# + ); + // A failed call that wrote nothing leaves no line either, and frees its key. s.begin_call(id("key-aaaa-3")).unwrap(); s.close_call(CallEnd::Failed("refused")).unwrap(); - assert_eq!(lines_of(tmp.path()).len(), before + 1); - assert!(s.recorded_call("token-1", "key-aaaa-3").is_none()); + assert_eq!(lines_of(tmp.path()).len(), before); + assert!(kept(&s, "token-1", "key-aaaa-3").is_none()); + // After a restart the key is forgotten: the repeat runs again, which is + // harmless because the first wrote nothing. + drop(s); + let s = Store::open(tmp.path()).unwrap(); + assert!(kept(&s, "token-1", "key-aaaa-2").is_none()); + assert_eq!(lines_of(tmp.path()).len(), before); +} + +#[test] +fn the_sessions_key_table_is_bounded_in_count_and_in_bytes() { + let tmp = tempfile::tempdir().unwrap(); + let mut s = books(tmp.path()); + for n in 0..SESSION_KEYS_MAX + 20 { + s.begin_call(id(&format!("key-bound-{n:05}"))).unwrap(); + s.close_call(CallEnd::Done(r#"{"ok":true}"#)).unwrap(); + } + let (_, (held, bytes)) = s.call_table(); + assert_eq!(held, SESSION_KEYS_MAX); + assert!(bytes <= SESSION_KEYS_MAX * 16); + // The oldest went first. + assert!(kept(&s, "token-1", "key-bound-00000").is_none()); + assert!( + kept( + &s, + "token-1", + &format!("key-bound-{:05}", SESSION_KEYS_MAX + 19) + ) + .is_some() + ); + // An answer above the cap is not kept for a call that wrote nothing. + s.begin_call(id("key-big-0001")).unwrap(); + s.close_call(CallEnd::Done(&"x".repeat(ANSWER_CAP + 1))) + .unwrap(); + assert!(kept(&s, "token-1", "key-big-0001").is_none()); +} + +#[test] +fn a_long_answer_is_kept_as_its_hash_and_a_repeat_is_told_in_words_what_was_done() { + let tmp = tempfile::tempdir().unwrap(); + let mut s = books(tmp.path()); + let long = format!(r#"{{"text":"{}"}}"#, "y".repeat(ANSWER_CAP)); + s.begin_call(id("key-long-0001")).unwrap(); + draft(&mut s, "Big answer"); + s.close_call(CallEnd::Done(&long)).unwrap(); + let lines = lines_of(tmp.path()); + let last = lines.last().unwrap(); + // The line is bounded: no answer text, its hash and length instead. + assert!(last.payload.get("answer").is_none()); + let closed = closed_of(last).unwrap(); + assert_eq!(closed.answer_bytes, Some(long.len() as u64)); + assert_eq!(closed.answer_sha256.as_deref().map(str::len), Some(64)); + assert!(serde_json::to_string(&last.payload).unwrap().len() < ANSWER_CAP); + let expect = |s: &Store| match kept(s, "token-1", "key-long-0001").unwrap().replay { + Replay::Summary { + first_seq, + last_seq, + closed_seq, + answer_sha256, + answer_bytes, + } => { + assert_eq!(first_seq, closed.first_seq.unwrap()); + assert_eq!(last_seq, closed.last_seq.unwrap()); + assert_eq!(closed_seq, last.seq); + assert_eq!(Some(answer_sha256), closed.answer_sha256.clone()); + assert_eq!(answer_bytes, long.len() as u64); + } + other => panic!("expected a summary: {other:?}"), + }; + expect(&s); + // After a restart the same. + drop(s); + let s = Store::open(tmp.path()).unwrap(); + expect(&s); + s.verify().unwrap(); + // A whole answer at the cap is kept whole. + let mut s = s; + let at_cap = "z".repeat(ANSWER_CAP); + s.begin_call(id("key-long-0002")).unwrap(); + draft(&mut s, "At the cap"); + s.close_call(CallEnd::Done(&at_cap)).unwrap(); + assert_eq!( + answer_of(&kept(&s, "token-1", "key-long-0002").unwrap()), + at_cap + ); +} + +#[test] +fn the_committed_journal_leaves_out_the_lines_of_a_call_that_failed() { + let tmp = tempfile::tempdir().unwrap(); + let mut s = books(tmp.path()); + // A failed call that wrote a draft: it took entry id 1 ... + s.begin_call(id("key-fail-0001")).unwrap(); + draft(&mut s, "Dead"); + s.close_call(CallEnd::Failed("it failed")).unwrap(); + // ... which a later call hands out again. + s.begin_call(id("key-fail-0002")).unwrap(); + draft(&mut s, "Alive"); + s.close_call(CallEnd::Done("{}")).unwrap(); + drop(s); + let lines = lines_of(tmp.path()); + let standing = ledger_store::calls::standings(&lines).unwrap(); + let of = |ty: &str, n: usize| { + lines + .iter() + .zip(&standing) + .filter(|(l, _)| l.line_type == ty) + .nth(n) + .map(|(_, s)| *s) + .unwrap() + }; + assert_eq!(of("entry.created", 0), Standing::Failed); + assert_eq!(of("entry.created", 1), Standing::Counts); + assert_eq!(of("call.begun", 0), Standing::Frame); + let committed = ledger_store::calls::committed(&lines).unwrap(); + // Both calls reused the same entry id; only the second's lines count. + let created: Vec<_> = committed + .iter() + .filter(|l| l.line_type == "entry.created") + .map(|l| l.payload["description"].as_str().unwrap().to_string()) + .collect(); + assert_eq!(created, ["Alive"]); + assert!(committed.iter().all(|l| !l.line_type.starts_with("call."))); + // The history lists every line, and says of the dead ones that they did not count. + let h = Store::open(tmp.path()) + .unwrap() + .journal_history(&ledger_store::describe::HistoryFilter { + limit: 200, + ..Default::default() + }) + .unwrap(); + let dead: Vec<_> = h + .lines + .iter() + .filter(|d| d.standing == Standing::Failed) + .collect(); + assert_eq!(dead.len(), 3); + assert!(dead.iter().all(|d| d.summary.contains("not counted"))); + assert!( + h.lines + .iter() + .filter(|d| d.standing == Standing::Counts) + .all(|d| !d.summary.contains("not counted")) + ); + // A snapshot reads the same. + let snap = Snapshot::load(tmp.path()).unwrap(); + assert_eq!(snap.committed_journal().unwrap().len(), committed.len()); + assert!(snap.journal().len() > committed.len()); } #[test] @@ -140,7 +304,7 @@ fn a_failed_call_is_on_the_record_and_builds_nothing() { assert_eq!(closed.error.as_deref(), Some("it went wrong")); assert!(lines.iter().any(|l| l.line_type == "entry.created")); // A failed key is free again: nothing happened under it. - assert!(s.recorded_call("token-1", "key-aaaa-4").is_none()); + assert!(kept(&s, "token-1", "key-aaaa-4").is_none()); // Books go on: the next call's ids do not collide with the failed one's. s.begin_call(id("key-aaaa-5")).unwrap(); draft(&mut s, "Whole"); @@ -194,7 +358,7 @@ fn a_crash_at_each_point_of_a_call_leaves_the_whole_call_or_none_of_it() { let reopened = Store::open(tmp.path()).unwrap(); same_books(reopened.ledger(), &committed); reopened.verify().unwrap(); - assert!(reopened.recorded_call("token-1", "key-crash-01").is_none()); + assert!(kept(&reopened, "token-1", "key-crash-01").is_none()); let types = types_of(tmp.path()); if k == 0 { // It had written nothing: there is nothing to close. @@ -427,7 +591,7 @@ fn a_call_that_rebuilds_the_projection_still_commits() { s.rebuild().unwrap(); s.close_call(CallEnd::Done("{}")).unwrap(); s.verify().unwrap(); - assert!(s.recorded_call("token-1", "key-heal-0001").is_some()); + assert!(kept(&s, "token-1", "key-heal-0001").is_some()); drop(s); let s = Store::open(tmp.path()).unwrap(); s.verify().unwrap(); From 98cbabde8e76b1cddd0e2b883d404c385e0e422f Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 10:19:26 -0700 Subject: [PATCH 4/6] fix(mcp,vault,store): the tax-id vault is inside the transaction; a read never sees an open call; the commit outcome is told truthfully (P15 T1 review) The vault wrote a tax id before its journal line, so a call that failed or was cut left the new tax id (and lost the old) with no line to say so. A vault write made for a call is now staged under a name no reader opens (.staged-TAG, .purging-TAG) and is made final, or dropped, only when the call closes: a purge is set aside and put back if the call fails. A crash between the closing line and the settle is finished at the next start by what the journal says of the call. The readers that check a vault record against the party's committed vault_record hash (the 1099 and CPA package paths) therefore only ever see committed records; the filing scan reads every final record on purpose (more tax ids scanned is safer). close_call(Done) told the caller none of a call counted when its closing line was on disk and only SQLite failed. It counted: the store now heals from the journal where it can, and otherwise says the call counts, stops taking writes and rebuilds at the next open. A call whose begin line the projection refused left its frame open, so the next call began inside it (a corrupt journal): the frame is now closed failed. A read arriving between a call's return and its closing line waits for the close (a call that has written no line leaves reads free), so no read shows what a call did before it committed. Tests added through the tools: a call that writes lines and fails, a repeat arriving while its original runs, the same key under two tokens, a crash with the ok close on disk and SQLite behind, the vault under a failed and a crashed call, a key reused for another tax id. The helpers that drop frame lines no longer back the checks that a refusal or a preview wrote nothing. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/tests/agent_surface.rs | 4 +- crates/ledger-cli/tests/audit.rs | 12 +- crates/ledger-cli/tests/call_transactions.rs | 600 ++++++++++++++++++- crates/ledger-cli/tests/documents.rs | 24 +- crates/ledger-cli/tests/drafts.rs | 8 +- crates/ledger-cli/tests/evidence.rs | 24 +- crates/ledger-cli/tests/mcp_journeys.rs | 10 +- crates/ledger-cli/tests/spec_1099.rs | 20 +- crates/ledger-cli/tests/spec_assets.rs | 24 +- crates/ledger-cli/tests/spec_attachments.rs | 20 +- crates/ledger-cli/tests/spec_mcp.rs | 49 +- crates/ledger-cli/tests/spec_parties.rs | 28 +- crates/ledger-cli/tests/spec_party_totals.rs | 24 +- crates/ledger-cli/tests/spec_projects.rs | 32 +- crates/ledger-cli/tests/spec_vault.rs | 26 +- crates/ledger-mcp/src/calls.rs | 253 +++++++- crates/ledger-mcp/src/server.rs | 77 ++- crates/ledger-mcp/src/tools/parties.rs | 12 +- crates/ledger-store/src/calls.rs | 28 +- crates/ledger-store/tests/calls.rs | 106 ++++ crates/ledger-vault/src/lib.rs | 164 ++++- crates/ledger-vault/tests/vault.rs | 140 +++++ 22 files changed, 1516 insertions(+), 169 deletions(-) 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}" + ); + } +} From 4c23fade7a5671fc3ae923adca83e35d8462bd47 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 10:23:47 -0700 Subject: [PATCH 5/6] test(store): the call frames and an old-books fixture written before call transactions (P15 T1, 8.0.6 items 1 and 2) books_written_under_older_rules_still_open gains hand-written call frames through JournalWriter (an ok call, a failed call whose party id is handed out again, a call that never finished, a call with an answer too long to keep): only the lines of calls that closed ok are the books'. old-books/p15_t1_before was written by main 7058fbd2, the version before this unit (no frames, no request keys), through the old-books-writer pattern, with that version's expected.json: this version opens it, every line counts, the figures are the same, it takes no call until the owner's upgrade and keeps every figure after it. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-store/tests/calls.rs | 91 +++ .../fixtures/old-books-writer/Cargo.toml | 6 + .../old-books-writer/src/bin/p15_t1_before.rs | 115 ++++ ...279a6ced262a8670bd5d7063a0668469398ac6523e | 1 + ...ae55fafe083dc33e2111abe6cafaf6fcb02a7d8ad8 | 1 + ...f9a10c590f8f4cc26ff4d854e30c9551ef7ad5898f | 1 + .../old-books/p15_t1_before/expected.json | 594 ++++++++++++++++++ .../old-books/p15_t1_before/journal.jsonl | 66 ++ crates/ledger-store/tests/store.rs | 59 ++ 9 files changed, 934 insertions(+) create mode 100644 crates/ledger-store/tests/fixtures/old-books-writer/src/bin/p15_t1_before.rs create mode 100644 crates/ledger-store/tests/fixtures/old-books/p15_t1_before/blobs/0d/46/0d462b0d3e7b13628aa5b6279a6ced262a8670bd5d7063a0668469398ac6523e create mode 100644 crates/ledger-store/tests/fixtures/old-books/p15_t1_before/blobs/65/c7/65c730c09a9b8c3ecf4cc2ae55fafe083dc33e2111abe6cafaf6fcb02a7d8ad8 create mode 100644 crates/ledger-store/tests/fixtures/old-books/p15_t1_before/blobs/dd/30/dd3075d12716028c7ae1b8f9a10c590f8f4cc26ff4d854e30c9551ef7ad5898f create mode 100644 crates/ledger-store/tests/fixtures/old-books/p15_t1_before/expected.json create mode 100644 crates/ledger-store/tests/fixtures/old-books/p15_t1_before/journal.jsonl diff --git a/crates/ledger-store/tests/calls.rs b/crates/ledger-store/tests/calls.rs index ee10bc5a..2a8a0701 100644 --- a/crates/ledger-store/tests/calls.rs +++ b/crates/ledger-store/tests/calls.rs @@ -702,3 +702,94 @@ fn a_call_whose_begin_line_the_projection_refuses_still_closes_its_frame() { drop(s); Store::open(tmp.path()).unwrap().verify().unwrap(); } + +/// 8.0.6: books the version before this feature wrote (the fixture +/// `old-books/p15_t1_before`, written by main 7058fbd2 through its Store +/// API, with its expected.json) open as ever and report the same figures: +/// every line of theirs is outside a frame, so every line counts; they +/// take no call until the owner's upgrade (D-89); an upgrade then gives +/// them a books id and leaves every figure where it was. +#[test] +fn books_the_version_before_call_transactions_wrote_open_and_report_the_same_figures() { + let fixture = + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/old-books/p15_t1_before"); + let tmp = tempfile::tempdir().unwrap(); + for e in std::fs::read_dir(&fixture).unwrap() { + let e = e.unwrap(); + if e.file_name() == "expected.json" { + continue; + } + let to = tmp.path().join(e.file_name()); + if e.file_type().unwrap().is_dir() { + copy_dir(&e.path(), &to); + } else { + std::fs::copy(e.path(), to).unwrap(); + } + } + let expected: Value = + serde_json::from_str(&std::fs::read_to_string(fixture.join("expected.json")).unwrap()) + .unwrap(); + let lines = lines_of(tmp.path()); + assert!(lines.iter().all(|l| !l.line_type.starts_with("call."))); + let mut s = Store::open(tmp.path()).unwrap(); + s.verify().unwrap(); + // Every line counts, and the figures are the old version's. + let standing = ledger_store::calls::standings(&lines).unwrap(); + assert!(standing.iter().all(|s| s.counts())); + assert_eq!( + ledger_store::calls::committed(&lines).unwrap().len(), + lines.len() + ); + let snapshot = + serde_json::to_value(ledger_core::reports::snapshot(s.ledger()).unwrap()).unwrap(); + assert_eq!(snapshot, expected["snapshot"]["Ok"]); + assert_eq!( + serde_json::to_value(s.ledger().invoices()).unwrap(), + expected["invoices"] + ); + assert_eq!( + serde_json::to_value(s.ledger().bills()).unwrap(), + expected["bills"] + ); + // They take no call yet, and say what the owner does. + assert!(!s.takes_calls()); + let refused = s.begin_call(id("key-old-books-1")).unwrap_err(); + assert!( + matches!(refused, StoreError::FormatUpgradePending { .. }), + "{refused:?}" + ); + assert_eq!( + lines_of(tmp.path()).len(), + lines.len(), + "refusing wrote nothing" + ); + // The owner's upgrade: books keep every figure and are given an id. + drop(s); + let mut s = Store::open(tmp.path()).unwrap(); + s.upgrade_format().unwrap().expect("waited for an upgrade"); + assert!(s.takes_calls()); + assert!(s.books_id().is_some()); + let after = serde_json::to_value(ledger_core::reports::snapshot(s.ledger()).unwrap()).unwrap(); + assert_eq!(after, expected["snapshot"]["Ok"]); + s.begin_call(id("key-old-books-2")).unwrap(); + // January is closed in these books: the first framed call is a March one. + let e = s.create_entry(d(2026, 3, 1), "A first framed call").unwrap(); + let bank = s.ledger().chart().find_by_code("1000").unwrap().id; + let capital = s.ledger().chart().find_by_code("3000").unwrap().id; + s.add_line(e, bank, Side::Debit, money(10)).unwrap(); + s.add_line(e, capital, Side::Credit, money(10)).unwrap(); + s.close_call(CallEnd::Done("{}")).unwrap(); + s.verify().unwrap(); +} + +fn copy_dir(from: &Path, to: &Path) { + std::fs::create_dir_all(to).unwrap(); + for e in std::fs::read_dir(from).unwrap() { + let e = e.unwrap(); + if e.file_type().unwrap().is_dir() { + copy_dir(&e.path(), &to.join(e.file_name())); + } else { + std::fs::copy(e.path(), to.join(e.file_name())).unwrap(); + } + } +} diff --git a/crates/ledger-store/tests/fixtures/old-books-writer/Cargo.toml b/crates/ledger-store/tests/fixtures/old-books-writer/Cargo.toml index 9dac2a31..3ef67d38 100644 --- a/crates/ledger-store/tests/fixtures/old-books-writer/Cargo.toml +++ b/crates/ledger-store/tests/fixtures/old-books-writer/Cargo.toml @@ -17,6 +17,12 @@ # cargo run --bin p5_before -- OUT (p5_before: run against b97234ac, the # revision before P5: a revised # convention, two decisions, two open items) +# cargo run --bin p15_t1_before -- OUT (p15_t1_before: run against 7058fbd2, +# the revision before P15 T1: a +# receipted opening, a reversal, an +# invoice with a part payment, a bill, +# an open draft, a closed January; no +# call frames, no request keys) # cargo run --bin expect -- OUT (expected.json beside each journal) # and copy each journal.jsonl, blobs/ and expected.json into old-books/. # x_member_closes was written later, the same way, by main 00226a4c diff --git a/crates/ledger-store/tests/fixtures/old-books-writer/src/bin/p15_t1_before.rs b/crates/ledger-store/tests/fixtures/old-books-writer/src/bin/p15_t1_before.rs new file mode 100644 index 00000000..490cdacd --- /dev/null +++ b/crates/ledger-store/tests/fixtures/old-books-writer/src/bin/p15_t1_before.rs @@ -0,0 +1,115 @@ +//! Writes `p15_t1_before`: books the version before P15 T1 (main +//! 7058fbd2, which has no call transactions: no request keys, no +//! `call.begun` or `call.closed`, no books id) wrote through its Store API: +//! a receipted opening and purchase, a purchase with no receipt, a +//! reversal, an invoice with a part payment, a vendor bill, an open draft, +//! and a closed January. This version opens the same journal, reads it as +//! ever, takes no write until the owner's format upgrade (D-89), and +//! reports the same figures. +use chrono::NaiveDate; +use ledger_core::{AccountType, Currency, DocumentLine, Money, Side}; +use ledger_store::Store; +use rust_decimal::Decimal; +use std::path::PathBuf; + +fn d(y: i32, m: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(y, m, day).unwrap() +} +fn cents(c: i64) -> Decimal { + Decimal::new(c, 2) +} +fn usd(c: i64) -> Money { + Money::new(cents(c), Currency::USD) +} + +fn main() { + let root = PathBuf::from(std::env::args().nth(1).unwrap()); + let dir = root.join("p15_t1_before"); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = Store::create(&dir, Currency::USD).unwrap(); + let bank = s.add_account("1000", "Bank", AccountType::Asset, None, false).unwrap(); + let capital = s.add_account("3000", "Capital", AccountType::Equity, None, false).unwrap(); + let sales = s.add_account("4000", "Sales", AccountType::Revenue, None, false).unwrap(); + let rent = s.add_account("6000", "Rent", AccountType::Expense, None, false).unwrap(); + let software = s.add_account("6100", "Software", AccountType::Expense, None, false).unwrap(); + let post = |s: &mut Store, date: NaiveDate, what: &str, dr: u64, cr: u64, c: i64| { + let e = s.create_entry(date, what).unwrap(); + s.add_line(e, dr, Side::Debit, usd(c)).unwrap(); + s.add_line(e, cr, Side::Credit, usd(c)).unwrap(); + e + }; + let seed = post(&mut s, d(2026, 1, 1), "Opening capital", bank, capital, 100_000); + s.post_entry(seed).unwrap(); + s.attach_receipt(Some(seed), "opening.txt", "text/plain", b"Opening deposit 1000.00 2026-01-01", None) + .unwrap(); + let rent_jan = post(&mut s, d(2026, 1, 5), "January rent", rent, bank, 50_000); + s.post_entry(rent_jan).unwrap(); + s.attach_receipt(Some(rent_jan), "rent.txt", "text/plain", b"Rent January 500.00 2026-01-05", None) + .unwrap(); + // 40.00 is over the 25.00 threshold: no receipt, so an audit finds it. + let paper = post(&mut s, d(2026, 1, 7), "Printer paper", software, bank, 4_000); + s.post_entry(paper).unwrap(); + // Under the threshold: needs none. + let stamps = post(&mut s, d(2026, 1, 8), "Stamps", software, bank, 1_200); + s.post_entry(stamps).unwrap(); + let wrong = post(&mut s, d(2026, 1, 12), "Rent paid twice", rent, bank, 50_000); + s.post_entry(wrong).unwrap(); + s.attach_receipt(Some(wrong), "rent2.txt", "text/plain", b"Rent again 500.00 2026-01-12", None) + .unwrap(); + s.reverse_entry(wrong, d(2026, 1, 14), "Entered twice").unwrap(); + let customer = s.add_customer("Fernhill Labs").unwrap(); + let inv = s + .create_invoice( + customer, + d(2026, 1, 10), + d(2026, 2, 9), + vec![DocumentLine { + description: "Design".into(), + amount: cents(120_000), + class_id: None, + account: None, + quantity: None, + unit_price: None, + }], + ) + .unwrap(); + s.receive_payment(inv, d(2026, 1, 20), cents(40_000), bank).unwrap(); + // An open draft in February; January closes around it. + let vendor = s.add_vendor("Paper Co").unwrap(); + s.create_bill( + vendor, + d(2026, 1, 15), + d(2026, 2, 14), + vec![DocumentLine { + description: "Toner".into(), + amount: cents(8_000), + class_id: None, + account: None, + quantity: None, + unit_price: None, + }], + ) + .unwrap(); + let vendor = s.add_vendor("Paper Co").unwrap(); + s.create_bill( + vendor, + d(2026, 1, 15), + d(2026, 2, 14), + vec![DocumentLine { + description: "Toner".into(), + amount: cents(8_000), + class_id: None, + account: None, + quantity: None, + unit_price: None, + }], + ) + .unwrap(); + let _open = post(&mut s, d(2026, 2, 12), "Coworking day pass", rent, bank, 3_500); + let jan = s.create_period("2026-01", d(2026, 1, 1), d(2026, 1, 31)).unwrap(); + s.close_period(jan).unwrap(); + let _ = sales; + s.verify().unwrap(); + println!("WROTE {:?}", dir); +} diff --git a/crates/ledger-store/tests/fixtures/old-books/p15_t1_before/blobs/0d/46/0d462b0d3e7b13628aa5b6279a6ced262a8670bd5d7063a0668469398ac6523e b/crates/ledger-store/tests/fixtures/old-books/p15_t1_before/blobs/0d/46/0d462b0d3e7b13628aa5b6279a6ced262a8670bd5d7063a0668469398ac6523e new file mode 100644 index 00000000..c0a41246 --- /dev/null +++ b/crates/ledger-store/tests/fixtures/old-books/p15_t1_before/blobs/0d/46/0d462b0d3e7b13628aa5b6279a6ced262a8670bd5d7063a0668469398ac6523e @@ -0,0 +1 @@ +Opening deposit 1000.00 2026-01-01 \ No newline at end of file diff --git a/crates/ledger-store/tests/fixtures/old-books/p15_t1_before/blobs/65/c7/65c730c09a9b8c3ecf4cc2ae55fafe083dc33e2111abe6cafaf6fcb02a7d8ad8 b/crates/ledger-store/tests/fixtures/old-books/p15_t1_before/blobs/65/c7/65c730c09a9b8c3ecf4cc2ae55fafe083dc33e2111abe6cafaf6fcb02a7d8ad8 new file mode 100644 index 00000000..22c35d34 --- /dev/null +++ b/crates/ledger-store/tests/fixtures/old-books/p15_t1_before/blobs/65/c7/65c730c09a9b8c3ecf4cc2ae55fafe083dc33e2111abe6cafaf6fcb02a7d8ad8 @@ -0,0 +1 @@ +Rent again 500.00 2026-01-12 \ No newline at end of file diff --git a/crates/ledger-store/tests/fixtures/old-books/p15_t1_before/blobs/dd/30/dd3075d12716028c7ae1b8f9a10c590f8f4cc26ff4d854e30c9551ef7ad5898f b/crates/ledger-store/tests/fixtures/old-books/p15_t1_before/blobs/dd/30/dd3075d12716028c7ae1b8f9a10c590f8f4cc26ff4d854e30c9551ef7ad5898f new file mode 100644 index 00000000..e77bc398 --- /dev/null +++ b/crates/ledger-store/tests/fixtures/old-books/p15_t1_before/blobs/dd/30/dd3075d12716028c7ae1b8f9a10c590f8f4cc26ff4d854e30c9551ef7ad5898f @@ -0,0 +1 @@ +Rent January 500.00 2026-01-05 \ No newline at end of file diff --git a/crates/ledger-store/tests/fixtures/old-books/p15_t1_before/expected.json b/crates/ledger-store/tests/fixtures/old-books/p15_t1_before/expected.json new file mode 100644 index 00000000..38698c36 --- /dev/null +++ b/crates/ledger-store/tests/fixtures/old-books/p15_t1_before/expected.json @@ -0,0 +1,594 @@ +{ + "assets": [], + "bills": [ + { + "amount_paid": "0", + "date": "2026-01-15", + "due_date": "2026-02-14", + "entry_id": 9, + "id": 1, + "lines": [ + { + "amount": "80.00", + "description": "Toner" + } + ], + "status": "Open", + "vendor_id": 1 + }, + { + "amount_paid": "0", + "date": "2026-01-15", + "due_date": "2026-02-14", + "entry_id": 10, + "id": 2, + "lines": [ + { + "amount": "80.00", + "description": "Toner" + } + ], + "status": "Open", + "vendor_id": 2 + } + ], + "entries": [ + { + "date": "2026-01-01", + "description": "Opening capital", + "id": 1, + "lines": [ + { + "account": 1, + "amount": { + "amount": "1000.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Debit" + }, + { + "account": 2, + "amount": { + "amount": "1000.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Credit" + } + ], + "reversal_of": null, + "status": "Posted" + }, + { + "date": "2026-01-05", + "description": "January rent", + "id": 2, + "lines": [ + { + "account": 4, + "amount": { + "amount": "500.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Debit" + }, + { + "account": 1, + "amount": { + "amount": "500.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Credit" + } + ], + "reversal_of": null, + "status": "Posted" + }, + { + "date": "2026-01-07", + "description": "Printer paper", + "id": 3, + "lines": [ + { + "account": 5, + "amount": { + "amount": "40.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Debit" + }, + { + "account": 1, + "amount": { + "amount": "40.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Credit" + } + ], + "reversal_of": null, + "status": "Posted" + }, + { + "date": "2026-01-08", + "description": "Stamps", + "id": 4, + "lines": [ + { + "account": 5, + "amount": { + "amount": "12.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Debit" + }, + { + "account": 1, + "amount": { + "amount": "12.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Credit" + } + ], + "reversal_of": null, + "status": "Posted" + }, + { + "date": "2026-01-12", + "description": "Rent paid twice", + "id": 5, + "lines": [ + { + "account": 4, + "amount": { + "amount": "500.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Debit" + }, + { + "account": 1, + "amount": { + "amount": "500.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Credit" + } + ], + "reversal_of": null, + "status": "Posted" + }, + { + "date": "2026-01-14", + "description": "Entered twice", + "id": 6, + "lines": [ + { + "account": 4, + "amount": { + "amount": "500.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Credit" + }, + { + "account": 1, + "amount": { + "amount": "500.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Debit" + } + ], + "reversal_of": 5, + "status": "Posted" + }, + { + "date": "2026-01-10", + "description": "Invoice 1", + "id": 7, + "lines": [ + { + "account": 6, + "amount": { + "amount": "1200.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Debit" + }, + { + "account": 3, + "amount": { + "amount": "1200.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Credit" + } + ], + "reversal_of": null, + "status": "Posted" + }, + { + "date": "2026-01-20", + "description": "Payment on invoice 1", + "id": 8, + "lines": [ + { + "account": 6, + "amount": { + "amount": "400.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Credit" + }, + { + "account": 1, + "amount": { + "amount": "400.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Debit" + } + ], + "reversal_of": null, + "status": "Posted" + }, + { + "date": "2026-01-15", + "description": "Bill 1", + "id": 9, + "lines": [ + { + "account": 7, + "amount": { + "amount": "80.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Debit" + }, + { + "account": 8, + "amount": { + "amount": "80.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Credit" + } + ], + "reversal_of": null, + "status": "Posted" + }, + { + "date": "2026-01-15", + "description": "Bill 2", + "id": 10, + "lines": [ + { + "account": 7, + "amount": { + "amount": "80.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Debit" + }, + { + "account": 8, + "amount": { + "amount": "80.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Credit" + } + ], + "reversal_of": null, + "status": "Posted" + }, + { + "date": "2026-02-12", + "description": "Coworking day pass", + "id": 11, + "lines": [ + { + "account": 4, + "amount": { + "amount": "35.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Debit" + }, + { + "account": 1, + "amount": { + "amount": "35.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Credit" + } + ], + "reversal_of": null, + "status": "Draft" + }, + { + "date": "2026-01-31", + "description": "Close period 2026-01", + "id": 12, + "lines": [ + { + "account": 3, + "amount": { + "amount": "1200.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Debit" + }, + { + "account": 4, + "amount": { + "amount": "500.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Credit" + }, + { + "account": 5, + "amount": { + "amount": "52.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Credit" + }, + { + "account": 7, + "amount": { + "amount": "160.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Credit" + }, + { + "account": 9, + "amount": { + "amount": "488.00", + "currency": [ + 85, + 83, + 68 + ] + }, + "side": "Credit" + } + ], + "reversal_of": null, + "status": "Posted" + } + ], + "entry_parties": [ + [ + 7, + [ + { + "party_id": 1, + "share": "derived" + } + ] + ], + [ + 8, + [ + { + "party_id": 1, + "share": "derived" + } + ] + ], + [ + 9, + [ + { + "party_id": 2, + "share": "derived" + } + ] + ], + [ + 10, + [ + { + "party_id": 3, + "share": "derived" + } + ] + ] + ], + "invoices": [ + { + "amount_paid": "400.00", + "customer_id": 1, + "date": "2026-01-10", + "due_date": "2026-02-09", + "entry_id": 7, + "id": 1, + "lines": [ + { + "amount": "1200.00", + "description": "Design" + } + ], + "status": "Partial" + } + ], + "payroll_runs": [], + "periods": [ + { + "close_seq": 1, + "closing_entry": 12, + "end": "2026-01-31", + "id": 1, + "member_close": null, + "name": "2026-01", + "start": "2026-01-01", + "status": "Closed" + } + ], + "recurring": [], + "schedules": [], + "snapshot": { + "Ok": { + "balance_sheet": { + "assets": "1648", + "balanced": true, + "current_earnings": "0", + "equity": "1488", + "liabilities": "160" + }, + "profit_and_loss": { + "expenses": "0", + "net_income": "0", + "revenue": "0" + }, + "trial_balance": { + "lines": [ + { + "code": "1000", + "credit": "0", + "debit": "848", + "name": "Bank" + }, + { + "code": "1200", + "credit": "0", + "debit": "800", + "name": "Accounts Receivable" + }, + { + "code": "2000", + "credit": "160", + "debit": "0", + "name": "Accounts Payable" + }, + { + "code": "3000", + "credit": "1000", + "debit": "0", + "name": "Capital" + }, + { + "code": "3999", + "credit": "488", + "debit": "0", + "name": "Retained Earnings" + } + ], + "total_credits": "1648", + "total_debits": "1648" + } + } + }, + "verify": { + "Ok": null + } +} diff --git a/crates/ledger-store/tests/fixtures/old-books/p15_t1_before/journal.jsonl b/crates/ledger-store/tests/fixtures/old-books/p15_t1_before/journal.jsonl new file mode 100644 index 00000000..5f98d1e2 --- /dev/null +++ b/crates/ledger-store/tests/fixtures/old-books/p15_t1_before/journal.jsonl @@ -0,0 +1,66 @@ +{"payload":{"base_currency":"USD"},"prev":"0000000000000000000000000000000000000000000000000000000000000000","seq":1,"ts":"2026-11-21T17:21:17Z","type":"store.created"} +{"payload":{"features":["account_renamed","asset_basis","attachment_text","audits","depreciation_catch_up","disposal_before_service","document_line_projects","document_standing","documents_v2","drafts_v2","members_cumulative","month_reposting","party_creditors","payment_instruments","projects","require_tax_category","schedule_convention","schedule_minor_unit","source_revisions","tax_categories_gain_exempt","vendor_1099_decisions"],"format":2},"prev":"2b84eff6c3870874bd3b147f92a9f4afae201804c4bbe6fcbd898754905aa657","seq":2,"ts":"2026-11-21T17:21:17Z","type":"journal.format_set"} +{"payload":{"account_type":"Asset","code":"1000","currency":"USD","id":1,"name":"Bank","parent":null,"placeholder":false},"prev":"e1ab1c72030a2a0710158fca913aca1f42a3ddf06a864d0e14e6a290d3a2feab","seq":3,"ts":"2026-11-21T17:21:17Z","type":"account.added"} +{"payload":{"account_type":"Equity","code":"3000","currency":"USD","id":2,"name":"Capital","parent":null,"placeholder":false},"prev":"6717f495b84133c3f02280db421be6da564d7a742415f60067b3fc102780cd3c","seq":4,"ts":"2026-11-21T17:21:17Z","type":"account.added"} +{"payload":{"account_type":"Revenue","code":"4000","currency":"USD","id":3,"name":"Sales","parent":null,"placeholder":false},"prev":"ed7d9fe2e9501fb6519aa6bbe42eb7c7682254f4b35b0c3db22e9fd47b4dc638","seq":5,"ts":"2026-11-21T17:21:17Z","type":"account.added"} +{"payload":{"account_type":"Expense","code":"6000","currency":"USD","id":4,"name":"Rent","parent":null,"placeholder":false},"prev":"7642d09215f0a106829fea696429f192970f41bd89f22c820fd7aa8e7078ea31","seq":6,"ts":"2026-11-21T17:21:17Z","type":"account.added"} +{"payload":{"account_type":"Expense","code":"6100","currency":"USD","id":5,"name":"Software","parent":null,"placeholder":false},"prev":"6f5e42a32c90e5fe9aa194404910e0f4352d04e37c8d3fd280940aa623eb1563","seq":7,"ts":"2026-11-21T17:21:17Z","type":"account.added"} +{"payload":{"date":"2026-01-01","description":"Opening capital","id":1},"prev":"1e7f06bdf05c2d3818507adfff1df00b970112b231ea6a8f76b10a85c9e42c8f","seq":8,"ts":"2026-11-21T17:21:17Z","type":"entry.created"} +{"payload":{"account":1,"amount":"1000.00","currency":"USD","id":1,"side":"debit"},"prev":"ba05e967a853e32cb712bf62e3df6791880d9c575b849296da96bc8ce6450811","seq":9,"ts":"2026-11-21T17:21:17Z","type":"entry.line_added"} +{"payload":{"account":2,"amount":"1000.00","currency":"USD","id":1,"side":"credit"},"prev":"5232348c2c19a5b7ec0969cef65cb5ac2c8e3d8d65ecaec0d295ec60c7d3611f","seq":10,"ts":"2026-11-21T17:21:17Z","type":"entry.line_added"} +{"payload":{"date":"2026-01-01","description":"Opening capital","id":1,"lines":[{"account":1,"amount":"1000.00","currency":"USD","side":"debit"},{"account":2,"amount":"1000.00","currency":"USD","side":"credit"}],"reversal_of":null},"prev":"e0b96ba7f5827397e2c89e878ca89a17c480e76e220ac123318ad2c1723f9bdc","seq":11,"ts":"2026-11-21T17:21:17Z","type":"entry.posted"} +{"payload":{"attachment_id":1,"blob_sha":"0d462b0d3e7b13628aa5b6279a6ced262a8670bd5d7063a0668469398ac6523e","category":"receipts","description":null,"entry_id":1,"file_name":"opening.txt","mime_type":"text/plain","size_bytes":34},"prev":"6edd977de13ff0aabca5c2f858ecc98de51f776c54106fa91a25440b634ac06d","seq":12,"ts":"2026-11-21T17:21:17Z","type":"receipt.attached"} +{"payload":{"attachment_id":1,"extractor":"wanderbooks","pages":1,"status":"ok","text_sha256":"0d462b0d3e7b13628aa5b6279a6ced262a8670bd5d7063a0668469398ac6523e","version":"0.1.0"},"prev":"41ca2d42a98d8b5eab5749c2bf71ee674f6135621a1507e26c378b06300c0257","seq":13,"ts":"2026-11-21T17:21:17Z","type":"attachment.text_extracted"} +{"payload":{"date":"2026-01-05","description":"January rent","id":2},"prev":"9708c879fa1b9bf0ec0a428dbc90729538b5955ebd04ef00b5fb40548463584f","seq":14,"ts":"2026-11-21T17:21:17Z","type":"entry.created"} +{"payload":{"account":4,"amount":"500.00","currency":"USD","id":2,"side":"debit"},"prev":"cf9c43907f31ca54887f2de7daac8c6ff9ebe7458ef27b440eb0cf492adf3d4e","seq":15,"ts":"2026-11-21T17:21:17Z","type":"entry.line_added"} +{"payload":{"account":1,"amount":"500.00","currency":"USD","id":2,"side":"credit"},"prev":"1cb79ebc08696ad70a990b08fa54025d48db4ad1e8eee9f4110ef92ec905c68e","seq":16,"ts":"2026-11-21T17:21:17Z","type":"entry.line_added"} +{"payload":{"date":"2026-01-05","description":"January rent","id":2,"lines":[{"account":4,"amount":"500.00","currency":"USD","side":"debit"},{"account":1,"amount":"500.00","currency":"USD","side":"credit"}],"reversal_of":null},"prev":"841b939d3ef9524aeaef5eb37ef045cafb19ae66647906e573b370f8c2df31a5","seq":17,"ts":"2026-11-21T17:21:17Z","type":"entry.posted"} +{"payload":{"attachment_id":2,"blob_sha":"dd3075d12716028c7ae1b8f9a10c590f8f4cc26ff4d854e30c9551ef7ad5898f","category":"receipts","description":null,"entry_id":2,"file_name":"rent.txt","mime_type":"text/plain","size_bytes":30},"prev":"3f149bb954e0c132a0673de90a6028cb3378e3bba70aa8d2ac6da74f8aec0f0c","seq":18,"ts":"2026-11-21T17:21:17Z","type":"receipt.attached"} +{"payload":{"attachment_id":2,"extractor":"wanderbooks","pages":1,"status":"ok","text_sha256":"dd3075d12716028c7ae1b8f9a10c590f8f4cc26ff4d854e30c9551ef7ad5898f","version":"0.1.0"},"prev":"e963e11c535bd64fea1a052f164c23c6a69e0e30119bb31dc03ce3f2bbc1e009","seq":19,"ts":"2026-11-21T17:21:17Z","type":"attachment.text_extracted"} +{"payload":{"date":"2026-01-07","description":"Printer paper","id":3},"prev":"a5e0cd4357ca13480837afcf430bd7d7d1fe71f19e7e0b94b5f83127449b484c","seq":20,"ts":"2026-11-21T17:21:17Z","type":"entry.created"} +{"payload":{"account":5,"amount":"40.00","currency":"USD","id":3,"side":"debit"},"prev":"60a961e8d2a377a5060ac7b9855ecd9fa980acda3df626f843465bd699f20683","seq":21,"ts":"2026-11-21T17:21:17Z","type":"entry.line_added"} +{"payload":{"account":1,"amount":"40.00","currency":"USD","id":3,"side":"credit"},"prev":"79ec9eb7e2964e39c3495a494e6207a5fcaa888c90be3784da24274e900e47d2","seq":22,"ts":"2026-11-21T17:21:17Z","type":"entry.line_added"} +{"payload":{"date":"2026-01-07","description":"Printer paper","id":3,"lines":[{"account":5,"amount":"40.00","currency":"USD","side":"debit"},{"account":1,"amount":"40.00","currency":"USD","side":"credit"}],"reversal_of":null},"prev":"1b032147bac04d88d186dd898015ecf1760540f87309fb34726d6581c25e25e5","seq":23,"ts":"2026-11-21T17:21:17Z","type":"entry.posted"} +{"payload":{"date":"2026-01-08","description":"Stamps","id":4},"prev":"7c6576c6e37574f37aa19367bcb6eb903bced46ae9af4743cb013e5108394379","seq":24,"ts":"2026-11-21T17:21:17Z","type":"entry.created"} +{"payload":{"account":5,"amount":"12.00","currency":"USD","id":4,"side":"debit"},"prev":"5ba613907078b656dc44b89902bdcfd3f2d852bd46476ed572a3aceb1bda5fd3","seq":25,"ts":"2026-11-21T17:21:17Z","type":"entry.line_added"} +{"payload":{"account":1,"amount":"12.00","currency":"USD","id":4,"side":"credit"},"prev":"7974e98292837366d966fdae04a9b1da20343b9716402b00446e91961e91b5be","seq":26,"ts":"2026-11-21T17:21:18Z","type":"entry.line_added"} +{"payload":{"date":"2026-01-08","description":"Stamps","id":4,"lines":[{"account":5,"amount":"12.00","currency":"USD","side":"debit"},{"account":1,"amount":"12.00","currency":"USD","side":"credit"}],"reversal_of":null},"prev":"103ffeb3ea65bcb6fb9d1d98e053b820854bb365a5ecd6e79ca9566ddfc2d1a3","seq":27,"ts":"2026-11-21T17:21:18Z","type":"entry.posted"} +{"payload":{"date":"2026-01-12","description":"Rent paid twice","id":5},"prev":"fb2fd5dac822d531039a36dc21acdf01fa52e7fd7742503b1dc0f57d169bde2f","seq":28,"ts":"2026-11-21T17:21:18Z","type":"entry.created"} +{"payload":{"account":4,"amount":"500.00","currency":"USD","id":5,"side":"debit"},"prev":"4173cac71861ded819608087a7d1f8b95eacf66def4d771f52352659551eefde","seq":29,"ts":"2026-11-21T17:21:18Z","type":"entry.line_added"} +{"payload":{"account":1,"amount":"500.00","currency":"USD","id":5,"side":"credit"},"prev":"8bec73a440c2775a7c2db2ea4646224ee3fa750099afa51f0c98d23fe9c670c9","seq":30,"ts":"2026-11-21T17:21:18Z","type":"entry.line_added"} +{"payload":{"date":"2026-01-12","description":"Rent paid twice","id":5,"lines":[{"account":4,"amount":"500.00","currency":"USD","side":"debit"},{"account":1,"amount":"500.00","currency":"USD","side":"credit"}],"reversal_of":null},"prev":"b3f437e100a5f779b482e5beedde09803d3824a7e6ef2b20ad8153d6d08fd385","seq":31,"ts":"2026-11-21T17:21:18Z","type":"entry.posted"} +{"payload":{"attachment_id":3,"blob_sha":"65c730c09a9b8c3ecf4cc2ae55fafe083dc33e2111abe6cafaf6fcb02a7d8ad8","category":"receipts","description":null,"entry_id":5,"file_name":"rent2.txt","mime_type":"text/plain","size_bytes":28},"prev":"e5605c49331605dcfa94abed01ea4eb3bc709c8a8cc135e152567fb9b4f4bbf5","seq":32,"ts":"2026-11-21T17:21:18Z","type":"receipt.attached"} +{"payload":{"attachment_id":3,"extractor":"wanderbooks","pages":1,"status":"ok","text_sha256":"65c730c09a9b8c3ecf4cc2ae55fafe083dc33e2111abe6cafaf6fcb02a7d8ad8","version":"0.1.0"},"prev":"3c50461894af5053a8fb32bb0c3c194b2f206c368e59e1730da85bef70469c64","seq":33,"ts":"2026-11-21T17:21:18Z","type":"attachment.text_extracted"} +{"payload":{"date":"2026-01-14","description":"Entered twice","id":6,"lines":[{"account":4,"amount":"500.00","currency":"USD","side":"credit"},{"account":1,"amount":"500.00","currency":"USD","side":"debit"}],"reverses":5},"prev":"ec86f4668bfafe0a6b2c17ca4e7bff2fdc5a053f3b8793f1d7684b15b75afe91","seq":34,"ts":"2026-11-21T17:21:18Z","type":"entry.reversed"} +{"payload":{"id":1,"name":"Fernhill Labs"},"prev":"fbbf3ba9de71b08916b141169d3a6afc02012dacd75c65a6e1ea1ca2c5870226","seq":35,"ts":"2026-11-21T17:21:18Z","type":"customer.added"} +{"payload":{"account_type":"Asset","code":"1200","currency":"USD","id":6,"name":"Accounts Receivable","parent":null,"placeholder":false},"prev":"9bb260c5fc23b8979a86dfb82434f27fbec5f08f05e14fabe263a7ebf5ac06f2","seq":36,"ts":"2026-11-21T17:21:18Z","type":"account.added"} +{"payload":{"date":"2026-01-10","description":"Invoice 1","id":7},"prev":"c7bb545bbd78dbd9c0e484ca0b30daf365428c184a2d0a1c7026a6c9f1534f28","seq":37,"ts":"2026-11-21T17:21:18Z","type":"entry.created"} +{"payload":{"account":6,"amount":"1200.00","currency":"USD","id":7,"side":"debit"},"prev":"b2eed9cb65adb9b62d6d8f1edb612f5c457dc10860669431cd38ff3e1063875d","seq":38,"ts":"2026-11-21T17:21:18Z","type":"entry.line_added"} +{"payload":{"account":3,"amount":"1200.00","currency":"USD","id":7,"side":"credit"},"prev":"3b562385f5122e382edef85cebf101572a7f942b8bdc661d974ff04b790c6a4a","seq":39,"ts":"2026-11-21T17:21:18Z","type":"entry.line_added"} +{"payload":{"date":"2026-01-10","description":"Invoice 1","id":7,"lines":[{"account":6,"amount":"1200.00","currency":"USD","side":"debit"},{"account":3,"amount":"1200.00","currency":"USD","side":"credit"}],"reversal_of":null},"prev":"d12b8ed32eb20092a70772e0d5c41d1e3282fae11c2fe2e41464932d12338c2d","seq":40,"ts":"2026-11-21T17:21:18Z","type":"entry.posted"} +{"payload":{"customer_id":1,"date":"2026-01-10","due_date":"2026-02-09","entry_id":7,"id":1,"lines":[{"amount":"1200.00","description":"Design"}]},"prev":"db2f943a9fc4f63ce1bdb693c337b677ade9b2c8304644e2eaa305430f4ea460","seq":41,"ts":"2026-11-21T17:21:18Z","type":"invoice.created"} +{"payload":{"date":"2026-01-20","description":"Payment on invoice 1","id":8},"prev":"6fdfb950b0348503b3f15d7e30bc7df82bd8e7fa89d5536c3a278c0e62848b50","seq":42,"ts":"2026-11-21T17:21:18Z","type":"entry.created"} +{"payload":{"account":6,"amount":"400.00","currency":"USD","id":8,"side":"credit"},"prev":"9c7e1b9401452196792a66965b83976e1a729841ade564e0ce4040b5508065bc","seq":43,"ts":"2026-11-21T17:21:18Z","type":"entry.line_added"} +{"payload":{"account":1,"amount":"400.00","currency":"USD","id":8,"side":"debit"},"prev":"3efb25e4c64f06bde9906e2613050eed434e194c4375e89c77a01a9268651edd","seq":44,"ts":"2026-11-21T17:21:18Z","type":"entry.line_added"} +{"payload":{"date":"2026-01-20","description":"Payment on invoice 1","id":8,"lines":[{"account":6,"amount":"400.00","currency":"USD","side":"credit"},{"account":1,"amount":"400.00","currency":"USD","side":"debit"}],"reversal_of":null},"prev":"2cbd6a77427a46a5768516971a08848971b369a2d98d5151366776d1bfd212e4","seq":45,"ts":"2026-11-21T17:21:18Z","type":"entry.posted"} +{"payload":{"amount":"400.00","cash_account":1,"date":"2026-01-20","entry_id":8,"invoice_id":1},"prev":"9d6f20f7dceed2bfc4ad665add8646619c504c4368c1edf71df47835150b5c49","seq":46,"ts":"2026-11-21T17:21:18Z","type":"invoice.payment_received"} +{"payload":{"id":1,"name":"Paper Co"},"prev":"4c50d9955f03b91e2c3fce29fd887deb5ab9096584e47c5a85efc34f49ed72a2","seq":47,"ts":"2026-11-21T17:21:18Z","type":"vendor.added"} +{"payload":{"account_type":"Expense","code":"6999","currency":"USD","id":7,"name":"General Expenses","parent":null,"placeholder":false},"prev":"5553de03d5aac9b56f60a9bbde5aa42e44ff344586c418b9856227f22f1f46e2","seq":48,"ts":"2026-11-21T17:21:18Z","type":"account.added"} +{"payload":{"account_type":"Liability","code":"2000","currency":"USD","id":8,"name":"Accounts Payable","parent":null,"placeholder":false},"prev":"30f702f2b37017c5c874db07dcd6c67613b9109a12d56f8239ed6f4eff1eae19","seq":49,"ts":"2026-11-21T17:21:18Z","type":"account.added"} +{"payload":{"date":"2026-01-15","description":"Bill 1","id":9},"prev":"61e35219d6faa4b6340533b8a2cacfd43debe53782c8d4e63eac22ca5d2e5805","seq":50,"ts":"2026-11-21T17:21:18Z","type":"entry.created"} +{"payload":{"account":7,"amount":"80.00","currency":"USD","id":9,"side":"debit"},"prev":"a4ebfaa95046b0a5d59a7cd32871ffbe18b3250a6134b164089267e7bec63ba0","seq":51,"ts":"2026-11-21T17:21:18Z","type":"entry.line_added"} +{"payload":{"account":8,"amount":"80.00","currency":"USD","id":9,"side":"credit"},"prev":"28858765913dfef4c936f4fdf7d875a5851fa63b09f5a0adbc4cee4e2fc4ff58","seq":52,"ts":"2026-11-21T17:21:18Z","type":"entry.line_added"} +{"payload":{"date":"2026-01-15","description":"Bill 1","id":9,"lines":[{"account":7,"amount":"80.00","currency":"USD","side":"debit"},{"account":8,"amount":"80.00","currency":"USD","side":"credit"}],"reversal_of":null},"prev":"218c776b0c1154a98411a33181dd6d3cafd8043efac16f6af95b9795d39ebb22","seq":53,"ts":"2026-11-21T17:21:18Z","type":"entry.posted"} +{"payload":{"date":"2026-01-15","due_date":"2026-02-14","entry_id":9,"id":1,"lines":[{"amount":"80.00","description":"Toner"}],"vendor_id":1},"prev":"e1229f4d739cc44e2c78d931779122ca55a5d4606c828e59258e7dd0741bed6f","seq":54,"ts":"2026-11-21T17:21:18Z","type":"bill.created"} +{"payload":{"id":2,"name":"Paper Co"},"prev":"18235b3318fecf59ffbf80dd90fec3040aa71e5ac35fcf6a7343839ef0f3e51e","seq":55,"ts":"2026-11-21T17:21:18Z","type":"vendor.added"} +{"payload":{"date":"2026-01-15","description":"Bill 2","id":10},"prev":"3948822602f054c0c5f175bf772267a1a504663d71b51cc2b6e4d2873c2aa585","seq":56,"ts":"2026-11-21T17:21:18Z","type":"entry.created"} +{"payload":{"account":7,"amount":"80.00","currency":"USD","id":10,"side":"debit"},"prev":"6c8573a7d6478bfc33a3400179e0144e84f8fa335f3ed4f522ffb802258ac57d","seq":57,"ts":"2026-11-21T17:21:18Z","type":"entry.line_added"} +{"payload":{"account":8,"amount":"80.00","currency":"USD","id":10,"side":"credit"},"prev":"972930a53a0eaf33104f6ef30564bc700b4f0555e6fc30c51e8530adfd7377b5","seq":58,"ts":"2026-11-21T17:21:18Z","type":"entry.line_added"} +{"payload":{"date":"2026-01-15","description":"Bill 2","id":10,"lines":[{"account":7,"amount":"80.00","currency":"USD","side":"debit"},{"account":8,"amount":"80.00","currency":"USD","side":"credit"}],"reversal_of":null},"prev":"2209efd9c19b9294c129ae160212b8c9b43af67795d6b27428f51131305eb5bf","seq":59,"ts":"2026-11-21T17:21:18Z","type":"entry.posted"} +{"payload":{"date":"2026-01-15","due_date":"2026-02-14","entry_id":10,"id":2,"lines":[{"amount":"80.00","description":"Toner"}],"vendor_id":2},"prev":"42303256a0b0a6b78348fdaaec5d40005e6fd3f423822d0059ac88116115a42a","seq":60,"ts":"2026-11-21T17:21:18Z","type":"bill.created"} +{"payload":{"date":"2026-02-12","description":"Coworking day pass","id":11},"prev":"298490d98419cf6c6160cc13985e1d8ed7b89c0a22ff562bea61adc48644b638","seq":61,"ts":"2026-11-21T17:21:18Z","type":"entry.created"} +{"payload":{"account":4,"amount":"35.00","currency":"USD","id":11,"side":"debit"},"prev":"85eb41426eaa06c547b0de87a9a2d316c52c99857370685abfdebcebcdba4a95","seq":62,"ts":"2026-11-21T17:21:18Z","type":"entry.line_added"} +{"payload":{"account":1,"amount":"35.00","currency":"USD","id":11,"side":"credit"},"prev":"a2471ce2220b5149a57111bc24b8e2099272a7ba70df2ed0c0d0cc4f07a85894","seq":63,"ts":"2026-11-21T17:21:18Z","type":"entry.line_added"} +{"payload":{"end":"2026-01-31","id":1,"name":"2026-01","start":"2026-01-01"},"prev":"2404ced35786e0fc18b89e6abc40ae38b71744d11e873c268861eb161d44955c","seq":64,"ts":"2026-11-21T17:21:18Z","type":"period.created"} +{"payload":{"account_type":"Equity","code":"3999","currency":"USD","id":9,"name":"Retained Earnings","parent":null,"placeholder":false},"prev":"eba0c17e576a4cda32ec8dc1d0e5009d43aa75bf4bb15f62dc8486a23f49e259","seq":65,"ts":"2026-11-21T17:21:18Z","type":"account.added"} +{"payload":{"close_to":"retained_earnings","closing_entry":12,"entry":{"date":"2026-01-31","description":"Close period 2026-01","id":12,"lines":[{"account":3,"amount":"1200.00","currency":"USD","side":"debit"},{"account":4,"amount":"500.00","currency":"USD","side":"credit"},{"account":5,"amount":"52.00","currency":"USD","side":"credit"},{"account":7,"amount":"160.00","currency":"USD","side":"credit"},{"account":9,"amount":"488.00","currency":"USD","side":"credit"}]},"id":1},"prev":"2ee4640029200f64e0e12dee7b23b8d320617f17843eb43c45ce1a29bd8fd04f","seq":66,"ts":"2026-11-21T17:21:18Z","type":"period.closed"} diff --git a/crates/ledger-store/tests/store.rs b/crates/ledger-store/tests/store.rs index b2fa05e8..a8a62319 100644 --- a/crates/ledger-store/tests/store.rs +++ b/crates/ledger-store/tests/store.rs @@ -2316,11 +2316,70 @@ fn books_written_under_older_rules_still_open() { "method": method, "audit_run_id": 1}), ) .unwrap(); + // P15 T1's new shape (`call_transactions`), hand-written as this + // version writes it: a call's lines between `call.begun` and + // `call.closed`. They count only when the closing line says `ok`. An + // ok call (a note on the party), a call that failed (whose party id + // is handed out again by the standalone line after it), a call that + // never finished, and an ok call whose answer was too long to keep. + let frame = |w: &mut JournalWriter, outcome: &str, lines: &[(&str, serde_json::Value)]| { + let id = json!({"tool": "books.update_party", "token": "t-1", + "key": format!("key-frame-{outcome}"), "args": "ab".repeat(32)}); + let begun = w.append("call.begun", id.clone()).unwrap().seq; + let mut last = begun; + for (ty, payload) in lines { + last = w.append(ty, payload.clone()).unwrap().seq; + } + let mut closed = id; + closed["outcome"] = json!(outcome); + closed["first_seq"] = json!(begun); + closed["last_seq"] = json!(last); + match outcome { + "ok" => closed["answer"] = json!(r#"{"party_id":1}"#), + "long" => { + closed["outcome"] = json!("ok"); + closed["answer_sha256"] = json!("cd".repeat(32)); + closed["answer_bytes"] = json!(9000); + } + "failed" => closed["error"] = json!("the call failed after its lines"), + _ => closed["error"] = json!("the call never finished"), + } + w.append("call.closed", closed).unwrap(); + }; + let note = |text: &str| { + ( + "party.updated", + json!({"id": 1, "change": {"field": "notes", "value": text}}), + ) + }; + frame(&mut w, "ok", &[note("counted")]); + frame( + &mut w, + "failed", + &[ + ("party.added", json!({"id": 4, "name": "Dead", "roles": []})), + note("not counted: failed"), + ], + ); + // The id the failed call had is handed out again. + w.append("party.added", json!({"id": 4, "name": "Real", "roles": []})) + .unwrap(); + frame(&mut w, "unfinished", &[note("not counted: unfinished")]); + frame(&mut w, "long", &[note("counted, long answer")]); drop(w); // Opening rebuilds from the journal; it must accept all of it. let _ = std::fs::remove_file(dir.join(ledger_store::db_file())); let store = Store::open(&dir).expect("older books still open"); store.verify().unwrap(); + // Only the lines of calls that closed ok are the books': the last note + // is the long-answer call's, the failed call's party never was, and + // the id it had is the standalone party's. + assert_eq!( + store.ledger().get_party(1).unwrap().notes.as_deref(), + Some("counted, long answer") + ); + assert_eq!(store.ledger().get_party(4).unwrap().name, "Real"); + assert!(store.ledger().get_party(5).is_none()); assert_eq!(store.journal_format().format, 1); assert_eq!(store.ledger().chart().len(), 9); assert_eq!(store.ledger().list_periods().len(), 2); From b592aaf4163b6965031343a6cd351dc1a153f444 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 10:40:00 -0700 Subject: [PATCH 6/6] docs,test: claims WB-format-8 to 10, the interface, the handbook and the tests follow the review WB-format-8 now says every reader applies the frame rule because ids are reused after a failed call, and names the committed accessor and the labels; WB-format-9 the keyed argument digest, the bounded answer, the in-memory table for calls that wrote nothing and what a repeat of a long answer is told; WB-format-10 the vault staged inside the transaction and the honest words when the closing line is on disk. docs/mcp-interface.md, the receipt store's frame paragraph and the handbook (contract, tracing figures) say the same. Tests follow the new shapes: a call that wrote nothing leaves no line, the head a write answers is where its own lines end and its closing line follows, the idempotency table compares events, and the checks that a refusal or a preview wrote nothing compare the raw journal. Co-Authored-By: Claude Fable 5.2 --- crates/ledger-cli/tests/agent_surface.rs | 11 +- crates/ledger-cli/tests/documents.rs | 2 +- crates/ledger-cli/tests/drafts.rs | 4 +- crates/ledger-cli/tests/format_upgrade.rs | 6 +- crates/ledger-cli/tests/spec_mcp.rs | 5 - crates/ledger-cli/tests/spec_vault.rs | 4 +- crates/ledger-mcp/handbook/contract.md | 1 + crates/ledger-mcp/handbook/tracing-figures.md | 1 + crates/ledger-mcp/src/tools/journal.rs | 2 +- crates/ledger-store/tests/calls.rs | 4 +- docs/mcp-interface.md | 35 +++++ docs/receipt-store.md | 26 +++- docs/spec/claims/format.md | 142 ++++++++++++------ 13 files changed, 175 insertions(+), 68 deletions(-) diff --git a/crates/ledger-cli/tests/agent_surface.rs b/crates/ledger-cli/tests/agent_surface.rs index 223bd2af..9e72a9a0 100644 --- a/crates/ledger-cli/tests/agent_surface.rs +++ b/crates/ledger-cli/tests/agent_surface.rs @@ -471,11 +471,18 @@ fn a_mutating_call_answers_with_the_head_and_a_refusal_names_its_remedy() { .unwrap(); let head = added["head"]["seq"].as_u64().unwrap(); let start = answer_of(&w.call("books.start", json!({}))).unwrap(); + // The head a write call answers is where its own lines end; its closing + // line (which holds this very answer) follows at once, and is the + // journal's head from then on (WB-format-8). assert_eq!( start["head"]["seq"], - json!(head), - "the head the call answered is the journal's" + json!(head + 1), + "the journal ends one line past the head the call answered: its closing line" ); + let journal = String::from_utf8(books.journal_raw()).unwrap(); + let last: serde_json::Value = serde_json::from_str(journal.lines().last().unwrap()).unwrap(); + assert_eq!(last["type"], "call.closed"); + assert_eq!(last["payload"]["last_seq"], json!(head)); assert!(!added["next_steps"].as_array().unwrap().is_empty()); // A confirm with no preview is refused as stale_preview, naming the // tool that previews. diff --git a/crates/ledger-cli/tests/documents.rs b/crates/ledger-cli/tests/documents.rs index c36455c8..dd733bf7 100644 --- a/crates/ledger-cli/tests/documents.rs +++ b/crates/ledger-cli/tests/documents.rs @@ -156,7 +156,7 @@ fn an_invoice_from_issue_to_paid() { 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_raw(), before, "a preview journals nothing"); - assert!(books.journal().len() == before.len()); + assert!(books.journal_raw().len() == before.len()); // The confirm: the same number, the issued copy filed with the invoice. let mut confirmed = issue.clone(); diff --git a/crates/ledger-cli/tests/drafts.rs b/crates/ledger-cli/tests/drafts.rs index 022fed3f..e8ee8524 100644 --- a/crates/ledger-cli/tests/drafts.rs +++ b/crates/ledger-cli/tests/drafts.rs @@ -349,13 +349,13 @@ fn a_package_the_build_refuses_journals_no_decision_even_with_a_reason() { draft(&mut w, "2026-03-10", "Open", "40.00"); let mut args = json!({"as_of": "2026-03-31", "cash_accounts": ["1000"]}); args["allow_open_drafts"] = json!({"reason": "the CPA wants it before the receipt comes"}); - let before = books.journal().len(); + let before = books.journal_raw().len(); for _ in 0..2 { let why = answer_of(&w.call("books.export_cpa_package", args.clone())) .expect_err("the build refuses an unknown capital account"); assert!(why.contains("unknown capital account 3999"), "{why}"); assert_eq!( - books.journal().len(), + books.journal_raw().len(), before, "a decision was journaled for a package that was refused" ); diff --git a/crates/ledger-cli/tests/format_upgrade.rs b/crates/ledger-cli/tests/format_upgrade.rs index bfa8aff0..a26aa078 100644 --- a/crates/ledger-cli/tests/format_upgrade.rs +++ b/crates/ledger-cli/tests/format_upgrade.rs @@ -997,11 +997,11 @@ fn books_p2_served_cut_over_whole() { } let verified = a.call("books.verify", json!({})).unwrap(); assert_eq!(verified["status"], "ok", "{verified}"); - // It counts the lines there were when it ran: the call's own closing - // line comes after its answer. + // It counts the lines there were when it ran, all of them: a call that + // wrote nothing leaves no closing line of its own. let events = verified["events"].as_u64().unwrap(); let on_disk = journal(&dir).iter().filter(|b| **b == b'\n').count() as u64; - assert!(events > 470 && events < on_disk, "{events} of {on_disk}"); + assert!(events > 470 && events == on_disk, "{events} of {on_disk}"); assert_eq!(verified["database"], ledger_store::db_file()); assert_eq!(verified["other_databases"], json!(["wanderbooks.db"])); assert_eq!( diff --git a/crates/ledger-cli/tests/spec_mcp.rs b/crates/ledger-cli/tests/spec_mcp.rs index aca43151..5cad70a5 100644 --- a/crates/ledger-cli/tests/spec_mcp.rs +++ b/crates/ledger-cli/tests/spec_mcp.rs @@ -224,11 +224,6 @@ impl Mcp { mcp } - /// The journal, without the frames of tool calls (D-88): the events. - fn journal(&self) -> Vec { - 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 { diff --git a/crates/ledger-cli/tests/spec_vault.rs b/crates/ledger-cli/tests/spec_vault.rs index 0f2f8d7d..b72fe215 100644 --- a/crates/ledger-cli/tests/spec_vault.rs +++ b/crates/ledger-cli/tests/spec_vault.rs @@ -2104,7 +2104,9 @@ 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_raw() != journal || vault_bytes(&m) != vault; + // The events, not the frames: a repeat with a new key is a call of + // its own, and its frame is no change of the books. + let changed = m.journal() != journal || vault_bytes(&m) != vault; *repeats_change.entry(name).or_default() |= changed; } let wrong: Vec = repeats_change diff --git a/crates/ledger-mcp/handbook/contract.md b/crates/ledger-mcp/handbook/contract.md index 374c9ff2..0eff1c98 100644 --- a/crates/ledger-mcp/handbook/contract.md +++ b/crates/ledger-mcp/handbook/contract.md @@ -11,6 +11,7 @@ You are the bookkeeping agent for these books. The engine enforces the accountin - Never invent accounts. If the account you need does not exist, add it with books.add_account first. - Posted entries are immutable; there is no edit. Corrections go through books.reverse_entry. - {evidence_rule} +- Every tool that changes the books takes a request_key you make up (8 to 128 characters, a UUID is fine), new for each different action. If an answer is lost, send the same call again with the same key and the same arguments: the books do not do it twice, and answer what they answered (for a very long answer, they say the call was done and name its journal lines). The same key with other arguments is refused. A call that fails changes nothing and leaves its key free; fix it and send it again with the same key. Books waiting for the owner's format upgrade take no write at all (the format-upgrade section). - Show the numbers: after every change, show the human the affected balances. - After posting, check books.digest and offer it to the human (the review of what changed), so they can review it too. - A full TIN goes only into the vault (books.set_tin, books.set_w9); never repeat one anywhere (the parties-and-tins section). diff --git a/crates/ledger-mcp/handbook/tracing-figures.md b/crates/ledger-mcp/handbook/tracing-figures.md index 4b01bcba..21e9a1bb 100644 --- a/crates/ledger-mcp/handbook/tracing-figures.md +++ b/crates/ledger-mcp/handbook/tracing-figures.md @@ -3,6 +3,7 @@ - Reports are pure functions of the posted entries. When the human questions a figure, trace it to its entries with the tools: the report (books.trial_balance, books.profit_and_loss, books.balance_sheet, books.cash_flow), then books.search_entries and books.get_entry for the entries behind it, and books.show to put them on the human's screen. - A report without dates covers the fiscal year to date, everywhere (the report tools, the export, books.show and the viewer); one with only an end date covers that date's fiscal year to it. {period_rule} The IIF is never a period: every posted entry from the first through its as_of. Every result names the dates it covers: say them when you quote a figure, and pass dates whenever the human means another period. - A cash flow line names its entry (books.cash_flow: each line's entry, kind and accounts). An expense a member paid personally (or equipment a lender paid for) is cash borrowed and spent on its date: a financing line and an operating (or investing) line, each with on_behalf, the part no bank account moved; the reimbursement is a repayment. A noncash disclosure is an entry that moved no cash at all (property contributed, debt converted to capital). A warning names an entry whose later payment or collection the books can't classify, with the fix. A role refusal names the setting to change. +- books.journal_history shows every line of the journal. A line it says did not count belongs to a call that failed, never finished or is still running: nothing it wrote is in the books, and the ids it took were handed out again, so never trace a figure to such a line. - Never guess, and never look for the books' files: the tools are the evidence. - books.verify checks the books end to end when a number looks wrong or a human asks whether the books are intact. - A member's odd cent: closes, the statement of members' equity, the K-1 worksheet and the viewer split earnings among the members one running way. Each close gives a member their share of everything closed to the same members and shares so far, to the cent (odd cents by largest remainder, ties to the member listed first when that count began), less what earlier closes gave them, so no member is ever a cent from their exact share. Earnings not yet closed are split the way their close will split them, so a member's capital on a day never changes when its month is closed. books.close_period's members shows each member's part, running total and exact share; the first close that posts may carry a one-time correction of the rounding left by closes made under an earlier rule (a cent or so per member; each member's this_close shows it) (books.list_periods' close_rule names each close's rule). A change of members or shares starts a new count. diff --git a/crates/ledger-mcp/src/tools/journal.rs b/crates/ledger-mcp/src/tools/journal.rs index fe40299f..bac3cb7e 100644 --- a/crates/ledger-mcp/src/tools/journal.rs +++ b/crates/ledger-mcp/src/tools/journal.rs @@ -90,7 +90,7 @@ impl BooksServer { #[tool( name = "books.journal_history", title = "Journal history", - description = "The journal in words, in order: each line's seq, time, type and a sentence saying what it did, to what, and the entry it belongs to. Filter by after_seq, types (an exact type like entry.posted, or a group like entry.) and subject (entry:12, invoice:3, bill:3, account:10, party:5, asset:2). The way to trace a figure back to what produced it, and the only way to see what the journal holds. Read-only; at most 200 lines a call.", + description = "The journal in words, in order: each line's seq, time, type and a sentence saying what it did, to what, and the entry it belongs to. Filter by after_seq, types (an exact type like entry.posted, or a group like entry.) and subject (entry:12, invoice:3, bill:3, account:10, party:5, asset:2). The way to trace a figure back to what produced it, and the only way to see what the journal holds. A line of a call that failed or never finished is listed and says it did not count. Read-only; at most 200 lines a call.", annotations(read_only_hint = true, open_world_hint = false) )] pub(super) async fn journal_history( diff --git a/crates/ledger-store/tests/calls.rs b/crates/ledger-store/tests/calls.rs index 2a8a0701..3989ec75 100644 --- a/crates/ledger-store/tests/calls.rs +++ b/crates/ledger-store/tests/calls.rs @@ -773,7 +773,9 @@ fn books_the_version_before_call_transactions_wrote_open_and_report_the_same_fig assert_eq!(after, expected["snapshot"]["Ok"]); s.begin_call(id("key-old-books-2")).unwrap(); // January is closed in these books: the first framed call is a March one. - let e = s.create_entry(d(2026, 3, 1), "A first framed call").unwrap(); + let e = s + .create_entry(d(2026, 3, 1), "A first framed call") + .unwrap(); let bank = s.ledger().chart().find_by_code("1000").unwrap().id; let capital = s.ledger().chart().find_by_code("3000").unwrap().id; s.add_line(e, bank, Side::Debit, money(10)).unwrap(); diff --git a/docs/mcp-interface.md b/docs/mcp-interface.md index d2a4f266..65c5ab81 100644 --- a/docs/mcp-interface.md +++ b/docs/mcp-interface.md @@ -634,6 +634,41 @@ count. Every write call is one transaction: its lines commit together with its closing line or not at all, and after a crash a call without its closing line is not treated as done (WB-format-8 to WB-format-10). +What the books keep of a call, and what a repeat is told: + +- A call that wrote journal lines is framed by `call.begun` and + `call.closed`; its closing line keeps the answer (at most 4096 bytes). A + repeat of it returns that answer byte for byte. If the answer was longer, + the closing line keeps its SHA-256 and length instead, and a repeat is + told in words that the call was done, with the journal lines it wrote + (`books.journal_history` with `after_seq` lists them), and nothing is + done again. +- A call that wrote no journal line leaves no line at all. Its key and + answer are kept in memory for the life of the server: a repeat within the + session gets the same answer, and after a restart a repeat simply runs + again, which is harmless because it wrote nothing (`books.back_up_now`, + `books.begin_upload`). +- "The same arguments" is a keyed digest of them, tax ids included, under a + secret of the books' own that is never journaled: two requests that differ + only in a tax id are two requests, and the same key with the other tax id + is refused. +- A write that fails after it wrote lines is on the record + (`books.journal_history` lists its lines and says of each that it did not + count); ids it took are handed out again to the next call, so a reader + that takes the journal raw would pin its dead lines on whatever takes the + id next: every reader applies the frame rule, and the journal in words + (`books.journal_history`) and the viewer's journal page show every line and + say of the ones that did not count that they did not. +- A write to the tax-id vault is part of the call: it is final only when the + call commits, so a failed or cut call never replaces or destroys a tax id. +- A request that arrives while a call that has written a line is still + open waits for its closing line: no read shows what a call did before the + call committed. +- If a call's closing line is saved but the books' working copy cannot be + brought up to it, the call is told so in words: it was completed and + counts, the books server stopped to protect the books, and sending the call + again with the same key answers what it answered and changes nothing. + Books an older version wrote take no write at all until the owner gives the format upgrade its go-ahead (D-89, WB-format-11): every write is refused, before it runs, with `format_upgrade_pending` and the words "nothing can be diff --git a/docs/receipt-store.md b/docs/receipt-store.md index d9ce4134..0ef2c7fe 100644 --- a/docs/receipt-store.md +++ b/docs/receipt-store.md @@ -199,14 +199,24 @@ a backup is then proven where it lands, by a drill (docs/mcp-interface.md, - **A tool call is a frame, not a record** (plan P15 2a, D-88, feature `call_transactions`): a call that writes lines is framed by `call.begun {tool, token, key, args}` before its first line and - `call.closed {tool, token, key, args, outcome, first_seq?, last_seq?, - answer?, error?}` after its last. The lines between count only when - `outcome` is `ok` (then `answer` is the text of the answer given, kept - so a repeat of `key` returns it); `failed` and `unfinished` (written by - the open that finds a call that never closed) say the lines in the frame - never count, in any replay. A call that wrote no line is a closing line - alone. A line outside a frame applies as ever, so every journal written - before the feature replays as it was. `store.created` carries + `call.closed {tool, token, key, args, outcome, first_seq, last_seq, + answer | answer_sha256 + answer_bytes | error}` after its last. `args` + is an HMAC-SHA256 of the call's arguments under the books' own secret + (`keys/calls.key`), never a plain hash (a tax id would be guessable). The + lines between count only when `outcome` is `ok` (then `answer` is the + text of the answer given, kept so a repeat of `key` returns it, when at + most 4096 bytes; above that `answer_sha256` and `answer_bytes` stand in + its place); `failed` and `unfinished` (written by the open that finds a + call that never closed) say the lines in the frame never count, in any + replay. A call that wrote no line has no frame and no closing line (its + key and answer are kept in memory for the life of the server only). A + line outside a frame applies as ever, so every journal written before + the feature replays as it was. **Every reader that derives a fact reads + the committed journal** (`calls::committed`: the lines outside a frame and + those of `ok` frames), because ids are handed out again after a failed + call and a raw reader would pin the dead lines on whatever takes the id + next; a reader that shows history shows every line and says of the dead + ones that they did not count (`calls::standings`). `store.created` carries `books_id` (the books' own unique id) in books made since the feature; older books are given one in the `journal.format_set` of their upgrade. Neither frame line moves the audit's figure head. diff --git a/docs/spec/claims/format.md b/docs/spec/claims/format.md index 8bb193a3..23405935 100644 --- a/docs/spec/claims/format.md +++ b/docs/spec/claims/format.md @@ -222,39 +222,62 @@ others are there; none is deleted for being stale. **WB-format-8 Every write a tool makes is one transaction in the journal.** (The owner, 2026-11-20, D-88: "Writes have to be TRANSACTIONAL ALWAYS! You -can record a failed transaction.") A tool call that writes frames its journal -lines: `call.begun { tool, token, key, args }` just before its first line, and -`call.closed { tool, token, key, args, outcome, first_seq, last_seq, answer | -error }` when it is over, `outcome` being `ok` (the answer given is `answer`, -kept as text so a repeat returns it byte for byte), `failed`, or `unfinished`. -A call that wrote no line is only its closing line. The lines between a begin -and its close count only when the close says `ok`: that is how a reader tells -a complete call from an incomplete one. Every replay (opening the books, the -viewer, verify, rebuild, the projection a restart catches up) goes through -one rule (`CallGate`): a line outside a frame applies at once (every line -before the books declared `call_transactions`, and the owner's own acts: the -format declaration, a repaired tail); a line inside a frame waits, and is +can record a failed transaction.") A tool call that writes journal lines +frames them: `call.begun { tool, token, key, args }` just before its first +line, and `call.closed { tool, token, key, args, outcome, first_seq, +last_seq, answer | answer_sha256 + answer_bytes | error }` when it is over, +`outcome` being `ok` (the answer given is `answer`, kept as text so a repeat +returns it byte for byte, when it is at most 4096 bytes; above that the line +keeps `answer_sha256`, the SHA-256 of the answer, and `answer_bytes`, its +length, so every closing line is bounded), `failed` (`error` says how), or +`unfinished` (written by the next open of books whose last call never +closed). `args` is a keyed digest of the call's arguments (WB-format-9). A +call that wrote no journal line has no frame and no closing line: there is +nothing to frame, and nothing it did can be half done. The lines between a +begin and its close count only when the close says `ok`: that is how a reader +tells a complete call from an incomplete one. Every replay (opening the +books, the viewer, verify, rebuild, the projection a restart catches up) goes +through one rule (`CallGate`): a line outside a frame applies at once (every +line before the books declared `call_transactions`, and the owner's own acts: +the format declaration, a repaired tail); a line inside a frame waits, and is applied with its closing line when that says `ok`, and never when it says -`failed` or `unfinished` or when no closing line follows. So no state is built -from half a call, and a replay of any prefix that ends inside a call equals the -replay of the prefix before it. A close must name the frame it ends (its -`first_seq` is the begin line's, its `last_seq` the line before it); a frame -that begins inside another, a close with no frame, or a close that does not -match is a corrupt journal. The projection keeps a call's changes in one -SQLite transaction, released only after the `ok` closing line is on disk. When -the books are opened and the journal's last call never closed, its lines are -not applied, it is closed `unfinished` before anything else is written, and a -projection that holds its lines is rebuilt. The envelope `{seq, ts, type, -payload, prev}` is untouched: the feature adds two line types -(`call_transactions`, WB-format-2) and nothing else. Calls take turns: the -server runs one write call at a time, so a call's lines are one run in the -journal. `books.import_bank_csv` is one transaction like every other write -(plan P15 6a). The reader's view: a viewer reads a call's lines only once its -closing line is read; a reader of the memory sees a call's lines for the -moment between its tool finishing and its closing line (never after a -restart). -*Enforced:* `ledger_store::calls` (`CallGate`, `gate_all`, `closed_of`, `begun_of`, `Store::begin_call`, `Store::close_call`), `Store::open`, `Store::verify`, `Store::rebuild`, `Snapshot::refresh`, `format::CALL_TRANSACTIONS`, ledger-mcp `SharedStore::write_turn`. -*Checked:* `ledger-store` `tests/calls.rs` (`a_call_is_framed_and_its_answer_kept_by_key`, `a_call_that_wrote_nothing_is_only_a_closing_line`, `a_crash_at_each_point_of_a_call_leaves_the_whole_call_or_none_of_it`, `a_replay_of_any_prefix_inside_a_call_is_the_replay_of_the_prefix_before_it`, `a_viewer_applies_a_call_only_when_it_closes`, `a_frame_that_does_not_close_what_it_follows_is_corrupt`, `a_call_cannot_begin_inside_another_or_after_a_failed_close`), the unit test `call_transactions_is_its_own_feature` in `format.rs`, `tests/format.rs` (`every_event_the_store_replays_passes_the_gate`); `ledger-cli` `tests/call_transactions.rs` (`a_call_is_one_frame_in_the_journal_closed_with_its_answer`, `the_import_is_one_transaction`). +`failed` or `unfinished` or when no closing line follows. So no state is +built from half a call, and a replay of any prefix that ends inside a call +equals the replay of the prefix before it. A close must name the frame it +ends (its `first_seq` is the begin line's, its `last_seq` the line before +it); a frame that begins inside another, a close with no frame, or a close +that does not match is a corrupt journal. The projection keeps a call's +changes in one SQLite transaction, released only after the `ok` closing line +is on disk. When the books are opened and the journal's last call never +closed, its lines are not applied, it is closed `unfinished` before anything +else is written, and a projection that holds its lines is rebuilt. The +envelope `{seq, ts, type, payload, prev}` is untouched: the feature adds two +line types (`call_transactions`, WB-format-2) and nothing else. Calls take +turns: the server runs one write call at a time, so a call's lines are one +run in the journal. `books.import_bank_csv` is one transaction like every +other write (plan P15 6a). + +**Every reader of the journal applies the frame rule, because ids are reused +after a failed call.** A failed call's entry, account, party and document ids +were never taken (nothing it wrote counted), so the next call hands them out +again; a reader that took the raw lines would pin the dead lines of a failed +call on whatever took the id next (a failed `books.create_bill` for entry 42, +then a manual entry 42, would read as a "Bill"). So a reader that derives a +fact (an entry's origin and events, an asset's trail, a party's events, an +attention item, a package, what adopting books would keep) reads the +committed journal (`committed`: the lines outside any call and those of calls +that closed `ok`, the frame lines left out) and never the raw one; a reader +that shows history (the viewer's journal page, `books.journal_history`) +shows every line and says in words of each line of a call that failed, never +finished or is still running that it did not count (`Standing`, `standings`). +Backups and restores copy the journal's bytes whole and read none of its +facts. The reader's view of a running call: a viewer reads a call's lines only +once its closing line is read; a request on the server that arrives between a +call's tool finishing and its closing line, when the call has written a line, +waits for the close, so no read shows what a call did before the call +committed. +*Enforced:* `ledger_store::calls` (`CallGate`, `gate_all`, `standings`, `committed`, `Standing`, `closed_of`, `begun_of`, `ANSWER_CAP`, `Store::begin_call`, `Store::close_call`), `Store::open`, `Store::verify`, `Store::rebuild`, `Snapshot::refresh`, `Snapshot::committed_journal`, `Snapshot::journal_standings`, `Store::journal_history`, `history_standing`, ledger-package `PackageBooks`, ledger-gui `Books::build`, `adopt`, `format::CALL_TRANSACTIONS`, ledger-mcp `SharedStore::write_turn`, `BooksServer::lock`. +*Checked:* `ledger-store` `tests/calls.rs` (`a_call_is_framed_and_its_answer_kept_by_key`, `a_call_that_wrote_nothing_leaves_no_line_and_is_remembered_for_the_session`, `a_long_answer_is_kept_as_its_hash_and_a_repeat_is_told_in_words_what_was_done`, `the_committed_journal_leaves_out_the_lines_of_a_call_that_failed`, `a_crash_at_each_point_of_a_call_leaves_the_whole_call_or_none_of_it`, `a_replay_of_any_prefix_inside_a_call_is_the_replay_of_the_prefix_before_it`, `a_viewer_applies_a_call_only_when_it_closes`, `a_frame_that_does_not_close_what_it_follows_is_corrupt`, `a_call_cannot_begin_inside_another_or_after_a_failed_close`, `a_call_whose_begin_line_the_projection_refuses_still_closes_its_frame`, `books_the_version_before_call_transactions_wrote_open_and_report_the_same_figures`), `tests/store.rs` (`books_written_under_older_rules_still_open`, `books_an_earlier_version_wrote_open_to_its_figures`), the unit test `call_transactions_is_its_own_feature` in `format.rs`, `tests/format.rs` (`every_event_the_store_replays_passes_the_gate`); `ledger-gui` `tests/view_model.rs` (`a_failed_calls_lines_are_not_facts_when_its_ids_are_used_again`: the viewer's books, the feed attention reads, and the history after a failed call and an id handed out again); `ledger-cli` `tests/call_transactions.rs` (`a_call_is_one_frame_in_the_journal_closed_with_its_answer`, `the_import_is_one_transaction`, `a_call_that_wrote_lines_and_then_failed_leaves_the_books_and_its_key_as_they_were`). **WB-format-9 Every write call carries a request key, and a repeat of it writes nothing.** Every tool that can change the books (no `readOnlyHint`; @@ -269,14 +292,34 @@ call committed, with the same tool and arguments, returns that call's answer as it was given, writes nothing, and is recorded in the access log as `repeat`; with other arguments or another tool it is refused in words as a misuse of the key, and nothing is changed. A key is the token's own: two -tokens with one key are two keys. The key table is rebuilt at every open from -the `ok` closing lines alone. A repeat that arrives while its original is -still running waits for it (calls take turns) and gets its answer. An answer -is kept as given: no tool answer holds a full TIN, and the three tools that -can are no transaction; an error text that holds one is kept masked -(BS-partner-2: no journal line holds one). -*Enforced:* ledger-mcp `calls::is_write_call`, `calls::key_problem`, `calls::begin`, `calls::close`, `calls::add_key_to_schema`, `Store::recorded_call`, `Keys`. -*Checked:* `ledger-cli` `tests/call_transactions.rs` (`a_repeat_of_a_key_returns_the_first_answer_and_writes_nothing`, `the_same_key_for_another_request_is_refused_in_words`, `a_write_without_a_usable_key_is_not_run`, `every_tool_that_can_write_asks_for_a_key_and_no_other_does`); `ledger-store` `tests/calls.rs` (`a_call_is_framed_and_its_answer_kept_by_key`). +tokens with one key are two keys. "The same arguments" is a keyed digest +(`args_mac`): HMAC-SHA256 over the arguments' canonical JSON, unmasked, under +a secret of the books' own (`keys/calls.key`, 32 random bytes, made on first +need, mode 0600, never journaled, logged or answered), so two requests that +differ only in a tax id are two requests, and nothing journaled lets anyone +recover or test a guess of a tax id (a plain hash of nine digits would be +guessable). The key file is part of the books' keys folder and travels with +its backups; books restored without it refuse a repeat of an older key as a +misuse of the key (nothing is changed), never as a repeat. The key table is +rebuilt at every open from the `ok` closing lines alone and holds one small +entry per committed call, no answers: a repeat reads its answer from the +closing line. A call that answered `ok` but wrote no journal line leaves no +line, so its key and answer are kept in memory for the life of the server +only, in a table bounded at 512 calls and 2 MiB of answers, oldest first out +(an answer above 4096 bytes is not kept); a repeat within the session gets +the same answer, and after a restart a repeat simply runs again, which is +harmless because it wrote nothing (`books.back_up_now` and `books.begin_upload` +are such calls: a second backup or a second empty upload slot is no harm). +A call that wrote lines and whose answer was above 4096 bytes is repeated in +words: it says the call was done, with its journal lines, the answer's +length and SHA-256, that the answer was too long to keep, and writes +nothing. A repeat that arrives while its original is still running waits for +it (calls take turns) and gets its answer. An answer is kept as given: no +tool answer holds a full TIN, and the three tools that can are no +transaction; an error text that holds one is kept masked (BS-partner-2: no +journal line holds one). +*Enforced:* ledger-mcp `calls::is_write_call`, `calls::key_problem`, `calls::begin`, `calls::close`, `calls::add_key_to_schema`, `Store::recorded_call`, `Keys`, `Replay`, `args_mac`, `Store::args_mac`, `hmac_sha256_hex`, `ANSWER_CAP`, `SESSION_KEYS_MAX`. +*Checked:* `ledger-cli` `tests/call_transactions.rs` (`a_repeat_of_a_key_returns_the_first_answer_and_writes_nothing`, `the_same_key_for_another_request_is_refused_in_words`, `a_write_without_a_usable_key_is_not_run`, `every_tool_that_can_write_asks_for_a_key_and_no_other_does`, `the_same_key_under_two_tokens_is_two_calls`, `a_repeat_arriving_while_its_original_runs_gets_its_answer_and_changes_nothing`, `a_repeat_of_a_call_whose_answer_was_too_long_is_told_it_was_done`, `a_call_that_wrote_nothing_leaves_no_line_and_is_answered_again_only_within_the_session`, `a_key_reused_for_another_tax_id_is_refused_not_repeated`); `ledger-store` `tests/calls.rs` (`a_call_is_framed_and_its_answer_kept_by_key`, `the_sessions_key_table_is_bounded_in_count_and_in_bytes`, `a_long_answer_is_kept_as_its_hash_and_a_repeat_is_told_in_words_what_was_done`) and the unit tests `hmac_sha256_matches_rfc_4231` and `args_mac_tells_tax_ids_apart_and_holds_none` in `calls.rs`. **WB-format-10 A failed write is on the record, and builds nothing.** A call that answers with an error, is stopped by a close, or fails any other way @@ -285,11 +328,22 @@ its lines are never applied, the projection's changes are rolled back and the live ledger is rebuilt from the journal without them; if it had written none, the access log has it (as every call has) and the journal has nothing. A failed call leaves its key unused: nothing happened under it, so the corrected -call may use it. A call whose closing line cannot be written has not +call may use it. Nothing a call writes outside the journal is final before +the call commits: the tax-id vault's writes (`books.set_tin`, `books.set_w9`, +`books.purge_tin`) are staged under names no reader opens and made final when +the call's closing line is written, or dropped (and a purge put back) when +the call fails; a crash between the closing line and that settling is +finished at the next start by what the journal says of the call, so a failed +or cut call never replaces or destroys a record (`ledger_vault::settle`, +`pending_tags`). A call whose closing line cannot be written has not committed; the store takes no further write, and the books server stops, as -it does when an access record cannot be written. -*Enforced:* `Store::close_call`, ledger-mcp `calls::answered_ok`, `calls::close`. -*Checked:* `ledger-store` `tests/calls.rs` (`a_failed_call_is_on_the_record_and_builds_nothing`, `a_call_that_wrote_nothing_is_only_a_closing_line`); `ledger-cli` `tests/call_transactions.rs` (`a_failed_write_leaves_the_books_and_its_key_as_they_were`). +it does when an access record cannot be written. A call whose closing line +*is* on disk but whose projection cannot be brought up to it has committed: +the store heals from the journal where it can, and where it cannot says so +(`StoreError::CallCommitted`: the call was completed and counts, do not do +it again), stops taking writes, and is rebuilt at the next open. +*Enforced:* `Store::close_call`, `StoreError::CallCommitted`, ledger-mcp `calls::answered_ok`, `calls::close`, `calls::recover_vault`, `calls::put_tin`, `calls::purge_records`, `calls::settle_vault`, `ledger_vault::stage_tin`, `ledger_vault::stage_w9`, `ledger_vault::stage_purge`, `ledger_vault::settle`, `ledger_vault::pending_tags`. +*Checked:* `ledger-store` `tests/calls.rs` (`a_failed_call_is_on_the_record_and_builds_nothing`, `a_call_that_wrote_nothing_leaves_no_line_and_is_remembered_for_the_session`, `a_closing_line_on_disk_but_sqlite_failing_is_a_call_that_counts`); `ledger-vault` `tests/vault.rs` (`a_staged_record_is_read_by_no_one_until_its_call_commits`, `a_call_that_did_not_commit_leaves_the_old_record_whole`, `a_purge_is_final_only_when_its_call_commits`); `ledger-cli` `tests/call_transactions.rs` (`a_failed_write_leaves_the_books_and_its_key_as_they_were`, `a_call_that_wrote_lines_and_then_failed_leaves_the_books_and_its_key_as_they_were`, `a_crash_with_the_ok_close_on_disk_but_sqlite_not_committed_leaves_the_call_done_once`, `a_set_tin_that_fails_leaves_the_vault_as_it_was`, `a_crash_between_the_commit_and_the_vault_settling_is_finished_at_the_next_start`). **WB-format-11 Books that have not declared `call_transactions` take no write.** (The owner, 2026-11-20, D-89.) This replaces WB-format-3's "everything