Skip to content

fix(policy_engine): deliver guardrail text rewrites on multi-choice, unfinished, and envelope-less streams - #41933

Merged
mateo-berri merged 3 commits into
mainfrom
litellm_deliver_multi_choice_stream_rewrites
Sep 19, 2026
Merged

mateo-berri merged 3 commits into
mainfrom
litellm_deliver_multi_choice_stream_rewrites

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Post-call guardrail rewrites were dropped on streamed chat requests with n > 1
  • A stream cut off before its finish marker dropped the rewrite too
  • A Responses stream with no final envelope dropped it as well
  • Each case failed open: the raw model text reached the client

How it solves it:

  • The ended chat stream is rebuilt one choice index at a time
  • Each choice's rewrite lands on that choice's own buffered deltas
  • An unfinished Messages stream gets the rewrite spread over its text deltas
  • An envelope-less Responses stream gets it spread over its output_text events
  • Spread shape stays the one n = 1 already uses: first delta full, later deltas blank

User Flow

Before: a proxy admin attaches a masking policy to chat completions, but a streamed request asking for two choices comes back unmasked

  1. The admin attaches a post-call content filter that masks the word persimmon as [KEYWORD_REDACTED] and restarts the proxy
  2. A developer sends POST https://litellm-domain/v1/chat/completions with "model": "gpt-4.1-mini", "stream": true, "n": 2 and the prompt "Reply with exactly the word persimmon and nothing else."
  3. The 200 SSE stream carries choice 0 deltas pers, im, mon and choice 1 deltas pers, im, mon: both choices spell persimmon, nothing is masked
  4. The same request with "n": 1, or with "stream": false, comes back masked, so only the streamed multi-choice shape leaks

After: the same two-choice stream comes back masked on both choices

  1. The admin attaches the same post-call content filter and restarts the proxy
  2. The developer sends the same POST https://litellm-domain/v1/chat/completions with "stream": true, "n": 2
  3. The 200 SSE stream carries [KEYWORD_REDACTED] as the first content delta of choice 0 and of choice 1, and the remaining content deltas of each choice are empty
  4. The "n": 1 and "stream": false requests come back masked exactly as before

Relevant issues

Affected release

Linear ticket

Resolves LIT-7178

Test expectation changes

Each of these tests asserted the fail-open UndeliverableStreamRewrite for a shape this PR now delivers, so its expectation flips to the delivered rewrite:

  • test_openai_guardrail_handler.py::test_deliver_ended_stream_rewrite_on_multi_choice_stream_fails_closed becomes ..._lands_on_the_rewritten_choice_only plus ..._rewrites_each_choice_with_its_own_text: a two-choice chat stream now gets each choice's own rewrite
  • test_anthropic_guardrail_handler.py::test_unended_stream_rewrite_with_delivery_expected_fails_closed becomes ..._lands_in_the_buffered_deltas: a Messages stream with no message_stop now gets the rewrite in its text deltas
  • test_openai_responses_guardrail_handler.py::test_fallback_rewrite_with_delivery_expected_fails_closed, ::test_fallback_delta_only_rewrite_with_delivery_expected_fails_closed, and ::test_output_item_done_last_rewrite_with_delivery_expected_fails_closed become their ..._lands_in_the_delta_and_done_events, ..._spreads_over_the_deltas, and ..._syncs_every_text_event forms: a Responses stream with no response envelope now gets the rewrite in its output_text events

The fail-open contract itself is still covered: test_deliver_ended_stream_tool_call_rewrite_on_multi_choice_stream_fails_closed (tool-call rewrites on n > 1) is unchanged, test_fallback_rewrite_over_an_unplaceable_scanned_event_fails_open is new for a Responses stream whose scanned text sits on an event the spread cannot place, and test_unended_stream_rewrite_with_no_text_delta_to_carry_it_fails_open is new for a Messages stream cut off before any text delta, where a guardrail that turns empty text into something has nowhere to land it. test_deliver_ended_stream_rewrites_every_choice_when_a_usage_only_chunk_closes_the_stream is new for the stream_options.include_usage shape, where the last chunk carries no choices

test_guardrail_pipeline.py::test_streaming_iterator_hook_delivers_legacy_hook_rewrite_on_every_choice is new: a guardrail that still rewrites through async_post_call_success_hook (which dumps and rebuilds the response) gets its rewrite delivered on both choices of a two-choice stream. test_moderations.py and test_openai_moderation_streaming.py only gain index = 0 on their mocked stream choices, the field every real streaming choice carries; their expectations are unchanged

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/test_litellm/<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
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

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

Shared setup for both legs: proxy booted from the worktree with --num_workers 2 on a random port, no database, the config below, and every request sent with the master key. Real OpenAI and Anthropic calls

model_list:
  - model_name: gpt-4.1-mini
    litellm_params:
      model: openai/gpt-4.1-mini
      api_key: os.environ/OPENAI_API_KEY
  - model_name: claude-haiku-4-5
    litellm_params:
      model: anthropic/claude-haiku-4-5
      api_key: os.environ/ANTHROPIC_API_KEY

guardrails:
  - guardrail_name: output-word-filter
    litellm_params:
      guardrail: litellm_content_filter
      mode: post_call
      blocked_words:
        - keyword: kumquat
          action: BLOCK
        - keyword: persimmon
          action: MASK

policies:
  response-governance:
    guardrails:
      add:
        - output-word-filter
    pipeline:
      mode: post_call
      steps:
        - guardrail: output-word-filter
          on_pass: allow
          on_fail: block

policy_attachments:
  - policy: response-governance
    scope: global

Request used in the chat cases (only n, stream, and stream_options vary):

curl -sS -N http://localhost:$PORT/v1/chat/completions \
  -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' \
  -d '{"model":"gpt-4.1-mini","stream":true,"n":2,"messages":[{"role":"user","content":"Reply with exactly the word persimmon and nothing else."}]}'

Cut-stream setup for the unfinished and envelope-less cases: no provider ends a stream early on demand, so a small relay on localhost forwards each request to the real provider unchanged, streams the provider's SSE back, and closes the stream cleanly right after content_block_stop (Anthropic) or response.output_text.done (OpenAI). The model calls are real and paid; only the tail of the stream is dropped. Two extra deployments on the same config point at it through api_base: claude-haiku-4-5-cut (anthropic/claude-haiku-4-5, api_base: http://127.0.0.1:$RELAY/anthropic) and gpt-4.1-mini-cut (openai/gpt-4.1-mini, api_base: http://127.0.0.1:$RELAY/openai/v1). Requests used:

curl -sS -N http://localhost:$PORT/v1/messages \
  -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' \
  -d '{"model":"claude-haiku-4-5-cut","stream":true,"max_tokens":64,"messages":[{"role":"user","content":"Reply with exactly the word persimmon and nothing else."}]}'

curl -sS -N http://localhost:$PORT/v1/responses \
  -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json' \
  -d '{"model":"gpt-4.1-mini-cut","stream":true,"input":"Reply with exactly the word persimmon and nothing else."}'

Before (12ddb35)

Streamed, n=2

  1. Sent the request above
  2. Observed choices per chunk, in order:
[{"index":0,"delta":{"content":"","role":"assistant"}}]
[{"index":0,"delta":{"content":"pers"}}]
[{"index":0,"delta":{"content":"im"}}]
[{"index":0,"delta":{"content":"mon"}}]
[{"index":1,"delta":{"content":"pers"}}]
[{"index":1,"delta":{"content":"im"}}]
[{"index":1,"delta":{"content":"mon"}}]
[{"finish_reason":"stop","index":0,"delta":{}}]

Both choices spell persimmon; the mask never lands, and the proxy log carries the "rewrite was discarded and the original stream released" warning

Streamed, n=2, "stream_options":{"include_usage":true}

  1. Same request plus "stream_options":{"include_usage":true}
  2. Same seven content chunks as above, both choices spelling persimmon, then the finish chunk and a closing chunk with "choices":[] and "usage":{"completion_tokens":6,...}

Streamed, n=1 (control)

  1. Same request with "n":1
  2. First content delta is [KEYWORD_REDACTED], every later content delta is ""

Not streamed, n=2 (control)

  1. Same request with "stream":false
  2. Both choices[].message.content are [KEYWORD_REDACTED]

Other endpoints (controls)

  1. POST /v1/responses with "stream":true on gpt-4.1-mini and on claude-haiku-4-5: the first response.output_text.delta carries [KEYWORD_REDACTED], later deltas "", and response.output_text.done plus the response.completed envelope carry [KEYWORD_REDACTED]
  2. POST /v1/messages with "stream":true on claude-haiku-4-5 and on gpt-4.1-mini: the first text_delta carries [KEYWORD_REDACTED], later deltas "", message_stop closes the stream
  3. BLOCK (kumquat) on the n=2 chat stream, the n=1 chat stream, and the native Messages stream: 400 with Content blocked: keyword 'kumquat' detected

Unfinished Messages stream (relay-cut)

  1. Sent the /v1/messages request above on claude-haiku-4-5-cut, status 200
  2. The stream carries message_start, content_block_start, ping, then:
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"pers"} }

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

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

and ends there: no message_delta, no message_stop. The deltas spell persimmon, and the proxy log carries the "rewrite was discarded and the original stream released" warning

Envelope-less Responses stream (relay-cut)

  1. Sent the /v1/responses request above on gpt-4.1-mini-cut, status 200
  2. Event types in order, with the text each carries:
response.created
response.in_progress
response.output_item.added
response.content_part.added
response.output_text.delta   "pers"
response.output_text.delta   "im"
response.output_text.delta   "mon"
response.output_text.done    "persimmon"
data: [DONE]

no response.completed envelope. The text spells persimmon, and the proxy log carries the same discarded-rewrite warning

Finished streams on the same proxy (controls)

The same two requests on claude-haiku-4-5 and gpt-4.1-mini (not through the relay) end with message_stop and response.completed and come back masked, so the leak is specific to the cut streams

After (4fe1549)

Streamed, n=2

  1. Sent the request above
  2. Observed choices per chunk, in order:
[{"index":0,"delta":{"content":"[KEYWORD_REDACTED]","role":"assistant"}}]
[{"index":0,"delta":{"content":""}}]
[{"index":0,"delta":{"content":""}}]
[{"index":0,"delta":{"content":""}}]
[{"index":1,"delta":{"content":"[KEYWORD_REDACTED]"}}]
[{"index":1,"delta":{"content":""}}]
[{"index":1,"delta":{"content":""}}]
[{"finish_reason":"stop","index":0,"delta":{}}]

Both choices carry [KEYWORD_REDACTED] in their first content delta and nothing after it; the proxy log has no "rewrite was discarded" warning

Streamed, n=2, "stream_options":{"include_usage":true}

  1. Same request plus "stream_options":{"include_usage":true}
  2. Same eight chunks as above, both choices masked, then the closing chunk with "choices":[] and "usage":{"completion_tokens":6,...} intact

Streamed, n=1 (control)

  1. Same request with "n":1
  2. First content delta is [KEYWORD_REDACTED], every later content delta is "", unchanged from Before

Not streamed, n=2 (control)

  1. Same request with "stream":false
  2. choices[0].message.content and choices[1].message.content are both [KEYWORD_REDACTED], unchanged from Before

Other endpoints (controls)

The Responses streams on both models, the Messages streams on both models, and the three BLOCK cases come back with the same event shapes and the same masked or blocked text as Before

Unfinished Messages stream (relay-cut)

  1. Same /v1/messages request on claude-haiku-4-5-cut, status 200
  2. Same message_start, content_block_start, ping, then:
event: content_block_delta
data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "[KEYWORD_REDACTED]"}}

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

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

and ends there, still with no message_delta or message_stop. The first text delta carries [KEYWORD_REDACTED], the second is empty, and the proxy log has no discarded-rewrite warning

Envelope-less Responses stream (relay-cut)

  1. Same /v1/responses request on gpt-4.1-mini-cut, status 200
  2. Event types in order, with the text each carries:
response.created
response.in_progress
response.output_item.added
response.content_part.added
response.output_text.delta   "[KEYWORD_REDACTED]"
response.output_text.delta   ""
response.output_text.delta   ""
response.output_text.done    "[KEYWORD_REDACTED]"
data: [DONE]

still no response.completed envelope; the mask lands in the first delta and in done, and the proxy log has no discarded-rewrite warning

Finished streams on the same proxy (controls)

The same two requests on claude-haiku-4-5 and gpt-4.1-mini end with message_stop and response.completed and come back masked, unchanged from Before

Observed next to the fix, same on both legs, left alone by this PR:

  • n=2 chat stream ends with one finish chunk, index 0 only
  • Cut Messages stream ends silently, no error event on either leg

Type

🐛 Bug Fix

Caveats (if any)

Low

  • Tool-call rewrites on n > 1 streams still fail open, exactly as before this PR. The ticket asks for text rewrites, a guardrail that rewrites tool-call arguments on a multi-choice stream has not come up, and stitching argument JSON per choice is its own change, so it stays out of this PR on purpose
  • A Responses stream with no envelope whose scanned text mixes in a reasoning-summary, refusal, or tool-argument delta still fails open, tracked in LIT-8166. That shape needs a decision on where each kind of text goes back, which is that ticket's call rather than something to pick silently here
  • The rewrite always lands whole in the first delta of each part, later deltas blank, the same shape n = 1 already had
  • For an n > 1 stream the stitched response the guardrail scans carries the token usage of choice 0's chunks only; the usage chunk the client receives is the provider's own and untouched, as the include_usage case above shows, and no guardrail reads usage today
  • Three CircleCI jobs are red at this tip on tests this PR does not touch, and main's own scheduled pipelines 89818 and 89834 fail the same three the same way, each already tracked: litellm_utils_testing on test_models_by_provider (since feat(proxy): add Amazon Transcribe pass-through with completion-time job pricing #41515), integration-providers on test_retry_counts_and_public_errors_match_actual_provider_attempts (since fix(responses): emit typed streaming failure events #40243), and proxy_e2e_anthropic_messages_tests on both test_bedrock_invoke_messages_with_all_beta_headers cases (LIT-8149, since fix(anthropic): register thinking-binding-controls-2026-08-01 in beta headers config #41203)

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

  • 4fe1549 passes /live-pr-risk

…unfinished, and envelope-less streams

Post-call pipeline rewrites on buffered streams failed open on three shapes:
chat streams with n > 1 (the rebuilt response collapsed every choice into
index 0), streams that ended without a finish marker, and Responses streams
whose final event carried no response envelope.

The chat handler now rebuilds the ended stream one choice index at a time and
writes each choice's rewrite back to that choice's buffered deltas. The
Anthropic handler writes an unended stream's rewrite across its text deltas.
The Responses handler spreads an envelope-less rewrite over the buffered
output_text events, still failing open when a scanned event cannot be placed.

Tool-call rewrites on n > 1 chat streams keep failing open.
@devin-ai-integration

devin-ai-integration Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@codspeed

codspeed Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_deliver_multi_choice_stream_rewrites (4fe1549) with main (5611607)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

The PR appears safe to merge; no outstanding correctness or repository-rule violations were identified.

Findings

  1. P1 Valid stream rewrites are discarded ▶

Summary

This PR ensures post-call guardrail text rewrites are delivered across additional streaming response shapes.

  • Rebuilds OpenAI chat streams per choice so multi-choice rewrites remain correctly attributed.
  • Writes rewrites into buffered Anthropic text deltas even when the stream lacks a terminal marker.
  • Spreads envelope-less OpenAI Responses rewrites across placeable output-text events while preserving fail-open handling for mixed, unplaceable content.
  • Adds focused unit and pipeline coverage for the newly supported stream shapes.

Reviews (3) · Last reviewed commit: "fix(policy_engine): keep the per-choice ..."

Comment on lines +1020 to +1021
if len(placeable_positions) != len(scanned_positions) or any(
stream_item_field(event, "type") not in _OUTPUT_TEXT_EVENT_TYPES for event in scanned_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.

P1 Valid stream rewrites are discarded

For envelope-less streams containing reasoning or tool-argument deltas, the fallback scans those deltas but rejects the resulting rewrite here. The policy executor then restores the original buffered events, so the client receives the unguarded text instead of the guardrail rewrite.

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.

That scanned string mixes reasoning or tool-argument text with output text, so no single event can carry the rewrite; those streams keep today's fail-open (LIT-8166)

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. When the fallback input includes reasoning or tool-argument text alongside output text, the rewrite cannot be safely mapped back to only response.output_text.* events, especially when the rewrite changes length or crosses event boundaries. The explicit placeability check correctly preserves the existing fail-open behavior for that LIT-8166 shape; my comment does not identify a bug in this change.

@codecov

codecov Bot commented Sep 19, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri mateo-berri added run-ci and removed run-ci labels Sep 19, 2026
@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.

…list so legacy hook rewrites survive the model_dump round-trip
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@mateo-berri mateo-berri added run-ci and removed run-ci labels Sep 19, 2026

@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 4fe1549. 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 5f1268c into main Sep 19, 2026
141 of 145 checks passed
@mateo-berri
mateo-berri deleted the litellm_deliver_multi_choice_stream_rewrites branch September 19, 2026 07:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant