diff --git a/crates/ledger-cli/tests/book_open_close.rs b/crates/ledger-cli/tests/book_open_close.rs index d0189af3..fd90bac4 100644 --- a/crates/ledger-cli/tests/book_open_close.rs +++ b/crates/ledger-cli/tests/book_open_close.rs @@ -778,6 +778,30 @@ mod raw { self.stream.write_all(rest).unwrap(); } + /// Everything the server sends until it closes the connection, + /// which it must do within `within`. + pub fn until_closed(&mut self, within: Duration) -> String { + self.stream.set_read_timeout(Some(within)).unwrap(); + let mut seen = std::mem::take(&mut self.taken); + let mut buf = [0u8; 4096]; + loop { + match self.stream.read(&mut buf) { + Ok(0) => break, + Ok(n) => seen.extend_from_slice(&buf[..n]), + Err(e) + if matches!( + e.kind(), + std::io::ErrorKind::ConnectionReset | std::io::ErrorKind::BrokenPipe + ) => + { + break; + } + Err(e) => panic!("the connection was left open: {e}"), + } + } + String::from_utf8_lossy(&seen).to_string() + } + /// The response's status line and headers (the body is left). pub fn head(&mut self) -> (u16, String) { self.stream @@ -1260,6 +1284,242 @@ fn an_upload_in_flight_finishes_before_the_close_is_answered() { assert!(server.close().success()); } +/// Whether the access log of `id` holds a record of `action` on `subject` +/// that the close cut (never a record of it having run). +fn cut_records(home: &Home, id: &str, action: &str) -> Vec { + access_of(home, id) + .into_iter() + .filter(|r| { + r.access.action == action + && r.access.result + == ledger_store::access::Outcome::Refused("cut_by_close".to_string()) + }) + .collect() +} + +/// An upload whose body stalls half way (the client neither sends the rest +/// nor hangs up) is inside the book's door, and would hold the close for +/// ever. The close waits the grace, cuts it: its connection is closed, its +/// part file is gone, its record says the close cut it, nothing was +/// kept. The close is answered, and the log is a whole chain through a +/// reopening (local.rs INVARIANT 10, the cut). +#[cfg(unix)] +#[test] +fn a_stalled_upload_body_cannot_hold_a_close_and_leaves_no_part_file() { + let home = Home::new("close-stalled-upload"); + let server = Server::start_with(&home, &["--answer-grace", "600", "--timers", "10"]); + home.create(A, "USD"); + let mut w = Wire::new(&home, A); + w.initialize("uploader"); + let bytes: Vec = (0..200_000u32).map(|n| (n % 251) as u8).collect(); + let (id, mut raw) = half_sent_upload(&home, &mut w, A, &bytes); + let started = std::time::Instant::now(); + assert_eq!(close_book(&home, A), CloseOutcome::Closed); + let took = started.elapsed(); + assert!( + took >= Duration::from_millis(500), + "the upload was cut before the grace ran out ({took:?})" + ); + assert!( + took < Duration::from_secs(20), + "a stalled upload held the close ({took:?})" + ); + assert_eq!(parts_under(&home.book_dir(A)), Vec::::new()); + assert!( + !tree_of(&home.book_dir(A)) + .keys() + .any(|k| k.contains(&id) && k.ends_with(".bin")), + "bytes of a cut upload were kept" + ); + let said = raw.until_closed(Duration::from_secs(10)); + assert!(said.contains("cut_by_close"), "{said}"); + assert_eq!(cut_records(&home, A, "upload").len(), 1); + stands_still( + &home, + A, + Duration::from_millis(300), + "after the close was answered", + ); + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + let mut again = Wire::new(&home, A); + again.initialize("after"); + draft(&mut again, "after"); + access_of(&home, A); + assert!(server.close().success()); + access_of(&home, A); +} + +/// The same for an MCP call whose body never finishes arriving: no tool saw +/// it, so nothing is in the journal; the close is not held; the record says +/// the close cut it. +#[cfg(unix)] +#[test] +fn a_stalled_mcp_body_cannot_hold_a_close_and_nothing_of_it_is_journaled() { + let home = Home::new("close-stalled-mcp"); + let server = Server::start_with(&home, &["--answer-grace", "600", "--timers", "10"]); + home.create(A, "USD"); + let mut w = Wire::new(&home, A); + w.initialize("caller"); + draft(&mut w, "before"); + let mut raw = raw::Raw::connect(&home, A); + let body = json!({"jsonrpc": "2.0", "id": 9, "method": "tools/call", "params": { + "name": "books.draft_entry", + "arguments": {"date": "2026-03-01", "description": "never finished"}}}) + .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() / 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(); + assert!( + took >= Duration::from_millis(500), + "cut too early ({took:?})" + ); + assert!(took < Duration::from_secs(20), "held by a stall ({took:?})"); + let said = raw.until_closed(Duration::from_secs(10)); + assert!(said.contains("cut_by_close"), "{said}"); + assert!( + !files_of(&home, A) + .0 + .iter() + .any(|l| l.payload["description"] == json!("never finished")), + "a call whose body never arrived was journaled" + ); + assert_eq!(cut_records(&home, A, "connect").len(), 1); + assert_eq!(open_book(&home, A), OpenOutcome::Opened); + let mut again = Wire::new(&home, A); + again.initialize("after"); + draft(&mut again, "after"); + access_of(&home, A); + assert!(server.close().success()); +} + +/// A slow upload that is still arriving, and finishes within the grace, is +/// not cut: it is kept and answered, as without a close. +#[cfg(unix)] +#[test] +fn a_slow_upload_that_finishes_within_the_grace_is_not_cut() { + let home = Home::new("close-slow-upload"); + let server = Server::start_with(&home, &["--answer-grace", "2500", "--timers", "10"]); + home.create(A, "USD"); + let mut w = Wire::new(&home, A); + w.initialize("uploader"); + let bytes: Vec = (0..200_000u32).map(|n| (n % 247) as u8).collect(); + let (id, mut raw) = half_sent_upload(&home, &mut w, A, &bytes); + 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("the book is listed closed", Duration::from_secs(30), || { + listed(&home, A).1 + }); + for chunk in bytes[bytes.len() / 2..].chunks(25_000) { + std::thread::sleep(Duration::from_millis(150)); + raw.finish(chunk); + } + let (status, head) = raw.head(); + assert_eq!(status, 200, "{head}"); + match closing.join().unwrap() { + Response::CloseBook { outcome, .. } => assert_eq!(outcome, CloseOutcome::Closed), + other => panic!("{other:?}"), + } + assert!(cut_records(&home, A, "upload").is_empty()); + assert!( + tree_of(&home.book_dir(A)) + .keys() + .any(|k| k.ends_with(&format!("{id}.bin"))), + "the bytes were kept" + ); + assert!(server.close().success()); +} + +/// 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. +#[cfg(unix)] +#[test] +fn a_running_call_is_never_cut_when_the_grace_runs_out() { + 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", + ], + ); + 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 raw = raw::Raw::connect(&home, A); + let body = json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": { + "name": "books.back_up_now", "arguments": {}}}) + .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(), + ); + wait_for("the call reached git", Duration::from_secs(30), || { + shim.join("stalled").exists() + }); + 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. + 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}"); + let _ = closing.join().unwrap(); + assert!(cut_records(&home, A, "books.back_up_now").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" + && r.access.result == ledger_store::access::Outcome::Ok), + "the call that ran is on record as having run" + ); + drop(raw); + assert!(server.close().success()); +} + /// A backup of `id`, taken now to its folder target; the repository. #[cfg(unix)] fn backed_up_to_folder(home: &Home, w: &mut Wire, id: &str) -> PathBuf { @@ -1290,7 +1550,7 @@ fn a_restore_over_an_open_book_waits_for_what_is_inside_it() { &home, &[ "--answer-grace", - "500", + "15000", "--timers", "10", "--backup-quiet", @@ -1302,6 +1562,8 @@ fn a_restore_over_an_open_book_waits_for_what_is_inside_it() { w.initialize("owner"); let repo = backed_up_to_folder(&home, &mut w, A); let bytes: Vec = (0..200_000u32).map(|n| (n % 241) as u8).collect(); + // (The grace is longer than the 5 seconds watched below: an upload + // that finishes within it is waited for, never cut.) let (id, mut raw) = half_sent_upload(&home, &mut w, A, &bytes); let source = repo.display().to_string(); let preview = match home.admin(Request::Restore { @@ -1384,6 +1646,75 @@ fn a_restore_over_an_open_book_waits_for_what_is_inside_it() { assert!(server.close().success()); } +/// A restore over an open book is held by an upload that stalls no longer +/// than the grace: the upload is cut (no part file in `legacy/`, its record +/// in the replaced book's log says so), and the restore is answered. +#[cfg(unix)] +#[test] +fn a_restore_over_an_open_book_is_not_held_by_a_stalled_upload() { + let home = Home::new("restore-stalled"); + let server = Server::start_with( + &home, + &[ + "--answer-grace", + "600", + "--timers", + "10", + "--backup-quiet", + "3600000", + ], + ); + home.create(A, "USD"); + let mut w = Wire::new(&home, A); + w.initialize("owner"); + let repo = backed_up_to_folder(&home, &mut w, A); + let bytes: Vec = (0..200_000u32).map(|n| (n % 239) as u8).collect(); + let (id, mut raw) = half_sent_upload(&home, &mut w, A, &bytes); + let source = repo.display().to_string(); + let preview = match home.admin(Request::Restore { + id: A.into(), + source: source.clone(), + replace: true, + confirmed: false, + expect_head: None, + }) { + Response::RestorePreview(p) => p, + other => panic!("{other:?}"), + }; + let started = std::time::Instant::now(); + let restored = match home.admin(Request::Restore { + id: A.into(), + source, + replace: true, + confirmed: true, + expect_head: Some(preview.head), + }) { + Response::Restored(r) => r, + other => panic!("{other:?}"), + }; + assert!(started.elapsed() < Duration::from_secs(30)); + assert!(restored.replaced.is_some(), "{restored:?}"); + let said = raw.until_closed(Duration::from_secs(10)); + assert!(said.contains("cut_by_close"), "{said}"); + let legacy = home.root().join("legacy"); + assert_eq!(parts_under(&legacy), Vec::::new()); + let old = std::fs::read_dir(&legacy) + .unwrap() + .next() + .unwrap() + .unwrap() + .path(); + let (records, _) = ledger_store::access::read(&old).expect("the replaced book's log is whole"); + assert!( + records.iter().any(|r| r.access.action == "upload" + && r.access.subject == id + && r.access.result + == ledger_store::access::Outcome::Refused("cut_by_close".to_string())), + "{records:?}" + ); + assert!(server.close().success()); +} + /// Downloads running while a book closes each complete whole, and are on /// record, or are refused unrun: never cut, never answered from a book /// after it was closed. diff --git a/crates/ledger-mcp/src/access.rs b/crates/ledger-mcp/src/access.rs index 7dd30145..8931880f 100644 --- a/crates/ledger-mcp/src/access.rs +++ b/crates/ledger-mcp/src/access.rs @@ -120,6 +120,8 @@ pub(crate) const UNAUTHORIZED: &str = "unauthorized"; pub(crate) const INSUFFICIENT_SCOPE: &str = "insufficient_scope"; /// The books were closing. pub(crate) const CLOSING: &str = "closing"; +/// A close cut the request while its body was still arriving. +pub(crate) const CUT: &str = "cut_by_close"; /// The server had stopped. pub(crate) const STOPPED: &str = "stopped"; /// A file's bytes or text came as an argument (D-46). diff --git a/crates/ledger-mcp/src/local.rs b/crates/ledger-mcp/src/local.rs index 6803f500..8dd81d46 100644 --- a/crates/ledger-mcp/src/local.rs +++ b/crates/ledger-mcp/src/local.rs @@ -68,8 +68,9 @@ //! one change at a time (create, adopt and restore among them). Open: //! a closed (or failed) book of the root is opened and verified as at //! 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 call already -//! running on it, on any route, finishes (nothing is killed, nothing +//! 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 @@ -122,6 +123,25 @@ //! and none checks for a duplicate): a draft asked for twice is two //! drafts. That is an open design point (plan/p15-app-and-relay.md), //! not something the close hides. +//! 15. A request that has begun and never finishes arriving can't hold a +//! close: when the answer grace (counted from the start of the close, +//! or of the server's) has run out, every request inside the door +//! whose body has not yet been read to its end is cut. The line is +//! the body's end, and no later: a body read to its end is whole, +//! whatever the request does after (a call running, its answer being +//! sent), and is never cut; a body not yet read to its end, however +//! slowly or quickly it is coming, is cut at that moment. A cut +//! request's connection is closed (`Connection: close`, 503, +//! `x-wanderbooks-refused: cut_by_close`), what it had written is +//! removed (an upload's part file, by `receive` on its read error), +//! and its access record, written before its answer, says +//! `cut_by_close`. Nothing of an MCP call can have been journaled: +//! the service reads the whole body before it gives any message to a +//! session or a tool (rmcp `expect_json`, which answers a body that +//! fails with an error before anything else), and the handler checks +//! for the cut again before it binds a session. This holds for a +//! book's close, for a restore over an open book (both are +//! `Books::release`) and for the server's close. //! SCENARIOS: //! 1. Two books open; one is closed while agents call both: the other //! answers throughout, the closed one's calls are refused unrun @@ -147,6 +167,11 @@ //! is left in `legacy/`. //! 8. The timers run every few milliseconds on a book that is closed and //! opened over and over: while it is closed not a file of it moves. +//! 9. An upload stops sending half way, and another call's body stops +//! half way, and the book is closed: the close waits the grace, cuts +//! both (no part file, nothing journaled, the records say cut), and +//! answers closed. An upload still coming within the grace, and a +//! call running past it, are not cut. //! ``` use crate::admin::{self, Request, Response}; @@ -347,6 +372,26 @@ pub(crate) struct Gate { inside: AtomicUsize, answering: AtomicUsize, left: tokio::sync::Notify, + /// Cancelled when the close's grace has run out: a request inside + /// whose body hasn't finished arriving is cut (see [`Arrival`]). + cut: CancellationToken, +} + +/// Where a request's body is: still coming, whole, or cut by a close. +/// The body of a request inside a book's door is wrapped by +/// [`Inside::arriving`], which changes this state in one place only (its +/// own poll), so a body is never both whole and cut. +pub(crate) struct Arrival(std::sync::atomic::AtomicU8); + +const ARRIVING: u8 = 0; +const ARRIVED: u8 = 1; +const CUT: u8 = 2; + +impl Arrival { + /// Whether a close cut this request's body before it was whole. + fn was_cut(&self) -> bool { + self.0.load(Ordering::SeqCst) == CUT + } } /// A request inside a book's door, counted until dropped. @@ -366,6 +411,58 @@ impl Inside { self.0.answering.fetch_add(1, Ordering::SeqCst); Answering(self.0.clone()) } + + /// The request, its body watched: it is whole once the body's end has + /// been read (a request with no body is whole at once), and until + /// then a close whose grace ran out cuts it: the body fails, as a + /// connection that dropped would, and the returned [`Arrival`] says + /// so. A body already whole is never cut, whatever runs after it. + fn arriving(&self, request: axum::extract::Request) -> (axum::extract::Request, Arc) { + use axum::body::HttpBody as _; + use futures_util::StreamExt; + use std::task::Poll; + let arrival = Arc::new(Arrival(std::sync::atomic::AtomicU8::new(ARRIVING))); + let (parts, body) = request.into_parts(); + if body.is_end_stream() { + arrival.0.store(ARRIVED, Ordering::SeqCst); + return (axum::extract::Request::from_parts(parts, body), arrival); + } + let mut data = body.into_data_stream(); + let mut cut = Box::pin(self.0.cut.clone().cancelled_owned()); + let seen = arrival.clone(); + let stream = futures_util::stream::poll_fn(move |cx| { + match seen.0.load(Ordering::SeqCst) { + ARRIVED => return Poll::Ready(None), + CUT => return Poll::Ready(Some(Err(cut_error()))), + _ => {} + } + // Checked before the data: a body that keeps coming past the + // grace is cut too, not only one that stalled. + if cut.as_mut().poll(cx).is_ready() { + seen.0.store(CUT, Ordering::SeqCst); + return Poll::Ready(Some(Err(cut_error()))); + } + match data.poll_next_unpin(cx) { + Poll::Ready(None) => { + seen.0.store(ARRIVED, Ordering::SeqCst); + Poll::Ready(None) + } + Poll::Ready(Some(r)) => Poll::Ready(Some(r.map_err(std::io::Error::other))), + Poll::Pending => Poll::Pending, + } + }); + ( + axum::extract::Request::from_parts(parts, axum::body::Body::from_stream(stream)), + arrival, + ) + } +} + +fn cut_error() -> std::io::Error { + std::io::Error::new( + std::io::ErrorKind::ConnectionAborted, + "the request wasn't finished when the books closed", + ) } /// An answer on its way out of a book's door (see [`Gate`]). @@ -386,6 +483,13 @@ impl Gate { (!self.shut.load(Ordering::SeqCst)).then_some(inside) } + /// Cut every request inside whose body isn't whole (see + /// [`Inside::arriving`]); the ones whose body is whole are left to + /// finish. + fn cut_unfinished(&self) { + self.cut.cancel(); + } + /// Let no request in from now on. fn shut(&self) { self.shut.store(true, Ordering::SeqCst); @@ -1216,7 +1320,10 @@ impl Books { /// /// In this order, each step ending before the next begins: /// 1. the store's tools finish, and its door empties (every request - /// inside has finished, its record written); + /// inside has finished, its record written); a request whose body + /// isn't whole when ANSWER_GRACE has run out is cut (its + /// connection closed, what it wrote removed, its record saying the + /// close cut it), a running call is not; /// 2. the answers on their way out are sent, for ANSWER_GRACE at most: /// a client that never reads its answer doesn't hold the book /// open (the call it was answering ran and is in the journal and @@ -1244,9 +1351,22 @@ impl Books { backups, ended, } = parts; - // No tool starts, and every one that did start has finished. - rt.block_on(store.close()); - rt.block_on(gate.emptied()); + // No tool starts, and every one that did start has finished. A + // request that has begun and isn't whole when the grace runs out + // is cut, so one that never finishes sending can't hold the book; + // a call whose body is whole and that is running is left to end. + rt.block_on(async { + let cutter = { + let (gate, grace) = (gate.clone(), self.timers.answer_grace); + tokio::spawn(async move { + tokio::time::sleep(grace).await; + gate.cut_unfinished(); + }) + }; + store.close().await; + gate.emptied().await; + cutter.abort(); + }); if rt .block_on(tokio::time::timeout( self.timers.answer_grace, @@ -1285,6 +1405,14 @@ impl Books { problem.map(|why| self.hide(why)) } + /// The door of every open book. + fn gates(&self) -> Vec> { + self.held() + .values() + .filter_map(|b| b.parts().map(|p| p.gate)) + .collect() + } + /// End the MCP sessions of the book `id` and forget their bindings. fn end_sessions(&self, id: &BookId, ended: &CancellationToken) { ended.cancel(); @@ -1745,6 +1873,36 @@ async fn refused_at_door( response } +/// The answer to a request a close cut while its body was still arriving +/// (INVARIANT 10): recorded in the access log as cut by the close, and the +/// connection ends with it. +async fn cut_by_the_close( + book: &Book, + inside: Inside, + principal: Principal, + asked: &Asked, +) -> axum::response::Response { + let mut response = refused_at_door( + book, + inside, + principal, + asked, + crate::access::CUT, + axum::http::StatusCode::SERVICE_UNAVAILABLE, + "the books closed before this request was all sent: it wasn't run".into(), + ) + .await; + close_connection(&mut response); + response +} + +fn close_connection(response: &mut axum::response::Response) { + response.headers_mut().insert( + axum::http::header::CONNECTION, + axum::http::HeaderValue::from_static("close"), + ); +} + /// The door to `book` (INVARIANT 8): the books held open, the server not /// closing, and a live token for those books; else the answer refusing /// the request (recorded in the books' access log, where there is one). @@ -1918,6 +2076,10 @@ async fn upload( else { unreachable!("the door lets only open books through") }; + // Its body watched: a close whose grace ran out cuts it while it is + // still arriving, which ends `receive` with its part file removed. + let (request, arrival) = inside.arriving(request); + let cut_seen = arrival.clone(); // Streamed to the disk as it comes, never held whole; `receive` reads // no more than the size declared and one byte. The bytes and their // record are one blocking task, which runs to its end even if the @@ -1951,6 +2113,12 @@ async fn upload( let _ = std::io::copy(&mut (&mut body).take(rest), &mut std::io::sink()); } let (status, outcome, text) = match &received { + _ if cut_seen.was_cut() => ( + StatusCode::SERVICE_UNAVAILABLE, + Outcome::Refused(crate::access::CUT.into()), + "the books closed before this upload was all sent: send it again once they are open" + .to_string(), + ), Ok(g) => ( StatusCode::OK, Outcome::Ok, @@ -2003,10 +2171,14 @@ async fn upload( ) .into_response(); }; - match outcome { + let mut response = match outcome { Outcome::Refused(code) => (status, [(REFUSED_HEADER, code)], text).into_response(), _ => (status, text).into_response(), + }; + if arrival.was_cut() { + close_connection(&mut response); } + response } /// `GET /b/{book}/a/{attachment}`: a stored file's bytes, for a token @@ -2275,6 +2447,11 @@ async fn mcp( kind: "agent".into(), label: t.name.clone(), }; + // Its body watched: a close whose grace ran out cuts it while it is + // still arriving (never once whole), before any tool has seen it. + let (rewatched, arrival) = inside.arriving(request); + request = rewatched; + let who = principal(&token); let session = request .headers() .get(SESSION_HEADER) @@ -2308,6 +2485,9 @@ async fn mcp( request = axum::extract::Request::from_parts(parts, axum::body::Body::from(bytes)); opens }; + if arrival.was_cut() { + return cut_by_the_close(&held, inside, who, &Asked::connect(&method)).await; + } if full { return refused_at_door( &held, @@ -2340,6 +2520,14 @@ async fn mcp( Ok(response) => response, Err(never) => match never {}, }; + // The service reads a whole body before it hands any message to a + // session or a tool (rmcp's `expect_json`, which ends in an error + // answer on a body that fails), so a body cut here reached nothing: + // no call ran, nothing is in the journal. + if arrival.was_cut() { + drop(response); + return cut_by_the_close(&held, inside, who, &Asked::connect(&method)).await; + } // A session the answer opened is bound to the token that opened it; // one ended, or found gone, is forgotten. { @@ -2871,11 +3059,23 @@ async fn serve( }; tokio::select! { () = answers => {} - () = tokio::time::sleep(ANSWER_GRACE) => { + () = tokio::time::sleep(books.timers.answer_grace) => { eprintln!("wanderbooks server: a client didn't finish its request; closing without it"); } () = stops.hurry.cancelled() => {} } + // A request that began and still isn't whole is cut, whatever it had + // written removed and its record saying so; a call whose body is whole + // has finished already (the stores were closed above). + let gates = books.gates(); + for gate in &gates { + gate.cut_unfinished(); + } + tokio::select! { + () = async { for gate in &gates { gate.emptied().await } } => {} + () = tokio::time::sleep(HTTP_GRACE) => {} + () = stops.hurry.cancelled() => {} + } books.sessions.cancel(); // A call that set out just before its client heard of the close still // meets a refusal, never a connection cut mid-way (which it couldn't diff --git a/docs/mcp-interface.md b/docs/mcp-interface.md index e423e824..098f8d61 100644 --- a/docs/mcp-interface.md +++ b/docs/mcp-interface.md @@ -361,7 +361,13 @@ didn't open, with why). Protocol version 1: the requests are new, the 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 are sent, for 10 seconds at most (a client that never reads its answer - doesn't hold the book open); its MCP sessions end (an agent's next + 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 + close: an upload or a call that began and stopped sending) is cut: its + connection is closed, an upload's part file is removed, nothing of an + MCP call reached the journal, and the access log says `cut_by_close`; + a call whose body arrived whole and is running is never cut, it + finishes; its MCP sessions end (an agent's next request on one gets the "isn't open" words above, and after a reopening a 404 "Session not found", which a client takes as "open a new one"); its last backup is made, as at the server's close, for 60 seconds at most: diff --git a/docs/testing.md b/docs/testing.md index 165eaff7..292d7ddc 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -4316,6 +4316,11 @@ one book never refuses or holds up a call on another. | `local::tests::handles_from_before_a_close_do_nothing_after_the_book_is_open_again` | the access log, uploads, exports and backups taken before a close, used after the same book is opened again (a late record, a sweep, a grant, an export, a run, a drill, a format upgrade), write nothing: the reopened book's tree is byte for byte what its own upgrade left, and its backup record is a whole chain (fails when the backups' shut flag and record close are removed) | | `ledger-store` `access::tests::a_closed_log_writes_nothing_and_a_reopened_one_stays_whole`, `uploads::tests::closed_uploads_change_nothing`, `exports::tests::closed_exports_change_nothing_and_give_nothing`, `backup::tests::a_cancelled_git_stops_what_runs_and_starts_nothing` | the closed state of each handle (under the lock its writes go in under), and git's cancel flag (a running command is stopped with all it started, none starts) | | `book_open_close::a_client_that_never_reads_its_answer_cannot_hold_a_close_nor_break_the_log` | a client asks for the 500 KB tools list and never reads it (the answer is stuck in the socket): the close waits the answer grace (shortened to 700 ms) and then answers; the folder doesn't move afterwards; after the reopening the access log is one whole chain | +| `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_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) | | `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` |