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(responses): keep strong refs to stream and websocket logging tasks (GC race) (#31074)
Charles5a1fa1c87950
diff --git a/litellm/responses/streaming_iterator.py b/litellm/responses/streaming_iterator.pyindex ffde8c66c20..bcd917c69d5 100644--- a/litellm/responses/streaming_iterator.py+++ b/litellm/responses/streaming_iterator.py@@ -622,7 +622,9 @@ class BaseResponsesAPIStreamingIterator:# the terminal event; dispatching now would snapshot metadata early.self.logging_obj._deferred_stream_complete_args = (logging_coroutine,)else:- asyncio.create_task(logging_coroutine)+ spawn_logging_task(+ asyncio.get_running_loop(), logging_coroutine, task_name="Responses stream success logging"+ )else:run_async_function(async_function=self.logging_obj.async_success_handler,@@ -2385,14 +2387,20 @@ class ResponsesWebSocketStreaming:events: Final = list(turn.events)exception: Final = turn.failure(self.authorized_model or "", self.custom_llm_provider or "", self.logging_obj)if exception is None:- asyncio.create_task(turn.logging_obj.dispatch_success_handlers(events, prefer_async_handlers=True))+ spawn_logging_task(+ asyncio.get_running_loop(),+ turn.logging_obj.dispatch_success_handlers(events, prefer_async_handlers=True),+ task_name="Responses WebSocket success logging",+ )returnif self._failure is None:self._failure = exception_record_usage_for_failure(turn.logging_obj, events)traceback_exception: Final = "".join(traceback.format_exception(exception))- asyncio.create_task(- turn.logging_obj.dispatch_failure_handlers(exception, traceback_exception, prefer_async_handlers=True)+ spawn_logging_task(+ asyncio.get_running_loop(),+ turn.logging_obj.dispatch_failure_handlers(exception, traceback_exception, prefer_async_handlers=True),+ task_name="Responses WebSocket failure logging",)def _wrap_response_event(self, response_str: str) -> str:diff --git a/tests/unit/llms/base_llm/responses/test_transformation.py b/tests/unit/llms/base_llm/responses/test_transformation.pyindex eb01cc8a9ce..8d21af83668 100644--- a/tests/unit/llms/base_llm/responses/test_transformation.py+++ b/tests/unit/llms/base_llm/responses/test_transformation.py@@ -24,7 +24,7 @@ from litellm.types.llms.openai import(ResponsesAPIStreamEvents,)from tests._vcr_conftest_common import install_live_call_probe, record_vcr_outcome-from typing import Any, AsyncIterator, List+from typing import Any, AsyncIterator, Final, Listfrom unittest.mock import AsyncMock, MagicMock, Mock, patch@@ -438,9 +438,9 @@ class TestBaseResponsesAPIStreamingIterator:# This should NOT raise an exception# Previously it would fail with: TypeError: cannot pickle 'ValidatorIterator'- # Mock asyncio.create_task and executor.submit since we're not in async contextwith (- patch("asyncio.create_task") as mock_create_task,+ patch("asyncio.get_running_loop"),+ patch("litellm.responses.streaming_iterator.spawn_logging_task"),patch("litellm.responses.streaming_iterator.executor") as mock_executor,):try:@@ -728,7 +728,8 @@ class TestBaseResponsesAPIStreamingIterator:"update_responses_api_response_id_with_model_id",return_value=mock_responses_api_response,),- patch("asyncio.create_task") as mock_create_task,+ patch("asyncio.get_running_loop"),+ patch("litellm.responses.streaming_iterator.spawn_logging_task") as mock_spawn_logging_task,patch("litellm.responses.streaming_iterator.executor") as mock_executor,):result = iterator._process_chunk(json.dumps(test_chunk_data))@@ -739,7 +740,8 @@ class TestBaseResponsesAPIStreamingIterator:# Success handlers are dispatched as one async task (via _handle_logging_completed_response);# the sync handler must never be submitted to the executor concurrently (LIT-4210)- mock_create_task.assert_called_once()+ spawned_task_names: Final = [call.kwargs["task_name"] for call in mock_spawn_logging_task.call_args_list]+ assert spawned_task_names.count("Responses stream success logging") == 1mock_executor.submit.assert_not_called()# Failure handlers should NOT have been calleddiff --git a/tests/unit/proxy/guardrails/test_deferred_guardrail_logging.py b/tests/unit/proxy/guardrails/test_deferred_guardrail_logging.pyindex 17427e839b9..7e5d0f6342e 100644--- a/tests/unit/proxy/guardrails/test_deferred_guardrail_logging.py+++ b/tests/unit/proxy/guardrails/test_deferred_guardrail_logging.py@@ -16,7 +16,7 @@ Streaming: CSW.__anext__ stores args on logging_obj at stream end.import asyncioimport logging-from collections.abc import Callable, Mapping+from collections.abc import Callable, Coroutine, Mappingfrom datetime import datetimefrom typing import Any, Final, castfrom unittest.mock import AsyncMock, MagicMock, patch@@ -1442,10 +1442,10 @@ class TestResponsesIteratorDeferredLogging:logging_obj._on_deferred_stream_complete = MagicMock()iterator = self._iterator(logging_obj)- with patch("asyncio.create_task") as mock_create_task:+ with patch("litellm.responses.streaming_iterator.spawn_logging_task") as mock_spawn_logging_task:iterator._log_completed_response(is_async=True)- mock_create_task.assert_not_called()+ mock_spawn_logging_task.assert_not_called()args = logging_obj._deferred_stream_complete_argsassert isinstance(args, tuple) and len(args) == 1assert "dispatched" not in recorded@@ -1458,15 +1458,25 @@ class TestResponsesIteratorDeferredLogging:logging_obj._on_deferred_stream_complete = Noneiterator = self._iterator(logging_obj)- created = []- real_create_task = asyncio.create_task+ from litellm.responses import streaming_iterator- def tracking_create_task(coro):- task = real_create_task(coro)+ created: Final[list[asyncio.Task[object]]] = []+ real_spawn_logging_task: Final = streaming_iterator.spawn_logging_task++ def tracking_spawn_logging_task(+ running_loop: asyncio.AbstractEventLoop,+ coroutine: Coroutine[object, object, object],+ *,+ task_name: str,+ ) -> asyncio.Task[object]:+ task: Final = real_spawn_logging_task(running_loop, coroutine, task_name=task_name)created.append(task)return task- with patch("asyncio.create_task", side_effect=tracking_create_task):+ with patch(+ "litellm.responses.streaming_iterator.spawn_logging_task",+ side_effect=tracking_spawn_logging_task,+ ):iterator._log_completed_response(is_async=True)assert len(created) == 1diff --git a/tests/unit/responses/test_streaming_iterator.py b/tests/unit/responses/test_streaming_iterator.pyindex e5054ed3cef..d0e07e1cc23 100644--- a/tests/unit/responses/test_streaming_iterator.py+++ b/tests/unit/responses/test_streaming_iterator.py@@ -5,8 +5,10 @@ completion_start_time = end_time."""import asyncio, importlibimport functools+import gcimport jsonimport threading+import weakreffrom collections.abc import Callable, Mappingfrom datetime import datetimefrom typing import Final, Optional@@ -14,6 +16,7 @@ from unittest.mock import AsyncMock, MagicMock, Mock, patchimport httpximport pytest+import websockets.exceptionsfrom pydantic_core import PydanticSerializationErrorimport litellm@@ -509,16 +512,22 @@ class _OrderRecordingSyncLogger(CustomLogger):def _real_logging_obj(- *, call_type: str = "aresponses", litellm_params: dict[str, object] | None = None+ *,+ call_type: str = "aresponses",+ litellm_params: dict[str, object] | None = None,+ callbacks: tuple[CustomLogger, ...] | None = None,+ stream: bool = True,) -> LiteLLMLoggingObj:logging_obj: Final = LiteLLMLoggingObj(model="gpt-4o-mini",messages=[{"role": "user", "content": "hi"}],- stream=True,+ stream=stream,call_type=call_type,start_time=datetime.now(),litellm_call_id="lit-8678-test",function_id="lit-8678-test",+ dynamic_async_success_callbacks=None if callbacks is None else list(callbacks),+ dynamic_async_failure_callbacks=None if callbacks is None else list(callbacks),)logging_obj.model_call_details["litellm_params"] = (dict(litellm_params) if litellm_params is not None else {"aresponses": True}@@ -2598,24 +2607,156 @@ def test_faked_stream_builds_each_refusal_summary_and_custom_tool_input_once_for@pytest.mark.asyncioasync def test_shutdown_drain_waits_for_a_pending_logging_task():- row_written = asyncio.Event()-- async def write_row():- await asyncio.sleep(0.05)- row_written.set()-- streaming_module.spawn_logging_task(asyncio.get_running_loop(), write_row(), task_name="row")+ release: Final = asyncio.Event()+ row: Final = streaming_module.spawn_logging_task(asyncio.get_running_loop(), release.wait(), task_name="row")- await streaming_module.drain_logging_tasks(timeout=1)+ drain_held: Final = await _drain_held_until_released(release)- assert row_written.is_set()+ assert drain_held+ assert row.done()@pytest.mark.asyncioasync def test_shutdown_drain_gives_up_on_a_stuck_logging_task_at_its_timeout():- stuck = streaming_module.spawn_logging_task(asyncio.get_running_loop(), asyncio.Event().wait(), task_name="stuck")+ stuck: Final = streaming_module.spawn_logging_task(asyncio.get_running_loop(), asyncio.Event().wait(), task_name="stuck")await asyncio.wait_for(streaming_module.drain_logging_tasks(timeout=0.05), timeout=1)assert not stuck.done()stuck.cancel()+++async def _drain_held_until_released(release: asyncio.Event) -> bool:+ drain: Final = asyncio.create_task(streaming_module.drain_logging_tasks(timeout=5))+ await asyncio.sleep(0)+ held: Final = not drain.done()+ release.set()+ await drain+ return held+++class _GatedLogger(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.entered: Final = asyncio.Event()+ self.release: Final = asyncio.Event()+ self.logged = False++ async def _log(self) -> None:+ self.entered.set()+ await self.release.wait()+ self.logged = True++ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):+ await self._log()++ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time):+ await self._log()+++class _UnreferencedWaitLogger(CustomLogger):+ def __init__(self) -> None:+ super().__init__()+ self.parked: Final = asyncio.Event()+ self.waiting_tasks: Final = weakref.WeakSet[asyncio.Task[object]]()++ async def _wait_forever(self) -> None:+ self.waiting_tasks.add(asyncio.current_task())+ self.parked.set()+ await asyncio.get_running_loop().create_future()++ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):+ await self._wait_forever()++ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time):+ await self._wait_forever()+++async def _shutdown_drain_held_for(logger: _GatedLogger) -> bool:+ await asyncio.wait_for(logger.entered.wait(), timeout=5)+ return await _drain_held_until_released(logger.release)+++async def _logging_tasks_left_after_garbage_collection(logger: _UnreferencedWaitLogger) -> int:+ await asyncio.wait_for(logger.parked.wait(), timeout=5)+ gc.collect()+ survivors: Final = tuple(logger.waiting_tasks)+ for task in survivors:+ task.cancel()+ await asyncio.gather(*survivors, return_exceptions=True)+ return len(survivors)+++async def _stream_to_completion(logger: CustomLogger) -> None:+ iterator: Final = _make_iterator(+ sse_events=_COMPLETE_STREAM_EVENTS, logging_obj=_real_logging_obj(callbacks=(logger,))+ )+ async for _ in iterator:+ pass+++_WS_TERMINAL_EVENTS: Final = [+ pytest.param({"type": "response.completed", "response": {}}, id="success"),+ pytest.param(+ {"type": "response.failed", "response": {"error": {"code": "server_error", "message": "boom"}}},+ id="failure",+ ),+]+++async def _run_websocket_turn(logger: CustomLogger, terminal_event: dict[str, object]) -> None:+ backend_ws: Final = MagicMock()+ backend_ws.recv = AsyncMock(+ side_effect=[json.dumps(terminal_event), websockets.exceptions.ConnectionClosedOK(None, None)]+ )+ streaming: Final = streaming_module.ResponsesWebSocketStreaming(+ websocket=MagicMock(send_text=AsyncMock()),+ backend_ws=backend_ws,+ logging_obj=_real_logging_obj(+ call_type=CallTypes.aresponses_websocket.value,+ litellm_params={CallTypes.aresponses_websocket.value: True},+ callbacks=(logger,),+ stream=False,+ ),+ )+ await streaming.backend_to_client()+++async def test_shutdown_drain_waits_for_a_completed_streams_success_logging():+ logger: Final = _GatedLogger()+ await _stream_to_completion(logger)++ drain_held: Final = await _shutdown_drain_held_for(logger)++ assert drain_held+ assert logger.logged++[email protected]("terminal_event", _WS_TERMINAL_EVENTS)+async def test_shutdown_drain_waits_for_a_websocket_turns_logging(terminal_event: dict[str, object]):+ logger: Final = _GatedLogger()+ await _run_websocket_turn(logger, terminal_event)++ drain_held: Final = await _shutdown_drain_held_for(logger)++ assert drain_held+ assert logger.logged+++async def test_completed_streams_success_logging_survives_garbage_collection():+ logger: Final = _UnreferencedWaitLogger()+ await _stream_to_completion(logger)++ assert await _logging_tasks_left_after_garbage_collection(logger) == 1++[email protected]("terminal_event", _WS_TERMINAL_EVENTS)+async def test_websocket_turns_logging_survives_garbage_collection(terminal_event: dict[str, object]):+ logger: Final = _UnreferencedWaitLogger()+ await _run_websocket_turn(logger, terminal_event)++ assert await _logging_tasks_left_after_garbage_collection(logger) == 1