Long-Session Compression and Unexpected Token Usage: A Technical Analysis
Long-session compression keeps AI coding assistants within the model context window, but it can also invalidate prefix caches and trigger repeated full-price input processing. This article explains how compression, cache pricing, context-window thresholds, tool definitions, and parallel requests interact; how to distinguish expected cost amplification from implementation defects; and how to reduce unnecessary cache misses in long-running coding sessions.
Long-session compression is designed to replace older conversation turns that are no longer central to the current decision with a summary. This keeps requests within the model’s context window. For AI coding assistants, it is often essential: repository instructions, tool definitions, failed commands, logs, and multiple revisions can quickly consume the available context.
The problem appears when compression interacts with prefix-cache discounts and a pricing model in which uncached input is significantly more expensive than cached input. The tokens saved by removing old history may not compensate for the cost of replaying the prefix at the full input rate.
The user-visible symptom is straightforward: a relatively short period of actual work consumes an allowance equivalent to several hours. This is usually the result of interacting mechanisms rather than a defect that can be fixed by changing a single conditional.
Where the Unexpected Cost Comes From
A model request can generally be divided into three billable categories:
- Uncached input tokens
- Cached input tokens
- Output tokens
In common industry pricing models, cached input is often an order of magnitude cheaper than new input, while output is more expensive than input. As a result, the key question is often not how much text the model generated, but whether the beginning of the request is byte-for-byte aligned with a recent request.
Automatic compression changes the early conversation that follows the stable request prefix. Once the original turns are replaced by a summary, the prefix changes. The next request must then include the system instructions, tool definitions, summary, and recent conversation as uncached input.
If the task continues, the summary itself occupies part of the context window. New tool results may push usage over the threshold again, causing another compression cycle. The same full-price prefix can then be paid for repeatedly. A single compression may reduce the amount of historical text, while repeated compression can increase total input cost.
Therefore, a sudden increase in usage after a particular date does not necessarily mean that the billing rules changed on that date. More common explanations include:
- The client or service moved the compression threshold earlier.
- The context-window declaration in the model directory changed.
- The proportion of long-running sessions increased.
- Multiple conditions that were previously rare began occurring together.
Without version information and request traces, the behavior should not immediately be labeled a defect. With proper traces, the first things to check are the number of compression events and the cache hit rate—not output length.
Why Compression Is Inevitable in Long Sessions
The context window is a hard limit. As usage approaches that limit, continuing to append the conversation unchanged may cause a request to fail or be truncated. The assistant must then discard content, summarize it, or use a sliding window.
A common design uses a soft threshold and a hard limit. For example, compression may begin when usage reaches roughly 90% of the window and become mandatory around 95%, regardless of the user’s configuration. Earlier turns are replaced with a summary. The interface may only show messages such as “Compressing context” and “Compression complete,” without revealing how much future cache value was lost when the original content was replaced.
Configuration is often asymmetric. Users may be allowed to trigger compression earlier, while delaying it is restricted by the declared context window. If a disable switch exists, it may be available only to internal service threads and not to ordinary user configurations.
This means that compression is not optional in a sufficiently long session. Its goal is to reduce the request size and prevent context overflow, not to maximize cache discounts. These goals rarely conflict in short sessions, but the difference becomes visible in long ones.
Model directories cached in different environments may also declare different context-window sizes for the same model. If the declared limit changes, the compression threshold moves with it. Users may therefore see the same type of task become more or less expensive on a particular day even though the application code did not change.
Troubleshooting should record:
- The declared context-window limit
- The soft and hard thresholds
- The actual number of compression events
- Context usage before and after compression
Looking only at the number of generated code lines is insufficient.
The First Cost: Breaking the Prefix Cache
Prefix-cache matching is strict. The service must determine that the request matches a recent request exactly from the beginning up to a particular byte offset before that section can be billed as cached input.
The cache key commonly includes:
- Fixed system prompts
- Tool and function definitions
- Repository-level instructions
- Earlier conversation turns that have not been rewritten
A change in ordering, whitespace, or the field order of a tool schema may be enough to invalidate the key.
Compression performs the opposite operation. Instead of appending content, it replaces a large block of old text with a new summary. Content before the replacement point may remain stable, but everything after that point shifts. In many implementations, the entire previously cacheable prefix is treated as new content.
The first model request after compression may therefore resend hundreds of thousands of tokens as uncached input.
The price difference can be illustrated with hypothetical numbers. These figures are not current prices for any particular provider; they only demonstrate the scale. Assume:
- Uncached input: 250 units per million tokens
- Cached input: 25 units per million tokens
- Output: 1,250 units per million tokens
After compression, replaying 300,000 input tokens with almost no additional output would cost approximately 7.5 units if the input remained cached, but 75 units if it became uncached. The difference is one order of magnitude.
If compression happens two more times, the same large prefix may be paid for twice again. The input-side cost would approach 225 units, even if the newly generated code and explanations amounted to only a few tens of thousands of output tokens. This is how a few minutes of work can appear to consume an allowance equivalent to several hours.
Compression may remove 180,000 tokens by replacing 200,000 tokens of history with a 20,000-token summary. However, the removed history may already have been very cheap because it was cached. Once the cache discount disappears, the remaining prefix can be billed at the full uncached rate.
The result can be counterintuitive:
Fewer transmitted bytes, but a higher bill.
The Second Cost: Summaries Can Trigger More Compression
A summary is not free context. To preserve continuity, it must retain enough detail about:
- Files that were changed
- Commands that failed
- Constraints rejected by the user
- Decisions already made
- Work that remains incomplete
The more reliable the summary needs to be, the longer it becomes. That means the context window does not fall as far after compression. As the task continues to produce tool output and diffs, usage can quickly approach the threshold again.
This creates the pattern often described as repeated automatic compression in a long session. Each compression may:
- Generate a new summary that differs from the previous prefix, invalidating the cache again
- Require an additional model call to produce the summary
- Cause the first business request after compression to be billed as uncached input
- Lead to repeated file inspection and exploration if the summary is incomplete, increasing the number of tool rounds
This is a feedback loop rather than a linear cost. A short task may trigger compression zero or one time. A multi-file coding session that runs for hours may have its compression frequency become a major part of the cost curve.
The Third Cost: Tool Definitions and System Prompts Are Replayed
The prefix of a coding-assistant request often contains system instructions and tool definitions that are longer than the user’s latest question. These sections are highly stable and should be among the best candidates for caching.
If compression causes these stable sections to be reordered, regenerated, or combined with a different tool list, they may lose their cache discount as well. Even if only the early conversation needed to change, a coarse-grained implementation may treat the entire request prefix as new.
Compression also tends to occur when the context is nearly full, which is precisely when the prefix is largest. The most expensive replay can therefore happen at the moment when invalidating the cache is most costly.
If the client immediately starts several parallel subtasks after compression, every subtask may carry the new uncached prefix. Parallelism improves throughput in many situations, but during a cache-cold period it can multiply the cost.
Distinguishing a Mechanism Effect from an Implementation Defect
The following observations help separate expected pricing behavior from a genuine implementation problem.
1. Align the timeline
Mark the exact timestamps of compression events on the usage chart rather than grouping usage by calendar day. If a spike occurs immediately after the first request—or first batch of requests—following compression, that strongly supports a mechanism-level explanation.
2. Separate the three token categories
If uncached input rises sharply while output remains relatively stable, the model did not necessarily become more verbose. The likely causes are cache invalidation or a longer effective prefix.
3. Measure compression frequency
If compression intervals become shorter within the same session, the summary may not be reducing the context enough, or tool output may be growing faster than compression can offset it.
4. Check the declared context window
If the client’s cached model directory was updated on a particular date, the soft and hard thresholds may have moved with the declared context limit. A sudden change in usage may therefore resemble a configuration release rather than a logic error.
5. Check prefix stability
Compare hashes of the system prompt, tool schemas, and repository instructions before and after compression. An ideal implementation replaces only the early conversation while leaving the stable sections byte-for-byte identical. If the entire request stream changes, the implementation is operating at an unnecessarily coarse granularity.
6. Separate summary calls from business calls
The call that generates the summary is an additional cost. It should be tracked separately from the subsequent call that continues the coding task.
If compression did not occur, the prefix hash did not change, and cache hit rates remained normal, but usage is still abnormal, investigate duplicate requests, retry storms, or incorrect billing aggregation. Those cases are more likely to indicate a defect or a client retry-policy problem.
By contrast, when compression, cache invalidation, and full-prefix replay occur together, the pricing structure should be examined first.
Practical Ways to Flatten the Cost Curve
When automatic compression cannot be disabled, the goal is not to eliminate compression entirely. The goal is to reduce:
- How often the stable prefix is invalidated
- How large the prefix is when invalidation occurs
Split sessions by task
Keep one objective, branch, or related group of files in a single session. When the task, repository, or scope changes substantially, start a new session instead of appending unrelated history indefinitely.
The first request of a new session may not benefit from the old cache, but the prefix is shorter. Subsequent requests can then build a stable cacheable prefix.
Keep stable instructions byte-for-byte consistent
Repository instructions, coding guidelines, and tool definitions should avoid unnecessary changes to whitespace, ordering, and schema fields. Frequently modifying the system prompt effectively gives up the cache discount, even when the user has not triggered compression.
Limit tool-output volume
Before adding test logs, dependency trees, and search results to the context, truncate or deduplicate them. Keep the failure-relevant portions rather than carrying the complete output forward.
Raw logs are a major driver of context growth and are also likely to be repeated in later summaries.
Avoid high concurrency immediately after compression
After compression, allow one primary request to establish the new cacheable prefix before launching parallel subtasks. Otherwise, several requests may pay for the same full-price prefix at the same time.
Set an information budget for summaries
A summary should preserve decisions, constraints, verified facts, and unfinished work rather than restating the full conversation. A budget that is too small causes repeated exploration; a budget that is too large causes the next compression to arrive sooner.
A fixed summary template can limit section sizes and make the amount of context reclaimed more predictable.
Monitor the right metrics
At minimum, collect:
- Context-window utilization
- Compression count
- Prefix hashes before and after compression
- Cached input tokens
- Uncached input tokens
- Output tokens
- Retry count
Alerts should not focus only on total allowance consumption. A more direct signal is uncached input immediately after each compression event, because it corresponds directly to the first major cost in this analysis.
Separate long and short sessions in quota reporting
Average costs for short questions can hide the replay cost of long coding sessions. When evaluating whether a tool has become more expensive, analyze long-session share and compression frequency rather than relying only on per-user averages.
An Illustrative Control Flow
The following pseudocode describes the control logic. It is not an interface for any specific product.
on_before_request(session):usage = estimate_tokens(session.prefix)limit = session.declared_windowif usage >= hard_ratio * limit or usage >= soft_ratio * limit:summary = compact_older_turns(session, budget=summary_budget)session.prefix_hash = hash(system + tools + summary + recent)mark_cache_cold(session) # Expect the next business request to be uncachedrecord_metric("compact", usage, summary.tokens)else:record_metric("cache_expect_hit", session.prefix_hash)call_model(session)record_metric("billable_input_miss", "billable_input_cached", "output")
Two details are important.
First, compression occurs before the business request. The user may not have received any new code yet, but the billing system may already record a large amount of uncached input.
Second, declared_window comes from the model directory available at that time. Updating that directory can change which branch executes even when the business logic is unchanged.
How Mechanism Effects Can Coexist with Real Defects
A real implementation defect is still possible. Examples include:
- Compressing when the context is below the configured threshold
- Appending summaries instead of replacing the original summaries
- Failing to reuse the prefix that was just generated
- Resending the entire request during retries
- Exposing an internal-only compression strategy to all users
These problems can make the cost much higher than the intended design.
A useful test is whether full-price replay occurs when the prefix is stable and context usage has not crossed the declared threshold. If it does, the behavior deserves investigation as a defect.
If compression occurs only at the expected threshold and naturally invalidates the cache, the behavior is more likely a consequence of the interaction between compression and cache semantics. It should then be addressed through session management and product strategy.
Possible mitigation strategies include:
- Keeping tool definitions and system prompts byte-for-byte unchanged during compression
- Reusing the compressed prefix for multiple subsequent requests
- Applying cost protection to the request immediately following compression
Cost protection does not necessarily require changing the unit price. For example, if the next request differs from the previous one only in the summary section, a service could charge the changed section as uncached while preserving the cache discount for the stable prefix.
That requires server-side prefix-difference caching rather than a cache model based only on complete byte-for-byte equality. If differential caching is unavailable, the client must reduce the number of compression events. The two approaches are complementary.
Conclusion
Unexpected quota consumption in long sessions is best understood as the combination of three costs:
- Compression rewrites early conversation turns, invalidates the prefix cache, and causes the largest request in the session to be replayed as uncached input.
- The summary itself consumes context space, allowing compression to recur.
- Tool definitions, system prompts, and parallel subtasks can multiply the cost of each cache invalidation.
Compression is designed to keep a session within the context window, not to minimize billing. During troubleshooting, align compression timestamps, prefix hashes, and the three token categories. For mitigation, split sessions by task, keep stable prefixes unchanged, limit tool output, and avoid high concurrency while the cache is cold.
This framework explains how a short period of work can consume a surprisingly large allowance without incorrectly treating a pricing interaction as a one-time code defect.
