diff --git a/crates/mcp/src/intake.rs b/crates/mcp/src/intake.rs index 35a7bb17ad..2053d74583 100644 --- a/crates/mcp/src/intake.rs +++ b/crates/mcp/src/intake.rs @@ -20,12 +20,12 @@ use std::io::BufRead; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::SyncSender; use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; -use std::time::{Duration, Instant}; +use std::time::Duration; use serde_json::{Value, json}; use vectorcraft_engine::cancel::CancelToken; -use crate::server::{INVALID_REQUEST, MAX_LINE_BYTES, PARSE_ERROR, SERVER_BUSY, error, error_with, read_line_capped}; +use crate::server::{Clock, INVALID_REQUEST, MAX_LINE_BYTES, PARSE_ERROR, SERVER_BUSY, error, error_with, read_line_capped}; /// Most lines waiting for the engine. Past this the reader waits (it still reads nothing else). pub(crate) const MAX_QUEUED: usize = 64; @@ -55,7 +55,8 @@ struct Running { method: String, token: CancelToken, label: String, - since: Instant, + /// When it started, on [`Shared`]'s clock. + since: Duration, } #[derive(Default)] @@ -66,6 +67,9 @@ struct State { eof: bool, /// The output failed: nobody reads replies any more. closed: bool, + /// How often the reader found [`MAX_QUEUED`] lines queued and waited for room. + #[cfg(test)] + waits_for_room: usize, } /// What the reader and the engine thread share. @@ -75,6 +79,7 @@ pub(crate) struct Shared { /// Whether the client speaks the `2026-07-28` revision, for results answered by the reader. pub(crate) modern: Arc, busy_after: Duration, + clock: Clock, } fn lock(m: &Mutex) -> MutexGuard<'_, T> { @@ -83,8 +88,8 @@ fn lock(m: &Mutex) -> MutexGuard<'_, T> { } impl Shared { - pub(crate) fn new(modern: Arc, busy_after: Duration) -> Self { - Self { state: Mutex::new(State::default()), wake: Condvar::new(), modern, busy_after } + pub(crate) fn new(modern: Arc, busy_after: Duration, clock: Clock) -> Self { + Self { state: Mutex::new(State::default()), wake: Condvar::new(), modern, busy_after, clock } } /// The next job, or `None` once the transport is done and the queue empty (or the output @@ -102,7 +107,7 @@ impl Shared { method: m.method.clone(), token: m.token.clone(), label: m.label.clone(), - since: Instant::now(), + since: (self.clock)(), }); } // The reader may be waiting for room. @@ -145,7 +150,7 @@ impl Shared { /// pipelined neighbour fail). fn long_running(&self, st: &State) -> Option { let r = st.running.as_ref()?; - let secs = r.since.elapsed(); + let secs = (self.clock)().saturating_sub(r.since); // A long id isn't repeated: every busy reply would carry it twice. let key = r.key.as_deref().filter(|k| k.len() <= MAX_ECHOED_ID); (secs >= self.busy_after).then(|| json!({"running": r.label, "requestId": key, "seconds": secs.as_secs()})) @@ -236,6 +241,11 @@ fn submit_canned(shared: &Shared, out: &SyncSender, reply: String) { if st.queue.len() < MAX_QUEUED { break; } + #[cfg(test)] + { + st.waits_for_room += 1; + shared.wake.notify_all(); + } // Wake now and then: the call ahead may turn long-running while the queue is full. st = shared.wake.wait_timeout(st, Duration::from_millis(50)).unwrap_or_else(PoisonError::into_inner).0; } @@ -289,6 +299,11 @@ fn intake(shared: &Shared, out: &SyncSender, line: &str) { if st.queue.len() < MAX_QUEUED { break; } + #[cfg(test)] + { + st.waits_for_room += 1; + shared.wake.notify_all(); + } // Wake now and then: the call that fills the queue may be the one that turns it away. st = shared.wake.wait_timeout(st, Duration::from_millis(50)).unwrap_or_else(PoisonError::into_inner).0; } @@ -331,20 +346,20 @@ mod tests { #[test] fn parse_errors_wait_for_room_in_the_queue() { // No call has run past the busy limit, so the replies queue rather than go out at once. - let shared = Shared::new(Arc::new(AtomicBool::new(false)), Duration::from_secs(60)); + let shared = Shared::new(Arc::new(AtomicBool::new(false)), Duration::from_secs(60), Arc::new(|| Duration::ZERO)); let (out, _replies) = std::sync::mpsc::sync_channel(1); let lines = 3 * MAX_QUEUED; let input = "not json\n".repeat(lines); std::thread::scope(|scope| { let reader = scope.spawn(|| read_loop(&shared, &out, input.as_bytes())); - // Nothing takes jobs off the queue yet, so the reader stops at the limit. - let end = Instant::now() + Duration::from_secs(10); - while !reader.is_finished() && lock(&shared.state).queue.len() < MAX_QUEUED && Instant::now() < end { - std::thread::sleep(Duration::from_millis(5)); + // Nothing takes jobs off the queue yet, so the reader stops at the limit and waits. + let mut st = lock(&shared.state); + while st.waits_for_room == 0 && !st.eof { + st = shared.wake.wait(st).unwrap_or_else(PoisonError::into_inner); } - std::thread::sleep(Duration::from_millis(100)); - let queued = lock(&shared.state).queue.len(); - assert!(queued <= MAX_QUEUED, "{queued} lines queued, more than {MAX_QUEUED}"); + let queued = st.queue.len(); + assert_eq!(queued, MAX_QUEUED, "the reader waited with {queued} lines queued, not {MAX_QUEUED}"); + drop(st); // Once the engine takes jobs, every line is answered with its parse error. let mut answered = 0; while let Some(job) = shared.next() { diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index a445c7146d..c402c33b91 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -50,24 +50,33 @@ const OUTBOX: usize = 256; /// Fewest time between two `notifications/progress` of one request, the last one excepted. const PROGRESS_EVERY: Duration = Duration::from_millis(200); +/// The time since a fixed start, for the busy limit and the progress throttle. +pub(crate) type Clock = Arc Duration + Send + Sync>; + +fn system_clock() -> Clock { + let origin = Instant::now(); + Arc::new(move || origin.elapsed()) +} + /// The sink that turns the engine's progress into `notifications/progress` for the request /// `msg`, when the client asked for it with `_meta.progressToken`. /// -fn progress_sink(out: SyncSender, msg: &Value) -> Option { +fn progress_sink(out: SyncSender, msg: &Value, clock: Clock) -> Option { let token = msg.get("params")?.get("_meta")?.get("progressToken").filter(|t| t.is_string() || t.is_number())?.clone(); let last = Cell::new(None::); - let at = Cell::new(None::); + let at = Cell::new(None::); Some(Rc::new(move |done, total, what| { // `progress` must increase with each notification. if last.get().is_some_and(|l| done <= l) { return; } let finished = total > 0 && done >= total; - if !finished && at.get().is_some_and(|t| t.elapsed() < PROGRESS_EVERY) { + let now = clock(); + if !finished && at.get().is_some_and(|t| now.saturating_sub(t) < PROGRESS_EVERY) { return; } last.set(Some(done)); - at.set(Some(Instant::now())); + at.set(Some(now)); let mut params = json!({"progressToken": token, "progress": done, "message": what}); if total > 0 { params["total"] = json!(total); @@ -98,6 +107,7 @@ pub struct Server { /// process-wide, so a server whose client didn't ask leaves it to the one that did. logging: bool, busy_after: Duration, + clock: Clock, } pub(crate) fn response(id: Value, result: Value) -> Value { @@ -225,7 +235,14 @@ fn write_reply(output: &mut impl Write, line: &str) -> std::io::Result<()> { impl Server { pub fn new(backend: Box) -> Self { - Self { backend, initialized: false, modern: Arc::new(AtomicBool::new(false)), logging: false, busy_after: DEFAULT_BUSY_AFTER } + Self { + backend, + initialized: false, + modern: Arc::new(AtomicBool::new(false)), + logging: false, + busy_after: DEFAULT_BUSY_AFTER, + clock: system_clock(), + } } /// How long a call runs before [`Server::serve`] turns away a request that would have to wait @@ -236,6 +253,13 @@ impl Server { self } + /// The clock that [`Server::serve`] measures the busy limit and the progress throttle on. + #[cfg(test)] + pub(crate) fn with_clock(mut self, clock: Clock) -> Self { + self.clock = clock; + self + } + pub fn backend(&mut self) -> &mut dyn Backend { self.backend.as_mut() } @@ -275,7 +299,7 @@ impl Server { /// (the running call is then cancelled and the queue dropped; the reader thread ends with its /// next line, which a client that closed our output closes as well). pub fn serve(&mut self, input: R, mut output: W) -> std::io::Result<()> { - let shared = Shared::new(self.modern.clone(), self.busy_after); + let shared = Shared::new(self.modern.clone(), self.busy_after, self.clock.clone()); let shared = &shared; let (tx, rx) = sync_channel::(OUTBOX); let reader_tx = tx.clone(); @@ -323,7 +347,7 @@ impl Server { fn run(&mut self, m: Message, out: &SyncSender) { let Message { value, key, token, .. } = m; - let sink = key.is_some().then(|| progress_sink(out.clone(), &value)).flatten(); + let sink = key.is_some().then(|| progress_sink(out.clone(), &value, self.clock.clone())).flatten(); let reply = cancel::scope(&token, sink, || self.handle_parsed(value)); // A cancelled request gets no reply (MCP: the receiver should not answer it). A call that // finished before it noticed is dropped the same way: the client has stopped waiting. diff --git a/crates/mcp/src/tests/concurrency.rs b/crates/mcp/src/tests/concurrency.rs index e6d2ec6975..10a2c2cef3 100644 --- a/crates/mcp/src/tests/concurrency.rs +++ b/crates/mcp/src/tests/concurrency.rs @@ -3,6 +3,7 @@ //! client on stdio drives it, with a backend that works until it is told to stop. use std::io::{BufReader, Write}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -13,13 +14,33 @@ use vectorcraft_engine::cancel; use super::TempFolder; use crate::{Backend, Server}; -/// A backend whose `engine.execute` runs until cancelled (or for `limit`), like a long export. +/// A clock the test moves, in milliseconds, and the server's view of it. +fn manual_clock() -> (Arc, crate::server::Clock) { + let ms = Arc::new(AtomicU64::new(0)); + let read = ms.clone(); + (ms, Arc::new(move || Duration::from_millis(read.load(Ordering::SeqCst)))) +} + +/// A backend whose `engine.execute` runs until the test releases it or the call is cancelled, +/// like a long export. Commands whose id starts with `quick` return at once. struct Slow { - limit: Duration, + /// One message lets one command finish. The test dropping its end lets every command finish. + go: Receiver<()>, /// Commands that ran to the end, and the ones that were cancelled. log: Arc>>, /// Told when a command starts. started: Sender, + /// Told what [`Slow::log`] records, when it records it. + ended: Sender, + /// The server's clock, which `progress.demo` moves between its pages. + clock: Arc, +} + +impl Slow { + fn end(&self, line: String) { + self.log.lock().unwrap().push(line.clone()); + self.ended.send(line).ok(); + } } impl Backend for Slow { @@ -31,22 +52,26 @@ impl Backend for Slow { self.started.send(id.clone()).ok(); if id == "progress.demo" { for page in 1..=3 { - // Enough apart to pass the sender's throttle. - std::thread::sleep(Duration::from_millis(230)); + // Far enough apart on the server's clock to pass the sender's throttle. + self.clock.fetch_add(230, Ordering::SeqCst); cancel::progress(page, 3, &format!("page {page}")); } return Ok(json!({"ran": id})); } - let limit = if id.starts_with("quick") { Duration::ZERO } else { self.limit }; - let start = Instant::now(); - while start.elapsed() < limit { - if let Err(e) = cancel::check() { - self.log.lock().unwrap().push(format!("cancelled {id}")); - return Err(e.to_string()); + if !id.starts_with("quick") { + loop { + if let Err(e) = cancel::check() { + self.end(format!("cancelled {id}")); + return Err(e.to_string()); + } + // The token has no wait of its own: look at it again between waits for the release. + match self.go.recv_timeout(Duration::from_millis(5)) { + Ok(()) | Err(RecvTimeoutError::Disconnected) => break, + Err(RecvTimeoutError::Timeout) => {} + } } - std::thread::sleep(Duration::from_millis(5)); } - self.log.lock().unwrap().push(format!("done {id}")); + self.end(format!("done {id}")); Ok(json!({"ran": id})) } @@ -84,22 +109,38 @@ struct Rig { to_server: std::io::PipeWriter, replies: Receiver, started: Receiver, + ended: Receiver, log: Arc>>, + go: Sender<()>, + clock: Arc, thread: Option>, } impl Rig { - fn new(limit: Duration, busy_after: Duration) -> Self { + fn new(busy_after: Duration) -> Self { let (read, to_server) = std::io::pipe().unwrap(); let (tx, replies) = mpsc::channel(); let (started_tx, started) = mpsc::channel(); + let (ended_tx, ended) = mpsc::channel(); + let (go, go_rx) = mpsc::channel(); let log = Arc::new(Mutex::new(vec![])); - let backend = Slow { limit, log: log.clone(), started: started_tx }; + let (clock, server_clock) = manual_clock(); + let backend = Slow { go: go_rx, log: log.clone(), started: started_tx, ended: ended_tx, clock: clock.clone() }; let thread = std::thread::spawn(move || { - let mut server = Server::new(Box::new(backend)).with_busy_after(busy_after); + let mut server = Server::new(Box::new(backend)).with_busy_after(busy_after).with_clock(server_clock); server.serve(BufReader::new(read), Lines(tx, vec![])).unwrap(); }); - Self { to_server, replies, started, log, thread: Some(thread) } + Self { to_server, replies, started, ended, log, go, clock, thread: Some(thread) } + } + + /// Lets the running command (or the next one to run) finish. + fn release(&self) { + self.go.send(()).unwrap(); + } + + /// Moves the server's clock on by `by`. + fn advance(&self, by: Duration) { + self.clock.fetch_add(u64::try_from(by.as_millis()).unwrap(), Ordering::SeqCst); } fn send(&mut self, msg: Value) { @@ -140,7 +181,8 @@ impl Rig { fn finish(mut self) { let thread = self.thread.take().unwrap(); - drop(self.to_server); + // The input closes and every command still waiting for a release finishes. + drop(self); thread.join().unwrap(); } } @@ -148,17 +190,17 @@ impl Rig { /// How long a test waits for the server to start a command, to answer or to log. The wait only ends /// a test whose server never does. A machine busy with other builds can hold a thread for seconds. const WAIT: Duration = Duration::from_secs(20); -/// How long [`Slow`]'s long command runs unless it is cancelled: longer than [`WAIT`], so a request -/// that waits behind it is not answered within the wait. +/// How long [`Gated`] waits for its cancel before it lets the export run anyway: longer than +/// [`WAIT`], so it only ends a test whose cancel never arrives. const LONG: Duration = Duration::from_secs(60); #[test] fn ping_is_answered_while_a_command_runs() { - let mut rig = Rig::new(LONG, Duration::from_millis(50)); + let mut rig = Rig::new(Duration::from_millis(50)); rig.run(1, "document.export"); assert_eq!(rig.started.recv_timeout(WAIT).unwrap(), "document.export"); // Past `busy_after` the call counts as long-running. - std::thread::sleep(Duration::from_millis(120)); + rig.advance(Duration::from_millis(120)); rig.request(2, "ping", json!({})); let pong = rig.reply(2, WAIT).expect("ping must not wait for the running command"); assert_eq!(pong["result"], json!({})); @@ -168,32 +210,34 @@ fn ping_is_answered_while_a_command_runs() { #[test] fn cancelling_stops_the_running_command_and_sends_no_reply() { - let mut rig = Rig::new(LONG, Duration::from_secs(60)); + let mut rig = Rig::new(Duration::from_secs(60)); rig.run(1, "document.export"); rig.started.recv_timeout(WAIT).unwrap(); rig.notify("notifications/cancelled", json!({"requestId": 1, "reason": "user"})); // The engine is free again: the next command runs and answers. rig.run(2, "pdf.preset.list"); - let end = Instant::now() + WAIT; + let ended = rig.ended.recv_timeout(WAIT); + assert_eq!(ended.as_deref(), Ok("cancelled document.export"), "the export kept running: {:?}", rig.log.lock().unwrap()); + rig.notify("notifications/cancelled", json!({"requestId": 2})); + // Request 1 was cancelled: nothing answers it (MCP: the receiver should not reply). Requests are + // answered in order, so every reply to request 1 comes before the answer to a later ping. + rig.request(3, "ping", json!({})); loop { - if rig.log.lock().unwrap().iter().any(|l| l == "cancelled document.export") { + let v = rig.next(WAIT).expect("an answer to the ping"); + assert_ne!(v.get("id"), Some(&json!(1)), "the cancelled request was answered: {v}"); + if v.get("id") == Some(&json!(3)) { break; } - assert!(Instant::now() < end, "the export kept running: {:?}", rig.log.lock().unwrap()); - std::thread::sleep(Duration::from_millis(10)); } - rig.notify("notifications/cancelled", json!({"requestId": 2})); - // Request 1 was cancelled: nothing answers it (MCP: the receiver should not reply). - assert!(rig.reply(1, Duration::from_millis(300)).is_none()); rig.finish(); } #[test] fn a_request_that_would_wait_behind_a_long_call_is_refused_as_busy() { - let mut rig = Rig::new(LONG, Duration::from_millis(50)); + let mut rig = Rig::new(Duration::from_millis(50)); rig.run(1, "document.export"); rig.started.recv_timeout(WAIT).unwrap(); - std::thread::sleep(Duration::from_millis(120)); + rig.advance(Duration::from_millis(120)); rig.run(2, "pdf.preset.list"); let busy = rig.reply(2, WAIT).expect("a busy answer, not a wait"); assert_eq!(busy["error"]["code"], -32003, "{busy}"); @@ -208,21 +252,33 @@ fn a_request_that_would_wait_behind_a_long_call_is_refused_as_busy() { #[test] fn quick_calls_pipelined_together_queue_and_answer_in_order() { - let mut rig = Rig::new(Duration::from_millis(30), Duration::from_secs(60)); + let mut rig = Rig::new(Duration::from_secs(60)); + // A call holds the engine while the quick calls arrive behind it. + rig.run(9, "document.export"); + assert_eq!(rig.started.recv_timeout(WAIT).unwrap(), "document.export"); for id in 1..=4 { rig.run(id, &format!("cmd{id}")); } + // The reader takes lines in order, so once it has cancelled the call ahead it has taken in the + // four calls behind it, while that call was still short of the busy limit. + rig.notify("notifications/cancelled", json!({"requestId": 9})); + assert_eq!(rig.ended.recv_timeout(WAIT).unwrap(), "cancelled document.export"); + // Each command holds the engine until it is released. + for id in 1..=4 { + assert_eq!(rig.started.recv_timeout(WAIT).unwrap(), format!("cmd{id}")); + rig.release(); + } for id in 1..=4 { let r = rig.reply(id, WAIT).unwrap_or_else(|| panic!("no reply to {id}")); assert!(r.get("error").is_none(), "{r}"); } - assert_eq!(*rig.log.lock().unwrap(), ["done cmd1", "done cmd2", "done cmd3", "done cmd4"]); + assert_eq!(*rig.log.lock().unwrap(), ["cancelled document.export", "done cmd1", "done cmd2", "done cmd3", "done cmd4"]); rig.finish(); } #[test] fn a_queued_request_that_is_cancelled_never_runs() { - let mut rig = Rig::new(LONG, Duration::from_secs(60)); + let mut rig = Rig::new(Duration::from_secs(60)); rig.run(1, "document.export"); rig.started.recv_timeout(WAIT).unwrap(); rig.run(2, "never.runs"); @@ -242,7 +298,7 @@ fn a_queued_request_that_is_cancelled_never_runs() { #[test] fn cancelling_an_unknown_or_finished_request_changes_nothing() { - let mut rig = Rig::new(Duration::from_millis(10), Duration::from_secs(60)); + let mut rig = Rig::new(Duration::from_secs(60)); rig.run(1, "quick"); assert!(rig.reply(1, WAIT).unwrap().get("result").is_some()); rig.notify("notifications/cancelled", json!({"requestId": 1})); @@ -256,7 +312,7 @@ fn cancelling_an_unknown_or_finished_request_changes_nothing() { #[test] fn initialize_cannot_be_cancelled() { - let mut rig = Rig::new(LONG, Duration::from_secs(60)); + let mut rig = Rig::new(Duration::from_secs(60)); rig.request(1, "initialize", json!({})); rig.notify("notifications/cancelled", json!({"requestId": 1})); assert!(rig.reply(1, WAIT).unwrap().get("result").is_some()); @@ -265,7 +321,7 @@ fn initialize_cannot_be_cancelled() { #[test] fn progress_reaches_a_client_that_gave_a_token_before_the_reply() { - let mut rig = Rig::new(LONG, Duration::from_secs(60)); + let mut rig = Rig::new(Duration::from_secs(60)); rig.request(1, "tools/call", json!({"name": "command_run", "arguments": {"id": "progress.demo"}, "_meta": {"progressToken": "tok"}})); let mut seen = vec![]; let reply = loop { @@ -369,6 +425,7 @@ fn a_remote_call_stops_waiting_for_the_app_when_cancelled() { let addr = listener.local_addr().unwrap().to_string(); // An app that answers the connection's token, then takes the request and never answers. let (done, held) = mpsc::channel::<()>(); + let (asked, request_read) = mpsc::channel::<()>(); let app = std::thread::spawn(move || { let (conn, _) = listener.accept().unwrap(); let mut reader = BufReader::new(conn.try_clone().unwrap()); @@ -378,6 +435,7 @@ fn a_remote_call_stops_waiting_for_the_app_when_cancelled() { writeln!(&conn, "{}", json!({"id": auth["id"], "ok": true})).unwrap(); line.clear(); reader.read_line(&mut line).unwrap(); + asked.send(()).ok(); // Hold the connection open until the test is done with it (or for `WAIT`). let _ = held.recv_timeout(WAIT); drop(conn); @@ -385,8 +443,9 @@ fn a_remote_call_stops_waiting_for_the_app_when_cancelled() { let mut remote = crate::Remote::connect(&addr, "test").unwrap(); let token = cancel::CancelToken::new(); let raise = token.clone(); + // Cancel once the app holds the request (or has stopped, which ends the call by itself). std::thread::spawn(move || { - std::thread::sleep(Duration::from_millis(200)); + let _ = request_read.recv(); raise.cancel(); }); let r = cancel::scope(&token, None, || remote.call("engine.execute", json!({"command": "document.export"})));