Skip to content

fix: clean up resources in Query.close() to prevent memory leaks#657

Open
MaxwellCalkin wants to merge 1 commit intoanthropics:mainfrom
MaxwellCalkin:fix/query-resource-leak-on-close
Open

fix: clean up resources in Query.close() to prevent memory leaks#657
MaxwellCalkin wants to merge 1 commit intoanthropics:mainfrom
MaxwellCalkin:fix/query-resource-leak-on-close

Conversation

@MaxwellCalkin
Copy link

Summary

  • Bug: Query.close() cancels the task group and closes the transport, but leaves several resources uncleaned:
    • hook_callbacks dictionary (populated during initialize(), never cleared)
    • pending_control_responses and pending_control_results dictionaries
    • _message_send and _message_receive anyio memory object streams
  • Impact: In long-running applications or those creating multiple Query instances, these orphaned references prevent garbage collection and cause memory leaks.
  • Fix: After closing the transport, clear all dictionaries and explicitly close both ends of the memory object stream. Stream close calls are wrapped in suppress(Exception) to handle cases where they may already be closed.

Test plan

  • Existing tests pass (change is additive cleanup only, no behavioral change)
  • Verify ruff check and ruff format pass
  • Manual verification: create and close multiple Query instances in a loop, confirm memory usage stays flat

🤖 Generated with Claude Code

The close() method cancels the task group and closes the transport, but
does not clear hook_callbacks, pending_control_responses,
pending_control_results, or close the memory object streams. In
long-running applications or those creating multiple Query instances,
these orphaned references prevent garbage collection and cause memory
leaks.

Add cleanup calls after transport.close() to clear all dictionaries
and explicitly close both ends of the anyio memory object stream.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
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.

1 participant