From ca6f5aa9823bb6136d19d6efdc58da2d1b9038d3 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Fri, 20 Nov 2026 12:22:19 -0700 Subject: [PATCH] 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 --- crates/ledger-cli/tests/book_open_close.rs | 29 +++-- crates/ledger-mcp/src/local.rs | 17 +-- crates/ledger-store/src/exports.rs | 61 ++++++++++- crates/ledger-store/src/uploads.rs | 118 ++++++++++++++++++++- docs/mcp-interface.md | 5 +- docs/testing.md | 2 + 6 files changed, 211 insertions(+), 21 deletions(-) diff --git a/crates/ledger-cli/tests/book_open_close.rs b/crates/ledger-cli/tests/book_open_close.rs index fd90bac4..18555ceb 100644 --- a/crates/ledger-cli/tests/book_open_close.rs +++ b/crates/ledger-cli/tests/book_open_close.rs @@ -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..]); diff --git a/crates/ledger-mcp/src/local.rs b/crates/ledger-mcp/src/local.rs index 8dd81d46..082beb2a 100644 --- a/crates/ledger-mcp/src/local.rs +++ b/crates/ledger-mcp/src/local.rs @@ -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); } diff --git a/crates/ledger-store/src/exports.rs b/crates/ledger-store/src/exports.rs index a006e512..39419986 100644 --- a/crates/ledger-store/src/exports.rs +++ b/crates/ledger-store/src/exports.rs @@ -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. diff --git a/crates/ledger-store/src/uploads.rs b/crates/ledger-store/src/uploads.rs index daee4766..9b0e4abe 100644 --- a/crates/ledger-store/src/uploads.rs +++ b/crates/ledger-store/src/uploads.rs @@ -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>, + reads: usize, + before: Box, + } + + impl std::io::Read for Feed<'_> { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + 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 { + 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 = (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(); diff --git a/docs/mcp-interface.md b/docs/mcp-interface.md index 098f8d61..7f7f5cce 100644 --- a/docs/mcp-interface.md +++ b/docs/mcp-interface.md @@ -394,7 +394,10 @@ didn't open, with why). Protocol version 1: the requests are new, the record, `books.audit`) before it repeats a write. A restore over an open book (`restore --replace`) lets go of the book in the same way (waits for what is inside the book's door, ends its sessions, stops its backups, - closes its logs) before it moves the book into `legacy/`. + closes its logs) before it moves the book into `legacy/`; the book is + listed closed from the moment the restore begins, so a call that comes + meanwhile is told the books aren't open (503, as in a close), never that + there are no such books (404). - `sessions` lists, for each open book, its live MCP sessions: the token's **name** (never the token, its text or its hash), the client's name and version from `initialize`, the agent's self-report (`books.start`'s diff --git a/docs/testing.md b/docs/testing.md index 292d7ddc..63d31609 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -4319,6 +4319,8 @@ one book never refuses or holds up a call on another. | `book_open_close::a_stalled_upload_body_cannot_hold_a_close_and_leaves_no_part_file` | an upload stops sending half way: the close waits the grace (600 ms), cuts it (connection closed, no part file, no bytes kept, record `cut_by_close`) and answers; the folder stands still; one whole access chain across the reopening (hung before the change) | | `book_open_close::a_stalled_mcp_body_cannot_hold_a_close_and_nothing_of_it_is_journaled` | a `tools/call` whose body stops half way is cut by the close: connection closed, the call is not in the journal, record `cut_by_close` (hung before the change) | | `book_open_close::a_restore_over_an_open_book_is_not_held_by_a_stalled_upload` | a restore over an open book with an upload stalled half way: the upload is cut after the grace, no part file in `legacy/`, the replaced book's log records `cut_by_close`, the restore is answered | +| `book_open_close::a_restore_over_an_open_book_waits_for_what_is_inside_it` | (extended) every call while the restore waits for a half-received upload gets 503 and the closed words, never 404 `no such books` (fails when the restore takes the book out of the list before it shuts the door) | +| `ledger-store` `uploads::tests::a_close_in_the_middle_of_a_file_stops_it_at_the_next_chunk`, `uploads::tests::a_close_between_the_last_byte_and_the_rename_keeps_nothing`, `exports::tests::a_close_waits_for_a_fetch_that_is_reading` | the types' own claims (INVARIANT 6 of uploads, 5 of exports): a close in the middle of a file stops it at the next chunk (no read after, no part left), a close between the last byte and the rename keeps nothing, and a fetch reads under the lock a close takes (a named pipe holds it inside its read; `close` must not return); each fails with its guard removed | | `book_open_close::a_slow_upload_that_finishes_within_the_grace_is_not_cut` | an upload dripping in over ~600 ms with a 2.5 s grace is kept and answered 200, nothing cut | | `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_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) |