litellm/tests/unit/llms/databricks/test_databricks_streaming_utils.py
quietjules beb69b2464
fix(openai_like): end an async stream cleanly when the connection drops after the finish (#54565)
* fix(openai_like): end an async stream cleanly when the connection drops after the finish

The async SSE reader wrapped every read error in a bare RuntimeError, so the
stream wrapper's rule that ends a stream cleanly on an httpx ReadError or
RemoteProtocolError after a finish_reason never matched. Catch only ValueError,
as the sync reader does, so transport errors reach that rule unchanged

* test(databricks): name the RuntimeError wrap tests for the ValueError they raise

* fix(streaming): warn when an upstream drop after the finish ends the stream

* fix(logging): classify httpx network errors as provider connection errors

A stream drop before the finish now reaches failure logging as a raw
httpx.ReadError. With the httpx transport its message is empty, so
normalized_error fell to UNCLASSIFIED where main reported an internal
state error. Map httpx NetworkError and RemoteProtocolError to
500_PROVIDER_CONNECTION_ERROR, which the aiohttp transport already gets
from the message.

The after-finish integration test now also asserts that no error event
reaches the client.

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
2026-11-26 07:48:41 +00:00

279 lines
9.9 KiB
Python

"""
Regression test for the databricks streaming chunk parser.
OpenAI-compatible servers (e.g. Vertex AI Model Garden vLLM endpoints) send a final
usage-only chunk with an empty `choices` list when `stream_options.include_usage` is
set. `chunk_parser` previously did `choices[0]` unconditionally, raising
`IndexError` -> `MidStreamFallbackError` and crashing the stream.
"""
import json
from typing import Final
import httpx
import pytest
import respx
import litellm
from litellm.llms.databricks.streaming_utils import ModelResponseIterator
def test_chunk_parser_handles_empty_choices_usage_chunk():
"""A usage-only final chunk (empty choices) must not raise IndexError."""
iterator = ModelResponseIterator(streaming_response=None, sync_stream=True)
usage_only_chunk = {
"id": "chatcmpl-x",
"object": "chat.completion.chunk",
"created": 1,
"model": "m",
"choices": [],
"usage": {"prompt_tokens": 20, "completion_tokens": 8, "total_tokens": 28},
}
result = iterator.chunk_parser(chunk=usage_only_chunk)
assert result["text"] == ""
assert result["is_finished"] is False
assert result["usage"] is not None
assert result["usage"]["prompt_tokens"] == 20
assert result["usage"]["completion_tokens"] == 8
def test_chunk_parser_empty_choices_without_usage():
"""An empty-choices chunk with no usage block returns usage=None, no error."""
iterator = ModelResponseIterator(streaming_response=None, sync_stream=True)
chunk = {
"id": "chatcmpl-x",
"object": "chat.completion.chunk",
"created": 1,
"model": "m",
"choices": [],
}
result = iterator.chunk_parser(chunk=chunk)
assert result["text"] == ""
assert result["usage"] is None
def test_chunk_parser_normal_content_chunk_still_works():
"""A regular content chunk is unaffected by the empty-choices guard."""
iterator = ModelResponseIterator(streaming_response=None, sync_stream=True)
chunk = {
"id": "chatcmpl-x",
"object": "chat.completion.chunk",
"created": 1,
"model": "m",
"choices": [{"index": 0, "delta": {"content": "hi"}, "finish_reason": None}],
}
result = iterator.chunk_parser(chunk=chunk)
assert result["text"] == "hi"
def test_chunk_parser_keeps_cached_tokens_on_usage_only_chunk():
iterator = ModelResponseIterator(streaming_response=None, sync_stream=True)
usage_only_chunk = {
"id": "chatcmpl-x",
"object": "chat.completion.chunk",
"created": 1,
"model": "m",
"choices": [],
"usage": {
"prompt_tokens": 340,
"completion_tokens": 1,
"total_tokens": 341,
"prompt_tokens_details": {"cached_tokens": 320},
},
}
result = iterator.chunk_parser(chunk=usage_only_chunk)
assert result["usage"] is not None
assert result["usage"]["prompt_tokens_details"] is not None
assert result["usage"]["prompt_tokens_details"]["cached_tokens"] == 320
def _sse_event(body: dict[str, object]) -> bytes:
return f"data: {json.dumps(body)}\n\n".encode()
@pytest.mark.respx(assert_all_called=True)
def test_stream_usage_after_finish_chunk_reaches_the_caller(respx_mock: respx.MockRouter) -> None:
chunk_header: Final = {"id": "chatcmpl-x", "object": "chat.completion.chunk", "created": 1, "model": "sabia-3"}
stream_body: Final = b"".join(
(
_sse_event({**chunk_header, "choices": [{"index": 0, "delta": {"role": "assistant", "content": "144"}}]}),
_sse_event({**chunk_header, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}),
_sse_event(
{
**chunk_header,
"choices": [],
"usage": {
"prompt_tokens": 340,
"completion_tokens": 1,
"total_tokens": 341,
"prompt_tokens_details": {"cached_tokens": 320},
},
}
),
b"data: [DONE]\n\n",
)
)
respx_mock.post("http://upstream.test/chat/completions").mock(
return_value=httpx.Response(200, headers={"content-type": "text/event-stream"}, content=stream_body)
)
stream: Final = litellm.completion(
model="maritalk/sabia-3",
api_base="http://upstream.test",
api_key="sk-test",
messages=[{"role": "user", "content": "What is 12*12?"}],
stream=True,
stream_options={"include_usage": True},
)
usages: Final = [chunk.usage for chunk in stream if getattr(chunk, "usage", None)]
assert [(usage.prompt_tokens, usage.prompt_tokens_details.cached_tokens) for usage in usages] == [(340, 320)]
def _stream_with_sse_fields(fields: str) -> bytes:
chunk_header: Final = {"id": "chatcmpl-x", "object": "chat.completion.chunk", "created": 1, "model": "m"}
events: Final = (
{**chunk_header, "choices": [{"index": 0, "delta": {"role": "assistant", "content": "ok"}}]},
{**chunk_header, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]},
{**chunk_header, "choices": [], "usage": {"prompt_tokens": 74, "completion_tokens": 52, "total_tokens": 126}},
)
return "".join(f"{fields.format(n=n)}data: {json.dumps(event)}\n\n" for n, event in enumerate(events, 1)).encode()
_STREAM_ARGS: Final = {
"model": "maritalk/sabia-3",
"api_base": "http://upstream.test",
"api_key": "sk-test",
"messages": [{"role": "user", "content": "Reply with the single word: ok"}],
"stream": True,
"stream_options": {"include_usage": True},
}
_ID_EVENT_RETRY_AND_COMMENT: Final = "id: {n}\nevent: message\nretry: 3000\n: keep-alive\n"
@pytest.mark.respx(assert_all_called=True)
@pytest.mark.parametrize(
"fields",
[_ID_EVENT_RETRY_AND_COMMENT, "x-trace: {n}\n", "id\n"],
ids=["id-event-retry-comment", "unknown-field", "bare-field-name"],
)
def test_stream_usage_survives_sse_non_data_fields(respx_mock: respx.MockRouter, fields: str) -> None:
respx_mock.post("http://upstream.test/chat/completions").mock(
return_value=httpx.Response(
200, headers={"content-type": "text/event-stream"}, content=_stream_with_sse_fields(fields)
)
)
stream: Final = litellm.completion(**_STREAM_ARGS)
usages: Final = [chunk.usage for chunk in stream if getattr(chunk, "usage", None)]
assert [(usage.prompt_tokens, usage.completion_tokens) for usage in usages] == [(74, 52)]
@pytest.mark.asyncio
async def test_async_stream_skips_sse_non_data_fields_and_keeps_the_usage_chunk():
async def lines():
for line in _stream_with_sse_fields(_ID_EVENT_RETRY_AND_COMMENT).decode().split("\n"):
yield line
chunks: Final = [chunk async for chunk in ModelResponseIterator(streaming_response=lines(), sync_stream=False)]
parsed: Final = [
(chunk["text"], chunk["finish_reason"], (chunk["usage"] or {}).get("prompt_tokens")) for chunk in chunks
]
assert parsed == [("ok", "", None), ("", "stop", None), ("", "", 74)]
def test_chunk_parser_keeps_usage_on_the_finish_chunk():
iterator: Final = ModelResponseIterator(streaming_response=None, sync_stream=True)
result: Final = iterator.chunk_parser(
chunk={
"id": "chatcmpl-x",
"object": "chat.completion.chunk",
"created": 1,
"model": "m",
"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 340, "completion_tokens": 1, "total_tokens": 341},
}
)
assert result["is_finished"] is True
assert result["usage"] is not None
assert result["usage"]["prompt_tokens"] == 340
_SSE_LINES_WITH_BLANK_SEPARATORS: Final = (
'data: {"id":"c","object":"chat.completion.chunk","created":1,"model":"m",'
'"choices":[{"index":0,"delta":{"content":"144"},"finish_reason":null}]}',
"",
'data: {"id":"c","object":"chat.completion.chunk","created":1,"model":"m",'
'"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}',
"",
"data: {not json",
"",
'data: {"id":"c","object":"chat.completion.chunk","created":1,"model":"m","choices":[],'
'"usage":{"prompt_tokens":340,"completion_tokens":1,"total_tokens":341}}',
"",
"data: [DONE]",
"",
)
@pytest.mark.asyncio
async def test_async_stream_skips_blank_sse_lines_and_keeps_the_usage_chunk():
async def lines():
for line in _SSE_LINES_WITH_BLANK_SEPARATORS:
yield line
chunks: Final = [chunk async for chunk in ModelResponseIterator(streaming_response=lines(), sync_stream=False)]
assert [(chunk["text"], chunk["finish_reason"], (chunk["usage"] or {}).get("prompt_tokens")) for chunk in chunks] == [
("144", "", None),
("", "stop", None),
("", "", None),
("", "", 340),
]
class _UnreadableChunk(ValueError):
pass
def test_sync_stream_value_error_surfaces_as_runtime_error():
def lines():
yield _SSE_LINES_WITH_BLANK_SEPARATORS[0]
raise _UnreadableChunk("unreadable chunk")
with pytest.raises(RuntimeError, match="unreadable chunk"):
list(ModelResponseIterator(streaming_response=lines(), sync_stream=True))
@pytest.mark.asyncio
async def test_async_stream_value_error_surfaces_as_runtime_error():
async def lines():
yield _SSE_LINES_WITH_BLANK_SEPARATORS[0]
raise _UnreadableChunk("unreadable chunk")
with pytest.raises(RuntimeError, match="unreadable chunk"):
[chunk async for chunk in ModelResponseIterator(streaming_response=lines(), sync_stream=False)]
@pytest.mark.asyncio
async def test_async_stream_without_done_marker_ends_after_the_last_chunk():
async def lines():
for line in _SSE_LINES_WITH_BLANK_SEPARATORS[:4]:
yield line
chunks: Final = [chunk async for chunk in ModelResponseIterator(streaming_response=lines(), sync_stream=False)]
assert [(chunk["text"], chunk["finish_reason"]) for chunk in chunks] == [("144", ""), ("", "stop")]