Add tests for resource leak in streamable_http SSE handlers #1490
+445
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #1450
I found that HTTP responses don't get closed properly when SSE streaming fails with exceptions in the streamable HTTP client.
The Problem:
When the async for loop in
_handle_sse_responseand_handle_resumption_requestthrows an exception (malformed JSON, network error, etc.), the response is never closed becauseresponse.aclose()is only called in the success path.Impact:
This can cause connection pool exhaustion in long-running clients, eventually causing new requests to hang or fail.
What I Added:
test_resource_leak_reproduction.py- Standalone script that demonstrates the issuetests/client/test_streamable_http_resource_leak.py- Pytest tests that verify the resource leak and show how the fix should workBoth test files show that when SSE parsing fails, the response doesn't get closed, confirming the resource leak.
The Fix:
The methods need
finallyblocks to ensureresponse.aclose()is always called:This ensures resources are properly cleaned up regardless of whether exceptions occur.