Skip to content

fix(streaming): add CustomStreamWrapper.close() and release the connection when a sync stream ends - #46354

Merged
klu-berri merged 5 commits into
mainfrom
litellm_sync_stream_close
Oct 14, 2026
Merged

klu-berri merged 5 commits into
mainfrom
litellm_sync_stream_close

Conversation

@klu-berri

@klu-berri klu-berri commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • CustomStreamWrapper had aclose() but no sync close(), so a sync caller could not release an abandoned stream
  • A sync Anthropic stream read to its last chunk left the httpx response checked out of the pool forever
  • Providers on the shared BaseLLMHTTPHandler sync path (databricks, openrouter, cohere, ...) had the same shape
  • Each such stream pinned one pooled connection, and GC later finalized it under the pool lock (hung sync workers)

How it solves it:

  • CustomStreamWrapper.close() closes the wrapped provider stream, mirrors aclose(), idempotent, context managers added
  • Sync and async wrappers close the provider stream when they raise their final StopIteration or re-raise a mid-stream error
  • Anthropic ModelResponseIterator keeps its httpx.Response and closes it on close() / aclose()
  • Shared BaseLLMHTTPHandler sync branch hands the response to BaseModelResponseIterator, which gets close() next to aclose()
  • Supersedes fix(anthropic): close abandoned streaming responses #38082 (same leak, Anthropic handler only), its author is credited as co-author on the commit

User Flow

Before: a developer streaming Anthropic through the SDK from sync workers sees connections pile up until the worker hangs

  1. They call litellm.completion(model="anthropic/claude-sonnet-5-5", messages=[...], stream=True) and iterate the stream to its last chunk
  2. The text arrives in full, but the connection the stream used stays checked out of the shared httpx pool
  3. The next litellm.completion(..., stream=True) opens a fresh connection, and the pool grows by one per stream
  4. A caller that stops early has nothing to call, stream.close() raises AttributeError: 'CustomStreamWrapper' object has no attribute 'close'

After: the same calls release the connection every time

  1. They call litellm.completion(model="anthropic/claude-sonnet-5-5", messages=[...], stream=True) and iterate the stream to its last chunk
  2. The text arrives in full and the pool has no checked out connection left behind
  3. The next litellm.completion(..., stream=True) completes with the pool still empty afterwards
  4. A caller that stops early calls stream.close() (or uses with litellm.completion(...) as stream:) and the peer sees the socket closed

Linear ticket

Resolves LIT-9573

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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 more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Screenshots / Proof of Fix

Live Anthropic, real key, the SDK call the customer makes. proof.py:

import litellm

pool = litellm.module_level_client.client._transport._pool
print("litellm from", litellm.__file__)
for call in (1, 2):
    stream = litellm.completion(
        model="anthropic/claude-sonnet-5-5",
        messages=[{"role": "user", "content": "say hi in three words"}],
        stream=True,
        max_tokens=20,
    )
    text = "".join(chunk.choices[0].delta.content or "" for chunk in stream)
    checked_out = [c for c in pool.connections if not c.is_idle()]
    print(f"call {call}: {text!r} pool_connections={len(pool.connections)} checked_out={len(checked_out)}")

Before (083d48f)

Two sync Anthropic streams read to the end on one process

  1. ANTHROPIC_API_KEY=... python proof.py
  2. Observed, each finished stream leaves its connection checked out and the next call opens another one
litellm from /tmp/lit_main/litellm/__init__.py
call 1: 'Hello, lovely human!' pool_connections=1 checked_out=1
call 2: 'Hello, lovely human!' pool_connections=2 checked_out=2

Regression test on the owned peer

  1. python tests/integration/run.py sdk tests/integration/sdk/test_sync_stream_connection_release_wire.py
  2. Observed, 6 failed, 2 passed
test_sync_stream_read_to_its_last_chunk_releases_the_connection[anthropic] -> AssertionError: State did not converge: 2
test_sync_stream_read_to_its_last_chunk_releases_the_connection[openai] -> PASS
test_sync_stream_read_to_its_last_chunk_releases_the_connection[databricks] -> AssertionError: State did not converge: 2
test_sync_stream_closed_after_its_first_chunk_releases_the_connection[anthropic] -> AttributeError: 'CustomStreamWrapper' object has no attribute 'close'. Did you mean: 'aclose'?
test_sync_stream_closed_after_its_first_chunk_releases_the_connection[openai] -> AttributeError: 'CustomStreamWrapper' object has no attribute 'close'. Did you mean: 'aclose'?
test_sync_stream_closed_after_its_first_chunk_releases_the_connection[databricks] -> AttributeError: 'CustomStreamWrapper' object has no attribute 'close'. Did you mean: 'aclose'?
test_async_stream_read_to_its_last_chunk_releases_the_connection -> PASS
test_async_stream_aclosed_after_its_first_chunk_releases_the_connection -> AssertionError: aclose() left the TCP session open | assert 1 == 0

After (b1a55ba)

Two sync Anthropic streams read to the end on one process

  1. ANTHROPIC_API_KEY=... python proof.py
  2. Observed, both streams complete and nothing stays checked out
litellm from /home/ubuntu/repos/litellm/litellm/__init__.py
call 1: 'Hello, lovely human!' pool_connections=0 checked_out=0
call 2: 'Hello, lovely human!' pool_connections=0 checked_out=0

Regression test on the owned peer

  1. python tests/integration/run.py sdk tests/integration/sdk/test_sync_stream_connection_release_wire.py
  2. Observed
======================= 9 passed, 10 warnings in 11.49s ========================
  1. Mutation check, put back self._restore_consumer_correlation_context() in place of self.close() where __next__ re-raises its final StopIteration, rerun
test_sync_stream_read_to_its_last_chunk_releases_the_connection[anthropic] -> AssertionError: State did not converge: 2
================== 1 failed, 5 passed, 10 warnings in 21.13s ===================
  1. Second mutation, drop the completion_stream.http_response = response line on the sync branch of llm_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 response
  2. test_sync_stream_that_raises_mid_stream_releases_the_connection (an Anthropic error event 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 after
  3. pytest tests/unit/litellm_core_utils/test_streaming_handler.py tests/unit/llms/anthropic/chat/test_anthropic_chat_handler.py at the tip, 242 passed. A later tests-only commit adds unit tests for close(), the with / async with blocks and BaseModelResponseIterator.close() in the mapped tests/unit files, no behavior change after cbc73c0

Live multi-provider sweep at 25810d8 (before the mid-stream error commit, connection behavior unchanged by it)

  1. 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 with psutil. 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)
  2. Observed, every row flat across the three streams, no row grows. Empty last_text on gemini and groq is the 20 token budget going to reasoning, not a stream problem
anthropic  sync_full      ok  established_443_after_each_of_3_streams=[0, 0, 0]  last_text='hello world'
anthropic  sync_abandon   ok  established_443_after_each_of_3_streams=[0, 0, 0]  last_text='closed'
anthropic  async_full     ok  established_443_after_each_of_3_streams=[1, 1, 1]  last_text='hello world'
anthropic  async_abandon  ok  established_443_after_each_of_3_streams=[0, 0, 0]  last_text='aclosed'
openai     sync_full      ok  established_443_after_each_of_3_streams=[0, 0, 0]  last_text='hello world'
openai     sync_abandon   ok  established_443_after_each_of_3_streams=[0, 0, 0]  last_text='closed'
openai     async_full     ok  established_443_after_each_of_3_streams=[0, 0, 1]  last_text='hello world'
openai     async_abandon  ok  established_443_after_each_of_3_streams=[0, 0, 0]  last_text='aclosed'
gemini     sync_full      ok  established_443_after_each_of_3_streams=[1, 1, 1]  last_text=''
gemini     sync_abandon   ok  established_443_after_each_of_3_streams=[0, 0, 0]  last_text='closed'
gemini     async_full     ok  established_443_after_each_of_3_streams=[1, 1, 1]  last_text=''
gemini     async_abandon  ok  established_443_after_each_of_3_streams=[1, 0, 0]  last_text='aclosed'
mistral    sync_full      ok  established_443_after_each_of_3_streams=[2, 2, 2]  last_text='hello world'
mistral    sync_abandon   ok  established_443_after_each_of_3_streams=[1, 1, 1]  last_text='closed'
mistral    async_full     ok  established_443_after_each_of_3_streams=[2, 2, 2]  last_text='hello world'
mistral    async_abandon  ok  established_443_after_each_of_3_streams=[1, 1, 1]  last_text='aclosed'
bedrock    sync_full      ok  established_443_after_each_of_3_streams=[1, 1, 1]  last_text='hello world'
bedrock    sync_abandon   ok  established_443_after_each_of_3_streams=[0, 0, 0]  last_text='closed'
bedrock    async_full     ok  established_443_after_each_of_3_streams=[1, 1, 1]  last_text='hello world'
bedrock    async_abandon  ok  established_443_after_each_of_3_streams=[0, 0, 0]  last_text='aclosed'
groq       sync_full      ok  established_443_after_each_of_3_streams=[0, 0, 0]  last_text=''
groq       sync_abandon   ok  established_443_after_each_of_3_streams=[0, 0, 0]  last_text='closed'
groq       async_full     ok  established_443_after_each_of_3_streams=[1, 1, 1]  last_text=''
groq       async_abandon  ok  established_443_after_each_of_3_streams=[0, 0, 0]  last_text='aclosed'

Not 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 = response line 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

  • Streams close the response at the end instead of draining to EOF, so each sync stream costs one TCP+TLS handshake on the next call
    • Draining would block on a gateway that keeps the body open after the last event, the openai SDK makes the same choice
    • Flip, drain inside the Anthropic iterator after message_stop only, if the handshake matters

Low

  • A sync stream abandoned without close() or a with block still leaks, same as main, __del__ does not close on purpose

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

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

devin-ai-integration Bot and others added 2 commits October 14, 2026 02:41
… 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>
@devin-ai-integration

Copy link
Copy Markdown
Contributor

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@codspeed

codspeed Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 31 untouched benchmarks


Comparing litellm_sync_stream_close (b1a55ba) with main (0d67ccc)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (0915691) during the generation of this report, so 0d67ccc was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@codecov

codecov Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.33962% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/litellm_core_utils/streaming_handler.py 91.17% 3 Missing ⚠️

📢 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>

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@litellm-stampbot litellm-stampbot Bot added the risk:high Sensitive, broad, or high-risk change label Oct 14, 2026
…hared iterator close()

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@BerriAI BerriAI deleted a comment from litellm-stampbot Bot Oct 14, 2026
…eam error

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

@kerry-berri kerry-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@klu-berri
klu-berri enabled auto-merge (squash) October 14, 2026 19:07
@klu-berri klu-berri removed the risk:high Sensitive, broad, or high-risk change label Oct 14, 2026
@klu-berri
klu-berri merged commit 6bd5580 into main Oct 14, 2026
91 checks passed
@klu-berri
klu-berri deleted the litellm_sync_stream_close branch October 14, 2026 19:14
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.

3 participants