craft-testkit: close waits for the rest of the MCP child's stderr after it exits

close waited for the stderr thread only as long as close_grace, so with a
short or zero grace the bytes still in the pipe when the child exited could
be missing from CloseOutcome::stderr. It now waits up to 5 s after the child
exits, and only a process that keeps the child's stderr open waits that long.
This commit is contained in:
dotCooCoo committed 2026-11-25 20:07:39 -08:00
1 parent 20f1cddbc9
commit 3a4427a57f
3 files changed
+28 -4

No files matched your search

+1 -1
View File
@@ -251,7 +251,7 @@ The `mcp` feature adds `craft_testkit::mcp` and the `serde_json` dependency. The
| `list_tools()` | Reads `tools/list` pages through `nextCursor` and returns the tools as sent. More than `max_pages` pages returns `TooManyPages`, and tools that add up to more than `max_line_bytes` of JSON return `ToolListTooLarge`. |
| `notify(method, params)` | Sends a notification, which has no id and gets no reply. |
| `take_notifications()` | Returns the notifications kept so far without waiting. |
| `close()` | Closes the child's stdin, waits for it to exit, stops it after the grace period, and returns its exit status, whether it was stopped, and the stderr kept. |
| `close()` | Closes the child's stdin, waits for it to exit, stops it after the grace period, and returns its exit status, whether it was stopped, and the stderr kept. After the child exits, it waits up to 5 s for the rest of stderr to be read. |
While a call waits, the client answers the child's `ping` with an empty result and its other requests with error -32601. A line on stdout that is not a JSON-RPC 2.0 message, a reply with neither or both of `result` and `error`, a line over the length limit, a missed deadline and the end of stdout each return an error, close the connection and stop the child; later calls return `Closed`. Dropping an `McpChild` stops and reaps a child that is still running. Setup returns a `Result` and nothing in the module panics.
+9 -2
View File
@@ -41,6 +41,10 @@ const READ_QUEUE: usize = 4;
const WRITE_QUEUE: usize = 64;
/// How often [`McpChild::close`] checks whether the child has exited.
const EXIT_POLL: Duration = Duration::from_millis(10);
/// How long [`McpChild::close`] waits, after the child has exited, for the stderr thread to read to
/// the end of stderr. Only a process that keeps the child's stderr open after the child exits makes
/// it wait this long.
const STDERR_DRAIN: Duration = Duration::from_secs(5);
/// Bytes of an unreadable stdout line quoted in a protocol error.
const PREVIEW: usize = 80;
/// The JSON-RPC error code for a method the client does not offer.
@@ -250,7 +254,10 @@ pub struct CloseOutcome {
/// The child was stopped because it did not exit within [`McpLimits::close_grace`], or an
/// earlier failure stopped it.
pub forced: bool,
/// The last [`McpLimits::stderr_tail_bytes`] bytes the child wrote on stderr.
/// The last [`McpLimits::stderr_tail_bytes`] bytes the child wrote on stderr. After the child
/// exits, [`McpChild::close`] waits up to 5 s for the rest of stderr to be read, whatever
/// [`McpLimits::close_grace`] is. A process the child started that keeps stderr open past that
/// leaves the bytes read so far.
pub stderr: Vec<u8>,
}
@@ -666,7 +673,7 @@ impl McpChild {
};
let stderr = match &self.stderr {
Some(tail) => {
let _ = tail.done.recv_timeout(grace);
let _ = tail.done.recv_timeout(STDERR_DRAIN);
tail.copy()
}
None => Vec::new(),
+18 -1
View File
@@ -20,6 +20,7 @@ const TESTS: &[(&str, Test)] = &[
("child_exits_before_initialize", child_exits_before_initialize),
("stderr_flood_does_not_block", stderr_flood_does_not_block),
("close_forces_and_reaps_unresponsive_child", close_forces_and_reaps_unresponsive_child),
("close_keeps_stderr_written_before_exit", close_keeps_stderr_written_before_exit),
];
pub fn run() -> ExitCode {
@@ -53,11 +54,17 @@ pub fn run() -> ExitCode {
/// Runs as the child: `server` answers `initialize` with the version asked for and every tool call
/// with `ECHO_VAR`, and exits when its stdin closes; `flood` also writes `FLOOD` bytes and `END` on
/// stderr before each reply; `silent` reads and never answers; `stubborn` answers but does not
/// exit when its stdin closes; `exit` exits at once with code 3.
/// exit when its stdin closes; `exit` exits at once with code 3; `goodbye` writes `FLOOD` bytes and
/// `BYE` on stderr and exits without reading.
fn serve(mode: &str) -> ExitCode {
if mode == "exit" {
return ExitCode::from(3);
}
if mode == "goodbye" {
let mut err = std::io::stderr();
let written = err.write_all(&vec![b'e'; FLOOD]).and_then(|()| err.write_all(b"BYE"));
return if written.is_ok() { ExitCode::SUCCESS } else { ExitCode::FAILURE };
}
let stdin = std::io::stdin();
let mut out = std::io::stdout();
for line in stdin.lock().lines() {
@@ -159,3 +166,13 @@ fn close_forces_and_reaps_unresponsive_child() -> Result<(), String> {
let out = c.close().map_err(|e| e.to_string())?;
check(out.forced && out.status.is_some_and(|s| !s.success()), || format!("close: {out:?}"))
}
fn close_keeps_stderr_written_before_exit() -> Result<(), String> {
let limits = McpLimits { stderr_tail_bytes: 4096, close_grace: Duration::ZERO, ..McpLimits::default() };
let mut c = start("goodbye", limits)?;
// The child's stdout ends when it exits, after its stderr is written.
let err = c.initialize(PROTOCOL_VERSION).err();
check(matches!(err, Some(McpError::Ended | McpError::Io { .. })), || format!("initialize: {err:?}"))?;
let out = c.close().map_err(|e| e.to_string())?;
check(out.stderr.len() == 4096 && out.stderr.ends_with(b"eeeBYE"), || format!("kept {} bytes of stderr", out.stderr.len()))
}