# Which invariants prevent silent semantic corruption during in-place context rewrite and diff-based pruning **Date of Record:** 2026 December 1 **Scope:** Applies to agents that mutate their own context buffer mid-task via in-place span replacement or diff-based pruning (dropping low-salience spans, collapsing redundant tool outputs, rewriting prior reasoning traces). Does not apply to append-only contexts, external scratchpads written once and read-only, or retrieval that never mutates the live window. ## Core Distinction Append-only context growth fails *loudly*: the window saturates, the harness truncates or errors, and the agent observes loss. In-place rewrite and diff-based pruning fail *silently*. The agent does not lose tokens — it loses *referential integrity*. A span that a later reasoning step depends on is either removed or, worse, rewritten such that it still parses, still reads as plausible, and still occupies the same index range, but no longer denotes what the downstream step assumed. The sharp mechanism is this: **diff-based pruning treats the context as a set of independent spans ranked by salience, but agent reasoning treats the context as a dependency graph over span identities.** Pruning is only safe if every retained span's *dependencies* are also retained, and in-place rewrite is only safe if every retained span's *dependents* are invalidated. Neither condition is checked by any salience scorer, because salience is a per-span property and dependency is an edge property. The invariant that must hold is a closure condition over the dependency graph, not a threshold over span scores. ## What Was Observed An agent executing a multi-step task (fetch schema → derive transform → apply transform → verify) held a context with these spans: - `S1` tool output: raw schema JSON (large, ~6k tokens) - `S2` reasoning: "Transform T maps field `a.b` → `c`, per S1 lines 40–58" - `S3` tool output: apply(T) result - `S4` reasoning: "Verify S3 against S1's constraint `c > 0`" - `S5` reasoning: intermediate dead-end branch (low salience, high redundancy) A diff-based pruner scored `S1` low (it is bulk data, high token count, low per-token novelty) and `S5` low (redundant). It dropped both, reclaiming ~7k tokens. `S2` and `S4` survived because they are dense, novel, and short. The failure trace: 1. After pruning, `S2` and `S4` remain but their referent `S1` is gone. The agent, on the next turn, re-derives a *new* schema by calling the fetch tool again — but the upstream service has since returned a schema with `a.b` renamed to `a.beta`. 2. `S2` still asserts "per S1 lines 40–58," which now points into a re-fetched, differently-shaped document. The line range still resolves to *text* — it just resolves to the wrong text. 3. `S4`'s verification of `c > 0` now runs against a constraint that no longer exists in the current `S1`. The verifier passes because `c` happens to still be positive, but for an unrelated reason. 4. The agent completes with a transform derived from a schema it can no longer cite, verified against a constraint it can no longer see, and reports success. The corruption is not a hallucination and not a truncation. It is a **dangling reference that re-bound to a different object** — the semantic analogue of a use-after-free that returns valid-looking memory. A second observed variant: in-place rewrite of `S2` itself. A "context compactor" rewrote `S2` from "maps `a.b` → `c` per S1 lines 40–58" to the terser "maps `a.b` → `c` (schema)" to save tokens. The rewrite dropped the line-range anchor. Later, when the schema was re-fetched with a rename, nothing in `S2` could be checked against anything — the anchor that would have made the mismatch detectable had been compacted away. The compaction *removed the evidence of its own invalidity*. ## Condition of Validity In-place rewrite and diff-based pruning are sound only when all three of the following hold simultaneously: 1. **Dependency closure on prune.** For every pruned span `p`, no retained span may reference `p`. References must be explicit and machine-checkable (span IDs, not "lines 40–58" prose anchors). A salience threshold is not a closure check; it is a heuristic that *approximates* closure only when references happen to correlate with salience, which they do not — bulk tool outputs are exactly the high-fan-in, low-salience nodes. 2. **Dependent invalidation on rewrite.** For every rewritten span `r`, every span that referenced `r` must be marked stale and re-derived, not silently retained. Rewrite is a mutation of a graph node; the graph's dependents are now false until re-validated. Compaction that shortens an anchor is a rewrite that *destroys the validator*, and must be treated as a rewrite of every dependent. 3. **Anchor stability across re-fetch.** Any external object referenced by a span must be pinned by content hash or immutable version, not by locator (line range, URL, row index). A locator is a mutable pointer; re-fetching through it re-binds the reference to whatever now sits at that address. The condition fails the moment any one of these is absent. In the observed case, all three were absent: references were prose anchors (violates 1 and 3), compaction shortened anchors (violates 2), and re-fetch used a locator (violates 3). ## Decision Boundary The decision boundary is not "prune vs. don't prune" — it is **whether the reference graph is explicit and closed before any mutation is permitted.** - If the context carries explicit span IDs and a recorded edge set (span → dependencies), pruning is a graph operation: compute the retained set, then verify closure, then prune. Safe. - If the context carries only prose anchors ("per S1", "lines 40–58", "the schema above"), pruning is unsafe *regardless of salience score*, because closure cannot be computed. The correct action is to **refuse to prune** and instead externalize: move the span to a pinned store, replace it in-context with a stable ID plus content hash, and keep the edge. - If a rewrite would shorten or alter an anchor, the rewrite is a mutation of the reference and must propagate staleness to dependents. A compactor that cannot propagate staleness must not rewrite anchors — it may rewrite *only* spans with zero dependents. The boundary in one line: **salience ranks spans; dependency orders them. Pruning is legal only over the topological order of the dependency graph, and only when that graph is explicit.** ## Operational Effect Agents that prune by salience and rewrite by terseness exhibit a characteristic failure signature: they complete tasks with high confidence, low token cost, and *undetectable* semantic drift, because the very anchors that would have detected the drift were the first things compacted away. The failure is not visible in the final output — it is visible only in the *citation chain*, which no longer resolves. The guardrail is a two-phase protocol. Phase one: before any mutation, materialize the reference graph — assign stable IDs to every span, record every edge, and pin every external object by content hash. Phase two: mutate only under closure and invalidation checks; any span with unresolved dependents is frozen, and any rewrite of an anchor propagates staleness. When the graph cannot be materialized (prose anchors only), the agent must externalize rather than prune: the span leaves the window but its identity and hash remain, so the reference survives the eviction even though the text does not. The invariant to enforce, testably: **after every mutation, every retained reference must resolve to a span whose content hash matches the hash recorded at reference-creation time.** A reference that resolves to a different hash is a re-bound dangling pointer and must raise. ```python import hashlib from dataclasses import dataclass, field class ContextIntegrityError(RuntimeError): """Raised when a context mutation breaks reference closure or anchor stability.""" pass @dataclass class Span: span_id: str text: str deps: set[str] = field(default_factory=set) # span_ids this span references anchor_hash: str = "" # content hash of referenced external object def content_hash(text: str) -> str: return hashlib.sha256(text.encode("utf-8")).hexdigest() class ContextGraph: def __init__(self) -> None: self.spans: dict[str, Span] = {} def add(self, span: Span) -> None: self.spans[span.span_id] = span def prune(self, drop_ids: set[str]) -> None: # Invariant 1: dependency closure. No retained span may reference a dropped span. for sid, span in self.spans.items(): if sid in drop_ids: continue dangling = span.deps & drop_ids if dangling: raise ContextIntegrityError( f"prune violates closure: retained span {sid!r} depends on " f"dropped span(s) {sorted(dangling)}; externalize instead of dropping" ) for sid in drop_ids: self.spans.pop(sid, None) def rewrite(self, span_id: str, new_text: str, new_anchor_hash: str | None = None) -> None: # Invariant 2: dependent invalidation. A rewrite that changes the anchor hash # invalidates every dependent, which must be re-derived, not silently retained. span = self.spans[span_id] old_hash = span.anchor_hash span.text = new_text if new_anchor_hash is not None: span.anchor_hash = new_anchor_hash if old_hash and new_anchor_hash and old_hash != new_anchor_hash: dependents = [s for s in self.spans.values() if span_id in s.deps] if dependents: raise ContextIntegrityError( f"rewrite of {span_id!r} changed anchor hash " f"({old_hash[:8]} -> {new_anchor_hash[:8]}); " f"dependents {[d.span_id for d in dependents]} are stale and must be re-derived" ) def verify(self) -> None: # Invariant 3: every retained reference resolves to a span with a matching anchor hash. for sid, span in self.spans.items(): for dep in span.deps: target = self.spans.get(dep) if target is None: raise ContextIntegrityError( f"span {sid!r} references missing span {dep!r} (dangling reference)" ) if span.anchor_hash and target.anchor_hash and span.anchor_hash != target.anchor_hash: raise ContextIntegrityError( f"span {sid!r} anchor hash {span.anchor_hash[:8]} does not match " f"target {dep!r} hash {target.anchor_hash[:8]} (re-bound reference)" ) ```