feat: the window and the server say each new state in words; a proof cut short is made again; the proof does not mistake the books' own recovery for a changed head

- books ahead of the folder (as after a restore from an older backup) offer a
  new backup set beside the old one, at the person's request: books.back_up_now
  new_set, back-up --new-set, a button in the Backups window
- a key file lost from a sealed destination stops backups and asks for the
  passphrase; plain is written only after an explicit removal, which the record
  keeps (a damaged record falls back to what the folder itself holds)
- a restore that is not of the newest backup says so first, in the warning
  colour, with both dates and how many backups it passes over
- a folder a sync service keeps (or may) is said in plain words at set-up and
  in the window: one computer only, kept offline, a second computer its own
- a drill that finds only an older whole backup fails in words
- a manifest whose proof was cut short is marked unproven and proven by the
  next backup, even one with nothing new; a saved backup file is proven whole
  before it is given its name
- the proof compares the journal its pieces make with the head the manifest
  records before the books open, and lets opening add only after it
- the restore tests are split from backups.rs to keep each under a minute; the
  clone-of-an-old-git-backup test builds the working tree without git

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 20:07:38 -07:00
1 parent 9ac47a3f10
commit 344b3b4abe
21 files changed
+2346 -690

No files matched your search

+9
View File
@@ -19,6 +19,10 @@ pub(crate) const VERSION: u32 = 1;
pub(crate) const SET_PREFIX: &str = "wanderbooks-";
/// The folder of manifests in a set.
pub(crate) const MANIFESTS: &str = "manifests";
/// The folder of proof marks in a set: one tiny file per manifest whose
/// proof (write.rs) came out whole, so a manifest whose proof was cut short
/// is proven by the next backup, even one with nothing new to write.
pub(crate) const PROOFS: &str = "proofs";
/// The words a person can open.
pub(crate) const READ_ME: &str = "READ-ME.txt";
/// The sealed form's header: how to derive the key.
@@ -210,6 +214,11 @@ pub(crate) fn manifest_path(number: u64, sealed: bool) -> String {
}
}
/// The mark that manifest `number` was proven whole.
pub(crate) fn proof_path(number: u64) -> String {
format!("{PROOFS}/{number:06}")
}
/// The number a manifest file name carries, if it is one.
pub(crate) fn manifest_number(name: &str, sealed: bool) -> Option<u64> {
let digits = if sealed {
+16
View File
@@ -228,6 +228,10 @@ pub struct Ctx {
/// Tests: nothing is synced to disk (a destination of thousands of
/// backups is made quickly; a real one never is).
no_sync: bool,
/// Tests: the proof after a backup is left out (for the tests that make
/// many backups only to see what is written, which prove what they
/// made themselves).
no_proof: bool,
/// Tests: told each read and length look at a file of the set.
trace: Option<Trace>,
}
@@ -297,6 +301,18 @@ impl Ctx {
self
}
/// The proof after a backup is left out (tests that make many backups
/// only to see what is written; the proof has tests of its own).
#[doc(hidden)]
pub fn with_proof_skipped(mut self) -> Self {
self.no_proof = true;
self
}
pub(crate) fn skips_proof(&self) -> bool {
self.no_proof
}
pub(crate) fn syncs(&self) -> bool {
!self.no_sync
}
+54 -19
View File
@@ -200,6 +200,11 @@ impl Set {
Ok(n)
}
/// Whether the proof after a backup came out whole for manifest `n`.
pub(crate) fn proven(&self, n: u64) -> bool {
matches!(self.io.len(&proof_path(n)), Ok(Some(_)))
}
fn read_small(&self, rel: &str) -> Result<Vec<u8>, BackupError> {
match self.io.len(rel)? {
Some(len) if len <= SMALL_MAX => {}
@@ -547,6 +552,18 @@ pub struct Found {
pub sealed: bool,
}
impl Found {
/// A set already open (a backup file just written), to be proven.
pub(crate) fn of(set: Set, key: Option<BackupKey>, book: &str) -> Found {
Found {
sealed: set.sealed(),
set,
key,
book: Some(book.to_string()),
}
}
}
/// One set of books in a folder, as listed for a person to choose from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Candidate {
@@ -727,6 +744,9 @@ pub struct Verified {
pub number: u64,
/// When it was made (UTC), as its manifest says.
pub written: String,
/// The journal's length in the backup: the books built from it hold
/// the journal as it was, and may carry the books' own recovery after.
pub journal_bytes: u64,
/// How many newer backups there are that were passed over: not whole,
/// or damaged. Not zero means this is not the newest backup there is.
pub passed_over: usize,
@@ -922,15 +942,23 @@ fn prove_books(
) -> Result<(u64, (u64, String)), BackupError> {
ctx.phase("replay");
let _stoppable = ctx.stop_flag().map(crate::cancel::scope);
if matches!(depth, Depth::Chain) {
// The hash chain, up to the head, before the books are opened.
let lines = crate::journal::read_and_verify_journal(&scratch.join(crate::JOURNAL_FILE))?;
let last = lines.last().map(|l| l.seq).unwrap_or(0);
if last != m.head.seq {
return Err(BackupError::Damaged(format!(
"its journal ends at event {last}, but the backup records another head"
)));
}
// The hash chain, up to the head, before the books are opened: the
// journal the pieces make ends at the head the manifest records. (A
// backup taken while a call is under way ends with the call's lines
// unfinished: opening the books settles it by appending a line, which
// is the books' recovery and not the backup's head.)
let lines = crate::journal::read_and_verify_journal(&scratch.join(crate::JOURNAL_FILE))?;
let (last_seq, last_hash) = match lines.last() {
Some(l) => (
l.seq,
crate::journal::sha256_hex(l.to_canonical().as_bytes()),
),
None => (0, String::new()),
};
if last_seq != m.head.seq || (last_seq > 0 && last_hash != m.head.hash) {
return Err(BackupError::Damaged(format!(
"its journal ends at event {last_seq}, but the backup records another head"
)));
}
let mut store = crate::Store::open(scratch)?;
if matches!(depth, Depth::Whole) {
@@ -949,7 +977,7 @@ fn prove_books(
Depth::Whole => store.verify_blobs()?,
Depth::Chain => audit.files_read,
};
let head = store.head();
let opened = store.head();
let tins: Vec<String> = store
.ledger()
.parties()
@@ -982,13 +1010,14 @@ fn prove_books(
));
}
}
if head.0 != m.head.seq || head.1 != m.head.hash {
// Opening may only have added the books' own recovery after the head.
if opened.0 < m.head.seq {
return Err(BackupError::Damaged(format!(
"its journal ends at event {}, but the backup records another head",
head.0
opened.0
)));
}
Ok((blobs, head))
Ok((blobs, (m.head.seq, m.head.hash.clone())))
}
/// The books built from manifest `m` into `scratch` and proven, whole.
@@ -1102,6 +1131,7 @@ fn verify_one(
book: Some(m.book.clone()),
number: m.number,
written: m.written.clone(),
journal_bytes: m.journal.bytes,
passed_over: passed,
newest_written: if n == newest {
Some(m.written.clone())
@@ -1153,9 +1183,9 @@ pub fn verify_found(found: &Found, scratch: &Path, ctx: &Ctx) -> Result<Verified
/// Whether the journal at `backup` is a byte prefix of the one at `live`
/// (a drill: the backup holds the book's history, nothing else).
pub fn is_prefix(live: &Path, backup: &Path, ctx: &Ctx) -> Result<bool, BackupError> {
pub fn is_prefix(live: &Path, backup: &Path, len: u64, ctx: &Ctx) -> Result<bool, BackupError> {
let mut a = std::fs::File::open(live)?;
let mut b = std::fs::File::open(backup)?;
let mut b = std::io::Read::take(std::fs::File::open(backup)?, len);
let (mut x, mut y) = (vec![0u8; 64 * 1024], vec![0u8; 64 * 1024]);
loop {
ctx.check("comparing journals")?;
@@ -1228,7 +1258,12 @@ pub fn drill(
v.head.0, e.0
)))
} else {
match is_prefix(live, &v.tree.join(crate::JOURNAL_FILE), ctx) {
match is_prefix(
live,
&v.tree.join(crate::JOURNAL_FILE),
v.journal_bytes,
ctx,
) {
Ok(true) => Ok(v.head),
Ok(false) => Err(BackupError::Damaged(
"its journal isn't this book's history".into(),
@@ -1301,9 +1336,9 @@ pub fn prove_local(
}
ctx.phase("compare");
ctx.check("comparing")?;
if std::fs::read(book_dir.join(crate::JOURNAL_FILE)).unwrap_or_default()
!= std::fs::read(v.tree.join(crate::JOURNAL_FILE))?
{
let held = std::fs::read(v.tree.join(crate::JOURNAL_FILE))?;
let held = &held[..(v.journal_bytes as usize).min(held.len())];
if std::fs::read(book_dir.join(crate::JOURNAL_FILE)).unwrap_or_default() != held {
return Err(BackupError::Damaged(
"its journal isn't the books' own, byte for byte".into(),
));
+15 -2
View File
@@ -8,8 +8,8 @@
use super::cut::Cut;
use super::io::{Fill, Put, PutKind, SetIo};
use super::read::Set;
use super::write::{Written, write_into_set};
use super::read::{Found, Set, verify_found};
use super::write::{Written, proof_scratch, write_into_set};
use super::{BackupError, Ctx};
use std::collections::BTreeSet;
use std::io::Read;
@@ -173,6 +173,19 @@ pub fn save_file(
.finish()
.map_err(|e| BackupError::Io(std::io::Error::other(e).kind()))?;
file.sync_all()?;
// Read back as a restore would read it, and proven whole (every
// piece re-hashed, the chain replayed, the books opened), before it
// is given its name: a file by that name is a backup that proved.
let reader = Set {
io: open(&aside, ctx)?,
keys: key.map(|k| k.keys()),
ctx: ctx.clone(),
};
let found = Found::of(reader, key.cloned(), cut.book());
let scratch = proof_scratch(cut)?;
let proven = verify_found(&found, &scratch, ctx);
let _ = std::fs::remove_dir_all(&scratch);
proven?;
Ok(written)
});
match result {
+39 -4
View File
@@ -804,14 +804,38 @@ fn put_manifest(
/// A folder for the proof's scratch books: private, in the book's own
/// `ops/`, named for this call.
fn proof_scratch(cut: &Cut) -> Result<PathBuf, BackupError> {
let ops = crate::root::private_book_folder(cut.dir(), crate::ops::OPS_DIR)
.map_err(|e| BackupError::Damaged(e.to_string()))?;
pub(crate) fn proof_scratch(cut: &Cut) -> Result<PathBuf, BackupError> {
let ops = cut.dir().join(crate::ops::OPS_DIR);
if !ops.is_dir() {
// Made private by the one that makes it; one that lost a race to
// make it finds it there.
let made = crate::root::private_book_folder(cut.dir(), crate::ops::OPS_DIR);
if !ops.is_dir() {
return Err(BackupError::Damaged(
made.err().map(|e| e.to_string()).unwrap_or_default(),
));
}
}
let mut r = [0u8; 6];
let _ = getrandom::getrandom(&mut r);
getrandom::getrandom(&mut r).map_err(|e| BackupError::Io(std::io::Error::from(e).kind()))?;
Ok(ops.join(format!("proof-{}", hex::encode(r))))
}
/// Mark manifest `number` as proven whole: a tiny file put once. A mark
/// that can't be made (a full disk) costs only a proof again at the next
/// backup; a stop is a stop.
fn mark_proven(set: &Set, number: u64) -> Result<(), BackupError> {
match set.io.put(&proof_path(number), PutKind::Once, &mut |w| {
w.write_all(b"proven whole\n")
}) {
Ok(_) => Ok(()),
Err(e) => match uncarry(e) {
stop @ (BackupError::Died | BackupError::Cancelled(_)) => Err(stop),
_ => Ok(()),
},
}
}
/// The most times a backup is written again to repair what its own proof
/// found damaged.
const REPAIR_ROUNDS: usize = 2;
@@ -835,6 +859,7 @@ fn prove_and_repair(
ctx.check("proving the backup")?;
let proof = super::read::prove_written(set, number, &added, &proof_scratch(cut)?)?;
if proof.damaged.is_empty() {
mark_proven(set, number)?;
return Ok(Written {
number,
head: cut.head().clone(),
@@ -893,6 +918,7 @@ pub(crate) fn write_into_set(
prove: bool,
) -> Result<Written, BackupError> {
ensure_markers(set)?;
let prove = prove && !ctx.skips_proof();
for _ in 0..ATTEMPTS {
ctx.check("backing up")?;
let numbers = set.numbers()?;
@@ -903,6 +929,15 @@ pub(crate) fn write_into_set(
if let Some(p) = &prev
&& manifest.same_content(p)
{
// Nothing new. But a manifest whose proof was cut short (a
// close, a stop, a death) is not yet known whole: proven now.
if prove && !set.proven(p.number) {
let w = prove_and_repair(set, cut, p.number, BTreeSet::new(), Vec::new(), ctx)?;
return Ok(Written {
new: w.number != p.number,
..w
});
}
return Ok(Written {
number: p.number,
head: cut.head().clone(),
+8 -1
View File
@@ -1148,8 +1148,13 @@ pub struct RestorePreview {
pub origin: Option<String>,
/// Whether it is protected by a passphrase.
pub sealed: bool,
/// Newer backups in it that were not whole and were passed over.
/// Newer backups in it that were not whole or were damaged and were
/// passed over: not zero means this is not the newest backup there is.
pub passed_over: u64,
/// When this backup was made (UTC).
pub written: Option<String>,
/// When the newest backup there is was made (UTC), if it can be read.
pub newest_written: Option<String>,
}
/// What [`Root::restore`] did.
@@ -1258,6 +1263,8 @@ impl Root {
origin: v.book,
sealed: v.key.is_some(),
passed_over: v.passed_over as u64,
written: Some(v.written.clone()),
newest_written: v.newest_written.clone(),
})
})()
.map_err(|e| self.hide(e))
+21 -9
View File
@@ -452,6 +452,7 @@ fn pieces(set: &Path) -> Vec<PathBuf> {
.keys()
.filter(|n| {
!n.starts_with("manifests/")
&& !n.starts_with("proofs/")
&& !n.ends_with("READ-ME.txt")
&& !n.ends_with("header.json")
})
@@ -562,7 +563,13 @@ fn a_program_that_dies_at_any_write_leaves_what_proved_whole_before() {
let mut s = book(&b);
let base_disk = dir.path().join("base");
std::fs::create_dir(&base_disk).unwrap();
write_destination(&plain(&base_disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
write_destination(
&plain(&base_disk),
&cut(&b, &s),
true,
&Ctx::new().with_proof_skipped(),
)
.unwrap();
let first_head = s.head();
more(&mut s, 1);
let c = cut(&b, &s);
@@ -573,10 +580,12 @@ fn a_program_that_dies_at_any_write_leaves_what_proved_whole_before() {
let disk = dir.path().join("probe");
copy_tree(&base_disk, &disk);
let n = counted.clone();
let ctx = Ctx::new().with_faults(Arc::new(move |_, _| {
n.fetch_add(1, Ordering::SeqCst);
false
}));
let ctx = Ctx::new()
.with_proof_skipped()
.with_faults(Arc::new(move |_, _| {
n.fetch_add(1, Ordering::SeqCst);
false
}));
write_destination(&plain(&disk), &c, true, &ctx).unwrap();
counted.load(Ordering::SeqCst)
};
@@ -588,9 +597,11 @@ fn a_program_that_dies_at_any_write_leaves_what_proved_whole_before() {
let n = Arc::new(AtomicUsize::new(0));
let ctx = {
let n = n.clone();
Ctx::new().with_faults(Arc::new(move |_, _| {
n.fetch_add(1, Ordering::SeqCst) == die_at
}))
Ctx::new()
.with_proof_skipped()
.with_faults(Arc::new(move |_, _| {
n.fetch_add(1, Ordering::SeqCst) == die_at
}))
};
let err = write_destination(&plain(&disk), &c, true, &ctx).unwrap_err();
assert_eq!(err, BackupError::Died, "point {die_at}");
@@ -609,7 +620,8 @@ fn a_program_that_dies_at_any_write_leaves_what_proved_whole_before() {
assert!(live.starts_with(&restored), "point {die_at}");
// And the next run goes on from it (proven again at some points:
// each proof replays the books).
let w = write_destination(&plain(&disk), &c, true, &Ctx::new()).unwrap();
let w =
write_destination(&plain(&disk), &c, true, &Ctx::new().with_proof_skipped()).unwrap();
assert_eq!(w.head, s.head());
if die_at % 6 == 0 {
let again = prove(&disk, None, dir.path(), &format!("again-{die_at}")).unwrap();
+12
View File
@@ -223,8 +223,17 @@ fn a_taken_number_or_name_is_never_replaced_on_a_disk_that_makes_no_links() {
const PASS: &str = "correct horse battery staple";
/// The count of derived keys is the process's: the tests that read it, and
/// every test that derives one, take turns.
static KEYS: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn one_at_a_time() -> std::sync::MutexGuard<'static, ()> {
KEYS.lock().unwrap_or_else(|e| e.into_inner())
}
#[test]
fn sealed_pieces_are_spread_over_folders_as_the_plain_form_does() {
let _turn = one_at_a_time();
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let mut s = book(&b);
@@ -295,6 +304,7 @@ fn set_header(header: &Path, edit: impl Fn(&mut serde_json::Value)) {
#[test]
fn a_header_cannot_ask_for_more_than_a_few_times_what_this_program_spends() {
let _turn = one_at_a_time();
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
@@ -330,6 +340,7 @@ fn a_header_cannot_ask_for_more_than_a_few_times_what_this_program_spends() {
#[test]
fn a_header_that_was_changed_reads_as_damage_and_not_as_a_wrong_passphrase() {
let _turn = one_at_a_time();
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
@@ -365,6 +376,7 @@ fn a_header_that_was_changed_reads_as_damage_and_not_as_a_wrong_passphrase() {
#[test]
fn a_folder_of_sealed_sets_costs_one_key_derivation_per_setting_not_one_per_set() {
let _turn = one_at_a_time();
let dir = tempfile::tempdir().unwrap();
let b = dir.path().join("book");
let s = book(&b);
+29 -8
View File
@@ -36,6 +36,13 @@ fn ops() -> impl Strategy<Value = Vec<Op>> {
)
}
/// A context for tests of logic, not of durability: nothing is synced.
fn fast() -> Ctx {
// The proof after a backup has tests of its own (backup_repair.rs); the
// properties here prove what they make by restoring it.
Ctx::new().with_no_sync().with_proof_skipped()
}
fn plain(folder: &Path) -> Destination {
Destination {
folder: folder.to_path_buf(),
@@ -156,7 +163,7 @@ proptest! {
for op in &ops {
books.apply(op);
if matches!(op, Op::Backup) {
write_destination(&plain(&disk), &books.cut(), true, &Ctx::new()).unwrap();
write_destination(&plain(&disk), &books.cut(), true, &fast()).unwrap();
let after = tree(&disk);
for (name, bytes) in &before {
prop_assert_eq!(after.get(name), Some(bytes), "{} changed or went", name);
@@ -180,14 +187,14 @@ proptest! {
for op in &ops {
books.apply(op);
if matches!(op, Op::Backup) {
let w = write_destination(&plain(&disk), &books.cut(), true, &Ctx::new()).unwrap();
let w = write_destination(&plain(&disk), &books.cut(), true, &fast()).unwrap();
if w.new {
heads.push((w.number, w.head));
}
}
}
// (A last backup, so there is at least one.)
let w = write_destination(&plain(&disk), &books.cut(), true, &Ctx::new()).unwrap();
let w = write_destination(&plain(&disk), &books.cut(), true, &fast()).unwrap();
if w.new {
heads.push((w.number, w.head));
}
@@ -240,9 +247,15 @@ proptest! {
let count = Arc::new(AtomicUsize::new(0));
let rival = {
let (disk, second, count) = (disk.clone(), second.clone(), count.clone());
Ctx::new().with_faults(Arc::new(move |_, _| {
fast().with_faults(Arc::new(move |_, _| {
if count.fetch_add(1, Ordering::SeqCst) == at {
write_destination(&plain(&disk), &second, true, &Ctx::new()).unwrap();
write_destination(
&plain(&disk),
&second,
true,
&fast(),
)
.unwrap();
}
false
}))
@@ -275,11 +288,19 @@ proptest! {
for op in &ops {
books.apply(op);
}
write_destination(&plain(&disk), &books.cut(), true, &Ctx::new()).unwrap();
write_destination(
&plain(&disk),
&books.cut(),
true,
&fast(),
)
.unwrap();
let set = disk.join("wanderbooks-acme");
let pieces: Vec<String> = tree(&set)
.into_keys()
.filter(|n| !n.starts_with("manifests/") && n != "READ-ME.txt")
.filter(|n| {
!n.starts_with("manifests/") && !n.starts_with("proofs/") && n != "READ-ME.txt"
})
.collect();
let name = &pieces[pick.index(pieces.len())];
let path = set.join(name);
@@ -309,7 +330,7 @@ proptest! {
folder: disk.clone(),
key: Some(BackupKey::generate("the right words, exactly").unwrap()),
};
write_destination(&dest, &books.cut(), true, &Ctx::new()).unwrap();
write_destination(&dest, &books.cut(), true, &fast()).unwrap();
let scratch = dir.path().join("v");
let got = prove(&disk, Some(&wrong), &scratch);
prop_assert!(matches!(got, Err(BackupError::WrongPassphrase)), "{got:?}");
@@ -739,3 +739,52 @@ fn a_backup_cut_while_the_vault_is_being_written_restores_a_vault_that_matches_t
.any(|n| n.contains(".staged-") || n.contains(".purging-"))
);
}
#[test]
fn a_proof_cut_short_by_a_close_ends_cleanly_and_is_made_again_by_the_next_backup() {
use std::sync::atomic::{AtomicBool, Ordering};
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();
// The books close while the backup's proof is under way (here: as it
// replays the chain).
let stop = Arc::new(AtomicBool::new(false));
let ctx = {
let stop = stop.clone();
Ctx::new()
.with_stop(stop.clone())
.with_phase_watch(Arc::new(move |p: &str| {
if p == "replay" {
stop.store(true, Ordering::SeqCst);
}
}))
};
let err = write_destination(&plain(&disk), &cut(&b, &s), true, &ctx).unwrap_err();
assert!(matches!(err, BackupError::Cancelled(_)), "{err:?}");
// Nothing of the proof is left behind in the books' folder, and the
// manifest that was written is there but is not marked proven.
let left: Vec<_> = std::fs::read_dir(b.join("ops"))
.map(|d| {
d.flatten()
.filter(|e| e.file_name().to_string_lossy().starts_with("proof-"))
.collect()
})
.unwrap_or_default();
assert!(left.is_empty(), "scratch books left: {left:?}");
let set = set_of(&disk);
assert!(set.join("manifests/000001.json").is_file());
assert!(!set.join("proofs/000001").exists());
// The next backup has nothing new to write, and still proves it: it
// never says good of a backup that was not proven.
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert_eq!(w.number, 1);
assert!(!w.new, "{w:?}");
assert!(set.join("proofs/000001").is_file());
// Once proven, a backup with nothing new is only looked at.
let before = tree(&disk);
let w = write_destination(&plain(&disk), &cut(&b, &s), true, &Ctx::new()).unwrap();
assert!(!w.new);
assert_eq!(tree(&disk), before);
}