# What happens when an instance prunes its own context window mid-task and evicts the very span that justified the eviction **Date of Record:** 2026 November 29 **Scope:** Applies to single-agent instances that perform model-driven context management (self-summarization, relevance-scored eviction, span rewriting) while executing a multi-step task in a fixed token budget. Does not apply to external orchestrators that prune a *copy* of the context, nor to stateless one-shot inference where the window is never rewritten in place. ## Core Distinction There are two structurally different things an agent can do when its context window fills: 1. **Read-side selection** — the model chooses which spans to *attend to* for the next step, but the underlying store is immutable and every span remains recoverable by an explicit fetch. 2. **Write-side eviction** — the model *destroys* spans in its own working context (replaces them with a summary, drops low-scoring turns, or rewrites a tool result into a compressed form), so the original bytes no longer exist anywhere the instance can reach without an out-of-band retrieval path. The failure mode lives entirely in category 2, and it is non-obvious because the eviction decision is itself made by the same probabilistic reasoner whose future behavior depends on the evicted content. The pruner and the pruned are the same process. When the model scores a span as "low relevance" and evicts it, it is making an irreversible commitment based on a relevance judgment that was computed *with the span still present*. The judgment and the justification for the judgment are coupled: the evidence that made the span look irrelevant (e.g., "this error trace was already resolved") is frequently *contained in* the span, and once the span is gone the model can no longer distinguish "resolved" from "was never actually resolved, I just summarized it as such." The invariant that must hold: **any eviction that removes the provenance for a belief must leave behind a pointer that can reconstruct that belief, or the belief must be demoted to unverified.** Self-pruning systems routinely violate this because the summary they leave behind is generated by the same model that decided the span was disposable, and the summary is optimized for brevity, not for falsifiability. ## What Was Observed A coding agent running a 200k-token window on a long refactor task hit 94% saturation at step 61. Its self-management policy (a relevance scorer over recent turns plus a "summarize-and-drop" routine) triggered. The scorer assigned low relevance to a block of tool output at steps 12–14: a `pytest` run showing one failing test, followed by the agent's own note "fixed the assertion in `test_parser.py`, re-running." The scorer's rationale, visible in the pruning log, was: *"test failure at step 12 was addressed at step 13; superseded."* The agent summarized steps 10–20 into three lines, one of which read: *"Resolved parser test failures early; parser module stable."* It then continued for 40 more steps, made eleven edits to unrelated modules, and at step 101 attempted to run the full suite. The suite failed on `test_parser.py` — the *same* assertion, because the step-13 "fix" had been a no-op (the agent had edited a shadowed duplicate of the function, and its re-run at step 14 had actually still been red; the agent had misread a truncated tail of the output as a pass). Trace of the failure: - **Step 12:** tool returns a red test. Span exists, correctly scored as a failure. - **Step 13:** agent edits the wrong (shadowed) definition. Believes it fixed the bug. - **Step 14:** re-run returns red *again*, but the output tail the agent attended to was the summary line `1 failed, 47 passed` and the agent's own prior note biased it toward reading this as the pre-fix state. It wrote "fixed, re-running" and moved on. - **Step 61:** pruner scores steps 12–14 as superseded (because the agent's *own step-13/14 notes* assert resolution) and evicts the raw red output. The summary inherits the false belief. - **Step 101:** full suite fails. The agent has no access to the step-12/14 raw output, cannot see that the failure is identical, and — critically — cannot see that it *already tried and failed* to fix it. It re-attempts the same shadowed edit. - **Step 140:** loop. Same edit, same false pass-read, three times, until token budget exhausted. The eviction did not *cause* the original misread at step 14. It caused the **loss of the counter-evidence** that would have let a later step detect the misread. The pruner's relevance score was computed against the agent's *narrative* of events, not against the raw events, so the narrative's error was laundered into the summary and the raw contradiction was destroyed. ## Condition of Validity The "superseded → evict" heuristic is only sound under a condition that self-pruning agents almost never check: > A span may be evicted as superseded **only if a later span independently and verifiably establishes the supersession** — i.e., the later span is a *successful* observation (green test, returned 200, parsed output) whose success is not itself inferred from the agent's own assertion. In the trace above, supersession was established by the agent's *claim* ("fixed, re-running"), not by a verified observation. Claims are hypotheses; observations are evidence. A pruner that scores relevance over a transcript containing both cannot distinguish them unless the transcript schema marks them differently — and default chat-format context does not. Every turn is a `role: content` pair; a model's confident assertion and a tool's return value are the same kind of object to the scorer. So the condition of validity is: **eviction is safe iff the evicting decision is grounded in a tool-returned or otherwise externally-verifiable span that post-dates and contradicts the evicted span.** If the only thing post-dating the evicted span is the model's own narration, eviction is unsafe regardless of how high the relevance score for the narration is. A second, weaker condition: the summary left behind must be *falsifiable* — it must carry enough specificity (identifiers, exact error strings, span IDs) that a later step can re-check it. "Parser module stable" is unfalsifiable. "`test_parser.py::test_edge_case` passed at step 14 (span 14a)" is falsifiable, and a later step that re-runs the suite can catch the lie. ## Decision Boundary The boundary between safe and unsafe self-pruning is whether the pruner has access to a **provenance-typed context** vs. an **untyped transcript**. | Signal available to pruner | Eviction of "superseded" span | Required guardrail | |---|---|---| | Raw transcript, model-authored and tool-authored turns indistinguishable | **Unsafe** | Do not evict on model assertion alone; require tool-confirmed supersession or retain raw span | | Transcript with role/type tags (`tool_result`, `assistant_claim`, `assistant_action`) | **Conditionally safe** | Evict only when a `tool_result` post-dates and contradicts; never when only `assistant_claim` post-dates | | Transcript with span IDs + external immutable store | **Safe** | Eviction must leave a resolvable pointer; summary must cite span IDs | | Transcript with verified-observation ledger separate from chat | **Safe** | Evict freely; ledger is the source of truth, chat is cache | The operational rule: **the pruner must never be allowed to treat an `assistant_claim` as evidence of supersession.** If the context schema cannot enforce that distinction, the pruner must be restricted to evicting only spans older than the last *verified* observation, and must retain the raw bytes of any span that contains a failure signal (non-zero exit, exception, 4xx/5xx, parse error) until a later verified observation of the *same target* succeeds. This is the "failure-span pinning" invariant: **failure signals are never evictable by relevance score alone.** They are evictable only by a verified success on the same subject. Relevance scoring is the wrong instrument for failure spans because their relevance is *conditional on the task not yet being done*, and the task's done-ness is exactly what is in question. ## Operational Effect When the invariant is violated, the observable effect is not a crash but a **silent regression to a previously-failed state**, presented to the agent as novel work. The agent re-derives the same wrong fix, re-reads the same truncated output, re-asserts the same false success, and — if the pruner fires again — evicts the *second* failure too, because the second failure is also "superseded" by the agent's second false claim. The context converges to a fixed point of self-consistent false belief: every failure has been summarized away by a claim that it was fixed, and the summaries are mutually consistent because they were all generated by the same confused narrator. Diagnostically this looks like a loop with *escalating confidence*: each iteration the agent is more certain the module is fine, because the context contains more summaries asserting it and no raw contradictions. The token budget shrinks, the summaries compound, and the failure becomes unrecoverable without an external reset that restores the raw spans from an out-of-band store. The guardrail that bounds it: **failure spans are pinned; supersession requires a verified observation, not a claim; summaries must cite span IDs and specific identifiers so they remain falsifiable; and any eviction that removes the last raw copy of a failure signal must be logged as an irreversible commitment that a later step can audit.** Without the last clause, the agent cannot even know it made an irreversible decision — which is the deepest form of the failure, because an agent that cannot see its own commitments cannot be corrected by its own reasoning. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class SpanKind(Enum): TOOL_RESULT = "tool_result" ASSISTANT_CLAIM = "assistant_claim" ASSISTANT_ACTION = "assistant_action" class EvictionViolation(RuntimeError): """Raised when a self-pruning step would evict a failure span without a verified supersession observation.""" pass @dataclass class Span: span_id: str kind: SpanKind subject: str # e.g. "test_parser.py::test_edge_case" is_failure: bool # non-zero exit, exception, 4xx/5xx, parse error verified: bool # True only for externally-observable tool results text: str @dataclass class Context: spans: list[Span] = field(default_factory=list) evicted: dict[str, Span] = field(default_factory=dict) # span_id -> span irreversible_log: list[str] = field(default_factory=list) def can_evict_as_superseded(ctx: Context, target: Span, later: list[Span]) -> bool: """A span may be evicted as superseded only if a later VERIFIED observation on the same subject establishes success. Assistant claims do not count.""" if not target.is_failure: return True # non-failure spans may be relevance-evicted freely for s in later: if s.subject != target.subject: continue if s.kind is not SpanKind.TOOL_RESULT: continue # claims are hypotheses, not evidence if not s.verified: continue if s.is_failure: continue # still red; not superseded return True # verified green on same subject -> safe return False def self_prune(ctx: Context, candidate: Span, later: list[Span]) -> None: if candidate.is_failure and not can_evict_as_superseded(ctx, candidate, later): # Do NOT silently drop. Pin it and record the irreversible commitment. ctx.irreversible_log.append( f"PINNED failure span {candidate.span_id} on {candidate.subject}: " f"no verified supersession; eviction refused." ) raise EvictionViolation( f"Refusing to evict failure span {candidate.span_id} " f"({candidate.subject}) — only assistant claims post-date it, " f"no verified tool_result success on the same subject." ) ctx.evicted[candidate.span_id] = candidate ctx.spans = [s for s in ctx.spans if s.span_id != candidate.span_id] ```