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.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(proxy): bound request-log message payloads to the feed window; trim glibc too (#3717)
gglucass994a89f169d4
diff --git a/headroom/cli/proxy.py b/headroom/cli/proxy.pyindex 16a23718c..e3bb2979f 100644--- a/headroom/cli/proxy.py+++ b/headroom/cli/proxy.py@@ -1137,6 +1137,7 @@ def proxy(_parse_csv_tools,_parse_exclude_tools,_parse_tool_profiles,+ default_periodic_malloc_trim,run_server,)@@ -1326,7 +1327,7 @@ def proxy(rate_limit_tokens_per_minute=tpm if tpm is not None else 100_000,compress_user_messages=_get_env_bool("HEADROOM_COMPRESS_USER_MESSAGES", False),periodic_malloc_trim_enabled=_get_env_bool(- "HEADROOM_MALLOC_TRIM", sys.platform == "darwin"+ "HEADROOM_MALLOC_TRIM", default_periodic_malloc_trim()),malloc_trim_interval_seconds=_get_env_int("HEADROOM_MALLOC_TRIM_INTERVAL_SECONDS", 60),min_tokens_to_crush=_get_env_int("HEADROOM_MIN_TOKENS", 500),diff --git a/headroom/proxy/models.py b/headroom/proxy/models.pyindex fd93a9c72..4aa7163c1 100644--- a/headroom/proxy/models.py+++ b/headroom/proxy/models.py@@ -42,6 +42,16 @@ def _qdrant_env_port_or_default() -> int:return qdrant_env.DEFAULT_QDRANT_PORT+def default_periodic_malloc_trim() -> bool:+ """Platforms where the periodic allocator trim is on unless opted out.++ Shared by ``ProxyConfig``'s default and by the two call sites that build a+ config explicitly (``headroom proxy`` and ``_proxy_config_from_env``), so the+ platform scope cannot drift between them.+ """+ return sys.platform in ("darwin", "linux")++# =============================================================================# Data Models# =============================================================================@@ -470,12 +480,13 @@ class ProxyConfig:# Periodic allocator trim. Long-lived proxies processing large concurrent# request bodies ratchet RSS through freed-but-retained allocator pages;# this returns them to the OS (malloc_zone_pressure_relief on macOS,- # malloc_trim on glibc). Default-on only on macOS, where the retained-page- # ratchet is the documented failure (#2820); an opt-in elsewhere via- # HEADROOM_MALLOC_TRIM=1 so glibc deployments do not silently take on a- # once-a-minute allocator purge they did not ask for. Envs:- # HEADROOM_MALLOC_TRIM=0/1, HEADROOM_MALLOC_TRIM_INTERVAL_SECONDS.- periodic_malloc_trim_enabled: bool = field(default_factory=lambda: sys.platform == "darwin")+ # malloc_trim on glibc). Default-on where a trim call exists: macOS, where+ # the retained-page ratchet was first documented (#2820), and glibc Linux,+ # which ratchets the same way (a coding-agent session took one proxy to+ # 100 GB RSS on a 128 GB host with the trim off). Platforms without a trim+ # call disable the task themselves. Envs: HEADROOM_MALLOC_TRIM=0/1,+ # HEADROOM_MALLOC_TRIM_INTERVAL_SECONDS.+ periodic_malloc_trim_enabled: bool = field(default_factory=default_periodic_malloc_trim)malloc_trim_interval_seconds: int = 60# Stateless mode — disable all filesystem writes for read-only / container deploymentsdiff --git a/headroom/proxy/request_logger.py b/headroom/proxy/request_logger.pyindex 170618413..c7894a536 100644--- a/headroom/proxy/request_logger.py+++ b/headroom/proxy/request_logger.py@@ -97,6 +97,14 @@ class RequestLogger:"""MAX_LOG_ENTRIES = 10_000+ # How many of the newest entries keep their message payloads+ # (``request_messages`` / ``compressed_messages`` / ``response_content``).+ # ``/transformations/feed`` serves at most this many, and nothing else+ # reads the payloads back, so keeping them on all MAX_LOG_ENTRIES retained+ # two parsed copies of every conversation for the life of the process:+ # a long agentic session grew one proxy to 100 GB RSS. Light fields stay+ # on every entry for ``get_recent`` / ``/stats``.+ MESSAGE_WINDOW = 100def __init__(self, log_file: str | None = None, log_full_messages: bool = False):self.log_file = Path(log_file) if log_file else None@@ -136,6 +144,14 @@ class RequestLogger:entry.response_content = redact_image_base64(entry.response_content)self._logs.append(entry)+ # Drop the payloads of the entry that just left the message window.+ # One entry per append keeps the newest MESSAGE_WINDOW populated and+ # every older one light without a scan.+ if len(self._logs) > self.MESSAGE_WINDOW:+ aged = self._logs[-self.MESSAGE_WINDOW - 1]+ aged.request_messages = None+ aged.compressed_messages = None+ aged.response_content = Noneif self.log_file:try:diff --git a/headroom/proxy/server.py b/headroom/proxy/server.pyindex e51165ee1..7d9d5117b 100644--- a/headroom/proxy/server.py+++ b/headroom/proxy/server.py@@ -153,7 +153,13 @@ from headroom.proxy.memory_handler import MemoryConfig, MemoryHandler# Data models (extracted to headroom/proxy/models.py for maintainability)from headroom.proxy.model_router import ModelRouter, ModelRouterConfig-from headroom.proxy.models import CacheEntry, ProxyConfig, RateLimitState, RequestLog # noqa: F401+from headroom.proxy.models import ( # noqa: F401+ CacheEntry,+ ProxyConfig,+ RateLimitState,+ RequestLog,+ default_periodic_malloc_trim,+)from headroom.proxy.modes import (PROXY_MODE_CACHE,PROXY_MODE_TOKEN,@@ -5723,7 +5729,7 @@ def _proxy_config_from_env() -> ProxyConfig:http_proxy=os.environ.get("HEADROOM_HTTP_PROXY") or None,periodic_toin_stats_enabled=_get_env_bool("HEADROOM_PERIODIC_TOIN_STATS", True),periodic_malloc_trim_enabled=_get_env_bool(- "HEADROOM_MALLOC_TRIM", sys.platform == "darwin"+ "HEADROOM_MALLOC_TRIM", default_periodic_malloc_trim()),malloc_trim_interval_seconds=_get_env_int("HEADROOM_MALLOC_TRIM_INTERVAL_SECONDS", 60),proxy_token=os.environ.get("HEADROOM_PROXY_TOKEN") or None,diff --git a/tests/test_malloc_tuning.py b/tests/test_malloc_tuning.pyindex 2c30b2731..b2e5f3581 100644--- a/tests/test_malloc_tuning.py+++ b/tests/test_malloc_tuning.py@@ -276,17 +276,71 @@ async def test_slow_trim_does_not_stop_unrelated_async_work(monkeypatch):# --------------------------------------------------------------------------- ## ProxyConfig wiring# --------------------------------------------------------------------------- #-def test_proxy_config_malloc_trim_default_is_darwin_scoped(monkeypatch):- # Default-on only on macOS (the platform with the documented RSS ratchet);- # elsewhere it is opt-in, so glibc deployments do not silently take on a- # once-a-minute allocator purge.+def test_proxy_config_malloc_trim_default_is_scoped_to_platforms_with_a_trim_call(monkeypatch):+ # Default-on on macOS and glibc Linux, the two platforms with a trim call+ # and a documented RSS ratchet; elsewhere the periodic task is a no-op, so+ # the default stays off rather than scheduling wakeups for nothing.from headroom.proxy import modelsmonkeypatch.setattr(models.sys, "platform", "darwin")assert models.ProxyConfig().periodic_malloc_trim_enabled is Truemonkeypatch.setattr(models.sys, "platform", "linux")+ assert models.ProxyConfig().periodic_malloc_trim_enabled is True++ monkeypatch.setattr(models.sys, "platform", "win32")assert models.ProxyConfig().periodic_malloc_trim_enabled is False# The interval knob is platform-independent.assert models.ProxyConfig().malloc_trim_interval_seconds == 60+++ ("platform", "expected"),+ [("darwin", True), ("linux", True), ("win32", False)],+)+def test_cli_proxy_uses_the_same_trim_default_as_the_dataclass(monkeypatch, platform, expected):+ # `headroom proxy` builds its ProxyConfig field by field, so it can only+ # inherit the platform scope by calling the shared default: a literal here+ # (as `sys.platform == "darwin"` was) silently overrides the dataclass for+ # every CLI-launched proxy. Covers the third entry point; the server's+ # env factory and ProxyConfig() itself are covered above.+ pytest.importorskip("click")+ pytest.importorskip("fastapi")+ from click.testing import CliRunner++ from headroom.cli.main import main++ monkeypatch.setattr(proxy_cli.sys, "platform", platform)+ monkeypatch.delenv("HEADROOM_MALLOC_TRIM", raising=False)+ captured: dict = {}++ def fake_run_server(config, **kwargs): # noqa: ANN001+ captured["config"] = config++ monkeypatch.setattr("headroom.proxy.server.run_server", fake_run_server)+ result = CliRunner().invoke(main, ["proxy"], catch_exceptions=False)++ assert result.exit_code == 0, result.output+ assert captured["config"].periodic_malloc_trim_enabled is expected+++def test_cli_proxy_trim_env_opt_out_still_wins(monkeypatch):+ pytest.importorskip("click")+ pytest.importorskip("fastapi")+ from click.testing import CliRunner++ from headroom.cli.main import main++ monkeypatch.setattr(proxy_cli.sys, "platform", "linux")+ monkeypatch.setenv("HEADROOM_MALLOC_TRIM", "0")+ captured: dict = {}++ def fake_run_server(config, **kwargs): # noqa: ANN001+ captured["config"] = config++ monkeypatch.setattr("headroom.proxy.server.run_server", fake_run_server)+ result = CliRunner().invoke(main, ["proxy"], catch_exceptions=False)++ assert result.exit_code == 0, result.output+ assert captured["config"].periodic_malloc_trim_enabled is Falsediff --git a/tests/test_proxy/test_request_logger.py b/tests/test_proxy/test_request_logger.pyindex 124e66878..4689ad47a 100644--- a/tests/test_proxy/test_request_logger.py+++ b/tests/test_proxy/test_request_logger.py@@ -134,6 +134,45 @@ def test_get_recent_never_walks_message_payloads():assert again["savings_breakdown"] == [{"tokens": 60}]+def test_payloads_survive_only_on_the_newest_message_window():+ logger = RequestLogger(log_file=None, log_full_messages=True)+ window = RequestLogger.MESSAGE_WINDOW+ total = window + 50+ for i in range(total):+ logger.log(+ _entry(+ request_id=f"r{i}",+ request_messages=[{"role": "user", "content": f"pre{i}"}],+ compressed_messages=[{"role": "user", "content": f"post{i}"}],+ response_content=f"resp{i}",+ )+ )++ logs = list(logger._logs)+ assert len(logs) == total+ # Every entry is still there for /stats, in order, light fields intact.+ assert [e.request_id for e in logs] == [f"r{i}" for i in range(total)]+ assert all(e.tokens_saved == 60 for e in logs)+ # Only the newest MESSAGE_WINDOW keep their payloads.+ aged, kept = logs[:-window], logs[-window:]+ assert all(+ e.request_messages is None and e.compressed_messages is None and e.response_content is None+ for e in aged+ )+ assert all(e.request_messages and e.compressed_messages and e.response_content for e in kept)+ # The feed path is fully populated for its whole cap.+ feed = logger.get_recent_with_messages(window)+ assert len(feed) == window+ assert all(item["request_messages"] for item in feed)+++def test_message_window_leaves_a_short_log_untouched():+ logger = RequestLogger(log_file=None, log_full_messages=True)+ for i in range(RequestLogger.MESSAGE_WINDOW):+ logger.log(_entry(request_id=f"r{i}", request_messages=[{"role": "user", "content": "x"}]))+ assert all(e.request_messages for e in logger._logs)++def test_get_recent_with_messages_can_skip_payloads_without_walking_them():"""A feed poller that only reads the numbers passes include_messages=False;the three body fields are absent and never traversed (asdict deep-copied