Skip to content

fix: wait for a stopped windows mcp server before deleting its capture - #47880

Open
winnythedev wants to merge 1 commit into
mainfrom
fix/47853-wait-for-mcp-server-exit
Open

winnythedev wants to merge 1 commit into
mainfrom
fix/47853-wait-for-mcp-server-exit

Conversation

@winnythedev

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: On Windows, a script cron's MCP server stop deletes the server's stderr capture file instead of leaving it behind with a warning.

On Windows, McpToolClient.close() can leave an mcp-stderr-<random>.log file in the temp folder and log could not delete MCP stderr capture. The same race fails Backend Tests (Windows) (6) at session teardown, through the strict temp-residue check, after test/test_cron_script_mcp_answer_time.py::test_an_unanswered_call_raises_by_the_answer_time_and_stops_its_server, on PRs that do not touch this code (twice on 5 Dec, both on bases that already carry #47517).

Why it matters

Every script cron that calls an MCP tool on Windows can leave a stray capture file per stopped server, and nothing deletes it later. On CI the leftover turns an unrelated PR's Windows shard red.

Not a goal

  • Changing kill_popen_tree, job objects, process groups or any other process-isolation code.
  • The .cmd wrapper case, where a grandchild server can still hold the capture after cmd.exe exits.
  • A teardown that outlasts the 5 s grace wait (the TimeoutExpired fallback); it is named as a known limit in the code and the spec.

What changed (motivation → approach → change)

  • Symptom: the capture delete is refused and the file stays behind.
  • Cause: on Windows close() calls platform_compat.kill_popen_tree(proc) (taskkill /T /F, then proc.kill()), then proc.wait(timeout=_STOP_GRACE_SECS), then deletes the capture under _capture_lock. CPython's Windows Popen.terminate() (which kill() is) catches the PermissionError that TerminateProcess raises on a process whose exit has begun, reads GetExitCodeProcess, and stores it as returncode. _wait() calls WaitForSingleObject only while returncode is None. So wait() returns at once while the server still holds its inherited stderr handle, and Windows refuses the delete.
  • Change: close() clears self._proc.returncode after kill_popen_tree and before wait(), so wait() waits on the process handle Popen keeps open. A server that has already exited still returns at once. A shortcut: comment names the timeout-fallback limit. The "Script-mode MCP server lifetime" spec sentence in docs/system-specs/modules/learn-cron-dashboard.md says the same.

Backwards compatibility

Compatible: only the Windows stop path waits for a server that is already being stopped; a server that exited returns at once, as before.

Removes nothing: the diff adds a wait on an existing path and takes away no key, record, path or function.

Tests

  • test/test_cron_script_mcp_close.py::test_windows_close_deletes_the_capture_only_once_the_stopped_server_lets_go_of_it (new): a fake Windows server teardown (the first TerminateProcess starts the stop, a second is refused, the exit code reads back, the process object is signalled only when the test releases it) under CPython's Windows kill/poll/wait. It drives the real close() Windows branch and the real kill_popen_tree, with IS_POSIX and kill_process_tree patched through the platform_compat facade as test/test_facade_mirror_guards.py requires. It asserts the capture is gone and no WARNING was logged. It waits on events only, bounded by default_timeout().

Proof: PROVEN test/test_cron_script_mcp_close.py::test_windows_close_deletes_the_capture_only_once_the_stopped_server_lets_go_of_it (head 4054dbd)

Verified by test on Linux x86_64 with the platform flag patched; this relies on CI's Windows lane for the real-platform run.

Checks run locally on Linux x86_64 (Python 3.12):

  • The new test repeated 200 times: 200 of 200 red on main, 200 of 200 green with the fix.
  • A throwaway repro (not in this PR) of the answer-time test's body with a real stub server, the real close() Windows branch and CPython's Windows kill/wait semantics, refusing the delete while any process holds the file open: on main, forced 20 of 20 and natural 4 of 400 (given-up and end-of-run paths) left the capture with the product's WARNING; with the fix, 0 of 20 and 0 of 400.
  • Nearby inputs, with the fix: the given-up call and the end-of-run close of a kept server (both above); a server already gone before close() (deleted); taskkill failing so kill() stops the server (deleted). Not covered: a .cmd wrapper's grandchild and a teardown longer than the grace wait (both out of scope, see Not a goal).
  • test/test_cron_script*.py and test/test_facade_mirror_guards.py: 561 passed, 1 skipped. test/test_wait_discipline_ratchet.py and test/test_flake_pattern_ratchet.py green in committed-baseline and PR-base modes. test/test_interrupted_children_spawn_unblocked.py green.
  • scripts/local-gate.py --tree-scans against upstream main: related tests 1150 passed. Tree-scan shard 2 passed. Shard 1 had 16 reds, all in files this PR does not touch, that come from this host (child interpreters that cannot load a system library, a missing pytest plugin, a coverage version, load-timed probes), plus one real red from this PR's first draft (test_interrupted_children_spawn_unblocked.py counting the fake's terminate()), fixed by renaming the fake's method and re-run green.
  • black, isort, flake8, mypy, comment-history, brand, agent-sdk-boundary, file-line-cap, docs-lint, and semgrep 1.78.0 against the merge-base: clean.

Review (multi-model interrogate)

Independent reviewers (three valid reviews plus one re-check of the revised hunks) found no critical issue.

  • Acted on: the spec sentence overstated the guarantee for the timeout fallback (now qualified, and a shortcut: comment names it); the test thread could outlive a failed wait_until (now released and joined in finally); the re-check's clearer wording of that comment.
  • Dismissed: "the Windows wait ignores the given-up zero grace" (warning). A zero wait would bring the leftover back on exactly the given-up path this fixes; the Windows branch already waited up to 5 s on any server its kill() stopped, and this change only adds that wait for a server whose teardown has already begun. "A second close() call" (warning): callers close once, from KeptMcpServers and the run's finally.

Manual verification

N/A — the fix is Windows-only logic, proven by the unit test and the repro above on Linux; CI's Windows lane runs it on the real platform. No live dashboard or gateway run was done.

Real-machine verification

Machine: own computer, Linux x86_64.
Before (main dcc6fd1): python -m pytest test/test_cron_script_mcp_close.py -n0 -q -> 1 failed (close() deleted the capture before the server let go of it), 6 passed; the test repeated 200 times -> 200 failed; the forced repro -> 20 of 20 left the capture.
After (head 4054dbd): the same commands -> 7 passed; 200 of 200 passed; the forced repro 0 of 20.
Cleanup: own computer; throwaway repro files removed from the tree.

Related Issues

Fixes #47853. Completes #47487 (fixed by #47517).

Overlap: open #43906 also edits close() in src/kiro_crew/cron_script_mcp.py (it adds a working-directory cleanup after the capture delete, a different line); #43611 edits other parts of the same file. Many open PRs edit docs/system-specs/modules/learn-cron-dashboard.md; this PR changes one sentence of "Script-mode MCP server lifetime" and is rebased onto current main.

Sibling sweep

Swept: git grep -n 'kill_popen_tree(' -- src/
Sibling: src/kiro_crew/dashboard_verify.py:1016 -- not affected -- the same kill then wait shape, but its profile delete already retries until a deadline
Sibling: src/kiro_crew/mcp_gateway/footprint_probe.py:272 -- not affected -- deletes no file the child inherited after the wait
Sibling: src/kiro_crew/apps/git_install.py:270 -- not affected -- same kill then wait shape, but a checkout it cannot delete is reported through rmtree_force's result instead of left silently; out of this issue's scope

Pattern harvest

Not generalizable: only this caller deletes a file the stopped child inherited right after kill_popen_tree and wait(), and changing kill_popen_tree itself is out of scope.

Checklist

  • A Conventional Commits title (feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert: ...); PR Hygiene does not count commits
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (if applicable)
  • No secrets, credentials, or internal references in the diff

Contribution License Agreement

Contributions are accepted under the project's Apache-2.0 license; see the Licensing section of CONTRIBUTING.md.

On Windows, close() stops a script-mode MCP server with kill_popen_tree,
whose closing Popen.kill() runs after taskkill. TerminateProcess is
refused on a process whose exit has begun, and CPython then stores the
exit code, so the wait() that follows returns at once while the server
still holds the stderr capture it inherited. Windows refuses the
delete, close() logs "could not delete MCP stderr capture" and the
file stays behind, which also fails the Windows test shard's strict
residue check after the answer-time test.

close() now clears the stored code before it waits, so wait() waits on
the process handle Popen keeps open. A server that has already exited
still returns at once. A new test drives the real close() Windows
branch and the real kill_popen_tree over a fake server teardown.

Fixes #47853
@winnythedev
winnythedev requested review from a team and KiroCrewCaptain as code owners December 5, 2026 19:23
@github-actions github-actions Bot added the readiness: checking Automated validation is still running label Dec 5, 2026
@github-actions

github-actions Bot commented Dec 5, 2026

Copy link
Copy Markdown
Contributor

UX Review (Opus 5.5) — ⏭️ skipped

Revision 4054dbdd2ff612ef9bd5d42047649f655e425fed touches no user-facing surface (no changes under website/ or committed screenshots), so the UX review was skipped. Does not block merge.

@github-actions

github-actions Bot commented Dec 5, 2026

Copy link
Copy Markdown
Contributor

Design Review (Opus 5.5) — ✅ PASS

Design-level review of 4054dbdd2ff612ef9bd5d42047649f655e425fed — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS does not.

Design-Verdict: PASS

Nothing blocks. The fix targets the real cause, the exit code that CPython's Windows kill() records, and leaves the code that stops the process tree alone.

Notes

  • Every kill_popen_tree caller that then calls wait() gets the same early return. If clearing returncode happened inside platform_compat.kill_popen_tree, one owner would fix all of them. The sibling sweep shows those callers tolerate the early return today, so this can be a follow-up.
  • Setting Popen.returncode = None by hand depends on how CPython implements Popen internally. A test that fails if a future CPython changes that would let the fix fail loudly instead of quietly bringing the leftover file back.

[DESIGN-REVIEWED] 4054dbd

Description read

[DESCRIPTION-READ] 260f57e1686c8765300456e104a6d16a07106bf0cfc23b2dcb7a9e0069723cbe

That sha256 names everything this verdict read: the PR description, plus the 1 evidence file(s) the workflow collected from it and handed this review. It covers that evidence because the media strip replaces every attachment URL with the same placeholder, so an edit swapping one attachment for another would leave the description's captured text identical while what this review judged changed. Recompute it with .github/scripts/pr-description-capture.sh over the same inputs; if it differs, the description or that evidence changed after this verdict was formed and any finding drawn from either is unproven.

@github-actions

github-actions Bot commented Dec 5, 2026

Copy link
Copy Markdown
Contributor

First Principles Review (Opus 5.5) — ✅ PASS

Premise-level review of 4054dbdd2ff612ef9bd5d42047649f655e425fed — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS does not.

First-Principles-Verdict: PASS

The fix is in the caller, but the stale exit code comes from the shared helper. Whether to change the helper is outside this PR's stated goal, so that is a note, not a blocker.

Not checked: whether CPython's Windows Popen.kill() really records returncode when TerminateProcess refuses a process that is already stopping.

Notes

  • Item 1 — symptom-level: kill_popen_tree (platform_compat_kill.py:571-572) ends with proc.kill(), which on Windows can record an exit code before the process has let go of its handles. That makes every later wait() return early for all 15 callers (grepped kill_popen_tree\( under src/: 16 hits, one of them the definition). This PR patches one caller with self._proc.returncode = None, and ## Not a goal deliberately leaves the helper alone. Subtraction: defer. The two-line caller patch is the smaller change for now. Retire it once the helper stops leaving a stale returncode.

What this change ships

Inventory (3 items) — 2 justified

Intent: when a script cron stops an MCP server on Windows, it should delete the server's stderr capture file instead of leaving it behind with a warning. This is a FIX.

  1. On Windows, stopping a server now waits until the process has actually exited before deleting its stderr capture — symptom-level (the stale exit code comes from kill_popen_tree)
  2. The spec sentence describing Windows capture deletion and its timeout limit — justified
  3. A regression test simulating the Windows teardown race — justified

[FIRST-PRINCIPLES-REVIEWED] 4054dbd

Description read

[DESCRIPTION-READ] aed92b04f1323d61c153435d0ae5271f9b0b3e60852e387d12324e0ae905089f

That sha256 names the PR description this verdict read. Recompute it with .github/scripts/pr-description-capture.sh; if it differs, the description changed after this verdict was formed and any finding drawn from the description is unproven.

@github-actions

github-actions Bot commented Dec 5, 2026

Copy link
Copy Markdown
Contributor

Opus 5.5 Review — ✅ no blocking findings

Reviewed 4054dbdd2ff612ef9bd5d42047649f655e425fed — this comment is updated in place on each push.

Review details

No findings.

[OPUS-REVIEWED] 4054dbd

Verdict parsed from the review's SHA-scoped output markers for commit 4054dbdd2ff612ef9bd5d42047649f655e425fed.

False positive or not applicable? A repository writer can comment:
/ai-review override fable 4054dbdd2ff612ef9bd5d42047649f655e425fed false-positive: <reason, 20 to 500 characters>

@github-actions

github-actions Bot commented Dec 5, 2026

Copy link
Copy Markdown
Contributor

GPT 6.1 Review — ✅ no blocking findings

GPT 6.1 completed its review of 4054dbdd2ff612ef9bd5d42047649f655e425fed and found no blocking issues.

This comment is updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] 4054dbd

False positive or not applicable? A repository writer can comment:
/ai-review override gpt 4054dbdd2ff612ef9bd5d42047649f655e425fed false-positive: <reason, 20 to 500 characters>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

readiness: checking Automated validation is still running

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Flaky: the MCP answer-time test still leaves an mcp-stderr-*.log on Windows; close() deletes it while the stopped server holds it

1 participant