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(cache): partial cached-prefix replay + idle-aware net-cost; don't… (#1933)
Tejas Choprab0440f958dd5
diff --git a/headroom/cache/prefix_tracker.py b/headroom/cache/prefix_tracker.pyindex 09dc80b73..c30865395 100644--- a/headroom/cache/prefix_tracker.py+++ b/headroom/cache/prefix_tracker.py@@ -289,27 +289,66 @@ def overlay_cached_prefix(if not prev_orig or not prev_fwd:return optimized_messagesn = len(prev_orig)- # One forwarded message per original, and the frozen prefix must fit within- # both the current originals and this turn's optimized output.+ # Positional 1:1 correspondence between prev_orig[i] and prev_fwd[i] holds+ # only when last turn forwarded exactly one message per original (the+ # append-only, no-injection shape update_from_response records). If the+ # counts differ, an injected / dropped / merged message shifted the+ # mapping, so replaying prev_fwd[i] at position i could forward the wrong+ # content — bail (leave this turn's output untouched) rather than risk it.if len(prev_fwd) != n:+ logger.debug(+ "overlay: forwarded/original count mismatch (prev_fwd=%d, prev_orig=%d) "+ "— skipping cached-prefix replay (possible bust)",+ len(prev_fwd),+ n,+ )return optimized_messages- if len(current_original_messages) < n or len(optimized_messages) < n:- return optimized_messages- # Append-only guard on CONTENT ONLY: the frozen region must be the same- # messages we cached. Compare with the shared canonicalizer (not just- # cache_control-stripping) so the guard is robust to ALL per-turn transport /- # annotation churn — cache_control movement (Anthropic), litellm `caller`,+ # Append-only guard on CONTENT ONLY, message-by-message. Replay the+ # previously-forwarded (cached, compressed) bytes for the longest LEADING+ # run of messages that is byte-for-byte (content-canonical) identical to+ # what we forwarded last turn, and stop at the first divergence.+ #+ # This is the cache-safety centerpiece for token mode (which relies solely+ # on this replay; cache mode is already byte-stable by construction). The+ # prior all-or-nothing guard busted the ENTIRE cached prefix the moment any+ # single leading message failed to canonicalize-equal last turn — most+ # commonly the just-added assistant turn, whose client-resent form can+ # differ trivially from the copy we reconstructed and recorded. Stopping at+ # the first divergence instead keeps the (much larger) cache-hit region+ # up to that point and only re-forwards from the changed message onward.+ #+ # Comparison uses the shared canonicalizer (not just cache_control+ # stripping) so it is robust to ALL per-turn transport / annotation churn —+ # cache_control movement (Anthropic), litellm `caller`,# provider_specific_fields, streaming `index`, string<->block content shape,- # etc. — across providers/clients. Content stability is what the provider's- # prefix cache actually keys on; a coarser cache_control-only strip let other- # clients' noise spuriously fail the guard, skip the replay, and bust. This- # helps every handler that shares overlay_cached_prefix (Anthropic + OpenAI).- if _canonicalize_for_prefix_compare(- current_original_messages[:n]- ) != _canonicalize_for_prefix_compare(prev_orig):+ # etc. Content stability is what the provider's prefix cache actually keys+ # on. Safe by construction: we only replay prev_fwd[k] where+ # current_original[k] canonicalize-equals prev_orig[k], and prev_fwd[k]+ # positionally corresponds to prev_orig[k] (guaranteed by the count check+ # above), so no wrong bytes are ever forwarded.+ limit = min(n, len(current_original_messages), len(optimized_messages))+ k = 0+ while k < limit and _canonicalize_for_prefix_compare(+ current_original_messages[k]+ ) == _canonicalize_for_prefix_compare(prev_orig[k]):+ k += 1+ if k == 0:+ logger.debug(+ "overlay: prefix diverged at message 0 — no cached-prefix replay "+ "(cold prefix or client rewrote history head)"+ )return optimized_messages- # Replay the cached (compressed) prefix byte-identical; keep this turn's tail.- return list(prev_fwd) + list(optimized_messages[n:])+ if k < n:+ logger.debug(+ "overlay: cached-prefix replay for %d/%d leading messages "+ "(diverged at %d — re-forwarding tail fresh)",+ k,+ n,+ k,+ )+ # Replay the cached (compressed) prefix byte-identical up to the first+ # divergence; keep this turn's freshly-produced output for the rest.+ return list(prev_fwd[:k]) + list(optimized_messages[k:])def normalize_message_cache_control(@@ -390,6 +429,13 @@ class PrefixCacheTracker:self._last_activity: float = time.time()self._last_original_messages: list[dict[str, Any]] = []self._last_forwarded_messages: list[dict[str, Any]] = []+ # Idle gap (seconds) since the PREVIOUS turn's response, captured by+ # SessionTrackerStore.get_or_create at fetch time — BEFORE it refreshes+ # _last_activity. Without this snapshot, seconds_since_activity() reads+ # ~0 on every request (the fetch itself bumps the clock), so the+ # net-cost/TTL P_alive gate could never see idle time. The handler reads+ # this and forwards it to the pipeline as `idle_seconds`.+ self._idle_seconds_at_fetch: float = 0.0# Session-scoped ReadMaturationManager (Mechanism B), created# lazily by the handler when read maturation is enabled. Rides@@ -737,10 +783,15 @@ class SessionTrackerStore:if session_id in self._trackers:tracker = self._trackers[session_id]+ # Snapshot idle-since-last-response BEFORE bumping the access clock,+ # so the net-cost/TTL gate sees the true gap (see the attribute's+ # docstring in PrefixCacheTracker.__init__).+ tracker._idle_seconds_at_fetch = max(0.0, time.time() - tracker._last_activity)tracker._last_activity = time.time()return trackertracker = PrefixCacheTracker(provider, self._default_config)+ tracker._idle_seconds_at_fetch = 0.0 # cold start: nothing cached to lapseself._trackers[session_id] = trackerreturn trackerdiff --git a/headroom/proxy/handlers/anthropic.py b/headroom/proxy/handlers/anthropic.pyindex 600a55727..a6b0f5fb4 100644--- a/headroom/proxy/handlers/anthropic.py+++ b/headroom/proxy/handlers/anthropic.py@@ -1052,6 +1052,14 @@ class AnthropicHandlerMixin:session_id = self.session_tracker_store.compute_session_id(request, model, messages)prefix_tracker = self.session_tracker_store.get_or_create(session_id, "anthropic")frozen_message_count = prefix_tracker.get_frozen_message_count()+ # Idle gap since the previous turn's response, snapshotted at fetch+ # (before get_or_create bumped the access clock). Forwarded to the+ # pipeline so the net-cost/TTL gate (HEADROOM_NET_COST_POLICY=1) can+ # decay P_alive as the ~300s prompt-cache lapse nears and admit+ # otherwise-frozen compaction as a free rewrite. Harmless when the+ # policy is off (router ignores idle_seconds unless enabled) and near+ # 0 for back-to-back agent turns (cache still warm → no decay).+ idle_seconds = getattr(prefix_tracker, "_idle_seconds_at_fetch", 0.0)if is_cache_mode(self.config.mode):frozen_message_count = self._strict_previous_turn_frozen_count(original_client_messages,@@ -1273,6 +1281,7 @@ class AnthropicHandlerMixin:model_limit=context_limit,context=extract_user_query(working_messages),frozen_message_count=frozen_message_count,+ idle_seconds=idle_seconds,biases=biases,request_id=request_id,compression_policy=compression_policy,@@ -1302,6 +1311,7 @@ class AnthropicHandlerMixin:model_limit=context_limit,context=extract_user_query(working_messages),frozen_message_count=frozen_message_count,+ idle_seconds=idle_seconds,biases=biases,request_id=request_id,compression_policy=compression_policy,@@ -1435,6 +1445,7 @@ class AnthropicHandlerMixin:model_limit=context_limit,context=extract_user_query(compression_input),frozen_message_count=prefix_n,+ idle_seconds=idle_seconds,biases=biases,request_id=request_id,compression_policy=compression_policy,@@ -1493,7 +1504,8 @@ class AnthropicHandlerMixin:prefix_tracker.get_last_original_messages(),prefix_tracker.get_last_forwarded_messages(),)- if _ov != optimized_messages:+ _overlay_replayed = _ov != optimized_messages+ if _overlay_replayed:optimized_messages = _ovoptimized_tokens = tokenizer.count_messages(optimized_messages)@@ -1509,7 +1521,18 @@ class AnthropicHandlerMixin:# Guard: if "optimization" inflated tokens, revert to originals.# Skip in cache mode where prefix-stability may legitimately shift counts.- if optimized_tokens > original_tokens and not is_cache_mode(self.config.mode):+ # ALSO skip when overlay_cached_prefix just replayed a byte-identical+ # cached prefix (token mode): reverting to the raw originals there+ # would re-forward the uncompressed prefix and BUST the live prompt+ # cache — trading a 90% read discount for a full re-write — which is+ # far more expensive than the small tail inflation this guard exists+ # to avoid. The nominal "inflation" is also an artifact of comparing+ # the cached (compressed) forwarding against the raw original count.+ if (+ optimized_tokens > original_tokens+ and not is_cache_mode(self.config.mode)+ and not _overlay_replayed+ ):logger.warning(f"[{request_id}] Optimization inflated tokens "f"({original_tokens} -> {optimized_tokens}), reverting to original messages"