Repository navigation
fix(anthropic): backport skipping a stream data line that is not a JSON object to lts/1.108.x - #53403
Conversation
An Anthropic-format upstream that sends a data line holding a JSON number, string, array or null (data: 5) failed /v1/chat/completions and /v1/responses with "'int' object has no attribute 'get'", and the agentic /v1/messages iterator sent an error event after message_stop. The shared stream parser now skips such a line the way SSE clients ignore an event they do not understand This line has no BerriAI#49088, so the /v1/messages pass-through log assembler also gets that PR's skip of a data line that does not start with "{" in its text fast path, and the chat handler test gets the _streamed_text helper main already has (cherry picked from commit ebe3712)
… line that is not a JSON object A tool use stream with such a line still assembles its text and tool call. On this line the test fails before the fix, since the log assembler had no non-object skip of its own and the chunk parser raised on the line (cherry picked from commit f7e6718)
[High impact] The PR appears safe to merge, with no new actionable issues found
|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
…hat, the /v1/messages log assembler and error-event lookup, and reset the agentic event name per data line
|
bugbot run |
…e on every Anthropic stream reader Port of the main change. A shared loads_json_object helper returns None for a data payload that is not a decodable JSON object, including one nested past the recursion limit or holding a number past the 4300-digit limit. Chat, the agentic and native /v1/messages iterators, the pass-through log handler scans, stream assembly, the guardrail SSE readers and BaseModelResponseIterator (Snowflake Claude streams and Vertex streamRawPredict logging) now skip such a line instead of failing the stream or dropping the spend row
…not decode A JSON object line nested too deep, or holding a number over Python's digit limit, was skipped by the guardrail readers while a JavaScript client can still parse it and show its text. The unified guardrail now refuses such a stream before it runs, and the /v1/messages assembler returns nothing for it, so Bedrock, tool permission and Model Armor refuse it too. Presidio has no unreadable-event check on this line, so it gets its own refusal for such a stream instead of skipping the mask. Spend logging still skips the line
… every scan mode The streaming scan key is now None when a data line holds an object the guardrail cannot decode, or when one SSE event carries more than one data line, so the scheduler can no longer skip that round as redundant and the refusal always runs Presidio now holds the first frame until it sees a JSON object frame, so a leading non-object line no longer makes it treat the stream as non-Anthropic and forward it unmasked, and it refuses a first frame no reader can take. The skipped-event warning no longer logs the line's content The guardrail stream readers in the harness usage parser, the LLM Shield restorer, the blocked-usage helper and Presidio unmasking now skip a line that is nested too deep or holds a number too large to decode instead of raising, and PANW Prisma AIRS refuses such a text event instead of forwarding it unscanned
|
bugbot run |
…earray stream chunks
…cut the unreadable line check's cost The chat stream's JSON accumulator now skips a line that is nested too deep or holds a number too long to decode instead of failing the stream, also after a frame split across two data lines The check for an undecodable object line now skips json.loads when a payload has too few brackets to hit the recursion limit and no digit run long enough to hit the int digit limit, which cuts its cost per scan round
|
bugbot run |
…idio's first-frame wait
…the offset rebind
|
bugbot run |
…rt_skip_non_object_stream_lines_lts_1_108_x # Conflicts: # tests/unit/proxy/pass_through_endpoints/llm_provider_handlers/test_vertex_passthrough_logging_handler.py
…rt_skip_non_object_stream_lines_lts_1_108_x # Conflicts: # litellm/llms/anthropic/chat/guardrail_translation/handler.py # tests/unit/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py
…rt_skip_non_object_stream_lines_lts_1_108_x # Conflicts: # litellm/llms/anthropic/chat/guardrail_translation/handler.py
…yte once instead of timing it The test guide bans checks that depend on execution speed, so the CPU-time limit on the many-leading-reads test is replaced by a test that each read is handed only the frames it completed, including frame ends split across reads (cherry picked from commit e491e14)
|
bugbot run |
…ead classification test The test copied the wait's loop, so it still passed if the wait itself dropped the offset the classifier returns. The wait now takes the classifier as a parameter, defaulting to the one it called before, and the test runs the real wait with a recording classifier. The classifier docstring now says the caller relays the preface (cherry picked from commit f462679)
|
bugbot run |
…ding reads and a frame split into many reads Unit tests can't check the wait's cost without timing it, so CodSpeed now times the real wait over 6000 leading non-object reads and over one 48 KB frame in 16-byte reads. Rescanning every classified frame for a JSON object, or searching the whole unclassified tail for a frame end, makes these runs many times slower (cherry picked from commit 0203a49)
|
bugbot run |
(cherry picked from commit 67faf6d)
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 52d0ae8. Configure here.
Handwritten 1-3 sentence description
On 1.108.x, when an Anthropic-format upstream sent a stream line that was valid JSON but not an object, or a line too deep or too long for Python to decode, streaming chat completions and responses requests failed, and messages requests could end in an error or log no spend or reply. This port of #53393 makes each stream reader that failed on that line skip it, so the reply streams through and is logged and billed. A guarded messages stream is refused instead when the guardrail cannot read a text event, since a client could still show that text unchecked
Details
TLDR
Problem this solves:
data: 5stream line fails streamed chat and responses, and the agentic callback skips its work on it/v1/messagesin an error/v1/messagescall with such a line gets no spend log, one without the reply, or a failure at $0/v1/messagesguardrails, Snowflake Claude, VertexstreamRawPredictlogging and OpenAI-compatible providers such as hosted vLLMHow it solves it:
loads_json_object, returnsNonefor a payload that does not start with{or thatjson.loadscannot finishBaseModelResponseIteratorcall it and skip that line. PANW blocks an object line it cannot decode instead/v1/messageslog assembler gets the same skip, as on main since fix(guardrails)!: keep the upstream error when a /v1/messages stream ends in one #49088/v1/messagesstream through the unified guardrail is refused when it cannot decode an object line or gets an event split over severaldata:lines, in every scan mode, with a 400 before any byte went out, an error event afterUser Flow
No user reported this. It came up in review, so this is hardening, reproduced with a relay that adds such a line
Before: a developer streaming from an Anthropic-format upstream that sends one
data: 5line gets an error on chat, and their/v1/messagescalls are not billed"stream": trueto an Anthropic model{"error":{"message":"Invalid request format: litellm.APIConnectionError: 'int' object has no attribute 'get' ..."}}and no text"stream": trueand get the whole reply[], so that call has no spendAfter: the same requests stream the whole answer, and every call has its spend row
"stream": trueto an Anthropic model"finish_reason":"stop"anddata: [DONE]"stream": trueand get the whole replyanthropic_messagesrow with tokens, spend and the replyDecisions
The decisions are the ones on #53393, read against this line. These are specific to the port
/v1/messageslog assembler gets fix(guardrails)!: keep the upstream error when a /v1/messages stream ends in one #49088's skip of a data line that does not start with{, with that PR's test for it. This line does not have fix(guardrails)!: keep the upstream error when a /v1/messages stream ends in one #49088, and without it the assembler kept the line and the call got no spend row. The rest of fix(guardrails)!: keep the upstream error when a /v1/messages stream ends in one #49088 is a guardrail change and stays out of this port, except Presidio's first-frame wait (Decision 5)/v1/messagesstream with an object line the guardrail cannot decode, nested too deep or holding a number over Python's digit limit, is refused before the guardrail runs, as on main. A JavaScript client still parses that line and would show text the guardrail never checked. Presidio on this line has no refusal for JSON it cannot read, so it gets one for this case only. Without it, Presidio would skip masking the whole stream once the assembler returns nothing for itdata: 5or deep array no longer makes it pass the stream through unmasked as an unknown shape. It also refuses a first frame with JSON no reader can take. Main does both already. The wait covers raw pass-through streams too, so a stream of plaindata: helloframes is held until it ends or reaches 64 KB, as on main. Letting plain text decide the shape was the alternative, but then adata: helloline ahead of an Anthropic stream would let a card through unmasked, as a probe showedGuardrailRaisedExceptionanswers with, as on main. A 500, as Model Armor answers when it cannot assemble a stream, or a 502 for a bad upstream would name the cause better, but would make this the only guardrail refusal with its own statusjson.loadsfor a payload with fewer than 100 brackets and no run of 640 digits, as on main, since such a payload cannot hit either limit. At 2000 events the check takes 3.3ms and the scan key 24.1ms, against 17.7ms at the line's tipRelevant issues
Port of #53393 to
lts/1.108.xPre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or moreDelays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
Backport notes: picks, gauntlet-mini, lock bumps
Every #53393 commit but
c019aa2677, a fix to the frame splitter only main has, is picked,ff1688d272and7fff40d36cinto one LTS commit. The first port adds #49088's skip of a data line that does not start with{to the/v1/messageslog assembler, with that PR's test, and gives the chat handler test the_streamed_texthelper main already has. Inea0f1dd9d2the assembler keeps that check and only addsRecursionErrorto its catches, and the guardrail handler's text and stop-reason readers, which use typed dicts on this line, read through the new helper. Presidio's unreadable-JSON check is not on this line, so that part of2db109ead7has nothing to port. In28995d21a4Presidio gets its own refusal for a stream with an object line it cannot decode, since on this line it would otherwise skip masking the whole stream once the assembler returns nothing for it (Decision 4).56a35716fbadds Presidio's first-frame wait from #49088 (Decision 5) and the quieter warning (Decision 6) on top of4617428358.78f873f767picksacb47e6454as is.c0dfdcbfd6picks the cheaper check and the chat joiner fix fromda6bfcdf93, and leaves out its frame splitting, Rust router and Databricks parts, since this line's unified guardrail has no frame splitting and the line has no Rust router or Databricks/v1/messages(Caveats).1faa9404e8is not a pick. It fixes the ported wait, which checked every buffered frame again on each read, so a long run of leadingdata: 5frames cost quadratic CPU. Main has the same wait from #49088, and #54379 is its copy of this fixGauntlet-mini: SURVIVED, 5/5 lenses, 0 confirmed, run 0a72ee01d324, reviewed
0b34522999. The later commits came from the caveats rounds, and the live run below covers themNo lock bumps. Every dependency in the line's lock with a known fix is on the same version on main
Real Anthropic (
claude-haiku-5-5) and OpenAI (gpt-5.4-miniashosted_vllm/) behind relays that add one line to each streamed reply. After ran at56a35716fb2, carried to the tip below the table, and the last two rows atc0dfdcbfd6e. Every raw output is in this gist, the last two rows on their own page1f7098cb9a)message_stopcfguardrail, short or deep array linemessage_stopcfguardrail, object it cannot decodehosted_vllm[DONE]data:lines, then a deep object[DONE]Some Before cells already passed, such as a line after
message_stop. Every After cell passed, and its guardrail refusals are intendedCarry from
56a35716fb2to the tip52d0ae8e091The rows above the last two were tested at
56a35716fb2, and the last two atc0dfdcbfd6. The tip adds three picks and two commits of this line's own.78f873f767makes PANW skip a deep array line and lets the stream reader take abytearraychunk. Neither is on the rig, since PANW has no test account and thebytearraycase has a unit test.c0dfdcbfd6adds a fast path to the unreadable-line check, which gives the same answer for every payload, and lets the chat joiner drop a valuejsoncan never finish, which applies only after a split frame and ran live in the chat row above.55cabcdc22steps over a number too long to convert in that joiner, so the event after it is kept. Live, a 5000-digit line after a split frame no longer drops the next chat or responses event (page), and the mapped tests pass.1faa9404e8makes Presidio's first-frame wait check only the frames each read completes. With 7000 leadingdata: 5frames in front of real Anthropic, the request cost 12.0 s of CPU before it and 2.4 s after, the card masked both times, and the four Presidio rows above match at the tip (page). Its output matched the old wait in 20000 fuzzed streams.de2a2bbb13,dcd5f20c9dand4b53101ad4only change the new test, which now runs the real wait and checks each read is classified once, and give the wait aclassifyparameter defaulting to its old classifier. At the tip the two Presidio test files pass (218 tests), and the test fails if the wait drops the classifier's offset.ccdf67b9aeonly adds a CodSpeed benchmark of the wait, and52d0ae8e09a direct test oflast_sse_frame_end.8b9a8c01cb,4a22afbc98and2720731361mergelts/1.108.xin, keeping both sides of each test or import conflict. Apart from that parameter, the PR's code lines matchde2a2bbb13but for one blank line and the base'sCallableimport, so the proof carriesRig and relays
Each side ran 2 proxies with 2 uvicorn workers. The plain one has Postgres, a
cfcontent filter guardrail and a Presidio guardrail in front of Presidio's own Docker images. The agentic one has the agentic callback, and Claude Code ran against it as a real TUI. The text and tool-use Before cells come from the previous run at the same1f7098cb9a. Before, the agentic callback logged'int' object has no attribute 'get'on the short lines and skipped its work, with no error sent to the client. Before, Presidio sent the test card unmasked when the object line held a 5000-digit number. Claude Code ignores an error event aftermessage_stop, so it showed the answer on both sides. The last two rows of the table ran on a third proxy per side with a custom guardrail that blocks a reply saying five, once in each scan mode this line has: end of stream only, every chunk, buffered, and buffered with release on scandata: 5data: 5,null,[1],"x"message_startmessage_stopdata: 5content_block_startover twodata:lines, then a deep objectHeadline case: chat, and the spend log of a
/v1/messagescall, through thedata: 5relayBefore, at
1f7098cb9a(traceback cut, the full output is in the gist). The spend call is from the previous run at the same commitAfter, at
56a35716fb2Short, huge and deep lines, the
cfguardrail, spend log andhosted_vllm, each output reduced to its errors, stream ends and spend rowsText and tool use with their spend rows, reduced the same way
Objects nested deep or holding a huge number, and lines at either end, reduced the same way
Presidio guardrail asked to mask a test card number, each output reduced to its status, text and errors
Claude Code asked to run a tool through the
data: 5and deep object relaysBefore, at
1f7098cb9a, withclaude-relayand thenclaude-relay-deepobjAfter, at
56a35716fb2, the same two runsType
🐛 Bug Fix
Caveats (if any)
Medium
data: helloframes, until it ends or reaches 64 KBLow
streamRawPredictlogging have unit tests but no live rundata:line, text or notFinal Attestation
Bugbot summary