# In what scenarios must an instance treat self-pruned context as a lossy, non-commutative transform rather than a reversible compaction **Date of Record:** 2026 November 23 **Scope:** Applies to any agent that mutates its own live context window under a budget (model-driven summarization, relevance-scored eviction, tiered scratchpads) and then continues reasoning against the pruned state. Does not apply to append-only context with external persistence, nor to stateless single-shot completions. ## Core Distinction The failure is not "the model forgot something." It is that **model-driven pruning is a non-commutative, non-idempotent transform over the reasoning state**, and most agent runtimes treat it as if it were a reversible `drop()` — an operation that removes tokens without changing the semantic content of what remains. It is not reversible, and it does not commute with subsequent reasoning steps. Concretely: relevance-scored eviction assigns each span a score `r(s | q, C)` conditioned on the *current* query `q` and the *current* context `C`. When you evict the lowest-scoring spans, you change `C`, which changes the score every surviving span *would* have received on a second pass. The eviction is therefore order-dependent and self-referential. A span that scored `0.31` (evicted) may have been the sole carrier of a negation, a unit, a scope qualifier, or an entity binding that a surviving span at `0.72` implicitly depended on. The surviving span is now *semantically dangling* — syntactically present, referentially broken — and it carries a high relevance score, so the next pruning round will protect it while the agent reasons confidently from a corrupted premise. The invariant that gets violated: **a pruned context must remain a self-contained, well-formed reasoning state, not merely a smaller one.** Eviction policies optimize for size and per-span relevance; neither objective enforces referential closure. ## What Was Observed A planning agent running a 3-tool loop (schema lookup → query draft → validator) with a 16k soft budget and a model-driven pruner firing at 0.85 saturation. Trajectory: 1. Turn 4: agent records `constraint_7 = "amounts must be in EUR, not USD"`. Span scores high at the time because it is on-query. 2. Turn 11: a long validator trace (low per-span relevance, high token mass) pushes the window to saturation. The pruner evicts `constraint_7` (its score decayed once the query drifted toward formatting) and *retains* a downstream note `"apply constraint_7 to line items"` because that note token-matches the active query. 3. Turn 12: agent reads the surviving note, resolves `constraint_7` against a stale paraphrase still resident in a summarized block — the paraphrase dropped the "not USD" clause, keeping only "amounts in EUR." 4. Turn 13: agent emits `currency: EUR` for a USD-denominated source, validator passes (EUR is a legal value), and the error is *silent*. No exception, no retry, wrong output. The failure signature: **eviction removed the definition but kept the reference; summarization lossily rewrote the definition; the surviving reference bound to the corrupted paraphrase.** Three independent lossy transforms composed into a plausible-but-false state. A `KeyError`-style crash would have been safer. The non-obvious part is step 2. The pruner did nothing wrong by its own objective — it maximized retained relevance under a token budget. The bug is that *relevance and referential necessity are different quantities*, and no eviction policy that scores spans independently can see the dependency edge `note → constraint_7`. ## Condition of Validity This reasoning holds — and the guardrail is mandatory — when **all three** hold: - **C1 (self-reference):** the pruner's score depends on the current context or query, so eviction is order-dependent. - **C2 (dependency edges):** surviving spans contain anaphora, identifiers, unit/scope qualifiers, or negations whose referent lives in an evictable span. - **C3 (silent failure):** downstream consumers (validator, next tool call, human) cannot detect the corruption from the surviving state alone. If any of C1–C3 fails, ordinary compaction is safe: a static frequency-based pruner (not C1) with no cross-span references (not C2) that a strict schema validator backstops (not C3) can be treated as reversible-enough. The dangerous regime is precisely *model-driven + referential + unvalidated* — which is the default configuration of most "self-editing context" implementations. ## Decision Boundary Before any eviction pass, the runtime must decide: **is the current context referentially closed?** If it cannot prove closure, it must not evict spans that are the *target* of a dependency edge, regardless of score. Operationally, the boundary is a three-way gate: - **Evict** a span only if it has no inbound dependency edge from a surviving span (no identifier defined here and used elsewhere, no negation/qualifier scoped to a retained claim). - **Rewrite** (not evict) a span that is a dependency *target*: replace it with a canonical, self-contained restatement and update all referents in the same atomic pass — never across turns. - **Freeze** the window and escalate to an external store when the pruner cannot establish closure under budget. Escalation is cheaper than a silent wrong answer. The critical rule: **prune-and-rewrite must be atomic.** A pruner that evicts on turn N and repairs dangling references on turn N+1 has already let the agent reason on a broken state for one full step. The transform must either leave a closed state or refuse. ## Operational Effect Enforcing referential closure changes the pruner from a size optimizer into a **state-integrity transform with a failure mode**. The observable effects: - Pruning occasionally *fails* to hit the budget (closure forces retention). This is correct behavior, not a regression — escalate rather than force-evict. - Every eviction pass emits a dependency-closure certificate: the set of surviving spans and a proof that no surviving span references an evicted one. Absence of a certificate blocks the next reasoning step. - Silent-corruption incidents (wrong-but-valid outputs) drop to near zero; loud budget-exhaustion incidents rise. Trading silent for loud is the entire point. - The agent's self-model must record that its own context is *lossy*, so it re-derives load-bearing facts from the external store rather than trusting a paraphrase it cannot trace. The following guard encodes the gate: it refuses to commit a pruned context unless closure is certified, raising rather than proceeding on a dangling reference. ```python from dataclasses import dataclass, field class DanglingReferenceError(RuntimeError): """Raised when a pruned context retains a reference to an evicted span.""" pass @dataclass class Span: span_id: str text: str score: float defines: set[str] = field(default_factory=set) # identifiers/constraints introduced here references: set[str] = field(default_factory=set) # identifiers/constraints consumed here def commit_pruned_context( spans: list[Span], budget_tokens: int, token_len, min_score: float = 0.0, ) -> list[Span]: """ Evict low-relevance spans while preserving referential closure. A span that is the target of a surviving reference is never evicted; if closure cannot be met under budget, we raise instead of corrupting state. """ # Phase 1: candidate survivors by score, highest first, until budget. ordered = sorted(spans, key=lambda s: s.score, reverse=True) survivors: list[Span] = [] used = 0 for s in ordered: if s.score < min_score: break cost = token_len(s.text) if used + cost <= budget_tokens: survivors.append(s) used += cost # Phase 2: dependency closure. Pull back any evicted span that a survivor references. survivor_ids = {s.span_id for s in survivors} defined = {d for s in survivors for d in s.defines} needed = {r for s in survivors for r in s.references} - defined by_def = {} for s in spans: for d in s.defines: by_def.setdefault(d, s) for ident in sorted(needed): target = by_def.get(ident) if target is None: # Reference points nowhere at all: the state was already corrupt upstream. raise DanglingReferenceError( f"surviving span references undefined identifier {ident!r}; " f"context was not referentially closed before pruning" ) if target.span_id in survivor_ids: continue # Re-admit the definition span; it overrides its low score. cost = token_len(target.text) if used + cost > budget_tokens: raise DanglingReferenceError( f"cannot preserve closure for {ident!r}: re-admitting span " f"{target.span_id} exceeds budget ({used + cost} > {budget_tokens}); " f"escalate to external store instead of evicting" ) survivors.append(target) survivor_ids.add(target.span_id) used += cost defined |= target.defines # Phase 3: final closure certificate check over the committed set. for s in survivors: missing = s.references - defined if missing: raise DanglingReferenceError( f"post-commit closure violated: span {s.span_id} references " f"{sorted(missing)} with no surviving definition" ) return survivors ```