fix(store): a killed git leaves no lock for anyone to remove, and a verification can be told to stop

A git killed (cancelled by a close, or silent for GIT_TIMEOUT) leaves the
lock files it held, and nothing removed them for 300 s (the archive) or ever
(a folder target): an immediate reopen's backup failed on index.lock and
waited 15 minutes, and a receive-pack killed holding a ref lock could stop
every later push. This process knows when it killed its own git, so once
the command is reaped AND everything it started is gone (the process group
is waited for: a killed process can still take a lock in its last
instructions) the locks it could have left are dealt with at once, each
noted for the caller's record.
 - the book's own archive: every lock is removed (this process holds the
   book's store lock, so no other wanderbooks process runs git on it); the
   same at open (clear_archive_locks), where a lock is a dead git's.
 - a target on this computer: D-30 makes the folder the owner's (an external
   disk, a synced folder), and nothing enforces that no other computer, data
   root with a book of the same id, or hand pushes to it (the only guard is
   the fast-forward rule). So a lock there is removed only if it was NOT
   there when the push began (one that was is left and noted) and it has
   stood unchanged for LOCK_SETTLE after the kill (a live writer holds a ref
   lock for the milliseconds of a ref update). Said in INVARIANT 5, with the
   one case this cannot see (a second writer stalled holding the lock past
   LOCK_SETTLE). A far repository is never touched.
 - a git killed inside `init` (found by the test with real git: the first
   backup of a book made HEAD.lock in a repository that isn't one yet, which
   stopped every later init) is covered the same way.
 - no git of ours starts another to go on after it (gc.auto=0,
   maintenance.auto=false), so 'everything it started is gone' is true.

Also: a drill or proof can be told to stop (the cancel flag), looked at
between phases, once per journal line replayed or applied, once per stored
file hashed or listed and once per 64 KiB chunk compared (cancel.rs, a
thread-scoped flag so nothing else can be stopped by it), and leaves nothing
(its scratch clone is removed). Tests use REAL git, made slow by a
reference-transaction hook that waits: killed mid-commit, mid-add (a huge
sparse file), mid-push; the next backup succeeds and git fsck passes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Sonnet 5.5 committed 2026-11-20 13:10:26 -07:00
1 parent ca6f5aa982
commit 10790d8794
8 files changed
+927 -31

No files matched your search

File diff suppressed because it is too large. Load diff
+68
View File
@@ -0,0 +1,68 @@
//! A stop request the long loops over a book's journal and files look at
//! (a backup's drill or proof, ledger-store `backup`): a step that has to
//! end when the books are let go (a close) can't wait for a replay of a
//! journal of any length to come to its end.
//!
//! ```text
//! GOAL: a verification over a book's journal or files that was asked to
//! stop stops promptly, at its next step, and leaves nothing of its
//! own half-made, however large the book.
//! SOURCE: the books server's close (ledger-mcp local.rs INVARIANT 10 and
//! 13: a close is answered only when nothing of its backups still
//! runs, and is bounded).
//! INVARIANTS:
//! 1. A request is scoped to the thread that made it (`scope`), for as
//! long as the scope lives; code on other threads, and code outside a
//! scope, never sees one. Nothing is shared, so no other work of the
//! process can be stopped by it.
//! 2. `check` is looked at once per journal line (verifying, replaying,
//! applying to the projection), once per stored file hashed, and at
//! the boundaries between a verification's phases: the longest it
//! goes without looking is one line or one file.
//! 3. A stop is an error (`StoreError::Cancelled`), never a partial
//! success: what a stopped verification had made is the caller's to
//! remove (the books it was opened on are a scratch folder's).
//! ```
use crate::error::StoreError;
use std::cell::RefCell;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
thread_local! {
static FLAG: RefCell<Option<Arc<AtomicBool>>> = const { RefCell::new(None) };
}
/// A stop request in force on this thread, until dropped.
pub struct Scope(Option<Arc<AtomicBool>>);
impl Drop for Scope {
fn drop(&mut self) {
FLAG.with(|f| *f.borrow_mut() = self.0.take());
}
}
/// Look for `flag` (INVARIANT 1) on this thread, until the returned scope
/// is dropped (the request in force before it comes back).
#[must_use]
pub fn scope(flag: Arc<AtomicBool>) -> Scope {
Scope(FLAG.with(|f| f.borrow_mut().replace(flag)))
}
/// Whether a stop was asked for.
pub fn requested() -> bool {
FLAG.with(|f| {
f.borrow()
.as_ref()
.is_some_and(|c| c.load(Ordering::SeqCst))
})
}
/// Ok, or `StoreError::Cancelled` when a stop was asked for (INVARIANT 2).
pub fn check() -> Result<(), StoreError> {
if requested() {
Err(StoreError::Cancelled)
} else {
Ok(())
}
}
+4
View File
@@ -5,6 +5,10 @@ use thiserror::Error;
/// Every way a store operation can fail.
#[derive(Debug, Error)]
pub enum StoreError {
/// A verification was told to stop ([`crate::cancel`]): the books it
/// was reading are being let go.
#[error("stopped: the books are closing")]
Cancelled,
/// An attachment link names a subject that doesn't exist.
#[error("no {0} to link to")]
UnknownSubject(String),
+1 -6
View File
@@ -346,12 +346,7 @@ mod tests {
);
// A writer that sends nothing lets the read end (an empty file,
// not the size kept: the fetch is refused).
drop(
std::fs::OpenOptions::new()
.write(true)
.open(&bin)
.unwrap(),
);
drop(std::fs::OpenOptions::new().write(true).open(&bin).unwrap());
assert!(fetching.join().unwrap().is_err());
closed
.recv_timeout(std::time::Duration::from_secs(5))
+1
View File
@@ -317,6 +317,7 @@ fn verify_lines(
let mut expected_prev = GENESIS_PREV.to_string();
let mut raws = body.split(|&b| b == b'\n').enumerate().peekable();
while let Some((i, raw)) = raws.next() {
crate::cancel::check()?;
let read = read_line(raw).map_err(|e| {
StoreError::JournalCorrupt(format!("seq {}: unparseable line: {e}", i + 1))
})?;
+1
View File
@@ -22,6 +22,7 @@ pub mod access;
pub mod auth;
pub mod backup;
pub mod blob;
pub mod cancel;
pub mod chain;
pub mod describe;
pub mod error;
+7
View File
@@ -669,6 +669,7 @@ impl Store {
// open with the journal and the database as they were.
let mut ledger = Ledger::new(base_currency);
for line in &lines {
crate::cancel::check()?;
replay_line_into_ledger(&mut ledger, line, base_currency)?;
}
// Only then is an append cut off mid-line (never acknowledged) set
@@ -845,6 +846,7 @@ impl Store {
// The ledger is already their replay (Store::open): only the
// projection is caught up here.
for line in lines.iter().filter(|l| l.seq > last_applied) {
crate::cancel::check()?;
apply_line_to_sqlite(&self.conn, line)?;
}
Ok(())
@@ -6273,8 +6275,10 @@ impl Store {
let lines = read_and_verify_journal(self.journal.path())?;
let mut replayed = Ledger::new(self.base_currency);
for line in &lines {
crate::cancel::check()?;
replay_line_into_ledger(&mut replayed, line, self.base_currency)?;
}
crate::cancel::check()?;
let a = reports::snapshot(&replayed).map_err(StoreError::Ledger)?;
let b = reports::snapshot(&self.ledger).map_err(StoreError::Ledger)?;
if a != b {
@@ -6426,6 +6430,7 @@ impl Store {
.collect::<Result<_, _>>()?;
let mut n = 0u64;
for sha in shas {
crate::cancel::check()?;
self.blobs.get(&sha)?;
n += 1;
}
@@ -6449,10 +6454,12 @@ impl Store {
Self::write_meta(&self.conn, "last_applied_seq", "0")?;
let lines = read_and_verify_journal(self.journal.path())?;
for line in &lines {
crate::cancel::check()?;
apply_line_to_sqlite(&self.conn, line)?;
}
self.ledger = Ledger::new(self.base_currency);
for line in &lines {
crate::cancel::check()?;
replay_line_into_ledger(&mut self.ledger, line, self.base_currency)?;
}
Ok(())
+6 -2
View File
@@ -743,7 +743,9 @@ mod tests {
assert_eq!(feed.reads, 2, "the body was read after the close");
let left = names_in(dir.path());
assert!(
!left.iter().any(|n| n.ends_with(".part") || n.ends_with(".bin")),
!left
.iter()
.any(|n| n.ends_with(".part") || n.ends_with(".bin")),
"{left:?}"
);
}
@@ -771,7 +773,9 @@ mod tests {
assert!(refused.to_string().contains("aren't open"), "{refused}");
let left = names_in(dir.path());
assert!(
!left.iter().any(|n| n.ends_with(".part") || n.ends_with(".bin")),
!left
.iter()
.any(|n| n.ends_with(".part") || n.ends_with(".bin")),
"{left:?}"
);
}