Repository navigation
fix(policy_engine): deliver guardrail text rewrites on multi-choice, unfinished, and envelope-less streams - #41933
Conversation
…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.
|
I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".
|
|
| 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
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 Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…text delta to carry the rewrite
|
bugbot run |
…list so legacy hook rewrites survive the model_dump round-trip
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 4fe1549. Configure here.
TLDR
Problem this solves:
n > 1How it solves it:
output_texteventsn = 1already uses: first delta full, later deltas blankUser Flow
Before: a proxy admin attaches a masking policy to chat completions, but a streamed request asking for two choices comes back unmasked
persimmonas[KEYWORD_REDACTED]and restarts the proxy"model": "gpt-4.1-mini", "stream": true, "n": 2and the prompt "Reply with exactly the word persimmon and nothing else."pers,im,monand choice 1 deltaspers,im,mon: both choices spellpersimmon, nothing is masked"n": 1, or with"stream": false, comes back masked, so only the streamed multi-choice shape leaksAfter: the same two-choice stream comes back masked on both choices
"stream": true, "n": 2[KEYWORD_REDACTED]as the first content delta of choice 0 and of choice 1, and the remaining content deltas of each choice are empty"n": 1and"stream": falserequests come back masked exactly as beforeRelevant issues
Affected release
Linear ticket
Resolves LIT-7178
Test expectation changes
Each of these tests asserted the fail-open
UndeliverableStreamRewritefor 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_closedbecomes..._lands_on_the_rewritten_choice_onlyplus..._rewrites_each_choice_with_its_own_text: a two-choice chat stream now gets each choice's own rewritetest_anthropic_guardrail_handler.py::test_unended_stream_rewrite_with_delivery_expected_fails_closedbecomes..._lands_in_the_buffered_deltas: a Messages stream with nomessage_stopnow gets the rewrite in its text deltastest_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_closedbecome their..._lands_in_the_delta_and_done_events,..._spreads_over_the_deltas, and..._syncs_every_text_eventforms: a Responses stream with noresponseenvelope now gets the rewrite in itsoutput_texteventsThe fail-open contract itself is still covered:
test_deliver_ended_stream_tool_call_rewrite_on_multi_choice_stream_fails_closed(tool-call rewrites onn > 1) is unchanged,test_fallback_rewrite_over_an_unplaceable_scanned_event_fails_openis new for a Responses stream whose scanned text sits on an event the spread cannot place, andtest_unended_stream_rewrite_with_no_text_delta_to_carry_it_fails_openis 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_streamis new for thestream_options.include_usageshape, where the last chunk carries no choicestest_guardrail_pipeline.py::test_streaming_iterator_hook_delivers_legacy_hook_rewrite_on_every_choiceis new: a guardrail that still rewrites throughasync_post_call_success_hook(which dumps and rebuilds the response) gets its rewrite delivered on both choices of a two-choice stream.test_moderations.pyandtest_openai_moderation_streaming.pyonly gainindex = 0on their mocked stream choices, the field every real streaming choice carries; their expectations are unchangedPre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
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@greptileaito 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 2on a random port, no database, the config below, and every request sent with the master key. Real OpenAI and Anthropic callsRequest used in the chat cases (only
n,stream, andstream_optionsvary):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) orresponse.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 throughapi_base:claude-haiku-4-5-cut(anthropic/claude-haiku-4-5,api_base: http://127.0.0.1:$RELAY/anthropic) andgpt-4.1-mini-cut(openai/gpt-4.1-mini,api_base: http://127.0.0.1:$RELAY/openai/v1). Requests used:Before (12ddb35)
Streamed, n=2
choicesper chunk, in order:Both choices spell
persimmon; the mask never lands, and the proxy log carries the "rewrite was discarded and the original stream released" warningStreamed, n=2,
"stream_options":{"include_usage":true}"stream_options":{"include_usage":true}persimmon, then the finish chunk and a closing chunk with"choices":[]and"usage":{"completion_tokens":6,...}Streamed, n=1 (control)
"n":1[KEYWORD_REDACTED], every later content delta is""Not streamed, n=2 (control)
"stream":falsechoices[].message.contentare[KEYWORD_REDACTED]Other endpoints (controls)
POST /v1/responseswith"stream":trueongpt-4.1-miniand onclaude-haiku-4-5: the firstresponse.output_text.deltacarries[KEYWORD_REDACTED], later deltas"", andresponse.output_text.doneplus theresponse.completedenvelope carry[KEYWORD_REDACTED]POST /v1/messageswith"stream":trueonclaude-haiku-4-5and ongpt-4.1-mini: the firsttext_deltacarries[KEYWORD_REDACTED], later deltas"",message_stopcloses the streamkumquat) on then=2chat stream, then=1chat stream, and the native Messages stream: 400 withContent blocked: keyword 'kumquat' detectedUnfinished Messages stream (relay-cut)
/v1/messagesrequest above onclaude-haiku-4-5-cut, status 200message_start,content_block_start,ping, then:and ends there: no
message_delta, nomessage_stop. The deltas spellpersimmon, and the proxy log carries the "rewrite was discarded and the original stream released" warningEnvelope-less Responses stream (relay-cut)
/v1/responsesrequest above ongpt-4.1-mini-cut, status 200no
response.completedenvelope. The text spellspersimmon, and the proxy log carries the same discarded-rewrite warningFinished streams on the same proxy (controls)
The same two requests on
claude-haiku-4-5andgpt-4.1-mini(not through the relay) end withmessage_stopandresponse.completedand come back masked, so the leak is specific to the cut streamsAfter (4fe1549)
Streamed, n=2
choicesper chunk, in order:Both choices carry
[KEYWORD_REDACTED]in their first content delta and nothing after it; the proxy log has no "rewrite was discarded" warningStreamed, n=2,
"stream_options":{"include_usage":true}"stream_options":{"include_usage":true}"choices":[]and"usage":{"completion_tokens":6,...}intactStreamed, n=1 (control)
"n":1[KEYWORD_REDACTED], every later content delta is"", unchanged from BeforeNot streamed, n=2 (control)
"stream":falsechoices[0].message.contentandchoices[1].message.contentare both[KEYWORD_REDACTED], unchanged from BeforeOther 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)
/v1/messagesrequest onclaude-haiku-4-5-cut, status 200message_start,content_block_start,ping, then:and ends there, still with no
message_deltaormessage_stop. The first text delta carries[KEYWORD_REDACTED], the second is empty, and the proxy log has no discarded-rewrite warningEnvelope-less Responses stream (relay-cut)
/v1/responsesrequest ongpt-4.1-mini-cut, status 200still no
response.completedenvelope; the mask lands in the first delta and indone, and the proxy log has no discarded-rewrite warningFinished streams on the same proxy (controls)
The same two requests on
claude-haiku-4-5andgpt-4.1-miniend withmessage_stopandresponse.completedand come back masked, unchanged from BeforeObserved next to the fix, same on both legs, left alone by this PR:
n=2chat stream ends with one finish chunk, index 0 onlyType
🐛 Bug Fix
Caveats (if any)
Low
n > 1streams 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 purposen = 1already hadn > 1stream 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 theinclude_usagecase above shows, and no guardrail reads usage todaylitellm_utils_testingontest_models_by_provider(since feat(proxy): add Amazon Transcribe pass-through with completion-time job pricing #41515),integration-providersontest_retry_counts_and_public_errors_match_actual_provider_attempts(since fix(responses): emit typed streaming failure events #40243), andproxy_e2e_anthropic_messages_testson bothtest_bedrock_invoke_messages_with_all_beta_headerscases (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