Files
wanderbooks/crates/ledger-gui/tests/newer_journal.rs
T
swaitsandClaude Opus 5.5 aec55b8d12 Store: say "newer wanderbooks", not "corrupt", for books from a newer version
An unknown event type on a whole, chained line, or a journal.format_set
declaring a newer journal format, now raises StoreError::NewerJournal
(update wanderbooks) instead of JournalCorrupt. Corruption (bad hash,
seq, or JSON) is still corruption. The gate runs in the store, the
Snapshot and the GUI, after each line's parse, seq and hash checks, and
never skips a line it can't read. Adds the journal.format_set event
(format 1 today; nothing writes it yet) and a registry of every event
type this version reads, tested against the replay and projection arms.

Review fixes (P0 review, 2026-10-16):
- A line's own hash is checked only by the next line's prev, and the
  gate used to refuse a line before reading the next: a flipped bit in a
  middle line's type (or a format_set edited from 1 to 2) was reported
  as "newer, the books are not damaged". Now the reader settles every
  refusal against the next line (format::settle): a next line that
  doesn't chain makes it corrupt; one that chains makes it newer and
  verified; with no next line the message says "newer or damaged; update,
  then run verify", never "not damaged" (NewerJournal.verified).
- A newer format number is judged newer before its features are parsed:
  a newer format may shape them differently.
- Snapshot treats a blank complete line as corrupt, as the writer does.
- docs/spec/rules.md B-27, which the code cites, now exists.

Round-2 review fixes (2026-10-16):
- The envelope {seq, ts, type, payload, prev} and its hash (SHA-256 of
  the canonical JSON) are frozen across formats (rules.md B-27); new
  fields go in payload. settle reads only the next line's prev, leniently,
  so a newer format's next line (a float, a string seq, keys of its own)
  is never called corrupt: no readable prev means unverified newer.
- A key beside the envelope's was silently dropped (and the chain then
  broke as "corrupt"): it is now NewerJournal, hashed over the raw
  canonical JSON so the next line still checks it; JournalLine::parse
  refuses such a line.
- "the books are not damaged" overclaimed: a verified refusal says line N
  is intact and this version can't check the lines after it.
- The writer read the journal with BufRead::lines (invalid UTF-8 was an
  I/O error); it now splits bytes on newlines as the Snapshot does, so a
  non-UTF-8 line is JournalCorrupt in both.
- Store::open truncated a torn tail before the gate ran, altering newer
  books (perhaps mid-append) before refusing them. The gate now runs over
  the complete lines first; the tail is set aside (and journaled) only
  when they pass.
- Mutation testing (docs/testing.md, P0): the viewer and the writer say
  the same words about the same damaged line (the newline is no part of
  it); read_journal_and_format returns every line and the format in
  force; the journal page tells a format declaration.
Plan: plan/served.md P0 and 5.1.

Review round 3 (S6, S7). Store::open replays every complete line in
memory (the first line's currency, then the ledger) before a cut-off
last line is set aside, so a complete line the books can't apply
refuses the open with the journal byte for byte as it was and nothing
set aside (B-27 SCENARIO 3; test
a_bad_complete_line_before_a_torn_tail_leaves_the_journal_as_it_was);
catch_up now only projects. The viewer
applies the writer's first-line rule (created_currency, shared) instead
of guessing USD: any other first line, or a store.created without a
sound base_currency, is corrupt to both (test
the_first_line_is_store_created_for_the_viewer_and_the_writer). fuzz_store_replay varies the
first line (14,696 runs clean).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01T3gXMVt7XJPi6ens1or9Dj
2026-10-17 00:32:42 -06:00

165 lines
5.8 KiB
Rust

//! Books written by a newer wanderbooks: the viewer says to update, never
//! that the books are corrupt, on its first load and while following them.
//!
//! ```text
//! GOAL: Stephen, Kat or the CPA, on an older viewer, learn to update it,
//! not that the books are damaged.
//! SOURCE: rules.md B-27; plan/served.md 5.1 (the viewer reads the journal
//! directly, so it meets the same gate).
//! ```
use chrono::NaiveDate;
use ledger_core::{AccountType, Currency};
use ledger_gui::data::{self, Loader, Source, Update};
use ledger_store::{JOURNAL_FILE, JournalWriter, Store};
use serde_json::json;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
fn books(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("ledger-gui-gate-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let data = dir.join("books-data");
let mut store = Store::create(&data, Currency::USD).unwrap();
store
.add_account("1000", "Checking", AccountType::Asset, None, false)
.unwrap();
data
}
fn source(data: &Path) -> Source {
Source {
data_dir: data.to_path_buf(),
books_toml: None,
today: NaiveDate::from_ymd_opt(2026, 10, 16),
}
}
fn rate() -> serde_json::Value {
json!({"currency": "EUR", "date": "2026-10-01", "rate": "1.10"})
}
/// The last line can't be checked: the viewer says so, and never that the
/// books are not damaged (rules.md B-27).
fn says_newer_or_damaged(text: &str) {
assert!(text.starts_with("Journal line"), "{text}");
assert!(text.contains("or the line is damaged"), "{text}");
assert!(text.contains("Update wanderbooks"), "{text}");
assert!(!text.contains("not damaged"), "{text}");
}
fn says_update(text: &str) {
assert!(
text.starts_with("These books were written by a newer version of wanderbooks"),
"{text}"
);
assert!(text.contains("Update wanderbooks"), "{text}");
assert!(!text.contains("corrupt"), "{text}");
}
/// Opening: a newer event type, or a newer declared format, reads as
/// "update"; a damaged journal still reads as corrupt.
#[test]
fn the_viewer_says_update_for_newer_books_and_corrupt_for_damaged_ones() {
for (tag, line_type, payload) in [
("type", "settings.set", json!({"key": "company.name"})),
(
"format",
"journal.format_set",
json!({"format": 2, "features": []}),
),
] {
let data = books(tag);
let mut w = JournalWriter::open(&data.join(JOURNAL_FILE)).unwrap();
w.append(line_type, payload.clone()).unwrap();
// The next line chains onto it: its bytes are checked.
w.append("fx.rate_set", rate()).unwrap();
let err = data::load_once(&source(&data))
.err()
.expect("newer books loaded");
says_update(&err);
// As the last line nothing checks it: newer, or damaged.
let data = books(&format!("{tag}-last"));
JournalWriter::open(&data.join(JOURNAL_FILE))
.unwrap()
.append(line_type, payload)
.unwrap();
let err = data::load_once(&source(&data))
.err()
.expect("newer books loaded");
says_newer_or_damaged(&err);
}
let data = books("damaged");
let path = data.join(JOURNAL_FILE);
let text = std::fs::read_to_string(&path).unwrap();
std::fs::write(&path, text.replacen("\"prev\":\"", "\"prev\":\"1", 2)).unwrap();
let err = data::load_once(&source(&data))
.err()
.expect("damaged books loaded");
assert!(err.contains("journal corrupt"), "{err}");
assert!(!err.contains("newer"), "{err}");
}
/// Following: the viewer has the books open when a newer wanderbooks
/// writes a line this one can't read. It says to update, and keeps the
/// books it had.
#[test]
fn a_live_viewer_says_update_when_the_books_move_ahead_of_it() {
let data = books("live");
let loader = Loader::spawn(source(&data), egui::Context::default());
match loader.wait(Duration::from_secs(10)) {
Some(Update::Books(_)) => {}
_ => panic!("no initial load"),
}
let mut w = JournalWriter::open(&data.join(JOURNAL_FILE)).unwrap();
w.append("entry.evidence_inherited", json!({"entry_id": 1}))
.unwrap();
w.append("fx.rate_set", rate()).unwrap();
let deadline = Instant::now() + Duration::from_secs(10);
let mut said = None;
while Instant::now() < deadline {
match loader.wait(Duration::from_millis(200)) {
Some(Update::Error(e)) => {
said = Some(e);
break;
}
Some(Update::Books(_)) => panic!("the viewer read a line it doesn't know"),
_ => {}
}
}
says_update(&said.expect("the viewer never said to update"));
}
/// A declared format this version reads opens like any books, and the
/// journal page tells it as its own event (it is no step of an entry).
#[test]
fn a_format_this_version_reads_opens_and_the_journal_page_tells_it() {
let data = books("current-format");
let mut w = JournalWriter::open(&data.join(JOURNAL_FILE)).unwrap();
w.append(
ledger_store::format::FORMAT_SET,
json!({"format": ledger_store::format::SUPPORTED_JOURNAL_FORMAT, "features": []}),
)
.unwrap();
w.append("fx.rate_set", rate()).unwrap();
let b = data::load_once(&source(&data)).expect("books in a format this version reads");
let told: Vec<_> = b
.journal
.iter()
.filter(|l| l.line_type == ledger_store::format::FORMAT_SET)
.map(|l| ledger_gui::pages::journal::describe(&b, l).map(|e| (e.text, e.route)))
.collect();
assert_eq!(
told,
[Some((
format!(
"Journal format {} declared",
ledger_store::format::SUPPORTED_JOURNAL_FORMAT
),
None
))]
);
}