Files
headroom/tests/test_lossless_excluded_compaction.py
9f068a6c13 fix(router): validate lossless provider output on the excluded-tool path (#4486)
Fixes #4475

## Description

`ContentRouter._lossless_compact_excluded` (protected / excluded tool
output) returned the lossless provider's result unvalidated, although
`lossless_provider.py` says a malformed or empty result is ignored and
`kind` is sanitised. The general path (`_lossless_provider_result`)
already enforced this. On the excluded path a 3-tuple made `folded, kind
= compacted` raise `ValueError` out of `ContentRouter.apply`, an empty
fold replaced the tool result with `""`, and any `kind` string went into
`transforms_applied`.

This PR moves the contract check into one helper,
`_validate_provider_output`, and uses it on both paths.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/transforms/content_router.py`: new static
`_validate_provider_output(supplied)` holding the exact checks that were
inline in `_lossless_provider_result` (None, shape, str members,
non-empty, `kind` fullmatch with fallback label).
`_lossless_provider_result` now calls it (behaviour unchanged, memo
kept). `_lossless_compact_excluded` calls it on the provider's return
value.
- Unchanged semantics on the excluded path: a provider that raises still
falls back to the built-in folds; a provider result of `None` (now also
any ignored result) leaves the content unchanged and does not run the
built-in folds.
- `tests/test_lossless_excluded_compaction.py`: four tests through
`ContentRouter.apply` on an excluded tool (`Grep`): valid 2-tuple
control, 3-tuple, empty fold, hostile kind. The file's autouse fixture
resets the provider after each test.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [ ] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [ ] Manual testing performed

### Review round 1

Devin flagged that the Real Behavior Proof lacked runtime evidence
(`tests/test_lossless_excluded_compaction.py:302-303`). No code change:
the proof section now shows a real proxy run against a local stub
upstream, before and after, below. The commit is unchanged.

### Test Output

Fail before (source change reverted, new tests kept), `pytest -q
tests/test_lossless_excluded_compaction.py`:

```text
FAILED tests/test_lossless_excluded_compaction.py::test_excluded_three_tuple_is_ignored_not_fatal
FAILED tests/test_lossless_excluded_compaction.py::test_excluded_empty_fold_leaves_content_unchanged
FAILED tests/test_lossless_excluded_compaction.py::test_excluded_hostile_kind_is_replaced
======================== 3 failed, 33 passed in 20.53s =========================
```

Pass after:

```text
tests/test_lossless_excluded_compaction.py ............................. [ 80%]
.......                                                                  [100%]
============================== 36 passed in 8.46s ==============================
```

Neighbours (every test file mentioning `lossless_provider`, `_lossless_`
or `set_lossless`, plus `tests/test_transforms/test_content_router.py`,
including the existing `test_provider_exception_falls_back_to_builtin`
and `test_registered_provider_is_authoritative`):

```text
============= 532 passed, 2 skipped, 1 warning in 79.36s (0:01:19) =============
```

Ruff:

```text
$ ruff check headroom/transforms/content_router.py tests/test_lossless_excluded_compaction.py
All checks passed!
$ ruff format --check headroom/transforms/content_router.py tests/test_lossless_excluded_compaction.py
2 files already formatted
```

## Real Behavior Proof

- Environment: real proxy `python -m headroom.proxy.server --host
127.0.0.1 --port 18961 --no-cache --no-rate-limit` (Python 3.12.15, WSL2
Ubuntu, Windows 11) at upstream main 3fef15d3 plus this commit,
`ANTHROPIC_TARGET_API_URL` pointing at a local stub upstream on
127.0.0.1:18962 that records what it receives; fake key `sk-ant-test`,
no provider API contacted. A proof-only extension registered through the
real `headroom.proxy_extension` entry point calls
`set_lossless_provider` at proxy start.
- Exact command / steps: start the stub, start the proxy with
`HEADROOM_PROXY_EXTENSIONS=lossless_ext
PROOF_PROVIDER_MODE=<tuple3|empty|hostile|good>`, then one non-streaming
`POST /v1/messages` whose last message is a `tool_result` of a `Grep`
tool_use (40 lines `src/app.py:N: handler_N()`); run once with this PR's
source change reverted (`git apply -R`) and once at PR head.
- Observed result: stub upstream tool_result, before vs after. 3-tuple
provider: before the proxy logs `Transform content_router failed;
aborting compression pipeline` / `ValueError` (the whole compression
pipeline is skipped for that request), after no error and the
tool_result arrives verbatim; empty-fold provider: before the stub
receives `' '` (the grep output blanked, 5 chars logged), after it
receives the original 1,264-char tool_result verbatim; hostile kind:
content applied in both (unchanged by design); valid 2-tuple control:
folded content (` | `-joined) reaches the stub in both,
`route_counts={'excluded_tool_lossless': 1}`.
- Not tested: the OpenAI Responses handler (`proxy/handlers/openai.py`,
`_lossless_compact_excluded` caller) end to end; the hostile-kind label
itself over the wire (it only lands in `transforms_applied`, covered by
the unit test); streaming; a real provider API; the optional verifier on
the excluded path (not consulted before or after this PR, out of scope);
`mypy`.

Raw lines (stub upstream receives; proxy log excerpts):

```text
BEFORE (change reverted)
3-tuple : proxy log: ERROR headroom.transforms.pipeline - Transform content_router failed; aborting compression pipeline
          ValueError ... content_router.py:7684 in _process_content_blocks
          proxy log: WARNING Optimization failed: ValueError ...; stub receives the original tool_result (client still HTTP 200)
empty   : PERF tok_before=465 tok_after=26 tok_saved=439   stub: tool_result='   '
AFTER (PR head)
3-tuple : no ERROR/Traceback in proxy log; stub: tool_result == original (1,264 chars, verified equal)
empty   : no ERROR/Traceback; PERF not blanked; stub: tool_result == original (1,264 chars, verified equal)
good    : route_counts={'content_blocks': 1, 'excluded_tool_lossless': 1}; stub: 'src/app.py:1:    handler_1() | src/app.py:2:    handler_2() | ...'
```

Scripts and raw outputs (WSL):
`/var/tmp/cb-pub/proof/fix-lossless-excluded-provider-contract/`
(`run.sh`, `stub.py`, `client.py`, `ext/`, `before_*.out`,
`after_*.out`, `src.patch`).

## Runtime Rollout Safety

- Rollout-managed feature(s): none (lossless provider seam is an
operator-installed extension point, no rollout flag involved)
- Minimum rollout channel: n/a
- Stable/default behavior changed: no for the default (no provider
registered); with a provider registered, malformed or empty results on
excluded tool output are now ignored instead of raising or blanking the
result
- Kill switch / disable path: `set_lossless_provider(None)`
- Unsafe override required: no
- Qualification impact: none expected
- Rollback path: revert this commit

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Screenshots (if applicable)

N/A

## Additional Notes

- The issue suggested calling `self._lossless_provider_result(content)`
directly. That helper catches provider exceptions and returns `None`,
which would make the excluded path stop falling back to the built-in
folds when a provider raises
(`test_provider_exception_falls_back_to_builtin` pins that). So the
shared piece is the validation, factored out as
`_validate_provider_output`; the excluded path keeps its own try/except
and has no memo (it had none before).
- Documentation: no docs change; the behaviour now matches what
`lossless_provider.py` already documents.

Produced with AI assistance (Claude Code) operated by me (HetCreep); the
tests above were run on my machine against a clone of the repository.

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
2026-10-28 23:37:02 -05:00

333 lines
13 KiB
Python

"""Information-preserving compaction for EXCLUDED tool output.
Excluded tools (Grep/Glob/Write/Edit) are protected from *lossy* compression for
accuracy. This feature still compacts them by detected shape, using only
reversible / data-preserving transforms:
* SEARCH (grep) -> ripgrep --heading fold [byte-lossless]
* LOG -> ANSI strip + run-collapse [byte-lossless modulo ANSI color]
* JSON -> whitespace-minify [data-lossless; same object, NOT byte-exact]
Source code and glob path-lists match nothing -> untouched. Always on
(information-preserving, so it needs no feature gate) in every path.
File-READ tools (`Read`/`read`, Copilot's `view`) are the exception: they are in
DEFAULT_VERBATIM_EXCLUDE_TOOLS and skip the fold entirely, because their bytes
come back to us as the model's `Edit(old_string=...)` anchor and must therefore
be byte-faithful, not merely recoverable.
"""
from __future__ import annotations
import json
import pytest
from headroom.providers import OpenAIProvider
from headroom.tokenizer import Tokenizer
from headroom.transforms.content_router import ContentRouter, ContentRouterConfig
from headroom.transforms.lossless_compaction import expand_runs, search_unheading, strip_ansi
from headroom.transforms.lossless_provider import (
get_lossless_provider,
set_lossless_provider,
)
GREP = "".join(
f"src/module_{f}.py:{ln * 3}:matched occurrence with some real content here\n"
for f in range(6)
for ln in range(15)
)
LOG = "".join(
f"\x1b[32m2026-07-03 INFO worker {i % 3} processing job batch\x1b[0m\n" for i in range(40)
)
LOG += "".join("2026-07-03 WARN transient retry, backing off\n" for _ in range(25))
JSON = json.dumps(
{"users": [{"id": i, "name": f"user{i}", "active": i % 2 == 0} for i in range(40)]},
indent=2,
)
CODE = "def foo(x):\n return x + 1\n\nclass Bar:\n value = 42\n" * 30
GLOB = "\n".join(f"src/module_{i}.py" for i in range(60)) + "\n"
@pytest.fixture
def tokenizer():
provider = OpenAIProvider()
return Tokenizer(provider.get_token_counter("gpt-4o"), "gpt-4o")
def _compact(content: str):
router = ContentRouter(ContentRouterConfig())
return router._lossless_compact_excluded(content)
# --- helper: right transform per shape, right guarantee ---
def test_grep_search_fold_is_byte_lossless():
out, kind = _compact(GREP)
assert kind == "search"
assert len(out) < len(GREP)
assert search_unheading(out) == GREP # byte-exact
def test_log_compaction_recovers_modulo_ansi():
out, kind = _compact(LOG)
assert kind == "log"
assert len(out) < len(LOG)
assert expand_runs(out) == strip_ansi(LOG) # recover the lines (ANSI dropped)
def test_json_minify_is_data_lossless():
out, kind = _compact(JSON)
assert kind == "json"
assert len(out) < len(JSON)
assert json.loads(out) == json.loads(JSON) # same object; NOT byte-exact
def test_source_and_glob_untouched():
assert _compact(CODE) is None
assert _compact(GLOB) is None
# --- end-to-end through the router pipeline (excluded tools) ---
def _run(content: str, tool: str, tokenizer):
router = ContentRouter(ContentRouterConfig())
messages = [
{
"role": "assistant",
"tool_calls": [{"id": "c1", "function": {"name": tool, "arguments": "{}"}}],
},
{"role": "tool", "tool_call_id": "c1", "content": content},
]
result = router.apply(messages, tokenizer, compress_user_messages=True)
return result.messages[1]["content"], result.transforms_applied
def test_pipeline_folds_grep_and_recovers(tokenizer):
out, transforms = _run(GREP, "grep", tokenizer)
assert "router:excluded:lossless_search" in transforms
assert search_unheading(out) == GREP
# The two shape tests below drive `grep`, not `read`. A file-read tool is now
# short-circuited before the fold ever runs (see the byte-faithfulness tests
# further down), so `read` would prove nothing about the fold. `grep` is
# excluded-but-foldable: its output is search results the agent greps again,
# never a string it re-emits as an Edit anchor.
def test_pipeline_compacts_log_from_excluded_tool(tokenizer):
out, transforms = _run(LOG, "grep", tokenizer)
assert "router:excluded:lossless_log" in transforms
assert expand_runs(out) == strip_ansi(LOG)
def test_pipeline_minifies_json_from_excluded_tool(tokenizer):
out, transforms = _run(JSON, "grep", tokenizer)
assert "router:excluded:lossless_json" in transforms
assert json.loads(out) == json.loads(JSON) # data-lossless (same object)
def test_pipeline_leaves_source_read_untouched(tokenizer):
out, _ = _run(CODE, "read", tokenizer)
assert out == CODE
# --- file reads must be BYTE-faithful, not merely recoverable ----------------
#
# Regression for the read-then-Edit miss: `Read`/`read` were excluded from LOSSY
# compression but not from the excluded-tool lossless fold, so a read of a
# pretty-printed JSON file came back json-min'd. That fold is data-lossless and
# the proxy can invert it -- but the inverse runs on OUR side, while the copy
# that has to match on disk is typed by the MODEL from the bytes it was shown.
# It built `Edit(old_string=...)` out of minified JSON, the file on disk was
# still pretty-printed, the edit missed, and the retry turn cost more than the
# ~480 tokens the fold saved. Copilot's equivalent `view` was already protected;
# `Read` was the asymmetry.
def _run_anthropic(content: str, tool: str, tokenizer):
"""Claude Code's own wire shape: tool_use / tool_result content blocks.
Gated by a *separate* guard from the OpenAI chat path (`_run`), so the
byte-exact rule has to be asserted on both or one wire keeps folding.
"""
router = ContentRouter(ContentRouterConfig())
messages = [
{
"role": "assistant",
"content": [{"type": "tool_use", "id": "t1", "name": tool, "input": {}}],
},
{
"role": "user",
"content": [{"type": "tool_result", "tool_use_id": "t1", "content": content}],
},
]
result = router.apply(messages, tokenizer, compress_user_messages=True)
return result.messages[1]["content"][0]["content"], result.transforms_applied
@pytest.mark.parametrize("shape", [_run, _run_anthropic], ids=["openai_chat", "anthropic_blocks"])
@pytest.mark.parametrize("tool", ["Read", "read", "view"])
@pytest.mark.parametrize("body", [JSON, LOG, GREP], ids=["json", "log", "grep"])
def test_file_read_result_is_byte_exact(shape, tool, body, tokenizer):
out, transforms = shape(body, tool, tokenizer)
assert out == body, f"{tool} result was rewritten; the model's Edit anchor would miss"
assert "router:excluded:tool" in transforms
assert not any(t.startswith("router:excluded:lossless") for t in transforms)
def test_read_json_edit_anchor_survives(tokenizer):
"""The exact failure this protects: an Edit anchor copied out of a Read.
`old_string` is a verbatim slice of the pretty-printed file. Before the fix
the model saw minified JSON, so the anchor it could construct was not a
substring of the file on disk and `Edit` missed.
"""
anchor = ' "users": [\n {\n "id": 0,'
assert anchor in JSON # the anchor is real on disk
shown, _ = _run(JSON, "Read", tokenizer)
assert anchor in shown
def test_read_is_still_cross_turn_deduped(tokenizer):
"""The deliberate line between the two protection sets — hold it.
Read is byte-exact against the FOLD, not blanket-verbatim. The one-line
alternative (adding Read to DEFAULT_VERBATIM_EXCLUDE_TOOLS, next to `view`)
would also switch off cross-turn dedup, which is worth ~66% of the tokens on
a file read three times — the largest Read-side saving there is, and unlike
the fold it does not destroy the bytes: keep-earliest guarantees the first,
unrewritten copy is still in the window for the model to copy its anchor
from. If someone later "simplifies" the two sets into one, this fails.
"""
config = ContentRouterConfig()
config.enable_cross_turn_dedup = True
router = ContentRouter(config)
messages = []
for k in range(3):
messages.append(
{
"role": "assistant",
"tool_calls": [{"id": f"c{k}", "function": {"name": "Read", "arguments": "{}"}}],
}
)
messages.append({"role": "tool", "tool_call_id": f"c{k}", "content": CODE})
result = router.apply(messages, tokenizer, compress_user_messages=True)
outs = [m["content"] for m in result.messages if m.get("role") == "tool"]
assert outs[0] == CODE # keep-earliest: the anchor copy is never rewritten
assert len(outs[2]) < len(CODE) # …and the later repeats still fold to pointers
# --- pluggable lossless provider seam ---------------------------------------
@pytest.fixture(autouse=True)
def _reset_provider():
"""Never leak a registered provider between tests."""
yield
set_lossless_provider(None)
def test_default_no_provider_uses_builtin():
# Unset (default) → built-in folds run; GREP compacts via search-heading.
assert get_lossless_provider() is None
out, kind = _compact(GREP)
assert kind == "search" and search_unheading(out) == GREP
def test_registered_provider_is_authoritative():
# A registered provider fully owns excluded-tool compaction; the built-in
# search fold does NOT run (we'd get "search", not our sentinel).
set_lossless_provider(lambda content: ("<<folded>>", "custom"))
assert _compact(GREP) == ("<<folded>>", "custom")
# Authoritative on None too: provider says "leave it" → no built-in fallback.
set_lossless_provider(lambda content: None)
assert _compact(GREP) is None
def test_byte_exact_read_gate_runs_before_the_provider_seam(tokenizer):
"""The read gate is OSS's own guarantee, not something a provider can opt out of.
An external provider is contractually only "information-preserving" (see
transforms/lossless_provider.py) — that admits json-min, which is exactly the
rewrite that misses the Edit. And the seam hands over `content` with no tool
name, so a provider *cannot* recognise a read and protect it itself. So the
gate sits in front of the seam: a read is never offered to a provider at all.
Every other excluded tool still reaches it, unchanged — the seam's reach
narrows for file reads only.
"""
seen: list[str] = []
set_lossless_provider(lambda content: (seen.append(content), None)[1])
for tool in ("Read", "read"):
seen.clear()
_run(GREP, tool, tokenizer)
assert seen == [], f"{tool} content was handed to the provider"
for tool in ("Grep", "grep", "Glob", "Write", "Edit"):
seen.clear()
_run(GREP, tool, tokenizer)
assert seen, f"provider lost reach for {tool}"
def test_provider_exception_falls_back_to_builtin():
def boom(content):
raise RuntimeError("provider blew up")
set_lossless_provider(boom)
# Falls back to the built-in fold rather than crashing or passing through raw.
out, kind = _compact(GREP)
assert kind == "search" and search_unheading(out) == GREP
# --- excluded path enforces the same provider contract as the general path ----
def _run_excluded_anthropic(tokenizer):
router = ContentRouter(ContentRouterConfig())
messages = [
{"role": "user", "content": "find it"},
{
"role": "assistant",
"content": [{"type": "tool_use", "id": "t1", "name": "Grep", "input": {}}],
},
{
"role": "user",
"content": [{"type": "tool_result", "tool_use_id": "t1", "content": GREP}],
},
]
result = router.apply(messages, tokenizer, compress_user_messages=True)
return result.messages[2]["content"][0]["content"], result.transforms_applied
def test_excluded_valid_two_tuple_still_applied(tokenizer):
set_lossless_provider(lambda content: ("compact", "myfold"))
out, applied = _run_excluded_anthropic(tokenizer)
assert out == "compact"
assert "router:excluded:lossless_myfold" in applied
def test_excluded_three_tuple_is_ignored_not_fatal(tokenizer):
set_lossless_provider(lambda content: ("compact", "k", "extra"))
out, applied = _run_excluded_anthropic(tokenizer)
assert out == GREP
assert not any(t.startswith("router:excluded:lossless_") for t in applied)
def test_excluded_empty_fold_leaves_content_unchanged(tokenizer):
set_lossless_provider(lambda content: (" ", "k"))
out, applied = _run_excluded_anthropic(tokenizer)
assert out == GREP
assert not any(t.startswith("router:excluded:lossless_") for t in applied)
def test_excluded_hostile_kind_is_replaced(tokenizer):
set_lossless_provider(lambda content: ("compact", "BAD LABEL{x=1}" + chr(10)))
out, applied = _run_excluded_anthropic(tokenizer)
assert out == "compact"
labels = [t for t in applied if t.startswith("router:excluded:lossless_")]
assert labels == ["router:excluded:lossless_provider"]