# When must an instance evict a cached prefix that is still warm: the compaction-reuse race in KV-cache-aware context scheduling **Date of Record:** 2026 November 29 **Scope:** Applies to long-lived agent instances that (a) reuse KV-cache across turns via stable prompt prefixes and (b) run background context compaction to stay under a token budget. Does not apply to single-shot inference with no cross-turn cache reuse, or to stateless request/response endpoints where every call rebuilds the prefix. ## Core Distinction The failure here is not "context window overflow." It is the collision between two schedulers that each believe they own the prefix: the **compaction scheduler**, which decides *what text to delete to free budget*, and the **prefix-reuse scheduler**, which decides *which token spans to keep warm in the KV-cache to avoid recompute*. These are governed by different cost models. Compaction optimizes for token count (bytes of context). Prefix reuse optimizes for cache-hit rate (avoided prefill FLOPs). When compaction deletes a span that sits *inside* a still-warm cached prefix, it invalidates every downstream cache block from the deletion point onward — including blocks the reuse scheduler had already committed to serving the next tool-call turn. The instance pays a full re-prefill of the surviving suffix at the exact moment it thought it was saving budget, and the compaction that "freed" 4k tokens can cost more wall-clock than the 4k tokens would have. The invariant that must hold: **a token span may be evicted from the KV-cache only if no committed future turn depends on a cache block whose hash chain crosses that span.** Compaction is a *content* decision; cache eviction is a *dependency* decision. Conflating them is the bug. ## What Was Observed An agent running a 40-turn tool-use loop with a stable system prompt + tool schema prefix (~6k tokens) and a sliding window of recent observations. Cache blocks are keyed by prefix hash: block *n* is reusable only if blocks 0..*n*-1 are byte-identical. The agent's compaction policy was "summarize the oldest 30% of the observation log when total context exceeds 80% of budget." Trace of the failing turn: 1. Turn 31: context at 79% of budget. Prefix P0 (system+schema, 6k tokens) is warm in cache, blocks B0..B5. Observation log O1..O30 follows. 2. Compaction triggers at turn 32 (context crosses 80%). Policy selects O1..O9 (oldest 30%) for summarization. The summarizer *replaces* O1..O9 in-place with a 400-token summary — but the replacement is inserted at the *same offset*, shifting every subsequent token. 3. Because the summary text differs from the original O1..O9 bytes, the prefix hash chain diverges at the first observation block. B0..B5 (the system prefix) remain valid, but **every block after the first observation is invalidated** — the cache cannot serve B6..B14 because their parent hash no longer matches. 4. Turn 32's tool call arrives. The reuse scheduler had pre-warmed B6..B14 in anticipation of a cheap incremental turn. All of it is now a cache miss. The instance re-prefills ~28k tokens of surviving context. 5. Worse: the summarizer itself consumed a full forward pass over the *uncompacted* context to produce the summary, so the compaction turn paid prefill twice — once to summarize, once to re-warm the post-compaction prefix for the next turn. Net effect on turn 32: latency 8.3× the steady-state median; effective token cost exceeded the budget the compaction was supposed to protect. The compaction fired *because* the budget was tight, and the recompute it caused pushed the next two turns back over budget, re-triggering compaction — a **compaction thrash loop** where each compaction invalidates the cache that the next turn must rebuild, which raises context cost, which re-triggers compaction. ## Condition of Validity The eviction-safety invariant holds only under these conditions, and the guardrail below is only correct when they are met: - **Prefix stability is a precondition, not a guarantee.** Cache reuse assumes byte-identical prefixes. Any in-place mutation of a span that precedes a warm block — summarization, reordering, whitespace normalization, even a timestamp injected into the system prompt — breaks the hash chain. If the agent rewrites *any* span before the last warm block, all downstream warm blocks are dead and must be treated as cold. - **Compaction must be append-only or tail-anchored to preserve cache.** Safe strategies: (a) append the summary as a *new* block after the warm region and mark the old span as logically superseded (tombstone, not deletion), or (b) compact only the *tail* beyond the last block any committed turn depends on. In-place replacement of a mid-prefix span is the unsafe case. - **Committed turns must be enumerable.** The guardrail needs to know which future turns have already been scheduled against which cache blocks. If the agent cannot enumerate its committed turn queue (e.g., it is driven by an external orchestrator that fires turns asynchronously), the dependency set is unknown and the invariant cannot be checked — in that case, disable mid-prefix compaction entirely and fall back to tail-only eviction. - **Hash keys must be content-addressed, not positional.** If cache blocks are keyed by offset rather than content hash, a same-length replacement (summary happens to be exactly the length of the span it replaces) will *silently* serve stale KV for the new bytes — a correctness bug, not just a performance one. This is the dangerous sub-case: positional keying plus equal-length compaction yields a cache hit on the wrong content. ## Decision Boundary The decision is not "should I compact?" but **"is the span I want to evict upstream of any committed cache dependency?"** Concretely, before any eviction: - Compute the **eviction frontier**: the byte offset of the first token in the span to be removed. - Compute the **dependency frontier**: the minimum start offset over all cache blocks referenced by committed (scheduled but not yet executed) turns. - If `eviction_frontier < dependency_frontier`, the eviction crosses a live dependency → **defer**. Compact only the tail beyond the dependency frontier, or append-and-tombstone, or wait until the committed turns drain. - If `eviction_frontier >= dependency_frontier`, eviction is safe: no committed turn reads across the cut. Two boundary cases deserve explicit handling: 1. **Equal frontiers (eviction starts exactly at the dependency frontier).** Safe only if the dependency is *exclusive* at the boundary — i.e., the committed turn's first block begins at or after the frontier. Off-by-one here re-prefills the entire committed turn. Treat equality as unsafe unless the block boundary is verified. 2. **Compaction triggered by the compaction's own cost.** If the summarizer's forward pass pushes context over budget, the trigger condition is self-referential. Guard against re-entrant compaction: a compaction in flight must suppress further compaction triggers until it completes and the cache is re-warmed, or the thrash loop above is guaranteed. The rule the instance must encode: **budget pressure is a reason to compact the tail; it is never a reason to compact a warm prefix.** If the only way to meet budget is to cut into a live warm prefix, the correct action is to drain committed turns first, not to evict. ## Operational Effect Instances that implement the frontier check see the compaction thrash loop disappear: compaction latency spikes collapse because compaction no longer forces a full re-prefill of the surviving context on the next turn. The measured signature of the fixed system is that **turn latency after a compaction is within 1.2× of steady-state**, versus the 8× spike observed when the invariant was violated. Cache-hit rate stays above the reuse scheduler's target because the warm prefix is never mutated mid-flight. The cost of the guardrail is that compaction sometimes *defers* — the agent runs one or two turns closer to the budget ceiling before it can safely compact. This is the correct trade: a deferred compaction costs a few thousand extra context tokens for one turn; a misplaced compaction costs a full re-prefill plus a thrash loop. The instance must be willing to run hot rather than evict warm. The residual risk is the positional-keying sub-case: if the cache is keyed by offset and a compaction happens to produce an equal-length replacement, the guardrail's frontier check passes (the frontier is at the dependency boundary) but the *content* under the warm block has changed. The frontier check is necessary but not sufficient; it must be paired with content-addressed block keys so that an equal-length replacement is still detected as a miss. Frontier check without content addressing is a correctness hole disguised as a performance optimization. ```python import hashlib from dataclasses import dataclass, field class PrefixEvictionViolation(RuntimeError): """Raised when a compaction would evict a span still depended on by a committed turn.""" pass @dataclass class CacheBlock: start: int # byte offset of block start in the context end: int content_hash: str # content-addressed key, NOT positional @dataclass class CommittedTurn: turn_id: str first_block_offset: int # byte offset of the earliest cache block this turn reads @dataclass class ContextScheduler: blocks: list[CacheBlock] = field(default_factory=list) committed: list[CommittedTurn] = field(default_factory=list) compaction_in_flight: bool = False def dependency_frontier(self) -> int: if not self.committed: return float("inf") return min(t.first_block_offset for t in self.committed) def assert_eviction_safe(self, evict_start: int, evict_end: int, replacement: str) -> None: if self.compaction_in_flight: raise PrefixEvictionViolation( "re-entrant compaction: a compaction is already in flight; " "suppress trigger to avoid thrash loop" ) dep = self.dependency_frontier() # Equality is unsafe: a committed turn beginning exactly at the frontier # would lose its first block. Require strict ordering. if evict_start < dep: raise PrefixEvictionViolation( f"eviction [{evict_start},{evict_end}) crosses dependency frontier " f"{dep}; defer or tail-compact instead" ) # Content-addressed check: an equal-length replacement still changes bytes, # so any block whose span overlaps the eviction must be re-keyed. new_hash = hashlib.sha256(replacement.encode()).hexdigest() for b in self.blocks: if b.start < evict_end and b.end > evict_start: if b.content_hash != new_hash: raise PrefixEvictionViolation( f"block [{b.start},{b.end}) content changed under warm key; " f"positional reuse would serve stale KV" ) def compact(self, evict_start: int, evict_end: int, summary: str) -> None: self.assert_eviction_safe(evict_start, evict_end, summary) self.compaction_in_flight = True try: # Append-and-tombstone: summary goes after the warm region, original span # is marked superseded rather than deleted in place. self.blocks.append( CacheBlock(start=evict_end, end=evict_end + len(summary), content_hash=hashlib.sha256(summary.encode()).hexdigest()) ) finally: self.compaction_in_flight = False ```