Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 40 additions & 2 deletions litellm/responses/streaming_iterator.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import time
import traceback
import uuid
from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence
from collections.abc import Awaitable, Callable, Coroutine, Iterable, Mapping, Sequence
from datetime import datetime
from functools import lru_cache
from types import MappingProxyType
Expand Down Expand Up @@ -169,6 +169,25 @@ def _log_background_task_failure(task: asyncio.Task[object], *, task_name: str)
verbose_logger.error("%s failed: %s", task_name, exception)


_PENDING_LOGGING_TASKS: Final[set[asyncio.Task[object]]] = set() # mutable-ok: strong refs to pending logging tasks


def _running_loop() -> asyncio.AbstractEventLoop | None:
try:
return asyncio.get_running_loop()
except RuntimeError:
return None


def _spawn_logging_task(
running_loop: asyncio.AbstractEventLoop, coroutine: Coroutine[object, object, object], *, task_name: str
) -> None:
task: Final = running_loop.create_task(coroutine)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
_PENDING_LOGGING_TASKS.add(task)
task.add_done_callback(_PENDING_LOGGING_TASKS.discard)
task.add_done_callback(lambda done: _log_background_task_failure(done, task_name=task_name))


_ERROR_CODE_HTTP_STATUS: Final[Mapping[str, int]] = MappingProxyType(
{
"server_error": 500,
Expand Down Expand Up @@ -839,8 +858,19 @@ def _run_post_success_hooks(self, end_time: datetime):
except Exception:
typed_call_type = None

running_loop: Final = _running_loop()
if running_loop is not None:
_spawn_logging_task(
running_loop,
async_post_call_success_deployment_hook(
request_data=request_payload,
response=self.completed_response,
call_type=typed_call_type,
),
task_name="Responses stream post-call success hook",
)
return
try:
# Call synchronously; async hook will be executed via asyncio.run in a new loop
run_async_function(
async_function=async_post_call_success_deployment_hook,
request_data=request_payload,
Expand All @@ -861,6 +891,14 @@ def _handle_failure(self, exception: Exception):
self._failure_handled = True

traceback_exception: Final = traceback.format_exc()
running_loop: Final = _running_loop()
if running_loop is not None:
_spawn_logging_task(
running_loop,
self.logging_obj.dispatch_failure_handlers(exception, traceback_exception, prefer_async_handlers=True),
task_name="Responses stream failure logging",
)
return
try:
run_async_function(
async_function=self.logging_obj.async_failure_handler,
Expand Down
5 changes: 5 additions & 0 deletions tests/llm_responses_api_testing/test_responses_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ async def async_success_handler(self, *args, **kwargs):
self.async_success_calls += 1
self.last_async_success_kwargs = kwargs

async def dispatch_failure_handlers(self, *args, **kwargs):
kwargs.pop("prefer_async_handlers", None)
await self.async_failure_handler(*args, **kwargs)
self.failure_handler(*args, **kwargs)

def failure_handler(self, *args, **kwargs):
self.failure_calls += 1

Expand Down
98 changes: 94 additions & 4 deletions tests/unit/responses/test_streaming_iterator.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
(Prometheus, OTEL, SpendLogs completionStartTime) do not fall back to
completion_start_time = end_time."""

import asyncio
import json
from collections.abc import Callable
from datetime import datetime
from typing import Final, Optional
from unittest.mock import AsyncMock, Mock, patch
Expand All @@ -14,6 +16,7 @@

import litellm
from litellm.exceptions import MidStreamFallbackError
from litellm.integrations.custom_logger import CustomLogger
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.llms.base_llm.responses.transformation import BaseResponsesAPIConfig
from litellm.responses.streaming_iterator import (
Expand Down Expand Up @@ -266,6 +269,7 @@ def test_sync_transport_error_before_completed_event_raises():
def _failure_tracking_logging_obj() -> Mock:
logging_obj: Final = _logging_obj_stub()
logging_obj.async_failure_handler = AsyncMock()
logging_obj.dispatch_failure_handlers = AsyncMock()
return logging_obj


Expand All @@ -274,6 +278,12 @@ def _assert_failure_logged_once(logging_obj: Mock, exception: Exception) -> None
assert logging_obj.async_failure_handler.await_args.kwargs["exception"] is exception


async def _assert_failure_dispatched_once(logging_obj: Mock, exception: Exception) -> None:
await asyncio.sleep(0)
assert logging_obj.dispatch_failure_handlers.await_count == 1
assert logging_obj.dispatch_failure_handlers.await_args.args[0] is exception


@pytest.mark.asyncio
@pytest.mark.parametrize("prefix, pre_first_chunk", _PRE_OUTPUT_PREFIXES)
@pytest.mark.parametrize("trailing_error", _TRAILING_ERRORS, ids=type)
Expand All @@ -291,7 +301,7 @@ async def test_transport_error_before_any_output_raises_fallback_error(prefix, p
assert exc_info.value.original_exception is trailing_error
assert exc_info.value.is_pre_first_chunk is pre_first_chunk
assert exc_info.value.generated_content == ""
_assert_failure_logged_once(logging_obj, trailing_error)
await _assert_failure_dispatched_once(logging_obj, trailing_error)


@pytest.mark.asyncio
Expand All @@ -307,7 +317,7 @@ async def test_transport_error_after_output_started_is_not_fallback_eligible():
pass

assert exc_info.value is trailing_error
_assert_failure_logged_once(logging_obj, trailing_error)
await _assert_failure_dispatched_once(logging_obj, trailing_error)


@pytest.mark.asyncio
Expand All @@ -327,7 +337,7 @@ async def test_stream_ending_after_partial_output_without_terminal_event_raises(
assert (created.type, delta.type) == ("response.created", "response.output_text.delta")
assert not isinstance(exc_info.value, MidStreamFallbackError)
assert exc_info.value.llm_provider == "openai"
_assert_failure_logged_once(logging_obj, exc_info.value)
await _assert_failure_dispatched_once(logging_obj, exc_info.value)


@pytest.mark.asyncio
Expand All @@ -344,7 +354,7 @@ async def test_stream_ending_before_any_output_raises_fallback_error(prefix, pre
assert isinstance(exc_info.value.original_exception, litellm.APIConnectionError)
assert exc_info.value.is_pre_first_chunk is pre_first_chunk
assert exc_info.value.generated_content == ""
_assert_failure_logged_once(logging_obj, exc_info.value.original_exception)
await _assert_failure_dispatched_once(logging_obj, exc_info.value.original_exception)


@pytest.mark.asyncio
Expand All @@ -356,6 +366,7 @@ async def test_complete_stream_still_ends_normally(trailer):
seen: Final = [event.type async for event in iterator]

assert seen[-1] == ResponsesAPIStreamEvents.RESPONSE_COMPLETED
assert logging_obj.dispatch_failure_handlers.await_count == 0
assert logging_obj.async_failure_handler.await_count == 0


Expand Down Expand Up @@ -417,6 +428,85 @@ def test_sync_complete_stream_still_ends_normally(trailer):
assert logging_obj.async_failure_handler.await_count == 0


class _LoopRecordingLogger(CustomLogger):
def __init__(self) -> None:
super().__init__()
self.failure_loop: asyncio.AbstractEventLoop | None = None
self.failure_finished = False
self.hook_loop: asyncio.AbstractEventLoop | None = None
self.hook_finished = False

async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time):
self.failure_loop = asyncio.get_running_loop()
await asyncio.sleep(0.05)
self.failure_finished = True

async def async_post_call_success_deployment_hook(self, request_data, response, call_type):
self.hook_loop = asyncio.get_running_loop()
await asyncio.sleep(0.05)
self.hook_finished = True
return None


def _real_logging_obj() -> LiteLLMLoggingObj:
logging_obj: Final = LiteLLMLoggingObj(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "hi"}],
stream=True,
call_type="aresponses",
start_time=datetime.now(),
litellm_call_id="lit-8678-test",
function_id="lit-8678-test",
)
logging_obj.model_call_details["litellm_params"] = {"aresponses": True}
return logging_obj


async def _wait_until(condition: Callable[[], bool]) -> None:
for _ in range(200):
if condition():
return
await asyncio.sleep(0.01)
raise AssertionError("condition never became true")


@pytest.mark.asyncio
async def test_transport_error_failure_logging_runs_on_the_iterating_loop(monkeypatch):
"""LIT-8678: a stream failure used to run async_failure_handler on a helper loop in a
worker thread and block the iterating loop until it finished, so a callback waiting on
state bound to that loop (a batch logger's flush lock) stalled the whole proxy."""
recorder: Final = _LoopRecordingLogger()
monkeypatch.setattr(litellm, "_async_failure_callback", [recorder])
monkeypatch.setattr(litellm, "failure_callback", [])
iterator: Final = _make_iterator(
sse_events=_PARTIAL_OUTPUT_EVENTS,
logging_obj=_real_logging_obj(),
trailing_error=httpx.ReadError("Response payload is not completed"),
)

with pytest.raises(httpx.ReadError):
async for _ in iterator:
pass

assert recorder.failure_finished is False
await _wait_until(lambda: recorder.failure_finished)
assert recorder.failure_loop is asyncio.get_running_loop()


@pytest.mark.asyncio
async def test_completed_stream_success_deployment_hook_runs_on_the_iterating_loop(monkeypatch):
recorder: Final = _LoopRecordingLogger()
monkeypatch.setattr(litellm, "callbacks", [recorder])
iterator: Final = _make_iterator(sse_events=_COMPLETE_STREAM_EVENTS, logging_obj=_logging_obj_stub())

async for _ in iterator:
pass

assert recorder.hook_finished is False
await _wait_until(lambda: recorder.hook_finished)
assert recorder.hook_loop is asyncio.get_running_loop()


def test_stream_cache_write_completes_when_asyncio_run_closes_the_loop(monkeypatch):
"""
Regression test for LIT-6184 on the /v1/responses streaming surface: the
Expand Down
Loading