Skip to content

Fix stdio_client BrokenResourceError race condition during shutdown#2268

Open
weiguangli-io wants to merge 1 commit intomodelcontextprotocol:mainfrom
weiguangli-io:fix/stdio-shutdown-race-1960
Open

Fix stdio_client BrokenResourceError race condition during shutdown#2268
weiguangli-io wants to merge 1 commit intomodelcontextprotocol:mainfrom
weiguangli-io:fix/stdio-shutdown-race-1960

Conversation

@weiguangli-io
Copy link

Summary

Fixes #1960. Supersedes #2219 (which was closed).

During stdio_client shutdown, the finally block closes read_stream (the receiving end of a zero-buffer memory channel) while stdout_reader may still be blocked on send(). When the receiving end closes underneath a pending send(), anyio raises BrokenResourceError — not ClosedResourceError. The existing except clause only caught ClosedResourceError, so BrokenResourceError escaped into an ExceptionGroup.

The fix catches BrokenResourceError alongside ClosedResourceError in both stdout_reader and stdin_writer. This is the minimal, correct change: ClosedResourceError means "you called send on a handle you already closed", while BrokenResourceError means "the other end was closed" — both are expected during shutdown and should be handled identically.

Test plan

  • Added regression test test_stdio_client_no_broken_resource_error_on_shutdown that reproduces the exact scenario: server sends a JSON-RPC message, client exits without consuming the read stream
  • All 12 existing tests/client/test_stdio.py tests pass

During shutdown, the finally block closes the receiving end of the
read_stream memory channel while stdout_reader may still be blocked
on send(). This causes BrokenResourceError (not ClosedResourceError)
because the *other* end of the stream was closed. The existing except
clause only caught ClosedResourceError, letting BrokenResourceError
propagate into an ExceptionGroup.

Catch BrokenResourceError alongside ClosedResourceError in both
stdout_reader and stdin_writer to handle this race gracefully.

Closes modelcontextprotocol#1960
Github-Issue:modelcontextprotocol#1960
Reported-by:maxisbey
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BrokenResourceError race condition in stdio_client cleanup when context exits quickly

1 participant