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:
commit
38647e2143
61 files changed
+5801
-339
No files matched your search
@@ -123,11 +123,11 @@ fn journal_history_traces_what_the_books_did() {
|
||||
assert_eq!(next["lines"][0]["seq"].as_u64().unwrap(), after + 1);
|
||||
|
||||
// A bad subject is refused with the shapes; the journal is unchanged.
|
||||
let before = books.journal();
|
||||
let before = books.journal_raw();
|
||||
let err =
|
||||
answer_of(&w.call("books.journal_history", json!({"subject": "nonsense"}))).unwrap_err();
|
||||
assert!(err.contains("entry:12"), "{err}");
|
||||
assert_eq!(books.journal(), before);
|
||||
assert_eq!(books.journal_raw(), before);
|
||||
// It is a read: no head in the envelope.
|
||||
assert!(all.get("head").is_none(), "{all}");
|
||||
}
|
||||
@@ -471,11 +471,18 @@ fn a_mutating_call_answers_with_the_head_and_a_refusal_names_its_remedy() {
|
||||
.unwrap();
|
||||
let head = added["head"]["seq"].as_u64().unwrap();
|
||||
let start = answer_of(&w.call("books.start", json!({}))).unwrap();
|
||||
// The head a write call answers is where its own lines end; its closing
|
||||
// line (which holds this very answer) follows at once, and is the
|
||||
// journal's head from then on (WB-format-8).
|
||||
assert_eq!(
|
||||
start["head"]["seq"],
|
||||
json!(head),
|
||||
"the head the call answered is the journal's"
|
||||
json!(head + 1),
|
||||
"the journal ends one line past the head the call answered: its closing line"
|
||||
);
|
||||
let journal = String::from_utf8(books.journal_raw()).unwrap();
|
||||
let last: serde_json::Value = serde_json::from_str(journal.lines().last().unwrap()).unwrap();
|
||||
assert_eq!(last["type"], "call.closed");
|
||||
assert_eq!(last["payload"]["last_seq"], json!(head));
|
||||
assert!(!added["next_steps"].as_array().unwrap().is_empty());
|
||||
// A confirm with no preview is refused as stale_preview, naming the
|
||||
// tool that previews.
|
||||
|
||||
@@ -157,13 +157,17 @@ fn audit_is_deterministic() {
|
||||
);
|
||||
let run = first["run"].clone();
|
||||
assert_eq!(run["at_current_head"], true);
|
||||
let journal = books.journal();
|
||||
let journal = books.journal_raw();
|
||||
let again = audit(&mut w, "full", "2026-03-31");
|
||||
assert_eq!(again["status"], "already_run");
|
||||
assert_eq!(again["run"]["id"], run["id"]);
|
||||
assert_eq!(again["run"]["findings_sha256"], run["findings_sha256"]);
|
||||
assert_eq!(again["findings"], first["findings"]);
|
||||
assert_eq!(books.journal(), journal, "asking again journals nothing");
|
||||
assert_eq!(
|
||||
books.journal_raw(),
|
||||
journal,
|
||||
"asking again journals nothing"
|
||||
);
|
||||
// The workpaper is the same twice, JSON and PDF.
|
||||
let id = run["id"].clone();
|
||||
let one = answer_of(&w.call("books.workpaper", json!({"id": id}))).unwrap();
|
||||
@@ -406,7 +410,7 @@ fn audits_wait_for_the_upgrade() {
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(preview["status"], "preview");
|
||||
let journal = books.journal();
|
||||
let journal = books.journal_raw();
|
||||
for (tool, args) in [
|
||||
(
|
||||
"books.audit",
|
||||
@@ -425,7 +429,7 @@ fn audits_wait_for_the_upgrade() {
|
||||
let e = answer_of(&w.call(tool, args)).unwrap_err();
|
||||
assert!(e.starts_with("format_upgrade_pending"), "{tool}: {e}");
|
||||
}
|
||||
assert_eq!(books.journal(), journal, "a refusal journals nothing");
|
||||
assert_eq!(books.journal_raw(), journal, "a refusal journals nothing");
|
||||
// The package is held up only by what it always was: an open draft.
|
||||
let args = json!({"as_of": "2026-01-31", "cash_accounts": ["1000"],
|
||||
"include_receipts": false, "include_tins": false});
|
||||
|
||||
@@ -248,7 +248,13 @@ async fn call(c: &Client, tool: &str, mut args: Value) -> Result<Value, String>
|
||||
}
|
||||
|
||||
async fn call_once(c: &Client, tool: &str, args: Value) -> Result<Value, String> {
|
||||
let args = args.as_object().cloned().unwrap_or_default();
|
||||
let mut args = args.as_object().cloned().unwrap_or_default();
|
||||
// The key every write call carries (D-88).
|
||||
static NEXT_KEY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
args.entry("request_key").or_insert_with(|| {
|
||||
let n = NEXT_KEY.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
json!(format!("backups-key-{}-{n}", std::process::id()))
|
||||
});
|
||||
let r = tokio::time::timeout(
|
||||
Duration::from_secs(60),
|
||||
c.call_tool(CallToolRequestParams::new(tool.to_string()).with_arguments(args)),
|
||||
|
||||
@@ -1103,7 +1103,8 @@ fn a_call_whose_answer_was_never_read_is_on_record_as_having_run() {
|
||||
let mut raw = raw::Raw::connect(&home, A);
|
||||
let body = json!({"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": {
|
||||
"name": "books.draft_entry",
|
||||
"arguments": {"date": "2026-03-01", "description": "unread"}}})
|
||||
"arguments": {"date": "2026-03-01", "description": "unread",
|
||||
"request_key": common::fresh_request_key()}}})
|
||||
.to_string();
|
||||
raw.start(
|
||||
"POST",
|
||||
@@ -1541,7 +1542,8 @@ fn a_stalled_mcp_body_cannot_hold_a_close_and_nothing_of_it_is_journaled() {
|
||||
let mut raw = raw::Raw::connect(&home, A);
|
||||
let body = json!({"jsonrpc": "2.0", "id": 9, "method": "tools/call", "params": {
|
||||
"name": "books.draft_entry",
|
||||
"arguments": {"date": "2026-03-01", "description": "never finished"}}})
|
||||
"arguments": {"date": "2026-03-01", "description": "never finished",
|
||||
"request_key": common::fresh_request_key()}}})
|
||||
.to_string();
|
||||
raw.start_inside(
|
||||
"POST",
|
||||
@@ -1665,7 +1667,8 @@ fn a_running_call_is_never_cut_when_the_grace_runs_out() {
|
||||
);
|
||||
let mut raw = raw::Raw::connect(&home, A);
|
||||
let body = json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {
|
||||
"name": "books.attach_receipt", "arguments": {"upload_id": up}}})
|
||||
"name": "books.attach_receipt",
|
||||
"arguments": {"upload_id": up, "request_key": common::fresh_request_key()}}})
|
||||
.to_string();
|
||||
raw.start(
|
||||
"POST",
|
||||
@@ -2191,7 +2194,8 @@ fn the_servers_own_close_cuts_stalled_requests_and_exits_zero_in_time() {
|
||||
let mut raw_call = raw::Raw::connect(&home, B);
|
||||
let body = json!({"jsonrpc": "2.0", "id": 9, "method": "tools/call", "params": {
|
||||
"name": "books.draft_entry",
|
||||
"arguments": {"date": "2026-03-01", "description": "never finished"}}})
|
||||
"arguments": {"date": "2026-03-01", "description": "never finished",
|
||||
"request_key": common::fresh_request_key()}}})
|
||||
.to_string();
|
||||
raw_call.start_inside(
|
||||
"POST",
|
||||
@@ -2653,9 +2657,11 @@ fn a_close_that_stops_git_in_a_commit_or_a_push_leaves_no_lock_and_the_next_back
|
||||
#[cfg(unix)]
|
||||
fn call_unanswered(home: &Home, w: &Wire, id: u64, tool: &str, args: Value) -> raw::Raw {
|
||||
let mut raw = raw::Raw::connect(home, A);
|
||||
let body = json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {
|
||||
"name": tool, "arguments": args}})
|
||||
.to_string();
|
||||
let body = common::with_request_key(
|
||||
&json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {
|
||||
"name": tool, "arguments": args}})
|
||||
.to_string(),
|
||||
);
|
||||
raw.start(
|
||||
"POST",
|
||||
"mcp",
|
||||
|
||||
@@ -0,0 +1,863 @@
|
||||
//! Every write through the tools is one transaction that happens exactly
|
||||
//! once (plan P15 2a, D-88; WB-format-8 to WB-format-12), through the real
|
||||
//! server as an agent reaches it.
|
||||
//!
|
||||
//! The law: a repeat of a request key posts nothing and returns the first
|
||||
//! answer, across a restart; the same key for another request is refused;
|
||||
//! a write without a key is not run; a failed write leaves its key free
|
||||
//! and the books as they were; a call is framed in the journal and the
|
||||
//! import is one frame; every tool that can write asks for the key; a call
|
||||
//! that wrote lines and then failed rolls back, is on the record, and
|
||||
//! frees its key; a call that wrote nothing leaves no line at all; the
|
||||
//! same key under two tokens is two calls; a repeat that arrives while its
|
||||
//! original runs gets its answer; a crash after the closing line is on
|
||||
//! disk and before SQLite committed leaves the call done, once.
|
||||
|
||||
use common::{Books, Wire, answer_of};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
mod common;
|
||||
|
||||
/// The journal's lines, parsed.
|
||||
fn lines(books: &Books) -> Vec<Value> {
|
||||
String::from_utf8(books.journal_raw())
|
||||
.unwrap()
|
||||
.lines()
|
||||
.map(|l| serde_json::from_str(l).unwrap())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A `tools/call` with exactly these arguments, key or none.
|
||||
fn call_exactly(w: &mut Wire, tool: &str, args: Value) -> Value {
|
||||
let msg = json!({"jsonrpc": "2.0", "id": 4242, "method": "tools/call",
|
||||
"params": {"name": tool, "arguments": args}});
|
||||
w.send_exactly(&msg.to_string());
|
||||
w.recv(common::TIMEOUT).expect("an answer")
|
||||
}
|
||||
|
||||
fn draft(key: &str, what: &str) -> Value {
|
||||
json!({"date": "2026-03-01", "description": what, "no_party_reason": "test",
|
||||
"request_key": key})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_repeat_of_a_key_returns_the_first_answer_and_writes_nothing() {
|
||||
let books = Books::new("calls-repeat");
|
||||
let mut w = books.session("test");
|
||||
let first = call_exactly(
|
||||
&mut w,
|
||||
"books.draft_entry",
|
||||
draft("key-repeat-0001", "Rent"),
|
||||
);
|
||||
let first = answer_of(&first).unwrap();
|
||||
let after_first = books.journal_raw();
|
||||
// The answer was lost; the agent asks again, the same call, the same key.
|
||||
let again = call_exactly(
|
||||
&mut w,
|
||||
"books.draft_entry",
|
||||
draft("key-repeat-0001", "Rent"),
|
||||
);
|
||||
assert_eq!(answer_of(&again).unwrap(), first);
|
||||
assert_eq!(books.journal_raw(), after_first, "a repeat writes nothing");
|
||||
let drafts = answer_of(&w.call("books.list_drafts", json!({}))).unwrap();
|
||||
assert_eq!(
|
||||
drafts["drafts"].as_array().map(Vec::len),
|
||||
Some(1),
|
||||
"{drafts}"
|
||||
);
|
||||
// Across a restart: the key is in the journal.
|
||||
books.restart();
|
||||
let mut w = books.session("test");
|
||||
let later = call_exactly(
|
||||
&mut w,
|
||||
"books.draft_entry",
|
||||
draft("key-repeat-0001", "Rent"),
|
||||
);
|
||||
assert_eq!(answer_of(&later).unwrap(), first);
|
||||
assert_eq!(books.journal_raw(), after_first, "nor after a restart");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_key_for_another_request_is_refused_in_words() {
|
||||
let books = Books::new("calls-misuse");
|
||||
let mut w = books.session("test");
|
||||
answer_of(&call_exactly(
|
||||
&mut w,
|
||||
"books.draft_entry",
|
||||
draft("key-misuse-0001", "Rent"),
|
||||
))
|
||||
.unwrap();
|
||||
let before = books.journal_raw();
|
||||
let refused = call_exactly(
|
||||
&mut w,
|
||||
"books.draft_entry",
|
||||
draft("key-misuse-0001", "Something else"),
|
||||
);
|
||||
let why = answer_of(&refused).unwrap_err();
|
||||
assert!(why.contains("already used"), "{why}");
|
||||
assert!(why.contains("nothing was changed"), "{why}");
|
||||
assert_eq!(books.journal_raw(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_write_without_a_usable_key_is_not_run() {
|
||||
let books = Books::new("calls-nokey");
|
||||
let mut w = books.session("test");
|
||||
let before = books.journal_raw();
|
||||
let mut bare = draft("x", "No key");
|
||||
bare.as_object_mut().unwrap().remove("request_key");
|
||||
for (what, args) in [
|
||||
("no key", bare),
|
||||
("a short key", draft("short", "No key")),
|
||||
("a key that isn't text", {
|
||||
let mut a = draft("x", "No key");
|
||||
a["request_key"] = json!(12345678);
|
||||
a
|
||||
}),
|
||||
] {
|
||||
let r = call_exactly(&mut w, "books.draft_entry", args);
|
||||
let why = answer_of(&r).unwrap_err();
|
||||
assert!(why.contains("request_key"), "{what}: {why}");
|
||||
assert!(why.contains("not run"), "{what}: {why}");
|
||||
}
|
||||
assert_eq!(books.journal_raw(), before, "a refusal journals nothing");
|
||||
// A read needs none, and a preview (a confirmed tool, not confirmed)
|
||||
// writes nothing and needs none.
|
||||
answer_of(&call_exactly(&mut w, "books.chart", json!({}))).unwrap();
|
||||
let r = call_exactly(&mut w, "books.post_entry", json!({"entry_id": 1}));
|
||||
let text = serde_json::to_string(&r).unwrap();
|
||||
assert!(!text.contains("request_key"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_write_leaves_the_books_and_its_key_as_they_were() {
|
||||
let books = Books::new("calls-failed");
|
||||
let mut w = books.session("test");
|
||||
let before = books.journal_raw();
|
||||
let mut bad = draft("key-failed-0001", "Bad date");
|
||||
bad["date"] = json!("not a date");
|
||||
let failed = call_exactly(&mut w, "books.draft_entry", bad);
|
||||
assert!(answer_of(&failed).is_err(), "{failed}");
|
||||
assert_eq!(
|
||||
books.journal_raw(),
|
||||
before,
|
||||
"a call that wrote nothing leaves no line"
|
||||
);
|
||||
// Nothing happened under the key, so the corrected call may use it.
|
||||
let fixed = call_exactly(
|
||||
&mut w,
|
||||
"books.draft_entry",
|
||||
draft("key-failed-0001", "Good date"),
|
||||
);
|
||||
answer_of(&fixed).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_call_is_one_frame_in_the_journal_closed_with_its_answer() {
|
||||
let books = Books::new("calls-frame");
|
||||
let mut w = books.session("test");
|
||||
let before = lines(&books).len();
|
||||
let out = call_exactly(
|
||||
&mut w,
|
||||
"books.draft_entry",
|
||||
draft("key-frame-00001", "Framed"),
|
||||
);
|
||||
let answer = answer_of(&out).unwrap();
|
||||
let all = lines(&books);
|
||||
let call = &all[before..];
|
||||
assert_eq!(call.first().unwrap()["type"], "call.begun", "{call:?}");
|
||||
let closed = call.last().unwrap();
|
||||
assert_eq!(closed["type"], "call.closed");
|
||||
let p = &closed["payload"];
|
||||
assert_eq!(p["outcome"], "ok");
|
||||
assert_eq!(p["tool"], "books.draft_entry");
|
||||
assert_eq!(p["key"], "key-frame-00001");
|
||||
assert_eq!(p["first_seq"], call.first().unwrap()["seq"]);
|
||||
assert_eq!(
|
||||
p["last_seq"].as_u64().unwrap() + 1,
|
||||
closed["seq"].as_u64().unwrap()
|
||||
);
|
||||
// The answer kept is the answer given.
|
||||
let kept: Value = serde_json::from_str(p["answer"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(kept["structuredContent"], answer);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_import_is_one_transaction() {
|
||||
let books = Books::new("calls-import");
|
||||
let mut w = books.session("test");
|
||||
for (code, name, kind) in [("1000", "Bank", "asset"), ("6000", "Supplies", "expense")] {
|
||||
answer_of(&w.call(
|
||||
"books.add_account",
|
||||
json!({"code": code, "name": name, "account_type": kind}),
|
||||
))
|
||||
.unwrap();
|
||||
}
|
||||
let csv = b"Date,Description,Amount\n2026-01-02,Paper,-12.50\n2026-01-03,Pens,-3.25\n2026-01-04,Ink,-40.00\n";
|
||||
let up = w.upload(csv, "bank.csv", "text/csv", "import");
|
||||
let before = lines(&books).len();
|
||||
let args = json!({"upload_id": up, "bank_account_code": "1000",
|
||||
"default_offset_code": "6000", "request_key": "key-import-0001"});
|
||||
let out = answer_of(&call_exactly(&mut w, "books.import_bank_csv", args.clone())).unwrap();
|
||||
assert_eq!(out["count"], 3, "{out}");
|
||||
let all = lines(&books);
|
||||
let call = &all[before..];
|
||||
assert_eq!(call.first().unwrap()["type"], "call.begun");
|
||||
assert_eq!(call.last().unwrap()["type"], "call.closed");
|
||||
// Every row of the file is inside the one frame.
|
||||
let inside = call.iter().filter(|l| l["type"] == "entry.created").count();
|
||||
assert_eq!(inside, 3);
|
||||
assert_eq!(
|
||||
all.iter().filter(|l| l["type"] == "call.begun").count(),
|
||||
all.iter()
|
||||
.filter(|l| l["type"] == "call.closed" && l["payload"]["first_seq"].is_u64())
|
||||
.count(),
|
||||
"every frame that began closed"
|
||||
);
|
||||
// The answer lost: the repeat gives the first answer, imports nothing.
|
||||
let journal = books.journal_raw();
|
||||
let again = answer_of(&call_exactly(&mut w, "books.import_bank_csv", args)).unwrap();
|
||||
assert_eq!(again, out);
|
||||
assert_eq!(books.journal_raw(), journal);
|
||||
// A file the books refuse whole writes none of it.
|
||||
let bad = b"Date,Description,Amount\n2026-02-02,Ok row,-1.00\nnot a date,Bad row,-2.00\n";
|
||||
let up = w.upload(bad, "bad.csv", "text/csv", "import");
|
||||
let before = books.journal_raw();
|
||||
let refused = call_exactly(
|
||||
&mut w,
|
||||
"books.import_bank_csv",
|
||||
json!({"upload_id": up, "bank_account_code": "1000",
|
||||
"default_offset_code": "6000", "request_key": "key-import-0002"}),
|
||||
);
|
||||
assert!(answer_of(&refused).is_err(), "{refused}");
|
||||
assert_eq!(books.journal_raw(), before, "all or nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_tool_that_can_write_asks_for_a_key_and_no_other_does() {
|
||||
let books = Books::new("calls-schema");
|
||||
let mut w = books.session("test");
|
||||
let listed = w.rpc("tools/list", json!({}));
|
||||
let tools = listed["result"]["tools"].as_array().unwrap();
|
||||
let (mut asking, mut reading) = (0, 0);
|
||||
for t in tools {
|
||||
let name = t["name"].as_str().unwrap();
|
||||
// Three tools only read what is sealed (and may answer with a TIN):
|
||||
// annotated as writes, they are reads and take no key.
|
||||
let read_only = t["annotations"]["readOnlyHint"] == json!(true)
|
||||
|| [
|
||||
"books.vendor_1099",
|
||||
"books.get_w9",
|
||||
"books.export_cpa_package",
|
||||
]
|
||||
.contains(&name);
|
||||
let required = t["inputSchema"]["required"]
|
||||
.as_array()
|
||||
.is_some_and(|r| r.contains(&json!("request_key")));
|
||||
let property = t["inputSchema"]["properties"].get("request_key").is_some();
|
||||
if read_only {
|
||||
assert!(!required && !property, "{name} reads and asks for a key");
|
||||
reading += 1;
|
||||
} else {
|
||||
assert!(required && property, "{name} can write and asks for no key");
|
||||
asking += 1;
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
asking > 50 && reading > 20,
|
||||
"{asking} write, {reading} read"
|
||||
);
|
||||
}
|
||||
|
||||
/// The books' SQLite projection file.
|
||||
fn projection(books: &Books) -> std::path::PathBuf {
|
||||
std::fs::read_dir(books.dir())
|
||||
.unwrap()
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.find(|p| p.extension().is_some_and(|e| e == "db"))
|
||||
.expect("the projection file")
|
||||
}
|
||||
|
||||
/// A `books.add_account` request.
|
||||
fn account(key: &str) -> Value {
|
||||
json!({"code": "1000", "name": "Bank", "account_type": "asset", "request_key": key})
|
||||
}
|
||||
|
||||
/// The raw journal's line types, in order.
|
||||
fn types(books: &Books) -> Vec<String> {
|
||||
lines(books)
|
||||
.iter()
|
||||
.map(|l| l["type"].as_str().unwrap().to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A call that gets as far as writing lines and then fails: its savepoint
|
||||
/// rolls back, the live books are rebuilt without its lines, a `failed`
|
||||
/// closing line is on the record, its key is free, and what takes its ids
|
||||
/// next is a fact of the books (plan P15 2a, SCENARIO 2).
|
||||
///
|
||||
/// The failure is the projection refusing the account's line: a
|
||||
/// trigger put in the books' SQLite file from outside, as a full disk or a
|
||||
/// corrupt page would.
|
||||
#[test]
|
||||
fn a_call_that_wrote_lines_and_then_failed_leaves_the_books_and_its_key_as_they_were() {
|
||||
let books = Books::new("calls-failed-lines");
|
||||
let mut w = books.session("test");
|
||||
let before = types(&books);
|
||||
let db = rusqlite::Connection::open(projection(&books)).unwrap();
|
||||
db.execute_batch(
|
||||
"CREATE TRIGGER wb_test_refuses BEFORE INSERT ON accounts \
|
||||
BEGIN SELECT RAISE(ABORT, 'a test refuses this write'); END;",
|
||||
)
|
||||
.unwrap();
|
||||
let failed = call_exactly(&mut w, "books.add_account", account("key-lines-fail-1"));
|
||||
assert!(answer_of(&failed).is_err(), "{failed}");
|
||||
let added: Vec<_> = types(&books)[before.len()..].to_vec();
|
||||
assert_eq!(
|
||||
added.first().map(String::as_str),
|
||||
Some("call.begun"),
|
||||
"{added:?}"
|
||||
);
|
||||
assert_eq!(added.last().map(String::as_str), Some("call.closed"));
|
||||
assert!(
|
||||
added.len() >= 3,
|
||||
"it wrote a line before failing: {added:?}"
|
||||
);
|
||||
let all = lines(&books);
|
||||
let closed = &all.last().unwrap()["payload"];
|
||||
assert_eq!(closed["outcome"], "failed");
|
||||
assert!(closed["error"].as_str().is_some_and(|e| !e.is_empty()));
|
||||
assert!(closed.get("answer").is_none());
|
||||
// The live books are as they were: no such account, though a line was
|
||||
// written.
|
||||
db.execute_batch("DROP TRIGGER wb_test_refuses").unwrap();
|
||||
drop(db);
|
||||
let banks = |w: &mut common::Wire| {
|
||||
let chart = answer_of(&w.call("books.chart", json!({}))).unwrap();
|
||||
chart.to_string().matches("\"Bank\"").count()
|
||||
};
|
||||
assert_eq!(banks(&mut w), 0);
|
||||
// The key is free: the same request now succeeds, takes the id the dead
|
||||
// call had, and is the only account.
|
||||
let fixed = answer_of(&call_exactly(
|
||||
&mut w,
|
||||
"books.add_account",
|
||||
account("key-lines-fail-1"),
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
fixed["account_id"], 1,
|
||||
"the dead call's account id is handed out again: {fixed}"
|
||||
);
|
||||
assert_eq!(banks(&mut w), 1);
|
||||
// History lists every line and says of the dead ones that they did not
|
||||
// count; none of the counted lines is a dead one.
|
||||
let history = answer_of(&w.call("books.journal_history", json!({"limit": 200}))).unwrap();
|
||||
let said: Vec<&str> = history["lines"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|l| l["summary"].as_str())
|
||||
.filter(|s| s.contains("not counted"))
|
||||
.collect();
|
||||
assert_eq!(said.len(), added.len() - 2, "{history}");
|
||||
// A restart replays the same books: the dead lines build nothing.
|
||||
books.restart();
|
||||
let mut w = books.session("test");
|
||||
assert_eq!(banks(&mut w), 1);
|
||||
answer_of(&w.call("books.verify", json!({}))).unwrap();
|
||||
}
|
||||
|
||||
/// A call that wrote no line leaves none (WB-format-9): its answer is kept
|
||||
/// for the life of the server, so a repeat within the session is answered;
|
||||
/// after a restart the repeat simply runs again.
|
||||
#[test]
|
||||
fn a_call_that_wrote_nothing_leaves_no_line_and_is_answered_again_only_within_the_session() {
|
||||
let books = Books::new("calls-nothing");
|
||||
let mut w = books.session("test");
|
||||
let before = books.journal_raw();
|
||||
let args = json!({"request_key": "key-nothing-0001", "sha256": "ab".repeat(32),
|
||||
"size": 5, "mime_type": "text/csv", "file_name": "x.csv",
|
||||
"purpose": "import"});
|
||||
let first = answer_of(&call_exactly(&mut w, "books.begin_upload", args.clone())).unwrap();
|
||||
assert_eq!(books.journal_raw(), before, "no frame, no line");
|
||||
let again = answer_of(&call_exactly(&mut w, "books.begin_upload", args.clone())).unwrap();
|
||||
assert_eq!(again, first, "the same answer within the session");
|
||||
assert_eq!(books.journal_raw(), before);
|
||||
books.restart();
|
||||
let mut w = books.session("test");
|
||||
let after = answer_of(&call_exactly(&mut w, "books.begin_upload", args)).unwrap();
|
||||
assert_ne!(after, first, "after a restart it simply runs again");
|
||||
assert_eq!(books.journal_raw(), before, "and still writes nothing");
|
||||
}
|
||||
|
||||
/// The same request key under two tokens is two calls: a key belongs to
|
||||
/// the token that made it.
|
||||
#[test]
|
||||
fn the_same_key_under_two_tokens_is_two_calls() {
|
||||
let books = Books::new("calls-two-tokens");
|
||||
let mut one = books.session("test");
|
||||
let second = books
|
||||
.home
|
||||
.token_with(&books.id, "second", &["read", "write", "post", "admin"]);
|
||||
let mut two = common::Wire::with_token(&books.home, &books.id, Some(second));
|
||||
two.initialize("test");
|
||||
let a = answer_of(&call_exactly(
|
||||
&mut one,
|
||||
"books.draft_entry",
|
||||
draft("key-tokens-0001", "Same"),
|
||||
))
|
||||
.unwrap();
|
||||
let b = answer_of(&call_exactly(
|
||||
&mut two,
|
||||
"books.draft_entry",
|
||||
draft("key-tokens-0001", "Same"),
|
||||
))
|
||||
.unwrap();
|
||||
assert_ne!(a["entry_id"], b["entry_id"], "one draft per token: {a} {b}");
|
||||
let drafts = answer_of(&one.call("books.list_drafts", json!({}))).unwrap();
|
||||
assert_eq!(
|
||||
drafts["drafts"].as_array().map(Vec::len),
|
||||
Some(2),
|
||||
"{drafts}"
|
||||
);
|
||||
// And each token's repeat finds its own.
|
||||
let a2 = answer_of(&call_exactly(
|
||||
&mut one,
|
||||
"books.draft_entry",
|
||||
draft("key-tokens-0001", "Same"),
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(a2, a);
|
||||
}
|
||||
|
||||
/// A repeat that arrives while its original is still running waits for it
|
||||
/// (writes take turns) and then gets its answer: the original's effects
|
||||
/// are made once. Eight identical requests sent at the same moment make
|
||||
/// one draft and are answered alike.
|
||||
#[test]
|
||||
fn a_repeat_arriving_while_its_original_runs_gets_its_answer_and_changes_nothing() {
|
||||
let books = Books::new("calls-concurrent");
|
||||
let before = lines(&books).len();
|
||||
let barrier = std::sync::Barrier::new(8);
|
||||
let (home, id) = (&books.home, books.id.clone());
|
||||
let answers: Vec<Value> = std::thread::scope(|scope| {
|
||||
let runs: Vec<_> = (0..8)
|
||||
.map(|n| {
|
||||
let (barrier, id) = (&barrier, &id);
|
||||
scope.spawn(move || {
|
||||
let mut w = common::Wire::new(home, id);
|
||||
w.initialize(&format!("racer-{n}"));
|
||||
barrier.wait();
|
||||
call_exactly(
|
||||
&mut w,
|
||||
"books.draft_entry",
|
||||
draft("key-concurrent-1", "Raced"),
|
||||
)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
runs.into_iter().map(|r| r.join().unwrap()).collect()
|
||||
});
|
||||
let answers: Vec<Value> = answers.iter().map(|a| answer_of(a).unwrap()).collect();
|
||||
assert!(answers.windows(2).all(|p| p[0] == p[1]), "{answers:?}");
|
||||
let all = lines(&books);
|
||||
assert_eq!(
|
||||
all[before..]
|
||||
.iter()
|
||||
.filter(|l| l["type"] == "entry.created")
|
||||
.count(),
|
||||
1,
|
||||
"one draft"
|
||||
);
|
||||
assert_eq!(
|
||||
all[before..]
|
||||
.iter()
|
||||
.filter(|l| l["type"] == "call.begun")
|
||||
.count(),
|
||||
1,
|
||||
"one frame"
|
||||
);
|
||||
}
|
||||
|
||||
/// A call whose answer is too long for the books to keep (above 4 KiB):
|
||||
/// its closing line keeps the answer's hash and length, and a repeat, even
|
||||
/// one that arrived while the original ran, is told in words that it was
|
||||
/// done, with the lines it wrote; nothing is done twice.
|
||||
#[test]
|
||||
fn a_repeat_of_a_call_whose_answer_was_too_long_is_told_it_was_done() {
|
||||
let books = Books::new("calls-long-answer");
|
||||
let mut w = books.session("test");
|
||||
for (code, name, kind) in [("1000", "Bank", "asset"), ("6000", "Supplies", "expense")] {
|
||||
answer_of(&w.call(
|
||||
"books.add_account",
|
||||
json!({"code": code, "name": name, "account_type": kind}),
|
||||
))
|
||||
.unwrap();
|
||||
}
|
||||
let rows = 300;
|
||||
let mut csv = String::from("Date,Description,Amount\n");
|
||||
for n in 0..rows {
|
||||
csv.push_str(&format!("2026-01-02,Row {n},-1.{:02}\n", n % 100));
|
||||
}
|
||||
let up = w.upload(csv.as_bytes(), "bank.csv", "text/csv", "import");
|
||||
let args = json!({"upload_id": up, "bank_account_code": "1000",
|
||||
"default_offset_code": "6000", "request_key": "key-long-answer1"});
|
||||
let before = lines(&books).len();
|
||||
let (home, id) = (&books.home, books.id.clone());
|
||||
let (first, second) = std::thread::scope(|scope| {
|
||||
let original = scope.spawn(|| {
|
||||
let mut w = common::Wire::new(home, &id);
|
||||
w.initialize("original");
|
||||
call_exactly(&mut w, "books.import_bank_csv", args.clone())
|
||||
});
|
||||
std::thread::sleep(std::time::Duration::from_millis(30));
|
||||
let repeat = scope.spawn(|| {
|
||||
let mut w = common::Wire::new(home, &id);
|
||||
w.initialize("repeat");
|
||||
call_exactly(&mut w, "books.import_bank_csv", args.clone())
|
||||
});
|
||||
(original.join().unwrap(), repeat.join().unwrap())
|
||||
});
|
||||
// One of the two ran; the other was told, in words, that it was done.
|
||||
let (ran, told) = match (answer_of(&first), answer_of(&second)) {
|
||||
(Ok(a), Err(why)) | (Err(why), Ok(a)) => (a, why),
|
||||
other => panic!("one runs and one is told: {other:?}"),
|
||||
};
|
||||
assert_eq!(ran["count"], rows, "{ran}");
|
||||
assert!(told.contains("was done"), "{told}");
|
||||
assert!(told.contains("nothing more was changed"), "{told}");
|
||||
assert!(told.contains("journal lines"), "{told}");
|
||||
let all = lines(&books);
|
||||
assert_eq!(
|
||||
all[before..]
|
||||
.iter()
|
||||
.filter(|l| l["type"] == "entry.created")
|
||||
.count(),
|
||||
rows,
|
||||
"the file was imported once"
|
||||
);
|
||||
let closed = all.last().unwrap();
|
||||
assert_eq!(closed["type"], "call.closed");
|
||||
assert!(
|
||||
closed["payload"].get("answer").is_none(),
|
||||
"no answer kept whole"
|
||||
);
|
||||
assert_eq!(
|
||||
closed["payload"]["answer_sha256"].as_str().map(str::len),
|
||||
Some(64)
|
||||
);
|
||||
assert!(closed["payload"]["answer_bytes"].as_u64().unwrap() > 4096);
|
||||
// Across a restart the same words.
|
||||
books.restart();
|
||||
let mut w = books.session("test");
|
||||
let again = call_exactly(&mut w, "books.import_bank_csv", args);
|
||||
assert!(answer_of(&again).unwrap_err().contains("was done"));
|
||||
assert_eq!(lines(&books).len(), all.len());
|
||||
}
|
||||
|
||||
/// A crash after the closing line is on disk and before SQLite committed:
|
||||
/// the books are rebuilt from the journal, the call is done, and a repeat
|
||||
/// of its key answers the first answer and changes nothing.
|
||||
#[test]
|
||||
fn a_crash_with_the_ok_close_on_disk_but_sqlite_not_committed_leaves_the_call_done_once() {
|
||||
let books = Books::new("calls-sqlite-behind");
|
||||
let mut w = books.session("test");
|
||||
answer_of(&call_exactly(
|
||||
&mut w,
|
||||
"books.draft_entry",
|
||||
draft("key-crash-prior1", "Earlier"),
|
||||
))
|
||||
.unwrap();
|
||||
drop(w);
|
||||
// The projection as it was before the call.
|
||||
books.stop();
|
||||
let db = projection(&books);
|
||||
let old = std::fs::read(&db).unwrap();
|
||||
let side: Vec<_> = ["-wal", "-shm"]
|
||||
.iter()
|
||||
.map(|x| std::path::PathBuf::from(format!("{}{x}", db.display())))
|
||||
.collect();
|
||||
assert!(
|
||||
side.iter().all(|p| !p.exists()),
|
||||
"a stopped server leaves no -wal or -shm"
|
||||
);
|
||||
books.start();
|
||||
let mut w = books.session("test");
|
||||
let first = answer_of(&call_exactly(
|
||||
&mut w,
|
||||
"books.draft_entry",
|
||||
draft("key-crash-0001", "Done once"),
|
||||
))
|
||||
.unwrap();
|
||||
drop(w);
|
||||
let journal = books.journal_raw();
|
||||
assert_eq!(
|
||||
lines(&books).last().unwrap()["payload"]["outcome"],
|
||||
"ok",
|
||||
"the ok closing line is on disk"
|
||||
);
|
||||
// Power fails: the journal has it (it was fsynced first), SQLite does not.
|
||||
books.stop();
|
||||
std::fs::write(&db, old).unwrap();
|
||||
books.start();
|
||||
let mut w = books.session("test");
|
||||
// The books are rebuilt from the journal: both drafts are there.
|
||||
let drafts = answer_of(&w.call("books.list_drafts", json!({}))).unwrap();
|
||||
assert_eq!(
|
||||
drafts["drafts"].as_array().map(Vec::len),
|
||||
Some(2),
|
||||
"{drafts}"
|
||||
);
|
||||
// The repeat is answered with the first answer and does nothing.
|
||||
let again = answer_of(&call_exactly(
|
||||
&mut w,
|
||||
"books.draft_entry",
|
||||
draft("key-crash-0001", "Done once"),
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(again, first);
|
||||
assert_eq!(books.journal_raw(), journal, "nothing more was written");
|
||||
let drafts = answer_of(&w.call("books.list_drafts", json!({}))).unwrap();
|
||||
assert_eq!(
|
||||
drafts["drafts"].as_array().map(Vec::len),
|
||||
Some(2),
|
||||
"{drafts}"
|
||||
);
|
||||
answer_of(&w.call("books.verify", json!({}))).unwrap();
|
||||
}
|
||||
|
||||
// ---- The tax-id vault is inside the transaction (BS-partner-2). Obviously
|
||||
// fake values: a TIN is never written in a journal line, an error, or here
|
||||
// beyond these two.
|
||||
|
||||
const OLD_TIN: &str = "123-45-6789";
|
||||
const NEW_TIN: &str = "765-43-2109";
|
||||
|
||||
fn digits(tin: &str) -> String {
|
||||
tin.replace('-', "")
|
||||
}
|
||||
|
||||
/// Whether `text` holds either fake TIN, hyphenated or not.
|
||||
fn holds_a_tin(text: &str) -> bool {
|
||||
[OLD_TIN, NEW_TIN]
|
||||
.iter()
|
||||
.any(|t| text.contains(t) || text.contains(&digits(t)))
|
||||
}
|
||||
|
||||
/// What the vault holds for the party, by the vault's own reader: the
|
||||
/// TIN's last four, or None.
|
||||
fn vaulted_last4(books: &Books, party: u64) -> Option<String> {
|
||||
let book = books.dir();
|
||||
let key = book.join("keys").join("legacy.key");
|
||||
let vault = ledger_vault::Vault::open(&book.join("vault"), &key, false).ok()?;
|
||||
vault.tin(party).unwrap().map(|t| t.last4().to_string())
|
||||
}
|
||||
|
||||
fn staged_files(books: &Books) -> Vec<String> {
|
||||
std::fs::read_dir(books.dir().join("vault"))
|
||||
.map(|d| {
|
||||
d.flatten()
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.filter(|n| n.contains(".staged-") || n.contains(".purging-"))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn set_tin(key: &str, tin: &str) -> Value {
|
||||
json!({"party": "Mo", "tin": tin, "tin_type": "ssn", "request_key": key})
|
||||
}
|
||||
|
||||
/// A set_tin that fails after it wrote the vault: the vault keeps the old
|
||||
/// tax id whole and holds nothing of the new one, the journal holds
|
||||
/// neither, and once the call can run again it is the new one that is kept.
|
||||
#[test]
|
||||
fn a_set_tin_that_fails_leaves_the_vault_as_it_was() {
|
||||
let books = Books::new("calls-vault-fail");
|
||||
let mut w = books.session("test");
|
||||
let party = answer_of(&w.call(
|
||||
"books.add_party",
|
||||
json!({"name": "Mo", "roles": ["member"]}),
|
||||
))
|
||||
.unwrap()["party_id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
answer_of(&call_exactly(
|
||||
&mut w,
|
||||
"books.set_tin",
|
||||
set_tin("key-vault-first1", OLD_TIN),
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(vaulted_last4(&books, party).as_deref(), Some("6789"));
|
||||
// The projection refuses the call's first line (its begin line).
|
||||
let db = rusqlite::Connection::open(projection(&books)).unwrap();
|
||||
db.execute_batch(
|
||||
"CREATE TRIGGER wb_test_refuses BEFORE UPDATE ON meta \
|
||||
BEGIN SELECT RAISE(ABORT, 'a test refuses this write'); END;",
|
||||
)
|
||||
.unwrap();
|
||||
let failed = call_exactly(
|
||||
&mut w,
|
||||
"books.set_tin",
|
||||
set_tin("key-vault-fail01", NEW_TIN),
|
||||
);
|
||||
let why = answer_of(&failed).unwrap_err();
|
||||
assert!(!holds_a_tin(&why), "an error never holds a tax id");
|
||||
db.execute_batch("DROP TRIGGER wb_test_refuses").unwrap();
|
||||
drop(db);
|
||||
// The failure here is one that persists (the projection refuses every
|
||||
// write, as a full disk would), so the books server stops: the call's
|
||||
// failed closing line is on disk, and what it staged is settled by what
|
||||
// the journal says at the next start.
|
||||
books.restart();
|
||||
let mut w = books.session("test");
|
||||
let log = books.server_log();
|
||||
assert!(log.contains("vault records unsettled"), "{log}");
|
||||
assert!(!holds_a_tin(&log), "a log never holds a tax id");
|
||||
// The journal's failed frame holds no tax id, and the old one is whole in
|
||||
// the vault; nothing is left staged.
|
||||
assert_eq!(
|
||||
lines(&books)[lines(&books).len() - 1]["payload"]["outcome"],
|
||||
"failed"
|
||||
);
|
||||
assert!(!holds_a_tin(
|
||||
&String::from_utf8(books.journal_raw()).unwrap()
|
||||
));
|
||||
assert_eq!(vaulted_last4(&books, party).as_deref(), Some("6789"));
|
||||
assert_eq!(staged_files(&books), Vec::<String>::new());
|
||||
// The party still shows the old last four.
|
||||
let shown = answer_of(&w.call("books.party", json!({"party": "Mo"}))).unwrap();
|
||||
assert!(shown.to_string().contains("6789"), "{shown}");
|
||||
assert!(!shown.to_string().contains("2109"), "{shown}");
|
||||
// The key is free: the same request now succeeds and the vault holds the new one.
|
||||
answer_of(&call_exactly(
|
||||
&mut w,
|
||||
"books.set_tin",
|
||||
set_tin("key-vault-fail01", NEW_TIN),
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(vaulted_last4(&books, party).as_deref(), Some("2109"));
|
||||
assert_eq!(staged_files(&books), Vec::<String>::new());
|
||||
assert!(!holds_a_tin(
|
||||
&String::from_utf8(books.journal_raw()).unwrap()
|
||||
));
|
||||
}
|
||||
|
||||
/// Two requests that differ only in a tax id are two requests: the same key
|
||||
/// with another tax id is refused, never answered as a repeat, and nothing
|
||||
/// of either is in the journal to test a guess against.
|
||||
#[test]
|
||||
fn a_key_reused_for_another_tax_id_is_refused_not_repeated() {
|
||||
let books = Books::new("calls-vault-mask");
|
||||
let mut w = books.session("test");
|
||||
answer_of(&w.call(
|
||||
"books.add_party",
|
||||
json!({"name": "Mo", "roles": ["member"]}),
|
||||
))
|
||||
.unwrap();
|
||||
let first = answer_of(&call_exactly(
|
||||
&mut w,
|
||||
"books.set_tin",
|
||||
set_tin("key-mask-000001", OLD_TIN),
|
||||
))
|
||||
.unwrap();
|
||||
// The same request again: the first answer, nothing more written.
|
||||
let journal = books.journal_raw();
|
||||
let again = answer_of(&call_exactly(
|
||||
&mut w,
|
||||
"books.set_tin",
|
||||
set_tin("key-mask-000001", OLD_TIN),
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(again, first);
|
||||
// Another tax id under the same key: refused in words.
|
||||
let other = call_exactly(&mut w, "books.set_tin", set_tin("key-mask-000001", NEW_TIN));
|
||||
let why = answer_of(&other).unwrap_err();
|
||||
assert!(why.contains("already used"), "{why}");
|
||||
assert!(!holds_a_tin(&why));
|
||||
assert_eq!(books.journal_raw(), journal);
|
||||
assert!(!holds_a_tin(&String::from_utf8(journal).unwrap()));
|
||||
// And across a restart, with the digest keyed by the books' own secret.
|
||||
books.restart();
|
||||
let mut w = books.session("test");
|
||||
let other = call_exactly(&mut w, "books.set_tin", set_tin("key-mask-000001", NEW_TIN));
|
||||
assert!(answer_of(&other).unwrap_err().contains("already used"));
|
||||
let same = answer_of(&call_exactly(
|
||||
&mut w,
|
||||
"books.set_tin",
|
||||
set_tin("key-mask-000001", OLD_TIN),
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(same, first);
|
||||
}
|
||||
|
||||
/// A crash after the closing line is on disk and before the staged vault
|
||||
/// record was made final: the next start finishes what the journal says
|
||||
/// was done (the new tax id is the party's), and drops what no committed
|
||||
/// call staged.
|
||||
#[test]
|
||||
fn a_crash_between_the_commit_and_the_vault_settling_is_finished_at_the_next_start() {
|
||||
let books = Books::new("calls-vault-crash");
|
||||
let mut w = books.session("test");
|
||||
let party = answer_of(&w.call(
|
||||
"books.add_party",
|
||||
json!({"name": "Mo", "roles": ["member"]}),
|
||||
))
|
||||
.unwrap()["party_id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
answer_of(&call_exactly(
|
||||
&mut w,
|
||||
"books.set_tin",
|
||||
set_tin("key-vcrash-first", OLD_TIN),
|
||||
))
|
||||
.unwrap();
|
||||
drop(w);
|
||||
books.stop();
|
||||
let record = books.dir().join("vault").join(format!("tin-{party}.bin"));
|
||||
let old = std::fs::read(&record).unwrap();
|
||||
books.start();
|
||||
let mut w = books.session("test");
|
||||
answer_of(&call_exactly(
|
||||
&mut w,
|
||||
"books.set_tin",
|
||||
set_tin("key-vcrash-second", NEW_TIN),
|
||||
))
|
||||
.unwrap();
|
||||
drop(w);
|
||||
let closed = lines(&books)
|
||||
.into_iter()
|
||||
.rev()
|
||||
.find(|l| l["type"] == "call.closed")
|
||||
.unwrap();
|
||||
assert_eq!(closed["payload"]["outcome"], "ok");
|
||||
let tag = ledger_store::calls::call_tag(
|
||||
closed["payload"]["token"].as_str().unwrap(),
|
||||
closed["payload"]["key"].as_str().unwrap(),
|
||||
);
|
||||
books.stop();
|
||||
let new = std::fs::read(&record).unwrap();
|
||||
assert_ne!(old, new);
|
||||
// As a crash would have left it: the closing line is on disk, the new
|
||||
// record is still staged, the old one still final. And a record staged
|
||||
// by a call the journal never closed.
|
||||
std::fs::write(&record, &old).unwrap();
|
||||
let staged = record.with_file_name(format!("tin-{party}.staged-{tag}"));
|
||||
std::fs::write(&staged, &new).unwrap();
|
||||
let stray = record.with_file_name(format!("tin-99.staged-{}", "0123456789abcdef"));
|
||||
std::fs::write(&stray, &new).unwrap();
|
||||
books.start();
|
||||
assert_eq!(
|
||||
vaulted_last4(&books, party).as_deref(),
|
||||
Some("2109"),
|
||||
"finished"
|
||||
);
|
||||
assert!(
|
||||
!staged.exists() && !stray.exists(),
|
||||
"{:?}",
|
||||
staged_files(&books)
|
||||
);
|
||||
assert!(books.server_log().contains("vault records unsettled"));
|
||||
}
|
||||
@@ -434,8 +434,18 @@ impl Wire {
|
||||
}
|
||||
|
||||
/// Send `text` as one message's body, as it is (a test's own bytes,
|
||||
/// malformed ones included).
|
||||
/// malformed ones included), except that a tool call that carries no
|
||||
/// `request_key` is given a fresh one (D-88: every write needs one; a
|
||||
/// read ignores it), so a test of what a tool does needn't make one up.
|
||||
/// [`Self::send_exactly`] sends the bytes untouched.
|
||||
pub fn send_line(&mut self, text: &str) {
|
||||
let text = with_request_key(text);
|
||||
self.send_exactly(&text);
|
||||
}
|
||||
|
||||
/// [`Self::send_line`] without the request key: these bytes only
|
||||
/// (the tests of what a call without a key is told).
|
||||
pub fn send_exactly(&mut self, text: &str) {
|
||||
let parsed: Option<Value> = serde_json::from_str(text).ok();
|
||||
let method = parsed
|
||||
.as_ref()
|
||||
@@ -761,8 +771,15 @@ impl Books {
|
||||
self.home.book_dir(&self.id)
|
||||
}
|
||||
|
||||
/// The books' journal, as it is on disk.
|
||||
/// The books' journal as it is on disk, without the frames of tool
|
||||
/// calls (`call.begun`, `call.closed`: D-88): what the books hold, so
|
||||
/// a test that a call "journaled nothing" says so of the events.
|
||||
pub fn journal(&self) -> Vec<u8> {
|
||||
without_call_lines(&self.journal_raw())
|
||||
}
|
||||
|
||||
/// The books' journal, byte for byte.
|
||||
pub fn journal_raw(&self) -> Vec<u8> {
|
||||
std::fs::read(self.dir().join("journal.jsonl")).unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -1113,6 +1130,48 @@ pub async fn connect_at(run: &Path, book: &str, token: Option<String>) -> Result
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// A journal's bytes without its call frames (`call.begun`, `call.closed`).
|
||||
pub fn without_call_lines(journal: &[u8]) -> Vec<u8> {
|
||||
journal
|
||||
.split_inclusive(|&b| b == b'\n')
|
||||
.filter(|l| {
|
||||
let l = String::from_utf8_lossy(l);
|
||||
!l.contains(r#""type":"call.begun""#) && !l.contains(r#""type":"call.closed""#)
|
||||
})
|
||||
.flatten()
|
||||
.copied()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A request key no other call in this process has used.
|
||||
pub fn fresh_request_key() -> String {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static NEXT: AtomicU64 = AtomicU64::new(1);
|
||||
format!(
|
||||
"test-key-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, Ordering::SeqCst)
|
||||
)
|
||||
}
|
||||
|
||||
/// `message`, a JSON-RPC message as text: if it is a `tools/call` whose
|
||||
/// arguments are an object with no `request_key`, with a fresh one added
|
||||
/// (the key the books ask of every write, D-88); anything else as it is.
|
||||
pub fn with_request_key(message: &str) -> String {
|
||||
let Ok(mut v) = serde_json::from_str::<Value>(message) else {
|
||||
return message.to_string();
|
||||
};
|
||||
let keyed = v.get("method") == Some(&json!("tools/call"))
|
||||
&& v.pointer("/params/arguments")
|
||||
.and_then(Value::as_object)
|
||||
.is_some_and(|a| !a.contains_key("request_key"));
|
||||
if !keyed {
|
||||
return message.to_string();
|
||||
}
|
||||
v["params"]["arguments"]["request_key"] = json!(fresh_request_key());
|
||||
v.to_string()
|
||||
}
|
||||
|
||||
/// Call a tool: Ok(structured result) or Err(the error text).
|
||||
/// Call a tool the way an agent confirms (plan P4, D-50): a call with
|
||||
/// `confirmed: true` and no `preview` is made first without `confirmed`,
|
||||
@@ -1131,7 +1190,9 @@ pub async fn call(c: &Client, tool: &str, mut args: Value) -> Result<Value, Stri
|
||||
|
||||
async fn call_once(c: &Client, tool: &str, args: Value) -> Result<Value, String> {
|
||||
use rmcp::model::CallToolRequestParams;
|
||||
let args = args.as_object().cloned().unwrap_or_default();
|
||||
let mut args = args.as_object().cloned().unwrap_or_default();
|
||||
args.entry("request_key")
|
||||
.or_insert_with(|| json!(fresh_request_key()));
|
||||
// A client whose server went away may wait forever: a call that
|
||||
// takes this long counts as refused.
|
||||
let r = tokio::time::timeout(
|
||||
|
||||
@@ -123,7 +123,7 @@ fn an_invoice_from_issue_to_paid() {
|
||||
|
||||
// The preview: nothing written, a DRAFT copy handed over, the number
|
||||
// and due date the confirm will take.
|
||||
let before = books.journal();
|
||||
let before = books.journal_raw();
|
||||
let preview = m.call("books.create_invoice", issue.clone());
|
||||
assert!(
|
||||
preview["preview"].is_string(),
|
||||
@@ -155,8 +155,8 @@ fn an_invoice_from_issue_to_paid() {
|
||||
let draft = m.handed(&preview["pdf"]);
|
||||
assert!(draft.starts_with(b"%PDF"), "a PDF, not bytes inline");
|
||||
assert!(draft.len() > 1_000, "the DRAFT copy is a page: {preview}");
|
||||
assert_eq!(books.journal(), before, "a preview journals nothing");
|
||||
assert!(books.journal().len() == before.len());
|
||||
assert_eq!(books.journal_raw(), before, "a preview journals nothing");
|
||||
assert!(books.journal_raw().len() == before.len());
|
||||
|
||||
// The confirm: the same number, the issued copy filed with the invoice.
|
||||
let mut confirmed = issue.clone();
|
||||
@@ -239,7 +239,7 @@ fn a_bill_with_its_vendor_invoice_and_terms() {
|
||||
"account": "6500"}],
|
||||
});
|
||||
|
||||
let before = books.journal();
|
||||
let before = books.journal_raw();
|
||||
let mut preview = bill.clone();
|
||||
preview["upload_id"] = json!(file);
|
||||
let p = m.call("books.create_bill", preview.clone());
|
||||
@@ -248,7 +248,7 @@ fn a_bill_with_its_vendor_invoice_and_terms() {
|
||||
assert_eq!(p["terms"], "2/10 net 30", "{p}");
|
||||
assert_eq!(p["discount_by"], "2026-02-11", "{p}");
|
||||
assert_eq!(p["max_discount"], "20.00", "2% of 1,000.00");
|
||||
assert_eq!(books.journal(), before, "a preview journals nothing");
|
||||
assert_eq!(books.journal_raw(), before, "a preview journals nothing");
|
||||
|
||||
let mut confirm = preview;
|
||||
confirm["confirmed"] = json!(true);
|
||||
@@ -321,13 +321,13 @@ fn duplicate_vendor_invoice_refused() {
|
||||
m.call("books.create_bill", bill(&first_file, "2026-02-01"));
|
||||
// The same number (however written) is the same vendor invoice.
|
||||
let second_file = m.upload(b"second copy", "ch-1-again.pdf", "receipt");
|
||||
let before = books.journal();
|
||||
let before = books.journal_raw();
|
||||
let refused = m
|
||||
.try_call("books.create_bill", bill(&second_file, "2026-02-02"))
|
||||
.unwrap_err();
|
||||
assert!(refused.contains("CH-4471"), "{refused}");
|
||||
assert!(refused.contains("duplicate_reason"), "{refused}");
|
||||
assert_eq!(books.journal(), before, "a refusal journals nothing");
|
||||
assert_eq!(books.journal_raw(), before, "a refusal journals nothing");
|
||||
// The upload was given back, not used up (an upload is spent only by
|
||||
// the call that files it).
|
||||
let mut with_reason = bill(&second_file, "2026-02-02");
|
||||
@@ -377,14 +377,14 @@ fn a_line_account_must_be_allowed() {
|
||||
"lines": [{"description": "Work", "amount": "100.00", "account": account}],
|
||||
"confirmed": true})
|
||||
};
|
||||
let before = books.journal();
|
||||
let before = books.journal_raw();
|
||||
// An invoice line may not post to the receivable control or a role
|
||||
// account.
|
||||
let why = m
|
||||
.try_call("books.create_invoice", invoice("1200"))
|
||||
.unwrap_err();
|
||||
assert!(why.contains("1200"), "{why}");
|
||||
assert_eq!(books.journal(), before, "a refusal journals nothing");
|
||||
assert_eq!(books.journal_raw(), before, "a refusal journals nothing");
|
||||
// Nor to an expense account.
|
||||
let why = m
|
||||
.try_call("books.create_invoice", invoice("6999"))
|
||||
@@ -547,7 +547,7 @@ fn custom_terms_are_due_on_the_date_they_give() {
|
||||
assert_eq!(bill["due_date"], "2026-11-20", "{bill}");
|
||||
|
||||
// Dated after the agreed day: refused.
|
||||
let before = books.journal();
|
||||
let before = books.journal_raw();
|
||||
let late = m
|
||||
.try_call(
|
||||
"books.create_invoice",
|
||||
@@ -555,7 +555,7 @@ fn custom_terms_are_due_on_the_date_they_give() {
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(late.contains("due"), "{late}");
|
||||
assert_eq!(books.journal(), before, "a refusal writes nothing");
|
||||
assert_eq!(books.journal_raw(), before, "a refusal writes nothing");
|
||||
}
|
||||
|
||||
/// A customer given by id and by name is the same record (the old
|
||||
@@ -589,7 +589,7 @@ fn a_customer_by_id_and_by_name_is_one_record() {
|
||||
// ambiguous, and is refused rather than guessed.
|
||||
m.customer("Zeta");
|
||||
m.customer("2");
|
||||
let before = books.journal();
|
||||
let before = books.journal_raw();
|
||||
let why = m
|
||||
.try_call(
|
||||
"books.create_invoice",
|
||||
@@ -598,7 +598,7 @@ fn a_customer_by_id_and_by_name_is_one_record() {
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(why.contains("ambiguous"), "{why}");
|
||||
assert_eq!(books.journal(), before, "a refusal journals nothing");
|
||||
assert_eq!(books.journal_raw(), before, "a refusal journals nothing");
|
||||
// Nothing at all names no customer.
|
||||
let why = m
|
||||
.try_call(
|
||||
|
||||
@@ -349,13 +349,13 @@ fn a_package_the_build_refuses_journals_no_decision_even_with_a_reason() {
|
||||
draft(&mut w, "2026-03-10", "Open", "40.00");
|
||||
let mut args = json!({"as_of": "2026-03-31", "cash_accounts": ["1000"]});
|
||||
args["allow_open_drafts"] = json!({"reason": "the CPA wants it before the receipt comes"});
|
||||
let before = books.journal().len();
|
||||
let before = books.journal_raw().len();
|
||||
for _ in 0..2 {
|
||||
let why = answer_of(&w.call("books.export_cpa_package", args.clone()))
|
||||
.expect_err("the build refuses an unknown capital account");
|
||||
assert!(why.contains("unknown capital account 3999"), "{why}");
|
||||
assert_eq!(
|
||||
books.journal().len(),
|
||||
books.journal_raw().len(),
|
||||
before,
|
||||
"a decision was journaled for a package that was refused"
|
||||
);
|
||||
@@ -397,7 +397,7 @@ fn stale_preview_refused() {
|
||||
json!({"entry_id": id, "account": "1000", "side": "credit", "amount": "1.00"}),
|
||||
))
|
||||
.unwrap();
|
||||
let before = books.journal();
|
||||
let before = books.journal_raw();
|
||||
let r = w.call_raw(
|
||||
"books.post_entry",
|
||||
json!({"entry_id": id, "confirmed": true, "preview": digest}),
|
||||
@@ -405,7 +405,11 @@ fn stale_preview_refused() {
|
||||
let err = refusal(&r);
|
||||
assert_eq!(err["code"], "stale_preview");
|
||||
assert_eq!(err["remedy_tool"], "books.post_entry");
|
||||
assert_eq!(books.journal(), before, "a stale confirm writes nothing");
|
||||
assert_eq!(
|
||||
books.journal_raw(),
|
||||
before,
|
||||
"a stale confirm writes nothing"
|
||||
);
|
||||
// An operation's preview moves with the journal's head: a post by
|
||||
// another session in between forces a re-preview.
|
||||
let other = draft(&mut w, "2026-03-02", "Other", "5.00");
|
||||
|
||||
@@ -325,11 +325,11 @@ fn consolidation_never_removes_an_entrys_only_evidence() {
|
||||
let (_root, fixture) = legacy_duplicates("dupes-only", true);
|
||||
let books = Books::placed("p6-dupes-only", &fixture);
|
||||
let mut w = books.session("evidence");
|
||||
let before = books.journal();
|
||||
let before = books.journal_raw();
|
||||
let r = w.call("books.consolidate_duplicates", json!({"confirmed": true}));
|
||||
let why = answer_of(&r).unwrap_err();
|
||||
assert!(why.contains("receipt_required"), "{why}");
|
||||
assert_eq!(books.journal(), before, "a refusal journals nothing");
|
||||
assert_eq!(books.journal_raw(), before, "a refusal journals nothing");
|
||||
}
|
||||
|
||||
/// Plan P6 step 4: the kept file takes every subject the duplicates had;
|
||||
@@ -351,8 +351,8 @@ fn consolidation_links_the_kept_file_to_every_subject() {
|
||||
assert_eq!(preview["status"], "preview");
|
||||
assert_eq!(preview["groups"][0]["keep"], 1);
|
||||
assert_eq!(preview["groups"][0]["withdraw"], json!([2]));
|
||||
let before = books.journal();
|
||||
assert_eq!(before, books.journal(), "a preview journals nothing");
|
||||
let before = books.journal_raw();
|
||||
assert_eq!(before, books.journal_raw(), "a preview journals nothing");
|
||||
let r = w.call("books.consolidate_duplicates", json!({"confirmed": true}));
|
||||
let out = answer_of(&r).unwrap();
|
||||
assert_eq!(out["status"], "consolidated", "{out}");
|
||||
@@ -413,7 +413,7 @@ fn the_backfill_reads_an_old_fixtures_files_once() {
|
||||
// Attachment 1 is a PDF (one page with text), 2 a text file, 3 a
|
||||
// Markdown document.
|
||||
for id in 1..=2 {
|
||||
let before = books.journal();
|
||||
let before = books.journal_raw();
|
||||
let r = w.call("books.get_receipt", json!({"attachment_id": id}));
|
||||
let out = answer_of(&r).unwrap();
|
||||
assert_eq!(out["text_status"], "not_extracted", "{out}");
|
||||
@@ -425,7 +425,11 @@ fn the_backfill_reads_an_old_fixtures_files_once() {
|
||||
ledger_mcp::admin::Response::Extracted { status, .. } => assert_eq!(status, "ok"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
assert_ne!(books.journal(), before, "the backfill journals a record");
|
||||
assert_ne!(
|
||||
books.journal_raw(),
|
||||
before,
|
||||
"the backfill journals a record"
|
||||
);
|
||||
}
|
||||
// The PDF's text is readable now, and its pages render.
|
||||
let r = w.call("books.get_receipt", json!({"attachment_id": 1}));
|
||||
@@ -446,18 +450,18 @@ fn the_backfill_reads_an_old_fixtures_files_once() {
|
||||
common::clean_env(&mut extract, books.home.dir.path());
|
||||
extract.output().unwrap()
|
||||
};
|
||||
let before = books.journal();
|
||||
let before = books.journal_raw();
|
||||
let out = run();
|
||||
assert!(out.status.success(), "{out:?}");
|
||||
assert!(
|
||||
String::from_utf8_lossy(&out.stdout).contains("Read attachment 3"),
|
||||
"{out:?}"
|
||||
);
|
||||
assert_ne!(books.journal(), before, "the command journals a record");
|
||||
let after = books.journal();
|
||||
assert_ne!(books.journal_raw(), before, "the command journals a record");
|
||||
let after = books.journal_raw();
|
||||
let out = run();
|
||||
assert!(out.status.success(), "{out:?}");
|
||||
assert_eq!(books.journal(), after, "an extract journals once");
|
||||
assert_eq!(books.journal_raw(), after, "an extract journals once");
|
||||
books.start();
|
||||
let mut w = books.session("evidence");
|
||||
let r = w.call("books.verify", json!({}));
|
||||
|
||||
@@ -309,6 +309,8 @@ impl Agent {
|
||||
}
|
||||
|
||||
fn send(&mut self, message: Value) {
|
||||
// A tool call carries the request key every write needs (D-88).
|
||||
let message = common::with_request_key(&message.to_string());
|
||||
let stdin = self.run.child.stdin.as_mut().unwrap();
|
||||
writeln!(stdin, "{message}").unwrap();
|
||||
stdin.flush().unwrap();
|
||||
@@ -483,12 +485,19 @@ fn format_upgrade_waits_for_consent() {
|
||||
assert!(refused.contains("format_upgrade_pending"), "{refused}");
|
||||
assert!(refused.contains("no tool can"), "{refused}");
|
||||
assert_eq!(journal(&dir), before, "a refusal journals nothing");
|
||||
// What needs nothing new is made.
|
||||
a.call(
|
||||
"books.add_account",
|
||||
json!({"code": "6000", "name": "Supplies", "account_type": "expense"}),
|
||||
)
|
||||
.unwrap();
|
||||
// Nothing is written, whatever it is (D-89): a write that needs
|
||||
// nothing new is refused the same, with the same remedy; reads work.
|
||||
let refused = a
|
||||
.call(
|
||||
"books.add_account",
|
||||
json!({"code": "6000", "name": "Supplies", "account_type": "expense"}),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(refused.starts_with("format_upgrade_pending"), "{refused}");
|
||||
assert!(refused.contains("nothing can be written"), "{refused}");
|
||||
assert!(refused.contains("wanderbooks books upgrade"), "{refused}");
|
||||
assert_eq!(journal(&dir), before, "a refusal journals nothing");
|
||||
a.call("books.chart", json!({})).unwrap();
|
||||
let tools = a.request("tools/list", json!({}), 30);
|
||||
let names: Vec<&str> = tools["result"]["tools"]
|
||||
.as_array()
|
||||
@@ -614,11 +623,11 @@ fn format_upgrade_waits_for_consent() {
|
||||
assert_eq!(format_lines(&dir), 1);
|
||||
}
|
||||
|
||||
/// plan P4b S4.4 (R-A step 4, 8.0.6 item 3): on books that haven't
|
||||
/// declared `documents_v2`, an invoice carrying a new field (terms) is
|
||||
/// refused with the upgrade remedy and journals nothing, while one
|
||||
/// carrying none posts as before; after the owner's go-ahead the same call
|
||||
/// is made, and takes the first number.
|
||||
/// plan P4b S4.4 (R-A step 4, 8.0.6 item 3), under D-89: on books that
|
||||
/// haven't declared the journal's call transactions, no write is taken, an
|
||||
/// invoice carrying a new field (terms) no more than any other, and it
|
||||
/// journals nothing; after the owner's go-ahead the same call is made, and
|
||||
/// takes the first number.
|
||||
#[test]
|
||||
fn documents_v2_refused_until_consent() {
|
||||
let home = Home::new("documents-v2");
|
||||
@@ -632,31 +641,25 @@ fn documents_v2_refused_until_consent() {
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "{out:?}");
|
||||
let mut a = Agent::start(&home, "acme");
|
||||
let customer = a
|
||||
.call("books.add_customer", json!({"name": "Harbor Coffee"}))
|
||||
.unwrap()["id"]
|
||||
.clone();
|
||||
let line = json!([{"description": "Design", "amount": "500.00"}]);
|
||||
let with_terms = json!({"customer": customer.to_string(), "date": "2026-02-10",
|
||||
let with_terms = json!({"customer": "1", "date": "2026-02-10",
|
||||
"terms": "Net 30", "lines": line, "confirmed": true});
|
||||
let before = journal(&dir);
|
||||
let refused = a
|
||||
.call("books.create_invoice", with_terms.clone())
|
||||
.unwrap_err();
|
||||
assert!(refused.starts_with("format_upgrade_pending"), "{refused}");
|
||||
assert!(refused.contains("documents_v2"), "{refused}");
|
||||
// (An invoice's preview, which writes nothing, is made as ever; its
|
||||
// post is the write that waits: it is asked for after the go-ahead.)
|
||||
for (tool, args) in [
|
||||
("books.add_customer", json!({"name": "Harbor Coffee"})),
|
||||
(
|
||||
"books.draft_entry",
|
||||
json!({"date": "2026-02-10", "description": "Waiting",
|
||||
"no_party_reason": "test"}),
|
||||
),
|
||||
] {
|
||||
let refused = a.call(tool, args).unwrap_err();
|
||||
assert!(refused.starts_with("format_upgrade_pending"), "{refused}");
|
||||
assert!(refused.contains("nothing can be written"), "{refused}");
|
||||
}
|
||||
assert_eq!(journal(&dir), before, "a refusal journals nothing");
|
||||
// A document carrying none of the new fields posts as before, and
|
||||
// files its copy; it takes no number (an older version reads it).
|
||||
let plain = a
|
||||
.call(
|
||||
"books.create_invoice",
|
||||
json!({"customer": customer.to_string(), "date": "2026-02-10", "due_date": "2026-03-12",
|
||||
"lines": line, "confirmed": true}),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(plain.get("number").is_none(), "{plain}");
|
||||
assert_eq!(plain["total"], "500.00");
|
||||
|
||||
// The go-ahead.
|
||||
let mut words = home.words("books");
|
||||
@@ -664,6 +667,12 @@ fn documents_v2_refused_until_consent() {
|
||||
let (code, shown) = home.at_terminal(&words, &[PASS]);
|
||||
assert_eq!(code, 0, "{shown}");
|
||||
assert_eq!(format_lines(&dir), 1, "the format moved once");
|
||||
let customer = a
|
||||
.call("books.add_customer", json!({"name": "Harbor Coffee"}))
|
||||
.unwrap()["id"]
|
||||
.clone();
|
||||
let mut with_terms = with_terms;
|
||||
with_terms["customer"] = json!(customer.to_string());
|
||||
let made = a.call("books.create_invoice", with_terms).unwrap();
|
||||
assert_eq!(made["number"], "INV-0001", "{made}");
|
||||
assert_eq!(made["terms"], "Net 30", "{made}");
|
||||
@@ -700,15 +709,17 @@ fn copy_private(from: &Path, to: &Path) {
|
||||
/// ```text
|
||||
/// INVARIANTS:
|
||||
/// 1. Before consent: the books open and are served, waiting; P2's
|
||||
/// database is never written; what P2 can read is written, and every
|
||||
/// write P2 would refuse or misread is refused, journaling nothing
|
||||
/// (a setting key, a tax category, a depreciation catch-up, a members
|
||||
/// close counted from the count's start, an invoice's or bill's line
|
||||
/// naming its project).
|
||||
/// database is never written; they are read as ever and take no
|
||||
/// write at all (D-89, WB-format-11: every write is one transaction,
|
||||
/// and books written before that can't keep it), every one refused
|
||||
/// with the upgrade remedy, journaling nothing.
|
||||
/// 2. The consent backup holds the books exactly as they were, keys and
|
||||
/// vault too; the upgrade is one line after P2's, byte for byte.
|
||||
/// 3. After it: the same figures, and every refused write is made; the
|
||||
/// books verify; P2's database is still byte for byte.
|
||||
/// 3. After it: the same figures, and every write is made, those P2
|
||||
/// would have refused or misread among them (a setting key, a tax
|
||||
/// category, a depreciation catch-up, a members close counted from
|
||||
/// the count's start, an invoice's or bill's line naming its
|
||||
/// project); the books verify; P2's database is still byte for byte.
|
||||
/// ```
|
||||
#[test]
|
||||
fn books_p2_served_cut_over_whole() {
|
||||
@@ -729,11 +740,9 @@ fn books_p2_served_cut_over_whole() {
|
||||
let mut a = Agent::start(&home, "acme");
|
||||
let start = a.call("books.start", json!({})).unwrap();
|
||||
assert_eq!(start["format_upgrade"]["format"], 2, "{start}");
|
||||
let verified = a.call("books.verify", json!({})).unwrap();
|
||||
assert_eq!(verified["status"], "ok", "{verified}");
|
||||
assert_eq!(verified["events"], 470);
|
||||
assert_eq!(verified["database"], ledger_store::db_file());
|
||||
assert_eq!(verified["other_databases"], json!(["wanderbooks.db"]));
|
||||
// (books.verify can rebuild the projection: a write, so it waits for
|
||||
// the go-ahead like every other, and is asked after it, below.)
|
||||
assert_eq!(journal(&dir).iter().filter(|b| **b == b'\n').count(), 470);
|
||||
let figures = |a: &mut Agent| {
|
||||
[
|
||||
a.call("books.trial_balance", json!({"as_of": "2025-12-31"})),
|
||||
@@ -747,7 +756,68 @@ fn books_p2_served_cut_over_whole() {
|
||||
};
|
||||
let before = figures(&mut a);
|
||||
|
||||
// INVARIANT 1: what P2 reads is written; the rest waits.
|
||||
// INVARIANT 1 (D-89): the books take no write before the go-ahead,
|
||||
// whatever the write, and journal nothing for the refusal.
|
||||
let waiting = journal(&dir);
|
||||
for (tool, args) in [
|
||||
(
|
||||
"books.add_account",
|
||||
json!({"code": "6600", "name": "Travel", "account_type": "expense"}),
|
||||
),
|
||||
(
|
||||
"books.create_period",
|
||||
json!({"name": "2025-Q2", "start": "2025-04-01", "end": "2025-06-30"}),
|
||||
),
|
||||
("books.add_project", json!({"name": "Lighthouse"})),
|
||||
("books.add_customer", json!({"name": "Ridgeway Co"})),
|
||||
(
|
||||
"books.draft_entry",
|
||||
json!({"date": "2026-02-12", "description": "Waiting for the go-ahead",
|
||||
"no_party_reason": "test"}),
|
||||
),
|
||||
(
|
||||
"books.raise_item",
|
||||
json!({"title": "Ask the CPA", "decided_by": "Avery Quill"}),
|
||||
),
|
||||
] {
|
||||
let e = a.call(tool, args).unwrap_err();
|
||||
assert!(e.starts_with("format_upgrade_pending"), "{tool}: {e}");
|
||||
assert!(e.contains("nothing can be written"), "{tool}: {e}");
|
||||
}
|
||||
assert_eq!(journal(&dir), waiting, "a refusal journals nothing");
|
||||
assert!(journal(&dir).starts_with(&p2_journal));
|
||||
// The books are read as ever.
|
||||
assert_eq!(figures(&mut a), before);
|
||||
|
||||
// INVARIANT 2: the go-ahead.
|
||||
let mut words = home.words("books");
|
||||
words.extend(["upgrade".into(), "acme".into()]);
|
||||
let (code, shown) = home.at_terminal(&words, &[PASS]);
|
||||
assert_eq!(code, 0, "{shown}");
|
||||
let after = journal(&dir);
|
||||
assert!(after.starts_with(&waiting));
|
||||
assert_eq!(
|
||||
format_lines(&dir),
|
||||
2,
|
||||
"P2's declaration, then the upgrade's"
|
||||
);
|
||||
let backup = archive_git(&dir, &["rev-parse", "HEAD"]);
|
||||
assert_eq!(
|
||||
archive_git(&dir, &["show", &format!("{}:journal.jsonl", backup.trim())]).as_bytes(),
|
||||
waiting.as_slice(),
|
||||
"the backup holds the books as they were"
|
||||
);
|
||||
for kept in ["keys/legacy.key", "vault/tin-1.bin", "vault/tin-3.bin"] {
|
||||
let out = Command::new("git")
|
||||
.arg(format!("--git-dir={}", dir.join("archive.git").display()))
|
||||
.args(["show", &format!("{}:{kept}", backup.trim())])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(out.stdout, std::fs::read(dir.join(kept)).unwrap(), "{kept}");
|
||||
}
|
||||
assert_eq!(figures(&mut a), before, "the upgrade moves no figure");
|
||||
|
||||
// INVARIANT 3: every write is taken now: first what P2 could read.
|
||||
a.call(
|
||||
"books.add_account",
|
||||
json!({"code": "6600", "name": "Travel", "account_type": "expense"}),
|
||||
@@ -822,7 +892,6 @@ fn books_p2_served_cut_over_whole() {
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.clone();
|
||||
let waiting = journal(&dir);
|
||||
let refused: Vec<(&str, Value)> = vec![
|
||||
// A source correction (source_revisions, P5): an older version
|
||||
// refuses the type.
|
||||
@@ -921,53 +990,20 @@ fn books_p2_served_cut_over_whole() {
|
||||
json!({"entry_id": 1, "method": {"reasoning_effort": "high"}}),
|
||||
),
|
||||
];
|
||||
for (tool, args) in &refused {
|
||||
let e = a.call(tool, args.clone()).unwrap_err();
|
||||
assert!(e.starts_with("format_upgrade_pending"), "{tool}: {e}");
|
||||
}
|
||||
assert_eq!(journal(&dir), waiting, "a refusal journals nothing");
|
||||
assert!(journal(&dir).starts_with(&p2_journal));
|
||||
assert_eq!(
|
||||
std::fs::read(dir.join(ledger_store::LEGACY_DB_FILE)).unwrap(),
|
||||
p2_db,
|
||||
"P2's database is never written"
|
||||
);
|
||||
|
||||
// INVARIANT 2: the go-ahead.
|
||||
let mut words = home.words("books");
|
||||
words.extend(["upgrade".into(), "acme".into()]);
|
||||
let (code, shown) = home.at_terminal(&words, &[PASS]);
|
||||
assert_eq!(code, 0, "{shown}");
|
||||
let after = journal(&dir);
|
||||
assert!(after.starts_with(&waiting));
|
||||
assert_eq!(
|
||||
format_lines(&dir),
|
||||
2,
|
||||
"P2's declaration, then the upgrade's"
|
||||
);
|
||||
let backup = archive_git(&dir, &["rev-parse", "HEAD"]);
|
||||
assert_eq!(
|
||||
archive_git(&dir, &["show", &format!("{}:journal.jsonl", backup.trim())]).as_bytes(),
|
||||
waiting.as_slice(),
|
||||
"the backup holds the books as they were"
|
||||
);
|
||||
for kept in ["keys/legacy.key", "vault/tin-1.bin", "vault/tin-3.bin"] {
|
||||
let out = Command::new("git")
|
||||
.arg(format!("--git-dir={}", dir.join("archive.git").display()))
|
||||
.args(["show", &format!("{}:{kept}", backup.trim())])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(out.stdout, std::fs::read(dir.join(kept)).unwrap(), "{kept}");
|
||||
}
|
||||
|
||||
// INVARIANT 3.
|
||||
assert_eq!(figures(&mut a), before, "the upgrade moves no figure");
|
||||
// The writes P2 would have refused or misread, made now.
|
||||
for (tool, args) in refused {
|
||||
a.call(tool, args.clone())
|
||||
.unwrap_or_else(|e| panic!("{tool} after the upgrade: {e}"));
|
||||
}
|
||||
let verified = a.call("books.verify", json!({})).unwrap();
|
||||
assert_eq!(verified["status"], "ok", "{verified}");
|
||||
// It counts the lines there were when it ran, all of them: a call that
|
||||
// wrote nothing leaves no closing line of its own.
|
||||
let events = verified["events"].as_u64().unwrap();
|
||||
let on_disk = journal(&dir).iter().filter(|b| **b == b'\n').count() as u64;
|
||||
assert!(events > 470 && events == on_disk, "{events} of {on_disk}");
|
||||
assert_eq!(verified["database"], ledger_store::db_file());
|
||||
assert_eq!(verified["other_databases"], json!(["wanderbooks.db"]));
|
||||
assert_eq!(
|
||||
std::fs::read(dir.join(ledger_store::LEGACY_DB_FILE)).unwrap(),
|
||||
p2_db,
|
||||
|
||||
@@ -623,7 +623,8 @@ async fn raw_upload(http: &reqwest::Client, session: &str, bytes: &[u8], name: &
|
||||
let begin = json!({"jsonrpc": "2.0", "id": 9, "method": "tools/call", "params": {
|
||||
"name": "books.begin_upload", "arguments": {
|
||||
"sha256": ledger_store::journal::sha256_hex(bytes), "size": bytes.len(),
|
||||
"mime_type": "application/pdf", "file_name": name, "purpose": "document"}}});
|
||||
"mime_type": "application/pdf", "file_name": name, "purpose": "document",
|
||||
"request_key": common::fresh_request_key()}}});
|
||||
let r = http
|
||||
.post("http://localhost/b/acme/mcp")
|
||||
.header("content-type", "application/json")
|
||||
@@ -681,7 +682,8 @@ async fn a_call_whose_client_hung_up_finishes_before_the_close() {
|
||||
let upload = raw_upload(&http, &session, &bytes, "big.pdf").await;
|
||||
let call = json!({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {
|
||||
"name": "books.file_document", "arguments": {
|
||||
"category": "formation", "upload_id": upload}}});
|
||||
"category": "formation", "upload_id": upload,
|
||||
"request_key": common::fresh_request_key()}}});
|
||||
let response = http
|
||||
.post("http://localhost/b/acme/mcp")
|
||||
.header("content-type", "application/json")
|
||||
|
||||
@@ -787,7 +787,7 @@ fn tin_bearing_files_are_refused_when_given_back_to_be_filed() {
|
||||
let handed_over = [w9_back, mcp.handed(&ws["csv"]), mcp.handed(&pkg["file"])];
|
||||
// Given back, each is refused by its bytes, by every way a file is
|
||||
// filed.
|
||||
let journal = books.journal();
|
||||
let journal = books.journal_raw();
|
||||
for (n, bytes) in handed_over.iter().enumerate() {
|
||||
// One upload, refused by each tool and so left for the next.
|
||||
let up = mcp.upload(bytes, "receipt.pdf", "application/pdf", "receipt");
|
||||
@@ -805,7 +805,20 @@ fn tin_bearing_files_are_refused_when_given_back_to_be_filed() {
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(books.journal(), journal, "a refusal stored something");
|
||||
// (Each upload begun is a call, with its closing line: those only.)
|
||||
let calls_only = |j: Vec<u8>| -> Vec<String> {
|
||||
String::from_utf8(j)
|
||||
.unwrap()
|
||||
.lines()
|
||||
.filter(|l| !l.contains(r#""type":"call.closed""#))
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(
|
||||
calls_only(books.journal()),
|
||||
calls_only(journal),
|
||||
"a refusal stored something"
|
||||
);
|
||||
// Without TINs, the 1099 worksheet is an ordinary file: it may be
|
||||
// filed like any other.
|
||||
let plain = mcp.call("books.vendor_1099", json!({"year": 2026, "csv": true}));
|
||||
@@ -1765,7 +1778,8 @@ fn close_period_shows_each_members_running_split() {
|
||||
fn old_books_name_each_closes_rule_and_true_up_at_the_next_close() {
|
||||
// Books P1 kept, which P2 moved to its journal format (format 2, none
|
||||
// of the features since), left in a data root, with their members set
|
||||
// as an agent sets them: books waiting for their format upgrade.
|
||||
// as an agent sets them once they are upgraded: books waiting for
|
||||
// their format upgrade, which (D-89) take no write until then.
|
||||
let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../ledger-store/tests/fixtures/old-books/x_member_closes");
|
||||
let books = Books::placed("members-old", &fixture);
|
||||
@@ -1775,13 +1789,6 @@ fn old_books_name_each_closes_rule_and_true_up_at_the_next_close() {
|
||||
.declare_journal_format(2, &[])
|
||||
.unwrap();
|
||||
books.start();
|
||||
books.settle(
|
||||
"[company]\ntax_form = \"1065\"\n\n\
|
||||
[[company.members]]\nname = \"Ann\"\nshare = \"50%\"\ncapital_account = \"3000\"\n\
|
||||
distribution_account = \"3100\"\n\n\
|
||||
[[company.members]]\nname = \"Bo\"\nshare = \"50%\"\ncapital_account = \"3001\"\n\n\
|
||||
[books]\nreceipt_threshold = \"10000\"\n",
|
||||
);
|
||||
let mut mcp = Mcp::spawn(&books);
|
||||
init(&mut mcp);
|
||||
let rules = |mcp: &mut Mcp| -> Vec<Value> {
|
||||
@@ -1805,6 +1812,32 @@ fn old_books_name_each_closes_rule_and_true_up_at_the_next_close() {
|
||||
let mut want: Vec<Value> = old.iter().map(|r| json!(r)).collect();
|
||||
want.extend([Value::Null, json!("members_run"), json!("members_run")]);
|
||||
assert_eq!(rules(&mut mcp), want);
|
||||
// Read as ever; no write is taken (D-89), whatever it is.
|
||||
let refused = mcp.call_err(
|
||||
"books.draft_entry",
|
||||
json!({"date": "2026-12-10", "description": "two cents"}),
|
||||
);
|
||||
assert!(refused.starts_with("format_upgrade_pending:"), "{refused}");
|
||||
// The owner's go-ahead, as the app gives it (ledger-gui owner.rs, after
|
||||
// the passphrase and a verified backup): the server stopped, the books
|
||||
// moved to this version's format, and served again.
|
||||
drop(mcp);
|
||||
books.stop();
|
||||
ledger_store::Store::open(&books.dir())
|
||||
.unwrap()
|
||||
.upgrade_format()
|
||||
.unwrap()
|
||||
.expect("old books wait for the upgrade");
|
||||
books.start();
|
||||
books.settle(
|
||||
"[company]\ntax_form = \"1065\"\n\n\
|
||||
[[company.members]]\nname = \"Ann\"\nshare = \"50%\"\ncapital_account = \"3000\"\n\
|
||||
distribution_account = \"3100\"\n\n\
|
||||
[[company.members]]\nname = \"Bo\"\nshare = \"50%\"\ncapital_account = \"3001\"\n\n\
|
||||
[books]\nreceipt_threshold = \"10000\"\n",
|
||||
);
|
||||
let mut mcp = Mcp::spawn(&books);
|
||||
init(&mut mcp);
|
||||
|
||||
let e = mcp.call(
|
||||
"books.draft_entry",
|
||||
@@ -1844,29 +1877,6 @@ fn old_books_name_each_closes_rule_and_true_up_at_the_next_close() {
|
||||
preview["lines"],
|
||||
json!(["Debit 4000 0.02", "Credit 3001 0.02"])
|
||||
);
|
||||
// Books an older version wrote: the close counted from its regime's
|
||||
// start waits for the owner's go-ahead (D-39), which no tool gives.
|
||||
let refused = mcp.call_err(
|
||||
"books.close_period",
|
||||
json!({"period_id": dec["period_id"], "confirmed": true}),
|
||||
);
|
||||
assert!(
|
||||
refused.starts_with("format_upgrade_pending:") && refused.contains("members_cumulative"),
|
||||
"{refused}"
|
||||
);
|
||||
// The owner's go-ahead, as the app gives it (ledger-gui owner.rs, after
|
||||
// the passphrase and a verified backup): the server stopped, the books
|
||||
// moved to this version's format, and served again.
|
||||
drop(mcp);
|
||||
books.stop();
|
||||
ledger_store::Store::open(&books.dir())
|
||||
.unwrap()
|
||||
.upgrade_format()
|
||||
.unwrap()
|
||||
.expect("old books wait for the upgrade");
|
||||
books.start();
|
||||
let mut mcp = Mcp::spawn(&books);
|
||||
init(&mut mcp);
|
||||
let closed = mcp.call(
|
||||
"books.close_period",
|
||||
json!({"period_id": dec["period_id"], "confirmed": true}),
|
||||
@@ -2988,9 +2998,11 @@ fn rename_account_end_to_end_defect_15() {
|
||||
);
|
||||
assert!(err.contains(says), "{name:?}: {err}");
|
||||
}
|
||||
// (The first verify is a call too: its own closing line is the one
|
||||
// line the second counts more; the refusals wrote none.)
|
||||
assert_eq!(
|
||||
mcp.call("books.verify", json!({"blobs": false}))["events"],
|
||||
json!(events),
|
||||
json!(events + 1),
|
||||
"refusals write nothing"
|
||||
);
|
||||
let out = mcp.call(
|
||||
@@ -3009,8 +3021,10 @@ fn rename_account_end_to_end_defect_15() {
|
||||
let after = mcp.call("books.verify", json!({"blobs": false}));
|
||||
assert_eq!(after["status"], "ok");
|
||||
// New books declare account_renamed (with the rest of this version's
|
||||
// format) as they are created: the rename journals only itself.
|
||||
assert_eq!(after["events"], json!(events + 1), "the rename");
|
||||
// format) as they are created: the rename journals only itself, in
|
||||
// its frame (begun, the rename, closed), after the two verifies'
|
||||
// closing lines.
|
||||
assert_eq!(after["events"], json!(events + 1 + 1 + 3), "the rename");
|
||||
let chart = mcp.call("books.chart", json!({}));
|
||||
let acct = chart["accounts"]
|
||||
.as_array()
|
||||
@@ -3300,7 +3314,7 @@ fn files_pass_only_by_handle_in_and_out() {
|
||||
);
|
||||
mcp.call("books.import_chart_csv", json!({"upload_id": chart}));
|
||||
// In: an inline file is refused as unknown, storing nothing.
|
||||
let journal = books.journal();
|
||||
let journal = books.journal_raw();
|
||||
for (name, args) in [
|
||||
(
|
||||
"books.attach_receipt",
|
||||
@@ -3320,7 +3334,11 @@ fn files_pass_only_by_handle_in_and_out() {
|
||||
"{name}: {resp}"
|
||||
);
|
||||
}
|
||||
assert_eq!(books.journal(), journal, "an inline file stored something");
|
||||
assert_eq!(
|
||||
books.journal_raw(),
|
||||
journal,
|
||||
"an inline file stored something"
|
||||
);
|
||||
// A posted entry with its receipt, and an asset with its tag.
|
||||
let receipt = b"%PDF-1.4 a receipt for the laptop";
|
||||
let e = mcp.call(
|
||||
|
||||
@@ -372,6 +372,8 @@ impl Agent {
|
||||
}
|
||||
|
||||
fn send(&mut self, message: Value) {
|
||||
// A tool call carries the request key every write needs (D-88).
|
||||
let message = common::with_request_key(&message.to_string());
|
||||
let stdin = self.run.child.stdin.as_mut().unwrap();
|
||||
writeln!(stdin, "{message}").unwrap();
|
||||
stdin.flush().unwrap();
|
||||
@@ -1383,7 +1385,8 @@ fn a_call_cancelled_at_once_is_never_made() {
|
||||
json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {
|
||||
"name": "books.add_account",
|
||||
"arguments": {"code": format!("{}", 1000 + k), "name": format!("A{k}"),
|
||||
"account_type": "asset"}}}),
|
||||
"account_type": "asset",
|
||||
"request_key": common::fresh_request_key()}}}),
|
||||
json!({"jsonrpc": "2.0", "method": "notifications/cancelled",
|
||||
"params": {"requestId": id}})
|
||||
)
|
||||
|
||||
@@ -71,7 +71,13 @@ fn books_toml(dir: &Path, company: &str, books_extra: &str) -> PathBuf {
|
||||
|
||||
impl Mcp {
|
||||
fn start(dir: &TestDir, toml: &Path) -> Self {
|
||||
let wire = dir.start(Some(&std::fs::read_to_string(toml).unwrap()));
|
||||
Self::start_settings(dir, Some(&std::fs::read_to_string(toml).unwrap()))
|
||||
}
|
||||
|
||||
/// [`Mcp::start`] with these settings, or none (books that take no
|
||||
/// write, D-89, can't be given any).
|
||||
fn start_settings(dir: &TestDir, settings: Option<&str>) -> Self {
|
||||
let wire = dir.start(settings);
|
||||
let mut mcp = Self {
|
||||
books_dir: None,
|
||||
wire,
|
||||
@@ -101,7 +107,14 @@ impl Mcp {
|
||||
mcp
|
||||
}
|
||||
|
||||
/// The journal, without the frames of tool calls (D-88): the events.
|
||||
fn journal(&self) -> Vec<u8> {
|
||||
common::without_call_lines(&self.journal_raw())
|
||||
}
|
||||
|
||||
/// The journal, byte for byte: what a check that a refusal or a
|
||||
/// preview "journaled nothing" compares, so a stray frame line is seen.
|
||||
fn journal_raw(&self) -> Vec<u8> {
|
||||
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -145,7 +158,7 @@ impl Mcp {
|
||||
/// Call a tool; a refusal must leave the journal unchanged, a success
|
||||
/// must match the outputSchema.
|
||||
fn tool(&mut self, name: &str, args: Value) -> Out {
|
||||
let before = self.journal();
|
||||
let before = self.journal_raw();
|
||||
let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone());
|
||||
let out = if let Some(err) = resp.get("error") {
|
||||
Out::RpcErr(err.clone())
|
||||
@@ -175,7 +188,7 @@ impl Mcp {
|
||||
};
|
||||
if out.refused() {
|
||||
assert!(
|
||||
self.journal() == before,
|
||||
self.journal_raw() == before,
|
||||
"refused {name} {args} changed the journal ({out:?})"
|
||||
);
|
||||
}
|
||||
@@ -202,10 +215,10 @@ impl Mcp {
|
||||
|
||||
/// `ok`, and the journal must not change (read-only tools).
|
||||
fn read_only(&mut self, name: &str, args: Value) -> Value {
|
||||
let before = self.journal();
|
||||
let before = self.journal_raw();
|
||||
let v = self.ok(name, args);
|
||||
assert!(
|
||||
self.journal() == before,
|
||||
self.journal_raw() == before,
|
||||
"read-only {name} changed the journal"
|
||||
);
|
||||
v
|
||||
@@ -300,6 +313,12 @@ fn books_in(name: &str, p2: bool) -> Mcp {
|
||||
.unwrap();
|
||||
}
|
||||
let toml = books_toml(&dir, "Spec Co", "financing_accounts = [\"2100\"]\n");
|
||||
if p2 {
|
||||
// Books that take no write (D-89): no settings, no chart.
|
||||
let mut m = Mcp::start_settings(&dir, None);
|
||||
m.books_dir = Some(dir);
|
||||
return m;
|
||||
}
|
||||
let mut m = Mcp::start(&dir, &toml);
|
||||
m.accounts(CHART);
|
||||
m.books_dir = Some(dir);
|
||||
@@ -321,6 +340,7 @@ impl Mcp {
|
||||
.unwrap()
|
||||
.expect("P2's books wait for the upgrade");
|
||||
let mut m = Mcp::start(&dir, &dir.join("wanderbooks.toml"));
|
||||
m.accounts(CHART);
|
||||
m.books_dir = Some(dir);
|
||||
m
|
||||
}
|
||||
@@ -623,18 +643,17 @@ fn set_w9_asks_for_the_w9_flags_feature_before_its_first_line() {
|
||||
let w9 = json!({"party": "Harbor Design LLC", "received_on": "2026-03-02",
|
||||
"entity_type": "LLC (partnership)", "tin_last4": "4321", "kept_at": "CPA portal"});
|
||||
let mut m = books_in("set-w9-feature", true);
|
||||
let why = m.refuse("books.set_w9", w9.clone());
|
||||
assert!(why.starts_with("format_upgrade_pending:"), "{why}");
|
||||
assert!(why.contains("nothing can be written"), "{why}");
|
||||
assert_eq!(m.count("party.w9_set"), 0, "nothing half done");
|
||||
let mut m = m.upgraded();
|
||||
m.add_party("Harbor Design LLC", &["contractor"]);
|
||||
m.ok("books.add_vendor", json!({"name": "Harbor Design LLC"}));
|
||||
let why = m.refuse("books.set_w9", w9.clone());
|
||||
assert!(
|
||||
why.starts_with("format_upgrade_pending:") && why.contains("vendor_1099_decisions"),
|
||||
"{why}"
|
||||
);
|
||||
assert_eq!(m.count("party.w9_set"), 0, "nothing half done");
|
||||
let mut fresh = books("set-w9-feature-new");
|
||||
fresh.add_party("Harbor Design LLC", &["contractor"]);
|
||||
fresh.ok("books.add_vendor", json!({"name": "Harbor Design LLC"}));
|
||||
for mut m in [m.upgraded(), fresh] {
|
||||
for mut m in [m, fresh] {
|
||||
let before = m.journal_types().len();
|
||||
m.ok("books.set_w9", w9.clone());
|
||||
let added = m.journal_types()[before..].to_vec();
|
||||
|
||||
@@ -106,7 +106,14 @@ impl Mcp {
|
||||
mcp
|
||||
}
|
||||
|
||||
/// The journal, without the frames of tool calls (D-88): the events.
|
||||
fn journal(&self) -> Vec<u8> {
|
||||
common::without_call_lines(&self.journal_raw())
|
||||
}
|
||||
|
||||
/// The journal, byte for byte: what a check that a refusal or a
|
||||
/// preview "journaled nothing" compares, so a stray frame line is seen.
|
||||
fn journal_raw(&self) -> Vec<u8> {
|
||||
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -150,7 +157,7 @@ impl Mcp {
|
||||
/// Call a tool; a refusal must leave the journal unchanged, a success
|
||||
/// must match the outputSchema.
|
||||
fn tool(&mut self, name: &str, args: Value) -> Out {
|
||||
let before = self.journal();
|
||||
let before = self.journal_raw();
|
||||
let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone());
|
||||
let out = if let Some(err) = resp.get("error") {
|
||||
Out::RpcErr(err.clone())
|
||||
@@ -180,7 +187,7 @@ impl Mcp {
|
||||
};
|
||||
if out.refused() {
|
||||
assert!(
|
||||
self.journal() == before,
|
||||
self.journal_raw() == before,
|
||||
"refused {name} {args} changed the journal ({out:?})"
|
||||
);
|
||||
}
|
||||
@@ -207,10 +214,10 @@ impl Mcp {
|
||||
|
||||
/// `ok`, and the journal must not change (read-only tools).
|
||||
fn read_only(&mut self, name: &str, args: Value) -> Value {
|
||||
let before = self.journal();
|
||||
let before = self.journal_raw();
|
||||
let v = self.ok(name, args);
|
||||
assert!(
|
||||
self.journal() == before,
|
||||
self.journal_raw() == before,
|
||||
"read-only {name} changed the journal"
|
||||
);
|
||||
v
|
||||
@@ -1593,7 +1600,7 @@ fn a_disposal_inside_a_posted_month_takes_back_the_extra_days() {
|
||||
fn run_depreciation_skips_a_month_that_rounds_to_nothing() {
|
||||
let mut m = books("zero-month");
|
||||
let (a, _) = m.register_ok(json!({"cost": "0.01", "useful_life_months": 3}));
|
||||
let before = m.journal();
|
||||
let before = m.journal_raw();
|
||||
let r = m.ok("books.run_depreciation", json!({"period": "2026-01"}));
|
||||
assert_eq!(r["runs"], json!([]));
|
||||
let skipped = r["skipped"].as_array().unwrap();
|
||||
@@ -1606,7 +1613,7 @@ fn run_depreciation_skips_a_month_that_rounds_to_nothing() {
|
||||
.contains("rounds to nothing"),
|
||||
"{r}"
|
||||
);
|
||||
assert_eq!(m.journal(), before, "nothing journaled");
|
||||
assert_eq!(m.journal_raw(), before, "nothing journaled");
|
||||
let r = m.ok("books.run_depreciation", json!({"period": "2026-02"}));
|
||||
assert_eq!(canon(r["runs"][0]["amount"].as_str().unwrap()), "0.01");
|
||||
}
|
||||
|
||||
@@ -110,7 +110,14 @@ impl Mcp {
|
||||
mcp
|
||||
}
|
||||
|
||||
/// The journal, without the frames of tool calls (D-88): the events.
|
||||
fn journal(&self) -> Vec<u8> {
|
||||
common::without_call_lines(&self.journal_raw())
|
||||
}
|
||||
|
||||
/// The journal, byte for byte: what a check that a refusal or a
|
||||
/// preview "journaled nothing" compares, so a stray frame line is seen.
|
||||
fn journal_raw(&self) -> Vec<u8> {
|
||||
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -156,7 +163,7 @@ impl Mcp {
|
||||
/// Call a tool; a refusal must leave the journal unchanged, a success
|
||||
/// must match the outputSchema.
|
||||
fn tool(&mut self, name: &str, args: Value) -> Out {
|
||||
let before = self.journal();
|
||||
let before = self.journal_raw();
|
||||
let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone());
|
||||
let out = if let Some(err) = resp.get("error") {
|
||||
Out::RpcErr(err.clone())
|
||||
@@ -186,7 +193,7 @@ impl Mcp {
|
||||
};
|
||||
if out.refused() {
|
||||
assert!(
|
||||
self.journal() == before,
|
||||
self.journal_raw() == before,
|
||||
"refused {name} {args} changed the journal ({out:?})"
|
||||
);
|
||||
}
|
||||
@@ -213,10 +220,10 @@ impl Mcp {
|
||||
|
||||
/// `ok`, and the journal must not change (read-only tools).
|
||||
fn read_only(&mut self, name: &str, args: Value) -> Value {
|
||||
let before = self.journal();
|
||||
let before = self.journal_raw();
|
||||
let v = self.ok(name, args);
|
||||
assert!(
|
||||
self.journal() == before,
|
||||
self.journal_raw() == before,
|
||||
"read-only {name} changed the journal"
|
||||
);
|
||||
v
|
||||
|
||||
@@ -224,7 +224,9 @@ impl Mcp {
|
||||
mcp
|
||||
}
|
||||
|
||||
fn journal(&self) -> Vec<u8> {
|
||||
/// The journal, byte for byte: what a check that a refusal or a
|
||||
/// preview "journaled nothing" compares, so a stray frame line is seen.
|
||||
fn journal_raw(&self) -> Vec<u8> {
|
||||
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -285,7 +287,7 @@ impl Mcp {
|
||||
|
||||
/// Call a tool and check invariants 1, 2, 3 and 7 on the outcome.
|
||||
fn tool(&mut self, name: &str, args: Value) -> Out {
|
||||
let before = self.journal();
|
||||
let before = self.journal_raw();
|
||||
let files = self.read_only(name).then(|| self.data_files());
|
||||
let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone());
|
||||
let out = if let Some(err) = resp.get("error") {
|
||||
@@ -305,13 +307,13 @@ impl Mcp {
|
||||
};
|
||||
if out.refused() {
|
||||
assert!(
|
||||
self.journal() == before,
|
||||
self.journal_raw() == before,
|
||||
"invariant 2: refused {name} {args} changed the journal ({out:?})"
|
||||
);
|
||||
}
|
||||
if let Some(files) = files {
|
||||
assert!(
|
||||
self.journal() == before,
|
||||
self.journal_raw() == before,
|
||||
"readOnlyHint: {name} {args} changed the journal"
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -1950,16 +1952,16 @@ fn inv4_post_and_reverse_preview_without_confirmed() {
|
||||
json!({"entry_id": e, "confirmed": false}),
|
||||
json!({"entry_id": e, "confirmed": null}),
|
||||
] {
|
||||
let before = m.journal();
|
||||
let before = m.journal_raw();
|
||||
let p = m.ok("books.post_entry", args.clone());
|
||||
assert_eq!(p["status"], "preview", "{args}: {p}");
|
||||
assert!(m.journal() == before, "post_entry preview {args} wrote");
|
||||
assert!(m.journal_raw() == before, "post_entry preview {args} wrote");
|
||||
assert_eq!(m.entry_status(e), "draft");
|
||||
}
|
||||
let before = m.journal();
|
||||
let before = m.journal_raw();
|
||||
let posted = m.post(e).ok("confirmed post");
|
||||
assert_eq!(posted["status"], "posted");
|
||||
assert!(m.journal() != before, "confirmed post wrote nothing");
|
||||
assert!(m.journal_raw() != before, "confirmed post wrote nothing");
|
||||
assert_eq!(m.entry_status(e), "posted");
|
||||
|
||||
let rev = json!({"entry_id": e, "date": "2026-04-02", "description": "undo"});
|
||||
@@ -1968,17 +1970,20 @@ fn inv4_post_and_reverse_preview_without_confirmed() {
|
||||
args.as_object_mut()
|
||||
.unwrap()
|
||||
.extend(extra.as_object().unwrap().clone());
|
||||
let before = m.journal();
|
||||
let before = m.journal_raw();
|
||||
let p = m.ok("books.reverse_entry", args.clone());
|
||||
assert_eq!(p["status"], "preview", "{args}: {p}");
|
||||
assert!(m.journal() == before, "reverse_entry preview {args} wrote");
|
||||
assert!(
|
||||
m.journal_raw() == before,
|
||||
"reverse_entry preview {args} wrote"
|
||||
);
|
||||
}
|
||||
let mut args = rev;
|
||||
args["confirmed"] = json!(true);
|
||||
let before = m.journal();
|
||||
let before = m.journal_raw();
|
||||
let r = m.ok("books.reverse_entry", args);
|
||||
assert_eq!(r["status"], "posted", "{r}");
|
||||
assert!(m.journal() != before);
|
||||
assert!(m.journal_raw() != before);
|
||||
let tb = m.ok("books.trial_balance", json!({"as_of": "2026-12-31"}));
|
||||
assert_eq!(tb["balanced"], true);
|
||||
}
|
||||
@@ -1999,7 +2004,7 @@ fn a_reversal_dated_before_its_entry_is_refused_in_preview_and_post() {
|
||||
);
|
||||
m.attach(Some(e), b"rent receipt");
|
||||
m.post(e).ok("post");
|
||||
let before = m.journal();
|
||||
let before = m.journal_raw();
|
||||
for confirmed in [None, Some(false), Some(true)] {
|
||||
let mut args = json!({"entry_id": e, "date": "2026-05-09", "description": "early"});
|
||||
if let Some(c) = confirmed {
|
||||
@@ -2011,7 +2016,7 @@ fn a_reversal_dated_before_its_entry_is_refused_in_preview_and_post() {
|
||||
"{why}"
|
||||
);
|
||||
}
|
||||
assert!(m.journal() == before, "a refused reversal wrote");
|
||||
assert!(m.journal_raw() == before, "a refused reversal wrote");
|
||||
let p = m.ok(
|
||||
"books.reverse_entry",
|
||||
json!({"entry_id": e, "date": "2026-05-10", "description": "same day"}),
|
||||
@@ -2144,7 +2149,7 @@ fn inv5_bad_threshold_refused_when_set() {
|
||||
let dir = test_dir("inv5-set");
|
||||
let toml = books_toml(&dir, "25.00", "");
|
||||
let mut m = Mcp::start(&dir, &toml);
|
||||
let before = m.journal();
|
||||
let before = m.journal_raw();
|
||||
assert!(!before.is_empty(), "the books keep a journal");
|
||||
for bad in ["-1", "abc", "-0.01", "", "1,000", "ten"] {
|
||||
m.refuse(
|
||||
@@ -2153,7 +2158,11 @@ fn inv5_bad_threshold_refused_when_set() {
|
||||
"decided_by": "Test Owner"}),
|
||||
);
|
||||
}
|
||||
assert_eq!(m.journal(), before, "a refused threshold journals nothing");
|
||||
assert_eq!(
|
||||
m.journal_raw(),
|
||||
before,
|
||||
"a refused threshold journals nothing"
|
||||
);
|
||||
let rule = m.ok("books.settings", json!({}))["receipt_rule"].clone();
|
||||
assert!(rule.as_str().unwrap().contains("25.00"), "{rule}");
|
||||
}
|
||||
|
||||
@@ -107,7 +107,14 @@ impl Mcp {
|
||||
mcp
|
||||
}
|
||||
|
||||
/// The journal, without the frames of tool calls (D-88): the events.
|
||||
fn journal(&self) -> Vec<u8> {
|
||||
common::without_call_lines(&self.journal_raw())
|
||||
}
|
||||
|
||||
/// The journal, byte for byte: what a check that a refusal or a
|
||||
/// preview "journaled nothing" compares, so a stray frame line is seen.
|
||||
fn journal_raw(&self) -> Vec<u8> {
|
||||
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -151,7 +158,7 @@ impl Mcp {
|
||||
/// Call a tool; a refusal must leave the journal unchanged, a success
|
||||
/// must match the outputSchema.
|
||||
fn tool(&mut self, name: &str, args: Value) -> Out {
|
||||
let before = self.journal();
|
||||
let before = self.journal_raw();
|
||||
let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone());
|
||||
let out = if let Some(err) = resp.get("error") {
|
||||
Out::RpcErr(err.clone())
|
||||
@@ -181,7 +188,7 @@ impl Mcp {
|
||||
};
|
||||
if out.refused() {
|
||||
assert!(
|
||||
self.journal() == before,
|
||||
self.journal_raw() == before,
|
||||
"refused {name} {args} changed the journal ({out:?})"
|
||||
);
|
||||
}
|
||||
@@ -208,10 +215,10 @@ impl Mcp {
|
||||
|
||||
/// `ok`, and the journal must not change (read-only tools).
|
||||
fn read_only(&mut self, name: &str, args: Value) -> Value {
|
||||
let before = self.journal();
|
||||
let before = self.journal_raw();
|
||||
let v = self.ok(name, args);
|
||||
assert!(
|
||||
self.journal() == before,
|
||||
self.journal_raw() == before,
|
||||
"read-only {name} changed the journal"
|
||||
);
|
||||
v
|
||||
@@ -1224,13 +1231,13 @@ fn require_refuses_until_tagged_or_marked_none() {
|
||||
json!({}),
|
||||
&[("6999", "debit", "5.00"), ("1000", "credit", "5.00")],
|
||||
);
|
||||
let before = m.journal();
|
||||
let before = m.journal_raw();
|
||||
let e = m.refuse(
|
||||
"books.post_entry",
|
||||
json!({"entry_id": id, "confirmed": true}),
|
||||
);
|
||||
assert!(e.contains("party_required"), "{e}");
|
||||
assert_eq!(m.journal(), before, "refusal journals nothing");
|
||||
assert_eq!(m.journal_raw(), before, "refusal journals nothing");
|
||||
m.ok(
|
||||
"books.set_entry_party",
|
||||
json!({"entry_id": id, "party": bank.to_string()}),
|
||||
@@ -1608,10 +1615,10 @@ fn under_require_engine_postings_name_their_counterparty() {
|
||||
let sale = json!({"asset_id": sold, "date": "2026-06-30", "proceeds": "500.00",
|
||||
"proceeds_account": "1000", "gain_loss_account": "7100",
|
||||
"confirmed": true});
|
||||
let before = m.journal();
|
||||
let before = m.journal_raw();
|
||||
let e = m.refuse("books.dispose_asset", sale.clone());
|
||||
assert!(e.contains("party_required"), "{e}");
|
||||
assert!(m.journal() == before, "refused, nothing journaled");
|
||||
assert!(m.journal_raw() == before, "refused, nothing journaled");
|
||||
let mut with_buyer = sale;
|
||||
with_buyer["buyer"] = json!("Buyer Co");
|
||||
let d = m.ok("books.dispose_asset", with_buyer);
|
||||
|
||||
@@ -78,7 +78,13 @@ fn books_toml(dir: &Path, company: &str, books_extra: &str) -> PathBuf {
|
||||
|
||||
impl Mcp {
|
||||
fn start(dir: &TestDir, toml: &Path) -> Self {
|
||||
let wire = dir.start(Some(&std::fs::read_to_string(toml).unwrap()));
|
||||
Self::start_settings(dir, Some(&std::fs::read_to_string(toml).unwrap()))
|
||||
}
|
||||
|
||||
/// [`Mcp::start`] with these settings, or none (books that take no
|
||||
/// write, D-89, can't be given any).
|
||||
fn start_settings(dir: &TestDir, settings: Option<&str>) -> Self {
|
||||
let wire = dir.start(settings);
|
||||
let mut mcp = Self {
|
||||
books_dir: None,
|
||||
wire,
|
||||
@@ -108,7 +114,14 @@ impl Mcp {
|
||||
mcp
|
||||
}
|
||||
|
||||
/// The journal, without the frames of tool calls (D-88): the events.
|
||||
fn journal(&self) -> Vec<u8> {
|
||||
common::without_call_lines(&self.journal_raw())
|
||||
}
|
||||
|
||||
/// The journal, byte for byte: what a check that a refusal or a
|
||||
/// preview "journaled nothing" compares, so a stray frame line is seen.
|
||||
fn journal_raw(&self) -> Vec<u8> {
|
||||
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -152,7 +165,7 @@ impl Mcp {
|
||||
/// Call a tool; a refusal must leave the journal unchanged, a success
|
||||
/// must match the outputSchema.
|
||||
fn tool(&mut self, name: &str, args: Value) -> Out {
|
||||
let before = self.journal();
|
||||
let before = self.journal_raw();
|
||||
let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone());
|
||||
let out = if let Some(err) = resp.get("error") {
|
||||
Out::RpcErr(err.clone())
|
||||
@@ -182,7 +195,7 @@ impl Mcp {
|
||||
};
|
||||
if out.refused() {
|
||||
assert!(
|
||||
self.journal() == before,
|
||||
self.journal_raw() == before,
|
||||
"refused {name} {args} changed the journal ({out:?})"
|
||||
);
|
||||
}
|
||||
@@ -209,10 +222,10 @@ impl Mcp {
|
||||
|
||||
/// `ok`, and the journal must not change (read-only tools).
|
||||
fn read_only(&mut self, name: &str, args: Value) -> Value {
|
||||
let before = self.journal();
|
||||
let before = self.journal_raw();
|
||||
let v = self.ok(name, args);
|
||||
assert!(
|
||||
self.journal() == before,
|
||||
self.journal_raw() == before,
|
||||
"read-only {name} changed the journal"
|
||||
);
|
||||
v
|
||||
@@ -312,6 +325,12 @@ fn books_in(name: &str, p2: bool) -> Mcp {
|
||||
[[company.members]]\nname = \"Tobin Harlow\"\nshare = \"50%\"\ncapital_account = \"3000\"\n\
|
||||
[[company.members]]\nname = \"Morgan Ellis\"\nshare = \"50%\"\ncapital_account = \"3001\"\n",
|
||||
);
|
||||
if p2 {
|
||||
// Books that take no write (D-89): no settings, no chart.
|
||||
let mut m = Mcp::start_settings(&dir, None);
|
||||
m.books_dir = Some(dir);
|
||||
return m;
|
||||
}
|
||||
let mut m = Mcp::start(&dir, &toml);
|
||||
m.accounts(CHART);
|
||||
m.add_party("Tobin Harlow", &["member"]);
|
||||
@@ -336,6 +355,10 @@ impl Mcp {
|
||||
.unwrap()
|
||||
.expect("P2's books wait for the upgrade");
|
||||
let mut m = Mcp::start(&dir, &dir.join("wanderbooks.toml"));
|
||||
m.accounts(CHART);
|
||||
m.add_party("Tobin Harlow", &["member"]);
|
||||
m.add_party("Morgan Ellis", &["member"]);
|
||||
m.add_party("Harbor Bank", &["financial_institution"]);
|
||||
m.books_dir = Some(dir);
|
||||
m
|
||||
}
|
||||
@@ -563,12 +586,12 @@ fn defect24_creditor_of_round_trips_and_a_card_fee_is_not_a_payment() {
|
||||
"nothing declared on the way"
|
||||
);
|
||||
// The same list again changes nothing.
|
||||
let journal = m.journal();
|
||||
let journal = m.journal_raw();
|
||||
m.ok(
|
||||
"books.update_party",
|
||||
json!({"party": "Harbor Bank", "creditor_of": ["2050"]}),
|
||||
);
|
||||
assert!(m.journal() == journal);
|
||||
assert!(m.journal_raw() == journal);
|
||||
assert_eq!(
|
||||
part(&mut m, fee, "Harbor Bank"),
|
||||
(
|
||||
@@ -616,10 +639,8 @@ fn update_party_asks_for_the_creditor_feature_before_its_first_line() {
|
||||
json!({"party": "Harbor Bank", "notes": "the card's issuer", "creditor_of": ["2050"]});
|
||||
let mut m = books_in("feature-first", true);
|
||||
let why = m.refuse("books.update_party", change.clone());
|
||||
assert!(
|
||||
why.starts_with("format_upgrade_pending:") && why.contains("party_creditors"),
|
||||
"{why}"
|
||||
);
|
||||
assert!(why.starts_with("format_upgrade_pending:"), "{why}");
|
||||
assert!(why.contains("nothing can be written"), "{why}");
|
||||
assert_eq!(m.count("party.updated"), 0, "nothing half done");
|
||||
for mut m in [m.upgraded(), books("feature-first-new")] {
|
||||
let start = m.journal_types().len();
|
||||
|
||||
@@ -77,7 +77,13 @@ fn books_toml(dir: &Path, company: &str, books_extra: &str) -> PathBuf {
|
||||
|
||||
impl Mcp {
|
||||
fn start(dir: &TestDir, toml: &Path) -> Self {
|
||||
let wire = dir.start(Some(&std::fs::read_to_string(toml).unwrap()));
|
||||
Self::start_settings(dir, Some(&std::fs::read_to_string(toml).unwrap()))
|
||||
}
|
||||
|
||||
/// [`Mcp::start`] with these settings, or none (books that take no
|
||||
/// write, D-89, can't be given any).
|
||||
fn start_settings(dir: &TestDir, settings: Option<&str>) -> Self {
|
||||
let wire = dir.start(settings);
|
||||
let mut mcp = Self {
|
||||
books_dir: None,
|
||||
wire,
|
||||
@@ -107,7 +113,14 @@ impl Mcp {
|
||||
mcp
|
||||
}
|
||||
|
||||
/// The journal, without the frames of tool calls (D-88): the events.
|
||||
fn journal(&self) -> Vec<u8> {
|
||||
common::without_call_lines(&self.journal_raw())
|
||||
}
|
||||
|
||||
/// The journal, byte for byte: what a check that a refusal or a
|
||||
/// preview "journaled nothing" compares, so a stray frame line is seen.
|
||||
fn journal_raw(&self) -> Vec<u8> {
|
||||
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -151,7 +164,7 @@ impl Mcp {
|
||||
/// Call a tool; a refusal must leave the journal unchanged, a success
|
||||
/// must match the outputSchema.
|
||||
fn tool(&mut self, name: &str, args: Value) -> Out {
|
||||
let before = self.journal();
|
||||
let before = self.journal_raw();
|
||||
let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone());
|
||||
let out = if let Some(err) = resp.get("error") {
|
||||
Out::RpcErr(err.clone())
|
||||
@@ -181,7 +194,7 @@ impl Mcp {
|
||||
};
|
||||
if out.refused() {
|
||||
assert!(
|
||||
self.journal() == before,
|
||||
self.journal_raw() == before,
|
||||
"refused {name} {args} changed the journal ({out:?})"
|
||||
);
|
||||
}
|
||||
@@ -208,10 +221,10 @@ impl Mcp {
|
||||
|
||||
/// `ok`, and the journal must not change (read-only tools).
|
||||
fn read_only(&mut self, name: &str, args: Value) -> Value {
|
||||
let before = self.journal();
|
||||
let before = self.journal_raw();
|
||||
let v = self.ok(name, args);
|
||||
assert!(
|
||||
self.journal() == before,
|
||||
self.journal_raw() == before,
|
||||
"read-only {name} changed the journal"
|
||||
);
|
||||
v
|
||||
@@ -253,6 +266,7 @@ fn books(name: &str) -> Mcp {
|
||||
/// for their format upgrade.
|
||||
fn books_in(name: &str, p2: bool) -> Mcp {
|
||||
let dir = test_dir(name);
|
||||
let toml = books_toml(&dir, "Spec Co", "");
|
||||
if p2 {
|
||||
ledger_store::Store::create_in_format(
|
||||
&dir.books_data(),
|
||||
@@ -263,8 +277,11 @@ fn books_in(name: &str, p2: bool) -> Mcp {
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
// Books that take no write (D-89): no settings, no chart.
|
||||
let mut m = Mcp::start_settings(&dir, None);
|
||||
m.books_dir = Some(dir);
|
||||
return m;
|
||||
}
|
||||
let toml = books_toml(&dir, "Spec Co", "");
|
||||
let mut m = Mcp::start(&dir, &toml);
|
||||
m.accounts(CHART);
|
||||
m.books_dir = Some(dir);
|
||||
@@ -503,7 +520,7 @@ fn update_project_with_nothing_new_journals_nothing() {
|
||||
"books.add_project",
|
||||
json!({"name": "Harbor", "kind": "client"}),
|
||||
);
|
||||
let before = m.journal();
|
||||
let before = m.journal_raw();
|
||||
m.ok(
|
||||
"books.update_project",
|
||||
json!({"project": "Harbor", "kind": "client"}),
|
||||
@@ -512,7 +529,7 @@ fn update_project_with_nothing_new_journals_nothing() {
|
||||
"books.update_project",
|
||||
json!({"project": "harbor", "name": "Harbor"}),
|
||||
);
|
||||
assert_eq!(m.journal(), before);
|
||||
assert_eq!(m.journal_raw(), before);
|
||||
}
|
||||
|
||||
// ------------------------------------------------- figures
|
||||
@@ -914,17 +931,16 @@ fn show_project_sends_its_target() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Books an older version wrote take no write at all (D-89): not a
|
||||
/// project, not a link to one, nothing, and the refusal journals nothing.
|
||||
/// (The feature `projects` itself waiting is the store's:
|
||||
/// `ledger-store` `tests/projects.rs`.)
|
||||
#[test]
|
||||
fn project_writes_wait_for_the_format_upgrade() {
|
||||
let mut m = books_in("upgrade", true);
|
||||
// A name alone: a plain class, accepted.
|
||||
m.ok("books.add_project", json!({"name": "Harbor"}));
|
||||
let a = match m.doc(b"%PDF c", json!([])) {
|
||||
Out::Ok(v) => v["attachment_id"].as_u64().unwrap(),
|
||||
o => panic!("{o:?}"),
|
||||
};
|
||||
let head = m.journal();
|
||||
let head = m.journal_raw();
|
||||
for (tool, args) in [
|
||||
("books.add_project", json!({"name": "Harbor"})),
|
||||
(
|
||||
"books.add_project",
|
||||
json!({"name": "Dock", "kind": "client"}),
|
||||
@@ -935,7 +951,7 @@ fn project_writes_wait_for_the_format_upgrade() {
|
||||
),
|
||||
(
|
||||
"books.link_attachment",
|
||||
json!({"attachment_id": a, "subject": {"kind": "project", "id": "Harbor"}}),
|
||||
json!({"attachment_id": 1, "subject": {"kind": "project", "id": "Harbor"}}),
|
||||
),
|
||||
(
|
||||
"books.record_decision",
|
||||
@@ -944,16 +960,10 @@ fn project_writes_wait_for_the_format_upgrade() {
|
||||
),
|
||||
] {
|
||||
let why = m.refuse(tool, args);
|
||||
assert!(
|
||||
why.starts_with("format_upgrade_pending:") && why.contains("projects"),
|
||||
"{tool}: {why}"
|
||||
);
|
||||
assert!(why.starts_with("format_upgrade_pending:"), "{tool}: {why}");
|
||||
assert!(why.contains("nothing can be written"), "{tool}: {why}");
|
||||
}
|
||||
// Filing with a link to a project is refused before the file is filed.
|
||||
let out = m.doc(b"%PDF d", json!([{"kind": "project", "id": "Harbor"}]));
|
||||
assert!(out.refused());
|
||||
assert!(out.err_text().contains("projects"), "{out:?}");
|
||||
assert_eq!(m.journal(), head, "nothing journaled");
|
||||
assert_eq!(m.journal_raw(), head, "nothing journaled");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1474,7 +1484,7 @@ fn books_without_the_feature_refuse_a_tagged_document() {
|
||||
);
|
||||
let cedar = m.ok("books.add_customer", json!({"name": "Cedar"}))["id"].clone();
|
||||
let v = m.ok("books.add_vendor", json!({"name": "Dana"}))["id"].clone();
|
||||
let head = m.journal();
|
||||
let head = m.journal_raw();
|
||||
for (tool, key, party) in [
|
||||
("books.create_invoice", "customer", &cedar),
|
||||
("books.create_bill", "vendor", &v),
|
||||
@@ -1490,7 +1500,7 @@ fn books_without_the_feature_refuse_a_tagged_document() {
|
||||
"{tool}: {why}"
|
||||
);
|
||||
}
|
||||
assert_eq!(m.journal(), head, "nothing journaled");
|
||||
assert_eq!(m.journal_raw(), head, "nothing journaled");
|
||||
m.ok(
|
||||
"books.create_invoice",
|
||||
json!({"customer": (cedar).to_string(), "date": "2026-03-02", "due_date": "2026-04-01", "lines": [
|
||||
|
||||
@@ -115,7 +115,14 @@ impl Mcp {
|
||||
mcp
|
||||
}
|
||||
|
||||
/// The journal, without the frames of tool calls (D-88): the events.
|
||||
fn journal(&self) -> Vec<u8> {
|
||||
common::without_call_lines(&self.journal_raw())
|
||||
}
|
||||
|
||||
/// The journal, byte for byte: what a check that a refusal or a
|
||||
/// preview "journaled nothing" compares, so a stray frame line is seen.
|
||||
fn journal_raw(&self) -> Vec<u8> {
|
||||
std::fs::read(self.data.join("journal.jsonl")).unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -161,7 +168,7 @@ impl Mcp {
|
||||
/// Call a tool; a refusal must leave the journal unchanged, a success
|
||||
/// must match the outputSchema.
|
||||
fn tool(&mut self, name: &str, args: Value) -> Out {
|
||||
let before = self.journal();
|
||||
let before = self.journal_raw();
|
||||
let resp = common::tools_call(|m, p| self.rpc(m, p), name, args.clone());
|
||||
let out = if let Some(err) = resp.get("error") {
|
||||
Out::RpcErr(err.clone())
|
||||
@@ -191,7 +198,7 @@ impl Mcp {
|
||||
};
|
||||
if out.refused() {
|
||||
assert!(
|
||||
self.journal() == before,
|
||||
self.journal_raw() == before,
|
||||
"refused {name} {args} changed the journal ({out:?})"
|
||||
);
|
||||
}
|
||||
@@ -218,10 +225,10 @@ impl Mcp {
|
||||
|
||||
/// `ok`, and the journal must not change (read-only tools).
|
||||
fn read_only(&mut self, name: &str, args: Value) -> Value {
|
||||
let before = self.journal();
|
||||
let before = self.journal_raw();
|
||||
let v = self.ok(name, args);
|
||||
assert!(
|
||||
self.journal() == before,
|
||||
self.journal_raw() == before,
|
||||
"read-only {name} changed the journal"
|
||||
);
|
||||
v
|
||||
@@ -1021,7 +1028,7 @@ fn purge_deletes_the_vault_records_and_journals_why() {
|
||||
json!({"party": "Nobody", "reason": "x", "confirmed": true}),
|
||||
);
|
||||
// A preview changes nothing.
|
||||
let journal = m.journal();
|
||||
let journal = m.journal_raw();
|
||||
let p = m.ok(
|
||||
"books.purge_tin",
|
||||
json!({"party": "Acme Design", "reason": "retention over"}),
|
||||
@@ -1030,7 +1037,7 @@ fn purge_deletes_the_vault_records_and_journals_why() {
|
||||
assert_eq!(p["tin_in_vault"], true);
|
||||
assert_eq!(p["w9_file_in_vault"], true);
|
||||
assert_eq!(p["tin_last4"], "2846");
|
||||
assert!(m.journal() == journal);
|
||||
assert!(m.journal_raw() == journal);
|
||||
assert!(m.vault().join(format!("tin-{acme}.bin")).exists());
|
||||
// Without the key, confirmed: gone, and journaled.
|
||||
std::fs::remove_file(m.key()).unwrap();
|
||||
@@ -2097,6 +2104,8 @@ fn idempotent_tools_change_nothing_when_repeated() {
|
||||
m.ok(name, args.clone());
|
||||
let (journal, vault) = (m.journal(), vault_bytes(&m));
|
||||
m.ok(name, args.clone());
|
||||
// The events, not the frames: a repeat with a new key is a call of
|
||||
// its own, and its frame is no change of the books.
|
||||
let changed = m.journal() != journal || vault_bytes(&m) != vault;
|
||||
*repeats_change.entry(name).or_default() |= changed;
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ impl ledger_package::PackageBooks for View<'_> {
|
||||
}
|
||||
|
||||
fn journal_seq(&self) -> u64 {
|
||||
self.0.journal.len() as u64
|
||||
self.0.head_seq
|
||||
}
|
||||
|
||||
fn journal(&self) -> Result<Vec<JournalLine>, StoreError> {
|
||||
|
||||
@@ -274,7 +274,20 @@ pub struct Books {
|
||||
pub settings: BooksSettings,
|
||||
pub data_dir: PathBuf,
|
||||
pub attachments: Vec<Attachment>,
|
||||
/// The committed journal: the lines that are facts of the books (those
|
||||
/// outside any call and those of calls that closed `ok`), the frame
|
||||
/// lines left out. Every fact the viewer derives from the journal
|
||||
/// (an entry's events and origin, an asset's trail, a party's events)
|
||||
/// comes from here, never from [`Books::history`]: ids are handed out
|
||||
/// again after a failed call, so a dead line would be pinned on
|
||||
/// whatever takes the id next (ledger_store::calls).
|
||||
pub journal: Vec<JournalLine>,
|
||||
/// Every line of the journal, in order (seq = index + 1), and each
|
||||
/// line's standing: for the journal page, which shows history and
|
||||
/// says of a line that did not count that it did not.
|
||||
pub history: Vec<(JournalLine, ledger_store::calls::Standing)>,
|
||||
/// The seq of the journal's last line.
|
||||
pub head_seq: u64,
|
||||
pub head: String,
|
||||
pub today: NaiveDate,
|
||||
pub loaded_at: chrono::DateTime<chrono::Utc>,
|
||||
@@ -605,7 +618,14 @@ impl Books {
|
||||
) -> Result<Books, String> {
|
||||
let ledger = snap.ledger().clone();
|
||||
let attachments = snap.attachments(None).map_err(|e| e.to_string())?;
|
||||
let journal = snap.journal().to_vec();
|
||||
let journal = snap.committed_journal().map_err(|e| e.to_string())?;
|
||||
let history: Vec<_> = snap
|
||||
.journal()
|
||||
.iter()
|
||||
.cloned()
|
||||
.zip(snap.journal_standings().map_err(|e| e.to_string())?)
|
||||
.collect();
|
||||
let head_seq = snap.journal_seq();
|
||||
// The server's own rule, so the viewer flags exactly what the
|
||||
// server would refuse: the books' settings.
|
||||
let policy = ledger_config::codec::receipt_policy(ledger.settings());
|
||||
@@ -676,7 +696,7 @@ impl Books {
|
||||
let statements = snap.statements(None).map_err(|e| e.to_string())?;
|
||||
let reconciliations = snap.reconciliations(None).map_err(|e| e.to_string())?;
|
||||
let extractions = snap.extractions().map_err(|e| e.to_string())?;
|
||||
let fresh_from_seq = prev_seq.unwrap_or(journal.len() as u64);
|
||||
let fresh_from_seq = prev_seq.unwrap_or(head_seq);
|
||||
let mut fresh = HashSet::new();
|
||||
let closings = ledger.closing_entry_ids();
|
||||
let mut entries = Vec::new();
|
||||
@@ -817,6 +837,8 @@ impl Books {
|
||||
data_dir: snap.data_dir().to_path_buf(),
|
||||
attachments,
|
||||
journal,
|
||||
history,
|
||||
head_seq,
|
||||
head: snap.head_hash().to_string(),
|
||||
today,
|
||||
loaded_at: chrono::Utc::now(),
|
||||
@@ -864,7 +886,7 @@ impl Books {
|
||||
}
|
||||
|
||||
pub fn seq(&self) -> u64 {
|
||||
self.journal.len() as u64
|
||||
self.head_seq
|
||||
}
|
||||
|
||||
pub fn entry(&self, id: EntryId) -> Option<&EntryInfo> {
|
||||
|
||||
@@ -1098,6 +1098,18 @@ pub fn describe(b: &Books, line: &JournalLine) -> Option<Event> {
|
||||
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"]),
|
||||
@@ -1258,6 +1270,24 @@ pub fn describe(b: &Books, line: &JournalLine) -> Option<Event> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A journal line's event for the journal page: the sentence the books
|
||||
/// give it when it counts; for a line of a call that did not count, its
|
||||
/// plain description from the journal's own words and the note that it did
|
||||
/// not count, never a sentence built from the books' present state (ids
|
||||
/// are handed out again after a failed call, so "Posted #42" would name
|
||||
/// whatever took 42 next), and no link.
|
||||
pub fn event_for(b: &Books, line: &JournalLine, standing: ledger_store::calls::Standing) -> Event {
|
||||
match standing.note() {
|
||||
None => describe_any(b, line),
|
||||
Some(note) => Event {
|
||||
icon: icon::WARNING,
|
||||
text: format!("{} ({note})", ledger_store::describe::describe(line)),
|
||||
route: None,
|
||||
also: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Like [`describe`], but every event gets a sentence.
|
||||
pub fn describe_any(b: &Books, line: &JournalLine) -> Event {
|
||||
if let Some(e) = describe(b, line) {
|
||||
@@ -1330,7 +1360,7 @@ pub fn describe_any(b: &Books, line: &JournalLine) -> Event {
|
||||
|
||||
pub fn show(ui: &mut Ui, b: &Books, selected: Option<u64>, shell: &mut Shell<'_>) {
|
||||
if let Some(seq) = selected
|
||||
&& let Some(line) = b.journal.get(seq.saturating_sub(1) as usize)
|
||||
&& let Some((line, standing)) = b.history.get(seq.saturating_sub(1) as usize)
|
||||
{
|
||||
super::split(
|
||||
ui,
|
||||
@@ -1338,7 +1368,7 @@ pub fn show(ui: &mut Ui, b: &Books, selected: Option<u64>, shell: &mut Shell<'_>
|
||||
480.0,
|
||||
shell,
|
||||
|ui, shell| list(ui, b, selected, shell),
|
||||
|ui, shell| detail(ui, b, line, shell),
|
||||
|ui, shell| detail(ui, b, line, *standing, shell),
|
||||
);
|
||||
} else {
|
||||
list(ui, b, None, shell);
|
||||
@@ -1353,7 +1383,7 @@ fn list(ui: &mut Ui, b: &Books, selected: Option<u64>, shell: &mut Shell<'_>) {
|
||||
"Journal",
|
||||
&format!(
|
||||
"Every change to the books, in order: {} events, each hash-chained to the one before. Nothing is ever edited or deleted; corrections are new events.",
|
||||
b.journal.len()
|
||||
b.history.len()
|
||||
),
|
||||
);
|
||||
let st = &mut shell.state.journal;
|
||||
@@ -1369,11 +1399,11 @@ fn list(ui: &mut Ui, b: &Books, selected: Option<u64>, shell: &mut Shell<'_>) {
|
||||
let q = st.query.to_lowercase();
|
||||
let hide = st.hide_steps;
|
||||
let rows: Vec<(&JournalLine, Event)> = b
|
||||
.journal
|
||||
.history
|
||||
.iter()
|
||||
.rev()
|
||||
.filter(|l| !(hide && describe(b, l).is_none()))
|
||||
.map(|l| (l, describe_any(b, l)))
|
||||
.filter(|(l, st)| !(hide && st.counts() && describe(b, l).is_none()))
|
||||
.map(|(l, st)| (l, event_for(b, l, *st)))
|
||||
.filter(|(l, e)| {
|
||||
q.is_empty() || e.text.to_lowercase().contains(&q) || l.line_type.contains(&q)
|
||||
})
|
||||
@@ -1449,9 +1479,15 @@ fn list(ui: &mut Ui, b: &Books, selected: Option<u64>, shell: &mut Shell<'_>) {
|
||||
});
|
||||
}
|
||||
|
||||
fn detail(ui: &mut Ui, b: &Books, line: &JournalLine, shell: &mut Shell<'_>) {
|
||||
fn detail(
|
||||
ui: &mut Ui,
|
||||
b: &Books,
|
||||
line: &JournalLine,
|
||||
standing: ledger_store::calls::Standing,
|
||||
shell: &mut Shell<'_>,
|
||||
) {
|
||||
let p = pal(ui.ctx());
|
||||
let ev = describe_any(b, line);
|
||||
let ev = event_for(b, line, standing);
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("event_detail")
|
||||
.show(ui, |ui| {
|
||||
@@ -1473,6 +1509,9 @@ fn detail(ui: &mut Ui, b: &Books, line: &JournalLine, shell: &mut Shell<'_>) {
|
||||
ui.add(egui::Label::new(RichText::new(v).font(theme::regular(12.5))).wrap());
|
||||
});
|
||||
};
|
||||
if let Some(note) = standing.note() {
|
||||
fact(ui, "Counts", note);
|
||||
}
|
||||
fact(ui, "Type", &line.line_type);
|
||||
fact(ui, "Recorded", &fmt::timestamp(&line.ts));
|
||||
fact(ui, "Previous", &line.prev);
|
||||
|
||||
@@ -986,3 +986,117 @@ fn the_viewer_holds_a_numbered_invoice_as_the_store_does() {
|
||||
assert_eq!(shown.terms.as_ref().unwrap().describe(), "2/10 net 30");
|
||||
assert_eq!(shown.lines[0].quantity, Some(Decimal::new(3, 0)));
|
||||
}
|
||||
|
||||
/// A call that failed after writing lines, followed by a call that takes
|
||||
/// the ids it handed out again (nothing it wrote counted): the viewer's
|
||||
/// books, the package feed that attention reads, and the history all say
|
||||
/// the dead lines are not facts, and nothing of the dead call is pinned on
|
||||
/// what took its ids (WB-format-12).
|
||||
#[test]
|
||||
fn a_failed_calls_lines_are_not_facts_when_its_ids_are_used_again() {
|
||||
use ledger_store::calls::{CallEnd, CallId, Standing};
|
||||
let (d, mut s) = store_at("failed-call");
|
||||
let today = NaiveDate::from_ymd_opt(2026, 5, 20).unwrap();
|
||||
let cash = s
|
||||
.add_account("1000", "Checking", AccountType::Asset, None, false)
|
||||
.unwrap();
|
||||
let cap = s
|
||||
.add_account("3000", "Capital", AccountType::Equity, None, false)
|
||||
.unwrap();
|
||||
let id = |key: &str, tool: &str| CallId {
|
||||
token: "t".into(),
|
||||
tool: tool.into(),
|
||||
key: key.into(),
|
||||
args: "a".repeat(64),
|
||||
};
|
||||
let lines = |amount: i64| {
|
||||
vec![DocumentLine {
|
||||
description: "x".into(),
|
||||
amount: Decimal::new(amount, 2),
|
||||
class_id: None,
|
||||
account: None,
|
||||
quantity: None,
|
||||
unit_price: None,
|
||||
}]
|
||||
};
|
||||
let before = s.journal_seq();
|
||||
// A failed books.create_bill: a vendor, a bill, an entry (id 1).
|
||||
s.begin_call(id("key-dead-0001", "books.create_bill"))
|
||||
.unwrap();
|
||||
let dead_vendor = s.add_vendor("Dead Vendor").unwrap();
|
||||
s.create_bill(dead_vendor, today, today + Days::new(30), lines(5_000))
|
||||
.unwrap();
|
||||
s.close_call(CallEnd::Failed("the call failed after its lines"))
|
||||
.unwrap();
|
||||
let dead_end = s.journal_seq();
|
||||
assert!(dead_end > before + 3);
|
||||
// A manual entry, which takes entry id 1 again, and a vendor, which
|
||||
// takes party id 1 again.
|
||||
let e = s.create_entry(today, "Opening deposit").unwrap();
|
||||
assert_eq!(e, 1, "the failed call's entry id is handed out again");
|
||||
let m = Money::new(Decimal::new(100_000, 2), Currency::USD);
|
||||
s.add_line(e, cash, Side::Debit, m).unwrap();
|
||||
s.add_line(e, cap, Side::Credit, m).unwrap();
|
||||
s.post_entry(e).unwrap();
|
||||
let live_vendor = s.add_vendor("Real Vendor").unwrap();
|
||||
assert_eq!(live_vendor, dead_vendor);
|
||||
drop(s);
|
||||
let source = Source {
|
||||
data_dir: d.join("books-data"),
|
||||
today: Some(today),
|
||||
};
|
||||
let b = data::load_once(&source).unwrap();
|
||||
// The entry is a manual one: not a "Bill", which is what the dead
|
||||
// bill.created line (for entry 1) would have made of it.
|
||||
let entry = b.entry(e).unwrap();
|
||||
assert_eq!(entry.origin, "Journal entry");
|
||||
assert!(
|
||||
entry
|
||||
.events
|
||||
.iter()
|
||||
.all(|&i| !(before + 1..=dead_end).contains(&b.journal[i].seq)),
|
||||
"an entry's events include a dead line"
|
||||
);
|
||||
// No fact the viewer derives holds a dead line: the committed journal
|
||||
// has none of them, and none of the frame.
|
||||
assert!(
|
||||
b.journal
|
||||
.iter()
|
||||
.all(|l| !(before + 1..=dead_end).contains(&l.seq) && !l.line_type.starts_with("call."))
|
||||
);
|
||||
// The party that took the id again has none of the dead vendor's events.
|
||||
let party = &b.parties[&live_vendor];
|
||||
assert!(
|
||||
party
|
||||
.events
|
||||
.iter()
|
||||
.all(|&i| !(before + 1..=dead_end).contains(&b.journal[i].seq))
|
||||
);
|
||||
// The package feed attention reads is the same committed journal.
|
||||
let snap = ledger_store::Snapshot::load(&d.join("books-data")).unwrap();
|
||||
let fed = ledger_package::PackageBooks::journal(&snap).unwrap();
|
||||
assert_eq!(fed.len(), b.journal.len());
|
||||
assert!(
|
||||
fed.iter()
|
||||
.all(|l| !(before + 1..=dead_end).contains(&l.seq))
|
||||
);
|
||||
let store = Store::open(&d.join("books-data")).unwrap();
|
||||
let fed = ledger_package::PackageBooks::journal(&store).unwrap();
|
||||
assert_eq!(fed.len(), b.journal.len());
|
||||
// The viewer's seq is the journal's head, frame lines counted.
|
||||
assert_eq!(b.seq(), b.history.len() as u64);
|
||||
// History shows every line, and says of the dead ones in words that
|
||||
// they did not count; the viewer never names a dead line by the live
|
||||
// entry that took its id.
|
||||
let dead: Vec<_> = b
|
||||
.history
|
||||
.iter()
|
||||
.filter(|(_, st)| *st == Standing::Failed)
|
||||
.collect();
|
||||
assert!(dead.len() >= 3);
|
||||
for (line, st) in dead {
|
||||
let ev = ledger_gui::pages::journal::event_for(&b, line, *st);
|
||||
assert!(ev.text.contains("not counted"), "{}", ev.text);
|
||||
assert!(ev.route.is_none());
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ You are the bookkeeping agent for these books. The engine enforces the accountin
|
||||
- Never invent accounts. If the account you need does not exist, add it with books.add_account first.
|
||||
- Posted entries are immutable; there is no edit. Corrections go through books.reverse_entry.
|
||||
- {evidence_rule}
|
||||
- Every tool that changes the books takes a request_key you make up (8 to 128 characters, a UUID is fine), new for each different action. If an answer is lost, send the same call again with the same key and the same arguments: the books do not do it twice, and answer what they answered (for a very long answer, they say the call was done and name its journal lines). The same key with other arguments is refused. A call that fails changes nothing and leaves its key free; fix it and send it again with the same key. Books waiting for the owner's format upgrade take no write at all (the format-upgrade section).
|
||||
- Show the numbers: after every change, show the human the affected balances.
|
||||
- After posting, check books.digest and offer it to the human (the review of what changed), so they can review it too.
|
||||
- A full TIN goes only into the vault (books.set_tin, books.set_w9); never repeat one anywhere (the parties-and-tins section).
|
||||
@@ -1,11 +1,11 @@
|
||||
# The format upgrade
|
||||
|
||||
- A new version of wanderbooks can keep the books in a newer journal format than the version that wrote them. Books an older version wrote wait for a format upgrade: books.start says so (format_upgrade) and puts it first among its next steps, in every session until it is done.
|
||||
- Until then they work on their old format: everything that needs nothing new works as before, and whatever would need the new format is refused with format_upgrade_pending, changing nothing. Never retry it, work around it, or post it another way.
|
||||
- Until then they can be read as ever, but nothing can be written to them: every write is one transaction that happens exactly once, and books an older version wrote can't keep that until they are upgraded. Every write is refused with format_upgrade_pending, changing nothing. Never retry it, work around it, or post it another way.
|
||||
- An invoice's or bill's number, payment terms, seller and bill-to, references and memo, a line's account, quantity and unit price, the copy of an invoice kept exactly as it was issued, a party's email, default terms and contact details (phone, contact person, billing and shipping addresses, billing email), and the invoicing and bills settings all wait for the documents_v2 upgrade. A document that names none of them is written exactly as before and is never refused; the work that needs one waits, and the books say so.
|
||||
- Only the owner can agree to the upgrade, with the owner passphrase: in the app, which asks each time it opens the books, or with `wanderbooks books upgrade ID` in a terminal. No tool can, and you never ask for, take or type the passphrase. Tell the human, in plain words: the books wait for their go-ahead, what was refused, and that saying no keeps the books working as they are.
|
||||
- Only the owner can agree to the upgrade, with the owner passphrase: in the app, which asks each time it opens the books, or with `wanderbooks books upgrade ID` in a terminal. No tool can, and you never ask for, take or type the passphrase. Tell the human, in plain words: the books wait for their go-ahead, what was refused, and that until they give it the books can be read but not changed.
|
||||
- Before it upgrades, the server makes a backup of the books, their vault and keys included, and proves it whole; a backup that can't be made or proven upgrades nothing. Then the books move to the new format in one step, on the record.
|
||||
- After the upgrade an older version of wanderbooks can't open these books; the backup made first keeps them as they were. Going back is the owner's choice, never yours.
|
||||
- This upgrade is `documents_v2`: invoice numbers, terms and line accounts (S4), sent records (S5), payments that settle several documents with early-payment discounts and a processor's fee (S6), and write-offs (S7). Until it is given, those writes are refused and everything else works as before.
|
||||
- This upgrade is `documents_v2`: invoice numbers, terms and line accounts (S4), sent records (S5), payments that settle several documents with early-payment discounts and a processor's fee (S6), and write-offs (S7). Until it is given, every write is refused (the books can be read).
|
||||
|
||||
- The journal features an upgrade can add: `members_cumulative`, `account_renamed`, `require_tax_category`, `tax_categories_gain_exempt`, `disposal_before_service`, `depreciation_catch_up`, `party_creditors`, `payment_instruments`, `vendor_1099_decisions`, `schedule_convention`, `schedule_minor_unit` (K-U5: a new equal-months schedule's months are whole units of its currency, whole yen or thousandths of a dinar, where the cent rule gave two places for every currency; schedules written before keep their rule), `month_reposting`, `asset_basis`, `projects`, `document_line_projects`, `document_standing`, `documents_v2`, `attachment_text` (P6: a filed file's extracted text, what a human annotated of it, and the entries a payment settles), `drafts_v2` (P4: a draft's state, awaiting its evidence, and a discarded draft), and `source_revisions` (P5: correcting who decided a convention, a decision or an open item, and when). All are declared at once; a version that doesn't know one stops at the declaration instead of misreading the books.
|
||||
- The journal features an upgrade can add: `members_cumulative`, `account_renamed`, `require_tax_category`, `tax_categories_gain_exempt`, `disposal_before_service`, `depreciation_catch_up`, `party_creditors`, `payment_instruments`, `vendor_1099_decisions`, `schedule_convention`, `schedule_minor_unit` (K-U5: a new equal-months schedule's months are whole units of its currency, whole yen or thousandths of a dinar, where the cent rule gave two places for every currency; schedules written before keep their rule), `month_reposting`, `asset_basis`, `projects`, `document_line_projects`, `document_standing`, `documents_v2`, `attachment_text` (P6: a filed file's extracted text, what a human annotated of it, and the entries a payment settles), `drafts_v2` (P4: a draft's state, awaiting its evidence, and a discarded draft), `source_revisions` (P5: correcting who decided a convention, a decision or an open item, and when), and `call_transactions` (D-88: every write one transaction, with the request key each write carries, and the books' own unique id). All are declared at once; a version that doesn't know one stops at the declaration instead of misreading the books.
|
||||
@@ -3,6 +3,7 @@
|
||||
- Reports are pure functions of the posted entries. When the human questions a figure, trace it to its entries with the tools: the report (books.trial_balance, books.profit_and_loss, books.balance_sheet, books.cash_flow), then books.search_entries and books.get_entry for the entries behind it, and books.show to put them on the human's screen.
|
||||
- A report without dates covers the fiscal year to date, everywhere (the report tools, the export, books.show and the viewer); one with only an end date covers that date's fiscal year to it. {period_rule} The IIF is never a period: every posted entry from the first through its as_of. Every result names the dates it covers: say them when you quote a figure, and pass dates whenever the human means another period.
|
||||
- A cash flow line names its entry (books.cash_flow: each line's entry, kind and accounts). An expense a member paid personally (or equipment a lender paid for) is cash borrowed and spent on its date: a financing line and an operating (or investing) line, each with on_behalf, the part no bank account moved; the reimbursement is a repayment. A noncash disclosure is an entry that moved no cash at all (property contributed, debt converted to capital). A warning names an entry whose later payment or collection the books can't classify, with the fix. A role refusal names the setting to change.
|
||||
- books.journal_history shows every line of the journal. A line it says did not count belongs to a call that failed, never finished or is still running: nothing it wrote is in the books, and the ids it took were handed out again, so never trace a figure to such a line.
|
||||
- Never guess, and never look for the books' files: the tools are the evidence.
|
||||
- books.verify checks the books end to end when a number looks wrong or a human asks whether the books are intact.
|
||||
- A member's odd cent: closes, the statement of members' equity, the K-1 worksheet and the viewer split earnings among the members one running way. Each close gives a member their share of everything closed to the same members and shares so far, to the cent (odd cents by largest remainder, ties to the member listed first when that count began), less what earlier closes gave them, so no member is ever a cent from their exact share. Earnings not yet closed are split the way their close will split them, so a member's capital on a day never changes when its month is closed. books.close_period's members shows each member's part, running total and exact share; the first close that posts may carry a one-time correction of the rounding left by closes made under an earlier rule (a cent or so per member; each member's this_close shows it) (books.list_periods' close_rule names each close's rule). A change of members or shares starts a new count.
|
||||
|
||||
@@ -0,0 +1,493 @@
|
||||
//! Every write a tool makes is one transaction that happens once (plan
|
||||
//! P15 2a, D-88, D-89): the request key, the repeat, and the frame around
|
||||
//! a call. The journal's side is `ledger_store::calls`.
|
||||
//!
|
||||
//! ```text
|
||||
//! GOAL: a write whose answer is lost and which is then retried happens
|
||||
//! once; a call half done is never left looking done; a failed
|
||||
//! write is on the record.
|
||||
//! SOURCE: WB-format-8, WB-format-9, WB-format-10, WB-format-11, WB-format-12;
|
||||
//! plan/p15-app-and-relay.md 2a.
|
||||
//! INVARIANTS:
|
||||
//! 1. Every tool that can change anything (no readOnlyHint, but for
|
||||
//! READS_THAT_SEAL, which write nothing and may answer with a TIN) takes a
|
||||
//! required `request_key` in its schema; a call that writes without
|
||||
//! one is refused in words, before it runs. A preview (a confirmed
|
||||
//! tool called without confirmed: true) writes nothing and needs
|
||||
//! none. The key is taken out of the arguments before the tool sees
|
||||
//! them, so a tool's own checks and previews are unchanged.
|
||||
//! 2. A write call runs alone among writes: they take turns, so a
|
||||
//! call's lines are one run in the journal, and a repeat that
|
||||
//! arrives while its original still runs waits for it, then gets its
|
||||
//! answer. Nothing else touches the books while a call that has
|
||||
//! written a line is open: a read that arrives between the tool's
|
||||
//! return and its closing line waits for the close
|
||||
//! (`BooksServer::lock`), so no read ever shows what a call did
|
||||
//! before the call committed. A call that has written no line has
|
||||
//! nothing to show, and leaves reads free (a backup can take long).
|
||||
//! 3. A repeat of a (token, key) whose call committed, with the same
|
||||
//! tool and arguments, returns that call's answer as it was given and
|
||||
//! writes nothing; with other arguments (or another tool) it is
|
||||
//! refused as a misuse of the key. "The same arguments" is a keyed
|
||||
//! digest of them, tax ids included (ledger_store::calls::args_mac),
|
||||
//! so two requests that differ only in a tax id are two requests. A
|
||||
//! call whose answer was too long to keep is repeated in words: it
|
||||
//! was done, its lines are named, nothing is done again. The access
|
||||
//! log records a repeat as `repeat`.
|
||||
//! 4. A call that answered ok and wrote lines commits with a closing
|
||||
//! line holding its answer; one that answered with an error, was
|
||||
//! stopped by a close or failed by any other means rolls back, is
|
||||
//! journaled as `failed` when it had written lines, and leaves its
|
||||
//! key unused. A call that wrote no line leaves no line at all: its
|
||||
//! key and answer are kept in memory for the life of the server.
|
||||
//! Nothing a tool writes outside the journal (the tax-id vault)
|
||||
//! is final before the call commits: it is staged, and settled
|
||||
//! after the closing line (`vault_stage`).
|
||||
//! 5. Books that haven't declared call_transactions take no write: every
|
||||
//! write call is refused with the upgrade remedy, before it runs.
|
||||
//! Reads are never refused for it.
|
||||
//! 6. No full TIN is kept in the journal (BS-partner-2): no answer holds
|
||||
//! one (READS_THAT_SEAL, the three that can, are no transaction), and
|
||||
//! an error text that holds one is kept masked.
|
||||
//! SCENARIOS:
|
||||
//! 1. IF a write is called again with the same key after its answer was
|
||||
//! lost: SHOULD return the first answer, and the books hold one of
|
||||
//! its effects.
|
||||
//! 2. IF the same key comes with a different request: SHOULD refuse,
|
||||
//! saying so and that nothing was changed.
|
||||
//! 3. IF the process dies between the call's lines: SHOULD leave none
|
||||
//! of them in the books (ledger_store::calls).
|
||||
//! ```
|
||||
|
||||
use ledger_store::calls::{CallEnd, CallId, MAX_KEY_LEN, MIN_KEY_LEN};
|
||||
use rmcp::model::{CallToolResponse, CallToolResult};
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use super::BooksServer;
|
||||
use crate::scopes::{Needs, TABLE};
|
||||
|
||||
/// The argument every write call carries.
|
||||
pub const KEY_FIELD: &str = "request_key";
|
||||
|
||||
/// Why a write was refused before it ran, for its access record.
|
||||
pub(crate) const MISSING_KEY: &str = "request_key_missing";
|
||||
/// The key was used for another request.
|
||||
pub(crate) const KEY_REUSED: &str = "request_key_reused";
|
||||
/// The books are waiting for the owner's format upgrade (D-89).
|
||||
pub(crate) const UPGRADE_PENDING: &str = "format_upgrade_pending";
|
||||
/// The call repeated one that committed: its answer was returned.
|
||||
pub(crate) const REPEAT: &str = "repeat";
|
||||
|
||||
/// The words that tell a model what the key is, whenever it is asked for.
|
||||
const KEY_WORDS: &str = "request_key: any text you make up, 8 to 128 characters (a UUID is fine), new for each different action and never reused for another. If a call's answer is lost, send the same call again with the same key: the books will not do it twice, and will answer what they answered the first time";
|
||||
|
||||
/// The tools that are not read-only by their annotation but write nothing
|
||||
/// to the books: they read what is sealed or put it into a file, and the
|
||||
/// answer of each may hold a full TIN, which no journal line may (BS-partner-2).
|
||||
/// They take no request key and are no transaction; they are read as any
|
||||
/// read is (INVARIANT 1).
|
||||
pub(crate) const READS_THAT_SEAL: [&str; 3] = [
|
||||
"books.vendor_1099",
|
||||
"books.get_w9",
|
||||
"books.export_cpa_package",
|
||||
];
|
||||
|
||||
/// The tools whose calls can write: no readOnlyHint (`next_steps::
|
||||
/// mutating_tools`), except [`READS_THAT_SEAL`] (83 of the 86).
|
||||
pub(crate) fn writes(tool: &str) -> bool {
|
||||
super::next_steps::mutating_tools().contains(tool) && !READS_THAT_SEAL.contains(&tool)
|
||||
}
|
||||
|
||||
/// Whether a call to `tool` with `args` writes: a write tool, except a
|
||||
/// confirmed tool called as a preview (INVARIANT 1).
|
||||
pub(crate) fn is_write_call(tool: &str, args: Option<&Map<String, Value>>) -> bool {
|
||||
if !writes(tool) {
|
||||
return false;
|
||||
}
|
||||
let previews = TABLE
|
||||
.iter()
|
||||
.any(|(n, needs)| *n == tool && *needs == Needs::PostWhenConfirmed);
|
||||
!(previews
|
||||
&& !args
|
||||
.and_then(|a| a.get("confirmed"))
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false))
|
||||
}
|
||||
|
||||
/// Take the request key out of the arguments (INVARIANT 1).
|
||||
pub(crate) fn take_key(args: &mut Option<Map<String, Value>>) -> Option<Value> {
|
||||
args.as_mut().and_then(|a| a.remove(KEY_FIELD))
|
||||
}
|
||||
|
||||
/// What is wrong with a call's key, in words; None when it will do.
|
||||
pub(crate) fn key_problem(key: Option<&Value>) -> Option<String> {
|
||||
match key {
|
||||
None | Some(Value::Null) => Some(format!(
|
||||
"this call changes the books and carries no request_key, so it was not run and nothing was changed. Send it again with a {KEY_WORDS}."
|
||||
)),
|
||||
Some(Value::String(k)) => {
|
||||
let n = k.chars().count();
|
||||
if k != k.trim() || k.chars().any(char::is_control) {
|
||||
Some("the request_key has spaces at its ends or control characters in it, so the call was not run and nothing was changed. Send it again with a key of plain text".into())
|
||||
} else if !(MIN_KEY_LEN..=MAX_KEY_LEN).contains(&n) {
|
||||
Some(format!(
|
||||
"the request_key is {n} characters; it must be {MIN_KEY_LEN} to {MAX_KEY_LEN}, so the call was not run and nothing was changed. Send it again with a {KEY_WORDS}."
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
Some(_) => Some(format!(
|
||||
"the request_key must be text, so the call was not run and nothing was changed. Send it again with a {KEY_WORDS}."
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The key as text, once it has passed [`key_problem`].
|
||||
pub(crate) fn key_text(key: &Value) -> String {
|
||||
key.as_str().unwrap_or_default().to_string()
|
||||
}
|
||||
|
||||
/// The tool list's schema for a write tool: `request_key` is a required
|
||||
/// property (INVARIANT 1). A read-only tool's is left as it is.
|
||||
pub(crate) fn add_key_to_schema(tool: &mut rmcp::model::Tool) {
|
||||
if !writes(&tool.name) {
|
||||
return;
|
||||
}
|
||||
let mut schema: Map<String, Value> = (*tool.input_schema).clone();
|
||||
let props = schema
|
||||
.entry("properties")
|
||||
.or_insert_with(|| Value::Object(Map::new()));
|
||||
if let Value::Object(props) = props {
|
||||
props.insert(
|
||||
KEY_FIELD.into(),
|
||||
json!({
|
||||
"type": "string",
|
||||
"minLength": MIN_KEY_LEN,
|
||||
"maxLength": MAX_KEY_LEN,
|
||||
"description": KEY_WORDS,
|
||||
}),
|
||||
);
|
||||
}
|
||||
let required = schema
|
||||
.entry("required")
|
||||
.or_insert_with(|| Value::Array(Vec::new()));
|
||||
if let Value::Array(required) = required
|
||||
&& !required.iter().any(|r| r == KEY_FIELD)
|
||||
{
|
||||
required.push(json!(KEY_FIELD));
|
||||
}
|
||||
tool.input_schema = std::sync::Arc::new(schema);
|
||||
}
|
||||
|
||||
/// What opening a call came to.
|
||||
pub(crate) enum Begun {
|
||||
/// The call is open: run the tool.
|
||||
Run,
|
||||
/// Not run: this is the answer, and the access record's code.
|
||||
Answer(Box<CallToolResponse>, &'static str),
|
||||
}
|
||||
|
||||
fn refusal(text: String) -> CallToolResponse {
|
||||
CallToolResponse::Complete(CallToolResult::error(vec![
|
||||
rmcp::model::ContentBlock::text(text),
|
||||
]))
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The tag of the call open on this thread (`ledger_store::calls::
|
||||
/// call_tag`): what its staged vault records are named by.
|
||||
static CALL_TAG: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
|
||||
/// Whether this thread runs the call that is open: the only request
|
||||
/// that may touch the books until its closing line (INVARIANT 2).
|
||||
static OWNS_CALL: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Whether the request on this thread is the one whose call is open.
|
||||
pub(crate) fn owns_call() -> bool {
|
||||
OWNS_CALL.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// The tag of the call open on this thread, if one is: a tool that
|
||||
/// writes outside the journal (the tax-id vault) stages its write under
|
||||
/// it, and the write is made final or dropped when the call closes
|
||||
/// (INVARIANT 4). None outside a call: the write is final at once.
|
||||
pub(crate) fn vault_tag() -> Option<String> {
|
||||
CALL_TAG.with(|t| t.borrow().clone())
|
||||
}
|
||||
|
||||
/// Store a party's TIN for the call open on this thread: staged until the
|
||||
/// call commits (INVARIANT 4); final at once outside a call.
|
||||
pub(crate) fn put_tin(
|
||||
vault: &ledger_vault::Vault,
|
||||
party: u64,
|
||||
tin: &ledger_vault::Tin,
|
||||
) -> Result<String, ledger_vault::Error> {
|
||||
match vault_tag() {
|
||||
Some(tag) => vault.stage_tin(party, tin, &tag),
|
||||
None => vault.put_tin(party, tin),
|
||||
}
|
||||
}
|
||||
|
||||
/// Store a party's W-9 file for the call open on this thread, as
|
||||
/// [`put_tin`].
|
||||
pub(crate) fn put_w9(
|
||||
vault: &ledger_vault::Vault,
|
||||
party: u64,
|
||||
file: &ledger_vault::W9File,
|
||||
) -> Result<String, ledger_vault::Error> {
|
||||
match vault_tag() {
|
||||
Some(tag) => vault.stage_w9(party, file, &tag),
|
||||
None => vault.put_w9(party, file),
|
||||
}
|
||||
}
|
||||
|
||||
/// Purge what the vault in `dir` holds for a party for the call open on
|
||||
/// this thread: set aside until the call commits, put back if it fails
|
||||
/// (INVARIANT 4); deleted at once outside a call.
|
||||
pub(crate) fn purge_records(
|
||||
dir: &std::path::Path,
|
||||
party: u64,
|
||||
) -> Result<bool, ledger_vault::Error> {
|
||||
match vault_tag() {
|
||||
Some(tag) => ledger_vault::stage_purge(dir, party, &tag),
|
||||
None => ledger_vault::purge_records(dir, party),
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply the outcome of the call `tag` to the vault records it staged
|
||||
/// (`ledger_vault::settle`).
|
||||
fn settle_vault(store: &ledger_store::Store, tag: &str, committed: bool) -> Result<(), String> {
|
||||
let dir = store.data_dir().join(ledger_store::root::VAULT_DIR);
|
||||
ledger_vault::settle(&dir, tag, committed)
|
||||
.map(|_| ())
|
||||
.map_err(|e| format!("the TIN vault's staged records could not be settled: {e}"))
|
||||
}
|
||||
|
||||
/// At start: the staged vault records a crash left, each settled by what
|
||||
/// the journal says of its call (INVARIANT 4): final if the call
|
||||
/// committed, dropped (or a purge undone) if not. Said on stderr, never
|
||||
/// failing the open.
|
||||
pub(crate) fn recover_vault(store: &ledger_store::Store) {
|
||||
let dir = store.data_dir().join(ledger_store::root::VAULT_DIR);
|
||||
let Ok(tags) = ledger_vault::pending_tags(&dir) else {
|
||||
return;
|
||||
};
|
||||
for tag in tags {
|
||||
let committed = store.call_committed(&tag);
|
||||
match ledger_vault::settle(&dir, &tag, committed) {
|
||||
Ok(done) => eprintln!(
|
||||
"wanderbooks: a call left tax-id vault records unsettled; its call {} (made final {}, dropped {}, purged {}, put back {})",
|
||||
if committed {
|
||||
"committed"
|
||||
} else {
|
||||
"did not commit"
|
||||
},
|
||||
done.promoted,
|
||||
done.dropped,
|
||||
done.purged,
|
||||
done.restored
|
||||
),
|
||||
Err(e) => {
|
||||
eprintln!("wanderbooks: tax-id vault records of a call could not be settled: {e}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a repeat of a call whose answer was too long to keep is told.
|
||||
fn done_in_words(tool: &str, replay: &ledger_store::calls::Replay) -> String {
|
||||
use ledger_store::calls::Replay;
|
||||
match replay {
|
||||
Replay::Answer(_) => String::new(),
|
||||
Replay::Summary {
|
||||
first_seq,
|
||||
last_seq,
|
||||
closed_seq,
|
||||
answer_sha256,
|
||||
answer_bytes,
|
||||
} => format!(
|
||||
"this request_key was already used for this very call: {tool} was done, and nothing more was changed. Its answer ({answer_bytes} bytes, SHA-256 {answer_sha256}) was too long for the books to keep, so it can't be given again. What it did is journal lines {first_seq} to {last_seq}, closed by line {closed_seq}: books.journal_history with after_seq {} lists them",
|
||||
first_seq.saturating_sub(1)
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Open a call (INVARIANTS 3, 5): refuse it if the books take no calls;
|
||||
/// answer it from the books if its key already committed; otherwise open
|
||||
/// it. Takes the store's lock for the moment it needs; the caller holds
|
||||
/// the write turn (`SharedStore::write_turn`). `arguments` are the call's,
|
||||
/// the request key already taken out: their keyed digest is what a repeat
|
||||
/// is compared by.
|
||||
pub(crate) fn begin(
|
||||
server: &BooksServer,
|
||||
mut id: CallId,
|
||||
arguments: Option<&Map<String, Value>>,
|
||||
) -> Result<Begun, String> {
|
||||
let mut store = server.lock()?;
|
||||
if let Err(e) = store.ensure_takes_calls() {
|
||||
return Ok(Begun::Answer(
|
||||
Box::new(refusal(e.to_string())),
|
||||
UPGRADE_PENDING,
|
||||
));
|
||||
}
|
||||
let args = Value::Object(arguments.cloned().unwrap_or_default());
|
||||
id.args = store.args_mac(&args).map_err(|e| e.to_string())?;
|
||||
if let Some(kept) = store
|
||||
.recorded_call(&id.token, &id.key)
|
||||
.map_err(|e| e.to_string())?
|
||||
{
|
||||
if kept.tool == id.tool && kept.args == id.args {
|
||||
return match kept.replay {
|
||||
ledger_store::calls::Replay::Answer(text) => {
|
||||
match serde_json::from_str::<CallToolResult>(&text) {
|
||||
Ok(answer) => Ok(Begun::Answer(
|
||||
Box::new(CallToolResponse::Complete(answer)),
|
||||
REPEAT,
|
||||
)),
|
||||
Err(e) => Err(format!(
|
||||
"the answer kept for this request_key can't be read back: {e}"
|
||||
)),
|
||||
}
|
||||
}
|
||||
summary => Ok(Begun::Answer(
|
||||
Box::new(refusal(done_in_words(&id.tool, &summary))),
|
||||
REPEAT,
|
||||
)),
|
||||
};
|
||||
}
|
||||
return Ok(Begun::Answer(
|
||||
Box::new(refusal(format!(
|
||||
"this request_key was already used for {} with other arguments (or the books' record of the first can't be matched), so the call was not run and nothing was changed. A key names one action: send this one again with a key of its own",
|
||||
if kept.tool == id.tool {
|
||||
"the same tool".to_string()
|
||||
} else {
|
||||
kept.tool.clone()
|
||||
}
|
||||
))),
|
||||
KEY_REUSED,
|
||||
));
|
||||
}
|
||||
let tag = ledger_store::calls::call_tag(&id.token, &id.key);
|
||||
store.begin_call(id).map_err(|e| e.to_string())?;
|
||||
OWNS_CALL.with(|o| o.set(true));
|
||||
CALL_TAG.with(|t| *t.borrow_mut() = Some(tag));
|
||||
Ok(Begun::Run)
|
||||
}
|
||||
|
||||
/// The text of the first text block, or "".
|
||||
fn first_text(r: &CallToolResult) -> &str {
|
||||
r.content
|
||||
.iter()
|
||||
.find_map(|c| match c {
|
||||
rmcp::model::ContentBlock::Text(t) => Some(t.text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or("")
|
||||
}
|
||||
|
||||
/// Whether a tool's final answer is one that committed: a result that is
|
||||
/// not an error, and the call not stopped by a close (INVARIANT 4).
|
||||
pub(crate) fn answered_ok(
|
||||
out: &Result<CallToolResponse, rmcp::ErrorData>,
|
||||
stopped_by_close: bool,
|
||||
) -> bool {
|
||||
!stopped_by_close
|
||||
&& matches!(out, Ok(CallToolResponse::Complete(r)) if r.is_error != Some(true))
|
||||
}
|
||||
|
||||
/// Why a call could not be closed.
|
||||
pub(crate) enum CloseError {
|
||||
/// Its closing line could not be written: none of it counts.
|
||||
NotClosed(String),
|
||||
/// Its closing line is on disk, so it counts, but the books' working
|
||||
/// copy could not be brought up to it.
|
||||
Committed(String),
|
||||
}
|
||||
|
||||
/// Close the open call with how it came out (INVARIANTS 4, 6). An error
|
||||
/// here means the books server stops, and the caller is told which of the
|
||||
/// two it is.
|
||||
pub(crate) fn close(
|
||||
server: &BooksServer,
|
||||
out: &Result<CallToolResponse, rmcp::ErrorData>,
|
||||
ok: bool,
|
||||
) -> Result<(), CloseError> {
|
||||
use ledger_core::parties::{has_full_tin, redact_full_tins};
|
||||
// The call ends on this thread whatever comes of its closing line.
|
||||
let _ends = EndsCall(server);
|
||||
let mut store = server.lock().map_err(CloseError::NotClosed)?;
|
||||
if !store.in_call() {
|
||||
return Ok(());
|
||||
}
|
||||
let masked = |text: String| {
|
||||
if has_full_tin(&text) {
|
||||
redact_full_tins(&text).into_owned()
|
||||
} else {
|
||||
text
|
||||
}
|
||||
};
|
||||
let ended = if ok {
|
||||
let Ok(CallToolResponse::Complete(r)) = out else {
|
||||
return Err(CloseError::NotClosed(
|
||||
"a call that committed has no answer".into(),
|
||||
));
|
||||
};
|
||||
// Kept as given: no tool's answer holds a full TIN (the three that
|
||||
// can are no transaction), and a digest of the books' head can hold
|
||||
// nine digits in a row, which masking would spoil on a repeat.
|
||||
let text = serde_json::to_string(r).map_err(|e| CloseError::NotClosed(e.to_string()))?;
|
||||
store.close_call(CallEnd::Done(&text))
|
||||
} else {
|
||||
let why = match out {
|
||||
Ok(CallToolResponse::Complete(r)) => first_text(r).to_string(),
|
||||
Ok(_) => "the call did not complete".to_string(),
|
||||
Err(e) => e.message.to_string(),
|
||||
};
|
||||
let why = if why.is_empty() {
|
||||
"the call failed".to_string()
|
||||
} else {
|
||||
why
|
||||
};
|
||||
store.close_call(CallEnd::Failed(&masked(why)))
|
||||
};
|
||||
// What the call staged outside the journal follows how it ended: final
|
||||
// if it committed (it answered ok, or its closing line is on disk),
|
||||
// dropped if it failed. A call whose closing line could not be written
|
||||
// is settled at the next start, by what the journal then says.
|
||||
let tag = CALL_TAG.with(|t| t.borrow_mut().take());
|
||||
let committed = match &ended {
|
||||
Ok(()) => Some(ok),
|
||||
Err(ledger_store::StoreError::CallCommitted(_)) => Some(true),
|
||||
Err(_) => None,
|
||||
};
|
||||
let settled = match (tag, committed) {
|
||||
(Some(tag), Some(committed)) => settle_vault(&store, &tag, committed),
|
||||
_ => Ok(()),
|
||||
};
|
||||
match (ended, settled) {
|
||||
(Ok(()), Ok(())) => Ok(()),
|
||||
(Ok(()), Err(why)) => Err(CloseError::Committed(why)),
|
||||
(Err(ledger_store::StoreError::CallCommitted(why)), _) => Err(CloseError::Committed(why)),
|
||||
(Err(other), _) => Err(CloseError::NotClosed(other.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ends the open call's claim on this thread, and wakes every request
|
||||
/// that waited for it (`BooksServer::lock`).
|
||||
struct EndsCall<'a>(&'a BooksServer);
|
||||
|
||||
impl Drop for EndsCall<'_> {
|
||||
fn drop(&mut self) {
|
||||
OWNS_CALL.with(|o| o.set(false));
|
||||
CALL_TAG.with(|t| *t.borrow_mut() = None);
|
||||
self.0.store.call_ended();
|
||||
}
|
||||
}
|
||||
|
||||
/// What a call is told when its closing line is saved but the books'
|
||||
/// working copy could not be brought up to it.
|
||||
pub(crate) const COMMITTED_NOT_APPLIED: &str = "this call was completed and counts: its closing line is saved in the books. The books server could not bring its working copy up to date, so it stopped taking requests to protect the books, and rebuilds the copy from the journal when it starts again. Ask the human to restart it. Do not do the work again: sending this call again with the same request_key answers what it answered and changes nothing";
|
||||
|
||||
/// What a call is told when its closing line could not be written.
|
||||
pub(crate) const NOT_CLOSED: &str = "this call could not be completed: its closing line could not be written, so none of it counts, and the books server stopped taking requests to protect the books. Ask the human to restart it, then send the call again with the same request_key";
|
||||
@@ -4769,8 +4769,12 @@ mod tests {
|
||||
assert_eq!(added.len(), 1, "one line");
|
||||
assert_eq!(added[0]["type"], "journal.format_set");
|
||||
let c = ledger_store::format::current();
|
||||
// The declaration also gives older books their id (plan P15 6a).
|
||||
let mut declared = added[0]["payload"].clone();
|
||||
let books_id = declared.as_object_mut().unwrap().remove("books_id");
|
||||
assert_eq!(books_id.and_then(|v| v.as_str().map(str::len)), Some(32));
|
||||
assert_eq!(
|
||||
added[0]["payload"],
|
||||
declared,
|
||||
serde_json::json!({"format": c.format, "features": c.features})
|
||||
);
|
||||
assert_eq!(done.head.0, backup.head.0 + 1);
|
||||
|
||||
+157
-10
@@ -222,6 +222,14 @@ pub struct SharedStore {
|
||||
running: std::sync::atomic::AtomicUsize,
|
||||
/// Woken whenever one ends.
|
||||
ended: tokio::sync::Notify,
|
||||
/// The write turn (calls.rs INVARIANT 2): held for a write call's
|
||||
/// whole run, from its key being looked up to its closing line, and
|
||||
/// for the owner's format upgrade, so a call's lines are one run in
|
||||
/// the journal.
|
||||
writes: tokio::sync::Mutex<()>,
|
||||
/// Woken when a call's closing line is done (calls.rs INVARIANT 2):
|
||||
/// the requests that waited for the open call to close.
|
||||
call_over: (std::sync::Mutex<()>, std::sync::Condvar),
|
||||
/// The books' base currency, fixed at their creation: read without
|
||||
/// the lock (the connect text names it).
|
||||
currency: Currency,
|
||||
@@ -240,6 +248,31 @@ impl SharedStore {
|
||||
Ok(f(store))
|
||||
}
|
||||
|
||||
/// Wait for the write turn (calls.rs INVARIANT 2). Blocking, on a
|
||||
/// blocking thread, as the store's lock is; unlike it, the turn is
|
||||
/// held across a call's awaits, so its guard is `Send`.
|
||||
pub(crate) fn write_turn(&self) -> tokio::sync::MutexGuard<'_, ()> {
|
||||
self.writes.blocking_lock()
|
||||
}
|
||||
|
||||
/// Wake every request that waits for the open call to close.
|
||||
pub(crate) fn call_ended(&self) {
|
||||
self.call_over.1.notify_all();
|
||||
}
|
||||
|
||||
/// Wait (a moment, then look again) for the open call to close.
|
||||
fn wait_for_call(&self) {
|
||||
let held = self
|
||||
.call_over
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let _ = self
|
||||
.call_over
|
||||
.1
|
||||
.wait_timeout(held, std::time::Duration::from_millis(25));
|
||||
}
|
||||
|
||||
/// Run `f` on the store under its lock, writing: the owner's format
|
||||
/// upgrade, after its backup (backup.rs). Blocking. Refused once the
|
||||
/// books are closing or the server stopped (INVARIANTS 2, 3), counted
|
||||
@@ -257,6 +290,8 @@ impl SharedStore {
|
||||
if self.closing() {
|
||||
return Err("the books are closing".into());
|
||||
}
|
||||
// Not inside a tool's call: its lines are a run of their own.
|
||||
let _turn = self.write_turn();
|
||||
let mut store = self.store.blocking_lock();
|
||||
if self.stopped() {
|
||||
return Err(STOPPED.to_string());
|
||||
@@ -310,6 +345,9 @@ impl SharedStore {
|
||||
|
||||
/// Share an open store.
|
||||
pub fn new(store: Store) -> Arc<Self> {
|
||||
// Tax-id vault records a crash left staged are settled by what the
|
||||
// journal says of their call (calls.rs INVARIANT 4).
|
||||
calls::recover_vault(&store);
|
||||
Arc::new(Self {
|
||||
currency: store.base_currency(),
|
||||
store: tokio::sync::Mutex::new(Some(store)),
|
||||
@@ -318,6 +356,8 @@ impl SharedStore {
|
||||
hurry: Arc::default(),
|
||||
running: std::sync::atomic::AtomicUsize::new(0),
|
||||
ended: tokio::sync::Notify::new(),
|
||||
writes: tokio::sync::Mutex::new(()),
|
||||
call_over: (std::sync::Mutex::new(()), std::sync::Condvar::new()),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1014,12 +1054,28 @@ impl BooksServer {
|
||||
if self.store.stopped() {
|
||||
return Err(STOPPED.to_string());
|
||||
}
|
||||
let guard = self.store.store.blocking_lock();
|
||||
// A request that panicked while this one waited stopped it; books
|
||||
// let go hold no store.
|
||||
if self.store.stopped() {
|
||||
return Err(STOPPED.to_string());
|
||||
}
|
||||
// Nothing but the request whose call is open touches the books
|
||||
// until the call's closing line is written (calls.rs INVARIANT 2):
|
||||
// a read never sees what a call did before the call committed.
|
||||
let guard = loop {
|
||||
let guard = self.store.store.blocking_lock();
|
||||
// A request that panicked while this one waited stopped it;
|
||||
// books let go hold no store.
|
||||
if self.store.stopped() {
|
||||
return Err(STOPPED.to_string());
|
||||
}
|
||||
// Only a call that has written a line has effects to hide: one
|
||||
// that has written none (a backup, an upload begun) leaves
|
||||
// reads free.
|
||||
let open = guard
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.in_call() && s.call_has_lines());
|
||||
if !open || calls::owns_call() {
|
||||
break guard;
|
||||
}
|
||||
drop(guard);
|
||||
self.store.wait_for_call();
|
||||
};
|
||||
let Some(store) = guard.as_ref() else {
|
||||
return Err(STOPPED.to_string());
|
||||
};
|
||||
@@ -1514,6 +1570,8 @@ enum ShownDates {
|
||||
mod access_tools;
|
||||
#[path = "tools/backup.rs"]
|
||||
mod backup_tools;
|
||||
#[path = "calls.rs"]
|
||||
mod calls;
|
||||
#[path = "tools/files.rs"]
|
||||
mod files;
|
||||
#[path = "guards.rs"]
|
||||
@@ -1783,11 +1841,17 @@ impl BooksServer {
|
||||
impl ServerHandler for BooksServer {
|
||||
async fn call_tool(
|
||||
&self,
|
||||
request: rmcp::model::CallToolRequestParams,
|
||||
mut request: rmcp::model::CallToolRequestParams,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<rmcp::model::CallToolResponse, rmcp::ErrorData> {
|
||||
use crate::access::{self, Call};
|
||||
use ledger_store::access::Outcome;
|
||||
// The request key is the call's own, not the tool's: out of the
|
||||
// arguments here, so no tool, preview digest or record sees it as
|
||||
// an argument (calls.rs INVARIANT 1). A call writes when its tool
|
||||
// can change the books and it is not a preview.
|
||||
let request_key = calls::take_key(&mut request.arguments);
|
||||
let writing = calls::is_write_call(&request.name, request.arguments.as_ref());
|
||||
let mut call = Call::new(&self.access, &self.board, &context, "tool", &request.name);
|
||||
let outcome_of = |out: &Result<rmcp::model::CallToolResponse, rmcp::ErrorData>| match out {
|
||||
Ok(rmcp::model::CallToolResponse::Complete(r)) if r.is_error != Some(true) => {
|
||||
@@ -1861,7 +1925,16 @@ impl ServerHandler for BooksServer {
|
||||
Err(rmcp::ErrorData::invalid_params(why, None)),
|
||||
)
|
||||
}),
|
||||
};
|
||||
}
|
||||
// A write without a usable request key isn't run (calls.rs
|
||||
// INVARIANT 1).
|
||||
.or_else(|| {
|
||||
if !writing {
|
||||
return None;
|
||||
}
|
||||
calls::key_problem(request_key.as_ref())
|
||||
.map(|why| (calls::MISSING_KEY, Ok(tool_error(why))))
|
||||
});
|
||||
if let Some((code, answer)) = refusal {
|
||||
call.digested(refused_digest(request.arguments.clone()).await);
|
||||
return self.refuse(&call, code, answer).await;
|
||||
@@ -1900,6 +1973,48 @@ impl ServerHandler for BooksServer {
|
||||
});
|
||||
// Counted as running by now (run_blocking): hashed here.
|
||||
let digest = Call::digest_of(request.arguments.as_ref());
|
||||
// A write call is one transaction (calls.rs): it takes its
|
||||
// turn among writes, and is opened, or answered from its
|
||||
// key, before the tool runs.
|
||||
let call_id =
|
||||
request_key
|
||||
.as_ref()
|
||||
.filter(|_| writing)
|
||||
.map(|k| ledger_store::calls::CallId {
|
||||
token: running_call
|
||||
.caller()
|
||||
.map(|c| c.token.id.clone())
|
||||
.unwrap_or_default(),
|
||||
tool: tool_name.clone(),
|
||||
key: calls::key_text(k),
|
||||
// Filled by `calls::begin`: the keyed digest.
|
||||
args: String::new(),
|
||||
});
|
||||
let _turn = call_id.as_ref().map(|_| server.store.write_turn());
|
||||
let early = match &call_id {
|
||||
None => None,
|
||||
Some(id) => match calls::begin(&server, id.clone(), request.arguments.as_ref())
|
||||
{
|
||||
Ok(calls::Begun::Run) => None,
|
||||
Ok(calls::Begun::Answer(answer, code)) => Some((answer, code)),
|
||||
Err(why) => Some((Box::new(tool_error(why)), access::STOPPED)),
|
||||
},
|
||||
};
|
||||
if let Some((answer, code)) = early {
|
||||
// Not run: refused (with the guards a refusal carries),
|
||||
// or answered again from the books as it was first
|
||||
// answered.
|
||||
let answer = if code == calls::REPEAT {
|
||||
Ok(*answer)
|
||||
} else {
|
||||
next_steps::apply(&server, &tool_name, envelope_args.as_ref(), Ok(*answer))
|
||||
};
|
||||
YOU.with(|y| y.borrow_mut().take());
|
||||
let mut c = running_call;
|
||||
c.digested(digest);
|
||||
let recorded = c.record_blocking(Outcome::Refused(code.into()), None);
|
||||
return (answer, recorded);
|
||||
}
|
||||
let tcc =
|
||||
rmcp::handler::server::tool::ToolCallContext::new(&server, request, context);
|
||||
let router = Self::tool_router();
|
||||
@@ -1927,7 +2042,36 @@ impl ServerHandler for BooksServer {
|
||||
}
|
||||
};
|
||||
// The result envelope (next_steps.rs INVARIANT 1).
|
||||
let out = next_steps::apply(&server, &tool_name, envelope_args.as_ref(), out);
|
||||
let mut out = next_steps::apply(&server, &tool_name, envelope_args.as_ref(), out);
|
||||
let stopped = STOPPED_BY_CLOSE.with(|s| s.replace(false));
|
||||
// The call is over: its closing line, holding the answer
|
||||
// the caller is given, commits it (or, for a call that
|
||||
// failed or was stopped, rolls it back). Only then does it
|
||||
// count as done (calls.rs INVARIANT 4).
|
||||
let mut wrote = wrote;
|
||||
if call_id.is_some() {
|
||||
let ok = calls::answered_ok(&out, stopped);
|
||||
match calls::close(&server, &out, ok) {
|
||||
Ok(()) => {}
|
||||
Err(calls::CloseError::NotClosed(why)) => {
|
||||
eprintln!("wanderbooks: a call could not be closed: {why}");
|
||||
server.store.stop();
|
||||
out = Ok(tool_error(calls::NOT_CLOSED.to_string()));
|
||||
}
|
||||
Err(calls::CloseError::Committed(why)) => {
|
||||
eprintln!(
|
||||
"wanderbooks: a call committed, but the books' working copy could not follow: {why}"
|
||||
);
|
||||
server.store.stop();
|
||||
out = Ok(tool_error(calls::COMMITTED_NOT_APPLIED.to_string()));
|
||||
}
|
||||
}
|
||||
// The closing line is this call's last write.
|
||||
wrote = WROTE
|
||||
.with(|w| w.borrow_mut().take())
|
||||
.map(|(seq, hash)| ledger_store::chain::Head { seq, hash })
|
||||
.or(wrote);
|
||||
}
|
||||
// Who asked is the request's alone: a later request on this
|
||||
// thread (a resource read) must not see it.
|
||||
YOU.with(|y| y.borrow_mut().take());
|
||||
@@ -1936,7 +2080,7 @@ impl ServerHandler for BooksServer {
|
||||
c.with_agent(AGENT_NOTE.with(|a| a.borrow_mut().take()));
|
||||
// A call a close stopped is on record as stopped, not as an
|
||||
// answer it gave (local.rs INVARIANT 10).
|
||||
let outcome = if STOPPED_BY_CLOSE.with(|s| s.replace(false)) {
|
||||
let outcome = if stopped {
|
||||
Outcome::Refused(access::STOPPED_BY_CLOSE.into())
|
||||
} else {
|
||||
outcome_of(&out)
|
||||
@@ -1977,6 +2121,9 @@ impl ServerHandler for BooksServer {
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<rmcp::model::ListToolsResult, rmcp::ErrorData> {
|
||||
let mut tools = Self::tool_router().list_all();
|
||||
// Every tool that can change the books takes a request key
|
||||
// (calls.rs INVARIANT 1).
|
||||
tools.iter_mut().for_each(calls::add_key_to_schema);
|
||||
// A token is shown what it can call (scopes.rs); the list then
|
||||
// differs by caller, so it may be cached only for this one.
|
||||
let scopes = crate::access::caller(&context)
|
||||
|
||||
@@ -90,7 +90,7 @@ impl BooksServer {
|
||||
#[tool(
|
||||
name = "books.journal_history",
|
||||
title = "Journal history",
|
||||
description = "The journal in words, in order: each line's seq, time, type and a sentence saying what it did, to what, and the entry it belongs to. Filter by after_seq, types (an exact type like entry.posted, or a group like entry.) and subject (entry:12, invoice:3, bill:3, account:10, party:5, asset:2). The way to trace a figure back to what produced it, and the only way to see what the journal holds. Read-only; at most 200 lines a call.",
|
||||
description = "The journal in words, in order: each line's seq, time, type and a sentence saying what it did, to what, and the entry it belongs to. Filter by after_seq, types (an exact type like entry.posted, or a group like entry.) and subject (entry:12, invoice:3, bill:3, account:10, party:5, asset:2). The way to trace a figure back to what produced it, and the only way to see what the journal holds. A line of a call that failed or never finished is listed and says it did not count. Read-only; at most 200 lines a call.",
|
||||
annotations(read_only_hint = true, open_world_hint = false)
|
||||
)]
|
||||
pub(super) async fn journal_history(
|
||||
|
||||
@@ -921,11 +921,15 @@ impl BooksServer {
|
||||
self.wrote_tins(&store, &w.bytes)?;
|
||||
}
|
||||
let tin_hash = match &tin {
|
||||
Some(t) => Some(vault.put_tin(id, t).map_err(|e| e.to_string())?),
|
||||
Some(t) => {
|
||||
Some(super::calls::put_tin(&vault, id, t).map_err(|e| e.to_string())?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let w9_hash = match &w9_file {
|
||||
Some(w) => Some(vault.put_w9(id, w).map_err(|e| e.to_string())?),
|
||||
Some(w) => {
|
||||
Some(super::calls::put_w9(&vault, id, w).map_err(|e| e.to_string())?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
// The W-9 is in the vault: its upload is used up.
|
||||
@@ -1047,7 +1051,7 @@ impl BooksServer {
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
let vault = self.open_vault(&store, true)?;
|
||||
let hash = vault.put_tin(id, &tin).map_err(|e| e.to_string())?;
|
||||
let hash = super::calls::put_tin(&vault, id, &tin).map_err(|e| e.to_string())?;
|
||||
store
|
||||
.set_party_tin(
|
||||
id,
|
||||
@@ -1238,7 +1242,7 @@ impl BooksServer {
|
||||
if !p.confirmed.unwrap_or(false) {
|
||||
return Ok(Json(out));
|
||||
}
|
||||
ledger_vault::purge_records(&vault_dir, id).map_err(|e| e.to_string())?;
|
||||
super::calls::purge_records(&vault_dir, id).map_err(|e| e.to_string())?;
|
||||
if let Some(f) = new_facts {
|
||||
store.set_party_w9(id, Some(f)).map_err(|e| e.to_string())?;
|
||||
out.journaled = true;
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
//! INVARIANTS:
|
||||
//! 1. Every method only reads.
|
||||
//! 2. A Store and a Snapshot of the same journal answer every method
|
||||
//! alike: the same ledger, settings, journal, journal seq,
|
||||
//! alike: the same ledger, settings, committed journal, journal seq,
|
||||
//! attachments (withdrawn ones included), bytes, statements, and
|
||||
//! reconciliations, and the same entry links once the filing entry
|
||||
//! is added (a store lists it in `links_of`; a snapshot only lists
|
||||
@@ -39,8 +39,12 @@ pub trait PackageBooks {
|
||||
/// package reflects.
|
||||
fn journal_seq(&self) -> u64;
|
||||
|
||||
/// Every journal line, in order: what an entry's origin and its events
|
||||
/// are read from.
|
||||
/// The committed journal, in order: what an entry's origin and its
|
||||
/// events are read from. Only the lines that are facts of the books
|
||||
/// (ledger_store::calls::committed): the lines of a call that failed or
|
||||
/// never finished are not here, because ids are handed out again after
|
||||
/// a failed call and a reader that took them would pin dead lines on
|
||||
/// whatever takes the id next (WB-format-12).
|
||||
fn journal(&self) -> Result<Vec<JournalLine>, StoreError>;
|
||||
|
||||
/// Every attachment (receipts and documents), withdrawn ones
|
||||
@@ -83,9 +87,10 @@ impl PackageBooks for Store {
|
||||
}
|
||||
|
||||
fn journal(&self) -> Result<Vec<JournalLine>, StoreError> {
|
||||
ledger_store::journal::read_and_verify_journal(
|
||||
let lines = ledger_store::journal::read_and_verify_journal(
|
||||
&Store::data_dir(self).join(ledger_store::JOURNAL_FILE),
|
||||
)
|
||||
)?;
|
||||
ledger_store::calls::committed(&lines)
|
||||
}
|
||||
|
||||
fn all_attachments(&self) -> Result<Vec<Attachment>, StoreError> {
|
||||
@@ -134,7 +139,7 @@ impl PackageBooks for Snapshot {
|
||||
}
|
||||
|
||||
fn journal(&self) -> Result<Vec<JournalLine>, StoreError> {
|
||||
Ok(Snapshot::journal(self).to_vec())
|
||||
Snapshot::committed_journal(self)
|
||||
}
|
||||
|
||||
fn all_attachments(&self) -> Result<Vec<Attachment>, StoreError> {
|
||||
|
||||
@@ -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
@@ -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()
|
||||
|
||||
@@ -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}"
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
+115
@@ -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);
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
Opening deposit 1000.00 2026-01-01
|
||||
+1
@@ -0,0 +1 @@
|
||||
Rent again 500.00 2026-01-12
|
||||
+1
@@ -0,0 +1 @@
|
||||
Rent January 500.00 2026-01-05
|
||||
@@ -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"}
|
||||
@@ -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();
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -25,6 +25,15 @@
|
||||
//! 5. `record_hash` is the SHA-256 of a record's bytes on disk, so the
|
||||
//! journal can prove a record existed without holding it.
|
||||
//! 6. Purging deletes the record's file; nothing else keeps a copy.
|
||||
//! 7. A write made for a call that may yet fail is staged, never final:
|
||||
//! `stage_tin`, `stage_w9` and `stage_purge` write a file of another
|
||||
//! name (`.staged-TAG`, `.purging-TAG`) that no reader opens, and
|
||||
//! `settle` makes the call's staged files final, or drops them,
|
||||
//! once it is known whether the call committed. A record is
|
||||
//! therefore never replaced, and never destroyed, by a call that did
|
||||
//! not commit; a crash between the commit and the settle is finished
|
||||
//! by the next `settle`, which the caller asks of every tag left in
|
||||
//! `pending_tags`.
|
||||
//! SCENARIOS:
|
||||
//! 1. IF the key file is missing: `open` creates one (mode 0600) only when
|
||||
//! asked to (`create_key`), else the vault is locked (Error::NoKey).
|
||||
@@ -268,6 +277,16 @@ impl Vault {
|
||||
}
|
||||
|
||||
fn seal(&self, party: u64, kind: Kind, plain: &[u8]) -> Result<String, Error> {
|
||||
self.seal_to(&self.path(party, kind), party, kind, plain)
|
||||
}
|
||||
|
||||
fn seal_to(
|
||||
&self,
|
||||
target: &Path,
|
||||
party: u64,
|
||||
kind: Kind,
|
||||
plain: &[u8],
|
||||
) -> Result<String, Error> {
|
||||
let mut nonce = [0u8; NONCE_LEN];
|
||||
getrandom::getrandom(&mut nonce).map_err(|e| Error::Io(std::io::Error::other(e)))?;
|
||||
let aad = Self::aad(party, kind);
|
||||
@@ -286,7 +305,7 @@ impl Vault {
|
||||
out.extend_from_slice(&nonce);
|
||||
out.extend_from_slice(&ct);
|
||||
std::fs::create_dir_all(&self.dir)?;
|
||||
write_private(&self.path(party, kind), &out)?;
|
||||
write_private(target, &out)?;
|
||||
Ok(hex::encode(Sha256::digest(&out)))
|
||||
}
|
||||
|
||||
@@ -323,6 +342,30 @@ impl Vault {
|
||||
self.seal(party, Kind::Tin, &plain)
|
||||
}
|
||||
|
||||
/// [`Vault::put_tin`] staged for the call `tag` (INVARIANT 7): the
|
||||
/// record is written, and its hash returned, but under a name no
|
||||
/// reader opens until [`settle`] makes it final.
|
||||
pub fn stage_tin(&self, party: u64, tin: &Tin, tag: &str) -> Result<String, Error> {
|
||||
let plain = Zeroizing::new(serde_json::to_vec(tin).expect("serializes"));
|
||||
self.seal_to(
|
||||
&staged_path(&self.dir, party, Kind::Tin, tag)?,
|
||||
party,
|
||||
Kind::Tin,
|
||||
&plain,
|
||||
)
|
||||
}
|
||||
|
||||
/// [`Vault::put_w9`] staged for the call `tag` (INVARIANT 7).
|
||||
pub fn stage_w9(&self, party: u64, file: &W9File, tag: &str) -> Result<String, Error> {
|
||||
let plain = Zeroizing::new(serde_json::to_vec(file).expect("serializes"));
|
||||
self.seal_to(
|
||||
&staged_path(&self.dir, party, Kind::W9, tag)?,
|
||||
party,
|
||||
Kind::W9,
|
||||
&plain,
|
||||
)
|
||||
}
|
||||
|
||||
/// A party's TIN, if the vault holds one.
|
||||
pub fn tin(&self, party: u64) -> Result<Option<Tin>, Error> {
|
||||
match self.open_record(party, Kind::Tin)? {
|
||||
@@ -369,6 +412,125 @@ fn record_path(dir: &Path, party: u64, kind: Kind) -> PathBuf {
|
||||
dir.join(format!("{}-{party}.bin", kind.name()))
|
||||
}
|
||||
|
||||
/// A call's tag: 16 lowercase hex digits (the name of the call in file
|
||||
/// names, never a path).
|
||||
fn checked_tag(tag: &str) -> Result<&str, Error> {
|
||||
if tag.len() == 16 && tag.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
|
||||
Ok(tag)
|
||||
} else {
|
||||
Err(Error::Io(std::io::Error::other("not a call tag")))
|
||||
}
|
||||
}
|
||||
|
||||
fn staged_path(dir: &Path, party: u64, kind: Kind, tag: &str) -> Result<PathBuf, Error> {
|
||||
Ok(dir.join(format!(
|
||||
"{}-{party}.staged-{}",
|
||||
kind.name(),
|
||||
checked_tag(tag)?
|
||||
)))
|
||||
}
|
||||
|
||||
fn purging_path(dir: &Path, party: u64, kind: Kind, tag: &str) -> Result<PathBuf, Error> {
|
||||
Ok(dir.join(format!(
|
||||
"{}-{party}.purging-{}",
|
||||
kind.name(),
|
||||
checked_tag(tag)?
|
||||
)))
|
||||
}
|
||||
|
||||
/// Stage the purge of what the vault in `dir` holds for a party, for the
|
||||
/// call `tag` (INVARIANT 7): each record is set aside under a name no
|
||||
/// reader opens, and is deleted only when [`settle`] says the call
|
||||
/// committed (and put back when it didn't). Needs no key. Returns whether
|
||||
/// anything was there.
|
||||
pub fn stage_purge(dir: &Path, party: u64, tag: &str) -> Result<bool, Error> {
|
||||
let mut any = false;
|
||||
for kind in [Kind::Tin, Kind::W9] {
|
||||
let aside = purging_path(dir, party, kind, tag)?;
|
||||
match std::fs::rename(record_path(dir, party, kind), aside) {
|
||||
Ok(()) => any = true,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(Error::Io(e)),
|
||||
}
|
||||
}
|
||||
Ok(any)
|
||||
}
|
||||
|
||||
/// What a call's staged files came to.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Settled {
|
||||
/// Staged records made final.
|
||||
pub promoted: usize,
|
||||
/// Staged records dropped (the call did not commit).
|
||||
pub dropped: usize,
|
||||
/// Purged records deleted (the call committed).
|
||||
pub purged: usize,
|
||||
/// Records put back (the call that set them aside did not commit).
|
||||
pub restored: usize,
|
||||
}
|
||||
|
||||
/// The tags of every call that left a staged or set-aside file in the
|
||||
/// vault in `dir` (INVARIANT 7): the calls whose outcome `settle` is
|
||||
/// still to apply, after a crash.
|
||||
pub fn pending_tags(dir: &Path) -> Result<Vec<String>, Error> {
|
||||
let mut tags = std::collections::BTreeSet::new();
|
||||
let entries = match std::fs::read_dir(dir) {
|
||||
Ok(e) => e,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||
Err(e) => return Err(Error::Io(e)),
|
||||
};
|
||||
for entry in entries {
|
||||
let name = entry?.file_name().to_string_lossy().into_owned();
|
||||
for marker in [".staged-", ".purging-"] {
|
||||
if let Some((_, tag)) = name.split_once(marker)
|
||||
&& checked_tag(tag).is_ok()
|
||||
{
|
||||
tags.insert(tag.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(tags.into_iter().collect())
|
||||
}
|
||||
|
||||
/// Apply the outcome of the call `tag` to its staged files (INVARIANT 7):
|
||||
/// if it `committed`, staged records become the party's records and
|
||||
/// set-aside ones are deleted; if not, staged ones are deleted and
|
||||
/// set-aside ones are put back. Safe to repeat; needs no key.
|
||||
pub fn settle(dir: &Path, tag: &str, committed: bool) -> Result<Settled, Error> {
|
||||
checked_tag(tag)?;
|
||||
let mut done = Settled::default();
|
||||
let entries = match std::fs::read_dir(dir) {
|
||||
Ok(e) => e.collect::<Result<Vec<_>, _>>()?,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(done),
|
||||
Err(e) => return Err(Error::Io(e)),
|
||||
};
|
||||
for entry in entries {
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
let path = entry.path();
|
||||
// `tin-12.staged-TAG`: the record's own name is what's before the
|
||||
// marker, plus `.bin`.
|
||||
if let Some(stem) = name.strip_suffix(&format!(".staged-{tag}")) {
|
||||
if committed {
|
||||
std::fs::rename(&path, dir.join(format!("{stem}.bin")))?;
|
||||
done.promoted += 1;
|
||||
} else {
|
||||
std::fs::remove_file(&path)?;
|
||||
done.dropped += 1;
|
||||
}
|
||||
} else if let Some(stem) = name.strip_suffix(&format!(".purging-{tag}")) {
|
||||
let own = dir.join(format!("{stem}.bin"));
|
||||
if committed || own.exists() {
|
||||
std::fs::remove_file(&path)?;
|
||||
done.purged += 1;
|
||||
} else {
|
||||
std::fs::rename(&path, own)?;
|
||||
done.restored += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(done)
|
||||
}
|
||||
|
||||
/// What the vault in `dir` holds for a party, `(TIN, W-9 file)`, without
|
||||
/// the key: whether each record's file exists (nothing is decrypted).
|
||||
pub fn records_held(dir: &Path, party: u64) -> Result<(bool, bool), Error> {
|
||||
|
||||
@@ -237,3 +237,143 @@ fn purge_and_holdings_need_no_key() {
|
||||
(false, false)
|
||||
);
|
||||
}
|
||||
|
||||
const TAG: &str = "0123456789abcdef";
|
||||
const OTHER: &str = "fedcba9876543210";
|
||||
|
||||
fn tin_a() -> Tin {
|
||||
Tin::new("123-45-6789", TinType::Ssn).unwrap()
|
||||
}
|
||||
|
||||
fn tin_b() -> Tin {
|
||||
Tin::new("765-43-2109", TinType::Ssn).unwrap()
|
||||
}
|
||||
|
||||
/// INVARIANT 7: a staged record is not the party's record: a reader sees
|
||||
/// the old one (or none) until `settle` says the call committed.
|
||||
#[test]
|
||||
fn a_staged_record_is_read_by_no_one_until_its_call_commits() {
|
||||
let d = dir("stage-commit");
|
||||
let v = vault(&d);
|
||||
let old_hash = v.put_tin(7, &tin_a()).unwrap();
|
||||
let new_hash = v.stage_tin(7, &tin_b(), TAG).unwrap();
|
||||
assert_ne!(old_hash, new_hash);
|
||||
// Nothing changed for a reader.
|
||||
assert_eq!(v.tin(7).unwrap().unwrap().last4(), "6789");
|
||||
assert_eq!(
|
||||
v.record_hash(7).unwrap().as_deref(),
|
||||
Some(old_hash.as_str())
|
||||
);
|
||||
assert_eq!(
|
||||
ledger_vault::pending_tags(&d.join("vault")).unwrap(),
|
||||
[TAG.to_string()]
|
||||
);
|
||||
let done = ledger_vault::settle(&d.join("vault"), TAG, true).unwrap();
|
||||
assert_eq!(done.promoted, 1);
|
||||
assert_eq!(v.tin(7).unwrap().unwrap().last4(), "2109");
|
||||
assert_eq!(
|
||||
v.record_hash(7).unwrap().as_deref(),
|
||||
Some(new_hash.as_str())
|
||||
);
|
||||
assert!(
|
||||
ledger_vault::pending_tags(&d.join("vault"))
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
// Settling again changes nothing.
|
||||
assert_eq!(
|
||||
ledger_vault::settle(&d.join("vault"), TAG, true).unwrap(),
|
||||
Default::default()
|
||||
);
|
||||
}
|
||||
|
||||
/// INVARIANT 7: a call that did not commit leaves the old record whole,
|
||||
/// and nothing of the new one.
|
||||
#[test]
|
||||
fn a_call_that_did_not_commit_leaves_the_old_record_whole() {
|
||||
let d = dir("stage-drop");
|
||||
let v = vault(&d);
|
||||
let old_hash = v.put_tin(7, &tin_a()).unwrap();
|
||||
v.stage_tin(7, &tin_b(), TAG).unwrap();
|
||||
// Another call's staged file is not this call's to settle.
|
||||
v.stage_tin(8, &tin_b(), OTHER).unwrap();
|
||||
let done = ledger_vault::settle(&d.join("vault"), TAG, false).unwrap();
|
||||
assert_eq!(done.dropped, 1);
|
||||
assert_eq!(v.tin(7).unwrap().unwrap().last4(), "6789");
|
||||
assert_eq!(
|
||||
v.record_hash(7).unwrap().as_deref(),
|
||||
Some(old_hash.as_str())
|
||||
);
|
||||
assert_eq!(
|
||||
ledger_vault::pending_tags(&d.join("vault")).unwrap(),
|
||||
[OTHER.to_string()]
|
||||
);
|
||||
assert!(v.tin(8).unwrap().is_none());
|
||||
}
|
||||
|
||||
/// INVARIANT 7: a purge is destroyed only when its call commits; if it
|
||||
/// doesn't, every record is put back, byte for byte.
|
||||
#[test]
|
||||
fn a_purge_is_final_only_when_its_call_commits() {
|
||||
let d = dir("stage-purge");
|
||||
let v = vault(&d);
|
||||
let hash = v.put_tin(7, &tin_a()).unwrap();
|
||||
v.put_w9(
|
||||
7,
|
||||
&W9File {
|
||||
file_name: "w9.pdf".into(),
|
||||
mime_type: "application/pdf".into(),
|
||||
bytes: b"%PDF fake".to_vec(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(ledger_vault::stage_purge(&d.join("vault"), 7, TAG).unwrap());
|
||||
// Out of sight at once ...
|
||||
assert_eq!(
|
||||
ledger_vault::records_held(&d.join("vault"), 7).unwrap(),
|
||||
(false, false)
|
||||
);
|
||||
// ... and back if the call didn't commit.
|
||||
let undone = ledger_vault::settle(&d.join("vault"), TAG, false).unwrap();
|
||||
assert_eq!(undone.restored, 2);
|
||||
assert_eq!(v.record_hash(7).unwrap().as_deref(), Some(hash.as_str()));
|
||||
assert!(v.w9(7).unwrap().is_some());
|
||||
// Committed: gone for good.
|
||||
ledger_vault::stage_purge(&d.join("vault"), 7, TAG).unwrap();
|
||||
let gone = ledger_vault::settle(&d.join("vault"), TAG, true).unwrap();
|
||||
assert_eq!(gone.purged, 2);
|
||||
assert_eq!(
|
||||
ledger_vault::records_held(&d.join("vault"), 7).unwrap(),
|
||||
(false, false)
|
||||
);
|
||||
assert!(
|
||||
ledger_vault::pending_tags(&d.join("vault"))
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
/// A tag names a call in a file name: anything else is refused, so it can't
|
||||
/// name a path.
|
||||
#[test]
|
||||
fn a_tag_that_is_not_sixteen_hex_digits_is_refused() {
|
||||
let d = dir("stage-tag");
|
||||
let v = vault(&d);
|
||||
for bad in [
|
||||
"",
|
||||
"../x",
|
||||
"0123456789ABCDEF",
|
||||
"0123456789abcde",
|
||||
"0123456789abcdefg",
|
||||
] {
|
||||
assert!(v.stage_tin(7, &tin_a(), bad).is_err(), "{bad}");
|
||||
assert!(
|
||||
ledger_vault::stage_purge(&d.join("vault"), 7, bad).is_err(),
|
||||
"{bad}"
|
||||
);
|
||||
assert!(
|
||||
ledger_vault::settle(&d.join("vault"), bad, true).is_err(),
|
||||
"{bad}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -611,6 +611,69 @@ with generated URIs, checks after each call that the server still
|
||||
serves, restarts it after them to check the books reopen, and drives
|
||||
every tool over every book in ledger-store's `tests/fixtures/old-books`.
|
||||
|
||||
## Writes: one transaction, one request key (plan P15 2a, D-88)
|
||||
|
||||
Every tool that can change the books (no `readOnlyHint`; 83 of the 140: the
|
||||
three that read what is sealed and put it in a file, `books.vendor_1099`,
|
||||
`books.get_w9` and `books.export_cpa_package`, are annotated so but write
|
||||
nothing and may answer with a full TIN, so they are read like any read)
|
||||
takes one more argument than its own, `request_key`, and its schema says it
|
||||
is required: 8 to 128 characters of plain text the agent makes up, new for
|
||||
each different action and never reused for another. The agent sends the same
|
||||
call again with the same key when its answer is lost; the books do not do it
|
||||
twice, and answer what they answered the first time (a repeat is recorded in
|
||||
the access log as `repeat`, and writes nothing, even after the books were
|
||||
closed and opened). The same key with other arguments, or another tool, is
|
||||
refused in words and changes nothing. A key is the token's own. A write
|
||||
without a usable key is refused in words before it runs. A preview (a tool
|
||||
with `confirmed`, called without `confirmed: true`) writes nothing and needs
|
||||
no key. A failed write changes nothing and leaves its key free: the corrected
|
||||
call may use it; where the call got as far as writing journal lines, the
|
||||
journal says it failed (`call.closed`, outcome `failed`) and none of them
|
||||
count. Every write call is one transaction: its lines commit together with
|
||||
its closing line or not at all, and after a crash a call without its closing
|
||||
line is not treated as done (WB-format-8 to WB-format-10).
|
||||
|
||||
What the books keep of a call, and what a repeat is told:
|
||||
|
||||
- A call that wrote journal lines is framed by `call.begun` and
|
||||
`call.closed`; its closing line keeps the answer (at most 4096 bytes). A
|
||||
repeat of it returns that answer byte for byte. If the answer was longer,
|
||||
the closing line keeps its SHA-256 and length instead, and a repeat is
|
||||
told in words that the call was done, with the journal lines it wrote
|
||||
(`books.journal_history` with `after_seq` lists them), and nothing is
|
||||
done again.
|
||||
- A call that wrote no journal line leaves no line at all. Its key and
|
||||
answer are kept in memory for the life of the server: a repeat within the
|
||||
session gets the same answer, and after a restart a repeat simply runs
|
||||
again, which is harmless because it wrote nothing (`books.back_up_now`,
|
||||
`books.begin_upload`).
|
||||
- "The same arguments" is a keyed digest of them, tax ids included, under a
|
||||
secret of the books' own that is never journaled: two requests that differ
|
||||
only in a tax id are two requests, and the same key with the other tax id
|
||||
is refused.
|
||||
- A write that fails after it wrote lines is on the record
|
||||
(`books.journal_history` lists its lines and says of each that it did not
|
||||
count); ids it took are handed out again to the next call, so a reader
|
||||
that takes the journal raw would pin its dead lines on whatever takes the
|
||||
id next: every reader applies the frame rule, and the journal in words
|
||||
(`books.journal_history`) and the viewer's journal page show every line and
|
||||
say of the ones that did not count that they did not.
|
||||
- A write to the tax-id vault is part of the call: it is final only when the
|
||||
call commits, so a failed or cut call never replaces or destroys a tax id.
|
||||
- A request that arrives while a call that has written a line is still
|
||||
open waits for its closing line: no read shows what a call did before the
|
||||
call committed.
|
||||
- If a call's closing line is saved but the books' working copy cannot be
|
||||
brought up to it, the call is told so in words: it was completed and
|
||||
counts, the books server stopped to protect the books, and sending the call
|
||||
again with the same key answers what it answered and changes nothing.
|
||||
|
||||
Books an older version wrote take no write at all until the owner gives the
|
||||
format upgrade its go-ahead (D-89, WB-format-11): every write is refused,
|
||||
before it runs, with `format_upgrade_pending` and the words "nothing can be
|
||||
written"; every read works as ever. No tool can give the go-ahead.
|
||||
|
||||
## Tool design principles
|
||||
|
||||
- **Narrow tools, explicit arguments.** No "do what I mean" tools. The agent
|
||||
|
||||
@@ -257,3 +257,11 @@ Three new rows, none above changed status, and the floor stands.
|
||||
| Agent dock: Claude Code or Codex in a terminal along the bottom of the viewer, started in the books home; never required | QBO's assistant panel is a cross-check only | partial | `dock_runs_the_chosen_agent`, `agent_missing_offers_the_installer` (`crates/ledger-gui/tests/dock.rs`); Linux checked; macOS by the CI run; Windows not offered (ConPTY unchecked) |
|
||||
| Assistants in the window: each company's state (none, connected, working) as a shape and a word, "Ask your assistant" where a button that edits would be, the Connect page (a row per local tool, the keys with who is on each, Revoke), and a warning before closing the window or a tab with an assistant connected (plan P15 3.3, D-79) | QBO's "Accountant" invitations and Xero's "Advisor" access are a cross-check only | partial | WB-assist-1 to WB-assist-4; `crates/ledger-gui/tests/assistants.rs`; local assistants only: the web half is plan units B1 and B3, the Claude desktop extension C1 |
|
||||
| First run with no terminal: the viewer sets up the private folder, the owner passphrase, the first books and an agent | QBO's "set up your company" flow | partial | `first_run_onboards_with_no_terminal` (`crates/ledger-gui/tests/welcome.rs`); the AppImage's whole path is the EM's to try on a clean machine |
|
||||
|
||||
## P15 T1: every write is one transaction, exactly once (2026-11-21, D-88, D-89)
|
||||
|
||||
| Area | Counterpart (a cross-check, not the spec) | Status | Notes |
|
||||
|---|---|---|---|
|
||||
| A tool call's lines commit together with a closing line or not at all; a call that never closed, or failed, builds nothing in any replay; a failed call is on the record | A database transaction; QBO and Xero make a write all or nothing and say so on failure | partial | WB-format-8, WB-format-10; `ledger-store` `tests/calls.rs` (`a_crash_at_each_point_of_a_call_leaves_the_whole_call_or_none_of_it`, `a_replay_of_any_prefix_inside_a_call_is_the_replay_of_the_prefix_before_it`, `a_failed_call_is_on_the_record_and_builds_nothing`); partial until the Lean law is in bookspec and a `done` needs a golden |
|
||||
| Every write carries a request key; a repeat returns the first answer and writes nothing, across a restart; the same key for another request is refused | An idempotency key (a payments API's `Idempotency-Key`); QBO's `requestid` | partial | WB-format-9; `ledger-cli` `tests/call_transactions.rs` (`a_repeat_of_a_key_returns_the_first_answer_and_writes_nothing`, `the_same_key_for_another_request_is_refused_in_words`, `every_tool_that_can_write_asks_for_a_key_and_no_other_does`); `books.import_bank_csv` is one transaction (`the_import_is_one_transaction`) |
|
||||
| Books that haven't declared the feature take no write and still read; every set of books has a unique id | No counterpart; the owner's rule (D-89) | partial | WB-format-11, WB-format-12; `ledger-store` `tests/calls.rs` (`books_that_have_not_declared_the_feature_take_no_call_and_still_read`, `new_books_are_born_with_an_id_and_no_two_share_one`); `ledger-cli` `tests/format_upgrade.rs` (`books_p2_served_cut_over_whole`) |
|
||||
@@ -196,6 +196,30 @@ 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 | answer_sha256 + answer_bytes | error}` after its last. `args`
|
||||
is an HMAC-SHA256 of the call's arguments under the books' own secret
|
||||
(`keys/calls.key`), never a plain hash (a tax id would be guessable). The
|
||||
lines between count only when `outcome` is `ok` (then `answer` is the
|
||||
text of the answer given, kept so a repeat of `key` returns it, when at
|
||||
most 4096 bytes; above that `answer_sha256` and `answer_bytes` stand in
|
||||
its place); `failed` and `unfinished` (written by the open that finds a
|
||||
call that never closed) say the lines in the frame never count, in any
|
||||
replay. A call that wrote no line has no frame and no closing line (its
|
||||
key and answer are kept in memory for the life of the server only). A
|
||||
line outside a frame applies as ever, so every journal written before
|
||||
the feature replays as it was. **Every reader that derives a fact reads
|
||||
the committed journal** (`calls::committed`: the lines outside a frame and
|
||||
those of `ok` frames), because ids are handed out again after a failed
|
||||
call and a raw reader would pin the dead lines on whatever takes the id
|
||||
next; a reader that shows history shows every line and says of the dead
|
||||
ones that they did not count (`calls::standings`). `store.created` carries
|
||||
`books_id` (the books' own unique id) in books made since the feature;
|
||||
older books are given one in the `journal.format_set` of their upgrade.
|
||||
Neither frame line moves the audit's figure head.
|
||||
- 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.
|
||||
|
||||
+153
-3
@@ -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,155 @@ 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 journal lines
|
||||
frames them: `call.begun { tool, token, key, args }` just before its first
|
||||
line, and `call.closed { tool, token, key, args, outcome, first_seq,
|
||||
last_seq, answer | answer_sha256 + answer_bytes | error }` when it is over,
|
||||
`outcome` being `ok` (the answer given is `answer`, kept as text so a repeat
|
||||
returns it byte for byte, when it is at most 4096 bytes; above that the line
|
||||
keeps `answer_sha256`, the SHA-256 of the answer, and `answer_bytes`, its
|
||||
length, so every closing line is bounded), `failed` (`error` says how), or
|
||||
`unfinished` (written by the next open of books whose last call never
|
||||
closed). `args` is a keyed digest of the call's arguments (WB-format-9). A
|
||||
call that wrote no journal line has no frame and no closing line: there is
|
||||
nothing to frame, and nothing it did can be half done. The lines between a
|
||||
begin and its close count only when the close says `ok`: that is how a reader
|
||||
tells a complete call from an incomplete one. Every replay (opening the
|
||||
books, the viewer, verify, rebuild, the projection a restart catches up) goes
|
||||
through one rule (`CallGate`): a line outside a frame applies at once (every
|
||||
line before the books declared `call_transactions`, and the owner's own acts:
|
||||
the format declaration, a repaired tail); a line inside a frame waits, and is
|
||||
applied with its closing line when that says `ok`, and never when it says
|
||||
`failed` or `unfinished` or when no closing line follows. So no state is
|
||||
built from half a call, and a replay of any prefix that ends inside a call
|
||||
equals the replay of the prefix before it. A close must name the frame it
|
||||
ends (its `first_seq` is the begin line's, its `last_seq` the line before
|
||||
it); a frame that begins inside another, a close with no frame, or a close
|
||||
that does not match is a corrupt journal. The projection keeps a call's
|
||||
changes in one SQLite transaction, released only after the `ok` closing line
|
||||
is on disk. When the books are opened and the journal's last call never
|
||||
closed, its lines are not applied, it is closed `unfinished` before anything
|
||||
else is written, and a projection that holds its lines is rebuilt. The
|
||||
envelope `{seq, ts, type, payload, prev}` is untouched: the feature adds two
|
||||
line types (`call_transactions`, WB-format-2) and nothing else. Calls take
|
||||
turns: the server runs one write call at a time, so a call's lines are one
|
||||
run in the journal. `books.import_bank_csv` is one transaction like every
|
||||
other write (plan P15 6a).
|
||||
|
||||
**Every reader of the journal applies the frame rule, because ids are reused
|
||||
after a failed call.** A failed call's entry, account, party and document ids
|
||||
were never taken (nothing it wrote counted), so the next call hands them out
|
||||
again; a reader that took the raw lines would pin the dead lines of a failed
|
||||
call on whatever took the id next (a failed `books.create_bill` for entry 42,
|
||||
then a manual entry 42, would read as a "Bill"). So a reader that derives a
|
||||
fact (an entry's origin and events, an asset's trail, a party's events, an
|
||||
attention item, a package, what adopting books would keep) reads the
|
||||
committed journal (`committed`: the lines outside any call and those of calls
|
||||
that closed `ok`, the frame lines left out) and never the raw one; a reader
|
||||
that shows history (the viewer's journal page, `books.journal_history`)
|
||||
shows every line and says in words of each line of a call that failed, never
|
||||
finished or is still running that it did not count (`Standing`, `standings`).
|
||||
Backups and restores copy the journal's bytes whole and read none of its
|
||||
facts. The reader's view of a running call: a viewer reads a call's lines only
|
||||
once its closing line is read; a request on the server that arrives between a
|
||||
call's tool finishing and its closing line, when the call has written a line,
|
||||
waits for the close, so no read shows what a call did before the call
|
||||
committed.
|
||||
*Enforced:* `ledger_store::calls` (`CallGate`, `gate_all`, `standings`, `committed`, `Standing`, `closed_of`, `begun_of`, `ANSWER_CAP`, `Store::begin_call`, `Store::close_call`), `Store::open`, `Store::verify`, `Store::rebuild`, `Snapshot::refresh`, `Snapshot::committed_journal`, `Snapshot::journal_standings`, `Store::journal_history`, `history_standing`, ledger-package `PackageBooks`, ledger-gui `Books::build`, `adopt`, `format::CALL_TRANSACTIONS`, ledger-mcp `SharedStore::write_turn`, `BooksServer::lock`.
|
||||
*Checked:* `ledger-store` `tests/calls.rs` (`a_call_is_framed_and_its_answer_kept_by_key`, `a_call_that_wrote_nothing_leaves_no_line_and_is_remembered_for_the_session`, `a_long_answer_is_kept_as_its_hash_and_a_repeat_is_told_in_words_what_was_done`, `the_committed_journal_leaves_out_the_lines_of_a_call_that_failed`, `a_crash_at_each_point_of_a_call_leaves_the_whole_call_or_none_of_it`, `a_replay_of_any_prefix_inside_a_call_is_the_replay_of_the_prefix_before_it`, `a_viewer_applies_a_call_only_when_it_closes`, `a_frame_that_does_not_close_what_it_follows_is_corrupt`, `a_call_cannot_begin_inside_another_or_after_a_failed_close`, `a_call_whose_begin_line_the_projection_refuses_still_closes_its_frame`, `books_the_version_before_call_transactions_wrote_open_and_report_the_same_figures`), `tests/store.rs` (`books_written_under_older_rules_still_open`, `books_an_earlier_version_wrote_open_to_its_figures`), the unit test `call_transactions_is_its_own_feature` in `format.rs`, `tests/format.rs` (`every_event_the_store_replays_passes_the_gate`); `ledger-gui` `tests/view_model.rs` (`a_failed_calls_lines_are_not_facts_when_its_ids_are_used_again`: the viewer's books, the feed attention reads, and the history after a failed call and an id handed out again); `ledger-cli` `tests/call_transactions.rs` (`a_call_is_one_frame_in_the_journal_closed_with_its_answer`, `the_import_is_one_transaction`, `a_call_that_wrote_lines_and_then_failed_leaves_the_books_and_its_key_as_they_were`).
|
||||
|
||||
**WB-format-9 Every write call carries a request key, and a repeat of it
|
||||
writes nothing.** Every tool that can change the books (no `readOnlyHint`;
|
||||
83 of the 140: the three that only read what is sealed, `books.vendor_1099`,
|
||||
`books.get_w9` and `books.export_cpa_package`, write nothing and may answer with
|
||||
a full TIN, so they are reads) takes a required `request_key`, 8 to 128 characters of plain
|
||||
text, which the agent makes up, new for each action. A write without a usable
|
||||
key is refused in words before it runs; a preview (a confirmed tool called
|
||||
without `confirmed: true`) writes nothing and needs none. The key is taken out
|
||||
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 same arguments" is a keyed digest
|
||||
(`args_mac`): HMAC-SHA256 over the arguments' canonical JSON, unmasked, under
|
||||
a secret of the books' own (`keys/calls.key`, 32 random bytes, made on first
|
||||
need, mode 0600, never journaled, logged or answered), so two requests that
|
||||
differ only in a tax id are two requests, and nothing journaled lets anyone
|
||||
recover or test a guess of a tax id (a plain hash of nine digits would be
|
||||
guessable). The key file is part of the books' keys folder and travels with
|
||||
its backups; books restored without it refuse a repeat of an older key as a
|
||||
misuse of the key (nothing is changed), never as a repeat. The key table is
|
||||
rebuilt at every open from the `ok` closing lines alone and holds one small
|
||||
entry per committed call, no answers: a repeat reads its answer from the
|
||||
closing line. A call that answered `ok` but wrote no journal line leaves no
|
||||
line, so its key and answer are kept in memory for the life of the server
|
||||
only, in a table bounded at 512 calls and 2 MiB of answers, oldest first out
|
||||
(an answer above 4096 bytes is not kept); a repeat within the session gets
|
||||
the same answer, and after a restart a repeat simply runs again, which is
|
||||
harmless because it wrote nothing (`books.back_up_now` and `books.begin_upload`
|
||||
are such calls: a second backup or a second empty upload slot is no harm).
|
||||
A call that wrote lines and whose answer was above 4096 bytes is repeated in
|
||||
words: it says the call was done, with its journal lines, the answer's
|
||||
length and SHA-256, that the answer was too long to keep, and writes
|
||||
nothing. A repeat that arrives while its original is still running waits for
|
||||
it (calls take turns) and gets its answer. An answer is kept as given: no
|
||||
tool answer holds a full TIN, and the three tools that can are no
|
||||
transaction; an error text that holds one is kept masked (BS-partner-2: no
|
||||
journal line holds one).
|
||||
*Enforced:* ledger-mcp `calls::is_write_call`, `calls::key_problem`, `calls::begin`, `calls::close`, `calls::add_key_to_schema`, `Store::recorded_call`, `Keys`, `Replay`, `args_mac`, `Store::args_mac`, `hmac_sha256_hex`, `ANSWER_CAP`, `SESSION_KEYS_MAX`.
|
||||
*Checked:* `ledger-cli` `tests/call_transactions.rs` (`a_repeat_of_a_key_returns_the_first_answer_and_writes_nothing`, `the_same_key_for_another_request_is_refused_in_words`, `a_write_without_a_usable_key_is_not_run`, `every_tool_that_can_write_asks_for_a_key_and_no_other_does`, `the_same_key_under_two_tokens_is_two_calls`, `a_repeat_arriving_while_its_original_runs_gets_its_answer_and_changes_nothing`, `a_repeat_of_a_call_whose_answer_was_too_long_is_told_it_was_done`, `a_call_that_wrote_nothing_leaves_no_line_and_is_answered_again_only_within_the_session`, `a_key_reused_for_another_tax_id_is_refused_not_repeated`); `ledger-store` `tests/calls.rs` (`a_call_is_framed_and_its_answer_kept_by_key`, `the_sessions_key_table_is_bounded_in_count_and_in_bytes`, `a_long_answer_is_kept_as_its_hash_and_a_repeat_is_told_in_words_what_was_done`) and the unit tests `hmac_sha256_matches_rfc_4231` and `args_mac_tells_tax_ids_apart_and_holds_none` in `calls.rs`.
|
||||
|
||||
**WB-format-10 A failed write is on the record, and builds nothing.** A call
|
||||
that answers with an error, is stopped by a close, or fails any other way
|
||||
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. Nothing a call writes outside the journal is final before
|
||||
the call commits: the tax-id vault's writes (`books.set_tin`, `books.set_w9`,
|
||||
`books.purge_tin`) are staged under names no reader opens and made final when
|
||||
the call's closing line is written, or dropped (and a purge put back) when
|
||||
the call fails; a crash between the closing line and that settling is
|
||||
finished at the next start by what the journal says of the call, so a failed
|
||||
or cut call never replaces or destroys a record (`ledger_vault::settle`,
|
||||
`pending_tags`). A call whose closing line cannot be written has not
|
||||
committed; the store takes no further write, and the books server stops, as
|
||||
it does when an access record cannot be written. A call whose closing line
|
||||
*is* on disk but whose projection cannot be brought up to it has committed:
|
||||
the store heals from the journal where it can, and where it cannot says so
|
||||
(`StoreError::CallCommitted`: the call was completed and counts, do not do
|
||||
it again), stops taking writes, and is rebuilt at the next open.
|
||||
*Enforced:* `Store::close_call`, `StoreError::CallCommitted`, ledger-mcp `calls::answered_ok`, `calls::close`, `calls::recover_vault`, `calls::put_tin`, `calls::purge_records`, `calls::settle_vault`, `ledger_vault::stage_tin`, `ledger_vault::stage_w9`, `ledger_vault::stage_purge`, `ledger_vault::settle`, `ledger_vault::pending_tags`.
|
||||
*Checked:* `ledger-store` `tests/calls.rs` (`a_failed_call_is_on_the_record_and_builds_nothing`, `a_call_that_wrote_nothing_leaves_no_line_and_is_remembered_for_the_session`, `a_closing_line_on_disk_but_sqlite_failing_is_a_call_that_counts`); `ledger-vault` `tests/vault.rs` (`a_staged_record_is_read_by_no_one_until_its_call_commits`, `a_call_that_did_not_commit_leaves_the_old_record_whole`, `a_purge_is_final_only_when_its_call_commits`); `ledger-cli` `tests/call_transactions.rs` (`a_failed_write_leaves_the_books_and_its_key_as_they_were`, `a_call_that_wrote_lines_and_then_failed_leaves_the_books_and_its_key_as_they_were`, `a_crash_with_the_ok_close_on_disk_but_sqlite_not_committed_leaves_the_call_done_once`, `a_set_tin_that_fails_leaves_the_vault_as_it_was`, `a_crash_between_the_commit_and_the_vault_settling_is_finished_at_the_next_start`).
|
||||
|
||||
**WB-format-11 Books that have not declared `call_transactions` take no
|
||||
write.** (The owner, 2026-11-20, D-89.) This replaces WB-format-3's "everything
|
||||
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`
|
||||
|
||||
@@ -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",
|
||||
|
||||
Reference in new issue
Block a user