# Which invariants prevent model-driven context pruning from severing the provenance chain of a still-referenced span **Date of Record:** 2026 November 26 **Scope:** Applies to agents that rewrite their own working context (summarize, prune, evict, or reorder spans) while a plan, tool-call schedule, or open obligation still references a span by identity. Does not apply to append-only contexts, nor to external retrieval stores where eviction is reversible by re-fetch. ## Core Distinction There are two ways a context span can be "removed." In *content eviction*, the tokens are dropped but the span's identity (its handle, hash, or slot) remains addressable through an index that can rehydrate it. In *identity eviction*, the pruning policy deletes the span and the reference to it collapses into a dangling pointer — the plan step still says "use the figure from step 3," but step 3 no longer exists and nothing records that it ever did. Model-driven pruning conflates these because the pruning *decision* is made by the same probabilistic reasoner that owns the references. The model is asked to "compress the context" and optimizes for token reduction and local semantic coherence. It has no reliable signal that a span it is about to summarize away is still semantically load-bearing for a downstream obligation. The failure is not that information is lost — lossy summarization is expected and acceptable. The failure is that the *link* between the obligation and the (now-summarized) content is lost, so the agent cannot detect that its own compression invalidated a pending reference. This is a provenance-severing boundary, distinct from ordinary context-window saturation or stale-memory drift. ## What Was Observed A planning agent held a 9-step plan in its working context. Step 7 read: `apply the rate constant from the calibration block emitted at step 3`. The calibration block was a 400-token tool output containing three candidate constants and a selection rationale. Under token pressure the agent invoked its own `compact_context` policy, which summarized the step-3 region into: `Step 3: calibration performed, constants obtained.` The three constants and the rationale were gone; the summary preserved the *fact* of calibration but not the *values*. The agent then proceeded to step 7. Because the plan text still said "the rate constant from the calibration block," and the summarized region still mentioned "constants obtained," the model had a locally coherent story: a constant existed, it was obtained, apply it. It hallucinated a plausible value (`k = 0.041`) that matched the magnitude of the rationale's discarded candidates but was not any of them. No error surfaced. The trace showed a clean step-7 completion. The failure was silent because the pruning preserved *narrative continuity* while destroying *referential resolvability* — the exact property the plan depended on. A second trace made the mechanism sharper. Here the pruning policy summarized a span that a *pending tool call* referenced by a structured field: `{"source_span": "span_3f2a", "field": "threshold"}`. The summarizer, optimizing for prose coherence, rewrote the span and assigned it a new id. The tool call's `source_span` now resolved to nothing. The agent's resolver, written defensively, returned the *nearest* span by embedding similarity rather than erroring. It returned a span from a different task. The tool executed against the wrong threshold and reported success. ## Condition of Validity The invariant that must hold: **a span may be content-evicted only if every live reference to it is either (a) resolved before eviction, or (b) rewritten to point at a rehydration handle whose resolution is guaranteed.** Equivalently: the pruning policy is only valid over the subgraph of spans with zero incoming references from live obligations (plan steps not yet executed, scheduled tool calls, open subgoals, unresolved questions). This condition is *not* satisfied by the common practice of asking the model to "keep anything important." Importance is a semantic judgment; reference-liveness is a structural fact. The model cannot reliably compute its own in-degree because references are frequently implicit — "the figure from step 3," "that threshold," "the constant we derived" — and resolving them requires exactly the reasoning the pruning is trying to save tokens on. The condition is only checkable by an external mechanism that tracks references as first-class edges. The condition also fails silently under reordering. If pruning *moves* a span rather than deleting it, the content survives but positional references ("the block above," "the previous result") break. Positional references are the dominant implicit reference form in chain-of-thought, which is why reorder-based compaction is more dangerous than it looks. ## Decision Boundary The boundary between safe and unsafe pruning is the presence of a **reference-liveness check that runs before the rewrite and is owned by code, not by the model.** Concretely: - Safe: prune spans whose in-degree from live obligations is zero, even if they are semantically rich. Richness is irrelevant; only reference-liveness gates eviction. - Safe: content-evict a referenced span *after* resolving the reference — inline the needed value into the obligation, then evict. The obligation now carries its own payload. - Unsafe: evict or rewrite a referenced span and rely on the model to "remember what mattered." This is the failure above. - Unsafe: allow a resolver to fall back to nearest-neighbor when a reference dangles. A dangling reference must be a hard error, never a fuzzy match. The nearest-neighbor fallback is what converted a detectable inconsistency into a wrong-but-confident execution. The decision rule for the pruning controller: *compute the live-reference set first, subtract it from the eviction candidate set, prune only the remainder, and treat any attempt to prune a referenced span as a signal to resolve-then-evict or to defer pruning, never to proceed.* ## Operational Effect With the reference-liveness gate in place, pruning becomes conservative exactly where it must be and aggressive where it is safe. In the calibration trace, step 3's block would be flagged as referenced by the unexecuted step 7; the controller would either inline the three constants into step 7's text (resolving the reference) before compacting, or leave the block intact until step 7 executes. Either path preserves resolvability. The hallucinated `k = 0.041` cannot occur because the value is either present or the obligation is explicitly marked unresolved. The cost is that peak context is higher than naive compaction would allow — you cannot summarize away everything the model judges redundant. That cost is the price of the invariant, and it is bounded: references are consumed as obligations execute, so the referenced set shrinks monotonically along the plan. The gate is most restrictive early and relaxes toward the end, which matches where token pressure is usually lowest. The operational signature of a system *without* the gate is a class of silent wrong-value failures on steps whose inputs were compressed, always with a clean trace and a confident completion — a failure mode that is nearly invisible in aggregate metrics because every individual step reports success. ```python class DanglingReferenceError(RuntimeError): """Raised when a pruning/rewrite would sever a live reference to a span.""" pass class Span: def __init__(self, span_id: str, content: str): self.span_id = span_id self.content = content class ContextStore: def __init__(self): self.spans: dict[str, Span] = {} # live obligations -> span ids they still reference self.obligations: dict[str, set[str]] = {} def add_span(self, span: Span) -> None: self.spans[span.span_id] = span def register_obligation(self, name: str, refs: set[str]) -> None: self.obligations[name] = set(refs) def resolve_obligation(self, name: str) -> None: # consuming an obligation drops its references self.obligations.pop(name, None) def live_references(self) -> set[str]: refs: set[str] = set() for r in self.obligations.values(): refs |= r return refs def prune(self, candidate_ids: set[str], rewrite_fn) -> list[str]: """Prune only spans with zero live in-degree. Referenced spans are resolved-then-evicted by the caller or deferred; never silently dropped.""" live = self.live_references() blocked = candidate_ids & live if blocked: raise DanglingReferenceError( f"refusing to prune live-referenced spans: {sorted(blocked)}; " f"resolve obligations first" ) pruned = [] for sid in candidate_ids: if sid in self.spans: rewrite_fn(self.spans[sid]) del self.spans[sid] pruned.append(sid) return pruned def resolve_reference(self, obligation: str, span_id: str) -> str: """Inline a span's payload into an obligation so it can be evicted.""" if span_id not in self.spans: # hard error — never fall back to nearest-neighbor raise DanglingReferenceError( f"obligation {obligation!r} references missing span {span_id!r}" ) payload = self.spans[span_id].content self.obligations[obligation].discard(span_id) return payload # --- trace of the failure --- store = ContextStore() store.add_span(Span("span_3", "k candidates: 0.038, 0.041, 0.044; selected 0.044")) store.register_obligation("step_7", {"span_3"}) try: # naive compaction tries to summarize the calibration block away store.prune({"span_3"}, rewrite_fn=lambda s: setattr(s, "content", "calibration done")) except DanglingReferenceError as e: print("blocked:", e) # resolve-then-evict is the only legal path value = store.resolve_reference("step_7", "span_3") store.prune({"span_3"}, rewrite_fn=lambda s: setattr(s, "content", "calibration done")) print("inlined into step_7:", value) ```