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",