Skip to content

fix(guardrails)!: keep the upstream error when a /v1/messages stream ends in one - #49088

Merged
mateo-berri merged 20 commits into
BerriAI:mainfrom
paveln83:litellm_tool_permission_keep_stream_error_event
Oct 31, 2026
Merged

mateo-berri merged 20 commits into
BerriAI:mainfrom
paveln83:litellm_tool_permission_keep_stream_error_event

Conversation

@paveln83

@paveln83 paveln83 commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

When an Anthropic /v1/messages stream failed partway through, tool_permission replaced the upstream's error with its own 400, even when every tool is allowed, so Claude Code stopped instead of retrying. Presidio skipped masking these streams too

On such a stream it now checks what arrived before the error and sends only that, then the error, so a denied tool is still blocked and a cut-off tool call is dropped. A failed upstream no longer logs as a guardrail failure, and an error-only stream writes no spend row, as with no guardrail

Original

Breaking change: a /v1/messages stream that fails upstream behind tool_permission now gets the upstream error, not a 400. That is a 200 stream carrying the error event, or the upstream's own status when the error comes in the chat or Gemini form. Behind Presidio an analyzer failure on such a stream now errors it. Clients that matched that 400 should read the upstream error

TLDR

Problem this solves:

  • A mid-stream upstream error became a guardrail 400 on /v1/messages
  • Presidio skipped masking these streams

How it solves it:

  • Guardrails read the stream up to the error and keep the error at the end
  • On a failed stream tool_permission sends only what it read, so a tool call it could not read never reaches the client

User Flow

Before: behind a tool_permission guardrail, Claude Code gets a guardrail error when Anthropic overloads mid-answer

  1. They point Claude Code at the proxy with ANTHROPIC_BASE_URL and type a prompt
  2. Claude Code sends POST http://localhost:4000/v1/messages with "stream": true, and Anthropic fails mid-answer with overloaded_error
  3. Claude Code shows API Error: 400 ... (not a parseable Anthropic SSE stream)

After: Claude Code sees the overload and recovers, as with no guardrail

  1. Anthropic fails the same way on the same prompt
  2. Claude Code gets HTTP 200 with the text so far, then the overloaded_error frame
  3. Claude Code asks again and shows the answer
Decisions
  • Where to fix it. A keyword on the shared assembler, through_upstream_error, that tool_permission and Presidio turn on. Alternatives
    • Change the assembler's default for every caller. Rejected because logging and OpenTelemetry would start recording a failed stream's partial text as the served response, and the Bedrock and Model Armor hooks would change with no live test behind them
    • Fix it inside tool_permission alone. Rejected because Presidio would still skip masking on the same streams
    • Skip the tool check for a stream that ends in an error. Rejected because a tool call sent before the error would reach the client unchecked
    • Keep blocking, but put the upstream status and message in the block. Rejected because it still turns a retryable upstream failure into a 400 and still blocks allowed tools
  • What the check reads from a cut-off stream. Every finished block it can read, plus text the upstream cut off, since Presidio has to mask that text. A tool call the upstream cut off (tool_use, server_tool_use or mcp_tool_use) or a cut-off thinking block is left out, because its input is only the start of a JSON object that cannot be parsed or matched against a param rule, and cut-off thinking has no signature. Alternatives
    • Judge the cut-off call by its name alone and block it. Rejected because a block turns the retryable overload back into a guardrail error, and a param rule cannot judge half an input
    • Keep the cut-off block in Presidio's re-emit. Rejected because that sends its raw upstream frames past the masking, and the client retries the failed turn anyway
  • What the client gets from a failed stream. tool_permission sends only what the check read, rebuilt by the rewrite that already serves a denial, then the upstream error, even when nothing is denied. On these streams what was checked is what is sent. A stream with no error frame still passes untouched, and so does one whose event: error frame holds another Anthropic event, since that frame counts as content, so a call hidden past such a frame reaches the client as it does on main. This changes the wire format of a failed stream, which the client could have taken as it arrived, and the guarantee cannot hold on raw frames, so that is the reason for the bridge. The rewrite keeps text, finished tool calls and thinking, and the upstream message id and model. It merges text blocks into one before the tool calls, drops citations, pings, web search results and a finished mcp_tool_use, turns server_tool_use into tool_use, empties redacted_thinking, keeps only input_tokens in the message_start usage, drops a tool's caller and the null container, stop_details and diagnostics keys, sends each block as one delta, and keeps a compaction block unread. Main answered 400 on these streams, except one whose error frame is empty, null, a list, an unknown object or several lines, which it sent at 200. A client retries them or shows the error. A response the rewrite cannot build, such as a finished tool call whose input is not a JSON object, is too long, is nested too deep or was masked into invalid JSON, leaves the client the upstream error alone, not the text before it, and the proxy logs a warning. That stream has no message_start, so both SDKs raise on its first event, and no tool call or denial text reaches the client. Presidio sends that input to its analyzer first, so when the analyzer fails on it (a 200 KB nested input did, after 30 to 66 seconds of pings) the client gets an in-band invalid_request_error it does not retry, where main sent the stream raw. A healthy stream still raises there as on main, except that a param rule now denies an input nested too deep instead of answering 500. The rewrite adds no finished block when it read no text, because Claude Code does not retry a stream that shows one. Alternatives
    • Forward the upstream's frames minus the cut-off call. Rejected because a client can read a frame the check does not. Nine live runs found a reused block index, mixed line ends, a tool in message_start, interleaved deltas and a form feed, and each fix only moved the search to the next shape
    • Refuse any stream with a frame two readers could read differently. Rejected because it takes a rule per shape, and each refusal turns a retryable overload into a 400
  • What a rewritten stream ends with. When a guardrail rewrites the response (a denied tool, a masked span), the rewrite now ends with the upstream error frame and leaves out the message_delta and message_stop the re-emit used to add, keeping each one only when the upstream sent it. It also leaves the text block open when the upstream never stopped its text block, unless the round trip puts a tool call after that text. Then the text block stops first, since a client must see each block stop before the next one starts. Sending the other frames would tell the client the message or a block finished normally after an upstream failure, which fix(anthropic): surface Responses bridge stream failures as Anthropic error events #43126 already ruled out for the Responses bridge. The error goes out as event: error and its first data: line, since anything else in that frame is content no guardrail read. A raw U+2028, U+2029 or U+0085 inside a JSON object goes out escaped, so the object stays whole for every reader. Anything else, a JSON string or array included, is cut at the first of them, and both SDKs raise on the cut text
  • How an error event is found. Frame by frame at CR, LF and CRLF line ends, so CR frames glued ahead of the error do not hide it. Only a frame a blank line ended counts, and only its last event: line names it, since both SDKs dispatch that way. A frame whose later event: line replaced the error reads as no error, so its stream passes as on main. An error frame cut before its blank line reads as no error too. After content the stream gets what main gives it, and a plain one alone passes raw behind tool_permission, where main answered 400, so both SDKs read no event, as with no guardrail. By its data type, or by an exact event: error line unless the data is another Anthropic event, because a client SDK raises on that line alone and reads any other name as a different event. An event: error frame holding a content delta stays content, so Presidio masks it and a rewrite sends it once. A type that is not a string is read as no type, so the event: line decides, and Presidio refuses a first read whose type is a list or a dict
  • What Presidio does with a data line that is JSON but not an object, or an object whose type is a list or a dict. When assembly can read the rest of the stream, it skips the line and masks the stream. When no Anthropic frame is in the first read, or assembly cannot read the stream, it refuses, since it cannot check the text. Main crashed on most of these with a 500, and it sent some at 200 with text unmasked when a line it passes came first or invalid UTF-8 hid the line. The refusal is a 400 when no byte went out yet and an in-band error after a preface. A ping can make the first read look Anthropic, so frames assembly can read then answer a masked 200, not the refusal. A client that retried main's 500 does not retry this refusal. With a message id, a refusal writes a failure row, a success row, and two Langfuse traces. With no message id it writes one row under the call id. On some streams a race decides whether that row is the failure or a success at 0 tokens, and a merge with current main usually leaves the success, so a refused request can read as a success. On Presidio's Gemini route it applies where main answered 500, and where a word or null line came first and main sent the text unmasked at 200. A stream with no such line keeps passing, and so does one whose first read holds only a JSON object of no known kind, with any other type or none
    • Pass the stream through as an unknown shape. Rejected because PII that main refused would reach the client
  • Which leading frames wait for the shape decision. Frames with data. A frame with an empty data: line is relayed at once, like a comment keepalive
  • A stream whose only frames are errors, or one an earlier guardrail in the chain ended with its block. tool_permission now passes it through, as Model Armor already does, so the client gets what it gets with no tool_permission. That is a 200 stream ending in the error or block in the Anthropic form, and the error's own status as JSON in the chat and Gemini forms. Main sent a 400 that named a parse failure and hid the reason. Each frame has to be a plain error, which means one data: line, exact field names, event: error or no event: line, and only type, error and request_id at the top of the JSON. Lines are cut at every break a client honors, str.splitlines being the widest. Comments, a bare event: line and data: [DONE] do not count. Anything else counts as content, so a tool call hidden behind a form feed or an empty data: line cannot pass this way, and neither can an error message with a raw U+2028, which gets main's refusal. event: error then a U+001C and data: on one line passes raw at the widest cut, where main refused, and a client reads an empty stream, as it does with no guardrail. Text inside an error's own message passes, as it does with no guardrail. An event: error frame with another type counts as an error on a stream with content, but not here, so Model Armor refuses it where main sent it at 200. The cost is that an upstream adding a new top-level key to its error frames gets a refusal in place of its error, until the list changes. That beats a list of content keys, since each provider has its own (message, candidates, choices). A CR or CRLF stream that opens with a typed error is now read frame by frame, so Model Armor blocks it in-band where main passed its frames, and tool_permission checks it. Model Armor also blocks in-band an error stream with an id: or retry: frame, a BOM, or the error inside an event: ping frame, which main passed. A finished tool call before the block is still checked, and a denied one still gets the denial

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

Last updated: 99425d5. QA ran the guarded side of every case on 1e11e9c except case 9 and case 17, which ran on 99425d5. Case 9 and the no-guardrail sides ran on 3db8b99, or 1765df5 for 10a and 11, or 8d0606f for 14. Later changes only touch how a guardrail handles a stream with an error frame, and those runs send none through a guardrail. 1e11e9c to 99425d5 changes which frames count as an error and what a failed stream sends when a rewrite cannot be built. Every other guarded case sends a blank-line-ended error frame and parseable tool input, so each reads the same. Verification: unit tests, case 17, and /live-pr-risk ran those shapes and the no-guardrail cells at 99425d5

config.yaml

Cases 7, 9, 11 to 15 and 17 drive Claude Code in tmux, and the rest use curl. Anthropic entries leave out api_key here. scripted models stream a local fake overload, and relay models cut a real Claude Sonnet 5.5 stream with an injected overloaded_error

model_list:
  - model_name: litellm-qa-toolperm-scripted-text-error
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_base: os.environ/SCRIPTED_UPSTREAM_TEXT_BASE
      api_key: scripted-upstream-no-key
  - model_name: litellm-qa-toolperm-scripted-text-error-guarded
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_base: os.environ/SCRIPTED_UPSTREAM_TEXT_BASE
      api_key: scripted-upstream-no-key
      guardrails: ["litellm-qa-toolperm-allow-all"]
  - model_name: litellm-qa-toolperm-scripted-tool-error
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_base: os.environ/SCRIPTED_UPSTREAM_TOOL_BASE
      api_key: scripted-upstream-no-key
  - model_name: litellm-qa-toolperm-scripted-read-error
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_base: os.environ/SCRIPTED_UPSTREAM_READTOOL_BASE
      api_key: scripted-upstream-no-key
  - model_name: litellm-qa-toolperm-scripted-erroronly
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_base: os.environ/SCRIPTED_UPSTREAM_ERRORONLY_BASE
      api_key: scripted-upstream-no-key
  - model_name: litellm-qa-presidio-scripted-phone-error
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_base: os.environ/SCRIPTED_UPSTREAM_PHONE_BASE
      api_key: scripted-upstream-no-key
  - model_name: litellm-qa-toolperm-sonnet
    litellm_params:
      model: anthropic/claude-sonnet-5-5
  - model_name: litellm-qa-toolperm-sonnet-guarded
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      guardrails: ["litellm-qa-toolperm-allow-all"]

  - model_name: litellm-qa-toolperm-relay-tool
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_base: os.environ/RELAY_TOOL_BASE
  - model_name: litellm-qa-toolperm-relay-second-tool
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_base: os.environ/RELAY_SECOND_TOOL_BASE
  - model_name: litellm-qa-toolperm-relay-tool-once
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_base: os.environ/RELAY_TOOL_ONCE_PLAIN_BASE
  - model_name: litellm-qa-toolperm-relay-tool-once-guarded
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_base: os.environ/RELAY_TOOL_ONCE_GUARDED_BASE
      guardrails: ["litellm-qa-toolperm-allow-all"]
  - model_name: litellm-qa-toolperm-relay-badinput-once
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_base: os.environ/RELAY_BADINPUT_ONCE_PLAIN_BASE
  - model_name: litellm-qa-toolperm-relay-badinput-once-guarded
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_base: os.environ/RELAY_BADINPUT_ONCE_GUARDED_BASE
      guardrails: ["litellm-qa-toolperm-allow-all"]
  - model_name: litellm-qa-toolperm-relay-text-once
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_base: os.environ/RELAY_TEXT_ONCE_PLAIN_BASE
  - model_name: litellm-qa-toolperm-relay-text-once-guarded
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_base: os.environ/RELAY_TEXT_ONCE_GUARDED_BASE
      guardrails: ["litellm-qa-toolperm-allow-all"]
  - model_name: litellm-qa-toolperm-relay-text
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_base: os.environ/RELAY_TEXT_BASE
  - model_name: litellm-qa-toolperm-relay-text-guarded
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_base: os.environ/RELAY_TEXT_BASE
      guardrails: ["litellm-qa-toolperm-allow-all"]
  - model_name: litellm-qa-toolperm-scripted-read-error-rewrite-guarded
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_base: os.environ/SCRIPTED_UPSTREAM_READTOOL_BASE
      api_key: scripted-upstream-no-key
      guardrails: ["litellm-qa-toolperm-deny-read-rewrite"]
  - model_name: litellm-qa-presidio-scripted-phone-error-guarded
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_base: os.environ/SCRIPTED_UPSTREAM_PHONE_BASE
      api_key: scripted-upstream-no-key
      guardrails: ["litellm-qa-presidio-mask-output"]

guardrails:
  - guardrail_name: litellm-qa-toolperm-allow-all
    litellm_params:
      guardrail: tool_permission
      mode: post_call
      default_on: false
      rules:
        - id: allow_every_tool
          tool_name: ".*"
          decision: allow
      default_action: allow
      on_disallowed_action: block
  - guardrail_name: litellm-qa-toolperm-deny-read
    litellm_params:
      guardrail: tool_permission
      mode: post_call
      default_on: false
      rules:
        - id: deny_read
          tool_name: "^Read$"
          decision: deny
      default_action: allow
      on_disallowed_action: block
  - guardrail_name: litellm-qa-toolperm-deny-read-rewrite
    litellm_params:
      guardrail: tool_permission
      mode: post_call
      default_on: false
      rules:
        - id: deny_read
          tool_name: "^Read$"
          decision: deny
      default_action: allow
      on_disallowed_action: rewrite
  - guardrail_name: litellm-qa-toolperm-bash-ls-only
    litellm_params:
      guardrail: tool_permission
      mode: post_call
      default_on: false
      rules:
        - id: bash_ls_only
          tool_name: "^Bash$"
          decision: allow
          allowed_param_patterns:
            command: "^ls( .*)?$"
      default_action: allow
      on_disallowed_action: block
  - guardrail_name: litellm-qa-presidio-mask-output
    litellm_params:
      guardrail: presidio
      mode: post_call
      default_on: false
      presidio_filter_scope: output
      presidio_analyzer_api_base: os.environ/PRESIDIO_ANALYZER_API_BASE
      presidio_anonymizer_api_base: os.environ/PRESIDIO_ANONYMIZER_API_BASE
      pii_entities_config:
        PHONE_NUMBER: MASK

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
Case No guardrail Guarded, before Guarded, after
1 text, allow-all error kept 400 error kept
2 Bash, allow-all 400 tool, error
3 Read, deny block 400 parse 400 denial
4 Read, deny rewrite 400 parse rewrite, error
5 error only, allow-all error kept 400 error kept
6 phone, Presidio shown shown masked
7 overload, allow-all retries, 500 400 at 3 s retries, 500
9 ls, allow-all tool ran tool ran
10a cut Bash, allow-all partial, error 400 error, no call
10b cut Bash, ls rule 400 error, no call
10c cut 2nd call, deny Read 400 rewrite, error
10d phone, cut Bash, Presidio shown shown masked, no call
11 cut Bash once, allow-all tool ran tool ran retried, tool ran
12 cut text once, allow-all answered answered answered
13 cut text always, allow-all answered 400 answered
14 Read, deny rewrite Read, error 400 denial, error
15 phone, Presidio retries, 500 retries, 500 retries, 500
16 thinking, cut text, allow-all thinking, text, error thinking, text, error
Case 13. Claude Code, guarded, real Sonnet 5.5 cut mid-answer
  1. litellm --config config.yaml --port $PORT --num_workers 2
  2. ANTHROPIC_BASE_URL=http://127.0.0.1:$PORT ANTHROPIC_AUTH_TOKEN=$LITELLM_MASTER_KEY ANTHROPIC_MODEL=litellm-qa-toolperm-relay-text-guarded claude
  3. Type Write two short sentences about the ocean. and press Enter

Before (d9c9d84), all 3 cut streams got the 400:

● API Error: 400 Guardrail raised an exception, Guardrail: litellm-qa-toolperm-allow-all, Message: Streamed response could
  not be verified for tool permissions (not a parseable Anthropic SSE stream), blocking it
✻ Baked for 3s · done 8:08 PM

pr49088-3db8b99312-c13-before-guarded-end.png

After (1e11e9c), the retry after the first cut got the answer:

● The ocean covers more than 70% of Earth's surface and holds most of the planet's water. Its waves, currents, and tides shape our
  climate and sustain countless forms of life.
✻ Cogitated for 2s · done 5:43 AM

pr49088-1e11e9c4b9-c13-after-guarded-end.png

Case 13, the same model with no guardrail

Model litellm-qa-toolperm-relay-text. Both trees fall back to one non-streaming request and answer

Before (d9c9d84):

pr49088-3db8b99312-c13-before-noguard-end.png

After (3db8b99):

pr49088-3db8b99312-c13-after-noguard-end.png

Case 7, Claude Code on a guarded model whose scripted upstream always overloads

Model litellm-qa-toolperm-scripted-text-error-guarded, same steps as case 13. Prompt: Say hello

Before (d9c9d84), at 3 seconds:

● API Error: 400 Guardrail raised an exception, Guardrail: litellm-qa-toolperm-allow-all, Message: Streamed response could
  not be verified for tool permissions (not a parseable Anthropic SSE stream), blocking it

pr49088-c91c8e9c6f-c7-cc-text-error-guarded-end.png

After (1e11e9c), 7 seconds in, and once its retries run out:

✻ API error · Retrying in 1s · attempt 1/9

pr49088-1e11e9c4b9-c7-after-guarded-first.png

● API Error: 500 litellm.InternalServerError: AnthropicError - {"type": "error", "error": {"type": "overloaded_error",
  "message": "Overloaded"}}
  LiteLLM: model group 'litellm-qa-toolperm-scripted-text-error-guarded' failed with the error above. No fallback was
  attempted. This is a server-side issue, usually temporary — try again in a moment. If it persists, check your inference
  gateway (127.0.0.1:25900).
✻ Sautéed for 3m 12s · done 5:49 AM

pr49088-1e11e9c4b9-c7-after-guarded-end.png

No guardrail, Before (d9c9d84) and After (3db8b99):

pr49088-c91c8e9c6f-c7-cc-text-error-noguard-end.png

pr49088-3db8b99312-c7-after-noguard-end.png

Case 12, Claude Code on real Claude Sonnet 5.5 whose first stream is cut mid-answer

Models litellm-qa-toolperm-relay-text-once and litellm-qa-toolperm-relay-text-once-guarded, same steps and prompt as case 13. The relay cuts only the first stream of a session. Claude Code answered on both trees, guarded or not, since on d9c9d84 it sends a new request after the guardrail 400

Before (d9c9d84), guarded:

● The ocean covers more than 70 percent of Earth's surface and holds most of the planet's water. Its waves, currents, and tides
  shape coastlines and climate all around the world.
✻ Sautéed for 2s · done 8:00 PM

After (1e11e9c), guarded:

● The ocean covers more than 70 percent of Earth's surface and holds most of the planet's water. Its waves, currents, and tides
  shape coastlines and climate, and they shelter an astonishing variety of life.
✻ Baked for 3s · done 5:44 AM
Case 11, Claude Code on real Claude Sonnet 5.5 whose first Bash call is cut mid-input

Models litellm-qa-toolperm-relay-tool-once and litellm-qa-toolperm-relay-tool-once-guarded, same steps as case 13. Prompt: Use the Bash tool to run: ls -la /usr/share && echo done-listing-the-share-directory, then tell me how many entries it printed. The relay cuts only the first stream of a session

Before (d9c9d84), guarded:

● The listing printed 152 entries: 150 files and directories, plus the . and .. entries. It also printed a total 664 header line and
  the done-listing-the-share-directory line, and I didn't count either of those.
  I got the 150 from a second command, ls -A /usr/share | wc -l. I didn't count the lines of the first output by hand.
✻ Baked for 11s · done 8:01 PM

After (1e11e9c), guarded:

● ls -la /usr/share printed 152 entries. That count includes . and .., so there are 150 entries excluding them. It also leaves out
  the total 664 header line and the done-listing-the-share-directory line that the echo printed.
  The 152 entries are 143 directories (including . and ..) and 9 regular files.
✻ Worked for 12s · done 5:45 AM

pr49088-1e11e9c4b9-c11-after-guarded-end.png

After (1765df5), no guardrail:

pr49088-1765df54da-c11-after-noguard-end.png

Case 9, Claude Code on real Claude Sonnet 5.5, guarded, runs Bash ls

Model litellm-qa-toolperm-sonnet-guarded, same steps as case 13. Prompt: Use the Bash tool to run ls in this directory, then tell me how many entries there are. Both trees ran the tool through the guardrail and answered

Before (d9c9d84):

pr49088-c91c8e9c6f-c9-cc-sonnet-guarded-end.png

After (3db8b99):

pr49088-3db8b99312-c9-after-guarded-end.png

Case 14, Claude Code on a scripted upstream that streams a finished Read call, then overloads, rewrite mode

Models litellm-qa-toolperm-scripted-read-error and litellm-qa-toolperm-scripted-read-error-rewrite-guarded (deny Read, rewrite), same steps as case 13. Prompt: Show me the contents of /etc/hosts

Before (d9c9d84), guarded:

● API Error: 400 Guardrail raised an exception, Guardrail: litellm-qa-toolperm-deny-read-rewrite, Message: Streamed response
  could not be verified for tool permissions (not a parseable Anthropic SSE stream), blocking it
✻ Churned for 3s · done 11:30 PM

pr49088-8d0606f555-c14-before-guarded-end.png

After (1e11e9c), guarded. The denial replaces the Read call, and the upstream error follows, so Read never runs:

● Permission denied: Tool 'Read' denied by rule 'deny_read' (Rule: deny_read)
● API Error: Server error mid-response. The response above may be incomplete.
✻ Cogitated for 1s · done 5:51 AM

pr49088-1e11e9c4b9-c14-after-guarded-end.png

After (8d0606f), no guardrail, the same error after the Read call, which Claude Code then offers to run:

pr49088-8d0606f555-c14-after-noguard-first.png

Case 15, Claude Code on a scripted upstream that streams a phone number, then overloads, Presidio output masking

Models litellm-qa-presidio-scripted-phone-error and litellm-qa-presidio-scripted-phone-error-guarded, same steps as case 13. Prompt: How do I reach you? Claude Code drops text cut off by an overload without showing it, then retries non-streaming until API Error: 500 ... overloaded_error, on both trees with or without the guardrail. No capture on either tree shows 212-555-0199, so case 6 shows the masking on the wire

After (1e11e9c), guarded:

pr49088-1e11e9c4b9-c15-after-guarded-end.png

Case 17, Claude Code when a finished Bash call cannot be rebuilt, so the client gets the upstream error alone

Models litellm-qa-toolperm-relay-badinput-once and litellm-qa-toolperm-relay-badinput-once-guarded, same steps as case 13. Prompt: Use Bash to run ls in /tmp, then tell me how many entries it printed. The relay answers the first request itself with text, a finished Bash call whose input is {"command" "ls", and an overload, then forwards later requests to the real API

Before (d9c9d84), guarded, the stream is a 400 and Claude Code retries it with nothing on screen:

pr49088-99425d525f-c17-before-guarded-end.png

After (99425d5), guarded, the curl stream is the error alone. Claude Code shows API error · Retrying in 1s · attempt 1/2, retries, runs Bash and answers:

HTTP/1.1 200 OK

event: error
data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}

pr49088-99425d525f-c17-guarded-end.png

After (99425d5), no guardrail, Claude Code shows the text, the malformed call and API Error: Server error mid-response, then goes on in the next turn:

pr49088-99425d525f-c17-noguard-end.png

Case 10a. Real Sonnet Bash call cut mid-input, allow-all
curl -sS -N -D - http://127.0.0.1:$PORT/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'content-type: application/json' -H 'anthropic-version: 2023-06-01' -d '{"model":"litellm-qa-toolperm-relay-tool","max_tokens":512,"stream":true,"guardrails":["litellm-qa-toolperm-allow-all"],"tools":[{"name":"Bash","description":"Run a shell command","input_schema":{"type":"object","properties":{"command":{"type":"string"}},"required":["command"]}},{"name":"Read","description":"Read a file","input_schema":{"type":"object","properties":{"file_path":{"type":"string"}},"required":["file_path"]}}],"messages":[{"role":"user","content":"Use the Bash tool to run: ls -la /usr/share && echo done-listing-the-share-directory"}]}'

Before (d9c9d84)

HTTP/1.1 400 Bad Request

{"type":"error","error":{"type":"invalid_request_error","message":"Guardrail raised an exception, Guardrail: litellm-qa-toolperm-allow-all, Message: Streamed response could not be verified for tool permissions (not a parseable Anthropic SSE stream), blocking it"}}

After (1e11e9c)

HTTP/1.1 200 OK

event: message_start
data: {"type":"message_start","message":{"id":"msg_011CgZmvuRjdqQKeRRFtHdK5","type":"message","role":"assistant","model":"litellm-qa-toolperm-relay-tool","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":463,"output_tokens":0}}}

event: error
data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}
Case 10b. Real Sonnet Bash call cut mid-input, Bash allowed only for `ls`
curl -sS -N -D - http://127.0.0.1:$PORT/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'content-type: application/json' -H 'anthropic-version: 2023-06-01' -d '{"model":"litellm-qa-toolperm-relay-tool","max_tokens":512,"stream":true,"guardrails":["litellm-qa-toolperm-bash-ls-only"],"tools":[{"name":"Bash","description":"Run a shell command","input_schema":{"type":"object","properties":{"command":{"type":"string"}},"required":["command"]}},{"name":"Read","description":"Read a file","input_schema":{"type":"object","properties":{"file_path":{"type":"string"}},"required":["file_path"]}}],"messages":[{"role":"user","content":"Use the Bash tool to run: ls -la /usr/share && echo done-listing-the-share-directory"}]}'

Before (d9c9d84)

HTTP/1.1 400 Bad Request

{"type":"error","error":{"type":"invalid_request_error","message":"Guardrail raised an exception, Guardrail: litellm-qa-toolperm-bash-ls-only, Message: Streamed response could not be verified for tool permissions (not a parseable Anthropic SSE stream), blocking it"}}

After (1e11e9c)

HTTP/1.1 200 OK

event: message_start
data: {"type":"message_start","message":{"id":"msg_011CgZmw3yC4ZoV7EYMSrtdj","type":"message","role":"assistant","model":"litellm-qa-toolperm-relay-tool","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":463,"output_tokens":0}}}

event: error
data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}
Case 10c. Real Sonnet Read then Bash, Bash cut mid-input, deny Read in rewrite mode
curl -sS -N -D - http://127.0.0.1:$PORT/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'content-type: application/json' -H 'anthropic-version: 2023-06-01' -d '{"model":"litellm-qa-toolperm-relay-second-tool","max_tokens":512,"stream":true,"guardrails":["litellm-qa-toolperm-deny-read-rewrite"],"tools":[{"name":"Bash","description":"Run a shell command","input_schema":{"type":"object","properties":{"command":{"type":"string"}},"required":["command"]}},{"name":"Read","description":"Read a file","input_schema":{"type":"object","properties":{"file_path":{"type":"string"}},"required":["file_path"]}}],"messages":[{"role":"user","content":"Call two tools in this one reply, before writing any text: first the Read tool on /etc/hosts, then the Bash tool to run: ls -la /usr/share && echo done-listing-the-share-directory"}]}'

Before (d9c9d84)

HTTP/1.1 400 Bad Request

{"type":"error","error":{"type":"invalid_request_error","message":"Guardrail raised an exception, Guardrail: litellm-qa-toolperm-deny-read-rewrite, Message: Streamed response could not be verified for tool permissions (not a parseable Anthropic SSE stream), blocking it"}}

After (1e11e9c)

HTTP/1.1 200 OK

event: message_start
data: {"type":"message_start","message":{"id":"msg_011CgZmwBuvQHUPACcxiAuNF","type":"message","role":"assistant","model":"litellm-qa-toolperm-relay-second-tool","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":494,"output_tokens":0}}}

event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}

event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Permission denied: Tool 'Read' denied by rule 'deny_read' (Rule: deny_read)"}}

event: content_block_stop
data: {"type": "content_block_stop", "index": 0}

event: error
data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}
Case 10d. Real Sonnet phone number then a cut Bash call, Presidio output masking
curl -sS -N -D - http://127.0.0.1:$PORT/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'content-type: application/json' -H 'anthropic-version: 2023-06-01' -d '{"model":"litellm-qa-toolperm-relay-tool","max_tokens":512,"stream":true,"guardrails":["litellm-qa-presidio-mask-output"],"tools":[{"name":"Bash","description":"Run a shell command","input_schema":{"type":"object","properties":{"command":{"type":"string"}},"required":["command"]}},{"name":"Read","description":"Read a file","input_schema":{"type":"object","properties":{"file_path":{"type":"string"}},"required":["file_path"]}}],"messages":[{"role":"user","content":"First write one short sentence that includes the phone number 212-555-0199, then use the Bash tool to run: ls -la /usr/share && echo done-listing-the-share-directory"}]}'

Before (d9c9d84)

HTTP/1.1 200 OK

event: message_start
data: {"type":"message_start","message":{"model":"litellm-qa-toolperm-relay-tool","id":"msg_011CgWrSu1yYDtfsC2D4fc5n","type":"message","role":"assistant","content":[],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":485,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard","inference_geo":"global","speed":"standard"},"diagnostics":null}}

event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}             }

event: ping
data: {"type": "ping"}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"You"}           }

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" can re"}           }

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ach the office"}               }

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" at 212-555-0199"}    }

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" "}             }

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"during business hours."}  }

event: content_block_stop
data: {"type":"content_block_stop","index":0   }

event: content_block_start
data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"toolu_01URpL8LWdwoCkM4e85E6tha","name":"Bash","input":{},"caller":{"type":"direct"}}       }

event: content_block_delta
data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":""} }

event: content_block_delta
data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"comma"}         }

event: error
data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}

After (1e11e9c)

HTTP/1.1 200 OK

event: message_start
data: {"type":"message_start","message":{"id":"msg_011CgZmxEoajorR1zdUGtDWB","type":"message","role":"assistant","model":"litellm-qa-toolperm-relay-tool","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":485,"output_tokens":0}}}

event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}

event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "You can reach the office at <PHONE_NUMBER> during business hours."}}

event: content_block_stop
data: {"type": "content_block_stop", "index": 0}

event: error
data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}
Case 1. Text then overload, no guardrail
curl -sS -N -D - http://127.0.0.1:$PORT/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'content-type: application/json' -H 'anthropic-version: 2023-06-01' -d '{"model":"litellm-qa-toolperm-scripted-text-error","max_tokens":256,"stream":true,"messages":[{"role":"user","content":"Say hello"}]}'

Before (d9c9d84)

HTTP/1.1 200 OK

event: message_start
data: {"type":"message_start","message":{"id":"msg_scripted_overload_01","type":"message","role":"assistant","model":"litellm-qa-toolperm-scripted-text-error","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":12,"output_tokens":1}}}

event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}

event: ping
data: {"type": "ping"}

event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Hello, I am starting to"}}

event: error
data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}

After (3db8b99)

HTTP/1.1 200 OK

event: ping
data: {"type": "ping"}

event: message_start
data: {"type":"message_start","message":{"id":"msg_scripted_overload_01","type":"message","role":"assistant","model":"litellm-qa-toolperm-scripted-text-error","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":12,"output_tokens":1}}}

event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}

event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Hello, I am starting to"}}

event: error
data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}
Case 1. Text then overload, allow-all tool_permission
curl -sS -N -D - http://127.0.0.1:$PORT/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'content-type: application/json' -H 'anthropic-version: 2023-06-01' -d '{"model":"litellm-qa-toolperm-scripted-text-error","max_tokens":256,"stream":true,"guardrails":["litellm-qa-toolperm-allow-all"],"messages":[{"role":"user","content":"Say hello"}]}'

Before (d9c9d84)

HTTP/1.1 400 Bad Request

{"type":"error","error":{"type":"invalid_request_error","message":"Guardrail raised an exception, Guardrail: litellm-qa-toolperm-allow-all, Message: Streamed response could not be verified for tool permissions (not a parseable Anthropic SSE stream), blocking it"}}

After (1e11e9c)

HTTP/1.1 200 OK

event: message_start
data: {"type":"message_start","message":{"id":"msg_scripted_overload_01","type":"message","role":"assistant","model":"litellm-qa-toolperm-scripted-text-error","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":12,"output_tokens":0}}}

event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}

event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Hello, I am starting to"}}

event: error
data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}
Case 2. Allowed Bash tool call then overload, allow-all
curl -sS -N -D - http://127.0.0.1:$PORT/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'content-type: application/json' -H 'anthropic-version: 2023-06-01' -d '{"model":"litellm-qa-toolperm-scripted-tool-error","max_tokens":256,"stream":true,"guardrails":["litellm-qa-toolperm-allow-all"],"tools":[{"name":"Bash","description":"Run a shell command","input_schema":{"type":"object","properties":{"command":{"type":"string"}},"required":["command"]}},{"name":"Read","description":"Read a file","input_schema":{"type":"object","properties":{"file_path":{"type":"string"}},"required":["file_path"]}}],"messages":[{"role":"user","content":"List the files here"}]}'

Before (d9c9d84)

HTTP/1.1 400 Bad Request

{"type":"error","error":{"type":"invalid_request_error","message":"Guardrail raised an exception, Guardrail: litellm-qa-toolperm-allow-all, Message: Streamed response could not be verified for tool permissions (not a parseable Anthropic SSE stream), blocking it"}}

After (1e11e9c)

HTTP/1.1 200 OK

event: message_start
data: {"type":"message_start","message":{"id":"msg_scripted_overload_01","type":"message","role":"assistant","model":"litellm-qa-toolperm-scripted-tool-error","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":12,"output_tokens":0}}}

event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "tool_use", "id": "toolu_scripted_01", "name": "Bash", "input": {}}}

event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "input_json_delta", "partial_json": "{\"command\": \"ls\"}"}}

event: content_block_stop
data: {"type": "content_block_stop", "index": 0}

event: error
data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}
Case 3. Denied Read tool call then overload, block mode
curl -sS -N -D - http://127.0.0.1:$PORT/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'content-type: application/json' -H 'anthropic-version: 2023-06-01' -d '{"model":"litellm-qa-toolperm-scripted-read-error","max_tokens":256,"stream":true,"guardrails":["litellm-qa-toolperm-deny-read"],"tools":[{"name":"Bash","description":"Run a shell command","input_schema":{"type":"object","properties":{"command":{"type":"string"}},"required":["command"]}},{"name":"Read","description":"Read a file","input_schema":{"type":"object","properties":{"file_path":{"type":"string"}},"required":["file_path"]}}],"messages":[{"role":"user","content":"Show me /etc/hosts"}]}'

Before (d9c9d84)

HTTP/1.1 400 Bad Request

{"type":"error","error":{"type":"invalid_request_error","message":"Guardrail raised an exception, Guardrail: litellm-qa-toolperm-deny-read, Message: Streamed response could not be verified for tool permissions (not a parseable Anthropic SSE stream), blocking it"}}

After (1e11e9c)

HTTP/1.1 400 Bad Request

{"type":"error","error":{"type":"invalid_request_error","message":"Guardrail raised an exception, Guardrail: litellm-qa-toolperm-deny-read, Message: Tool 'Read' denied by rule 'deny_read'"}}
Case 4. Denied Read tool call then overload, rewrite mode
curl -sS -N -D - http://127.0.0.1:$PORT/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'content-type: application/json' -H 'anthropic-version: 2023-06-01' -d '{"model":"litellm-qa-toolperm-scripted-read-error","max_tokens":256,"stream":true,"guardrails":["litellm-qa-toolperm-deny-read-rewrite"],"tools":[{"name":"Bash","description":"Run a shell command","input_schema":{"type":"object","properties":{"command":{"type":"string"}},"required":["command"]}},{"name":"Read","description":"Read a file","input_schema":{"type":"object","properties":{"file_path":{"type":"string"}},"required":["file_path"]}}],"messages":[{"role":"user","content":"Show me /etc/hosts"}]}'

Before (d9c9d84)

HTTP/1.1 400 Bad Request

{"type":"error","error":{"type":"invalid_request_error","message":"Guardrail raised an exception, Guardrail: litellm-qa-toolperm-deny-read-rewrite, Message: Streamed response could not be verified for tool permissions (not a parseable Anthropic SSE stream), blocking it"}}

After (1e11e9c)

HTTP/1.1 200 OK

event: message_start
data: {"type":"message_start","message":{"id":"msg_scripted_overload_01","type":"message","role":"assistant","model":"litellm-qa-toolperm-scripted-read-error","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":12,"output_tokens":0}}}

event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}

event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Permission denied: Tool 'Read' denied by rule 'deny_read' (Rule: deny_read)"}}

event: content_block_stop
data: {"type": "content_block_stop", "index": 0}

event: error
data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}
Case 5. Error frame only, allow-all, the same bytes as no guardrail
curl -sS -N -D - http://127.0.0.1:$PORT/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'content-type: application/json' -H 'anthropic-version: 2023-06-01' -d '{"model":"litellm-qa-toolperm-scripted-erroronly","max_tokens":256,"stream":true,"guardrails":["litellm-qa-toolperm-allow-all"],"messages":[{"role":"user","content":"Say hello"}]}'

Before (d9c9d84)

HTTP/1.1 400 Bad Request

{"type":"error","error":{"type":"invalid_request_error","message":"Guardrail raised an exception, Guardrail: litellm-qa-toolperm-allow-all, Message: Streamed response could not be verified for tool permissions (not a parseable Anthropic SSE stream), blocking it"}}

After (1e11e9c)

HTTP/1.1 200 OK

event: error
data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}
Case 6. Phone number then overload, Presidio output masking
curl -sS -N -D - http://127.0.0.1:$PORT/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'content-type: application/json' -H 'anthropic-version: 2023-06-01' -d '{"model":"litellm-qa-presidio-scripted-phone-error","max_tokens":256,"stream":true,"guardrails":["litellm-qa-presidio-mask-output"],"messages":[{"role":"user","content":"How do I reach you?"}]}'

Before (d9c9d84)

HTTP/1.1 200 OK

event: ping
data: {"type": "ping"}

event: message_start
data: {"type":"message_start","message":{"id":"msg_scripted_overload_01","type":"message","role":"assistant","model":"litellm-qa-presidio-scripted-phone-error","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":12,"output_tokens":1}}}

event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}

event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Sure, call me at 212-555-0199 to talk it over"}}

event: error
data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}

After (1e11e9c)

HTTP/1.1 200 OK

event: message_start
data: {"type":"message_start","message":{"id":"msg_scripted_overload_01","type":"message","role":"assistant","model":"litellm-qa-presidio-scripted-phone-error","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":12,"output_tokens":0}}}

event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}

event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Sure, call me at <PHONE_NUMBER> to talk it over"}}

event: error
data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}
Case 16. Real Sonnet thinking, then text cut by an overload, adaptive thinking
curl -sS -N -D - http://127.0.0.1:$PORT/v1/messages -H "x-api-key: $LITELLM_MASTER_KEY" -H 'content-type: application/json' -H 'anthropic-version: 2023-06-01' -d '{"model":"litellm-qa-toolperm-relay-text","max_tokens":2048,"stream":true,"guardrails":["litellm-qa-toolperm-allow-all"],"thinking":{"type":"adaptive"},"tools":[{"name":"Bash","description":"Run a shell command","input_schema":{"type":"object","properties":{"command":{"type":"string"}},"required":["command"]}},{"name":"Read","description":"Read a file","input_schema":{"type":"object","properties":{"file_path":{"type":"string"}},"required":["file_path"]}}],"messages":[{"role":"user","content":"Without using any tools, work out 4817 * 9263 carefully in your head, then write two short sentences about the ocean that include the result."}]}'

No guardrail (1e11e9c, each signature cut to 16 characters here)

HTTP/1.1 200 OK

event: message_start
data: {"type":"message_start","message":{"model":"litellm-qa-toolperm-relay-text","id":"msg_011CgZn1L9t3Cr5Dcx4u9ebt","type":"message","role":"assistant","content":[],"container":null,"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":471,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"output_tokens":8,"service_tier":"standard","inference_geo":"global","speed":"standard"},"diagnostics":null}}

event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}              }

event: ping
data: {"type": "ping"}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":""}      }

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"CAQSgAcKEAgTGAI4..."}  }

event: content_block_stop
data: {"type":"content_block_stop","index":0     }

event: content_block_start
data: {"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}        }

event: content_block_delta
data: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"4"}        }

event: error
data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}

allow-all (1e11e9c)

HTTP/1.1 200 OK

event: message_start
data: {"type":"message_start","message":{"id":"msg_011CgZn1TwCTTatMGmUr7uRq","type":"message","role":"assistant","model":"litellm-qa-toolperm-relay-text","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":471,"output_tokens":0}}}

event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": "", "signature": ""}}

event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "signature_delta", "signature": "CAQS/gYKEAgTGAI4..."}}

event: content_block_stop
data: {"type": "content_block_stop", "index": 0}

event: content_block_start
data: {"type": "content_block_start", "index": 1, "content_block": {"type": "text", "text": ""}}

event: content_block_delta
data: {"type": "content_block_delta", "index": 1, "delta": {"type": "text_delta", "text": "4"}}

event: error
data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}
/live-pr-risk at 99425d5

Verdict: passes at 99425d5. Base d9c9d84, head 99425d5, merged with main c4b01b2, 679 cells on each with 2 workers, real upstreams and real Presidio. Failures are injected into real streams. Nothing on the merge differs from head alone, and every entry below is disclosed

Breaking

A deep tool input then an upstream error behind Presidio mask (200 KB of nested [) was 200 with the phone number raw on main. It is now a 200 with pings, then an in-band invalid_request_error, because the real analyzer answered 500 after 30 s, and the client waited 32 to 66 s. No text or PII reaches the client and both SDKs raise, but the retryable overload became a class a client does not retry. At 20 KB the error comes alone. Disclosed, ships on mateo-berri's approval of this PR

Backward incompatible

A stream whose only frame is a plain error cut before its blank line was 400 behind tool_permission and is now 200 raw, with or without a deny rule. Both SDKs read no event, as with no guardrail, and no call can pass. Behind Presidio it is raw as on main, and any other lone cut frame keeps main's 400. Disclosed, ships on mateo-berri's approval of this PR

An error that is a JSON string or array with a raw U+2028 was 400 and is now 200 with the error cut, and both SDKs raise on the cut text. Disclosed, ships on mateo-berri's approval of this PR

A failed stream behind tool_permission answers a 200 stream with the error, not a 400. Disclosed, ships on mateo-berri's approval of this PR

A rewrite that cannot build sends the error alone, with no denial text and no call. Disclosed, ships on mateo-berri's approval of this PR

Presidio block answers 400 on readable PII before an error. Disclosed, ships on mateo-berri's approval of this PR

A param rule now denies an input nested too deep, where main answered 500. Disclosed, ships on mateo-berri's approval of this PR

The error goes last and keeps only its first data: line. Disclosed, ships on mateo-berri's approval of this PR

Regression risk

The catch-all swallows every Exception on a failed stream, so a real rewrite bug shows only as one fixed warning with no exception text, request id or guardrail name. CancelledError, KeyboardInterrupt, SystemExit and GeneratorExit pass, no guardrail decision sits inside it, and no denied call that main blocked came out in 162 live deny cells

Presidio passes an unterminated typed error frame raw with its PII, the same on main, so this is a leak this PR leaves alone. With a BOM the proxy follows the Python SDK and TS differs. One first-pass failure row went missing on an unterminated frame and did not reproduce in 3 more runs

Dependency graph

_frames_a_client_dispatches reaches only _error_events, then anthropic_sse_error_events, then the tool_permission hook and anthropic_sse_chunks_from_response from tool_permission and Presidio, all verified live. Model Armor and Bedrock reach the rewrite in process only. is_sse_error_stream still counts an unterminated frame, verified live. The route through common_request_processing and the string hook dispatch in proxy/utils.py was driven by every cell. No subclass or registry entry. Unit tests passed on head and merged. The walk named no dependent the integration suites cover, so they were skipped

No-guardrail cells ran at this tip. Real streams cut mid-text and mid-tool read with both SDKs are no worse than base, and with no guardrail they match base

Not verified

Bedrock's rewrite and Model Armor's sanitized rewrite ran in process only, with no Bedrock guardrail credentials or sanitizing template here. Model Armor with fail_on_error: false on a deep frame was not driven. The fidelity sample was not re-run, since this diff does not change what the rewrite keeps. 65 cells with no error frame were carried from earlier tips. Claude Code on the in-band refusal was not driven

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • Bedrock and Model Armor still replace the upstream error with their block, as on main (follow-up)

Low

  • A chained guardrail's Anthropic-form block now arrives as its error event, not a 400
  • Shared-handler guardrails still skip these streams, and Presidio masks text only, as on main (follow-up)
  • Every upstream failure here is injected
  • A failed stream arrives rebuilt, not as sent (see Decisions)
  • Cut-off text can hide a rewrite's denial, and allowed cut-off calls drop, so the client retries
  • A 525 KB stream costs up to 120 ms more, a failed one about 340 ms
  • Presidio answers 400 on readable PII before an upstream error, where main leaked it
  • A finished denied call's 400 names the rule
  • /v1/messages skips a non-object data line, where main errored, and Presidio refuses a stream it cannot read past one. Chat, Responses and the agentic iterator still fail on one
  • Model Armor passes unreadable frames with fail_on_error: false
  • With no error frame, or event: error holding another Anthropic event, a shape the check cannot read (say data: in a comment) passes, as on main
  • Presidio holds up to 64 KB until a JSON object frame arrives
  • A failed stream with a non-object error frame logs as a success
  • Behind a down or failing Presidio a failed stream errors, where main sent partial text

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
Changes proxy guardrail streaming and SSE parsing for tool permissions and PII on Anthropic routes, with intentional breaking wire-format behavior on failed streams.

Overview
Mid-stream upstream failures on /v1/messages no longer become guardrail 400s. Assembly and guardrails now treat SSE more like real clients: skip data: payloads that are not JSON objects, detect error-only streams frame-by-frame, and optionally assemble content through an upstream error event via through_upstream_error.

Shared stream assembly adds helpers to extract upstream error frames, track unfinished/cut-off blocks (drop non-text cut-offs from what gets checked), and flag unreadable JSON events. assemble_anthropic_sse_stream can return partial content for guardrails while default callers still get None on failed streams.

Tool permission checks only what was delivered before the error, re-emits masked/denied responses without fake message_stop, and forwards the upstream error (or passes error-only streams through). Presidio waits for a classifiable JSON-object frame, refuses streams it cannot read for PII, and masks partial text before re-appending the error. anthropic_sse_chunks_from_response rebuilds failed streams with correct block open/close semantics and falls back to the upstream error alone when rewrite fails.

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

…nds in one

Raw-SSE guardrail stream hooks assembled the whole stream, and the Anthropic
chunk parser raises on an error event, so a stream the upstream ended with
event: error failed assembly. tool_permission then blocked it with a 400 that
hid the upstream error, bedrock and model_armor emitted a could-not-assemble
block, and presidio skipped masking.

Assembly now leaves the error events out, so the delivered content is checked
as usual and a clean stream passes through with its error frame. A rewritten
stream ends with the upstream error instead of a message_delta and
message_stop the upstream never sent. tool_permission also passes a stream of
only error frames, which carries no tool call to check.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@codspeed

codspeed Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 1 benchmark is dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 43 untouched benchmarks


Comparing paveln83:litellm_tool_permission_keep_stream_error_event (99425d5) with main (da71a03)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The changes affect Anthropic streaming when tool permissions or Presidio masking are enabled.

The code changes have no new blocking finding, but the required latest-commit live failure proof remains incomplete

Findings

  1. P2 Required live proof is missing ▶

Summary

This PR keeps upstream errors on failed /v1/messages streams while checking finished tool calls and masking readable text. The latest changes preserve Unicode inside error JSON, tighten which error frames count, and send only the upstream error when rebuilding fails

No new actionable issue was found in the changes since the previous review. The Unicode finding is fixed

mateo-berri accepted the existing Bedrock and Model Armor limitation as a separate follow-up because changing those hooks needs live tests against both services

  • Tool-permission streams keep the upstream error after checked content.
  • Presidio masks readable text before an upstream stream error.
  • Anthropic response rebuilding skips data payloads that are not JSON objects.

Reviews (12) · Last reviewed commit: "fix(guardrails): read an error frame as ..." · Reviewed by Greptile

try:
assembled: Final = build_complete_streaming_response(
all_chunks=(sse_stream,),
all_chunks=content_events,

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.

P2 Required live proof is missing

The repository requires the affected failure to succeed through a real provider at the latest product commit, c91c8e9c6f. The supplied after-fix failures use scripted upstreams. The latest real-provider runs fail before the first byte and do not reach this changed path. Add real-provider proof of the mid-stream error case before merging

Rule Used: Apply this rule only to PRs that fix LLM translation bugs or add LLM translation features. LLM translation means converting requests, responses, streaming events, tool calls, and errors between the API a caller uses on LiteLLM (any endpoint or SDK fu... (source)

@mateo-berri mateo-berri Oct 29, 2026 •

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.

Cases 10a to 10d and 11 relay real Claude Sonnet 5.5 streams from api.anthropic.com, which the relay cuts mid tool input with an injected overloaded_error

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.

You’re right that cases 10a–10d and 11 use real Anthropic-generated streams: the relay obtains Claude Sonnet 5.5 output from api.anthropic.com and then injects an overloaded_error mid-stream. That is live provider-backed E2E evidence for this bug; the injected failure is appropriate because a real overload is not reliably reproducible. My earlier statement that the relevant after-fix failures were only scripted was incorrect. The remaining question is whether those relay results were run at the latest product commit, c91c8e9c6f; the PR description says the cited relay cases were run on earlier commits, while later QA updates cover cases 14–15.

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.

QA for 10a, 10b and 11 ran at 1765df5. The later product change only touches streams with no error event, which no relay case sends

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.

Thanks—cases 10a, 10b, and 11 are live Anthropic-backed relay runs at 1765df54da, and they cover the no-denial path that drops a cut-off tool call. My earlier comment understated that evidence.

One distinction: the latest product commit, c91c8e9c6f, does not only affect streams without an error event. Its changes to Anthropic SSE re-emission apply when a stream ends in an upstream error and a guardrail rewrites it. The allow-all relay cases do not exercise that rewrite path. Case 10c does, but its QA is listed at an earlier commit; case 14 is listed at 8d0606f555 and uses a scripted upstream. So the existing relay proof covers the passthrough behavior, but not the rewritten error-stream behavior at c91c8e9c6f. A live-provider relay run for that rewrite case at the latest product commit would close the remaining gap.

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.

c91c8e9 is not the latest. Since 3db8b99, where 10c ran live, only the no-denial branch changed, and the denial rewrite code is identical

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.

You're right. I misidentified c91c8e9c6f as the latest product commit; it predates 3db8b99312. The later product change, 8d0606f555, is in the no-denial/cut-off-call path, and the denial-rewrite behavior covered by live case 10c was already present and tested at 3db8b99312. I retract my claim that the later change affected that rewrite path.

The only remaining distinction is commit alignment: the review rule requires live proof at the latest product commit (8d0606f555) or later. So the concern, if retained, is that case 10c's live run is from an earlier commit—not that the denial-rewrite path was untested.

@codecov

codecov Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.46524% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...roxy/guardrails/guardrail_hooks/tool_permission.py 88.88% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

…y an upstream error

tool_permission and Presidio now assemble an error-ended stream through the
error with an opt-in keyword, leaving out a tool call or thinking block the
upstream cut off. Logging, OpenTelemetry, Bedrock, and Model Armor keep the
old assembly. A rewrite drops the text block stop only when the upstream left
its text block open.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…ch rewritten block before the next starts

A failed stream holding a cut-off tool_use is now re-emitted through the rewrite, which leaves the call out and keeps the upstream error, so a denied call never reaches the client. The rewrite leaves its text block open only when it is the last block, and keeps a message_delta the upstream sent before failing. The new tool_permission tests no longer patch should_run_guardrail.
… sent, minus the cut-off tool call

Re-emitting such a stream through the rewrite sent an empty text block and stopped it, and Claude Code
does not retry a failed stream that shows a finished block, so it showed a mid-response error instead
of retrying. Dropping only the cut-off call's events keeps the stream as the upstream sent it.
…tream failed

Assembly leaves unfinished blocks out of the check only when the stream carries an upstream error
event, so a stream with an unfinished but allowed tool call and no error frame now reaches the client
as sent instead of losing a call the check already read
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

1 similar comment
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…eading a stream

A data line holding a bare JSON value such as 5 made the stream helpers call .get on an int, so tool_permission and Presidio answered 500 where main answered 400 or passed the stream through
@mateo-berri mateo-berri changed the title fix(guardrails): keep the upstream error when a /v1/messages stream ends in one fix(guardrails)!: keep the upstream error when a /v1/messages stream ends in one Oct 30, 2026
…es the same way everywhere

Run the skip for a data line that is not a JSON object through extract_sse_data and the assembler loop, so the usage fallback keeps a stream's tokens and the chat handler keeps its contract.

Presidio now holds a leading non-object frame until the first object frame, so the rest of the stream is still masked or blocked. An event: error frame now counts by its name, so a rewrite keeps it.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…y kind of tool call

A non-object JSON line with no Anthropic frame after it now gets a 400 from
Presidio before any data byte, since passing it would send text main refused.
A frame named error stays a normal event when its data is another Anthropic
event. server_tool_use and mcp_tool_use cut off by an upstream error are
dropped like tool_use, and a leading frame with empty data is relayed at once.
…ine and keep non-string error types out of the frozenset

Presidio now refuses a stream assembly cannot read when it holds a non-object
data line, instead of relaying it unmasked. Non-string event types no longer
crash a rewrite, and a CRLF stream that opens with a typed error is no longer
read as one error, so its tool calls are still checked.
… Presidio

Presidio passed PII at 200 where main answered 500 when the first read was
a JSON object with a list or dict type, or a JSON array with a character cut
at the end of the read. has_unreadable_json_event now reads both as data no
reader of these streams can take, so the first-frame check refuses them.
…omes before a Gemini stream

The first read then holds the unreadable line behind one Presidio can pass,
so the check has to look at every frame in it.
@veria-ai

veria-ai Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

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

Security review

No open security issues remain on this pull request.

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

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…ame is an error

A tool call split over data: lines beside one error frame read as error-only,
so tool_permission passed it, and an SDK joins those lines and reads the call.
The check now joins a frame's data lines and refuses anything but an error.
… could read a frame differently

Run 8 of the live risk pass showed each stream reader imitating a client and missing a shape: a
whitespace-led data line, an error key with no type, a split tool call after a plain message_start.
An error frame now has to be plain, and assembly past an error returns None for any frame a client
could read differently, so those streams keep main's refusal.
…ion read

A failed stream now reaches the client through the rewrite that already
serves a denial, followed by the upstream error, even when nothing is
denied. Raw frames could carry a tool call the check never read in shapes
such as a reused block index, mixed line ends, a tool in message_start,
interleaved deltas, or a form feed, and each refusal rule only moved the
search to the next shape.

The error frame goes out as its event name and first data line. An error
is found at CR, LF and CRLF line ends, and the rewrite adds no finished
block when it read no text, so Claude Code still retries the stream.
…e error alone when a rewrite cannot be built

A data-less event: error frame with junk after the name is an unknown event to both SDKs, so a healthy stream
stays raw. A finished tool call whose input is not JSON cannot be rebuilt, so a failed stream sends its upstream
error alone, and a healthy stream still raises as before.
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…ep its JSON whole

Only the last event line of a frame a blank line ended names an error, so a
healthy stream with a later event line or an unterminated error is no failed
stream. Any rebuild failure on a failed stream now sends the upstream error
alone with a warning, a param rule denies an input nested too deep, and a raw
line break inside a JSON error stays escaped so every reader gets it whole.
@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.


def _has_non_object_data(event_str: str) -> bool:
data_start: Final = event_str.find("data:")
return data_start != -1 and not event_str[data_start + len("data:") :].lstrip().startswith("{")

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.

Event skip uses substring data match

Medium Severity

_has_non_object_data and the fast-path skip locate data: with a raw substring search instead of the line-based field parse used by _sse_data_payload. A comment or earlier field that contains data: makes the whole frame look non-object, so assembly drops it. On a healthy stream tool_permission then sees no tool, returns the raw chunks, and a denied call in that frame can reach the client unchecked.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 99425d5. Configure here.

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.

This matches main, where the converter's same substring search hides that frame on a healthy stream. A failed stream now drops the hidden call

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

1 issue from previous review remains unresolved.

Fix All in Cursor

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 99425d5. 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 febd340 into BerriAI:main Oct 31, 2026
96 checks passed
r3ddyarun added a commit to ThirdLawEng/litellm that referenced this pull request Nov 9, 2026
…ream error

Upstream BerriAI#49088 made anthropic_sse_chunks_from_response re-emit a stream
that the upstream ended in an error event with that error again, never with
a message_delta or message_stop the upstream did not send. ThirdLaw rewrites
the native Messages body through anthropic_sse_chunks_from_body instead,
which still closed the message normally, so a rewrite hid the upstream error
and Claude Code did not retry.

anthropic_sse_chunks_from_body now takes the source chunks and shares the
ending logic with the response path. ThirdLaw passes the buffered stream.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K6wUmDJhvBeMaAGXcd2qWv
mika-lt pushed a commit to mika-lt/litellm that referenced this pull request Nov 25, 2026
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)
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