Repository navigation
fix(anthropic): skip a stream data line that is not a JSON object - #53393
Merged
mateo-berri merged 14 commits intoNov 22, 2026
Merged
mateo-berri merged 14 commits into
mateo-berri merged 14 commits into
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, so the /v1/messages logging path no longer needs its own copy of that check
… line that is not a JSON object The log assembler no longer has its own non-object check, so this pins that a tool use stream with such a line still assembles its text and tool call
…ct_anthropic_stream_lines # Conflicts: # litellm/llms/anthropic/chat/handler.py
Contributor
Contributor
Contributor
[Medium impact] The latest changes appear safe to merge, and the previously reported missed scans are fixed.
|
…reset the agentic event name per data line
…ooking for a /v1/messages error event
Contributor
Contributor
|
bugbot run |
…e on every Anthropic stream reader Chat, the agentic and native /v1/messages iterators, the /v1/messages log scans, guardrail SSE readers, and BaseModelResponseIterator (Snowflake Claude streams, Vertex streamRawPredict logging) now share one loads_json_object helper that returns None for a payload that is not a JSON object or that json.loads cannot finish (deep nesting, a number past the int digit limit)
Contributor
…ct_anthropic_stream_lines # Conflicts: # litellm/llms/anthropic/chat/guardrail_translation/handler.py
…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 Presidio, Bedrock, tool permission and Model Armor refuse it too. Spend logging still skips the line
Contributor
… 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 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
Contributor
Contributor
|
bugbot run |
…earray stream chunks
…d skip undecodable lines in more readers The unified guardrail now rejoins transport reads into whole SSE frames for every /v1/messages stream, not only when tool calls are held, so a text event split across two reads, or inside a UTF-8 character, is still checked The chat stream's JSON accumulator, the Rust router's /v1/messages usage reader and the Databricks invocation metrics filter now skip a line that is nested too deep or holds a number too long to decode instead of failing the stream 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 halves its cost per scan round
Contributor
…eads do not skip them
…ream joiner so the event after it is kept
Contributor
Contributor
|
bugbot run |
Contributor
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 f28c333. Configure here.
6 of 7 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Handwritten 1-3 sentence description
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 lose their spend log. The proxy now skips that line in each stream reader that failed on it, the way an SSE client ignores an event it does not understand. 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/v1/messagesloop sends an error event aftermessage_stop/v1/messageswith no spend recorded/v1/messagesguardrails, the Rust router's usage reader, Databricks, Snowflake Claude, VertexstreamRawPredictlogging and OpenAI-compatible providers such as hosted vLLM/v1/messagesguardrail lets a text event through unchecked when it cannot decode it or when the event arrives split across two network readsHow 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/messagesstream in whole events, so an event split across network reads is still checked/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 is hardening from review, reproduced with a relay that adds such a line
Before: a developer streaming from an Anthropic-format upstream that sends such a line gets an error
"stream": trueto an Anthropic model{"error":{"message":"... 'int' object has no attribute 'get' ..."}}and no textresponse.failedevent: erroraftermessage_stop{"type":"error",...,"message":"maximum recursion depth exceeded ..."}, and GET https://litellm-domain/spend/logs shows the call as a failure that cost $0After: the same requests stream the whole answer and end normally
"stream": trueto an Anthropic model"finish_reason":"stop"anddata: [DONE]response.completedwith the textmessage_stopwith no error eventmessage_stop, and the spend log shows the call as a success with its costDecisions
core_helpers.pythat every reader calls. The alternative was a check per reader, which is how/v1/messageslogging got its own copy and the other readers got none/v1/messagesalready skipped a non-object line{beforejson.loads, so a huge number or a deep array is skipped without being parsed. It also catchesValueErrorandRecursionError, so the same content inside an object is skipped too. Checking the type after parsing still raised on both, and no caller caught themJSONDecodeError, because that is how it notices a frame split across two lines and starts joining them. While joining, a number too long to convert is stepped over, keeping the value after it, and a value nested too deep meansjsoncan never finish it, so the joiner drops what it holds and the stream goes onBaseModelResponseIterator._string_to_dict_parseruses the helper, so Snowflake Claude, VertexstreamRawPredictlogging, OpenAI-compatible providers and the other provider iterators built on it skip such a line instead of crashing on'int'.get. Every one of their chunk parsers reads a dict, so none of them could use a non-object line before/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. A JavaScript client still parses that line and would show text the guardrail never checked, so skipping it as an unguarded stream does was rejected. Only an upstream that builds such a line can send one. A non-object line, such as a lone huge number or a deep array, carries no text and is still skipped. The/v1/messagesassembler returns nothing for such a stream, so Presidio, Bedrock, tool permission and Model Armor refuse it like any stream they cannot read, while spend logging still skips the line. The check reads the stream joined, since a line this long arrives split across reads. A payload with fewer than 100 brackets and no run of 640 digits, the lowest digit limit Python allows, skipsjson.loads, since it cannot hit either limit. At 2000 events the check takes 3.3ms, about a third of the guardrail's text reader at 9.2ms, and the scan key 24.8ms against 19.5ms at the merge baseevent:name at every data line, skipped or not, so a skipped line's name never labels the next frame/v1/messageslogging's own non-object check is removed, since the shared parser now returns nothing for such a lineNonefor a stream with such an event, so the unified guardrail never skips that scan as redundant and the refusal runs in every streaming mode. Before, a release-on-scan round, or a line after the last end-of-stream scan, passed the text to the client unchecked. Live, a custom guardrail refused a 20000-deep object sent after the first text in all five modes, where the merge base sent the whole reply uncheckeddata:line is refused by the unified guardrail, whatever its type. Presidio, PANW and other guardrails with their own streaming hook do not have this check. The SSE spec joins those lines with a newline, so a client shows the text, while the guardrail read each line alone and saw none. Joining them in the guardrail was the alternative, but no supported upstream sends them, so refusing is smaller and fails closedGuardrailRaisedExceptionanswers with. 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 status/v1/messagesstream in whole SSE events, where before onlyhold_tool_callsdid. A text event cut across two network reads, or a read ending inside a UTF-8 character, was never checked, at the merge base too. Fixing only the text reader was the alternative, but every reader of the scan would need the same fix. Clients get the same bytes, cut at event ends. Sampled scan rounds count whole-event reads, so a read that ends inside an event does not use up a due roundRecursionError, and Databricks/v1/messagesreads its metrics line withloads_json_objectand relays a line it cannot decode as sent, so neither fails the streamPre-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
Real Anthropic (
claude-haiku-5-5) and OpenAI (gpt-5.4-miniashosted_vllm/) behind relays that add a line to each streamed reply. The rig is below the table, and every raw output is in this gist, with the last three rows on their own pagemessage_stopmessage_stopcfguardrail, 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, refusals intended, and again at f28c333, with the two legs added since on the round 5 and round 6 pagesRig 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 last three 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: end of stream only, every chunk, buffered, buffered with release on scan, and backgrounddata: 5data: 5,null,[1],"x"message_startmessage_stopdata: 5content_block_startover twodata:lines, then a deep objectHeadline case: chat through the
data: 5relayBefore, at f3179ed (traceback cut, the full output is in the gist)
After, at da6bfcd
Deep and huge lines, guardrail and spend log, each output reduced to its errors and stream ends
Short lines, tool calls and
hosted_vllm, each output reduced the same wayPresidio guardrail asked to mask a test card number, each output reduced to its status, text and errors
The After direct leg sends no relay line. Its reply spent most of
max_tokenson a thinking block and stopped atmax_tokensafter 12 digits, which is not a valid card number, so Presidio left it. Three more runs of that leg finished and were maskedClaude Code asked to run a tool through the
data: 5and deep object relaysBefore, at f3179ed, with
claude-relayand thenclaude-relay-deepobjAfter, at da6bfcd, the same two runs
/live-pr-risk at da6bfcd
Carried to f28c333. c019aa2 only moves the sampled round counter after the frame split. Live, a guardrail checking every second round, with every second read ending inside an event, stopped after "Four", where da6bfcd sent "Five" to "Ten" unchecked. f28c333 steps over a number too long to convert in the chat joiner, so the event after it is kept. Its callers are Anthropic chat, where a 5000-digit line after a split frame no longer drops the next chat or responses event live, and Gemini streams, whose suite passes. Every leg above ran again at f28c333 with the same results
No breaking change found. Every dependent of the changed parsers and guardrail readers ran live above or has a test that runs through the change, except the ones named under Regression risk
Breaking: none
Backward incompatible:
ModelResponseIterator.convert_str_chunk_to_generic_chunkreturnsNonefor a line it skips, where it used to raise, and its one caller, the/v1/messageslog assembler, already drops aNone.BaseModelResponseIterator._string_to_dict_parserreturnsNonefor JSON that is not an object, where it returned the value, and every chunk parser behind it reads a dict, so none could use the value.AnthropicMessagesHandler.get_streaming_scan_keyreturnsNonefor a stream with an unreadable or multi-line event, which the unified guardrail already reads as a scan to run. A guarded/v1/messagesstream now reaches the client cut at event ends instead of at network reads, with the same bytesRegression risk: for a
/v1/messagesstream with an object line the assembler cannot decode, the served-output log and OTel span output record no output, as at the merge base. PANW and LLM Shield have tests for the new paths but no live leg, since there is no account for either to test againstDependency graph
/v1/messagesplain, guarded and agentic, the/v1/messagesspend log and Claude Code: verified live, blocks above/v1/messagesstream: verified live with text cut across reads, and a test cuts reads at 1, 7, 61 and 200 bytes, multibyte text included. Its sampled round count, fixed at c019aa2: verified live with every second read ending inside an event, and a test fails without the fix/v1/messages: a test each, failing without the fixdata:line each, so the multi-line check never fires on them, and their suite passesBaseModelResponseIterator: verified live withhosted_vllmstreamRawPredictlogging: tested, not run live (Decision 10)BaseModelResponseIterator: same method as the livehosted_vllmleg, and their suites pass/v1/messagesassembler returns nothing for, with existing tests for that pathNot verified: Snowflake and Vertex live (Decision 10), PANW and LLM Shield live
Type
🐛 Bug Fix
Caveats (if any)
Low
streamRawPredictlogging have unit tests but no live run (Decision 10)data:line, text or not (Decision 12)Final Attestation
Bugbot summary