litellm/tests/unit/proxy/test_modify_response_streaming_passthrough.py
srik-straiker f92a40faa6
feat(guardrails): hold streamed tool calls for the verdict and log prompts blocked with a reply (#51872)
* feat(guardrails): opt-in hold of streamed tool calls until the end-of-stream verdict

A guardrail that checks a live stream once, at its end (streaming_end_of_stream_only
without streaming_buffer_until_moderated), releases every chunk as it arrives and
holds back only the stream's final frames. A tool call in that stream reaches the
client before the verdict exists, so a client that runs tools has already run it
when the guardrail blocks.

streaming_hold_tool_calls is a new streaming flag, off by default and read the same
way as the other streaming flags. With it on, the shared streaming loop also holds
everything from the first item that starts a tool call the client would run. Text
before the tool call still streams live. The held items are released in order when
the check passes and dropped when it blocks, through the handling the final frames
already had.

The hold applies in every mode that releases a stream before its end-of-stream
verdict: scanned once at its end, scanned every few chunks in the foreground or in
the background, and the incremental text transform, which keeps back its raw
tool-call chunks until its end-of-stream block inspection. A stream buffered until
moderated already waits for a scan and is unchanged.

A held tool call is released only on a verdict that covered it. A stream that stops
without its terminal marker (an upstream error, a cut connection) is scanned closed
the way its endpoint ends a stream, as it already is after a client disconnect.

Each endpoint translation answers starts_client_tool_call for one stream item, so
nothing re-walks the stream: chat completions, messages, responses (every output
item the client runs) and the Bedrock pass-through frames, Converse and invoke.
The base answer is False: a guardrail that does not set the flag, and an endpoint
with no answer of its own, behave as before.

With the flag on, the loop reads the stream in whole frames. Native /v1/messages
relays raw transport reads, so an SSE event can arrive split across two of them,
which hides the start of a tool call, and the end of the stream, from a check that
reads one item at a time. split_whole_stream_frames cuts each read at the last
frame boundary and carries the rest into the next read. The client receives the
same bytes.

The Straiker guardrail sets the flag when stream_mode is "streaming". "buffered"
already holds the whole response and is unchanged.

* feat(guardrails): opt-in failure logging for a prompt blocked with a reply

A guardrail that blocks the prompt by raising ModifyResponseException is answered
with an HTTP 200 reply. The LLM is never called and the reply runs no success
logging, so the block reaches no logging callback on non-streamed chat completions,
messages, responses or text completions. Only a streamed chat completion logs it,
as a success event from the stream wrapper.

ModifyResponseException takes a new log_as_failure argument, off by default. When
a block sets it, post_call_failure_hook treats it like the other proxy-only errors
and sends one failure event to the logging callbacks.
The streamed chat completion path tells the hook its reply already logs a success
event, so that route still logs exactly one event.

A guardrail that does not set it behaves as before. Blocked answers and the spend
logs are unchanged.

The Straiker guardrail sets it on the reply it raises for a blocked prompt.

* fix(guardrails): always run the end-of-stream round while a tool call is held

The end-of-stream round was skipped as redundant when its scan key equalled the
key of the last sampled round. A scan key carries only what a translation
fingerprints, so with a held item it does not fingerprint (a Responses
shell_call, apply_patch_call or computer_call), the keys matched and the item was
released with no round after it arrived. The round now always runs while a tool
call is held, so a guardrail that reads the whole response judges the item.

The whole-frame split goes through a typed translation variable. The untyped
lookup it used left three later call sites partially unknown to the type checker.

Tests: the blocked-prompt logging test waits for the callback instead of a fixed
delay, and the new recording callback and its fixtures are typed.

* fix(guardrails): hold the whole stream on a route that cannot tell a tool call apart

With streaming_hold_tool_calls on, a translation with no tool-call detection, the
native Gemini generateContent one for example, answered that no stream item starts
a tool call, so a functionCall part reached the client before the end-of-stream
verdict.

The base answer of starts_client_tool_call is now True: a translation that cannot
tell a tool call apart holds its whole stream for the verdict. Text completions
answer False, since they carry no tool calls. A pass-through stream no translation
reads is not scanned at all, so it is still not held.

A guardrail that does not set the flag is unaffected.

* feat(straiker): hold_tool_calls option to turn the streamed tool-call hold off

In stream_mode `streaming` the guardrail holds a tool call the client would
run until the end-of-stream verdict. That was fixed on, with no way out for a
deployment that prefers tool calls to stream as they arrive.

`hold_tool_calls` (default true) is read only in `streaming` mode. False
releases tool calls as they arrive, as before the hold existed. A value the
initializer cannot read keeps the hold and logs a warning: raising there
would start the proxy without the guardrail.

* feat(guardrails): tell a function call apart on Gemini streams, so only it is held

With the tool-call hold on, the native Gemini generateContent route held its
whole stream for the verdict, because its translation could not tell a tool
call apart. Text that streamed live before arrived in one burst at the end.

The translation now recognises a functionCall part. Text streams live and
everything from the first function call waits for the verdict. An item it
cannot read for a function call (a cut event, a payload that is not a JSON
object) still waits.

A translation that never scans a stream gives no verdict to hold for, so the
base answer now holds a whole stream only for a translation that scans it.

* test(guardrails): type the new test helpers and drop a banned suppression

The hold_tool_calls tests in test_straiker.py left parameters and return
types unannotated, and the Gemini detection table used `# type: ignore`,
which the repository bans. The fixture now builds the second candidate with
a typed helper instead of indexing into a dict.
2026-11-20 16:58:15 -08:00

364 lines
15 KiB
Python

"""Regression test for the ModifyResponseException streaming passthrough.
When a guardrail blocks a *streaming* request pre-call by raising
``ModifyResponseException``, the chat-completion route streams the violation
message back as a 200 by building a ``CustomStreamWrapper``. The logging object
must be read from ``e.request_data`` (the processor's data, which carries
``litellm_logging_obj``) and NOT from the outer request body returned by
``_read_request_body`` -- the two diverge at ``function_setup`` and only the
processor copy gets ``litellm_logging_obj`` attached.
Reading it from the outer body passed ``logging_obj=None`` to
``CustomStreamWrapper.__init__``, which dereferences
``logging_obj.model_call_details`` and 500s with
``AttributeError: 'NoneType' object has no attribute 'model_call_details'``.
"""
import asyncio
import json
from collections.abc import AsyncGenerator, Mapping
from typing import Final
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi import Request, Response
from fastapi.responses import StreamingResponse
from starlette.types import Message
import litellm
import litellm.proxy.proxy_server as proxy_server
from litellm.caching.dual_cache import DualCache
from litellm.exceptions import RejectedRequestError
from litellm.integrations.custom_guardrail import CustomGuardrail, ModifyResponseException
from litellm.integrations.custom_logger import CustomLogger
from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
from litellm.proxy._types import UserAPIKeyAuth
from litellm.proxy.proxy_server import chat_completion, completion
from litellm.proxy.utils import ProxyLogging
from litellm.types.guardrails import GuardrailEventHooks
from litellm.types.utils import ModelResponse, ModelResponseStream, TextCompletionResponse
async def _run_streaming_block_and_get_wrapper(exception):
"""Drive chat_completion's streaming guardrail-passthrough handler for the
given pre-call block exception and return the patched CustomStreamWrapper.
The outer request body (what _read_request_body returns) is a streaming
request that does NOT carry litellm_logging_obj -- mirroring production,
where the outer body diverges from the processor's data at function_setup.
Only the processor copy (exposed as exception.request_data) carries it.
"""
request = MagicMock(spec=Request)
fastapi_response = MagicMock(spec=Response)
user_api_key_dict = UserAPIKeyAuth()
outer_body = {"model": "gpt-4o", "messages": [], "stream": True}
with patch(
"litellm.proxy.proxy_server.read_request_body",
new_callable=AsyncMock,
return_value=outer_body,
), patch(
"litellm.proxy.proxy_server.ProxyBaseLLMRequestProcessing.base_process_llm_request",
new_callable=AsyncMock,
side_effect=exception,
), patch(
"litellm.proxy.proxy_server.proxy_logging_obj"
) as mock_proxy_logging, patch(
"litellm.proxy.proxy_server.select_data_generator",
return_value=iter([]),
), patch(
"litellm.CustomStreamWrapper"
) as mock_csw:
mock_proxy_logging.post_call_failure_hook = AsyncMock()
await chat_completion(
request=request,
fastapi_response=fastapi_response,
user_api_key_dict=user_api_key_dict,
)
return mock_csw
@pytest.mark.asyncio
async def test_streaming_modify_response_uses_request_data_logging_obj():
sentinel_logging_obj = MagicMock(name="litellm_logging_obj")
exception = ModifyResponseException(
message="blocked by guardrail",
model="gpt-4o",
request_data={
"model": "gpt-4o",
"stream": True,
"litellm_logging_obj": sentinel_logging_obj,
},
guardrail_name="test-guardrail",
)
mock_csw = await _run_streaming_block_and_get_wrapper(exception)
# The wrapper must be built with the logging object from e.request_data,
# NOT None (which is what the outer body would have yielded).
mock_csw.assert_called_once()
assert mock_csw.call_args.kwargs["logging_obj"] is sentinel_logging_obj
@pytest.mark.asyncio
async def test_streaming_rejected_request_uses_request_data_logging_obj():
# RejectedRequestError gets the identical fix in its own streaming
# passthrough handler, so it needs the same regression guard.
sentinel_logging_obj = MagicMock(name="litellm_logging_obj")
exception = RejectedRequestError(
message="rejected by guardrail",
model="gpt-4o",
llm_provider="openai",
request_data={
"model": "gpt-4o",
"stream": True,
"litellm_logging_obj": sentinel_logging_obj,
},
)
mock_csw = await _run_streaming_block_and_get_wrapper(exception)
mock_csw.assert_called_once()
assert mock_csw.call_args.kwargs["logging_obj"] is sentinel_logging_obj
_BLOCK_TEXT: Final = "blocked by guardrail"
_PING: Final = ": ping"
class _BlockEveryRequestOnceReleased(CustomGuardrail):
def __init__(self, released: asyncio.Event) -> None:
super().__init__(guardrail_name="deny-list", event_hook=GuardrailEventHooks.pre_call, default_on=True)
self.released: Final = released
self.failures: tuple[Exception, ...] = ()
async def async_pre_call_hook(
self, user_api_key_dict: UserAPIKeyAuth, cache: DualCache, data: dict[str, object], call_type: str
) -> None:
await self.released.wait()
self.raise_passthrough_exception(violation_message=_BLOCK_TEXT, request_data=data)
async def async_post_call_failure_hook(
self,
request_data: dict[str, object],
original_exception: Exception,
user_api_key_dict: UserAPIKeyAuth,
traceback_str: str | None = None,
) -> None:
self.failures = (*self.failures, original_exception)
class _BlockEveryRequestAskingToBeLogged(CustomGuardrail):
"""Blocks the prompt with a reply and asks for the block to be logged. Records the logging events it is sent."""
def __init__(self) -> None:
super().__init__(guardrail_name="deny-list", event_hook=GuardrailEventHooks.pre_call, default_on=True)
self.logged: tuple[str, ...] = ()
self.first_logged: Final = asyncio.Event()
async def async_pre_call_hook(
self, user_api_key_dict: UserAPIKeyAuth, cache: DualCache, data: dict[str, object], call_type: str
) -> None:
raise ModifyResponseException(
message=_BLOCK_TEXT,
model="gpt-4o",
request_data=data,
guardrail_name=self.guardrail_name,
log_as_failure=True,
)
async def async_log_failure_event(
self, kwargs: dict[str, object], response_obj: object, start_time: object, end_time: object
) -> None:
self.logged = (*self.logged, "failure")
self.first_logged.set()
async def async_log_success_event(
self, kwargs: dict[str, object], response_obj: object, start_time: object, end_time: object
) -> None:
self.logged = (*self.logged, "success")
self.first_logged.set()
class _RejectEveryRequest(CustomLogger):
async def async_pre_call_hook(
self, user_api_key_dict: UserAPIKeyAuth, cache: DualCache, data: dict[str, object], call_type: str
) -> None:
raise RejectedRequestError(
message="rejected by the pre-call hook", model="gpt-4o", llm_provider="openai", request_data=data
)
def _post(path: str, body: Mapping[str, object]) -> Request:
async def receive() -> Message:
return {"type": "http.request", "body": json.dumps(body).encode(), "more_body": False}
return Request(
{
"type": "http",
"method": "POST",
"path": path,
"query_string": b"",
"headers": [(b"content-type", b"application/json")],
},
receive,
)
async def _frames_releasing_the_block(response: StreamingResponse, released: asyncio.Event) -> tuple[str, ...]:
async def chunks() -> AsyncGenerator[str, None]:
async for chunk in response.body_iterator:
released.set()
yield chunk if isinstance(chunk, str) else bytes(chunk).decode()
streamed: Final = "".join([chunk async for chunk in chunks()])
return tuple(frame for frame in streamed.split("\n\n") if frame)
async def _reply(
path: str,
body: Mapping[str, object],
rail: CustomLogger,
released: asyncio.Event,
keepalive_interval: float | None,
route: str | None = None,
) -> tuple[object, tuple[str, ...]]:
endpoint: Final = chat_completion if path == "/v1/chat/completions" else completion
with (
patch.object(
proxy_server, "proxy_logging_obj", new=ProxyLogging(user_api_key_cache=DualCache())
), # test-quality-ok: module global imported at call time; no injection seam
patch.object(litellm, "callbacks", new=[rail]), # test-quality-ok: guardrails register through this global
patch.object(
litellm, "sse_keepalive_ping_interval_seconds", new=keepalive_interval
), # test-quality-ok: the operator's keepalive interval is read from this global
):
response: Final = await endpoint(
request=_post(path, body),
fastapi_response=Response(),
user_api_key_dict=UserAPIKeyAuth(request_route=route),
)
if not isinstance(response, StreamingResponse):
return response, ()
return response, await _frames_releasing_the_block(response, released)
async def _blocked_reply(
path: str, body: Mapping[str, object], keepalive_interval: float | None
) -> tuple[object, tuple[str, ...], _BlockEveryRequestOnceReleased]:
released: Final = asyncio.Event()
if keepalive_interval is None:
released.set()
blocker: Final = _BlockEveryRequestOnceReleased(released)
response, frames = await _reply(path, body, blocker, released, keepalive_interval)
return response, frames, blocker
def _data_frames(frames: tuple[str, ...]) -> tuple[str, ...]:
return tuple(frame.removeprefix("data: ") for frame in frames if frame.startswith("data: {"))
KEEPALIVE_INTERVALS: Final = pytest.mark.parametrize(
"keepalive_interval", [0.05, None], ids=["blocked-after-a-keepalive-ping", "keepalive-off"]
)
@pytest.mark.asyncio
@KEEPALIVE_INTERVALS
async def test_a_blocked_chat_stream_gets_the_block_message_and_a_content_filter_finish(
keepalive_interval: float | None,
) -> None:
_, frames, blocker = await _blocked_reply(
"/v1/chat/completions", {"model": "gpt-4o", "messages": [], "stream": True}, keepalive_interval
)
chunks: Final = tuple(ModelResponseStream.model_validate_json(frame) for frame in _data_frames(frames))
assert (frames[0] == _PING) is (keepalive_interval is not None)
assert frames[-1] == "data: [DONE]"
assert not any('"error"' in frame for frame in frames)
assert "".join(chunk.choices[0].delta.content or "" for chunk in chunks) == _BLOCK_TEXT
assert chunks[-1].choices[0].finish_reason == "content_filter"
assert [type(failure) for failure in blocker.failures] == [ModifyResponseException]
@pytest.mark.asyncio
@KEEPALIVE_INTERVALS
async def test_a_blocked_text_completion_stream_gets_the_block_message(keepalive_interval: float | None) -> None:
_, frames, blocker = await _blocked_reply(
"/v1/completions", {"model": "gpt-4o", "prompt": "hi", "stream": True}, keepalive_interval
)
chunks: Final = tuple(TextCompletionResponse.model_validate_json(frame) for frame in _data_frames(frames))
assert (frames[0] == _PING) is (keepalive_interval is not None)
assert frames[-1] == "data: [DONE]"
assert not any('"error"' in frame for frame in frames)
assert "".join(chunk.choices[0].text or "" for chunk in chunks) == _BLOCK_TEXT
assert chunks[-1].choices[0].finish_reason == "content_filter"
assert [type(failure) for failure in blocker.failures] == [ModifyResponseException]
@pytest.mark.asyncio
async def test_a_blocked_chat_request_without_streaming_gets_the_block_message_and_a_content_filter_finish() -> None:
response, _, blocker = await _blocked_reply(
"/v1/chat/completions", {"model": "gpt-4o", "messages": [], "stream": False}, None
)
assert isinstance(response, ModelResponse)
assert response.choices[0].message.content == _BLOCK_TEXT
assert response.choices[0].finish_reason == "content_filter"
assert [type(failure) for failure in blocker.failures] == [ModifyResponseException]
@pytest.mark.asyncio
async def test_a_blocked_text_completion_without_streaming_gets_the_block_text_and_a_content_filter_finish() -> None:
response, _, blocker = await _blocked_reply(
"/v1/completions", {"model": "gpt-4o", "prompt": "hi", "stream": False}, None
)
assert isinstance(response, TextCompletionResponse)
assert response.choices[0].text == _BLOCK_TEXT
assert response.choices[0].finish_reason == "content_filter"
assert [type(failure) for failure in blocker.failures] == [ModifyResponseException]
@pytest.mark.asyncio
@pytest.mark.parametrize(
("path", "body", "logged"),
[
("/v1/chat/completions", {"model": "gpt-4o", "messages": [], "stream": False}, ("failure",)),
# A streamed chat reply goes out through a stream wrapper that logs it as a success event.
("/v1/chat/completions", {"model": "gpt-4o", "messages": [], "stream": True}, ("success",)),
("/v1/completions", {"model": "gpt-4o", "prompt": "hi", "stream": False}, ("failure",)),
("/v1/completions", {"model": "gpt-4o", "prompt": "hi", "stream": True}, ("failure",)),
],
ids=["chat", "chat-streamed", "text", "text-streamed"],
)
async def test_a_blocked_prompt_that_asks_to_be_logged_reaches_the_logging_callbacks_exactly_once(
path: str, body: Mapping[str, object], logged: tuple[str, ...]
) -> None:
released: Final = asyncio.Event()
released.set()
blocker: Final = _BlockEveryRequestAskingToBeLogged()
await _reply(path, body, blocker, released, None, route=path)
# Every route logs its one event from a task of its own. Wait for that event, then for anything the
# logging worker still holds, so a second event would be counted too.
await asyncio.wait_for(blocker.first_logged.wait(), timeout=10)
await GLOBAL_LOGGING_WORKER.flush()
assert blocker.logged == logged
@pytest.mark.asyncio
async def test_a_rejected_text_completion_stream_ends_with_a_stop_finish() -> None:
released: Final = asyncio.Event()
released.set()
_, frames = await _reply(
"/v1/completions", {"model": "gpt-4o", "prompt": "hi", "stream": True}, _RejectEveryRequest(), released, None
)
chunks: Final = tuple(TextCompletionResponse.model_validate_json(frame) for frame in _data_frames(frames))
assert frames[-1] == "data: [DONE]"
assert chunks[-1].choices[0].finish_reason == "stop"