ByteCosts
lossless-vs-lossy-context-compaction.mdx

AI Coding Agents

Lossless vs Lossy Context Compaction: What to Keep Verbatim

Lossless context management keeps content verbatim somewhere the agent can re-read, while lossy compaction replaces it with a summary or removes it from the active context. Save exact file paths, error strings, working commands, and user constraints when later steps depend on them. Summarize completed steps and clear old tool output once you have saved the evidence you still need.

Lossless context management keeps exact information somewhere the agent can retrieve it, such as a saved log or a versioned file. Lossy compaction replaces older turns with a summary or removes selected content from the active context. Preserve exact evidence for checks that depend on it, and summarize completed work by what it established. Then choose a mechanism based on what the next request must see and what it can re-read on demand.

The decision is per content class

For each content class, ask what would break if only a summary survived. Preserve strings that must match exactly, files the agent must be able to re-read in full, and constraints it must follow as written. For a completed exploration step, a record of the outcome may be enough.

Content classRecommended treatmentLossy risk if summarized
File paths and symbol namesKeep verbatim, or retain a path the agent can re-read on demandRenamed or hallucinated paths can send edits to the wrong symbol
Exact error text, codes, test namesVerbatim in a note or memory file so the agent greps the original laterParaphrased errors that no longer match logs or source
Commands that worked (build, test, deploy)Verbatim in CLAUDE.md, a note, or memoryRe-derived commands with wrong flags or order
User constraints and standing decisionsVerbatim, re-stated after any compactionSoftened constraints; “prefer X” becoming “use X”
Disproved hypothesesA short verbatim list of what was ruled outThe agent re-runs the same dead-end investigation
Successful intermediate stepsSummarize the outcome and retain any evidence needed for verificationA later check may need a detail the summary omits
Old tool results (file reads, searches, logs)Clear by rule after required evidence has been saved elsewhereA later check may need the original output
Superseded diffs and dead-end codeDrop once verified as superseded and re-read the current file as neededLost rationale if the discarded diff had the only record of a decision
Thinking blocksKeep the last N turns, or all on some model defaultsCleared reasoning can orphan later conclusions
Images, documents, fetched URLsRetain originals separately and re-supply attachments from summarized turns when neededDetails may need to be recovered from the original

Anthropic’s engineering guidance suggests tuning compaction for recall first, then removing excess detail. To apply that advice, start with evidence you can compare before and after compaction. If a failing test printed an exact error, retain the original log and note its location alongside the test command. Summarize the search that led to the test and preserve the result that determines the next edit.

A path reference can recover the exact evidence only while the file still contains the relevant version. If the file is being edited, record the revision or save the excerpt you need to reproduce the observation. For example, the current configuration can confirm what a setting is now, while a saved test result can establish what happened before the change.

What each mechanism preserves

Rule-based clearing on the Claude API

Context editing (beta header context-management-2025-06-27) clears content mechanically rather than by summary. The clear_tool_uses_20250919 strategy removes the oldest tool results in chronological order once context passes a trigger (default 100,000 input tokens, configurable in input_tokens or tool_uses), replaces each with a short notice saying it was removed, and keeps a configurable number of recent pairs (keep, default 3). exclude_tools names tools whose results are never cleared, your lossless carve-out for results that must stay verbatim. clear_tool_inputs (default false) also removes the call parameters if you want the fuller cleanup. clear_at_least sets a minimum token count per clearing pass; if the API cannot clear that much, the strategy does not run.

The sibling clear_thinking_20251015 strategy manages earlier thinking blocks, with keep set to {type: "thinking_turns", value: N} or "all"; without the strategy, the default varies by model class. The client keeps the original history. Claude sees a removal notice in place of a cleared tool result.

Server-side compaction

As of November 30, 2026, on-demand and threshold compaction are Messages API betas with model- and platform-specific availability. For on-demand compaction, send anthropic-beta: compact-2026-09-04 and set the top-level compaction parameter to {"type": "summarize"}. Send the header again on each request carrying the signed block. Non-blank instructions replace the default summarization prompt and can be up to 16,384 characters. Re-supply needed attachments from summarized turns and reissue any mid-conversation role: "system" instructions that still apply.

For threshold compaction, send anthropic-beta: compact-2026-01-12 and add compact_20260112 to context_management.edits. The only trigger type is input_tokens, with a default of 150,000 and a minimum of 50,000. Use separate requests for on-demand compaction and context editing. Threshold compaction cannot run on a request carrying a signed on-demand compaction block.

Claude Code compaction

/compact replaces the conversation with a structured summary, and the automatic pass works the same way. Claude Code preserves some material by reloading it from disk. It reloads project-root CLAUDE.md, unscoped rules, auto memory, and the plan-mode plan. It re-reads up to five recently read or edited files, most recently modified first. Skill bodies return capped at 5,000 tokens per skill and 25,000 total, with the oldest dropped first. A file over 5,000 tokens returns as a path reference. Re-read it if the contents are still needed. Earlier hook output is summarized with the conversation. SessionStart hooks matching the compact source run again and can add fresh context. You steer the summary’s recall with a focus (/compact focus on the auth bug fix) or standing “Compact instructions” in CLAUDE.md, and /rewind offers “Summarize from here” and “Summarize up to here” for partial compaction.

OpenAI and Codex

OpenAI’s Responses API offers server-side compaction via context_management with compact_threshold, plus a standalone POST /responses/compact endpoint for stateless compaction in long-running workflows. Both return an opaque compaction item. With in-band compaction and stateless input-array chaining, append the returned items in order, then you can drop items before the latest compaction item. With previous_response_id chaining, pass the new user message and let the API manage history. For POST /responses/compact, pass the entire returned window to the next Responses request.

The Codex CLI offers /compact to summarize earlier context and /fork for work that branches. Codex also compacts chats automatically.

Memory and offloading as the lossless layer

The memory tool (memory_20250818) lets Claude request file operations that your application runs against storage you control. Anthropic recommends pairing memory with compaction so information can remain available outside the active context. When context editing and the memory tool are enabled together, Claude receives a warning as the clearing threshold approaches. Check that the required evidence has been saved before depending on it. The low-tech equivalent is the same pattern by hand: a NOTES.md, a checkpoint file, or durable decisions in CLAUDE.md. Anthropic’s engineering post describes the same idea as structured note-taking, notes persisted outside the window and pulled back in when needed, citing Claude Code’s to-do list and a custom agent’s NOTES.md as instances of the pattern.

The cache price of each mechanism

Removing content from a cached prefix can require a new cache write.

  • Clearing invalidates the cached prefix at the point content is removed; Anthropic’s docs advise clearing enough to make the invalidation worthwhile, which is what clear_at_least is for. “You’ll incur cache write costs each time content is cleared, but subsequent requests can reuse the newly cached prefix.” Clearing thinking invalidates the cache at the clearing point. Keeping it avoids that particular invalidation.
  • Claude Code compaction makes a separate request that reads the history it summarizes. It can read cached history while the entry is warm and reads uncached input after expiry. The next request rebuilds the conversation and project-context cache with a shorter history. On the API, a cache_control breakpoint on the compaction block caches the summary, and a breakpoint at the end of the system prompt keeps that layer cached across repeated compactions.
  • Rewind in Claude Code can reuse the earlier prefix while its cache entry is warm and the other cached layers still match.
  • Memory is a standard client tool with no special caching interaction: its calls and results are ordinary tool turns. Include writes and later retrieval in the cost comparison.

Worked example clearing 40,000 tokens

Say a session has 100,000 history tokens, including 40,000 tokens of old tool results eligible for clearing. Assume the trigger is set below 100,000 input tokens, the first edited request writes an approximately 60,000-token prefix, and the following requests hit that cache. Compare 30 requests and count only the fixed history.

Rates are for Claude Sonnet 5.5 as of November 30, 2026. Per million tokens, base input is $2, output is $10, cache reads are $0.10, and five-minute cache writes are $2.50. See the provider pricing index for current rates.

  • Carry a warm prefix. 30 × 100,000 × $0.10/1M = $0.300 estimated.
  • Clear on the first request. 60,000 × $2.50/1M + 29 × 60,000 × $0.10/1M = $0.324 estimated.

Carrying a warm prefix costs $0.010 per request. Clearing costs $0.150 on the first request and $0.006 per request after that. The two paths break even at request 36 under these assumptions. If both paths start cold and write the prefix, carrying it costs 100,000 × $2.50/1M + 29 × 100,000 × $0.10/1M = $0.540 estimated. Clearing still costs $0.324 estimated.

Before choosing a clearing rule, inspect the affected requests. Record the actual cache-write and cache-read token counts, especially when an earlier breakpoint survives or the retained history changes. A long list of current tool results can make the cleared amount smaller than planned. Check how much context the rule frees and whether the next request can still recover the evidence it needs.

A practical policy

  1. Inventory what must match byte-for-byte: error strings, paths, symbol names, working commands, constraints, ruled-out theories. Route those to memory files, CLAUDE.md, exclude_tools, or post-compaction re-statements.
  2. Clear old tool results after verifying that required evidence is stored elsewhere. Test thinking-block clearing separately because later work may depend on earlier reasoning.
  3. Give compaction custom instructions naming your lossless classes, and treat its summary as lossy by default; anything verbatim lives outside it.
  4. Schedule summarization at a natural break while the cache is warm if the history needs summarizing. For mechanical clearing, compare the cost when the existing prefix is still warm with the cost when a write is already needed.
  5. For a durable artifact that survives even a session restart, use a structured checkpoint file rather than trusting any in-context mechanism.

What to do next

The sibling post on structured JSON checkpoint compaction implements the lossless side as a concrete file format. For the billing mechanics behind every option here, see compaction versus prompt cache cost and the context compression explainer. When the context itself is steering the agent wrong, the decision is different: read context poisoning and when to start fresh.

Sources

Interactive report

  • The Long-Context Mirage: A model can accept a million tokens and still miss the line of code you need. Follow the published accuracy results, then price the decision to keep, trim, or leave a long conversation.

How this note was produced

Drafted with AI assistance from committed ByteCosts pricing snapshots and deterministic cost formulas. Figures are grounded in the linked sources (last updated 2026-11-30). Read our editorial & automation policy, inspect the methodology, or report a discrepancy.

Lossless vs Lossy Context Compaction: What to Keep Verbatim. ByteCosts. Updated 2026-11-30. https://bytecosts.com/blog/lossless-vs-lossy-context-compaction/

Sources