From 49ae7c0d135226e2cce0f0f0316b76562e122a26 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Fri, 20 Nov 2026 20:20:24 -0700 Subject: [PATCH] fix(store): a stopped heal leaves no copy and no rebuild, and the bound names the heal verify_and_heal copied the database aside before looking at the stop, so a verification or an open that was stopped right after finding a drift left a .mismatch copy behind. The look now comes first (heal_drift), before anything is done: a stopped heal leaves the database and the folder exactly as they were. The rebuild and its verification stay unstoppable once begun, since stopped half way the live ledger would be part replayed. INVARIANT 10's close bound said that heal was one pass over the journal and named no term for it. It is about six (three in the rebuild, three in the verification) plus the copy and one hash of each stored file, so it is now the fourth named exception to the bound, with that cost, and 'an open stops anywhere' says where it cannot. Test: a stop before the heal leaves no copy and no rebuild; the same drift heals when not stopped. It fails with the look moved back after the copy. Co-Authored-By: Claude Sonnet 5.5 --- crates/ledger-mcp/src/local.rs | 37 ++++++++++++----- crates/ledger-store/src/cancel.rs | 2 + crates/ledger-store/src/store.rs | 53 +++++++++++++++--------- crates/ledger-store/tests/store.rs | 66 ++++++++++++++++++++++++++++++ 4 files changed, 128 insertions(+), 30 deletions(-) diff --git a/crates/ledger-mcp/src/local.rs b/crates/ledger-mcp/src/local.rs index 2f37ff4b..d767ab6f 100644 --- a/crates/ledger-mcp/src/local.rs +++ b/crates/ledger-mcp/src/local.rs @@ -129,9 +129,11 @@ //! is recorded as made); a stopped verification changed nothing. //! Two points of no return: `books.verify` heals a drifted database //! by rebuilding it from the journal, begun only if no stop was -//! asked before it, and then run to its end (stopped half way it -//! would leave the live ledger part replayed; it is one pass over -//! the journal, and only after a drift); and a format upgrade: a +//! asked before it (the look comes before the database is copied +//! aside, so a stopped heal leaves no `.mismatch` copy and no +//! rebuild), and then run to its end (stopped half way it would +//! leave the live ledger part replayed; it is the fourth named +//! exception below, and only after a drift); and a format upgrade: a //! stop is honoured up to its final look (made once the archive is //! proven, just before the `journal.format_set` line is appended); //! one that arrives after that look still upgrades and records @@ -179,16 +181,20 @@ //! the book is opened, which is itself stopped by the server's close //! and by a close of its id (the same stop the job held), left closed //! (its answer says so). Create's is the making of its folder, after which -//! it makes one empty book. Open has none: it stops anywhere (the -//! book is left closed, intact). +//! it makes one empty book. Open stops at every look of its +//! verification (the book is left closed, intact), but for one +//! place: once it has begun to heal a drifted database it finishes +//! the heal (the fourth named exception below); a stop asked before +//! the heal begins leaves no copy of the database either. //! Every other call does work bounded by the size of one request: its //! arguments, one entry, one stored file (at most MAX_UPLOAD) read, //! hashed or extracted (local CPU, no wait on a client, a disk of -//! another's or the network). Three calls are neither stoppable nor -//! bounded by one request's size, and they are the named exceptions to -//! the close's bound below, each with its worst case, which a close that -//! meets it waits for in full (nothing enforces a bound on them: that is -//! a defect to be closed, not a promise kept): +//! another's or the network). Three calls, and one step inside two +//! stoppable ones, are neither stoppable nor bounded by one request's +//! size, and they are the named exceptions to the close's bound below, +//! each with its worst case, which a close that meets it waits for in +//! full (nothing enforces a bound on them: that is a defect to be +//! closed, not a promise kept): //! - `books.import_bank_csv`: a file of up to MAX_UPLOAD is rehearsed //! whole, then written row by row, each row journaled, and a close //! doesn't stop it. Worst case: a full import of the largest file @@ -199,12 +205,21 @@ //! - `books.export_cpa_package` once it has journaled a decision (above). //! Worst case: one build of the package over the whole book (every //! stored file it holds read once). +//! - the heal of a drifted database, once begun, in `books.verify` and +//! in an open (ledger_store `verify_and_heal`, cancel INVARIANT 4): +//! the rebuild and its verification are shielded from the stop, and +//! met only after a drift. Worst case: the copy of the database, +//! and about six passes over the journal (three by the rebuild: +//! read and chain-checked, applied to the database, replayed; +//! three by the verification: read and chain-checked, replayed, +//! applied to a fresh projection), and each stored file read and +//! hashed once. //! The close is bounded, from its start, by the sum of these named //! terms, each enforced by code, and nothing else: //! a. T_calls: the longest ordinary call already running with its //! whole body (bounded by one request, above; none is cut or //! killed; nothing a client does lengthens it), or, for a -//! stoppable call, T_stop, or, for a call of the three named +//! stoppable call, T_stop, or, for a call or step of the four named //! exceptions above, its worst case (the bound is these terms, //! with that term unbounded by code while one of them runs); //! b. ANSWER_GRACE for the answers on their way out, counted from diff --git a/crates/ledger-store/src/cancel.rs b/crates/ledger-store/src/cancel.rs index 2a4b8e63..f9bb0a45 100644 --- a/crates/ledger-store/src/cancel.rs +++ b/crates/ledger-store/src/cancel.rs @@ -26,6 +26,8 @@ //! stop is looked at before it begins, never inside it. The database's //! rebuild from the journal (`verify_and_heal`, healing a drift) is //! one: stopped part way it would leave the live ledger part replayed. +//! The look comes before ANYTHING is done for the heal (the database +//! copied aside included), so a stopped heal leaves nothing behind. //! ``` use crate::error::StoreError; diff --git a/crates/ledger-store/src/store.rs b/crates/ledger-store/src/store.rs index 05747765..ec6ae4b5 100644 --- a/crates/ledger-store/src/store.rs +++ b/crates/ledger-store/src/store.rs @@ -6375,31 +6375,15 @@ impl Store { /// healed: none. /// 2. IF the projection or ledger diverged (VerifyMismatch): SHOULD copy /// the database aside, rebuild from the journal, verify again, and - /// report why it healed. + /// report why it healed. A stop asked before the copy leaves no + /// copy and no rebuild; from the copy on none is looked at. /// 3. IF the journal itself fails: SHOULD refuse /// - NEVER touch the journal. /// ``` pub fn verify_and_heal(&mut self) -> Result { let healed = match self.verify() { Ok(()) => None, - Err(StoreError::VerifyMismatch(why)) => { - let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string(); - let keep = self.db_path.with_extension(format!("mismatch.{stamp}")); - std::fs::copy(&self.db_path, &keep)?; - eprintln!( - "wanderbooks: {why}; kept the old database as {} beside it and rebuilt from the journal", - keep.file_name().unwrap_or_default().to_string_lossy() - ); - // A stop is looked at before the rebuild begins, never in it - // (cancel INVARIANT 4): half-rebuilt, the live ledger would - // be part replayed. - crate::cancel::check()?; - crate::cancel::shielded(|| -> Result<(), StoreError> { - self.rebuild()?; - self.verify() - })?; - Some(why) - } + Err(StoreError::VerifyMismatch(why)) => Some(self.heal_drift(why)?), Err(e) => return Err(e), }; let lines = read_and_verify_journal(self.journal.path())?; @@ -6415,6 +6399,37 @@ impl Store { }) } + /// The healing of a drifted projection (`verify_and_heal`), `why` being + /// what verification found. A stop is looked at FIRST, before the + /// database is copied aside or anything is touched: a stopped heal + /// leaves no `.mismatch` copy and no rebuild (cancel INVARIANT 4). From + /// the copy on, nothing looks at a stop: the rebuild and its second + /// verification are shielded, because stopped part way the live ledger + /// would be left part replayed. Their cost is the copy of the database + /// and about six passes over the journal (the rebuild reads and + /// chain-checks it, applies it to the database and replays it into the + /// ledger; the verification reads and chain-checks it, replays it and + /// applies it to a fresh projection), and each stored file read and + /// hashed once by the verification: a named term of the books server's + /// close bound (ledger-mcp local.rs INVARIANT 10), met only after a + /// drift. + #[doc(hidden)] + pub fn heal_drift(&mut self, why: String) -> Result { + crate::cancel::check()?; + let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string(); + let keep = self.db_path.with_extension(format!("mismatch.{stamp}")); + std::fs::copy(&self.db_path, &keep)?; + eprintln!( + "wanderbooks: {why}; kept the old database as {} beside it and rebuilt from the journal", + keep.file_name().unwrap_or_default().to_string_lossy() + ); + crate::cancel::shielded(|| -> Result<(), StoreError> { + self.rebuild()?; + self.verify() + })?; + Ok(why) + } + /// The SHA-256 of every stored file the books name (receipts and /// documents, withdrawn ones included). pub fn stored_blob_shas(&self) -> Result, StoreError> { diff --git a/crates/ledger-store/tests/store.rs b/crates/ledger-store/tests/store.rs index befd3ddd..b2fa05e8 100644 --- a/crates/ledger-store/tests/store.rs +++ b/crates/ledger-store/tests/store.rs @@ -883,6 +883,72 @@ fn vendor_1099_tags_replay_and_project() { } } +/// A stop asked before a heal begins leaves nothing behind (cancel INVARIANT +/// 4, store.rs `heal_drift`): no `.mismatch` copy of the database and no +/// rebuild, the database exactly as it was (still drifted), and the stop is +/// the answer. Healed with no stop, the same drift heals. +#[test] +fn a_stop_before_a_heal_leaves_no_copy_and_no_rebuild() { + let dir = test_dir("heal-stopped"); + let mut store = build_books(&dir); + let e = store + .ledger() + .posted_entries() + .next() + .map(|e| e.id()) + .unwrap(); + store + .attach_receipt(Some(e), "r.png", "image/png", b"receipt", None) + .unwrap(); + drop(store); + let db = dir.join(ledger_store::db_file()); + let conn = rusqlite::Connection::open(&db).unwrap(); + conn.execute("UPDATE attachments SET entry_id = NULL", []) + .unwrap(); + drop(conn); + let mut store = Store::open(&dir).unwrap(); + let Err(StoreError::VerifyMismatch(why)) = store.verify() else { + panic!("the drift wasn't found"); + }; + let files = |dir: &std::path::Path| { + let mut names: Vec = std::fs::read_dir(dir) + .unwrap() + .filter_map(|d| d.ok()) + .map(|d| d.file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + names + }; + let (names, db_bytes) = (files(&dir), std::fs::read(&db).unwrap()); + { + // The stop arrives after the drift was found, before the heal. + let _stop = ledger_store::cancel::scope(std::sync::Arc::new( + std::sync::atomic::AtomicBool::new(true), + )); + assert!(matches!( + store.heal_drift(why.clone()), + Err(StoreError::Cancelled) + )); + } + assert_eq!(files(&dir), names, "a stopped heal left a copy behind"); + assert_eq!( + std::fs::read(&db).unwrap(), + db_bytes, + "a stopped heal rebuilt the database" + ); + assert!( + matches!(store.verify(), Err(StoreError::VerifyMismatch(_))), + "still drifted: nothing was rebuilt" + ); + // Not stopped, the same drift heals, keeping its copy. + let report = store.verify_and_heal().unwrap(); + assert!(report.healed.is_some()); + assert!( + files(&dir).iter().any(|n| n.contains(".mismatch.")), + "the divergent database is kept for forensics" + ); +} + #[test] fn the_whole_projection_is_checked_and_healed() { let dir = test_dir("heal");