Repository navigation
fix(policy_engine): execute post_call guardrail pipelines on responses and streams - #38721
mateo-berri merged 37 commits into
Conversation
Greptile SummaryThis PR enables post-call policy pipelines for ordinary and buffered streaming responses while preserving legacy fail-open behavior for unsupported streaming shapes.
Confidence Score: 5/5The 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.
|
| 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
PR overviewThis 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 Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
…path guardrail loop
|
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: 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.
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.asyncioYou can send follow-ups to the cloud agent here.
…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.
|
bugbot run |
…itellm_fix_post_call_policy_pipeline
…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
…itellm_fix_post_call_policy_pipeline
…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
…itellm_fix_post_call_policy_pipeline
… 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.
…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
…itellm_fix_post_call_policy_pipeline
|
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: 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.
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"] == 1You can send follow-ups to the cloud agent here.
…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
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 6475443. Configure here.
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.

TLDR
Problem this solves:
pipeline: {mode: post_call}parsed but never executed on responses/policies/test-pipelineexecuted the same pipeline fine, so operators saw it "work"How it solves it:
blocksteps re-raise the guardrail's own error; in-place edits (masking) propagate to the clientmodify_responseoutcomes now carry the original response, so usage is reported from the real calln > 1, a stream that ended without a finish marker, a Responses stream with noresponseenvelope) is discarded and the original chunks are released; a stream on a route with no guardrail translation, a stream whose pipeline guardrail lacks the unifiedapply_guardrailinterface, and a streamed/v1/completionscall are released unscanned; abackground: truesubmit 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)default_onor added by the policy, and is managed by a pipeline on only one of them still runs its other stagex-litellm-applied-guardrailsand spend logs still name the guardrail that scanned the responsex-litellm-applied-guardrailsrewrites_streamed_outputguardrail hook is goneUser 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
mode: post_calland a step for their output guardrail, attaches it with scope"*", and restarts the proxyx-litellm-applied-policies: response-governance"guardrails": ["output-word-filter"]by hand does the same request return HTTP 400, showing the guardrail works and the policy wiring is deadhellowith no guardrail header, the hook never ranAfter: the same policy blocks and masks what it can govern, and every stream it cannot govern yet flows exactly as it did before
Content blocked: keyword 'kumquat' detected[KEYWORD_REDACTED]in its placex-litellm-applied-policies: response-governanceandx-litellm-applied-guardrails: output-word-filter"stream": truecomes back as HTTP 400 with a single SSE error frameContent blocked: keyword 'kumquat' detected, while a benign streaming request flows as a normal SSE stream ending indata: [DONE], chunks arriving together once the model finishes since the gateway holds the stream until the policy verdict[KEYWORD_REDACTED]in the text deltas"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"background": trueis accepted with HTTP 200 and"status": "queued", and GET http://litellm-domain/v1/responses/{id} returns the completed text ungoverned, as before this PRdefault_onguardrail 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)[LEGACY-GUARD stream ran] hello, andx-litellm-applied-guardrails: legacy-stream-guardContent blocked: keyword 'durian' detectedbefore the model is calledx-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 spendRelevant 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
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)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.yamlcovers every case but the threedefault_onrewrite ones, which run onconfig.rewrite.yaml(a second boot, same worktree). Next to the configs:legacy_hook.pyholdslegacyRewriter(aCustomGuardrailthat only implementsasync_post_call_success_hook, prefixing the reply with[REWRITTEN BY LEGACY HOOK], no unifiedapply_guardrail),legacyStreamGuard(onlyasync_post_call_streaming_iterator_hook, prefixing the first delta with[LEGACY-GUARD stream ran]) andlegacyEndBlock(yields every chunk, then raises 400);response_rewriter.pyreturns a replacementModelResponsefromasync_post_call_success_hookwith a configurable prefix;spend_probe.pyis aCustomLoggerthat appends one JSON line per spend log row (the call id, status, cost,applied_guardrailsand theguardrail_informationentries), so the rows quoted under a case are exactly what the spend log receives for it:Boot, per leg (base worktree at the merge base, tip worktree at this PR's head, same venv;
$PORTis a random free port):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)Command:
Observed:
Spend log rows the probe received for that call:
Fail-open 2: maskable text on a streamed
/v1/completionscallCommand:
Observed:
Spend log rows the probe received for that call:
Fail-open 3: maskable text on a streamed chat call with
n: 2Command:
Observed:
Spend log rows the probe received for that call:
Fail-open 4:
background: trueResponses submit asking for the blocked wordCommand:
Observed:
Spend log rows the probe received for that call:
Fail-open 4, retrieval:
GET /v1/responses/{id}for that background responseCommand:
Observed:
Fail-open 5: streamed chat under a pipeline whose guardrail has only the legacy success hook
Command:
Observed:
Spend log rows the probe received for that call:
Same legacy pipeline without streaming: the rewrite is delivered
Command:
Observed:
Spend log rows the probe received for that call:
Block: streamed chat asking for the blocked word (the rows are the streaming block's logging contract)
Command:
Observed:
Spend log rows the probe received for that call:
Mask: streamed chat asking for the masked word
Command:
Observed:
Spend log rows the probe received for that call:
Mask: streamed Responses asking for the masked word
Command:
Observed:
Spend log rows the probe received for that call:
Mask: streamed Messages (Anthropic) asking for the masked word
Command:
Observed:
Spend log rows the probe received for that call:
Block without streaming: chat asking for the blocked word
Command:
Observed:
Spend log rows the probe received for that call:
Fail-open 5 for a guardrail with only the streaming iterator hook, added and stepped by a post_call pipeline
Command:
Observed:
Spend log rows the probe received for that call:
Control: request-level flat guardrail that yields every chunk then raises 400 (the merge base's end-of-stream block)
Command:
Observed:
Spend log rows the probe received for that call:
Policy-added dual-stage guardrail stepped by a post_call pipeline: blocked word in the request
Command:
Observed:
Spend log rows the probe received for that call:
Same policy: blocked word in the response
Command:
Observed:
Spend log rows the probe received for that call:
Guardrail returning a replacement response as a post_call pipeline step
Command:
Observed:
Spend log rows the probe received for that call:
Second config:
default_onguardrail also stepped by a post_call pipeline prefixes exactly onceCommand:
Observed:
Spend log rows the probe received for that call:
Second config: same with
run_in_parallel: trueCommand:
Observed:
Spend log rows the probe received for that call:
Second config: cross-mode guardrail managed by a pre_call pipeline, its post_call stage still runs
Command:
Observed:
Spend log rows the probe received for that call:
After (08b60c4, this PR's tip)
Fail-open 1: guardrail edits a streamed tool-call argument (chat, forced
lookup_fruit)Command:
Observed:
Spend log rows the probe received for that call:
Fail-open 2: maskable text on a streamed
/v1/completionscallCommand:
Observed:
Spend log rows the probe received for that call:
Fail-open 3: maskable text on a streamed chat call with
n: 2Command:
Observed:
Spend log rows the probe received for that call:
Fail-open 4:
background: trueResponses submit asking for the blocked wordCommand:
Observed:
Spend log rows the probe received for that call:
Fail-open 4, retrieval:
GET /v1/responses/{id}for that background responseCommand:
Observed:
Fail-open 5: streamed chat under a pipeline whose guardrail has only the legacy success hook
Command:
Observed:
Spend log rows the probe received for that call:
Same legacy pipeline without streaming: the rewrite is delivered
Command:
Observed:
Spend log rows the probe received for that call:
Block: streamed chat asking for the blocked word (the rows are the streaming block's logging contract)
Command:
Observed:
Spend log rows the probe received for that call:
Mask: streamed chat asking for the masked word
Command:
Observed:
Spend log rows the probe received for that call:
Mask: streamed Responses asking for the masked word
Command:
Observed:
Spend log rows the probe received for that call:
Mask: streamed Messages (Anthropic) asking for the masked word
Command:
Observed:
Spend log rows the probe received for that call:
Block without streaming: chat asking for the blocked word
Command:
Observed:
Spend log rows the probe received for that call:
Fail-open 5 for a guardrail with only the streaming iterator hook, added and stepped by a post_call pipeline
Command:
Observed:
Spend log rows the probe received for that call:
Control: request-level flat guardrail that yields every chunk then raises 400 (the merge base's end-of-stream block)
Command:
Observed:
Spend log rows the probe received for that call:
Policy-added dual-stage guardrail stepped by a post_call pipeline: blocked word in the request
Command:
Observed:
Spend log rows the probe received for that call:
Same policy: blocked word in the response
Command:
Observed:
Spend log rows the probe received for that call:
Guardrail returning a replacement response as a post_call pipeline step
Command:
Observed:
Spend log rows the probe received for that call:
Second config:
default_onguardrail also stepped by a post_call pipeline prefixes exactly onceCommand:
Observed:
Spend log rows the probe received for that call:
Second config: same with
run_in_parallel: trueCommand:
Observed:
Spend log rows the probe received for that call:
Second config: cross-mode guardrail managed by a pre_call pipeline, its post_call stage still runs
Command:
Observed:
Spend log rows the probe received for that call:
QA observations (things a reviewer cannot see from the diff):
/v1/completionsstream: nothing scans it, the step reports pass and the header names the guardrail (LIT-7177)/policies/test-pipelinepasses post_call pipelines with no response; unchanged/v1/messagesblock error body is a stringified dict; pre-existing, LIT-6466Type
🐛 Bug Fix
Caveats (if any)
Severe
Medium
apply_guardrailinterface is released unscanned (LIT-7176)/v1/completionscall is released unscanned while its step reports a pass and the header names the guardrail (LIT-7177)background: trueResponses are accepted and never governed by a post_call pipeline (LIT-7175)Low
n > 1chat streams, streams without a finish marker, and envelope-less Responses streams are discarded and the originals released (LIT-7178)/policies/test-pipelinestill reports a vacuous "pass" for post_call pipelines, since it has no response to scanmodify_responseon 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 tip69d2ac1, 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_outputhook 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 9d0c9b9Note
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_rewritesanddeliver_ended_stream_rewrites=Trueso 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—raiseUndeliverableStreamRewriteor 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.indexrather than list position.Reviewed by Cursor Bugbot for commit 6475443. Bugbot is set up for automated code reviews on this repo. Configure here.