mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-12-03 02:16:29 +08:00
## Description Since the non-inflation size bound added in #3052 (shipped 0.36.x), the Anthropic proxy token path repeatedly busts the provider prompt cache: the bound declines the cached-prefix replay exactly when background compression lands a SMALLER form of an already-forwarded message, so the forwarded bytes change mid-history and the provider cache misses from the first changed byte. Steady state on a busy session is a 160-210k-token cache re-write every 1-2 requests (measured across a 0.35.0 -> 0.37.0 swap on identical workload: dollar cache-hit rate 90% -> 52%, billable input $/M up 2.2x; full data in #3379). Reworked per review (thanks @chopratejas - the direction is yours): rather than disabling the size bound wholesale, `overlay_cached_prefix` now takes `confirmed_frozen_count` and splits at that floor. - Inside the provider-confirmed prefix: replay is unconditional. The replay source is exactly what the provider hashed, so changing those bytes can only bust the cache; an "inflating" replay there bills at the ~0.1x cache-read rate and is still the cheaper request. - Beyond the floor: the size bound arbitrates each turn exactly as on main - a shrinking replay repairs freeze drift (#1850), an inflating one is declined so a fresh compression improvement reaches the wire. - When the provider count collapses (cold cache, TTL lapse) the floor collapses with it and every accumulated improvement lands at once: the natural re-baselining that bounds long-session growth (the #3026 direction of travel) by the TTL-lapse cadence instead of pinning forever. The #3052 alignment/append-only guards stay enforced unconditionally. The OpenAI chat path now carries the same floor (reviewer question: is the root cause live there too?). It is: the tracker is provider-generic and is fed OpenAI's own `prompt_tokens_details.cached_tokens`, the forwarded-bytes feedback loop is identical, both handlers compress through the same ContentRouter, and OpenAI's automatic prompt caching busts on the first changed byte exactly like Anthropic's. Exposure is narrower - the token path's `FREEZE_POLICY_REPLAYABLE` already stops most recompression of already-forwarded messages - but not zero: an entry evicted from the local byte-replay cache drops out of that freeze, and cache mode freezes from the tracker only. Remaining callers with no provider-confirmed count in scope (sidecar, `openai.py:9940`) pass nothing and keep today's fully size-bounded behavior; `bedrock.py` / `gemini.py` never call `finalize_turn` at all, tracked in #3391. Closes #3379 ## 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 - `overlay_cached_prefix` gains keyword-only `confirmed_frozen_count: int | None = None`: an unconditional-replay floor for the provider-confirmed prefix; the size bound still governs everything beyond it, and alignment guards are untouched. - `finalize_turn` forwards the floor (default `None`, so all existing callers are unchanged). - The OpenAI chat call site passes the same floor, snapshotted before `prepare_turn`'s replayable clamp (that count runs over the LOCAL byte-replay cache and can exceed what the provider confirmed; a cold prefix zeroes it, so cold re-baselining matches Anthropic's). - The Anthropic confirmed-clamp call site stashes the pre-clamp tracker count (the post-`prepare_turn` min under-floors when the local byte-replay cache evicted entries) and passes it; the stash defaults to 0 on paths that never compute a tracker count (backpressure). - Tests: floor replays a recompressed confirmed prefix; improvement beyond the floor lands while the confirmed region replays; originals-drift beyond the floor is still repaired when the replay shrinks; alignment guards unaffected by the floor; block-append within the floor; `finalize_turn` pass-through; the reviewer-requested multi-turn harness test - a background improvement to an already-forwarded message never busts the warm cache across 8 turns and lands on the first cold turn; the reviewer-requested growth bound - forwarded size grows by only its own delta each warm turn and the first cold turn re-baselines to exactly the fresh pipeline's output; and an end-to-end OpenAI chat test asserting the provider-confirmed prefix is replayed even when the replay inflates (fails without the new argument). ## 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 ### Test Output ```text $ uv run --frozen --extra dev pytest tests/test_cache_prefix_overlay.py tests/test_session_engine.py tests/test_cross_turn_cache_safety.py tests/test_cache_control_move_bust.py -q ============================== 58 passed in 0.44s ============================== $ uvx ruff check headroom/cache/prefix_tracker.py headroom/proxy/session_engine.py headroom/proxy/handlers/anthropic.py tests/test_cache_prefix_overlay.py tests/test_session_engine.py tests/test_cross_turn_cache_safety.py All checks passed! $ uv run --frozen --extra dev mypy headroom/cache/prefix_tracker.py headroom/proxy/session_engine.py Success: no issues found in 2 source files ``` ## Real Behavior Proof - Environment: macOS 15 (arm64), Python 3.12; regression measured on the released headroom-ai 0.37.0 under real Claude Code traffic through `headroom proxy` (token mode); this branch validated with the repo test suite. - Exact command / steps: diffed per-request PERF logs across a 0.35.0 -> 0.37.0 swap on the same machine and workload (sequences and aggregates in #3379); then ran the pytest/ruff/mypy commands above on this branch. A deployment carrying the unconditional-replay behavior on the confirmed prefix restored the healthy pattern live: the broken wheel capped cached reads at 157k across 32 large requests (prefix perpetually re-written) while the patched deployment accumulated to 305k cached reads within 15 minutes. - Observed result: 58 passed including the new multi-turn harness test; on stock 0.37.0 every background-compression completion produced a cache_read collapse to the ~7.7k tools+system head plus a 160-210k cache_write. - Not tested: a live OpenAI `cached_tokens` comparison for the OpenAI half (the Anthropic measurement is what #3379 carries; the OpenAI change is argued from shared mechanism plus an end-to-end handler test, not from its own dollar data). A live provider run of this exact branch (the wheel comparison plus the live patched-deployment measurement isolate the bound as the trigger; the unit and multi-turn regressions reproduce decline and fix deterministically). `mypy headroom` was run only on the two touched modules, not the whole package. ## Runtime Rollout Safety - Rollout-managed feature(s): None. - Minimum rollout channel: Stable. - Stable/default behavior changed: On the Anthropic proxy confirmed-clamp path and the OpenAI chat path, both of which now replay the provider-confirmed prefix unconditionally (the pre-0.36 posture) while keeping the size bound beyond the confirmed floor. The overlay's default and every other caller keep the fully size-bounded behavior. - Kill switch / disable path: remove the `confirmed_frozen_count=` argument at the two call sites (anthropic.py, openai.py chat); the parameter defaults to `None`. - Unsafe override required: No. - Qualification impact: None. - Rollback path: Revert the commits; the parameter is additive and default-preserving. ## 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) ## Screenshots (if applicable) Not applicable. ## Additional Notes Lineage for review: #1850 made freeze forward the cached prefix byte-identical, #3052 added alignment guards plus the size bound after #3026's misalignment blowup, #3271 unified both modes on the session engine. The first cut of this PR disabled the bound on the confirmed-clamp path wholesale; the reviewed rework scopes unconditional replay to the provider-confirmed prefix, which additionally gives cold-lapse re-baselining (improvements land whenever the floor collapses), addressing the growth analysis raised in review. Economics discussion in the review thread. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
318 lines
13 KiB
Python
318 lines
13 KiB
Python
# ruff: noqa: E402 — test sections import after helper/setup code by design.
|
|
"""overlay_cached_prefix: freeze must forward the CACHED (compressed) bytes.
|
|
|
|
The freeze path can emit the agent's ORIGINAL bytes for a frozen message, but
|
|
the provider cached whatever we FORWARDED last turn (the compressed form).
|
|
Forwarding original then mismatches the cached prefix and busts the prompt cache
|
|
(observed: 100% of misses were this ``prefix_change``, ~56% of all cache-writes).
|
|
``overlay_cached_prefix`` replays the previously-forwarded prefix byte-identical
|
|
so the cache still hits — in BOTH proxy modes.
|
|
"""
|
|
|
|
import copy
|
|
|
|
from headroom.cache.prefix_tracker import overlay_cached_prefix
|
|
|
|
|
|
def M(role, text):
|
|
return {"role": role, "content": text}
|
|
|
|
|
|
# Previous turn: 2 messages. Original was big; we FORWARDED the compressed form,
|
|
# so that compressed form is what the provider cached.
|
|
PREV_ORIG = [M("user", "READ foo.py:\n<2000 original lines>"), M("assistant", "ok")]
|
|
PREV_FWD = [M("user", "READ foo.py:\n<compressed>"), M("assistant", "ok")]
|
|
# This turn: agent appended one new message (append-only growth).
|
|
CUR_ORIG = PREV_ORIG + [M("user", "grep result:\n<800 original lines>")]
|
|
# What apply() produced in the buggy freeze path: ORIGINAL bytes for the frozen
|
|
# prefix (== PREV_ORIG) + compressed new tail.
|
|
OPTIMIZED_BUGGY = [PREV_ORIG[0], PREV_ORIG[1], M("user", "grep result:\n<compressed>")]
|
|
|
|
|
|
def test_replays_cached_compressed_prefix_byte_identical():
|
|
out = overlay_cached_prefix(OPTIMIZED_BUGGY, CUR_ORIG, PREV_ORIG, PREV_FWD)
|
|
# The frozen prefix now equals what the provider cached (compressed), NOT the
|
|
# agent's original bytes → cache hits instead of busting.
|
|
assert out[:2] == PREV_FWD
|
|
assert out[:2] != PREV_ORIG
|
|
# This turn's compressed tail is preserved.
|
|
assert out[2] == OPTIMIZED_BUGGY[2]
|
|
assert len(out) == len(CUR_ORIG)
|
|
|
|
|
|
def test_is_a_noop_relative_to_cache_when_already_correct():
|
|
# If the freeze path already forwarded the compressed (cached) prefix, the
|
|
# overlay reproduces exactly that — idempotent.
|
|
already_correct = [PREV_FWD[0], PREV_FWD[1], M("user", "grep result:\n<compressed>")]
|
|
out = overlay_cached_prefix(already_correct, CUR_ORIG, PREV_ORIG, PREV_FWD)
|
|
assert out == already_correct
|
|
|
|
|
|
def test_not_append_only_returns_unchanged():
|
|
# An early message changed → previous forwarded bytes may not correspond to
|
|
# the same positions; do NOT overlay (accept a possible bust over corruption).
|
|
changed = [M("user", "TOTALLY DIFFERENT"), PREV_ORIG[1], M("user", "x")]
|
|
out = overlay_cached_prefix(OPTIMIZED_BUGGY, changed, PREV_ORIG, PREV_FWD)
|
|
assert out == OPTIMIZED_BUGGY
|
|
|
|
|
|
def test_no_previous_state_returns_unchanged():
|
|
assert overlay_cached_prefix(OPTIMIZED_BUGGY, CUR_ORIG, None, None) == OPTIMIZED_BUGGY
|
|
assert overlay_cached_prefix(OPTIMIZED_BUGGY, CUR_ORIG, [], []) == OPTIMIZED_BUGGY
|
|
|
|
|
|
def test_forwarded_count_mismatch_returns_unchanged():
|
|
# Defensive: not exactly one forwarded message per original → bail.
|
|
assert (
|
|
overlay_cached_prefix(OPTIMIZED_BUGGY, CUR_ORIG, PREV_ORIG, PREV_FWD[:1]) == OPTIMIZED_BUGGY
|
|
)
|
|
|
|
|
|
def test_shorter_current_or_optimized_returns_unchanged():
|
|
assert overlay_cached_prefix([M("user", "x")], [M("user", "x")], PREV_ORIG, PREV_FWD) == [
|
|
M("user", "x")
|
|
]
|
|
|
|
|
|
def test_overlay_requires_positional_alignment_with_originals():
|
|
optimized = [M("user", "x")]
|
|
current = [M("user", "x"), M("assistant", "ok")]
|
|
assert overlay_cached_prefix(optimized, current, PREV_ORIG, PREV_FWD) == optimized
|
|
|
|
optimized = [M("user", "x"), M("assistant", "ok"), M("user", "tail")]
|
|
current = [M("user", "x"), M("assistant", "ok")]
|
|
previous = [M("user", "x"), M("assistant", "ok")]
|
|
forwarded = [M("user", "compressed"), M("assistant", "ok")]
|
|
assert overlay_cached_prefix(optimized, current, previous, forwarded) == optimized
|
|
|
|
|
|
def test_overlay_never_inflates_forwarded_payload():
|
|
optimized = [M("user", "small"), M("assistant", "ok"), M("user", "tail")]
|
|
inflated_forwarded = [M("user", "x" * 1000), M("assistant", "ok")]
|
|
previous = [M("user", "small"), M("assistant", "ok")]
|
|
current = previous + [M("user", "tail")]
|
|
assert overlay_cached_prefix(optimized, current, previous, inflated_forwarded) == optimized
|
|
|
|
|
|
def test_overlay_returns_optimized_when_json_sizing_fails(monkeypatch):
|
|
optimized = [M("user", "stable"), M("user", "tail")]
|
|
current = [M("user", "stable"), M("user", "tail")]
|
|
previous = [M("user", "stable")]
|
|
forwarded = [M("user", "compressed")]
|
|
|
|
monkeypatch.setattr(
|
|
"headroom.cache.prefix_tracker.json.dumps",
|
|
lambda *args, **kwargs: (_ for _ in ()).throw(TypeError("cannot size")),
|
|
)
|
|
|
|
assert overlay_cached_prefix(optimized, current, previous, forwarded) == optimized
|
|
|
|
|
|
def test_overlay_never_inflates_cache_control_only_replay():
|
|
previous = [M("user", "stable"), M("assistant", "ok")]
|
|
current = [
|
|
M("user", "stable"),
|
|
{**M("assistant", "ok"), "cache_control": {"type": "ephemeral"}},
|
|
]
|
|
optimized = copy.deepcopy(current)
|
|
inflated_forwarded = [M("user", "x" * 1000), M("assistant", "ok")]
|
|
assert overlay_cached_prefix(optimized, current, previous, inflated_forwarded) == optimized
|
|
|
|
|
|
def test_block_append_overlay_never_inflates_forwarded_payload():
|
|
previous = [
|
|
{
|
|
"role": "user",
|
|
"content": [{"type": "text", "text": "stable"}],
|
|
}
|
|
]
|
|
current = [
|
|
{
|
|
"role": "user",
|
|
"content": [
|
|
{"type": "text", "text": "stable"},
|
|
{"type": "text", "text": "tail"},
|
|
],
|
|
}
|
|
]
|
|
optimized = copy.deepcopy(current)
|
|
forwarded = [
|
|
{
|
|
"role": "user",
|
|
"content": [{"type": "text", "text": "x" * 1000}],
|
|
}
|
|
]
|
|
assert overlay_cached_prefix(optimized, current, previous, forwarded) == optimized
|
|
|
|
|
|
def test_confirmed_floor_replays_recompressed_confirmed_prefix():
|
|
# Background recompression produced a SMALLER form of already-forwarded,
|
|
# provider-CONFIRMED history. The floor replays the confirmed bytes
|
|
# unconditionally; without a floor the size bound declines the replay and
|
|
# the cache busts the moment compression improves.
|
|
recompressed = [
|
|
M("user", "READ foo.py:\n<tiny>"),
|
|
M("assistant", "ok"),
|
|
M("user", "grep result:\n<compressed>"),
|
|
]
|
|
out = overlay_cached_prefix(
|
|
recompressed, CUR_ORIG, PREV_ORIG, PREV_FWD, confirmed_frozen_count=2
|
|
)
|
|
assert out[:2] == PREV_FWD # confirmed bytes win over the smaller fresh form
|
|
assert out[2] == recompressed[2] # this turn's tail is preserved
|
|
# No floor: the same replay is declined as inflating (sidecar posture).
|
|
assert overlay_cached_prefix(recompressed, CUR_ORIG, PREV_ORIG, PREV_FWD) == recompressed
|
|
|
|
|
|
def test_confirmed_floor_keeps_alignment_guards():
|
|
# The floor relaxes ONLY the size bound; every alignment guard still bails.
|
|
changed = [M("user", "TOTALLY DIFFERENT"), PREV_ORIG[1], M("user", "x")]
|
|
assert (
|
|
overlay_cached_prefix(
|
|
OPTIMIZED_BUGGY, changed, PREV_ORIG, PREV_FWD, confirmed_frozen_count=2
|
|
)
|
|
== OPTIMIZED_BUGGY
|
|
)
|
|
assert (
|
|
overlay_cached_prefix(
|
|
OPTIMIZED_BUGGY, CUR_ORIG, PREV_ORIG, PREV_FWD[:1], confirmed_frozen_count=2
|
|
)
|
|
== OPTIMIZED_BUGGY
|
|
)
|
|
|
|
|
|
def test_improvement_beyond_floor_lands_while_confirmed_region_replays():
|
|
# Three previously-forwarded messages; only the first is provider-confirmed.
|
|
prev_orig = [
|
|
M("user", "old tool output " * 20),
|
|
M("user", "newer output"),
|
|
M("assistant", "ok"),
|
|
]
|
|
prev_fwd = [M("user", "[fwd-old-form-larger]"), M("user", "[fwd-newer]"), M("assistant", "ok")]
|
|
current = prev_orig + [M("user", "next")]
|
|
# Fresh compression improved BOTH forwarded forms. Only the beyond-floor
|
|
# improvement may land; the confirmed one would change provider bytes.
|
|
optimized = [
|
|
M("user", "[t0]"),
|
|
M("user", "[t1]"),
|
|
M("assistant", "ok"),
|
|
M("user", "next"),
|
|
]
|
|
out = overlay_cached_prefix(optimized, current, prev_orig, prev_fwd, confirmed_frozen_count=1)
|
|
assert out[0] == prev_fwd[0] # confirmed region: replayed unconditionally
|
|
assert out[1] == optimized[1] # improvement beyond the floor reaches the wire
|
|
assert out[3] == optimized[3]
|
|
|
|
|
|
def test_originals_drift_beyond_floor_still_repaired_when_replay_shrinks():
|
|
# The pipeline emitted the agent's ORIGINAL bytes beyond the floor (the
|
|
# #1850 freeze-drift case). The replay shrinks, the size bound passes, and
|
|
# the repair still covers the WHOLE prefix - the floor only decides the
|
|
# split when the bound would otherwise decline.
|
|
out = overlay_cached_prefix(
|
|
OPTIMIZED_BUGGY, CUR_ORIG, PREV_ORIG, PREV_FWD, confirmed_frozen_count=1
|
|
)
|
|
assert out[:2] == PREV_FWD
|
|
|
|
|
|
def test_block_append_within_confirmed_floor_replays_forwarded_blocks():
|
|
previous = [{"role": "user", "content": [{"type": "text", "text": "stable"}]}]
|
|
forwarded = [{"role": "user", "content": [{"type": "text", "text": "x" * 500}]}]
|
|
current = [
|
|
{
|
|
"role": "user",
|
|
"content": [{"type": "text", "text": "stable"}, {"type": "text", "text": "new"}],
|
|
}
|
|
]
|
|
optimized = copy.deepcopy(current)
|
|
out = overlay_cached_prefix(optimized, current, previous, forwarded, confirmed_frozen_count=1)
|
|
assert out[0]["content"][0]["text"] == "x" * 500
|
|
assert out[0]["content"][1]["text"] == "new"
|
|
|
|
|
|
def test_cache_hit_property_prefix_matches_last_forward():
|
|
# The invariant that guarantees a cache hit: forwarded[:n] this turn ==
|
|
# forwarded[:n] last turn (== what the provider cached).
|
|
out = overlay_cached_prefix(OPTIMIZED_BUGGY, CUR_ORIG, PREV_ORIG, PREV_FWD)
|
|
n = len(PREV_FWD)
|
|
assert out[:n] == PREV_FWD # exact byte-identical prefix → provider cache hit
|
|
|
|
|
|
# ============================================================================
|
|
# OpenAI function-calling frozen-count: tool_calls must be counted (Kimi bug)
|
|
# ============================================================================
|
|
# _estimate_message_tokens only counted `content` + Anthropic content-blocks,
|
|
# never OpenAI top-level `tool_calls`. So a function-calling assistant turn
|
|
# (content None, command in tool_calls) estimated to ~0, the frozen-prefix
|
|
# estimate overshot the real cache boundary, and the NEWEST delta got frozen —
|
|
# giving OpenAI/Kimi tool harnesses ~zero compression. These lock in the fix.
|
|
import json as _json
|
|
|
|
from headroom.cache.prefix_tracker import PrefixCacheTracker, PrefixFreezeConfig
|
|
|
|
|
|
def _openai_asst(cmd):
|
|
return {
|
|
"role": "assistant",
|
|
"content": None,
|
|
"tool_calls": [
|
|
{
|
|
"id": "c1",
|
|
"type": "function",
|
|
"function": {"name": "bash", "arguments": _json.dumps({"command": cmd})},
|
|
}
|
|
],
|
|
}
|
|
|
|
|
|
def test_estimate_counts_openai_tool_calls():
|
|
est = PrefixCacheTracker._estimate_message_tokens
|
|
cmd = "cd /tmp/core && cat suma/apps/underwriting/followup/service.py"
|
|
with_calls = est([_openai_asst(cmd)])[0]
|
|
# empty content + no tool_calls counted => only the +20 overhead (~5 tok)
|
|
bare = est([{"role": "assistant", "content": None}])[0]
|
|
assert with_calls > bare + 5, (with_calls, bare) # the command is now counted
|
|
# legacy function_call shape too
|
|
fc = est(
|
|
[
|
|
{
|
|
"role": "assistant",
|
|
"content": None,
|
|
"function_call": {"name": "bash", "arguments": _json.dumps({"command": cmd})},
|
|
}
|
|
]
|
|
)[0]
|
|
assert fc > bare + 5, (fc, bare)
|
|
|
|
|
|
def test_frozen_count_leaves_openai_tool_delta_mutable():
|
|
# A tool-based turn: cached prefix (system+task+prior tool obs) then a NEW
|
|
# assistant tool_call + its observation. After update_from_response reports
|
|
# the prefix cached, the frozen count must NOT swallow the newest delta.
|
|
trk = PrefixCacheTracker("openai", PrefixFreezeConfig(min_cached_tokens=10))
|
|
msgs = [
|
|
{"role": "system", "content": "s" * 400},
|
|
{"role": "user", "content": "task " * 200},
|
|
_openai_asst("cd /tmp/core && rg -n foo ."),
|
|
{"role": "tool", "tool_call_id": "c1", "content": "hit\n" * 300}, # cached prefix ends here
|
|
_openai_asst("cd /tmp/core && cat foo.py"), # NEW delta (assistant)
|
|
{
|
|
"role": "tool",
|
|
"tool_call_id": "c1",
|
|
"content": "code\n" * 400,
|
|
}, # NEW delta (observation)
|
|
]
|
|
counts = PrefixCacheTracker._estimate_message_tokens(msgs)
|
|
# cache_read ~= the first 4 messages' real tokens (prefix cached)
|
|
cached_prefix_tokens = sum(counts[:4])
|
|
trk.update_from_response(
|
|
cache_read_tokens=cached_prefix_tokens,
|
|
cache_write_tokens=0,
|
|
messages=msgs,
|
|
message_token_counts=counts,
|
|
)
|
|
frozen = trk.get_frozen_message_count()
|
|
# must freeze ~the cached prefix (<=4), NOT the whole 6 (which would freeze
|
|
# the newest observation delta and block all compression).
|
|
assert frozen <= 4, f"frozen={frozen} swallowed the delta (len={len(msgs)})"
|