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

+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 {