Merge branch 't3/transactional-mcp-writes': every write through the tools is one transaction, exactly once (P15 T1, D-88, D-89)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 10:40:34 -07:00
commit 38647e2143
61 files changed
+5801 -339

No files matched your search

+2
View File
@@ -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",
File diff suppressed because it is too large. Load diff
+39 -4
View File
@@ -43,6 +43,9 @@ pub struct Described {
pub subjects: Vec<String>,
/// The entry it belongs to, if it is about one.
pub entry_id: Option<u64>,
/// 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).
@@ -204,6 +207,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)
@@ -236,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<Described>, 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<Described>, bool) {
let wanted = |l: &JournalLine| {
l.seq > filter.after_seq
&& (filter.types.is_empty()
@@ -259,12 +288,17 @@ pub fn history(lines: &[JournalLine], filter: &HistoryFilter) -> (Vec<Described>
};
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)
}
@@ -290,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()
+22 -2
View File
@@ -106,6 +106,17 @@ 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),
/// 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),
@@ -185,13 +196,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}"
)
}
+56
View File
@@ -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
+1
View File
@@ -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,
+21 -2
View File
@@ -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)]
+38 -4
View File
@@ -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,17 +246,39 @@ impl Snapshot {
&self.format
}
/// The books' id, if they have one ([`crate::calls::books_id_of`]).
pub fn books_id(&self) -> Option<String> {
crate::calls::books_id_of(&self.lines)
}
/// The data directory.
pub fn data_dir(&self) -> &Path {
&self.data_dir
}
/// 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<Vec<crate::calls::Standing>, 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<Vec<JournalLine>, 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
+117 -18
View File
@@ -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<calls::ActiveCall>,
/// 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<String>,
/// 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<u64> {
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<Currency> {
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<JournalLine, StoreError> {
// 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,22 @@ 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)?;
}
// 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(())
}
@@ -7348,6 +7437,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 +8487,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 +9485,10 @@ fn file_name_of(path: &Path) -> String {
pub(crate) fn fresh_projection(lines: &[JournalLine]) -> Result<Connection, StoreError> {
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)
}
+797
View File
@@ -0,0 +1,797 @@
//! 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::{
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;
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),
}
}
/// What the store kept of a call, if anything.
fn kept(s: &Store, token: &str, key: &str) -> Option<Recorded> {
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::JournalLine> {
ledger_store::journal::read_and_verify_journal(&dir.join(JOURNAL_FILE)).unwrap()
}
fn types_of(dir: &Path) -> Vec<String> {
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 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!(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!(
answer_of(&kept(&s, "token-1", "key-aaaa-1").unwrap()),
r#"{"entry_id":1}"#
);
s.verify().unwrap();
}
#[test]
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();
// 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);
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]
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!(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");
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();
}
type Step = Box<dyn Fn(&mut Store)>;
/// A call of every kind of step, by how far it got.
fn steps() -> Vec<Step> {
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!(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.
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<usize> = 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(_))
));
}
#[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!(kept(&s, "token-1", "key-heal-0001").is_some());
drop(s);
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();
}
/// 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();
}
}
}
@@ -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
@@ -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);
}
@@ -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
}
}
@@ -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"}
+10 -2
View File
@@ -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();
+5 -1
View File
@@ -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(),
+59
View File
@@ -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);