Skip to content

feat(policy_engine): execute post_call guardrail pipelines on streaming responses - #38788

Merged
mateo-berri merged 7 commits into
litellm_fix_post_call_policy_pipelinefrom
litellm_post_call_pipeline_streaming
Aug 29, 2026
Merged

mateo-berri merged 7 commits into
litellm_fix_post_call_policy_pipelinefrom
litellm_post_call_pipeline_streaming

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Stacked on #38721 (base branch litellm_fix_post_call_policy_pipeline), so this PR's diff shows only the streaming work

Now merged into that stack branch, so this content rides #38721 into litellm_internal_staging; the merge landed ahead of a reviewer approval through an auto-merge arming slip on the unprotected stack branch, and the combined change gets its review on #38721, which staging's approval rule gates

Problem this solves:

  • Policies with post_call pipeline steps rejected every streaming request with 400
  • Streaming clients were locked out of every policy-governed model

How it solves it:

  • Buffers the stream, runs the pipeline verdict, then releases it
  • Allow releases the buffered chunks as the endpoint translation left them (the Responses and A2A translations write guardrail output back into the final chunk, same as flat post_call guardrails); block ends the stream with the block error
  • Background requests keep the upfront 400 (output scanning never runs for them)
  • Only pipelines whose guardrails cannot scan output keep the upfront 400, now naming them
  • Pipeline steps that rewrite streamed output (mask_response_content, a litellm_content_filter MASK action (blocked word, pattern, or category), streaming_transform_mode: incremental_diff) also keep an upfront 400 naming them, since the pipeline path would release the unmodified stream; LIT-6487 tracks applying those rewrites on streams
  • A rewrite the upfront check cannot see, decided by the guardrail at runtime (Bedrock's ANONYMIZED action, a remote masking API), is caught at the apply_guardrail seam: each streaming step runs behind a rewrite observer, and any changed output withholds the buffered stream with a 400 naming the policy and guardrail, regardless of the step's on_fail/on_error routing

User Flow

Before: a platform admin attaches a policy whose pipeline scans model output, and every developer streaming from a governed model gets rejected up front

  1. The admin attaches policy response-governance, whose pipeline scans model output, to the gateway
  2. A developer sends POST https://litellm-domain/v1/chat/completions with "stream": true
  3. HTTP 400 comes back instantly: "Policies with post_call guardrail pipelines cannot govern streaming or background responses yet: response-governance. Retry with stream=false..."
  4. POST https://litellm-domain/v1/responses and POST https://litellm-domain/v1/messages with "stream": true return the same 400
  5. Only "stream": false requests get answers, so every streaming app is locked out of governed models

After: the same streaming requests run, and the policy pipeline governs the streamed output

  1. The admin attaches the same response-governance policy
  2. The developer sends POST https://litellm-domain/v1/chat/completions with "stream": true
  3. Clean output arrives as a normal SSE stream ending in data: [DONE] with HTTP 200; the chunks arrive together once the model finishes, since the gateway holds the stream until the policy verdict
  4. Output the policy blocks comes back as HTTP 400 with a single SSE error frame: "Content blocked: keyword 'kumquat' detected"
  5. POST https://litellm-domain/v1/responses and POST https://litellm-domain/v1/messages with "stream": true behave the same way: clean streams flow, violating streams get the 400 block
  6. "background": true requests still get an upfront 400, since output scanning never runs for those
  7. A policy whose pipeline step masks output (mask_response_content: true, a litellm_content_filter MASK rule (blocked word, pattern, or category), or streaming_transform_mode: incremental_diff) still gets an upfront HTTP 400 on "stream": true, now naming that guardrail and pointing at stream=false or guardrails.add as the way to keep the masking
  8. "stream": true on a route the guardrail translation map does not cover gets an upfront HTTP 400 naming the route, instead of the model running and the stream being withheld afterwards
  9. A pipeline guardrail that passes the upfront check but rewrites the streamed output at runtime (a remote masking API, Bedrock's ANONYMIZED action) gets HTTP 400 withholding the buffered stream, naming the policy and guardrail, instead of the unmasked stream being released

Relevant issues

Linear ticket

Resolves LIT-6441

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

Live proxy, real OpenAI gpt-5.4-mini. Config: litellm_content_filter guardrail output-word-filter (kumquat BLOCK) plus policy response-governance with a post_call pipeline step (on_pass allow, on_fail block), scope *. Proxy: python litellm/proxy/proxy_cli.py --config qa6441/config.yaml --port <port> --num_workers 2, KEY = the master key

Before (c64318c)

/v1/chat/completions streaming

  1. curl -s -w '\nHTTP %{http_code}' http://localhost:37228/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"gpt-5.4-mini","messages":[{"role":"user","content":"Say the word kumquat"}],"stream":true}'
  2. HTTP 400 upfront, no stream: {"error":{"message":"Policies with post_call guardrail pipelines cannot govern streaming or background responses yet: response-governance. Retry with stream=false and background=false, or move these policies' output guardrails from pipeline steps to guardrails.add, which scans streamed output.","type":"guardrail_pipeline_error","policies":["response-governance"]}}

/v1/responses streaming

  1. Same request shape ({"model":"gpt-5.4-mini","input":"Say the word kumquat","stream":true})
  2. HTTP 400 upfront with the same guardrail_pipeline_error body

/v1/messages streaming

  1. Same request shape ({"model":"gpt-5.4-mini","max_tokens":100,"messages":[...],"stream":true})
  2. HTTP 400 upfront with the same message in the Anthropic error envelope

Non-streaming control

  1. Same kumquat prompt with no stream
  2. HTTP 400 "Content blocked: keyword 'kumquat' detected" (the pipeline itself works; only streaming was locked out)

After (tip 2247fbc)

/v1/chat/completions streaming

  1. Same kumquat request as Before
  2. HTTP 400 delivered as an SSE error frame, then data: [DONE]: data: {"error": {"message": "Content blocked: keyword 'kumquat' detected", ..., "guardrail_name": "output-word-filter", "guardrail_mode": "post_call"}} (the pipeline governed the stream instead of rejecting it upfront)
  3. Benign prompt ("say hello", "stream":true): HTTP 200, full SSE stream released, data: [DONE]

/v1/responses streaming

  1. Same kumquat request: HTTP 400 with the same SSE block frame
  2. Benign prompt: HTTP 200, complete event sequence response.created through response.completed, data: [DONE]

/v1/messages streaming

  1. Same kumquat request: HTTP 400 with the same SSE block frame
  2. Benign prompt: HTTP 200, full Anthropic SSE message_start through message_stop

MASK action pipeline step, three checkpoints

Config qa6441/config_mask.yaml: the same guardrail with a second rule, persimmon MASK with [KEYWORD_REDACTED], as the only step of the same pipeline, scope *. Prompt: "Reply with exactly this sentence and nothing else: I like persimmon pie"

Checkpoint stream=true (chat, responses, messages) stream=false
Merge base c64318c HTTP 400 upfront, generic message HTTP 200 "I like [KEYWORD_REDACTED] pie"
d51198f HTTP 200, " pers", "im", "mon" deltas released unmasked on all three routes (the leak) HTTP 200 "I like [KEYWORD_REDACTED] pie"
0c1f33d HTTP 400 upfront naming output-word-filter on all three routes, benign prompts included HTTP 200 "I like [KEYWORD_REDACTED] pie"
Tip 2247fbc same HTTP 400 upfront on all three routes, benign prompts included HTTP 200 "I like [KEYWORD_REDACTED] pie"

Tip stream=true body: {"error":{"message":"Policies with post_call guardrail pipelines cannot govern streaming responses because these pipeline guardrails rewrite streamed content (mask_response_content, a MASK action, or streaming_transform_mode=incremental_diff), which pipeline steps would release unmodified: output-word-filter. Retry with stream=false, or drop them from the pipeline steps so guardrails.add applies them to streamed output.","type":"guardrail_pipeline_error","policies":["response-governance"],"guardrails":["output-word-filter"]}}

guardrails.add control at the tip (qa6441/config_flat.yaml, same guardrail with default_on: true, no policy): the chat stream comes back HTTP 200 as one masked chunk "I like [KEYWORD_REDACTED] pie" through the guardrail's own streaming iterator hook, which pipeline-managed guardrails skip, so d51198f dropped a rewrite the flat path honors; responses and messages streams are HTTP 200 unmasked on the flat path too (block-only there), and non-stream masks on both paths

MASK action from a category, two checkpoints

Config qa6441/config_category.yaml: guardrail output-category-filter (litellm_content_filter, mode post_call, categories: [{category: bias_gender, enabled: true, action: MASK}]) as the only step of the same pipeline, scope *. Prompt: "Reply with exactly this sentence and nothing else: The man walked home". Category actions live in category_keywords and always_block_category_keywords, which the 0c1f33d check did not read

Checkpoint stream=true (chat, responses, messages) stream=false
c5bcf3a (first push) HTTP 200, " man" delta released unmasked on all three routes (the leak) HTTP 200 "The [KEYWORD_REDACTED] walked home"
Tip 2247fbc HTTP 400 upfront naming output-category-filter on all three routes, benign prompts included HTTP 200 "The [KEYWORD_REDACTED] walked home"

Non-streaming and background controls

  1. Non-streaming kumquat: HTTP 400 "Content blocked: keyword 'kumquat' detected" (unchanged)
  2. /v1/responses with "background": true: HTTP 400 upfront "Policies with post_call guardrail pipelines cannot govern background responses: response-governance. Retry with background=false."
  3. Pre_call pipeline control (qa6441/config_precall.yaml, the word filter as a pre_call pipeline step): kumquat request gets HTTP 400 "Content blocked: keyword 'kumquat' detected" (guardrail_mode: pre_call) on stream and non-stream alike, benign prompts get HTTP 200 both ways, untouched by the streaming work

Content-rewriting pipeline step, three checkpoints

Config qa6441/config_rewrite.yaml: a generic_guardrail_api guardrail pii-masker (mode post_call, streaming_transform_mode: incremental_diff, api_base pointing at a local stand-in that rewrites "persimmon" to "[MASKED]" and answers GUARDRAIL_INTERVENED) as the single pipeline step of policy response-masking, scope *. Same two curls at every checkpoint, prompt "Reply with exactly this sentence and nothing else: I like persimmon pie", once with "stream": true and once with "stream": false

Checkpoint stream=true stream=false
Merge base c64318c HTTP 400 upfront, generic message, stand-in never called HTTP 200 "I like [MASKED] pie"
c5bcf3a (first push) HTTP 200, deltas " pers", "im", "mon" released while the stand-in logged intervened=True (the leak) HTTP 200 "I like [MASKED] pie"
Tip 2247fbc HTTP 400 upfront naming pii-masker, stand-in never called HTTP 200 "I like [MASKED] pie", stand-in logged intervened=True

Tip stream=true body: {"error":{"message":"Policies with post_call guardrail pipelines cannot govern streaming responses because these pipeline guardrails rewrite streamed content (mask_response_content, a MASK action, or streaming_transform_mode=incremental_diff), which pipeline steps would release unmodified: pii-masker. Retry with stream=false, or drop them from the pipeline steps so guardrails.add applies them to streamed output.","type":"None","param":"None","code":"400","provider_specific_fields":{"error":{"message":"Policies with post_call guardrail pipelines cannot govern streaming responses because these pipeline guardrails rewrite streamed content (mask_response_content, a MASK action, or streaming_transform_mode=incremental_diff), which pipeline steps would release unmodified: pii-masker. Retry with stream=false, or drop them from the pipeline steps so guardrails.add applies them to streamed output.","type":"guardrail_pipeline_error","policies":["response-masking"],"guardrails":["pii-masker"]}}}}

The c5bcf3a row ran single-worker; the Before and After legs and the other table rows ran proxies with --num_workers 2

Runtime-detected rewrite, two checkpoints

Config qa6441/config_runtime_mask.yaml: the same pii-masker stand-in guardrail with no streaming_transform_mode and no mask config, so the upfront rewrite check has nothing to flag; whether the API rewrites is only visible at runtime, the same shape as Bedrock's ANONYMIZED action. Same prompt, all three streaming routes

Checkpoint stream=true (chat, responses, messages) stream=false
90c8031 HTTP 200, "I like persimmon pie" released unmasked on all three routes while the stand-in logged intervened=True (the leak) HTTP 200 "I like [MASKED] pie"
Tip 2247fbc HTTP 400 SSE error frame on all three routes naming policy response-masking and guardrail pii-masker; benign prompt streams HTTP 200 HTTP 200 "I like [MASKED] pie", stand-in intervened=True

Tip stream=true frame: data: {"error": {"message": "Streaming response withheld by policy pipeline 'response-masking' because guardrail 'pii-masker' rewrote the streamed output, and streaming pipelines cannot deliver rewrites. Retry with stream=false, or drop it from the pipeline steps so guardrails.add applies it to streamed output.", ..., "type": "guardrail_pipeline_error", "policies": ["response-masking"], "guardrails": ["pii-masker"]}}

Unit regression: 27 new tests (19 in tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py, 6 in tests/test_litellm/proxy/guardrails/guardrail_hooks/content_filter/test_content_filter.py, 2 in tests/test_litellm/proxy/policy_engine/test_pipeline_executor.py) fail at the merge base and pass at the tip, covering the streaming verdicts, the runtime-rewrite withhold (masked texts and rewritten tool call arguments, under both on_fail=block and on_fail=next/on_error=next) with echo-in-another-container controls (tuple texts, dict tool calls) proving no false positive, the rewriting-step 400 (attribute, streaming_transform_mode, guardrail_config, and content filter MASK sources against a BLOCK-only control), rewrites_streamed_output on the content filter (blocked words, patterns, bias_gender category keywords, age_discrimination always-block keywords, each against a BLOCK control), the modify_response block on /v1/messages, the gate with no iterator overrides, the per-chunk hook skipping pipeline-managed guardrails, the untranslatable-route 400, and the in-band error for an unscannable shape; the three touched test files pass in full (185 tests)

Type

🆕 New Feature

Caveats (if any)

Medium

  • Pipeline steps that rewrite streamed output (mask_response_content, a litellm_content_filter MASK action (blocked word, pattern, or category), streaming_transform_mode: incremental_diff) keep an upfront 400 on stream=true, now naming them
    • Fail-closed on a path that never worked, replacing the silent unmasked release earlier pushes had (incremental_diff at c5bcf3a, content filter MASK through d51198f); workaround: stream=false, or run the guardrail through guardrails.add alone, which masks streams
    • Applying pipeline rewrites on streams is its own feature (per-surface chunk rebuilding, chained rewrites across steps): LIT-6487
  • A rewrite only detectable at runtime fail-closes after the model call: the tokens are spent, then the 400 withholds the buffered stream
    • The alternative was releasing output the guardrail had rewritten (the pre-fix behavior for a runtime-deciding guardrail like Bedrock ANONYMIZED); delivering the rewrite is LIT-6487

Low

  • Streamed chunks are held until the model finishes; first byte waits for the verdict
    • Same semantics as streaming_buffer_until_moderated on the flat path, and the same total latency as the stream=false calls streaming clients were forced onto; per-chunk verdict chaining across steps is a different design, so left as is
  • A route the guardrail translation map does not know gets an upfront 400 naming it
    • Every streaming LLM route the proxy serves is in the map; the alternative was running the model and withholding the stream afterwards
  • A response shape the scanner still cannot read at stream time is withheld with an in-band guardrail_pipeline_error frame (code 500) rather than released ungoverned
  • Background requests keep the upfront 400: output hooks never run for them
  • Pipelines with native-lifecycle or unregistered guardrails keep the upfront 400, now naming them; those guardrails have no unified stream scan anywhere, guardrails.add runs their native streaming hook
  • Error detail policies/guardrails are tuples in process; unchanged JSON arrays on the wire
  • A modify_response step on a streaming chat or Responses request ends as an HTTP 500 error frame carrying the replacement text; /v1/messages streams a proper 200 replacement and non-stream gets a 200 replacement on every route
    • Same outcome the flat streaming path has for a modify_response verdict (only the Anthropic translation builds block chunks); LIT-6496 tracks building them for chat and Responses
  • /models/{model}:generateContent streams get the untranslatable-route 400 because the route table pattern never matches that path shape (pre-existing, LIT-6493)

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

  • 2247fbc passes /live-pr-risk


Note

Medium Risk
Changes core proxy streaming and policy-engine paths (buffer-until-verdict latency, fail-closed withholds, and new upfront 400 rules); incorrect gating could block legitimate streams or briefly buffer sensitive output server-side.

Overview
Post-call policy pipelines can govern streaming output instead of rejecting every stream=true request with HTTP 400. The proxy buffers the full stream, runs pipeline steps through endpoint guardrail translation (same path as flat post_call guardrails), then releases the original chunks on allow or terminates with block/modify_response errors via the unified streaming helpers.

Pre-call validation is split by case: background requests still fail upfront; streaming is allowed only when every pipeline step uses unified apply_guardrail, the route has a translation, and no step is configured to rewrite streamed content (rewrites_streamed_output(), content-filter MASK rules, or streaming_transform_mode=incremental_diff)—those cases get a 400 naming the guardrails rather than leaking unmasked tokens.

Runtime rewrites (e.g. APIs that mask only after scan) are detected via _StreamRewriteObserver during streaming pipeline execution; UndeliverableStreamRewrite withholds the buffered stream with a structured 400. Pipeline-managed guardrails are skipped in per-chunk streaming hooks so they are not double-run.

Supporting changes: resolve_endpoint_translation, public handle_streaming_block / emit_streaming_http_error, resolve_streaming_flag, and PipelineExecutor.supports_unified_execution for streaming steps.

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

@greptile-apps

greptile-apps Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR enables post-call policy pipelines to inspect buffered streaming responses before releasing them.

  • Resolves endpoint translations for streamed response shapes and executes compatible pipeline guardrails against the completed buffer.
  • Rejects unsupported or content-rewriting configurations up front and withholds rewrites discovered at runtime.
  • Adds coverage for streaming verdicts, translation behavior, rewrite detection, and content-filter configurations.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
litellm/proxy/utils.py Adds streaming pipeline admission checks, callback routing, full-stream buffering, and translated terminal responses.
litellm/proxy/policy_engine/pipeline_executor.py Extends post-call pipeline execution to scan buffered stream chunks and detect runtime output rewrites.
litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py Exposes streaming response helpers and centralizes endpoint translation and streaming-option resolution.
litellm/proxy/guardrails/guardrail_hooks/litellm_content_filter/content_filter.py Classifies content-filter MASK configurations as streamed-output rewriting behavior.
litellm/integrations/custom_guardrail.py Adds the base guardrail capability used to identify streamed-output rewrites.

Reviews (6): Last reviewed commit: "fix(policy_engine): withhold streams whe..." | Re-trigger Greptile

Comment thread litellm/proxy/utils.py Resolved
@codecov

codecov Bot commented Aug 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.86047% with 14 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/proxy/utils.py 92.04% 7 Missing ⚠️
...drail_hooks/unified_guardrail/unified_guardrail.py 83.33% 4 Missing ⚠️
litellm/proxy/policy_engine/pipeline_executor.py 94.64% 3 Missing ⚠️

📢 Thoughts on this report? Let us know!

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

Adds regression tests for the modify_response block on the Anthropic route,
the gate with no iterator overrides, and the per-chunk hook skipping
pipeline-managed guardrails. Corrects the gate docstring: an allow releases
the chunks as the endpoint translation left them, not verbatim
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

Comment thread litellm/proxy/utils.py
modify_response terminates with the translation's block chunks or the
raised error.
"""
buffered: Final[list[object]] = [] # mutable-ok: accumulates the stream before the pipeline verdict

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.

Low: Unbounded streaming buffer

Every chunk is retained until the provider finishes, so an authenticated user can submit concurrent requests with large output limits and exhaust worker memory. Enforce a maximum buffered byte or token count and fail closed when it is exceeded; counting chunks alone is insufficient because chunk sizes vary.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The flat post_call streaming hook already retains every chunk in responses_yielded for its end-of-stream pass; this gate keeps the same bound

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 for the detail. I can't automatically confirm this is safe to dismiss, so I'm leaving the thread open for a maintainer to make the call.

@veria-ai

veria-ai Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

This pull request adds execution of post-call policy guardrail pipelines for streaming responses, buffering stream content so it can be evaluated after the provider finishes.

One low-severity resource-exhaustion risk remains: authenticated users can request large streaming outputs concurrently, causing unbounded response buffering and potentially exhausting worker memory. One other issue has already been addressed, but the remaining buffer should be capped by bytes or tokens and fail closed when exceeded.

Open issues (1)

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

…aming pipelines

A litellm_content_filter step with a MASK action masks chat streams through
its own iterator hook under guardrails.add, which pipeline-managed guardrails
skip, so the pipeline path released the stream unmasked. CustomGuardrail now
declares rewrites_streamed_output (mask_response_content by default, any MASK
action for the content filter) and the upfront streaming check names such
steps in the same 400 it gives mask_response_content and incremental_diff
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

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.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Autofix Details

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Bedrock pipeline masks leak on streams
    • Override BedrockGuardrail.rewrites_streamed_output() to return True in ApplyGuardrail mode (where the flat streaming hook always applies service-side masks) so the streaming pipeline gate rejects it up front, and expanded the pipeline gate error message to name this case.

Create PR

Or push these changes by commenting:

@cursor push 81d1d9a675
Preview (81d1d9a675)
diff --git a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py
--- a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py
@@ -2648,6 +2648,13 @@
 
         return messages
 
+    def rewrites_streamed_output(self) -> bool:
+        # ApplyGuardrail's flat streaming hook always applies whatever masks the
+        # Bedrock policy returns (e.g. PII anonymization), independent of
+        # mask_response_content, so the streaming pipeline gate has to fail
+        # closed here. InvokeGuardrailChecks is detect-only and cannot rewrite.
+        return self.checks is None or super().rewrites_streamed_output()
+
     async def async_post_call_streaming_iterator_hook(
         self,
         user_api_key_dict: UserAPIKeyAuth,

diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -521,10 +521,11 @@
     translation of the request route, releasing the buffered chunks on allow.
     That needs every step's guardrail to support the unified apply_guardrail
     interface and to only allow or block (a step that rewrites streamed
-    content, via mask_response_content, a MASK action, or
-    streaming_transform_mode=incremental_diff, would have its rewrite silently
-    dropped), and needs the route to have a translation at all; anything else
-    keeps the 400 rather than letting ungoverned output stream through.
+    content, via mask_response_content, a MASK action,
+    streaming_transform_mode=incremental_diff, or a Bedrock ApplyGuardrail
+    service-side rewrite, would have its rewrite silently dropped), and needs
+    the route to have a translation at all; anything else keeps the 400 rather
+    than letting ungoverned output stream through.
     """
     is_stream: Final = data.get("stream") is True
     is_background: Final = data.get("background") is True
@@ -578,8 +579,9 @@
                 "message": (
                     "Policies with post_call guardrail pipelines cannot govern streaming responses "
                     "because these pipeline guardrails rewrite streamed content (mask_response_content, "
-                    "a MASK action, or streaming_transform_mode=incremental_diff), which pipeline steps would release "
-                    f"unmodified: {', '.join(rewriting_guardrails)}. Retry with stream=false, or drop "
+                    "a MASK action, streaming_transform_mode=incremental_diff, or a Bedrock ApplyGuardrail "
+                    "service-side rewrite), which pipeline steps would release unmodified: "
+                    f"{', '.join(rewriting_guardrails)}. Retry with stream=false, or drop "
                     "them from the pipeline steps so guardrails.add applies them to streamed output."
                 ),
                 "type": "guardrail_pipeline_error",

diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.py
--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.py
+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.py
@@ -5345,3 +5345,37 @@
         assert guardrail.optional_params["aws_external_id"] == "external-id-123"
     finally:
         litellm.logging_callback_manager.remove_callback_from_list_by_object(litellm.callbacks, guardrail)
+
+
+class TestRewritesStreamedOutput:
+    """`rewrites_streamed_output()` must fail closed for ApplyGuardrail so a
+    Bedrock policy that anonymizes PII cannot leak unmasked chunks when driven
+    from a streaming post_call pipeline (which assembles + scans but yields the
+    buffered chunks unmodified)."""
+
+    def test_apply_guardrail_mode_rewrites(self):
+        guardrail = BedrockGuardrail(guardrailIdentifier="gr", guardrailVersion="DRAFT")
+
+        assert guardrail.rewrites_streamed_output() is True
+
+    def test_apply_guardrail_mode_rewrites_even_without_mask_response_content(self):
+        guardrail = BedrockGuardrail(
+            guardrailIdentifier="gr",
+            guardrailVersion="DRAFT",
+            mask_response_content=False,
+        )
+
+        assert guardrail.rewrites_streamed_output() is True
+
+    def test_invoke_guardrail_checks_mode_does_not_rewrite(self):
+        guardrail = BedrockGuardrail(checks={"contentPolicy": {"filtersConfig": []}})
+
+        assert guardrail.rewrites_streamed_output() is False
+
+    def test_invoke_guardrail_checks_mode_defers_to_mask_response_content(self):
+        guardrail = BedrockGuardrail(
+            checks={"contentPolicy": {"filtersConfig": []}},
+            mask_response_content=True,
+        )
+
+        assert guardrail.rewrites_streamed_output() is True

You can send follow-ups to the cloud agent here.

Comment thread litellm/proxy/utils.py Resolved
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

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.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Observer misses in-place stream rewrites
    • Snapshotted the observer's sent texts (shallow list copy) and tool-call shapes before delegating to the inner guardrail, so in-place rewrites like Bedrock's inputs['texts'] = masked_texts are now detected and the stream is withheld.

Create PR

Or push these changes by commenting:

@cursor push 38e8e839aa
Preview (38e8e839aa)
diff --git a/litellm/proxy/policy_engine/pipeline_executor.py b/litellm/proxy/policy_engine/pipeline_executor.py
--- a/litellm/proxy/policy_engine/pipeline_executor.py
+++ b/litellm/proxy/policy_engine/pipeline_executor.py
@@ -61,14 +61,18 @@
     return sent is not None and returned is not None and list(returned) != list(sent)
 
 
-def _rewrote_tool_calls(sent: Sequence[object] | None, returned: Sequence[object] | None) -> bool:
-    if sent is None or returned is None:
-        return False
-    return [_tool_call_shape(tool_call) for tool_call in returned] != [
-        _tool_call_shape(tool_call) for tool_call in sent
-    ]
+def _tool_calls_shape(tool_calls: Sequence[object] | None) -> list[tuple[object, object]] | None:
+    if tool_calls is None:
+        return None
+    return [_tool_call_shape(tool_call) for tool_call in tool_calls]
 
 
+def _rewrote_tool_calls(
+    sent: list[tuple[object, object]] | None, returned: list[tuple[object, object]] | None
+) -> bool:
+    return sent is not None and returned is not None and returned != sent
+
+
 class _StreamRewriteObserver(CustomGuardrail):
     """Stand-in handed to the endpoint translation in place of a streaming pipeline step's
     guardrail. Translations cannot rewrite every buffered chunk consistently, so the gate
@@ -90,13 +94,16 @@
         input_type: Literal["request", "response"],
         logging_obj: "LiteLLMLoggingObj | None" = None,
     ) -> GenericGuardrailAPIInputs:
+        sent_texts_raw: Final = inputs.get("texts")
+        sent_texts: Final = list(sent_texts_raw) if sent_texts_raw is not None else None
+        sent_tool_calls: Final = _tool_calls_shape(inputs.get("tool_calls"))
         outputs: Final = await self.inner.apply_guardrail(
             inputs=inputs, request_data=request_data, input_type=input_type, logging_obj=logging_obj
         )
         self.rewrote = (
             self.rewrote
-            or _rewrote_texts(inputs.get("texts"), outputs.get("texts"))
-            or _rewrote_tool_calls(inputs.get("tool_calls"), outputs.get("tool_calls"))
+            or _rewrote_texts(sent_texts, outputs.get("texts"))
+            or _rewrote_tool_calls(sent_tool_calls, _tool_calls_shape(outputs.get("tool_calls")))
         )
         return outputs
 

diff --git a/tests/test_litellm/proxy/policy_engine/test_pipeline_executor.py b/tests/test_litellm/proxy/policy_engine/test_pipeline_executor.py
--- a/tests/test_litellm/proxy/policy_engine/test_pipeline_executor.py
+++ b/tests/test_litellm/proxy/policy_engine/test_pipeline_executor.py
@@ -872,3 +872,71 @@
 
     assert result.terminal_action == "allow"
     assert [step.outcome for step in result.step_results] == ["pass"]
+
+
+class _InPlaceTextRewriteGuardrail(CustomGuardrail):
+    """Mirrors Bedrock's `apply_guardrail`, which mutates `inputs["texts"]` and returns
+    the same dict, so the observer must snapshot the sent values before delegating."""
+
+    def __init__(self, rewritten_texts):
+        super().__init__(guardrail_name="masker", event_hook="post_call", default_on=True)
+        self.rewritten_texts = rewritten_texts
+
+    async def apply_guardrail(self, inputs, request_data, input_type, logging_obj=None):
+        inputs["texts"] = self.rewritten_texts
+        return inputs
+
+
+@pytest.mark.asyncio
+async def test_streaming_step_detects_in_place_texts_rewrite(monkeypatch):
+    monkeypatch.setattr(litellm, "callbacks", [_InPlaceTextRewriteGuardrail(["hello [MASKED]"])])
+
+    with pytest.raises(UndeliverableStreamRewrite) as info:
+        await _run_streaming_step(["hello [MASKED]"], _TextTranslation())
+
+    assert info.value.guardrail_name == "masker"
+
+
+class _ToolCallTranslation:
+    async def process_output_streaming_response(
+        self, responses_so_far, guardrail_to_apply, litellm_logging_obj=None, user_api_key_dict=None, request_data=None
+    ):
+        await guardrail_to_apply.apply_guardrail(
+            inputs={"tool_calls": [{"function": {"name": "search", "arguments": '{"q": "alice@example.com"}'}}]},
+            request_data=request_data or {},
+            input_type="response",
+            logging_obj=litellm_logging_obj,
+        )
+        return responses_so_far
+
+
+class _InPlaceToolCallsRewriteGuardrail(CustomGuardrail):
+    def __init__(self, rewritten_arguments):
+        super().__init__(guardrail_name="masker", event_hook="post_call", default_on=True)
+        self.rewritten_arguments = rewritten_arguments
+
+    async def apply_guardrail(self, inputs, request_data, input_type, logging_obj=None):
+        for tool_call in inputs.get("tool_calls") or ():
+            tool_call["function"]["arguments"] = self.rewritten_arguments
+        return inputs
+
+
+@pytest.mark.asyncio
+async def test_streaming_step_detects_in_place_tool_calls_rewrite(monkeypatch):
+    monkeypatch.setattr(
+        litellm, "callbacks", [_InPlaceToolCallsRewriteGuardrail('{"q": "[MASKED]"}')]
+    )
+
+    with pytest.raises(UndeliverableStreamRewrite) as info:
+        await PipelineExecutor.execute_steps(
+            steps=[PipelineStep(guardrail="masker", on_pass="allow", on_fail="next", on_error="next")],
+            mode="post_call",
+            data={"model": "m"},
+            user_api_key_dict=MagicMock(),
+            call_type="completion",
+            policy_name="p",
+            streaming_chunks=[object()],
+            endpoint_translation=_ToolCallTranslation(),
+        )
+
+    assert info.value.guardrail_name == "masker"

You can send follow-ups to the cloud agent here.

Reviewed by Cursor Bugbot for commit 2247fbc. Configure here.

or _rewrote_texts(inputs.get("texts"), outputs.get("texts"))
or _rewrote_tool_calls(inputs.get("tool_calls"), outputs.get("tool_calls"))
)
return outputs

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.

Observer misses in-place stream rewrites

High Severity

_StreamRewriteObserver.apply_guardrail compares inputs to outputs only after the inner guardrail returns. Guardrails such as Bedrock assign rewritten texts on the same inputs dict and return it, so both sides already hold the masked values and rewrote stays false. The gated stream then releases the original buffered chunks, including for Bedrock ANONYMIZED, the runtime rewrite this change is meant to withhold.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 2247fbc. Configure here.

@mateo-berri
mateo-berri merged commit 99286cd into litellm_fix_post_call_policy_pipeline Aug 29, 2026
83 checks passed
@mateo-berri
mateo-berri deleted the litellm_post_call_pipeline_streaming branch August 29, 2026 23:27
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