Long-Session Quota Drain: How Auto-Compaction and Prefix Cache Invalidation Stack Up
A long-context coding agent can burn an entire quota window on a task that should take minutes. This article breaks down the three cost layers that open at once in long sessions: auto-compaction shattering the prefix cache, summary generation and reinjection overhead, and agent loops with retries multiplying repeated calls. It also covers how to diagnose the issue by looking at compaction points and billing dimensions, plus engineering mitigations such as prefix stability, tool-output trimming, staged tasks, budget circuit breakers, and cost observability.
Symptom and Conclusion: A Multi-Minute Task Drains a Full Quota Window, and the Problem Looks Like Coupled Cost Structures
A certain class of long-context AI coding assistants started showing abnormal quota consumption after a specific point in time: an agent task that used to finish in a few minutes consumed an entire quota window. The first instinct is usually “the tool must have a bug.” But looking at how general long-session agent architectures work, this is most likely not a single-point issue fixable with a one-line change. Instead, three cost accounts open at the same time in a long session: automatic context compaction shatters the prefix cache, summary generation and reinjection add extra overhead, and the agent loop with retries amplifies repeated calls. In short sessions these three are unrelated; they only stack up in long tasks with many tool-call rounds and continuously growing context.
To decide whether it is a defect, you cannot look only at “how much quota was consumed.” You have to look at which billing dimensions the consumption lands in: how much goes to regular input, cached input, output, tool calls, and retried requests; how the cache hit rate changes before and after each compaction event; and whether the first request after compaction triggers full-prefix re-billing. If these metrics all degrade around the compaction point, it looks much more like the billing structure coupling with long-session mechanics than a single faulty code path.
The Trigger: Why Auto Context Compaction Is Hard to Turn Off
Every long-context model has a context window limit. As a session approaches the window threshold, the system typically compresses earlier turns into a summary to keep the input size of subsequent requests under control. The UI may show messages like “compacting context” or “context compacted.” The problem is that this compaction usually has no off switch exposed to ordinary configuration: a config option may only make compaction happen earlier, not delay or disable it; the context window ceiling may also be constrained by model metadata and cannot be pushed back indefinitely.
Compaction is meant to save money by sending fewer historical tokens. In agentic coding tasks, however, it can become the most expensive step. Compaction is not simple deletion; it rewrites the early conversation, replacing original messages, tool outputs, and code snippets with a semantic summary. The meaning survives, but the byte-level prefix changes.
The general trigger logic can be summarized with the following pseudocode:
if current_context_tokens >= compact_threshold:summary = generate_summary(early_messages)messages = [system_prompt, tool_defs, summary, recent_messages]emit("context_compacted")
The logic itself is not complex. What is complex is its effect on the billing chain.
Cost One: Compaction Breaks the Prefix Cache
In model billing, prefix caching usually offers a substantial discount. A cache hit requires the beginning of the request to be byte-for-byte identical to some recent request: the system prompt, tool definitions, early conversation, and fixed examples together form the cache key. If a single byte in the prefix changes, the whole cache key is invalidated.
Compaction does exactly the opposite of that requirement: it rewrites the early conversation into a summary. So the first request after compaction no longer hits the cache for a prefix of hundreds of thousands of tokens, and all of it is billed as regular input. An order-of-magnitude price difference is lost in this one step. Worse, compaction is not a one-time event. The summary itself takes up space, the task keeps advancing, tool outputs keep being reinjected, and the context quickly approaches the threshold again, triggering another compaction. Every compaction means paying the full prefix again.
before_compact: prefix = [system, tools, msg1, msg2, ...]after_compact: prefix = [system, tools, summary, recent...]cache_key(before) != cache_key(after)=> first request after compaction loses prefix cache
So the “abnormal quota usage” users see may not be the model suddenly getting more expensive, but the cache discount being repeatedly discarded at compaction points.
Cost Two: Summary Generation and Summary Reinjection Are Not Free
Compaction itself costs money. Generating a summary requires a model call, producing input and output tokens, and the summary then enters subsequent context and keeps occupying the window. More subtly, a summary may lose details, causing the agent to re-read files, re-run commands, and re-request tools, or to take more rounds because of a misunderstanding. In long sessions, those extra rounds push the context higher, forming a “compact—reinject—compact again” loop.
From an observability standpoint, compaction events often appear only as UI hints or log events and are not reflected directly in billing details. Users see quota dropping fast but cannot see how much each of “full input on the first request after compaction,” “summary generation output,” and “repeated tool calls” contributes. The problem then gets attributed to “a tool bug” rather than to “an opaque compaction strategy and billing dimensions.”
Cost Three: Agent Loops and Retries Amplify Everything
Intelligent coding tasks are usually not single-turn Q&A but multi-round agent loops: read code, run commands, inspect logs, edit files, verify again. Every round reinjects tool output into the context, and error logs, stack traces, patches, and test results can be very long. If the task automatically retries after a failure, or the agent repeatedly tries different approaches, the number of requests and input tokens multiplies. Once compaction triggers at that point, the cache-invalidation cost is amplified across many requests.
Stack the three accounts together: compaction triggers cache invalidation, summary reinjection grows the context, and the agent loop increases the request count. The end result is “a multi-minute task drains a full window.” This looks more like a long-session cost model lacking budget constraints and observability than a function written incorrectly.
How to Investigate: Look at the Compaction Point First, Then the Billing Dimensions
Recommended order of investigation:
- Minimal reproduction: run the same kind of task in a short session and a long session, and compare the quota consumption curves.
- Record compaction events: mark the time of each compaction, the context size before and after, and the number of compactions.
- Break down billing dimensions: measure the share of regular input, cached input, output, tool calls, and retried requests.
- Watch the cache hit rate: focus on whether the hit rate for the first request after compaction drops sharply.
- Check prefix stability: whether the system prompt, tool definitions, dynamic timestamps, or random IDs are inserted into the prefix.
- Set a budget circuit breaker: for long tasks, cap the maximum number of requests, maximum input tokens, and maximum number of compactions per stage.
If the compaction point overlaps closely with the cost spike and the cache hit rate falls to zero after compaction, prioritize improving prefix stability and the compaction strategy rather than chasing a single line of code.
Engineering Mitigations: Making Long-Session Cost Predictable
First, stabilize the prefix. Keep the system prompt and tool definitions fixed, move dynamic content later, and reduce unnecessary cache-key changes. Second, reduce tool-output reinjection: truncate, summarize, or externally store logs and code snippets, and put only the necessary references back into the context. Third, split the task into stages, replacing an infinitely long session with explicit stage summaries and keeping external memory in structured storage. Fourth, add a post-compaction budget circuit breaker: if the first request after compaction carries full input, limit subsequent rounds or require human confirmation. Fifth, build logging services and monitoring alerts that record compaction count, cache hit rate, input/output share, and tool-call count per session, forming a traceable cost chain.
The most worrying thing about this kind of “abnormal quota usage” is not any single consumption event but the invisibility of the cost chain. Only by observing auto-compaction, prefix caching, summary reinjection, and the agent loop separately can you tell whether it is an implementation defect or the combined result of long-session mechanics and the billing structure.
