fix(mcp,store): a close stops every call and job that can run long, and says so; an unrecorded refusal never ran

A close waited, unbounded, for a running books.back_up_now (git only Backups::shut
could cancel), for a restore, create or adopt (they hold the one lifecycle lock,
and at the server's close admin_jobs.wait() waited for them before anything was
released), and, through the store lock, for a verification or a package reading
every stored file. The bound's T_calls term was not finite.

Now a close calls hurry at its start, and the stoppable work looks at it:
books.back_up_now and timer-asked backups (git stopped, a stopped run records
'stopped' and no result of its own), books.verify (per journal line and file; a
heal of a drifted database is begun only if no stop came before it: stopped half
way it would leave the live ledger part replayed), books.export_cpa_package (per
stored file). Such a call answers that it was stopped because the books are
closing, and its access record says refused: stopped_by_close. On the admin
socket restore, adopt, create and open take a JobStop: asked at each phase and
file copied, they remove what they wrote and leave the root byte for byte as it
was; the renames that put the books in place are the point of no return, after
which they finish (two renames and two syncs). A close of any book, and the
server's own, raises the flag before it waits for the lifecycle lock.

A close whose last backup had to be killed in the owner's folder now says which
file was left, and the target's backup is marked failed by shut when the run's
future was dropped at its bound. INVARIANT 10 is rewritten so each term of the
bound is enforced by code, and lists the calls that can run long (and the one
known exception, books.import_bank_csv); INVARIANTS 8 and 9 say exactly which
refusals are recorded and why an unrecorded one never ran; the format upgrade's
wording says a stop is honoured up to its final look.

Tests: the close is held to the bound while a backup call, a verification, a
package and each admin job is running and would never end; the stopped job leaves
the root byte for byte as it was; a lock left in a backup folder is reported and
never removed. Sleeps that stood for 'the other side got there' now wait on the
condition (Expect: 100-continue for a half-sent body, a writable named pipe for a
fetch that is reading).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Sonnet 5.5 committed 2026-11-20 17:15:36 -07:00
1 parent 6f174f3f87
commit aa64df9a25
18 files changed
+1889 -248

No files matched your search

+745 -50
View File
@@ -752,6 +752,39 @@ mod raw {
self.stream.write_all(&body[..sent]).unwrap();
}
/// [`Raw::start`] for a request that sends its body only once the
/// server has asked for it (`Expect: 100-continue`): the server asks
/// when its handler first reads the body, which it does inside the
/// book's door. So once this returns the request is known to be
/// inside, with `sent` bytes of its body written: a condition, not a
/// guess at how long the server takes to read a head.
pub fn start_inside(
&mut self,
method: &str,
path: &str,
extra: &[(&str, &str)],
body: &[u8],
sent: usize,
) {
let mut extra = extra.to_vec();
extra.push(("expect", "100-continue"));
self.start(method, path, &extra, body, 0);
self.stream
.set_read_timeout(Some(Duration::from_secs(120)))
.unwrap();
let mut seen = Vec::new();
let mut byte = [0u8; 1];
while !seen.ends_with(b"\r\n\r\n") {
self.stream
.read_exact(&mut byte)
.expect("the server never asked for the body");
seen.push(byte[0]);
}
let said = String::from_utf8_lossy(&seen).to_string();
assert!(said.starts_with("HTTP/1.1 100"), "{said}");
self.stream.write_all(&body[..sent]).unwrap();
}
/// Wait until the server has sent something on this connection
/// (one byte is taken, and kept for [`Raw::head`]).
pub fn wait_for_bytes(&mut self) {
@@ -808,6 +841,43 @@ mod raw {
String::from_utf8_lossy(&seen).to_string()
}
/// The whole response: its status, and its body (as long as its
/// `content-length` says).
pub fn answer(&mut self) -> (u16, String) {
let (status, head) = self.head();
let lower = head.to_ascii_lowercase();
let mut body = Vec::new();
if lower.contains("transfer-encoding: chunked") {
// Chunks, each a hex size line, its bytes and a line end.
loop {
let mut size = String::new();
let mut byte = [0u8; 1];
while !size.ends_with("\r\n") {
self.stream.read_exact(&mut byte).unwrap();
size.push(byte[0] as char);
}
let n = usize::from_str_radix(size.trim(), 16).unwrap();
let mut chunk = vec![0u8; n + 2];
self.stream.read_exact(&mut chunk).unwrap();
if n == 0 {
break;
}
body.extend_from_slice(&chunk[..n]);
}
} else {
let length: usize = lower
.lines()
.find_map(|l| {
l.strip_prefix("content-length:")
.map(|v| v.trim().parse().unwrap())
})
.unwrap_or(0);
body = vec![0u8; length];
self.stream.read_exact(&mut body).unwrap();
}
(status, String::from_utf8_lossy(&body).to_string())
}
/// The response's status line and headers (the body is left).
pub fn head(&mut self) -> (u16, String) {
self.stream
@@ -1191,11 +1261,30 @@ fn a_close_whose_backup_fails_says_so_and_leaves_nothing_running() {
// The same book, backed up fine, is answered plainly.
assert_eq!(open_book(&home, A), OpenOutcome::Opened);
std::fs::create_dir(&unplugged).unwrap();
// The backup the opening makes (it may still be under way, and would be
// stopped by the close) is waited for: a backup asked for takes its turn
// after it.
match home.admin(Request::BackUpNow {
id: A.into(),
new_disk: false,
}) {
Response::BackedUp { targets, .. } => {
assert!(targets.iter().all(|t| t.problem.is_none()), "{targets:?}");
}
other => panic!("{other:?}"),
}
let mut w = Wire::new(&home, A);
w.initialize("owner");
draft(&mut w, "backed up");
w.end();
assert_eq!(close_book(&home, A), CloseOutcome::Closed);
let outcome = close_book(&home, A);
assert_eq!(
outcome,
CloseOutcome::Closed,
"{}",
std::fs::read_to_string(home.book_dir(A).join("ops").join("backup.jsonl"))
.unwrap_or_default()
);
assert!(server.close().success());
}
@@ -1256,6 +1345,8 @@ fn an_upload_in_flight_finishes_before_the_close_is_answered() {
wait_for("the book is listed closed", Duration::from_secs(30), || {
listed(&home, A).1
});
// A negative window: it can only fail if the close was answered, never
// because the machine was slow.
std::thread::sleep(Duration::from_millis(300));
assert!(
!closing.is_finished(),
@@ -1372,7 +1463,7 @@ fn a_stalled_mcp_body_cannot_hold_a_close_and_nothing_of_it_is_journaled() {
"name": "books.draft_entry",
"arguments": {"date": "2026-03-01", "description": "never finished"}}})
.to_string();
raw.start(
raw.start_inside(
"POST",
"mcp",
&[
@@ -1384,7 +1475,6 @@ fn a_stalled_mcp_body_cannot_hold_a_close_and_nothing_of_it_is_journaled() {
body.as_bytes(),
body.len() / 2,
);
std::thread::sleep(Duration::from_millis(200));
let started = std::time::Instant::now();
assert_eq!(close_book(&home, A), CloseOutcome::Closed);
let took = started.elapsed();
@@ -1459,42 +1549,43 @@ fn a_slow_upload_that_finishes_within_the_grace_is_not_cut() {
/// A call whose body is whole and that is running when the grace runs out
/// is not cut: it ends, is answered and recorded as having run, and only
/// then is the close answered. What this proves is that the close waits for
/// the call and does not kill it; that a body read to its end is never cut
/// (the line of INVARIANT 15) is proved at its seat, by
/// then is the close answered. The call is an ordinary one (`books.attach_
/// receipt`, which reads its upload: bounded by one request, so a close waits
/// for it instead of stopping it), held inside its read of the file, which
/// is a named pipe nothing writes to yet. What this proves is that the close
/// waits for such a call and does not kill it; that a body read to its end
/// is never cut (the line of INVARIANT 15) is proved at its seat, by
/// `local::tests::a_body_read_to_its_end_is_never_cut_and_one_not_yet_is`:
/// this test passes even with a cut that marks every request inside (the
/// call runs in the session's task, past the handler's own check for a cut).
/// (A backup asked for is no longer this call: it is stoppable, and a close
/// stops it: `a_close_stops_a_running_backup_call_and_says_so`.)
#[cfg(unix)]
#[test]
fn a_running_call_is_never_cut_when_the_grace_runs_out() {
use std::os::unix::fs::OpenOptionsExt;
let home = Home::new("close-running-call");
let shim = shim_git(&home);
let server = server_with_shim(
&home,
&shim,
&[
"--answer-grace",
"400",
"--close-backup",
"500",
"--backup-quiet",
"3600000",
"--timers",
"20",
],
);
let server = Server::start_with(&home, &["--answer-grace", "400", "--timers", "20"]);
home.create(A, "USD");
let disk = home.dir.path().join("disk");
std::fs::create_dir_all(&disk).unwrap();
let mut w = Wire::new(&home, A);
w.initialize("owner");
set_backup_folder(&mut w, &disk);
draft(&mut w, "moves the head");
std::fs::write(shim.join("stall"), b"").unwrap();
let bytes = b"%PDF-1.4 a receipt, read by a call that is held".to_vec();
let up = w.upload(&bytes, "r.pdf", "application/pdf", "receipt");
// The call takes its file (renaming it to `.taken`) and reads it: make
// what it reads a named pipe, so it waits there for a writer.
let uploads = home.book_dir(A).join("uploads");
let bin = uploads.join(format!("{up}.bin"));
std::fs::remove_file(&bin).unwrap();
assert!(
std::process::Command::new("mkfifo")
.arg(&bin)
.status()
.unwrap()
.success()
);
let mut raw = raw::Raw::connect(&home, A);
let body = json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {
"name": "books.back_up_now", "arguments": {}}})
"name": "books.attach_receipt", "arguments": {"upload_id": up}}})
.to_string();
raw.start(
"POST",
@@ -1508,31 +1599,56 @@ fn a_running_call_is_never_cut_when_the_grace_runs_out() {
body.as_bytes(),
body.len(),
);
wait_for("the call reached git", Duration::from_secs(30), || {
shim.join("stalled").exists()
});
// Inside its read: a writer can open the pipe without blocking only
// once a reader has it open. (The writer is kept, to feed it later.)
let taken = uploads.join(format!("{up}.taken"));
let mut feed = None;
wait_for(
"the call is reading its file",
Duration::from_secs(60),
|| match std::fs::OpenOptions::new()
.write(true)
.custom_flags(libc::O_NONBLOCK)
.open(&taken)
{
Ok(f) => {
feed = Some(f);
true
}
Err(_) => false,
},
);
let closing = std::thread::spawn({
let admin = home.run().join("admin.sock");
move || ledger_mcp::admin::call(&admin, Request::CloseBook { id: A.into() }).unwrap()
});
// Well past the grace: the call is still running, and not cut.
wait_for("the book is listed closed", Duration::from_secs(30), || {
listed(&home, A).1
});
// A negative window well past the grace (400 ms): the call is still
// running, and not cut. It can only fail if the close was answered, never
// because the machine was slow.
std::thread::sleep(Duration::from_millis(1200));
assert!(
!closing.is_finished(),
"the close didn't wait for a running call"
);
std::fs::remove_file(shim.join("stall")).unwrap();
let (status, head) = raw.head();
assert_eq!(status, 200, "{head}");
{
use std::io::Write;
let mut feed = feed.take().unwrap();
feed.write_all(&bytes).unwrap();
}
let (status, said) = raw.answer();
assert_eq!(status, 200, "{said}");
let _ = closing.join().unwrap();
assert!(cut_records(&home, A, "books.back_up_now").is_empty());
assert!(cut_records(&home, A, "books.attach_receipt").is_empty());
assert!(cut_records(&home, A, "connect").is_empty());
assert!(
access_of(&home, A)
.iter()
.any(|r| r.access.subject == "books.back_up_now"
.any(|r| r.access.subject == "books.attach_receipt"
&& r.access.result == ledger_store::access::Outcome::Ok),
"the call that ran is on record as having run"
"the call that ran is on record as having run: {said}"
);
drop(raw);
assert!(server.close().success());
@@ -1674,6 +1790,7 @@ fn a_restore_over_an_open_book_waits_for_what_is_inside_it() {
"{records:?}"
);
let at_answer = tree_of(&legacy);
// A negative window (it can only fail if something moved).
std::thread::sleep(Duration::from_millis(300));
assert_eq!(moved(&at_answer, &tree_of(&legacy)), Vec::<String>::new());
assert!(server.close().success());
@@ -1996,7 +2113,7 @@ fn the_servers_own_close_cuts_stalled_requests_and_exits_zero_in_time() {
"name": "books.draft_entry",
"arguments": {"date": "2026-03-01", "description": "never finished"}}})
.to_string();
raw_call.start(
raw_call.start_inside(
"POST",
"mcp",
&[
@@ -2008,7 +2125,6 @@ fn the_servers_own_close_cuts_stalled_requests_and_exits_zero_in_time() {
body.as_bytes(),
body.len() / 2,
);
std::thread::sleep(Duration::from_millis(200));
let started = std::time::Instant::now();
let status = server.close();
let took = started.elapsed();
@@ -2107,8 +2223,9 @@ fn a_late_timer_does_nothing(name: &str, held_timers: &str) {
let at_close = tree_of(&dir);
// The timers go on, with what they took before the close.
std::fs::remove_file(run.join("timer-hold")).unwrap();
std::thread::sleep(Duration::from_millis(300));
stands_still(&home, A, Duration::from_millis(500), "a late timer");
// (A window in which nothing may move, begun at the release: no wait
// before it for the timers to get going, which proved nothing.)
stands_still(&home, A, Duration::from_millis(800), "a late timer");
assert_eq!(moved(&at_close, &tree_of(&dir)), Vec::<String>::new());
assert!(dir.join("uploads").join("stray.bin").exists());
assert!(dir.join("exports").join("stray.bin").exists());
@@ -2291,10 +2408,11 @@ fn fsck_of(repo: &std::path::Path) {
}
/// A close that stops real git inside a commit, and inside a push to a
/// folder, leaves no lock for anyone to remove: each is gone before the
/// close is answered and noted in the backup's record, the book opened
/// again at once backs up with no step by hand, and both repositories pass
/// `git fsck` (ledger_store::backup INVARIANT 5).
/// folder, leaves no lock for anyone to remove: git is sent SIGTERM and
/// removes its own locks, so there is nothing for the server to clean up
/// (the backup's record holds no `lock_removed` or `lock_left`), the book
/// opened again at once backs up with no step by hand, and both
/// repositories pass `git fsck` (ledger_store::backup INVARIANT 5).
#[cfg(unix)]
#[test]
fn a_close_that_stops_git_in_a_commit_or_a_push_leaves_no_lock_and_the_next_backup_succeeds() {
@@ -2339,7 +2457,11 @@ fn a_close_that_stops_git_in_a_commit_or_a_push_leaves_no_lock_and_the_next_back
"git never reached its ref update"
);
assert_eq!(locks_under(&archive), Vec::<String>::new());
assert!(record().contains("HEAD.lock"), "{}", record());
assert!(
!record().contains("lock_removed") && !record().contains("lock_left"),
"git removed its own locks: nothing was cleaned up here: {}",
record()
);
std::fs::remove_file(shim.join("slow-commit")).unwrap();
std::fs::remove_file(shim.join("hooked")).unwrap();
assert_eq!(open_book(&home, A), OpenOutcome::Opened);
@@ -2373,8 +2495,8 @@ fn a_close_that_stops_git_in_a_commit_or_a_push_leaves_no_lock_and_the_next_back
);
assert_eq!(locks_under(&archive), Vec::<String>::new());
assert!(
record().contains("\"kind\":\"lock_removed\"") && record().contains("refs/heads/main.lock"),
"the removal wasn't recorded: {}",
!record().contains("lock_removed") && !record().contains("lock_left"),
"git removed its own locks: nothing was cleaned up here: {}",
record()
);
std::fs::remove_file(shim.join("slow-commit")).unwrap();
@@ -2410,8 +2532,8 @@ fn a_close_that_stops_git_in_a_commit_or_a_push_leaves_no_lock_and_the_next_back
assert_eq!(locks_under(&target), Vec::<String>::new());
assert_eq!(locks_under(&archive), Vec::<String>::new());
assert!(
record().contains("\"repo\":\"folder\""),
"the folder's lock wasn't recorded: {}",
!record().contains("lock_removed") && !record().contains("lock_left"),
"git removed its own locks: nothing was cleaned up here: {}",
record()
);
std::fs::remove_file(shim.join("slow-push")).unwrap();
@@ -2435,3 +2557,576 @@ fn a_close_that_stops_git_in_a_commit_or_a_push_leaves_no_lock_and_the_next_back
.expect("the backup record is a whole chain");
assert!(server.close().success());
}
/// A tool call sent on `w`'s session, its whole body written and its answer
/// not yet read: the connection it went out on.
#[cfg(unix)]
fn call_unanswered(home: &Home, w: &Wire, id: u64, tool: &str, args: Value) -> raw::Raw {
let mut raw = raw::Raw::connect(home, A);
let body = json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {
"name": tool, "arguments": args}})
.to_string();
raw.start(
"POST",
"mcp",
&[
("content-type", "application/json"),
("accept", "application/json, text/event-stream"),
("mcp-session-id", w.session().unwrap()),
("mcp-protocol-version", w.version().unwrap()),
],
body.as_bytes(),
body.len(),
);
raw
}
/// Hold every process of the group `pid` leads still (SIGSTOP): a SIGTERM
/// sent to it then stays pending, git can't end on it, and only the kill
/// after the grace ends it (how a git that can't end on SIGTERM, holding
/// its locks, is made on purpose).
#[cfg(unix)]
fn freeze_group_of(pid: u32) {
let out = std::process::Command::new("ps")
.args(["-o", "pgid=", "-p", &pid.to_string()])
.output()
.unwrap();
let group: i32 = String::from_utf8_lossy(&out.stdout)
.trim()
.parse()
.expect("ps names the group");
// SAFETY: stopping the group of a git this test's server started.
assert_eq!(unsafe { libc::kill(-group, libc::SIGSTOP) }, 0);
}
/// The most a close may take in these tests where what it stops would
/// otherwise run for ever (a stall that is never lifted): a guard against a
/// hang, not a measure of speed. That the close ends at all, with the stall
/// still in place, is what proves it stopped the call or job.
#[cfg(unix)]
const NEVER_LONGER: Duration = Duration::from_secs(120);
/// The backup record of `id`, whole.
#[cfg(unix)]
fn backup_record_of(home: &Home, id: &str) -> Vec<serde_json::Map<String, Value>> {
ledger_store::chain::read(
&ledger_store::ops::ops_dir(&home.book_dir(id)).join("backup.jsonl"),
"wanderbooks-backup-v1",
)
.expect("the backup record is a whole chain")
.records
}
/// A backup call that is running (git stalled) when a close begins is
/// STOPPED by it, not waited for: the call is answered, while git is still
/// stalled, that it was stopped because the books are closing; its access
/// record says `refused: stopped_by_close`; the backup records `stopped`
/// and no result of the run's own (nothing it was doing is recorded as
/// done); git and all it started are gone; and the close's own last
/// backup is made as always (local.rs INVARIANT 10).
#[cfg(unix)]
#[test]
fn a_close_stops_a_running_backup_call_and_says_so() {
let home = Home::new("close-stops-backup-call");
let shim = shim_git(&home);
let server = server_with_shim(
&home,
&shim,
&[
"--close-backup",
"20000",
"--backup-quiet",
"3600000",
"--timers",
"20",
],
);
home.create(A, "USD");
let disk = home.dir.path().join("disk");
std::fs::create_dir_all(&disk).unwrap();
let mut w = Wire::new(&home, A);
w.initialize("owner");
set_backup_folder(&mut w, &disk);
draft(&mut w, "moves the head");
std::fs::write(shim.join("stall"), b"").unwrap();
let mut call = call_unanswered(&home, &w, 4, "books.back_up_now", json!({}));
wait_for("the call reached git", Duration::from_secs(60), || {
shim.join("stalled").exists()
});
let started = std::time::Instant::now();
let closing = std::thread::spawn({
let admin = home.run().join("admin.sock");
move || ledger_mcp::admin::call(&admin, Request::CloseBook { id: A.into() }).unwrap()
});
// Answered with git still stalled: stopped by the close, not let go.
let (status, said) = call.answer();
assert_eq!(status, 200, "{said}");
assert!(
said.contains("stopped because the books are closing")
&& said.contains("nothing it was doing is recorded as done"),
"{said}"
);
assert!(shim.join("stall").exists(), "the stall was lifted first");
// Lifted now, so the close's own last backup can run.
std::fs::remove_file(shim.join("stall")).unwrap();
match closing.join().unwrap() {
Response::CloseBook { outcome, .. } => assert_eq!(outcome, CloseOutcome::Closed),
other => panic!("{other:?}"),
}
assert!(started.elapsed() < NEVER_LONGER);
let stalled: Vec<u32> = std::fs::read_to_string(shim.join("stalled"))
.unwrap_or_default()
.lines()
.filter_map(|l| l.trim().parse().ok())
.collect();
for pid in &stalled {
assert!(!alive(*pid), "git {pid} still runs");
}
let records = access_of(&home, A);
let mine = records
.iter()
.find(|r| r.access.subject == "books.back_up_now")
.expect("the call is on record");
assert_eq!(
mine.access.result,
ledger_store::access::Outcome::Refused("stopped_by_close".into())
);
assert!(mine.access.head_after.is_none());
let record = backup_record_of(&home, A);
assert!(
record
.iter()
.any(|r| r.get("kind") == Some(&json!("stopped"))
&& r.get("why") == Some(&json!("asked"))),
"{record:?}"
);
assert!(
!record
.iter()
.any(|r| r.get("why") == Some(&json!("asked"))
&& r.get("kind") != Some(&json!("stopped"))),
"the stopped run recorded a result of its own: {record:?}"
);
assert!(server.close().success());
}
/// A verification and a package that are running when a close begins are
/// stopped by it, each answering that it was stopped because the books are
/// closing, each on record as `refused: stopped_by_close`, and the journal
/// untouched. Each is held as it begins by the server's test knob
/// (`--timer-hold`: `call:books.verify`, `call:books.export_cpa_package`),
/// which the close's start releases; the stop is then at the call's first
/// look.
#[cfg(unix)]
#[test]
fn a_close_stops_a_running_verification_and_a_running_package_and_says_so() {
let home = Home::new("close-stops-verify-package");
let server = Server::start_with(
&home,
&[
"--timer-hold",
"--timers",
"20",
"--backup-quiet",
"3600000",
],
);
home.create(A, "USD");
let run = home.run();
let mut w = Wire::new(&home, A);
w.initialize("owner");
let mut other = Wire::new(&home, A);
other.initialize("packager");
let held = ["call:books.verify", "call:books.export_cpa_package"];
std::fs::write(run.join("timer-hold"), held.join(",")).unwrap();
let mut verify = call_unanswered(&home, &w, 4, "books.verify", json!({}));
let mut package = call_unanswered(
&home,
&other,
5,
"books.export_cpa_package",
json!({"cash_accounts": ["1000"]}),
);
let seen = || std::fs::read_to_string(run.join("timer-held")).unwrap_or_default();
wait_for("both calls are held", Duration::from_secs(60), || {
held.iter().all(|h| seen().lines().any(|l| l == *h))
});
let before = files_of(&home, A);
let started = std::time::Instant::now();
// The hold is never lifted by the test: the close does it (it is the
// close that releases the calls, which then stop at their first look).
let closing = std::thread::spawn({
let admin = home.run().join("admin.sock");
move || ledger_mcp::admin::call(&admin, Request::CloseBook { id: A.into() }).unwrap()
});
for (what, call) in [("verify", &mut verify), ("package", &mut package)] {
let (status, said) = call.answer();
assert_eq!(status, 200, "{what}: {said}");
assert!(
said.contains("stopped because the books are closing"),
"{what}: {said}"
);
}
match closing.join().unwrap() {
Response::CloseBook { outcome, .. } => assert_eq!(outcome, CloseOutcome::Closed),
other => panic!("{other:?}"),
}
assert!(started.elapsed() < NEVER_LONGER);
assert_eq!(files_of(&home, A).0.len(), before.0.len());
let records = access_of(&home, A);
for tool in ["books.verify", "books.export_cpa_package"] {
let mine = records
.iter()
.find(|r| r.access.subject == tool)
.unwrap_or_else(|| panic!("{tool} isn't on record"));
assert_eq!(
mine.access.result,
ledger_store::access::Outcome::Refused("stopped_by_close".into()),
"{tool}"
);
assert!(mine.access.head_after.is_none(), "{tool}");
}
std::fs::remove_file(run.join("timer-hold")).unwrap();
assert!(server.close().success());
}
/// The files of `books/` byte for byte (the staging and scratch folders
/// among them), but for the books in `live`: those the server has open and
/// works on by itself (its timers write their archives and logs).
#[cfg(unix)]
fn root_without(home: &Home, live: &[&str]) -> BTreeMap<String, (u64, String)> {
tree_of(&home.root().join("books"))
.into_iter()
.filter(|(k, _)| !live.iter().any(|b| k.starts_with(&format!("{b}/"))))
.collect()
}
/// A job on the admin socket (restore, adopt, create, open) that is running
/// when a close of another book begins is stopped by it, before its point of
/// no return: it answers that it was stopped because the books are closing,
/// what it wrote is removed, and the root is byte for byte as it was (the
/// job's staging or scratch folder is there while it is held, and gone after;
/// asked again with no close, it goes through). Each job is held inside a
/// phase by the server's test knob (`--timer-hold`, `job:phase`), which the
/// close's start releases; the stop is then at the job's next look.
#[cfg(unix)]
#[test]
fn a_close_stops_a_running_restore_adopt_create_and_open_leaving_the_root_as_it_was() {
const C: &str = "cedar";
let home = Home::new("close-stops-jobs");
let server = Server::start_with(
&home,
&[
"--timer-hold",
"--timers",
"20",
"--backup-quiet",
"3600000",
"--answer-grace",
"300",
],
);
home.create(A, "USD");
home.create(C, "USD");
assert!(matches!(close_book(&home, C), CloseOutcome::Closed));
let mut w = Wire::new(&home, A);
w.initialize("owner");
let repo = backed_up_to_folder(&home, &mut w, A);
w.end();
let old = tempfile::Builder::new()
.prefix("wb-close-old-")
.tempdir()
.unwrap();
let data = old.path().join("books-data");
drop(ledger_store::Store::create(&data, ledger_core::Currency::USD).unwrap());
let toml = "[company]\nname = \"Acme Widgets LLC\"\n".to_string();
let run = home.run();
let restore_head = match home.admin(Request::Restore {
id: "gamma".into(),
source: repo.display().to_string(),
replace: false,
confirmed: false,
expect_head: None,
}) {
Response::RestorePreview(p) => p.head,
other => panic!("{other:?}"),
};
let adopt = |confirmed: bool, head: Option<(u64, String)>| Request::Adopt {
id: "delta".into(),
source: data.clone(),
settings_toml: Some(toml.clone()),
config_json: None,
vault_dir: None,
vault_key: None,
confirmed,
expect_head: head,
skip_unknown: true,
};
let adopt_head = match home.admin(adopt(false, None)) {
Response::Preview(p) => p.source_head,
other => panic!("{other:?}"),
};
let restore = || Request::Restore {
id: "gamma".into(),
source: repo.display().to_string(),
replace: false,
confirmed: true,
expect_head: Some(restore_head.clone()),
};
// (the held name, the job, what it says it didn't do, whether it leaves
// a folder of its own in `books/` while it is held)
let jobs: Vec<(&str, Request, &str, bool)> = vec![
("restore:copy", restore(), "nothing was restored", true),
(
"adopt:open",
adopt(true, Some(adopt_head)),
"nothing was adopted",
true,
),
(
"create:start",
Request::Create {
id: "epsilon".into(),
currency: "USD".into(),
},
"nothing was created",
false,
),
(
"open:start",
Request::OpenBook { id: C.into() },
"not opened",
false,
),
];
let count = |name: &str| {
std::fs::read_to_string(run.join("timer-held"))
.unwrap_or_default()
.lines()
.filter(|l| *l == name)
.count()
};
// The books open and live while a job is held: not compared (the job's
// own book, not yet there, is).
let mut live = vec![A];
for (name, job, said, leaves_a_folder) in jobs {
let before = root_without(&home, &live);
let legacy_before = tree_of(&home.root().join("legacy"));
std::fs::write(run.join("timer-hold"), name).unwrap();
let seen = count(name);
let running = std::thread::spawn({
let admin = home.run().join("admin.sock");
let job = job.clone();
move || ledger_mcp::admin::call(&admin, job).unwrap()
});
wait_for(
&format!("{name} is held inside the job"),
Duration::from_secs(300),
|| count(name) > seen || running.is_finished(),
);
if running.is_finished() {
panic!(
"{name}: the job ended before it was held: {:?}",
running.join()
);
}
if leaves_a_folder {
assert_ne!(
root_without(&home, &live),
before,
"{name}: the job wrote nothing while held"
);
}
let started = std::time::Instant::now();
// The close of another book: it stops the job (it waits for the
// job's lock otherwise), and the test lifts nothing.
let closed = close_book(&home, A);
assert_eq!(closed, CloseOutcome::Closed, "{name}");
assert!(started.elapsed() < NEVER_LONGER, "{name}");
let answer = running.join().unwrap();
let text = format!("{answer:?}");
assert!(
text.contains("stopped because the books are closing") && text.contains(said),
"{name}: {text}"
);
std::fs::remove_file(run.join("timer-hold")).unwrap();
let after = root_without(&home, &live);
assert_eq!(
moved(&before, &after),
Vec::<String>::new(),
"{name}: the root isn't as it was"
);
assert_eq!(
tree_of(&home.root().join("legacy")),
legacy_before,
"{name}"
);
assert_eq!(open_book(&home, A), OpenOutcome::Opened, "{name}");
// Asked again, with nothing closing, it goes through.
match (name, home.admin(job)) {
("restore:copy", Response::Restored(_))
| ("adopt:open", Response::Adopted(_))
| ("create:start", Response::Created { .. })
| ("open:start", Response::OpenBook { .. }) => {}
(name, other) => panic!("{name}, asked again: {other:?}"),
}
live.push(match name {
"restore:copy" => "gamma",
"adopt:open" => "delta",
"create:start" => "epsilon",
_ => C,
});
}
assert_eq!(listed(&home, C), (true, false, None));
for id in ["gamma", "delta", "epsilon"] {
assert_eq!(listed(&home, id), (true, false, None), "{id}");
}
assert!(server.close().success());
}
/// A git that can't end on SIGTERM (its group frozen here, so the signal
/// stays pending) is killed once the grace has run out, and the lock it
/// leaves in a backup FOLDER is the owner's: the server never removes it. It
/// is recorded with its whole path, the target's backup is marked failed with
/// words naming the file and saying when it may be removed, the close says
/// its last backup wasn't whole, and the status (`books.backup`) says the
/// same after the book is opened again. The next backup, meeting the lock,
/// fails by git's own words and leaves the file; once the owner removes it
/// the backup goes on, and both repositories pass `git fsck`.
#[cfg(unix)]
#[test]
fn a_lock_a_kill_leaves_in_the_backup_folder_is_reported_and_never_removed_by_the_server() {
let home = Home::new("close-lock-left");
let shim = slow_real_git(&home);
// A bound long enough that the test freezes git before the close's own
// bound runs out: the freeze is made on the condition that git is
// inside the push, not on a guess at how long that takes.
let server = server_with_shim(
&home,
&shim,
&[
"--close-backup",
"8000",
"--backup-quiet",
"3600000",
"--timers",
"20",
],
);
home.create(A, "USD");
let disk = home.dir.path().join("disk");
std::fs::create_dir_all(&disk).unwrap();
let mut w = Wire::new(&home, A);
w.initialize("owner");
set_backup_folder(&mut w, &disk);
draft(&mut w, "the first backup");
match home.admin(Request::BackUpNow {
id: A.into(),
new_disk: false,
}) {
Response::BackedUp { targets, .. } => {
assert!(targets.iter().all(|t| t.problem.is_none()), "{targets:?}");
}
other => panic!("{other:?}"),
}
draft(&mut w, "to be pushed inside a push");
let target = disk.join(format!("{A}.git"));
let lock = target.join("refs").join("heads").join("main.lock");
// Another writer's lock, there before our push: never touched, never
// named.
let another = target.join("refs").join("heads").join("another.lock");
std::fs::write(&another, b"").unwrap();
std::fs::write(shim.join("slow-push"), b"").unwrap();
let closing = std::thread::spawn({
let admin = home.run().join("admin.sock");
move || ledger_mcp::admin::call(&admin, Request::CloseBook { id: A.into() }).unwrap()
});
wait_for("git is inside the push", Duration::from_secs(60), || {
shim.join("hooked").exists() && lock.exists()
});
let hooked: u32 = std::fs::read_to_string(shim.join("hooked"))
.unwrap()
.lines()
.next()
.unwrap()
.trim()
.parse()
.unwrap();
freeze_group_of(hooked);
let outcome = match closing.join().unwrap() {
Response::CloseBook { outcome, .. } => outcome,
other => panic!("{other:?}"),
};
let why = match outcome {
CloseOutcome::ClosedBackupIncomplete(why) => why,
other => panic!("a backup that left a lock was answered as {other:?}"),
};
let lock_text = lock.display().to_string();
assert!(why.contains(&lock_text), "{why}");
assert!(
why.contains("nothing else is using the backup folder"),
"{why}"
);
assert!(!why.contains("another.lock"), "{why}");
assert!(!why.contains(&home.root().display().to_string()), "{why}");
// Left where it was: the server deleted nothing in the owner's folder.
assert!(lock.exists(), "a file in the owner's folder was deleted");
assert!(another.exists());
let record = backup_record_of(&home, A);
assert!(
record
.iter()
.any(|r| r.get("kind") == Some(&json!("lock_left"))
&& r.get("repo") == Some(&json!("folder"))
&& r.get("path") == Some(&json!(lock_text))),
"{record:?}"
);
assert!(
!record
.iter()
.any(|r| r.get("kind") == Some(&json!("lock_removed"))
&& r.get("repo") == Some(&json!("folder"))),
"{record:?}"
);
// Opened again, the status says it, in words that name the file.
std::fs::remove_file(shim.join("slow-push")).unwrap();
assert_eq!(open_book(&home, A), OpenOutcome::Opened);
let mut w = Wire::new(&home, A);
w.initialize("owner");
let status = w.call("books.backup", json!({}));
let shown = status["result"]["structuredContent"]["targets"][0]["last_error"]
.as_str()
.unwrap_or_else(|| panic!("the status names no failure: {status}"))
.to_string();
assert!(shown.contains(&lock_text), "{shown}");
assert!(
shown.contains("nothing else is using the backup folder"),
"{shown}"
);
// With the lock still there the next backup fails (git's own words) and
// the file stays; once the owner removes it, it goes on.
match home.admin(Request::BackUpNow {
id: A.into(),
new_disk: false,
}) {
Response::BackedUp { targets, .. } => {
assert!(targets.iter().any(|t| t.problem.is_some()), "{targets:?}");
}
other => panic!("{other:?}"),
}
assert!(lock.exists(), "a later backup removed it");
std::fs::remove_file(&lock).unwrap();
match home.admin(Request::BackUpNow {
id: A.into(),
new_disk: false,
}) {
Response::BackedUp { targets, .. } => {
assert!(targets.iter().all(|t| t.problem.is_none()), "{targets:?}");
}
other => panic!("{other:?}"),
}
assert!(another.exists());
fsck_of(&home.book_dir(A).join("archive.git"));
fsck_of(&target);
assert!(server.close().success());
}
+3
View File
@@ -124,6 +124,9 @@ pub(crate) const CLOSING: &str = "closing";
pub(crate) const CUT: &str = "cut_by_close";
/// The server had stopped.
pub(crate) const STOPPED: &str = "stopped";
/// A call that was running when a close began, stopped by it: it answered
/// that it was stopped, and nothing it was doing is recorded as done.
pub(crate) const STOPPED_BY_CLOSE: &str = "stopped_by_close";
/// A file's bytes or text came as an argument (D-46).
pub(crate) const INLINE_FILE: &str = "inline_file";
+187 -44
View File
@@ -60,28 +60,51 @@
//! are doing: not in this process's later opening of the same books,
//! whose own backups are another object with another record handle.
//! 11. A close is not held by a step it doesn't wait for. When a close
//! begins (`hurry`, before its last backup), a drill, and a format
//! upgrade that has not yet appended its `journal.format_set` line,
//! stop at their next look (ledger_store::backup INVARIANT 6: between
//! git commands and phases, once per journal line, file or 64 KiB
//! chunk): a drill's scratch clone is removed and nothing is said of
//! its target (neither a pass nor a failure: it is due again when the
//! books next open); an upgrade is reported not done, the books
//! unchanged, and its backup (a commit it made on the way) recorded.
//! Once the `journal.format_set` line is appended the upgrade
//! finishes, which is quick (the line, the database's row). The last
//! backup of the close, and the stop `shut` makes of what is left of
//! it, are not hurried: only `shut` stops them. The close's whole
//! bound is the sum written in the books server's INVARIANT 10
//! (local.rs).
//! begins (`hurry`, before its last backup), these stop at their next
//! look: a drill, a format upgrade that has not yet reached its final
//! look, and a backup a call or a timer asked for (`run_with` for any
//! `why` but `close`), looking between git commands and phases, once
//! per journal line, file or 64 KiB chunk (ledger_store::backup
//! INVARIANT 6), and between targets. A drill's scratch clone is
//! removed and nothing is said of its target (neither a pass nor a
//! failure: it is due again when the books next open). A run stopped
//! this way records `stopped` (what it was doing: `commit` or `push`)
//! and no result of its own for the step it didn't finish: a commit it
//! had made stands in the archive and is recorded as made, a target it
//! hadn't pushed to is said nothing of, and its caller is told it was
//! stopped because the books are closing (tools/backup.rs, which marks
//! the call's access record `stopped_by_close`). The one thing a stop is
//! a failure for is a lock git left in the owner's folder (INVARIANT 12).
//! An upgrade is reported not done, the books unchanged, and its backup
//! (a commit it made on the way) recorded, if the close's stop reaches
//! it before its final look, which is made once everything it needs is
//! proven and just before the `journal.format_set` line is appended: a
//! stop is honoured up to that look. One that arrives between it and the
//! append does not undo the upgrade: the line is appended, the database's
//! row is written and the upgrade is recorded as made (safe: the books
//! are in this version's format and proven backed up, and the close that
//! asked for the stop is waiting for the books lock). The last backup of
//! the close, and the stop `shut` makes of what is left of it, are not
//! hurried: only `shut` stops them. The close's whole bound is the sum
//! written in the books server's INVARIANT 10 (local.rs).
//! 12. A lock file a stopped git left is dealt with by the step that
//! stopped it (ledger_store::backup INVARIANT 5) and recorded: a
//! record `lock_removed` (or `lock_left`, for one it must not touch)
//! with `repo` (`archive`, `folder` or `repository`), `lock` (a path
//! in that repository) and `why`; so are the locks found in the
//! archive when the books open (the store is open, and its lock is
//! ours). A close is not answered before these are recorded, the
//! backup record being closed after them.
//! record `lock_removed` (the archive's own, made by the git just
//! stopped) or `lock_left`, with `repo` (`archive`, `folder` or
//! `repository`), `lock` (a path in that repository), `why`, and for a
//! lock left in the owner's folder, `path`, its whole path. Git is sent
//! SIGTERM first and removes its own locks, so these records are the
//! rare case. A lock left in the owner's folder is never removed by
//! this program: it marks that target's backup failed, in a `push`
//! record whose error names the files and says to remove them only when
//! nothing else is using the backup folder; that error is the target's
//! `last_error` in `books.backup` and in the server's backup status, and
//! what a close that couldn't finish its last backup says. (A run whose
//! future was dropped at its bound has that record written by `shut`.)
//! The archive's locks found when the books open are dealt with the
//! same way (the store is open, and its lock is ours): only those older
//! than ten minutes are removed. A close is not answered before these
//! are recorded, the backup record being closed after them.
//! ```
use crate::server::SharedStore;
@@ -128,6 +151,9 @@ pub const RETRY_AFTER: std::time::Duration = std::time::Duration::from_secs(15 *
/// The most of an error kept.
const ERROR_MAX: usize = 500;
/// The test knob that holds a stoppable call as it begins ([`Backups::set_hold`]).
type CallHold = Arc<dyn Fn(&str) + Send + Sync>;
/// A book's backups.
pub struct Backups {
book: String,
@@ -142,8 +168,10 @@ pub struct Backups {
busy: Arc<Busy>,
/// Set when a close begins, before its last backup (INVARIANT 11): the
/// steps a close doesn't wait for (a drill, a format upgrade not yet
/// journaled) stop, and `shut` sets it too. A backup's own git is
/// stopped by `shut` alone, so the close's last backup can run.
/// journaled, a backup a call or a timer asked for) stop, and `shut`
/// sets it too. It is the book's store's flag (`SharedStore::hurry`), so
/// the book's calls that can run long see it too. The close's own last
/// backup is stopped by `shut` alone, so it can run.
hurry: Arc<AtomicBool>,
/// The lock files a stopped git left, as they were dealt with
/// (ledger_store::backup INVARIANT 5), until they are recorded.
@@ -154,6 +182,10 @@ pub struct Backups {
/// Phases that began their wait (the test knob), for a test to see
/// that a step is inside one.
paused: Arc<AtomicUsize>,
/// A test knob (`--timer-hold`): told the name of a call that can be
/// stopped by a close as it begins (`books.verify`, ...); it may wait,
/// and gives up when the close begins (`hurry`). Nothing without it.
hold: Mutex<Option<CallHold>>,
}
/// What a format upgrade did ([`Backups::upgrade_format`]).
@@ -325,6 +357,7 @@ impl Backups {
}
Err(e) => return Err(format!("its backup record can't be used: {e}")),
};
let hurry = store.hurry_flag();
let me = Self {
book: book.to_string(),
dir: dir.to_path_buf(),
@@ -333,17 +366,19 @@ impl Backups {
running: tokio::sync::Mutex::new(()),
shut: Arc::default(),
busy: Arc::default(),
hurry: Arc::default(),
hurry,
locks: LockNotes::default(),
slow_ms: AtomicU64::new(0),
paused: Arc::default(),
hold: Mutex::new(None),
};
for fields in carried {
me.record(fields);
}
// The store is open, so its lock is ours: no other wanderbooks
// process runs git on this archive, and none of this process's does
// yet, so a lock in it is a dead git's (store INVARIANT 5a).
// yet. A lock in it older than ten minutes is a dead git's; a
// younger one is left (store INVARIANT 5a).
for note in backup::clear_archive_locks(dir) {
me.record_lock(&note);
}
@@ -396,13 +431,25 @@ impl Backups {
Ok(step)
}
/// git, stopped by `shut`.
/// git, stopped by `shut`: the close's own last backup (INVARIANT 10).
fn git(&self) -> Result<Git, BackupError> {
Ok(Git::find()?
.with_cancel(self.shut.clone())
.with_lock_notes(self.locks.clone()))
}
/// git for a backup a call or a timer asked for: stopped as soon as a
/// close begins (INVARIANT 11), so it can't hold the close.
fn git_for(&self, why: &str) -> Result<Git, BackupError> {
if why == "close" {
self.git()
} else {
Ok(Git::find()?
.with_cancel(self.hurry.clone())
.with_lock_notes(self.locks.clone()))
}
}
/// git for a step a close hurries (a drill, a format upgrade): stopped
/// as soon as the close begins (INVARIANT 11).
fn hurried_git(&self) -> Result<Git, BackupError> {
@@ -434,6 +481,19 @@ impl Backups {
self.slow_ms.store(by.as_millis() as u64, Ordering::SeqCst);
}
/// Install the test knob that holds a stoppable call as it begins.
pub(crate) fn set_hold(&self, hold: CallHold) {
*self.hold.lock().unwrap_or_else(|e| e.into_inner()) = Some(hold);
}
/// A call that a close can stop has begun (the test knob's seam).
pub(crate) fn hold(&self, call: &str) {
let hold = self.hold.lock().unwrap_or_else(|e| e.into_inner()).clone();
if let Some(hold) = hold {
hold(call);
}
}
/// How many waits of the test knob have begun.
#[cfg(test)]
pub(crate) fn pauses_begun(&self) -> usize {
@@ -454,23 +514,30 @@ impl Backups {
/// A lock a stopped git left, as it was dealt with: a record of the
/// backup (INVARIANT 12).
fn record_lock(&self, note: &backup::LockNote) {
self.record(json!({
let mut fields = json!({
"kind": if note.removed { "lock_removed" } else { "lock_left" },
"repo": note.repo, "lock": note.lock, "why": note.why,
}));
});
// A lock left in the owner's folder is named by its whole path.
if let (Some(path), Value::Object(map)) = (&note.path, &mut fields) {
map.insert("path".into(), json!(path));
}
self.record(fields);
}
/// Record the locks dealt with since the last look.
fn note_locks(&self) {
for note in self.locks.take() {
self.record_lock(&note);
/// Record the locks dealt with since the last look; the notes.
fn note_locks(&self) -> Vec<backup::LockNote> {
let notes = self.locks.take();
for note in &notes {
self.record_lock(note);
}
notes
}
/// Shut these backups for good (INVARIANT 10): git stopped, every step
/// ended, the record closed. Call it after the last backup the books
/// will have, and before the books' store is let go.
pub async fn shut(&self) {
pub async fn shut(&self) -> Vec<String> {
self.shut.store(true, Ordering::SeqCst);
self.hurry.store(true, Ordering::SeqCst);
// The run or drill holding the books' turn ends (its git was just
@@ -483,8 +550,36 @@ impl Backups {
}
ended.await;
}
self.note_locks();
let notes = self.note_locks();
// A run whose future was dropped at its bound (a close's last
// backup) never recorded its push: a lock its stopped git left in the
// owner's folder is that target's failure all the same, named, in the
// standing the owner reads (ledger_store::backup INVARIANT 5b). Locks
// a run took in hand itself were recorded by it, and aren't here.
let left: Vec<&backup::LockNote> = notes
.iter()
.filter(|n| !n.removed && n.path.is_some())
.collect();
let mut said = Vec::new();
if !left.is_empty() {
for n in self.named().await {
let paths: Vec<&str> = left
.iter()
.filter(|l| l.repo == n.target.kind())
.filter_map(|l| l.path.as_deref())
.collect();
if !paths.is_empty() {
let error = BackupError::LockLeft(paths.join(", ")).to_string();
self.record(
json!({"kind": "push", "why": "close", "target": n.target.kind(),
"at": n.at, "key": n.key, "ok": false, "error": error}),
);
said.push(error);
}
}
}
self.log.lock().unwrap_or_else(|e| e.into_inner()).close();
said
}
fn records(&self) -> Vec<Map<String, Value>> {
@@ -554,12 +649,18 @@ impl Backups {
if self.store.is_stopped() {
return Err(crate::server::STOPPED.to_string());
}
// A run a call or a timer asked for is stopped by a close
// (INVARIANT 11); the close's own last backup is not.
let stoppable = why != "close";
if stoppable && self.hurried() {
return Err(self.stopped_words(None));
}
if self.named().await.is_empty() {
return Ok(self.status().await);
}
let step = self.begin()?;
let (store, dir, book) = (self.store.clone(), self.dir.clone(), self.book.clone());
let git = self.git();
let git = self.git_for(why);
let made = tokio::task::spawn_blocking(move || {
let _step = step;
let git = git?;
@@ -578,13 +679,26 @@ impl Backups {
})
.await
.unwrap_or(Err(BackupError::Damaged("the backup stopped".into())));
self.note_locks();
let _ = self.note_locks();
let (made, named, head) = match made {
Ok(m) => m,
// Stopped by a close: neither a success nor a failure of the
// backup, so nothing is said of any target (INVARIANT 11); what
// was committed before it stands in the archive, and the close
// makes its own last backup.
Err(BackupError::Cancelled(_)) if stoppable => {
self.record(json!({"kind": "stopped", "why": why, "during": "commit"}));
return Err(self.stopped_words(None));
}
Err(e) => {
let lock_left = matches!(e, BackupError::LockLeft(_));
let e = hide(&e.to_string(), &self.dir);
self.record(json!({"kind": "commit", "why": why, "ok": false, "error": e}));
return Err(e);
return Err(if stoppable && self.hurried() && lock_left {
self.stopped_words(Some(&e))
} else {
e
});
}
};
if let Some(m) = &made {
@@ -602,10 +716,14 @@ impl Backups {
{
continue;
}
if stoppable && self.hurried() {
self.record(json!({"kind": "stopped", "why": why, "during": "push"}));
return Err(self.stopped_words(None));
}
// Its repository is made only where it never took a backup.
let may_create = new_disk || !held_before(&n.key, &records);
let step = self.begin()?;
let git = self.git();
let git = self.git_for(why);
let (dir, book, t) = (self.dir.clone(), self.book.clone(), n.target.clone());
let pushed = tokio::task::spawn_blocking(move || {
let _step = step;
@@ -613,22 +731,47 @@ impl Backups {
})
.await
.unwrap_or(Err(BackupError::Damaged("the push stopped".into())));
self.note_locks();
let _ = self.note_locks();
match pushed {
Ok(commit) => self.record(
json!({"kind": "push", "why": why, "target": n.target.kind(),
"at": n.at, "key": n.key, "ok": true, "commit": commit,
"head": {"seq": head.0, "hash": head.1}}),
),
Err(e) => self.record(
json!({"kind": "push", "why": why, "target": n.target.kind(),
"at": n.at, "key": n.key, "ok": false, "error": e.to_string()}),
),
// Stopped by a close: not a failure of the target, and not
// a success: said once, of the run (INVARIANT 11).
Err(BackupError::Cancelled(_)) if stoppable => {
self.record(json!({"kind": "stopped", "why": why, "during": "push",
"target": n.target.kind(), "key": n.key}));
return Err(self.stopped_words(None));
}
Err(e) => {
let lock_left = matches!(e, BackupError::LockLeft(_));
self.record(
json!({"kind": "push", "why": why, "target": n.target.kind(),
"at": n.at, "key": n.key, "ok": false, "error": e.to_string()}),
);
// A stop that left a lock is a failure the owner must
// hear of, and the call is told both.
if stoppable && self.hurried() && lock_left {
return Err(self.stopped_words(Some(&hide(&e.to_string(), &self.dir))));
}
}
}
}
Ok(self.status().await)
}
/// What a run a close stopped answers: that it was stopped because the
/// books are closing (the call's access record says so), and, if it left
/// a lock in the owner's folder, that too.
fn stopped_words(&self, also: Option<&str>) -> String {
match also {
None => crate::server::STOPPED_BY_CLOSE_WORDS.to_string(),
Some(more) => format!("{} Also: {more}", crate::server::STOPPED_BY_CLOSE_WORDS),
}
}
/// The format upgrade, after a verified local backup with the keys
/// (plan/served.md 3.9, D-39; INVARIANT 9). The caller has the owner's
/// go-ahead (the passphrase, checked by the server).
@@ -739,7 +882,7 @@ impl Backups {
})
.await
.unwrap_or_else(|_| Err(UpgradeFailed::stopped("the upgrade stopped".into())));
self.note_locks();
let _ = self.note_locks();
match done {
Ok(u) => {
if let (Some(b), Some(up)) = (&u.backup, &u.upgrade) {
@@ -819,7 +962,7 @@ impl Backups {
})
.await
.unwrap_or(Err(BackupError::Damaged("the drill stopped".into())));
self.note_locks();
let _ = self.note_locks();
match drilled {
// Stopped by a close (INVARIANT 11): neither a pass nor a
// failure, so nothing is said of the target; the drill is
+309 -57
View File
@@ -42,9 +42,24 @@
//! 8. An MCP request reaches a book only with a bearer token that is
//! live for that book (auth/principals.jsonl; refused 401 without
//! one, 403 with another book's), and a session only with the token
//! that opened it (403). A request refused at the door is recorded
//! in that book's access log; the token rides with the request to
//! the book's tools, which check its scopes (access.rs). A session is
//! that opened it (403). A request that has entered an open book's
//! door and is then refused (no token, another book's, a revoked
//! one, the server closing), and a request cut by a close (INVARIANT
//! 15), are recorded in that book's access log. A request for a book
//! that is listed closed or failed, or that doesn't exist, and one
//! that loses the race at the door (the door shut by a close of the
//! book, a restore over it, or the server's close, between the lookup
//! and the entry), is refused before it is dispatched and is NOT
//! recorded: a closed book's log isn't written (it isn't open), and a
//! shut door belongs to a close that is waiting for the log. None of
//! these ran, and an unrecorded refusal can never be a call that
//! ran: the only way to a book's tools is through its door; a request
//! is counted inside it before anything of the book is touched, and
//! a call that ran is recorded before its answer goes (INVARIANT 14;
//! if it can't be, the server stops taking requests); a request
//! refused outside the door never reached the tools. The token rides
//! with the request to the book's tools, which check its scopes
//! (access.rs). A session is
//! bound to its token when opened, and forgotten when it ends, is
//! found gone, or its token is revoked or replaced; past MAX_SESSIONS
//! bindings a new session is refused (an initialize), never a binding
@@ -57,8 +72,10 @@
//! request: an upload only from the token that began it, a download
//! only with books:read, an export only to the token it was made for
//! (whose tool passed its own scope check; no other is asked). Each,
//! refused at the door or not, is recorded in the book's access log
//! as `upload`, `download` or `export` with its id, and the
//! once inside the door, ran or was refused there, is recorded in the
//! book's access log as `upload`, `download` or `export` with its id
//! (one refused outside the door is not recorded, and did not run:
//! INVARIANT 8), and the
//! bytes (kept, or read) and their record are one task that runs to
//! its end if the client hangs up (a process killed in that task
//! excepted); bytes whose record can't be written aren't kept, and
@@ -70,44 +87,97 @@
//! the start. Close: from the moment it begins, a call on that book is
//! refused at its door, unrun, and not in its journal; a request not
//! yet whole when the grace runs out is cut (INVARIANT 15); a call
//! already running on it, on any route, finishes (nothing is killed, nothing
//! is half-done); the answers on their way out are sent, for the
//! answer grace at most; its MCP sessions end; its last backup is
//! made, for BACKUP_AT_CLOSE at most; and the book is let go
//! (INVARIANT 13), its writer lock released, so another process could
//! open it; and only then is a close answered. It is answered
//! `closed`, or `closed_backup_incomplete` with why when its last
//! backup wasn't whole (a target that failed, git that failed, a
//! backup stopped after its time): never a plain `closed` for a backup
//! that wasn't made. After that answer no call on that book runs until
//! it is opened again. Every other book keeps serving, and a call on
//! it is never held up by this one's close. A restore over an open
//! book lets go of it the same way (but for its last backup), its
//! door shut and the book listed closed from the start: a call that
//! comes while the restore runs is told the books aren't open (503,
//! INVARIANT 11), never that there are no such books.
//! The close is bounded, from its start, by the sum of these named,
//! finite parts and nothing else:
//! a. T_calls: the longest of the calls already running with their
//! whole body (none is cut or killed; each is local work on the
//! book, and nothing a client does lengthens it);
//! already running on it, on any route, either finishes (an ordinary
//! call: nothing is killed, nothing is half-done) or, if it is one of
//! the stoppable calls below, is stopped at its next look; the answers
//! on their way out are sent, for the answer grace at most; its MCP
//! sessions end; its last backup is made, for BACKUP_AT_CLOSE at most;
//! and the book is let go (INVARIANT 13), its writer lock released, so
//! another process could open it; and only then is a close answered.
//! It is answered `closed`, or `closed_backup_incomplete` with why when
//! its last backup wasn't whole (a target that failed, git that
//! failed, a backup stopped after its time): never a plain `closed`
//! for a backup that wasn't made. After that answer no call on that
//! book runs until it is opened again. Every other book keeps serving,
//! and a call on it is never held up by this one's close. A restore
//! over an open book lets go of it the same way (but for its last
//! backup), its door shut and the book listed closed from the start: a
//! call that comes while the restore runs is told the books aren't
//! open (503, INVARIANT 11), never that there are no such books.
//!
//! What can run long, and what stops it. A close calls `hurry` at its
//! start, before it waits for anything. The calls and jobs that can do
//! long I/O or loop over a book's whole journal or files are exactly
//! these, and each is stoppable:
//! - on the book: `books.back_up_now`, and a backup a timer asked for
//! (git is sent SIGTERM and killed only after TERM_GRACE: ledger_
//! store backup INVARIANT 5; between targets the flag is looked at
//! too); `books.verify` (once per journal line replayed and per
//! stored file hashed); `books.export_cpa_package` (before it
//! builds, and once per stored file it reads); a drill; and a
//! format upgrade not yet journaled. A call stopped this way
//! answers its caller that it was stopped because the books are
//! closing, its access record says `refused: stopped_by_close`, and
//! nothing it was doing is recorded as done: a stopped backup
//! records `stopped` and no push or commit outcome for the step it
//! didn't finish (a commit made before it stands in the archive, and
//! 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
//! 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
//! success (safe: the books are in this version's format, proven
//! backed up first), and finishes (a line and a database row).
//! - on the admin socket, which hold the one lifecycle lock: restore
//! and its preview, adopt and its preview, create, and open. A
//! close of any book, and the server's close, stops them (a job
//! that starts while a close is under way is refused, and asked
//! again after it). Each is stopped, before its point of no return,
//! at its next look (a phase, a stored file, a journal line, a git
//! command): what it wrote is removed (a clone, a staging folder),
//! and the root is byte for byte as it was. The point of no return
//! of restore and adopt is the rename that puts the books in place;
//! after it they finish, which is a rename or two and the sync of
//! two folders (a restore over books moves them to `legacy/` and
//! renames the copy in, both within the root); then the book is
//! opened, which is itself stopped, 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).
//! 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, one report or export over the ledger that is
//! already in memory (local CPU, no wait on a client, a disk of
//! another's or the network). A call that is neither stoppable nor
//! bounded by one request's size is a defect to be listed here:
//! `books.import_bank_csv` is one (a file of up to MAX_UPLOAD is
//! rehearsed whole, then written row by row, each row journaled: long
//! for a very large file, and it isn't stopped by a close).
//! 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;
//! b. ANSWER_GRACE for the answers on their way out, counted from
//! when the door is empty (the cut of a body not yet whole is at
//! ANSWER_GRACE from the START of the close, inside (a): a
//! stalled client adds nothing);
//! c. T_stop for each step the close doesn't wait for, a drill or a
//! format upgrade not yet journaled, which are hurried at the
//! start (`Backups::hurry`) and stop at their next look: one git
//! kill (GROUP_GONE_WAIT, 2 s, and its pipes, 10 s at most, and
//! for a target on this computer LOCK_SETTLE, 1.5 s), or one
//! journal line, one file or one 64 KiB chunk, and the removal
//! of the step's scratch clone (as long as the clone is big);
//! a format upgrade whose `journal.format_set` line has been
//! appended is not stopped, it finishes (a line and a database
//! row: part of (a));
//! c. T_stop: the longest between two looks of what is stopped, one
//! of: a git command's stop (SIGTERM and up to TERM_GRACE, 5 s;
//! then a kill and GROUP_GONE_WAIT, 2 s, and its pipes, 10 s at
//! most), one journal line, one stored file, one 64 KiB chunk, one
//! phase of a job; and the removal of what a stopped job or drill
//! wrote (its scratch clone or staging folder: a local deletion of
//! the job's own output, as long as that is large, waiting on no
//! one);
//! d. BACKUP_AT_CLOSE for the last backup;
//! e. T_stop again for what is left of that backup at its bound
//! (`Backups::shut`: git killed, every step awaited);
//! (`Backups::shut`: git stopped, every step awaited);
//! f. closing the logs and letting go of the store (instant).
//! A drill (or a format upgrade) that took the backups' turn never
//! costs the last backup its time.
@@ -218,12 +288,25 @@
//! made, and the close is answered within INVARIANT 10's bound. A
//! format upgrade not yet journaled is stopped the same way, the books
//! unchanged.
//! 11. A backup's git is killed inside a commit or a push: the locks it
//! left are removed before the close is answered, each recorded; the
//! book opened again backs up at once.
//! 11. A backup's git is stopped inside a commit or a push: it is sent
//! SIGTERM and removes its own locks (nothing is left, nothing is
//! recorded), the book opened again backs up at once. A git that can't
//! end on SIGTERM and has to be killed after TERM_GRACE leaves locks
//! that this process removes from the book's own archive only, and
//! leaves in the owner's backup folder, recorded with their whole path
//! and said in the close's answer and in the backup's status, until the
//! owner removes them.
//! 12. The server is closed (standard input ends) with an upload stalled
//! on one book and a call's body stalled on another: both are cut one
//! grace after the close began, the server exits 0 within its bound.
//! 13. A backup asked for (`books.back_up_now`) is running, git stalled,
//! and the book is closed: the call is answered, git still stalled,
//! that it was stopped because the books are closing; its record says
//! `refused: stopped_by_close`; the close is answered `closed`.
//! 14. A restore of a large backup is running (an admin job) when another
//! book is closed: the restore is stopped, answers that it was stopped
//! because the books are closing, and the root is byte for byte as it
//! was; asked again it goes through.
//! ```
use crate::admin::{self, Request, Response};
@@ -244,6 +327,12 @@ use std::time::{Duration, Instant};
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
/// What a restore or adoption that a close stopped after its point of no
/// return says of the books it put in place (INVARIANT 10).
const STOPPED_AFTER_PLACED: &str = "they are in place, but were not opened: the books server is closing. Open them when it runs again";
/// Why a book's opening was stopped (by a close, INVARIANT 10): the book is
/// intact and stays closed.
const OPEN_STOPPED: &str = "stopped because the books are closing: they were not opened";
/// The server's MCP socket, in the root's `run/`.
pub const MCP_SOCKET: &str = "mcp.sock";
/// The server's admin socket, in the root's `run/`.
@@ -676,6 +765,13 @@ struct Books {
/// Held through every change to which books are open or exist (create,
/// adopt, restore, open, close): one at a time (INVARIANT 10).
lifecycle: Mutex<()>,
/// Set while any close of a book is under way, and for good once the
/// server closes: the admin jobs that can run long (restore, create,
/// adopt, open) look at it and stop, before their point of no return,
/// leaving the books as they were (INVARIANT 10). `closers` counts the
/// closes under way; the flag is clear when none is.
job_stop: Arc<std::sync::atomic::AtomicBool>,
closers: Mutex<usize>,
/// How these books are kept from agents (plan 3.8, P9a): what
/// `books.start` reports (`--isolation`).
isolation: Isolation,
@@ -683,6 +779,21 @@ struct Books {
timers: Timers,
}
/// A close of a book under way (`Books::closing_one`).
struct CloseGuard<'a>(&'a Books);
impl Drop for CloseGuard<'_> {
fn drop(&mut self) {
let mut closers = self.0.closers.lock().unwrap_or_else(|e| e.into_inner());
*closers -= 1;
if *closers == 0 && !self.0.closing.is_cancelled() {
self.0
.job_stop
.store(false, std::sync::atomic::Ordering::SeqCst);
}
}
}
impl Books {
/// A server's books for `root`, none held yet.
fn new(
@@ -705,6 +816,8 @@ impl Books {
backup_quiet,
drill_first,
lifecycle: Mutex::new(()),
job_stop: Arc::default(),
closers: Mutex::new(0),
isolation,
timers: Timers::default(),
}
@@ -716,6 +829,51 @@ impl Books {
self
}
/// A close of a book begins: the admin jobs that can run long stop
/// (INVARIANT 10) until the returned guard is dropped.
fn closing_one(&self) -> CloseGuard<'_> {
let mut closers = self.closers.lock().unwrap_or_else(|e| e.into_inner());
*closers += 1;
self.job_stop
.store(true, std::sync::atomic::Ordering::SeqCst);
CloseGuard(self)
}
/// What an admin job that can run long is asked as it goes whether to
/// stop (ledger_store::root `JobStop`). With the test knob
/// `--timer-hold` a job is held inside a phase named `job:phase` (in
/// `run/timer-hold`) until the name is gone or a stop is asked.
fn job(&self, job: &'static str) -> ledger_store::root::JobStop {
let stop = ledger_store::root::JobStop::new(self.job_stop.clone());
if !self.timers.timer_hold {
return stop;
}
let Ok(run) = self.root.run_dir() else {
return stop;
};
let flag = self.job_stop.clone();
stop.with_phase_watch(Arc::new(move |phase: &str| {
let name = format!("{job}:{phase}");
{
use std::io::Write;
if let Ok(mut said) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(run.join("timer-held"))
{
let _ = writeln!(said, "{name}");
}
}
let held = || {
std::fs::read_to_string(run.join("timer-hold"))
.is_ok_and(|names| names.split(',').any(|n| n.trim() == name))
};
while held() && !flag.load(std::sync::atomic::Ordering::SeqCst) {
std::thread::sleep(Duration::from_millis(10));
}
}))
}
/// The test knob `--timer-hold`: `timer` has taken the handles of a
/// book and is about to act on them. It says so (a line in
/// `run/timer-held`) and waits until `run/timer-hold` is gone, so a
@@ -823,6 +981,18 @@ impl Books {
}
}
/// [`Self::open`] for an admin job that can be stopped: the store's
/// replay and verification look at the stop, and a book whose opening
/// was stopped is closed, not failed (it is intact: it opens when asked).
fn open_stoppable(&self, id: &BookId, stop: &ledger_store::root::JobStop) -> Book {
let _scope = ledger_store::cancel::scope(stop.flag());
let book = self.open(id);
match &book {
Book::Failed(why) if why == OPEN_STOPPED => Book::Closed,
_ => book,
}
}
/// Open the book `id` from disk: served, or failed with why.
fn open(&self, id: &BookId) -> Book {
let opened = match Store::open(&self.root.book_dir(id)) {
@@ -830,6 +1000,7 @@ impl Books {
Err(ledger_store::StoreError::Locked(_)) => {
Err("another program has these books open".to_string())
}
Err(ledger_store::StoreError::Cancelled) => Err(OPEN_STOPPED.to_string()),
Err(e) => Err(self.hide(e.to_string())),
};
opened.unwrap_or_else(|why| {
@@ -840,9 +1011,10 @@ impl Books {
/// Verify an open store and build its service (INVARIANTS 3, 4).
fn serve(&self, mut store: Store) -> Result<Book, String> {
let report = store
.verify_and_heal()
.map_err(|e| format!("they don't verify: {}", self.hide(e.to_string())))?;
let report = store.verify_and_heal().map_err(|e| match e {
ledger_store::StoreError::Cancelled => OPEN_STOPPED.to_string(),
e => format!("they don't verify: {}", self.hide(e.to_string())),
})?;
if let Some(why) = &report.healed {
eprintln!(
"wanderbooks server: rebuilt a database from its journal ({})",
@@ -876,6 +1048,34 @@ impl Books {
..
} = served;
backups.slow_steps(self.timers.slow_steps);
// The test knob `--timer-hold`: a call a close can stop is held as
// it begins, named `call:<tool>` in `run/timer-hold`, until the
// name is gone or the close begins.
if self.timers.timer_hold
&& let Ok(run) = self.root.run_dir()
{
let flag = shared.hurry_flag();
backups.set_hold(Arc::new(move |call: &str| {
let name = format!("call:{call}");
{
use std::io::Write;
if let Ok(mut said) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(run.join("timer-held"))
{
let _ = writeln!(said, "{name}");
}
}
let held = || {
std::fs::read_to_string(run.join("timer-hold"))
.is_ok_and(|names| names.split(',').any(|n| n.trim() == name))
};
while held() && !flag.load(std::sync::atomic::Ordering::SeqCst) {
std::thread::sleep(Duration::from_millis(10));
}
}));
}
Ok(Book::Open {
gate: Arc::default(),
ended,
@@ -1023,7 +1223,12 @@ impl Books {
if self.held().contains_key(id.as_str()) {
return refused(RootError::Exists(id.to_string()));
}
match self.root.create_book(&id, currency) {
// Stopped by a close before its folder is made, it makes
// nothing; after that it makes one empty book (INVARIANT 10).
match self
.root
.create_book_stoppable(&id, currency, &self.job("create"))
{
Ok(store) => {
// Made: kept whether or not it opens (INVARIANT 3).
let book = self.serve(store).unwrap_or_else(Book::Failed);
@@ -1132,7 +1337,8 @@ impl Books {
if self.held().contains_key(id.as_str()) {
return refused(RootError::Exists(id.to_string()));
}
let found = match self.root.adopt_preview(&source) {
let stop = self.job("adopt");
let found = match self.root.adopt_preview_stoppable(&source, &stop) {
Ok(found) => found,
Err(e) => return refused(e),
};
@@ -1225,11 +1431,14 @@ impl Books {
vault_key,
expect_head,
};
match self.root.adopt(&source, &id, &options) {
match self.root.adopt_stoppable(&source, &id, &options, &stop) {
Ok(r) => {
// Adopted: kept whether or not it opens.
let book = self.open(&id);
let problem = book.problem();
// Adopted: kept whether or not it opens (not opened,
// if a close began: it is in place all the same).
let book = self.open_stoppable(&id, &stop);
let problem = book.problem().or_else(|| {
matches!(book, Book::Closed).then(|| STOPPED_AFTER_PLACED.to_string())
});
self.hold(&id, book);
Response::Adopted(admin::Adopted {
id: r.id.to_string(),
@@ -1355,7 +1564,16 @@ impl Books {
Err(e) => return Response::Refused(self.hide(e.to_string())),
},
}
let book = self.open(&id);
// Stopped by a close (INVARIANT 10): the book stays as it was.
let stop = self.job("open");
if stop.look("start") {
return said(admin::OpenOutcome::CouldNotOpen(OPEN_STOPPED.into()));
}
let book = self.open_stoppable(&id, &stop);
if matches!(book, Book::Closed) {
self.hold(&id, book);
return said(admin::OpenOutcome::CouldNotOpen(OPEN_STOPPED.into()));
}
let problem = book.problem();
self.hold(&id, book);
said(match problem {
@@ -1380,6 +1598,9 @@ impl Books {
id: id.to_string(),
outcome,
};
// From now the admin jobs that can run long stop (INVARIANT 10), so
// the lifecycle lock is not held for long by one of them.
let _closing = self.closing_one();
let _one = self.lifecycle.lock().unwrap_or_else(|e| e.into_inner());
if self.closing.is_cancelled() {
return Response::Refused("the books are closing: nothing was done".into());
@@ -1498,11 +1719,19 @@ impl Books {
};
// A run still going is stopped, and waited for: nothing of the
// backups runs once this returns.
backups.shut().await;
let left = backups.shut().await;
access.close();
uploads.close();
exports.close();
store.let_go().await;
// A git stopped at its bound that left locks in the owner's folder:
// said with the file, as the standing says it (ledger_store backup
// INVARIANT 5b), not only that the backup took too long.
let problem = match (problem, left.is_empty()) {
(problem, true) => problem,
(None, false) => Some(left.join("; ")),
(Some(why), false) => Some(format!("{why}; {}", left.join("; "))),
};
problem.map(|why| self.hide(why))
}
@@ -1616,6 +1845,7 @@ impl Books {
Err(e) => return said(e.to_string()),
};
let _one = self.lifecycle.lock().unwrap_or_else(|e| e.into_inner());
let stop = self.job("restore");
let git = match ledger_store::backup::Git::find() {
Ok(git) => git,
Err(e) => return said(e.to_string()),
@@ -1624,7 +1854,10 @@ impl Books {
// what it says): the restore itself is refused over books, or
// replacing none.
if !confirmed {
return match self.root.restore_preview(&git, &source, &id) {
return match self
.root
.restore_preview_stoppable(&git, &source, &id, &stop)
{
Ok(p) => Response::RestorePreview(admin::RestorePreview {
head: p.head,
blobs: p.blobs,
@@ -1638,6 +1871,10 @@ impl Books {
let Some(expect_head) = expect_head else {
return said("a restore is confirmed against the preview's head: preview first".into());
};
// Stopped by a close before anything is let go (INVARIANT 10).
if stop.look("begin") {
return said("stopped because the books are closing: nothing was restored".into());
}
let held = self.held().contains_key(id.as_str());
if replace && !held {
return said(format!(
@@ -1672,12 +1909,19 @@ impl Books {
self.hold(&id, Book::Closed);
rt.block_on(self.release(&id, &parts, false, Instant::now(), None));
}
match self.root.restore(&git, &source, &id, &expect_head, replace) {
match self
.root
.restore_stoppable(&git, &source, &id, &expect_head, replace, &stop)
{
Ok(r) => {
// Restored: kept whether or not it opens; its backups told
// whose books these were (backup.rs INVARIANTS 6, 7).
let book = self.open(&id);
let problem = book.problem();
// whose books these were (backup.rs INVARIANTS 6, 7). Past its
// point of no return a stop doesn't undo it: the books are
// in place, and not opened if the server is closing.
let book = self.open_stoppable(&id, &stop);
let problem = book.problem().or_else(|| {
matches!(book, Book::Closed).then(|| STOPPED_AFTER_PLACED.to_string())
});
self.hold(&id, book);
Response::Restored(admin::Restored {
id: r.id.to_string(),
@@ -1693,7 +1937,7 @@ impl Books {
// The books it would have replaced, let go above, open
// again (only this restore runs, so nothing else holds them).
if replace {
let book = self.open(&id);
let book = self.open_stoppable(&id, &stop);
self.hold(&id, book);
}
said(e.to_string())
@@ -3158,6 +3402,12 @@ async fn serve(
// a stalled client may not do is hold the close, whatever else the
// close is waiting for (an admin job, a slow backup of another book).
books.closing.cancel();
// The admin jobs that can run long stop at their next look, before
// their point of no return (INVARIANT 10): the wait below is for jobs
// that are stopping, not for a restore to run its course.
books
.job_stop
.store(true, std::sync::atomic::Ordering::SeqCst);
let begun = Instant::now();
let cutters: Vec<_> = books
.gates()
@@ -4806,6 +5056,8 @@ mod tests {
let (status, code, _) = at_the_door(&books, "acme", &acme).await.unwrap();
assert_eq!((status, code.as_deref()), (503, Some("closed")));
assert_eq!(at_the_door(&books, "beta", &beta).await, None);
// A negative window: it can only fail if the close was answered,
// never because the machine was slow.
tokio::time::sleep(Duration::from_millis(300)).await;
assert!(!closing.is_finished(), "closed with a request still inside");
drop(inside);
+47 -1
View File
@@ -213,6 +213,11 @@ pub struct SharedStore {
stopped: std::sync::atomic::AtomicBool,
/// Closing: no new request runs (INVARIANT 3).
closing: std::sync::atomic::AtomicBool,
/// A close of these books has begun (`hurry`): a call that can run
/// long (a verification, a backup asked for, a package of every stored
/// file) stops at its next look, answering that it was stopped. Shared
/// with the books' backups (backup.rs), whose git it stops.
hurry: Arc<std::sync::atomic::AtomicBool>,
/// Requests running (from before their blocking task to its end).
running: std::sync::atomic::AtomicUsize,
/// Woken whenever one ends.
@@ -310,6 +315,7 @@ impl SharedStore {
store: tokio::sync::Mutex::new(Some(store)),
stopped: std::sync::atomic::AtomicBool::new(false),
closing: std::sync::atomic::AtomicBool::new(false),
hurry: Arc::default(),
running: std::sync::atomic::AtomicUsize::new(0),
ended: tokio::sync::Notify::new(),
})
@@ -334,6 +340,23 @@ impl SharedStore {
self.closing.load(std::sync::atomic::Ordering::SeqCst)
}
/// A close of these books begins: every call and job that can run long
/// stops at its next look (local.rs INVARIANT 10).
pub fn hurry(&self) {
self.hurry.store(true, std::sync::atomic::Ordering::SeqCst);
}
/// Whether a close of these books has begun.
pub fn hurried(&self) -> bool {
self.hurry.load(std::sync::atomic::Ordering::SeqCst)
}
/// The stop flag itself, for what looks at it from another thread or
/// hands it to git (ledger_store `cancel`, `Git::with_cancel`).
pub fn hurry_flag(&self) -> Arc<std::sync::atomic::AtomicBool> {
self.hurry.clone()
}
fn stopped(&self) -> bool {
self.stopped.load(std::sync::atomic::Ordering::SeqCst)
}
@@ -357,6 +380,18 @@ impl SharedStore {
/// What every request gets after an internal error (SharedStore
/// INVARIANT 2).
/// What a call that a close stopped is told (local.rs INVARIANT 10): it
/// was stopped, because the books are closing, and nothing it was doing
/// is recorded as done.
pub(crate) const STOPPED_BY_CLOSE_WORDS: &str = "this call was stopped because the books are closing: nothing it was doing is recorded as done. Open the books again, then ask again";
/// The words of a call a close stopped, and the mark that its access record
/// says so (`refused: stopped_by_close`): returned as the call's error.
pub(crate) fn stopped_by_close() -> String {
STOPPED_BY_CLOSE.with(|s| s.set(true));
STOPPED_BY_CLOSE_WORDS.to_string()
}
pub(crate) const STOPPED: &str = "the books server stopped taking requests after an internal error, to protect the books: ask the human to restart the books server (the books are checked again when it starts)";
/// The store, locked for one stretch of synchronous work. Not `Send`, so
@@ -1385,6 +1420,9 @@ thread_local! {
/// The journal's head after the last write made by the request
/// running on this thread (StoreGuard's drop), for its access record.
static WROTE: std::cell::RefCell<Option<(u64, String)>> = const { std::cell::RefCell::new(None) };
/// Whether the request running on this thread was stopped by a close
/// (`stopped_by_close`), for its access record.
static STOPPED_BY_CLOSE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Who the request running on this thread is, as `books.start` shows
/// it: `{principal, kind, scopes, client_id}`. The token's own facts
/// and the client's name; set at the start of the request.
@@ -1843,6 +1881,7 @@ impl ServerHandler for BooksServer {
let result = run_blocking(&self.store, move || {
Box::pin(async move {
WROTE.with(|w| w.borrow_mut().take());
STOPPED_BY_CLOSE.with(|s| s.set(false));
ARGS.with(|a| *a.borrow_mut() = request.arguments.clone());
let caller = running_call
.caller()
@@ -1895,7 +1934,14 @@ impl ServerHandler for BooksServer {
let mut c = running_call;
c.digested(digest);
c.with_agent(AGENT_NOTE.with(|a| a.borrow_mut().take()));
let recorded = c.record_blocking(outcome_of(&out), wrote);
// A call a close stopped is on record as stopped, not as an
// answer it gave (local.rs INVARIANT 10).
let outcome = if STOPPED_BY_CLOSE.with(|s| s.replace(false)) {
Outcome::Refused(access::STOPPED_BY_CLOSE.into())
} else {
outcome_of(&out)
};
let recorded = c.record_blocking(outcome, wrote);
(out, recorded)
})
})
+10 -6
View File
@@ -111,11 +111,15 @@ impl BooksServer {
&self,
params: Parameters<BackUpNowParams>,
) -> Result<Json<BackupOut>, String> {
Ok(Json(
self.backups
.run_with("asked", params.0.new_disk)
.await?
.into(),
))
// Stopped by a close (backup.rs INVARIANT 11): said so, and on
// record as stopped, not as an answer it gave.
match self.backups.run_with("asked", params.0.new_disk).await {
Ok(status) => Ok(Json(status.into())),
Err(why) if why.starts_with(crate::server::STOPPED_BY_CLOSE_WORDS) => {
crate::server::stopped_by_close();
Err(why)
}
Err(why) => Err(why),
}
}
}
+32 -4
View File
@@ -266,6 +266,16 @@ fn cash_flow_csv(stmt: &ledger_core::CashFlowStatement) -> String {
csv
}
/// A store error as a call's answer: one that is a close's stop is said so,
/// and marks the call's access record (server.rs `stopped_by_close`).
fn stoppable(e: ledger_store::StoreError) -> String {
if matches!(e, ledger_store::StoreError::Cancelled) {
crate::server::stopped_by_close()
} else {
e.to_string()
}
}
#[tool_router(router = reports_router, vis = "pub(super)")]
impl BooksServer {
#[tool(
@@ -707,10 +717,16 @@ impl BooksServer {
)
)]
async fn verify(&self, params: Parameters<VerifyParams>) -> Result<Json<VerifyOut>, String> {
self.backups.hold("books.verify");
let mut store = self.lock()?;
let report = store.verify_and_heal().map_err(|e| e.to_string())?;
// The replay and the hashing of every stored file are looked at
// once per journal line and per file: a close stops them
// (local.rs INVARIANT 10). Healing a drifted database is begun only
// if no stop was asked for before it, and then finishes.
let _stop = ledger_store::cancel::scope(self.store.hurry_flag());
let report = store.verify_and_heal().map_err(stoppable)?;
let blobs = if params.0.blobs {
Some(store.verify_blobs().map_err(|e| e.to_string())?)
Some(store.verify_blobs().map_err(stoppable)?)
} else {
None
};
@@ -1144,6 +1160,7 @@ impl BooksServer {
) -> Result<Json<ExportCpaPackageOut>, String> {
let p = params.0;
let as_of = self.as_of(p.as_of.as_deref())?;
self.backups.hold("books.export_cpa_package");
let mut store = self.lock()?;
// A package no counted audit stands behind is not final either
// (plan P8, D-9): on books that declared `audits`, refused under
@@ -1251,7 +1268,10 @@ impl BooksServer {
.as_ref()
.map(|vault| move |id| vault_tin(ledger, vault, id));
// Built from the books under the lock, written nowhere
// (ledger_package INVARIANT 1).
// (ledger_package INVARIANT 1). Every stored file it holds is read
// one at a time, and a close stops it between two (local.rs
// INVARIANT 10).
let _stop = ledger_store::cancel::scope(self.store.hurry_flag());
let package = ledger_package::build_package(
&*store,
&package_settings(&self.settings()),
@@ -1264,7 +1284,15 @@ impl BooksServer {
include_receipts: p.include_receipts,
tins: tins.as_ref().map(|f| f as ledger_package::TinSource<'_>),
},
)?;
)
.map_err(|e| {
if e == ledger_store::StoreError::Cancelled.to_string() {
crate::server::stopped_by_close()
} else {
e
}
})?;
drop(_stop);
let vault_dir = if p.include_tins {
self.tin_record_dir(&store)?
} else {
+6
View File
@@ -126,6 +126,8 @@ pub fn build_package<B: PackageBooks + ?Sized>(
req: &PackageRequest<'_>,
) -> Result<Package, String> {
use ledger_import::{XlsxReport, report, report_to_xlsx, statement_pdf};
// A stop asked for before any of the work (the books server's close).
ledger_store::cancel::check().map_err(|e| e.to_string())?;
let company = settings.company;
let (as_of, today) = (req.as_of, req.prepared_on);
let meta = report_meta(company, req.prepared_on, books.journal_seq());
@@ -490,6 +492,10 @@ pub fn build_package<B: PackageBooks + ?Sized>(
};
let mut index = String::from("entry_id,date,description,amount,file,sha256\n");
for a in books.all_attachments().map_err(|e| e.to_string())? {
// A stop asked for (the books server's close) is looked at once
// per stored file read: a package of many files isn't held to
// its end by it (ledger_store::cancel).
ledger_store::cancel::check().map_err(|e| e.to_string())?;
if a.withdrawn_at.is_some() {
continue;
}
+19 -9
View File
@@ -55,7 +55,7 @@
//! stopped gently: SIGTERM to its whole process group first (git
//! removes the lock files it holds when it is sent one, and a push's
//! receiving end the objects it had not yet kept), up to TERM_GRACE
//! (3 s: git's handler takes milliseconds, so the grace is only for a
//! (5 s: git's handler takes milliseconds, so the grace is only for a
//! machine too loaded to schedule it) for the group to end, and only
//! then SIGKILL. So a lock left behind is the rare case, and there is
//! nothing to clean up in the usual one. (Windows has no signal to
@@ -138,9 +138,11 @@ pub const BACKED_UP: [&str; 5] = [
pub const GIT_TIMEOUT: Duration = Duration::from_secs(300);
/// How long a git that is to be stopped is given, after SIGTERM, to end
/// (and so remove its own lock files) before its whole process group is
/// killed (INVARIANT 5). Git's handler takes milliseconds; this is for a
/// machine so loaded that the handler is slow to be scheduled.
pub const TERM_GRACE: Duration = Duration::from_secs(3);
/// killed (INVARIANT 5). Git's handler takes milliseconds; the grace is for
/// a machine so loaded that the handler is slow to be scheduled. It is
/// generous on purpose: a lock left in the owner's folder costs the owner a
/// step by hand, while a longer grace costs only a git that ignores SIGTERM.
pub const TERM_GRACE: Duration = Duration::from_secs(5);
/// How old a lock in the book's own archive must be, at open and when a
/// backup begins, before it is taken for a dead git's (INVARIANT 5a): a
/// younger one is left, and the next backup tries again.
@@ -749,7 +751,10 @@ impl Watched {
fn open(&self) -> std::io::Result<crate::git_locks::RepoDir> {
if self.is_archive() {
match (self.dir.parent(), self.dir.file_name().and_then(|n| n.to_str())) {
match (
self.dir.parent(),
self.dir.file_name().and_then(|n| n.to_str()),
) {
(Some(book), Some(name)) => crate::git_locks::RepoDir::open_in(book, name),
_ => Err(std::io::ErrorKind::InvalidInput.into()),
}
@@ -2937,7 +2942,10 @@ mod tests {
assert!(Path::new(path).exists(), "{path}");
}
let words = said.to_string();
assert!(words.contains("nothing else is using the backup folder"), "{words}");
assert!(
words.contains("nothing else is using the backup folder"),
"{words}"
);
assert!(!words.contains("another.lock"), "{words}");
// Left where it was, and the one before our push untouched.
assert!(lock.exists(), "a file in the owner's folder was deleted");
@@ -2946,15 +2954,17 @@ mod tests {
assert!(
notes.iter().all(|n| n.repo == "folder"
&& !n.removed
&& n.path.as_deref()
== Some(repo.join(&n.lock).display().to_string().as_str())),
&& n.path.as_deref() == Some(repo.join(&n.lock).display().to_string().as_str())),
"{notes:?}"
);
assert!(
notes.iter().any(|n| n.lock == "refs/heads/main.lock"),
"{notes:?}"
);
assert!(!notes.iter().any(|n| n.lock.contains("another")), "{notes:?}");
assert!(
!notes.iter().any(|n| n.lock.contains("another")),
"{notes:?}"
);
// Still there, a later push fails by git's own words, and the file
// stays.
std::fs::remove_file(hooks.join("slow")).unwrap();
+14
View File
@@ -22,6 +22,10 @@
//! 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).
//! 4. A step that can't be left half-made is shielded (`shielded`): the
//! 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.
//! ```
use crate::error::StoreError;
@@ -49,6 +53,16 @@ pub fn scope(flag: Arc<AtomicBool>) -> Scope {
Scope(FLAG.with(|f| f.borrow_mut().replace(flag)))
}
/// Run `f` with no stop in force on this thread (the request in force
/// before comes back after): for the one step that can't be left half-made,
/// such as rebuilding the database from the journal, which would leave the
/// live ledger part replayed.
pub fn shielded<R>(f: impl FnOnce() -> R) -> R {
let outer = FLAG.with(|flag| flag.borrow_mut().take());
let _restore = Scope(outer);
f()
}
/// Whether a stop was asked for.
pub fn requested() -> bool {
FLAG.with(|f| {
+28 -4
View File
@@ -327,17 +327,41 @@ mod tests {
let (x, id) = (x.clone(), e.id.clone());
std::thread::spawn(move || x.get(&id, "t", NOW))
};
// The fetch holds the lock, blocked opening the pipe for reading
// (no writer yet): give it time to be there, then close.
std::thread::sleep(std::time::Duration::from_millis(300));
// The fetch holds the lock, blocked opening the pipe for reading (no
// writer yet). A writer can be opened without blocking only once a
// reader has the pipe open, so that is the condition waited for (the
// writer, kept, is the one that lets the read end later).
use std::os::unix::fs::OpenOptionsExt;
let by = std::time::Instant::now() + std::time::Duration::from_secs(60);
let writer = loop {
match std::fs::OpenOptions::new()
.write(true)
.custom_flags(libc::O_NONBLOCK)
.open(&bin)
{
Ok(w) => break w,
Err(_) => {
assert!(
std::time::Instant::now() < by,
"the fetch never reached the pipe"
);
std::thread::sleep(std::time::Duration::from_millis(5));
}
}
};
let (begun, started) = std::sync::mpsc::channel();
let (done, closed) = std::sync::mpsc::channel();
let closing = {
let x = x.clone();
std::thread::spawn(move || {
let _ = begun.send(());
x.close();
let _ = done.send(());
})
};
started.recv().unwrap();
// A negative window: it can only fail if the close returned, never
// because the machine was slow.
assert!(
closed
.recv_timeout(std::time::Duration::from_millis(500))
@@ -346,7 +370,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(writer);
assert!(fetching.join().unwrap().is_err());
closed
.recv_timeout(std::time::Duration::from_secs(5))
+3 -10
View File
@@ -376,9 +376,7 @@ mod imp {
pub fn regular(&self, rel: &str) -> Option<Option<SystemTime>> {
let path = self.at(rel).ok()?;
let meta = std::fs::symlink_metadata(path).ok()?;
meta.file_type()
.is_file()
.then(|| meta.modified().ok())
meta.file_type().is_file().then(|| meta.modified().ok())
}
pub fn refs(&self, out: &mut Vec<Found>, depth: usize) {
@@ -414,9 +412,7 @@ mod imp {
return Ok(false);
};
match std::fs::symlink_metadata(&path) {
Ok(meta) if meta.file_type().is_file() => {
std::fs::remove_file(path).map(|()| true)
}
Ok(meta) if meta.file_type().is_file() => std::fs::remove_file(path).map(|()| true),
_ => Ok(false),
}
}
@@ -548,10 +544,7 @@ mod tests {
b"theirs",
"the link's target was touched"
);
assert_eq!(
std::fs::read(outside.join("HEAD.lock")).unwrap(),
b"theirs"
);
assert_eq!(std::fs::read(outside.join("HEAD.lock")).unwrap(), b"theirs");
// And a repository that is a link when the handle is opened is
// refused, with the archive's own `open_in` too.
assert!(RepoDir::open(&second).is_err());
+262 -51
View File
@@ -116,6 +116,10 @@ pub enum RootError {
/// Adopting was refused, with why.
#[error("{0}")]
Adopt(String),
/// A job was stopped because the books are closing, before its point of
/// no return ([`JobStop`]): nothing it did is left.
#[error("{0}")]
Stopped(String),
/// The store refused (its message with the root's path taken out).
#[error("{0}")]
Store(String, #[source] StoreError),
@@ -146,6 +150,87 @@ impl From<std::io::Error> for RootError {
}
}
/// What a job that changes which books the root holds (create, adopt,
/// restore) is asked, as it goes, whether it must stop (the books server's
/// close): looked at as each phase begins and once per stored file copied;
/// a job stops, removes what it made, and leaves the books exactly as they
/// were. Each job has a point of no return (the rename that puts its books
/// in place), after which nothing is asked and the job finishes: a few
/// renames and directory syncs, so short and bounded.
#[derive(Clone)]
pub struct JobStop {
flag: std::sync::Arc<std::sync::atomic::AtomicBool>,
phase: Option<JobPhaseWatch>,
}
/// What is told the name of each phase of a job as it begins
/// ([`JobStop::with_phase_watch`]).
pub type JobPhaseWatch = std::sync::Arc<dyn Fn(&str) + Send + Sync>;
impl JobStop {
/// Stop when `flag` is set.
pub fn new(flag: std::sync::Arc<std::sync::atomic::AtomicBool>) -> Self {
Self { flag, phase: None }
}
/// Never asked to stop (a command run on its own, not in the server).
pub fn never() -> Self {
Self::new(std::sync::Arc::default())
}
/// Told the name of each phase as it begins, before the stop is looked
/// at (a seam for tests, and the server's test knob that holds a job
/// inside a phase: it may wait, but must give up when the flag is set).
#[must_use]
pub fn with_phase_watch(mut self, watch: JobPhaseWatch) -> Self {
self.phase = Some(watch);
self
}
/// The flag: what git and the store's loops are handed to look at.
pub fn flag(&self) -> std::sync::Arc<std::sync::atomic::AtomicBool> {
self.flag.clone()
}
/// Whether a stop was asked for.
pub fn requested(&self) -> bool {
self.flag.load(std::sync::atomic::Ordering::SeqCst)
}
/// A phase begins, for a caller that decides for itself what to do about
/// a stop: whether one was asked for (the phase watch is told first).
pub fn look(&self, phase: &str) -> bool {
if let Some(watch) = &self.phase {
watch(phase);
}
self.requested()
}
/// A phase begins: Ok, or `Stopped` (naming what was not done).
fn at(&self, phase: &str, undone: &str) -> Result<(), RootError> {
if let Some(watch) = &self.phase {
watch(phase);
}
if self.requested() {
Err(RootError::Stopped(format!(
"stopped because the books are closing: nothing was {undone}"
)))
} else {
Ok(())
}
}
/// A stop that reached the store's own loops or git, said as a job's.
fn said(&self, e: RootError, undone: &str) -> RootError {
match e {
RootError::Store(_, StoreError::Cancelled) => RootError::Stopped(format!(
"stopped because the books are closing: nothing was {undone}"
)),
other => other,
}
}
}
/// A book's id within the root: its folder name under `books/`.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BookId(String);
@@ -748,17 +833,35 @@ impl Root {
/// Start new, empty books called `id` in `base_currency`. Refused if
/// books of that id exist. Returns the open store.
pub fn create_book(&self, id: &BookId, base_currency: Currency) -> Result<Store, RootError> {
self.create_book_inner(id, base_currency)
self.create_book_stoppable(id, base_currency, &JobStop::never())
}
/// [`Self::create_book`], stopped if `stop` asks before its folder is
/// made (its point of no return); after that it makes one empty book,
/// the same few files and syncs whatever else is in the root.
pub fn create_book_stoppable(
&self,
id: &BookId,
base_currency: Currency,
stop: &JobStop,
) -> Result<Store, RootError> {
self.create_book_inner(id, base_currency, stop)
.map_err(|e| self.hide(e))
}
fn create_book_inner(&self, id: &BookId, base_currency: Currency) -> Result<Store, RootError> {
fn create_book_inner(
&self,
id: &BookId,
base_currency: Currency,
stop: &JobStop,
) -> Result<Store, RootError> {
let _lock = self.books_lock()?;
let (books, _) = self.private_subdir(BOOKS_DIR, false)?;
let dir = books.join(id.as_str());
if std::fs::symlink_metadata(&dir).is_ok() {
return Err(RootError::Exists(id.to_string()));
}
stop.at("start", "created")?;
make_private_dir(&dir)?;
match Store::create(&dir, base_currency) {
Ok(store) => {
@@ -793,7 +896,21 @@ impl Root {
id: &BookId,
options: &AdoptOptions,
) -> Result<AdoptReport, RootError> {
self.adopt_inner(source, id, options)
self.adopt_stoppable(source, id, options, &JobStop::never())
}
/// [`Self::adopt`], stopped if `stop` asks at any phase before the
/// rename that puts the books in place (its point of no return): the
/// staging folder is removed and the root is as it was. After the
/// rename it finishes, which is a directory sync.
pub fn adopt_stoppable(
&self,
source: &Path,
id: &BookId,
options: &AdoptOptions,
stop: &JobStop,
) -> Result<AdoptReport, RootError> {
self.adopt_inner(source, id, options, stop)
.map_err(|e| self.hide(e))
}
@@ -802,6 +919,7 @@ impl Root {
source: &Path,
id: &BookId,
options: &AdoptOptions,
stop: &JobStop,
) -> Result<AdoptReport, RootError> {
let _lock = self.books_lock()?;
let (books, _) = self.private_subdir(BOOKS_DIR, false)?;
@@ -809,6 +927,7 @@ impl Root {
if std::fs::symlink_metadata(&dest).is_ok() {
return Err(RootError::Exists(id.to_string()));
}
stop.at("start", "adopted")?;
let source = self.adoptable(source)?;
for (what, path) in [
("vault folder", &options.vault_dir),
@@ -825,8 +944,12 @@ impl Root {
// Step 1: the source's writer lock, held to the end, so nothing
// writes it while it is copied.
let (_source_lock, source_lock_created) = lock_source(&source)?;
// Step 2: verify the chain and record the head.
let (raw, lines) = read_source_journal(&source)?;
// Step 2: verify the chain and record the head. (The chain's check
// looks at the stop once per journal line.)
let scope = crate::cancel::scope(stop.flag());
let (raw, lines) = read_source_journal(&source).map_err(|e| stop.said(e, "adopted"))?;
drop(scope);
stop.at("journal", "adopted")?;
let head = head_of(&lines);
if let Some(expected) = &options.expect_head
&& *expected != head
@@ -859,11 +982,19 @@ impl Root {
}
let staging = books.join(format!("{STAGING_PREFIX}{id}-{}", std::process::id()));
make_private_dir(&staging)?;
// The store's own loops (opening, verifying) look at the stop too.
let scope = crate::cancel::scope(stop.flag());
let built = (|| -> Result<AdoptReport, RootError> {
stop.at("copy", "adopted")?;
// Step 3: the journal as read, then every stored file.
write_private_file(&staging.join(JOURNAL_FILE), &raw)?;
let blob_dir = crate::store::BLOBS_DIR;
let copied = copy_blobs(&source.join(blob_dir), &staging.join(blob_dir))?;
let copied = copy_blobs(
&source.join(blob_dir),
&staging.join(blob_dir),
stop,
"adopted",
)?;
// Step 5: the vault's records and the v1 key.
let vault_files = match &options.vault_dir {
Some(dir) => copy_flat_private(dir, &staging.join(VAULT_DIR))?,
@@ -879,6 +1010,7 @@ impl Root {
}
None => false,
};
stop.at("open", "adopted")?;
let mut store = Store::open(&staging)?;
if store.head() != head {
return Err(RootError::Adopt(format!(
@@ -899,6 +1031,7 @@ impl Root {
.join(", ")
)));
}
stop.at("verify", "adopted")?;
store.verify_and_heal()?;
let blobs_verified = store.verify_blobs()?;
// The copy is new books of this version, in its journal format
@@ -936,11 +1069,16 @@ impl Root {
format_upgraded,
})
})();
let renamed = built.and_then(|report| {
std::fs::rename(&staging, &dest)?;
sync_dir(&books)?;
Ok(report)
});
drop(scope);
let renamed = built
.map_err(|e| stop.said(e, "adopted"))
.and_then(|report| {
// The last look: from the rename on, the job finishes.
stop.at("place", "adopted")?;
std::fs::rename(&staging, &dest)?;
sync_dir(&books)?;
Ok(report)
});
if renamed.is_err() {
let _ = std::fs::remove_dir_all(&staging);
}
@@ -991,7 +1129,11 @@ impl Root {
source: &str,
books: &Path,
id: &BookId,
stop: &JobStop,
) -> Result<(PathBuf, crate::backup::Verified), RootError> {
stop.at("fetch", "restored")?;
// git, and the verification's own phases and loops, look at the stop.
let git = git.clone().with_cancel(stop.flag());
// Anything left from one that never finished goes first: none is
// in progress (each holds the books lock).
for entry in std::fs::read_dir(books)? {
@@ -1005,13 +1147,18 @@ impl Root {
}
}
let scratch = books.join(format!("{RESTORE_PREFIX}{id}-{}", std::process::id()));
match crate::backup::verify(git, source, &scratch) {
match crate::backup::verify(&git, source, &scratch) {
Ok(v) => Ok((scratch, v)),
Err(e) => {
// What the verification wrote goes with it (a stop leaves the
// root as it was).
let _ = std::fs::remove_dir_all(&scratch);
Err(RootError::Adopt(format!(
"that backup can't be restored: {e}"
)))
Err(match e {
crate::backup::BackupError::Cancelled(_) => RootError::Stopped(
"stopped because the books are closing: nothing was restored".into(),
),
e => RootError::Adopt(format!("that backup can't be restored: {e}")),
})
}
}
}
@@ -1024,10 +1171,23 @@ impl Root {
source: &str,
id: &BookId,
) -> Result<RestorePreview, RootError> {
self.restore_preview_stoppable(git, source, id, &JobStop::never())
}
/// [`Self::restore_preview`], stopped if `stop` asks: the clone is
/// removed and nothing is left.
pub fn restore_preview_stoppable(
&self,
git: &crate::backup::Git,
source: &str,
id: &BookId,
stop: &JobStop,
) -> Result<RestorePreview, RootError> {
let _scope = crate::cancel::scope(stop.flag());
(|| {
let _lock = self.books_lock()?;
let (books, _) = self.private_subdir(BOOKS_DIR, false)?;
let (scratch, v) = self.fetch_backup(git, source, &books, id)?;
let (scratch, v) = self.fetch_backup(git, source, &books, id, stop)?;
let vault = scratch.join(VAULT_DIR);
let vault_files = if vault.is_dir() {
std::fs::read_dir(&vault)
@@ -1063,7 +1223,24 @@ impl Root {
expect_head: &(u64, String),
replace: bool,
) -> Result<RestoreReport, RootError> {
self.restore_inner(git, source, id, expect_head, replace)
self.restore_stoppable(git, source, id, expect_head, replace, &JobStop::never())
}
/// [`Self::restore`], stopped if `stop` asks at any phase before the
/// renames that put the books in place (its point of no return): the
/// clone and the staging folder are removed and the root is as it was,
/// books that were to be replaced untouched. From the first rename on it
/// finishes: two renames and two directory syncs.
pub fn restore_stoppable(
&self,
git: &crate::backup::Git,
source: &str,
id: &BookId,
expect_head: &(u64, String),
replace: bool,
stop: &JobStop,
) -> Result<RestoreReport, RootError> {
self.restore_inner(git, source, id, expect_head, replace, stop)
.map_err(|e| match e {
// The copy's checks are the adoption's: said as a restore.
RootError::Adopt(text) => {
@@ -1081,6 +1258,7 @@ impl Root {
id: &BookId,
expect_head: &(u64, String),
replace: bool,
stop: &JobStop,
) -> Result<RestoreReport, RootError> {
let _lock = self.books_lock()?;
let (books, _) = self.private_subdir(BOOKS_DIR, false)?;
@@ -1106,9 +1284,12 @@ impl Root {
} else {
None
};
let (scratch, v) = self.fetch_backup(git, source, &books, id)?;
stop.at("start", "restored")?;
let _scope = crate::cancel::scope(stop.flag());
let (scratch, v) = self.fetch_backup(git, source, &books, id, stop)?;
let staging = books.join(format!("{RESTORE_PREFIX}{id}-{}-book", std::process::id()));
let built = (|| -> Result<RestoreReport, RootError> {
stop.at("copy", "restored")?;
if v.head != *expect_head {
return Err(RootError::Adopt(format!(
"that backup isn't the one previewed (it is now at event {}): nothing was restored; preview it again",
@@ -1124,7 +1305,12 @@ impl Root {
make_private_dir(&staging)?;
write_private_file(&staging.join(JOURNAL_FILE), &raw)?;
let blob_dir = crate::store::BLOBS_DIR;
let copied = copy_blobs(&scratch.join(blob_dir), &staging.join(blob_dir))?;
let copied = copy_blobs(
&scratch.join(blob_dir),
&staging.join(blob_dir),
stop,
"restored",
)?;
let vault_files = if scratch.join(VAULT_DIR).is_dir() {
copy_flat_private(&scratch.join(VAULT_DIR), &staging.join(VAULT_DIR))?
} else {
@@ -1151,6 +1337,7 @@ impl Root {
&crate::ops::ops_dir(&staging).join(RESTORED_FROM),
v.book.as_deref().unwrap_or("").as_bytes(),
)?;
stop.at("open", "restored")?;
let mut store = Store::open(&staging)?;
if store.head() != v.head {
return Err(RootError::Adopt(format!(
@@ -1165,6 +1352,7 @@ impl Root {
"the backup lacks stored files its books name: nothing was restored".into(),
));
}
stop.at("verify", "restored")?;
store.verify_and_heal()?;
let blobs_verified = store.verify_blobs()?;
let head = store.head();
@@ -1180,38 +1368,42 @@ impl Root {
})
})();
let _ = std::fs::remove_dir_all(&scratch);
let placed = built.and_then(|mut report| {
if exists {
let (legacy, _) = self.private_subdir(LEGACY_DIR, false)?;
let stamp = chrono::Utc::now().format("%Y%m%d-%H%M%S");
let mut name = format!("{id}-{stamp}");
let mut n = 1;
while std::fs::symlink_metadata(legacy.join(&name)).is_ok() {
n += 1;
name = format!("{id}-{stamp}-{n}");
}
std::fs::rename(&dest, legacy.join(&name))?;
if let Err(e) = std::fs::rename(&staging, &dest) {
// The books it would replace go back where they were.
if std::fs::rename(legacy.join(&name), &dest).is_err() {
return Err(RootError::Adopt(format!(
"the backup couldn't be put in place ({}), and the books it would \
replace are in the legacy folder as {name}: nothing was restored",
e.kind()
)));
let placed = built
.map_err(|e| stop.said(e, "restored"))
.and_then(|mut report| {
// The last look: from the first rename on, the job finishes.
stop.at("place", "restored")?;
if exists {
let (legacy, _) = self.private_subdir(LEGACY_DIR, false)?;
let stamp = chrono::Utc::now().format("%Y%m%d-%H%M%S");
let mut name = format!("{id}-{stamp}");
let mut n = 1;
while std::fs::symlink_metadata(legacy.join(&name)).is_ok() {
n += 1;
name = format!("{id}-{stamp}-{n}");
}
return Err(e.into());
std::fs::rename(&dest, legacy.join(&name))?;
if let Err(e) = std::fs::rename(&staging, &dest) {
// The books it would replace go back where they were.
if std::fs::rename(legacy.join(&name), &dest).is_err() {
return Err(RootError::Adopt(format!(
"the backup couldn't be put in place ({}), and the books it would \
replace are in the legacy folder as {name}: nothing was restored",
e.kind()
)));
}
return Err(e.into());
}
// In place: a folder that won't sync now is said no more
// than any later write's would be.
let _ = sync_dir(&legacy);
report.replaced = Some(name);
} else {
std::fs::rename(&staging, &dest)?;
}
// In place: a folder that won't sync now is said no more
// than any later write's would be.
let _ = sync_dir(&legacy);
report.replaced = Some(name);
} else {
std::fs::rename(&staging, &dest)?;
}
let _ = sync_dir(&books);
Ok(report)
});
let _ = sync_dir(&books);
Ok(report)
});
if placed.is_err() {
let _ = std::fs::remove_dir_all(&staging);
}
@@ -1242,7 +1434,19 @@ impl Root {
/// checks [`Self::adopt`] makes, writing nothing (not even a lock
/// file). The adoption itself reads it all again under the lock.
pub fn adopt_preview(&self, source: &Path) -> Result<SourcePreview, RootError> {
self.adopt_preview_stoppable(source, &JobStop::never())
}
/// [`Self::adopt_preview`], stopped if `stop` asks (the read of the
/// source's journal looks once per line).
pub fn adopt_preview_stoppable(
&self,
source: &Path,
stop: &JobStop,
) -> Result<SourcePreview, RootError> {
let _scope = crate::cancel::scope(stop.flag());
(|| {
stop.at("preview", "read")?;
let source = self.adoptable(source)?;
// Held for writing now: adoption would be refused, so is this.
if let Ok(lock) = std::fs::File::open(source.join(crate::store::LOCK_FILE))
@@ -1254,7 +1458,7 @@ impl Root {
.into(),
)));
}
let (_, lines) = read_source_journal(&source)?;
let (_, lines) = read_source_journal(&source).map_err(|e| stop.said(e, "read"))?;
Ok(SourcePreview {
head: head_of(&lines),
currency: crate::store::journal_currency(&lines)?,
@@ -2183,7 +2387,12 @@ struct CopiedBlobs {
/// its name; an unfinished write (`<sha>.tmp`, a put that never finished)
/// is left behind and counted; anything else (a link, a stray file) is
/// refused. Folders 0700, files 0600, every folder synced.
fn copy_blobs(from: &Path, to: &Path) -> Result<CopiedBlobs, RootError> {
fn copy_blobs(
from: &Path,
to: &Path,
stop: &JobStop,
undone: &str,
) -> Result<CopiedBlobs, RootError> {
use sha2::{Digest, Sha256};
let mut copied = CopiedBlobs {
shas: BTreeSet::new(),
@@ -2251,6 +2460,8 @@ fn copy_blobs(from: &Path, to: &Path) -> Result<CopiedBlobs, RootError> {
}
return Err(stray(&f.path()));
}
// Once per stored file (one read, one hash, one write).
stop.at("file", undone)?;
let bytes = std::fs::read(f.path())?;
if hex::encode(Sha256::digest(&bytes)) != name.to_lowercase() {
return Err(RootError::Adopt(format!(
+8 -2
View File
@@ -6390,8 +6390,14 @@ impl Store {
"wanderbooks: {why}; kept the old database as {} beside it and rebuilt from the journal",
keep.file_name().unwrap_or_default().to_string_lossy()
);
self.rebuild()?;
self.verify()?;
// 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(e) => return Err(e),
+142
View File
@@ -1734,3 +1734,145 @@ fn a_registry_rewritten_or_a_vault_given_unchecked_is_refused() {
}
assert!(p.vault.is_dir() && p.key.is_file());
}
/// A stop that is asked at `phase` (and the phases a job has asked, in
/// order): the job's own look at its phases, raised from the watcher.
fn stopping_at(
phase: &'static str,
) -> (
ledger_store::root::JobStop,
std::sync::Arc<std::sync::Mutex<Vec<String>>>,
) {
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
let flag = Arc::new(AtomicBool::new(false));
let seen = Arc::new(Mutex::new(Vec::<String>::new()));
let stop = ledger_store::root::JobStop::new(flag.clone()).with_phase_watch({
let (flag, seen) = (flag.clone(), seen.clone());
Arc::new(move |p: &str| {
seen.lock().unwrap().push(p.to_string());
if p == phase {
flag.store(true, Ordering::SeqCst);
}
})
});
(stop, seen)
}
/// What a job leaves of the root, byte for byte.
fn root_files(root: &Root) -> Vec<(PathBuf, Vec<u8>)> {
let mut out = snapshot_files(&root.path().join("books"));
if root.path().join("legacy").exists() {
out.extend(snapshot_files(&root.path().join("legacy")));
}
out
}
/// A job that changes which books the root holds (create, adopt, restore) is
/// asked at each of its phases whether it must stop (the books server's
/// close), and stopped at any of them leaves the root byte for byte as it
/// was: the staging and scratch folders are gone, books it would have
/// replaced untouched, `legacy/` as it was. The last phase it asks is the
/// look before its point of no return (the renames that put the books in
/// place): nothing is asked after, so a stop that comes then is not heeded
/// and the job finishes.
#[test]
fn a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_it_was() {
use ledger_store::root::JobStop;
let home = tmp("job-stop");
let (root, _) = Root::setup(home.path(), None, None).unwrap();
// create
let before = root_files(&root);
let (stop, seen) = stopping_at("start");
let e = refused(
root.create_book_stoppable(&id("new"), Currency::USD, &stop)
.map(|_| ()),
);
assert!(matches!(e, RootError::Stopped(_)), "{e:?}");
assert!(e.to_string().contains("nothing was created"), "{e}");
assert_eq!(root_files(&root), before);
assert!(root.list_books().unwrap().is_empty());
assert!(!root.book_dir(&id("new")).exists(), "its folder was made");
assert_eq!(*seen.lock().unwrap(), ["start"]);
// adopt
let old = tmp("job-stop-old");
drop(source_books(old.path(), true));
let options = AdoptOptions::default();
let phases = [
"start", "journal", "copy", "file", "open", "verify", "place",
];
for phase in phases {
let before = root_files(&root);
let (stop, seen) = stopping_at(phase);
let e = refused(root.adopt_stoppable(old.path(), &id("adopted"), &options, &stop));
assert!(matches!(e, RootError::Stopped(_)), "{phase}: {e:?}");
assert!(
e.to_string().contains("nothing was adopted"),
"{phase}: {e}"
);
assert_eq!(root_files(&root), before, "adopt stopped at {phase}");
assert!(root.list_books().unwrap().is_empty(), "{phase}");
assert_eq!(seen.lock().unwrap().last().map(String::as_str), Some(phase));
}
// Never stopped: every phase is asked, in this order, `place` the last.
let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let stop = JobStop::new(flag).with_phase_watch({
let seen = seen.clone();
std::sync::Arc::new(move |p: &str| seen.lock().unwrap().push(p.to_string()))
});
root.adopt_stoppable(old.path(), &id("adopted"), &options, &stop)
.unwrap();
let asked = seen.lock().unwrap().clone();
let mut distinct = asked.clone();
distinct.dedup();
assert_eq!(distinct, phases, "{asked:?}");
assert_eq!(asked.last().map(String::as_str), Some("place"), "{asked:?}");
// restore, over books that exist: they stay as they are.
let dir = root.book_dir(&id("adopted"));
let store = Store::open(&dir).unwrap();
let source = backed_up(home.path(), &dir, &store).expect("git is installed");
drop(store);
let git = ledger_store::backup::Git::find().unwrap();
let preview = root.restore_preview(&git, &source, &id("adopted")).unwrap();
let phases = ["start", "fetch", "copy", "file", "open", "verify", "place"];
for phase in phases {
let before = root_files(&root);
let (stop, seen) = stopping_at(phase);
let e = refused(root.restore_stoppable(
&git,
&source,
&id("adopted"),
&preview.head,
true,
&stop,
));
assert!(matches!(e, RootError::Stopped(_)), "{phase}: {e:?}");
assert!(
e.to_string().contains("nothing was restored"),
"{phase}: {e}"
);
assert_eq!(root_files(&root), before, "restore stopped at {phase}");
assert_eq!(seen.lock().unwrap().last().map(String::as_str), Some(phase));
}
// The preview too: stopped, nothing left of its clone.
let before = root_files(&root);
let (stop, _) = stopping_at("fetch");
let e = refused(root.restore_preview_stoppable(&git, &source, &id("adopted"), &stop));
assert!(matches!(e, RootError::Stopped(_)), "{e:?}");
assert_eq!(root_files(&root), before);
// Never stopped, a restore asks `place` last and goes through.
let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
let stop = JobStop::new(std::sync::Arc::default()).with_phase_watch({
let seen = seen.clone();
std::sync::Arc::new(move |p: &str| seen.lock().unwrap().push(p.to_string()))
});
let r = root
.restore_stoppable(&git, &source, &id("adopted"), &preview.head, true, &stop)
.unwrap();
assert!(r.replaced.is_some());
assert_eq!(
seen.lock().unwrap().last().map(String::as_str),
Some("place")
);
}
+39 -6
View File
@@ -359,7 +359,8 @@ didn't open, with why). Protocol version 1: the requests are new, the
why), `was_not_open` or `no_such_book`.
In this order: new calls on the book are refused (the door is shut and
the book listed closed); the calls running on it finish, on every route
(nothing is killed, nothing is half-done); the answers on their way out
(an ordinary call: nothing is killed, nothing is half-done; the calls
that can run long are stopped instead, see below); the answers on their way out
are sent, for 10 seconds at most (a client that never reads its answer
doesn't hold the book open); a request whose body has not been read
to its end when that time runs out (counted from the start of the
@@ -374,11 +375,43 @@ didn't open, with why). Protocol version 1: the requests are new, the
(a drill, or a format upgrade not yet journaled, is stopped when the
close begins, at its next look, so it never takes the last backup's
turn; its scratch clone is removed and the books are unchanged):
a backup still running after that is stopped (git is killed with all it
started, and any lock file it left, in the book's archive and in a
folder target on this computer, is removed and recorded in
`ops/backup.jsonl` as `lock_removed`; a lock that was there before the
push began is never touched, `lock_left`) and waited for to end;
a backup still running after that is stopped (git is sent SIGTERM, which
makes it remove its own lock files, and killed with all it started only
if it hasn't ended after 5 seconds) and waited for to end. The program
never writes to or deletes from a backup folder (it is the owner's, and
may be shared with other computers or a sync program): a lock git left
there when it had to be killed is left in place, recorded in
`ops/backup.jsonl` as `lock_left` with its whole path, and the target's
backup is marked failed with words naming the file and saying to remove
it only when nothing else is using the backup folder (`books.backup`
and the close's answer say the same; the next backup that finds the
lock gone goes on). In the book's own archive (`archive.git`, private to
the program; running git by hand inside it is unsupported) it removes
only the locks its own stopped git made, and, at open and when a backup
begins, locks older than ten minutes, each recorded `lock_removed`;
**What a close stops, and what it waits for.** At its start a close
stops the calls and jobs that can do long I/O or loop over a book's
whole journal or files, each at its next look: `books.back_up_now` and
a backup a timer asked for (git is stopped; the call answers that it was
stopped because the books are closing, its access record says
`refused: stopped_by_close`, and nothing it was doing is recorded as done;
a commit it had made stands), `books.verify` (once per journal line and
per stored file; a heal of a drifted database is begun only if no stop
was asked before it, then finishes), `books.export_cpa_package` (once per
stored file), a drill, and a format upgrade not yet at its final look (a
stop is honoured up to that look; one that arrives after it still
upgrades and records success). On the admin socket, restore (and its
preview), adopt (and its preview), create and open are stopped by a close
of any book, and by the server's own: before their point of no return
(the rename that puts the books in place; create's making of its folder)
they remove what they wrote and leave the root byte for byte as it was
and answer that they were stopped because the books are closing; after
it they finish (a rename or two and two directory syncs), and the book
is then opened unless that, too, is stopped (it is left closed, and the
answer says so). Every other call does work bounded by the size of one
request and is waited for; `books.import_bank_csv` is the one known
exception (a file of up to 25 MiB is rehearsed whole and then written row
by row, each row journaled: long for a very large file, and not stopped);
the close is bounded by the sum written in the server's INVARIANT 10
(`local.rs`: running calls, the grace, the answers' grace, the stop of a
hurried step, the last backup's 60 s, the stop of what is left of it);
+8 -1
View File
@@ -33,7 +33,14 @@ easily backupable, journable":
ahead, the commit under the store's lock) and pushes it to the
owner's private repository and backup folder, versioned and
deduplicated, with full history (docs/mcp-interface.md, "Tools —
backups").
backups"). The program stops its git gently (SIGTERM first, so git
removes its own lock files, and a kill only after 5 seconds), and never
writes to or deletes from a backup folder, which is the owner's (shared,
perhaps, with another computer or a sync program): a lock git left
there after a kill is reported with its path, never removed. The book's
own archive (`archive.git`) is private to the program; there it removes
only the locks its own stopped git made, and locks older than ten
minutes found when the books open or a backup begins.
- **Journable.** It literally is a journal: `{seq, ts, type, payload, prev}`.
Greppable, diffable, replayable. The audit trail isn't a feature bolted
on — it's the storage format.
+27 -3
View File
@@ -4326,12 +4326,17 @@ one book never refuses or holds up a call on another.
| `book_open_close::the_servers_own_close_cuts_stalled_requests_and_exits_zero_in_time` | one upload stalled on one book and one MCP body stalled on another, the server's stdin closed: exit code 0 within the bound, both cut after the grace, no part file, nothing journaled, two `cut_by_close` records, every log whole |
| `book_open_close::a_backup_and_a_sweep_that_took_their_handles_before_a_close_do_nothing_after_it`, `…a_drill_and_a_sweep…` | `--timer-hold` holds a timer between taking a book's handles and acting; the book is closed meanwhile, stray files planted, the timers go on: the closed book's tree doesn't move; opened again the sweep works (fail with the handles' closed state, the gate's check and the backups' shut flag removed) |
| `book_open_close::a_close_stops_a_slow_drill_instead_of_waiting_for_it` | `--slow-steps` makes each phase of a drill wait a minute: the close answers plain `closed` (the last backup was made), within the stated sum, with the drill's scratch clone removed (fails without `hurry`: `closed_backup_incomplete`) |
| `book_open_close::a_close_that_stops_git_in_a_commit_or_a_push_leaves_no_lock_and_the_next_backup_succeeds` | REAL git (a wrapper that points git's hooks at a `reference-transaction` hook that waits) killed inside `init`, a commit and a push to a folder by a close: no lock left in the archive or the folder before the close is answered, each recorded, the reopened book backs up with no step by hand, `git fsck --strict` passes on both |
| `book_open_close::a_close_that_stops_git_in_a_commit_or_a_push_leaves_no_lock_and_the_next_backup_succeeds` | REAL git (a wrapper that points git's hooks at a `reference-transaction` hook that waits) stopped inside `init`, a commit and a push to a folder by a close: git is sent SIGTERM and removes its own locks, so none is left in the archive or the folder and the backup's record holds no `lock_removed` or `lock_left` (nothing for the server to clean up), the reopened book backs up with no step by hand, `git fsck --strict` passes on both |
| `local::tests::a_close_stops_a_format_upgrade_before_it_is_journaled` | an upgrade held in its backup's proof: the close stops it, it says nothing was upgraded, the journal is byte for byte as before |
| `local::tests::a_body_read_to_its_end_is_never_cut_and_one_not_yet_is` | the line of the cut: a body read to its end is never cut (the cut firing, the body asked again), one not read to its end is cut even with bytes on the way |
| `ledger-store` `backup::tests::a_git_killed_mid_commit_…`, `…_mid_add_…`, `…_mid_push_…`, `locks_found_in_the_archive_when_the_books_open_…` | real git killed inside a commit (HEAD and ref locks), an add (the index lock) and a push to a folder (the target's ref lock): locks removed once the group is gone, noted; a lock that was in the target before the push is never removed, and the target's lock is removed only after LOCK_SETTLE; next backup succeeds, `git fsck` passes; the archive's locks are cleared at open |
| `ledger-store` `backup::tests::a_git_stopped_by_sigterm_mid_commit_…`, `…_stopped_mid_add_…`, `a_push_stopped_by_sigterm_…`, `a_git_that_ignores_sigterm_…`, `a_git_that_cannot_end_on_sigterm_…`, `a_lock_left_in_a_folder_target_…`, `a_push_stopped_during_the_pack_transfer_…`, `the_archives_age_rule_at_open`, `removal_after_a_stop_goes_through_the_handle_…`, `git_locks::tests` (3) | REAL git stopped inside a commit (HEAD and ref locks), an add (the index lock) and a push to a folder (the target's ref lock): on SIGTERM it removes its own locks and nothing is noted (the grace is long, so a git that needed the kill would show); a git whose group is frozen (SIGSTOP, so SIGTERM stays pending) is killed only after the grace, and the archive's locks it left (not there when the command began) are removed, noted; the folder target's lock is NEVER removed, reported with its whole path (`LockLeft`, `lock_left` with `path`), a lock that was there before the push is untouched and not named, a later push fails by git's words and removes nothing, the next one passes once the test removes the file; a fake git that traps SIGTERM is sent it first (marker) and killed after the grace with all it started; a 48 MiB pack held in the receiving end's `pre-receive` hook (the target's `incoming-` quarantine present) stopped by SIGTERM and by the kill, `git fsck --strict` on both repositories at once; the archive's locks at open: older than ten minutes removed and noted, younger left and said, non-lock names, folders and links untouched; a swapped `refs` folder or archive path after the handle was opened touches nothing outside; the handle module: exact lock names only, regular files only, no link followed |
| `ledger-store` `backup::tests::a_drill_stops_inside_the_phase_it_is_told_to_stop_in` | for each phase (clone, replay, verify, blobs, prefix) a stop set as the phase begins ends the drill inside it (the observer sees no later phase), scratch removed; each case fails when the loop's looks inside that phase are removed |
| `book_open_close::a_running_call_is_never_cut_when_the_grace_runs_out` | `books.back_up_now` held in a stalled `git` past the grace (body whole) is not cut: it finishes, is answered and recorded `ok`, and then the close is answered |
| `book_open_close::a_running_call_is_never_cut_when_the_grace_runs_out` | an ordinary call (`books.attach_receipt`, held inside its read of its file, a named pipe) past the grace (body whole) is not cut: it finishes when fed, is answered and recorded `ok`, and then the close is answered (a backup asked for is no longer this call: it is stoppable) |
| `book_open_close::a_close_stops_a_running_backup_call_and_says_so` | `books.back_up_now` held in a stalled `git` (never lifted until the call answers): the close stops it, the call is answered that it was stopped because the books are closing, its access record is `refused: stopped_by_close` with no head, the backup record holds `stopped` and no result of its own for the run, git and all it started are gone, the close's last backup is made and the close answers `closed` |
| `book_open_close::a_close_stops_a_running_verification_and_a_running_package_and_says_so` | `books.verify` and `books.export_cpa_package` held as they begin by `--timer-hold` (`call:...`), which the close releases: each is stopped at its first look, answers it was stopped, is recorded `refused: stopped_by_close`, the journal is unchanged |
| `book_open_close::a_close_stops_a_running_restore_adopt_create_and_open_leaving_the_root_as_it_was` | each admin job held inside a phase (`restore:copy`, `adopt:open`, `create:start`, `open:start`): its scratch or staging folder is there while held; a close of another book stops it, it answers it was stopped, the root's `books/` and `legacy/` are byte for byte as before; asked again it goes through |
| `ledger-store` `tests/root.rs::a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_it_was` | create, adopt, restore (over existing books) and the restore preview stopped at each phase they ask: `Stopped`, the root (`books/`, `legacy/`) byte for byte as before; never stopped, `place` is the last phase asked (nothing after the point of no return) |
| `book_open_close::a_lock_a_kill_leaves_in_the_backup_folder_is_reported_and_never_removed_by_the_server` | REAL git in a push to a folder with its group frozen, so only the kill after the grace ends it: the lock it leaves is still there after the close, recorded `lock_left` with its whole path, no `lock_removed` for the folder, the close's answer and `books.backup` name the file and say when it may be removed, a lock that was there before is neither touched nor named, a later backup fails by git's words and removes nothing, and once the file is removed the backup goes on, `git fsck --strict` on both |
| `book_open_close::a_call_whose_answer_was_never_read_is_on_record_as_having_run` | a journaled draft whose client goes without reading: after the close the access log has its record, outcome `ok`, with the head it wrote (INVARIANT 14: a retry isn't made safe by anything; the record says it ran) |
| `book_open_close::a_close_is_not_answered_while_its_backup_still_runs` | a book with a folder target and a stand-in `git` on the server's PATH that waits: the close isn't answered before its backup bound (1.2 s), then answers `closed_backup_incomplete`, git and all it started are gone, and lifting the stall makes nothing resume; the reopened book's backup record is a whole chain and it backs up (fails when `shut` is removed: git still runs after the answer) |
| `book_open_close::a_close_whose_backup_fails_says_so_and_leaves_nothing_running` | a target whose disk isn't there: `closed_backup_incomplete` naming the failure, quickly, no git run afterwards; the same book with its disk back is answered plainly `closed` |
@@ -4341,6 +4346,25 @@ one book never refuses or holds up a call on another.
| `book_open_close::the_timers_never_touch_a_closed_book` | `--timers 5` (sweep, backup look, drill look every 5 ms) on a book with a backup target, closed and opened 8 times: while closed, with strays planted for a sweep to take, not one file moves; open, it is backed up and drilled; the logs end as whole chains |
| `commands::tests::doctor_says_who_is_connected` | the doctor's lines for sessions |
**Waiting on conditions, not on guesses (review of 2026-11-20).** A test of
this branch that slept for a fixed time to let "the other side get there"
now waits on the condition: `exports::tests::a_close_waits_for_a_fetch_that_is_reading`
(it slept 300 ms assuming its thread had reached the named pipe; it now
opens a non-blocking writer on the pipe, which succeeds only once a reader
has it open); the two MCP bodies that stop half way
(`a_stalled_mcp_body_cannot_hold_a_close_…`, the server's-own-close test, the
second of which slept 200 ms and the first nothing at all) send their head
with `Expect: 100-continue` and their body only on the server's `100
Continue`, which the server sends when its handler first reads the body,
inside the book's door (`raw::Raw::start_inside`); the late-timer test no
longer sleeps 300 ms before its 800 ms window in which nothing may move;
`a_close_whose_backup_fails_…` waits out the backup the opening makes by
asking for one itself (it could be stopped by the close and leave a lock). The
sleeps that remain are negative windows (a close must NOT have been answered;
nothing must move), which can only fail when the property is broken, never
because the machine is slow, and pacing of a stimulus (the hammer's jitter,
a client trickling an upload on purpose).
**For P12 (mutation targets).** `Gate::enter` (count before looking at `shut`),
`Books::release`'s order (the store's close, the gate emptied, sessions ended, the last backup, `Backups::shut`, the logs and files closed, `let_go`) and `Backups::begin`'s count-before-flag, `Backups::shut` (the flag, the turn, the steps drained, the record closed), `ChainLog::close`, `refused_at_door` taking the request's place into its task, the sweep taking the gate, `door`'s entering
before it touches the book, and the gate's riding in the upload and