Repository navigation
feat(cache): solve cacheinject's placement policy and split the volatile system tail - #22
Merged
Merged
Conversation
…ile system tail
Two changes to how context-guru handles prompt caching, both driven by measurement on
real captured traffic rather than by heuristic.
1. cacheinject's placement policy is now the solution to the billed-cost
minimisation rather than a guess.
With R=0.1 (cache read), W=1.25 (5m write) and 1.0 (uncached) as multipliers on the
base input rate, four inequalities fix the policy:
* a token resent k more times is cheaper written when W + kR < 1 + k, i.e.
k > (W-1)/(1-R) = 0.28 -- so always breakpoint the LAST block;
* writes bill as a SPAN (highest breakpoint minus read point), not per
breakpoint, so an extra breakpoint below the top costs exactly zero and none of
the four slots should sit idle;
* a divergence at block d makes everything above it unmatchable, so anchoring at
d-1 recovers 0.9 per token -- worth 12.5x more than positional tuning because
it restores read->read rather than read->write;
* an anchor must sit at a turn-STABLE index, since a position is only readable on
turn t+1 if it was written on turn t.
The previous policy put its breakpoint on the message BEFORE the newest turn, which
shortens the cached prefix every turn: +5.50% standalone and +9.21% layered on an
agent that sets its own breakpoints, simulated on a stream calibrated to within
2.10pp of a live run's billed cache-hit rate. Its docs called the savings
"invisible to /stats", which made a negative effect unfalsifiable.
Against Claude Code this policy correctly places NOTHING: acted=0 across 69 live
runs, because claude-code already marks its own final message on 98.7% of requests.
Its value here is not losing the 5.5%; it earns its keep on agents that do not mark
their own tail, or whose prefix mutates mid-conversation.
TTL is configurable (ttl: 5m|1h, validated at load). A 1h write costs 2.0x instead
of 1.25x and only pays when P(entry lapses before reuse) > 83.3%; measured over
1,905 real turns that probability is ~0 and reads refresh the TTL for free, so 5m
stays the default.
2. A body-level volatile-tail split, gated on cacheinject being configured so it adds
no new config surface.
Claude Code appends live git state to the END of its main system block. That block
is 7,037 tokens whose first 6,877 (97.7%) are byte-identical across sessions, but it
is one cacheable unit with its breakpoint after the churn, so the shared part is
re-written every session. Splitting into [stable][volatile] with the breakpoint on
the stable half is byte-identical in concatenation, so the model sees the same
prompt.
Measured four ways:
* structural: across 50 real sessions the stable half takes 1 distinct value,
the volatile tail 50 -- so the breakpoint hash was unique per session;
* mechanical: through the live proxy, system blocks 3->4, concatenation
byte-identical, breakpoints 2->2 (no slot consumed);
* isolated live A/B (two sessions differing only in the git snapshot, judged by
cache_read_input_tokens): session-2 read 0 -> 8,597 and write 8,882 -> 0,
identical across three runs. Hit 0.0% -> 96.7%. At Sonnet 5 rates that first
request of a warm session costs $0.022205 -> $0.001719, i.e. $0.0205 saved per
session (-92.3%); $0.0512 on Opus 5;
* end-to-end: Terminal-Bench fix-code-vulnerability over 3 sequential trials,
$0.1945 -> $0.1282 mean, $0.0663 saved per run (34.1%), cache-write median
-58.8%, cost median -34.5% with a 4.4pp spread.
The saving is once per session, not once per turn: within a session turns 2..n
already read the prefix turn 1 wrote in both arms. The end-to-end figure exceeds
the per-session one because claude-code's sub-agent and side requests each re-send
the same system prompt, and each was independently re-writing it.
Explicit-breakpoint providers only. Under an implicit longest-prefix cache (OpenAI,
Gemini) the match already ends at the divergence.
Not claimed: a second Terminal-Bench task was within noise (95pp spread on
cache-write, step count moving 10->15 between arms), so neither its numbers nor the
pooled two-task total are quoted.
Latency: the proxy's own contribution is ~5 ms per request across all six measured
arms (0.03-0.07% of a request) against 8-18 s of upstream time, and the cacheonly arm
was faster upstream in 2 of 3 trials. An earlier apparent regression came from
dividing agent wall-clock by a step count that itself differed between arms.
A withdrawn claim, recorded in the docs so it is not rediscovered: an earlier version
also reordered the first system block, believing
`x-anthropic-billing-header: cc_version=2.1.222.<hex>;` to be a per-session nonce
poisoning a 28,297-token prefix. Across 74 conversations that suffix takes only 49
distinct values and one value appears in 24 different conversations, so it tracks the
claude-code build, not the session. A sequential run then showed session 2 reading
38,855 tokens written by session 1 with the header present. A live Azure OpenAI test
did show 0% -> 99.0% from moving a leading volatile block, but that nonce was
synthetic, so it demonstrates a mechanism rather than a real defect. The reorder and
its OpenAI/Gemini generalisation are not included.
Fails open throughout: any parse problem returns the request untouched, and the
existing top-level panic backstop forwards the original body.
Adds 24 tests: 12 for the placement policy (breakpoint cap, respecting existing
breakpoints, turn-stable anchors, string-content fallback) and 12 for the split
(behaviour, concatenation-identity, provider applicability, inertness, one-block cap,
non-text and unknown-field preservation, message integrity across the rewrite, plus
wiring through BodyFull with the cacheinject gate and the bypass path).
Self-review caught one real defect before this went up: the split rebuilt each half as
a fresh {"type","text"} map, which silently dropped any other field on the block
(citations today, whatever the API adds later) — a losslessness violation no existing
test covered. It now clones the original block and replaces only `text`, and removes
`cache_control` from the volatile half so the churn cannot re-enter a hashed prefix.
Signed-off-by: Osher-Elhadad <[email protected]>
This was referenced Aug 10, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What this does
Two changes to how
context-guruhandles prompt caching, both driven by measurement on real captured traffic.1.
cacheinject's placement policy is now solved, not guessedWith
R=0.1(cache read),W=1.25(5m write) and1.0(uncached) as multipliers on the base input rate, four inequalities fix the policy:kmore times is cheaper written whenW + kR < 1 + k, i.e.k > (W−1)/(1−R) = 0.28→ always breakpoint the last block;dmakes everything above it unmatchable, so anchoring atd−1recovers0.9per token — worth 12.5× more than positional tuning, because it restores read→read rather than read→write;t+1if it was written on turnt.The previous policy was a regression. It put its breakpoint on the message before the newest turn, which shortens the cached prefix every turn: +5.50% standalone and +9.21% layered on an agent that sets its own breakpoints (simulated on a stream calibrated to within 2.10pp of a live run's billed cache-hit rate). Its docs called the savings "invisible to
/stats", which made a negative effect unfalsifiable.Against Claude Code this policy correctly places nothing —
acted=0across 69 live runs, because claude-code already marks its own final message on 98.7% of requests. Its value here is not losing the 5.5%; it earns its keep on agents that don't mark their own tail, or whose prefix mutates mid-conversation.ttlis now configurable (5m|1h, validated at load). A 1h write costs 2.0× instead of 1.25× and only pays whenP(entry lapses before reuse) > 83.3%; measured over 1,905 real turns that is ~0, and reads refresh the TTL for free, so 5m stays the default.2. A volatile-tail split, gated on
cacheinjectbeing configuredClaude Code appends live git state to the end of its main system block. That block is 7,037 tokens whose first 6,877 (97.7%) are byte-identical across sessions — but it is one cacheable unit with its breakpoint after the churn, so the shared part is re-written every session.
Splitting into
[stable][volatile]with the breakpoint on the stable half is byte-identical in concatenation (adjacent text blocks concatenate), so the model sees the same prompt.What it saves — measured four ways
Structural. Across 50 real Claude Code sessions the stable half takes 1 distinct value, the volatile tail 50 — so the breakpoint hash was unique per session.
Mechanical. Through the live proxy on a real captured body: system blocks 3→4, concatenation byte-identical, breakpoints 2→2 (no slot consumed).
Isolated live A/B — two sessions differing only in the git snapshot, same breakpoints, judged by
cache_read_input_tokensfrom the API. Three runs, byte-identical results:At Sonnet 5 rates that first request of a warm session costs $0.022205 → $0.001719 = $0.0205 saved per session (−92.3%). Per session by model: Sonnet 5 $0.0205 ($0.0307 from 2026-09-01), Opus 5 $0.0512, Haiku 4.5 $0.0102. At 100k sessions on Sonnet 5: $2,048.
End-to-end — Terminal-Bench
fix-code-vulnerability, 3 sequential trials:Cache-write median −58.8%; cost median −34.5%, spread 4.4pp.
The saving is once per session, not once per turn: within a session, turns 2…n already read the prefix turn 1 wrote in both arms. The end-to-end figure exceeds the per-session one because claude-code's sub-agent and side requests each re-send the same system prompt, and each was independently re-writing it.
Scope and limits
Latency
The proxy's own contribution is ~5 ms per request across all six measured arms (0.03–0.07% of a request) against 8–18 s of upstream time, and the
cacheonlyarm was faster upstream in 2 of 3 trials. An earlier apparent regression came from dividing agent wall-clock by a step count that itself differed between arms — that metric is not used here.A withdrawn claim, recorded in the docs
An earlier version also reordered the first system block, believing
x-anthropic-billing-header: cc_version=2.1.222.<hex>;to be a per-session nonce poisoning a 28,297-token prefix.That was wrong. Across 74 conversations the suffix takes only 49 distinct values, and one value appears in 24 different conversations — it tracks the claude-code build, not the session. A sequential run then showed session 2 reading 38,855 tokens written by session 1 with the header present. A live Azure OpenAI test did show 0% → 99.0% from moving a leading volatile block, but that nonce was synthetic, so it demonstrates a mechanism rather than a real defect. The reorder and its OpenAI/Gemini generalisation are not included, and the docs keep the counter-evidence so it isn't rediscovered.
Safety
Fails open throughout: any parse problem returns the request untouched, and the existing top-level panic backstop forwards the original body.
Self-review caught one real defect before this went up: the split rebuilt each half as a fresh
{"type","text"}map, silently dropping any other field on the block (citations today, whatever the API adds later) — a losslessness violation no existing test covered. It now clones the original block and replaces onlytext, and removescache_controlfrom the volatile half so the churn cannot re-enter a hashed prefix.Tests
24 new tests, full suite green,
go vetandgofmtclean.BodyFullincluding thecacheinjectgate and the bypass path.