From 9ac47a3f108072db4dcdf6bbc3be92814dcc480b Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 21 Nov 2026 19:21:34 -0700 Subject: [PATCH] test(store): damaged pieces are repaired, a drill never passes on an older backup, books ahead and diverged, a disk with no links, headers, sync stand-ins, a destination of 3000 backups Each test fails without the change it covers: the reviewer's sequence (a byte flipped in backup 2's segment, more backups, a drill, a restore), a damaged stored file found by the rotating share, a drill that must fail when only an older manifest is whole, ahead told from diverged with a new set beside the old, the no-link path (and two writers racing on it), sealed pieces in folders, header settings capped and authenticated, one key derivation per setting, files not downloaded yet, vault scratch files, and a destination of 3000 backups made cheaply (12 MB of manifests, 0.8 KB for the newest, 32 ms to find and read it). Co-Authored-By: Claude Fable 5.2 --- crates/ledger-store/src/backup/io.rs | 12 +- crates/ledger-store/src/backup/mod.rs | 36 +- crates/ledger-store/src/backup/read.rs | 52 +- crates/ledger-store/src/backup/seal.rs | 11 + crates/ledger-store/src/backup/tests.rs | 279 ++++++++ crates/ledger-store/src/backup/write.rs | 37 +- crates/ledger-store/tests/backup_disk.rs | 461 +++++++++++++ crates/ledger-store/tests/backup_repair.rs | 741 +++++++++++++++++++++ 8 files changed, 1578 insertions(+), 51 deletions(-) create mode 100644 crates/ledger-store/src/backup/tests.rs create mode 100644 crates/ledger-store/tests/backup_disk.rs create mode 100644 crates/ledger-store/tests/backup_repair.rs diff --git a/crates/ledger-store/src/backup/io.rs b/crates/ledger-store/src/backup/io.rs index cab8a5b8..670ef8c6 100644 --- a/crates/ledger-store/src/backup/io.rs +++ b/crates/ledger-store/src/backup/io.rs @@ -382,6 +382,7 @@ impl SetIo for DirSet { } fn len(&self, rel: &str) -> std::io::Result> { + self.ctx.traced("len", rel); match std::fs::symlink_metadata(self.path(rel)) { // A link is not a file of a backup: it could lead anywhere. Ok(m) if m.is_file() && online_only(&m) => Err(carry(BackupError::NotDownloaded)), @@ -403,6 +404,7 @@ impl SetIo for DirSet { rel: &str, f: &mut dyn FnMut(&mut dyn Read) -> std::io::Result<()>, ) -> std::io::Result<()> { + self.ctx.traced("read", rel); let path = self.path(rel); let meta = match std::fs::symlink_metadata(&path) { Ok(m) => m, @@ -443,7 +445,11 @@ impl SetIo for DirSet { fill(&mut w)?; w.flush()?; } - file.sync_all() + if self.ctx.syncs() { + file.sync_all() + } else { + Ok(()) + } })(); if let Err(e) = written { // Something of ours that failed on its own: its scratch file @@ -474,7 +480,9 @@ impl SetIo for DirSet { return Err(e); } }; - sync_dir(&parent); + if self.ctx.syncs() { + sync_dir(&parent); + } self.ctx.point("published", rel).map_err(carry)?; Ok(put) } diff --git a/crates/ledger-store/src/backup/mod.rs b/crates/ledger-store/src/backup/mod.rs index 96f769ea..0c0401ec 100644 --- a/crates/ledger-store/src/backup/mod.rs +++ b/crates/ledger-store/src/backup/mod.rs @@ -67,12 +67,14 @@ mod io; mod read; mod seal; mod single; +#[cfg(test)] +mod tests; mod write; pub use cut::Cut; pub use read::list; pub use read::{Candidate, Found, Verified, drill, find, prove_local, verify_found}; -pub use seal::BackupKey; +pub use seal::{BackupKey, key_derivations}; pub use single::{FILE_EXTENSION, save_file}; pub use write::{ Destination, Options, Written, holds_only_sealed, set_name_for, write_destination, @@ -223,8 +225,16 @@ pub struct Ctx { /// refuse to replace. no_links: bool, no_noreplace: bool, + /// Tests: nothing is synced to disk (a destination of thousands of + /// backups is made quickly; a real one never is). + no_sync: bool, + /// Tests: told each read and length look at a file of the set. + trace: Option, } +/// A test's look at which files of a set are read or measured. +pub type Trace = Arc; + impl std::fmt::Debug for Ctx { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("Ctx") @@ -267,6 +277,30 @@ impl Ctx { self } + /// Told, in tests, each `read` and `len` of a file of a set. + #[doc(hidden)] + pub fn with_trace(mut self, trace: Trace) -> Self { + self.trace = Some(trace); + self + } + + pub(crate) fn traced(&self, kind: &str, rel: &str) { + if let Some(t) = &self.trace { + t(kind, rel); + } + } + + /// Nothing is synced to disk (tests that make thousands of backups). + #[doc(hidden)] + pub fn with_no_sync(mut self) -> Self { + self.no_sync = true; + self + } + + pub(crate) fn syncs(&self) -> bool { + !self.no_sync + } + pub(crate) fn refuses_links(&self) -> bool { self.no_links } diff --git a/crates/ledger-store/src/backup/read.rs b/crates/ledger-store/src/backup/read.rs index 5957bc35..2665ccb4 100644 --- a/crates/ledger-store/src/backup/read.rs +++ b/crates/ledger-store/src/backup/read.rs @@ -510,28 +510,27 @@ impl Set { ))), } } +} - /// The index of stored files a manifest names. - pub(crate) fn index(&self, m: &Manifest) -> Result, BackupError> { - let mut text = VecSink::default(); - self.read_series(&m.files, Kind::Index, &mut text)?; - let mut out = Vec::new(); - let mut seen = BTreeSet::new(); - for line in text.bytes.split(|b| *b == b'\n').filter(|l| !l.is_empty()) { - let l: IndexLine = serde_json::from_slice(line).map_err(|_| { - BackupError::Damaged("the backup's index of stored files is damaged".into()) - })?; - if !is_sha(&l.sha256) { - return Err(BackupError::Damaged( - "the backup's index of stored files names a file by no hash".into(), - )); - } - if seen.insert(l.sha256.clone()) { - out.push(l); - } +/// The index of stored files in `text` (one `{"sha256","bytes"}` per +/// line), each file once. +pub(crate) fn parse_index(text: &[u8]) -> Result, BackupError> { + let mut out = Vec::new(); + let mut seen = BTreeSet::new(); + for line in text.split(|b| *b == b'\n').filter(|l| !l.is_empty()) { + let l: IndexLine = serde_json::from_slice(line).map_err(|_| { + BackupError::Damaged("the backup's index of stored files is damaged".into()) + })?; + if !is_sha(&l.sha256) { + return Err(BackupError::Damaged( + "the backup's index of stored files names a file by no hash".into(), + )); + } + if seen.insert(l.sha256.clone()) { + out.push(l); } - Ok(out) } + Ok(out) } fn short(sha: &str) -> &str { @@ -825,18 +824,9 @@ fn materialize( let mut index = BTreeSet::new(); let mut lines = Vec::new(); if index_damage.is_empty() { - for line in text.bytes.split(|b| *b == b'\n').filter(|l| !l.is_empty()) { - let l: IndexLine = serde_json::from_slice(line).map_err(|_| { - BackupError::Damaged("the backup's index of stored files is damaged".into()) - })?; - if !is_sha(&l.sha256) { - return Err(BackupError::Damaged( - "the backup's index of stored files names a file by no hash".into(), - )); - } - if index.insert(l.sha256.clone()) { - lines.push(l); - } + for l in parse_index(&text.bytes)? { + index.insert(l.sha256.clone()); + lines.push(l); } } damaged.extend(index_damage); diff --git a/crates/ledger-store/src/backup/seal.rs b/crates/ledger-store/src/backup/seal.rs index 853752a2..73e00a94 100644 --- a/crates/ledger-store/src/backup/seal.rs +++ b/crates/ledger-store/src/backup/seal.rs @@ -102,12 +102,23 @@ fn header_aad(kdf: &Kdf) -> Vec { .into_bytes() } +/// How many keys this program has derived from a passphrase (tests: a +/// folder of sealed sets costs one derivation per distinct setting). +static DERIVATIONS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// How many keys have been derived by this process. +#[doc(hidden)] +pub fn key_derivations() -> usize { + DERIVATIONS.load(std::sync::atomic::Ordering::SeqCst) +} + fn stretch(passphrase: &str, kdf: &Kdf) -> Result, BackupError> { if !kdf_in_bounds(kdf) { return Err(BackupError::Damaged( "its header asks for a key this program won't derive".into(), )); } + DERIVATIONS.fetch_add(1, std::sync::atomic::Ordering::SeqCst); let salt = hex::decode(&kdf.salt).expect("checked"); let params = Params::new(kdf.m, kdf.t, kdf.p, Some(32)) .map_err(|_| BackupError::Damaged("its header's key settings are not valid".into()))?; diff --git a/crates/ledger-store/src/backup/tests.rs b/crates/ledger-store/src/backup/tests.rs new file mode 100644 index 00000000..3de1c684 --- /dev/null +++ b/crates/ledger-store/src/backup/tests.rs @@ -0,0 +1,279 @@ +//! Tests of the parts of a backup that need what the crate keeps to itself: +//! how a failed link is told from a disk that makes none, what a sync +//! service's stand-ins look like, the share of stored files each backup +//! re-reads, and a destination with thousands of backups. + +use super::Ctx; +use super::cut::Cut; +use super::form::*; +use super::io::{dataless_flags, is_stand_in_name, link_unsupported, placeholder_attributes}; +use super::read::{Set, in_rotation}; +use super::write::{kept_form, write_into_set}; +use std::io::Write; +use std::time::Instant; + +#[test] +fn only_an_error_that_means_no_links_is_taken_to_mean_it() { + use std::io::{Error, ErrorKind}; + assert!(link_unsupported(&Error::from(ErrorKind::Unsupported))); + // The name being taken, a missing folder, a refused permission and a + // full disk are what they say: never a reason to try a rename, which + // replaces. + for kind in [ + ErrorKind::AlreadyExists, + ErrorKind::NotFound, + ErrorKind::PermissionDenied, + ErrorKind::StorageFull, + ErrorKind::Other, + ] { + assert!(!link_unsupported(&Error::from(kind)), "{kind:?}"); + } + #[cfg(unix)] + { + for n in [libc::EPERM, libc::ENOSYS, libc::EOPNOTSUPP, libc::ENOTSUP] { + assert!(link_unsupported(&Error::from_raw_os_error(n)), "errno {n}"); + } + for n in [ + libc::EACCES, + libc::ENOENT, + libc::EEXIST, + libc::ENOSPC, + libc::EIO, + ] { + assert!(!link_unsupported(&Error::from_raw_os_error(n)), "errno {n}"); + } + } +} + +#[test] +fn what_a_sync_service_leaves_for_a_file_it_has_not_downloaded_is_known() { + // iCloud, before macOS 14: `.name.icloud` in the folder. + assert!(is_stand_in_name(".000002.json.icloud")); + assert!(is_stand_in_name(".a.icloud")); + assert!(!is_stand_in_name("000002.json")); + assert!(!is_stand_in_name(".wb-tmp-1-abc")); + assert!(!is_stand_in_name(".icloud")); + // Windows: offline (0x1000), recall on open (0x40000), recall on data + // access (0x400000); a plain file (archive, 0x20) and a read-only one + // (0x1) are not. + for attrs in [0x1000, 0x40000, 0x400000, 0x20 | 0x400000] { + assert!(placeholder_attributes(attrs), "{attrs:#x}"); + } + for attrs in [0x20, 0x1, 0x80, 0x100] { + assert!(!placeholder_attributes(attrs), "{attrs:#x}"); + } + // macOS: SF_DATALESS. + assert!(dataless_flags(0x4000_0000)); + assert!(!dataless_flags(0x0004_0000)); +} + +#[test] +fn a_piece_belongs_to_one_share_and_every_share_is_read_within_sixteen_backups() { + use super::read::ROTATION; + let mut x = 0x2545_f491_4f6c_dd1du64; + for _ in 0..2000 { + // A pseudo-random hash. + let mut sha = String::new(); + while sha.len() < 64 { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + sha.push_str(&format!("{x:016x}")); + } + sha.truncate(64); + for start in [1u64, 2, 17, 255, 3000] { + let reads = (start..start + ROTATION) + .filter(|n| in_rotation(&sha, *n)) + .count(); + assert_eq!(reads, 1, "{sha} from backup {start}"); + } + } +} + +#[test] +fn generations_and_set_names_round_trip() { + assert_eq!(generation_path("files/ab/xyz", 0), "files/ab/xyz"); + assert_eq!(generation_path("files/ab/xyz", 2), "files/ab/xyz.g2"); + assert_eq!(split_generation("files/ab/xyz.g2"), ("files/ab/xyz", 2)); + assert_eq!(split_generation("files/ab/xyz"), ("files/ab/xyz", 0)); + assert_eq!( + split_generation("journal/000001-abcd.g"), + ("journal/000001-abcd.g", 0) + ); + assert_eq!(plain_set_name("con", 1), "wanderbooks-con"); + assert_eq!(plain_set_name("acme", 3), "wanderbooks-acme.3"); + assert_eq!(parse_plain_set_name("wanderbooks-acme"), Some(("acme", 1))); + assert_eq!( + parse_plain_set_name("wanderbooks-acme.3"), + Some(("acme", 3)) + ); + // No book id holds a dot, so a later set is never another book's. + assert_eq!(parse_plain_set_name("wanderbooks-acme.1"), None); + assert_eq!(parse_plain_set_name("acme"), None); +} + +/// A `Set` over a fresh folder, nothing synced. +fn fresh_set(root: &std::path::Path) -> (Set, std::path::PathBuf) { + let at = root.join("disk/wanderbooks-acme"); + (Set::dir(at.clone(), None, &Ctx::new().with_no_sync()), at) +} + +/// What a person's backups look like after a while, made by the real +/// writer: every manifest names every segment once read, but is kept as +/// the one before it and what is new, and a chain is cut at 64. +#[test] +fn the_writers_manifests_chain_to_a_bounded_depth_and_are_proven_link_by_link() { + const N: u64 = 150; + let dir = tempfile::tempdir().unwrap(); + let book = dir.path().join("book"); + std::fs::create_dir(&book).unwrap(); + let ctx = Ctx::new().with_no_sync(); + let (set, at) = fresh_set(dir.path()); + // A journal of made-up lines: the writer never reads one, it hashes the + // bytes and takes the head from the caller. Each backup adds a line. + let mut journal = std::fs::File::create(book.join(crate::JOURNAL_FILE)).unwrap(); + for i in 1..=N { + let line = format!("{{\"seq\":{i},\"pad\":\"{}\"}}", "x".repeat(60)); + writeln!(journal, "{line}").unwrap(); + journal.flush().unwrap(); + let cut = Cut::take("acme", &book, (i, sha_hex(line.as_bytes()))).unwrap(); + let w = write_into_set(&set, &cut, &ctx, false).unwrap(); + assert!(w.new && w.number == i); + } + let mut depths = Vec::new(); + for n in 1..=N { + let m = set.manifest(n).unwrap(); + depths.push(m.depth); + assert_eq!(m.journal.segments.len() as u64, n, "manifest {n}"); + let raw = std::fs::read_to_string(at.join(manifest_path(n, false))).unwrap(); + let stored: Manifest = serde_json::from_str(raw.lines().next().unwrap()).unwrap(); + assert_eq!(stored.depth == 0, stored.base.is_none()); + // A stored manifest that chains names only what is new. + if stored.base.is_some() { + assert_eq!(stored.journal.segments.len(), 1, "manifest {n}"); + assert_eq!(stored.journal.keep as u64, n - 1); + } + } + // Chains of 64: a manifest that names everything at 1, 65, 129. + assert_eq!(depths[0], 0); + assert_eq!(depths[63], 63); + assert_eq!(depths[64], 0); + assert_eq!(depths[128], 0); + assert!(depths.iter().all(|d| *d < DELTA_CHAIN)); + + // Each link is proven by the hash its successor holds: a manifest in + // the chain that was changed makes the ones built on it unreadable, and + // the reader takes the newest that still reads, saying how many it + // passed. + let k = N - 5; + let bad = at.join(manifest_path(k, false)); + let mut bytes = std::fs::read(&bad).unwrap(); + let i = bytes.len() / 3; + bytes[i] = if bytes[i] == b'0' { b'1' } else { b'0' }; + std::fs::write(&bad, bytes).unwrap(); + assert!(matches!( + set.manifest(N), + Err(super::BackupError::Damaged(_)) + )); + let (m, passed) = set.newest_whole().unwrap().unwrap(); + assert_eq!((m.number, passed as u64), (k - 1, N - k + 1)); + assert_eq!(m.journal.segments.len() as u64, k - 1); +} + +/// A destination of thousands of backups, made cheaply: the real forms +/// (`kept_form`, `encode_manifest`) written straight into a folder with a +/// one-byte file for each segment, no books and no syncing, then read as +/// a restore reads it. The time and size are printed (the numbers the +/// docs quote) and bounded. +#[test] +fn a_destination_of_thousands_of_backups_stays_small_and_quick_to_read() { + const N: u64 = 3000; + let dir = tempfile::tempdir().unwrap(); + let (set, at) = fresh_set(dir.path()); + std::fs::create_dir_all(at.join("journal")).unwrap(); + std::fs::create_dir_all(at.join(MANIFESTS)).unwrap(); + let made = Instant::now(); + let mut full = Manifest { + format: FORMAT.into(), + version: VERSION, + book: "acme".into(), + number: 0, + written: "2026-11-21T00:00:00Z".into(), + head: Head { + seq: 0, + hash: String::new(), + }, + journal: Series::default(), + access: Series::default(), + files: Series::default(), + file_count: 0, + file_bytes: 0, + vault: Vec::new(), + keys: Vec::new(), + base: None, + depth: 0, + sha: String::new(), + }; + let mut prev: Option = None; + for i in 1..=N { + let name = format!("journal/{i:06}-{i:016x}"); + std::fs::write(at.join(&name), b"x").unwrap(); + full.journal.segments.push(Piece { + file: name, + stored: 1, + bytes: 1, + sha256: format!("{i:064x}"), + }); + full.journal.bytes = i; + full.journal.sha256 = format!("{i:064x}"); + full.number = i; + full.head = Head { + seq: i, + hash: format!("{i:064x}"), + }; + let kept = kept_form(&full, prev.as_ref()); + let bytes = encode_manifest(&kept); + std::fs::write(at.join(manifest_path(i, false)), &bytes).unwrap(); + let mut view = full.clone(); + view.depth = kept.depth; + view.sha = decode_manifest(&bytes).unwrap().sha; + prev = Some(view); + } + let made = made.elapsed(); + + let sizes: Vec = (1..=N) + .map(|n| { + std::fs::metadata(at.join(manifest_path(n, false))) + .unwrap() + .len() + }) + .collect(); + let total: u64 = sizes.iter().sum(); + let largest = *sizes.iter().max().unwrap(); + let newest = *sizes.last().unwrap(); + // What it would have been if every manifest named everything: a + // journal segment is ~170 bytes of a manifest. + let everything: u64 = (1..=N).map(|n| 170 * n).sum(); + + // Read as a restore reads it: the newest found, and whole. + let began = Instant::now(); + let (m, passed) = set.newest_whole().unwrap().unwrap(); + let found_in = began.elapsed(); + assert_eq!((m.number, passed), (N, 0)); + assert_eq!(m.journal.segments.len() as u64, N); + let began = Instant::now(); + let numbers = set.numbers().unwrap().len(); + let listed_in = began.elapsed(); + assert_eq!(numbers as u64, N); + println!( + "{N} backups: manifests {total} bytes in all (named in full each time: ~{everything}), largest {largest}, newest {newest}; made in {made:?}; newest found and whole in {found_in:?}; listed in {listed_in:?}" + ); + assert!(newest < 6 * 1024, "the newest manifest is {newest} bytes"); + assert!(total < everything / 20, "{total} of ~{everything}"); + assert!(found_in.as_secs() < 10, "{found_in:?}"); + // Any manifest in it reads whole (a sample: each read walks a chain). + for n in (1..=N).step_by(131).chain([N - 1]) { + let m = set.manifest(n).unwrap(); + assert_eq!(m.journal.segments.len() as u64, n); + } +} diff --git a/crates/ledger-store/src/backup/write.rs b/crates/ledger-store/src/backup/write.rs index a46b55db..3fd9d03e 100644 --- a/crates/ledger-store/src/backup/write.rs +++ b/crates/ledger-store/src/backup/write.rs @@ -519,9 +519,12 @@ fn plan( cut: &Cut, distrust: &BTreeSet, ctx: &Ctx, -) -> Result<(Manifest, Vec), BackupError> { +) -> Result<(Manifest, Vec, Vec), BackupError> { let keys = set.keys.as_ref(); let mut plans = Vec::new(); + // Damaged pieces this plan comes upon without being asked to repair + // them (the segments of an index it can't read, which it begins again). + let mut noticed: Vec = Vec::new(); if let Some(p) = prev { if p.book != cut.book() { return Err(BackupError::Elsewhere); @@ -570,18 +573,15 @@ fn plan( let mut restart = false; let known: Vec = match prev { Some(p) => { - if p.files.segments.iter().any(|s| distrust.contains(&s.file)) { + let mut text = VecSinkText::default(); + let damaged = set.read_series_lenient(&p.files, Kind::Index, &mut text)?; + let named_bad = p.files.segments.iter().any(|s| distrust.contains(&s.file)); + if !damaged.is_empty() || named_bad { restart = true; + noticed.extend(damaged.into_iter().map(|d| d.file)); Vec::new() } else { - match set.index(p) { - Ok(k) => k, - Err(BackupError::Damaged(_)) => { - restart = true; - Vec::new() - } - Err(e) => return Err(e), - } + super::read::parse_index(&text.0)? } } None => Vec::new(), @@ -694,7 +694,7 @@ fn plan( depth: 0, sha: String::new(), }; - Ok((manifest, plans)) + Ok((manifest, plans, noticed)) } /// Text gathered as a series is read. @@ -715,7 +715,7 @@ impl Sink for VecSinkText { /// The manifest as it is kept: when `prev` (whole, as read) is a link in a /// chain that is not yet [`DELTA_CHAIN`] long, built on it, naming only /// what each series adds to its segments. Otherwise it names everything. -fn kept_form(full: &Manifest, prev: Option<&Manifest>) -> Manifest { +pub(crate) fn kept_form(full: &Manifest, prev: Option<&Manifest>) -> Manifest { let mut m = full.clone(); let Some(p) = prev.filter(|p| p.depth + 1 < DELTA_CHAIN && !p.sha.is_empty()) else { return m; @@ -825,10 +825,11 @@ fn prove_and_repair( cut: &Cut, mut number: u64, mut added: BTreeSet, + noticed: Vec, ctx: &Ctx, ) -> Result { let mut distrust: BTreeSet = BTreeSet::new(); - let mut repaired: Vec = Vec::new(); + let mut repaired: Vec = noticed; for round in 0..=REPAIR_ROUNDS { ctx.phase("proof"); ctx.check("proving the backup")?; @@ -855,7 +856,7 @@ fn prove_and_repair( // them (the stored files are found by their hash and generation). ctx.phase("repair"); let prev = set.manifest(number)?; - let (mut manifest, plans) = plan(set, Some(&prev), cut, &distrust, ctx)?; + let (mut manifest, plans, _) = plan(set, Some(&prev), cut, &distrust, ctx)?; added = BTreeSet::new(); for p in &plans { ctx.check("backing up")?; @@ -898,7 +899,7 @@ pub(crate) fn write_into_set( let prev = set.newest_whole()?.map(|(m, _)| m); let next = numbers.last().map_or(1, |n| n + 1); ctx.phase("plan"); - let (mut manifest, plans) = plan(set, prev.as_ref(), cut, &BTreeSet::new(), ctx)?; + let (mut manifest, plans, noticed) = plan(set, prev.as_ref(), cut, &BTreeSet::new(), ctx)?; if let Some(p) = &prev && manifest.same_content(p) { @@ -921,13 +922,15 @@ pub(crate) fn write_into_set( } } match put_manifest(set, &mut manifest, prev.as_ref(), next, ctx)? { - Some(number) if prove => return prove_and_repair(set, cut, number, added, ctx), + Some(number) if prove => { + return prove_and_repair(set, cut, number, added, noticed, ctx); + } Some(number) => { return Ok(Written { number, head: cut.head().clone(), new: true, - repaired: Vec::new(), + repaired: noticed, files_proven: 0, }); } diff --git a/crates/ledger-store/tests/backup_disk.rs b/crates/ledger-store/tests/backup_disk.rs new file mode 100644 index 00000000..096fd365 --- /dev/null +++ b/crates/ledger-store/tests/backup_disk.rs @@ -0,0 +1,461 @@ +//! Backups onto the disks people really have (WB-backup-18 to WB-backup-22): +//! a disk that makes no hard links (FAT or exFAT on a stick), sealed pieces +//! in folders a small disk can hold, a header that asks for more than it +//! should, and a folder a sync service has not finished putting on this +//! computer. + +use ledger_core::{AccountType, Currency, Money, Side}; +use ledger_store::Store; +use ledger_store::backup::{ + BackupError, BackupKey, Ctx, Cut, Destination, Options, find, key_derivations, verify_found, + write_destination, write_destination_with, +}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +fn usd(s: &str) -> Money { + Money::new(s.parse().unwrap(), Currency::USD) +} + +fn book(dir: &Path) -> Store { + let mut s = Store::create(dir, Currency::USD).unwrap(); + let cash = s + .add_account("1000", "Cash", AccountType::Asset, None, false) + .unwrap(); + let cap = s + .add_account("3000", "Capital", AccountType::Equity, None, false) + .unwrap(); + let e = s + .create_entry( + chrono::NaiveDate::from_ymd_opt(2026, 3, 1).unwrap(), + "Start", + ) + .unwrap(); + s.add_line(e, cash, Side::Debit, usd("100.00")).unwrap(); + s.add_line(e, cap, Side::Credit, usd("100.00")).unwrap(); + s.post_entry(e).unwrap(); + s.attach_receipt(Some(e), "r.pdf", "application/pdf", b"%PDF-1.4 r", None) + .unwrap(); + s +} + +fn more(s: &mut Store, n: usize) { + s.add_account( + &format!("{}", 6000 + n), + &format!("Expense {n}"), + AccountType::Expense, + None, + false, + ) + .unwrap(); + s.attach_receipt( + None, + &format!("f{n}.txt"), + "text/plain", + format!("receipt number {n}").as_bytes(), + None, + ) + .unwrap(); +} + +fn cut(dir: &Path, s: &Store) -> Cut { + Cut::take("acme", dir, s.head()).unwrap() +} + +fn plain(folder: &Path) -> Destination { + Destination { + folder: folder.to_path_buf(), + key: None, + } +} + +fn tree(root: &Path) -> BTreeMap> { + fn walk(base: &Path, dir: &Path, out: &mut BTreeMap>) { + for e in std::fs::read_dir(dir).unwrap() { + let p = e.unwrap().path(); + if p.is_dir() { + walk(base, &p, out); + } else { + let rel = p + .strip_prefix(base) + .unwrap() + .to_string_lossy() + .replace('\\', "/"); + out.insert(rel, std::fs::read(&p).unwrap()); + } + } + } + let mut out = BTreeMap::new(); + if root.is_dir() { + walk(root, root, &mut out); + } + out +} + +fn prove( + source: &Path, + pass: Option<&str>, + root: &Path, + name: &str, +) -> ledger_store::backup::Verified { + let found = find(source, pass, &Ctx::new()).unwrap(); + verify_found(&found, &root.join(name), &Ctx::new()).unwrap() +} + +// --- a disk that makes no hard links --------------------------------------- + +#[test] +fn a_disk_that_makes_no_links_takes_whole_backups_and_only_grows() { + for ctx in [ + Ctx::new().with_no_hard_links(), + // And one whose move cannot refuse to replace either: exclusive + // create and copy. + Ctx::new().with_no_exclusive_move(), + ] { + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let mut s = book(&b); + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + let mut before = BTreeMap::new(); + for n in 0..3 { + more(&mut s, n); + let w = write_destination(&plain(&disk), &cut(&b, &s), true, &ctx).unwrap(); + assert!(w.new && w.repaired.is_empty(), "{w:?}"); + let now = tree(&disk); + for (name, bytes) in &before { + assert_eq!(now.get(name), Some(bytes), "{name} must not change"); + } + assert!(!now.keys().any(|n| n.contains(".wb-tmp-")), "scratch left"); + before = now; + } + let v = prove(&disk, None, dir.path(), "v"); + assert_eq!(v.head, s.head()); + assert_eq!(v.passed_over, 0); + } +} + +#[test] +fn two_writers_racing_on_a_disk_that_makes_no_links_do_not_corrupt_it() { + for exclusive_move_missing in [false, true] { + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let mut s = book(&b); + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + for round in 0..3 { + more(&mut s, round); + let c = cut(&b, &s); + let results: Vec<_> = std::thread::scope(|scope| { + let handles: Vec<_> = (0..3) + .map(|_| { + let (c, disk) = (c.clone(), disk.clone()); + scope.spawn(move || { + let ctx = if exclusive_move_missing { + Ctx::new().with_no_exclusive_move() + } else { + Ctx::new().with_no_hard_links() + }; + write_destination(&plain(&disk), &c, true, &ctx) + }) + }) + .collect(); + handles.into_iter().map(|h| h.join().unwrap()).collect() + }); + for r in &results { + let w = r + .as_ref() + .unwrap_or_else(|e| panic!("round {round}: {e:?}")); + assert_eq!(w.head, s.head()); + } + let v = prove(&disk, None, dir.path(), &format!("v{round}")); + assert_eq!(v.head, s.head()); + assert_eq!(v.passed_over, 0, "round {round}"); + assert!( + !tree(&disk).keys().any(|n| n.contains(".wb-tmp-")), + "scratch left" + ); + } + } +} + +#[test] +fn a_taken_number_or_name_is_never_replaced_on_a_disk_that_makes_no_links() { + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let mut s = book(&b); + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + let ctx = Ctx::new().with_no_hard_links(); + write_destination(&plain(&disk), &cut(&b, &s), true, &ctx).unwrap(); + let set = disk.join("wanderbooks-acme"); + // A rival's manifest 2 is already in place when this one comes to put + // its own as number 2. + more(&mut s, 1); + let rival = disk.join("rival"); + std::fs::create_dir(&rival).unwrap(); + let c = cut(&b, &s); + let taken = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let hook = { + let (set, taken) = (set.clone(), taken.clone()); + Ctx::new() + .with_no_hard_links() + .with_faults(std::sync::Arc::new(move |kind, rel| { + if kind == "create" + && rel.starts_with("manifests/") + && taken.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 + { + std::fs::write(set.join("manifests/000002.json"), b"a rival's, whole").unwrap(); + } + false + })) + }; + let _ = write_destination(&plain(&disk), &c, true, &hook); + assert_eq!( + std::fs::read(set.join("manifests/000002.json")).unwrap(), + b"a rival's, whole", + "the manifest that was there is never replaced" + ); +} + +// --- sealed pieces in folders a small disk can hold -------------------------- + +const PASS: &str = "correct horse battery staple"; + +#[test] +fn sealed_pieces_are_spread_over_folders_as_the_plain_form_does() { + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let mut s = book(&b); + for n in 0..30 { + more(&mut s, n); + } + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + let dest = Destination { + folder: disk.clone(), + key: Some(BackupKey::generate(PASS).unwrap()), + }; + write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap(); + let set = std::fs::read_dir(&disk) + .unwrap() + .flatten() + .find(|e| e.file_name().to_string_lossy().starts_with("sealed-")) + .unwrap() + .path(); + let mut in_folders = 0usize; + for entry in std::fs::read_dir(set.join("pieces")).unwrap().flatten() { + let name = entry.file_name().to_string_lossy().into_owned(); + assert!( + entry.path().is_dir(), + "{name}: a piece sits in a flat folder" + ); + assert_eq!(name.len(), 2, "{name}"); + for piece in std::fs::read_dir(entry.path()).unwrap().flatten() { + assert!( + piece.file_name().to_string_lossy().starts_with(&name), + "a piece is in the folder of its name's first two digits" + ); + in_folders += 1; + } + } + assert!(in_folders > 30, "{in_folders}"); + let v = prove(&disk, Some(PASS), dir.path(), "v"); + assert_eq!(v.head, s.head()); +} + +// --- a header that is read from a folder anyone may have written ------------- + +/// The sealed set's folder in `disk`. +fn sealed_set(disk: &Path) -> PathBuf { + std::fs::read_dir(disk) + .unwrap() + .flatten() + .find(|e| e.file_name().to_string_lossy().starts_with("sealed-")) + .unwrap() + .path() +} + +/// Rewrite the header's key settings and make its own check line right +/// again (what a person who meant to would do). +fn set_header(header: &Path, edit: impl Fn(&mut serde_json::Value)) { + let text = std::fs::read_to_string(header).unwrap(); + let body = text.lines().next().unwrap(); + let mut v: serde_json::Value = serde_json::from_str(body).unwrap(); + edit(&mut v); + let body = serde_json::to_string(&v).unwrap(); + let check = hex::encode(Sha256::digest(body.as_bytes())); + std::fs::write( + header, + format!("{body}\nwanderbooks-header-sha256 {check}\n"), + ) + .unwrap(); +} + +#[test] +fn a_header_cannot_ask_for_more_than_a_few_times_what_this_program_spends() { + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let s = book(&b); + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + let dest = Destination { + folder: disk.clone(), + key: Some(BackupKey::generate(PASS).unwrap()), + }; + write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap(); + let header = sealed_set(&disk).join("header.json"); + let original = std::fs::read(&header).unwrap(); + for (what, value) in [ + ("m", serde_json::json!(4_000_000u32)), + ("m", serde_json::json!(64 * 1024 * 5)), + ("t", serde_json::json!(13)), + ("p", serde_json::json!(5)), + ] { + set_header(&header, |v| v["kdf"][what] = value.clone()); + let derived = key_derivations(); + let err = find(&disk, Some(PASS), &Ctx::new()).err().unwrap(); + // Refused as damage before any key is derived: no memory spent. + assert!( + matches!(err, BackupError::Damaged(_) | BackupError::NotABackup), + "{what}: {err:?}" + ); + assert_eq!(key_derivations(), derived, "{what}: a key was derived"); + } + std::fs::write(&header, &original).unwrap(); + let v = prove(&disk, Some(PASS), dir.path(), "v"); + assert_eq!(v.head, s.head()); +} + +#[test] +fn a_header_that_was_changed_reads_as_damage_and_not_as_a_wrong_passphrase() { + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let s = book(&b); + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + let dest = Destination { + folder: disk.clone(), + key: Some(BackupKey::generate(PASS).unwrap()), + }; + write_destination(&dest, &cut(&b, &s), true, &Ctx::new()).unwrap(); + let header = sealed_set(&disk).join("header.json"); + // A setting changed in the file as a bad sector or a bad sync would: + // the header's own check line no longer matches. + let text = std::fs::read_to_string(&header).unwrap(); + let changed = text.replacen("\"t\":3", "\"t\":4", 1); + assert_ne!(text, changed, "the header names its passes"); + std::fs::write(&header, changed).unwrap(); + let err = find(&disk, Some(PASS), &Ctx::new()).err().unwrap(); + assert!( + matches!(err, BackupError::Damaged(_) | BackupError::NotABackup), + "{err:?}" + ); + // Changed on purpose and made consistent again: the key comes out + // different and opens nothing (the safe way to fail), and no + // passphrase is guessed any faster. + std::fs::write(&header, &text).unwrap(); + set_header(&header, |v| v["kdf"]["t"] = serde_json::json!(4)); + assert!(matches!( + find(&disk, Some(PASS), &Ctx::new()), + Err(BackupError::WrongPassphrase) + )); +} + +#[test] +fn a_folder_of_sealed_sets_costs_one_key_derivation_per_setting_not_one_per_set() { + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let s = book(&b); + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + let dest = Destination { + folder: disk.clone(), + key: Some(BackupKey::generate(PASS).unwrap()), + }; + let c = cut(&b, &s); + write_destination(&dest, &c, true, &Ctx::new()).unwrap(); + for _ in 0..2 { + write_destination_with( + &dest, + &c, + Options { + may_create: true, + new_set: true, + }, + &Ctx::new(), + ) + .unwrap(); + } + let sets = std::fs::read_dir(&disk) + .unwrap() + .flatten() + .filter(|e| e.file_name().to_string_lossy().starts_with("sealed-")) + .count(); + assert_eq!(sets, 3); + let derived = key_derivations(); + // Three sets of one book: it asks which, after one derivation. + let err = find(&disk, Some(PASS), &Ctx::new()).err().unwrap(); + assert!(matches!(err, BackupError::Several(_)), "{err:?}"); + assert_eq!(key_derivations() - derived, 1); +} + +// --- files a sync service has not downloaded --------------------------------- + +#[test] +fn a_file_that_is_not_downloaded_yet_reads_as_such_and_never_as_damage_or_absence() { + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let mut s = book(&b); + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + let set = disk.join("wanderbooks-acme"); + let before = tree(&disk); + + // A piece of the newest backup that iCloud has left as a stand-in + // (`.name.icloud`) in its place. + let manifest = std::fs::read_to_string(set.join("manifests/000001.json")).unwrap(); + let m: serde_json::Value = serde_json::from_str(manifest.lines().next().unwrap()).unwrap(); + let seg = set.join(m["journal"]["segments"][0]["file"].as_str().unwrap()); + let stand_in = seg.with_file_name(format!( + ".{}.icloud", + seg.file_name().unwrap().to_string_lossy() + )); + let held = std::fs::read(&seg).unwrap(); + std::fs::rename(&seg, &stand_in).unwrap(); + let found = find(&disk, None, &Ctx::new()); + // Nothing says "damaged", nothing says "not a backup": it is waiting. + assert_eq!(found.err(), Some(BackupError::NotDownloaded)); + more(&mut s, 1); + assert_eq!( + write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap_err(), + BackupError::NotDownloaded + ); + assert!( + BackupError::NotDownloaded + .to_string() + .contains("not downloaded to this computer yet") + ); + // Downloaded: all as it was. + std::fs::rename(&stand_in, &seg).unwrap(); + assert_eq!(std::fs::read(&seg).unwrap(), held); + assert_eq!(tree(&disk), before); + write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + + // The newest manifest as a stand-in: the folder is listed with it, and + // the writer will not make a manifest under its number. + let newest = set.join("manifests/000002.json"); + let stand = set.join("manifests/.000002.json.icloud"); + std::fs::rename(&newest, &stand).unwrap(); + more(&mut s, 2); + assert_eq!( + write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap_err(), + BackupError::NotDownloaded + ); + assert_eq!( + find(&disk, None, &Ctx::new()).err(), + Some(BackupError::NotDownloaded) + ); +} diff --git a/crates/ledger-store/tests/backup_repair.rs b/crates/ledger-store/tests/backup_repair.rs new file mode 100644 index 00000000..368978fc --- /dev/null +++ b/crates/ledger-store/tests/backup_repair.rs @@ -0,0 +1,741 @@ +//! A backup that restores old or wrong books while reporting good is the +//! worst defect this product can have (WB-backup-12 to WB-backup-17): a +//! damaged piece must not be reused by later backups, the drill must not +//! prove an older backup and say ok, a damaged piece must be found by the +//! proof after the backup and written again beside the damaged file, books +//! that are behind a destination must be told from books that have +//! diverged, and a restore must say when it is not of the newest backup. + +use ledger_core::{AccountType, Currency, Money, Role, Side, TinFacts, TinType}; +use ledger_store::Store; +use ledger_store::backup::{ + BackupError, Ctx, Cut, Destination, Options, drill, find, verify_found, write_destination, + write_destination_with, +}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +fn usd(s: &str) -> Money { + Money::new(s.parse().unwrap(), Currency::USD) +} + +fn book(dir: &Path) -> Store { + let mut s = Store::create(dir, Currency::USD).unwrap(); + let cash = s + .add_account("1000", "Cash", AccountType::Asset, None, false) + .unwrap(); + let cap = s + .add_account("3000", "Capital", AccountType::Equity, None, false) + .unwrap(); + let e = s + .create_entry( + chrono::NaiveDate::from_ymd_opt(2026, 3, 1).unwrap(), + "Start", + ) + .unwrap(); + s.add_line(e, cash, Side::Debit, usd("100.00")).unwrap(); + s.add_line(e, cap, Side::Credit, usd("100.00")).unwrap(); + s.post_entry(e).unwrap(); + s.attach_receipt(Some(e), "r.pdf", "application/pdf", b"%PDF-1.4 r", None) + .unwrap(); + s +} + +fn more(s: &mut Store, n: usize) { + s.add_account( + &format!("{}", 6000 + n), + &format!("Expense {n}"), + AccountType::Expense, + None, + false, + ) + .unwrap(); + s.attach_receipt( + None, + &format!("f{n}.txt"), + "text/plain", + format!("receipt number {n}").as_bytes(), + None, + ) + .unwrap(); +} + +fn cut(dir: &Path, s: &Store) -> Cut { + Cut::take("acme", dir, s.head()).unwrap() +} + +fn plain(folder: &Path) -> Destination { + Destination { + folder: folder.to_path_buf(), + key: None, + } +} + +fn set_of(disk: &Path) -> PathBuf { + disk.join("wanderbooks-acme") +} + +fn tree(root: &Path) -> BTreeMap> { + fn walk(base: &Path, dir: &Path, out: &mut BTreeMap>) { + for e in std::fs::read_dir(dir).unwrap() { + let p = e.unwrap().path(); + if p.is_dir() { + walk(base, &p, out); + } else { + let rel = p + .strip_prefix(base) + .unwrap() + .to_string_lossy() + .replace('\\', "/"); + out.insert(rel, std::fs::read(&p).unwrap()); + } + } + } + let mut out = BTreeMap::new(); + if root.is_dir() { + walk(root, root, &mut out); + } + out +} + +fn copy_tree(from: &Path, to: &Path) { + std::fs::create_dir_all(to).unwrap(); + for e in std::fs::read_dir(from).unwrap() { + let e = e.unwrap(); + let (src, dst) = (e.path(), to.join(e.file_name())); + if src.is_dir() { + copy_tree(&src, &dst); + } else { + std::fs::copy(&src, &dst).unwrap(); + } + } +} + +/// Flip one byte in the middle of a file, as a bad sector or a bad sync +/// would; the file keeps its length. +fn flip(path: &Path) { + let mut bytes = std::fs::read(path).unwrap(); + let at = bytes.len() / 2; + bytes[at] ^= 0x55; + std::fs::write(path, bytes).unwrap(); +} + +/// The manifest `n` of the set, as JSON. +fn manifest(set: &Path, n: u64) -> serde_json::Value { + let text = std::fs::read_to_string(set.join(format!("manifests/{n:06}.json"))).unwrap(); + serde_json::from_str(text.lines().next().unwrap()).unwrap() +} + +/// The newest journal segment a manifest names (the one its backup added). +fn newest_journal_segment(set: &Path, n: u64) -> String { + manifest(set, n)["journal"]["segments"] + .as_array() + .unwrap() + .last() + .unwrap()["file"] + .as_str() + .unwrap() + .to_string() +} + +fn sha(bytes: &[u8]) -> String { + hex::encode(Sha256::digest(bytes)) +} + +#[test] +fn one_damaged_segment_is_found_by_the_next_backup_and_the_drill_does_not_hide_it() { + // The reviewer's sequence: a byte flips in the segment backup 2 wrote; + // backups go on; a drill runs; a restore is made. Before: every later + // backup reused the damaged segment and was recorded good, the drill + // proved backup 1 and said ok, and a restore returned books from long + // ago. + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let mut s = book(&b); + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + let first_head = s.head(); + write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + more(&mut s, 1); + let w2 = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + assert_eq!(w2.number, 2); + assert!(w2.repaired.is_empty()); + let seg = newest_journal_segment(&set_of(&disk), 2); + let damaged = set_of(&disk).join(&seg); + flip(&damaged); + let flipped = std::fs::read(&damaged).unwrap(); + + // The very next backup finds it (its proof re-hashes every journal + // segment its manifest names) and writes the piece again beside it. + more(&mut s, 2); + let w3 = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + assert!(w3.new); + assert_eq!(w3.repaired, vec![seg.clone()], "{w3:?}"); + assert_eq!( + std::fs::read(&damaged).unwrap(), + flipped, + "the damaged file is left exactly where it is" + ); + let again = set_of(&disk).join(format!("{seg}.g1")); + assert!( + again.is_file(), + "the piece is written again as generation 1" + ); + assert_eq!(sha(&std::fs::read(&again).unwrap()), { + let m = manifest(&set_of(&disk), 2); + m["journal"]["segments"].as_array().unwrap().last().unwrap()["sha256"] + .as_str() + .unwrap() + .to_string() + }); + + // Many more backups: none reuses the damaged file, none finds more. + for n in 3..8 { + more(&mut s, n); + let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + assert!(w.new && w.repaired.is_empty(), "{n}: {w:?}"); + } + let last = s.head(); + // The drill proves the newest backup, which reaches the live head. + let got = drill( + &plain(&disk), + "acme", + &b.join("journal.jsonl"), + &dir.path().join("drill"), + Some(&last), + &Ctx::new(), + ) + .unwrap(); + assert_eq!(got, last); + // A restore gives the newest books, not backup 1's. + let found = find(&disk, None, &Ctx::new()).unwrap(); + let v = verify_found(&found, &dir.path().join("restore"), &Ctx::new()).unwrap(); + assert_eq!(v.head, last); + assert_ne!(v.head, first_head); + assert_eq!(v.passed_over, 0); + // Manifests 1, 2, 3, the repair's (4) and the five after it. + assert_eq!(v.number, 9); +} + +#[test] +fn a_drill_never_passes_on_an_older_backup() { + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let mut s = book(&b); + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + more(&mut s, 1); + write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + let second_head = s.head(); + more(&mut s, 2); + write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + let newest_head = s.head(); + // The newest backup's own segment is damaged after it was made, and no + // backup comes after it to find that. + flip(&set_of(&disk).join(newest_journal_segment(&set_of(&disk), 3))); + + // The drill is a failure that says so, with the date of the older one. + let err = drill( + &plain(&disk), + "acme", + &b.join("journal.jsonl"), + &dir.path().join("drill"), + Some(&newest_head), + &Ctx::new(), + ) + .unwrap_err(); + let words = err.to_string(); + match &err { + BackupError::NewestDamaged { + number, + older_from, + newest_from, + } => { + assert_eq!(*number, 3); + assert!(older_from.is_some() && newest_from.is_some(), "{err:?}"); + } + other => panic!("{other:?}"), + } + assert!(words.contains("the newest backup (number 3"), "{words}"); + assert!(words.contains("is damaged; an older one from "), "{words}"); + assert!(!dir.path().join("drill").exists()); + + // A restore passes over it, and the preview can say so: both dates and + // how many it passes over. + let found = find(&disk, None, &Ctx::new()).unwrap(); + let v = verify_found(&found, &dir.path().join("restore"), &Ctx::new()).unwrap(); + assert_eq!(v.number, 2); + assert_eq!(v.head, second_head); + assert_eq!(v.passed_over, 1); + assert!(v.newest_written.is_some() && !v.written.is_empty()); + + // Everything damaged: no older one proves whole either, and it says so. + for n in [1u64, 2] { + flip(&set_of(&disk).join(newest_journal_segment(&set_of(&disk), n))); + } + let err = drill( + &plain(&disk), + "acme", + &b.join("journal.jsonl"), + &dir.path().join("drill2"), + None, + &Ctx::new(), + ) + .unwrap_err(); + assert!( + err.to_string().contains("no older one proves whole either"), + "{err}" + ); +} + +#[test] +fn a_drill_needs_the_newest_backup_to_reach_the_last_one_recorded_good() { + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let mut s = book(&b); + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + let have = s.head(); + more(&mut s, 1); + let recorded = s.head(); + // A backup was recorded good through `recorded`, but the folder's + // newest stops at `have` (a manifest lost to a sync conflict, say). + let err = drill( + &plain(&disk), + "acme", + &b.join("journal.jsonl"), + &dir.path().join("d"), + Some(&recorded), + &Ctx::new(), + ) + .unwrap_err(); + assert!( + err.to_string() + .contains("a backup that was made is not there"), + "{err}" + ); + // The same head with another hash is no better. + let other = (have.0, "0".repeat(64)); + assert!( + drill( + &plain(&disk), + "acme", + &b.join("journal.jsonl"), + &dir.path().join("d"), + Some(&other), + &Ctx::new(), + ) + .is_err() + ); + // And it passes when it reaches what was recorded. + assert_eq!( + drill( + &plain(&disk), + "acme", + &b.join("journal.jsonl"), + &dir.path().join("d"), + Some(&have), + &Ctx::new(), + ) + .unwrap(), + have + ); +} + +#[test] +fn a_damaged_stored_file_is_found_by_the_rotation_and_the_next_backup_repairs_it() { + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let mut s = book(&b); + // Stored files, until one is in the share backup number 2 re-reads + // (the share a file belongs to is its hash's first four digits modulo + // 16: every stored file is re-read within 16 backups). + let mut chosen: Option<(String, Vec)> = None; + for n in 0..400 { + let bytes = format!("a stored file, number {n}").into_bytes(); + s.attach_receipt(None, &format!("s{n}.txt"), "text/plain", &bytes, None) + .unwrap(); + let h = sha(&bytes); + if chosen.is_none() && u64::from_str_radix(&h[..4], 16).unwrap() % 16 == 2 { + chosen = Some((h, bytes)); + } + if chosen.is_some() && n > 5 { + break; + } + } + let (h, bytes) = chosen.expect("some file is in the share"); + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + let rel = format!("files/{}/{h}", &h[..2]); + let piece = set_of(&disk).join(&rel); + flip(&piece); + let flipped = std::fs::read(&piece).unwrap(); + more(&mut s, 1); + let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + assert_eq!(w.number, 2); + assert_eq!(w.repaired, vec![rel.clone()], "{w:?}"); + assert_eq!(std::fs::read(&piece).unwrap(), flipped, "left where it is"); + let again = set_of(&disk).join(format!("{rel}.g1")); + assert_eq!(std::fs::read(&again).unwrap(), bytes); + // Every manifest of the set restores with the file whole (the reader + // takes the generation that hashes right). + let found = find(&disk, None, &Ctx::new()).unwrap(); + let v = verify_found(&found, &dir.path().join("v"), &Ctx::new()).unwrap(); + assert_eq!(v.passed_over, 0); + assert_eq!(v.head, s.head()); + let restored = v.tree.join("blobs").join(&h[..2]).join(&h[2..4]).join(&h); + assert_eq!(std::fs::read(restored).unwrap(), bytes); + // And the next backup carries on without finding it again. + more(&mut s, 2); + let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + assert!(w.new && w.repaired.is_empty(), "{w:?}"); +} + +#[test] +fn a_piece_damaged_as_it_is_written_is_repaired_in_the_same_backup() { + // A piece that is there under its name but is not what its name says + // (a copy that died half way on a disk that takes no links, a bad + // sector) is taken as the piece by a put; the proof finds it. + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let s = book(&b); + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + let set = set_of(&disk); + let flipped_once = Arc::new(Mutex::new(false)); + let ctx = { + let (set, done) = (set.clone(), flipped_once.clone()); + Ctx::new().with_faults(Arc::new(move |kind, rel| { + if kind == "published" && rel.starts_with("files/") { + let mut d = done.lock().unwrap(); + if !*d { + flip(&set.join(rel)); + *d = true; + } + } + false + })) + }; + let w = write_destination(&plain(&disk), &cut(&b, &s), true, &ctx).unwrap(); + assert!(w.new); + assert_eq!(w.repaired.len(), 1, "{w:?}"); + assert!(set.join(format!("{}.g1", w.repaired[0])).is_file()); + let found = find(&disk, None, &Ctx::new()).unwrap(); + let v = verify_found(&found, &dir.path().join("v"), &Ctx::new()).unwrap(); + assert_eq!(v.head, s.head()); +} + +#[test] +fn a_damaged_vault_record_and_an_index_segment_are_written_again_too() { + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let mut s = book(&b); + let vault_bytes = b"a sealed vault record".to_vec(); + std::fs::create_dir_all(b.join("vault")).unwrap(); + std::fs::write(b.join("vault").join("tin-1.bin"), &vault_bytes).unwrap(); + std::fs::create_dir_all(b.join("keys")).unwrap(); + std::fs::write(b.join("keys").join("legacy.key"), "ab".repeat(32)).unwrap(); + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + let set = set_of(&disk); + flip(&set.join(format!("vault/{}", sha(&vault_bytes)))); + let index = manifest(&set, 1)["files"]["segments"][0]["file"] + .as_str() + .unwrap() + .to_string(); + flip(&set.join(&index)); + more(&mut s, 1); + let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + assert!(w.new, "{w:?}"); + assert_eq!(w.repaired.len(), 2, "{w:?}"); + // The newest manifest names the new generations; the restore proves. + let found = find(&disk, None, &Ctx::new()).unwrap(); + let v = verify_found(&found, &dir.path().join("v"), &Ctx::new()).unwrap(); + assert_eq!(v.head, s.head()); + assert_eq!(v.passed_over, 0); + assert_eq!( + std::fs::read(v.tree.join("vault").join("tin-1.bin")).unwrap(), + vault_bytes + ); +} + +#[test] +fn books_behind_the_destination_are_ahead_and_other_books_are_diverged() { + let dir = tempfile::tempdir().unwrap(); + let (b, old, other) = ( + dir.path().join("book"), + dir.path().join("old"), + dir.path().join("other"), + ); + let mut s = book(&b); + // The books as they were: a copy of the folder at this point. + copy_tree(&b, &old); + more(&mut s, 1); + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + let before = tree(&disk); + + // Restored from an older backup: the live journal is the beginning of + // the destination's. That is ahead, and the words say what to do. + let old_store = Store::open(&old).unwrap(); + let err = write_destination( + &plain(&disk), + &Cut::take("acme", &old, old_store.head()).unwrap(), + true, + &Ctx::new(), + ) + .unwrap_err(); + assert!(matches!(err, BackupError::Ahead(..)), "{err:?}"); + let words = err.to_string(); + assert!(words.contains("a longer history of these books"), "{words}"); + assert!(words.contains("start a new backup set"), "{words}"); + assert_eq!(tree(&disk), before, "nothing was written"); + + // Another history under the same id is diverged, said as such (not + // ahead, whichever is longer). + let other_store = book(&other); + let err = write_destination( + &plain(&disk), + &Cut::take("acme", &other, other_store.head()).unwrap(), + true, + &Ctx::new(), + ) + .unwrap_err(); + assert_eq!(err, BackupError::Elsewhere); + assert!(err.to_string().contains("diverged"), "{err}"); + let mut longer = other_store; + for n in 0..4 { + more(&mut longer, n); + } + let err = write_destination( + &plain(&disk), + &Cut::take("acme", &other, longer.head()).unwrap(), + true, + &Ctx::new(), + ) + .unwrap_err(); + assert_eq!(err, BackupError::Elsewhere); + assert_eq!(tree(&disk), before); +} + +#[test] +fn a_new_set_begins_beside_the_old_at_the_persons_request_and_the_old_is_never_touched() { + let dir = tempfile::tempdir().unwrap(); + let (b, old) = (dir.path().join("book"), dir.path().join("old")); + let mut s = book(&b); + copy_tree(&b, &old); + more(&mut s, 1); + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + let before = tree(&disk); + let mut old_store = Store::open(&old).unwrap(); + let old_cut = Cut::take("acme", &old, old_store.head()).unwrap(); + assert!(matches!( + write_destination(&plain(&disk), &old_cut, true, &Ctx::new()), + Err(BackupError::Ahead(..)) + )); + + // At the person's request: a new set, `.2`, beside it. + let w = write_destination_with( + &plain(&disk), + &old_cut, + Options { + may_create: true, + new_set: true, + }, + &Ctx::new(), + ) + .unwrap(); + assert_eq!((w.number, w.new), (1, true)); + assert!( + disk.join("wanderbooks-acme.2/manifests/000001.json") + .is_file() + ); + let after = tree(&disk); + for (name, bytes) in &before { + assert_eq!( + after.get(name), + Some(bytes), + "{name}: the old set is untouched" + ); + } + + // The next ordinary backup goes to the new set, which grows; the old + // one stays as it was. + more(&mut old_store, 9); + let w = write_destination( + &plain(&disk), + &Cut::take("acme", &old, old_store.head()).unwrap(), + true, + &Ctx::new(), + ) + .unwrap(); + assert_eq!(w.number, 2); + assert!( + disk.join("wanderbooks-acme.2/manifests/000002.json") + .is_file() + ); + let after = tree(&disk); + for (name, bytes) in &before { + assert_eq!(after.get(name), Some(bytes), "{name}"); + } + // A drill takes the newest set too. + assert_eq!( + drill( + &plain(&disk), + "acme", + &old.join("journal.jsonl"), + &dir.path().join("d"), + Some(&old_store.head()), + &Ctx::new(), + ) + .unwrap(), + old_store.head() + ); + // The folder now holds two sets of the same books: a restore from it + // asks which (the sets are listed with their dates), never guesses. + assert!(matches!( + find(&disk, None, &Ctx::new()), + Err(BackupError::Several(_)) + )); + let listed = ledger_store::backup::list(&disk); + assert_eq!(listed.len(), 2); + assert!( + listed + .iter() + .all(|c| c.through_seq.is_some() && c.written.is_some()) + ); +} + +#[test] +fn a_set_folder_is_a_legal_name_whatever_the_books_are_called() { + let dir = tempfile::tempdir().unwrap(); + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + for id in ["con", "nul", "aux", "prn", "com1", "lpt9"] { + let b = dir.path().join(format!("book-{id}")); + let s = book(&b); + write_destination( + &plain(&disk), + &Cut::take(id, &b, s.head()).unwrap(), + true, + &Ctx::new(), + ) + .unwrap(); + assert!( + disk.join(format!("wanderbooks-{id}/manifests/000001.json")) + .is_file(), + "{id}" + ); + assert!(!disk.join(id).exists(), "{id}: no reserved name is made"); + } +} + +#[test] +fn only_the_newest_backup_is_tried_in_the_good_case() { + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let mut s = book(&b); + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + for n in 0..6 { + more(&mut s, n); + write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + } + // Each backup added one segment, and each manifest names only its own. + let segments: usize = (1..=6) + .map(|n| { + manifest(&set_of(&disk), n)["journal"]["segments"] + .as_array() + .unwrap() + .len() + }) + .sum(); + assert_eq!(segments, 6); + let probes = Arc::new(Mutex::new(0usize)); + let ctx = { + let probes = probes.clone(); + Ctx::new().with_trace(Arc::new(move |kind, rel| { + if kind == "len" && rel.starts_with("journal/") { + *probes.lock().unwrap() += 1; + } + })) + }; + let found = find(&disk, None, &ctx).unwrap(); + let v = verify_found(&found, &dir.path().join("v"), &ctx).unwrap(); + assert_eq!(v.number, 6); + // One look at each journal segment of the newest manifest to find the + // set's book, one to prove it: never the segments of the five older + // manifests, which reading every manifest first would have measured + // too (1 + 2 + ... + 6 more). + assert_eq!(*probes.lock().unwrap(), 2 * segments); +} + +#[test] +fn a_backup_cut_while_the_vault_is_being_written_restores_a_vault_that_matches_the_journal() { + // ledger-vault stages a record as `NAME.staged-TAG` and sets the old one + // aside as `NAME.purging-TAG` while a call is between its first step and + // its last. A backup taken then must hold the vault as the journal says + // it is: the staged record is not the books' yet, and the set-aside one + // still is. + let dir = tempfile::tempdir().unwrap(); + let b = dir.path().join("book"); + let mut s = book(&b); + let record = b"sealed tin record, party one".to_vec(); + let party = s.add_party("Mo", &[Role::Member]).unwrap(); + s.set_party_tin( + party, + Some(TinFacts { + tin_type: TinType::Ssn, + last4: "4915".into(), + vault_record: Some(sha(&record)), + purged: None, + }), + ) + .unwrap(); + std::fs::create_dir_all(b.join("vault")).unwrap(); + std::fs::create_dir_all(b.join("keys")).unwrap(); + std::fs::write(b.join("keys").join("legacy.key"), "ab".repeat(32)).unwrap(); + // The purge of party 1's record is staged: set aside, not yet journaled. + let tag = "0123456789abcdef"; + std::fs::write( + b.join("vault").join(format!("tin-1.purging-{tag}")), + &record, + ) + .unwrap(); + // And a new record for party 2 is staged, not the books'. + std::fs::write( + b.join("vault").join(format!("tin-2.staged-{tag}")), + b"staged, not committed", + ) + .unwrap(); + let disk = dir.path().join("disk"); + std::fs::create_dir(&disk).unwrap(); + let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap(); + assert!(w.new && w.repaired.is_empty(), "{w:?}"); + let found = find(&disk, None, &Ctx::new()).unwrap(); + let v = verify_found(&found, &dir.path().join("v"), &Ctx::new()).unwrap(); + let held: Vec = std::fs::read_dir(v.tree.join("vault")) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!(held, vec!["tin-1.bin".to_string()], "{held:?}"); + assert_eq!( + std::fs::read(v.tree.join("vault").join("tin-1.bin")).unwrap(), + record + ); + // No scratch name of the vault is anywhere in the destination. + assert!( + !tree(&disk) + .keys() + .any(|n| n.contains(".staged-") || n.contains(".purging-")) + ); +}