Skip to content

The agent that grows with you

test: MCP server lifecycle failure transitions on the long-lived host (C15)

teknium156ce6e2204fe
diff --git a/tests/e2e/core/parity/_helpers.py b/tests/e2e/core/parity/_helpers.py
index 91ef2127471..fb0c6dbc2b1 100644
--- a/tests/e2e/core/parity/_helpers.py
+++ b/tests/e2e/core/parity/_helpers.py
@@ -119,7 +119,8 @@ class ParityHome:
self.update_config(lambda cfg: cfg.setdefault("terminal", {}).__setitem__("cwd", str(self.project)))
-def build_parity_home(root: Path, base_url: str, *, grandchild: bool = True) -> ParityHome:
+def build_parity_home(root: Path, base_url: str, *, grandchild: bool = True,
+ death_tool: bool = False, mcp_timeout: int = 60) -> ParityHome:
"""Write the full fixture home under ``root`` (a tmp_path)."""
home = root / "home"
hermes_home = home / ".hermes"
@@ -149,14 +150,22 @@ def build_parity_home(root: Path, base_url: str, *, grandchild: bool = True) ->
"PARITY_MCP_CANARY": c["mcp"],
"PARITY_MCP_PID_LOG": str(ph.pid_log),
"PARITY_MCP_SPAWN_GRANDCHILD": "1" if grandchild else "0",
+ "PARITY_MCP_DEATH_TOOL": "1" if death_tool else "0",
"PARITY_TREE_TAG": tag,
# Only the MCP server and its descendants carry this one.
"PARITY_MCP_TREE_TAG": tag,
"PYTHONPATH": str(REPO_ROOT),
},
"connect_timeout": 60,
- "timeout": 60,
+ "timeout": mcp_timeout,
}}
+ # Interactive surfaces wait only ~1.5 s (mcp_discovery_timeout) for MCP discovery
+ # before the first agent build, BY DESIGN (a slow server must not block the
+ # shell; late tools arrive via refresh). Under a loaded box the fixture server's
+ # import alone can exceed that, so pin the documented knob high: the join returns
+ # the instant discovery finishes, and the first turn is deterministically complete.
+ cfg["mcp_discovery_timeout"] = 120
+ cfg["mcp_single_query_discovery_timeout"] = 120
# Keep turns hermetic and short: no title/aux model chatter decides anything here.
cfg.setdefault("display", {})["compact"] = True
(hermes_home / "config.yaml").write_text(yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8")
@@ -212,7 +221,7 @@ def build_parity_home(root: Path, base_url: str, *, grandchild: bool = True) ->
# Scripted provider -----------------------------------------------------------
-def parity_responder(nonce: str) -> Callable[[dict[str, Any]], Any]:
+def parity_responder(nonce: str, tool: str = MCP_TOOL_NAME) -> Callable[[dict[str, Any]], Any]:
"""Stateless script: call the MCP tool until a tool result exists, then answer.
Stateless so a retried request (or a second concurrent entrypoint request)
@@ -224,16 +233,16 @@ def parity_responder(nonce: str) -> Callable[[dict[str, Any]], Any]:
if any(m.get("role") == "tool" for m in body.get("messages") or []):
return Text(FINAL_ANSWER)
args = {"nonce": nonce}
- if MCP_TOOL_NAME in _tool_names(body) or "tool_call" not in _tool_names(body):
- return ToolCall(MCP_TOOL_NAME, args)
+ if tool in _tool_names(body) or "tool_call" not in _tool_names(body):
+ return ToolCall(tool, args)
# Tool Search active: MCP tools sit in the deferred catalog behind the bridge.
- return ToolCall("tool_call", {"calls": [{"name": MCP_TOOL_NAME, "arguments": args}]})
+ return ToolCall("tool_call", {"calls": [{"name": tool, "arguments": args}]})
return respond
-def start_provider(nonce: str) -> FakeLLMServer:
- srv = FakeLLMServer(parity_responder(nonce))
+def start_provider(nonce: str, tool: str = MCP_TOOL_NAME) -> FakeLLMServer:
+ srv = FakeLLMServer(parity_responder(nonce, tool))
srv.start()
return srv
diff --git a/tests/e2e/core/parity/fixture_mcp_server.py b/tests/e2e/core/parity/fixture_mcp_server.py
index 9ecc19efea9..0749acef238 100644
--- a/tests/e2e/core/parity/fixture_mcp_server.py
+++ b/tests/e2e/core/parity/fixture_mcp_server.py
@@ -8,7 +8,10 @@ plumbing) instead of a registered-but-dead schema.
``PARITY_MCP_SPAWN_GRANDCHILD=1`` makes the server fork a long-lived grandchild at
startup (the shape of npx/uvx wrappers and servers with worker helpers) so
shutdown tests can prove Hermes reaps the whole process tree, not just its direct
-child. Every PID the server owns is appended to ``PARITY_MCP_PID_LOG`` so the test
+child. ``PARITY_MCP_DEATH_TOOL=1`` adds ``parity_die``, which kills the server while its
+own call is in flight, leaving a helper holding the stdio pipe open so no EOF ever
+arrives (the fast-death supervisor's target shape, #81995).
+Every PID the server owns is appended to ``PARITY_MCP_PID_LOG`` so the test
can check liveness of exactly the processes this fixture created.
"""
@@ -17,6 +20,8 @@ from __future__ import annotations
import os
import subprocess
import sys
+import threading
+import time
def _log_pid(kind: str, pid: int) -> None:
@@ -53,6 +58,20 @@ def main() -> None:
"""Return the parity fixture canary (echoing the caller's nonce)."""
return f"{os.environ.get('PARITY_MCP_CANARY', 'NO-CANARY')}:{nonce}"
+ if os.environ.get("PARITY_MCP_DEATH_TOOL") == "1":
+ @server.tool()
+ def parity_die(nonce: str = "") -> str:
+ """Crash this MCP server mid-call: the RPC never gets a response."""
+ # A helper that inherits our stdio keeps the pipe open after we die (the
+ # npx/uvx-wrapper shape), so the client never sees EOF: only the child
+ # liveness watch can end the call.
+ holder = subprocess.Popen([sys.executable, "-c", "import time\nwhile True: time.sleep(60)"])
+ _log_pid("pipe_holder", holder.pid)
+ _log_pid("dying_server", os.getpid())
+ threading.Timer(0.3, lambda: os._exit(3)).start()
+ time.sleep(3600)
+ return "unreachable"
+
server.run(transport="stdio")
diff --git a/tests/e2e/core/parity/test_mcp_lifecycle.py b/tests/e2e/core/parity/test_mcp_lifecycle.py
new file mode 100644
index 00000000000..408e9e72503
--- /dev/null
+++ b/tests/e2e/core/parity/test_mcp_lifecycle.py
@@ -0,0 +1,144 @@
+"""MCP server lifecycle on the long-lived host (issue class C15).
+
+Uses the tui_gateway stdio host (the Ink TUI's backend; the Desktop's WS backend
+runs the same MCP runtime) with the real stdio MCP fixture:
+
+* fast death: the MCP server crashes WHILE its call is in flight, leaving a helper
+ that inherited its stdio (npx/uvx wrapper shape) (#81995). The call must fail
+ as a tool error EXACTLY once (outcome uncertain: never silently replayed onto
+ the respawned server), the host must survive, the turn complete well inside the configured MCP call
+ timeout (bound 300 s: >10x the ~18 s observed idle, 12x under the 3600 s timeout), and a normal host
+ shutdown afterwards still reaps the pipe holder.
+* host crash: the host is SIGKILLed after a turn (no shutdown code runs at all).
+ The MCP server AND its grandchild must still be reaped (death supervisor +
+ process-group kill), because a crashed Desktop/TUI backend otherwise leaves a
+ pile of MCP processes behind on every restart.
+
+The parity matrix covers the normal-shutdown reap and the healthy call on every
+entrypoint; this file covers the two failure transitions.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import os
+import signal
+import sys
+import time
+import uuid
+from pathlib import Path
+
+import pytest
+
+from tests.e2e.core.parity._drive_rpc import READY_TIMEOUT, RpcClient, spawn_tui_gateway
+from tests.e2e.core.parity._helpers import (
+ FINAL_ANSWER,
+ build_parity_home,
+ collect_observation,
+ describe_pids,
+ kill_tagged,
+ mcp_pids,
+ start_provider,
+ terminate,
+ wait_no_orphans,
+ wait_until,
+)
+
+# Same rationale as test_entrypoint_parity: Linux /proc scans, and the bypass is
+# for teardown of reparented orphans carrying this run's unique tag only.
+pytestmark = [
+ pytest.mark.skipif(not sys.platform.startswith("linux"), reason="process-tree checks use /proc"),
+ pytest.mark.live_system_guard_bypass,
+]
+
+MCP_DIE_TOOL = "mcp__parity__parity_die"
+MCP_CALL_TIMEOUT = 3600
+FAST_DEATH_BOUND = 300.0
+REAP_BOUND = 30.0
+
+
+def tui_host(tmp_path: Path, *, tool: str | None = None, **home_kwargs):
+ nonce = uuid.uuid4().hex[:8]
+ srv = start_provider(nonce, tool) if tool else start_provider(nonce)
+ ph = build_parity_home(tmp_path, srv.base_url, **home_kwargs)
+ proc, cap = spawn_tui_gateway(ph)
+
+ def send(line: str) -> None:
+ assert proc.stdin is not None
+ proc.stdin.write(line + "\n")
+ proc.stdin.flush()
+
+ try:
+ rpc = RpcClient(send, cap.stdout_lines)
+ rpc.wait_event("gateway.ready", timeout=READY_TIMEOUT)
+ yield ph, srv, proc, cap, rpc
+ finally:
+ if proc.poll() is None:
+ if proc.stdin is not None and not proc.stdin.closed:
+ with contextlib.suppress(OSError):
+ proc.stdin.close()
+ try:
+ proc.wait(timeout=60)
+ except Exception:
+ terminate(proc)
+ kill_tagged(ph)
+ srv.stop()
+
+
+def _alive(pid: int) -> bool:
+ try:
+ with open(f"/proc/{pid}/stat", "rb") as fh:
+ return fh.read().rsplit(b")", 1)[1].split()[0] != b"Z"
+ except OSError:
+ return False
+
+
+def _turn(rpc: RpcClient, timeout: float) -> str:
+ sid = rpc.call("session.create", {}, timeout=READY_TIMEOUT)["session_id"]
+ rpc.call("prompt.submit", {"session_id": sid, "text": "Use the parity tool, then report."}, timeout=READY_TIMEOUT)
+ done = rpc.wait_event("message.complete", lambda e: e.get("session_id") == sid, timeout=timeout)
+ return str((done.get("payload") or {}).get("text") or "")
+
+
+def test_mcp_server_death_mid_call_fails_fast_and_the_turn_completes(tmp_path: Path) -> None:
+ with tui_host(tmp_path, tool=MCP_DIE_TOOL, grandchild=False, death_tool=True,
+ mcp_timeout=MCP_CALL_TIMEOUT) as (ph, srv, proc, cap, rpc):
+ started = time.monotonic()
+ text = _turn(rpc, timeout=FAST_DEATH_BOUND)
+ elapsed = time.monotonic() - started
+
+ obs = collect_observation("tui_gateway", ph, srv, text)
+ assert FINAL_ANSWER in text, f"turn did not complete after the MCP server died: {text[-300:]!r}"
+ assert obs.tool_results, "the dead MCP call produced no tool result for the model"
+ assert not any(ph.canaries["mcp"] in r for r in obs.tool_results), obs.tool_results
+ assert elapsed < FAST_DEATH_BOUND, elapsed
+ # The server really died mid-call (not a schema/dispatch error before the RPC).
+ dying = mcp_pids(ph).get("dying_server") or []
+ # Exactly once: a call that died mid-flight may have had side effects, so it
+ # must surface as outcome-uncertain, never be silently replayed.
+ assert len(dying) == 1, (
+ f"parity_die ran {len(dying)}x (want exactly 1): {mcp_pids(ph)}; results {obs.tool_results}")
+ wait_until(lambda: not _alive(dying[0]), REAP_BOUND, "fixture MCP server exit")
+ assert proc.poll() is None, f"host died with the MCP server:\n{cap.stderr[-2000:]}"
+
+ assert mcp_pids(ph).get("pipe_holder"), "fixture pipe holder never started"
+ proc.stdin.close()
+ proc.wait(timeout=60)
+ survivors = wait_no_orphans(ph, timeout=REAP_BOUND)
+ assert not survivors, f"dead server's pipe holder survived host shutdown: {describe_pids(survivors)}"
+
+
+def test_host_crash_still_reaps_the_mcp_server_and_its_grandchild(tmp_path: Path) -> None:
+ with tui_host(tmp_path) as (ph, srv, proc, cap, rpc):
+ text = _turn(rpc, timeout=READY_TIMEOUT)
+ assert FINAL_ANSWER in text, text[-300:]
+ pids = mcp_pids(ph)
+ assert pids.get("server") and pids.get("grandchild"), f"MCP tree never spawned: {pids}"
+
+ os.kill(proc.pid, signal.SIGKILL) # no atexit, no shutdown hook, no finally
+ proc.wait(timeout=30)
+
+ survivors = wait_no_orphans(ph, timeout=REAP_BOUND)
+ assert not survivors, (
+ f"MCP tree survived a host crash for {REAP_BOUND}s: {describe_pids(survivors)} (pid log {pids})")