fix(store,mcp): a type claims only what it does alone, and a restore never says 'no such books'

ledger-store: a file coming in (Uploads::receive) now writes each chunk under
the lock a close takes and stops at the first chunk after a close, removing
its part; an export fetch (Exports::get) reads under that lock, so a close
waits for it. The INVARIANTS say exactly this: after close() returns no byte
is written or kept and none is read for a caller; the one thing a request
begun before the close does after it is remove the part file only it made;
a request still waiting for its next bytes is not woken by the type (the
books server's gate waits for it and cuts one that never finishes).

ledger-mcp: a restore over an open book took the book out of the list
before it shut the door, so every call while the restore waited for what was
inside got 404 'no such books' for a book that exists. The door is shut
first and the book listed closed: such a call gets the closed refusal (503,
the words), as in a close. The drain test now requires 503 throughout.
(A refusal at a shut door is not written to the access log, as in a close:
INVARIANT 11.)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Sonnet 5.5 committed 2026-11-20 12:22:19 -07:00
1 parent ce636adbb5
commit ca6f5aa982
6 files changed
+211 -21

No files matched your search

+22 -7
View File
@@ -1592,27 +1592,42 @@ fn a_restore_over_an_open_book_waits_for_what_is_inside_it() {
.unwrap()
}
});
// The books being replaced are no longer served as these.
// A call for the books being replaced is told they aren't open (503,
// the words, the closed header), as in a close; never that there are
// no such books (404), which they would be told if they were taken
// out of the list while the restore waits (INVARIANT 10).
let late_call = || {
let mut late = Wire::with_token(&home, A, Some(w.token().unwrap().to_string()));
late.send(&json!({"jsonrpc": "2.0", "id": 1, "method": "ping"}));
late.refused.clone().map(|r| (r.status, r.body))
};
wait_for(
"the replaced books are let go",
Duration::from_secs(30),
|| {
let mut late = Wire::with_token(&home, A, Some(w.token().unwrap().to_string()));
late.send(&json!({"jsonrpc": "2.0", "id": 1, "method": "ping"}));
late.refused
.as_ref()
.is_some_and(|r| r.status == 404 || r.status == 503)
|| match late_call() {
Some((404, body)) => panic!("books being restored were `no such books`: {body}"),
Some((503, body)) => {
assert_eq!(body, closed_words(A));
true
}
_ => false,
},
);
// The restore (a clone and a check of the backup, which take a second
// or so) is not answered while the upload is half received: watched
// for five seconds, in which a restore that doesn't wait would finish.
// Every call meanwhile gets the same answer.
let watched = std::time::Instant::now() + Duration::from_secs(5);
while std::time::Instant::now() < watched {
assert!(
!restoring.is_finished(),
"the restore was answered with an upload half received"
);
assert_eq!(
late_call(),
Some((503, closed_words(A))),
"a call while the books were being restored"
);
std::thread::sleep(Duration::from_millis(20));
}
raw.finish(&bytes[bytes.len() / 2..]);
+11 -6
View File
@@ -82,7 +82,10 @@
//! 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).
//! 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.
//! 11. A call for a book that exists but is closed is told apart from one
//! that does not exist, on the MCP, upload, download and export
//! routes: 503, `x-wanderbooks-refused: closed`, and the words `The
@@ -1556,17 +1559,19 @@ impl Books {
// file gone), their sessions ended, their backups stopped and
// waited for (none of theirs reaches a target after the backup is
// read), their logs and files closed, their writer lock released.
// The door is shut first and the book listed closed (never taken
// out of the list: a call that comes while the restore runs is
// told the books aren't open, as in a close, never that there are
// no such books).
let old = if replace {
self.held
.write()
.unwrap_or_else(|e| e.into_inner())
.remove(id.as_str())
self.held().get(id.as_str()).cloned()
} else {
None
};
if let Some(parts) = old.as_ref().and_then(Book::parts) {
let rt = tokio::runtime::Handle::current();
parts.gate.shut();
self.hold(&id, Book::Closed);
self.release(&rt, &id, &parts, false);
}
match self.root.restore(&git, &source, &id, &expect_head, replace) {
@@ -1589,7 +1594,7 @@ impl Books {
Err(e) => {
// The books it would have replaced, let go above, open
// again (only this restore runs, so nothing else holds them).
if replace && !self.held().contains_key(id.as_str()) {
if replace {
let book = self.open(&id);
self.hold(&id, book);
}
+59 -2
View File
@@ -25,7 +25,9 @@
//! folder is made under): after it none is made, given or swept by
//! any holder of these exports from before, so a book let go is
//! never touched by a late request or a sweep, whoever has it open
//! by then.
//! by then. A fetch (`get`) reads under that lock: `close` waits for
//! one under way, so no byte of a closed book's folder is read for a
//! caller after `close` has returned.
//! ```
use crate::journal::sha256_hex;
@@ -211,7 +213,10 @@ impl Exports {
return Err(ExportError::Unknown(id.chars().take(40).collect()));
}
let unknown = || ExportError::Unknown(id.to_string());
if *self.locked() {
// Read under the lock a close takes (INVARIANT 5): `close` waits
// for a fetch under way, and none begins after it.
let held = self.locked();
if *held {
return Err(ExportError::Bad("the books aren't open".into()));
}
let record = std::fs::read(self.path(id, "json")).map_err(|_| unknown())?;
@@ -223,6 +228,7 @@ impl Exports {
return Err(ExportError::NotYours);
}
let bytes = std::fs::read(self.path(id, "bin")).map_err(|_| unknown())?;
drop(held);
if bytes.len() as u64 != export.size || sha256_hex(&bytes) != export.sha256 {
return Err(ExportError::Damaged);
}
@@ -302,6 +308,57 @@ mod tests {
assert_eq!(seen(), before);
}
/// INVARIANT 5: a fetch reads under the lock a close takes, so a close
/// waits for the fetch under way instead of returning while bytes of
/// the folder are still being read for a caller. The fetch is held
/// inside its read (the export's file is a named pipe nothing writes
/// to yet), and `close` must not return until it is let go.
#[cfg(unix)]
#[test]
fn a_close_waits_for_a_fetch_that_is_reading() {
let dir = tempfile::tempdir().unwrap();
let x = Exports::open(dir.path(), NOW).unwrap();
let e = x.put("t", "a.csv", "text/csv", b"x", NOW).unwrap();
let bin = x.path(&e.id, "bin");
std::fs::remove_file(&bin).unwrap();
let made = std::process::Command::new("mkfifo").arg(&bin).status();
assert!(made.unwrap().success());
let fetching = {
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));
let (done, closed) = std::sync::mpsc::channel();
let closing = {
let x = x.clone();
std::thread::spawn(move || {
x.close();
let _ = done.send(());
})
};
assert!(
closed
.recv_timeout(std::time::Duration::from_millis(500))
.is_err(),
"the close returned while a fetch was reading the folder"
);
// 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(),
);
assert!(fetching.join().unwrap().is_err());
closed
.recv_timeout(std::time::Duration::from_secs(5))
.expect("the close returns once the fetch has ended");
closing.join().unwrap();
}
#[test]
fn an_export_is_kept_fifteen_minutes() {
// What its refusal tells the human: kept 15 minutes, then gone.
+113 -5
View File
@@ -29,11 +29,23 @@
//! 5. A token has at most MAX_LIVE grants under way, so what one agent
//! can keep on the disk is bounded.
//! 6. Uploads can be closed (`close`, under the lock every change to
//! the folder is made under): after it nothing is granted, received,
//! taken, swept, given back or forgotten, by any holder of these
//! uploads from before, so a book let go (closed, or replaced by a
//! restore) is never touched by a sweep, a late request or a claim
//! dropped after, whoever has the book open by then.
//! the folder is made under): after it nothing is granted, taken,
//! swept, given back or forgotten, by any holder of these uploads
//! from before, so a book let go (closed, or replaced by a restore)
//! is never touched by a sweep, a late request or a claim dropped
//! after, whoever has the book open by then. A file coming in
//! (`receive`) is the one change that spans time: each chunk is
//! written under that lock, and the rename that keeps the bytes is
//! made under it, so once `close` has returned no byte is written
//! and none is kept; what the request had written (its `.part`) is
//! removed by the request, when it next looks (its next chunk, or
//! its end), which is the only thing a request begun before the
//! close does to the folder after it, and the removal of a file
//! only that request made. A request that is still waiting for its
//! next bytes when the close returns is not woken by the type: a
//! caller that must not leave that part behind waits for the
//! request (the books server's gate does, and cuts one that never
//! finishes arriving).
//! ```
use crate::journal::sha256_hex;
@@ -461,6 +473,13 @@ impl Uploads {
break Ok(());
}
hasher.update(&buf[..n]);
// Each chunk is written under the lock a close takes
// (INVARIANT 6): once the uploads are closed no more bytes go
// into the part, which is removed below.
let held = self.locked();
if *held {
break Err(UploadError::Bad(CLOSED.into()));
}
if let Err(e) = out.write_all(&buf[..n]) {
break Err(e.into());
}
@@ -668,6 +687,95 @@ mod tests {
assert_eq!(seen(), held);
}
/// A body that hands out `chunks`, one per read, and tells the test
/// before each read (its number, from 1) so it can act at an exact
/// point of the transfer.
struct Feed<'a> {
chunks: std::collections::VecDeque<Vec<u8>>,
reads: usize,
before: Box<dyn FnMut(usize) + 'a>,
}
impl std::io::Read for Feed<'_> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.reads += 1;
(self.before)(self.reads);
match self.chunks.pop_front() {
Some(c) => {
buf[..c.len()].copy_from_slice(&c);
Ok(c.len())
}
None => Ok(0),
}
}
}
fn names_in(dir: &Path) -> Vec<String> {
let mut names: Vec<_> = std::fs::read_dir(dir.join(UPLOADS_DIR))
.unwrap()
.map(|f| f.unwrap().file_name().to_string_lossy().into_owned())
.collect();
names.sort();
names
}
/// INVARIANT 6, per chunk: a close that comes while a file is coming
/// in stops the request at the chunk that follows it. Not one more
/// read is made, no byte is written after the close, and the part the
/// request had written is removed.
#[test]
fn a_close_in_the_middle_of_a_file_stops_it_at_the_next_chunk() {
let dir = tempfile::tempdir().unwrap();
let u = Uploads::open(dir.path(), NOW).unwrap();
let bytes: Vec<u8> = (0..3000u32).map(|n| (n % 251) as u8).collect();
let g = grant_for(&u, "tok_a", &bytes);
let mut feed = Feed {
chunks: bytes.chunks(1000).map(<[u8]>::to_vec).collect(),
reads: 0,
before: Box::new(|read| {
if read == 2 {
u.close();
}
}),
};
let refused = u.receive(&g.id, "tok_a", &mut feed, NOW).unwrap_err();
assert!(refused.to_string().contains("aren't open"), "{refused}");
assert_eq!(feed.reads, 2, "the body was read after the close");
let left = names_in(dir.path());
assert!(
!left.iter().any(|n| n.ends_with(".part") || n.ends_with(".bin")),
"{left:?}"
);
}
/// INVARIANT 6, the last step: a close that comes after the last byte
/// and before the bytes are kept keeps nothing (the rename that makes
/// them the upload is under the lock a close takes).
#[test]
fn a_close_between_the_last_byte_and_the_rename_keeps_nothing() {
let dir = tempfile::tempdir().unwrap();
let u = Uploads::open(dir.path(), NOW).unwrap();
let bytes = b"%PDF-1.4 a receipt".to_vec();
let g = grant_for(&u, "tok_a", &bytes);
let mut feed = Feed {
chunks: [bytes.clone()].into(),
reads: 0,
// The second read is the one that finds the end.
before: Box::new(|read| {
if read == 2 {
u.close();
}
}),
};
let refused = u.receive(&g.id, "tok_a", &mut feed, NOW).unwrap_err();
assert!(refused.to_string().contains("aren't open"), "{refused}");
let left = names_in(dir.path());
assert!(
!left.iter().any(|n| n.ends_with(".part") || n.ends_with(".bin")),
"{left:?}"
);
}
#[test]
fn bytes_sent_as_declared_are_taken_once() {
let dir = tempfile::tempdir().unwrap();