litellm/tests/test_litellm_rust/responses/test_body_hooks.py
yujonglee 0fc11653e2
test(rust-bridge): pin Messages and Responses callback contracts on the native path (#46443)
* test(rust-bridge): pin Messages and Responses callback contracts on the native path

Each test runs the native route and asserts what the Python path does today, so a
known gap is a strict xfail that names its reason and the exception it fails with
Messages and Responses share one Surface and hook recorder in support/callbacks.py,
and each surface folder lists its own expected counts and gaps.

Body-level hooks from the function body (pre-request hook, websearch short-circuit,
Messages interceptors, planned and legacy agentic loops, streaming deployment hook)
are xfail until native runs them

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(rust-bridge): give every route folder the same one-concern-per-file layout

Route data, the route Surface and the server fixture move into each route folder, and support/ keeps only
route-neutral helpers. test_inference.py splits into chat_completions/ and responses/, ocr/test_requests.py
splits into requests, failures and settings, and Messages and Responses get streaming and body hook files.
Messages request tests that duplicate inference-messages request.rs are removed, and drop_params read
from litellm.drop_params is now covered

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(rust-bridge): expect the required-route decline error for unsupported Responses requests

Co-Authored-By: Yujong Lee <yujong@berri.ai>

* test(rust-bridge): import route data from the route folders in the secrets unit tests

Co-Authored-By: Yujong Lee <yujong@berri.ai>

* test(rust-bridge): import NoReturn in the OCR dispatch tests

Co-Authored-By: Yujong Lee <yujong@berri.ai>

* test(rust-bridge): move route-neutral helpers out of support/callbacks.py

Co-Authored-By: Yujong Lee <yujong@berri.ai>

* test(rust-bridge): cover deployment rejection and concurrent callbacks

* test(rust-bridge): assert native serving via the x-litellm-rust marker in the route folder tests

Co-Authored-By: Yujong Lee <yujong@berri.ai>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-14 17:07:20 -07:00

114 lines
4.2 KiB
Python

from collections.abc import Iterator
from datetime import datetime
from typing import Final
import pytest
from pydantic import BaseModel
import litellm
from litellm.integrations.custom_logger import CustomLogger
from litellm.litellm_core_utils.litellm_logging import Logging
from tests.test_litellm_rust.responses.data import (
BODY_HOOKS,
REQUEST,
RESPONSES_EVENTS,
RESPONSES_RESPONSE,
STREAMING,
call,
)
from tests.test_litellm_rust.support.body_hooks import LegacyAgenticLoop, PlannedAgenticLoop, agentic_hooks
from tests.test_litellm_rust.support.callback_recorder import drain_logging
from tests.test_litellm_rust.support.isolation import rebound
from tests.test_litellm_rust.support.recording_server import RecordingServer, ResponseSpec, relaxed
from tests.test_litellm_rust.support.results import consume, response_id
from tests.test_litellm_rust.support.routing import CALL_ID, assert_served_natively
pytestmark = pytest.mark.requires_rust_extension
STREAM: Final = ResponseSpec(body=None, events=RESPONSES_EVENTS)
@pytest.fixture
def server(server: RecordingServer) -> Iterator[RecordingServer]:
yield from relaxed(server)
@pytest.mark.asyncio
@STREAMING
async def test_body_streaming_deployment_hook_rewrites_chunks_before_delivery(server: RecordingServer) -> None:
seen: Final[list[str]] = []
class Rewrite(CustomLogger):
async def async_post_call_streaming_deployment_hook(
self, request_data: dict[str, object], response_chunk: BaseModel, call_type: object
) -> BaseModel:
seen.append(getattr(response_chunk, "type", ""))
if getattr(response_chunk, "type", None) != "response.output_text.delta":
return response_chunk
return response_chunk.model_copy(update={"delta": "rewritten"})
server.enqueue(STREAM)
with rebound(litellm, "callbacks", [Rewrite()]):
stream: Final = await call(server, stream=True)
chunks: Final = await consume(stream)
assert_served_natively(server)
assert seen == [event for event, _ in RESPONSES_EVENTS]
assert [getattr(chunk, "delta", None) for chunk in chunks] == [None, "rewritten", None]
@pytest.mark.asyncio
@BODY_HOOKS
async def test_body_planned_agentic_loop_sends_the_followup_and_replaces_the_response(server: RecordingServer) -> None:
loop: Final = PlannedAgenticLoop()
server.enqueue(ResponseSpec(body=RESPONSES_RESPONSE))
server.default_response = ResponseSpec(body={**RESPONSES_RESPONSE, "id": "followup"})
with rebound(litellm, "callbacks", [loop]):
response: Final = await call(server)
await drain_logging()
assert_served_natively(server, count=2)
assert isinstance(server.requests[1].body, dict)
assert server.requests[1].body["input"] == [{"role": "user", "content": "followup"}]
assert response_id(response) == "agentic-replaced"
assert agentic_hooks(loop) == (
"async_should_run_agentic_loop",
"async_build_agentic_loop_plan",
"async_should_run_agentic_loop",
"async_post_agentic_loop_response_hook",
"async_agentic_loop_cleanup_hook",
)
@pytest.mark.asyncio
@BODY_HOOKS
async def test_body_legacy_agentic_loop_replaces_the_response(server: RecordingServer) -> None:
loop: Final = LegacyAgenticLoop()
with rebound(litellm, "callbacks", [loop]):
response: Final = await call(server)
assert_served_natively(server)
assert response_id(response) == "agentic-replaced"
assert agentic_hooks(loop) == ("async_should_run_agentic_loop", "async_run_agentic_loop")
@pytest.mark.asyncio
async def test_body_logging_setup_drops_a_logger_fn_from_a_supplied_logging_object(server: RecordingServer) -> None:
observed: Final[list[object]] = []
logging_obj: Final = Logging(
model=REQUEST["model"],
messages=[],
stream=False,
start_time=datetime.now(),
call_type="aresponses",
litellm_call_id=CALL_ID,
function_id=CALL_ID,
)
logging_obj.update_environment_variables(litellm_params={"logger_fn": observed.append}, optional_params={})
await call(server, litellm_logging_obj=logging_obj)
assert_served_natively(server)
assert observed == []