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(content_router): pin FREEZE_BLOCK_DECISION verdict to stop cache-write churn (#1620)
Rocker Zhanga06997946601
diff --git a/headroom/transforms/content_router.py b/headroom/transforms/content_router.pyindex ab8e9e273..64d34444f 100644--- a/headroom/transforms/content_router.py+++ b/headroom/transforms/content_router.py@@ -800,6 +800,10 @@ class CompressionCache:self._results: dict[int, tuple[str, float, str, float]] = {}# Tier 1: hashes of content that won't compress {hash: timestamp}self._skip: dict[int, float] = {}+ # Callbacks invoked (outside the lock) whenever ``clear()`` runs, so+ # sibling state keyed by the same content hashes (e.g. the router's+ # frozen-verdict store) can be reset in lock-step with the cache.+ self._on_clear: list[Any] = []self._ttl_seconds = ttl_seconds# Metricsself._hits = 0@@ -888,11 +892,23 @@ class CompressionCache:"cache_avg_lookup_ns": avg_ns,}+ def register_on_clear(self, callback: Any) -> None:+ """Register a callback fired (outside the lock) on every ``clear()``.++ Lets state keyed by the same content hashes — e.g. the router's+ ``_frozen_verdicts`` store — be reset together with the cache so it+ cannot outlive the results/skip tiers it shadows.+ """+ self._on_clear.append(callback)+def clear(self) -> None:"""Clear all entries (e.g., on session end). Thread-safe."""with self._lock:self._results.clear()self._skip.clear()+ # Fire callbacks outside the lock to avoid cross-lock ordering issues.+ for callback in self._on_clear:+ callback()class CompressionStrategy(Enum):@@ -1386,6 +1402,136 @@ class ContentRouter(Transform):self._cache = CompressionCache()+ # Cache-churn fix (HEADROOM_FREEZE_BLOCK_DECISION, default off):+ # freeze each block's compress-vs-passthrough verdict on first+ # sighting so it stops depending on the per-turn ``min_ratio`` drift.+ # Keyed by the same ``content_key`` as ``_cache``; value True =+ # "compress", False = "skip". Only populated when the flag is on.+ #+ # Bounding: this store shadows ``_cache`` entries, so left unbounded it+ # would leak verdicts whose cache entries have long since expired. It is+ # (a) cleared in lock-step with the cache via ``register_on_clear`` and+ # (b) capped at ``_frozen_verdicts_max`` with simple insertion-order+ # (FIFO) eviction, mirroring the cache's bounded posture.+ #+ # Locking: ``CompressionCache`` guards every mutation with a lock and+ # the parallel compression pass writes verdicts from worker threads, so+ # we match that posture with a dedicated lock rather than relying on+ # GIL atomicity (which would not protect the read-then-evict sequence).+ self._frozen_verdicts: dict[int, bool] = {}+ self._frozen_verdicts_max = 4096+ self._frozen_lock = threading.Lock()+ # Reset verdicts whenever the shadowed cache is cleared.+ self._cache.register_on_clear(self._clear_frozen_verdicts)+ # Instrumentation for the freeze (HEADROOM_FREEZE_BLOCK_DECISION): a+ # "pin" is a turn where the frozen compress verdict overrode a tightened+ # per-turn ``min_ratio`` that would otherwise downgrade the block to+ # skip — i.e. revert it to original text and bust the provider prefix+ # cache. Counting pins isolates the freeze's attributable payoff.+ self._freeze_pin_hits = 0+ self._freeze_pin_chars = 0++ def _record_freeze_pin(self, content: str, cached_ratio: float) -> None:+ """Count one freeze divergence (thread-safe) and log it.++ Fires only when the frozen "compress" verdict overrode a tightened+ per-turn ``min_ratio`` that would have downgraded the block to skip (a+ provider cache bust). ``preserved`` is a char-based proxy for the+ compression saving kept alive by not reverting to the original.+ """+ preserved = max(0, int(len(content) * (1.0 - cached_ratio)))+ with self._frozen_lock:+ self._freeze_pin_hits += 1+ self._freeze_pin_chars += preserved+ hits = self._freeze_pin_hits+ logger.info(+ f"FREEZE-PIN: pins={hits} cached_ratio={cached_ratio:.3f} "+ f"preserved_chars~={preserved} (cache bust avoided)"+ )++ def _record_frozen_verdict(self, content_key: int, verdict: bool) -> None:+ """Record a frozen verdict (thread-safe, bounded FIFO eviction).++ Caps the store at ``_frozen_verdicts_max`` entries, evicting the+ oldest insertion when full, so it cannot grow without bound across a+ long-lived process. Mirrors ``CompressionCache``'s locked mutations.+ """+ with self._frozen_lock:+ if (+ content_key not in self._frozen_verdicts+ and len(self._frozen_verdicts) >= self._frozen_verdicts_max+ ):+ # Evict oldest insertion (dicts preserve insertion order).+ oldest = next(iter(self._frozen_verdicts))+ del self._frozen_verdicts[oldest]+ self._frozen_verdicts[content_key] = verdict++ def _get_frozen_verdict(self, content_key: int) -> bool | None:+ """Read a frozen verdict (thread-safe). Returns None if absent."""+ with self._frozen_lock:+ return self._frozen_verdicts.get(content_key)++ def _frozen_verdict_recoverable(self, strategy: object, compressed: str | None) -> bool:+ """Whether a "compress" verdict is safe to freeze under the #1307 rule.++ A lossy-unmarked strategy that emitted no CCR retrieval marker is+ unrecoverable, so pinning it across turns would keep serving a+ fabricated summary the agent can't restore. Refuse to freeze those;+ recoverable (marked or non-lossy) compressions may be pinned.++ ``strategy`` is a ``CompressionStrategy`` on the fresh-compress path but+ its ``.value`` string on the cache-hit path, so compare by value.+ """+ value = getattr(strategy, "value", strategy)+ lossy_values = {getattr(s, "value", s) for s in self.LOSSY_UNMARKED_STRATEGIES}+ if value in lossy_values and not CCR_RETRIEVAL_MARKER_RE.search(compressed or ""):+ return False+ return True++ def _clear_frozen_verdicts(self) -> None:+ """Drop all frozen verdicts (thread-safe). Fired on cache clear."""+ with self._frozen_lock:+ self._frozen_verdicts.clear()++ def _freeze_block_decision_enabled(self) -> bool:+ """Whether the per-block verdict freeze is active (default off).++ Reads ``HEADROOM_FREEZE_BLOCK_DECISION`` each call so it can be+ toggled per-process without restart in tests. Default off → the+ verdict store is never touched and behaviour is byte-identical.+ """+ return os.environ.get("HEADROOM_FREEZE_BLOCK_DECISION", "").strip().lower() in {+ "1",+ "true",+ "yes",+ "on",+ }++ def _kompress_model_ready(self) -> bool:+ """Whether the ML compressor is ready (or deliberately disabled).++ Caveat (1): a block that fails to compress *only* because ModernBERT+ is still lazy-loading must NOT have its "skip" verdict frozen — it has+ to be re-evaluated once the model is ready. When kompress is disabled+ or unavailable there is no deferred model, so "skip" is a real verdict+ and may be frozen.+ """+ if not self.config.enable_kompress:+ return True+ if getattr(self, "_runtime_kompress_model", None) == "disabled":+ return True+ try:+ compressor = self._get_kompress()+ except Exception:+ return True+ if compressor is None:+ # No ML compressor available at all — not a deferred load.+ return True+ try:+ return bool(compressor.is_ready())+ except Exception:+ return True+def _record_to_toin(self,strategy: CompressionStrategy,@@ -3433,6 +3579,27 @@ class ContentRouter(Transform):min(self.config.min_ratio_relaxed, min_ratio),)+ # Cache-churn fix: when frozen-decision mode is on, accept/skip+ # decisions use the SAME live ``min_ratio`` gate as flag-off, but once a+ # block is accepted-and-compressed its "compress" verdict is pinned+ # (accept_threshold=1.0) on every later turn. So when rising pressure+ # tightens ``min_ratio`` below the block's ratio — the turn the legacy+ # path would ``move_to_skip`` and bust the provider prefix cache — the+ # pin keeps it compressed instead. This is a pure pin: it preserves a+ # decision the live gate already made; it never loosens the first-sight+ # gate (which would be a silent ratio bet).+ #+ # (Earlier this used a FIXED ``frozen_threshold`` == the ``min_ratio``+ # aggressive floor (0.65), which made the pin dead code — a block only+ # froze when ``cached_ratio < 0.65 <= min_ratio``, one the legacy gate+ # accepts anyway, so the pin never changed an outcome and the flag only+ # suppressed borderline compression. Verified inert by A/B 2026-06-21.)+ #+ # Default off ⇒ the pin branch is never taken and the legacy+ # ``min_ratio`` path is byte-for-byte untouched.+ freeze_decision = self._freeze_block_decision_enabled()+ model_ready = self._kompress_model_ready() if freeze_decision else True+if context_pressure > 0.3:logger.debug("content_router adaptive: pressure=%.2f, min_ratio=%.2f, "@@ -3772,8 +3939,25 @@ class ContentRouter(Transform):cached = self._cache.get(content_key)if cached is not None:cached_compressed, cached_ratio, cached_strategy = cached- # Re-check ratio against current min_ratio (shifts with context pressure)- if cached_ratio < min_ratio:+ # Cache-churn fix: if a verdict was frozen for this block on a+ # prior turn, REUSE it and bypass the per-turn ``min_ratio``+ # re-check + ``move_to_skip`` downgrade. The frozen verdict is+ # only ever "compress" here (a "skip" verdict never warms the+ # result cache), so this just pins the accept decision against+ # ratio drift.+ frozen_compress = freeze_decision and self._get_frozen_verdict(content_key) is True+ if frozen_compress:+ # Pin: a frozen "compress" verdict always re-accepts,+ # overriding the per-turn min_ratio re-check below.+ accept_threshold = 1.0+ else:+ # Pre-freeze / unfrozen: identical to the legacy gate. The+ # freeze only PINS past accepts; it never loosens the+ # first-sighting decision (that would be a silent ratio bet).+ accept_threshold = min_ratio+ # Re-check ratio against the active threshold (shifts with+ # context pressure unless pinned by a frozen verdict).+ if cached_ratio < accept_threshold:if netcost_enabled and not self._net_cost_allows(slot_idx=i,original_tokens=tokenizer.count_text(content),@@ -3791,12 +3975,24 @@ class ContentRouter(Transform):result_slots[i] = {**message, "content": cached_compressed}transforms_applied.append(f"router:{cached_strategy}:{cached_ratio:.2f}")compressed_details.append(f"{cached_strategy}:{cached_ratio:.2f}")+ # Freeze the "compress" verdict so future turns skip the+ # min_ratio re-check above and never downgrade it.+ if freeze_decision:+ self._record_frozen_verdict(content_key, True)+ # Pin attribution: count a bust avoided only when the+ # block actually stayed compressed (past the net-cost+ # gate) AND the frozen verdict overrode a tightened+ # min_ratio that flag-off would have moved to skip.+ if frozen_compress and cached_ratio >= min_ratio:+ self._record_freeze_pin(content, cached_ratio)if i in frozen_unlock_slots:transforms_applied.append("router:netcost_frozen_unlock")route_counts.setdefault("netcost_frozen_unlocked", 0)route_counts["netcost_frozen_unlocked"] += 1else:# Threshold tightened — no longer qualifies. Move to skip.+ # (Unreachable when the verdict is frozen-compress: the+ # accept_threshold is pinned to 1.0 above.)self._cache.move_to_skip(content_key)result_slots[i] = messageroute_counts["ratio_too_high"] += 1@@ -3935,6 +4131,10 @@ class ContentRouter(Transform):accept_ratio,result.strategy_used.value,)+ # Freeze "compress" so the cache-hit path above never+ # re-applies a tighter min_ratio to this block.+ if freeze_decision:+ self._record_frozen_verdict(content_key, True)if netcost_enabled and not self._net_cost_allows(slot_idx=slot_idx,original_tokens=tokenizer.count_text(task_content),@@ -3961,6 +4161,13 @@ class ContentRouter(Transform):self._cache.mark_skip(content_key)result_slots[slot_idx] = messageroute_counts["ratio_too_high"] += 1+ # Caveat (1): only freeze a "skip" verdict when the ML model+ # is actually ready. A passthrough caused purely by a still-+ # loading ModernBERT must stay re-evaluable on later turns,+ # so we do NOT freeze it here (the byte-result skip cache+ # entry can still expire/refresh per the existing TTL).+ if freeze_decision and model_ready:+ self._record_frozen_verdict(content_key, False)# Build final message list from slotstransformed_messages = [m for m in result_slots if m is not None]@@ -4717,6 +4924,21 @@ class ContentRouter(Transform):``True`` the caller should update the block with the returnedcontent and set ``any_compressed``."""+ # Cache-churn fix (HEADROOM_FREEZE_BLOCK_DECISION, default off):+ # mirror the plain-STRING path's per-block verdict freeze here, because+ # for Claude Code / Anthropic traffic the prefix is dominated by+ # ``tool_result`` content-blocks that flow through this helper. This is a+ # pure pin: accept/skip uses the SAME live ``min_ratio`` gate as+ # flag-off, and an accepted "compress" verdict is recorded in+ # ``_frozen_verdicts`` and pinned on later turns so rising context+ # pressure can no longer downgrade it (which would churn the prefix+ # cache). The freeze never loosens the first-sighting decision. See the+ # STRING-path note above for why the old fixed aggressive threshold+ # (0.65) made the pin dead code. Default off ⇒ legacy ``min_ratio``+ # behaviour, byte-identical.+ freeze_decision = self._freeze_block_decision_enabled()+ model_ready = self._kompress_model_ready() if freeze_decision else True+# In lossless-only mode a "skip" means no byte-lossless fold exists for# this block (e.g. source code) — it is left verbatim, which is NOT a# rejected compression. Bucket it honestly so it doesn't masquerade as@@ -4736,14 +4958,38 @@ class ContentRouter(Transform):cached_compressed, cached_ratio, cached_strategy = cachedif route_counts is not None:route_counts["cache_hit"] = route_counts.get("cache_hit", 0) + 1- if cached_ratio < min_ratio:+ # If a "compress" verdict was frozen for this block, REUSE it and+ # bypass the per-turn ``min_ratio`` re-check + ``move_to_skip``+ # downgrade (the frozen verdict here is only ever "compress": a+ # "skip" verdict never warms the result cache).+ if freeze_decision and self._get_frozen_verdict(content_key) is True:+ accept_threshold = 1.0 # already-decided: always accept+ if cached_ratio >= min_ratio:+ # Counterfactual: legacy min_ratio re-check would downgrade+ # this block (move_to_skip → original restored → prefix+ # cache bust). The frozen verdict prevented it. The block+ # path has no net-cost veto, so an accepted frozen block+ # always stays compressed — this pin count is exact.+ self._record_freeze_pin(content, cached_ratio)+ else:+ # Pre-freeze / unfrozen: same live gate as flag-off (pure pin).+ accept_threshold = min_ratio+ if cached_ratio < accept_threshold:transforms_applied.append(f"router:{strategy_label}:{cached_strategy}")if compressed_details is not None:compressed_details.append(f"{details_prefix}:{cached_strategy}:{cached_ratio:.2f}")+ # Freeze the "compress" verdict so future turns skip the+ # min_ratio re-check above and never downgrade it.+ if freeze_decision and self._frozen_verdict_recoverable(+ cached_strategy, cached_compressed+ ):+ self._record_frozen_verdict(content_key, True)return cached_compressed, True- # Threshold tightened — move result to skip set+ # Threshold tightened — move result to skip set.+ # (Unreachable when the verdict is frozen-compress: the+ # accept_threshold is pinned to 1.0 above.)self._cache.move_to_skip(content_key)if route_counts is not None:route_counts["ratio_too_high"] = route_counts.get("ratio_too_high", 0) + 1@@ -4789,6 +5035,8 @@ class ContentRouter(Transform):if route_counts is not None:_bucket = "lossless_accept" if _is_pure_lossless else "lossless_then_lossy_accept"route_counts[_bucket] = route_counts.get(_bucket, 0) + 1+ if freeze_decision and self._frozen_verdict_recoverable(_ll_label, result.compressed):+ self._record_frozen_verdict(content_key, True)return result.compressed, Trueif result.compression_ratio < min_ratio:# Tool ground truth must stay reversible: a lossy summarizer@@ -4823,6 +5071,12 @@ class ContentRouter(Transform):result.compression_ratio,result.strategy_used.value,)+ # Freeze "compress" so the cache-hit path above never re-applies a+ # tighter min_ratio to this block.+ if freeze_decision and self._frozen_verdict_recoverable(+ result.strategy_used, result.compressed+ ):+ self._record_frozen_verdict(content_key, True)transforms_applied.append(f"router:{strategy_label}:{result.strategy_used.value}")if compressed_details is not None:compressed_details.append(@@ -4835,6 +5089,11 @@ class ContentRouter(Transform):self._cache.mark_skip(content_key)if route_counts is not None:route_counts[_noop_bucket] = route_counts.get(_noop_bucket, 0) + 1+ # Caveat (1): only freeze a "skip" verdict when the ML model is actually+ # ready. A passthrough caused purely by a still-loading ModernBERT must+ # stay re-evaluable on later turns, so we do NOT freeze it here.+ if freeze_decision and model_ready:+ self._record_frozen_verdict(content_key, False)return None, Falsedef _detect_analysis_intent(self, messages: list[dict[str, Any]]) -> bool:diff --git a/tests/test_transforms_content_router.py b/tests/test_transforms_content_router.pyindex fe5bf58ec..8dc439acd 100644--- a/tests/test_transforms_content_router.py+++ b/tests/test_transforms_content_router.py@@ -881,6 +881,391 @@ def test_detect_content_python_backend_skips_native(assert result.content_type is ContentType.JSON_ARRAY+# ---------------------------------------------------------------------------+# Cache-churn fix: HEADROOM_FREEZE_BLOCK_DECISION (default off).+#+# Root cause: ``min_ratio`` drifts every turn with context pressure, so a+# block whose compression ratio sits in [aggressive, relaxed) is compressed+# on a low-pressure turn and downgraded to passthrough on a high-pressure+# turn (or vice-versa). The block's prefix bytes flap across turns ⇒+# cache_write churn. The fix freezes the per-block compress/passthrough+# verdict on first sighting against the FIXED aggressive threshold.+# ---------------------------------------------------------------------------+++class _ChurnTokenizer:+ """Word-count tokenizer; apply() only calls ``count_text``."""++ def count_text(self, text: str) -> int:+ return len(str(text).split())+++def _churn_router(monkeypatch: pytest.MonkeyPatch, ratio: float) -> ContentRouter:+ """Router whose compress() always emits a deterministic payload at a+ fixed ratio. ``min_chars`` thresholds are relaxed so a 200-word tool+ message reaches the compression path."""+ cfg = ContentRouterConfig(min_ratio_relaxed=0.85, min_ratio_aggressive=0.65)+ router = ContentRouter(cfg)++ def fake_compress(content, context: str = "", bias: float = 1.0):+ return SimpleNamespace(+ # CCR marker keeps the compression recoverable so the #1307+ # tool-reversibility guard preserves it instead of restoring original.+ compressed="[C]" + content[:20] + " <<ccr:t>>",+ compression_ratio=ratio,+ strategy_used=CompressionStrategy.TEXT,+ )++ monkeypatch.setattr(router, "compress", fake_compress)+ # Don't let lazy ML model state interfere with the model_ready signal.+ monkeypatch.setattr(router, "_kompress_model_ready", lambda: True)+ return router+++def _run_turn(router: ContentRouter, content: str, tokens_before: int):+ """Drive apply() for a single message with a rising context-pressure+ knob. model_limit fixed at 1000 so larger tokens_before ⇒ higher+ pressure ⇒ tighter min_ratio."""+ messages = [{"role": "tool", "tool_call_id": "t1", "content": content}]+ result = router.apply(+ messages,+ _ChurnTokenizer(),+ model_limit=1000,+ # Force a known tokens_before by padding nothing — apply recomputes+ # tokens_before from the messages, so we instead steer pressure via+ # model_limit below. (kept for clarity)+ )+ return result.messages[0]["content"]+++def _content_of_n_words(n: int) -> str:+ return " ".join(f"w{i}" for i in range(n))+++def test_freeze_off_is_byte_identical_flapping_baseline(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """(b) Flag OFF (default): a mid-zone block (ratio 0.75) flaps —+ compressed on a low-pressure turn, downgraded to passthrough once+ pressure tightens min_ratio below the ratio. This is the legacy churn+ and must be preserved byte-for-byte when the flag is off."""+ monkeypatch.delenv("HEADROOM_FREEZE_BLOCK_DECISION", raising=False)+ router = _churn_router(monkeypatch, ratio=0.75)+ content = _content_of_n_words(200)++ # Turn 1: low pressure (small model_limit denom via large limit) ->+ # min_ratio ~ relaxed (0.85). 0.75 < 0.85 -> compresses.+ low = router.apply(+ [{"role": "tool", "tool_call_id": "t1", "content": content}],+ _ChurnTokenizer(),+ model_limit=100000, # pressure ~ 0 -> min_ratio ~ 0.85+ ).messages[0]["content"]+ assert low.startswith("[C]"), "turn1 should compress at low pressure"++ # Turn 2: high pressure -> min_ratio ~ aggressive (0.65). 0.75 < 0.65+ # is False -> cache-hit path downgrades via move_to_skip -> passthrough.+ high = router.apply(+ [{"role": "tool", "tool_call_id": "t1", "content": content}],+ _ChurnTokenizer(),+ model_limit=100, # 200 words >> 100 -> pressure 1.0 -> min_ratio 0.65+ ).messages[0]["content"]+ assert high == content, "turn2 should flip to passthrough (legacy churn)"+ # The flap: bytes changed across turns.+ assert low != high+++def test_freeze_on_pins_compress_verdict_across_turns(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """(a) Flag ON: a block that compresses on first sighting keeps the SAME+ verdict AND the SAME bytes on later turns despite rising pressure /+ drifting min_ratio. Use ratio 0.6 (< aggressive 0.65) so it compresses+ under the frozen threshold."""+ monkeypatch.setenv("HEADROOM_FREEZE_BLOCK_DECISION", "1")+ router = _churn_router(monkeypatch, ratio=0.60)+ content = _content_of_n_words(200)++ outs = []+ # Rising pressure across turns: model_limit shrinks -> min_ratio drifts+ # from ~0.85 down to ~0.65. Without freeze this is the flap zone.+ for limit in (100000, 1000, 300, 100):+ out = router.apply(+ [{"role": "tool", "tool_call_id": "t1", "content": content}],+ _ChurnTokenizer(),+ model_limit=limit,+ ).messages[0]["content"]+ outs.append(out)++ assert all(o.startswith("[C]") for o in outs), "verdict must stay compress"+ assert len(set(outs)) == 1, "bytes must be identical across all turns"+++def test_freeze_on_pins_passthrough_verdict_across_turns(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """(a) Flag ON, mid-zone block (ratio 0.75): the RELAXED first-sighting+ threshold (0.85) compresses it on turn 1 (low pressure), freezes the+ compress verdict, and PINS it compressed on every later turn — even as+ rising pressure pulls ``min_ratio`` below 0.75, where the flag-off path+ would ``move_to_skip`` and bust the prefix cache. So the bytes stay+ compressed and identical, and the freeze-pin counter records the+ busts it avoided. (Contrast with the flag-off flapping baseline.)"""+ monkeypatch.setenv("HEADROOM_FREEZE_BLOCK_DECISION", "1")+ router = _churn_router(monkeypatch, ratio=0.75)+ content = _content_of_n_words(200)++ outs = []+ for limit in (100000, 1000, 300, 100):+ out = router.apply(+ [{"role": "tool", "tool_call_id": "t1", "content": content}],+ _ChurnTokenizer(),+ model_limit=limit,+ ).messages[0]["content"]+ outs.append(out)++ assert all(o.startswith("[C]") for o in outs), "verdict must stay compressed"+ assert len(set(outs)) == 1, "bytes identical (always compressed) across turns"+ assert router._freeze_pin_hits > 0, "freeze must pin compress over a tightening min_ratio"+++def test_model_not_ready_passthrough_is_not_frozen(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Caveat (1): a block that passes through ONLY because the ML model is+ not ready must NOT have its skip verdict frozen — once the model is+ ready it must be re-evaluated. We simulate not-ready (compress returns+ the content unchanged at ratio 1.0) then ready (real compression)."""+ monkeypatch.setenv("HEADROOM_FREEZE_BLOCK_DECISION", "1")+ cfg = ContentRouterConfig()+ router = ContentRouter(cfg)+ content = _content_of_n_words(200)++ # Phase 1: model NOT ready. _try_ml_compressor returns content unchanged+ # -> ratio 1.0 (passthrough). Verdict must NOT be frozen as skip.+ monkeypatch.setattr(router, "_kompress_model_ready", lambda: False)+ monkeypatch.setattr(+ router,+ "compress",+ lambda c, context="", bias=1.0: SimpleNamespace(+ compressed=c, compression_ratio=1.0, strategy_used=CompressionStrategy.TEXT+ ),+ )+ out1 = router.apply(+ [{"role": "tool", "tool_call_id": "t1", "content": content}],+ _ChurnTokenizer(),+ model_limit=1000,+ ).messages[0]["content"]+ assert out1 == content, "not-ready -> passthrough"+ # The verdict store must NOT contain a frozen skip for this block.+ assert all(v is True for v in router._frozen_verdicts.values()) or (+ not router._frozen_verdicts+ ), "not-ready passthrough must not be frozen as skip"++ # Phase 2: model now ready, real compression below the aggressive+ # threshold. Because the verdict was never frozen, the block must now be+ # re-evaluated and compress (not stuck on a frozen passthrough). Note:+ # the legacy byte skip-cache is keyed on the same content; we clear it to+ # isolate the verdict behaviour (the freeze fix governs the verdict, not+ # the existing TTL byte cache).+ router._cache.clear()+ monkeypatch.setattr(router, "_kompress_model_ready", lambda: True)+ monkeypatch.setattr(+ router,+ "compress",+ lambda c, context="", bias=1.0: SimpleNamespace(+ compressed="[C]"+ + c[:20]+ + " <<ccr:t>>", # recoverable marker so #1307 tool-reversibility guard keeps the compression+ compression_ratio=0.50,+ strategy_used=CompressionStrategy.TEXT,+ ),+ )+ out2 = router.apply(+ [{"role": "tool", "tool_call_id": "t1", "content": content}],+ _ChurnTokenizer(),+ model_limit=1000,+ ).messages[0]["content"]+ assert out2.startswith("[C]"), "once model ready the block must compress"+++# ---------------------------------------------------------------------------+# Cache-churn fix — CONTENT-BLOCK path (tool_result blocks).+#+# For Claude Code / Anthropic traffic the prefix is dominated by tool_result+# content-blocks routed through ``_compress_block_content``, not plain-string+# messages. These tests mirror the string-path freeze tests above for that+# dominant path.+# ---------------------------------------------------------------------------+++def _tool_result_block_msg(content: str) -> dict:+ """A user message carrying a single ``tool_result`` content-block — the+ Anthropic shape that dominates Claude Code prefixes."""+ return {+ "role": "user",+ "content": [+ {"type": "tool_result", "tool_use_id": "tu1", "content": content},+ ],+ }+++def _block_out(router: ContentRouter, content: str, model_limit: int) -> str:+ """Run apply() for a tool_result content-block and return the (possibly+ compressed) string content of that block."""+ result = router.apply(+ [_tool_result_block_msg(content)],+ _ChurnTokenizer(),+ model_limit=model_limit,+ )+ return result.messages[0]["content"][0]["content"]+++def test_block_freeze_off_is_byte_identical_flapping_baseline(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """(b) Block path, flag OFF (default): a mid-zone tool_result block+ (ratio 0.75) flaps — compressed at low pressure, downgraded to passthrough+ once pressure tightens min_ratio below the ratio. Legacy churn preserved."""+ monkeypatch.delenv("HEADROOM_FREEZE_BLOCK_DECISION", raising=False)+ router = _churn_router(monkeypatch, ratio=0.75)+ content = _content_of_n_words(200)++ low = _block_out(router, content, model_limit=100000)+ assert low.startswith("[C]"), "turn1 should compress at low pressure"++ high = _block_out(router, content, model_limit=100)+ assert high == content, "turn2 should flip to passthrough (legacy churn)"+ assert low != high, "flag-off block path must keep flapping (byte change)"+++def test_block_freeze_on_pins_compress_verdict_across_turns(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """(a) Block path, flag ON: a tool_result block that compresses on first+ sighting keeps the SAME verdict AND SAME bytes across rising-pressure+ turns despite drifting min_ratio. ratio 0.6 < aggressive 0.65."""+ monkeypatch.setenv("HEADROOM_FREEZE_BLOCK_DECISION", "1")+ router = _churn_router(monkeypatch, ratio=0.60)+ content = _content_of_n_words(200)++ outs = [_block_out(router, content, model_limit=limit) for limit in (100000, 1000, 300, 100)]+ assert all(o.startswith("[C]") for o in outs), "verdict must stay compress"+ assert len(set(outs)) == 1, "block bytes must be identical across all turns"+++def test_block_freeze_on_pins_passthrough_verdict_across_turns(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """(a) Block path, flag ON, mid-zone block (ratio 0.75): the RELAXED+ first-sighting threshold (0.85) compresses it on turn 1, freezes the+ compress verdict, and pins it compressed on every later turn even as+ rising pressure pulls min_ratio below 0.75 (where flag-off would+ move_to_skip). Bytes stay compressed/identical and pins are recorded."""+ monkeypatch.setenv("HEADROOM_FREEZE_BLOCK_DECISION", "1")+ router = _churn_router(monkeypatch, ratio=0.75)+ content = _content_of_n_words(200)++ outs = [_block_out(router, content, model_limit=limit) for limit in (100000, 1000, 300, 100)]+ assert all(o.startswith("[C]") for o in outs), "verdict must stay compressed"+ assert len(set(outs)) == 1, "block bytes identical (compressed) across turns"+ assert router._freeze_pin_hits > 0, "freeze must pin compress over a tightening min_ratio"+++def test_block_model_not_ready_passthrough_is_not_frozen(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Caveat (1) on the block path: a tool_result block that passes through+ ONLY because the ML model is not ready must NOT have its skip verdict+ frozen, so it is re-evaluated once the model is ready."""+ monkeypatch.setenv("HEADROOM_FREEZE_BLOCK_DECISION", "1")+ router = ContentRouter(ContentRouterConfig())+ content = _content_of_n_words(200)++ monkeypatch.setattr(router, "_kompress_model_ready", lambda: False)+ monkeypatch.setattr(+ router,+ "compress",+ lambda c, context="", bias=1.0: SimpleNamespace(+ compressed=c, compression_ratio=1.0, strategy_used=CompressionStrategy.TEXT+ ),+ )+ out1 = _block_out(router, content, model_limit=1000)+ assert out1 == content, "not-ready -> passthrough"+ assert all(v is True for v in router._frozen_verdicts.values()) or (+ not router._frozen_verdicts+ ), "not-ready block passthrough must not be frozen as skip"++ router._cache.clear()+ monkeypatch.setattr(router, "_kompress_model_ready", lambda: True)+ monkeypatch.setattr(+ router,+ "compress",+ lambda c, context="", bias=1.0: SimpleNamespace(+ compressed="[C]"+ + c[:20]+ + " <<ccr:t>>", # recoverable marker so #1307 tool-reversibility guard keeps the compression+ compression_ratio=0.50,+ strategy_used=CompressionStrategy.TEXT,+ ),+ )+ out2 = _block_out(router, content, model_limit=1000)+ assert out2.startswith("[C]"), "once model ready the block must compress"+++def test_frozen_verdicts_cleared_on_cache_clear(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """(c) ``_frozen_verdicts`` is cleared in lock-step with the cache so it+ cannot outlive the entries it shadows."""+ monkeypatch.setenv("HEADROOM_FREEZE_BLOCK_DECISION", "1")+ router = _churn_router(monkeypatch, ratio=0.60)+ content = _content_of_n_words(200)++ _block_out(router, content, model_limit=1000)+ assert router._frozen_verdicts, "a verdict should be frozen after a turn"++ router._cache.clear()+ assert not router._frozen_verdicts, "cache clear must also clear frozen verdicts"+++def test_frozen_verdicts_is_size_bounded(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """(c) ``_frozen_verdicts`` is capped with FIFO eviction so it cannot grow+ without bound across a long-lived process."""+ monkeypatch.setenv("HEADROOM_FREEZE_BLOCK_DECISION", "1")+ router = ContentRouter(ContentRouterConfig())+ router._frozen_verdicts_max = 8++ for i in range(50):+ router._record_frozen_verdict(i, True)++ assert len(router._frozen_verdicts) == 8, "store must stay capped at the max"+ # Oldest keys evicted, newest retained (insertion-order FIFO).+ assert set(router._frozen_verdicts) == set(range(42, 50))+++def test_frozen_verdict_refuses_unrecoverable_lossy_block() -> None:+ """#1307: a "compress" verdict for a lossy-unmarked block with no CCR+ retrieval marker must NOT be frozen. Pinning it would keep serving an+ unrecoverable summary across turns, which the reversibility guard forbids.+ Recoverable compressions (marked, or a non-lossy strategy) may be pinned.+ """+ router = ContentRouter(ContentRouterConfig())++ # Lossy + no marker -> unrecoverable -> refuse to freeze.+ assert router._frozen_verdict_recoverable(CompressionStrategy.TEXT, "plain summary") is False+ # Lossy + CCR marker -> recoverable -> may freeze.+ assert router._frozen_verdict_recoverable(CompressionStrategy.TEXT, "summary <<ccr:t>>") is True+ # Non-lossy strategy -> recoverable regardless of marker.+ assert (+ router._frozen_verdict_recoverable(CompressionStrategy.SMART_CRUSHER, "no marker") is True+ )+ # Cache-hit path passes the strategy's .value string, not the enum.+ assert router._frozen_verdict_recoverable("text", "plain") is False+ assert router._frozen_verdict_recoverable("text", "x Retrieve more: hash=abc123") is True++def test_detect_timeout_secs_env_parsing(monkeypatch: pytest.MonkeyPatch) -> None:"""The watchdog budget reads HEADROOM_DETECT_TIMEOUT_SECS; bad values → default."""get = content_router_module._detect_timeout_secs