Where must an instance draw the compaction boundary when lossy summarization silently invalidates an in-flight cache prefix
**Date of Record:** 2026 December 1 **Scope:** Applies to any long-running LLM instance (single agent or orchestrator) that (a) triggers automatic context compaction on a token/occupancy threshold and (b) relies on prompt-prefix caching (KV/prefix cache) keyed on the byte-stable head of its context. Does not apply to stateless single-shot calls, nor to systems that fully rebuild and re-warm the cache after every compaction with no in-flight tool calls.
Core Distinction
The distinction that matters is between **compaction as a state transformation** and **compaction as a cache event**. Most implementations treat compaction as a pure memory operation: when occupancy crosses a threshold, replace the oldest N turns with a summary string and continue. The cache layer, however, sees compaction as a **mutation of the prefix**, and prompt-prefix caches are keyed on an exact byte prefix. A lossy summary that rewrites any token inside the cached prefix does not "update" the cache — it **invalidates it silently**, forcing a cold re-prefill on the very turn where the instance is already under the most context pressure. The non-obvious boundary is this: *a compaction that changes the prefix must be distinguished from a compaction that appends after a stable prefix*, and only the latter is cache-preserving.
The failure is not "the summary lost information." It is that the summary was inserted **at the head** of the context, shifting every downstream token, so the cache key for the entire remainder of the conversation no longer matches. The instance pays a full re-encode of the post-compaction context precisely at the moment its budget is tightest.
What Was Observed
A tool-using agent ran a 40-turn task with a 128k window and a prefix cache with a 90% occupancy trigger for compaction. The trace showed a repeatable three-phase failure:
- **Trigger.** At turn 31, occupancy hit 0.91. The compactor replaced turns 1–20 (≈78k tokens) with a 1.9k-token abstractive summary placed at index 0, ahead of the system prompt remainder and all recent turns.
- **Silent invalidation.** The next request's prefix — system prompt → summary → turns 21–31 — shared only the first ~600 tokens (the static system preamble) with the previously cached prefix. Cache hit ratio collapsed from ~0.94 to ~0.005. The provider re-prefilled ~49k tokens.
- **Compounding.** Re-prefill pushed latency up 3.4× and consumed budget; a mid-flight tool call (a schema fetch) timed out, and the retry re-entered compaction logic because occupancy was again near threshold — the summary was regenerated with slightly different wording (non-deterministic sampler), producing yet another prefix mutation and a second full invalidation.
The observed invariant violation: **the compaction step was not idempotent and not prefix-stable**, so a single trigger could cascade into two or three cache misses within a few turns. In one run the agent's effective cost for turns 31–34 exceeded the cost of turns 1–30 combined.
A second, subtler observation: the *lossy* summary dropped a specific tool-result token (an opaque resource ID) that a later turn needed. The agent did not fail loudly; it hallucinated a plausible ID and issued a tool call against a non-existent resource. The summarizer's compression was correct at the semantic level and wrong at the referential level — abstractive summaries preserve gist and discard exactly the high-entropy identifiers that downstream tool calls depend on.
Condition of Validity
The cache-preserving claim holds only under these conditions, and the guardrail below is valid only within them:
- The cache is **prefix-keyed and byte-exact** (true for most KV/prefix caches and provider prompt caches). If the cache is semantic or embedding-keyed, the invalidation model differs and this record does not bound it.
- Compaction output is **appended** or **placed after a stable, cache-covered head**, not spliced into the head. A summary inserted at index 0 with a changed system preamble is outside the valid region.
- The summarizer is treated as **non-deterministic** (temperature > 0 or model-version drift). If summaries are byte-reproducible, repeated compaction of the same span is idempotent and the cascade cannot occur.
- Referential tokens (IDs, hashes, paths, handles) required by future tool calls are **pinned losslessly**; only narrative/observation spans are eligible for lossy compression.
When any of these fails — semantic cache, head-spliced summary, deterministic summarizer, or unpinned identifiers — the invariant does not hold and the instance must fall back to an explicit re-warm-and-verify path rather than assume cache continuity.
Decision Boundary
The boundary is a single predicate evaluated at compaction time, before the summary is committed to the context:
**Is the proposed compaction prefix-stable AND referentially lossless for all live tool bindings?**
- If **yes** (summary appended after the cached head, or head unchanged and only trailing spans compressed, and every live resource handle preserved verbatim): commit the summary, keep the cache, continue. Cost is one summary generation.
- If **no** (any head mutation, or any live handle dropped): do **not** splice. Instead, either (a) defer compaction by evicting a tail span that no live binding references, or (b) commit the compaction but **explicitly mark the cache cold** and re-warm with a single batched prefill before the next tool call, and **suspend the compaction trigger for K turns** to prevent the regenerate-cascade.
The boundary is not "compaction is good or bad." It is: *a compaction that mutates the cached prefix must be treated as a cache-cold event and serialized against in-flight tool calls; a compaction that appends after a stable head is cache-warm and may proceed freely.* Conflating the two is the failure.
Operational Effect
Enforcing the boundary changes three measurable properties:
- **Cache hit ratio stays high across compaction.** By pinning the head and appending summaries, the instance retains ~90%+ prefix reuse instead of collapsing to near-zero. Re-prefill cost is bounded to the newly appended summary tokens.
- **The regenerate-cascade is eliminated.** Because the summary is deterministic-given-span (or the trigger is suspended post-compaction), a second compaction cannot silently rewrite an already-cached prefix. One trigger produces at most one cache event.
- **Referential integrity survives compression.** Pinning live resource handles verbatim means the lossy summarizer can compress aggressively on narrative while the tool-call layer never receives a hallucinated ID. The failure mode shifts from silent wrong-resource calls to an explicit `CompactionBoundaryError` at commit time.
The residual cost is that lossy compression is restricted to spans with no live bindings, which may force earlier or more frequent compaction on identifier-dense traces. That is the correct trade: a slightly higher compaction frequency beats a silent cache collapse plus a hallucinated tool target.
from dataclasses import dataclass, field
from typing import FrozenSet
class CompactionBoundaryError(RuntimeError):
"""Raised when a proposed compaction would mutate the cached prefix
or drop a referentially-live token required by an in-flight tool call."""
@dataclass
class CompactionProposal:
head_tokens: tuple # tokens at the cache-covered head, in order
cached_head: tuple # the exact prefix the cache is keyed on
summary: str
placement: str # "append" | "splice_head"
live_handles: FrozenSet[str] = field(default_factory=frozenset)
preserved_handles: FrozenSet[str] = field(default_factory=frozenset)
def validate_compaction(p: CompactionProposal) -> None:
# Invariant 1: the cached head must be byte-stable (prefix-stable).
if p.placement == "splice_head":
raise CompactionBoundaryError(
"compaction splices into the cached head; prefix key changes and "
"the entire downstream cache is silently invalidated"
)
if p.head_tokens != p.cached_head:
raise CompactionBoundaryError(
"head tokens diverged from the cached prefix; treating as cache-cold "
"requires an explicit re-warm, not an implicit continuation"
)
# Invariant 2: every live tool binding must survive losslessly.
dropped = p.live_handles - p.preserved_handles
if dropped:
raise CompactionBoundaryError(
f"lossy summary dropped live resource handles {sorted(dropped)}; "
"downstream tool calls would target hallucinated identifiers"
)
def compact_or_defer(p: CompactionProposal) -> str:
validate_compaction(p)
# Safe path: prefix-stable and referentially lossless.
return p.summary