Repository navigation
fix(proxy): deterministically close upstream streams for /v1/responses and /v1/messages #36272
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
vivekvar-dl
wants to merge
3
commits into
BerriAI:main
Choose a base branch
from
vivekvar-dl:litellm_fix_stream_close_responses_messages
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
a4ce0f2
fix(proxy): deterministically close upstream streams for /v1/response…
vivekvar-dl e8e7db2
fix(proxy): suppress BLE001 on upstream close guard to stay within st…
vivekvar-dl 62ca98a
fix(responses): propagate aclose through MCPEnhancedStreamingIterator…
vivekvar-dl File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
114 changes: 114 additions & 0 deletions
114
tests/test_litellm/proxy/pass_through_endpoints/test_streaming_handler.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| """Regression tests: chunk_processor must close the upstream httpx.Response | ||
| when the stream ends, including on client disconnect (generator aclose), so | ||
| the provider connection is released and backends like vLLM stop generating. | ||
| """ | ||
|
|
||
| from collections.abc import AsyncIterator | ||
| from datetime import datetime, timezone | ||
| from typing import Final | ||
| from unittest.mock import MagicMock, patch | ||
|
|
||
| import httpx | ||
| import pytest | ||
|
|
||
| from litellm.llms.anthropic.experimental_pass_through.messages.streaming_iterator import ( | ||
| AnthropicMessagesStreamHiddenParams, | ||
| AnthropicMessagesStreamingResponse, | ||
| ) | ||
| from litellm.proxy.pass_through_endpoints.streaming_handler import ( | ||
| PassThroughStreamingHandler, | ||
| ) | ||
| from litellm.types.passthrough_endpoints.pass_through_endpoints import EndpointType | ||
|
|
||
|
|
||
| class _TrackingStream(httpx.AsyncByteStream): | ||
| def __init__(self, chunks: list[bytes]): | ||
| self._chunks = chunks | ||
| self.aclose_called = False | ||
|
|
||
| async def __aiter__(self) -> AsyncIterator[bytes]: | ||
| for chunk in self._chunks: | ||
| yield chunk | ||
|
|
||
| async def aclose(self) -> None: | ||
| self.aclose_called = True | ||
|
|
||
|
|
||
| def _streaming_response(chunks: list[bytes]) -> tuple[httpx.Response, _TrackingStream]: | ||
| stream: Final = _TrackingStream(chunks) | ||
| response: Final = httpx.Response( | ||
| 200, | ||
| stream=stream, | ||
| request=httpx.Request("POST", "http://upstream.test/v1/messages"), | ||
| ) | ||
| return response, stream | ||
|
|
||
|
|
||
| def _logging_obj_stub() -> MagicMock: | ||
| logging_obj: Final = MagicMock() | ||
| logging_obj.completion_start_time = None | ||
| logging_obj.model_call_details = {} | ||
| return logging_obj | ||
|
|
||
|
|
||
| def _chunk_processor(response: httpx.Response): | ||
| return PassThroughStreamingHandler.chunk_processor( | ||
| response=response, | ||
| request_body={"model": "claude-sonnet-4-5"}, | ||
| litellm_logging_obj=_logging_obj_stub(), | ||
| endpoint_type=EndpointType.ANTHROPIC, | ||
| start_time=datetime.now(timezone.utc), | ||
| passthrough_success_handler_obj=MagicMock(), | ||
| url_route="/v1/messages", | ||
| ) | ||
|
|
||
|
greptile-apps[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
| def _drop_scheduled_coroutine(async_coroutine) -> None: | ||
| async_coroutine.close() | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_chunk_processor_closes_response_on_client_disconnect(): | ||
| response, stream = _streaming_response([b"event: message_start\n\n", b"event: message_stop\n\n"]) | ||
| generator: Final = _chunk_processor(response) | ||
|
|
||
| with patch("litellm.proxy.pass_through_endpoints.streaming_handler.GLOBAL_LOGGING_WORKER") as worker: | ||
| worker.ensure_initialized_and_enqueue.side_effect = _drop_scheduled_coroutine | ||
| first_chunk: Final = await generator.__anext__() | ||
| assert first_chunk == b"event: message_start\n\n" | ||
| await generator.aclose() | ||
|
|
||
| assert stream.aclose_called | ||
| assert response.is_closed | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_chunk_processor_closes_response_on_natural_completion(): | ||
| response, stream = _streaming_response([b"event: message_start\n\n", b"event: message_stop\n\n"]) | ||
| generator: Final = _chunk_processor(response) | ||
|
|
||
| with patch("litellm.proxy.pass_through_endpoints.streaming_handler.GLOBAL_LOGGING_WORKER") as worker: | ||
| worker.ensure_initialized_and_enqueue.side_effect = _drop_scheduled_coroutine | ||
| collected: Final = [chunk async for chunk in generator] | ||
|
|
||
| assert collected == [b"event: message_start\n\n", b"event: message_stop\n\n"] | ||
| assert stream.aclose_called | ||
| assert response.is_closed | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_anthropic_messages_streaming_response_aclose_closes_upstream_response(): | ||
| response, stream = _streaming_response([b"event: message_start\n\n"]) | ||
| wrapped: Final = AnthropicMessagesStreamingResponse( | ||
| completion_stream=_chunk_processor(response), | ||
| hidden_params=AnthropicMessagesStreamHiddenParams(additional_headers={}), | ||
| ) | ||
|
|
||
| with patch("litellm.proxy.pass_through_endpoints.streaming_handler.GLOBAL_LOGGING_WORKER") as worker: | ||
| worker.ensure_initialized_and_enqueue.side_effect = _drop_scheduled_coroutine | ||
| first_chunk: Final = await wrapped.__anext__() | ||
| assert first_chunk == b"event: message_start\n\n" | ||
| await wrapped.aclose() | ||
|
|
||
| assert stream.aclose_called | ||
| assert response.is_closed | ||
44 changes: 44 additions & 0 deletions
44
...responses/litellm_completion_transformation/test_litellm_completion_streaming_iterator.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| """Regression test: the /v1/responses bridge iterator must expose aclose() | ||
| so the proxy's streaming cleanup can release the upstream provider | ||
| connection on client disconnect. | ||
| """ | ||
|
|
||
| from typing import Final | ||
| from unittest.mock import MagicMock | ||
|
|
||
| import pytest | ||
|
|
||
| from litellm.litellm_core_utils.streaming_handler import CustomStreamWrapper | ||
| from litellm.responses.litellm_completion_transformation.streaming_iterator import ( | ||
| LiteLLMCompletionStreamingIterator, | ||
| ) | ||
|
|
||
|
|
||
| class _TrackingCompletionStream: | ||
| def __init__(self): | ||
| self.aclose_called = False | ||
|
|
||
| async def aclose(self) -> None: | ||
| self.aclose_called = True | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_aclose_closes_wrapped_completion_stream(): | ||
| completion_stream: Final = _TrackingCompletionStream() | ||
| wrapper: Final = CustomStreamWrapper( | ||
| completion_stream=completion_stream, | ||
| model="gpt-4o-mini", | ||
| logging_obj=MagicMock(), | ||
| custom_llm_provider="openai", | ||
| ) | ||
| iterator: Final = LiteLLMCompletionStreamingIterator( | ||
| model="gpt-4o-mini", | ||
| litellm_custom_stream_wrapper=wrapper, | ||
| request_input="hello", | ||
| responses_api_request={}, | ||
| ) | ||
|
|
||
| await iterator.aclose() | ||
|
|
||
| assert completion_stream.aclose_called | ||
| assert wrapper.completion_stream is None |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.