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(proxy): cancel upstream LLM stream when client disconnects during time-to-first-token (#31499)
Yassin Kortamc33a7f875704
diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.pyindex c2ffd9b077d..b5e98dbc2af 100644--- a/litellm/proxy/common_request_processing.py+++ b/litellm/proxy/common_request_processing.py@@ -349,11 +349,97 @@ class _UpstreamClosingStreamingResponse(StreamingResponse):)+class _ClientDisconnectedBeforeFirstChunk(Exception):+ """Client went away during create_response's first-chunk buffering window.++ The upstream LLM stream has already been closed by the time this is raised.+ """+++async def _wait_for_http_disconnect(request: Request) -> None:+ try:+ while True:+ message = await request.receive()+ if message.get("type") == "http.disconnect":+ return+ except asyncio.CancelledError:+ raise+ except Exception as exc: # noqa: BLE001+ verbose_proxy_logger.warning(+ "create_response: request.receive() raised %s; first-chunk disconnect "+ "monitoring disabled for this request",+ exc,+ )+ # A receive() failure must not masquerade as a disconnect.+ await asyncio.Event().wait()+++async def _buffer_first_chunk_honoring_disconnect(+ generator: AsyncGenerator[str, None],+ request: Optional[Request],+) -> str:+ """Fetch the first streamed chunk, cancelling the upstream LLM call if the+ client disconnects before it arrives.++ create_response buffers the first chunk to detect error-only streams before+ handing the StreamingResponse to Starlette, which only begins listening for+ client disconnects once it is serving that response. A disconnect during a+ long time-to-first-token would otherwise leave the upstream call running+ until the request timeout (LIT-3568). Cancelling the fetch propagates into+ async_streaming_data_generator, whose finally block records the 499 and+ closes the upstream stream.+ """+ if request is None:+ return await generator.__anext__()++ chunk_task: asyncio.Task[str] = asyncio.ensure_future(generator.__anext__())+ disconnect_task: asyncio.Task[None] = asyncio.ensure_future(+ _wait_for_http_disconnect(request)+ )+ try:+ await asyncio.wait(+ {chunk_task, disconnect_task}, return_when=asyncio.FIRST_COMPLETED+ )+ # A completed disconnect_task has already consumed the http.disconnect+ # message, so Starlette's later listen_for_disconnect would never see it.+ # Take the cancellation path whenever a disconnect was observed, even if+ # the first chunk landed in the same scheduler turn.+ disconnect_observed = disconnect_task.done()+ finally:+ disconnect_task.cancel()+ try:+ await disconnect_task+ except BaseException: # noqa: BLE001+ pass++ if not disconnect_observed and chunk_task.done() and not chunk_task.cancelled():+ return chunk_task.result()++ chunk_task.cancel()+ with anyio.CancelScope(shield=True):+ try:+ await chunk_task+ except BaseException: # noqa: BLE001+ pass+ try:+ await generator.aclose()+ except BaseException as exc: # noqa: BLE001+ verbose_proxy_logger.debug(+ "create_response: error closing generator on disconnect: %s", exc+ )+ verbose_proxy_logger.info(+ "create_response: client disconnected before first chunk, "+ "upstream LLM request cancelled"+ )+ raise _ClientDisconnectedBeforeFirstChunk()++async def create_response(generator: AsyncGenerator[str, None],media_type: str,headers: dict,default_status_code: int = status.HTTP_200_OK,+ request: Optional[Request] = None,) -> Union[StreamingResponse, JSONResponse]:"""Create streaming response, checking if the first chunk is an error.@@ -376,7 +462,9 @@ async def create_response(generator = await generator# Now get the first chunk from the actual generator- first_chunk_value = await generator.__anext__()+ first_chunk_value = await _buffer_first_chunk_honoring_disconnect(+ generator, request+ )if first_chunk_value is not None:try:@@ -409,6 +497,21 @@ async def create_response(except Exception as e:verbose_proxy_logger.debug(f"Error parsing first chunk value: {e}")+ except _ClientDisconnectedBeforeFirstChunk:+ # Client vanished during the time-to-first-token wait; the upstream+ # stream is already closed. Return a 499 the (now-gone) client never reads.+ return JSONResponse(+ status_code=LITELLM_HTTP_STATUS_CLIENT_DISCONNECTED,+ content={+ "error": {+ "message": _CLIENT_DISCONNECT_DETAIL,+ "type": "client_disconnect",+ "param": "None",+ "code": str(LITELLM_HTTP_STATUS_CLIENT_DISCONNECTED),+ }+ },+ headers=headers,+ )except StopAsyncIteration:# Generator was empty. Default statusasync def empty_gen() -> AsyncGenerator[str, None]:@@ -1587,6 +1690,7 @@ class ProxyBaseLLMRequestProcessing:generator=selected_data_generator,media_type="text/event-stream",headers=custom_headers,+ request=request,)# Non-streaming response - fall through to normal response handlingelif select_data_generator:@@ -1615,6 +1719,7 @@ class ProxyBaseLLMRequestProcessing:generator=selected_data_generator,media_type="text/event-stream",headers=custom_headers,+ request=request,)### CALL HOOKS ### - modify outgoing datadiff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex b49d8ad7965..b1f8e98bef3 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -11019,6 +11019,7 @@ async def run_thread(),media_type="text/event-stream",headers={}, # Added empty headers dict, original call missed this argument+ request=request,)### ALERTING ###diff --git a/tests/test_litellm/proxy/test_common_request_processing.py b/tests/test_litellm/proxy/test_common_request_processing.pyindex 3d3a2cc1013..c77ee2b784d 100644--- a/tests/test_litellm/proxy/test_common_request_processing.py+++ b/tests/test_litellm/proxy/test_common_request_processing.py@@ -17,7 +17,9 @@ from litellm.proxy.common_request_processing import (ProxyBaseLLMRequestProcessing,ProxyConfig,_await_llm_call_cancelling_on_disconnect,+ _buffer_first_chunk_honoring_disconnect,_cancel_llm_call_on_client_disconnect,+ _ClientDisconnectedBeforeFirstChunk,_extract_error_from_sse_chunk,_get_cost_breakdown_from_logging_obj,_has_attribute_error_in_chain,@@ -2676,6 +2678,176 @@ class TestStreamCloseOnDisconnect:assert upstream.aclosed+ @staticmethod+ def _request_that_disconnects() -> Request:+ async def receive():+ return {"type": "http.disconnect"}++ return Request({"type": "http", "method": "POST", "headers": []}, receive)++ @staticmethod+ def _request_that_stays_connected() -> Request:+ async def receive():+ await asyncio.Event().wait()++ return Request({"type": "http", "method": "POST", "headers": []}, receive)++ async def test_create_response_returns_499_on_disconnect_before_first_chunk(self):+ """LIT-3568: client disconnects during the time-to-first-token wait.++ create_response buffers the first chunk before Starlette starts serving+ the StreamingResponse, so this window has no disconnect listener. The+ request must be cancelled (upstream generator closed) and a 499 returned+ instead of blocking until the request timeout.+ """+ upstream_closed = asyncio.Event()++ async def never_yields_first_chunk():+ try:+ await asyncio.Event().wait()+ yield "data: never\n\n"+ finally:+ upstream_closed.set()++ response = await asyncio.wait_for(+ create_response(+ generator=never_yields_first_chunk(),+ media_type="text/event-stream",+ headers={},+ request=self._request_that_disconnects(),+ ),+ timeout=5,+ )++ assert isinstance(response, JSONResponse)+ assert response.status_code == 499+ assert upstream_closed.is_set()++ async def test_create_response_streams_normally_when_connected(self):+ """The disconnect race must not steal a first chunk that does arrive:+ a connected client still gets a StreamingResponse, not a 499."""++ async def yields_immediately():+ yield "data: hello\n\n"+ yield "data: world\n\n"++ response = await asyncio.wait_for(+ create_response(+ generator=yields_immediately(),+ media_type="text/event-stream",+ headers={},+ request=self._request_that_stays_connected(),+ ),+ timeout=5,+ )++ assert isinstance(response, StreamingResponse)+ assert response.status_code == status.HTTP_200_OK++ async def test_buffer_first_chunk_without_request_is_passthrough(self):+ """No request -> preserve the original eager __anext__ behavior."""++ async def gen():+ yield "data: first\n\n"++ first = await _buffer_first_chunk_honoring_disconnect(gen(), request=None)+ assert first == "data: first\n\n"++ async def test_create_response_prioritizes_disconnect_in_same_scheduler_turn(self):+ """Same-turn race: the first chunk and the disconnect both resolve before+ the branch runs. Because the disconnect watcher has already consumed+ http.disconnect, returning the chunk would leave Starlette's later+ listener blind to it and the upstream running. The observed disconnect+ must win -> 499 and the generator closed."""+ closed = asyncio.Event()++ async def yields_immediately():+ try:+ yield "data: hello\n\n"+ finally:+ closed.set()++ response = await asyncio.wait_for(+ create_response(+ generator=yields_immediately(),+ media_type="text/event-stream",+ headers={},+ request=self._request_that_disconnects(),+ ),+ timeout=5,+ )++ assert isinstance(response, JSONResponse)+ assert response.status_code == 499+ assert closed.is_set()++ async def test_receive_error_does_not_trigger_false_disconnect(self):+ """A request.receive() that raises must not masquerade as a disconnect;+ a first chunk that arrives is still served as a normal stream."""++ async def receive():+ raise RuntimeError("receive boom")++ request = Request({"type": "http", "method": "POST", "headers": []}, receive)++ async def yields_immediately():+ yield "data: hello\n\n"++ response = await asyncio.wait_for(+ create_response(+ generator=yields_immediately(),+ media_type="text/event-stream",+ headers={},+ request=request,+ ),+ timeout=5,+ )++ assert isinstance(response, StreamingResponse)+ assert response.status_code == status.HTTP_200_OK++ async def test_disconnect_cancellation_survives_generator_aclose_error(self):+ """A failing upstream aclose() during disconnect cleanup must not swallow+ the disconnect signal: the sentinel is still raised."""++ class AcloseRaises:+ def __aiter__(self):+ return self++ async def __anext__(self):+ await asyncio.Event().wait()+ raise StopAsyncIteration++ async def aclose(self):+ raise RuntimeError("aclose boom")++ with pytest.raises(_ClientDisconnectedBeforeFirstChunk):+ await asyncio.wait_for(+ _buffer_first_chunk_honoring_disconnect(+ AcloseRaises(), request=self._request_that_disconnects()+ ),+ timeout=5,+ )++ async def test_buffer_first_chunk_raises_sentinel_and_closes_on_disconnect(self):+ closed = asyncio.Event()++ async def blocking_gen():+ try:+ await asyncio.Event().wait()+ yield "data: never\n\n"+ finally:+ closed.set()++ with pytest.raises(_ClientDisconnectedBeforeFirstChunk):+ await asyncio.wait_for(+ _buffer_first_chunk_honoring_disconnect(+ blocking_gen(), request=self._request_that_disconnects()+ ),+ timeout=5,+ )+ assert closed.is_set()+class TestHandleLLMApiExceptionRetryAfter:"""RouterRateLimitError cooldown_time must surface as a retry-after header."""