Direct answer
Compaction can cost more than continuing without it because the session processes material to create a summary, then uses a new prefix after older turns are replaced. It does not always cost twice, and the supplied sources publish no universal compaction price. Model the summary pass, the retained recent turns, the resumed prefix, cache state, and later work as separate cost inputs.
Official: compaction replaces older conversation turns with a summary written on the server. Recent turns remain word for word. On-demand compaction is user-triggered, while threshold compaction triggers at a configured input-token threshold.
The practical response is to measure a fixed task with and without compaction. Use normalized prices or actual usage records, show every assumption, and compare total verified cost rather than the price of one request. A smaller resumed context can repay the summary cost over later turns, but that outcome depends on how much work remains.
The concrete win is a manageable starting state for continued work. The honest loss is an extra billed transition plus a summary that may omit exact details. Automatic compaction should follow a cost and retention policy, not a belief that summarizing is free.
Why the transition has a cost
A summary changes session state. Older turns are replaced, recent turns remain, and the next request uses the resulting prefix. Each of those stages can involve input processing and output generation.
The phrase “cost twice” describes a possibility, not a guaranteed multiplier. Material may be processed during summarization and then represented again by the summary and retained turns in later requests. Whether that produces a higher total depends on context size, cache state, output length, and the number of remaining turns.
Separate compaction from ordinary context growth. A long session can become expensive because each new turn carries a large prefix even without compaction. Compaction may reduce that repeated prefix while adding a summary event. The comparison must cover the same task and the same acceptance check.
| Cost stage | What changes | What to record |
|---|---|---|
| Before compaction | Full recent conversation and older turns | Input size, cache state, current task |
| Summary pass | Older material is summarized on the server | Actual submitted input and summary output |
| Prefix transition | Older turns are replaced by the summary | New prefix size and retained recent turns |
| Resumed work | Session continues from the new state | Fresh input, cache reads, output, retries |
| Later turns | Work proceeds after the transition | Repeated-prefix cost and remaining task length |
The compaction context-retention test answers a different question: which facts survive. Cost analysis should include that test because a cheap summary that drops a critical constraint can increase review and rework.
Use the cost per verified change framework as the final unit. A lower token total is not a win if the resumed agent repeats discovery or violates an acceptance criterion.
What compaction changes
Official: older turns become a server-written summary, while recent turns remain word for word. The summary is therefore not a rewrite of the entire transcript. It replaces one part of the state and leaves another part intact.
On-demand compaction begins with a user action. Threshold compaction begins when a configured input-token threshold is reached. The frozen sources do not provide a universal default threshold, a fixed summary length, or a guaranteed retention ratio. Do not fill those gaps with remembered values.
A threshold is a trigger, not a cost cap. Crossing it can start a state transition whose price depends on the material being summarized and the cache state. Teams that need a firm spending boundary should use separate controls rather than treating the threshold as a budget guarantee.
| Compaction mode | Trigger | Cost question | Retention question |
|---|---|---|---|
| On-demand | User chooses the transition | Is now a useful boundary for the remaining work? | Are exact constraints preserved? |
| Threshold-based | Configured input-token threshold is reached | Does automatic timing match the task’s economics? | Does the summary carry active decisions? |
| No compaction | Session continues with existing context | How quickly does repeated-prefix cost grow? | Is full detail still available in context? |
The task budgets versus hard stops guide explains why advisory limits should not be confused with enforced controls. Compaction thresholds belong on the trigger side of that distinction.
The stop reasons documentation describes response states such as model_context_window_exceeded and max_tokens. Those API states are not compaction triggers. Separate response limits, context pressure, and compaction policy when diagnosing a session.
The summary pass
The summary pass is the first cost bucket. Its input depends on what the service actually submits for summarization, and its output includes the generated summary. The frozen fact pack does not expose a universal request shape for every Claude Code surface.
Use observed request or usage data when the client provides it. If the exact input is not visible, mark it unknown and model a range instead of asserting that every older token was submitted in one request.
Cache state can change the input price. Official: five-minute cache writes cost 1.25 times base input price, one-hour writes cost 2 times, and cache reads cost 0.1 times, with model-specific exceptions. Those multipliers matter only if the relevant prompt segments are cacheable and identical.
The summary output also has a price. The prompt-caching economics guide focuses on input-prefix reuse, but a compaction worksheet must keep output tokens in a separate column. Do not apply an input cache multiplier to generated summary tokens.
A practical estimate uses variables rather than a memorized dollar amount:
Summary pass ≈ cached-write input + cache-read input + fresh input + summary output
Each term needs its own applicable price. This is a worksheet model, not an official billing formula or a claim that the service exposes those buckets separately in every interface.
The new prefix
After compaction, the resumed session carries the summary and the recent turns that remained word for word. Other instructions and task material may also be present. The new prefix is therefore not just the summary length.
A changed prefix can affect caching. If the new sequence differs from a previous cached sequence, the affected segment may need fresh processing or a new cache write. Do not assume that a shorter prefix automatically produces a cache hit.
The idle-session cache-miss analysis explains why time away can change cache state. An expired TTL or a changed prefix can create a miss, but not every idle resume misses. Measure the actual state before assigning a cause.
The new prefix also carries a retention risk. A concise summary can omit an exact file path, a rejected dependency, or a test constraint. The context-portable migration guide recommends keeping critical task state outside the transcript so a new session can recover it.
Treat prefix size and prefix usefulness as separate measures. A smaller prefix that forces the agent to reread the repository can cost more overall than a slightly larger brief that preserves the investigation.
Cache interaction
Compaction and caching solve different problems. Compaction changes what the conversation carries. Caching changes the price of processing an identical prompt segment within its lifetime. Combining them can help or hurt depending on timing and prefix identity.
A stable prefix can reduce repeated input cost. A compaction event can change that prefix and require a new write or fresh processing. The prompt-caching documentation also lists model-specific minimum cacheable prompt sizes, so not every short prefix qualifies.
Track three measurements separately: fresh input tokens, cache-write tokens, and cache-read tokens. Then note the applicable TTL and model. Without those fields, a before-and-after cost comparison can mistake a cache change for a compaction effect.
| Cache state during compaction | Possible cost effect | Evidence needed |
|---|---|---|
| Existing prefix is read | Summary-pass input may use read pricing | Cache-read token count and TTL |
| Prefix is written | Input may use write pricing | Cache-write count and selected TTL |
| Prefix changes after summary | New sequence may miss or require a write | Prefix identity and fresh-input count |
| Prompt is below minimum | Segment may not be cacheable | Model family and prompt size |
| Idle period exceeds TTL | A later resume may miss | Timestamps and observed cache state |
Official: cache hits require 100 percent identical prompt segments. That rule makes prefix design important, but it does not prove that a particular compaction sequence will hit. Model-specific exceptions also prevent treating the published multipliers as universal across every model.
The long-context prefill latency test provides a measurement pattern for waiting stages. The frozen sources publish no universal prefill or decode rate for Claude Code, so avoid translating cache pricing into an invented speed claim.
A cost worksheet
Build the worksheet from observed inputs. If a field is unavailable, use a named assumption and show the result as a range. Do not hide the gap inside a single total.
| Input | Symbol | Where to obtain it |
|---|---|---|
| Base input price per token | P |
Official model pricing for the selected model |
| Output price per token | O |
Official model pricing for the selected model |
| Summary-pass input | A |
Request or usage record, otherwise bounded assumption |
| Summary output | S |
Observed summary length, otherwise scenario value |
| New resumed prefix | B |
Summary plus retained turns and other instructions |
| New work input | Q |
Input added after the transition |
| Resumed output | T |
Generated answer or tool-planning output |
| Cache multipliers | W, R |
Observed cache state and documented TTL |
A simplified no-cache estimate is:
Compaction path = A × P + S × O + (B + Q) × P + T × O
A no-compaction comparison needs its own input and output measurements for the same remaining task. If the uncompacted session would exceed a limit or require a restart, record that outcome rather than pretending the comparison continued under identical conditions.
Derived: the difference between paths is compact total − no-compaction total. A positive result means the compaction path costs more over the measured window. A negative result means it costs less. Neither result predicts the next task unless its context and workload are comparable.
The cost documentation describes /usage for session metrics and plan bars. Use the available session view as one evidence source, but do not assume it exposes every cache bucket needed for this worksheet.
Worked example: a normalized transition
This example uses invented token counts to demonstrate arithmetic. It is not a benchmark and does not describe a guaranteed Claude Code request shape. Let P be the base input price per token and O the output price per token.
Assume 12,000 older tokens and 2,000 recent tokens before compaction. For simplicity, assume the summary pass submits the 12,000 older tokens and produces an 800-token summary. Assume the resumed prefix contains that summary plus the 2,000 retained recent tokens. The next task adds 1,000 fresh input tokens and generates 600 output tokens.
| Path | Input calculation | Output calculation | Normalized cost |
|---|---|---|---|
| Compaction summary pass | 12,000 fresh input tokens | 800 summary tokens | 12,000P + 800O |
| Resumed turn after compaction | 800 summary + 2,000 recent + 1,000 new = 3,800 input tokens | 600 answer tokens | 3,800P + 600O |
| Combined compaction path | 15,800 input tokens | 1,400 output tokens | 15,800P + 1,400O |
| No compaction, same next turn | 12,000 older + 2,000 recent + 1,000 new = 15,000 input tokens | 600 answer tokens | 15,000P + 600O |
Derived difference: the compaction path costs an extra 800P + 800O over this single-turn window under the stated assumptions. The extra input is the summary carried into the resumed prefix, and the extra output is the summary itself. A single-turn comparison answers only whether the transition added cost before later reuse, while the full task may become cheaper once several resumed turns avoid carrying the older context again.
That result does not prove compaction is wasteful. If later turns would otherwise carry the 12,000 older tokens again, the smaller prefix can repay the upfront difference. The example also ignores cache writes, cache reads, retries, tool results, and any difference in task behavior.
For a simple extension, suppose each later turn avoids d tokens of fresh input at price P. After n later turns, the avoided input cost is n × d × P. Compare that amount with the upfront difference, while keeping output and cache effects separate.
Practical response: measure before automating
Use this sequence when deciding whether automatic compaction fits a workflow. It keeps the cost comparison tied to a real task.
- Define the remaining work and acceptance check.
- Record the pre-compaction context and cache state.
- Choose a natural boundary for an on-demand test when possible.
- Capture the summary-pass input and output if visible.
- Record the new prefix and retained recent turns.
- Continue the same task and capture later input, output, and retries.
- Run a comparable no-compaction control when the context limit allows it.
- Compare total cost and verification quality over the same window.
- Store exact constraints in an external task brief.
- Decide whether threshold compaction helps, hurts, or needs a narrower policy.
For team workflows, use the usage tracking and cost API guide to understand historical accounting. Official: the Usage and Cost API typically provides data within five minutes of request completion, usage buckets can be 1m, 1h, or 1d, and cost data is daily. Priority Tier costs are excluded from the cost endpoint, and the API is legacy; new integrations should use the Analytics API.
Those granularities are not a real-time compaction trace. If the interface does not expose the summary request, mark the stage unknown and use a controlled before-and-after task comparison instead.
The MCP output truncation guide matters when tool results dominate context. Structure logs so the decisive error survives, then decide whether compaction or narrower retrieval is the better response. A summary should not be the first place a hidden failure is discovered.
The monorepo search and token-budget guide can reduce unnecessary context before compaction becomes necessary. Scoped retrieval and compaction are different controls, and either one can be the wrong choice for a particular task.
Budget the measurement, not only the summary
A compaction decision often sits inside a larger delegated workflow. Parallel agents can repeat discovery before the parent compacts, which makes the summary larger without making the evidence better. The subagent context and duplicate-work analysis provides a briefing pattern that can reduce that overlap before it reaches the transcript.
If a scout stops before returning evidence, the subagent stop and resume semantics determine whether to dispatch a fresh task or resume completed history. If parallel editors are changing files, the worktree isolation pattern keeps their working directories separate while the parent measures the combined session cost.
Perform the measurement outside the session being summarized. A short task log should record the pre-compaction state, the trigger, the observed summary size, and the acceptance result. The proof-of-work packet helps ensure that a lower resumed cost is paired with a result that can be reviewed.
A stale background count is not evidence of continuing spend. The background running-count diagnosis separates display state from process and result state. Use request or usage evidence for cost, not the presence of a running badge.
Security constraints also deserve stable wording. The agent harness security boundaries explain why permission enforcement and model intent are separate. Preserve forbidden paths and credential rules in the external brief so compaction does not become the only record of a boundary that must survive.
Honest loss and data gaps
The concrete win is a smaller resumed prefix. That can make continued work easier to manage and can reduce repeated input over later turns. The honest loss is the transition itself: summary generation adds work, the new prefix can disturb caching, and exact context can be lost.
Unknown: the frozen sources do not publish a universal compaction price, default threshold, summary-length ratio, or controlled Claude Code cost comparison. They also do not establish that automatic compaction saves money for a typical session. Future updates should include the model, client version, task fixture, cache observations, and total verified cost.
The compaction documentation is the authority for state replacement, not a billing guarantee. The prompt-caching documentation supplies rates and minimums, but it cannot predict the cache state of a specific compaction event.
Do not convert a subscription quota into a token price. The cost documentation describes plan and session controls, while API pricing is a separate measurement. A team comparing pathways should keep subscription cost, API usage, and human review effort in distinct columns.
The legacy-code characterization workflow is relevant when a summary drops an undocumented rule. Cost savings do not justify continuing with a handoff that no longer states the behavior the change must preserve.
A limited OpenAI-format test route
For a separate cost experiment in an OpenAI-format agent, One AI API Key provides a hosted lane. On 2026-11-27, its catalogue showed 76 listed models and 46 available-now free IDs across 22 families. The free IDs share 100 requests and 5,000,000 tokens per day per account, resetting at 05:30 IST / 00:00 UTC. Accounts can have up to three keys, with one request in flight per key on free models.
The free IDs are OpenAI-format only. They are not a Claude Code route. Claude Code uses the Anthropic-format endpoint, and all four Claude IDs were marked unavailable on 2026-11-27. Do not paste a free ID into Claude Code or use this lane to claim a Claude compaction benchmark.
An OpenAI-format agent such as OpenCode, Cline, or Cursor can use the endpoint quickstart for setup. The prepaid pricing page documents signup credit and billing without a subscription or seat fee. Use the LLM cost calculator for a separate estimate and review the privacy and retention policy before sending session material.
The loss is comparability. Another harness may summarize context differently and expose different usage fields. A smoke test can validate the route and your worksheet, not reproduce Claude Code’s server-written summary behavior. The coding-agent model selection guide can help choose a test model without treating model choice as the cause of a compaction cost.
FAQ
Does compaction always cost twice?
No. It can add a summary pass and a new prefix, but later turns may carry less context. The frozen sources publish no universal multiplier. Compare the complete task with and without compaction under stated assumptions.
Are recent turns summarized?
Official: recent turns remain word for word. Older turns are replaced with the server-written summary. The exact split and summary length are not fixed in the supplied sources.
Is threshold compaction a spending cap?
No. It triggers at a configured input-token threshold. The resulting cost depends on the summarized input, cache state, output summary, and resumed prefix. Use separate hard controls when spending must stop.
Can prompt caching make compaction cheaper?
It can change the price of eligible input segments, but a new prefix may miss or require a write. Cache hits require identical segments, and model-specific minimums and exceptions apply. Measure fresh, write, and read tokens separately.
What data should I capture before enabling automatic compaction?
Capture the task, model, client version, pre-compaction context, cache state, summary input and output if visible, new prefix, resumed work, later turns, and verification result. Mark unavailable fields unknown instead of inventing them.
More Claude Code troubleshooting
- Claude Code WSL IDE environment-variable diagnosis
- Claude Code WSL2 memory-warning breakdown
- Claude Code Windows subagent MCP memory leaks
- Claude Code VS Code WebSocket regression test
- Claude Code desktop browser-pane crash recovery
- Claude Code subagent hang and timeout controls
- Claude Code 429 error decision tree
- Claude Code billing-dispute evidence packet
- Claude Code refund and support policy guide
- Claude Code hallucinated-package supply-chain controls
- Claude Code GitHub Actions secret boundaries
- Claude Code repository-hook security review
- Claude Code extension-trojan remediation steps
- Claude Code CVE-2026-55607 sandbox boundary
- Claude Code auto-mode classifier limitations
- Claude Code destructive git guardrails
- Claude Code generated-test oracle bias
Sources
- Claude Code compaction documentation, official older-turn replacement, verbatim recent turns, and trigger modes.
- Claude prompt caching documentation, official cache rates, TTLs, minimums, and identity rule.
- Claude Code cost documentation, official session usage and team cost controls.
- Claude Usage and Cost API documentation, official historical latency, buckets, filters, and caveats.
- Claude stop reasons documentation, official response states distinct from compaction triggers.
- Claude Code troubleshooting documentation, official recovery guidance for host and session symptoms.