The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(auto-router compression): close three review findings on the per-hop policy
moe-berri6385c7b3c536
diff --git a/litellm/constants.py b/litellm/constants.pyindex 25fdaec20de..43fefaae048 100644--- a/litellm/constants.py+++ b/litellm/constants.py@@ -217,7 +217,6 @@ PRE_CALL_EXECUTED_GUARDRAILS_KEY: Final = "_pre_call_executed_guardrails"# Metadata key listing compression guardrails an auto router's own compression# policy suppresses for this request. See litellm.proxy.guardrails.auto_router_compression.-AUTO_ROUTER_SUPPRESSED_COMPRESSION_GUARDRAILS_KEY: Final = "_auto_router_suppressed_compression_guardrails"# Generic fallback for unknown modelsDEFAULT_REASONING_EFFORT_MINIMAL_THINKING_BUDGET: Final = int(diff --git a/litellm/integrations/custom_guardrail.py b/litellm/integrations/custom_guardrail.pyindex 1ec08641706..f511d128dfc 100644--- a/litellm/integrations/custom_guardrail.py+++ b/litellm/integrations/custom_guardrail.py@@ -45,7 +45,6 @@ dc: Final = DualCache()from litellm.constants import (- AUTO_ROUTER_SUPPRESSED_COMPRESSION_GUARDRAILS_KEY,GUARDRAIL_SCANNED_MESSAGES_CACHE_TTL_SECONDS,PRE_CALL_EXECUTED_GUARDRAILS_KEY,)@@ -941,33 +940,22 @@ class CustomGuardrail(CustomLogger):"""return False- def auto_router_suppression_marker(self) -> str | None:- """The value `arm_pre_call` must write to suppress this guardrail.+ def _suppressed_by_auto_router_compression(self) -> bool:+ """True when an auto router's own compression policy suppresses this guardrail.- Carries the per-process token for the same reason `_pre_call_marker` does: a- caller controls request metadata, so a bare guardrail name there would let any- request switch off a PII, content-filter, or compression guardrail for itself.- The token is never sent to the caller, so the marker cannot be forged.+ Reads request-scoped state set by `arm_pre_call`, never request metadata. The+ caller controls metadata, and metadata reaches spend logs the caller can read,+ so a suppression list carried there would be one a request could replay to+ switch off a PII or content-filter guardrail for itself."""name: Final = self.guardrail_nameif not name:- return None- return f"{_PRE_CALL_EXECUTED_TOKEN}:{name}"-- def _suppressed_by_auto_router_compression(self, data: Mapping[str, object]) -> bool:- """True when an auto router's own compression policy suppresses this guardrail."""- marker: Final = self.auto_router_suppression_marker()- if marker is None:return False- for meta_key in ("metadata", "litellm_metadata"):- meta = data.get(meta_key)- if isinstance(meta, Mapping):- # arm_pre_call writes a tuple; it arrives as a list once the metadata- # has been round-tripped through JSON.- suppressed = meta.get(AUTO_ROUTER_SUPPRESSED_COMPRESSION_GUARDRAILS_KEY)- if isinstance(suppressed, (list, tuple)) and marker in suppressed:- return True- return False+ from litellm.proxy.guardrails.auto_router_compression import (+ suppressed_compression_guardrails,+ )++ return name in suppressed_compression_guardrails()def should_run_guardrail(self,@@ -977,7 +965,7 @@ class CustomGuardrail(CustomLogger):"""Returns True if the guardrail should be run on the event_type"""- if self._suppressed_by_auto_router_compression(data):+ if self._suppressed_by_auto_router_compression():return Falserequested_guardrails: Final = self.get_guardrail_from_metadata(data)diff --git a/litellm/proxy/guardrails/auto_router_compression.py b/litellm/proxy/guardrails/auto_router_compression.pyindex 3b0804e40e2..2a4a0c82022 100644--- a/litellm/proxy/guardrails/auto_router_compression.py+++ b/litellm/proxy/guardrails/auto_router_compression.py@@ -15,11 +15,9 @@ each hop sees.import contextvarsfrom collections.abc import Iterable, Mapping, Sequencefrom dataclasses import dataclass-from types import MappingProxyTypefrom typing import TYPE_CHECKING, Finalfrom litellm._logging import verbose_proxy_logger-from litellm.constants import AUTO_ROUTER_SUPPRESSED_COMPRESSION_GUARDRAILS_KEYfrom litellm.litellm_core_utils.core_helpers import get_or_create_metadata_bucketfrom litellm.router_utils.auto_router_model_naming import AUTO_ROUTER_MODEL_PREFIXfrom litellm.types.utils import GenericGuardrailAPIInputs@@ -31,16 +29,22 @@ if TYPE_CHECKING:COMPRESSION_GUARDRAIL_PROVIDERS: Final = frozenset({"headroom", "compresr"})_NO_COMPRESSION: Final = "none"-# The pre-compression messages, so a routing decision that does not share the model-# call's compression still classifies on the original text. Deliberately a ContextVar-# rather than a metadata key: `refresh_proxy_server_request_body_snapshot` copies-# metadata into `proxy_server_request.body`, which deployments persist to spend logs,-# and this holds the prompt as it was before any masking guardrail rewrote it.-_routing_messages_snapshot: Final[contextvars.ContextVar[tuple[Mapping[str, object], ...] | None]] = (- contextvars.ContextVar("litellm_auto_router_routing_messages_snapshot", default=None)+# Compression guardrails this request's auto router has switched off. Deliberately a+# ContextVar rather than a metadata key: `refresh_proxy_server_request_body_snapshot`+# copies metadata into `proxy_server_request.body`, which deployments persist to spend+# logs. A suppression list that reaches a log the caller can read is a list the caller+# can replay, which would let any request switch off a PII or content-filter guardrail.+# Nothing here is caller-supplied, so there is no marker to forge in the first place.+_suppressed_compression_guardrails: Final[contextvars.ContextVar[frozenset[str]]] = contextvars.ContextVar(+ "litellm_auto_router_suppressed_compression_guardrails", default=frozenset())+def suppressed_compression_guardrails() -> frozenset[str]:+ """Names of the compression guardrails this request's auto router suppresses."""+ return _suppressed_compression_guardrails.get()++@dataclass(frozen=True, slots=True)class AutoRouterCompressionPolicy:"""An auto router's compression choice for each hop. ``None`` means no compression."""@@ -96,7 +100,11 @@ def policy_for_model(tag_matched: Final = tuple(params for params in markers if (tags := params.get("tags")) and requested.issuperset(frozenset(tags)))- for params in (*tag_matched, *markers):+ # Only untagged markers may serve as the fallback. A marker scoped to tags this+ # request does not carry describes a different slice of traffic, so falling back+ # to it would apply, say, an "eu" policy to a "us" request purely on config order.+ untagged: Final = tuple(params for params in markers if not params.get("tags"))+ for params in (*tag_matched, *untagged):policy = policy_from_litellm_params(params)if policy is not None:return policy@@ -135,12 +143,10 @@ async def arm_pre_call() -> None:"""Apply an auto router's compression policy, if any, before guardrails run.- Suppresses every other compression guardrail, re-enables the model-side- guardrail the policy names (if any) even when it isn't ``default_on``, and- snapshots the pre-compression messages so the routing decision can read them- independently of whatever the model-side guardrail does to `data`.+ Suppresses every other compression guardrail and re-enables the model-side+ guardrail the policy names (if any) even when it isn't ``default_on``."""- _routing_messages_snapshot.set(None)+ _suppressed_compression_guardrails.set(frozenset())if llm_router is None:return@@ -162,18 +168,16 @@ async def arm_pre_call(if policy is None:return- _, metadata = get_or_create_metadata_bucket(data)- # Markers carry a per-process token so a caller cannot suppress a guardrail by- # naming it in its own request metadata.- suppressed: Final = tuple(- marker- for guardrail in _active_compression_guardrails()- if guardrail.guardrail_name != policy.model and (marker := guardrail.auto_router_suppression_marker())+ _suppressed_compression_guardrails.set(+ frozenset(+ name+ for guardrail in _active_compression_guardrails()+ if (name := guardrail.guardrail_name) and name != policy.model+ ))- if suppressed:- metadata[AUTO_ROUTER_SUPPRESSED_COMPRESSION_GUARDRAILS_KEY] = suppressedif policy.model is not None:+ _, metadata = get_or_create_metadata_bucket(data)requested: Final = metadata.get("guardrails")existing: Final = tuple(requested) if isinstance(requested, (list, tuple)) else ()if policy.model not in existing:@@ -181,20 +185,6 @@ async def arm_pre_call(# isinstance(..., list) and extends it, and would drop a tuple on the floor.metadata["guardrails"] = [*existing, policy.model] # mutable-ok: this key's contract is a list- from litellm.litellm_core_utils.prompt_templates.factory import resolve_structured_messages-- raw_messages: Final = data.get("messages")- snapshot: Final = resolve_structured_messages(- messages=raw_messages if isinstance(raw_messages, list) else None,- request_kwargs=data,- )- if snapshot is not None:- _routing_messages_snapshot.set(tuple(MappingProxyType(dict(message)) for message in snapshot))---def _snapshot_messages() -> tuple[Mapping[str, object], ...] | None:- return _routing_messages_snapshot.get()-def _as_routing_messages(messages: Iterable[Mapping[str, object]],@@ -213,23 +203,22 @@ async def messages_for_routing("""Messages to use for a routing decision, per `policy.routing`.Returns None when the caller should route on whatever messages it already has.- The model call is untouched either way: model-side compression, if any, already- ran as an ordinary pre-call guardrail before the router was reached, so when the- two hops differ the routing decision reads the pre-compression snapshot rather- than what that guardrail left behind.- """- if policy is None:- return None- snapshot: Final = _snapshot_messages()- original: Final = snapshot if snapshot is not None else messages+ Always reads the live messages, never a pre-guardrail copy of them. The routing+ hop compresses through a real guardrail, which POSTs the text to an external+ compression service, so it must see what every other guardrail has already done+ to the request. Routing on a snapshot taken before the pre-call hook would send+ a masking guardrail's own input straight back out of the proxy.- if policy.routing is None:- # Explicitly no compression for routing. When the model side compressed, the- # messages in hand are its output, so fall back to the untouched snapshot.- return _as_routing_messages(snapshot) if policy.model is not None and snapshot is not None else None+ The consequence, when the model hop compressed and the two hops differ: the+ messages in hand are that guardrail's output, and there is no un-compressed copy+ left to route on. The routing decision reads the compressed text in that one+ combination rather than leaking the original.+ """+ if policy is None or policy.routing is None:+ return None- if not original:+ if not messages:return Nonefrom litellm.proxy.common_utils.registry_read_through import (@@ -241,20 +230,20 @@ async def messages_for_routing(verbose_proxy_logger.warning("AutoRouter compression: guardrail '%s' not found; routing on uncompressed messages", policy.routing)- return _as_routing_messages(original)+ return _as_routing_messages(messages)inputs: Final[GenericGuardrailAPIInputs] = {- "structured_messages": _as_routing_messages(original) # pyright: ignore[reportAssignmentType] # plain dicts, not AllMessageValues; see headroom.py's own use of this shape+ "structured_messages": _as_routing_messages(messages) # pyright: ignore[reportAssignmentType] # plain dicts, not AllMessageValues; see headroom.py's own use of this shape}model: Final = request_kwargs.get("model")# A throwaway request_data: apply_guardrail writes its stats onto this dict, not the# real request's metadata, so routing-side compression never double-counts against# extract_compression_saved_tokens's model-savings accounting.- stats_sink: Final = {"messages": original, "model": model} # mutable-ok: apply_guardrail writes its stats here+ stats_sink: Final = {"messages": messages, "model": model} # mutable-ok: apply_guardrail writes its stats hereresult: Final = await guardrail.apply_guardrail(inputs=inputs,request_data=stats_sink,input_type="request",)compressed: Final = result.get("structured_messages")- return compressed if isinstance(compressed, list) else _as_routing_messages(original)+ return compressed if isinstance(compressed, list) else _as_routing_messages(messages)diff --git a/tests/test_litellm/integrations/test_custom_guardrail.py b/tests/test_litellm/integrations/test_custom_guardrail.pyindex f590903cb74..c4a702d453c 100644--- a/tests/test_litellm/integrations/test_custom_guardrail.py+++ b/tests/test_litellm/integrations/test_custom_guardrail.py@@ -13,7 +13,6 @@ from litellm.types.utils import GenericGuardrailAPIInputs, GuardrailTracingDetaiclass TestCustomGuardrailDeploymentHook:-@pytest.mark.asyncioasync def test_async_pre_call_deployment_hook_no_guardrails(self):"""Test that method returns kwargs unchanged when no guardrails are present"""@@ -26,18 +25,14 @@ class TestCustomGuardrailDeploymentHook:"guardrails": None,}- result = await custom_guardrail.async_pre_call_deployment_hook(- kwargs=kwargs, call_type=CallTypes.completion- )+ result = await custom_guardrail.async_pre_call_deployment_hook(kwargs=kwargs, call_type=CallTypes.completion)assert result == kwargs# Test with guardrails as non-listkwargs["guardrails"] = "not_a_list"- result = await custom_guardrail.async_pre_call_deployment_hook(- kwargs=kwargs, call_type=CallTypes.completion- )+ result = await custom_guardrail.async_pre_call_deployment_hook(kwargs=kwargs, call_type=CallTypes.completion)assert result == kwargs@@ -64,9 +59,7 @@ class TestCustomGuardrailDeploymentHook:"user_api_key_request_route": "test_route",}- result = await custom_guardrail.async_pre_call_deployment_hook(- kwargs=kwargs, call_type=CallTypes.completion- )+ result = await custom_guardrail.async_pre_call_deployment_hook(kwargs=kwargs, call_type=CallTypes.completion)# Verify async_pre_call_hook was called with correct parameterscustom_guardrail.async_pre_call_hook.assert_called_once()@@ -99,9 +92,7 @@ class TestCustomGuardrailDeploymentHook:super().__init__(guardrail_name="g1", default_on=True)self.pre_call_count = 0- async def async_pre_call_hook(- self, user_api_key_dict, cache, data, call_type- ):+ async def async_pre_call_hook(self, user_api_key_dict, cache, data, call_type):self.pre_call_count += 1return data@@ -114,9 +105,7 @@ class TestCustomGuardrailDeploymentHook:}guardrail.mark_pre_call_hook_ran(kwargs)- await guardrail.async_pre_call_deployment_hook(- kwargs=kwargs, call_type=CallTypes.completion- )+ await guardrail.async_pre_call_deployment_hook(kwargs=kwargs, call_type=CallTypes.completion)assert guardrail.pre_call_count == 0@@ -130,9 +119,7 @@ class TestCustomGuardrailDeploymentHook:super().__init__(guardrail_name="g1", default_on=True)self.pre_call_count = 0- async def async_pre_call_hook(- self, user_api_key_dict, cache, data, call_type- ):+ async def async_pre_call_hook(self, user_api_key_dict, cache, data, call_type):self.pre_call_count += 1return data@@ -144,9 +131,7 @@ class TestCustomGuardrailDeploymentHook:"metadata": {},}- await guardrail.async_pre_call_deployment_hook(- kwargs=kwargs, call_type=CallTypes.completion- )+ await guardrail.async_pre_call_deployment_hook(kwargs=kwargs, call_type=CallTypes.completion)assert guardrail.pre_call_count == 1@@ -175,9 +160,7 @@ class TestCustomGuardrailDeploymentHook:super().__init__(guardrail_name="g1", default_on=True)self.pre_call_count = 0- async def async_pre_call_hook(- self, user_api_key_dict, cache, data, call_type- ):+ async def async_pre_call_hook(self, user_api_key_dict, cache, data, call_type):self.pre_call_count += 1return data@@ -189,15 +172,12 @@ class TestCustomGuardrailDeploymentHook:"metadata": {PRE_CALL_EXECUTED_GUARDRAILS_KEY: ["g1"]},}- await guardrail.async_pre_call_deployment_hook(- kwargs=kwargs, call_type=CallTypes.completion- )+ await guardrail.async_pre_call_deployment_hook(kwargs=kwargs, call_type=CallTypes.completion)assert guardrail.pre_call_count == 1class TestCustomGuardrailShouldRunGuardrail:-def test_should_run_guardrail_with_litellm_metadata(self):"""Test that should_run_guardrail works with litellm_metadata pattern"""from litellm.types.guardrails import GuardrailEventHooks@@ -214,9 +194,7 @@ class TestCustomGuardrailShouldRunGuardrail:"litellm_metadata": {"guardrails": ["test_guardrail"]},}- result = custom_guardrail.should_run_guardrail(- data=data, event_type=GuardrailEventHooks.pre_call- )+ result = custom_guardrail.should_run_guardrail(data=data, event_type=GuardrailEventHooks.pre_call)assert result is True@@ -236,9 +214,7 @@ class TestCustomGuardrailShouldRunGuardrail:"metadata": {"guardrails": ["test_guardrail"]},}- result = custom_guardrail.should_run_guardrail(- data=data, event_type=GuardrailEventHooks.pre_call- )+ result = custom_guardrail.should_run_guardrail(data=data, event_type=GuardrailEventHooks.pre_call)assert result is True@@ -255,9 +231,7 @@ class TestCustomGuardrailShouldRunGuardrail:# Test with guardrails at root leveldata = {"model": "gpt-3.5-turbo", "guardrails": ["test_guardrail"]}- result = custom_guardrail.should_run_guardrail(- data=data, event_type=GuardrailEventHooks.pre_call- )+ result = custom_guardrail.should_run_guardrail(data=data, event_type=GuardrailEventHooks.pre_call)assert result is True@@ -277,9 +251,7 @@ class TestCustomGuardrailShouldRunGuardrail:"litellm_metadata": {"guardrails": ["different_guardrail"]},}- result = custom_guardrail.should_run_guardrail(- data=data, event_type=GuardrailEventHooks.pre_call- )+ result = custom_guardrail.should_run_guardrail(data=data, event_type=GuardrailEventHooks.pre_call)assert result is False@@ -298,9 +270,7 @@ class TestCustomGuardrailShouldRunGuardrail:"model": "gpt-3.5-turbo","messages": [{"role": "user", "content": "test"}],}- result = custom_guardrail.should_run_guardrail(- data=data, event_type=GuardrailEventHooks.pre_call- )+ result = custom_guardrail.should_run_guardrail(data=data, event_type=GuardrailEventHooks.pre_call)assert result is True, "Global guardrail should run when default_on=True"# Test 2: User-injected disable at root level is IGNORED@@ -312,9 +282,7 @@ class TestCustomGuardrailShouldRunGuardrail:result = custom_guardrail.should_run_guardrail(data=data_with_disable_root, event_type=GuardrailEventHooks.pre_call)- assert (- result is True- ), "User-injected disable_global_guardrails should be ignored"+ assert result is True, "User-injected disable_global_guardrails should be ignored"# Test 3: User-injected disable in metadata is IGNOREDdata_with_disable_metadata = {@@ -345,12 +313,8 @@ class TestCustomGuardrailShouldRunGuardrail:"metadata": {"user_api_key_metadata": {"disable_global_guardrails": True}},"litellm_metadata": {"request_tags": ["user-supplied"]},}- result = custom_guardrail.should_run_guardrail(- data=data_cross_key, event_type=GuardrailEventHooks.pre_call- )- assert (- result is False- ), "Admin config in metadata must not be shadowed by user-supplied litellm_metadata"+ result = custom_guardrail.should_run_guardrail(data=data_cross_key, event_type=GuardrailEventHooks.pre_call)+ assert result is False, "Admin config in metadata must not be shadowed by user-supplied litellm_metadata"# Test 6: After the pre-call strip runs, user-injected# user_api_key_metadata in the non-authoritative metadata key is gone.@@ -361,12 +325,8 @@ class TestCustomGuardrailShouldRunGuardrail:"metadata": {"user_api_key_metadata": {"disable_global_guardrails": True}},"litellm_metadata": {}, # post-strip: attacker payload removed}- result = custom_guardrail.should_run_guardrail(- data=data_post_strip, event_type=GuardrailEventHooks.pre_call- )- assert (- result is False- ), "Admin config in metadata must be respected when other metadata key is empty"+ result = custom_guardrail.should_run_guardrail(data=data_post_strip, event_type=GuardrailEventHooks.pre_call)+ assert result is False, "Admin config in metadata must be respected when other metadata key is empty"def test_should_run_guardrail_key_disable_global_not_overruled_by_team_guardrail_list(self,@@ -432,12 +392,7 @@ class TestCustomGuardrailShouldRunGuardrail:"messages": [{"role": "user", "content": "test"}],"opted_out_global_guardrails": ["global_guardrail"],}- assert (- custom_guardrail.should_run_guardrail(- data=data_root, event_type=GuardrailEventHooks.pre_call- )- is True- )+ assert custom_guardrail.should_run_guardrail(data=data_root, event_type=GuardrailEventHooks.pre_call) is True# Test 2: User-injected opt-out in metadata is IGNOREDdata_metadata = {@@ -446,10 +401,7 @@ class TestCustomGuardrailShouldRunGuardrail:"metadata": {"opted_out_global_guardrails": ["global_guardrail"]},}assert (- custom_guardrail.should_run_guardrail(- data=data_metadata, event_type=GuardrailEventHooks.pre_call- )- is True+ custom_guardrail.should_run_guardrail(data=data_metadata, event_type=GuardrailEventHooks.pre_call) is True)# Test 4: a different guardrail in the opt-out list → still runs@@ -458,12 +410,7 @@ class TestCustomGuardrailShouldRunGuardrail:"messages": [{"role": "user", "content": "test"}],"metadata": {"opted_out_global_guardrails": ["some_other_guardrail"]},}- assert (- custom_guardrail.should_run_guardrail(- data=data_other, event_type=GuardrailEventHooks.pre_call- )- is True- )+ assert custom_guardrail.should_run_guardrail(data=data_other, event_type=GuardrailEventHooks.pre_call) is True# Test 5: empty opt-out list → still runsdata_empty = {@@ -471,12 +418,7 @@ class TestCustomGuardrailShouldRunGuardrail:"messages": [{"role": "user", "content": "test"}],"metadata": {"opted_out_global_guardrails": []},}- assert (- custom_guardrail.should_run_guardrail(- data=data_empty, event_type=GuardrailEventHooks.pre_call- )- is True- )+ assert custom_guardrail.should_run_guardrail(data=data_empty, event_type=GuardrailEventHooks.pre_call) is True# Test 6: malformed value (bool instead of list) → safely ignored, guardrail runsdata_malformed = {@@ -485,10 +427,7 @@ class TestCustomGuardrailShouldRunGuardrail:"metadata": {"opted_out_global_guardrails": True},}assert (- custom_guardrail.should_run_guardrail(- data=data_malformed, event_type=GuardrailEventHooks.pre_call- )- is True+ custom_guardrail.should_run_guardrail(data=data_malformed, event_type=GuardrailEventHooks.pre_call) is True)def test_should_run_guardrail_opt_out_does_not_affect_non_global(self):@@ -511,17 +450,12 @@ class TestCustomGuardrailShouldRunGuardrail:"guardrails": ["opt_in_guardrail"],},}- assert (- non_global.should_run_guardrail(- data=data, event_type=GuardrailEventHooks.pre_call- )- is True- )+ assert non_global.should_run_guardrail(data=data, event_type=GuardrailEventHooks.pre_call) is Truedef test_should_run_guardrail_suppressed_by_auto_router_compression(self):"""An auto router's own compression policy can suppress an otherwise-eligibleguardrail, even one that is default_on and explicitly requested."""- from litellm.constants import AUTO_ROUTER_SUPPRESSED_COMPRESSION_GUARDRAILS_KEY+ from litellm.proxy.guardrails import auto_router_compressionfrom litellm.types.guardrails import GuardrailEventHooksalways_on = CustomGuardrail(@@ -529,22 +463,17 @@ class TestCustomGuardrailShouldRunGuardrail:default_on=True,event_hook=GuardrailEventHooks.pre_call,)- data = {- "model": "smart-router",- "metadata": {- AUTO_ROUTER_SUPPRESSED_COMPRESSION_GUARDRAILS_KEY: [- always_on.auto_router_suppression_marker()- ],- },- }-- assert (- always_on.should_run_guardrail(data=data, event_type=GuardrailEventHooks.pre_call)- is False- )+ token = auto_router_compression._suppressed_compression_guardrails.set(frozenset({"headroom-default"}))+ try:+ assert (+ always_on.should_run_guardrail(data={"model": "smart-router"}, event_type=GuardrailEventHooks.pre_call)+ is False+ )+ finally:+ auto_router_compression._suppressed_compression_guardrails.reset(token)- def test_should_run_guardrail_suppression_list_does_not_affect_other_names(self):- from litellm.constants import AUTO_ROUTER_SUPPRESSED_COMPRESSION_GUARDRAILS_KEY+ def test_should_run_guardrail_suppression_does_not_affect_other_names(self):+ from litellm.proxy.guardrails import auto_router_compressionfrom litellm.types.guardrails import GuardrailEventHooksalways_on = CustomGuardrail(@@ -552,25 +481,20 @@ class TestCustomGuardrailShouldRunGuardrail:default_on=True,event_hook=GuardrailEventHooks.pre_call,)- other = CustomGuardrail(guardrail_name="some-other-guardrail", default_on=True)- data = {- "model": "smart-router",- "metadata": {- AUTO_ROUTER_SUPPRESSED_COMPRESSION_GUARDRAILS_KEY: [- other.auto_router_suppression_marker()- ],- },- }-- assert (- always_on.should_run_guardrail(data=data, event_type=GuardrailEventHooks.pre_call)- is True- )-- def test_should_run_guardrail_ignores_a_forged_suppression_marker(self):- """A caller controls request metadata, so a bare guardrail name there must not- switch off an always-on guardrail: only the per-process marker counts."""- from litellm.constants import AUTO_ROUTER_SUPPRESSED_COMPRESSION_GUARDRAILS_KEY+ token = auto_router_compression._suppressed_compression_guardrails.set(frozenset({"some-other-guardrail"}))+ try:+ assert (+ always_on.should_run_guardrail(data={"model": "smart-router"}, event_type=GuardrailEventHooks.pre_call)+ is True+ )+ finally:+ auto_router_compression._suppressed_compression_guardrails.reset(token)++ def test_request_metadata_can_never_suppress_a_guardrail(self):+ """Regression (security): suppression state is request-scoped and server-set,+ never read from metadata. Metadata reaches spend logs the caller can read, so+ anything honored from there is something a later request could replay to switch+ off a PII or content-filter guardrail for itself."""from litellm.types.guardrails import GuardrailEventHooksalways_on = CustomGuardrail(@@ -581,17 +505,14 @@ class TestCustomGuardrailShouldRunGuardrail:forged = {"model": "smart-router","metadata": {- AUTO_ROUTER_SUPPRESSED_COMPRESSION_GUARDRAILS_KEY: [+ "_auto_router_suppressed_compression_guardrails": ["headroom-default",- "forged-token:headroom-default",+ "any-token:headroom-default",],},}- assert (- always_on.should_run_guardrail(data=forged, event_type=GuardrailEventHooks.pre_call)- is True- )+ assert always_on.should_run_guardrail(data=forged, event_type=GuardrailEventHooks.pre_call) is Trueclass TestApplyGuardrailCheck:@@ -630,35 +551,33 @@ class TestApplyGuardrailCheck:child_with_override = ChildGuardrailWithOverride()# Test: CustomGuardrail itself has apply_guardrail in its __dict__- assert (- "apply_guardrail" in type(CustomGuardrail()).__dict__- ), "CustomGuardrail should have apply_guardrail in its own __dict__"+ assert "apply_guardrail" in type(CustomGuardrail()).__dict__, (+ "CustomGuardrail should have apply_guardrail in its own __dict__"+ )# Test: ParentGuardrail inherits but doesn't override, so it should NOT be in __dict__- assert (- "apply_guardrail" not in type(parent_instance).__dict__- ), "ParentGuardrail should NOT have apply_guardrail in its own __dict__ (only inherited)"+ assert "apply_guardrail" not in type(parent_instance).__dict__, (+ "ParentGuardrail should NOT have apply_guardrail in its own __dict__ (only inherited)"+ )# Test: ChildGuardrailWithoutOverride only inherits, should NOT be in __dict__- assert (- "apply_guardrail" not in type(child_without_override).__dict__- ), "ChildGuardrailWithoutOverride should NOT have apply_guardrail in its own __dict__ (only inherited)"+ assert "apply_guardrail" not in type(child_without_override).__dict__, (+ "ChildGuardrailWithoutOverride should NOT have apply_guardrail in its own __dict__ (only inherited)"+ )# Test: ChildGuardrailWithOverride overrides the method, SHOULD be in __dict__- assert (- "apply_guardrail" in type(child_with_override).__dict__- ), "ChildGuardrailWithOverride SHOULD have apply_guardrail in its own __dict__ (overridden)"+ assert "apply_guardrail" in type(child_with_override).__dict__, (+ "ChildGuardrailWithOverride SHOULD have apply_guardrail in its own __dict__ (overridden)"+ )# Verify that all instances still have the method via inheritance (hasattr)- assert hasattr(- parent_instance, "apply_guardrail"- ), "All instances should have apply_guardrail via inheritance"- assert hasattr(- child_without_override, "apply_guardrail"- ), "All instances should have apply_guardrail via inheritance"- assert hasattr(- child_with_override, "apply_guardrail"- ), "All instances should have apply_guardrail via inheritance"+ assert hasattr(parent_instance, "apply_guardrail"), "All instances should have apply_guardrail via inheritance"+ assert hasattr(child_without_override, "apply_guardrail"), (+ "All instances should have apply_guardrail via inheritance"+ )+ assert hasattr(child_with_override, "apply_guardrail"), (+ "All instances should have apply_guardrail via inheritance"+ )class TestGuardrailLoggingAggregation:@@ -685,11 +604,7 @@ class TestGuardrailLoggingAggregation:def test_appends_to_existing_metadata_list(self):request_data = {- "metadata": {- "standard_logging_guardrail_information": [- {"guardrail_name": "existing_guardrail"}- ]- }+ "metadata": {"standard_logging_guardrail_information": [{"guardrail_name": "existing_guardrail"}]}}self._invoke_add_log(request_data)@@ -701,11 +616,7 @@ class TestGuardrailLoggingAggregation:assert info[1]["guardrail_name"] == "test_guardrail"def test_converts_existing_metadata_dict_to_list(self):- request_data = {- "metadata": {- "standard_logging_guardrail_information": {"guardrail_name": "legacy"}- }- }+ request_data = {"metadata": {"standard_logging_guardrail_information": {"guardrail_name": "legacy"}}}self._invoke_add_log(request_data)@@ -717,18 +628,12 @@ class TestGuardrailLoggingAggregation:def test_appends_to_litellm_metadata(self):request_data = {- "litellm_metadata": {- "standard_logging_guardrail_information": [- {"guardrail_name": "litellm_existing"}- ]- }+ "litellm_metadata": {"standard_logging_guardrail_information": [{"guardrail_name": "litellm_existing"}]}}self._invoke_add_log(request_data)- info = request_data["litellm_metadata"][- "standard_logging_guardrail_information"- ]+ info = request_data["litellm_metadata"]["standard_logging_guardrail_information"]assert isinstance(info, list)assert len(info) == 2assert info[1]["guardrail_name"] == "test_guardrail"@@ -745,12 +650,10 @@ class TestGuardrailLoggingAggregation:self._invoke_add_log(request_data)- assert (- "standard_logging_guardrail_information" not in request_data["metadata"]- ), "entry landed in the caller's metadata, where the spend log does not read it"- info = request_data["litellm_metadata"][- "standard_logging_guardrail_information"- ]+ assert "standard_logging_guardrail_information" not in request_data["metadata"], (+ "entry landed in the caller's metadata, where the spend log does not read it"+ )+ info = request_data["litellm_metadata"]["standard_logging_guardrail_information"]assert len(info) == 1assert info[0]["guardrail_name"] == "test_guardrail"@@ -768,9 +671,7 @@ class TestGuardrailLoggingAggregation:}self._invoke_add_log(request_data)- add_guardrail_to_applied_guardrails_header(- request_data=request_data, guardrail_name="test_guardrail"- )+ add_guardrail_to_applied_guardrails_header(request_data=request_data, guardrail_name="test_guardrail")buckets = {key@@ -816,9 +717,7 @@ class TestGuardrailOtelSpanEmission:assert len(captured) == 1emitted = captured[0]- recorded = request_data["metadata"]["standard_logging_guardrail_information"][- -1- ]+ recorded = request_data["metadata"]["standard_logging_guardrail_information"][-1]assert emitted is recordedassert emitted["guardrail_name"] == "emit_guard"assert emitted["start_time"] == 1.0@@ -828,9 +727,7 @@ class TestGuardrailOtelSpanEmission:def _boom(_entry):raise RuntimeError("otel exporter down")- monkeypatch.setattr(- "litellm.integrations.otel.logger.emit_guardrail_span", _boom- )+ monkeypatch.setattr("litellm.integrations.otel.logger.emit_guardrail_span", _boom)request_data = {"metadata": {}}self._record(self._make_guardrail(), request_data)@@ -927,9 +824,7 @@ class TestGuardrailSensitiveFieldStripping:duration=1.0,)- logged_response = request_data["metadata"][- "standard_logging_guardrail_information"- ][0]["guardrail_response"]+ logged_response = request_data["metadata"]["standard_logging_guardrail_information"][0]["guardrail_response"]assert "secret_fields" not in logged_responseassert "sk-live-SHOULD-NOT-APPEAR" not in json.dumps(logged_response)@@ -942,9 +837,7 @@ class TestGuardrailSensitiveFieldStripping:guardrail_json_response=[{"result": "ok",- "secret_fields": {- "raw_headers": {"authorization": "Bearer sk-secret"}- },+ "secret_fields": {"raw_headers": {"authorization": "Bearer sk-secret"}},},{"result": "also_ok"},],@@ -998,9 +891,7 @@ class TestGuardrailResponseCredentialMasking:duration=1.0,)- logged = request_data["metadata"]["standard_logging_guardrail_information"][0][- "guardrail_response"- ]+ logged = request_data["metadata"]["standard_logging_guardrail_information"][0]["guardrail_response"]masked_key = logged["metadata_snapshot"]["callback_vars"]["langsmith_api_key"]assert masked_key != plaintext_key@@ -1009,10 +900,7 @@ class TestGuardrailResponseCredentialMasking:assert logged["model"] == "gpt-4o-mini"assert logged["messages"] == [{"role": "user", "content": "hi"}]- assert (- logged["metadata_snapshot"]["callback_vars"]["langsmith_project"]- == "proj-name"- )+ assert logged["metadata_snapshot"]["callback_vars"]["langsmith_project"] == "proj-name"def test_nested_user_api_key_auth_metadata_is_masked(self):import json@@ -1071,9 +959,7 @@ class TestGuardrailResponseCredentialMasking:request_data: dict = {"metadata": {}}guardrail.add_standard_logging_guardrail_information_to_request_data(- guardrail_json_response={- "filters": [{"regex": r"\d{3}-\d{2}-\d{4}", "action": "BLOCKED"}]- },+ guardrail_json_response={"filters": [{"regex": r"\d{3}-\d{2}-\d{4}", "action": "BLOCKED"}]},request_data=request_data,guardrail_status="success",)@@ -1096,9 +982,7 @@ class TestGuardrailResponseCredentialMasking:guardrail_status="success",)- logged = request_data["metadata"]["standard_logging_guardrail_information"][0][- "guardrail_response"- ]+ logged = request_data["metadata"]["standard_logging_guardrail_information"][0]["guardrail_response"]assert logged["flagged"] is Trueassert logged["score"] == 0.94assert logged["tokens_used"] == 42@@ -1110,18 +994,14 @@ class TestGuardrailResponseCredentialMasking:plaintext = "lsv2_pt_abcdef1234567890"guardrail.add_standard_logging_guardrail_information_to_request_data(- guardrail_json_response={- "metadata_snapshot": {- "callback_vars": {"langsmith_api_key": plaintext}- }- },+ guardrail_json_response={"metadata_snapshot": {"callback_vars": {"langsmith_api_key": plaintext}}},request_data=request_data,guardrail_status="success",)- masked = request_data["metadata"]["standard_logging_guardrail_information"][0][- "guardrail_response"- ]["metadata_snapshot"]["callback_vars"]["langsmith_api_key"]+ masked = request_data["metadata"]["standard_logging_guardrail_information"][0]["guardrail_response"][+ "metadata_snapshot"+ ]["callback_vars"]["langsmith_api_key"]assert masked != plaintextassert masked.startswith(plaintext[:4])assert masked.endswith(plaintext[-4:])@@ -1615,9 +1495,7 @@ class TestEventTypeLogging:guardrail = TestGuardrail()request_data = {"metadata": {}}- await guardrail.apply_guardrail(- inputs={"texts": ["x"]}, request_data=request_data- )+ await guardrail.apply_guardrail(inputs={"texts": ["x"]}, request_data=request_data)logged_info = request_data["metadata"]["standard_logging_guardrail_information"]assert len(logged_info) == 1, (@@ -1659,9 +1537,7 @@ class TestEventTypeLogging:request_data = {"metadata": {}}with pytest.raises(ValueError, match="blocked"):- await guardrail.apply_guardrail(- inputs={"texts": ["x"]}, request_data=request_data- )+ await guardrail.apply_guardrail(inputs={"texts": ["x"]}, request_data=request_data)logged_info = request_data["metadata"]["standard_logging_guardrail_information"]assert len(logged_info) == 1@@ -1790,9 +1666,7 @@ class TestTracingFieldsPopulation:guardrail_json_response="blocked",request_data=request_data,guardrail_status="guardrail_intervened",- tracing_detail=GuardrailTracingDetail(- policy_template="EU AI Act Article 5"- ),+ tracing_detail=GuardrailTracingDetail(policy_template="EU AI Act Article 5"),)slg_list = request_data["metadata"]["standard_logging_guardrail_information"]@@ -1834,13 +1708,7 @@ class TestCustomGuardrailSpendLogMatchRedaction:cg = CustomGuardrail(guardrail_name="test-rail")raw = {"assessments": [- {- "sensitiveInformationPolicy": {- "piiEntities": [- {"type": "NAME", "match": "GG", "action": "BLOCKED"}- ]- }- }+ {"sensitiveInformationPolicy": {"piiEntities": [{"type": "NAME", "match": "GG", "action": "BLOCKED"}]}}]}request_data: dict = {"metadata": {}}@@ -1851,17 +1719,10 @@ class TestCustomGuardrailSpendLogMatchRedaction:)slg = request_data["metadata"]["standard_logging_guardrail_information"][0]assert (- slg["guardrail_response"]["assessments"][0]["sensitiveInformationPolicy"][- "piiEntities"- ][0]["match"]+ slg["guardrail_response"]["assessments"][0]["sensitiveInformationPolicy"]["piiEntities"][0]["match"]== "[REDACTED]")- assert (- raw["assessments"][0]["sensitiveInformationPolicy"]["piiEntities"][0][- "match"- ]- == "GG"- )+ assert raw["assessments"][0]["sensitiveInformationPolicy"]["piiEntities"][0]["match"] == "GG"def test_add_standard_logging_redacts_regex_field(self):cg = CustomGuardrail(guardrail_name="test-rail")diff --git a/tests/test_litellm/proxy/guardrails/test_auto_router_compression.py b/tests/test_litellm/proxy/guardrails/test_auto_router_compression.pyindex de667e8ed48..0b47e56cb02 100644--- a/tests/test_litellm/proxy/guardrails/test_auto_router_compression.py+++ b/tests/test_litellm/proxy/guardrails/test_auto_router_compression.py@@ -4,15 +4,16 @@ Unit tests for litellm.proxy.guardrails.auto_router_compression.Covers:- policy_from_litellm_params: absent keys mean no policy; the "none" sentinelnormalizes to explicit no-compression within an active policy; is_same-- policy_for_model: finds the auto-router marker deployment for an alias, and- picks the tag-scoped marker the request's tags actually match+- policy_for_model: finds the auto-router marker deployment for an alias, picks the+ tag-scoped marker the request's tags actually match, and never falls back to a+ marker scoped to tags the request does not carry- arm_pre_call: no-op without a policy; suppresses active compression guardrails- with a forgery-proof marker; arms the model-side guardrail even when it isn't- default_on; keeps the pre-compression snapshot out of persisted metadata-- messages_for_routing: no-op without a policy; routes on the pre-compression- snapshot when the two hops differ; compresses via the named guardrail's- apply_guardrail; never writes stats onto the caller's own request_kwargs- (regression for double-counted compression savings)+ through request-scoped state rather than metadata, which reaches spend logs a+ caller can read; arms the model-side guardrail even when it isn't default_on+- messages_for_routing: no-op without a policy; compresses the live messages every+ earlier guardrail has already rewritten, never a pre-guardrail copy of them;+ never writes stats onto the caller's own request_kwargs (regression for+ double-counted compression savings)"""import json@@ -20,7 +21,6 @@ from typing import Anyimport pytest-from litellm.constants import AUTO_ROUTER_SUPPRESSED_COMPRESSION_GUARDRAILS_KEYfrom litellm.integrations.custom_guardrail import CustomGuardrailfrom litellm.proxy.guardrails import auto_router_compressionfrom litellm.proxy.guardrails.auto_router_compression import (@@ -136,6 +136,26 @@ class TestPolicyForModel:)assert policy == AutoRouterCompressionPolicy(routing="headroom-a", model=None)+ def test_a_marker_scoped_to_other_tags_is_never_the_fallback(self):+ """Regression: an "eu" marker describes a different slice of traffic, so a "us"+ request must not fall back to its policy just because it is configured first."""+ router = _FakeRouter(+ [+ _marker({"auto_router_routing_compression": "headroom-eu"}, tags=["eu"]),+ _marker({"auto_router_routing_compression": "headroom-default"}),+ ]+ )+ policy = policy_for_model(llm_router=router, model_alias="smart-router", team_id=None, request_tags=("us",))+ assert policy == AutoRouterCompressionPolicy(routing="headroom-default", model=None)++ def test_no_untagged_fallback_means_no_policy(self):+ """With only tag-scoped markers and none matching, there is no policy to apply:+ inheriting an unrelated slice's compression is worse than inheriting nothing."""+ router = _FakeRouter([_marker({"auto_router_routing_compression": "headroom-eu"}, tags=["eu"])])+ assert (+ policy_for_model(llm_router=router, model_alias="smart-router", team_id=None, request_tags=("us",)) is None+ )+def test_tag_scoped_marker_takes_precedence_over_untagged(self):"""Regression: when multiple markers exist, the tag-scoped one the requestactually matches should be used, not the first untagged one."""@@ -220,25 +240,30 @@ class TestArmPreCall:)data = {"model": "smart-router", "messages": [{"role": "user", "content": "hi"}]}await arm_pre_call(data=data, llm_router=router)- suppressed = data["metadata"][AUTO_ROUTER_SUPPRESSED_COMPRESSION_GUARDRAILS_KEY]- assert tuple(suppressed) == (always_on.auto_router_suppression_marker(),)- # The bare name alone must never suppress: that is what a caller could forge.- assert "always-on-compression" not in suppressed+ assert auto_router_compression.suppressed_compression_guardrails() == frozenset({"always-on-compression"})+ # Suppression state must never ride along in metadata: that reaches spend+ # logs the caller can read, and anything there is replayable.+ assert "always-on-compression" not in json.dumps(data.get("metadata", {}))assert always_on.should_run_guardrail(data=data, event_type=GuardrailEventHooks.pre_call) is Falsefinally:litellm.logging_callback_manager.remove_callback_from_all_lists(always_on)@pytest.mark.asyncio- async def test_a_caller_cannot_suppress_a_guardrail_by_naming_it_in_metadata(self):- """Regression: request metadata is caller-controlled, so a bare guardrail name- there must not switch off a PII, content-filter, or compression guardrail."""+ async def test_suppression_state_never_enters_request_metadata(self):+ """Regression (security): a suppression list written to metadata is copied into+ proxy_server_request.body and persisted to spend logs, so a caller could read it+ back and replay it to switch off a PII or content-filter guardrail."""guardrail = _RecordingCompressionGuardrail(guardrail_name="always-on-compression")- forged = {- "model": "smart-router",- "metadata": {AUTO_ROUTER_SUPPRESSED_COMPRESSION_GUARDRAILS_KEY: ["always-on-compression"]},- }+ import litellm- assert guardrail._suppressed_by_auto_router_compression(forged) is False+ litellm.logging_callback_manager.add_litellm_callback(guardrail)+ try:+ router = _FakeRouter([_marker({"auto_router_routing_compression": "headroom-a"})])+ data = {"model": "smart-router", "messages": [{"role": "user", "content": "hi"}]}+ await arm_pre_call(data=data, llm_router=router)+ assert "suppress" not in json.dumps(data).lower()+ finally:+ litellm.logging_callback_manager.remove_callback_from_all_lists(guardrail)@pytest.mark.asyncioasync def test_model_side_guardrail_is_requested_even_when_not_default_on(self):@@ -259,52 +284,20 @@ class TestArmPreCall:assert data["metadata"]["guardrails"] == ["headroom-b"]@pytest.mark.asyncio- async def test_snapshot_never_lands_in_persisted_metadata(self):- """Regression: refresh_proxy_server_request_body_snapshot copies metadata into- proxy_server_request.body, which deployments persist to spend logs. The- pre-compression snapshot holds the prompt before any masking guardrail ran, so- it must live outside anything that gets serialized."""+ async def test_arm_pre_call_keeps_no_copy_of_the_prompt(self):+ """Regression (security): arm_pre_call runs before the pre-call guardrails, so+ any copy of the messages it retained would be the pre-masking text. Routing-side+ compression POSTs its input to an external service, so that copy must not exist."""router = _FakeRouter([_marker({"auto_router_routing_compression": "headroom-a"})])- original_messages = [{"role": "user", "content": "my ssn is 123-45-6789"}]- data = {"model": "smart-router", "messages": original_messages}+ data = {"model": "smart-router", "messages": [{"role": "user", "content": "my ssn is 123-45-6789"}]}await arm_pre_call(data=data, llm_router=router)- assert "123-45-6789" not in json.dumps(data["metadata"])- assert [dict(m) for m in auto_router_compression._snapshot_messages()] == original_messages-- @pytest.mark.asyncio- async def test_snapshot_is_a_copy_not_the_live_message_list(self):- router = _FakeRouter([_marker({"auto_router_routing_compression": "headroom-a"})])- original_messages = [{"role": "user", "content": "hi"}]-- await arm_pre_call(data={"model": "smart-router", "messages": original_messages}, llm_router=router)- original_messages[0]["content"] = "mutated after the snapshot"-- assert [dict(m) for m in auto_router_compression._snapshot_messages()] == [{"role": "user", "content": "hi"}]-- @pytest.mark.asyncio- async def test_a_request_without_a_policy_clears_a_previous_snapshot(self):- router_with = _FakeRouter([_marker({"auto_router_routing_compression": "headroom-a"})])- await arm_pre_call(- data={"model": "smart-router", "messages": [{"role": "user", "content": "first"}]}, llm_router=router_with- )-- router_without = _FakeRouter([{"model_name": "plain", "litellm_params": {"model": "openai/gpt-4o-mini"}}])- await arm_pre_call(- data={"model": "plain", "messages": [{"role": "user", "content": "second"}]}, llm_router=router_without- )-- assert auto_router_compression._snapshot_messages() is None+ assert "123-45-6789" not in json.dumps(data.get("metadata", {}))+ assert not hasattr(auto_router_compression, "_routing_messages_snapshot")class TestMessagesForRouting:- @pytest.fixture(autouse=True)- def _clear_snapshot(self):- auto_router_compression._routing_messages_snapshot.set(None)- yield- auto_router_compression._routing_messages_snapshot.set(None)-@pytest.mark.asyncioasync def test_no_policy_returns_none(self):assert await messages_for_routing(policy=None, messages=[], request_kwargs={}) is None@@ -316,18 +309,15 @@ class TestMessagesForRouting:assert await messages_for_routing(policy=policy, messages=[], request_kwargs={}) is None@pytest.mark.asyncio- async def test_routing_none_with_model_compression_routes_on_the_snapshot(self):- """Regression: with routing explicitly off and the model side compressed, the- messages in hand are the model-side guardrail's output. Routing asked for no- compression, so it must read the pre-compression snapshot instead."""- original = [{"role": "user", "content": "the full original conversation"}]- auto_router_compression._routing_messages_snapshot.set(tuple(dict(m) for m in original))+ async def test_routing_none_never_reaches_for_a_pre_guardrail_copy(self):+ """Routing asked for no compression while the model hop compressed, so the+ messages in hand are that guardrail's output and no uncompressed copy survives.+ Routing reads them as-is: the alternative is keeping a pre-guardrail copy, which+ is the text a masking guardrail exists to remove."""policy = AutoRouterCompressionPolicy(routing=None, model="headroom-a")model_compressed = [{"role": "user", "content": "[COMPRESSED] the full original conversation"}]- result = await messages_for_routing(policy=policy, messages=model_compressed, request_kwargs={})-- assert result == original+ assert await messages_for_routing(policy=policy, messages=model_compressed, request_kwargs={}) is None@pytest.mark.asyncioasync def test_unknown_guardrail_name_routes_on_the_uncompressed_messages(self):@@ -344,15 +334,18 @@ class TestMessagesForRouting:assert result == [{"role": "user", "content": "[COMPRESSED] hello world"}]@pytest.mark.asyncio- async def test_uses_the_snapshot_when_present(self, registered_guardrail):+ async def test_routing_compresses_what_the_other_guardrails_left_behind(self, registered_guardrail):+ """Regression (security): routing-side compression POSTs its input to an external+ service, so it must read the live messages every earlier guardrail has already+ rewritten. Routing on a pre-guardrail copy would send a masking guardrail's own+ input straight back out of the proxy."""policy = AutoRouterCompressionPolicy(routing="fake-compress", model="headroom-b")- auto_router_compression._routing_messages_snapshot.set(({"role": "user", "content": "original"},))- # `messages` here stands in for whatever the model-side guardrail already- # rewrote `data["messages"]` to -- routing must ignore it and compress the- # pristine snapshot instead.- already_rewritten = [{"role": "user", "content": "rewritten by another guardrail"}]- result = await messages_for_routing(policy=policy, messages=already_rewritten, request_kwargs={})- assert result == [{"role": "user", "content": "[COMPRESSED] original"}]+ masked = [{"role": "user", "content": "my ssn is [REDACTED]"}]++ result = await messages_for_routing(policy=policy, messages=masked, request_kwargs={})++ assert result == [{"role": "user", "content": "[COMPRESSED] my ssn is [REDACTED]"}]+ assert registered_guardrail.request_data_seen[0]["messages"] == masked@pytest.mark.asyncioasync def test_guardrail_receives_a_throwaway_request_data_not_the_real_request_kwargs(self, registered_guardrail):diff --git a/tests/test_litellm/test_router.py b/tests/test_litellm/test_router.pyindex 4c5813911ac..b4de20e9f0a 100644--- a/tests/test_litellm/test_router.py+++ b/tests/test_litellm/test_router.py@@ -10106,32 +10106,29 @@ class TestAutoRouterCompressionDecoupling:assert registered_guardrail.call_count == 0@pytest.mark.asyncio- async def test_routing_none_routes_on_the_original_not_the_model_compressed_messages(+ async def test_routing_none_classifies_on_the_live_messages_not_a_pre_guardrail_copy(self, registered_guardrail):- """Regression: with routing explicitly off and the model side compressed, the- messages the router holds are the model-side guardrail's output. Routing asked- for no compression, so it has to classify on the pre-compression snapshot."""- from litellm.proxy.guardrails import auto_router_compression+ """Routing asked for no compression while the model hop compressed, so the only+ messages left are that guardrail's output and the strategy classifies on them.+ Keeping a pre-compression copy to classify on instead is what this deliberately+ gives up: that copy is taken before the pre-call guardrails run, so it still+ holds whatever a masking guardrail exists to strip, and routing-side compression+ POSTs its input to an external service."""router, strategy = self._router({"auto_router_routing_compression": "none","auto_router_model_compression": "fake-compress",})- original_messages = self._messages()- auto_router_compression._routing_messages_snapshot.set(tuple(dict(m) for m in original_messages))model_compressed = [{"role": "user", "content": "[COMPRESSED] What is the capital of France?"}]- try:- await router.async_pre_routing_hook(- model="smart-router", request_kwargs={"metadata": {}}, messages=model_compressed- )- finally:- auto_router_compression._routing_messages_snapshot.set(None)+ await router.async_pre_routing_hook(+ model="smart-router", request_kwargs={"metadata": {}}, messages=model_compressed+ )- assert strategy.received_messages == original_messages+ assert strategy.received_messages == model_compressedassert registered_guardrail.call_count == 0@pytest.mark.asyncio