The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix: complete streaming connection pool leak fix with regression tests
Ryan Crabbe9f09b02c65ce
diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.pyindex f3556b2d18f..0eaa700ffdf 100644--- a/litellm/litellm_core_utils/streaming_handler.py+++ b/litellm/litellm_core_utils/streaming_handler.py@@ -156,10 +156,22 @@ class CustomStreamWrapper:return selfasync def aclose(self):- if self.completion_stream is not None and hasattr(- self.completion_stream, "aclose"- ):- await self.completion_stream.aclose()+ if self.completion_stream is not None:+ # Shield from anyio cancellation so cleanup awaits can complete.+ # Without this, CancelledError is thrown into every await during+ # task group cancellation, preventing HTTP connection release.+ import anyio++ with anyio.CancelScope(shield=True):+ try:+ if hasattr(self.completion_stream, "aclose"):+ await self.completion_stream.aclose()+ elif hasattr(self.completion_stream, "close"):+ result = self.completion_stream.close()+ if result is not None:+ await result+ except BaseException:+ passdef check_send_stream_usage(self, stream_options: Optional[dict]):return (diff --git a/litellm/llms/custom_httpx/aiohttp_transport.py b/litellm/llms/custom_httpx/aiohttp_transport.pyindex fb98006c7e4..64488e2248f 100644--- a/litellm/llms/custom_httpx/aiohttp_transport.py+++ b/litellm/llms/custom_httpx/aiohttp_transport.py@@ -324,7 +324,7 @@ class LiteLLMAiohttpTransport(AiohttpTransport):return httpx.Response(status_code=response.status,headers=response.headers,- content=AiohttpResponseStream(response),+ stream=AiohttpResponseStream(response),request=request,)diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.pyindex a02bc7f9e51..d0969de7ca0 100644--- a/litellm/proxy/common_request_processing.py+++ b/litellm/proxy/common_request_processing.py@@ -3,6 +3,7 @@ import jsonimport loggingimport tracebackfrom datetime import datetime+from functools import partialfrom typing import (TYPE_CHECKING,Any,@@ -14,10 +15,13 @@ from typing import (Union,)+import anyioimport httpximport orjsonfrom fastapi import HTTPException, Request, statusfrom fastapi.responses import JSONResponse, Response, StreamingResponse+from starlette._utils import collapse_excgroups+from starlette.types import Receive, Scope, Sendimport litellmfrom litellm._logging import verbose_proxy_logger@@ -138,6 +142,39 @@ def _extract_error_from_sse_chunk(event_line: Union[str, bytes]) -> dict:return default_error+async def _disconnect_aware_call(+ self: StreamingResponse, scope: Scope, receive: Receive, send: Send+) -> None:+ """Patched StreamingResponse.__call__ that detects client disconnects.++ Starlette >= 0.45.3 relies on ASGI spec 2.4 where send() should raise OSError+ on client disconnect. Uvicorn does not implement this — send() silently returns.+ This means async generators keep running forever after clients disconnect,+ leaking upstream HTTP connections.++ This restores the pre-0.45.3 behavior: a concurrent task listens for+ http.disconnect and cancels the streaming task group when detected.++ See: https://github.com/encode/starlette/pull/2732+ See: https://github.com/encode/uvicorn/pull/2276+ """+ with collapse_excgroups():+ async with anyio.create_task_group() as task_group:++ async def wrap(func: Callable[[], Any]) -> None:+ await func()+ task_group.cancel_scope.cancel()++ task_group.start_soon(wrap, partial(self.stream_response, send))+ await wrap(partial(self.listen_for_disconnect, receive))++ if self.background is not None:+ await self.background()+++StreamingResponse.__call__ = _disconnect_aware_call # type: ignore[assignment]++async def create_response(generator: AsyncGenerator[str, None],media_type: str,diff --git a/litellm/router.py b/litellm/router.pyindex 888c97ca0b1..f767ff59a59 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -13,6 +13,8 @@ import enumimport hashlibimport inspectimport json++import anyioimport loggingimport threadingimport time@@ -1593,6 +1595,14 @@ class Router:f"Fallback also failed: {fallback_error}")raise fallback_error+ finally:+ # Close the underlying stream to release the HTTP connection+ # back to the connection pool when the generator is closed+ # (e.g. on client disconnect).+ # Shield from anyio cancellation so the await can complete.+ if hasattr(model_response, "aclose"):+ with anyio.CancelScope(shield=True):+ await model_response.aclose()return FallbackStreamWrapper(stream_with_fallbacks())diff --git a/tests/test_litellm/test_streaming_connection_cleanup.py b/tests/test_litellm/test_streaming_connection_cleanup.pynew file mode 100644index 00000000000..907c8a0b2f7--- /dev/null+++ b/tests/test_litellm/test_streaming_connection_cleanup.py@@ -0,0 +1,226 @@+"""+Regression tests for streaming connection pool leak fix.+"""++import asyncio+import os+import sys+from unittest.mock import AsyncMock, MagicMock, patch++import anyio+import httpx+import pytest++sys.path.insert(0, os.path.abspath("../.."))++from litellm.litellm_core_utils.streaming_handler import CustomStreamWrapper+from litellm.llms.custom_httpx.aiohttp_transport import (+ AiohttpResponseStream,+ LiteLLMAiohttpTransport,+)+++async def test_aiohttp_transport_response_uses_stream_not_content():+ """handle_async_request must use stream= so aclose() propagates to AiohttpResponseStream."""++ class FakeSession:+ closed = False++ def __init__(self):+ try:+ self._loop = asyncio.get_running_loop()+ except RuntimeError:+ self._loop = None++ def request(self, **kwargs):+ class Resp:+ status = 200+ headers = {}++ async def __aenter__(self):+ return self++ async def __aexit__(self, *args):+ pass++ @property+ def content(self):+ class C:+ async def iter_chunked(self, size):+ yield b"data"++ return C()++ return Resp()++ transport = LiteLLMAiohttpTransport(client=lambda: FakeSession()) # type: ignore+ response = await transport.handle_async_request(+ httpx.Request("GET", "http://example.com")+ )++ assert isinstance(response.stream, AiohttpResponseStream)+++async def test_aiohttp_response_stream_aclose_releases_connection():+ """AiohttpResponseStream.aclose() must call __aexit__ on the aiohttp response."""+ aexit_called = False++ class MockResponse:+ status = 200+ headers = {}++ @property+ def content(self):+ class C:+ async def iter_chunked(self, size):+ yield b"data"++ return C()++ async def __aexit__(self, *args):+ nonlocal aexit_called+ aexit_called = True++ stream = AiohttpResponseStream(MockResponse()) # type: ignore+ await stream.aclose()+ assert aexit_called+++async def test_aclose_falls_back_to_close():+ """OpenAI's AsyncStream has close() but not aclose(). Must fall back."""+ close_called = False++ class FakeAsyncStream:+ async def close(self):+ nonlocal close_called+ close_called = True++ wrapper = CustomStreamWrapper(+ completion_stream=FakeAsyncStream(),+ model=None,+ logging_obj=MagicMock(),+ custom_llm_provider=None,+ )++ await wrapper.aclose()+ assert close_called+++async def test_aclose_prefers_aclose_over_close():+ """When both aclose() and close() exist, aclose() should be preferred."""+ aclose_called = False+ close_called = False++ class FakeStream:+ async def aclose(self):+ nonlocal aclose_called+ aclose_called = True++ async def close(self):+ nonlocal close_called+ close_called = True++ wrapper = CustomStreamWrapper(+ completion_stream=FakeStream(),+ model=None,+ logging_obj=MagicMock(),+ custom_llm_provider=None,+ )++ await wrapper.aclose()+ assert aclose_called+ assert not close_called+++async def test_aclose_completes_under_cancellation():+ """aclose() must shield cleanup from CancelledError so streams actually close."""+ aclose_completed = False++ class SlowCloseStream:+ async def aclose(self):+ await asyncio.sleep(0)+ nonlocal aclose_completed+ aclose_completed = True++ wrapper = CustomStreamWrapper(+ completion_stream=SlowCloseStream(),+ model=None,+ logging_obj=MagicMock(),+ custom_llm_provider=None,+ )++ with anyio.CancelScope() as scope:+ scope.cancel()+ await wrapper.aclose()++ assert aclose_completed+++async def test_stream_with_fallbacks_closes_stream_on_generator_close():+ """Closing the generator from async_function_with_fallbacks must aclose() the stream."""+ from litellm.router import Router++ stream_closed = False++ class FakeStream:+ def __init__(self):+ self.chunks = ["chunk1", "chunk2", "chunk3"]+ self.index = 0++ def __aiter__(self):+ return self++ async def __anext__(self):+ if self.index >= len(self.chunks):+ raise StopAsyncIteration+ chunk = self.chunks[self.index]+ self.index += 1+ return chunk++ async def aclose(self):+ nonlocal stream_closed+ stream_closed = True++ router = Router(+ model_list=[+ {+ "model_name": "test-model",+ "litellm_params": {+ "model": "openai/test",+ "api_key": "fake",+ },+ }+ ]+ )++ fake_stream = FakeStream()++ with patch.object(router, "acompletion", return_value=fake_stream):+ result = await router.async_function_with_fallbacks(+ original_function=router.acompletion,+ model="test-model",+ messages=[{"role": "user", "content": "hi"}],+ stream=True,+ num_retries=0,+ )++ async for chunk in result:+ break++ await result.aclose()++ assert stream_closed+++def test_streaming_response_monkey_patch_applied():+ """_disconnect_aware_call must be applied to StreamingResponse.__call__."""+ from litellm.proxy.common_request_processing import _disconnect_aware_call+ from starlette.responses import StreamingResponse++ assert StreamingResponse.__call__ is _disconnect_aware_call