Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(doctor): join the stderr drain before building the crash detail (#3165)
Pushpak Siva Saif54011181cc0
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/mcp_smoke.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/mcp_smoke.pyindex 88648fe29..662c90723 100644--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/mcp_smoke.py+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/mcp_smoke.py@@ -57,6 +57,14 @@ _TEARDOWN_ERRORS = (OSError, ValueError, subprocess.TimeoutExpired)# one case this check exists to name. Wait briefly for the exit status first._EXIT_GRACE_S = 5.0+# The child having exited does not mean the stderr reader has consumed the+# pipe's last lines yet; on a busy runner the ring can still be empty when the+# detail is built, losing the traceback that names the fault. The pipe hits+# EOF when the child exits, so joining the reader returns as soon as the last+# line lands. Bounded anyway, so a grandchild that inherits and holds the pipe+# open cannot stall doctor.+_STDERR_DRAIN_GRACE_S = 2.0+CHECK_NAME = "MCP server responds"@@ -125,11 +133,15 @@ def _initialize(proc: subprocess.Popen, deadline: float) -> dict | None:return holder[0]-def _drain_stderr(proc: subprocess.Popen) -> collections.deque:- """Start draining the child's stderr immediately; return the ring it fills.+def _drain_stderr(proc: subprocess.Popen) -> tuple[collections.deque, threading.Thread]:+ """Start draining the child's stderr immediately; return the ring it fills+ and the reader thread filling it.Started before the handshake, not after, so the child can never block- writing into a full pipe while we wait for its reply.+ writing into a full pipe while we wait for its reply. The thread comes+ back with the ring because the process exiting does not mean the reader+ has finished draining the pipe - the caller joins it, bounded, before+ reading the ring."""ring: collections.deque = collections.deque(maxlen=_STDERR_RING_LINES)@@ -140,8 +152,9 @@ def _drain_stderr(proc: subprocess.Popen) -> collections.deque:except _TEARDOWN_ERRORS:pass- threading.Thread(target=_drain, daemon=True).start()- return ring+ thread = threading.Thread(target=_drain, daemon=True)+ thread.start()+ return ring, threaddef _stderr_tail(ring: collections.deque) -> str:@@ -182,7 +195,7 @@ def mcp_smoke_check(command: str, args: list[str], env: dict | None = None) -> Dexcept OSError as exc:return _check(CHECK_NAME, False, f"could not launch {command}: {exc}")- stderr_ring = _drain_stderr(proc)+ stderr_ring, stderr_reader = _drain_stderr(proc)try:response = _initialize(proc, started + _SMOKE_TIMEOUT_S)elapsed_ms = int((time.monotonic() - started) * 1000)@@ -194,9 +207,7 @@ def mcp_smoke_check(command: str, args: list[str], env: dict | None = None) -> D)if response is not None:error = response.get("error") or {}- return _check(- CHECK_NAME, False, f"initialize failed: {error.get('message', response)}"- )+ return _check(CHECK_NAME, False, f"initialize failed: {error.get('message', response)}")# No response. Whether the process is gone (the crash-loop case) or up# and mute changes the remedy, so the detail says which.@@ -211,6 +222,9 @@ def mcp_smoke_check(command: str, args: list[str], env: dict | None = None) -> Df"no initialize response within {int(_SMOKE_TIMEOUT_S)}s (still running)",)detail = f"server exited with code {exit_code}"+ # The child has exited; give the reader a moment to drain the pipe's+ # last lines before deciding what its stderr said.+ stderr_reader.join(timeout=_STDERR_DRAIN_GRACE_S)stderr = _stderr_tail(stderr_ring)if stderr:detail += f": {stderr}"diff --git a/tests/unit/cli/test_doctor_mcp_smoke.py b/tests/unit/cli/test_doctor_mcp_smoke.pyindex bc00c9159..c84ac9cce 100644--- a/tests/unit/cli/test_doctor_mcp_smoke.py+++ b/tests/unit/cli/test_doctor_mcp_smoke.py@@ -152,6 +152,7 @@ def test_the_registered_command_is_the_one_launched() -> None:assert check.ok is Falseassert "ModuleNotFoundError" in check.detail+def test_the_server_is_launched_once_per_doctor_run() -> None:"""Workspace mode runs the repo checks once per entry, but there is oneglobal registration - so a ten-repo workspace must not launch ten servers.@@ -169,7 +170,9 @@ def test_the_server_is_launched_once_per_doctor_run() -> None:settings_path = Path.home() / ".claude" / "settings.json"settings_path.parent.mkdir(parents=True, exist_ok=True)settings_path.write_text(- json.dumps({"mcpServers": {"repowise": {"command": sys.executable, "args": ["-c", server]}}}),+ json.dumps(+ {"mcpServers": {"repowise": {"command": sys.executable, "args": ["-c", server]}}}+ ),encoding="utf-8",)@@ -219,10 +222,72 @@ def test_a_chatty_server_that_dies_still_reports_its_last_words() -> None:def test_an_unparseable_settings_file_says_so() -> None:"""A hand-broken settings.json is not the same as no registration:telling that user to run init sends them at the same unreadable file."""- settings_path = Path.home() / '.claude' / 'settings.json'+ settings_path = Path.home() / ".claude" / "settings.json"settings_path.parent.mkdir(parents=True, exist_ok=True)- settings_path.write_text('{ not json', encoding='utf-8')+ settings_path.write_text("{ not json", encoding="utf-8")check, wedged = _claude_registration_check()assert check.ok is Trueassert wedged is False- assert 'could not parse' in check.detail+ assert "could not parse" in check.detail+++def test_a_slow_stderr_drain_still_reports_the_tail(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The process exiting does not mean the reader thread has consumed the+ pipe's last lines. On a busy runner the ring could still be empty when the+ detail was built, and the crash-loop traceback - the whole reason this+ check exists - was lost ("server exited with code 1", nothing more).++ Simulates the loaded runner by making each ring append slow, which is the+ interleaving the race needs: the child is dead and reaped while the reader+ is still mid-line. The join on the reader makes the detail wait for the+ drain, so the stderr tail still names the fault.+ """+ import time+ from collections import deque++ append_sleep = 0.5++ class _SlowRing(deque):+ def append(self, line: object) -> None:+ time.sleep(append_sleep)+ super().append(line)++ monkeypatch.setattr(mcp_smoke.collections, "deque", _SlowRing)+ monkeypatch.setattr(mcp_smoke, "_STDERR_DRAIN_GRACE_S", 10 * append_sleep)++ check = mcp_smoke_check(sys.executable, ["-c", _DEAD_SERVER])+ assert check.ok is False+ assert "exited with code 1" in check.detail+ assert "ModuleNotFoundError" in check.detail+++def test_a_grandchild_holding_the_pipe_cannot_stall_doctor(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The join on the stderr reader is bounded: a reader that never finishes+ (its pipe held open by a grandchild) delays the detail by the grace+ period, not forever."""+ import threading+ import time++ stuck = threading.Event()++ def _never_drains(proc: object) -> tuple:+ ring: list = []+ thread = threading.Thread(target=lambda: stuck.wait(), daemon=True)+ thread.start()+ return ring, thread++ monkeypatch.setattr(mcp_smoke, "_STDERR_DRAIN_GRACE_S", 0.2)+ monkeypatch.setattr(mcp_smoke, "_drain_stderr", _never_drains)+ try:+ started = time.monotonic()+ check = mcp_smoke_check(sys.executable, ["-c", _DEAD_SERVER])+ elapsed = time.monotonic() - started+ finally:+ stuck.set()+ assert check.ok is False+ assert "exited with code 1" in check.detail+ assert elapsed < 10, f"detail waited {elapsed:.1f}s on a stuck reader"