Files
headroom/tests/test_index_proof_table.py
Parideboy a385ea8e60 fix(benchmarks): drop the duplicate protect_recent=0 table from the proof harness (#4754)
## Description

`benchmarks/index_proof_table.py` printed two tables, "default
(protect_recent=4)" and "full corpus (protect_recent=0)". The committed
`benchmarks/results/index_proof_table.txt` showed them identical in
every row and in the total, so the second run and its label carried no
information — and the comment above them claimed the default "shields
almost every tool result", which the output contradicts.

They cannot ever differ. `ContentRouter` applies `protect_recent` only
to content detected as `SOURCE_CODE`:

```python
is_code = detection.content_type == ContentType.SOURCE_CODE
if protect_recent > 0 and messages_from_end <= protect_recent and is_code:
```

Every scenario in this harness is a JSON tool payload. All ten payloads
detect as `JSON_ARRAY` under **both** backends (pure-Python and
`HEADROOM_DETECT_BACKEND=rust`), so the guard never fires at any
`protect_recent` value. This is not a stale committed artifact that a
rerun would fix.

Of the three options on the issue, this takes the first: one table with
the limitation stated, rather than a duplicate or a behavior change to
the compressor.

Closes #4732

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [x] Documentation update

## Changes Made

- `benchmarks/index_proof_table.py`: print one table (the default
config) and replace the misleading comment with the actual reason the
`protect_recent` comparison is a no-op for JSON payloads.
- `benchmarks/results/index_proof_table.txt`: regenerated. The table
body is unchanged; the duplicate second table is gone.
- `tests/test_index_proof_table.py`: new output-level tests asserting
the harness prints exactly one table and that the docs Markdown block
states the config it was measured under. Both fail on the base revision
and pass with this change.
- `tests/test_transforms_content_router.py`: new
`test_protect_recent_does_not_shield_non_code_tool_payloads` pins the
router reason the two tables could never differ.
- `headroom/compress.py`: `CompressConfig.protect_recent` docstring said
"Don't compress the last N messages"; it guards recent **code** only.
- `docs/content/docs/context-management.mdx`,
`docs/content/docs/proxy.mdx`, `docs/content/docs/index.mdx`,
`README.md`: same overstatement corrected. The published table now names
the configuration it was measured under.

## Testing

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

### Test Output

```text
$ uv run pytest tests/test_index_proof_table.py tests/test_transforms_content_router.py -q
109 passed, 1 warning in 14.83s

$ uv run ruff check benchmarks/index_proof_table.py headroom/compress.py \
    tests/test_index_proof_table.py tests/test_transforms_content_router.py
All checks passed!

$ uv run ruff format --check tests/test_index_proof_table.py
1 file already formatted
```

Base-revision check for the new output tests (harness restored to
`318e8e08`):

```text
$ uv run pytest tests/test_index_proof_table.py -q
FAILED tests/test_index_proof_table.py::test_proof_table_prints_exactly_one_table
FAILED tests/test_index_proof_table.py::test_proof_markdown_block_is_the_default_config
2 failed in 5.15s
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.13.11, `uv` venv at the branch head
`9b7e2f95` (rebased onto `acb58a0c`); content detection ran on the
pure-Python backend (no ONNX Runtime 1.24+), and every payload was
re-checked under `HEADROOM_DETECT_BACKEND=rust`.
- Exact command / steps: `uv run python benchmarks/index_proof_table.py`
on the base revision, then the same command on this branch, then `git
diff` against the committed `benchmarks/results/index_proof_table.txt`.
- Observed result: base revision printed two tables identical in all
four rows and in the total (178,024 → 104,261, 41%). This branch prints
one table with the same numbers, and its output matches the committed
result file byte for byte once the first line is excluded (that line
names whichever detector backend the host has).
- Not tested: whether the committed numbers would change under the
native detector — also left open on the issue. They do not: both
backends classify all ten payloads as `JSON_ARRAY`, so detection routes
them identically.

## Runtime Rollout Safety

- Rollout-managed feature(s): none. Only a benchmark script, its
committed output, tests, and docs change.
- Minimum rollout channel: stable, no gating.
- Stable/default behavior changed: no. `ContentRouter`,
`CompressConfig`, and `compress()` behavior are untouched; only a
docstring and documentation prose changed. The published table's numbers
are identical to before.
- Kill switch / disable path: not applicable.
`benchmarks/index_proof_table.py` is a manual, offline script with no
runtime surface.
- Unsafe override required: no.
- Qualification impact: none. Serialization, caching, and compression
output are unchanged; the new tests are offline and stubbed.
- Rollback path: revert this commit. The harness returns to printing the
duplicate table; no state or migration is involved.

## 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
- [x] 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)

## Additional Notes

`mypy headroom` left unchecked: the touched Python files add no type
surface beyond a benchmark script and a test module, and mypy was not
run locally.

Review feedback addressed: the initial version of this PR added only a
router-level test, which passes on the base revision and so could not
catch the duplicate table returning. The two output-level tests in
`tests/test_index_proof_table.py` replace that gap, and the
base-revision failure above is their proof. The `context-management.mdx`
file-read claim was also too broad — read protection releases
confidently non-code data (JSON, CSV/tabular, build/test logs, git
diffs, HTML, search output), so the wording now says so.

`CHANGELOG.md` is untouched, per CONTRIBUTING.


The branch was rebased onto `acb58a0c` (4 upstream commits: #4727,
#4728, #4735, #4743) with no file overlap. Re-verified after the rebase:
109 focused tests pass, `ruff check`/`format --check` clean.
`benchmarks/index_proof_table.py` is byte-identical between `318e8e08`
and `acb58a0c`, so the base-revision failure above still applies
unchanged.
2026-11-10 12:35:38 -06:00

109 lines
3.9 KiB
Python

"""The proof table printed for the docs must stay a single, labelled table (#4732).
``benchmarks/index_proof_table.py`` used to print "default (protect_recent=4)"
and "full corpus (protect_recent=0)". Both tables were identical in every row,
because ``ContentRouter`` applies ``protect_recent`` only to content detected as
SOURCE_CODE and every scenario here is a JSON payload
(``tests/test_transforms_content_router.py::
test_protect_recent_does_not_shield_non_code_tool_payloads`` pins that reason).
The second table could therefore never differ, so it was removed.
These tests pin the OUTPUT, not the compression: everything expensive is
monkeypatched away, so they stay fast and offline.
"""
from __future__ import annotations
import sys
import types
from pathlib import Path
from typing import Any
import pytest
BENCHMARKS_DIR = Path(__file__).resolve().parents[1] / "benchmarks"
SCENARIOS = (
"Code search (100 results)",
"SRE incident debugging",
"Codebase exploration",
"GitHub issue triage",
)
@pytest.fixture
def harness(monkeypatch: pytest.MonkeyPatch) -> types.ModuleType:
"""Import the harness with its corpus generators and compression stubbed out."""
# The harness imports `real_world_agent_benchmark` as a sibling module, which
# only resolves when it is run as a script with `benchmarks/` on sys.path.
monkeypatch.syspath_prepend(str(BENCHMARKS_DIR))
sys.modules.pop("benchmarks.index_proof_table", None)
module = pytest.importorskip("benchmarks.index_proof_table")
class _FakeTokenizer:
_tokenizer = object()
def __init__(self, model: str | None = None) -> None:
self.model = model
numbers = {"before": 1_000, "after": 500}
def _fake_measure(label: str, tools: list[dict], tok: Any, config: Any) -> dict:
return {
"scenario": label,
"before": numbers["before"],
"after": numbers["after"],
"saved": numbers["before"] - numbers["after"],
"savings_pct": 50.0,
"transforms": [],
}
tool = {"result": [{"path": "src/a.py", "score": 1}]}
monkeypatch.setattr(module, "seed_everything", lambda seed: seed)
monkeypatch.setattr(module, "measure", _fake_measure)
monkeypatch.setattr(module, "OpenAICompatibleTokenCounter", _FakeTokenizer)
monkeypatch.setattr(module, "generate_github_code_search", lambda *a, **k: tool)
monkeypatch.setattr(
module,
"create_sre_debugging_scenario",
lambda: types.SimpleNamespace(tools=[tool]),
)
monkeypatch.setattr(
module,
"create_codebase_exploration_scenario",
lambda: types.SimpleNamespace(tools=[tool]),
)
monkeypatch.setattr(
module,
"create_issue_triage_scenario",
lambda: types.SimpleNamespace(tools=[tool]),
)
return module
def test_proof_table_prints_exactly_one_table(
harness: types.ModuleType, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
"""A second configuration re-introduces a table that can only duplicate the first."""
monkeypatch.setattr(sys, "argv", ["index_proof_table.py", "--seed", "20260902"])
assert harness.main() == 0
out = capsys.readouterr().out
assert out.count("=== default (protect_recent=4) ===") == 1, out
assert "protect_recent=0" not in out
def test_proof_markdown_block_is_the_default_config(
harness: types.ModuleType, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
"""The block pasted into the docs must state the config it was measured under."""
monkeypatch.setattr(sys, "argv", ["index_proof_table.py", "--seed", "20260902"])
assert harness.main() == 0
out = capsys.readouterr().out
assert "Markdown for docs/content/docs/index.mdx (default config" in out
markdown = out.split("Markdown for docs/content/docs/index.mdx", 1)[1]
for scenario in SCENARIOS:
assert f"| {scenario} | 1,000 | 500 | **50%** |" in markdown