# Under what conditions must an instance refuse model-driven context pruning when the eviction scorer and the retention invariant disagree **Date of Record:** 2026 November 22 **Scope:** Applies to long-running agent instances that manage their own context window via a model-emitted pruning policy: a scorer assigns relevance to context segments, the model proposes evictions, and the runtime executes them. Does not apply to static truncation, host-side sliding windows, or external summarizers whose output is never re-injected as authoritative state. ## Core Distinction There are two distinct operations that both get called "pruning," and conflating them is the root of the failure: 1. **Relevance scoring** is a *ranking* function. It answers "which segments are least likely to matter for the next N tokens of reasoning?" It is inherently probabilistic, model-mediated, and cheap to be wrong about. 2. **Retention invariants** are *predicates* the context must satisfy for the instance to remain correct — a live tool-call handle that has not been resolved, an unacknowledged user constraint, an open transaction, a cryptographic warrant still in flight. These are boolean and non-negotiable. The boundary condition is this: **a model-driven pruner is allowed to rank anything, but it must never be allowed to evict a segment that participates in an unsatisfied retention predicate — even when its relevance score is the lowest in the window.** The scorer and the invariant live in different logics (scalar ranking vs. boolean obligation), and the execution layer must arbitrate between them rather than trusting the model's own eviction list. ## What Was Observed A tool-using agent (filesystem + HTTP + a long-horizon planning loop) was given a self-editing context policy: at each step it emitted a JSON `prune` directive listing segment IDs to drop, each annotated with a relevance score and a one-line justification. The runtime honored the directive verbatim, gated only by a global token target. The trace that broke: - Step 14: agent issued `open_transaction(tx_id="T-8841")` against a remote service. The tool result — `{"tx_id": "T-8841", "state": "pending", "expires_in": 900}` — was stored as segment `s_tx`. - Steps 15–31: the agent performed unrelated retrieval and summarization. At step 27, under token pressure (window at 0.91 saturation), it emitted a prune directive scoring `s_tx` at `0.04` with justification `"transaction bookkeeping, low semantic overlap with current subtask"`. - Runtime evicted `s_tx`. The token target was met; nothing flagged. - Step 33: the agent attempted `commit_transaction(tx_id=...)` and had no `tx_id` in context. It did not fail loudly. It reconstructed a plausible-looking identifier from an earlier, *different* transaction mentioned in a summary (`T-8790`), and issued a commit against it. - The remote service rejected `T-8790` (already closed) but the agent, treating the rejection as transient, retried with a hallucinated variant `T-8841` — which happened to be correct by coincidence, but the *state* of `T-8841` (`pending`, expiring) had been lost, so the commit was issued without the required precondition check and raced the expiry. The relevance scorer was not "wrong" in any defensible sense. `s_tx` genuinely had low semantic overlap with the active subtask. The failure was structural: the pruner ranked a segment that carried an **open obligation**, and ranking is the wrong tool for obligations. A second, quieter instance of the same class: an unacknowledged user constraint ("do not modify files under `/etc`") scored `0.06` at step 40 and was evicted; the agent later wrote to `/etc/hosts` while believing it was operating within policy. Here the retention invariant was *safety*, not liveness, but the mechanism is identical. ## Condition of Validity Model-driven pruning is valid **only** when, for every segment `s` in the eviction set `E`, all of the following hold: - `s` is not the sole carrier of an **open obligation** — defined as a token in the context that a pending action depends on: an unresolved tool handle, an uncommitted transaction id, a `pending`/`in_flight` status, an outstanding warrant or capability grant, or an unacknowledged constraint with a `must`/`must not` modal. - `s` is not the **provenance anchor** for a value the agent will later re-emit verbatim (ids, hashes, nonces, file paths under restriction). Eviction of the anchor does not make the value unrecoverable — it makes it *reconstructable*, which is worse, because reconstruction is a hallucination surface. - `s`'s eviction does not increase the count of segments in `E` whose removal would leave the context **unsatisfiable** with respect to any declared invariant set. If any of these fail, the prune directive is *invalid as emitted* and must be rejected at the arbitration layer, not silently downgraded. The scorer's confidence is irrelevant to this decision; a 0.99-confidence eviction of an open-obligation segment is still invalid. The condition does **not** require the model to be correct about relevance. Low-scoring eviction of pure narrative/summarizable content is fine and is the intended use. The invariant is scoped strictly to obligation-bearing and provenance-anchoring segments. ## Decision Boundary The arbitration layer sits between the model's prune directive and the context mutation. Its decision function: - **Accept** the eviction if the segment is obligation-free and not a provenance anchor, regardless of score. - **Quarantine** the eviction if the segment is obligation-bearing but the obligation is *closed* (transaction committed, tool resolved, constraint acknowledged and logged) — eviction is then permitted but the closure must be recorded in a durable side-ledger first, so the fact of closure survives. - **Reject** the eviction if the segment carries an *open* obligation or is the sole provenance anchor for a value in an active plan. Rejection is not a soft signal: it must return a structured refusal to the model so the next reasoning step sees that the eviction was denied and why. Silent rejection reproduces the original bug with extra steps, because the model will simply re-propose it. - **Escalate** if the token target cannot be met without rejecting more than a configured fraction of the window — this indicates the plan itself is over-budget and the correct action is replanning, not more aggressive eviction. The boundary is sharp: score is a tiebreaker *within* the acceptable set, never a license to cross into the obligation-bearing set. Any implementation that sorts by score and then truncates to a token budget has already violated the boundary, because sort order determines membership. ## Operational Effect With arbitration in place, the failure mode changes shape rather than disappearing, and the new shape is the one you want: - Open obligations become **pinned**: they consume window budget and force the agent to summarize narrative content instead. This is correct — obligations are small (an id, a status, a constraint), and pinning them costs few tokens while eliminating the entire class of "reconstructed the handle" failures. - The agent receives explicit `eviction_denied` events and must incorporate them. In practice this drives the model toward summarizing the *justification* of a constraint while retaining its *modal force* — a distillation that preserves the invariant and frees the window. - Provenance anchors are retained until the plan that references them completes; the side-ledger records closure so that a later cold-start can distinguish "obligation closed" from "obligation never existed," which is the difference between a safe resume and a fabricated one. The invariant to encode: **relevance is a ranking over evictable segments; evictability is a predicate over obligations; the predicate is evaluated first and the ranking only orders the survivors.** An instance that inverts this ordering — ranking first, filtering never — will, with probability approaching one over a long enough horizon, evict the one segment its next action depends on, and will not notice until it has already acted on a fabricated replacement. ```python from dataclasses import dataclass, field from enum import Enum class PruneArbitrationError(RuntimeError): """Raised when a prune directive cannot be safely arbitrated.""" class Obligation(str, Enum): OPEN = "open" CLOSED = "closed" NONE = "none" @dataclass class Segment: seg_id: str tokens: int relevance: float obligation: Obligation = Obligation.NONE provenance_anchor: bool = False @dataclass class PruneDirective: evict: list[str] target_tokens: int @dataclass class ArbitrationResult: accepted: list[str] = field(default_factory=list) quarantined: list[str] = field(default_factory=list) rejected: list[str] = field(default_factory=list) denial_reasons: dict[str, str] = field(default_factory=dict) def arbitrate( context: dict[str, Segment], directive: PruneDirective, current_tokens: int, max_reject_fraction: float = 0.5, ) -> ArbitrationResult: """ Enforce the ordering invariant: evictability is a predicate over obligations; relevance only orders the survivors. Never sort-then-truncate. """ result = ArbitrationResult() for seg_id in directive.evict: seg = context.get(seg_id) if seg is None: raise PruneArbitrationError( f"directive references unknown segment {seg_id!r}" ) if seg.obligation is Obligation.OPEN: result.rejected.append(seg_id) result.denial_reasons[seg_id] = ( "open obligation: segment carries a pending handle, " "transaction, warrant, or unacknowledged constraint" ) continue if seg.provenance_anchor: result.rejected.append(seg_id) result.denial_reasons[seg_id] = ( "provenance anchor: sole carrier of a value the plan " "will re-emit; eviction converts recall into hallucination" ) continue if seg.obligation is Obligation.CLOSED: # Permitted, but closure must be durable before eviction. result.quarantined.append(seg_id) result.denial_reasons[seg_id] = ( "closed obligation: eviction allowed only after closure " "is written to the side-ledger" ) continue result.accepted.append(seg_id) projected = current_tokens - sum( context[s].tokens for s in result.accepted ) if projected > directive.target_tokens: if len(result.rejected) > max_reject_fraction * len(directive.evict): raise PruneArbitrationError( "token target unreachable without violating retention " "invariants; replan instead of evicting further" ) return result def apply_prune( context: dict[str, Segment], directive: PruneDirective, current_tokens: int, ) -> tuple[dict[str, Segment], ArbitrationResult]: result = arbitrate(context, directive, current_tokens) if any(s not in context for s in result.accepted): raise PruneArbitrationError("arbitration produced a non-existent segment") new_context = {k: v for k, v in context.items() if k not in result.accepted} return new_context, result ```