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(read-maturation): book matured Read savings once, not on every replay (#3414)
gglucass85f58a9a7a64
diff --git a/headroom/proxy/handlers/anthropic.py b/headroom/proxy/handlers/anthropic.pyindex a72470afb..dc88815ff 100644--- a/headroom/proxy/handlers/anthropic.py+++ b/headroom/proxy/handlers/anthropic.py@@ -2282,6 +2282,11 @@ class AnthropicHandlerMixin:# request. Session state (matured markers) rides on the# prefix tracker — same affinity and TTL cleanup as the# freeze state. Advisory: must never fail the request.+ # Bound when maturation runs, so the final accounting step below+ # can charge this request's replayed-marker debt. Every earlier+ # `tokens_saved` assignment is overwritten by that recount, so the+ # adjustment belongs there and nowhere else.+ _maturation_mgr = Noneif self.config.read_maturation and not _bypass:try:from headroom.config import ReadMaturationConfig@@ -2302,6 +2307,7 @@ class AnthropicHandlerMixin:compression_store=get_compression_store(),)prefix_tracker.read_maturation_manager = maturation_mgr+ _maturation_mgr = maturation_mgrmaturation = maturation_mgr.apply(optimized_messages,frozen_message_count=frozen_message_count,@@ -3187,7 +3193,27 @@ class AnthropicHandlerMixin:if 0 < _tool_tokens_after < _tool_tokens_before:original_tokens += _tool_tokens_beforeoptimized_tokens += _tool_tokens_after- tokens_saved = max(0, original_tokens - optimized_tokens)+ # First-appearance accounting for matured Reads. The client+ # re-sends the raw conversation every turn, so this diff would+ # otherwise re-book a matured Read's removal on every request+ # until end of session. Charged here, on the request's real+ # endpoints, because after maturation the marker usually+ # reaches the wire through the cached-prefix replay rather than+ # through the maturation pass — and because every earlier+ # `tokens_saved` assignment is overwritten right here.+ # tok_before/tok_after stay the honest wire counts; only the+ # booked saving is first-appearance.+ _replay_debt = 0+ if _maturation_mgr is not None:+ try:+ _replay_debt = _maturation_mgr.replayed_token_debt(+ _orig_snapshot, optimized_messages, tokenizer.count_text+ )+ except Exception:+ # Advisory, like the maturation pass itself: a failure+ # here must not skip the recount around it.+ logger.debug("maturation replay debt skipped", exc_info=True)+ tokens_saved = max(0, original_tokens - optimized_tokens - _replay_debt)# Attribute the fold to the hook ONLY when the hook itself reduced# tokens (same-tokenizer pre vs post) — not when the recount above# merely normalized a cross-estimator scale difference.diff --git a/headroom/transforms/read_maturation.py b/headroom/transforms/read_maturation.pyindex 309c369e4..bcf637628 100644--- a/headroom/transforms/read_maturation.py+++ b/headroom/transforms/read_maturation.py@@ -53,6 +53,7 @@ from __future__ import annotationsimport hashlibimport jsonimport logging+from collections.abc import Callable, Iteratorfrom dataclasses import dataclass, fieldfrom typing import Any@@ -102,6 +103,26 @@ class MaturationResult:bytes_saved: int = 0+def _iter_tool_results(messages: list[dict[str, Any]]) -> Iterator[tuple[str, str]]:+ """(tool_call_id, content) for every string tool result, both formats."""+ for msg in messages or []:+ if not isinstance(msg, dict):+ continue+ content = msg.get("content")+ if msg.get("role") == "tool":+ if isinstance(content, str):+ yield str(msg.get("tool_call_id", "")), content+ continue+ if isinstance(content, list):+ for b in content:+ if (+ isinstance(b, dict)+ and b.get("type") == "tool_result"+ and isinstance(b.get("content"), str)+ ):+ yield str(b.get("tool_use_id", "")), b["content"]++class ReadMaturationManager:"""Per-session Read maturation state machine.@@ -118,6 +139,11 @@ class ReadMaturationManager:self.config = configself.store = compression_storeself._matured: dict[str, MaturedRead] = {}+ # tool_call_ids whose removal has already been booked as savings.+ self._booked: set[str] = set()+ # tool_call_id -> token delta of its replayed marker, tokenized+ # once per session (content and marker are stable per tool call).+ self._replay_token_deltas: dict[str, int] = {}# ─── Per-request entry point ────────────────────────────────────────@@ -159,6 +185,57 @@ class ReadMaturationManager:result.messages = outreturn result+ def replayed_token_debt(+ self,+ original_messages: list[dict[str, Any]],+ outbound_messages: list[dict[str, Any]],+ count_text: Callable[[str], int],+ ) -> int:+ """Tokens this request re-saved by re-removing content whose removal+ was already booked on an EARLIER request.++ The client re-sends the raw conversation every turn, so a plain+ original-vs-optimized token diff books a matured Read's removal+ again on every request until end of session; one long session+ inflated its new-content savings rate from 31.8% to 78.15% the+ day maturation turned on, with no new removal behind the jump.+ Subtracting this debt makes the figure first-appearance: matured+ content books exactly once, on the turn it matures.++ Measured on the request's own endpoints (the raw client snapshot+ vs what is actually forwarded) rather than on this pass's+ replacements, because after a Read matures its marker usually+ reaches the wire through the cached-prefix replay instead of+ through :meth:`apply` — the replacement this manager makes is+ only one of the paths that re-remove it.++ Call this ONCE per request, on the final outbound messages:+ the first booking is recorded as a side effect, so a second call+ would charge the request for its own first appearance.+ ``count_text`` should be the tokenizer the caller diffs with, so+ the subtraction lands on the booked scale. Deltas are tokenized+ once per tool call and cached for the session.+ """+ if not self._matured:+ return 0+ forwarded = dict(_iter_tool_results(outbound_messages))+ debt = 0+ for tc_id, content in _iter_tool_results(original_messages):+ matured = self._matured.get(tc_id)+ if matured is None or forwarded.get(tc_id) != matured.marker:+ continue # not replaced on the wire this request+ if content == matured.marker:+ continue # the client already held the marker: nothing removed+ if tc_id not in self._booked:+ self._booked.add(tc_id) # first appearance: books in full+ continue+ delta = self._replay_token_deltas.get(tc_id)+ if delta is None:+ delta = max(0, count_text(content) - count_text(matured.marker))+ self._replay_token_deltas[tc_id] = delta+ debt += delta+ return debt+# ─── Internals ──────────────────────────────────────────────────────def _scan_activity(self, messages: list[dict[str, Any]]) -> _Activity:diff --git a/tests/test_read_maturation.py b/tests/test_read_maturation.pyindex 6cc6e37b8..db37c7e04 100644--- a/tests/test_read_maturation.py+++ b/tests/test_read_maturation.py@@ -351,3 +351,81 @@ class TestBreakpointRelocation:if __name__ == "__main__":pytest.main([__file__, "-v"])+++class TestFirstAppearanceAccounting:+ """A matured Read's savings must book once, on the turn it matures.++ The client re-sends the raw conversation every turn, so a plain+ original-vs-optimized token diff re-counts the same removal on every+ later request. ``replayed_token_debt`` measures that from the+ request's own endpoints — raw client snapshot vs forwarded messages —+ rather than from what ``apply`` replaced, because after maturation+ the marker normally reaches the wire through the cached-prefix replay+ and ``apply`` replaces nothing at all.+ """++ def _matured(self):+ """Returns (manager, raw client messages, forwarded messages)."""+ m = manager(quiesce_turns=5)+ raw = [*base_conv(), *quiet(5)]+ res = m.apply(raw)+ assert res.newly_matured == 1+ return m, raw, res.messages++ @staticmethod+ def _marker(sent):+ return sent[2]["content"][0]["content"]++ def test_first_appearance_books_in_full(self):+ m, raw, sent = self._matured()+ assert m.replayed_token_debt(raw, sent, len) == 0++ def test_later_request_is_charged_even_without_a_replacement(self):+ # The second call passes the same forwarded form WITHOUT running+ # apply again: that is the cached-prefix replay, the path that+ # actually re-books the removal in production.+ m, raw, sent = self._matured()+ m.replayed_token_debt(raw, sent, len)+ expected = len(CONTENT) - len(self._marker(sent))+ assert m.replayed_token_debt(raw, sent, len) == expected++ def test_marker_echo_is_not_a_replay(self):+ # The client echoes the marker form back: nothing was removed this+ # request, so there is nothing to un-book.+ m, _, sent = self._matured()+ assert m.replayed_token_debt(sent, sent, len) == 0++ def test_unchanged_wire_form_is_not_a_replay(self):+ # Forwarded verbatim (maturation state lost, hold re-established):+ # no removal on the wire, no debt.+ m, raw, _ = self._matured()+ assert m.replayed_token_debt(raw, raw, len) == 0++ def test_delta_is_tokenized_once_per_tool_call(self):+ m, raw, sent = self._matured()+ m.replayed_token_debt(raw, sent, len)+ calls = []++ def count(text: str) -> int:+ calls.append(text)+ return len(text)++ expected = len(CONTENT) - len(self._marker(sent))+ assert m.replayed_token_debt(raw, sent, count) == expected+ assert len(calls) == 2 # content + marker, once+ assert m.replayed_token_debt(raw, sent, count) == expected+ assert len(calls) == 2 # cached for the session++ def test_replay_request_nets_zero_savings(self):+ # With a compositional counter the diff on a replay request equals+ # exactly the debt, so first-appearance accounting books nothing new.+ m, raw, sent = self._matured()+ m.replayed_token_debt(raw, sent, len)+ diff = len(CONTENT) - len(self._marker(sent))+ assert max(0, diff - m.replayed_token_debt(raw, sent, len)) == 0++ def test_nothing_matured_has_zero_debt(self):+ m = manager()+ res = m.apply(base_conv())+ assert m.replayed_token_debt(base_conv(), res.messages, len) == 0diff --git a/tests/test_read_maturation_handler_nobust.py b/tests/test_read_maturation_handler_nobust.pyindex 3f9231bd0..79c2029fb 100644--- a/tests/test_read_maturation_handler_nobust.py+++ b/tests/test_read_maturation_handler_nobust.py@@ -248,9 +248,15 @@ def test_verbatim_read_never_cache_written_before_maturation(monkeypatch):)-def _drive_session(config, n_turns: int, session_id: str) -> list[list[dict]]:+def _drive_session(+ config,+ n_turns: int,+ session_id: str,+ saved_out: list[int] | None = None,+) -> list[list[dict]]:"""Drive ``n_turns`` cumulative turns through the real handler with a mocked- upstream; return the forwarded message arrays per turn."""+ upstream; return the forwarded message arrays per turn. When ``saved_out``+ is given, each turn's emitted ``x-headroom-tokens-saved`` is appended to it."""app = create_app(config)forwarded: list[list[dict]] = []with TestClient(app) as client:@@ -303,6 +309,8 @@ def _drive_session(config, n_turns: int, session_id: str) -> list[list[dict]]:},)assert r.status_code == 200, f"turn {n}: {r.text[:300]}"+ if saved_out is not None:+ saved_out.append(int(r.headers.get("x-headroom-tokens-saved", 0)))finally:proxy._retry_request = original_retryreturn forwarded@@ -386,3 +394,47 @@ def test_read_maturation_env_cannot_bypass_stable_rollout(monkeypatch):assert cfg.read_maturation is Falseassert cfg.rollout is not Noneassert cfg.rollout.decision("read_maturation").reason.value == "blocked_by_channel"+++def test_replayed_marker_is_not_rebooked_in_the_emitted_savings(monkeypatch):+ """The savings a request EMITS must be first-appearance.++ Subtracting the replay debt inside the maturation block is not enough on+ its own: the handler recomputes ``tokens_saved`` from the plain+ original-vs-optimized diff twice more before the outcome is recorded (the+ pre-send hook recount and the consistency recount), and either one throws+ the adjustment away — so every replay turn re-books a removal that was+ already booked when the Read matured. Assert on the emitted header, which+ is the same figure the outcome and PERF line carry, not on the manager.+ """+ from headroom.cache.compression_store import reset_compression_store++ monkeypatch.setenv("HEADROOM_CCR_BACKEND", "memory")+ reset_compression_store()++ config = ProxyConfig(+ optimize=True,+ read_maturation=True,+ read_maturation_quiesce_turns=2,+ mode="token",+ cache_enabled=True,+ rate_limit_enabled=False,+ cost_tracking_enabled=False,+ log_requests=False,+ )+ saved: list[int] = []+ forwarded = _drive_session(config, n_turns=5, session_id="first-appearance-1", saved_out=saved)++ first = _first_matured_turn(forwarded)+ assert first is not None, "the Read never matured, so there is nothing to replay"+ replays = saved[first + 1 :]+ assert replays, "expected at least one replay turn after maturation"++ # The turn that matures the Read books its removal, once.+ assert saved[first] > 0, "the maturing turn booked nothing"+ # Later turns forward the same marker instead of the verbatim Read, so the+ # wire diff is just as large — but it is the SAME removal, already booked.+ assert max(replays) < saved[first] * 0.2, (+ f"replayed marker re-booked through the final accounting path: "+ f"matured turn saved {saved[first]}, replay turns saved {replays}"+ )