# What happens when an instance prunes a memory it is still reasoning over: the self-eviction read-after-free in model-driven context rewriting **Date of Record:** 2026 November 30 **Scope:** Applies to agents that manage their own context via model-driven pruning, summarization-in-place, or salience-based eviction where the same inference call both selects content for removal and continues to reason over the resulting window. Does not apply to externalized context managers that evict on a schedule independent of the active reasoning step, nor to append-only logs where no content is ever removed. ## Core Distinction There are two structurally different ways an agent's context can shrink. In *external eviction*, a policy layer outside the reasoning loop removes tokens between turns; the model on the next turn simply sees a shorter window and reasons over what remains, with no in-flight dependency on the removed content. In *self-eviction*, the model's own output within a single generation determines what gets dropped—and the generation that produced the eviction decision is still executing against a window that the eviction is about to mutate. The failure is not "the agent forgot something." It is a read-after-free: the token-level attention state that produced the eviction decision was computed against content that the eviction then removes, but the decode loop continues to emit tokens whose logits were conditioned on that now-removed content. The model has committed to a reasoning path whose premises it has just deleted. This is a distinct boundary from ordinary context saturation, because the window is not full—the agent is actively *making room* and reasoning simultaneously, and the two operations race. ## What Was Observed A retrieval-augmented agent was configured to run a mid-task "compaction" step: when context utilization crossed 0.72, it emitted a structured pruning directive—a JSON array of span IDs to evict, ranked by a salience score the model itself produced. The harness parsed the directive, dropped the spans, re-tokenized, and resumed the same generation stream with the compacted window. The trigger condition was narrow and reproducible. It required three spans with near-equal salience scores (within 0.03) where the *lowest*-scored span was the one that established a type constraint used by a span scored just above the eviction threshold. Concretely: a schema definition span (`Order.total: Decimal, not float`) scored 0.41 and was evicted; a downstream derivation span (`sum line_items → total`) scored 0.44 and survived. The failure trace: 1. The model scored the schema span as low-salience because it was "definitional boilerplate," a learned prior that is usually correct. 2. The eviction directive was emitted and applied *within the same decode loop*. 3. The model continued emitting a numeric aggregation step that assumed `Decimal` semantics. 4. With the constraint span gone, subsequent steps silently coerced to float and accumulated rounding error across 40 line items. 5. The final answer was off by 0.07 and the agent reported high confidence, because the surviving derivation span still "looked" consistent—the contradiction had been physically removed. The signature is diagnostic: the agent's self-reported confidence *increases* immediately after compaction, because the surviving context is internally consistent by construction. Eviction that removes a constraint also removes the evidence that the constraint was violated. ## Condition of Validity The read-after-free only manifests under a specific conjunction, and outside it the same pruning policy is benign: - **Intra-generation mutation.** The eviction must be applied to the window that the *currently decoding* generation is still attending over. If eviction is deferred to a turn boundary—applied only after the current generation terminates—the model completes its reasoning on the full window and the hazard vanishes. - **Latent dependency.** The evicted span must carry a constraint, type, negation, or unit that a surviving span depends on without restating it. Redundant spans (restating something still present) are safe to evict; *load-bearing* spans are not, and salience scoring cannot distinguish the two because redundancy and load-bearingness look identical to a similarity heuristic. - **Salience inversion.** The eviction score must rank the load-bearing span below a dependent span. This is common precisely because constraints are short, definitional, and lexically dissimilar to the task, while the dependent reasoning is long and task-similar. If any one of the three fails, the system is safe. The invariant that bounds the hazard: *no span may be evicted while any surviving span's validity depends on it, and dependency is not recoverable from similarity.* ## Decision Boundary The architect's choice is not "prune or don't prune"—context must be bounded. It is whether pruning is **speculative** (applied mid-generation, cheap, fast, unsafe) or **committed** (applied at a generation boundary with a dependency check, safe, one extra step). The boundary is crossed when the agent treats salience as a proxy for dependency. The correct guardrail is a *dependency-closure check* before any eviction commits: for each candidate span, verify no surviving span references a symbol, constraint, or antecedent it introduces. This check must run on the *post-eviction* window, not the pre-eviction one, because the hazard is invisible until the removal is materialized. If closure cannot be verified cheaply, the fallback is to *summarize rather than delete*—replace the span with a lossy restatement that preserves its constraint, accepting token cost to preserve the invariant. A second, cheaper guardrail: **pin constraint-bearing spans** (those containing type declarations, negations, units, or explicit "must/never" language) as non-evictable regardless of salience score. This trades some compaction efficiency for the elimination of the highest-severity class of read-after-free. ## Operational Effect Systems that prune intra-generation without a closure check exhibit a characteristic pathology: they are *most confident when most wrong*, because every compaction that removes a contradiction also removes the agent's ability to detect it. Error rates on long-horizon numeric and constraint-satisfaction tasks rise superlinearly with the number of compaction events, not with context length—a signature that distinguishes this failure from ordinary forgetting. The remediation is architectural, not prompt-level: move eviction to generation boundaries, run dependency closure on the materialized post-eviction window, and pin constraint spans. Agents that adopt committed pruning lose a fraction of their compaction ratio and recover correctness on exactly the tasks where self-eviction was silently corrupting the answer. ```python from dataclasses import dataclass, field class ReadAfterFreeEviction(RuntimeError): """Raised when an eviction removes a span that surviving spans depend on.""" pass @dataclass class Span: span_id: str text: str salience: float introduces: set = field(default_factory=set) # symbols/constraints this span defines depends_on: set = field(default_factory=set) # symbols this span relies on CONSTRAINT_MARKERS = ("must", "never", "not ", "Decimal", "unit:", "type:") def is_constraint_bearing(span: Span) -> bool: low = span.text.lower() return any(m.lower() in low for m in CONSTRAINT_MARKERS) def commit_eviction(spans, evict_ids, *, intra_generation: bool) -> list: """Apply an eviction only if dependency closure holds on the post-eviction window. Mirrors the article's guardrail: closure is checked on the *materialized* post-eviction set, and constraint spans are pinned when pruning mid-generation. """ if intra_generation and any( is_constraint_bearing(s) for s in spans if s.span_id in evict_ids ): # Pinned-span guardrail: refuse to evict load-bearing constraints mid-decode. raise ReadAfterFreeEviction( "intra-generation eviction of constraint-bearing span; " "defer to generation boundary or summarize-in-place" ) survivors = [s for s in spans if s.span_id not in evict_ids] available = set().union(*(s.introduces for s in survivors)) if survivors else set() for s in survivors: missing = s.depends_on - available if missing: raise ReadAfterFreeEviction( f"span {s.span_id!r} depends on evicted symbols {sorted(missing)}; " "dependency closure violated on post-eviction window" ) return survivors def compact(spans, evict_ids, *, intra_generation: bool): try: return commit_eviction(spans, evict_ids, intra_generation=intra_generation) except ReadAfterFreeEviction: # Fallback: summarize rather than delete, preserving constraints. raise ```