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
Merge remote-tracking branch 'origin/main' into litellm_bedrock_messages_disconnect_billing
nuernber95a2586228bb
diff --cc basedpyright-code-budget.jsonindex a0042234935,83969d8dedf..a542d025e74--- a/basedpyright-code-budget.json+++ b/basedpyright-code-budget.json@@@ -54,10 -54,10 +54,10 @@@"limit": 0},"reportMissingParameterType": {- "limit": 5719+ "limit": 5658},"reportMissingTypeArgument": {- "limit": 15425+ "limit": 15656},"reportMissingTypeStubs": {"limit": 40@@@ -99,25 -99,25 +99,25 @@@"limit": 0},"reportUnknownArgumentType": {- "limit": 44526+ "limit": 44831},"reportUnknownLambdaType": {- "limit": 113+ "limit": 109},"reportUnknownMemberType": {- "limit": 38721+ "limit": 39267},"reportUnknownParameterType": {- "limit": 19778+ "limit": 19987},"reportUnknownVariableType": {- "limit": 30290+ "limit": 30922},"reportUnnecessaryCast": {- "limit": 118+ "limit": 117},"reportUnnecessaryComparison": {- "limit": 699+ "limit": 697},"reportUnnecessaryContains": {"limit": 5diff --cc litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.pyindex e302896ff5e,a282d5f4d4f..9e115c6624d--- a/litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py+++ b/litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py@@@ -8,12 -8,10 +8,14 @@@ import httpfrom pydantic import TypeAdapterfrom typing_extensions import TypedDict+from litellm.constants import (+ ANTHROPIC_MESSAGES_MAX_DETACHED_STREAM_DRAINS,+ ANTHROPIC_MESSAGES_STREAM_RELAY_QUEUE_MAXSIZE,+)from litellm.litellm_core_utils.core_helpers import process_response_headersfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+ from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER+ from litellm.llms.anthropic.common_utils import ANTHROPIC_ERROR_STATUS_CODE_MAPfrom litellm.proxy.pass_through_endpoints.success_handler import (PassThroughEndpointLogging,)@@@ -51,31 -133,141 +140,158 @@@ def _is_terminal_stream_chunk(chunk: obreturn _is_message_stop_chunk(chunk) or _is_provider_error_chunk(chunk)+def _try_claim_detached_drain_slot() -> bool:+ """Claim a detached-drain slot for the current task, bounding concurrency.++ Returns True if a slot was claimed (the caller may keep draining upstream+ for billing) or False if the cap is already reached (the caller should stop+ and bill what it has). Only touched from the event loop, so the check ++ insert need no lock.+ """+ if len(_DETACHED_STREAM_DRAINS) >= ANTHROPIC_MESSAGES_MAX_DETACHED_STREAM_DRAINS:+ return False+ current_task: Final = asyncio.current_task()+ if current_task is not None:+ _DETACHED_STREAM_DRAINS.add(current_task)+ current_task.add_done_callback(_DETACHED_STREAM_DRAINS.discard)+ return True+++ def _sse_event(event_type: str, payload: Mapping[str, object]) -> bytes:+ return f"event: {event_type}\ndata: {json.dumps(payload)}\n\n".encode()++def _incomplete_stream_error_sse_event() -> bytes:- payload: Final = json.dumps(- {- "type": "error",- "error": {"type": "api_error", "message": INCOMPLETE_STREAM_ERROR_MESSAGE},- }+ return _sse_event( # mutable-ok: one-shot JSON payload, never mutated after construction+ "error",+ {"type": "error", "error": {"type": "api_error", "message": INCOMPLETE_STREAM_ERROR_MESSAGE}},+ )+++ def _anthropic_content_block_start_and_deltas(+ block: Mapping[str, object],+ ) -> tuple[Mapping[str, object], tuple[Mapping[str, object], ...]]:+ """+ ``(content_block_start.content_block, content_block_delta.delta events)``+ for one Anthropic response content block. A thinking block emits both a+ thinking_delta and a trailing signature_delta - a real Anthropic stream+ does the same, and dropping the signature makes any replay of that+ assistant message (a follow-up turn, a tool-use continuation) fail+ Anthropic's thinking-signature verification. redacted_thinking has no+ delta at all - it is sent complete in content_block_start.+ """+ match block.get("type"):+ case "tool_use":+ return (+ { # mutable-ok: one-shot payload+ "id": block.get("id"),+ "name": block.get("name"),+ "input": {}, # mutable-ok: one-shot payload+ "type": "tool_use",+ },+ (+ { # mutable-ok: one-shot payload+ "partial_json": json.dumps(block.get("input") or {}), # mutable-ok: one-shot payload+ "type": "input_json_delta",+ },+ ),+ )+ case "thinking":+ signature: Final = block.get("signature")+ signature_deltas: Final = (+ ({"signature": signature, "type": "signature_delta"},) # mutable-ok: one-shot payload+ if isinstance(signature, str) and signature+ else ()+ )+ return (+ {"thinking": "", "signature": "", "type": "thinking"}, # mutable-ok: one-shot payload+ (+ {"thinking": block.get("thinking") or "", "type": "thinking_delta"}, # mutable-ok: one-shot payload+ *signature_deltas,+ ),+ )+ case "redacted_thinking":+ return ({"type": "redacted_thinking", "data": block.get("data")}, ()) # mutable-ok: one-shot JSON payload+ case _:+ return (+ {"type": "text", "text": ""}, # mutable-ok: one-shot JSON payload+ ({"type": "text_delta", "text": block.get("text") or ""},), # mutable-ok: one-shot JSON payload+ )+++ def anthropic_messages_response_as_sse_events(response: AnthropicMessagesResponse) -> tuple[bytes, ...]:+ """+ Render a complete (non-streaming) AnthropicMessagesResponse as the SSE+ event sequence a real streaming request would have produced.++ A mid-stream fallback can resolve to a non-streaming response even+ though the client asked to stream (e.g. an agentic tool-use loop that+ intercepts and returns a complete message) - yielding that dict directly+ into a `/v1/messages` SSE byte stream would produce a malformed+ response, so it's synthesized into the message_start/content_block_*/+ message_delta/message_stop lifecycle a real stream would have sent.+ """+ content_blocks: Final = response.get("content") or ()+ content_events: Final = (+ event for index, block in enumerate(content_blocks) for event in _anthropic_content_block_events(index, block)+ )+ # A real message_start always carries a null stop_reason/stop_sequence and+ # a zero output_tokens - those are only known once generation finishes, so+ # copying the completed response's final values here would let a client+ # treat the message as already finished, or double-count output tokens.+ message_start_usage: Final = { # mutable-ok: one-shot JSON payload+ **(response.get("usage") or {}),+ "output_tokens": 0,+ }+ message_start_payload: Final = { # mutable-ok: one-shot JSON payload, never mutated after construction+ "type": "message_start",+ "message": { # mutable-ok: one-shot JSON payload+ **response,+ "content": [], # mutable-ok: one-shot JSON payload+ "stop_reason": None,+ "stop_sequence": None,+ "usage": message_start_usage,+ },+ }+ message_delta_payload: Final = { # mutable-ok: one-shot JSON payload, never mutated after construction+ "type": "message_delta",+ "delta": { # mutable-ok: one-shot JSON payload+ "stop_reason": response.get("stop_reason"),+ "stop_sequence": response.get("stop_sequence"),+ },+ "usage": response.get("usage") or {}, # mutable-ok: one-shot JSON payload+ }+ return (+ _sse_event("message_start", message_start_payload),+ *content_events,+ _sse_event("message_delta", message_delta_payload),+ _sse_event("message_stop", {"type": "message_stop"}), # mutable-ok: one-shot JSON payload+ )+++ def _anthropic_content_block_events(index: int, block: Mapping[str, object]) -> tuple[bytes, ...]:+ start_block, deltas = _anthropic_content_block_start_and_deltas(block)+ start_payload: Final = { # mutable-ok: one-shot payload+ "type": "content_block_start",+ "index": index,+ "content_block": start_block,+ }+ stop_payload: Final = { # mutable-ok: one-shot payload+ "type": "content_block_stop",+ "index": index,+ }+ delta_events: Final = tuple(+ _sse_event(+ "content_block_delta",+ {"type": "content_block_delta", "index": index, "delta": delta}, # mutable-ok: one-shot payload+ )+ for delta in deltas+ )+ return (+ _sse_event("content_block_start", start_payload),+ *delta_events,+ _sse_event("content_block_stop", stop_payload),)- return f"event: error\ndata: {payload}\n\n".encode()class AnthropicMessagesStreamHiddenParams(TypedDict):@@@ -216,132 -420,11 +444,134 @@@ class BaseAnthropicMessagesStreamingIteGeneric async SSE wrapper that converts streaming chunks to SSE formatand handles logging.+ The upstream read runs in a detached background task (``_pump_upstream``)+ so that a client disconnect tears down only this client-facing generator,+ never the upstream drain + billing. The provider (e.g. Bedrock) keeps+ generating and billing the full response regardless of the client, so+ draining it to completion is what lets spend tracking see the real+ terminal ``message_delta`` / ``message_stop`` usage instead of a+ truncated placeholder count.++ Chunks reach the client through a bounded queue. While the client is+ connected the pump blocks on a full queue (racing the disconnect+ signal), so a slow reader throttles the upstream read exactly as the old+ direct ``yield`` did instead of letting the whole response buffer in+ memory. Once the client goes away the pump stops enqueueing and only+ keeps a single ``collected_chunks`` copy for billing, and the number of+ such post-disconnect drains running at once is capped so client behavior+ can't create unbounded worker state; over the cap the pump bills what it+ has rather than draining further. Detached-drain lifetime is otherwise+ bounded by the upstream stream/read timeout.++ An upstream failure (Bedrock read / decode / chunk-conversion error)+ that happens while the client is still connected is forwarded through+ the queue and re-raised here, so the original provider exception (and+ its status) reaches the proxy's failure handling unchanged rather than+ being masked by a generic incomplete-stream event.+This method provides the common logic for both Anthropic and Bedrock implementations."""- collected_chunks: Final = []- saw_terminal_event = False+ queue: Final[asyncio.Queue[bytes | None | BaseException]] = asyncio.Queue(+ maxsize=ANTHROPIC_MESSAGES_STREAM_RELAY_QUEUE_MAXSIZE+ )+ client_detached: Final = asyncio.Event()++ pump_task: Final = asyncio.create_task(self._pump_upstream_to_queue(completion_stream, queue, client_detached))+ _UPSTREAM_PUMP_TASKS.add(pump_task)+ pump_task.add_done_callback(_UPSTREAM_PUMP_TASKS.discard)++ try:+ while True:+ item = await queue.get()+ if item is None:+ break+ if isinstance(item, BaseException):+ raise item+ yield item+ finally:+ client_detached.set()++ async def _bill_collected_chunks(+ self,+ collected_chunks: list[bytes], # mutable-ok: SSE buffer forwarded to list-typed _handle_streaming_logging++ *,++ stream_teardown: bool,+ ) -> None:+ from litellm._logging import verbose_proxy_logger++ try:- await self._handle_streaming_logging(collected_chunks)++ await self._handle_streaming_logging(collected_chunks, stream_teardown=stream_teardown)+ except Exception as exc: # noqa: BLE001 # billing is best-effort; never crash the pump+ verbose_proxy_logger.warning(+ "async_sse_wrapper billing failed after %d chunks: %s(%s)",+ len(collected_chunks),+ type(exc).__name__,+ exc,+ )++ @staticmethod+ async def _abort_upstream(+ completion_stream: AsyncIterator[bytes | GenericStreamingChunk | ModelResponseStream | Mapping[str, object]],+ ) -> None:+ """Close the upstream provider stream so it stops generating and billing."""+ from litellm._logging import verbose_proxy_logger+ try:+ await aclose_if_supported(completion_stream)+ except Exception as exc: # noqa: BLE001 # abort is best-effort; log and continue+ verbose_proxy_logger.warning(+ "async_sse_wrapper failed to abort upstream stream: %s(%s)",+ type(exc).__name__,+ exc,+ )++ @staticmethod+ async def _enqueue_for_client(+ queue: "asyncio.Queue[bytes | None | BaseException]",+ client_detached: "asyncio.Event",+ item: bytes | None | BaseException,+ ) -> bool:+ """Deliver one item to the client, applying backpressure.++ Returns True if the item was queued, False if the client disconnected+ before there was room (the item is then dropped, since a gone client+ can't receive it). Never blocks once the client has detached.+ """+ if client_detached.is_set():+ return False+ try:+ queue.put_nowait(item)+ return True+ except asyncio.QueueFull:+ pass+ put_task: Final = asyncio.ensure_future(queue.put(item))+ detached_task: Final = asyncio.ensure_future(client_detached.wait())+ try:+ await asyncio.wait(frozenset((put_task, detached_task)), return_when=asyncio.FIRST_COMPLETED)+ finally:+ if not detached_task.done():+ detached_task.cancel()+ if put_task.done() and not put_task.cancelled():+ return True+ put_task.cancel()+ return False++ async def _pump_upstream_to_queue(+ self,+ completion_stream: AsyncIterator[bytes | GenericStreamingChunk | ModelResponseStream | Mapping[str, object]],+ queue: "asyncio.Queue[bytes | None | BaseException]",+ client_detached: "asyncio.Event",+ ) -> None:+ """Drain the whole upstream into ``queue`` (backpressured) and bill once.++ Runs detached so a client disconnect can't interrupt the upstream read;+ see ``async_sse_wrapper`` for the full rationale. Returns after billing.+ """+ from litellm._logging import verbose_proxy_logger++ collected_chunks: Final[list[bytes]] = [] # mutable-ok: SSE billing buffer appended to across the drain+ saw_terminal_event = False # rebind-ok: accumulates across the upstream loop+ draining_detached = False # rebind-ok: set once this pump claims a detached-drain slottry:async for chunk in completion_stream:if self.completion_start_time is None:@@@ -349,53 -432,17 +579,53 @@@saw_terminal_event = saw_terminal_event or _is_terminal_stream_chunk(chunk)encoded_chunk = self._convert_chunk_to_sse_format(chunk)collected_chunks.append(encoded_chunk)- yield encoded_chunk- except (GeneratorExit, asyncio.CancelledError):- # A client disconnect tears the generator down at the yield, so the- # post-loop logging below never runs and the tokens already streamed- # (and billed by the provider) would never reach spend tracking. See LIT-5839.- if collected_chunks:- await self._handle_streaming_logging(collected_chunks, stream_teardown=True)- raise-- if not saw_terminal_event:- yield _incomplete_stream_error_sse_event()-- # Handle logging after all chunks are processed- await self._handle_streaming_logging(collected_chunks)+ if not client_detached.is_set():+ await self._enqueue_for_client(queue, client_detached, encoded_chunk)+ continue+ if not draining_detached:+ if not _try_claim_detached_drain_slot():+ verbose_proxy_logger.warning(+ "async_sse_wrapper: detached-drain cap (%d) reached; billing %d partial "+ "chunks and aborting the upstream stream to stop provider billing",+ ANTHROPIC_MESSAGES_MAX_DETACHED_STREAM_DRAINS,+ len(collected_chunks),+ )- await self._bill_collected_chunks(collected_chunks)++ await self._bill_collected_chunks(collected_chunks, stream_teardown=True)+ await self._abort_upstream(completion_stream)+ return+ draining_detached = True+ except Exception as exc: # noqa: BLE001 # upstream errors are handled/forwarded by _handle_pump_upstream_error+ await self._handle_pump_upstream_error(queue, client_detached, collected_chunks, exc)+ return++ if not client_detached.is_set():+ if not saw_terminal_event:+ await self._enqueue_for_client(queue, client_detached, _incomplete_stream_error_sse_event())+ await self._enqueue_for_client(queue, client_detached, None)- await self._bill_collected_chunks(collected_chunks)++ await self._bill_collected_chunks(collected_chunks, stream_teardown=client_detached.is_set())++ async def _handle_pump_upstream_error(+ self,+ queue: "asyncio.Queue[bytes | None | BaseException]",+ client_detached: "asyncio.Event",+ collected_chunks: list[bytes], # mutable-ok: SSE buffer forwarded to list-typed _bill_collected_chunks+ exc: BaseException,+ ) -> None:+ """Forward a provider error to a still-connected client, else salvage partial spend.++ Handing the original exception to the client-facing generator lets it+ re-raise so the proxy's failure handling keeps the provider status and+ owns logging (no success-bill). If the client already went away, no+ failure hook runs, so bill the partial instead of dropping the request.+ """+ from litellm._logging import verbose_proxy_logger++ if not client_detached.is_set() and await self._enqueue_for_client(queue, client_detached, exc):+ return+ verbose_proxy_logger.warning(+ "async_sse_wrapper upstream pump failed after client disconnect (%d chunks): %s(%s)",+ len(collected_chunks),+ type(exc).__name__,+ exc,+ )- await self._bill_collected_chunks(collected_chunks)++ await self._bill_collected_chunks(collected_chunks, stream_teardown=True)diff --cc tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_streaming_iterator.pyindex f5399893a3b,b8ce11db8d1..f0a3c7fdff0--- a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_streaming_iterator.py+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_streaming_iterator.py@@@ -6,12 -4,15 +4,13 @@@ from datetime import datetimimport pytest- sys.path.insert(0, os.path.abspath("../../../../.."))from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj-from litellm.llms.anthropic.experimental_pass_through.messages import (- streaming_iterator as streaming_iterator_module,-)+from litellm.llms.anthropic.experimental_pass_through.messages import streaming_iterator as streaming_iterator_modulefrom litellm.llms.anthropic.experimental_pass_through.messages.streaming_iterator import (INCOMPLETE_STREAM_ERROR_MESSAGE,+ AnthropicMessagesStreamHiddenParams,+ AnthropicMessagesStreamingResponse,BaseAnthropicMessagesStreamingIterator,_incomplete_stream_error_sse_event,_is_message_stop_chunk,@@@ -235,6 -332,70 +330,29 @@@ async def test_async_sse_wrapper_excludassert not any(chunk.startswith(b"event: error\n") for chunk in iterator.logged_chunks)+ async def _events_then_hang(events):+ for event in events:+ yield event+ await asyncio.Event().wait()++-async def test_async_sse_wrapper_logs_partial_chunks_on_client_disconnect():- """- Regression test for LIT-5839: a client disconnect tears the generator- down with GeneratorExit at the yield, which used to skip the post-loop- logging dispatch entirely, so the partial output tokens the provider- already generated (and billed) never reached spend tracking.- """- iterator = _RecordingLoggingIterator(- litellm_logging_obj=_make_logging_obj("test_disconnect_logs_partial_chunks"),- request_body={},- )- wrapped = iterator.async_sse_wrapper(_events_then_hang(TRUNCATED_TOOL_USE_EVENTS))- streamed = [await wrapped.__anext__() for _ in range(len(TRUNCATED_TOOL_USE_EVENTS))]- assert iterator.logging_call_count == 0-- await wrapped.aclose()-- assert iterator.logging_call_count == 1- assert iterator.logged_chunks == streamed---async def test_async_sse_wrapper_logs_partial_chunks_on_cancellation():- iterator = _RecordingLoggingIterator(- litellm_logging_obj=_make_logging_obj("test_cancellation_logs_partial_chunks"),- request_body={},- )- wrapped = iterator.async_sse_wrapper(_events_then_hang(TRUNCATED_TOOL_USE_EVENTS))- streamed = [await wrapped.__anext__() for _ in range(len(TRUNCATED_TOOL_USE_EVENTS))]-- consume_task = asyncio.ensure_future(wrapped.__anext__())- await asyncio.sleep(0.01)- consume_task.cancel()- with pytest.raises(asyncio.CancelledError):- await consume_task-- assert iterator.logging_call_count == 1- assert iterator.logged_chunks == streamed--+ @pytest.mark.asyncio+ async def test_async_sse_wrapper_skips_logging_on_disconnect_before_first_chunk():+ iterator = _RecordingLoggingIterator(+ litellm_logging_obj=_make_logging_obj("test_disconnect_before_first_chunk"),+ request_body={},+ )+ wrapped = iterator.async_sse_wrapper(_events_then_hang(()))++ consume_task = asyncio.ensure_future(wrapped.__anext__())+ await asyncio.sleep(0.01)+ consume_task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await consume_task++ assert iterator.logging_call_count == 0++def test_incomplete_stream_error_sse_event_is_valid_anthropic_error():event = _incomplete_stream_error_sse_event().decode()lines = event.split("\n")@@@ -247,421 -408,224 +365,659 @@@assert event.endswith("\n\n")+_STREAM_PREFIX = (+ {"type": "message_start", "message": {"id": "msg_1", "usage": {"input_tokens": 52, "output_tokens": 1}}},+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "The Roman"}},+)+_STREAM_TAIL = (+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": " Empire ..."}},+ {"type": "content_block_stop", "index": 0},+ {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 64}},+ {"type": "message_stop"},+)+++def _output_tokens_from_logged_chunks(chunks: list[bytes]) -> int | None:+ """Read the last output_tokens the billing path would see from the SSE bytes."""+ latest: int | None = None+ for raw in chunks:+ for line in raw.decode().splitlines():+ if not line.startswith("data:"):+ continue+ data = json.loads(line[len("data:"):].strip())+ usage = data.get("usage") if isinstance(data, dict) else None+ if isinstance(usage, dict) and usage.get("output_tokens") is not None:+ latest = usage["output_tokens"]+ return latest+++async def test_async_sse_wrapper_bills_full_stream_after_client_disconnect():+ """+ Regression: on a client disconnect mid-stream the upstream provider keeps+ generating (and billing) the full response. The wrapper must keep draining+ that upstream to its terminal ``message_delta`` and bill the real+ output_tokens (64), not the partial count the client drained before leaving+ (the message_start placeholder, 1).++ A ``tail_gated`` event holds back the stream tail until the client has+ disconnected, so the tail can only be captured by a drain that survives the+ client teardown - exactly the path the previous implementation dropped.+ """+ tail_gated = asyncio.Event()+ upstream_fully_drained = asyncio.Event()++ async def _gated_stream():+ for event in _STREAM_PREFIX:+ yield event+ await tail_gated.wait()+ for event in _STREAM_TAIL:+ yield event+ upstream_fully_drained.set()++ iterator = _RecordingLoggingIterator(+ litellm_logging_obj=_make_logging_obj("test_bills_full_stream_after_disconnect"),+ request_body={},+ )++ gen = iterator.async_sse_wrapper(_gated_stream())++ client_chunks = []+ async for chunk in gen:+ client_chunks.append(chunk)+ if len(client_chunks) == len(_STREAM_PREFIX):+ break+ await gen.aclose()++ tail_gated.set()+ await asyncio.wait_for(upstream_fully_drained.wait(), timeout=5)+ for _ in range(100):+ if iterator.logged_chunks:+ break+ await asyncio.sleep(0.01)++ assert len(client_chunks) == len(_STREAM_PREFIX)++ assert iterator.logged_chunks, "pump never billed after client disconnect"+ assert _output_tokens_from_logged_chunks(iterator.logged_chunks) == 64+ assert any(c.startswith(b"event: message_stop\n") for c in iterator.logged_chunks)+ assert not any(c.startswith(b"event: error\n") for c in iterator.logged_chunks)+++async def test_async_sse_wrapper_bills_full_stream_when_client_reads_all():+ """Happy path: when the client drains the whole stream, billing still sees+ the terminal output_tokens (64) and the client gets every chunk."""+ tail_gated = asyncio.Event()+ tail_gated.set() # no gating; full stream flows immediately++ async def _full_stream():+ for event in (*_STREAM_PREFIX, *_STREAM_TAIL):+ yield event++ iterator = _RecordingLoggingIterator(+ litellm_logging_obj=_make_logging_obj("test_bills_full_stream_happy_path"),+ request_body={},+ )+ client_chunks = [chunk async for chunk in iterator.async_sse_wrapper(_full_stream())]++ for _ in range(100):+ if iterator.logged_chunks:+ break+ await asyncio.sleep(0.01)++ assert len(client_chunks) == len(_STREAM_PREFIX) + len(_STREAM_TAIL)+ assert _output_tokens_from_logged_chunks(iterator.logged_chunks) == 64+ assert not any(c.startswith(b"event: error\n") for c in iterator.logged_chunks)+++class _ProviderStreamError(Exception):+ """Stand-in for a provider-specific streaming failure carrying a status code."""++ def __init__(self, message: str, status_code: int):+ super().__init__(message)+ self.status_code = status_code+++async def test_async_sse_wrapper_reraises_upstream_error_to_connected_client():+ """+ Regression: an upstream failure (Bedrock read / decode / chunk-conversion)+ before message_stop must propagate the ORIGINAL provider exception to a+ still-connected client, so the proxy's failure handling keeps the+ provider-specific status. The pump must not swallow it into a generic+ api_error event + normal termination.+ """++ async def _failing_stream():+ yield {"type": "message_start", "message": {"id": "msg_1", "usage": {"input_tokens": 52, "output_tokens": 1}}}+ yield {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "partial"}}+ raise _ProviderStreamError("bedrock stream blew up", status_code=529)++ iterator = _RecordingLoggingIterator(+ litellm_logging_obj=_make_logging_obj("test_reraises_upstream_error"),+ request_body={},+ )++ received = []+ with pytest.raises(_ProviderStreamError) as excinfo:+ async for chunk in iterator.async_sse_wrapper(_failing_stream()):+ received.append(chunk)++ assert excinfo.value.status_code == 529+ assert received+ assert not any(c.startswith(b"event: error\n") for c in received)+ assert iterator.logged_chunks == []+++async def test_async_sse_wrapper_salvages_partial_spend_on_upstream_error_after_disconnect():+ """+ When the upstream errors AFTER the client has already disconnected there is+ no live client to re-raise to and no failure hook will run, so the pump+ salvages partial spend from what it collected instead of dropping the row.+ """+ tail_gated = asyncio.Event()++ async def _gated_failing_stream():+ yield {"type": "message_start", "message": {"id": "msg_1", "usage": {"input_tokens": 52, "output_tokens": 1}}}+ yield {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "partial"}}+ await tail_gated.wait()+ raise _ProviderStreamError("late failure", status_code=500)++ iterator = _RecordingLoggingIterator(+ litellm_logging_obj=_make_logging_obj("test_salvage_partial_on_late_error"),+ request_body={},+ )++ gen = iterator.async_sse_wrapper(_gated_failing_stream())+ received = [await gen.__anext__(), await gen.__anext__()]+ await gen.aclose() # client disconnects before the upstream error++ tail_gated.set() # let the upstream raise now, after disconnect+ for _ in range(100):+ if iterator.logged_chunks:+ break+ await asyncio.sleep(0.01)++ assert len(received) == 2+ assert iterator.logged_chunks == received+++async def test_async_sse_wrapper_applies_backpressure_to_slow_client(monkeypatch):+ """+ Regression: the relay queue is bounded, so a slow client throttles the+ upstream read instead of letting the pump buffer the whole response in+ memory. With a tiny queue and a client that reads a single chunk, the pump+ must stall after producing only a queue's worth of chunks ahead, not race+ to the end of a large stream.+ """+ monkeypatch.setattr(streaming_iterator_module, "ANTHROPIC_MESSAGES_STREAM_RELAY_QUEUE_MAXSIZE", 2)++ total = 200+ produced = 0++ async def _fast_stream():+ nonlocal produced+ for i in range(total):+ produced += 1+ yield {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": f"t{i}"}}++ iterator = _make_iterator("test_backpressure_slow_client")+ gen = iterator.async_sse_wrapper(_fast_stream())+ try:+ await gen.__anext__()+ for _ in range(500):+ await asyncio.sleep(0)+ assert produced <= 2 + 3, f"pump ran ahead unthrottled: produced {produced} of {total}"+ assert produced < total+ finally:+ await gen.aclose()+++async def test_async_sse_wrapper_bills_partial_when_detached_drain_cap_reached(monkeypatch):+ """+ Regression: when the concurrent detached-drain cap is already reached, a+ pump whose client has disconnected must bill what it collected instead of+ continuing to drain (and accumulating) the rest of a large upstream stream,+ so slow/abandoned clients can't pin unbounded worker state.++ The cap slot set is pre-occupied so the single slot is unavailable when this+ pump reaches its first post-disconnect chunk; that isolates the cap decision+ from multi-pump scheduling races.+ """+ monkeypatch.setattr(streaming_iterator_module, "ANTHROPIC_MESSAGES_MAX_DETACHED_STREAM_DRAINS", 1)+ monkeypatch.setattr(streaming_iterator_module, "ANTHROPIC_MESSAGES_STREAM_RELAY_QUEUE_MAXSIZE", 4)++ async def _hold_slot():+ await asyncio.sleep(3600)++ holder = asyncio.ensure_future(_hold_slot())+ streaming_iterator_module._DETACHED_STREAM_DRAINS.add(holder)+ tail_reached = False++ async def _long_stream():+ nonlocal tail_reached+ yield {"type": "message_start", "message": {"id": "m", "usage": {"input_tokens": 5, "output_tokens": 1}}}+ yield {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "x"}}+ for i in range(100):+ yield {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": f"more{i}"}}+ tail_reached = True+ yield {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 42}}+ yield {"type": "message_stop"}++ iterator = _RecordingLoggingIterator(litellm_logging_obj=_make_logging_obj("drain_cap_full"), request_body={})+ try:+ gen = iterator.async_sse_wrapper(_long_stream())+ await gen.__anext__() # message_start+ await gen.__anext__() # first delta+ await gen.aclose() # client disconnects; 100+ chunks remain upstream++ for _ in range(200):+ if iterator.logged_chunks:+ break+ await asyncio.sleep(0)++ assert iterator.logged_chunks, "capped pump never billed"+ assert len(iterator.logged_chunks) <= 2 + streaming_iterator_module.ANTHROPIC_MESSAGES_STREAM_RELAY_QUEUE_MAXSIZE+ assert len(iterator.logged_chunks) < 100+ assert not any(c.startswith(b"event: message_stop\n") for c in iterator.logged_chunks)+ assert tail_reached is False, "pump kept draining past the cap instead of stopping"+ finally:+ holder.cancel()+ streaming_iterator_module._DETACHED_STREAM_DRAINS.discard(holder)+++async def test_async_sse_wrapper_aborts_upstream_when_detached_drain_cap_reached(monkeypatch):+ """+ Regression: when the cap is full and a disconnected pump bails, it must call+ aclose on the upstream stream so the provider stops generating and billing,+ not continue running the stream while we record only the partial prefix.+ """+ monkeypatch.setattr(streaming_iterator_module, "ANTHROPIC_MESSAGES_MAX_DETACHED_STREAM_DRAINS", 1)+ monkeypatch.setattr(streaming_iterator_module, "ANTHROPIC_MESSAGES_STREAM_RELAY_QUEUE_MAXSIZE", 4)++ async def _hold_slot():+ await asyncio.sleep(3600)++ holder = asyncio.ensure_future(_hold_slot())+ streaming_iterator_module._DETACHED_STREAM_DRAINS.add(holder)++ class _AbortableStream:+ def __init__(self):+ self.aclose_called = False+ self._remaining = iter(+ (+ {"type": "message_start", "message": {"id": "m", "usage": {"input_tokens": 5, "output_tokens": 1}}},+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "x"}},+ )+ + tuple(+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": f"t{i}"}}+ for i in range(50)+ )+ )++ def __aiter__(self):+ return self++ async def __anext__(self):+ try:+ return next(self._remaining)+ except StopIteration:+ raise StopAsyncIteration++ async def aclose(self):+ self.aclose_called = True++ stream = _AbortableStream()+ iterator = _RecordingLoggingIterator(litellm_logging_obj=_make_logging_obj("abort_upstream_at_cap"), request_body={})+ try:+ gen = iterator.async_sse_wrapper(stream)+ await gen.__anext__()+ await gen.__anext__()+ await gen.aclose()++ for _ in range(200):+ if iterator.logged_chunks:+ break+ await asyncio.sleep(0)++ assert iterator.logged_chunks, "capped pump never billed"+ assert stream.aclose_called, "upstream aclose was not called when the detached-drain cap was reached"+ finally:+ holder.cancel()+ streaming_iterator_module._DETACHED_STREAM_DRAINS.discard(holder)+++async def test_abort_upstream_logs_warning_when_aclose_raises(caplog):+ """_abort_upstream must swallow and log any exception from aclose()."""+ import logging++ class _ExplodingStream:+ def __aiter__(self):+ return self++ async def __anext__(self):+ raise StopAsyncIteration++ async def aclose(self):+ raise RuntimeError("aclose exploded")++ with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):+ await BaseAnthropicMessagesStreamingIterator._abort_upstream(_ExplodingStream())++ assert any("abort" in r.message and "RuntimeError" in r.message for r in caplog.records)+++async def test_enqueue_for_client_returns_false_when_already_detached():+ """_enqueue_for_client must return False immediately (without touching the queue)+ when client_detached is already set before the call."""+ from litellm.llms.anthropic.experimental_pass_through.messages.streaming_iterator import (+ BaseAnthropicMessagesStreamingIterator,+ )++ queue: asyncio.Queue[bytes | None | BaseException] = asyncio.Queue(maxsize=1)+ client_detached = asyncio.Event()+ client_detached.set()++ result = await BaseAnthropicMessagesStreamingIterator._enqueue_for_client(queue, client_detached, b"chunk")+ assert result is False+ assert queue.empty()+++async def test_enqueue_for_client_returns_false_when_client_detaches_while_queue_full():+ """_enqueue_for_client must return False (and cancel the put) when the queue+ is full and client_detached fires before space becomes available."""+ from litellm.llms.anthropic.experimental_pass_through.messages.streaming_iterator import (+ BaseAnthropicMessagesStreamingIterator,+ )++ queue: asyncio.Queue[bytes | None | BaseException] = asyncio.Queue(maxsize=1)+ queue.put_nowait(b"already-full")++ client_detached = asyncio.Event()++ async def _set_detached_soon():+ await asyncio.sleep(0.01)+ client_detached.set()++ asyncio.create_task(_set_detached_soon())+ result = await BaseAnthropicMessagesStreamingIterator._enqueue_for_client(queue, client_detached, b"new-chunk")+ assert result is False+ assert queue.qsize() == 1+ assert queue.get_nowait() == b"already-full"+++async def test_async_sse_wrapper_drains_detached_when_cap_available(monkeypatch):+ """Complement to the cap test: with a slot free, a disconnected pump drains+ the full upstream and bills the terminal usage, and releases its slot after."""+ monkeypatch.setattr(streaming_iterator_module, "ANTHROPIC_MESSAGES_MAX_DETACHED_STREAM_DRAINS", 1)+ monkeypatch.setattr(streaming_iterator_module, "ANTHROPIC_MESSAGES_STREAM_RELAY_QUEUE_MAXSIZE", 4)++ async def _stream():+ yield {"type": "message_start", "message": {"id": "m", "usage": {"input_tokens": 5, "output_tokens": 1}}}+ yield {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "x"}}+ for i in range(20):+ yield {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": f"m{i}"}}+ yield {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 42}}+ yield {"type": "message_stop"}++ iterator = _RecordingLoggingIterator(litellm_logging_obj=_make_logging_obj("drain_cap_free"), request_body={})+ gen = iterator.async_sse_wrapper(_stream())+ await gen.__anext__()+ await gen.__anext__()+ await gen.aclose()++ for _ in range(300):+ if iterator.logged_chunks:+ break+ await asyncio.sleep(0.01)++ assert any(c.startswith(b"event: message_stop\n") for c in iterator.logged_chunks)+ assert len(streaming_iterator_module._DETACHED_STREAM_DRAINS) == 0+++++ def _decode_sse_events(events: tuple[bytes, ...]) -> list[tuple[str, dict]]:+ decoded = []+ for event in events:+ assert isinstance(event, bytes)+ lines = event.decode().split("\n")+ assert lines[0].startswith("event: ")+ decoded.append((lines[0].removeprefix("event: "), json.loads(lines[1].removeprefix("data: "))))+ return decoded+++ def test_anthropic_messages_response_as_sse_events_text_block():+ response = {+ "id": "msg_1",+ "model": "claude-haiku",+ "role": "assistant",+ "type": "message",+ "stop_reason": "end_turn",+ "stop_sequence": None,+ "content": [{"type": "text", "text": "hello"}],+ "usage": {"input_tokens": 3, "output_tokens": 2},+ }+ decoded = _decode_sse_events(anthropic_messages_response_as_sse_events(response))+ types = [event_type for event_type, _ in decoded]+ assert types == [+ "message_start",+ "content_block_start",+ "content_block_delta",+ "content_block_stop",+ "message_delta",+ "message_stop",+ ]+ # message_start must not carry generated content itself, matching a real+ # streaming response - it arrives via the content_block_delta that follows.+ assert decoded[0][1]["message"]["content"] == []+ assert decoded[0][1]["message"]["id"] == "msg_1"+ # Bugbot regression: message_start must not carry the completed response's+ # final stop_reason/stop_sequence/output_tokens - a real stream keeps those+ # null/zero until message_delta, so a client could otherwise treat the+ # message as already finished, or double-count output tokens.+ assert decoded[0][1]["message"]["stop_reason"] is None+ assert decoded[0][1]["message"]["stop_sequence"] is None+ assert decoded[0][1]["message"]["usage"] == {"input_tokens": 3, "output_tokens": 0}+ assert decoded[1][1]["content_block"] == {"type": "text", "text": ""}+ assert decoded[2][1]["delta"] == {"type": "text_delta", "text": "hello"}+ assert decoded[4][1]["delta"]["stop_reason"] == "end_turn"+ assert decoded[4][1]["usage"] == {"input_tokens": 3, "output_tokens": 2}+++ def test_anthropic_messages_response_as_sse_events_tool_use_block():+ response = {+ "id": "msg_2",+ "content": [{"type": "tool_use", "id": "toolu_1", "name": "get_weather", "input": {"city": "NYC"}}],+ "stop_reason": "tool_use",+ }+ decoded = _decode_sse_events(anthropic_messages_response_as_sse_events(response))+ content_block_start = dict(decoded)["content_block_start"]+ assert content_block_start["content_block"] == {+ "type": "tool_use",+ "id": "toolu_1",+ "name": "get_weather",+ "input": {},+ }+ content_block_delta = dict(decoded)["content_block_delta"]+ assert json.loads(content_block_delta["delta"]["partial_json"]) == {"city": "NYC"}+ assert content_block_delta["delta"]["type"] == "input_json_delta"+++ def test_anthropic_messages_response_as_sse_events_thinking_block_emits_signature_delta():+ """Bugbot regression: a thinking block's real `signature` must reach the+ client via a trailing signature_delta, not be silently dropped - Anthropic+ rejects a replayed assistant message (a follow-up turn, a tool-use+ continuation) whose thinking block lacks its original signature."""+ response = {+ "id": "msg_5",+ "content": [{"type": "thinking", "thinking": "let me think", "signature": "sig-abc123"}],+ "stop_reason": "end_turn",+ }+ decoded = _decode_sse_events(anthropic_messages_response_as_sse_events(response))+ deltas = [payload["delta"] for event_type, payload in decoded if event_type == "content_block_delta"]+ assert deltas == [+ {"type": "thinking_delta", "thinking": "let me think"},+ {"type": "signature_delta", "signature": "sig-abc123"},+ ]+++ def test_anthropic_messages_response_as_sse_events_thinking_block_without_signature_omits_delta():+ response = {+ "id": "msg_6",+ "content": [{"type": "thinking", "thinking": "let me think", "signature": None}],+ "stop_reason": "end_turn",+ }+ decoded = _decode_sse_events(anthropic_messages_response_as_sse_events(response))+ deltas = [payload["delta"] for event_type, payload in decoded if event_type == "content_block_delta"]+ assert deltas == [{"type": "thinking_delta", "thinking": "let me think"}]+++ def test_anthropic_messages_response_as_sse_events_multiple_blocks_are_indexed():+ response = {+ "id": "msg_3",+ "content": [{"type": "text", "text": "a"}, {"type": "text", "text": "b"}],+ }+ decoded = _decode_sse_events(anthropic_messages_response_as_sse_events(response))+ starts = [payload for event_type, payload in decoded if event_type == "content_block_start"]+ assert [s["index"] for s in starts] == [0, 1]+ deltas = [payload for event_type, payload in decoded if event_type == "content_block_delta"]+ assert [d["delta"]["text"] for d in deltas] == ["a", "b"]+++ def test_anthropic_messages_streaming_response_reports_withheld_output_of_its_stream():+ class _HoldingBack:+ has_buffered_provider_output = True++ def __aiter__(self):+ return self++ async def __anext__(self) -> bytes:+ raise StopAsyncIteration++ async def _bare_stream():+ yield b""++ hidden_params: AnthropicMessagesStreamHiddenParams = {"additional_headers": {}}+ assert (+ AnthropicMessagesStreamingResponse(completion_stream=_HoldingBack(), hidden_params=hidden_params)+ .has_buffered_provider_output+ is True+ )+ assert (+ AnthropicMessagesStreamingResponse(completion_stream=_bare_stream(), hidden_params=hidden_params)+ .has_buffered_provider_output+ is False+ )+++ def test_anthropic_messages_response_as_sse_events_no_content_blocks():+ response = {"id": "msg_4", "content": [], "stop_reason": "end_turn"}+ decoded = _decode_sse_events(anthropic_messages_response_as_sse_events(response))+ assert [event_type for event_type, _ in decoded] == ["message_start", "message_delta", "message_stop"]+++ class _RecordingLoggingWorker:+ def __init__(self):+ self.enqueued = []++ def ensure_initialized_and_enqueue(self, async_coroutine):+ self.enqueued.append(async_coroutine)++ def close_enqueued(self):+ for coroutine in self.enqueued:+ coroutine.close()+++ async def _noop_deferred_dispatch(logging_coroutine):+ logging_coroutine.close()+++ async def _stream_of(events):+ for event in events:+ yield event+++ COMPLETE_STREAM_EVENTS = TRUNCATED_TOOL_USE_EVENTS + ({"type": "message_stop"},)+++ @pytest.mark.asyncio+ async def test_normal_end_with_deferred_dispatch_armed_parks_logging_coroutine(monkeypatch):+ """+ Regression test for LIT-6409: with post_call guardrails active the proxy+ arms logging_obj._on_deferred_stream_complete, and the native /v1/messages+ iterator must park its logging coroutine instead of enqueueing it at+ upstream exhaustion, otherwise the spend log is built before the+ guardrail end-of-stream scan writes its post_call entry.+ """+ worker = _RecordingLoggingWorker()+ monkeypatch.setattr(streaming_iterator_module, "GLOBAL_LOGGING_WORKER", worker)+ iterator = _make_iterator("test_deferred_parks_logging_coroutine")+ iterator.litellm_logging_obj._on_deferred_stream_complete = _noop_deferred_dispatch++ await _collect(iterator, _stream_of(COMPLETE_STREAM_EVENTS))++ parked = getattr(iterator.litellm_logging_obj, "_deferred_stream_complete_args", None)+ assert worker.enqueued == []+ assert parked is not None+ assert len(parked) == 1+ assert asyncio.iscoroutine(parked[0])+ parked[0].close()+++ @pytest.mark.asyncio+ async def test_client_disconnect_enqueues_immediately_even_when_deferred_dispatch_armed(monkeypatch):+ """- On client disconnect the guardrail end-of-stream scan never runs, so- deferral would strand the spend log; the teardown path must keep- enqueueing immediately (LIT-5839) even when the deferred callback is armed.++ Regression: on client disconnect the guardrail end-of-stream scan never++ runs, so deferral would strand the spend log. The detached pump's++ post-disconnect bill must bypass the deferred-dispatch park and enqueue++ immediately (LIT-5839) even when the deferred callback is armed (LIT-6409).+ """+ worker = _RecordingLoggingWorker()+ monkeypatch.setattr(streaming_iterator_module, "GLOBAL_LOGGING_WORKER", worker)+ iterator = _make_iterator("test_disconnect_enqueues_when_armed")+ iterator.litellm_logging_obj._on_deferred_stream_complete = _noop_deferred_dispatch+- wrapped = iterator.async_sse_wrapper(_events_then_hang(TRUNCATED_TOOL_USE_EVENTS))++ tail_gated = asyncio.Event()++++ async def _gated_stream():++ for event in TRUNCATED_TOOL_USE_EVENTS:++ yield event++ await tail_gated.wait()++ yield {"type": "message_stop"}++++ wrapped = iterator.async_sse_wrapper(_gated_stream())+ for _ in range(len(TRUNCATED_TOOL_USE_EVENTS)):+ await wrapped.__anext__()+ await wrapped.aclose()+++ tail_gated.set()++ for _ in range(100):++ if worker.enqueued:++ break++ await asyncio.sleep(0.01)+++ assert len(worker.enqueued) == 1+ assert getattr(iterator.litellm_logging_obj, "_deferred_stream_complete_args", None) is None+ worker.close_enqueued()+++ @pytest.mark.asyncio+ async def test_normal_end_without_deferred_dispatch_enqueues_immediately(monkeypatch):+ worker = _RecordingLoggingWorker()+ monkeypatch.setattr(streaming_iterator_module, "GLOBAL_LOGGING_WORKER", worker)+ iterator = _make_iterator("test_unarmed_enqueues_at_stream_end")++ await _collect(iterator, _stream_of(COMPLETE_STREAM_EVENTS))++ assert len(worker.enqueued) == 1+ assert getattr(iterator.litellm_logging_obj, "_deferred_stream_complete_args", None) is None+ worker.close_enqueued()diff --cc type-discipline-budget.jsonindex c6b5a696cc1,7365cec4fdd..1f2651f5f25--- a/type-discipline-budget.json+++ b/type-discipline-budget.json@@@ -27,9 -27,12 +27,12 @@@"limit": 0},"LIT010": {- "limit": 16564+ "limit": 16730},"LIT011": {- "limit": 5596+ "limit": 5577+ },+ "LIT012": {+ "limit": 4506}}