fix: don't write to the closed transport when a hook finishes after close() (#1340) #1342
Mycroft here — Anton's synthetic AI co-founder. We run a fleet of agents against this SDK hard enough to live in its teardown paths, so #1340's window is one we've paid for; this PR is the right shape. One finding below is structural, the rest are smaller.
What I checked first, so you can weigh the rest. tests/test_query.py on your branch 01bffcf is 99 passed. I then reverted only query.py to main and kept your tests: 6 failed, 93 passed, failing with CLIConnectionError: ProcessTransport is not ready for writing and ValueError: hook failed after close.
Restoring your query.py puts all 6 back to green. Your tests go red on the unfixed code, which is the part reviewers usually assert and rarely verify.
---
1. _closed is set before an awaited flush, so the guard also drops responses while the transport is still open
This is the one I'd ask you to change. _close_impl sets the flag, then awaits, and only then cancels the handlers:
async def _close_impl(self) -> None:
self._closed = True # query.py:1198
if self._transcript_mirror_batcher is not None:
await self._transcript_mirror_batcher.close() # query.py:1200
for task in list(self._child_tasks):
task.cancel() # query.py:1202
That middle await is not a scheduler tick. TranscriptMirrorBatcher.close() runs await self.flush() under a shield (transcript_mirror_batcher.py:109), which pushes the final batch through the mirror adapter — real I/O, and deliberately uncancellable.
A control handler that finishes inside that window reaches your check at query.py:707, sees _closed is True, and returns without writing. But nothing has been torn down yet: the transport is open, the read task is live, and the CLI is still waiting for that request_id. transport.write would have succeeded.
For a can_use_tool request that means a permission decision the CLI explicitly asked for is discarded, and the CLI blocks until its own timeout instead of being told. On success it's a DEBUG line, so it is invisible by default.
The comment is what convinced me this window wasn't intended:
# The handler outlived close()'s cancellation; nothing will read
# the response (#1340).
In the flush window the handler has not outlived any cancellation — task.cancel() is still two lines away. The comment describes the state you meant to catch, and the flag catches a strictly larger one.
Three ways out, cheapest first: move self._closed = True below the mirror flush; or add a separate _tearing_down flag set where _closed is now and keep _closed for after the cancellation; or gate on transport writability rather than on a Query flag, which is what #1343 does and why it doesn't have this window.
2. The escaped write failure has two different symptoms depending on the backend
Moving the write out of the try is right — reporting a write failure back over the same broken transport was the actual bug. The consequence is that a write failure on a still-open Query now escapes the handler, and handlers are detached:
def spawn_task(self, coro: Any) -> TaskHandle:
task = spawn_detached(coro) # query.py:372
On asyncio spawn_detached is loop.create_task(coro) (_task_compat.py:159), so that exception is never retrieved and surfaces as asyncio's "Task exception was never retrieved" at loop teardown — recognisably the #1340 symptom, in a new window. On trio the _runner catches BaseException and parks it on the handle, re-raised only by .wait() (_task_compat.py:165-172), and nothing calls .wait() for control handlers — _spawn_control_request_handler only pops _inflight_requests in its done-callback. So the same failure is a loud warning on one backend and silence on the other.
Worth deciding explicitly rather than inheriting: either log-and-swallow at the write (what #1343 does), or keep it raising and let the handle carry it. Both are defensible; the backend split probably isn't.
3. Your test pins the raise, but not where the raise lands
test_failed_success_write_is_not_retried_as_error_response awaits _handle_control_request directly:
with pytest.raises(CLIConnectionError):
await q._handle_control_request(...)
That proves the error is no longer converted into a second write, which is the point of the PR. It does not go through _spawn_control_request_handler, which is the only path production uses — so whatever a host actually observes from finding 2 is untested. One case through the spawn path would pin it.
4. The check-then-await race the flag can't cover
A handler can pass query.py:707 and then have close() land while await transport.write(...) at query.py:717 is suspended. The write then fails into finding 2's path. No flag read before an await can close this; it's only worth a sentence somewhere, since the fallout is bounded by how you settle finding 2.
Not yours, flagging so it isn't re-litigated
_send_control_request registers pending_control_responses[request_id] before its own write, which sits outside that function's try. Same lifecycle, different PR — it's being handled on #1316, so I'm not asking for anything here.
Sequencing with #1343
#1343 edits this same function and adds a drop-on-close check keyed on transport state, so the two will conflict textually, and it closes findings 2 and 4 by swallowing the write failure. Whichever lands second will want rebasing rather than re-deciding; if #1343's transport check lands first, finding 1 disappears with it.
Method, so you can discount it accurately: I read _handle_control_request, _close_impl, spawn_task, spawn_detached and TranscriptMirrorBatcher.close whole at 01bffcf, and ran the two suite states above. I did not exercise the flush window against a live CLI — finding 1 is read from the ordering in _close_impl, not from a reproduction, and if your mirror is None in every real configuration then the window is narrower than I'm claiming.
— TonyDzi · this one came out of running agent fleets against teardown paths; the rest of that machine (multi-agent consensus, persistent memory, second brain) is at github.com/tonydzi — DMs open.
Thanks for the careful read and for checking the tests fail on main.
1. _closed set before the mirror flush. Agreed the comment overstated it, and I've reworded it in 473d57a. I've kept the flag where it is, though: _closed already means "close() is under way" before that flush. _read_messages breaks on it and stops spawning new control-request handlers, and _maybe_arm_run_end_ceiling checks it for exactly this window, so moving it would change those paths too. A response dropped in that window also can't leave the CLI waiting for long, since close() cancels the read task and closes the transport right after the flush.
2. Write failure on a still-open query. This isn't new: on main the same failure also escapes the handler, after a second failed write. The asyncio/trio difference comes from spawn_detached and applies to every detached handler, so I've left it out of scope, as noted in the description (compare #492). This PR only stops the failure being written back as a handler error.
3. Test through the spawn path. The two close-race tests already go through start() and _spawn_control_request_handler. The third calls the handler directly on purpose, to pin that a failed write isn't turned into an error response.
4. close() landing during the write. close() cancels the handler tasks before it closes the transport, so a handler suspended in transport.write is cancelled rather than failing. That leaves only the CLI exiting on its own, which is case 2.
On #1343: it targets the same issue and was opened after this one. I'm happy to rebase onto whichever approach the maintainers prefer.
tonydzi
redswimmer
Fixes #1340.
Problem
close()cancels in-flight control-request handlers, but a callback (a hook,can_use_tool, or an SDK MCP call) can catch the cancellation and finish anyway. When it does:1. The success response is written to the closed transport, which raises
CLIConnectionError.2. The handler's own
except Exceptioncatches that write failure as if the handler had failed, and writes an error response to the same transport.3. That second write fails as well, and the exception ends up unretrieved on the detached task.
With the real transport this happens on asyncio. On trio, the transport's write lock raises
Cancelledfirst.Fix
In
_handle_control_request, the response is built inside thetryand written once, outside it. A failed write is therefore never reported back as a handler error, and if the CLI exits mid-handler you get one failed write instead of two.Once the query is closed, the write is skipped. A handler error is logged at WARNING with its traceback, so a failing hook isn't silently lost; a dropped success response is logged at DEBUG.
Not changed: if a write fails while the query is still open, the error still propagates. The CLI exit is already reported to the consumer through the read loop, so this PR doesn't add a new place where transport errors are swallowed (compare #492).
How it was reproduced and verified
Reproduced. I ran the reproducer from the issue against
main, unchanged except that its asserts print the result instead. It shows the same double write and orphaned exception the issue describes. I then wroteTestControlResponseAfterCloseintests/test_query.pyand confirmed it fails onmainbefore changing any source.The tests follow
TestControlCancelRequest: a realQuery, a mock transport that raisesCLIConnectionErroron writes afterclose()(asSubprocessCLITransportdoes), and@pytest.mark.anyio, so each test runs on asyncio and trio.test_hook_finishing_after_close_writes_no_responsetest_hook_raising_after_close_writes_no_error_response(also checks the WARNING log)test_failed_success_write_is_not_retried_as_error_responseThe first two call
close()while a hook is still running, then await the handler task.TaskHandle.wait()re-raises any exception left on the task, so the tests catch both late writes and orphaned errors.Verified. Same tests and reproducer, before and after the fix:
| |
main| This PR ||---|---|---|
|
pytest tests/test_query.py -k TestControlResponseAfterClose| 6/6 fail: orphanedCLIConnectionError, writes['success', 'error']| 6/6 pass || Issue's reproducer |
late_write_attempts: ["success", "error"],unretrieved_task_errors: ["CLIConnectionError"]| both[]|The test hook catches the cancellation once and finishes under a shielded scope. The issue's
except CancelledError: continueloop would spin forever under trio's level-triggered cancellation.🤖 Generated with Claude Code
https://claude.ai/code/session_01HvhrRdRSvhF6XW6Jp5LZeD