Skip to content

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]

fix(headroom): bound the /v1/compress and /v1/retrieve calls with a timeout (#39527)

yucheng-berri59d42d36e6a0
diff --git a/litellm/proxy/guardrails/guardrail_hooks/headroom/__init__.py b/litellm/proxy/guardrails/guardrail_hooks/headroom/__init__.py
index cffef84e966..d569802ce89 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/headroom/__init__.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/headroom/__init__.py
@@ -35,6 +35,7 @@ def initialize_guardrail(litellm_params: LitellmParams, guardrail: Guardrail) ->
event_hook=_coerce_event_hook(litellm_params.mode),
default_on=litellm_params.default_on or False,
unreachable_fallback=litellm_params.unreachable_fallback,
+ timeout=litellm_params.timeout,
)
litellm.logging_callback_manager.add_litellm_callback( # pyright: ignore[reportUnknownMemberType]
_callback
diff --git a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py
index 9d993384461..685b90f1754 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
+import math
import re
import time
import uuid
@@ -15,6 +16,7 @@ from pydantic import TypeAdapter
import litellm
from litellm._logging import verbose_proxy_logger
from litellm.compression.compress import get_protected_indices
+from litellm.constants import HTTP_HANDLER_CONNECT_TIMEOUT_SECONDS
from litellm.integrations.custom_guardrail import (
CustomGuardrail,
log_guardrail_information,
@@ -47,12 +49,16 @@ from litellm.types.utils import CallTypes, GenericGuardrailAPIInputs
if TYPE_CHECKING:
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+ from litellm.types.guardrails import LitellmParams
from litellm.types.proxy.guardrails.guardrail_hooks.base import GuardrailConfigModel
BYPASS_HEADER: Final = "x-headroom-bypass"
_STREAM_CONVERTIBLE_CALL_TYPES: Final = frozenset(
(CallTypes.completion, CallTypes.acompletion, CallTypes.responses, CallTypes.aresponses)
)
+# The shared GuardrailCallback client carries no per-call bound, so without this a
+# stalled service holds the caller's request and a pooled connection for 600s or more.
+_COMPRESS_TIMEOUT_SECONDS: Final = 60.0
HEADROOM_RETRIEVE_TOOL_NAME: Final = "headroom_retrieve"
_HASH_PATTERN: Final = re.compile(r"hash=([a-f0-9]{24})")
_HASH_CACHE_TTL_SECONDS: Final = 15 * 60
@@ -472,6 +478,7 @@ class HeadroomGuardrail(CustomGuardrail):
event_hook: GuardrailEventHooks | list[GuardrailEventHooks] | Mode | None = None,
default_on: bool = False,
unreachable_fallback: str | None = None,
+ timeout: float | None = None,
):
self.headroom_api_base = (api_base or get_secret_str("HEADROOM_API_BASE") or "").rstrip("/")
if not self.headroom_api_base:
@@ -484,6 +491,7 @@ class HeadroomGuardrail(CustomGuardrail):
self.unreachable_fallback: Literal["fail_closed", "fail_open"] = (
"fail_open" if unreachable_fallback == "fail_open" else "fail_closed"
)
+ self.timeout: httpx.Timeout = self._resolve_timeout(timeout)
self.async_handler = get_async_httpx_client(
llm_provider=httpxSpecialProvider.GuardrailCallback,
)
@@ -511,6 +519,29 @@ class HeadroomGuardrail(CustomGuardrail):
headers["Authorization"] = f"Bearer {self.headroom_api_key}"
return headers
+ @staticmethod
+ def _resolve_timeout(timeout: float | None) -> httpx.Timeout:
+ """Budget for one call to the compression service, unset meaning the default.
+
+ Zero, negative and non-finite values are rejected instead of passed through:
+ httpx accepts them, and the transport then reads 0 and inf as no deadline at
+ all and a negative one as a deadline already past.
+ """
+ rejected: Final = timeout is not None and not (math.isfinite(timeout) and timeout > 0)
+ if rejected:
+ verbose_proxy_logger.warning(
+ "Headroom: ignoring unusable timeout %s, using %s seconds",
+ timeout,
+ _COMPRESS_TIMEOUT_SECONDS,
+ )
+ seconds: Final = _COMPRESS_TIMEOUT_SECONDS if timeout is None or rejected else timeout
+ return httpx.Timeout(timeout=seconds, connect=min(seconds, HTTP_HANDLER_CONNECT_TIMEOUT_SECONDS))
+
+ def update_in_memory_litellm_params(self, litellm_params: LitellmParams) -> None:
+ """Re-resolve the timeout, which the base implementation would otherwise null out."""
+ super().update_in_memory_litellm_params(litellm_params)
+ self.timeout = self._resolve_timeout(litellm_params.timeout)
+
def _prune_expired_hashes(self) -> None:
now: Final = time.monotonic()
self._issued_hashes_by_call_id = {
@@ -548,6 +579,7 @@ class HeadroomGuardrail(CustomGuardrail):
url=f"{self.headroom_api_base}/v1/compress",
json=payload,
headers=self._request_headers(),
+ timeout=self.timeout,
)
except httpx.HTTPStatusError as e:
return (
@@ -685,6 +717,7 @@ class HeadroomGuardrail(CustomGuardrail):
url=f"{self.headroom_api_base}/v1/retrieve/{hash_value}",
params=params,
headers=self._request_headers(),
+ timeout=self.timeout,
)
except (httpx.ConnectError, httpx.TimeoutException, httpx.TransportError, litellm.Timeout) as e:
verbose_proxy_logger.warning("Headroom: retrieve failed for hash=%s: %s", hash_value, e)
diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py
index 400eaf8ab3f..a49d7723bcc 100644
--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py
+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py
@@ -1694,8 +1694,6 @@ async def test_apply_guardrail_litellm_timeout_fail_open_forwards_uncompressed()
assert result["structured_messages"] == ORIGINAL_MESSAGES
-
-
# ---------------------------------------------------------------------------
# Content-parts flattening (LIT-4795)
#
@@ -2669,7 +2667,9 @@ async def _plan_for(guardrail: HeadroomGuardrail, response, messages: list):
return_value=_make_retrieve_response("ORIGINAL CONTENT"),
):
return await guardrail.async_build_agentic_loop_plan(
- tools={"tool_calls": [{"id": "call_1", "name": HEADROOM_RETRIEVE_TOOL_NAME, "arguments": {"hash": "h" * 24}}]},
+ tools={
+ "tool_calls": [{"id": "call_1", "name": HEADROOM_RETRIEVE_TOOL_NAME, "arguments": {"hash": "h" * 24}}]
+ },
model="claude-sonnet-4-5-20250929",
messages=messages,
response=response,
@@ -2732,3 +2732,153 @@ async def test_chat_followup_echoes_only_the_retrieve_call(guardrail: HeadroomGu
assert assistant["content"] == "Getting the original first."
assert [tc["id"] for tc in assistant["tool_calls"]] == ["call_1"]
assert [m["tool_call_id"] for m in messages[2:]] == ["call_1"]
+
+
+# --- LIT-5881: the calls to the compression service must be time-bounded ---
+
+
+def _timeout_of(mock_call) -> httpx.Timeout:
+ timeout = mock_call.kwargs["timeout"]
+ assert isinstance(timeout, httpx.Timeout), timeout
+ return timeout
+
+
+async def test_compress_call_passes_bounded_timeout(guardrail: HeadroomGuardrail):
+ """Without an explicit timeout the call inherits the shared client's 600s read leg."""
+ inputs = GenericGuardrailAPIInputs(texts=["A" * 5000], structured_messages=ORIGINAL_MESSAGES)
+
+ with patch.object(
+ guardrail.async_handler,
+ "post",
+ new_callable=AsyncMock,
+ return_value=_make_compress_response(COMPRESSED_MESSAGES),
+ ) as mock_post:
+ await guardrail.apply_guardrail(inputs=inputs, request_data={}, input_type="request")
+
+ timeout = _timeout_of(mock_post.call_args)
+ assert timeout.read == 60.0
+ assert timeout.write == 60.0
+ assert timeout.pool == 60.0
+ assert timeout.connect == 5.0
+
+
+async def test_retrieve_call_passes_bounded_timeout(guardrail: HeadroomGuardrail):
+ """The retrieval leg runs on the same request and needs the same bound."""
+ with patch.object(
+ guardrail.async_handler,
+ "get",
+ new_callable=AsyncMock,
+ return_value=_make_retrieve_response("original"),
+ ) as mock_get:
+ result = await guardrail._call_retrieve("a" * 24)
+
+ assert result == "original"
+ timeout = _timeout_of(mock_get.call_args)
+ assert timeout.read == 60.0
+ assert timeout.connect == 5.0
+
+
+async def test_configured_timeout_overrides_the_default():
+ """Headroom accepted litellm_params.timeout and ignored it."""
+ guardrail = _make_guardrail(timeout=3.5)
+ inputs = GenericGuardrailAPIInputs(texts=["A" * 5000], structured_messages=ORIGINAL_MESSAGES)
+
+ with patch.object(
+ guardrail.async_handler,
+ "post",
+ new_callable=AsyncMock,
+ return_value=_make_compress_response(COMPRESSED_MESSAGES),
+ ) as mock_post:
+ await guardrail.apply_guardrail(inputs=inputs, request_data={}, input_type="request")
+
+ timeout = _timeout_of(mock_post.call_args)
+ assert timeout.read == 3.5
+ assert timeout.connect == 3.5
+
+
+async def test_read_timeout_is_surfaced_as_unreachable_under_fail_closed():
+ """A stalled service must reach the fail policy, not escape as a 500."""
+ guardrail = _make_guardrail()
+ inputs = GenericGuardrailAPIInputs(texts=["hello"], structured_messages=ORIGINAL_MESSAGES)
+
+ with patch.object(
+ guardrail.async_handler,
+ "post",
+ new_callable=AsyncMock,
+ side_effect=httpx.ReadTimeout("timed out"),
+ ):
+ with pytest.raises(HTTPException) as exc_info:
+ await guardrail.apply_guardrail(inputs=inputs, request_data={}, input_type="request")
+
+ assert exc_info.value.status_code == 502
+ assert "unreachable" in str(exc_info.value.detail)
+
+
+async def test_read_timeout_forwards_uncompressed_under_fail_open():
+ guardrail = _make_guardrail(unreachable_fallback="fail_open")
+ inputs = GenericGuardrailAPIInputs(texts=["hello"], structured_messages=ORIGINAL_MESSAGES)
+
+ with patch.object(
+ guardrail.async_handler,
+ "post",
+ new_callable=AsyncMock,
+ side_effect=httpx.ReadTimeout("timed out"),
+ ):
+ result = await guardrail.apply_guardrail(inputs=inputs, request_data={}, input_type="request")
+
+ assert result.get("structured_messages") == ORIGINAL_MESSAGES
+
+
+def test_initializer_forwards_configured_timeout(monkeypatch: pytest.MonkeyPatch):
+ """Wiring it only in __init__ leaves `timeout:` in config.yaml silently ignored."""
+ from litellm.proxy.guardrails.guardrail_hooks.headroom import initialize_guardrail
+ from litellm.types.guardrails import LitellmParams
+
+ monkeypatch.setattr(
+ litellm.logging_callback_manager,
+ "add_litellm_callback",
+ lambda callback: None,
+ )
+ params = LitellmParams(
+ guardrail="headroom",
+ mode="pre_call",
+ api_base=FAKE_API_BASE,
+ api_key=FAKE_API_KEY,
+ timeout=7.0,
+ )
+ callback = initialize_guardrail(params, {"guardrail_name": "headroom"}) # type: ignore[arg-type]
+
+ assert callback.timeout.read == 7.0
+
+
+def test_in_place_update_keeps_the_timeout_resolved():
+ """The base implementation copies every attribute over, nulling an unset timeout."""
+ from litellm.types.guardrails import LitellmParams
+
+ guardrail = _make_guardrail(timeout=5.0)
+ assert guardrail.timeout.read == 5.0
+
+ guardrail.update_in_memory_litellm_params(
+ LitellmParams(guardrail="headroom", mode="pre_call", api_base=FAKE_API_BASE)
+ )
+ assert isinstance(guardrail.timeout, httpx.Timeout)
+ assert guardrail.timeout.read == 60.0
+
+ guardrail.update_in_memory_litellm_params(
+ LitellmParams(guardrail="headroom", mode="pre_call", api_base=FAKE_API_BASE, timeout=7.0)
+ )
+ assert guardrail.timeout.read == 7.0
+
+
[email protected]("configured", [0, 0.0, -1, -30.0, float("inf"), float("-inf"), float("nan")])
+def test_unusable_timeout_falls_back_to_the_default(configured: float):
+ """0 and inf read as no deadline at all, a negative one as a deadline already past."""
+ guardrail = _make_guardrail(timeout=configured)
+
+ assert guardrail.timeout.read == 60.0
+ assert guardrail.timeout.connect == 5.0