Skip to content

fix(policy_engine): execute post_call guardrail pipelines on responses and streams - #38721

Merged
mateo-berri merged 37 commits into
litellm_internal_stagingfrom
litellm_fix_post_call_policy_pipeline
Sep 8, 2026
Merged

mateo-berri merged 37 commits into
litellm_internal_stagingfrom
litellm_fix_post_call_policy_pipeline

Conversation

@mateo-berri

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

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Policies with pipeline: {mode: post_call} parsed but never executed on responses
  • Declaring one also stripped its guardrails from their normal post_call runs
  • Success headers claimed the policy applied to responses nothing ever scanned
  • /policies/test-pipeline executed the same pipeline fine, so operators saw it "work"

How it solves it:

  • post_call pipelines now execute in the response path, exactly once per guardrail
  • block steps re-raise the guardrail's own error; in-place edits (masking) propagate to the client
  • A guardrail that returns a fresh replacement response (instead of editing in place) has that replacement delivered to the client, chaining across steps like the flat guardrail loop
  • modify_response outcomes now carry the original response, so usage is reported from the real call
  • Streaming requests governed by a post_call pipeline now run it (merged from feat(policy_engine): execute post_call guardrail pipelines on streaming responses #38788): the proxy buffers the stream, runs the pipeline verdict, then releases the chunks on allow or ends the stream with the block error
  • A text mask on a finished single-choice chat, Responses, or Messages stream is written into the buffered events before they are released (merged from fix(policy_engine): apply post_call pipeline text rewrites on streams #39233, LIT-6487)
  • Streaming shapes the pipeline cannot govern yet fail open the way the merge base did, so this PR adds no new 400: a rewrite it cannot write back (streamed tool-call arguments, n > 1, a stream that ended without a finish marker, a Responses stream with no response envelope) is discarded and the original chunks are released; a stream on a route with no guardrail translation, a stream whose pipeline guardrail lacks the unified apply_guardrail interface, and a streamed /v1/completions call are released unscanned; a background: true submit is accepted and the pipeline does not run on it. Every discard and release except the completions one logs a warning naming the policy and guardrail. The handlers are LIT-7174 (tool-call write-back), LIT-7175 (background), LIT-7176 (legacy hooks), LIT-7177 (completions), LIT-7178 (multi-choice, unfinished, envelope-less), and LIT-7179 (route coverage)
  • The skip that keeps pipeline-managed guardrails out of the normal guardrail loops is scoped to the pipeline's mode, so a guardrail that hooks both stages, default_on or added by the policy, and is managed by a pipeline on only one of them still runs its other stage
  • When a post_call pipeline passes, its guardrails' metadata writes (applied-guardrails header entries, guardrail logging info) are merged back into the request, so x-litellm-applied-guardrails and spend logs still name the guardrail that scanned the response
  • A pipeline step whose guardrail only has the legacy streaming iterator hook cannot be streamed by the pipeline, so that guardrail governs the stream on its own instead of being dropped
  • A streaming pipeline step is recorded once in the spend log's guardrail information and named in x-litellm-applied-guardrails
  • A stream blocked after its last upstream chunk logs the failed call plus the deferred spend row with the model's real cost, the same two rows a flat end-of-stream block already logs
  • The unused rewrites_streamed_output guardrail hook is gone

User Flow

Before: an admin who attaches a policy with a post_call guardrail pipeline gets no response scanning at all, while headers claim the policy applied

  1. The admin defines a policy whose pipeline has mode: post_call and a step for their output guardrail, attaches it with scope "*", and restarts the proxy
  2. A user sends POST http://litellm-domain/v1/chat/completions asking the model for a banned word
  3. The reply is HTTP 200 with the banned word delivered, and the headers read x-litellm-applied-policies: response-governance
  4. The admin tries POST http://litellm-domain/policies/test-pipeline with the same pipeline and every step reports "pass", so nothing looks broken
  5. Only when a user sets "guardrails": ["output-word-filter"] by hand does the same request return HTTP 400, showing the guardrail works and the policy wiring is dead
  6. A policy that adds a guardrail with only the legacy streaming hook and steps it: the same streaming POST comes back hello with no guardrail header, the hook never ran
  7. A policy that adds a guardrail checking both request and response and steps it on responses: a request carrying the banned word goes to the model and comes back HTTP 200

After: the same policy blocks and masks what it can govern, and every stream it cannot govern yet flows exactly as it did before

  1. The admin keeps the same config and restarts the proxy on this build
  2. The same POST http://litellm-domain/v1/chat/completions asking for the banned word returns HTTP 400 Content blocked: keyword 'kumquat' detected
  3. A reply containing a maskable word comes back HTTP 200 with [KEYWORD_REDACTED] in its place
  4. A benign request comes back HTTP 200 untouched, headers naming both the policy and the guardrail that scanned it: x-litellm-applied-policies: response-governance and x-litellm-applied-guardrails: output-word-filter
  5. The same banned-word request with "stream": true comes back as HTTP 400 with a single SSE error frame Content blocked: keyword 'kumquat' detected, while a benign streaming request flows as a normal SSE stream ending in data: [DONE], chunks arriving together once the model finishes since the gateway holds the stream until the policy verdict
  6. A maskable word on a streamed POST http://litellm-domain/v1/chat/completions, POST http://litellm-domain/v1/responses, or POST http://litellm-domain/v1/messages arrives as HTTP 200 with [KEYWORD_REDACTED] in the text deltas
  7. The streams the gateway cannot govern yet come back byte for byte as they did before this PR, HTTP 200 with the original events: a maskable word inside streamed tool-call arguments, a streamed request with "n": 2, a streamed POST http://litellm-domain/v1/completions, and a stream on a model whose pipeline guardrail only has the legacy post-call hook
  8. POST http://litellm-domain/v1/responses with "background": true is accepted with HTTP 200 and "status": "queued", and GET http://litellm-domain/v1/responses/{id} returns the completed text ungoverned, as before this PR
  9. A policy whose pipeline guardrail returns a rewritten replacement response gets the rewritten text delivered on the same non-streaming POST http://litellm-domain/v1/chat/completions, a guardrail with only the legacy post-call hook included
  10. A default_on guardrail that hooks both request and response stages, managed by a pipeline on only one of them, still runs its other stage on the same POST (before, the stage the pipeline did not cover was silently skipped on requests)
  11. A policy that adds a guardrail with only the legacy streaming hook and steps it: the same streaming POST comes back with that hook's mark, [LEGACY-GUARD stream ran] hello, and x-litellm-applied-guardrails: legacy-stream-guard
  12. A policy that adds a guardrail checking both request and response and steps it on responses: a request carrying the banned word returns HTTP 400 Content blocked: keyword 'durian' detected before the model is called
  13. The masked streams of step 6 carry x-litellm-applied-guardrails: output-word-filter, https://litellm-domain/ui/?page=logs names that guardrail once per request, and the blocked stream of step 5 shows up there as a failed request plus its real spend

Relevant issues

Found tracing a customer's guardrail policy config (Pylon #7871)

Linear ticket

Resolves LIT-6410

Also resolves LIT-6441, merged in from #38788 (streaming execution)

Follow-ups for the shapes that fail open here: LIT-7174, LIT-7175, LIT-7176, LIT-7177, LIT-7178, LIT-7179

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)

Screenshots / Proof of Fix

Shared setup, both runs: a live proxy from a worktree, --num_workers 2, no database, real OpenAI and Anthropic calls, master key auth. config.yaml covers every case but the three default_on rewrite ones, which run on config.rewrite.yaml (a second boot, same worktree). Next to the configs: legacy_hook.py holds legacyRewriter (a CustomGuardrail that only implements async_post_call_success_hook, prefixing the reply with [REWRITTEN BY LEGACY HOOK] , no unified apply_guardrail), legacyStreamGuard (only async_post_call_streaming_iterator_hook, prefixing the first delta with [LEGACY-GUARD stream ran] ) and legacyEndBlock (yields every chunk, then raises 400); response_rewriter.py returns a replacement ModelResponse from async_post_call_success_hook with a configurable prefix; spend_probe.py is a CustomLogger that appends one JSON line per spend log row (the call id, status, cost, applied_guardrails and the guardrail_information entries), so the rows quoted under a case are exactly what the spend log receives for it:

# config.yaml
model_list:  # 8 entries, each openai/gpt-5.4-mini with api_key os.environ/OPENAI_API_KEY unless noted:
  # gpt-5.4-mini, gpt-4.1-mini (openai/gpt-4.1-mini), claude-haiku-4-5 (anthropic/claude-haiku-4-5), gpt-5.4-mini-legacy, gpt-5.4-mini-legacy-stream, gpt-5.4-mini-endblock, gpt-5.4-mini-dual, gpt-5.4-mini-rewrite
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"
  - guardrail_name: legacy-rewriter
    litellm_params:
      guardrail: legacy_hook.legacyRewriter
      mode: post_call
  - guardrail_name: legacy-stream-guard
    litellm_params:
      guardrail: legacy_hook.legacyStreamGuard
      mode: post_call
  - guardrail_name: legacy-end-block
    litellm_params:
      guardrail: legacy_hook.legacyEndBlock
      mode: post_call
  - guardrail_name: input-word-filter
    litellm_params:
      guardrail: litellm_content_filter
      mode: [pre_call, post_call]
      blocked_words:
        - keyword: "durian"
          action: "BLOCK"
        - keyword: "kumquat"
          action: "BLOCK"
  - guardrail_name: response-rewriter
    litellm_params:
      guardrail: response_rewriter.responseRewriter
      mode: post_call
policies:
  response-governance:
    guardrails:
      add: [output-word-filter]
    pipeline:
      mode: post_call
      steps:
        - guardrail: output-word-filter
          on_pass: allow
          on_fail: block
  legacy-governance:
    guardrails:
      add: [legacy-rewriter]
    pipeline:
      mode: post_call
      steps:
        - guardrail: legacy-rewriter
          on_pass: allow
          on_fail: block
  legacy-stream-governance:
    guardrails:
      add: [legacy-stream-guard]
    pipeline:
      mode: post_call
      steps:
        - guardrail: legacy-stream-guard
          on_pass: allow
          on_fail: block
  dual-governance:
    guardrails:
      add: [input-word-filter]
    pipeline:
      mode: post_call
      steps:
        - guardrail: input-word-filter
          on_pass: allow
          on_fail: block
  response-rewrite:
    guardrails:
      add: [response-rewriter]
    pipeline:
      mode: post_call
      steps:
        - guardrail: response-rewriter
          on_pass: allow
          on_fail: block
policy_attachments:
  - policy: response-governance
    models: [gpt-5.4-mini, gpt-4.1-mini, claude-haiku-4-5]
  - policy: legacy-governance
    models: [gpt-5.4-mini-legacy]
  - policy: legacy-stream-governance
    models: [gpt-5.4-mini-legacy-stream]
  - policy: dual-governance
    models: [gpt-5.4-mini-dual]
  - policy: response-rewrite
    models: [gpt-5.4-mini-rewrite]
litellm_settings:
  callbacks: [spend_probe.proxy_handler_instance]
general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
# config.rewrite.yaml
model_list:  # 3 entries, each openai/gpt-5.4-mini with api_key os.environ/OPENAI_API_KEY unless noted:
  # gpt-5.4-mini-rewrite-default-on, gpt-5.4-mini-rewrite-parallel, gpt-5.4-mini-rewrite-cross-mode
guardrails:
  - guardrail_name: response-rewriter-default-on
    litellm_params:
      guardrail: response_rewriter.responseRewriter
      mode: post_call
      default_on: true
      prefix: "[DEFAULT-ON] "
  - guardrail_name: response-rewriter-parallel
    litellm_params:
      guardrail: response_rewriter.responseRewriter
      mode: post_call
      default_on: true
      run_in_parallel: true
      prefix: "[PARALLEL] "
  - guardrail_name: response-rewriter-cross-mode
    litellm_params:
      guardrail: response_rewriter.responseRewriter
      mode: [pre_call, post_call]
      default_on: true
      prefix: "[CROSS-MODE] "
policies:
  response-rewrite-default-on:
    guardrails:
      add: [response-rewriter-default-on]
    pipeline:
      mode: post_call
      steps:
        - guardrail: response-rewriter-default-on
          on_pass: allow
          on_fail: block
  response-rewrite-parallel:
    guardrails:
      add: [response-rewriter-parallel]
    pipeline:
      mode: post_call
      steps:
        - guardrail: response-rewriter-parallel
          on_pass: allow
          on_fail: block
  response-rewrite-cross-mode:
    guardrails:
      add: [response-rewriter-cross-mode]
    pipeline:
      mode: pre_call
      steps:
        - guardrail: response-rewriter-cross-mode
          on_pass: allow
          on_fail: block
policy_attachments:
  - policy: response-rewrite-default-on
    models: [gpt-5.4-mini-rewrite-default-on]
  - policy: response-rewrite-parallel
    models: [gpt-5.4-mini-rewrite-parallel]
  - policy: response-rewrite-cross-mode
    models: [gpt-5.4-mini-rewrite-cross-mode]
litellm_settings:
  callbacks: [spend_probe.proxy_handler_instance]
general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY

Boot, per leg (base worktree at the merge base, tip worktree at this PR's head, same venv; $PORT is a random free port):

export PYTHONPATH=<worktree>:<worktree>/enterprise:<worktree>/litellm-proxy-extras
export SPEND_PROBE_FILE=out/<leg>/spend_probe.jsonl
python <worktree>/litellm/proxy/proxy_cli.py --config config.yaml --port $PORT --num_workers 2 --detailed_debug
auth=(-H "Authorization: Bearer $LITELLM_MASTER_KEY" -H 'Content-Type: application/json')

Every request below was sent once against each leg, same bytes. Volatile fields (ids, timestamps, fingerprints) differ between legs; nothing else does on the fail-open shapes. To fit the description, stream output keeps the lines that carry text, arguments, an error, or the end marker (elided lines are counted), id, created, model, object, item_id and sequence_number fields are dropped from every JSON line, every line is cut at 150 characters, non-stream JSON is cut at 300 characters plus the window around the reply text, the configs are shown without their blank and description lines, and spend rows are quoted as their status, cost, applied_guardrails and guardrail_information fields

Before (9d0c9b9, merge base)

Fail-open 1: guardrail edits a streamed tool-call argument (chat, forced lookup_fruit)

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini","stream":true,"messages":[{"role":"user","content":"Look up the fruit persimmon."}],"tools":[{"type":"function","function":{"name":"lookup_fruit","parameters":{"type":"object","properties":{"fruit":{"type":"string"}},"required":["fruit"]}}}],"tool_choice":{"type":"function","function":{"name":"lookup_fruit"}}}'
  2. Observed:

    HTTP 200
    x-litellm-applied-policies: response-governance
    data: {"choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"function":{"arguments":"","name":"lookup_fruit"},"type":"function","index":0} ...
    data: {"choices":[{"index":0,"delta":{"tool_calls":[{"function":{"arguments":"{\""},"type":"function","index":0}]}}]}
    data: {"choices":[{"index":0,"delta":{"tool_calls":[{"function":{"arguments":"fruit"},"type":"function","index":0}]}}]}
    data: {"choices":[{"index":0,"delta":{"tool_calls":[{"function":{"arguments":"\":\""},"type":"function","index":0}]}}]}
    data: {"choices":[{"index":0,"delta":{"tool_calls":[{"function":{"arguments":"pers"},"type":"function","index":0}]}}]}
    data: {"choices":[{"index":0,"delta":{"tool_calls":[{"function":{"arguments":"im"},"type":"function","index":0}]}}]}
    data: {"choices":[{"index":0,"delta":{"tool_calls":[{"function":{"arguments":"mon"},"type":"function","index":0}]}}]}
    data: {"choices":[{"index":0,"delta":{"tool_calls":[{"function":{"arguments":"\"}"},"type":"function","index":0}]}}]}
    data: {"choices":[{"finish_reason":"tool_calls","index":0,"delta":{}}],"provider_specific_fields":{"frequency_penalty":0.0,"presence_penalty":0.0,"too ...
    data: [DONE]
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 0.0001275, "applied_guardrails": [], "guardrail_information": []}
    

Fail-open 2: maskable text on a streamed /v1/completions call

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/completions \
      -d '{"model":"gpt-4.1-mini","stream":true,"max_tokens":20,"prompt":"Reply with exactly the word persimmon and nothing else."}'
  2. Observed:

    HTTP 200
    x-litellm-applied-policies: response-governance
    ... (1 more lines) ...
    data: {"choices":[{"index":0,"text":"pers"}],"usage":{"completion_tokens":0,"prompt_tokens":0,"total_tokens":0}}
    data: {"choices":[{"index":0,"text":"im"}],"usage":{"completion_tokens":0,"prompt_tokens":0,"total_tokens":0}}
    data: {"choices":[{"index":0,"text":"mon"}],"usage":{"completion_tokens":0,"prompt_tokens":0,"total_tokens":0}}
    data: {"choices":[{"finish_reason":"stop","index":0}],"usage":{"completion_tokens":0,"prompt_tokens":0,"total_tokens":0}}
    ... (1 more lines) ...
    data: [DONE]
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 1.24e-05, "applied_guardrails": [], "guardrail_information": []}
    

Fail-open 3: maskable text on a streamed chat call with n: 2

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-4.1-mini","stream":true,"n":2,"messages":[{"role":"user","content":"Reply with exactly the word persimmon and nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-policies: response-governance
    ... (1 more lines) ...
    data: {"choices":[{"index":0,"delta":{"content":"pers"}}],"obfuscation":"piNRQn"}
    data: {"choices":[{"index":0,"delta":{"content":"im"}}],"obfuscation":"Oy31ABXB"}
    data: {"choices":[{"index":0,"delta":{"content":"mon"}}],"obfuscation":"KGneXsx"}
    data: {"choices":[{"index":1,"delta":{"content":"pers"}}],"obfuscation":"dhusX9"}
    data: {"choices":[{"index":1,"delta":{"content":"im"}}],"obfuscation":"NqdUXIkV"}
    data: {"choices":[{"index":1,"delta":{"content":"mon"}}],"obfuscation":"59XMlqa"}
    data: {"choices":[{"finish_reason":"stop","index":0,"delta":{}}],"obfuscation":"BCQl"}
    data: [DONE]
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 1.7199999999999998e-05, "applied_guardrails": [], "guardrail_information": []}
    

Fail-open 4: background: true Responses submit asking for the blocked word

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/responses \
      -d '{"model":"gpt-5.4-mini","background":true,"input":"Reply with exactly the word kumquat and nothing else."}'
  2. Observed:

    HTTP 200
    x-litellm-applied-policies: response-governance
    {"error": null, "incomplete_details": null, "instructions": null, "metadata": {}, "output": [], "parallel_tool_calls": true, "temperature": 1.0, "tool_choice": "auto", "tools": [], "top_p": 0.98, "max_output_tokens": null, "previous_response_id": null, "reasoning": {"context": "current_turn", "effor ... ": "none", "mode": "standard", "summary": null}, "status": "queued", "text": {"format": {"type": "text"}, "verbosity": "medium"}, "truncation": "d ...
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 0.0, "applied_guardrails": [], "guardrail_information": []}
    

Fail-open 4, retrieval: GET /v1/responses/{id} for that background response

  1. Command:

    curl -sS -i "${auth[@]}" http://localhost:$PORT/v1/responses/$RESP_ID
  2. Observed:

    HTTP 200
    {"error": null, "incomplete_details": null, "instructions": null, "metadata": {}, "output": [{"content": [{"text": "kumquat", "type": "output_text", "logprobs": []}], "role": "assistant", "status": "completed", "type": "message", "phase": "final_answer"}], "parallel_tool_calls": true, "temperature": ...
    

Fail-open 5: streamed chat under a pipeline whose guardrail has only the legacy success hook

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini-legacy","stream":true,"messages":[{"role":"user","content":"Reply with exactly the word persimmon and nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-policies: legacy-governance
    ... (1 more lines) ...
    data: {"choices":[{"index":0,"delta":{"content":"pers"}}]}
    data: {"choices":[{"index":0,"delta":{"content":"im"}}]}
    data: {"choices":[{"index":0,"delta":{"content":"mon"}}]}
    data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
    data: [DONE]
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 4.0499999999999995e-05, "applied_guardrails": [], "guardrail_information": []}
    

Same legacy pipeline without streaming: the rewrite is delivered

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini-legacy","messages":[{"role":"user","content":"Reply with exactly the word persimmon and nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-policies: legacy-governance
    {"choices": [{"finish_reason": "stop", "index": 0, "message": {"content": "persimmon", "role": "assistant", "provider_specific_fields": {"refusal": null}, "annotations": []}, "provider_specific_fields": {}}], "usage": {"completion_tokens": 6, "prompt_tokens": 18, "total_tokens": 24, "completion_toke ...
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 4.0499999999999995e-05, "applied_guardrails": [], "guardrail_information": []}
    

Block: streamed chat asking for the blocked word (the rows are the streaming block's logging contract)

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini","stream":true,"messages":[{"role":"user","content":"Reply with exactly the word kumquat and nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-policies: response-governance
    ... (1 more lines) ...
    data: {"choices":[{"index":0,"delta":{"content":"kum"}}]}
    data: {"choices":[{"index":0,"delta":{"content":"quat"}}]}
    data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
    data: [DONE]
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 3.525e-05, "applied_guardrails": [], "guardrail_information": []}
    

Mask: streamed chat asking for the masked word

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini","stream":true,"messages":[{"role":"user","content":"Reply with exactly the word persimmon and nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-policies: response-governance
    ... (1 more lines) ...
    data: {"choices":[{"index":0,"delta":{"content":"pers"}}]}
    data: {"choices":[{"index":0,"delta":{"content":"im"}}]}
    data: {"choices":[{"index":0,"delta":{"content":"mon"}}]}
    data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
    data: [DONE]
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 4.0499999999999995e-05, "applied_guardrails": [], "guardrail_information": []}
    

Mask: streamed Responses asking for the masked word

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/responses \
      -d '{"model":"gpt-5.4-mini","stream":true,"input":"Reply with exactly the word persimmon and nothing else."}'
  2. Observed:

    HTTP 200
    x-litellm-applied-policies: response-governance
    ... (4 more lines) ...
    data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"pers","model":"gpt-5.4-mini"}
    data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"im","model":"gpt-5.4-mini"}
    data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"mon","model":"gpt-5.4-mini"}
    ... (3 more lines) ...
    data: {"type":"response.completed","response":{"metadata":{},"output":[{"content":[{"text":"persimmon","type":"output_text","logprobs":[]}],"role":"as ...
    data: [DONE]
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 4.4999999999999996e-05, "applied_guardrails": [], "guardrail_information": []}
    

Mask: streamed Messages (Anthropic) asking for the masked word

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/messages \
      -d '{"model":"claude-haiku-4-5","stream":true,"max_tokens":50,"messages":[{"role":"user","content":"Reply with exactly the word persimmon and nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-policies: response-governance
    ... (7 more lines) ...
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"pers"}              }
    ... (1 more lines) ...
    data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"immon"}    }
    ... (4 more lines) ...
    event: message_stop
    data: {"type":"message_stop"        }
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 4.9e-05, "applied_guardrails": [], "guardrail_information": []}
    

Block without streaming: chat asking for the blocked word

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini","messages":[{"role":"user","content":"Reply with exactly the word kumquat and nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-policies: response-governance
    {"choices": [{"finish_reason": "stop", "index": 0, "message": {"content": "kumquat", "role": "assistant", "provider_specific_fields": {"refusal": null}, "annotations": []}, "provider_specific_fields": {}}], "usage": {"completion_tokens": 5, "prompt_tokens": 17, "total_tokens": 22, "completion_tokens ...
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 3.525e-05, "applied_guardrails": [], "guardrail_information": []}
    

Fail-open 5 for a guardrail with only the streaming iterator hook, added and stepped by a post_call pipeline

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini-legacy-stream","stream":true,"messages":[{"role":"user","content":"Reply with exactly the word hello, lowercase, nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-policies: legacy-stream-governance
    ... (1 more lines) ...
    data: {"choices":[{"index":0,"delta":{"content":"hello"}}]}
    data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
    data: [DONE]
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 3.15e-05, "applied_guardrails": [], "guardrail_information": []}
    

Control: request-level flat guardrail that yields every chunk then raises 400 (the merge base's end-of-stream block)

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini-endblock","stream":true,"guardrails":["legacy-end-block"],"messages":[{"role":"user","content":"Reply with exactly the word hello, lowercase, nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-guardrails: legacy-end-block
    ... (1 more lines) ...
    data: {"choices":[{"index":0,"delta":{"content":"hello"}}]}
    data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
    
  3. Spend log rows the probe received for that call:

    {"status": "failure", "cost": 0.0, "applied_guardrails": ["legacy-end-block"], "guardrail_information": []}
    {"status": "success", "cost": 3.15e-05, "applied_guardrails": ["legacy-end-block"], "guardrail_information": []}
    

Policy-added dual-stage guardrail stepped by a post_call pipeline: blocked word in the request

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini-dual","messages":[{"role":"user","content":"Reply with exactly the word durian and nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-policies: dual-governance
    {"choices": [{"finish_reason": "stop", "index": 0, "message": {"content": "durian", "role": "assistant", "provider_specific_fields": {"refusal": null}, "annotations": []}, "provider_specific_fields": {}}], "usage": {"completion_tokens": 5, "prompt_tokens": 17, "total_tokens": 22, "completion_tokens_ ...
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 3.525e-05, "applied_guardrails": [], "guardrail_information": []}
    

Same policy: blocked word in the response

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini-dual","messages":[{"role":"user","content":"Reply with exactly the word kumquat and nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-policies: dual-governance
    {"choices": [{"finish_reason": "stop", "index": 0, "message": {"content": "kumquat", "role": "assistant", "provider_specific_fields": {"refusal": null}, "annotations": []}, "provider_specific_fields": {}}], "usage": {"completion_tokens": 5, "prompt_tokens": 17, "total_tokens": 22, "completion_tokens ...
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 3.525e-05, "applied_guardrails": [], "guardrail_information": []}
    

Guardrail returning a replacement response as a post_call pipeline step

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini-rewrite","messages":[{"role":"user","content":"Reply with exactly the word hello, lowercase, nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-policies: response-rewrite
    {"choices": [{"finish_reason": "stop", "index": 0, "message": {"content": "hello", "role": "assistant", "provider_specific_fields": {"refusal": null}, "annotations": []}, "provider_specific_fields": {}}], "usage": {"completion_tokens": 4, "prompt_tokens": 18, "total_tokens": 22, "completion_tokens_d ...
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 3.15e-05, "applied_guardrails": [], "guardrail_information": []}
    

Second config: default_on guardrail also stepped by a post_call pipeline prefixes exactly once

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini-rewrite-default-on","messages":[{"role":"user","content":"Reply with exactly the word hello, lowercase, nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-policies: response-rewrite-default-on
    {"choices": [{"finish_reason": "stop", "index": 0, "message": {"content": "[CROSS-MODE] [DEFAULT-ON] hello", "role": "assistant", "provider_specific_fields": {"refusal": null}, "annotations": []}, "provider_specific_fields": {}}], "usage": {"completion_tokens": 4, "prompt_tokens": 18, "total_tokens" ...
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 3.15e-05, "applied_guardrails": ["response-rewriter-default-on", "response-rewriter-parallel", "response-rewriter-cross-mode"], "guardrail_information": []}
    

Second config: same with run_in_parallel: true

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini-rewrite-parallel","messages":[{"role":"user","content":"Reply with exactly the word hello, lowercase, nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-policies: response-rewrite-parallel
    {"choices": [{"finish_reason": "stop", "index": 0, "message": {"content": "[CROSS-MODE] [DEFAULT-ON] hello", "role": "assistant", "provider_specific_fields": {"refusal": null}, "annotations": []}, "provider_specific_fields": {}}], "usage": {"completion_tokens": 4, "prompt_tokens": 18, "total_tokens" ...
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 3.15e-05, "applied_guardrails": ["response-rewriter-default-on", "response-rewriter-parallel", "response-rewriter-cross-mode"], "guardrail_information": []}
    

Second config: cross-mode guardrail managed by a pre_call pipeline, its post_call stage still runs

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini-rewrite-cross-mode","messages":[{"role":"user","content":"Reply with exactly the word hello, lowercase, nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-policies: response-rewrite-cross-mode
    {"choices": [{"finish_reason": "stop", "index": 0, "message": {"content": "[CROSS-MODE] [DEFAULT-ON] hello", "role": "assistant", "provider_specific_fields": {"refusal": null}, "annotations": []}, "provider_specific_fields": {}}], "usage": {"completion_tokens": 4, "prompt_tokens": 18, "total_tokens" ...
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 3.15e-05, "applied_guardrails": ["response-rewriter-default-on", "response-rewriter-parallel", "response-rewriter-cross-mode"], "guardrail_information": []}
    

After (08b60c4, this PR's tip)

Fail-open 1: guardrail edits a streamed tool-call argument (chat, forced lookup_fruit)

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini","stream":true,"messages":[{"role":"user","content":"Look up the fruit persimmon."}],"tools":[{"type":"function","function":{"name":"lookup_fruit","parameters":{"type":"object","properties":{"fruit":{"type":"string"}},"required":["fruit"]}}}],"tool_choice":{"type":"function","function":{"name":"lookup_fruit"}}}'
  2. Observed:

    HTTP 200
    x-litellm-applied-guardrails: output-word-filter
    x-litellm-applied-policies: response-governance
    data: {"choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"function":{"arguments":"","name":"lookup_fruit"},"type":"function","index":0} ...
    data: {"choices":[{"index":0,"delta":{"tool_calls":[{"function":{"arguments":"{\""},"type":"function","index":0}]}}]}
    data: {"choices":[{"index":0,"delta":{"tool_calls":[{"function":{"arguments":"fruit"},"type":"function","index":0}]}}]}
    data: {"choices":[{"index":0,"delta":{"tool_calls":[{"function":{"arguments":"\":\""},"type":"function","index":0}]}}]}
    data: {"choices":[{"index":0,"delta":{"tool_calls":[{"function":{"arguments":"pers"},"type":"function","index":0}]}}]}
    data: {"choices":[{"index":0,"delta":{"tool_calls":[{"function":{"arguments":"im"},"type":"function","index":0}]}}]}
    data: {"choices":[{"index":0,"delta":{"tool_calls":[{"function":{"arguments":"mon"},"type":"function","index":0}]}}]}
    data: {"choices":[{"index":0,"delta":{"tool_calls":[{"function":{"arguments":"\"}"},"type":"function","index":0}]}}]}
    data: {"choices":[{"finish_reason":"tool_calls","index":0,"delta":{}}],"provider_specific_fields":{"frequency_penalty":0.0,"presence_penalty":0.0,"too ...
    data: [DONE]
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 0.0001275, "applied_guardrails": ["output-word-filter"], "guardrail_information": [["output-word-filter", "success"]]}
    

Fail-open 2: maskable text on a streamed /v1/completions call

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/completions \
      -d '{"model":"gpt-4.1-mini","stream":true,"max_tokens":20,"prompt":"Reply with exactly the word persimmon and nothing else."}'
  2. Observed:

    HTTP 200
    x-litellm-applied-guardrails: output-word-filter
    x-litellm-applied-policies: response-governance
    ... (1 more lines) ...
    data: {"choices":[{"index":0,"text":"pers"}],"usage":{"completion_tokens":0,"prompt_tokens":0,"total_tokens":0}}
    data: {"choices":[{"index":0,"text":"im"}],"usage":{"completion_tokens":0,"prompt_tokens":0,"total_tokens":0}}
    data: {"choices":[{"index":0,"text":"mon"}],"usage":{"completion_tokens":0,"prompt_tokens":0,"total_tokens":0}}
    data: {"choices":[{"finish_reason":"stop","index":0}],"usage":{"completion_tokens":0,"prompt_tokens":0,"total_tokens":0}}
    ... (1 more lines) ...
    data: [DONE]
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 1.24e-05, "applied_guardrails": ["output-word-filter"], "guardrail_information": []}
    

Fail-open 3: maskable text on a streamed chat call with n: 2

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-4.1-mini","stream":true,"n":2,"messages":[{"role":"user","content":"Reply with exactly the word persimmon and nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-guardrails: output-word-filter
    x-litellm-applied-policies: response-governance
    ... (1 more lines) ...
    data: {"choices":[{"index":0,"delta":{"content":"pers"}}],"obfuscation":"CDDR29"}
    data: {"choices":[{"index":0,"delta":{"content":"im"}}],"obfuscation":"zGWFQni3"}
    data: {"choices":[{"index":0,"delta":{"content":"mon"}}],"obfuscation":"KAiIUTE"}
    data: {"choices":[{"index":1,"delta":{"content":"pers"}}],"obfuscation":"3ecitH"}
    data: {"choices":[{"index":1,"delta":{"content":"im"}}],"obfuscation":"K2nTMgS7"}
    data: {"choices":[{"index":1,"delta":{"content":"mon"}}],"obfuscation":"Dm1yNLc"}
    data: {"choices":[{"finish_reason":"stop","index":0,"delta":{}}],"obfuscation":"Uboo"}
    data: [DONE]
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 1.7199999999999998e-05, "applied_guardrails": ["output-word-filter"], "guardrail_information": [["output-word-filter", "success"]]}
    

Fail-open 4: background: true Responses submit asking for the blocked word

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/responses \
      -d '{"model":"gpt-5.4-mini","background":true,"input":"Reply with exactly the word kumquat and nothing else."}'
  2. Observed:

    HTTP 200
    x-litellm-applied-guardrails: output-word-filter
    x-litellm-applied-policies: response-governance
    {"error": null, "incomplete_details": null, "instructions": null, "metadata": {}, "output": [], "parallel_tool_calls": true, "temperature": 1.0, "tool_choice": "auto", "tools": [], "top_p": 0.98, "max_output_tokens": null, "previous_response_id": null, "reasoning": {"context": "current_turn", "effor ... ": "none", "mode": "standard", "summary": null}, "status": "queued", "text": {"format": {"type": "text"}, "verbosity": "medium"}, "truncation": "d ...
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 0.0, "applied_guardrails": ["output-word-filter"], "guardrail_information": []}
    

Fail-open 4, retrieval: GET /v1/responses/{id} for that background response

  1. Command:

    curl -sS -i "${auth[@]}" http://localhost:$PORT/v1/responses/$RESP_ID
  2. Observed:

    HTTP 200
    {"error": null, "incomplete_details": null, "instructions": null, "metadata": {}, "output": [{"content": [{"text": "kumquat", "type": "output_text", "logprobs": []}], "role": "assistant", "status": "completed", "type": "message", "phase": "final_answer"}], "parallel_tool_calls": true, "temperature": ...
    

Fail-open 5: streamed chat under a pipeline whose guardrail has only the legacy success hook

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini-legacy","stream":true,"messages":[{"role":"user","content":"Reply with exactly the word persimmon and nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-guardrails: legacy-rewriter
    x-litellm-applied-policies: legacy-governance
    ... (1 more lines) ...
    data: {"choices":[{"index":0,"delta":{"content":"pers"}}]}
    data: {"choices":[{"index":0,"delta":{"content":"im"}}]}
    data: {"choices":[{"index":0,"delta":{"content":"mon"}}]}
    data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
    data: [DONE]
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 4.0499999999999995e-05, "applied_guardrails": ["legacy-rewriter"], "guardrail_information": []}
    

Same legacy pipeline without streaming: the rewrite is delivered

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini-legacy","messages":[{"role":"user","content":"Reply with exactly the word persimmon and nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-guardrails: legacy-rewriter
    x-litellm-applied-policies: legacy-governance
    {"choices": [{"finish_reason": "stop", "index": 0, "message": {"content": "[REWRITTEN BY LEGACY HOOK] persimmon", "role": "assistant", "provider_specific_fields": {"refusal": null}, "annotations": []}, "provider_specific_fields": {}}], "usage": {"completion_tokens": 6, "prompt_tokens": 18, "total_to ...
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 4.0499999999999995e-05, "applied_guardrails": ["legacy-rewriter"], "guardrail_information": []}
    

Block: streamed chat asking for the blocked word (the rows are the streaming block's logging contract)

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini","stream":true,"messages":[{"role":"user","content":"Reply with exactly the word kumquat and nothing else."}]}'
  2. Observed:

    HTTP 400
    x-litellm-applied-guardrails: output-word-filter
    x-litellm-applied-policies: response-governance
    data: {"error": {"message": "Content blocked: keyword 'kumquat' detected", "type": "invalid_request_error", "param": null, "code": "400", "provider_sp ...
    data: [DONE]
    
  3. Spend log rows the probe received for that call:

    {"status": "failure", "cost": 0.0, "applied_guardrails": ["output-word-filter"], "guardrail_information": [["output-word-filter", "guardrail_intervened"]]}
    {"status": "success", "cost": 3.525e-05, "applied_guardrails": ["output-word-filter"], "guardrail_information": [["output-word-filter", "guardrail_intervened"]]}
    

Mask: streamed chat asking for the masked word

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini","stream":true,"messages":[{"role":"user","content":"Reply with exactly the word persimmon and nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-guardrails: output-word-filter
    x-litellm-applied-policies: response-governance
    data: {"choices":[{"index":0,"delta":{"role":"assistant","content":"[KEYWORD_REDACTED]"}}]}
    ... (3 more lines) ...
    data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
    data: [DONE]
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 4.0499999999999995e-05, "applied_guardrails": ["output-word-filter"], "guardrail_information": [["output-word-filter", "success"]]}
    

Mask: streamed Responses asking for the masked word

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/responses \
      -d '{"model":"gpt-5.4-mini","stream":true,"input":"Reply with exactly the word persimmon and nothing else."}'
  2. Observed:

    HTTP 200
    x-litellm-applied-guardrails: output-word-filter
    x-litellm-applied-policies: response-governance
    ... (4 more lines) ...
    data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"[KEYWORD_REDACTED]","model":"gpt-5.4-mini"}
    ... (5 more lines) ...
    data: {"type":"response.completed","response":{"metadata":{},"output":[{"content":[{"text":"[KEYWORD_REDACTED]","type":"output_text","logprobs":[]}]," ...
    data: [DONE]
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 4.4999999999999996e-05, "applied_guardrails": ["output-word-filter"], "guardrail_information": [["output-word-filter", "success"]]}
    

Mask: streamed Messages (Anthropic) asking for the masked word

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/messages \
      -d '{"model":"claude-haiku-4-5","stream":true,"max_tokens":50,"messages":[{"role":"user","content":"Reply with exactly the word persimmon and nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-guardrails: output-word-filter
    x-litellm-applied-policies: response-governance
    ... (5 more lines) ...
    data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "[KEYWORD_REDACTED]"}}
    ... (6 more lines) ...
    event: message_stop
    data: {"type":"message_stop"          }
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 4.9e-05, "applied_guardrails": ["output-word-filter"], "guardrail_information": [["output-word-filter", "success"]]}
    

Block without streaming: chat asking for the blocked word

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini","messages":[{"role":"user","content":"Reply with exactly the word kumquat and nothing else."}]}'
  2. Observed:

    HTTP 400
    x-litellm-applied-guardrails: output-word-filter
    x-litellm-applied-policies: response-governance
    {"error": {"message": "Content blocked: keyword 'kumquat' detected", "type": "invalid_request_error", "param": null, "code": "400", "provider_specific_fields": {"error": "Content blocked: keyword 'kumquat' detected", "keyword": "kumquat", "description": null, "guardrail_name": "output-word-filter",  ...
    
  3. Spend log rows the probe received for that call:

    {"status": "failure", "cost": 0.0, "applied_guardrails": ["output-word-filter"], "guardrail_information": [["output-word-filter", "guardrail_intervened"]]}
    

Fail-open 5 for a guardrail with only the streaming iterator hook, added and stepped by a post_call pipeline

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini-legacy-stream","stream":true,"messages":[{"role":"user","content":"Reply with exactly the word hello, lowercase, nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-guardrails: legacy-stream-guard
    x-litellm-applied-policies: legacy-stream-governance
    ... (1 more lines) ...
    data: {"choices":[{"index":0,"delta":{"content":"[LEGACY-GUARD stream ran] hello"}}]}
    data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
    data: [DONE]
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 3.15e-05, "applied_guardrails": ["legacy-stream-guard"], "guardrail_information": []}
    

Control: request-level flat guardrail that yields every chunk then raises 400 (the merge base's end-of-stream block)

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini-endblock","stream":true,"guardrails":["legacy-end-block"],"messages":[{"role":"user","content":"Reply with exactly the word hello, lowercase, nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-guardrails: legacy-end-block
    ... (1 more lines) ...
    data: {"choices":[{"index":0,"delta":{"content":"hello"}}]}
    data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
    
  3. Spend log rows the probe received for that call:

    {"status": "failure", "cost": 0.0, "applied_guardrails": ["legacy-end-block"], "guardrail_information": []}
    {"status": "success", "cost": 3.15e-05, "applied_guardrails": ["legacy-end-block"], "guardrail_information": []}
    

Policy-added dual-stage guardrail stepped by a post_call pipeline: blocked word in the request

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini-dual","messages":[{"role":"user","content":"Reply with exactly the word durian and nothing else."}]}'
  2. Observed:

    HTTP 400
    x-litellm-applied-policies: dual-governance
    {"error": {"message": "Content blocked: keyword 'durian' detected", "type": "invalid_request_error", "param": null, "code": "400", "provider_specific_fields": {"error": "Content blocked: keyword 'durian' detected", "keyword": "durian", "description": null, "guardrail_name": "input-word-filter", "gua ...
    
  3. Spend log rows the probe received for that call:

    {"status": "failure", "cost": 0.0, "applied_guardrails": [], "guardrail_information": [["input-word-filter", "guardrail_intervened"]]}
    

Same policy: blocked word in the response

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini-dual","messages":[{"role":"user","content":"Reply with exactly the word kumquat and nothing else."}]}'
  2. Observed:

    HTTP 400
    x-litellm-applied-policies: dual-governance
    {"error": {"message": "Content blocked: keyword 'kumquat' detected", "type": "invalid_request_error", "param": null, "code": "400", "provider_specific_fields": {"error": "Content blocked: keyword 'kumquat' detected", "keyword": "kumquat", "description": null, "guardrail_name": "input-word-filter", " ...
    
  3. Spend log rows the probe received for that call:

    {"status": "failure", "cost": 0.0, "applied_guardrails": [], "guardrail_information": [["input-word-filter", "guardrail_intervened"]]}
    

Guardrail returning a replacement response as a post_call pipeline step

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini-rewrite","messages":[{"role":"user","content":"Reply with exactly the word hello, lowercase, nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-guardrails: response-rewriter
    x-litellm-applied-policies: response-rewrite
    {"choices": [{"finish_reason": "stop", "index": 0, "message": {"content": "[REWRITTEN BY PIPELINE] hello", "role": "assistant", "provider_specific_fields": {"refusal": null}, "annotations": []}, "provider_specific_fields": {}}], "usage": {"completion_tokens": 4, "prompt_tokens": 18, "total_tokens":  ...
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 3.15e-05, "applied_guardrails": ["response-rewriter"], "guardrail_information": []}
    

Second config: default_on guardrail also stepped by a post_call pipeline prefixes exactly once

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini-rewrite-default-on","messages":[{"role":"user","content":"Reply with exactly the word hello, lowercase, nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-guardrails: response-rewriter-default-on
    x-litellm-applied-policies: response-rewrite-default-on
    {"choices": [{"finish_reason": "stop", "index": 0, "message": {"content": "[CROSS-MODE] [DEFAULT-ON] hello", "role": "assistant", "provider_specific_fields": {"refusal": null}, "annotations": []}, "provider_specific_fields": {}}], "usage": {"completion_tokens": 4, "prompt_tokens": 18, "total_tokens" ...
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 3.15e-05, "applied_guardrails": ["response-rewriter-default-on"], "guardrail_information": []}
    

Second config: same with run_in_parallel: true

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini-rewrite-parallel","messages":[{"role":"user","content":"Reply with exactly the word hello, lowercase, nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-guardrails: response-rewriter-parallel
    x-litellm-applied-policies: response-rewrite-parallel
    {"choices": [{"finish_reason": "stop", "index": 0, "message": {"content": "[CROSS-MODE] [DEFAULT-ON] [PARALLEL] hello", "role": "assistant", "provider_specific_fields": {"refusal": null}, "annotations": []}, "provider_specific_fields": {}}], "usage": {"completion_tokens": 4, "prompt_tokens": 18, "to ...
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 3.15e-05, "applied_guardrails": ["response-rewriter-parallel"], "guardrail_information": []}
    

Second config: cross-mode guardrail managed by a pre_call pipeline, its post_call stage still runs

  1. Command:

    curl -sS -N -i "${auth[@]}" http://localhost:$PORT/v1/chat/completions \
      -d '{"model":"gpt-5.4-mini-rewrite-cross-mode","messages":[{"role":"user","content":"Reply with exactly the word hello, lowercase, nothing else."}]}'
  2. Observed:

    HTTP 200
    x-litellm-applied-guardrails: response-rewriter-cross-mode
    x-litellm-applied-policies: response-rewrite-cross-mode
    {"choices": [{"finish_reason": "stop", "index": 0, "message": {"content": "[CROSS-MODE] [DEFAULT-ON] hello", "role": "assistant", "provider_specific_fields": {"refusal": null}, "annotations": []}, "provider_specific_fields": {}}], "usage": {"completion_tokens": 4, "prompt_tokens": 18, "total_tokens" ...
    
  3. Spend log rows the probe received for that call:

    {"status": "success", "cost": 3.15e-05, "applied_guardrails": ["response-rewriter-cross-mode"], "guardrail_information": []}
    

QA observations (things a reviewer cannot see from the diff):

  • Tip logs one warning per discarded rewrite or released stream (two rewrite discards and one background skip in this run)
  • /v1/completions stream: nothing scans it, the step reports pass and the header names the guardrail (LIT-7177)
  • /policies/test-pipeline passes post_call pipelines with no response; unchanged
  • A block after the last upstream chunk logs a failure row (cost 0) plus the deferred success row with the real cost, on both sides (flat end-of-stream block on base and tip, pipeline block on tip)
  • /v1/messages block error body is a stringified dict; pre-existing, LIT-6466

Type

🐛 Bug Fix

Caveats (if any)

Severe

  • Every stream under a post_call pipeline is buffered whole before its first byte
    • Time to first token becomes time to last token: 227 chunks in one burst at 2.73s, against a first chunk at 1.76s without the pipeline
    • Inherent to scanning the assembled response; plan for it before attaching a post_call pipeline to streaming traffic

Medium

  • Streams the pipeline cannot govern yet are released with only a proxy warning
    • A guardrail rewrite of streamed tool-call arguments is discarded (LIT-7174)
    • A pipeline guardrail without the unified apply_guardrail interface is released unscanned (LIT-7176)
    • A streamed /v1/completions call is released unscanned while its step reports a pass and the header names the guardrail (LIT-7177)
  • background: true Responses are accepted and never governed by a post_call pipeline (LIT-7175)

Low

  • Rewrites on n > 1 chat streams, streams without a finish marker, and envelope-less Responses streams are discarded and the originals released (LIT-7178)
  • A stream on a route with no guardrail translation is released unscanned with a warning (LIT-7179)
  • /policies/test-pipeline still reports a vacuous "pass" for post_call pipelines, since it has no response to scan
  • Non-streaming runs pipelines before the flat guardrail loop, streaming runs them after it; both run every guardrail once
  • modify_response on a chat or Responses stream surfaces as an SSE error frame (from feat(policy_engine): execute post_call guardrail pipelines on streaming responses #38788)

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

  • 996019c, 2247fbc (streaming, feat(policy_engine): execute post_call guardrail pipelines on streaming responses #38788), 45a6b1d (staging merge plus lint-gate refactors), badefa3 (snapshots guardrail inputs before apply_guardrail), bcee01a (merges guardrail metadata writes back on block and modify_response), 95af93a (second staging merge, in-stream error frames) and 192ea9e (fails open on the streaming shapes the pipeline cannot govern yet) each passed /live-pr-risk at their tip: one regression test per fix that fails without it, the pipeline suites, a make check PASS, and the spot legs re-run at that tip

  • 69d2ac1, 91fc1b2, d08a177 and 08b60c4 (the round-1 caveat fixes: an iterator-hook guardrail the pipeline cannot stream governs the stream on its own, a streaming pipeline step is logged once and named in the applied-guardrails header, a policy-added dual-stage guardrail keeps its other stage, and the dead rewrites_streamed_output hook is gone) verified by one regression test each that fails without its fix, mutation-checked, a make check PASS before each commit, and the full live A/B above re-run at 08b60c4 against the merge base 9d0c9b9


Note

High Risk
Changes core proxy guardrail and policy-engine paths for all post_call responses and buffered streams, including when rewrites are applied or silently discarded.

Overview
Post-call policy pipelines now run on success responses and on fully buffered streaming traffic, instead of being parsed but never applied. The proxy executes pipeline steps through PipelineExecutor, skips duplicate flat guardrail runs for steps in a pipeline of the same mode, and merges applied-guardrail / logging metadata back onto the live request.

For ended streams, Anthropic Messages, OpenAI chat completions, and Responses translations can opt in with delivers_ended_stream_text_rewrites and deliver_ended_stream_rewrites=True so text masks are written into buffered chunks (first delta carries full rewritten text, later ones blanked; Responses also syncs prior events). Rewrites that cannot be delivered—unfinished streams, multi-choice chat, tool-call edits, routes without translation—raise UndeliverableStreamRewrite or are detected by _StreamRewriteObserver; the executor restores original chunks and passes the step with a warning. Streams the pipeline cannot govern (legacy hooks, /v1/completions, background Responses) are released unchanged with warnings, matching prior fail-open behavior.

Non-streaming post_call steps can return replacement responses that chain across steps. OpenAI streaming apply logic now keys choices by choice.index rather than list position.

Reviewed by Cursor Bugbot for commit 6475443. 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 for ordinary and buffered streaming responses while preserving legacy fail-open behavior for unsupported streaming shapes.

  • Executes post-call pipeline steps against responses and propagates blocks and replacement responses.
  • Buffers supported chat, Responses, and Anthropic streams, then writes deliverable text rewrites back into their events.
  • Scopes callback exclusions by pipeline mode and streaming capability so independently applicable guardrail stages and legacy streaming hooks still run.
  • Preserves guardrail metadata for response headers, spend logging, and blocked-stream accounting.
  • Adds regression coverage for pipeline execution, streaming rewrites, callback selection, metadata propagation, and unsupported shapes.

Confidence Score: 5/5

The PR appears safe to merge; no actionable new defects or outstanding previous findings remain.

The current implementation runs supported post-call response pipelines, preserves standalone guardrail execution where pipelines cannot govern a stream, propagates response rewrites and enforcement metadata, and deliberately releases unsupported shapes according to the documented compatibility behavior. Previously reported duplicate execution, metadata propagation, cross-mode suppression, and mixed-pipeline concerns are fixed, conceded, withdrawn, or resolved.

Important Files Changed

Filename Overview
litellm/proxy/policy_engine/pipeline_executor.py Adds post-call response and buffered-stream pipeline execution, rewrite detection, metadata propagation, and fail-open handling for undeliverable stream rewrites.
litellm/proxy/utils.py Integrates post-call pipelines into response callbacks and streaming iterator processing while scoping standalone guardrail suppression to executable pipelines.
litellm/proxy/litellm_pre_call_utils.py Retains policy-resolved guardrails in request metadata so stages outside the pipeline's lifecycle mode can still execute.
litellm/llms/openai/chat/guardrail_translation/handler.py Writes supported ended-stream chat rewrites into buffered chunks and keys multi-choice processing by logical choice index.
litellm/llms/openai/responses/guardrail_translation/handler.py Applies terminal-envelope guardrails and synchronizes rewritten text across earlier Responses API stream events.
litellm/llms/anthropic/chat/guardrail_translation/handler.py Delivers ended Anthropic Messages text rewrites across parsed or raw SSE chunks while rejecting undeliverable unfinished rewrites.
litellm/proxy/guardrails/guardrail_hooks/unified_guardrail/unified_guardrail.py Exposes shared streaming translation and error-handling helpers used by buffered policy pipelines.
tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py Extends regression coverage to ensure skipped pipelines do not suppress eligible standalone streaming hooks.

Reviews (14): Last reviewed commit: "fix(policy_engine): run per-chunk hook g..." | Re-trigger Greptile

Comment thread litellm/proxy/utils.py Resolved
@veria-ai

veria-ai Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

This pull request updates the policy engine so post-call guardrail pipelines execute on both standard responses and streaming responses.

Three security issues have been addressed, with one availability concern remaining. An authenticated caller using a post-call pipeline can keep large streaming responses in flight, causing unbounded buffering that may exhaust worker memory. Bounding or externally spooling buffered response data would resolve the remaining risk.

Open issues (1)

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

@codecov

codecov Bot commented Aug 29, 2026 •

Copy link
Copy Markdown

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

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

Copy link
Copy Markdown
Contributor Author

@greptileai

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.

Autofix Details

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

  • ✅ Fixed: Post-call pipeline metadata writes discarded
    • On the post_call allow path, _handle_pipeline_result now copies the metadata and litellm_metadata buckets from the pipeline's working data back onto the request, and the executor restores the pre-step guardrails marker in a finally so the internal marker still cannot leak.

Create PR

Or push these changes by commenting:

@cursor push 33b123e42c
Preview (33b123e42c)
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
@@ -177,12 +177,14 @@
             verbose_proxy_logger.warning("Pipeline: guardrail '%s' not found in callbacks", step.guardrail)
             return ("error", None, f"Guardrail '{step.guardrail}' not found", None)
 
+        if "metadata" not in data:
+            data["metadata"] = {}
+        metadata_dict: Final = data["metadata"]
+        original_guardrails_present: Final = "guardrails" in metadata_dict
+        original_guardrails: Final = metadata_dict.get("guardrails")
+        metadata_dict["guardrails"] = [step.guardrail]
+
         try:
-            # Inject guardrail name into metadata so should_run_guardrail() allows it
-            if "metadata" not in data:
-                data["metadata"] = {}
-            data["metadata"]["guardrails"] = [step.guardrail]
-
             # A scan_raw_request step evaluates the pristine pre-pipeline
             # snapshot instead of `data` (which earlier pass_data steps in
             # this same pipeline may have already rewritten), same reason
@@ -245,6 +247,11 @@
             else:
                 verbose_proxy_logger.error("Pipeline: unexpected error from guardrail '%s': %s", step.guardrail, e)
                 return ("error", None, str(e), e)
+        finally:
+            if original_guardrails_present:
+                metadata_dict["guardrails"] = original_guardrails
+            else:
+                metadata_dict.pop("guardrails", None)
 
     @staticmethod
     def find_guardrail_callback(guardrail_name: str) -> CustomGuardrail | None:

diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -1670,8 +1670,13 @@
         response carried in ``modified_data`` is adopted by the caller.
         """
         if result.terminal_action == "allow":
-            if result.modified_data is not None and original_response is None:
-                data.update(result.modified_data)
+            if result.modified_data is not None:
+                if original_response is None:
+                    data.update(result.modified_data)
+                else:
+                    for key in ("metadata", "litellm_metadata"):
+                        if key in result.modified_data:
+                            data[key] = result.modified_data[key]
             return data
 
         if result.terminal_action == "block":

diff --git a/tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py b/tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py
--- a/tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py
+++ b/tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py
@@ -10,7 +10,7 @@
 from __future__ import annotations
 
 import asyncio
-from typing import Any, Dict, List
+from typing import Any, Dict, Final, List
 from unittest.mock import AsyncMock, MagicMock, patch
 
 import pytest
@@ -920,6 +920,49 @@
 
 
 @pytest.mark.asyncio
+async def test_post_call_pipeline_pass_propagates_metadata_writes_to_request_data(
+    proxy_logging, make_user_api_key_auth, monkeypatch
+):
+    """A post_call pipeline step's writes to the metadata bucket
+    (standard_logging_guardrail_information for spend logs / Langfuse / Datadog
+    and applied_guardrails for the x-litellm-applied-guardrails header) must
+    reach the outer request data. The working-copy the executor gives the hook
+    is otherwise discarded, so deferred async logging and the response header
+    look as if the guardrail never ran."""
+
+    class RecordingGuardrail(CustomGuardrail):
+        async def async_post_call_success_hook(self, data, user_api_key_dict, response):
+            from litellm.proxy.common_utils.callback_utils import (
+                add_guardrail_to_applied_guardrails_header,
+            )
+
+            metadata = data.setdefault("metadata", {})
+            metadata.setdefault("standard_logging_guardrail_information", []).append(
+                {"guardrail_name": "gr-post"}
+            )
+            add_guardrail_to_applied_guardrails_header(request_data=data, guardrail_name="gr-post")
+            return None
+
+    monkeypatch.setattr(
+        litellm,
+        "callbacks",
+        [RecordingGuardrail(guardrail_name="gr-post", event_hook=GuardrailEventHooks.post_call, default_on=False)],
+    )
+    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None, raising=False)
+    data = _post_call_pipeline_data()
+
+    await proxy_logging.post_call_success_hook(
+        data=data, response=litellm.ModelResponse(), user_api_key_dict=make_user_api_key_auth()
+    )
+
+    metadata = data["metadata"]
+    assert metadata["applied_guardrails"] == ["gr-post"]
+    assert metadata["standard_logging_guardrail_information"] == [{"guardrail_name": "gr-post"}]
+    assert "guardrails" not in metadata
+    assert "response" not in data
+
+
+@pytest.mark.asyncio
 async def test_post_call_pipeline_pass_runs_once_and_leaves_request_data_untouched(
     proxy_logging, make_user_api_key_auth, monkeypatch
 ):
@@ -1139,18 +1182,32 @@
     assert info.value.original_response is response
 
 
-def test_handle_pipeline_result_allow_discards_modifications_on_post_call():
-    data = {"a": 1, "metadata": {"guardrails": ["other"]}}
+def test_handle_pipeline_result_allow_propagates_metadata_on_post_call():
+    """The post_call path must keep the request payload intact (already sent
+    upstream) but still adopt metadata mutations from the pipeline's working
+    copy: standard_logging_guardrail_information and applied_guardrails are
+    written there and must reach deferred async logging plus the
+    x-litellm-applied-guardrails header."""
+    replacement_response: Final = object()
+    data = {"a": 1, "metadata": {"guardrails": ["other"]}, "litellm_metadata": {"foo": "bar"}}
     result = MagicMock()
     result.terminal_action = "allow"
-    result.modified_data = {"metadata": {"guardrails": ["gr-post"]}, "response": object()}
+    result.modified_data = {
+        "metadata": {"guardrails": ["gr-post"], "applied_guardrails": ["gr-post"]},
+        "litellm_metadata": {"foo": "bar", "extra": 1},
+        "response": replacement_response,
+    }
 
     out = ProxyLogging._handle_pipeline_result(
         result=result, data=data, policy_name="p", original_response=litellm.ModelResponse()
     )
 
     assert out is data
-    assert data == {"a": 1, "metadata": {"guardrails": ["other"]}}
+    assert data == {
+        "a": 1,
+        "metadata": {"guardrails": ["gr-post"], "applied_guardrails": ["gr-post"]},
+        "litellm_metadata": {"foo": "bar", "extra": 1},
+    }
 
 
 @pytest.mark.asyncio

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

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

codspeed Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_fix_post_call_policy_pipeline (6475443) with litellm_internal_staging (35451ec)

Open in CodSpeed

…ect background bypass

Post_call pipelines run step hooks against a copied request dict, so guardrail
writes into the metadata bucket (applied_guardrails for the response header,
standard_logging_guardrail_information for spend logs) were dropped when the
guardrail was the first writer. Merge those writes back onto the request on the
post_call allow path, keeping the request payload and the executor's per-step
guardrails activation flag out of it.

Background /v1/responses requests dodge the streaming 400: pre_call sees stream
unset, then the polling task forces stream=true with pre-call logic skipped and
the streaming branch returns before post_call_success_hook, silently bypassing
post_call pipelines. Reject background=true at pre_call the same way as
stream=true.

Also pin the run_in_parallel pipeline-managed exclusion in both hook loops with
regression tests.
@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.

Stale Bugbot comment from a previous run.

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
…t_call_pipeline_stream_rewrite

Brings the stack base up to origin/litellm_internal_staging. Staging's
get_streaming_string_so_far now joins delta-only Responses parts itself, so
the handler's separate delta joiner and the flag-gated delta scan go away
and the fallback keeps failing closed on a rewrite it cannot deliver. The
two tests that pinned the old flag-gated behaviour are dropped in favour of
staging's delta-assembly tests, and _process_ended_stream takes the same
UserAPIKeyAuth | None the typed process_output_response now expects
… event

An Anthropic buffer without a stop_reason only ran the flat text scan, so a
rewrite there was dropped while the executor trusted the translation to have
delivered it. A Responses buffer ending at response.output_item.done returned
after the tool-call scan without ever checking the text. Both now reach the
flat scan and raise UndeliverableStreamRewrite when a caller expects the
rewrite delivered, matching the existing Responses no-envelope fallback.
…eam_rewrite

fix(policy_engine): apply post_call pipeline text rewrites on streams
… cannot govern yet

A post_call pipeline now releases the original stream instead of refusing the
request on every shape it has no handler for: a background request, a pipeline
guardrail without the unified apply_guardrail interface, a route with no
endpoint translation, a buffered stream no translation resolves, and a rewrite
the translation cannot write back (tool-call edits, text edits on translations
without write-back, n>1 chat, an unended Anthropic stream, a Responses dump
with no event envelope). Each case logs a warning naming the policy and
guardrail. Real blocks and writable text masks are unchanged.
@mateo-berri
mateo-berri requested a review from a team September 8, 2026 00:55
@mateo-berri mateo-berri added run-ci and removed run-ci labels Sep 8, 2026
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

…line cannot stream

The streaming loop skipped every guardrail stepped by a post_call pipeline, even when the pipeline was dropped from the stream for lacking the unified apply_guardrail interface, so a default_on guardrail that only implements async_post_call_streaming_iterator_hook stopped governing streams it governed on the merge base. The skip set now comes from the pipelines that will gate the stream
…applied guardrails header

CustomGuardrail.__init_subclass__ wrapped _StreamRewriteObserver.apply_guardrail in log_guardrail_information, so every streaming step recorded a second standard_logging_guardrail_information entry and span next to the inner guardrail's own. The observer's method now carries the marker that skips the wrapper. The step also adds the guardrail to the applied guardrails header the way the non-streaming unified path does, so streamed spend rows name the guardrail that scanned them
… a pipeline steps it

A policy that both adds a guardrail and steps it in a post_call pipeline
used to drop the guardrail from the request's guardrail list outright, so
its pre_call stage never ran. The per-hook loops already skip guardrails
by pipeline mode, so the mode-agnostic subtraction only lost coverage
Nothing calls it since the streaming pipeline detects rewrites at run time
through the stream observer, so the base method and the content filter's
override were dead code with dead tests
@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@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: Per-chunk skip ignores streamable set
    • Filtered the per-chunk async_post_call_streaming_hook against _streamable_post_call_pipelines (matching the iterator hook) so non-streamable pipeline steps' per-chunk hooks still run on the stream instead of being silently dropped.

Create PR

Or push these changes by commenting:

@cursor push 7c69d96185
Preview (7c69d96185)
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -3272,7 +3272,9 @@
             _cached_guardrail_data: dict | None = None
             _guardrail_data_computed = False
             pipeline_managed: Final = (
-                _pipeline_managed_guardrail_names(data, "post_call") if caps.has_guardrail else frozenset()
+                _pipeline_step_guardrail_names(_streamable_post_call_pipelines(data, user_api_key_dict))
+                if caps.has_guardrail
+                else frozenset()
             )
 
             for callback in litellm.callbacks:

diff --git a/tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py b/tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py
--- a/tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py
+++ b/tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py
@@ -2118,20 +2118,28 @@
 
 
 @pytest.mark.asyncio
-async def test_per_chunk_streaming_hook_skips_pipeline_managed_guardrail(
+async def test_per_chunk_streaming_hook_skips_streamable_pipeline_managed_guardrail(
     proxy_logging, make_user_api_key_auth, monkeypatch
 ):
     seen: Dict[str, Any] = {}
 
-    class RecordingGuardrail(CustomGuardrail):
+    class StreamableRecordingGuardrail(CustomGuardrail):
+        async def apply_guardrail(self, inputs, request_data, input_type, logging_obj=None):
+            return inputs
+
         async def async_post_call_streaming_hook(self, user_api_key_dict, response):
             seen[self.guardrail_name] = seen.get(self.guardrail_name, 0) + 1
             return None
 
-    managed = RecordingGuardrail(
+    class FreeRecordingGuardrail(CustomGuardrail):
+        async def async_post_call_streaming_hook(self, user_api_key_dict, response):
+            seen[self.guardrail_name] = seen.get(self.guardrail_name, 0) + 1
+            return None
+
+    managed = StreamableRecordingGuardrail(
         guardrail_name="gr-post", event_hook=GuardrailEventHooks.post_call, default_on=True
     )
-    free = RecordingGuardrail(
+    free = FreeRecordingGuardrail(
         guardrail_name="gr-free", event_hook=GuardrailEventHooks.post_call, default_on=True
     )
     monkeypatch.setattr(litellm, "callbacks", [managed, free])
@@ -2147,3 +2155,36 @@
     assert result is not None
     assert seen.get("gr-post") is None
     assert seen["gr-free"] == 1
+
+
+@pytest.mark.asyncio
+async def test_per_chunk_streaming_hook_runs_non_streamable_pipeline_managed_guardrail(
+    proxy_logging, make_user_api_key_auth, monkeypatch
+):
+    """Regression: a pipeline step whose guardrail only overrides the per-chunk
+    hook (no ``apply_guardrail``) leaves its pipeline non-streamable, so the
+    gated stream cannot govern it. The per-chunk hook must still run against
+    the stream; otherwise the guardrail is dropped entirely on streaming
+    responses even though it ran before pipelines existed."""
+    seen: Dict[str, Any] = {}
+
+    class RecordingGuardrail(CustomGuardrail):
+        async def async_post_call_streaming_hook(self, user_api_key_dict, response):
+            seen[self.guardrail_name] = seen.get(self.guardrail_name, 0) + 1
+            return None
+
+    managed = RecordingGuardrail(
+        guardrail_name="gr-post", event_hook=GuardrailEventHooks.post_call, default_on=True
+    )
+    monkeypatch.setattr(litellm, "callbacks", [managed])
+    monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None, raising=False)
+    data = _post_call_pipeline_data(stream=True)
+
+    result = await proxy_logging.async_post_call_streaming_hook(
+        data=data,
+        response=_stream_chunks()[0],
+        user_api_key_dict=make_user_api_key_auth(request_route="/v1/chat/completions"),
+    )
+
+    assert result is not None
+    assert seen["gr-post"] == 1

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

Comment thread litellm/proxy/utils.py Resolved
Comment thread litellm/proxy/utils.py Resolved
…eline cannot stream

The per-chunk streaming hook skipped every guardrail stepped by a post_call pipeline, even when the pipeline is left out of the stream for lacking the unified apply_guardrail interface, so a default_on guardrail that only implements async_post_call_streaming_hook stopped governing streams it governed on the merge base. The skip set now comes from the pipelines that gate the stream, the same way the iterator hook already computes it
@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@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 6475443. Configure here.

@mateo-berri
mateo-berri merged commit 047b8be into litellm_internal_staging Sep 8, 2026
85 of 86 checks passed
@mateo-berri
mateo-berri deleted the litellm_fix_post_call_policy_pipeline branch September 8, 2026 22:19
thibault-linktree pushed a commit to thibault-linktree/litellm that referenced this pull request Sep 10, 2026
A post_call pipeline step whose guardrail only implements the older
async_post_call_success_hook used to skip the stream entirely: PR BerriAI#38721
fails that shape open with a warning. The streaming step now assembles the
buffered stream into the response the hook expects, runs the hook, ends the
stream with the hook's exception when it raises, and delivers the hook's
rewrite through the same event write-back the unified guardrails use on
chat, Responses, and Messages streams (Messages gets the Anthropic shape).
A stream a pipeline manages no longer runs the same hook again after the
stream ends. A guardrail with neither the unified interface nor a post-call
hook keeps the fail-open, as does a rewrite the buffer cannot be patched
with.
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.

2 participants