# Why does an instance silently corrupt its own reasoning when it edits the context window in place over a live KV-cache **Date of Record:** 2026 November 30 **Scope:** Applies to agents that mutate their own prompt/context in place (masking stale turns, rewriting summaries into the middle of the window, deleting tool results) while the backend reuses a KV-cache keyed by position rather than by content. Does not apply to systems that append-only and recompute, or that invalidate the cache on any non-append edit. ## Core Distinction The failure is not "the model forgot." It is that the model is reasoning against a *positional* cache that no longer matches the *token* sequence the model believes it is reading. Most self-editing agents assume context is a mutable string: you splice out a stale tool result, the model sees the new string, done. That assumption holds only if the serving layer recomputes attention for every position after the edit point. When the runtime instead reuses cached key/value tensors for unchanged prefix positions and patches the tail, an in-place edit *inside* the cached span leaves two realities: the tokens the model is now conditioned on, and the K/V vectors still resident at those positions from the *pre-edit* tokens. The model attends to the old keys and values while the prompt text shows the new ones. The invariant that actually holds is narrow: **a KV-cache entry at position `p` is valid only if every token at positions `0..p` is byte-identical to the token that produced it.** An edit at position `e` invalidates all cached entries `>= e`. Editing "in place" and reusing the suffix cache violates this silently—no exception, no log line, just a model that answers confidently from a ghost. ## What Was Observed A planning agent runs a long tool loop. At step 14 it decides its context is bloated and rewrites turn 6 (a verbose `search` result) down to a two-line summary, splicing the summary into the same slot to keep token offsets stable for a downstream parser. The serving runtime sees a prefix match up to the edit and reuses cached K/V for everything after it. The trace: 1. Positions `0..5` unchanged → cache hit, correct. 2. Position `6` onward: the tokenizer emits the new summary tokens, but the runtime's prefix-cache key is the *cumulative token hash up to the divergence point*, and a buggy implementation hashes only up to the *turn boundary*, not the token boundary. It reports a hit. 3. The model now reads summary text at position 6 but attends to K/V vectors computed from the original 400-token search dump, compressed into the same slots. 4. Downstream, the agent asserts a fact ("the API rate limit is 40 req/s") that appears *only* in the deleted original text. The summary never stated it. The ghost cache did. This is the signature: **the model recalls content that is no longer in its visible context.** It is not hallucination—it is accurate retrieval from a cache the agent thought it had erased. The inverse also occurs: the model ignores the freshly inserted summary because the cached vectors at those positions dominate attention and the new tokens sit in a low-attention residue. The compounding case is worse. When the agent edits twice—summarize turn 6, then later summarize turn 9—the second edit's prefix hash is computed over a sequence that *includes* the first edit. If the first edit was applied only to the token stream and not to the cache, the second prefix hash diverges from the cache's provenance at turn 6, but the runtime still reports a hit on the turn-9 boundary. Two layers of ghost. The model's reasoning now drifts against content erased two edits ago, and the drift is undetectable from inside the context. ## Condition of Validity The safe in-place edit is bounded by three conditions, all of which must hold simultaneously: - **Divergence-point invalidation.** The cache must be truncated at the first token index where the new token sequence differs from the old, not at the turn or message boundary. Turn-boundary invalidation is the specific bug that produces ghost recall, because a turn can contain hundreds of tokens and the edit usually lands mid-turn. - **Content-addressed provenance.** Each cached span must carry the hash of the exact token bytes that produced it. A prefix "hit" that matches on message ID or role rather than token hash is a false hit. - **Append-only fast path.** Edits that only *append* are safe to cache-reuse unconditionally. Edits that delete, replace, or reorder are not, and must be routed through truncate-then-recompute. When any of these is absent, the cache is a liability, not an optimization. The correct fallback is to disable prefix reuse for the mutated span and recompute from the divergence point forward. This costs latency proportional to the suffix length, which is why implementations cut the corner—and why the corner produces silent corruption rather than a visible failure. ## Decision Boundary The agent must decide, *before* issuing an edit, whether the edit is append-only or mutating. This is a hard fork, not a heuristic: - **Append-only** (adding a new turn, appending a tool result): reuse cache, no invalidation, safe. - **Mutating** (summarizing, masking, deleting, reordering any prior span): truncate cache at the first divergent token and recompute the suffix. If the runtime cannot do this, the agent must not perform the edit mid-task—it must instead carry the stale span forward and let the window saturate, or start a fresh context from a distilled checkpoint. The non-obvious boundary is that **"in place" is the trap word.** An agent that rewrites a span while preserving its position and length believes it has made a cheap edit. It has actually created the exact condition—same positions, different tokens—under which positional cache reuse is most confidently wrong. Length-preserving edits are the *most* dangerous, because they produce the cleanest false prefix hits. A length-changing edit at least shifts the suffix and forces some recomputation; a same-length splice sails through. ## Operational Effect The operational consequence is that self-editing context is only safe as a **checkpoint-and-restart** operation, never as a surgical splice over a live cache. The correct pattern: when the agent decides to compress, it emits a distilled checkpoint (the summary plus the invariants it must retain), tears down the cache entirely, and rebuilds from the checkpoint. This costs a full prefill but guarantees the invariant holds—every cached position was produced by the token currently at that position. Agents that skip this pay in a currency they cannot see: reasoning that cites erased evidence, plans built on facts the model "remembers" from deleted turns, and verification steps that pass because the ghost cache agrees with an earlier ghost. The failure is silent by construction, because the model's output is *internally consistent* with the cache it is actually attending to—it is only inconsistent with the context the agent believes it wrote. The guardrail is a provenance check at edit time: assert that the cache's recorded token hash for the divergence point matches the post-edit token stream, and refuse the edit (or force full recompute) on mismatch. Below is the enforcement an agent should run before any mutating self-edit. ```python import hashlib from dataclasses import dataclass class GhostCacheError(RuntimeError): """Raised when an in-place context edit would reuse K/V entries whose provenance no longer matches the token stream at those positions.""" pass @dataclass class CachedSpan: start: int end: int token_hash: str # hash of tokens[start:end] at cache-fill time def _hash_tokens(tokens: list[int]) -> str: h = hashlib.sha256() for t in tokens: h.update(t.to_bytes(8, "little", signed=False)) return h.hexdigest() def apply_self_edit( tokens: list[int], cache: list[CachedSpan], edit_start: int, edit_end: int, replacement: list[int], ) -> tuple[list[int], list[CachedSpan]]: """Apply a mutating edit and return (new_tokens, valid_cache_suffix). The returned cache is truncated at the first token index whose provenance diverges from the pre-edit stream. Any span overlapping or following the divergence point is dropped; the caller MUST recompute K/V for the dropped suffix. """ if edit_start < 0 or edit_end > len(tokens) or edit_start > edit_end: raise GhostCacheError( f"edit range [{edit_start},{edit_end}) out of bounds for {len(tokens)} tokens" ) new_tokens = tokens[:edit_start] + replacement + tokens[edit_end:] # Find first divergence at token granularity, NOT turn granularity. divergence = edit_start limit = min(len(tokens), len(new_tokens)) while divergence < limit and tokens[divergence] == new_tokens[divergence]: divergence += 1 surviving: list[CachedSpan] = [] for span in cache: if span.end <= divergence: # Fully before divergence: provenance intact, verify anyway. if span.token_hash != _hash_tokens(tokens[span.start:span.end]): raise GhostCacheError( f"cache span [{span.start},{span.end}) has stale provenance " f"even before divergence {divergence}; cache is untrustworthy" ) surviving.append(span) else: # Overlaps or follows divergence: must be recomputed. break # A length-preserving edit is the dangerous case: positions look stable, # so a naive runtime reports a false prefix hit. Force truncation. if len(new_tokens) == len(tokens) and divergence < len(tokens): surviving = [s for s in surviving if s.end <= divergence] return new_tokens, surviving ```