Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(proxy): bound the model-keyed tokenizer, beacon and litellm caches (#4497)

Gaurav Dubeye51b8065a4a2
diff --git a/headroom/pricing/litellm_pricing.py b/headroom/pricing/litellm_pricing.py
index ab16ccc6e..2bfc3525c 100644
--- a/headroom/pricing/litellm_pricing.py
+++ b/headroom/pricing/litellm_pricing.py
@@ -27,6 +27,7 @@ from headroom.pricing.litellm_model_resolution import (
pricing_lookup_candidates,
resolve_litellm_model_name,
)
+from headroom.utils import remember_bounded
# litellm calls `dotenv.load_dotenv()` during its own import, which loads
# the project `.env` into `os.environ`. We don't want that side effect —
@@ -59,7 +60,10 @@ except ImportError:
litellm = None # type: ignore[assignment]
LITELLM_AVAILABLE = False
+# Least-recently-used first. Keyed by the client-supplied model name, so the
+# entry count is capped (#4479); an evicted name is simply resolved again.
_resolved_model_cache: dict[str, str] = {}
+_RESOLVED_MODEL_CACHE_MAXSIZE = 256
logger = logging.getLogger("headroom.pricing")
@@ -113,14 +117,16 @@ def resolve_litellm_model(model: str) -> str:
the bare-prefix rules. Shared by the live (cost.py) and persisted
(savings_tracker) pricing paths so both figures price identically.
"""
- if model in _resolved_model_cache:
- return _resolved_model_cache[model]
+ cached = _resolved_model_cache.get(model)
+ if cached is not None:
+ remember_bounded(_resolved_model_cache, model, cached, _RESOLVED_MODEL_CACHE_MAXSIZE)
+ return cached
priced: str | None = None
alias = _static_alias_map()
if alias:
priced = _reduce_to_priced_key(alias.get(model, model))
resolved = priced if priced is not None else _resolve_litellm_model_uncached(model)
- _resolved_model_cache[model] = resolved
+ remember_bounded(_resolved_model_cache, model, resolved, _RESOLVED_MODEL_CACHE_MAXSIZE)
return resolved
diff --git a/headroom/telemetry/session.py b/headroom/telemetry/session.py
index aecbf50ef..da761dcb4 100644
--- a/headroom/telemetry/session.py
+++ b/headroom/telemetry/session.py
@@ -120,6 +120,7 @@ from pathlib import Path
from typing import Any
from headroom.offline import pin_litellm_cost_map_local
+from headroom.utils import remember_bounded
logger = logging.getLogger(__name__)
@@ -511,7 +512,11 @@ def _config_snapshot() -> dict[str, str]:
return out
+# Least-recently-used first. ``model`` comes from the request body, so the
+# entry count is capped (#4479); a model that falls out is simply looked up
+# again the next time it is seen.
_model_cache: dict[str, str | None] = {}
+_MODEL_CACHE_MAXSIZE = 256
def _public_model(model: str) -> str | None:
@@ -530,8 +535,13 @@ def _public_model(model: str) -> str | None:
"""
if not model:
return None
- if model in _model_cache:
- return _model_cache[model]
+ try:
+ cached = _model_cache[model]
+ except KeyError:
+ pass
+ else:
+ remember_bounded(_model_cache, model, cached, _MODEL_CACHE_MAXSIZE)
+ return cached
resolved: str | None = None
try:
@@ -546,9 +556,7 @@ def _public_model(model: str) -> str | None:
except Exception:
resolved = None
- # ponytail: unbounded dict, but it is keyed by distinct model ids seen in
- # one process — a handful. Cap it if a router ever fans out over hundreds.
- _model_cache[model] = resolved
+ remember_bounded(_model_cache, model, resolved, _MODEL_CACHE_MAXSIZE)
return resolved
diff --git a/headroom/tokenizers/registry.py b/headroom/tokenizers/registry.py
index fe89bc28c..9e8e984ef 100644
--- a/headroom/tokenizers/registry.py
+++ b/headroom/tokenizers/registry.py
@@ -11,6 +11,7 @@ import re
from collections.abc import Callable
from typing import TYPE_CHECKING
+from ..utils import remember_bounded
from .base import TokenCounter
from .estimator import EstimatingTokenCounter
@@ -144,8 +145,13 @@ class TokenizerRegistry:
# Registered model factories (model -> factory function)
_model_factories: dict[str, Callable[[str], TokenCounter]] = {}
- # Cache for auto-detected tokenizers
+ # Cache for auto-detected tokenizers, least-recently-used first. ``model``
+ # is the ``model`` field of a proxied request body, so the entry count is
+ # capped (#4479): each entry owns its own TokenCountCache, and a client
+ # sending a new name per request must not grow this without limit. Real
+ # traffic uses a handful of models, far below the cap.
_cache: dict[str, TokenCounter] = {}
+ _CACHE_MAXSIZE = 64
def __new__(cls) -> TokenizerRegistry:
"""Singleton pattern."""
@@ -198,8 +204,10 @@ class TokenizerRegistry:
# Check cache
cache_key = f"{model_lower}:{backend or 'auto'}"
- if cache_key in registry._cache:
- return registry._cache[cache_key]
+ cached = registry._cache.get(cache_key)
+ if cached is not None:
+ remember_bounded(registry._cache, cache_key, cached, cls._CACHE_MAXSIZE)
+ return cached
uses_model_factory = backend is None and model_lower in registry._model_factories
@@ -209,7 +217,7 @@ class TokenizerRegistry:
tokenizer = registry._model_factories[model_lower](model)
else:
tokenizer = registry._create_tokenizer(model, backend)
- registry._cache[cache_key] = tokenizer
+ remember_bounded(registry._cache, cache_key, tokenizer, cls._CACHE_MAXSIZE)
return tokenizer
except Exception as e:
if fallback:
@@ -218,7 +226,7 @@ class TokenizerRegistry:
)
tokenizer = EstimatingTokenCounter()
if not uses_model_factory:
- registry._cache[cache_key] = tokenizer
+ remember_bounded(registry._cache, cache_key, tokenizer, cls._CACHE_MAXSIZE)
return tokenizer
raise ValueError(f"No tokenizer available for {model}: {e}") from e
diff --git a/headroom/utils.py b/headroom/utils.py
index e0ba74e5d..65aaa6d0a 100644
--- a/headroom/utils.py
+++ b/headroom/utils.py
@@ -9,7 +9,10 @@ import re
import uuid
import warnings
from datetime import datetime, timezone
-from typing import Any
+from typing import Any, TypeVar
+
+_K = TypeVar("_K")
+_V = TypeVar("_V")
# Marker format for Headroom modifications
MARKER_PREFIX = "<headroom:"
@@ -42,6 +45,41 @@ def compute_short_hash(data: str | bytes, length: int = 16) -> str:
return compute_hash(data)[:length]
+def remember_bounded(cache: dict[_K, _V], key: _K, value: _V, maxsize: int) -> None:
+ """Store ``key`` as the newest entry of ``cache``, keeping at most ``maxsize``.
+
+ ``cache`` is a plain dict used as a least-recently-used cache: insertion
+ order is recency order, so the first key is the stalest and is evicted
+ first. Call this again on a cache hit to mark the key recently used.
+
+ Meant for caches keyed by client-controlled strings, such as a proxied
+ request's ``model`` field: the entry count stays bounded however many
+ distinct keys arrive, and an evicted key is recomputed on its next use
+ rather than answered wrongly.
+
+ Safe to call from several threads without a lock: a race can evict a key
+ early or leave the cache briefly one entry over ``maxsize``, never raise.
+
+ Args:
+ cache: The dict to update in place.
+ key: Cache key.
+ value: Value to store.
+ maxsize: Maximum number of entries. ``<= 0`` stores nothing.
+ """
+ if maxsize <= 0:
+ cache.clear()
+ return
+ cache.pop(key, None)
+ while len(cache) >= maxsize:
+ try:
+ oldest = next(iter(cache))
+ except (StopIteration, RuntimeError):
+ # Emptied, or resized by another thread mid-iteration.
+ break
+ cache.pop(oldest, None)
+ cache[key] = value
+
+
def fast_hash(data: str | bytes, length: int = 16) -> str:
"""Fast non-cryptographic content hash for caches and dedup.
diff --git a/tests/test_bounded_model_caches.py b/tests/test_bounded_model_caches.py
new file mode 100644
index 000000000..a6445e139
--- /dev/null
+++ b/tests/test_bounded_model_caches.py
@@ -0,0 +1,193 @@
+"""Regression: caches keyed by the request's ``model`` string stay bounded (#4479).
+
+``model`` comes straight off a proxied request body, so a client that sends a
+new name on every request must not be able to grow a process-wide cache
+without limit. #4407 bounded the per-model maps in the cost and savings
+trackers; these tests pin the same property for the three remaining caches:
+
+- ``TokenizerRegistry._cache`` (``headroom/tokenizers/registry.py``)
+- the beacon's ``_model_cache`` behind ``_public_model``
+ (``headroom/telemetry/session.py``)
+- ``_resolved_model_cache`` behind ``resolve_litellm_model``
+ (``headroom/pricing/litellm_pricing.py``)
+
+Each is least-recently-used: a name in steady use is never evicted, and an
+evicted name is recomputed on its next use rather than answered wrongly.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from headroom.pricing import litellm_pricing as lp
+from headroom.telemetry import session
+from headroom.tokenizers.estimator import EstimatingTokenCounter
+from headroom.tokenizers.registry import TokenizerRegistry
+from headroom.utils import remember_bounded
+
+# --------------------------------------------------------------------------
+# remember_bounded
+# --------------------------------------------------------------------------
+
+
+def test_remember_bounded_evicts_least_recently_inserted():
+ cache: dict[str, int] = {}
+ for i in range(5):
+ remember_bounded(cache, f"k{i}", i, maxsize=3)
+
+ assert list(cache) == ["k2", "k3", "k4"]
+
+
+def test_remember_bounded_reinsert_moves_key_to_newest():
+ cache: dict[str, int] = {}
+ for i in range(3):
+ remember_bounded(cache, f"k{i}", i, maxsize=3)
+
+ remember_bounded(cache, "k0", 0, maxsize=3) # a hit re-records the key
+ remember_bounded(cache, "k3", 3, maxsize=3)
+
+ assert list(cache) == ["k2", "k0", "k3"]
+
+
+def test_remember_bounded_nonpositive_maxsize_stores_nothing():
+ cache: dict[str, int] = {"stale": 1}
+ remember_bounded(cache, "k", 1, maxsize=0)
+
+ assert cache == {}
+
+
+def test_remember_bounded_tolerates_a_dict_resized_by_another_thread():
+ class ResizedDuringIteration(dict):
+ def __iter__(self):
+ raise RuntimeError("dictionary changed size during iteration")
+
+ cache = ResizedDuringIteration({"k0": 0, "k1": 1})
+ remember_bounded(cache, "k2", 2, maxsize=2)
+
+ # The eviction is skipped for this call rather than raising on the request
+ # path; the next insert that can iterate trims the cache again.
+ assert dict.__getitem__(cache, "k2") == 2
+
+
+# --------------------------------------------------------------------------
+# TokenizerRegistry._cache
+# --------------------------------------------------------------------------
+
+
+def clean_tokenizer_cache():
+ TokenizerRegistry.clear_cache()
+ yield
+ TokenizerRegistry.clear_cache()
+
+
+def test_tokenizer_registry_cache_is_bounded(clean_tokenizer_cache):
+ cap = TokenizerRegistry._CACHE_MAXSIZE
+ for i in range(cap + 50):
+ TokenizerRegistry.get(f"client-model-{i}-" + "m" * 1_000)
+
+ assert len(TokenizerRegistry._cache) == cap
+
+
+def test_tokenizer_registry_estimation_fallback_is_bounded(clean_tokenizer_cache):
+ cap = TokenizerRegistry._CACHE_MAXSIZE
+ for i in range(cap + 10):
+ tokenizer = TokenizerRegistry.get(f"client-model-{i}", backend="no-such-backend")
+ assert isinstance(tokenizer, EstimatingTokenCounter)
+
+ assert len(TokenizerRegistry._cache) == cap
+
+
+def test_tokenizer_registry_keeps_a_model_in_steady_use(clean_tokenizer_cache):
+ cap = TokenizerRegistry._CACHE_MAXSIZE
+ hot = TokenizerRegistry.get("gpt-4o")
+ for i in range(cap + 50):
+ TokenizerRegistry.get(f"client-model-{i}")
+ assert TokenizerRegistry.get("gpt-4o") is hot
+
+ oldest = TokenizerRegistry.get("client-model-0")
+ assert "client-model-0:auto" in TokenizerRegistry._cache
+ assert oldest is TokenizerRegistry.get("client-model-0")
+
+
+# --------------------------------------------------------------------------
+# telemetry.session._model_cache
+# --------------------------------------------------------------------------
+
+
+def clean_public_model_cache():
+ session._model_cache.clear()
+ yield
+ session._model_cache.clear()
+
+
+def test_public_model_cache_is_bounded(clean_public_model_cache):
+ cap = session._MODEL_CACHE_MAXSIZE
+ for i in range(cap + 50):
+ assert session._public_model(f"custom-{i}-" + "m" * 1_000) is None
+
+ assert len(session._model_cache) == cap
+
+
+def test_public_model_evicted_name_is_recomputed(clean_public_model_cache, monkeypatch):
+ calls: list[str] = []
+ real_pin = session.pin_litellm_cost_map_local
+
+ def counting_pin() -> None:
+ calls.append("probe")
+ real_pin()
+
+ monkeypatch.setattr(session, "pin_litellm_cost_map_local", counting_pin)
+
+ cap = session._MODEL_CACHE_MAXSIZE
+ session._public_model("seed-model")
+ for i in range(cap):
+ session._public_model(f"custom-{i}")
+ probes_before = len(calls)
+
+ assert session._public_model("seed-model") is None
+ assert len(calls) == probes_before + 1
+ assert len(session._model_cache) == cap
+
+
+# --------------------------------------------------------------------------
+# litellm_pricing._resolved_model_cache
+# --------------------------------------------------------------------------
+
+
+def counted_resolution(monkeypatch):
+ lp._resolved_model_cache.clear()
+ calls: dict[str, int] = {}
+
+ def fake_uncached(model: str) -> str:
+ calls[model] = calls.get(model, 0) + 1
+ return f"resolved/{model}"
+
+ monkeypatch.setattr(lp, "_resolve_litellm_model_uncached", fake_uncached)
+ monkeypatch.delenv("HEADROOM_MODEL_ALIAS_MAP", raising=False)
+ yield calls
+ lp._resolved_model_cache.clear()
+
+
+def test_resolved_model_cache_is_bounded(counted_resolution):
+ cap = lp._RESOLVED_MODEL_CACHE_MAXSIZE
+ for i in range(cap + 50):
+ assert lp.resolve_litellm_model(f"custom-{i}") == f"resolved/custom-{i}"
+
+ assert len(lp._resolved_model_cache) == cap
+
+
+def test_resolved_model_cache_is_lru(counted_resolution):
+ cap = lp._RESOLVED_MODEL_CACHE_MAXSIZE
+ lp.resolve_litellm_model("hot-model")
+ lp.resolve_litellm_model("cold-model")
+ for i in range(cap):
+ lp.resolve_litellm_model(f"custom-{i}")
+ lp.resolve_litellm_model("hot-model")
+
+ assert counted_resolution["hot-model"] == 1
+
+ assert lp.resolve_litellm_model("cold-model") == "resolved/cold-model"
+ assert counted_resolution["cold-model"] == 2