Skip to content

Commit 33b123e

Browse files
committed
fix(policy_engine): propagate post_call pipeline metadata writes to request data
execute_steps hands the step hook a shallow copy of the request metadata so the pipeline's guardrail marker cannot poison the caller. On the post_call allow path _handle_pipeline_result then dropped that working copy entirely, so a hook's standard_logging_guardrail_information and applied_guardrails writes never reached the outer request. Deferred async logging built the StandardLoggingPayload from the untouched original, so spend logs, Langfuse, Datadog, and x-litellm-applied-guardrails all looked as if the scanner never ran. Copy the metadata bucket back on the post_call path and restore the should_run_guardrail marker to its pre-step value in the executor so the internal marker still cannot leak.
1 parent 5556972 commit 33b123e

3 files changed

Lines changed: 81 additions & 12 deletions

File tree

‎litellm/proxy/policy_engine/pipeline_executor.py‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -177,12 +177,14 @@ async def _run_step(
177177
verbose_proxy_logger.warning("Pipeline: guardrail '%s' not found in callbacks", step.guardrail)
178178
return ("error", None, f"Guardrail '{step.guardrail}' not found", None)
179179

180-
try:
181-
# Inject guardrail name into metadata so should_run_guardrail() allows it
182-
if "metadata" not in data:
183-
data["metadata"] = {}
184-
data["metadata"]["guardrails"] = [step.guardrail]
180+
if "metadata" not in data:
181+
data["metadata"] = {}
182+
metadata_dict: Final = data["metadata"]
183+
original_guardrails_present: Final = "guardrails" in metadata_dict
184+
original_guardrails: Final = metadata_dict.get("guardrails")
185+
metadata_dict["guardrails"] = [step.guardrail]
185186

187+
try:
186188
# A scan_raw_request step evaluates the pristine pre-pipeline
187189
# snapshot instead of `data` (which earlier pass_data steps in
188190
# this same pipeline may have already rewritten), same reason
@@ -245,6 +247,11 @@ async def _run_step(
245247
else:
246248
verbose_proxy_logger.error("Pipeline: unexpected error from guardrail '%s': %s", step.guardrail, e)
247249
return ("error", None, str(e), e)
250+
finally:
251+
if original_guardrails_present:
252+
metadata_dict["guardrails"] = original_guardrails
253+
else:
254+
metadata_dict.pop("guardrails", None)
248255

249256
@staticmethod
250257
def find_guardrail_callback(guardrail_name: str) -> CustomGuardrail | None:

‎litellm/proxy/utils.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1670,8 +1670,13 @@ def _handle_pipeline_result(
16701670
response carried in ``modified_data`` is adopted by the caller.
16711671
"""
16721672
if result.terminal_action == "allow":
1673-
if result.modified_data is not None and original_response is None:
1674-
data.update(result.modified_data)
1673+
if result.modified_data is not None:
1674+
if original_response is None:
1675+
data.update(result.modified_data)
1676+
else:
1677+
for key in ("metadata", "litellm_metadata"):
1678+
if key in result.modified_data:
1679+
data[key] = result.modified_data[key]
16751680
return data
16761681

16771682
if result.terminal_action == "block":

‎tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py‎

Lines changed: 62 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from __future__ import annotations
1111

1212
import asyncio
13-
from typing import Any, Dict, List
13+
from typing import Any, Dict, Final, List
1414
from unittest.mock import AsyncMock, MagicMock, patch
1515

1616
import pytest
@@ -919,6 +919,49 @@ async def async_post_call_success_hook(self, data, user_api_key_dict, response):
919919
assert seen["response"] is response
920920

921921

922+
@pytest.mark.asyncio
923+
async def test_post_call_pipeline_pass_propagates_metadata_writes_to_request_data(
924+
proxy_logging, make_user_api_key_auth, monkeypatch
925+
):
926+
"""A post_call pipeline step's writes to the metadata bucket
927+
(standard_logging_guardrail_information for spend logs / Langfuse / Datadog
928+
and applied_guardrails for the x-litellm-applied-guardrails header) must
929+
reach the outer request data. The working-copy the executor gives the hook
930+
is otherwise discarded, so deferred async logging and the response header
931+
look as if the guardrail never ran."""
932+
933+
class RecordingGuardrail(CustomGuardrail):
934+
async def async_post_call_success_hook(self, data, user_api_key_dict, response):
935+
from litellm.proxy.common_utils.callback_utils import (
936+
add_guardrail_to_applied_guardrails_header,
937+
)
938+
939+
metadata = data.setdefault("metadata", {})
940+
metadata.setdefault("standard_logging_guardrail_information", []).append(
941+
{"guardrail_name": "gr-post"}
942+
)
943+
add_guardrail_to_applied_guardrails_header(request_data=data, guardrail_name="gr-post")
944+
return None
945+
946+
monkeypatch.setattr(
947+
litellm,
948+
"callbacks",
949+
[RecordingGuardrail(guardrail_name="gr-post", event_hook=GuardrailEventHooks.post_call, default_on=False)],
950+
)
951+
monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None, raising=False)
952+
data = _post_call_pipeline_data()
953+
954+
await proxy_logging.post_call_success_hook(
955+
data=data, response=litellm.ModelResponse(), user_api_key_dict=make_user_api_key_auth()
956+
)
957+
958+
metadata = data["metadata"]
959+
assert metadata["applied_guardrails"] == ["gr-post"]
960+
assert metadata["standard_logging_guardrail_information"] == [{"guardrail_name": "gr-post"}]
961+
assert "guardrails" not in metadata
962+
assert "response" not in data
963+
964+
922965
@pytest.mark.asyncio
923966
async def test_post_call_pipeline_pass_runs_once_and_leaves_request_data_untouched(
924967
proxy_logging, make_user_api_key_auth, monkeypatch
@@ -1139,18 +1182,32 @@ def test_handle_pipeline_result_modify_response_carries_original_response():
11391182
assert info.value.original_response is response
11401183

11411184

1142-
def test_handle_pipeline_result_allow_discards_modifications_on_post_call():
1143-
data = {"a": 1, "metadata": {"guardrails": ["other"]}}
1185+
def test_handle_pipeline_result_allow_propagates_metadata_on_post_call():
1186+
"""The post_call path must keep the request payload intact (already sent
1187+
upstream) but still adopt metadata mutations from the pipeline's working
1188+
copy: standard_logging_guardrail_information and applied_guardrails are
1189+
written there and must reach deferred async logging plus the
1190+
x-litellm-applied-guardrails header."""
1191+
replacement_response: Final = object()
1192+
data = {"a": 1, "metadata": {"guardrails": ["other"]}, "litellm_metadata": {"foo": "bar"}}
11441193
result = MagicMock()
11451194
result.terminal_action = "allow"
1146-
result.modified_data = {"metadata": {"guardrails": ["gr-post"]}, "response": object()}
1195+
result.modified_data = {
1196+
"metadata": {"guardrails": ["gr-post"], "applied_guardrails": ["gr-post"]},
1197+
"litellm_metadata": {"foo": "bar", "extra": 1},
1198+
"response": replacement_response,
1199+
}
11471200

11481201
out = ProxyLogging._handle_pipeline_result(
11491202
result=result, data=data, policy_name="p", original_response=litellm.ModelResponse()
11501203
)
11511204

11521205
assert out is data
1153-
assert data == {"a": 1, "metadata": {"guardrails": ["other"]}}
1206+
assert data == {
1207+
"a": 1,
1208+
"metadata": {"guardrails": ["gr-post"], "applied_guardrails": ["gr-post"]},
1209+
"litellm_metadata": {"foo": "bar", "extra": 1},
1210+
}
11541211

11551212

11561213
@pytest.mark.asyncio

0 commit comments

Comments
 (0)