Skip to content

fix(query): guard Query.close() cleanup with try/finally (#886)#887

Open
MukundaKatta wants to merge 1 commit intoanthropics:mainfrom
MukundaKatta:fix/query-close-try-finally
Open

fix(query): guard Query.close() cleanup with try/finally (#886)#887
MukundaKatta wants to merge 1 commit intoanthropics:mainfrom
MukundaKatta:fix/query-close-try-finally

Conversation

@MukundaKatta
Copy link
Copy Markdown

Summary

Query.close() runs several await cleanup steps (_transcript_mirror_batcher.close(), child-task cancel, _read_task.wait(), _message_send.close()) before finally calling await self.transport.close(). Because these are not wrapped in try/finally, a raise from any earlier step short-circuits and skips transport.close() — leaking the CLI subprocess and the stderr reader task.

This wraps the pre-transport cleanup in try/finally so transport.close() always runs, regardless of earlier failures.

Fixes #886.

Changes

  • src/claude_agent_sdk/_internal/query.py: wrap pre-transport cleanup in try/finally; the await self.transport.close() now lives in the finally branch.
  • tests/test_query_close_cleanup.py: regression test that injects a mirror-batcher whose close() raises and asserts transport.close() is still called.

Test plan

  • New regression test test_close_runs_transport_close_when_mirror_batcher_close_raises fails on the unpatched code (because transport.close() is never invoked) and passes with the fix.
  • Existing close-related tests in tests/test_query.py (test_close_from_same_task_still_works, test_close_from_different_task_does_not_raise, the trio backend variants) still pass — the behavior on the happy path is identical, only the error path changes.
  • CI runs the full pytest suite on Ubuntu/macOS/Windows.

Wraps the pre-transport cleanup in close() with try/finally so
transport.close() always runs. Without this, a raise from
_transcript_mirror_batcher.close() or _read_task.wait() leaked the
CLI subprocess and the stderr reader task.

Adds a regression test that injects a mirror-batcher whose close()
raises and asserts transport.close() is still invoked.

Fixes anthropics#886
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.

Query.close(): transport.close() not guarded by try/finally — can be skipped if earlier cleanup raises

1 participant