headroom/tests/test_content_router_single_item_deadline.py
Tejas Chopra 8884d87378
fix(transforms): stop compression garbling mixed subagent output (#3286)
## The report

A user's model called compressed subagent output "too garbled to use"
and burned CCR retrievals to reconstruct it — **not** because it needed
more context. One retrieval returned nothing but the Claude Code harness
sanitizer banner, reported as `original_item_count: 33,
compressed_item_count: 25`.

Root-cause chain (verified by reproduction): the harness prepends a
bracket-delimited banner (`[harness: ... you.]` — exactly 33
whitespace-delimited words) and neutralizes `<` → `<\`. Headroom's
mixed-content splitter typed the banner as JSON (bracket balance, no
validation) → SmartCrusher couldn't parse it → the fallback chain fed it
to lossy Kompress → Kompress word-dropped the banner 33→25 and stored it
behind a retrieval hash. Meanwhile tabular sections rendered as
quote-wrapped JSON-string blobs with `\n` as two-character escapes, and
`ensure_ascii=True` boundaries turned the output's unicode (`→ └ ✓`)
into `\uXXXX` soup. The model reasonably concluded the output was
garbled.

## Fixes

1. **`split_into_sections` validates JSON before typing a block
`JSON_ARRAY`** — same validation its own mixed-content gate
(`_has_valid_json_block_with_text`) has always used. Tag-protection
placeholders, which self-isolated only by accident of that bug
(`{{HEADROOM_TAG_N}}` bracket-balances), are now isolated explicitly via
a new `isolate=` parameter fed by the router; contiguous prose fragments
re-coalesce so the `\n\n` reassembly stops doubling newlines in
uncompressed prose.
2. **Kompress gets a real floor: `min_input_words = 64`**
(config-tunable, clamped at the historical 10), applied on the
in-process, batch, apply, and remote paths. Below it, lossy
word-dropping is a net loss — the retrieval marker alone is ~20 words —
and short blocks are disproportionately instruction-like.
3. **The mixed path unwraps SmartCrusher's whole-array CSV render** when
it comes back as a bare JSON string, splicing raw readable lines into
the text instead of a quoted escape blob.
4. **`ensure_ascii=False` at model-visible boundaries**: MCP
retrieve/stats responses and the audit-safe splice reserialization
(which now also matches serde_json's non-escaping behavior).
5. **Kompress honesty**: the marker says `N words compressed to M`
(shared `ccr_retrieval_marker` helper, unit-tested), and
`store_kompress_in_ccr` no longer writes word counts into the store's
*item count* fields — token counts already carry the size story.

The upstream trigger (the harness's `<` → `<\` neutralization corrupting
JSON semantics) is not Headroom's to fix, but with #1 and #2 the banner
now passes through byte-intact and nothing lossy touches it.

## Testing

- New `tests/test_garbled_compression_fixes.py` (12 tests) pins every
fix, including an end-to-end router pass over a reconstructed
harness-sanitized fixture asserting the banner survives byte-identical
and no `\uXXXX` appears.
- Existing small-fixture kompress/router tests updated to set
`min_input_words=10` explicitly (they test other mechanics; fixtures sit
under the new production floor by design).
- Affected sweep (`-k "compress or ccr or crusher or router or mixed or
kompress or hermes"`, ~2.9k tests): green apart from order-dependent
flakes that shift identity between runs (deepseek tokenizer `AutoConfig`
import, hermes/proxy-ccr) — each passes standalone and in direct
combination with the new tests; the full CI shards are the authoritative
check.
- ruff 0.16.3 `check` + `format --check` clean.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01EWKCmcH47hvvoQ35wftXhE

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-27 13:22:26 +05:30

184 lines
5.4 KiB
Python

from __future__ import annotations
import time
import headroom.transforms.kompress_compressor as kc
from headroom.transforms.content_detector import ContentType
from headroom.transforms.content_router import (
CompressionStrategy,
ContentRouter,
ContentRouterConfig,
RouterCompressionResult,
RoutingDecision,
)
from headroom.transforms.kompress_compressor import KompressCompressor, KompressConfig
class _Tokenizer:
def count_text(self, content: str) -> int:
return len(content.split())
def _compression_result(content: str, compressed: str) -> RouterCompressionResult:
return RouterCompressionResult(
compressed=compressed,
original=content,
strategy_used=CompressionStrategy.TEXT,
routing_log=[
RoutingDecision(
content_type=ContentType.PLAIN_TEXT,
strategy=CompressionStrategy.TEXT,
original_tokens=len(content.split()),
compressed_tokens=len(compressed.split()),
)
],
)
def _router() -> ContentRouter:
return ContentRouter(
ContentRouterConfig(
protect_recent_code=0,
protect_analysis_context=False,
skip_user_messages=False,
)
)
def _messages() -> list[dict[str, str]]:
return [
{"role": "assistant", "content": "frozen prefix content remains unchanged"},
{
"role": "assistant",
"content": "pending cache miss content takes the inline compression branch today",
},
]
def test_single_cache_miss_fails_open_at_deadline(monkeypatch, caplog):
router = _router()
def slow_compress(content, *, context="", bias=1.0):
time.sleep(0.2)
return _compression_result(content, "compressed output")
monkeypatch.setattr(router, "compress", slow_compress)
monkeypatch.setenv("HEADROOM_COMPRESSION_DEADLINE_MS", "10")
started = time.perf_counter()
result = router.apply(
_messages(),
_Tokenizer(),
frozen_message_count=1,
min_tokens_to_compress=1,
)
assert time.perf_counter() - started < 0.12
assert result.messages[1]["content"] == _messages()[1]["content"]
assert "failing open via PASSTHROUGH" in caplog.text
def test_single_cache_miss_preserves_under_deadline_output(monkeypatch):
router = _router()
monkeypatch.setattr(
router,
"compress",
lambda content, *, context="", bias=1.0: _compression_result(content, "compressed output"),
)
monkeypatch.setenv("HEADROOM_COMPRESSION_DEADLINE_MS", "1000")
result = router.apply(
_messages(),
_Tokenizer(),
frozen_message_count=1,
min_tokens_to_compress=1,
)
assert result.messages[1]["content"] == "compressed output"
def test_single_cache_miss_preserves_disabled_deadline(monkeypatch):
router = _router()
monkeypatch.setattr(
router,
"compress",
lambda content, *, context="", bias=1.0: _compression_result(content, "compressed output"),
)
monkeypatch.setenv("HEADROOM_COMPRESSION_DEADLINE_MS", "0")
result = router.apply(
_messages(),
_Tokenizer(),
frozen_message_count=1,
min_tokens_to_compress=1,
)
assert result.messages[1]["content"] == "compressed output"
def test_single_cache_miss_deadline_starts_before_kompress_load(monkeypatch, caplog):
router = _router()
class _Encoding(dict):
def __init__(self, rows: list[list[str]]):
super().__init__(
input_ids=[[0] * len(row) for row in rows],
attention_mask=[[1] * len(row) for row in rows],
)
self._rows = rows
def word_ids(self, batch_index: int = 0):
return list(range(len(self._rows[batch_index])))
class _Tokenizer:
def count_text(self, content: str) -> int:
return len(content.split())
def __call__(self, words, **_kwargs):
rows = words if words and isinstance(words[0], list) else [words]
return _Encoding(rows)
class _Model:
def __init__(self):
self.calls = 0
def get_keep_mask(self, input_ids, attention_mask):
self.calls += 1
return [[i % 2 == 0 for i in range(len(row))] for row in input_ids]
model = _Model()
compressor = KompressCompressor(config=KompressConfig(enable_ccr=False, min_input_words=10))
monkeypatch.setattr(compressor, "_should_batch_single_content", lambda *a, **k: False)
load_state = {"calls": 0}
def _slow_load(*_args, **_kwargs):
load_state["calls"] += 1
time.sleep(0.05)
return model, _Tokenizer(), "onnx"
monkeypatch.setattr(kc, "_load_kompress", _slow_load)
monkeypatch.setattr(
router,
"compress",
lambda content, *, context="", bias=1.0: _compression_result(
content,
compressor.compress(content).compressed,
),
)
monkeypatch.setenv("HEADROOM_COMPRESSION_DEADLINE_MS", "10")
started = time.perf_counter()
result = router.apply(
_messages(),
_Tokenizer(),
frozen_message_count=1,
min_tokens_to_compress=1,
)
elapsed = time.perf_counter() - started
time.sleep(0.1)
assert elapsed < 0.12
assert result.messages[1]["content"] == _messages()[1]["content"]
assert "failing open via PASSTHROUGH" in caplog.text
assert load_state["calls"] == 1
assert model.calls == 0