diff --git a/litellm/integrations/compression_interception/handler.py b/litellm/integrations/compression_interception/handler.py index 941b953d22a..3440fe6725a 100644 --- a/litellm/integrations/compression_interception/handler.py +++ b/litellm/integrations/compression_interception/handler.py @@ -5,11 +5,13 @@ CustomLogger that compresses inbound Anthropic Messages requests and fulfills litellm_content_retrieve tool calls server-side via the typed agentic loop plan. """ +import itertools import time import uuid from collections.abc import Mapping, Sequence from typing import Any, ClassVar, Final, Protocol, cast +from pydantic import TypeAdapter, ValidationError from typing_extensions import ReadOnly, TypedDict from litellm._logging import verbose_logger @@ -18,6 +20,7 @@ from litellm.integrations.custom_logger import CustomLogger from litellm.litellm_core_utils.allowed_tools_tool_choice import allowed_tools_tool_choice_with_function from litellm.litellm_core_utils.asyncify import asyncify from litellm.litellm_core_utils.core_helpers import int_of +from litellm.llms.anthropic.messages.utils import object_mapping from litellm.types.integrations.compression_interception import ( CompressionInterceptionConfig, CompressionSavingsMetadata, @@ -30,6 +33,7 @@ from litellm.types.utils import CallTypes LITELLM_CONTENT_RETRIEVE_TOOL_NAME: Final = "litellm_content_retrieve" _CACHE_TTL_SECONDS: Final = 15 * 60 +_CONTENT_BLOCKS: Final = TypeAdapter(list[Mapping[str, object]]) class _AgenticLoopParams(TypedDict, total=False): @@ -45,6 +49,19 @@ class _AgenticLoopLoggingObj(Protocol): def model_call_details(self) -> Mapping[str, _AgenticLoopParams]: ... +def _text_blocks_streamed_before_first_tool_use(response: object) -> tuple[Mapping[str, str], ...]: + message: Final = object_mapping(response) + if message is None: + return () + try: + blocks: Final = _CONTENT_BLOCKS.validate_python(message.get("content")) + except ValidationError: + return () + leading_blocks: Final = itertools.takewhile(lambda block: block.get("type") != "tool_use", blocks) + texts: Final = (block.get("text") for block in leading_blocks if block.get("type") == "text") + return tuple({"type": "text", "text": text} for text in texts if isinstance(text, str) and text) + + def _compression_savings_from_counts( original_tokens: object, compressed_tokens: object ) -> CompressionSavingsMetadata | None: @@ -258,10 +275,12 @@ class CompressionInterceptionLogger(CustomLogger): call_id: Final = self._resolve_call_id(logging_obj=logging_obj, kwargs=kwargs) cache: Final = self._get_cache(call_id=call_id) retrieval_results: Final = [self._resolve_retrieval_content(tc, cache) for tc in tool_calls] + streamed_text_blocks: Final = _text_blocks_streamed_before_first_tool_use(response) if stream else () assistant_message: Final = { "role": "assistant", "content": thinking_blocks + + list(streamed_text_blocks) + [ { "type": "tool_use", diff --git a/litellm/llms/anthropic/messages/native/agentic_streaming_iterator.py b/litellm/llms/anthropic/messages/native/agentic_streaming_iterator.py index efaaf51c7c1..1ad02cf2d09 100644 --- a/litellm/llms/anthropic/messages/native/agentic_streaming_iterator.py +++ b/litellm/llms/anthropic/messages/native/agentic_streaming_iterator.py @@ -7,24 +7,32 @@ all bytes, and on stream exhaustion rebuilds the full Anthropic response to run through agentic completion hooks. If an agentic hook fires, the follow-up response is chained as Phase 2 of the same iterator. -In hold-back mode (``hold_back=True``) chunks are buffered instead of yielded -live, keepalive pings run whenever no other byte is ready, and then either the -follow-up replaces the message or the buffer replays, except that a tool_use for -a server-fulfilled tool fails the turn rather than reaching a client that cannot -execute it. +In hold-back mode (``hold_back=True``) frames stream live until the first tool_use +block or the frames that end the message, which are held behind keepalive pings while +the hooks run. A follow-up then continues the same message, a server-fulfilled tool_use +the hooks did not replace fails the turn with an error frame, and otherwise the held +frames replay. """ import asyncio import contextlib import json -from collections.abc import AsyncIterable, AsyncIterator -from typing import TYPE_CHECKING, Any, Final, cast +from collections.abc import AsyncGenerator, AsyncIterable, AsyncIterator, Mapping, Sequence +from enum import Enum, auto +from typing import TYPE_CHECKING, Any, Final, Literal, cast from pydantic import TypeAdapter from litellm._logging import verbose_logger from litellm.constants import STREAM_SSE_KEEPALIVE_PING_BYTES from litellm.litellm_core_utils.core_helpers import has_attributes, loads_json_object +from litellm.llms.anthropic.messages.native.streaming_iterator import ( + SSE_FRAME_TERMINATORS, + sse_frame_event, + sse_frames, +) +from litellm.llms.anthropic.messages.utils import anthropic_sse_frame, object_mapping +from litellm.llms.custom_httpx.stream_close import aclose_if_supported from litellm.types.integrations.custom_logger import AgenticLoopLimitError, AgenticLoopSafetyError if TYPE_CHECKING: @@ -46,19 +54,87 @@ AGENTIC_LOOP_LIMIT_ERROR_SSE_BYTES: Final = ( b'Raise max_agentic_loops to allow more loops."}}\n\n' ) _AGENTIC_HOOK_RESULT: Final = TypeAdapter(object) +_CONTENT_BLOCKS: Final = TypeAdapter(list[object]) +_HOLD_START_EVENTS: Final = frozenset(("message_delta", "message_stop")) +_CONTENT_BLOCK_EVENTS: Final = frozenset(("content_block_start", "content_block_delta", "content_block_stop")) + + +class _KeepAlive(Enum): + PING_DUE = auto() def is_server_fulfilled_tool_leak_error(chunk: object) -> bool: return chunk in (SERVER_FULFILLED_TOOL_LEAK_ERROR_SSE_BYTES, AGENTIC_LOOP_LIMIT_ERROR_SSE_BYTES) -async def _anext_or_none(iterator: AsyncIterator) -> bytes | None: +async def _anext_or_none(iterator: AsyncIterator[bytes]) -> bytes | None: try: return await iterator.__anext__() except StopAsyncIteration: return None +async def _settles_by(task: asyncio.Task[object], deadline: float) -> bool: + done, _ = await asyncio.wait((task,), timeout=max(deadline - asyncio.get_running_loop().time(), 0)) + return bool(done) + + +def _frame_event(frame: object) -> Mapping[str, object] | None: + return sse_frame_event(frame) if isinstance(frame, bytes) else None + + +def _is_content_block_start(frame: bytes) -> bool: + event: Final = _frame_event(frame) + return event is not None and event.get("type") == "content_block_start" + + +def _is_whole_frame(frame: object) -> bool: + return isinstance(frame, bytes) and frame.endswith(SSE_FRAME_TERMINATORS) + + +def _starts_hold(frame: bytes) -> bool: + if not _is_whole_frame(frame): + return True + event: Final = _frame_event(frame) + if event is None: + return False + if event.get("type") in _HOLD_START_EVENTS: + return True + block: Final = object_mapping(event.get("content_block")) + return event.get("type") == "content_block_start" and block is not None and block.get("type") == "tool_use" + + +def _block_shifted(frame: bytes, event: Mapping[str, object], block_offset: int) -> bytes: + index: Final = event.get("index") + if block_offset == 0 or event.get("type") not in _CONTENT_BLOCK_EVENTS or not isinstance(index, int): + return frame + return anthropic_sse_frame({**event, "index": index + block_offset}) + + +async def _continuing_message(follow_up: AsyncIterator[bytes], block_offset: int) -> AsyncGenerator[bytes, None]: + async with contextlib.aclosing(sse_frames(follow_up)) as frames: + async for frame in frames: + event = _frame_event(frame) + if event is None: + yield frame + elif event.get("type") != "message_start": + yield _block_shifted(frame, event, block_offset) + + +def _without_blocks_the_client_has( + response: Mapping[str, object], live_message_id: object, live_block_count: int +) -> Mapping[str, object]: + content: Final = response.get("content") + if response.get("id") != live_message_id or not isinstance(content, list): + return response + return {**response, "content": _CONTENT_BLOCKS.validate_python(content)[live_block_count:]} + + +async def _replayed(frames: Sequence[bytes]) -> AsyncGenerator[bytes, None]: + for frame in frames: + yield frame + + # --------------------------------------------------------------------------- # SSE parsing helpers (module-level to keep the class lean) # --------------------------------------------------------------------------- @@ -186,6 +262,10 @@ class AgenticAnthropicStreamingIterator: Phase 2: If an agentic hook fires and returns a follow-up response (streaming or non-streaming), yield those bytes to the caller. + + In hold-back mode only the frames from the first tool_use block or the message's + end onward wait for the hooks, and a follow-up continues the message the client is + already reading, with its content blocks numbered after the ones it has seen. """ def __init__( @@ -203,7 +283,7 @@ class AgenticAnthropicStreamingIterator: server_fulfilled_tool_names: frozenset[str] = frozenset(), ping_interval_seconds: float = HOLD_BACK_PING_INTERVAL_SECONDS, ): - self._inner = completion_stream.__aiter__() + self._inner: Final[AsyncIterator[bytes]] = completion_stream.__aiter__() self._http_handler = http_handler self._model = model self._messages = messages @@ -220,16 +300,17 @@ class AgenticAnthropicStreamingIterator: self._stream_exhausted = False self._hook_processing_done = False self._follow_up_iterator: AsyncIterator | None = None - self._drain_task: asyncio.Task | None = None - self._hook_task: asyncio.Task | None = None - self._follow_up_chunk_task: asyncio.Task | None = None - self._replay_index = 0 - self._error_emitted = False + self._upstream_frames: Final = sse_frames(self._inner) + self._holding = False + self._live_frame_count = 0 + self._frame_task: asyncio.Task[bytes | None] | None = None + self._hook_task: asyncio.Task[None] | None = None + self._frames_after_hooks: AsyncIterator[bytes] | None = None self._loop_limit_reached = False @property def has_buffered_provider_output(self) -> bool: - """Whether provider output was received but withheld from the client behind keepalive pings.""" + """Whether a held-back stream received provider output, sent live or still held behind keepalive pings.""" return self._hold_back and bool(self._collected_bytes) def __aiter__(self): @@ -257,68 +338,64 @@ class AgenticAnthropicStreamingIterator: raise StopAsyncIteration - async def _drain_upstream(self) -> None: - try: - while True: - self._collected_bytes.append(await self._inner.__anext__()) - except StopAsyncIteration: - return - - async def _completed_within_ping_interval(self, task: asyncio.Task) -> bool: - try: - await asyncio.wait_for(asyncio.shield(task), timeout=self._ping_interval_seconds) - except asyncio.TimeoutError: - return False - return True + async def _next_frame( + self, frames: AsyncIterator[bytes], deadline: float + ) -> bytes | None | Literal[_KeepAlive.PING_DUE]: + if self._frame_task is None: + self._frame_task = asyncio.create_task(_anext_or_none(frames)) + task: Final = self._frame_task + if not await _settles_by(task, deadline): + return _KeepAlive.PING_DUE + frame: Final = task.result() + self._frame_task = None + return frame async def _anext_held_back(self) -> bytes: - if self._drain_task is None: - self._drain_task = asyncio.create_task(self._drain_upstream()) - return STREAM_SSE_KEEPALIVE_PING_BYTES - - if not self._stream_exhausted: - if not await self._completed_within_ping_interval(self._drain_task): + deadline: Final = asyncio.get_running_loop().time() + self._ping_interval_seconds + while not self._stream_exhausted: + frame = await self._next_frame(self._upstream_frames, deadline) + if frame is _KeepAlive.PING_DUE: return STREAM_SSE_KEEPALIVE_PING_BYTES - self._stream_exhausted = True + if frame is None: + self._stream_exhausted = True + continue + self._collected_bytes.append(frame) + self._holding = self._holding or _starts_hold(frame) + if not self._holding: + self._live_frame_count += 1 + return frame if self._hook_task is None: self._hook_task = asyncio.create_task(self._process_agentic_hooks()) - if not await self._completed_within_ping_interval(self._hook_task): + if not await _settles_by(self._hook_task, deadline): return STREAM_SSE_KEEPALIVE_PING_BYTES + self._hook_task.result() + if self._frames_after_hooks is None: + self._frames_after_hooks = self._ending_frames() + frame_after_hooks: Final = await self._next_frame(self._frames_after_hooks, deadline) + if frame_after_hooks is _KeepAlive.PING_DUE: + return STREAM_SSE_KEEPALIVE_PING_BYTES + if frame_after_hooks is None: + raise StopAsyncIteration + return frame_after_hooks + + def _ending_frames(self) -> AsyncIterator[bytes]: if self._follow_up_iterator is not None: - return await self._next_follow_up_chunk(self._follow_up_iterator) - + return _continuing_message(self._follow_up_iterator, self._live_block_count()) if self._buffer_holds_server_fulfilled_tool_use(): - if self._error_emitted: - raise StopAsyncIteration - self._error_emitted = True verbose_logger.error( "AgenticStreamingIterator: hooks did not replace a message containing a server-fulfilled " "tool_use [model=%s]; emitting an SSE error instead of leaking the tool call to the client", self._model, ) if self._loop_limit_reached: - return AGENTIC_LOOP_LIMIT_ERROR_SSE_BYTES - return SERVER_FULFILLED_TOOL_LEAK_ERROR_SSE_BYTES + return _replayed((AGENTIC_LOOP_LIMIT_ERROR_SSE_BYTES,)) + return _replayed((SERVER_FULFILLED_TOOL_LEAK_ERROR_SSE_BYTES,)) + return _replayed(tuple(self._collected_bytes[self._live_frame_count :])) - if self._replay_index < len(self._collected_bytes): - chunk: Final = self._collected_bytes[self._replay_index] - self._replay_index += 1 - return chunk - - raise StopAsyncIteration - - async def _next_follow_up_chunk(self, follow_up_iterator: AsyncIterator) -> bytes: - if self._follow_up_chunk_task is None: - self._follow_up_chunk_task = asyncio.create_task(_anext_or_none(follow_up_iterator)) - if not await self._completed_within_ping_interval(self._follow_up_chunk_task): - return STREAM_SSE_KEEPALIVE_PING_BYTES - chunk: Final = self._follow_up_chunk_task.result() - self._follow_up_chunk_task = None - if chunk is None: - raise StopAsyncIteration - return chunk + def _live_block_count(self) -> int: + return sum(1 for frame in self._collected_bytes[: self._live_frame_count] if _is_content_block_start(frame)) def _buffer_holds_server_fulfilled_tool_use(self) -> bool: if not self._server_fulfilled_tool_names: @@ -336,7 +413,7 @@ class AgenticAnthropicStreamingIterator: ) @staticmethod - async def _settle_task(task: asyncio.Task | None) -> None: + async def _settle_task(task: asyncio.Task[object] | None) -> None: if task is None: return if task.done(): @@ -348,13 +425,10 @@ class AgenticAnthropicStreamingIterator: await task async def aclose(self) -> None: - from litellm.llms.anthropic.messages.native.streaming_iterator import ( - aclose_if_supported, - ) - - await self._settle_task(self._drain_task) await self._settle_task(self._hook_task) - await self._settle_task(self._follow_up_chunk_task) + await self._settle_task(self._frame_task) + await self._upstream_frames.aclose() + await aclose_if_supported(self._frames_after_hooks) await aclose_if_supported(self._inner) await aclose_if_supported(self._follow_up_iterator) @@ -392,7 +466,7 @@ class AgenticAnthropicStreamingIterator: if has_attributes(result, AsyncIterable[object], "__aiter__"): self._follow_up_iterator = result.__aiter__() - elif isinstance(result, dict): + elif (whole_message := object_mapping(result)) is not None: from litellm.llms.anthropic.messages.native.fake_stream_iterator import ( FakeAnthropicMessagesStreamIterator, ) @@ -400,7 +474,10 @@ class AgenticAnthropicStreamingIterator: AnthropicMessagesResponse, ) - fake: Final = FakeAnthropicMessagesStreamIterator(response=cast(AnthropicMessagesResponse, result)) + unseen: Final = _without_blocks_the_client_has( + whole_message, rebuilt.get("id"), self._live_block_count() + ) + fake: Final = FakeAnthropicMessagesStreamIterator(response=cast(AnthropicMessagesResponse, unseen)) self._follow_up_iterator = fake.__aiter__() else: verbose_logger.warning( diff --git a/litellm/llms/anthropic/messages/native/streaming_iterator.py b/litellm/llms/anthropic/messages/native/streaming_iterator.py index 9caeb52c152..803d9ff5ba7 100644 --- a/litellm/llms/anthropic/messages/native/streaming_iterator.py +++ b/litellm/llms/anthropic/messages/native/streaming_iterator.py @@ -452,21 +452,21 @@ class AnthropicMessagesStreamingResponse: _SSE_FRAME_END: Final = re.compile(rb"(?<=\n\n)|(?<=\r\n\r\n)") -_SSE_FRAME_TERMINATORS: Final = (b"\n\n", b"\r\n\r\n") -_SSE_TERMINATOR_OVERLAP: Final = max(len(terminator) for terminator in _SSE_FRAME_TERMINATORS) - 1 +SSE_FRAME_TERMINATORS: Final = (b"\n\n", b"\r\n\r\n") +_SSE_TERMINATOR_OVERLAP: Final = max(len(terminator) for terminator in SSE_FRAME_TERMINATORS) - 1 def _sse_data_payload(line: bytes) -> bytes | None: return line[len(b"data:") :].removeprefix(b" ") if line.startswith(b"data:") else None -def _sse_frame_event(frame: bytes) -> Mapping[str, object] | None: +def sse_frame_event(frame: bytes) -> Mapping[str, object] | None: payloads: Final = (_sse_data_payload(line) for line in frame.splitlines()) return loads_json_object(b"\n".join(payload for payload in payloads if payload is not None)) async def _stamped_sse_frame(frame: bytes, safeguard_results: StreamedSafeguardResults) -> bytes: - event: Final = _sse_frame_event(frame) + event: Final = sse_frame_event(frame) if event is None: return frame stamped: Final = await safeguard_results.observe(event) @@ -474,7 +474,7 @@ async def _stamped_sse_frame(frame: bytes, safeguard_results: StreamedSafeguardR def _ends_a_frame(open_frame: bytearray, scan_from: int) -> bool: - return any(open_frame.find(terminator, scan_from) != -1 for terminator in _SSE_FRAME_TERMINATORS) + return any(open_frame.find(terminator, scan_from) != -1 for terminator in SSE_FRAME_TERMINATORS) async def _stamped_sse_frames( diff --git a/tests/unit/integrations/compression_interception/test_compression_interception_handler.py b/tests/unit/integrations/compression_interception/test_compression_interception_handler.py index 9c5ef7ac4e4..2ca26995ce4 100644 --- a/tests/unit/integrations/compression_interception/test_compression_interception_handler.py +++ b/tests/unit/integrations/compression_interception/test_compression_interception_handler.py @@ -398,6 +398,57 @@ async def test_build_agentic_loop_plan_missing_key_fallback(): ) +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("stream", "text_the_client_saw"), + [(True, [{"type": "text", "text": "I'll fetch your tides notes."}]), (False, [])], + ids=["streamed", "not_streamed"], +) +async def test_build_agentic_loop_plan_keeps_only_the_text_the_client_already_received(stream, text_the_client_saw): + logger = CompressionInterceptionLogger() + logger._compression_cache_by_call_id["call_text"] = ({"message_3": "tides notes"}, 9999999999.0) + logging_obj = MagicMock() + logging_obj.litellm_call_id = "call_text" + logging_obj.model_call_details = {"agentic_loop_params": {}} + thinking = {"type": "thinking", "thinking": "", "signature": "sig"} + tool_use = {"type": "tool_use", "id": "toolu_1", "name": "litellm_content_retrieve", "input": {"key": "message_3"}} + response = { + "role": "assistant", + "content": [ + thinking, + {"type": "text", "text": "I'll fetch your tides notes."}, + tool_use, + {"type": "text", "text": "Held back behind the call."}, + ], + } + request_params = {"tools": [{"type": "custom", "name": "litellm_content_retrieve"}]} + + should_run, tools = await logger.async_should_run_agentic_loop( + response=response, + model="claude-sonnet", + messages=[{"role": "user", "content": "quote my tides notes"}], + tools=request_params["tools"], + stream=stream, + custom_llm_provider="anthropic", + kwargs={}, + ) + plan = await logger.async_build_agentic_loop_plan( + tools=tools, + model="claude-sonnet", + messages=[{"role": "user", "content": "quote my tides notes"}], + response=response, + anthropic_messages_provider_config=None, + anthropic_messages_optional_request_params=request_params, + logging_obj=logging_obj, + stream=stream, + kwargs={}, + ) + + assert should_run is True + assert plan.request_patch is not None + assert plan.request_patch.messages[-2]["content"] == [thinking, *text_the_client_saw, tool_use] + + def _stub_compress_result(original_tokens, compressed_tokens, cache): return { "messages": [{"role": "user", "content": "stubbed"}], diff --git a/tests/unit/llms/anthropic/messages/native/test_agentic_streaming_iterator.py b/tests/unit/llms/anthropic/messages/native/test_agentic_streaming_iterator.py index 0279143c077..0e1148f3ebf 100644 --- a/tests/unit/llms/anthropic/messages/native/test_agentic_streaming_iterator.py +++ b/tests/unit/llms/anthropic/messages/native/test_agentic_streaming_iterator.py @@ -3,8 +3,10 @@ Tests for AgenticAnthropicStreamingIterator and SSE rebuild helpers. """ import asyncio +import functools import json -from typing import Any, Dict, List, Optional, Tuple +import selectors +from typing import Any, AsyncGenerator, Callable, Coroutine, Dict, Final, List, Optional, ParamSpec, Tuple, TypeVar from unittest.mock import AsyncMock, MagicMock import pytest @@ -248,6 +250,47 @@ class MockSlowAsyncStream(MockAsyncStream): return await super().__anext__() +class _IdleSkippingSelector(selectors.DefaultSelector): + def __init__(self) -> None: + super().__init__() + self.skipped_seconds = 0.0 + + def select(self, timeout: Optional[float] = None) -> List[Tuple[selectors.SelectorKey, int]]: + ready = super().select(0) + if ready or timeout == 0: + return ready + if timeout is None: + raise AssertionError("every task is waiting and no timer is left to fire") + self.skipped_seconds += timeout + return ready + + +class _VirtualClockLoop(asyncio.SelectorEventLoop): + def __init__(self) -> None: + self._idle_skipping_selector = _IdleSkippingSelector() + super().__init__(self._idle_skipping_selector) + + def time(self) -> float: + return super().time() + self._idle_skipping_selector.skipped_seconds + + +_P = ParamSpec("_P") +_T = TypeVar("_T") + + +def _on_virtual_clock(test: Callable[_P, Coroutine[object, object, _T]]) -> Callable[_P, _T]: + @functools.wraps(test) + def run(*args: _P.args, **kwargs: _P.kwargs) -> _T: + loop: Final = _VirtualClockLoop() + try: + return loop.run_until_complete(test(*args, **kwargs)) + finally: + loop.run_until_complete(loop.shutdown_asyncgens()) + loop.close() + + return run + + class MockFailingAsyncStream(MockAsyncStream): """Async iterator that raises after yielding its chunks.""" @@ -261,10 +304,13 @@ class MockFailingAsyncStream(MockAsyncStream): return await super().__anext__() +PING_INTERVAL_SECONDS = 15.0 + + def _build_hold_back_iterator( stream: MockAsyncStream, mock_handler: MagicMock, - ping_interval_seconds: float = 15.0, + ping_interval_seconds: float = PING_INTERVAL_SECONDS, server_fulfilled_tool_names: frozenset = frozenset({"litellm_content_retrieve"}), ) -> AgenticAnthropicStreamingIterator: return AgenticAnthropicStreamingIterator( @@ -283,6 +329,161 @@ def _build_hold_back_iterator( ) +def _compact_sse_event(event_type: str, data: dict) -> bytes: + return f"event: {event_type}\ndata: {json.dumps(data, separators=(',', ':'))}\n\n".encode() + + +def _text_then_tool_use_stream(tool_name: str = "litellm_content_retrieve") -> List[bytes]: + return [ + _sse_event( + "message_start", + { + "type": "message_start", + "message": { + "id": "msg_live", + "type": "message", + "role": "assistant", + "model": "claude-sonnet-4-20250514", + "content": [], + "stop_reason": None, + "usage": {"input_tokens": 30, "output_tokens": 0}, + }, + }, + ), + _sse_event( + "content_block_start", + {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}, + ), + _sse_event( + "content_block_delta", + { + "type": "content_block_delta", + "index": 0, + "delta": {"type": "text_delta", "text": "Let me look that up."}, + }, + ), + _sse_event("content_block_stop", {"type": "content_block_stop", "index": 0}), + _sse_event( + "content_block_start", + { + "type": "content_block_start", + "index": 1, + "content_block": {"type": "tool_use", "id": "toolu_1", "name": tool_name, "input": {}}, + }, + ), + _sse_event( + "content_block_delta", + { + "type": "content_block_delta", + "index": 1, + "delta": {"type": "input_json_delta", "partial_json": '{"key": "section_1"}'}, + }, + ), + _sse_event("content_block_stop", {"type": "content_block_stop", "index": 1}), + _sse_event( + "message_delta", + {"type": "message_delta", "delta": {"stop_reason": "tool_use"}, "usage": {"output_tokens": 12}}, + ), + _sse_event("message_stop", {"type": "message_stop"}), + ] + + +LIVE_TEXT_FRAMES = 4 + + +def _follow_up_stream() -> List[bytes]: + return [ + _compact_sse_event( + "message_start", + { + "type": "message_start", + "message": { + "id": "msg_follow_up", + "type": "message", + "role": "assistant", + "model": "claude-sonnet-4-20250514", + "content": [], + "stop_reason": None, + "usage": {"input_tokens": 60, "output_tokens": 0}, + }, + }, + ), + _compact_sse_event( + "content_block_start", + {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}, + ), + _compact_sse_event( + "content_block_delta", + {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Section 1 says hi."}}, + ), + _compact_sse_event("content_block_stop", {"type": "content_block_stop", "index": 0}), + _compact_sse_event( + "message_delta", + {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 7}}, + ), + _compact_sse_event("message_stop", {"type": "message_stop"}), + ] + + +class GatedStream: + """Yields `before`, then waits for `gate` before yielding `after`; `closed` records that it ended or was closed.""" + + def __init__(self, before: List[bytes], after: List[bytes]): + self.gate = asyncio.Event() + self.closed = False + self._chunks = self._run(before, after) + + async def _run(self, before: List[bytes], after: List[bytes]) -> AsyncGenerator[bytes, None]: + try: + for chunk in before: + yield chunk + await self.gate.wait() + for chunk in after: + yield chunk + finally: + self.closed = True + + def __aiter__(self) -> "GatedStream": + return self + + async def __anext__(self) -> bytes: + return await self._chunks.__anext__() + + async def aclose(self) -> None: + await self._chunks.aclose() + + +def _hooks_returning(result: object) -> MagicMock: + handler = MagicMock() + handler._call_agentic_completion_hooks = AsyncMock(return_value=result) + return handler + + +def _hooks_running(hooks: Callable[..., Coroutine[object, object, object]]) -> MagicMock: + handler = MagicMock() + handler._call_agentic_completion_hooks = AsyncMock(side_effect=hooks) + return handler + + +async def _read_until_ping(iterator: AgenticAnthropicStreamingIterator) -> List[bytes]: + chunks = [] + while (chunk := await iterator.__anext__()) != STREAM_SSE_KEEPALIVE_PING_BYTES: + chunks.append(chunk) + return chunks + + +async def _drain_without_pings(iterator: AgenticAnthropicStreamingIterator) -> List[bytes]: + return [chunk async for chunk in iterator if chunk != STREAM_SSE_KEEPALIVE_PING_BYTES] + + +def _wire_events(chunks: List[bytes]) -> List[Tuple[str, dict]]: + return [(event, json.loads(data)) for event, data in _sse_frames(b"".join(chunks).decode())] + + +def _block_starts(events: List[Tuple[str, dict]]) -> List[Tuple[int, str]]: + return [(data["index"], data["content_block"]["type"]) for event, data in events if event == "content_block_start"] + + # --------------------------------------------------------------------------- # Tests for _parse_sse_events # --------------------------------------------------------------------------- @@ -903,113 +1104,266 @@ class TestAgenticStreamingIteratorErrorHandling: class TestAgenticStreamingIteratorHoldBack: @pytest.mark.asyncio - async def test_should_not_leak_intercepted_message_when_follow_up_fires(self): - """The buffered tool_use message must be dropped: only pings and follow-up bytes reach the client.""" - phase1_chunks = _build_tool_use_stream() - phase2_chunks = [b"follow-up-chunk-1", b"follow-up-chunk-2"] + async def test_text_before_a_tool_use_reaches_the_client_while_the_model_is_still_writing(self): + chunks = _text_then_tool_use_stream() + upstream = GatedStream(chunks[:LIVE_TEXT_FRAMES], chunks[LIVE_TEXT_FRAMES:]) + iterator = _build_hold_back_iterator(upstream, _hooks_returning(None)) - mock_handler = MagicMock() - mock_handler._call_agentic_completion_hooks = AsyncMock(return_value=MockAsyncStream(phase2_chunks)) + for expected in chunks[:LIVE_TEXT_FRAMES]: + assert await iterator.__anext__() == expected - iterator = _build_hold_back_iterator(MockAsyncStream(phase1_chunks), mock_handler) - - collected = [] - async for chunk in iterator: - collected.append(chunk) - - non_ping = [c for c in collected if c != STREAM_SSE_KEEPALIVE_PING_BYTES] - assert non_ping == phase2_chunks - assert b"litellm_content_retrieve" not in b"".join(collected) - assert collected[0] == STREAM_SSE_KEEPALIVE_PING_BYTES + upstream.gate.set() + assert await _drain_without_pings(iterator) == [SERVER_FULFILLED_TOOL_LEAK_ERROR_SSE_BYTES] @pytest.mark.asyncio - async def test_should_replay_buffer_verbatim_when_no_hook_fires(self): - """Without interception the buffered message is replayed byte-identical after the pings.""" - chunks = _build_simple_text_stream() - - mock_handler = MagicMock() - mock_handler._call_agentic_completion_hooks = AsyncMock(return_value=None) - - iterator = _build_hold_back_iterator(MockAsyncStream(chunks), mock_handler) - - collected = [] - async for chunk in iterator: - collected.append(chunk) - - assert [c for c in collected if c != STREAM_SSE_KEEPALIVE_PING_BYTES] == chunks - mock_handler._call_agentic_completion_hooks.assert_awaited_once() - - @pytest.mark.asyncio - async def test_should_emit_pings_while_upstream_is_slow(self): - """Pings keep the client connection alive while the upstream message is buffered.""" - chunks = _build_simple_text_stream() - - mock_handler = MagicMock() - mock_handler._call_agentic_completion_hooks = AsyncMock(return_value=None) - + async def test_a_follow_up_continues_the_message_the_client_is_already_reading(self): + follow_up = _follow_up_stream() iterator = _build_hold_back_iterator( - MockSlowAsyncStream(chunks, delay_seconds=0.05), - mock_handler, - ping_interval_seconds=0.02, + MockAsyncStream(_text_then_tool_use_stream()), _hooks_returning(MockAsyncStream(follow_up)) ) - collected = [] - async for chunk in iterator: - collected.append(chunk) + received = await _drain_without_pings(iterator) + events = _wire_events(received) - assert collected.count(STREAM_SSE_KEEPALIVE_PING_BYTES) >= 2 - assert [c for c in collected if c != STREAM_SSE_KEEPALIVE_PING_BYTES] == chunks + assert [data["message"]["id"] for event, data in events if event == "message_start"] == ["msg_live"] + assert _block_starts(events) == [(0, "text"), (1, "text")] + assert [(data["index"], data["delta"]["text"]) for event, data in events if event == "content_block_delta"] == [ + (0, "Let me look that up."), + (1, "Section 1 says hi."), + ] + assert [data["index"] for event, data in events if event == "content_block_stop"] == [0, 1] + assert received[-2:] == follow_up[-2:] + assert b"tool_use" not in b"".join(received) @pytest.mark.asyncio - async def test_should_propagate_upstream_error_instead_of_partial_message(self): - """An upstream failure surfaces as an error; the client never receives a truncated message.""" - chunks = _build_simple_text_stream()[:2] - - mock_handler = MagicMock() - mock_handler._call_agentic_completion_hooks = AsyncMock(return_value=None) - + async def test_a_follow_up_after_a_leading_tool_use_passes_through_unchanged_without_its_message_start(self): + tool_use_first = _text_then_tool_use_stream() + upstream = [tool_use_first[0], *tool_use_first[LIVE_TEXT_FRAMES:]] + follow_up = _follow_up_stream() iterator = _build_hold_back_iterator( - MockFailingAsyncStream(chunks, RuntimeError("upstream died")), - mock_handler, + MockAsyncStream(upstream), + _hooks_returning(MockAsyncStream([STREAM_SSE_KEEPALIVE_PING_BYTES, *follow_up])), ) - collected = [] + assert [chunk async for chunk in iterator] == [upstream[0], STREAM_SSE_KEEPALIVE_PING_BYTES, *follow_up[1:]] - async def _drain(): - async for chunk in iterator: - collected.append(chunk) + @pytest.mark.asyncio + async def test_a_non_streaming_follow_up_continues_the_message_too(self): + follow_up = { + "id": "msg_follow_up", + "type": "message", + "role": "assistant", + "model": "claude-sonnet-4-20250514", + "content": [{"type": "text", "text": "Section 1 says hi."}], + "stop_reason": "end_turn", + "stop_sequence": None, + "usage": {"input_tokens": 60, "output_tokens": 7}, + } + iterator = _build_hold_back_iterator(MockAsyncStream(_text_then_tool_use_stream()), _hooks_returning(follow_up)) + + events = _wire_events(await _drain_without_pings(iterator)) + + assert [data["message"]["id"] for event, data in events if event == "message_start"] == ["msg_live"] + assert _block_starts(events) == [(0, "text"), (1, "text")] + assert [event for event, _ in events][-2:] == ["message_delta", "message_stop"] + + @pytest.mark.asyncio + async def test_a_hook_that_resends_the_live_message_does_not_repeat_what_the_client_already_has(self): + resent = { + "id": "msg_live", + "type": "message", + "role": "assistant", + "model": "claude-sonnet-4-20250514", + "content": [{"type": "text", "text": "Let me look that up."}], + "stop_reason": "end_turn", + "stop_sequence": None, + "usage": {"input_tokens": 30, "output_tokens": 9}, + } + iterator = _build_hold_back_iterator(MockAsyncStream(_text_then_tool_use_stream()), _hooks_returning(resent)) + + events = _wire_events(await _drain_without_pings(iterator)) + + assert _block_starts(events) == [(0, "text")] + assert [data["delta"]["text"] for event, data in events if event == "content_block_delta"] == [ + "Let me look that up." + ] + assert [data["delta"]["stop_reason"] for event, data in events if event == "message_delta"] == ["end_turn"] + + @pytest.mark.asyncio + async def test_a_server_tool_use_the_hooks_left_in_place_fails_the_turn_after_the_live_text(self): + chunks = _text_then_tool_use_stream() + iterator = _build_hold_back_iterator(MockAsyncStream(chunks), _hooks_returning(None)) + + assert [chunk async for chunk in iterator] == [ + *chunks[:LIVE_TEXT_FRAMES], + SERVER_FULFILLED_TOOL_LEAK_ERROR_SSE_BYTES, + ] + + @pytest.mark.asyncio + @pytest.mark.parametrize("chunk_size", [1, 7, 64]) + async def test_a_plain_answer_reaches_the_client_as_the_upstream_frames_however_upstream_splits_them( + self, chunk_size + ): + message_start, *rest = _build_simple_text_stream() + frames = [message_start, b": upstream comment\n\n", *rest] + wire = b"".join(frames) + upstream = [wire[start : start + chunk_size] for start in range(0, len(wire), chunk_size)] + handler = _hooks_returning(None) + iterator = _build_hold_back_iterator(MockAsyncStream(upstream), handler) + + assert [chunk async for chunk in iterator] == frames + handler._call_agentic_completion_hooks.assert_awaited_once() + + @_on_virtual_clock + async def test_a_client_tool_use_waits_for_the_hooks_then_reaches_the_client_unchanged(self): + chunks = _text_then_tool_use_stream(tool_name="get_weather") + release_hooks = asyncio.Event() + + async def hooks(**_kwargs): + await release_hooks.wait() + + iterator = _build_hold_back_iterator(MockAsyncStream(chunks), _hooks_running(hooks)) + + assert await _read_until_ping(iterator) == chunks[:LIVE_TEXT_FRAMES] + assert await iterator.__anext__() == STREAM_SSE_KEEPALIVE_PING_BYTES + release_hooks.set() + assert await _drain_without_pings(iterator) == chunks[LIVE_TEXT_FRAMES:] + + @pytest.mark.parametrize("first_ending_frame", ["message_delta", "message_stop"]) + @_on_virtual_clock + async def test_the_end_of_an_answer_waits_for_the_hooks(self, first_ending_frame): + frames = _build_simple_text_stream() + chunks = frames if first_ending_frame == "message_delta" else [*frames[:LIVE_TEXT_FRAMES], frames[-1]] + release_hooks = asyncio.Event() + + async def hooks(**_kwargs): + await release_hooks.wait() + + iterator = _build_hold_back_iterator(MockAsyncStream(chunks), _hooks_running(hooks)) + + assert await _read_until_ping(iterator) == chunks[:LIVE_TEXT_FRAMES] + release_hooks.set() + assert await _drain_without_pings(iterator) == chunks[LIVE_TEXT_FRAMES:] + + @_on_virtual_clock + async def test_a_frame_the_stream_cut_off_waits_for_the_hooks(self): + streamed = _build_simple_text_stream()[:3] + cut_off_delta = _sse_event( + "content_block_delta", + {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": " and then"}}, + ).rstrip(b"\n") + release_hooks = asyncio.Event() + + async def hooks(**_kwargs): + await release_hooks.wait() + + iterator = _build_hold_back_iterator(MockAsyncStream([*streamed, cut_off_delta]), _hooks_running(hooks)) + + assert await _read_until_ping(iterator) == streamed + release_hooks.set() + assert await _drain_without_pings(iterator) == [cut_off_delta] + + @_on_virtual_clock + async def test_keepalive_pings_cover_a_stalled_upstream_without_losing_or_repeating_a_frame(self): + chunks = _build_simple_text_stream() + upstream = GatedStream(chunks[:2], chunks[2:]) + iterator = _build_hold_back_iterator(upstream, _hooks_returning(None)) + + assert await _read_until_ping(iterator) == chunks[:2] + assert await iterator.__anext__() == STREAM_SSE_KEEPALIVE_PING_BYTES + upstream.gate.set() + assert await _drain_without_pings(iterator) == chunks[2:] + + @_on_virtual_clock + async def test_keepalive_pings_cover_a_slow_held_tail_and_slow_hooks_without_leaking_held_frames(self): + chunks = _text_then_tool_use_stream() + upstream = GatedStream(chunks[: LIVE_TEXT_FRAMES + 1], chunks[LIVE_TEXT_FRAMES + 1 :]) + hooks_started = asyncio.Event() + release_hooks = asyncio.Event() + + async def hooks(**_kwargs): + hooks_started.set() + await release_hooks.wait() + return MockAsyncStream(_follow_up_stream()) + + iterator = _build_hold_back_iterator(upstream, _hooks_running(hooks)) + + assert await _read_until_ping(iterator) == chunks[:LIVE_TEXT_FRAMES] + assert await iterator.__anext__() == STREAM_SSE_KEEPALIVE_PING_BYTES + upstream.gate.set() + while not hooks_started.is_set(): + assert await iterator.__anext__() == STREAM_SSE_KEEPALIVE_PING_BYTES + assert await iterator.__anext__() == STREAM_SSE_KEEPALIVE_PING_BYTES + release_hooks.set() + received = await _drain_without_pings(iterator) + + assert _block_starts(_wire_events(received)) == [(1, "text")] + assert b"litellm_content_retrieve" not in b"".join(received) + + @_on_virtual_clock + async def test_keepalive_pings_keep_flowing_while_a_held_tool_use_trickles_in_faster_than_the_interval(self): + chunks = _text_then_tool_use_stream(tool_name="get_weather") + input_delta = _sse_event( + "content_block_delta", + {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": " "}}, + ) + trickled = [*chunks[: LIVE_TEXT_FRAMES + 1], *[input_delta] * 10, *chunks[LIVE_TEXT_FRAMES + 1 :]] + iterator = _build_hold_back_iterator( + MockSlowAsyncStream(trickled, delay_seconds=PING_INTERVAL_SECONDS * 0.4), _hooks_returning(None) + ) + + received = [chunk async for chunk in iterator] + + assert received[:LIVE_TEXT_FRAMES] == chunks[:LIVE_TEXT_FRAMES] + held = received[received.index(chunks[LIVE_TEXT_FRAMES - 1]) + 1 : received.index(chunks[LIVE_TEXT_FRAMES])] + assert STREAM_SSE_KEEPALIVE_PING_BYTES in held + assert [chunk for chunk in received if chunk != STREAM_SSE_KEEPALIVE_PING_BYTES] == trickled + + @pytest.mark.asyncio + async def test_an_upstream_failure_before_any_output_fails_the_first_read_instead_of_answering_a_ping(self): + handler = _hooks_returning(None) + iterator = _build_hold_back_iterator(MockFailingAsyncStream([], RuntimeError("upstream died")), handler) with pytest.raises(RuntimeError, match="upstream died"): - await _drain() + await iterator.__anext__() - assert all(c == STREAM_SSE_KEEPALIVE_PING_BYTES for c in collected) - mock_handler._call_agentic_completion_hooks.assert_not_awaited() + handler._call_agentic_completion_hooks.assert_not_awaited() @pytest.mark.asyncio - async def test_should_emit_pings_while_hooks_are_slow(self): - """Retrieval and follow-up generation can outlast a client's idle timeout, so hooks get keepalives too.""" - chunks = _build_tool_use_stream() - phase2_chunks = [b"follow-up-chunk"] + @pytest.mark.parametrize("partial_frame_bytes", [0, 20], ids=["at_a_frame_boundary", "mid_frame"]) + async def test_an_upstream_failure_after_text_reaches_the_client_after_that_text_and_keeps_failing( + self, partial_frame_bytes + ): + chunks = _text_then_tool_use_stream() + handler = _hooks_returning(None) + upstream = [*chunks[:LIVE_TEXT_FRAMES], chunks[LIVE_TEXT_FRAMES][:partial_frame_bytes]] + iterator = _build_hold_back_iterator(MockFailingAsyncStream(upstream, RuntimeError("upstream died")), handler) - async def slow_hooks(**_kwargs): - await asyncio.sleep(0.12) - return MockAsyncStream(phase2_chunks) + received = [] - mock_handler = MagicMock() - mock_handler._call_agentic_completion_hooks = AsyncMock(side_effect=slow_hooks) + async def drain(): + async for chunk in iterator: + received.append(chunk) - iterator = _build_hold_back_iterator( - MockAsyncStream(chunks), - mock_handler, - ping_interval_seconds=0.02, - ) + with pytest.raises(RuntimeError, match="upstream died"): + await drain() + with pytest.raises(RuntimeError, match="upstream died"): + await iterator.__anext__() - collected = [] - async for chunk in iterator: - collected.append(chunk) + assert received == chunks[:LIVE_TEXT_FRAMES] + handler._call_agentic_completion_hooks.assert_not_awaited() - assert collected.count(STREAM_SSE_KEEPALIVE_PING_BYTES) >= 4 - assert [c for c in collected if c != STREAM_SSE_KEEPALIVE_PING_BYTES] == phase2_chunks + @pytest.mark.asyncio + async def test_a_nested_agentic_follow_up_error_reaches_the_client_byte_identical(self): + nested = _build_hold_back_iterator(MockAsyncStream(_text_then_tool_use_stream()), _hooks_returning(None)) + iterator = _build_hold_back_iterator(MockAsyncStream(_text_then_tool_use_stream()), _hooks_returning(nested)) + + received = await _drain_without_pings(iterator) + events = _wire_events(received[:-1]) + + assert received[-1] == SERVER_FULFILLED_TOOL_LEAK_ERROR_SSE_BYTES + assert [data["message"]["id"] for event, data in events if event == "message_start"] == ["msg_live"] + assert _block_starts(events) == [(0, "text"), (1, "text")] @pytest.mark.asyncio async def test_a_rate_limited_follow_up_reaches_the_client_as_its_anthropic_error_event(self): @@ -1061,22 +1415,6 @@ class TestAgenticStreamingIteratorHoldBack: assert "retry" not in error_messages[0].lower() assert "litellm_content_retrieve" not in wire - @pytest.mark.asyncio - async def test_should_error_instead_of_replaying_when_no_hook_fires_on_tool_use(self): - """Hooks returning None on a retrieval tool_use is still a leak, so the turn fails loudly.""" - chunks = _build_tool_use_stream() - - mock_handler = MagicMock() - mock_handler._call_agentic_completion_hooks = AsyncMock(return_value=None) - - iterator = _build_hold_back_iterator(MockAsyncStream(chunks), mock_handler) - - collected = [] - async for chunk in iterator: - collected.append(chunk) - - assert [c for c in collected if c != STREAM_SSE_KEEPALIVE_PING_BYTES] == [SERVER_FULFILLED_TOOL_LEAK_ERROR_SSE_BYTES] - @pytest.mark.asyncio async def test_should_replay_client_owned_tool_use_verbatim(self): """Only server-fulfilled tools are withheld: a client's own tool_use still reaches it byte-identical.""" @@ -1097,30 +1435,27 @@ class TestAgenticStreamingIteratorHoldBack: assert [c for c in collected if c != STREAM_SSE_KEEPALIVE_PING_BYTES] == chunks - @pytest.mark.asyncio - async def test_should_emit_pings_while_the_follow_up_stream_is_slow(self): - """The corrected answer can be slow to generate, so the follow-up stream gets keepalives too.""" - chunks = _build_tool_use_stream() - phase2_chunks = [b"follow-up-chunk-1", b"follow-up-chunk-2"] - - mock_handler = MagicMock() - mock_handler._call_agentic_completion_hooks = AsyncMock( - return_value=MockSlowAsyncStream(phase2_chunks, delay_seconds=0.06) - ) - + @_on_virtual_clock + async def test_keepalive_pings_cover_a_stalled_follow_up(self): + follow_up = _follow_up_stream() + stalled = GatedStream(follow_up[:2], follow_up[2:]) + chunks = _text_then_tool_use_stream() iterator = _build_hold_back_iterator( - MockAsyncStream(chunks), - mock_handler, - ping_interval_seconds=0.02, + MockAsyncStream(chunks), _hooks_returning(stalled) ) - collected = [] - async for chunk in iterator: - collected.append(chunk) + before_stall = await _read_until_ping(iterator) + stalled.gate.set() + after_stall = await _drain_without_pings(iterator) - first_follow_up_index = collected.index(phase2_chunks[0]) - assert collected[first_follow_up_index + 1] == STREAM_SSE_KEEPALIVE_PING_BYTES - assert [c for c in collected if c != STREAM_SSE_KEEPALIVE_PING_BYTES] == phase2_chunks + assert before_stall[:LIVE_TEXT_FRAMES] == chunks[:LIVE_TEXT_FRAMES] + assert _block_starts(_wire_events(before_stall[LIVE_TEXT_FRAMES:])) == [(1, "text")] + assert [(event, data.get("index")) for event, data in _wire_events(after_stall)] == [ + ("content_block_delta", 1), + ("content_block_stop", 1), + ("message_delta", None), + ("message_stop", None), + ] @pytest.mark.asyncio async def test_should_propagate_follow_up_stream_error(self): @@ -1138,63 +1473,56 @@ class TestAgenticStreamingIteratorHoldBack: async for _ in iterator: pass - @pytest.mark.asyncio - async def test_aclose_cancels_in_flight_follow_up_chunk_task(self): - """Closing while a follow-up chunk is pending must not orphan that task.""" - chunks = _build_tool_use_stream() + @_on_virtual_clock + async def test_closing_while_upstream_is_pending_closes_upstream_without_running_hooks(self): + chunks = _text_then_tool_use_stream() + upstream = GatedStream(chunks[:LIVE_TEXT_FRAMES], chunks[LIVE_TEXT_FRAMES:]) + handler = _hooks_returning(None) + iterator = _build_hold_back_iterator(upstream, handler) - mock_handler = MagicMock() - mock_handler._call_agentic_completion_hooks = AsyncMock( - return_value=MockSlowAsyncStream([b"follow-up-chunk"], delay_seconds=5.0) + await _read_until_ping(iterator) + await iterator.aclose() + + assert upstream.closed + handler._call_agentic_completion_hooks.assert_not_awaited() + + @pytest.mark.parametrize("follow_up_frame_pending", [True, False]) + @_on_virtual_clock + async def test_closing_during_the_follow_up_closes_it(self, follow_up_frame_pending): + follow_up_frames = _follow_up_stream() + follow_up = GatedStream(follow_up_frames[:2], follow_up_frames[2:]) + iterator = _build_hold_back_iterator( + MockAsyncStream(_text_then_tool_use_stream()), _hooks_returning(follow_up) ) - iterator = _build_hold_back_iterator(MockAsyncStream(chunks), mock_handler, ping_interval_seconds=0.02) - - while iterator._follow_up_chunk_task is None: - await iterator.__anext__() - + if follow_up_frame_pending: + await _read_until_ping(iterator) + else: + for _ in range(LIVE_TEXT_FRAMES + 1): + await iterator.__anext__() await iterator.aclose() - assert iterator._follow_up_chunk_task.cancelled() - @pytest.mark.asyncio - async def test_aclose_cancels_drain_task(self): - """Closing the iterator mid-buffer must cancel the background drain task.""" - chunks = _build_simple_text_stream() + assert follow_up.closed - mock_handler = MagicMock() - mock_handler._call_agentic_completion_hooks = AsyncMock(return_value=None) + @_on_virtual_clock + async def test_closing_while_hooks_run_cancels_them(self): + hooks_started = asyncio.Event() + hooks_cancelled = asyncio.Event() + + async def hooks(**_kwargs): + hooks_started.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + hooks_cancelled.set() + raise iterator = _build_hold_back_iterator( - MockSlowAsyncStream(chunks, delay_seconds=5.0), - mock_handler, + MockAsyncStream(_text_then_tool_use_stream()), _hooks_running(hooks) ) - first = await iterator.__anext__() - assert first == STREAM_SSE_KEEPALIVE_PING_BYTES - assert iterator._drain_task is not None - - await iterator.aclose() - assert iterator._drain_task.cancelled() - - @pytest.mark.asyncio - async def test_aclose_cancels_in_flight_hook_task(self): - """Closing while hooks are running must not leave the retrieval follow-up task orphaned.""" - chunks = _build_tool_use_stream() - - async def never_finishing_hooks(**_kwargs): - await asyncio.sleep(5.0) - - mock_handler = MagicMock() - mock_handler._call_agentic_completion_hooks = AsyncMock(side_effect=never_finishing_hooks) - - iterator = _build_hold_back_iterator( - MockAsyncStream(chunks), - mock_handler, - ping_interval_seconds=0.02, - ) - - while iterator._hook_task is None: + while not hooks_started.is_set(): await iterator.__anext__() - await iterator.aclose() - assert iterator._hook_task.cancelled() + + assert hooks_cancelled.is_set()