Skip to content

fix(anthropic): skip a stream data line that is not a JSON object - #53393

Merged
mateo-berri merged 14 commits into
BerriAI:mainfrom
owen-hj:litellm_skip_non_object_anthropic_stream_lines
Nov 22, 2026
Merged

mateo-berri merged 14 commits into
BerriAI:mainfrom
owen-hj:litellm_skip_non_object_anthropic_stream_lines

Conversation

@owen-hj

@owen-hj owen-hj commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • A data: 5 stream line fails streamed chat and responses, and the agentic /v1/messages loop sends an error event after message_stop
  • A line Python's JSON parser cannot finish, such as one nested 20000 deep, fails the same routes and can end /v1/messages with no spend recorded
  • The same lines break /v1/messages guardrails, the Rust router's usage reader, Databricks, Snowflake Claude, Vertex streamRawPredict logging and OpenAI-compatible providers such as hosted vLLM
  • A /v1/messages guardrail lets a text event through unchecked when it cannot decode it or when the event arrives split across two network reads

How it solves it:

  • A new helper, loads_json_object, returns None for a payload that does not start with { or that json.loads cannot finish
  • Every Anthropic stream reader, guardrail readers included, and BaseModelResponseIterator call it and skip that line. PANW blocks an object line it cannot decode instead
  • The unified guardrail reads every /v1/messages stream in whole events, so an event split across network reads is still checked
  • A /v1/messages stream through the unified guardrail is refused when it cannot decode an object line or gets an event split over several data: lines, in every scan mode, with a 400 before any byte went out, an error event after

User 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

  1. They send POST https://litellm-domain/v1/chat/completions with "stream": true to an Anthropic model
  2. The proxy answers {"error":{"message":"... 'int' object has no attribute 'get' ..."}} and no text
  3. The same ask on POST https://litellm-domain/v1/responses ends in response.failed
  4. With an agentic callback loaded, POST https://litellm-domain/v1/messages streams the reply, then sends event: error after message_stop
  5. When the line is nested 20000 deep, POST https://litellm-domain/v1/messages ends in {"type":"error",...,"message":"maximum recursion depth exceeded ..."}, and GET https://litellm-domain/spend/logs shows the call as a failure that cost $0

After: the same requests stream the whole answer and end normally

  1. They send POST https://litellm-domain/v1/chat/completions with "stream": true to an Anthropic model
  2. The stream carries "One, two, three, ... ten.", "finish_reason":"stop" and data: [DONE]
  3. The same ask on POST https://litellm-domain/v1/responses ends in response.completed with the text
  4. With an agentic callback loaded, POST https://litellm-domain/v1/messages ends at message_stop with no error event
  5. With the nested line, POST https://litellm-domain/v1/messages ends at message_stop, and the spend log shows the call as a success with its cost
Decisions
  1. One helper in core_helpers.py that every reader calls. The alternative was a check per reader, which is how /v1/messages logging got its own copy and the other readers got none
  2. A line the helper cannot read is skipped, never turned into an error. The SSE spec has clients ignore what they do not understand, and /v1/messages already skipped a non-object line
  3. The helper checks for a leading { before json.loads, so a huge number or a deep array is skipped without being parsed. It also catches ValueError and RecursionError, so the same content inside an object is skipped too. Checking the type after parsing still raised on both, and no caller caught them
  4. The chat parser keeps raising JSONDecodeError, 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 means json can never finish it, so the joiner drops what it holds and the stream goes on
  5. BaseModelResponseIterator._string_to_dict_parser uses the helper, so Snowflake Claude, Vertex streamRawPredict logging, 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
  6. A guarded /v1/messages stream 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/messages assembler 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, skips json.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 base
  7. The agentic iterator clears its pending event: name at every data line, skipped or not, so a skipped line's name never labels the next frame
  8. /v1/messages logging's own non-object check is removed, since the shared parser now returns nothing for such a line
  9. Chat logs a skipped line at debug level with its first 100 characters, and the guardrail readers keep their warning
  10. QA ran locally because the injecting relays have to sit next to the proxies. Snowflake, Vertex, PANW and LLM Shield were not run live. Both Snowflake QA accounts get 403 from Cortex, the Vertex pass-through has no base URL setting to put a relay in front of, and there is no PANW or LLM Shield account to test against. Unit tests cover all four
  11. The guardrail's scan key is None for 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 unchecked
  12. An event with more than one data: 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 closed
  13. The refusal keeps the 400 that every GuardrailRaisedException answers 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
  14. PANW raises in its text extractor for any object line it cannot decode, and its streaming hook already turns that into a blocked error event. Skipping the line would forward its text unscanned. A non-object line, such as a deep array, carries no text and is skipped
  15. The unified guardrail reads every /v1/messages stream in whole SSE events, where before only hold_tool_calls did. 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 round
  16. The Rust router's usage reader also catches RecursionError, and Databricks /v1/messages reads its metrics line with loads_json_object and relays a line it cannot decode as sent, so neither fails the stream

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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 more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays 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-mini as hosted_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 page

Case Before (f3179ed) After (da6bfcd)
Chat and responses, streamed Error Full text
Chat and responses, tool call Error The call
Messages, agentic callback Error event message_stop
Messages, Claude Code tool call Answer, proxy logs errors Answer, no errors
Messages, no callback Error on deep lines message_stop
Messages, cf guardrail, deep array line Error message_stop
Messages, cf guardrail, object it cannot decode Unchecked, or a 500 400 from the guardrail
Messages, Presidio, deep array line 500 Card masked
Messages, Presidio, object it cannot decode Card unmasked, or a 500 400 from Presidio
Messages, spend log Failure at $0, or no row Success with cost
Chat, hosted_vllm Error Full text, [DONE]
Messages, guardrail checking as it streams, text cut across reads Text unchecked Blocked, no text
Messages, deep object late in the stream, 5 scan modes Whole reply, unchecked Refused in all 5
Chat, frame over two data: lines, then a deep object Cut off mid-reply Full text, [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 pages

Rig and relays

Each side ran 2 proxies with 2 uvicorn workers. The plain one has Postgres, a cf content 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 background

Added line Where Port
data: 5 After the first frame 28337
data: 5, null, [1], "x" After the first frame 30146
5000-digit number After the first frame 20973
Array nested 20000 deep After the first frame 24641
Object nested 20000 deep After the first frame 25984
Object with a 5000-digit number After the first frame 26346
Array nested 20000 deep Before message_start 20639
Array nested 20000 deep After message_stop 28315
OpenAI, data: 5 After the first frame 25386
OpenAI, array nested 20000 deep After the first frame 31730
Each text delta cut in two reads 0.3s apart Every text delta 30477
Object nested 20000 deep After the sixth frame 21111
content_block_start over two data: lines, then a deep object After the fourth frame 20494
Headline case: chat through the data: 5 relay

Before, at f3179ed (traceback cut, the full output is in the gist)

$ curl -sN localhost:30507/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"claude-relay","stream":true,"stream_options":{"include_usage":true},"max_tokens":60,"messages":[{"role":"user","content":"Count from 1 to 10 in words."}]}'
{"error":{"message":"Invalid request format: litellm.APIConnectionError: 'int' object has no attribute 'get'\nTraceback (most recent call last): ...

After, at da6bfcd

$ curl -sN localhost:26534/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"claude-relay","stream":true,"stream_options":{"include_usage":true},"max_tokens":60,"messages":[{"role":"user","content":"Count from 1 to 10 in words."}]}'
data: {"id":"chatcmpl-e2bf4869-6864-41f8-a479-2a15a31dc96b","created":1795382352,"model":"claude-relay","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"One, two, three, four,","role":"assistant"}}]}

data: {"id":"chatcmpl-e2bf4869-6864-41f8-a479-2a15a31dc96b","created":1795382352,"model":"claude-relay","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":" five, six, seven, e"}}]}

data: {"id":"chatcmpl-e2bf4869-6864-41f8-a479-2a15a31dc96b","created":1795382352,"model":"claude-relay","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"ight, nine, ten."}}]}

data: {"id":"chatcmpl-e2bf4869-6864-41f8-a479-2a15a31dc96b","created":1795382352,"model":"claude-relay","object":"chat.completion.chunk","choices":[{"finish_reason":"stop","index":0,"delta":{}}]}

data: {"id":"chatcmpl-e2bf4869-6864-41f8-a479-2a15a31dc96b","created":1795382352,"model":"claude-relay","object":"chat.completion.chunk","choices":[],"usage":{"completion_tokens":26,"prompt_tokens":21,"total_tokens":47,"completion_tokens_details":{"reasoning_tokens":0,"text_tokens":26},"prompt_tokens_details":{"cached_tokens":0,"text_tokens":21,"cache_write_tokens":0,"cache_creation_tokens":0,"cache_creation_token_details":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0}},"cost":0.0000151,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"inference_geo":"global","speed":"standard"}}

data: [DONE]
Deep and huge lines, guardrail and spend log, each output reduced to its errors and stream ends
$ setopt extended_glob; P="'int' object has no attribute 'get'|Exceeds the limit \(4300 digits\)|maximum recursion depth exceeded|could not read an event in the upstream stream|\"type\": ?\"error\"|response\.(completed|failed)|\"finish_reason\":\"stop\"|message_stop|\"spend\":[0-9.e-]+|\"status\":\"(success|failure)\"|\[DONE\]"
$ for f in r2-before-f3179ed/^headers-*.txt; do printf '%s: ' ${f:t:r}; sed 1d $f | grep -oE "$P" | sort -u | paste -sd, -; done
chat-claude-relay-deep-end: "finish_reason":"stop",[DONE]
chat-claude-relay-deep-first: maximum recursion depth exceeded
chat-claude-relay-deepobj: maximum recursion depth exceeded
chat-claude-relay-hugeobj: Exceeds the limit (4300 digits)
messages-agentic-claude-relay-deep-end: "type":"error",maximum recursion depth exceeded
messages-agentic-claude-relay-deep-first: "type":"error",maximum recursion depth exceeded
messages-agentic-claude-relay-deepobj: "type": "error",maximum recursion depth exceeded,message_stop
messages-agentic-claude-relay-hugeobj: message_stop
messages-cf-claude-relay-deep-end: "type":"error",maximum recursion depth exceeded
messages-cf-claude-relay-deep-first: "type":"error",maximum recursion depth exceeded
messages-cf-claude-relay-deepobj: message_stop
messages-cf-claude-relay-hugeobj: "type":"error",Exceeds the limit (4300 digits)
messages-claude-relay-deep-end: "type":"error",maximum recursion depth exceeded
messages-claude-relay-deep-first: "type":"error",maximum recursion depth exceeded
messages-claude-relay-deepobj: message_stop
messages-claude-relay-hugeobj: message_stop
responses-claude-relay-deep-end: response.completed
responses-claude-relay-deep-first: maximum recursion depth exceeded,response.failed
responses-claude-relay-deepobj: maximum recursion depth exceeded,response.failed
responses-claude-relay-hugeobj: Exceeds the limit (4300 digits),response.failed
spend-messages-cf-claude-relay-deep-end: "spend":0.0,"status":"failure"
spend-messages-cf-claude-relay-deep-first: "spend":0.0,"status":"failure"
spend-messages-cf-claude-relay-deepobj: 
spend-messages-cf-claude-relay-hugeobj: "spend":0.0,"spend":0.0000151,"status":"failure","status":"success"
spend-messages-claude-relay-deep-end: "spend":0.0,"status":"failure"
spend-messages-claude-relay-deep-first: "spend":0.0,"status":"failure"
spend-messages-claude-relay-deepobj: 
spend-messages-claude-relay-hugeobj: "spend":0.0000151,"status":"success"

$ for f in r2-after-da6bfcd/^headers-*.txt; do printf '%s: ' ${f:t:r}; sed 1d $f | grep -oE "$P" | sort -u | paste -sd, -; done
chat-claude-relay-deep-end: "finish_reason":"stop",[DONE]
chat-claude-relay-deep-first: "finish_reason":"stop",[DONE]
chat-claude-relay-deepobj: "finish_reason":"stop",[DONE]
chat-claude-relay-hugeobj: "finish_reason":"stop",[DONE]
messages-agentic-claude-relay-deep-end: message_stop
messages-agentic-claude-relay-deep-first: message_stop
messages-agentic-claude-relay-deepobj: message_stop
messages-agentic-claude-relay-hugeobj: message_stop
messages-cf-claude-relay-deep-end: message_stop
messages-cf-claude-relay-deep-first: message_stop
messages-cf-claude-relay-deepobj: "type":"error",could not read an event in the upstream stream
messages-cf-claude-relay-hugeobj: "type":"error",could not read an event in the upstream stream
messages-claude-relay-deep-end: message_stop
messages-claude-relay-deep-first: message_stop
messages-claude-relay-deepobj: message_stop
messages-claude-relay-hugeobj: message_stop
responses-claude-relay-deep-end: response.completed
responses-claude-relay-deep-first: response.completed
responses-claude-relay-deepobj: response.completed
responses-claude-relay-hugeobj: response.completed
spend-messages-cf-claude-relay-deep-end: "spend":0.0000151,"status":"success"
spend-messages-cf-claude-relay-deep-first: "spend":0.0000151,"status":"success"
spend-messages-cf-claude-relay-deepobj: "spend":0.0,"spend":0.0000151,"status":"failure","status":"success"
spend-messages-cf-claude-relay-hugeobj: "spend":0.0,"spend":0.0000151,"status":"failure","status":"success"
spend-messages-claude-relay-deep-end: "spend":0.0000151,"status":"success"
spend-messages-claude-relay-deep-first: "spend":0.0000151,"status":"success"
spend-messages-claude-relay-deepobj: "spend":0.0000151,"status":"success"
spend-messages-claude-relay-hugeobj: "spend":0.0000151,"status":"success"
Short lines, tool calls and hosted_vllm, each output reduced the same way
$ setopt extended_glob; P="'int' object has no attribute 'get'|Exceeds the limit \(4300 digits\)|maximum recursion depth exceeded|could not read an event in the upstream stream|\"type\": ?\"error\"|response\.(completed|failed)|\"finish_reason\":\"(stop|tool_calls)\"|\"name\":\"get_weather\"|message_stop|\"spend\":[0-9.e-]+|\"status\":\"(success|failure)\"|\[DONE\]"
$ for f in r1-before-f3179ed/^headers-*.txt; do printf '%s: ' ${f:t:r}; sed 1d $f | grep -oE "$P" | sort -u | paste -sd, -; done
chat-claude-relay-deep: maximum recursion depth exceeded
chat-claude-relay-huge: Exceeds the limit (4300 digits)
chat-claude-relay-mixed: 'int' object has no attribute 'get'
chat-claude-relay: 'int' object has no attribute 'get'
messages-agentic-claude-relay-deep: "type":"error",maximum recursion depth exceeded
messages-agentic-claude-relay-huge: message_stop
messages-agentic-claude-relay-mixed: "type": "error",'int' object has no attribute 'get',message_stop
messages-agentic-claude-relay: "type": "error",'int' object has no attribute 'get',message_stop
messages-cf-claude-relay-deep: "type":"error",maximum recursion depth exceeded
messages-cf-claude-relay-huge: "type":"error",Exceeds the limit (4300 digits)
messages-cf-claude-relay-mixed: message_stop
messages-cf-claude-relay: message_stop
messages-claude-relay-deep: "type":"error",maximum recursion depth exceeded
messages-claude-relay-huge: message_stop
messages-claude-relay-mixed: message_stop
messages-claude-relay: message_stop
responses-claude-relay-deep: maximum recursion depth exceeded,response.failed
responses-claude-relay-huge: Exceeds the limit (4300 digits),response.failed
responses-claude-relay-mixed: 'int' object has no attribute 'get',response.failed
responses-claude-relay: 'int' object has no attribute 'get',response.failed
spend-messages-cf-claude-relay-deep: "spend":0.0,"status":"failure"
spend-messages-cf-claude-relay-huge: "spend":0.0,"spend":0.0000151,"status":"failure","status":"success"
spend-messages-cf-claude-relay-mixed: "spend":0.0000151,"status":"success"
spend-messages-cf-claude-relay: "spend":0.0000151,"status":"success"
spend-messages-claude-relay-deep: "spend":0.0,"status":"failure"
spend-messages-claude-relay-huge: "spend":0.0000151,"status":"success"
spend-messages-claude-relay-mixed: "spend":0.0000151,"status":"success"
spend-messages-claude-relay: "spend":0.0000151,"status":"success"

$ for f in r1-after-da6bfcd/^headers-*.txt; do printf '%s: ' ${f:t:r}; sed 1d $f | grep -oE "$P" | sort -u | paste -sd, -; done
chat-claude-relay-deep: "finish_reason":"stop",[DONE]
chat-claude-relay-huge: "finish_reason":"stop",[DONE]
chat-claude-relay-mixed: "finish_reason":"stop",[DONE]
chat-claude-relay: "finish_reason":"stop",[DONE]
messages-agentic-claude-relay-deep: message_stop
messages-agentic-claude-relay-huge: message_stop
messages-agentic-claude-relay-mixed: message_stop
messages-agentic-claude-relay: message_stop
messages-cf-claude-relay-deep: message_stop
messages-cf-claude-relay-huge: message_stop
messages-cf-claude-relay-mixed: message_stop
messages-cf-claude-relay: message_stop
messages-claude-relay-deep: message_stop
messages-claude-relay-huge: message_stop
messages-claude-relay-mixed: message_stop
messages-claude-relay: message_stop
responses-claude-relay-deep: response.completed
responses-claude-relay-huge: response.completed
responses-claude-relay-mixed: response.completed
responses-claude-relay: response.completed
spend-messages-cf-claude-relay-deep: "spend":0.0000151,"status":"success"
spend-messages-cf-claude-relay-huge: "spend":0.0000151,"status":"success"
spend-messages-cf-claude-relay-mixed: "spend":0.0000151,"status":"success"
spend-messages-cf-claude-relay: "spend":0.0000151,"status":"success"
spend-messages-claude-relay-deep: "spend":0.0000151,"status":"success"
spend-messages-claude-relay-huge: "spend":0.0000151,"status":"success"
spend-messages-claude-relay-mixed: "spend":0.0000151,"status":"success"
spend-messages-claude-relay: "spend":0.0000151,"status":"success"

$ for f in tools-before-f3179ed/^headers-*.txt; do printf '%s: ' ${f:t:r}; sed 1d $f | grep -oE "$P" | sort -u | paste -sd, -; done
chat-tool-claude-relay-deep: maximum recursion depth exceeded
chat-tool-claude-relay-huge: Exceeds the limit (4300 digits)
chat-tool-claude-relay-mixed: 'int' object has no attribute 'get'
chat-tool-claude-relay: 'int' object has no attribute 'get'
responses-tool-claude-relay-deep: maximum recursion depth exceeded,response.failed
responses-tool-claude-relay-huge: Exceeds the limit (4300 digits),response.failed
responses-tool-claude-relay-mixed: 'int' object has no attribute 'get',response.failed
responses-tool-claude-relay: 'int' object has no attribute 'get',response.failed

$ for f in tools-after-da6bfcd/^headers-*.txt; do printf '%s: ' ${f:t:r}; sed 1d $f | grep -oE "$P" | sort -u | paste -sd, -; done
chat-tool-claude-relay-deep: "finish_reason":"tool_calls","name":"get_weather",[DONE]
chat-tool-claude-relay-huge: "finish_reason":"tool_calls","name":"get_weather",[DONE]
chat-tool-claude-relay-mixed: "finish_reason":"tool_calls","name":"get_weather",[DONE]
chat-tool-claude-relay: "finish_reason":"tool_calls","name":"get_weather",[DONE]
responses-tool-claude-relay-deep: "name":"get_weather",response.completed
responses-tool-claude-relay-huge: "name":"get_weather",response.completed
responses-tool-claude-relay-mixed: "name":"get_weather",response.completed
responses-tool-claude-relay: "name":"get_weather",response.completed

$ for f in extra-before-f3179ed/^headers-*.txt; do printf '%s: ' ${f:t:r}; sed 1d $f | grep -oE "$P" | sort -u | paste -sd, -; done
chat-cf-claude-direct: "finish_reason":"stop",[DONE]
chat-oai-direct-vllm: "finish_reason":"stop",[DONE]
chat-oai-relay-deep: [DONE],maximum recursion depth exceeded
chat-oai-relay: 'int' object has no attribute 'get',[DONE]
messages-cf-claude-direct: message_stop

$ for f in extra-after-da6bfcd/^headers-*.txt; do printf '%s: ' ${f:t:r}; sed 1d $f | grep -oE "$P" | sort -u | paste -sd, -; done
chat-cf-claude-direct: "finish_reason":"stop",[DONE]
chat-oai-direct-vllm: "finish_reason":"stop",[DONE]
chat-oai-relay-deep: "finish_reason":"stop",[DONE]
chat-oai-relay: "finish_reason":"stop",[DONE]
messages-cf-claude-direct: message_stop
Presidio guardrail asked to mask a test card number, each output reduced to its status, text and errors
$ P='message_stop|maximum recursion depth exceeded|could not read the upstream stream'
$ for f in pii-before-f3179ed/messages-*.txt; do printf '%s %s: text=%s ' "$(head -1 pii-before-f3179ed/headers-${f:t} | cut -d' ' -f2)" ${f:t:r} "$(sed 1d $f | grep -oE '"text": ?"[^"]*"' | sed -E 's/"text": ?"//; s/"$//' | tr -d '\n')"; sed 1d $f | grep -oE "$P" | sort -u | paste -sd, -; done
200 messages-pii-claude-direct: text=<CREDIT_CARD> message_stop
500 messages-pii-claude-relay-deep-first: text= maximum recursion depth exceeded
500 messages-pii-claude-relay-deepobj: text= maximum recursion depth exceeded
200 messages-pii-claude-relay-hugeobj: text=4111 1111 1111 1111 message_stop
$ for f in pii-after-da6bfcd/messages-*.txt; do printf '%s %s: text=%s ' "$(head -1 pii-after-da6bfcd/headers-${f:t} | cut -d' ' -f2)" ${f:t:r} "$(sed 1d $f | grep -oE '"text": ?"[^"]*"' | sed -E 's/"text": ?"//; s/"$//' | tr -d '\n')"; sed 1d $f | grep -oE "$P" | sort -u | paste -sd, -; done
200 messages-pii-claude-direct: text=4111 1111 1111 message_stop
200 messages-pii-claude-relay-deep-first: text=<CREDIT_CARD> message_stop
400 messages-pii-claude-relay-deepobj: text= could not read the upstream stream
400 messages-pii-claude-relay-hugeobj: text= could not read the upstream stream

The After direct leg sends no relay line. Its reply spent most of max_tokens on a thinking block and stopped at max_tokens after 12 digits, which is not a valid card number, so Presidio left it. Three more runs of that leg finished and were masked

$ d=pii-after-da6bfcd-direct-rerun; for f in $d/direct-*.txt; do printf '%s %s: text=%s ' "$(head -1 $d/headers-${f:t} | cut -d' ' -f2)" ${f:t:r} "$(sed 1d $f | grep -oE '"text": ?"[^"]*"' | sed -E 's/"text": ?"//; s/"$//' | tr -d '\n')"; sed 1d $f | grep -oE "$P" | sort -u | paste -sd, -; done
200 direct-1: text=<CREDIT_CARD> message_stop
200 direct-2: text=<CREDIT_CARD> message_stop
200 direct-3: text=<CREDIT_CARD> message_stop
Claude Code asked to run a tool through the data: 5 and deep object relays

Before, at f3179ed, with claude-relay and then claude-relay-deepobj

❯ Use the Bash tool to run cat notes.txt, then reply with exactly what it printed and nothing else.
  Read 1 file
● notes for the qa run
❯ Use the Bash tool to run cat notes.txt, then reply with exactly what it printed and nothing else.
  Read 1 file
● notes for the qa run
$ grep -cE ' - LiteLLM[^:]*:ERROR: ' proxy-log-claude-code-relay.txt proxy-log-claude-code-deepobj.txt
proxy-log-claude-code-relay.txt:3
proxy-log-claude-code-deepobj.txt:15
08:01:21 - LiteLLM Proxy:ERROR: common_request_processing.py:5743 - litellm.proxy.proxy_server.async_data_generator(): Exception occured - 'int' object has no attribute 'get'
08:01:46 - LiteLLM Proxy:ERROR: anthropic_passthrough_logging_handler.py:569 - Unable to build complete streaming response for Anthropic passthrough endpoint, not logging...

After, at da6bfcd, the same two runs

❯ Use the Bash tool to run cat notes.txt, then reply with exactly what it printed and nothing else.
  Read 1 file
● notes for the qa run
❯ Use the Bash tool to run cat notes.txt, then reply with exactly what it printed and nothing else.
  Read 1 file
● notes for the qa run
$ grep -cE ' - LiteLLM[^:]*:ERROR: ' proxy-log-agentic.txt
0
/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_chunk returns None for a line it skips, where it used to raise, and its one caller, the /v1/messages log assembler, already drops a None. BaseModelResponseIterator._string_to_dict_parser returns None for 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_key returns None for a stream with an unreadable or multi-line event, which the unified guardrail already reads as a scan to run. A guarded /v1/messages stream now reaches the client cut at event ends instead of at network reads, with the same bytes

Regression risk: for a /v1/messages stream 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 against

Dependency graph

  • Chat, responses, /v1/messages plain, guarded and agentic, the /v1/messages spend log and Claude Code: verified live, blocks above
  • The unified guardrail's streaming scheduler, which now always runs the scan for such a stream: verified live in all five scan modes with a deep object late in the stream
  • The frame splitter, which now runs on every guarded /v1/messages stream: 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
  • The Rust router's usage reader and Databricks /v1/messages: a test each, failing without the fix
  • The chat joiner after a split frame, which Gemini streams share: verified live on Anthropic, Gemini's stream suite passes, and its tests fail without the fix
  • Bedrock invoke streams, which reuse the Anthropic scan key: their events are rebuilt one data: line each, so the multi-line check never fires on them, and their suite passes
  • OpenAI-compatible providers through BaseModelResponseIterator: verified live with hosted_vllm
  • Snowflake Claude and Vertex streamRawPredict logging: tested, not run live (Decision 10)
  • Other providers built on BaseModelResponseIterator: same method as the live hosted_vllm leg, and their suites pass
  • Presidio masking: verified live in the Presidio block above. Presidio unmasking, the blocked-response usage reader, the harness usage parser, LLM Shield and PANW: a test per reader, each failing at the merge base
  • Bedrock guardrail, Model Armor and tool permission: refuse a stream the /v1/messages assembler returns nothing for, with existing tests for that path
  • Served-output log and OTel span output: record no output for such a stream, unchanged from the merge base and filed for a follow-up
  • Current main: 39 commits ahead of the merge base f3179ed

Not verified: Snowflake and Vertex live (Decision 10), PANW and LLM Shield live

Type

🐛 Bug Fix

Caveats (if any)

Low

  • PANW, LLM Shield, Snowflake Claude and Vertex streamRawPredict logging have unit tests but no live run (Decision 10)
  • OTel spans and the served-output log record no output for a stream with an undecodable object line, as at the merge base. Filed for a follow-up
  • The unified guardrail refuses any event with more than one data: line, text or not (Decision 12)
  • Guarded streams use a little more CPU per scan round (Decision 6)

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR
Bugbot summary

[!NOTE]
Medium Risk
Broad changes to streaming and guardrail parsing paths, including fail-closed refusals when moderated streams contain undecodable events; behavior shifts for edge-case SSE payloads but reduces crash/leak risk.

Overview
Adds shared loads_json_object / is_undecodable_json_object helpers so Anthropic-style SSE readers only accept decodable JSON objects, and skip (or step over) data: lines that are bare numbers/arrays/null or nested/oversized payloads that trigger ValueError / RecursionError.

Wires that parsing through chat, messages, responses, Databricks, passthrough logging, base stream iterators, the JSON fragment joiner, and the Rust usage parser so streams keep flowing instead of erroring or miscounting usage.

Guardrails now treat unreadable object events (including events split across multiple data: lines) as unscannable: Anthropic translation and PANW raise GuardrailRaisedException, scan keys return None, and stream assembly returns None when an undecodable object is present. The unified guardrail always reassembles whole SSE frames before scanning, not only in tool-call hold mode.

Reviewed by Cursor Bugbot for commit f28c333. Bugbot is set up for automated code reviews on this repo. Configure here.

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
@veria-ai

veria-ai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Fixed/addressed: 1 · PR risk: 0/10

Reviews

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@greptile-apps

greptile-apps Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The latest changes appear safe to merge, and the previously reported missed scans are fixed.

Summary

The PR skips unreadable Anthropic stream lines and refuses guarded messages streams that cannot be checked.

  • Chat and responses streams continue past lines that are not readable objects.
  • Message and provider stream readers keep going past lines they cannot use.
  • Guardrails scan complete message events and refuse text they cannot read.

Reviews (7) · Last reviewed commit: "fix(anthropic): step over a number too l..." · Reviewed by Greptile

Comment thread litellm/llms/anthropic/chat/handler.py Resolved
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

Comment thread litellm/llms/anthropic/chat/handler.py Resolved
@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous 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)
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…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
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

… 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
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

…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
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.

@mateo-berri mateo-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@mateo-berri
mateo-berri merged commit fd0ee2c into BerriAI:main Nov 22, 2026
56 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants