Memory that survives the cache
ReCAP keeps a small graph of how an agent used its history, then retrieves the right original messages when the next request arrives.
Persistent Context Graphs for Efficient Memory Compaction in LLM Agents
1. The problem: a long history is not the same as useful memory
A coding agent may read a file, run a test, diagnose a failure, edit a function, and discuss the result with a user. Every action adds messages. On its next call, the model needs enough of those messages to continue correctly—but not necessarily all of them.
Before generating an answer, a language model processes its input in a stage called prefill. The resulting key–value, or KV, cache holds model-internal representations of those tokens. If the next call shares the same prefix and the cache remains resident, the serving system can reuse that work. After a long user pause, the cache may expire. The model then has to process its input again.
Text archive
The durable record of messages and tool outputs. It is relatively easy to store and can survive a session pause.
KV cache
A model-specific inference acceleration structure. It can be large, evicted, and expensive to reconstruct.
Memory compaction chooses a smaller input from the accumulated history. A summary is compact, but writing it requires computation and can lose details. KV eviction can avoid carrying some cached tokens, but the evaluated eviction baseline permanently discards entries. Keeping only recent messages is cheap, but an old constraint can matter more than a new log.
Why attention is a plausible signal
Attention tells us how token positions distribute weight over earlier token positions during a forward pass. ReCAP reduces that fine-grained signal to message-level statistics. A block often attended to is a candidate for retention; a later block that attends to an earlier one may need that earlier block as supporting context.
This is a heuristic signal of use, not a proof of truth or causal necessity. The paper combines it with explicit protections and query matching rather than trusting attention alone.
Of historical attention retained by a 10% token selection in one illustrated coding session.
Median next-turn identifier coverage from past attention at a 10% text budget, versus about 0.71 for a future-use oracle.
Mean attention redistribution when changing the target file, versus 5.3% for paraphrasing the same target.
These are diagnostic studies, not task-success rates: the reuse study has 64 transitions from eight sessions; the controlled request study has 32 fixed histories. Identifier coverage measures reuse of code-like names, not complete semantic understanding.
2. What the graph actually contains
A node is an atomic history block: a user message, a plain assistant message, or an assistant tool-call message together with its results. Keeping calls and results together prevents invalid conversation sequences. Each node has a stable chronological ID, an importance score, and observation/staleness flags.
An edge points from an earlier support block to a later dependent block. If a diagnosis attends to a test failure, the stored edge is failure → diagnosis. During retrieval, ReCAP traverses incoming edges of the diagnosis to retrieve the failure. This reverses the direction in which attention was measured.
Agent produces messages and attention.
Reduce attention to scores and edges.
Text and graph persist even if KV expires.
New request retrieves blocks and support.
A. Accumulate importance without forgetting omitted blocks
ReCAP samples attention rows from the completed turn, averages across heads and selected layers, clips extreme received-attention values, and computes mean attention per token for each observed block. This avoids giving a long log a high score merely because it contains many tokens.
unew(v) = (1 − α) uold(v) + α r(v) / max r
Paper setting: α = 0.6
For example, an old score of 0.40 and a newly normalized observation of 0.90 become 0.4 × 0.40 + 0.6 × 0.90 = 0.70. This exponential moving average favors recent evidence but retains earlier evidence. Blocks absent from the working context are not measured and keep their previous scores; they do not automatically decay toward zero.
For dependencies, sampled positions inside a later block contribute their attention mass to earlier blocks. Above a threshold of 0.02, ReCAP adds a support edge and retains its maximum observed weight across updates. Selection uses the edge’s presence—not a weighted path optimization.
B. Let the arriving request change the ranking
The new query may say “verify get_org_auth_event_metrics again.” That rare identifier is a strong clue, even if the relevant grep output has been omitted for several turns. ReCAP extracts code-like identifiers and dotted paths, then weights exact overlaps by inverse document frequency:
s(v) = z(u(v)) + λ z(ℓ(v)) + exploration(v) − stale_penalty(v)
Here N is the number of history blocks and df(w) is how many contain identifier w. A name present everywhere has weight zero; a rare function name has higher weight. The z operation standardizes each channel across the history, so different numerical scales do not dominate the combination. A constant channel contributes zero.
The paper uses λ = 0.5, a small seeded bonus of 0.05–0.10 for never-observed nodes, and a penalty of 2 standardized-score units for stale nodes. Staleness is a heuristic: an earlier block must have identifier-set Jaccard similarity above 0.5 with a later block that receives substantially stronger attention. Stale marks persist; the original text still remains available.
C. Protect, pack, expand, render
- Protect the session skeleton. Keep all historical user messages and the latest edit/write record for each modified file.
- Pack by score. The nominal budget is
B = floor(β × historical character cost), withβ = 0.10. Starting with protected blocks, scan other nodes in descending score order and keep each one that fits. This is not a knapsack optimizer or a score-per-character ranking. - Add support. From a fixed copy of the packed set, inspect incoming edges in stored order. Add non-stale predecessors that fit under
(1 + δ)B, withδ = 0.10. This is one hop only; newly added supports do not become new expansion seeds. - Restore chronology. Place selected historical blocks between the system instructions and current turn. Freeze that historical prefix during tool steps within the turn.
max(protected cost, 1.1B). The implementation’s 360k-character full-request cap can override protection and prefix stability by dropping oldest selected blocks.The need for protection is supported by failure cases, not just intuition. Score-only selection once discarded a long “analysis only, no implementation” task statement while keeping the agent’s short preamble; the agent invented a different task and edited unrelated code. Another run lost the agent’s latest edit record and treated its own fix as pre-existing code. In the cross-turn study, attention ranking omitted about 37% of user messages and 28% of latest-edit records even when the complete protected set could fit.
3. Playground: retrieve a diagnosis and its evidence
This miniature coding session uses synthetic, hand-authored importance scores and edges, not model attention. It implements standardized importance plus IDF query overlap, stale penalties, protected packing, and one-hop support expansion using the displayed text’s character lengths. All nodes are treated as already observed, so it omits the exploration bonus and graph updates.
Blue = protected · Green = ranked selection · Orange = added support · Gray = omitted. Arrows always point support → dependent. Expansion allowance stays at 10% of the nominal budget.
| Block | Characters | Importance u | Query ℓ | Score s | Decision |
|---|
Resulting historical prefix
System instructions and the incoming request would be rendered separately; they are not part of this historical budget.
Experiments to try
- At the default 45% budget, the diagnosis is ranked in and its lower-importance failure trace can enter through a dependency. Switch off support expansion and compare the prefix.
- Change the request to
cache_key serializer. An older, otherwise low-priority block can return from the archive. Set λ to zero to remove the request’s influence. - Lower the budget to 10%. Protected content exceeds the nominal allowance. Turn protection off and see how task constraints can disappear.
- Raise the budget. More evidence fits, but expanding from a support still does not recursively pull in its own predecessors.
The selector in miniature
// Scores have already been computed; blocks include call/result pairs.
B = Math.floor(beta * sum(blocks.map(v => v.cost)));
C = new Set(protectedIds);
for (const v of descendingScoreThenChronology(blocks)) {
if (!C.has(v.id) && cost(C) + v.cost <= B) C.add(v.id);
}
const seeds = chronological(C); // fixed before expansion
for (const b of seeds) {
for (const a of incomingSupportsInStoredOrder(b)) {
if (!C.has(a.id) && !a.stale &&
cost(C) + a.cost <= 1.1 * B) C.add(a.id);
}
}
return chronological(C);This small routine handles retrieval, not attention instrumentation. A real integration must map sampled attention positions back to stable block IDs, persist updates, detect latest edits, serialize valid messages, and coordinate cache boundaries.
4. What the evaluation shows
The authors evaluate two open model families: Qwen3-Coder-30B-A3B-Instruct and gpt-oss-20b. SWE-Together has 106 repository-level tasks with tool use and user feedback; GPT-5.4 simulates users. Lost-in-Conversation (LiC) has 100 code instances, each with five conversations that reveal requirements across turns.
Comparators include full history, recency, random selection, LLMLingua-2, LongLLMLingua, Codex-style summarization, and query-aware KV eviction. Hyperparameters are fixed during execution; token counts are outcomes, not exactly matched experimental inputs. SWE results summarize two replicates; LiC means and standard deviations summarize five repeats.
Task quality and realized context
| Benchmark / model | Policy | Score ± SD | Mean context tokens |
|---|---|---|---|
| SWE · Qwen | Full history | 24.4 ± 1.87 | 28,504 |
| Summarization | 28.7 ± 1.26 | 5,239 | |
| ReCAP | 28.5 ± 0.40 | 15,344 | |
| SWE · gpt-oss | Full history | 8.2 ± 0.15 | 8,508 |
| Summarization | 8.1 ± 0.45 | 4,543 | |
| ReCAP | 9.0 ± 0.01 | 4,043 | |
| LiC · Qwen | Full history | 65.6 ± 1.82 | 1,121 |
| Summarization | 75.4 ± 2.70 | 372 | |
| ReCAP | 85.4 ± 1.95 | 94 | |
| LiC · gpt-oss | Full history | 26.4 ± 3.44 | 1,023 |
| Summarization | 36.8 ± 5.12 | 602 | |
| ReCAP | 67.6 ± 3.58 | 73 |
Selected rows from paper Table 1. SWE scores are reward × 100; LiC scores are accuracy × 100. SWE context counts retained history only, excluding system instructions, tool definitions, and the current turn. LiC counts the complete input minus the fixed system prefix, including the current request and framing. Compare policies within a benchmark; do not treat these scopes as identical.
Reading the result carefully: ReCAP roughly halves SWE history versus full restoration. Qwen summarization is slightly higher in reward and uses substantially fewer context tokens than ReCAP. ReCAP’s advantage there is low selection overhead, not the smallest prompt. On LiC it improves accuracy over full history by 19.8 and 41.2 percentage points, and beats all evaluated baselines.
The random-selection baseline also improves LiC over full history: 75.2 versus 65.6 for Qwen. This suggests that removing accumulated material can help this benchmark, but does not itself isolate the mechanism. ReCAP’s additional benefit needs the ablation evidence.
Is the graph doing useful work?
LiC Qwen ablation
Removing importance, dependencies, and stale marks loses 8.8 accuracy points with nearly identical context sizes: 94 versus 95 tokens.
Block granularity matters
Paragraph and line segmentation score 83.2 and 83.0, versus 85.4 for message blocks, while using 152 and 168 tokens.
This favors intact message blocks in this setting. It does not establish a universally optimal chunking size.
The graph-removal ablation is a bundled intervention: it removes multiple mechanisms together. It supports the attention-graph package, but does not separately quantify the contribution of importance versus support edges versus stale penalties.
Latency: separate selection from restoration
On one H100, synthetic uncached inputs matching mean SWE historical lengths give cold time-to-first-token reductions from 0.985 to 0.395 seconds for Qwen and 0.261 to 0.128 seconds for gpt-oss. Those are about 60% and 51% reductions relative to full history—not 95%.
The approximately 95% headline compares estimated compaction plus cold restoration against summarization. Summarization adds a full generation call: about 7.67 seconds for Qwen and 2.43 seconds for gpt-oss in the SWE measurements. ReCAP’s prepared-graph selection adds about 0.02 seconds and under 0.01 seconds respectively.
Storage, revival, and cache coexistence
The graph averages about 19 KB of CPU metadata per Qwen SWE session and under 3 KB in the other evaluated settings. This count uses compact 12-byte node and edge records and excludes the full text archive, which every harness retains. It should not be read as the complete memory footprint of a deployed application.
In Qwen SWE runs, 70% of turn transitions revive at least one previously omitted block. One appendix example recovers an early grep result at turn 8 after seven omitted turns: the user explicitly names six handler functions, and their rare identifiers lift that block into the new selection.
ReCAP also need not fight prefix caching. In a separate vLLM experiment, it selects only at idle boundaries where KV has been discarded; warm boundaries append to the resident context. Warm boundaries reuse over 99.9% of prompt tokens. As simulated warm probability increases from 25% to 75%, aggregate cache-hit rate rises from 72% to 87%, while uncached prompt tokens fall 44%. Median engine TTFT is 0.10 seconds warm and 1.58 seconds idle in that experiment. These times come from a different protocol than the synthetic cold-restoration measurements.
What if the API hides attention?
The authors replay served context through a Qwen3-0.6B proxy model and map its attention back to the same blocks. Its scores are close to the agent-attention version: 85.2 versus 85.4 on Qwen LiC, 68.2 versus 67.6 on gpt-oss LiC, and 29.0 versus 28.5 on Qwen SWE, with no statistically significant differences reported.
This is encouraging for black-box agents, but the proxy is extra model computation. “No additional model call for selection” still describes querying the prepared graph; it should not be extended to claim that the proxy produces attention for free.
5. Limits and practical interpretation
The paper provides implementation details and failure cases, but no separate limitations section. The following cautions follow from its mechanism and evaluation:
- Scope is interactive coding. Two model families and two coding benchmarks do not establish results for legal research, dialogue, or arbitrary enterprise documents. SWE’s simulated users and low absolute gpt-oss rewards also matter when judging generality.
- Exact names are a special advantage. Identifier overlap is good for functions, files, and errors. A request that refers to an old decision using unrelated vocabulary may fail to revive its block. The method does not perform semantic query understanding during selection.
- Attention dependencies are not verified facts. An edge represents observed attention mass, not a logically proven dependency. One-hop expansion can miss longer chains, and stored traversal order can affect what fits.
- Staleness is imperfect. Identifier overlap and attention dominance can mistake a related earlier observation for superseded content. Persistent stale marks can continue suppressing it even after the request changes.
- Protection is valuable but finite. Preserving all user messages and latest edits may dominate the budget. A hard serving cap can still remove protected content. Low-level cache validity and context-limit policies must be engineered explicitly.
- “Attention already computed” does not mean zero engineering cost. Capturing sampled rows requires retained query vectors or hidden states and resident keys. Background graph updates cost time; black-box proxy replay adds inference. Serving integration remains a substantive task.
- Evaluation is not exactly token-matched. Every policy produces its own history. Different block splitting and realized budgets mean quality comparisons involve multiple operational differences.
The engineering lesson
ReCAP’s most useful abstraction is not “use a graph instead of a summary.” It is separate durable history, reusable evidence of past use, and the temporary prompt for this request. Protect records whose loss changes the task, combine historical evidence with current cues, and retrieve supporting observations without throwing away the archive.