Repository navigation
feat(policy_engine): execute post_call guardrail pipelines on streaming responses - #38788
Conversation
Greptile SummaryThis PR enables post-call policy pipelines to inspect buffered streaming responses before releasing them.
Confidence Score: 5/5The PR appears safe to merge. No blocking failure remains.
|
| 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
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
…peline steps and untranslatable routes
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
| 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.
PR overviewThis 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
… for streaming pipelines
|
bugbot run |
There was a problem hiding this comment.
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.
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 TrueYou can send follow-ups to the cloud agent here.
…es output at runtime
|
bugbot run |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
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_textsare now detected and the stream is withheld.
- 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
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 |
There was a problem hiding this comment.
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.
Reviewed by Cursor Bugbot for commit 2247fbc. Configure here.
99286cd
into
litellm_fix_post_call_policy_pipeline



TLDR
Stacked on #38721 (base branch
litellm_fix_post_call_policy_pipeline), so this PR's diff shows only the streaming workNow 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 gatesProblem this solves:
How it solves it:
mask_response_content, alitellm_content_filterMASK 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 streamsapply_guardrailseam: 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'son_fail/on_errorroutingUser 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
response-governance, whose pipeline scans model output, to the gateway"stream": true"stream": truereturn the same 400"stream": falserequests get answers, so every streaming app is locked out of governed modelsAfter: the same streaming requests run, and the policy pipeline governs the streamed output
response-governancepolicy"stream": truedata: [DONE]with HTTP 200; the chunks arrive together once the model finishes, since the gateway holds the stream until the policy verdict"stream": truebehave the same way: clean streams flow, violating streams get the 400 block"background": truerequests still get an upfront 400, since output scanning never runs for thosemask_response_content: true, alitellm_content_filterMASK rule (blocked word, pattern, or category), orstreaming_transform_mode: incremental_diff) still gets an upfront HTTP 400 on"stream": true, now naming that guardrail and pointing atstream=falseorguardrails.addas the way to keep the masking"stream": trueon 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 afterwardsRelevant issues
Linear ticket
Resolves LIT-6441
Pre-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
Live proxy, real OpenAI
gpt-5.4-mini. Config:litellm_content_filterguardrailoutput-word-filter(kumquat BLOCK) plus policyresponse-governancewith 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 keyBefore (c64318c)
/v1/chat/completions streaming
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}'{"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
{"model":"gpt-5.4-mini","input":"Say the word kumquat","stream":true})guardrail_pipeline_errorbody/v1/messages streaming
{"model":"gpt-5.4-mini","max_tokens":100,"messages":[...],"stream":true})Non-streaming control
stream"Content blocked: keyword 'kumquat' detected"(the pipeline itself works; only streaming was locked out)After (tip 2247fbc)
/v1/chat/completions streaming
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)"say hello","stream":true): HTTP 200, full SSE stream released,data: [DONE]/v1/responses streaming
response.createdthroughresponse.completed,data: [DONE]/v1/messages streaming
message_startthroughmessage_stopMASK 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""I like [KEYWORD_REDACTED] pie"" pers","im","mon"deltas released unmasked on all three routes (the leak)"I like [KEYWORD_REDACTED] pie"output-word-filteron all three routes, benign prompts included"I like [KEYWORD_REDACTED] pie""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.addcontrol at the tip (qa6441/config_flat.yaml, same guardrail withdefault_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 pathsMASK action from a category, two checkpoints
Config
qa6441/config_category.yaml: guardrailoutput-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 incategory_keywordsandalways_block_category_keywords, which the 0c1f33d check did not read" man"delta released unmasked on all three routes (the leak)"The [KEYWORD_REDACTED] walked home"output-category-filteron all three routes, benign prompts included"The [KEYWORD_REDACTED] walked home"Non-streaming and background controls
"Content blocked: keyword 'kumquat' detected"(unchanged)/v1/responseswith"background": true: HTTP 400 upfront"Policies with post_call guardrail pipelines cannot govern background responses: response-governance. Retry with background=false."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 workContent-rewriting pipeline step, three checkpoints
Config
qa6441/config_rewrite.yaml: ageneric_guardrail_apiguardrailpii-masker(mode post_call,streaming_transform_mode: incremental_diff,api_basepointing at a local stand-in that rewrites "persimmon" to "[MASKED]" and answersGUARDRAIL_INTERVENED) as the single pipeline step of policyresponse-masking, scope*. Same two curls at every checkpoint, prompt "Reply with exactly this sentence and nothing else: I like persimmon pie", once with"stream": trueand once with"stream": false"I like [MASKED] pie"" pers","im","mon"released while the stand-in loggedintervened=True(the leak)"I like [MASKED] pie"pii-masker, stand-in never called"I like [MASKED] pie", stand-in loggedintervened=TrueTip 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 2Runtime-detected rewrite, two checkpoints
Config
qa6441/config_runtime_mask.yaml: the samepii-maskerstand-in guardrail with nostreaming_transform_modeand 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"I like persimmon pie"released unmasked on all three routes while the stand-in loggedintervened=True(the leak)"I like [MASKED] pie"response-maskingand guardrailpii-masker; benign prompt streams HTTP 200"I like [MASKED] pie", stand-inintervened=TrueTip 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 intests/test_litellm/proxy/guardrails/guardrail_hooks/content_filter/test_content_filter.py, 2 intests/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 bothon_fail=blockandon_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_outputon the content filter (blocked words, patterns,bias_gendercategory keywords,age_discriminationalways-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
mask_response_content, alitellm_content_filterMASK action (blocked word, pattern, or category),streaming_transform_mode: incremental_diff) keep an upfront 400 onstream=true, now naming themincremental_diffat c5bcf3a, content filter MASK through d51198f); workaround:stream=false, or run the guardrail throughguardrails.addalone, which masks streamsLow
streaming_buffer_until_moderatedon the flat path, and the same total latency as thestream=falsecalls streaming clients were forced onto; per-chunk verdict chaining across steps is a different design, so left as isguardrail_pipeline_errorframe (code 500) rather than released ungovernedguardrails.addruns their native streaming hookpolicies/guardrailsare tuples in process; unchanged JSON arrays on the wiremodify_responsestep on a streaming chat or Responses request ends as an HTTP 500 error frame carrying the replacement text;/v1/messagesstreams a proper 200 replacement and non-stream gets a 200 replacement on every routemodify_responseverdict (only the Anthropic translation builds block chunks); LIT-6496 tracks building them for chat and Responses/models/{model}:generateContentstreams 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=truerequest 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, orstreaming_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
_StreamRewriteObserverduring streaming pipeline execution;UndeliverableStreamRewritewithholds 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, publichandle_streaming_block/emit_streaming_http_error,resolve_streaming_flag, andPipelineExecutor.supports_unified_executionfor streaming steps.Reviewed by Cursor Bugbot for commit 2247fbc. Bugbot is set up for automated code reviews on this repo. Configure here.