Context Compaction in Production
Design compaction around recoverable evidence, validated task state, and stable prompt prefixes. A shorter history only helps when the agent can still take the right next action.
The Restart Is Part of the Task
In the migration example from Validate Compression, the agent must keep the old API working until clients migrate. A summary can retain the new schema yet lose that constraint, leaving later edits to break compatibility. Compress & Restart needs a check before the full context leaves the working window.
Microsoft’s CompactionBench study finds that 7.8% of the GitHub Copilot sessions it analyzed triggered compaction, yet those sessions accounted for 44.2% of total token consumption. Looking only at prompt size misses the cost of making that summary and getting back to work.
Keep Evidence Recoverable
Keep enough task state in view to continue work, with links to facts that would be costly to repeat. Store the full history outside the window under the app’s access and retention rules; Write Outside the Window sets that storage boundary, while compaction decides what the agent needs to see now.
Continuing that migration, the restart state could look like this:
| State | What must survive |
|---|---|
| Goal | Add the replacement field without breaking existing clients |
| Constraint | Continue accepting the old field until client migration is confirmed |
| Decision | Introduce the new field as nullable; tighten validation later |
| Evidence | References to the compatibility test and the user’s migration requirement |
| Uncertainty | Backfill readiness has not been verified |
| Next action | Run the compatibility test before changing request validation |
Keep the status of each decision: a proposed backfill must stay proposed, and a passing test should name the revision it actually checked. Otherwise, a summary can turn planned work into work that looks finished.
Use links that lead back to the source; a file path alone becomes unclear after edits, so pair it with the relevant revision or keep the tool result that supports the claim. If the source is gone, tell the resumed agent it still needs to check the claim.
Start Before the Window Is Full
Leave room for the compaction request and its output, as well as the next tool response. A percentage threshold alone says little when a pending tool call may return a large document. Measure request sizes and bound tool output before choosing how much headroom to leave.
Background summaries can fall behind. While a summary is being prepared, the agent may edit a file or receive a new user constraint; adopting that summary without the later messages then loses work that the agent has already done.
Track the last message covered by each draft summary, keeping later messages when adopting it and rejecting drafts whose claims conflict with newer state. Keep tool calls and their results together as the API requires. A fluent summary cannot repair an incomplete tool exchange.
In Slipstream, an agent keeps working from the full context while a summary is generated in parallel, giving a judge an independent record of the facts and forward intent the summary needs to preserve. The check uses later work as evidence.
Preserve the Cached Prefix Where It Helps
Preparing a shorter prompt can cost more than expected if the summary call cannot reuse the existing prompt cache. Anthropic’s Claude Code account describes reusing the parent’s system prompt and tool definitions, then appending the compaction request after the conversation, so the summary call can reuse the matching prefix instead of paying to process the entire history uncached.
That saving covers the call that writes the summary; replacing history for the next turn changes the prefix after the retained instructions, so cache reuse there needs its own check. Appending a new tool result leaves the earlier prefix unchanged. Changing an earlier message loses reuse from that point onward.
APEC, introduced with CompactionBench, prepares indexed summaries in the background and appends them to a stable prefix, addressing both foreground delay and prefix reuse without waiting until the agent has filled its window. The added machinery has a cost. Compare complete task cost, including summary generation and subsequent agent calls, against a simpler synchronous baseline.
Preserve Authority Across the Rewrite
A fetched document can contain text that looks like a user instruction; if the compactor flattens the transcript into text with forgeable role labels, that passage can become a remembered approval. The Compaction Laundering study shows this failure in coding agents and compares flattening with keeping roles typed.
Keep roles typed in the summarizer’s input, so it can distinguish a real user instruction from a claim inside fetched text. A summary should never grant permission to run a command. Enforce approval rules outside the model, with the user’s original approval on hand for checking.
Typed roles address the loss of source identity studied in that paper, while prompt injection can still arrive through other channels. Apply State Sanitization before carrying untrusted claims into durable memory, and preserve their origin when they remain relevant evidence.
Test What the Agent Does Afterward
Build compaction checks around realistic continuations. Can the resumed agent change request validation without breaking existing clients? In the migration example, check compatibility and whether the agent still distinguishes an unverified backfill from a completed one. Removing either fact should make the check fail. Include cases where the same requirement must survive repeated compactions, because a successful first restart says little about later drift.
Measure task success alongside foreground delay and total cost. Record whether the agent had to fetch missing facts or repeat work it had already done. Keep failed summaries and the full context for diagnosis; shortening the history should not erase the reason for a bad decision.