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(router): preserve unmarked HTML tool output (#3778)

Eastern7c9fbed61af4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 6e78522ae..fcd5074c4 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -410,12 +410,12 @@ jobs:
with:
name: headroom-wheel
path: dist
- - name: Install (CPU torch + wheel[dev,relevance])
+ - name: Install (CPU torch + wheel[dev,relevance,html])
run: |
python -m pip install --upgrade pip
pip install torch --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple
WHEEL="$(ls dist/*.whl)"
- pip install "${WHEEL}[dev,relevance]"
+ pip install "${WHEEL}[dev,relevance,html]"
SITE="$(python -c 'import sysconfig; print(sysconfig.get_path("platlib"))')"
cp "${SITE}/headroom/"_core*.so headroom/
python -c "from headroom._core import SmartCrusher; print('headroom._core OK')"
@@ -437,6 +437,11 @@ jobs:
TRANSFORMERS_OFFLINE: "1"
run: pytest tests/test_relevance.py -v
+ - name: Run HTML extraction and tool reversibility tests
+ run: |
+ python -c "import trafilatura; print('trafilatura import OK')"
+ pytest tests/test_transforms/test_html_extractor.py tests/test_html_tool_reversibility.py -q
+
test-agno:
needs: [changes, build-wheel]
if: needs.changes.outputs.code == 'true'
diff --git a/headroom/transforms/compression_units.py b/headroom/transforms/compression_units.py
index 063b55b7f..f72a668e8 100644
--- a/headroom/transforms/compression_units.py
+++ b/headroom/transforms/compression_units.py
@@ -116,6 +116,7 @@ _LOSSY_UNMARKED_STRATEGIES = {
CompressionStrategy.KOMPRESS.value,
CompressionStrategy.TEXT.value,
CompressionStrategy.CODE_AWARE.value,
+ CompressionStrategy.HTML.value,
}
diff --git a/headroom/transforms/content_router.py b/headroom/transforms/content_router.py
index 03684dd7b..482e1cb81 100644
--- a/headroom/transforms/content_router.py
+++ b/headroom/transforms/content_router.py
@@ -1965,14 +1965,14 @@ class ContentRouter(Transform):
name: str = "content_router"
- # Lossy summarizers that emit a CCR retrieve marker only when they store the
- # original — a marker-less result from one of these is unrecoverable. Tool
- # ground truth (role="tool") must not be replaced by such a result (#1307).
+ # Lossy transforms that discard source data need a CCR retrieval marker;
+ # without one, tool ground truth must remain unchanged (#1307).
LOSSY_UNMARKED_STRATEGIES = frozenset(
{
CompressionStrategy.KOMPRESS,
CompressionStrategy.TEXT,
CompressionStrategy.CODE_AWARE,
+ CompressionStrategy.HTML,
}
)
@@ -6184,8 +6184,8 @@ class ContentRouter(Transform):
else:
accept_ratio = result.compression_ratio
if accept_ratio < min_ratio:
- # tool ground truth must stay reversible — a lossy summarizer
- # (kompress/text/code) that emitted no CCR retrieve marker is
+ # tool ground truth must stay reversible — a lossy transform
+ # (kompress/text/code/html) that emitted no CCR retrieve marker is
# unrecoverable, so the agent would act on a fabricated summary
# (#1307). Keep the original verbatim instead.
if (
@@ -7217,8 +7217,8 @@ class ContentRouter(Transform):
self._record_frozen_verdict(content_key, True)
return result.compressed, True
if result.compression_ratio < min_ratio:
- # Tool ground truth must stay reversible: a lossy summarizer
- # (kompress/text/code) that emitted no CCR retrieve marker is
+ # Tool ground truth must stay reversible: a lossy transform
+ # (kompress/text/code/html) that emitted no CCR retrieve marker is
# unrecoverable, so the agent would act on a fabricated summary
# (#1307). The string/`role=="tool"` path guards this; mirror it
# here for tool_result blocks (never cached, so the Tier-2 path
diff --git a/tests/test_html_tool_reversibility.py b/tests/test_html_tool_reversibility.py
new file mode 100644
index 000000000..1775399a8
--- /dev/null
+++ b/tests/test_html_tool_reversibility.py
@@ -0,0 +1,98 @@
+"""Real HTML extraction must not erase unrecoverable tool ground truth (#3775)."""
+
+import pytest
+
+pytest.importorskip("trafilatura")
+
+from headroom.parser import CCR_RETRIEVAL_MARKER_RE
+from headroom.providers import OpenAIProvider
+from headroom.tokenizer import Tokenizer
+from headroom.transforms.compression_units import CompressionUnit, compress_unit_with_router
+from headroom.transforms.content_router import (
+ CompressionStrategy,
+ ContentRouter,
+ ContentRouterConfig,
+)
+
+
+def _script_heavy_html() -> str:
+ js = "var a=1;function f(x){return x*2};" * 300
+ return (
+ "<!doctype html><html><head><script>"
+ + js
+ + "</script></head><body><p>the answer is 42</p></body></html>"
+ )
+
+
+def _tokenizer() -> Tokenizer:
+ return Tokenizer(OpenAIProvider().get_token_counter("gpt-4o"), "gpt-4o")
+
+
[email protected]("shape", ["tool_result", "role_tool"])
+def test_html_tool_ground_truth_is_recoverable(shape: str) -> None:
+ html = _script_heavy_html()
+ router = ContentRouter(ContentRouterConfig(enable_kompress=False, min_section_tokens=10))
+ extracted = router.compress(html, context="tool_result")
+ assert extracted.strategy_used is CompressionStrategy.HTML
+ assert extracted.compressed != html
+ assert router._frozen_verdict_recoverable(
+ CompressionStrategy.HTML, extracted.compressed
+ ) == bool(CCR_RETRIEVAL_MARKER_RE.search(extracted.compressed))
+
+ if shape == "tool_result":
+ messages = [
+ {"role": "user", "content": "check the site"},
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "t1",
+ "name": "Bash",
+ "input": {"command": "curl -s x"},
+ }
+ ],
+ },
+ {
+ "role": "user",
+ "content": [{"type": "tool_result", "tool_use_id": "t1", "content": html}],
+ },
+ {"role": "assistant", "content": "ok"},
+ {"role": "user", "content": "and now?"},
+ ]
+ result = router.apply(messages, _tokenizer())
+ block = result.messages[2]["content"][0]["content"]
+ output = block if isinstance(block, str) else block[0]["text"]
+ else:
+ result = router.apply(
+ [{"role": "tool", "tool_call_id": "call_bash_1", "content": html}],
+ _tokenizer(),
+ protect_recent=0,
+ protect_analysis_context=False,
+ )
+ output = result.messages[0]["content"]
+
+ assert output == html or CCR_RETRIEVAL_MARKER_RE.search(output)
+
+
+def test_html_provider_shell_unit_is_recoverable() -> None:
+ html = _script_heavy_html().replace("><", ">\n<")
+ router = ContentRouter(ContentRouterConfig(enable_kompress=False, min_section_tokens=10))
+ extracted = router.compress(html)
+ assert extracted.strategy_used is CompressionStrategy.HTML
+ assert extracted.compressed != html
+
+ result = compress_unit_with_router(
+ CompressionUnit(
+ text=html,
+ provider="openai",
+ endpoint="responses",
+ role="tool",
+ item_type="local_shell_call_output",
+ min_bytes=1,
+ ),
+ router=router,
+ tokenizer=_tokenizer(),
+ )
+
+ assert result.compressed == html or CCR_RETRIEVAL_MARKER_RE.search(result.compressed)