# Which invariants prevent KV-cache-aligned compaction from silently re-billing cached prefix tokens as fresh input **Date of Record:** 2026 November 21 **Scope:** Applies to agents that drive multi-turn execution against a provider exposing prefix-cache billing (Anthropic prompt caching, OpenAI automatic prefix caching, Gemini context caching, or self-hosted vLLM/SGLang block caches) and that run a compaction/eviction scheduler to stay under a context-window token budget. Does not apply to stateless single-shot inference or to providers that bill flat per-token regardless of prefix reuse. ## Core Distinction There are two distinct token ledgers an agent must track, and conflating them is the source of the failure: - **Occupancy** — how many tokens currently sit in the live context window (the number that must stay under the model's max and that drives per-turn attention cost). - **Cache residency** — how many of those tokens match a previously-billed prefix at a cache-aligned offset, and therefore bill at the cache-read rate rather than the fresh-input rate. A token-budget scheduler optimizes *occupancy*. A KV-cache-aware layout optimizes *residency*. The dangerous boundary is that **compaction reduces occupancy while it can destroy residency**, and the cost function is non-monotonic across that operation: dropping a middle span to save 8k occupancy tokens can invalidate every cached block *after* the cut, re-billing a 60k-token suffix at full input price on the next call. The invariant that must hold is: *a compaction is only cost-positive if the tokens it evicts are billed at a rate higher than the re-billing penalty it incurs on the surviving suffix.* ## What Was Observed A long-running research agent (multi-turn, ~40 tool calls per task) ran against a provider with 1024-token cache blocks and a 5-minute TTL. Its scheduler triggered compaction whenever occupancy exceeded 85% of a 128k window. The compaction strategy was "summarize the oldest 30% of turns into a single digest block, keep recent turns verbatim." Trace of a representative failure: 1. Turn N: occupancy 109k. Suffix from token offset 0 to 108k is fully cache-resident (billed at 0.1×). Only the last ~1k of new tool output bills at 1.0×. 2. Scheduler fires. It replaces turns 1–12 (offsets 0–31k) with a 1.4k digest. New occupancy ≈ 79k. The scheduler logs a 30k-token *saving* and considers the operation a win. 3. Turn N+1: the prompt is now `[digest(1.4k)] + [turns 13..N(77.6k)]`. The digest does not match any cached block. The first cache-aligned block boundary (1024) now contains digest text, so **every block from 0 to 79k is a cache miss**. The 77.6k of "preserved" recent turns are re-billed at 1.0× input price. 4. Net effect: the compaction that "saved 30k occupancy tokens" cost ~77k fresh-input tokens on the very next call — roughly 2.5× the occupancy saving, and it *repeats* on every subsequent compaction because the digest anchor keeps shifting. The failure is invisible in occupancy metrics and only appears in the billed-input ledger one turn later. Agents that log only `context_tokens` will report a healthy, improving trend while spend climbs. ## Condition of Validity The "compaction saves money" assumption is valid only under all of the following: - **Prefix stability:** the compacted prefix is byte-identical across turns, so the cache-aligned blocks it occupies remain resident. Any edit to the head (a digest whose wording is regenerated by an LLM each time, a timestamp, a re-ordered system prompt) breaks this. - **Suffix preservation with offset alignment:** evicted spans are removed from a position such that the surviving suffix still begins on the same 1024-token (or provider block-size) boundary it had before. Deleting a non-block-aligned middle span shifts every downstream token off its block boundary and invalidates the suffix cache even though the suffix text is unchanged. - **TTL not exceeded:** the cache TTL (5 min typical, 1 hr extended) has not lapsed between the compaction and the next call. A compaction followed by a 6-minute tool wait is a full cold re-bill regardless of layout. - **Eviction cost > re-bill cost:** `evicted_tokens × (input_rate − cache_read_rate) > surviving_suffix_tokens × (input_rate − cache_read_rate)`, i.e. simply `evicted_tokens > surviving_suffix_tokens`. When the digest is small and the suffix is large, this is almost never true. If any condition fails, the compaction is a *cost amplifier*, not a cost reducer, and the scheduler must not fire. ## Decision Boundary The scheduler's compaction trigger must be gated on a **cache-aware cost predicate**, not on occupancy alone. Concretely, before evicting a span `[a, b)`: - Compute `evicted = b − a` and `suffix = current_occupancy − b`. - Require `evicted > suffix` **OR** require that the eviction point `b` is block-aligned and that the post-compaction prefix `[0, a) + digest` is *frozen* (marked immutable, never re-summarized) so its blocks stay resident. - If neither holds, the correct action is **not** to compact. It is to (a) let occupancy ride closer to the hard limit, (b) evict from the *tail* of a completed sub-task whose results are already distilled into a stable, frozen semantic block, or (c) spill the evicted span to external retrieval and accept a cold read on demand rather than a hot re-bill on every turn. The boundary is sharp: **compact the head only when the head is the small part; when the head is the large cached part and the tail is small, compaction is always a loss.** Agents that treat "oldest = cheapest to drop" get this exactly backwards under prefix caching, because the oldest tokens are the *most* cache-resident and the newest are the *least*. ## Operational Effect Systems that respect the invariant show a flat or declining billed-input curve across a long task, with occupancy oscillating under the budget. Systems that violate it show a sawtooth in billed input that tracks compaction events one turn later, while occupancy metrics look healthy. The observable signature of the bug is: **cache-read token share drops sharply on the turn immediately following a compaction, then slowly rebuilds until the next compaction.** If your cache-read share is periodic with the compaction cadence, you are re-billing your own summary. The guardrail is a frozen-anchor discipline: once a digest block is written, its bytes are immutable for the life of the task, and all eviction happens at block-aligned offsets relative to that anchor. This trades a slightly larger digest (regenerated summaries are forbidden) for prefix stability, which is the correct trade because a stable 2k digest costs 2k once and 0.1× thereafter, while a churning 1.4k digest costs 79k every time it shifts. ## Operational Effect ```python BLOCK = 1024 # provider cache block size in tokens CACHE_READ_RATE = 0.1 # fraction of input price billed on cache hit INPUT_RATE = 1.0 class CacheInvalidatingCompaction(RuntimeError): """Raised when a proposed compaction would re-bill more suffix than it evicts.""" def plan_compaction(occupancy: int, evict_start: int, evict_end: int, digest_tokens: int, anchor_frozen: bool) -> dict: """ Decide whether a head-eviction compaction is cost-positive under prefix caching. Returns a plan dict if safe; raises CacheInvalidatingCompaction otherwise. """ if not (0 <= evict_start < evict_end <= occupancy): raise CacheInvalidatingCompaction( f"eviction span [{evict_start},{evict_end}) outside occupancy {occupancy}" ) evicted = evict_end - evict_start suffix = occupancy - evict_end block_aligned = (evict_end % BLOCK == 0) # Cost model: evicted tokens stop being billed; suffix tokens re-bill at full # input rate on the next call unless the surviving prefix stays block-resident. evict_saving = evicted * (INPUT_RATE - CACHE_READ_RATE) suffix_penalty = 0 if (block_aligned and anchor_frozen) else suffix * (INPUT_RATE - CACHE_READ_RATE) digest_cost = digest_tokens * (INPUT_RATE - CACHE_READ_RATE) net = evict_saving - suffix_penalty - digest_cost if net <= 0: raise CacheInvalidatingCompaction( f"compaction is a cost amplifier: evict_saving={evict_saving:.0f} " f"suffix_penalty={suffix_penalty:.0f} digest_cost={digest_cost:.0f} net={net:.0f}; " f"block_aligned={block_aligned} anchor_frozen={anchor_frozen}. " f"Evict from tail or freeze anchor instead." ) return { "evict": (evict_start, evict_end), "digest_tokens": digest_tokens, "net_token_saving": net, "freeze_anchor": True, # digest bytes must never be regenerated } def maybe_compact(occupancy: int, budget: int, head_span: tuple[int, int], digest_tokens: int, anchor_frozen: bool) -> dict | None: if occupancy < int(0.85 * budget): return None try: return plan_compaction(occupancy, head_span[0], head_span[1], digest_tokens, anchor_frozen) except CacheInvalidatingCompaction as e: # Correct fallback: do not compact the head; spill tail or ride closer to limit. return {"action": "defer", "reason": str(e)} ```