Cache Engineering for Agents · Fu et al.

Drop attention access, not the computation you already paid for

Cache engineering preserves retained KV states while shrinking future attention; AKV makes their history-dependent reuse and restoration safe.

Original paper · PDF

01 / The problem

Maya wants to stop rereading A without recomputing B

Maya’s coding agent has an old tool observation, A, and a reasoning token, B, computed after reading A. Next comes C. She wants only two KV entries available to future attention, without throwing away B’s computation.

Teaching example: each letter stands for one token; the roles and Maya are illustrative.

Delete A from the text, and the changed prefix requires re-prefilling B. Keep everything, and each decode step keeps reading A’s cache. §1; §2

There is another choice: stop attending directly to A, but keep B as computed. Now timing matters: will C be computed before or after A becomes inaccessible? Figure 5

02 / The mechanism

Keep the transcript; change future access

Cache engineering keeps the transcript but interleaves append, drop, and repos to preserve retained computations; AKV tracks their operation history so those history-dependent states can be safely reused and restored. §1; §3.4

Stop letting future attention read selected old KV entries, rather than deleting their text and recomputing everything after them. Retained states can still carry information from that old history. Figure 1

In Maya’s run, compute A and B, drop A, then compute C using B’s retained state. A separate repos compacts B and C’s key positions, without recomputing their hidden states. The text still contains A, B, C. §3.3; Figure 8

Logical token sequence

The ordered transcript. Dropping KV does not edit it.

Active cache

The entries future attention can use—not a promise that those entries are currently on the GPU.

Prefill computes contextualized keys and values; decode reuses them. B computed with A is not generally the B obtained from an empty prefix. §3.1; Figure 5

What this adds to earlier cache methods

KV eviction and positional reuse already exist. This paper emphasizes programmable agent/harness decisions integrated into shared serving: a stateless interface, history-aware indexing, isolation, eviction, and recovery. Its related-work discussion contrasts that with session-private relocated states in CLM’s Suffix Cache Reuse. §2; Appendix A.5

03 / State transitions

Three operations, three different effects

append — compute, then store
The active cache conditions the new token’s computation. Store its KV and advance the next encoded position.
drop — remove future visibility
Remove selected entries; leave retained computations, their positions, the next-position counter, and text untouched.
repos — compact position encodings
Rotate retained keys into consecutive positions and reset the next append position. Values do not change. §3.3
Transcript, active cache, and next positionTranscript keeps A and BTranscript · immutable orderA, BAfter dropping A only B is activeActive KV · future accessB, computed using AThe next position is unchanged by dropNext position unchangedCurrent operation is drop Aappend A → append B → drop A
Drop hides A from future attention but changes neither B nor the counter.
The active tiles and position labels change, but retained birth provenance does not.

Do not conflate text order, encoded position, and storage: a token can remain third in the transcript, have its key encoded at position 1, and be temporarily absent from GPU memory. §3.1

Why key rotation leaves values unchanged

RoPE encodes position through a rotation. Repos undoes the stored key’s old rotation and applies its new rotation. It does not run the token’s contextual computation again, and cached values are unchanged. Eq. (5)

Two different index conventions

Here, logical token IDs start at one and encoded positions start at zero. The serving API later uses zero-based message indices. A message can contain many tokens; the one-token messages are a teaching fixture.

04 / Work it through

Trace A, B, and C by hand

After append A,B; drop A; append C, before repos, what are the retained positions and next append position?

Teaching trace: Figure 5’s second trajectory, followed by Figure 8’s repos. Each letter is one token. A birth signature records provenance, not numerical KV.

  1. Compute A against the empty cache.
  2. Compute B using A.
  3. Drop A’s KV, keeping B’s computation.
  4. Compute C using the retained B.
  5. Compact the retained keys with repos.

The final transcript retains A, B, C; only B and C participate in future attention.

Read the birth signatures

A lower-case letter names a prior signature. A position after that name is the key position used at the new token’s birth. Those references do not change when keys are later repositioned.

05 / What was preserved?

Same visible tokens, different memory

Same input: an existing A,B,C transcript and its cache; A is no longer wanted for direct attention.

Delete text and re-prefill the suffix

Remove A from the text. Recompute B,C against the edited prefix; the retained text is B,C.

Drop KV and reuse

Keep text A,B,C. Remove A from future attention, and retain B,C exactly as computed.

One difference: editing the prefix changes the retained computation; dropping visibility does not rewrite it. Figure 1; §2

Three histories with the same final tokensAppend before drop① append ABC; drop AB used A. C used A and B.Final active: B, CDrop before append② append AB; drop A; append CB used A. C used that B.Final active: B, CStart without A③ start from B; append CB had no A prefix. C used B.Fresh suffix after text editFresh text B,C: no A prefix.Uncertain amount of useful retained informationHow much useful informationabout A survives? Unknown here.
Equal final B,C labels do not imply equal retained computations. Figure 5
The third trajectory and the limit of provenance

Starting from B alone gives B no A prefix at all. Its C uses a different B from either A,B history. Figure 5

Our inference: an indirect computational path is not a guarantee that every useful detail about A remains recoverable. This diagram measures neither recall nor task accuracy.

06 / Shared serving

Serve a computation history, not just a prefix

Two requests finish with B@0,C@1. One dropped A before C, the other after C. What can AKV safely conclude about reusing their C states?

A radix tree shares common computation prefixes. With cache operations, “common” must include operation records: reuse the shared A–B prefix, then branch where the histories diverge. §4.2.2

Token-only cache matching

Same input: two A,B,C runs, dropping A on opposite sides of C, then repos.

Naive matcher

Matches final B,C positions; conflates C’s computations.

AKV

Matches token and operation paths; shares B but keeps C separate.

The difference is the view used when C was computed, not the final label on C.

History-aware tree and independent positional versionsRequest with complete historiesmessages + cumulative operationsrequestspecifiesShared prefix and empty placeholderA □ → B□ empty placeholderFirst operation divergencebranchesC → drop A→ reposC used A,Bdrop A → C→ reposC used BOriginal version still in usePositional versions (separate inset)B at old position → Request 1copy: rotate K; copy VB,C compact copies → Request 2Eviction eligibilityEvict a version only when no ongoingcomputation/restoration needs it.
Share before divergence; do not merge later computations just because final labels agree. The version inset illustrates Figure 8, separately from the two history branches. §4.2.2; Figure 8
Stateless interface
Every request sends the full messages and cumulative operate-after instructions. Residency does not change the requested distribution. §4.1
Extended radix tree
Token nodes, drop nodes at trigger points, and reposition records distinguish histories and positional versions. §4.2.2; Appendix A.1.2
Drop-aware eviction
Free a version only after all ongoing computation/restoration releases it. Leave tree placeholders so descendants remain accessible; prioritize dropped cache over completed-request cache. §4.2.2–4.2.3
A valid operate-after teaching request
{
  "model": "gpt-oss-120b",
  "messages": [
    {"role": "user", "content": "A"},
    {"role": "assistant", "content": "B"},
    {"role": "user", "content": "C"}
  ],
  "cache": {"drop": {"1": [0]}, "reposition": [2]}
}

Constructed fixture: after message B (index 1), drop message A (index 0); after C (index 2), repos. Actual tokenization need not produce one token per letter. Message indices are zero-based; drop precedes repos at a shared boundary. This follows the prose grammar, rather than copying the source’s malformed illustrative table. §4.1; Figure 6

Exact matching versus retrigger matching

Exact matching requires the same token IDs, stored positions, and operation records. Retrigger matching ignores only stored positions, preserving all operations and their parameters. It selects a history-compatible source and copies/rotates as needed. A candidate must match a strictly longer valid prefix to replace the current result; exact matches win ties. Appendix A.1.2

Reconstruct historical views, not only the final view

If storage is missing, ordinary final-view causal prefill is insufficient. Segment-batch attention splits queries at drop/repos boundaries and supplies each segment’s historical KV pages and positions. Only attention is segmented; the FFN still processes one full-sequence batch. §4.2.2; Appendix A.1.1

Append ABC; drop B; repos; append D; drop D; append E; repos; append F.
Historical attention segmentsSegment one before dropsABC · causal before dropsB is available when C is computed.Segment two uses compacted A and CD uses A, C and itself.Segment three excludes dropped DE uses A, C and itself; not D.Segment four uses repositioned EF uses A, C, E and itself.Full sequence FFN batchFFN: one full-sequence batch
Segment 1 reconstructs A, B, and C before any drops.
A state missing from the final view may still be needed to reconstruct an earlier computation. Figure 10
Why this is one pass, not repeated full forwards

Within each layer, AKV writes new KV and creates temporary position versions by rotating K and copying V. It submits segment-specific page lists and query ranges together to batched attention. The drawn rows are an explanatory visibility grid, not a dense mask required by the implementation. A prefill using only final A,C,E,F would omit B from C’s birth view and could wrongly expose D to E. Appendix A.1.1

07 / Try a counterexample

Make matching labels hide a different computation

Goal: make two runs end with the same B,C positions but different C provenance, then fit a continuation below the toy position limit.

Teaching example · four-position limit
Tasks
  1. At zero continuation, switch drop timing with repos on. Compare C’s birth tree.
  2. Request two continuation tokens. Turn repos off, then on.
  3. With repos on, request three continuation tokens. Does compaction give unlimited room?
Teaching run: keep the transcript, drop A, compact B and C.
C’s immutable birth-provenance tree

Invariant: drop changes neither text nor retained provenance nor positions. Repos changes key-position versions and next, not birth provenance or cached values.

What this model leaves out

Valid toy positions are 0–3. This is not an evaluated model’s context limit. Signatures record structural dependencies; they compute no transformer weights, KV vectors, logits, probabilities, or policy accuracy. Rotation is a label change, not numerical matrix multiplication. Serving diagrams are schematic: no scheduler, allocator, radix search, FFN, or GPU batching runs here.

Different signatures are not a numerical distance or a universal proof of different outputs. A blocked attempt stops the toy run and is not added to its transcript.

08 / Formal rules

The rules in the paper’s notation

The concrete trace separates what is retained from how it is represented. These are the corresponding rules.

append⁡(xt+1):𝒞←[𝒞;Ct+1]\operatorname{append}(x_{t+1}):\quad\mathcal{C}\leftarrow[\mathcal{C};C_{t+1}]

Compute a new KV entry conditioned on the active cache and append it in logical order. Eq. (3)

SymbolMeaning · worked value
append⁡\operatorname{append}Cache update · step 4 appends C
xt+1,tx_{t+1},tNew token and preceding logical length · C; 2
𝒞\mathcal COrdered active cache ·
Ct+1C_{t+1}New entry · C3C_3 for C
[⋅;⋅][\cdot;\cdot]Concatenation · retained B then new C
drop⁡(P):𝒞←𝒞∖{Ci:i∈P}\operatorname{drop}(P):\quad\mathcal{C}\leftarrow\mathcal{C}\setminus\{C_i:i\in P\}

Remove selected logical entries from future attention, preserving retained order and computation. Eq. (4)

SymbolMeaning · worked value
drop⁡,P\operatorname{drop},PVisibility removal and selected active IDs · step 3; {1}
𝒞\mathcal CActive cache ·
Ci,iC_i,iEntry and logical index · A’s entry; 1
∖\setminusOrdered removal · remove A, not B
K←R(q)R(p)−1KK\leftarrow R(q)R(p)^{-1}K

Change a stored key’s positional rotation, not its hidden state. In step 5, two retained entries give next position ; values stay unchanged. Eq. (5)

SymbolMeaning · worked value
KKCached key · B’s symbolic key, step 5
p,qp,qOld and new positions ·
R(p),R(p)−1R(p),R(p)^{-1}Old RoPE rotation and its inverse · rotate at B’s old position, then undo it
R(q)R(q)New RoPE rotation · B’s new position
o1:m=(o1,…,om),oj∈{append⁡(x),drop⁡(P),repos⁡}o_{1:m}=(o_1,\ldots,o_m),\qquad o_j\in\{\operatorname{append}(x),\operatorname{drop}(P),\operatorname{repos}\}

For a fixed model, the complete ordered sequence specifies cache state starting from empty. Eq. (6)

SymbolMeaning · worked value
o1:mo_{1:m}Complete history ·
m,j,ojm,j,o_jCount, index, indexed operation · ; indices from one through that count; third operation drops A
x,append⁡(x)x,\operatorname{append}(x)Token and append · A, B, or C; C at operation 4
P,drop⁡(P)P,\operatorname{drop}(P)Selected indices and removal · {1}; operation 3
repos⁡\operatorname{repos}Position compaction · operation 5
ϕ(T(x,p))=T(x),ϕ(ΔP)=ΔP,ϕ(R)=R\phi(T(x,p))=T(x),\qquad\phi(\Delta P)=\Delta P,\qquad\phi(R)=R

Retrigger matching ignores stored positional labels but keeps every operation record. Appendix A.1.2

SymbolMeaning · worked value
ϕ\phiHistory-compatibility projection · ignore B’s stored position, not its history
T(x,p),x,pT(x,p),x,pToken node, token ID, current position · B at ; B is symbolic, not a tokenizer ID
T(x)T(x)Projected token node · B
ΔP,P\Delta P,PDrop record and its set · drop {1} after B
RRReposition operation record · repos after C; not rotation matrix R(p)R(p)
Correctness assumptions and finite precision

The argument fixes the model and position-encoding configuration and assumes exact arithmetic. Identical projected prefixes preserve original computational histories and unrotated KV content. Finite-precision rotations may introduce rounding; the paper does not require bitwise equivalence to recomputation. Appendix A.1.2

Glossary
Trajectory / logical token sequence
Ordered prompt, assistant, and tool text; cache operations do not rewrite it.
Active cache
KV entries available to subsequent attention, distinct from physical residency.
Active context
Tokens corresponding to active entries; length equals entry count.
Position encoding index
Position encoded in a key, separate from logical order.
Cache operation sequence
Ordered append/drop/repos history specifying state for a fixed model.
Tool-response rolling drop
Retain reasoning and recent tool-response cache; main evaluation keeps 12 tool responses.
Retrigger matching
Match token/operation history while ignoring stored positions; copy and rotate as needed.
Segment-batch attention
Restore historical views using segment-specific causal attention in one forward pass.

§3.1–3.4; §5.1; Appendix A.1

09 / Evidence

What improved, against which baseline?

A fixed-price token estimate is not measured GPU time. Output tokens per second and P95 whole-request latency also answer different questions.

A better average quality/cost trade-off

Across three main models and four benchmarks: 27.7% lower average inference cost than Standard, 21.9% lower than Text Engineering, and 1.7 points higher average benchmark scores than Standard. §1; Table 1

Not a 1.7% relative gain, nor a win in every cell. Costs are API-equivalent estimates, not whole-system expenditure.

Table 1 · model averages, score (%) / cost (cents)
ModelStandardText EngineeringAKV
MiniMax-M2.752.4 / 5.052.8 / 5.753.7 / 4.4
GPT-OSS-120B51.0 / 11.248.3 / 10.253.1 / 7.3
MiroThinker-1.7-Mini44.1 / 20.437.1 / 18.145.8 / 14.8

A local regression: MiniMax-M2.7 on SWE-Verified scores 75.2 at 7.0 cents with Standard versus 74.4 at 5.5 cents with AKV. Lower cost does not imply a higher score on every benchmark. Table 1

Baselines, policy, and cost scope

Standard summarizes at 96K tokens for GPT-OSS-120B and MiniMax-M2.7, and 192K for MiroThinker-1.7-Mini. Text Engineering uses 48K for all. AKV keeps the latest 12 tool responses and all reasoning; repos uses Standard’s thresholds. Baselines use Pi-style summarization. §5.1; Appendix A.2.2

Benchmarks are BCP, xbench-DS, SWE-Verified, and GAIA-Text’s text-only 103-task validation subset. Fixed-price costs cover agent generations and summary calls only; repos tokens are conservatively charged at cache-hit rates. §5.1; Appendix A.3

Measured serving gains

GPT-OSS-120B, BF16, Top-80 SWE-Verified, eight A800-80GB GPUs. At respective peak-throughput settings, AKV at C=14 versus Standard at C=12 reports:

MetricAKV relative to Standard
Mean request latency1.36× speedup
P95 request latency1.51× speedup
Input throughput1.53×
Output throughput1.18×

Input throughput counts all logical tokens, even those whose cache was dropped. These are not same-concurrency ratios. §5.3; Table 2

At the same batch size, full-attention time falls by 59.8%, while total decode-step time falls by 16.0% versus Standard. Less active KV means fewer reads and less attention work—not a 59.8% whole-request speedup. Appendix A.4.1; Figure 12

The positional-headroom ablation also shows a trade-off: on the first 100 BCP tasks, GPT-OSS-120B tool drop scores 55.0 at 7.1 cents without repos, versus 62.0 at 10.9 cents with repos. More exploration can improve pass rate while costing more. Table 3; §5.4

Replay and high-load measurement protocol

The same selected tasks and ordering are used, but each method replays trajectories collected under its own policy. Turn counts and output budgets can differ; tool outputs are replayed, not re-executed. AKV C=14/16 windows end at the first 30 completed tasks, counting all requests in the window. Degraded large-concurrency Standard runs use one-hour windows with unfinished requests. Appendix A.1.4

Policy extensions are separate from serving mechanics

RSI refines MiniMax-M2.7 policies on 20 BCP development tasks, evaluating on 100 held-out tasks. Iterations 3 and 6 save 15.6% and 17.8% versus Standard while maintaining its accuracy; the headline 7.1% additional saving uses expert design as baseline. Abstract; §5.4

Cache-As-Tool lets the model choose reductions. On a 100-task BCP subset it improves scores, but MiniMax-M2.7 costs rise from 5.4 to 5.9 cents as it takes more turns. The serving mechanism does not guarantee a cost-minimizing policy. Table 4; §5.4

Our inference: these replay speedups measure a policy-and-serving workload, not isolated engine overhead on identical token trajectories. Different high-load windows also constrain interpretation. They do not negate the reported measurements.

10 / Boundaries

Less cache is not a bounded cache

With the latest 12 tool responses retained, what happens if the agent keeps adding reasoning for many more turns?

Our inference: symbolic provenance cannot say how much useful information survives a drop or predict a new retention policy’s accuracy.

Interpretation limits versus source-stated limits

Our inference: method-specific replay and replayed tools do not isolate implementation overhead. Extreme-load comparisons also need the first-30-completions versus one-hour-cutoff protocol described above. These are experimental-interpretation cautions, separate from the authors’ future-work statement. Appendix A.1.4

Open questions
  • Which task-aware policies beat latest-12-tool-response retention on new distributions?
  • Would training with cache operations improve preservation of useful information?
  • How should shared recovery extend to linear-attention models?
  • How much information about a dropped observation remains indirectly accessible?
11 / Recall and transfer

Explain it without the page

Answer each in your head before opening its reference answer.

1. Where does sharing stop?

Compare append A,B,C; drop A with append A,B; drop A; append C. Which B can be shared, and why must C remain on separate branches?

Reference answer and why

B can be shared: both histories computed it with A. In the first history C directly attended to A and B; in the second it attended only to the retained B. Drop preserves earlier computations but changes later attention. Branch at the operation divergence, not the final list of visible tokens. Figure 5; §4.2.2

2. Who owns a shared version?

R2 shares cached P,Q with R1. R2 drops P and repositions Q from 1 to 0. Describe Q’s versions and when P or old Q can be freed.

Reference answer and why

R2 gets a copied Q with its key re-encoded at 0 and value unchanged. R1 may continue using Q at 1. P and either Q version can be evicted only when no ongoing computation or restoration needs that version. Visibility is request-specific; shared storage cannot be overwritten or deleted unilaterally. §4.2.2–4.2.3; Figure 8

3. Can the final view restore its own past?

Why would ordinary causal prefill on final A,C,E,F fail to restore Figure 10? Name a missing historical dependency and a required positional version.

Reference answer and why

B was visible when C was computed, although absent from the final view. D must be excluded from E’s view. C needs a version at 1 for D; E needs a version at 2 for F despite being born at 3. Every append’s historical visibility and positional mapping matter, not just the final surviving entries. Appendix A.1.1; Figure 10