Files
headroom/tests/test_system_compaction.py
Tejas ChopraandClaude Opus 5 a2bf5ed1ba fix(cache): stop prefix transforms from busting the provider cache (#3735)
## Why

A `cache_control` marker means the provider has already hashed
everything up to and including that point, and is billing it at the
**cache-read rate (0.1x)**. Rewriting any of those bytes busts the entry
and re-bills the whole prefix at the **write rate (1.25x)** — a 12.5x
swing that dwarfs anything the transform saves.

Preserving the `cache_control` *field* does **not** preserve the
*entry*. The provider keys on content, not on the marker. A transform
that copies the marker onto rewritten text reads as cache-safe and is
not.

The arithmetic: if a transform invalidates the prefix, it has to cut
**>92%** of tokens just to break even against leaving the cache intact.
Real compaction cuts single-digit percentages. It is never worth it.

## What was wrong

**`compact_tool_descriptions`** truncated tool descriptions with no
marker check at all. A client that pinned any tool lost its entire tools
prefix — and every message behind it — to save a few hundred bytes.

**`_compact_system_blocks`** rewrote pinned system text and copied the
marker onto the new block. Its own docstring said "`cache_control` and
other non-text fields are preserved unchanged", which is true of the
field and misleading about the effect.

## What changed

- Tool-description compaction is skipped when any tool carries a marker.
This mirrors guards that already exist on
`_sort_tools_deterministically` and on `any_tool_has_cache_control` in
the Rust live zone — this path was simply missed.
- System compaction now compacts only blocks **after** the last
breakpoint, via a new `_last_cache_control_index` helper.

Both transforms behave exactly as before when the client pins nothing —
the common case, and the one they were written for. Neither is silent:
the skip logs `event=tool_desc_compaction_skipped`.

## Tests

New `tests/test_cache_prefix_safety.py` (7 tests) covers both
transforms: pinned content stays byte-identical, unpinned content still
compacts, and a marker on the final block is a full no-op.

Two existing expectations changed, deliberately:

- `test_preserves_cache_control` asserted that a pinned block is
compacted *and* keeps its marker — precisely the bug. Replaced by
`test_marked_block_is_left_byte_identical`, plus a new test that
compaction still runs after the breakpoint.
- `_make_anthropic_payload_with_long_system` had a single pinned block,
so the guard made it a no-op. It now carries a pinned block followed by
dynamic content — the shape agentic clients actually send — so the tests
still exercise compaction while asserting the pinned block survives.

318 related tests pass; `ruff check` and `ruff format --check` clean.

## Scope

Not addressed here, tracked separately:

- Savings accounting clamps every component at `max(…, 0)`
(`savings_tracker.py:958-965`) and never debits `cache_bust_tokens_lost`
from the headline, so a net-negative deployment reports a gain.
`cost.py:496` already computes the honest figure and nothing consumes
it.
- `normalize_message_cache_control` was investigated and left alone: the
client-mirroring path is correct, and the legacy fallback deliberately
consolidates accumulated replay leftovers (#2375). An earlier attempt to
"preserve" markers there broke five existing tests for good reasons.

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

---

### Known limitation — read before relying on this

Adversarial review after the fact found the guard is **narrower than
this description implies**. It is not a regression, but it does not
fully deliver what the title promises, and that is worth recording
rather than discovering later.

Anthropic evaluates the cache prefix in the order **tools → system →
messages**, so a marker in a *later* section freezes every *earlier*
one. Neither new guard accounts for that:

1. **`compact_tools` is unguarded** (`tool_schema_compaction.py`,
`compact_tools`). It strips `$schema`/`title`/`examples` and collapses
whitespace on every `input_schema`, and it runs **first, on the same
array**, one block above the guard that was added. Verified on this
branch: a tools array containing a `cache_control`-marked tool is still
rewritten, 436 → 374 bytes. A client that pins its tools still gets its
whole tools prefix rewritten.
2. **A marker in `system` or `messages` does not stop tool compaction**,
even though tools sit inside that prefix. The updated test in this PR
encodes exactly this: it pins `system[0]`, then asserts the tools were
compacted anyway — so the cached prefix is busted on the very request
where the new system guard carefully preserved `system[0]`
byte-for-byte.
3. **`_compact_system_blocks` ignores markers in `messages`.** A client
whose only breakpoint sits on the last user message has its whole system
array inside the cached prefix, yet `frozen_upto == -1` and every block
is rewritten. Fixing this needs a signature change — the function only
receives `blocks`, not the payload.

Net: this helps a client that pins **only** system, and buys little for
one that pins its tools. Fixing it properly requires cross-section
marker awareness, and the tools-side guard must be widened *after* (2)
is fixed, not before — widening it first makes things worse.

Merging as incremental progress with the limitation stated. Follow-up
tracked separately.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 22:39:33 +02:00

279 lines
8.9 KiB
Python

"""Tests for headroom.proxy.system_compaction — Layer 3 system-prompt compression.
Verifies that system-prompt compaction:
- compresses eligible (long) text blocks via a mock ContentRouter
- preserves short blocks, cache_control, and non-text blocks
- handles both string and content-blocks system field formats
- returns payload unchanged when compaction doesn't help
"""
from __future__ import annotations
from headroom.proxy.system_compaction import (
compact_system_prompt,
system_compact_enabled,
system_compact_min_chars,
)
class _MockCompressResult:
def __init__(self, compressed: str):
self.compressed = compressed
class _MockRouter:
"""Minimal mock of ContentRouter that shortens text by 50%."""
def compress(self, text: str, context: str = "", model: str = "") -> _MockCompressResult:
# Simple "compression": keep first half
half = len(text) // 2
return _MockCompressResult(text[:half])
class _NoopRouter:
"""Mock router whose compression never reduces size."""
def compress(self, text: str, context: str = "", model: str = "") -> _MockCompressResult:
# Return something longer than input
return _MockCompressResult(text + " expanded")
class _FailRouter:
"""Mock router that always raises."""
def compress(self, text: str, context: str = "", model: str = "") -> None:
raise RuntimeError("CCR unavailable")
class TestCompactSystemPromptContentBlocks:
"""Tests for content-blocks format (Anthropic standard)."""
def test_compresses_long_blocks(self) -> None:
payload = {
"model": "claude-sonnet-4-20250514",
"system": [
{"type": "text", "text": "A" * 1000},
{"type": "text", "text": "B" * 600},
],
"messages": [],
}
result, modified, before, after = compact_system_prompt(
payload,
router=_MockRouter(),
model="claude-sonnet-4-20250514",
request_id="test1",
)
assert modified is True
assert after < before
# Each block should be compressed
for block in result["system"]:
if block.get("type") == "text":
assert len(block["text"]) < 1000
def test_preserves_short_blocks(self) -> None:
"""Blocks shorter than min_chars should not be touched."""
payload = {
"system": [
{"type": "text", "text": "Short instruction."},
],
}
result, modified, _, _ = compact_system_prompt(
payload,
router=_MockRouter(),
model="m",
request_id="test2",
)
assert modified is False
assert result["system"][0]["text"] == "Short instruction."
def test_marked_block_is_left_byte_identical(self) -> None:
"""A cached block must not be rewritten, marker or not.
Preserving the ``cache_control`` field does not preserve the cache
entry: the provider keys on the content. Rewriting a block it has
already hashed re-bills the whole prefix at the write rate.
"""
payload = {
"system": [
{
"type": "text",
"text": "A" * 1000,
"cache_control": {"type": "ephemeral"},
},
],
}
result, modified, _, _ = compact_system_prompt(
payload,
router=_MockRouter(),
model="m",
request_id="test3",
)
assert modified is False
block = result["system"][0]
assert block["text"] == "A" * 1000
assert block["cache_control"] == {"type": "ephemeral"}
def test_compacts_after_the_breakpoint_and_keeps_the_marker(self) -> None:
"""Blocks past the last marker are still fair game."""
payload = {
"system": [
{
"type": "text",
"text": "A" * 1000,
"cache_control": {"type": "ephemeral"},
},
{"type": "text", "text": "B" * 1000},
],
}
result, modified, _, _ = compact_system_prompt(
payload,
router=_MockRouter(),
model="m",
request_id="test3b",
)
assert modified is True
assert result["system"][0]["text"] == "A" * 1000
assert result["system"][0]["cache_control"] == {"type": "ephemeral"}
assert result["system"][1]["text"] != "B" * 1000
def test_preserves_non_text_blocks(self) -> None:
payload = {
"system": [
{"type": "text", "text": "A" * 1000},
{"type": "image", "source": {"type": "base64", "data": "..."}},
],
}
result, modified, _, _ = compact_system_prompt(
payload,
router=_MockRouter(),
model="m",
request_id="test4",
)
assert modified is True
# Image block preserved unchanged
image_block = result["system"][1]
assert image_block["type"] == "image"
def test_noop_router_returns_unchanged(self) -> None:
payload = {
"system": [
{"type": "text", "text": "A" * 1000},
],
}
result, modified, _, _ = compact_system_prompt(
payload,
router=_NoopRouter(),
model="m",
request_id="test5",
)
assert modified is False
assert result is payload
def test_failing_router_returns_unchanged(self) -> None:
payload = {
"system": [
{"type": "text", "text": "A" * 1000},
],
}
result, modified, _, _ = compact_system_prompt(
payload,
router=_FailRouter(),
model="m",
request_id="test6",
)
assert modified is False
def test_no_system_field_returns_unchanged(self) -> None:
payload = {"model": "claude-sonnet-4-20250514", "messages": []}
result, modified, _, _ = compact_system_prompt(
payload,
router=_MockRouter(),
model="m",
request_id="test7",
)
assert modified is False
assert result is payload
def test_empty_system_list(self) -> None:
payload = {"system": []}
result, modified, _, _ = compact_system_prompt(
payload,
router=_MockRouter(),
model="m",
request_id="test8",
)
assert modified is False
def test_preserves_non_system_fields(self) -> None:
payload = {
"model": "claude-sonnet-4-20250514",
"max_tokens": 8192,
"system": [
{"type": "text", "text": "A" * 1000},
],
"messages": [{"role": "user", "content": "hi"}],
}
result, _, _, _ = compact_system_prompt(
payload,
router=_MockRouter(),
model="m",
request_id="test9",
)
assert result["model"] == "claude-sonnet-4-20250514"
assert result["max_tokens"] == 8192
assert len(result["messages"]) == 1
class TestCompactSystemPromptString:
"""Tests for string-format system field."""
def test_compresses_long_string(self) -> None:
payload = {
"system": "A" * 1000,
}
result, modified, before, after = compact_system_prompt(
payload,
router=_MockRouter(),
model="m",
request_id="test_s1",
)
assert modified is True
assert after < before
assert len(result["system"]) < 1000
def test_short_string_unchanged(self) -> None:
payload = {
"system": "Short instruction.",
}
result, modified, _, _ = compact_system_prompt(
payload,
router=_MockRouter(),
model="m",
request_id="test_s2",
)
assert modified is False
class TestEnvVarHelpers:
"""Tests for env-var configuration helpers."""
def test_system_compact_enabled_default(self, monkeypatch) -> None:
monkeypatch.delenv("HEADROOM_SYSTEM_COMPACT", raising=False)
# Force re-read
import headroom.proxy.system_compaction as sc
# The function reads env directly, so this should work
assert not sc.system_compact_enabled()
def test_system_compact_enabled_true(self, monkeypatch) -> None:
monkeypatch.setenv("HEADROOM_SYSTEM_COMPACT", "1")
assert system_compact_enabled()
def test_system_compact_min_chars_default(self, monkeypatch) -> None:
monkeypatch.delenv("HEADROOM_SYSTEM_COMPACT_MIN_CHARS", raising=False)
assert system_compact_min_chars() == 500
def test_system_compact_min_chars_custom(self, monkeypatch) -> None:
monkeypatch.setenv("HEADROOM_SYSTEM_COMPACT_MIN_CHARS", "200")
assert system_compact_min_chars() == 200