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(transforms): judge the code_aware Kompress fallback in tokens (#3881)

gglucass63269650462c
diff --git a/headroom/transforms/content_router.py b/headroom/transforms/content_router.py
index 482e1cb81..18514253f 100644
--- a/headroom/transforms/content_router.py
+++ b/headroom/transforms/content_router.py
@@ -3704,7 +3704,11 @@ class ContentRouter(Transform):
)
if output is not None and output.compressed:
compressed = output.content
- compressed_tokens = len(output.content.split())
+ # Tokens, like ``original_tokens`` and every other
+ # branch: a word count here (code runs ~2.2
+ # tokens/word) made an unchanged block look like a
+ # 55% compression and no fallback could beat it.
+ compressed_tokens = _estimate_tokens(output.content)
decision_reason = "code_aware"
if compressed is None:
# Fallback to Kompress
@@ -3728,19 +3732,17 @@ class ContentRouter(Transform):
# lossless has no savings. Reads are protected upstream, so
# only NON-read code reaches here. Keep Kompress ONLY if it
# actually shrinks (never inflate).
- _k, _kt = self._try_ml_compressor(content, context, question)
- if (
- _k is not None
- and _kt is not None
- and _kt < original_tokens
- and len(_k) < len(content)
- ):
+ # Recorded as tried even if it loses, so the no-savings
+ # fallback below does not run the same inference again.
+ strategy_chain.append(CompressionStrategy.KOMPRESS.value)
+ _k, _ = self._try_ml_compressor(content, context, question)
+ _kt = _estimate_tokens(_k)
+ if _kt < original_tokens and len(_k) < len(content):
compressed, compressed_tokens = _k, _kt
strategy = CompressionStrategy.KOMPRESS
actual_strategy = strategy
compressor_name = "KompressCompressor"
decision_reason = "code_aware_no_shrink_fallback_kompress"
- strategy_chain.append(CompressionStrategy.KOMPRESS.value)
elif strategy == CompressionStrategy.SMART_CRUSHER:
# SmartCrusher handles its own TOIN recording
@@ -3965,9 +3967,11 @@ class ContentRouter(Transform):
already_tried_kompress = CompressionStrategy.KOMPRESS.value in strategy_chain
if not already_tried_kompress:
strategy_chain.append(CompressionStrategy.KOMPRESS.value)
- fallback_compressed, fallback_tokens = self._try_ml_compressor(
- content, context, question
- )
+ fallback_compressed, _ = self._try_ml_compressor(content, context, question)
+ # Measure with the router's estimator, the unit of
+ # ``compressed_tokens``. Kompress reports a passthrough in
+ # WORDS, which would let an unchanged block "win".
+ fallback_tokens = _estimate_tokens(fallback_compressed)
else:
fallback_compressed = compressed
fallback_tokens = compressed_tokens
diff --git a/tests/test_code_aware_regressions.py b/tests/test_code_aware_regressions.py
index 632d8fc80..2dbcc2c11 100644
--- a/tests/test_code_aware_regressions.py
+++ b/tests/test_code_aware_regressions.py
@@ -7,8 +7,9 @@ default flip).
2. Multi-line Go signature (`) error {`) — the brace-bearing signature line
survives truncation instead of being silently dropped.
3. ContentRouter CODE_AWARE token accounting — compressed_tokens must come
- from the same word-count metric as original_tokens, not the compressor's
- own (differently-scaled) estimator, or real savings get misread as none.
+ from the same metric as original_tokens (the router's token estimator),
+ not the compressor's own (differently-scaled) estimator, or real savings
+ get misread as none.
4. prefer_code_aware_for_code defaults to True, both on the dataclass and via
the HEADROOM_PREFER_CODE_AWARE_FOR_CODE env var.
"""
@@ -27,6 +28,7 @@ from headroom.transforms.content_router import (
CompressionStrategy,
ContentRouter,
ContentRouterConfig,
+ _estimate_tokens,
)
pytestmark = pytest.mark.skipif(
@@ -96,13 +98,13 @@ class _FakeCodeCompressor:
r.compressed = self._compressed
# Deliberately inflated/differently-scaled "own" token estimate —
# simulates a compressor whose internal counter isn't comparable to
- # the router's len(text.split()) word count.
+ # the router's own token estimate.
r.compressed_tokens = 10_000_000
return r
-def test_content_router_code_aware_token_accounting_matches_word_count() -> None:
- """compressed_tokens must be derived from len(result.compressed.split()),
+def test_content_router_code_aware_token_accounting_matches_router_estimate() -> None:
+ """compressed_tokens must be derived from _estimate_tokens(result.compressed),
the same metric as original_tokens, not the compressor's own estimator.
Using the mismatched estimator made a real compression look like "no
savings" and forced a needless fallback to Kompress."""
@@ -117,7 +119,7 @@ def test_content_router_code_aware_token_accounting_matches_word_count() -> None
)
assert compressed == compressed_text
- assert compressed_tokens == len(compressed_text.split())
+ assert compressed_tokens == _estimate_tokens(compressed_text)
assert strategy_chain == ["code_aware"], (
f"real compression must not trigger a Kompress fallback, got {strategy_chain}"
)
diff --git a/tests/test_openai_responses_context_compaction.py b/tests/test_openai_responses_context_compaction.py
index 74dc99cba..48f7c11ca 100644
--- a/tests/test_openai_responses_context_compaction.py
+++ b/tests/test_openai_responses_context_compaction.py
@@ -12,6 +12,7 @@ from headroom.transforms.content_router import (
CompressionStrategy,
ContentRouter,
ContentRouterConfig,
+ _estimate_tokens,
)
@@ -432,7 +433,8 @@ def test_content_router_retries_kompress_when_structured_strategy_noops(monkeypa
)
assert compressed == "short summary"
- assert compressed_tokens == 2
+ # Measured with the router's estimator, the unit of the strategy result.
+ assert compressed_tokens == _estimate_tokens("short summary")
# The fallback chain must record both strategies it tried.
assert strategy_chain == ["smart_crusher", "kompress"]
diff --git a/tests/test_router_registry_dispatch.py b/tests/test_router_registry_dispatch.py
index 1846f631a..92257a105 100644
--- a/tests/test_router_registry_dispatch.py
+++ b/tests/test_router_registry_dispatch.py
@@ -244,8 +244,8 @@ def test_code_aware_router_dispatch_matches_direct(monkeypatch: pytest.MonkeyPat
content, CompressionStrategy.CODE_AWARE, "q", language="python", bias=1.0
)
assert out == shrunk
- # CODE_AWARE's historical token metric is len(compressed.split()), NOT _estimate_tokens.
- assert tokens == len(shrunk.split())
+ # Measured in the router's token estimate, the unit of original_tokens.
+ assert tokens == _estimate_tokens(shrunk)
assert chain == [CompressionStrategy.CODE_AWARE.value]
# The flip forwarded content, language, and context through the registry adapter.
assert seen == {"content": content, "language": "python", "context": "q"}
diff --git a/tests/test_router_registry_smartcrusher.py b/tests/test_router_registry_smartcrusher.py
index 1a820b7a0..d80684a31 100644
--- a/tests/test_router_registry_smartcrusher.py
+++ b/tests/test_router_registry_smartcrusher.py
@@ -144,12 +144,15 @@ def test_smart_crusher_kompress_fallback_matches_direct(monkeypatch: pytest.Monk
lambda: SimpleNamespace(crush=lambda c, query="", bias=1.0: SimpleNamespace(compressed=c)),
)
# Kompress shrinks (fallback_tokens < compressed_tokens) so it is adopted.
- monkeypatch.setattr(router, "_try_ml_compressor", lambda c, ctx, q: ("KOMPRESSED::" + c, 3))
+ # The fallback is measured with the router's estimator, not the count the
+ # ML compressor reports, so the mock must actually return less text.
+ kompressed = "KOMPRESSED::" + _JSON[:40]
+ monkeypatch.setattr(router, "_try_ml_compressor", lambda c, ctx, q: (kompressed, 3))
out, tokens, chain = router._apply_strategy_to_content(
_JSON, CompressionStrategy.SMART_CRUSHER, "ctx", bias=1.0
)
- assert out == "KOMPRESSED::" + _JSON
- assert tokens == 3
+ assert out == kompressed
+ assert tokens == _estimate_tokens(kompressed)
assert chain == [
CompressionStrategy.SMART_CRUSHER.value,
CompressionStrategy.KOMPRESS.value,
diff --git a/tests/test_transforms_content_router.py b/tests/test_transforms_content_router.py
index 7ff3619b6..946710f6b 100644
--- a/tests/test_transforms_content_router.py
+++ b/tests/test_transforms_content_router.py
@@ -2251,3 +2251,123 @@ def test_html_extraction_miss_still_gets_deferred_json_splice() -> None:
assert len(text) < len(shell)
json_marker = '"id":'
assert json_marker not in text # the array was compressed away
+
+
+# A Claude Code Read of Rust: line-numbered code that code_aware hands back
+# unchanged (it cannot parse the number column) while reporting compressed=True.
+# Code runs ~2 tokens per whitespace word, so a word count badly undercounts it.
+_NUMBERED_RUST = "\n".join(
+ f"{i}\tlet value_{i} = compute(&items[{i}..], Some(opts.clone()))?;" for i in range(1, 121)
+)
+
+
+def _noop_code_aware_router(monkeypatch: pytest.MonkeyPatch, kompress_out: str) -> ContentRouter:
+ monkeypatch.delenv("HEADROOM_LOSSLESS_THEN_LOSSY", raising=False)
+ router = ContentRouter(ContentRouterConfig(enable_code_aware=True))
+
+ class NoopCodeCompressor:
+ def compress(self, content: str, language=None, context: str = "") -> SimpleNamespace:
+ return SimpleNamespace(compressed=content, compressed_tokens=0)
+
+ monkeypatch.setattr(router, "_get_code_compressor", lambda: NoopCodeCompressor())
+
+ def kompress(content: str, *_args: object, **_kwargs: object) -> tuple[str, int]:
+ # What Kompress reports: payload tokens for a real compression, the
+ # WORD count for a passthrough.
+ if kompress_out == content:
+ return content, len(content.split())
+ return kompress_out, _estimate_tokens(kompress_out)
+
+ monkeypatch.setattr(router, "_try_ml_compressor", kompress)
+ return router
+
+
+def test_code_aware_noop_keeps_a_smaller_kompress_fallback(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The fallback is judged in tokens, the unit of the code_aware result.
+
+ With code_aware's result counted in words, a Kompress result at ~60% of the
+ tokens still "lost" to the unchanged block, so the inference always ran and
+ was always thrown away.
+ """
+ kompressed = "\n".join(f"{i}\tvalue_{i} compute(&items[{i}..])" for i in range(1, 121))
+ assert _estimate_tokens(kompressed) < _estimate_tokens(_NUMBERED_RUST)
+ assert _estimate_tokens(kompressed) > len(_NUMBERED_RUST.split())
+ router = _noop_code_aware_router(monkeypatch, kompressed)
+
+ compressed, compressed_tokens, strategy_chain = router._apply_strategy_to_content(
+ _NUMBERED_RUST, CompressionStrategy.CODE_AWARE, context=""
+ )
+
+ assert compressed == kompressed
+ assert compressed_tokens == _estimate_tokens(kompressed)
+ assert strategy_chain == ["code_aware", "kompress"]
+
+
+def test_code_aware_noop_reports_tokens_when_kompress_passes_through(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """An unchanged block is reported at its own token count, never its word count."""
+ router = _noop_code_aware_router(monkeypatch, _NUMBERED_RUST)
+
+ compressed, compressed_tokens, _chain = router._apply_strategy_to_content(
+ _NUMBERED_RUST, CompressionStrategy.CODE_AWARE, context=""
+ )
+
+ assert compressed == _NUMBERED_RUST
+ assert compressed_tokens == _estimate_tokens(_NUMBERED_RUST)
+
+
+def test_code_aware_noop_runs_kompress_once_when_it_passes_through(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Lossless-then-lossy tries Kompress inline; a passthrough must not be retried."""
+ router = _noop_code_aware_router(monkeypatch, _NUMBERED_RUST)
+ router._lossless_then_lossy = True
+ calls: list[str] = []
+ kompress = router._try_ml_compressor
+
+ def counting(content: str, *args: object, **kwargs: object) -> tuple[str, int]:
+ calls.append(content)
+ return kompress(content, *args, **kwargs)
+
+ monkeypatch.setattr(router, "_try_ml_compressor", counting)
+
+ compressed, compressed_tokens, _chain = router._apply_strategy_to_content(
+ _NUMBERED_RUST, CompressionStrategy.CODE_AWARE, context=""
+ )
+
+ assert compressed == _NUMBERED_RUST
+ assert compressed_tokens == _estimate_tokens(_NUMBERED_RUST)
+ assert len(calls) == 1
+
+
+def test_code_aware_noop_keeps_a_smaller_inline_kompress(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Lossless-then-lossy's inline attempt keeps a Kompress result that wins.
+
+ Measured in tokens, a code_aware no-op no longer looks like a shrink, so the
+ inline attempt fires and its smaller result is kept without a second call.
+ """
+ kompressed = "\n".join(f"{i}\tvalue_{i} compute(&items[{i}..])" for i in range(1, 121))
+ router = _noop_code_aware_router(monkeypatch, kompressed)
+ router._lossless_then_lossy = True
+ calls: list[str] = []
+ kompress = router._try_ml_compressor
+
+ def counting(content: str, *args: object, **kwargs: object) -> tuple[str, int]:
+ calls.append(content)
+ return kompress(content, *args, **kwargs)
+
+ monkeypatch.setattr(router, "_try_ml_compressor", counting)
+
+ compressed, compressed_tokens, strategy_chain = router._apply_strategy_to_content(
+ _NUMBERED_RUST, CompressionStrategy.CODE_AWARE, context=""
+ )
+
+ assert compressed == kompressed
+ assert compressed_tokens == _estimate_tokens(kompressed)
+ assert strategy_chain == ["code_aware", "kompress"]
+ assert len(calls) == 1