Commit Graph
2 Commits
Author SHA1 Message Date
Tejas ChopraandClaude Opus 5 a6a9cef945 fix(cache): stop skipping tool compaction on a pinned tools array (#3750)
Follow-up to #3735, which I reviewed against the real API before
extending. The extension turned out to be the wrong move — the guard
itself is.

## The hole in the original reasoning

#3735 skipped tool-description compaction whenever any tool carried a
`cache_control` marker, on the grounds that *"a marker means the
provider hashed these bytes, so rewriting them re-bills the prefix."*

**The provider never saw the client's bytes.** It only ever sees ours.
Compaction is a pure deterministic transform over a fixed key set, so
turn 2 sends exactly what turn 1 cached — and hits.

## Measured

30 pinned tools, 6 turns, each run salted so they cannot share cache
(haiku-4-5):

| | turn 0 | turns 1–5 | billed prefix |
|---|---|---|---|
| always raw (the guard) | write 12,536 | read 12,536 ×5 | **21,938** |
| always compacted | write 8,726 | read 8,726 ×5 | **15,270** |

The guard made the cached prefix **30% larger for the life of every
session that pins its tools**, and every single read paid it — to avoid
a bust that never occurred.

## The hazard that *is* real, and why it doesn't justify the guard

Inconsistency — compacting on some turns and not others, which
`_decision.should_compress` can produce via a per-request
`x-headroom-bypass` header or a license gate flipping mid-session.

That's bounded. Anthropic keeps **both** prefixes alive, so alternating
turns each hit their own entry:

```
TOGGLING   turn 0  write 12,506
           turn 1  write  8,666
           turn 2  read  12,506
           turn 3  read   8,666      <- alternating hits, not busts
```

One extra write, once — not a bust per flip. Not worth a permanent 30%
tax.

## What this changes

* Removes the marker guard from `compact_tool_descriptions`.
* Leaves `compact_tools` (layer 1) unguarded **deliberately**. Extending
the guard there was the obvious symmetry and is what I started with; it
would have made things worse, because `normalize_message_cache_control`
runs *before* compaction, so the guard would have seen the breakpoint
**Headroom itself placed** and disabled tool compaction on essentially
every request.
* **Keeps the system-prompt guard from #3735 untouched.** The
determinism argument is specific to a pure byte transform; system
compaction goes through a pluggable compressor I have not established to
be deterministic.

## Testing

Byte-stability is now **asserted, not assumed** —
`test_compaction_is_byte_stable_across_calls` fails if compaction ever
stops being deterministic, which is the condition that would require the
guard back. 1125 tests pass across the compaction, cache-prefix,
transform and byte-faithful-forwarding suites; ruff clean.

Reproduction script used for the numbers is in the session scratchpad
(`compaction_cache.py`).

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

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 00:24:26 +02:00
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