Skip to content

fix(anthropic): backport skipping a stream data line that is not a JSON object to lts/1.108.x - #53403

Merged
mateo-berri merged 19 commits into
BerriAI:lts/1.108.xfrom
edvinsq:litellm_backport_skip_non_object_stream_lines_lts_1_108_x
Nov 25, 2026
Merged

mateo-berri merged 19 commits into
BerriAI:lts/1.108.xfrom
edvinsq:litellm_backport_skip_non_object_stream_lines_lts_1_108_x

Conversation

@edvinsq

@edvinsq edvinsq commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • A data: 5 stream line fails streamed chat and responses, and the agentic callback skips its work on it
  • A line Python's JSON parser cannot finish, nested 20000 deep or holding a number over 4300 digits, fails the same routes and can end /v1/messages in an error
  • A streamed /v1/messages call with such a line gets no spend log, one without the reply, or a failure at $0
  • The same lines break /v1/messages guardrails, Snowflake Claude, Vertex streamRawPredict logging and OpenAI-compatible providers such as hosted vLLM
  • Presidio sends PII unmasked on a stream with an object line it cannot decode

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 /v1/messages log assembler gets the same skip, as on main since fix(guardrails)!: keep the upstream error when a /v1/messages stream ends in one #49088
  • 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 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: 5 line gets an error on chat, and their /v1/messages calls are not billed

  1. They send POST https://litellm-domain/v1/chat/completions with "stream": true to an Anthropic model
  2. The proxy answers {"error":{"message":"Invalid request format: litellm.APIConnectionError: 'int' object has no attribute 'get' ..."}} and no text
  3. They send POST https://litellm-domain/v1/messages with "stream": true and get the whole reply
  4. GET https://litellm-domain/spend/logs?request_id= returns [], so that call has no spend

After: the same requests stream the whole answer, and every call has its spend row

  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. They send POST https://litellm-domain/v1/messages with "stream": true and get the whole reply
  4. GET https://litellm-domain/spend/logs?request_id= returns its anthropic_messages row with tokens, spend and the reply
Decisions

The decisions are the ones on #53393, read against this line. These are specific to the port

  1. The /v1/messages log 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)
  2. An error frame whose data is a JSON string is skipped like any other non-object line. That is the fix, and main does the same
  3. No lock bumps. Every dependency in the line's lock with a known fix is on the same version on main
  4. 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, 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 it
  5. Presidio gets fix(guardrails)!: keep the upstream error when a /v1/messages stream ends in one #49088's wait for the first frame with a JSON object on its data line, so a leading data: 5 or 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 plain data: hello frames is held until it ends or reaches 64 KB, as on main. Letting plain text decide the shape was the alternative, but then a data: hello line ahead of an Anthropic stream would let a card through unmasked, as a probe showed
  6. The guardrail's warning for a skipped event no longer logs the line's first 100 characters, since that line can hold the text the guardrail is there to check, such as a card number. Main logs only the event type there
  7. The refusal keeps the 400 that every GuardrailRaisedException answers 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 status
  8. The unreadable-line check skips json.loads for 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 tip

Relevant issues

Port of #53393 to lts/1.108.x

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

Backport notes: picks, gauntlet-mini, lock bumps

Every #53393 commit but c019aa2677, a fix to the frame splitter only main has, is picked, ff1688d272 and 7fff40d36c into one LTS commit. The first port adds #49088's skip of a data line that does not start with { to the /v1/messages log assembler, with that PR's test, and gives the chat handler test the _streamed_text helper main already has. In ea0f1dd9d2 the assembler keeps that check and only adds RecursionError to 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 of 2db109ead7 has nothing to port. In 28995d21a4 Presidio 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). 56a35716fb adds Presidio's first-frame wait from #49088 (Decision 5) and the quieter warning (Decision 6) on top of 4617428358. 78f873f767 picks acb47e6454 as is. c0dfdcbfd6 picks the cheaper check and the chat joiner fix from da6bfcdf93, 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). 1faa9404e8 is not a pick. It fixes the ported wait, which checked every buffered frame again on each read, so a long run of leading data: 5 frames cost quadratic CPU. Main has the same wait from #49088, and #54379 is its copy of this fix

Gauntlet-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 them

No 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-mini as hosted_vllm/) behind relays that add one line to each streamed reply. After ran at 56a35716fb2, carried to the tip below the table, and the last two rows at c0dfdcbfd6e. Every raw output is in this gist, the last two rows on their own page

Case Before (1f7098cb9a) After
Chat and responses, streamed Error Full text
Messages, text, tool use or agentic callback Error on deep lines message_stop
Messages, Claude Code tool call Answer, proxy logs errors Answer, no errors
Messages, cf guardrail, short or deep array line Error message_stop
Messages, cf guardrail, object it cannot decode Error 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
Spend log, text or tool use No row, no reply, or $0 failure Success with the reply
Chat, hosted_vllm Error Full text, [DONE]
Messages, deep object late in the stream, 4 scan modes Whole reply, then an error Refused in all 4
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, and its guardrail refusals are intended

Carry from 56a35716fb2 to the tip 52d0ae8e091

The rows above the last two were tested at 56a35716fb2, and the last two at c0dfdcbfd6. The tip adds three picks and two commits of this line's own. 78f873f767 makes PANW skip a deep array line and lets the stream reader take a bytearray chunk. Neither is on the rig, since PANW has no test account and the bytearray case has a unit test. c0dfdcbfd6 adds a fast path to the unreadable-line check, which gives the same answer for every payload, and lets the chat joiner drop a value json can never finish, which applies only after a split frame and ran live in the chat row above. 55cabcdc22 steps 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. 1faa9404e8 makes Presidio's first-frame wait check only the frames each read completes. With 7000 leading data: 5 frames 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, dcd5f20c9d and 4b53101ad4 only change the new test, which now runs the real wait and checks each read is classified once, and give the wait a classify parameter 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. ccdf67b9ae only adds a CodSpeed benchmark of the wait, and 52d0ae8e09 a direct test of last_sse_frame_end. 8b9a8c01cb, 4a22afbc98 and 2720731361 merge lts/1.108.x in, keeping both sides of each test or import conflict. Apart from that parameter, the PR's code lines match de2a2bbb13 but for one blank line and the base's Callable import, so the proof carries

$ uv run --no-sync pytest -q tests/unit/proxy/guardrails/guardrail_hooks/test_presidio.py tests/unit/proxy/common_utils
1700 passed, 192 warnings in 364.76s (0:06:04)
$ uv run --no-sync pytest -q tests/unit/llms/anthropic/chat/guardrail_translation tests/unit/proxy/guardrails/guardrail_hooks/test_headroom.py tests/unit/llms/anthropic/chat/test_anthropic_chat_handler.py tests/unit/llms/anthropic/pass_through tests/unit/proxy/guardrails/guardrail_hooks/test_panw_prisma_airs.py tests/unit/litellm_core_utils/test_core_helpers.py tests/unit/litellm_core_utils/test_json_fragment_accumulator.py tests/unit/responses/litellm_completion_transformation/test_anthropic_responses_bridge.py tests/unit/proxy/pass_through_endpoints/llm_provider_handlers tests/unit/proxy/guardrails/guardrail_hooks/test_presidio.py tests/unit/litellm_core_utils/test_tool_fields.py
3820 passed, 60 warnings in 226.52s (0:03:46)
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 text and tool-use Before cells come from the previous run at the same 1f7098cb9a. 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 after message_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 scan

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, and the spend log of a /v1/messages call, through the data: 5 relay

Before, at 1f7098cb9a (traceback cut, the full output is in the gist). The spend call is from the previous run at the same commit

$ curl -sN localhost:25920/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): ...

$ curl -s 'localhost:26737/spend/logs?request_id=382e7db4-9dfc-4b67-93bb-c0d7b4bf311b' -H "Authorization: Bearer $KEY" | jq -c '[.[] | {call_type, spend, prompt_tokens, completion_tokens, status, text: .response.choices[0].message.content, tool_calls: [.response.choices[0].message.tool_calls[]?.function]}]'
[]

After, at 56a35716fb2

$ curl -sN localhost:28496/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-4995ddf3-be95-4fd2-8f1b-79d84dab6eb9","object":"chat.completion.chunk","created":1795364412,"model":"claude-relay","choices":[{"index":0,"delta":{"role":"assistant","content":"One, two, three, four,"}}]}
data: {"id":"chatcmpl-4995ddf3-be95-4fd2-8f1b-79d84dab6eb9","object":"chat.completion.chunk","created":1795364412,"model":"claude-relay","choices":[{"index":0,"delta":{"content":" five, six, seven, e"}}]}
data: {"id":"chatcmpl-4995ddf3-be95-4fd2-8f1b-79d84dab6eb9","object":"chat.completion.chunk","created":1795364412,"model":"claude-relay","choices":[{"index":0,"delta":{"content":"ight, nine, ten."}}]}
data: {"id":"chatcmpl-4995ddf3-be95-4fd2-8f1b-79d84dab6eb9","object":"chat.completion.chunk","created":1795364412,"model":"claude-relay","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: {"id":"chatcmpl-4995ddf3-be95-4fd2-8f1b-79d84dab6eb9","created":1795364412,"model":"claude-relay","object":"chat.completion.chunk","choices":[{"index":0,"delta":{}}],"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]

$ curl -s 'localhost:28496/spend/logs?request_id=8bda688f-b919-4e71-9c03-5f7d561a0b8a' -H "Authorization: Bearer $KEY" | jq -c '[.[] | {call_type, spend, prompt_tokens, completion_tokens, status, text: .response.choices[0].message.content, tool_calls: [.response.choices[0].message.tool_calls[]?.function]}]'
[{"call_type":"anthropic_messages","spend":0.0000151,"prompt_tokens":21,"completion_tokens":26,"status":"success","text":"One, two, three, four, five, six, seven, eight, nine, ten.","tool_calls":[]}]
Short, huge and deep lines, the cf guardrail, spend log and hosted_vllm, each output reduced to its errors, stream ends and spend rows
$ 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-1f7098c/^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: message_stop
messages-agentic-claude-relay: 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: "type":"error",'int' object has no attribute 'get'
messages-cf-claude-relay: "type":"error",'int' object has no attribute 'get'
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: [DONE],maximum recursion depth exceeded,response.failed
responses-claude-relay-huge: Exceeds the limit (4300 digits),[DONE],response.failed
responses-claude-relay-mixed: 'int' object has no attribute 'get',[DONE],response.failed
responses-claude-relay: 'int' object has no attribute 'get',[DONE],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.0,"status":"failure"
spend-messages-cf-claude-relay: "spend":0.0,"status":"failure"
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-messages-claude-relay: 

$ for f in r1-after-56a3571/^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: [DONE],response.completed
responses-claude-relay-huge: [DONE],response.completed
responses-claude-relay-mixed: [DONE],response.completed
responses-claude-relay: [DONE],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 oai-before-1f7098c/^headers-*.txt; do printf '%s: ' ${f:t:r}; sed 1d $f | grep -oE "$P" | sort -u | paste -sd, -; done
chat-oai-direct-vllm: "finish_reason":"stop",[DONE]
chat-oai-relay-deep: maximum recursion depth exceeded
chat-oai-relay: 'int' object has no attribute 'get'

$ for f in oai-after-56a3571/^headers-*.txt; do printf '%s: ' ${f:t:r}; sed 1d $f | grep -oE "$P" | sort -u | paste -sd, -; done
chat-oai-direct-vllm: "finish_reason":"stop",[DONE]
chat-oai-relay-deep: "finish_reason":"stop",[DONE]
chat-oai-relay: "finish_reason":"stop",[DONE]
Text and tool use with their spend rows, 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)\"|\"text\":\"[A-Za-z]*|\[DONE\]"
$ for f in tools-before-1f7098c/^headers-*.txt; do printf '%s: ' ${f:t:r}; sed 1d $f | grep -oE "$P" | sort -u | paste -sd, -; done
messages-text-claude-relay-deep: "type":"error",maximum recursion depth exceeded
messages-text-claude-relay-huge: "text":","text":"One,"text":"ight,message_stop
messages-text-claude-relay-mixed: "text":","text":"One,"text":"ight,message_stop
messages-text-claude-relay: "text":","text":"One,"text":"ight,message_stop
messages-tool-claude-relay-deep: "type":"error",maximum recursion depth exceeded
messages-tool-claude-relay-huge: "name":"get_weather",message_stop
messages-tool-claude-relay-mixed: "name":"get_weather",message_stop
messages-tool-claude-relay: "name":"get_weather",message_stop
spend-messages-text-claude-relay-deep: "spend":0.0,"status":"failure"
spend-messages-text-claude-relay-huge: "spend":0.0000151,"status":"success","text":"
spend-messages-text-claude-relay-mixed: 
spend-messages-text-claude-relay: 
spend-messages-tool-claude-relay-deep: "spend":0.0,"status":"failure"
spend-messages-tool-claude-relay-huge: "spend":0.000067,"status":"success","text":"
spend-messages-tool-claude-relay-mixed: 
spend-messages-tool-claude-relay: 

$ for f in tools-after-56a3571/^headers-*.txt; do printf '%s: ' ${f:t:r}; sed 1d $f | grep -oE "$P" | sort -u | paste -sd, -; done
messages-text-claude-relay-deep: "text":","text":"One,"text":"ight,message_stop
messages-text-claude-relay-huge: "text":","text":"One,"text":"ight,message_stop
messages-text-claude-relay-mixed: "text":","text":"One,"text":"ight,message_stop
messages-text-claude-relay: "text":","text":"One,"text":"ight,message_stop
messages-tool-claude-relay-deep: "name":"get_weather",message_stop
messages-tool-claude-relay-huge: "name":"get_weather",message_stop
messages-tool-claude-relay-mixed: "name":"get_weather",message_stop
messages-tool-claude-relay: "name":"get_weather",message_stop
spend-messages-text-claude-relay-deep: "spend":0.0000151,"status":"success","text":"One
spend-messages-text-claude-relay-huge: "spend":0.0000151,"status":"success","text":"One
spend-messages-text-claude-relay-mixed: "spend":0.0000151,"status":"success","text":"One
spend-messages-text-claude-relay: "spend":0.0000151,"status":"success","text":"One
spend-messages-tool-claude-relay-deep: "name":"get_weather","spend":0.000067,"status":"success","text":"
spend-messages-tool-claude-relay-huge: "name":"get_weather","spend":0.000067,"status":"success","text":"
spend-messages-tool-claude-relay-mixed: "name":"get_weather","spend":0.000067,"status":"success","text":"
spend-messages-tool-claude-relay: "name":"get_weather","spend":0.000067,"status":"success","text":"
Objects nested deep or holding a huge number, and lines at either end, 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\"|message_stop|\"spend\":[0-9.e-]+|\"status\":\"(success|failure)\"|\[DONE\]"
$ for f in r2-before-1f7098c/^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: "type": "error",maximum recursion depth exceeded,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: "type": "error",maximum recursion depth exceeded,message_stop
messages-claude-relay-hugeobj: message_stop
responses-claude-relay-deep-end: [DONE],response.completed
responses-claude-relay-deep-first: [DONE],maximum recursion depth exceeded,response.failed
responses-claude-relay-deepobj: [DONE],maximum recursion depth exceeded,response.failed
responses-claude-relay-hugeobj: Exceeds the limit (4300 digits),[DONE],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":0.0,"status":"failure"
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":0.0,"status":"failure"
spend-messages-claude-relay-hugeobj: "spend":0.0000151,"status":"success"

$ for f in r2-after-56a3571/^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: [DONE],response.completed
responses-claude-relay-deep-first: [DONE],response.completed
responses-claude-relay-deepobj: [DONE],response.completed
responses-claude-relay-hugeobj: [DONE],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"
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-1f7098c/messages-*.txt; do printf '%s %s: text=%s ' "$(head -1 pii-before-1f7098c/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-56a3571/messages-*.txt; do printf '%s %s: text=%s ' "$(head -1 pii-after-56a3571/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
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
Claude Code asked to run a tool through the data: 5 and deep object relays

Before, at 1f7098cb9a, 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
`proxy-log-claude-code.txt` is the Before agentic proxy's log, the proxy Claude Code ran against

$ grep -E ' - LiteLLM[^:]*:ERROR: ' proxy-log-claude-code.txt | sed -E 's/^[0-9:]+ - //; s/\[call_id=[^]]*\]//' | cut -c1-150 | sort | uniq -c | sort -rn
     14 LiteLLM Proxy:ERROR: anthropic_passthrough_logging_handler.py:543 - Unable to build complete streaming response for Anthropic passthrough endpoint, no
      9 LiteLLM Proxy:ERROR: streaming_handler.py:409 - Error in _route_streaming_logging_to_handler: [Non-Blocking] LiteLLM.Success_Call Error: Attempted to 
      5 LiteLLM:ERROR: agentic_streaming_iterator.py:398 - AgenticStreamingIterator: Error in agentic hook processing : 'int' object has no attribute 'get'
      4 LiteLLM Proxy:ERROR: common_request_processing.py:4570 - litellm.proxy.proxy_server.async_data_generator(): Exception occured - maximum recursion dept
      3 LiteLLM:ERROR: logging_worker.py:205 - LoggingWorker error: maximum recursion depth exceeded while decoding a JSON object from a unicode string
      3 LiteLLM:ERROR: agentic_streaming_iterator.py:398 - AgenticStreamingIterator: Error in agentic hook processing : maximum recursion depth exceeded while

After, at 56a35716fb2, 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

Type

🐛 Bug Fix

Caveats (if any)

Medium

Low

  • PANW, LLM Shield, Snowflake Claude and Vertex streamRawPredict logging have unit tests but no live run
  • OTel spans and the served-output log record no output for a stream with an undecodable object line. Unchanged, filed
  • Operators get no sign of skipped lines, since chat logs them at debug level only. Filed
  • The unified guardrail refuses any event with more than one data: line, text or not
  • Guarded streams use a little more CPU per scan round (Decision 8)

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 across streaming parsers, billing/assembly, and guardrail refusal paths affect production SSE and security-sensitive output filtering, though behavior is additive hardening with heavy test coverage.

Overview
This backport hardens Anthropic-style SSE handling when a data: line is valid JSON but not an object (data: 5, arrays, null) or when Python cannot finish decoding it (deep nesting, oversized numbers). Streaming chat, responses, pass-through logging, and stream assembly now skip those lines via shared helpers loads_json_object and is_undecodable_json_object, with JSONFragmentAccumulator stepping over unconvertible numbers instead of wedging the buffer.

Guarded /v1/messages paths take the opposite stance: if a guardrail cannot read a text-bearing or structurally ambiguous event (including JSON split across multiple data: lines), processing raises GuardrailRaisedException so unchecked content is not delivered. Presidio’s first-frame coalescing now waits for a frame whose data line starts with {, classifies only bytes completed per read via last_sse_frame_end, and refuses streams with unreadable object events.

Streaming, assembly, PANW, LLM Shield, and pass-through loggers are wired through the same parsing behavior; extensive unit and benchmark tests cover skip vs refuse cases.

Reviewed by Cursor Bugbot for commit 52d0ae8. 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

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)
@edvinsq
edvinsq requested a review from a team November 21, 2026 21:19
@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: 3 · 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

[High impact] The PR appears safe to merge, with no new actionable issues found

Summary

This backport skips stream lines that readers cannot use as JSON objects. Guarded Messages streams are refused when unreadable events could hide unchecked text

  • Anthropic stream readers skip unusable data lines and keep later events flowing.
  • Guardrails refuse unreadable events instead of passing unchecked text through.

Reviews (13) · Last reviewed commit: "test(proxy): check the SSE frame-end sea..." · Reviewed by Greptile

Comment thread litellm/llms/anthropic/chat/handler.py Resolved
@codecov

codecov Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.98995% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/litellm_core_utils/core_helpers.py 91.66% 2 Missing ⚠️
...llm/llms/anthropic/pass_through/stream_assembly.py 97.14% 1 Missing ⚠️
...tellm/proxy/guardrails/guardrail_hooks/presidio.py 96.96% 1 Missing ⚠️

📢 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
@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.

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

Copy link
Copy Markdown
Contributor

@greptileai

Comment thread litellm/llms/anthropic/chat/handler.py Resolved
…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
@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

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

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

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

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

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

…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)
@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.

…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)
@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.

@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 52d0ae8. 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 f57b2c5 into BerriAI:lts/1.108.x Nov 25, 2026
61 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