Repository navigation
fix(streaming): add CustomStreamWrapper.close() and release the connection when a sync stream ends - #46354
Conversation
… pool CustomStreamWrapper gets a sync close() (plus context manager support) that closes the wrapped provider stream, and both the sync and async wrappers close the provider stream when the stream reaches its end. The Anthropic stream iterator keeps the httpx response it reads so close()/aclose() can release the socket after message_stop instead of leaving it checked out of the pool Co-authored-by: Blair Jordan <blair.j.jordan@gmail.com> Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…pper.close() Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
|
Merging this PR will not alter performance
|
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
BaseModelResponseIterator gets a sync close() next to its aclose(), and the sync branch of BaseLLMHTTPHandler hands it the httpx response the way the async branch already does, so providers built on it release the socket on close() instead of waiting for garbage collection Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
@litellm-stampbot |
…hared iterator close() Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…eam error Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
TLDR
Problem this solves:
CustomStreamWrapperhadaclose()but no syncclose(), so a sync caller could not release an abandoned streamBaseLLMHTTPHandlersync path (databricks, openrouter, cohere, ...) had the same shapeHow it solves it:
CustomStreamWrapper.close()closes the wrapped provider stream, mirrorsaclose(), idempotent, context managers addedStopIterationor re-raise a mid-stream errorModelResponseIteratorkeeps itshttpx.Responseand closes it onclose()/aclose()BaseLLMHTTPHandlersync branch hands the response toBaseModelResponseIterator, which getsclose()next toaclose()User Flow
Before: a developer streaming Anthropic through the SDK from sync workers sees connections pile up until the worker hangs
litellm.completion(model="anthropic/claude-sonnet-5-5", messages=[...], stream=True)and iterate the stream to its last chunklitellm.completion(..., stream=True)opens a fresh connection, and the pool grows by one per streamstream.close()raisesAttributeError: 'CustomStreamWrapper' object has no attribute 'close'After: the same calls release the connection every time
litellm.completion(model="anthropic/claude-sonnet-5-5", messages=[...], stream=True)and iterate the stream to its last chunklitellm.completion(..., stream=True)completes with the pool still empty afterwardsstream.close()(or useswith litellm.completion(...) as stream:) and the peer sees the socket closedLinear ticket
Resolves LIT-9573
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or moreScreenshots / Proof of Fix
Live Anthropic, real key, the SDK call the customer makes.
proof.py:Before (083d48f)
Two sync Anthropic streams read to the end on one process
ANTHROPIC_API_KEY=... python proof.pyRegression test on the owned peer
python tests/integration/run.py sdk tests/integration/sdk/test_sync_stream_connection_release_wire.pyAfter (b1a55ba)
Two sync Anthropic streams read to the end on one process
ANTHROPIC_API_KEY=... python proof.pyRegression test on the owned peer
python tests/integration/run.py sdk tests/integration/sdk/test_sync_stream_connection_release_wire.pyself._restore_consumer_correlation_context()in place ofself.close()where__next__re-raises its finalStopIteration, reruncompletion_stream.http_response = responseline on the sync branch ofllm_http_handler.py, rerun: still 8 passed. CPython refcounting closes the socket as soon as the wrapper lets go of the iterator, so the peer cannot tell explicit close from refcount close on that path. The explicit close is there so release no longer depends on the interpreter freeing the responsetest_sync_stream_that_raises_mid_stream_releases_the_connection(an Anthropicerrorevent mid-stream) was added last, red before its two-line fix (State did not converge: 1, the exception reached the caller but the socket stayed open), green afterpytest tests/unit/litellm_core_utils/test_streaming_handler.py tests/unit/llms/anthropic/chat/test_anthropic_chat_handler.pyat the tip, 242 passed. A later tests-only commit adds unit tests forclose(), thewith/async withblocks andBaseModelResponseIterator.close()in the mappedtests/unitfiles, no behavior change after cbc73c0Live multi-provider sweep at 25810d8 (before the mid-stream error commit, connection behavior unchanged by it)
live_multi.py: for each provider, three streams per mode (sync_full,sync_abandon+close(),async_full,async_abandon+aclose()),max_tokens=20, and after every stream count this process's ESTABLISHED TCP sockets to port 443 withpsutil. A leak shows as the count growing by one per stream, a healthy client keeps it flat (0, or 1 to 2 idle keep-alive sockets)last_texton gemini and groq is the 20 token budget going to reasoning, not a stream problemNot proven here: the customer's GC deadlock under httpcore's pool lock itself (the leaked checked-out connection that feeds it is what the Before leg shows), and the shared-path explicit close on its own (removing the sync
http_response = responseline keeps all 8 peer rows green because CPython refcounting closes the dropped response, so the explicit close removes a dependency rather than fixing a red test)Type
🐛 Bug Fix
Caveats (if any)
Medium
message_stoponly, if the handshake mattersLow
close()or awithblock still leaks, same as main,__del__does not close on purposeFinal Attestation
Link to Devin session: https://app.devin.ai/sessions/297a0a6f9e3048d8b0a3e7534dffe547
Open in Devin Desktop: https://app.devin.ai/desktop/session/297a0a6f9e3048d8b0a3e7534dffe547?variant=devin
Requested by: @kerrylu-berri