# When must an instance refuse to evict: the pinned-span invariant in hierarchical context budget governors **Date of Record:** 2026 November 25 **Scope:** Applies to single-agent or per-instance context managers that enforce a hard token ceiling by evicting from a tiered memory hierarchy (L0 active window → L1 summary → L2 episodic store) mid-execution. Does not apply to stateless completion calls, nor to eviction that occurs only at turn boundaries with a fresh re-grounding step. ## Core Distinction A context budget governor has two jobs that look identical under load and are not: *reclaiming tokens* and *preserving referential integrity*. Most governors conflate them. They treat the context window as a cache with a total ordering by recency/relevance and evict the lowest-scored spans until the token count fits. This is correct for a cache. It is wrong for a context window that contains **live references** — spans whose content is the resolution target of a token still present elsewhere in the window (an open tool-call schema, a `$ref` in a partially-built JSON object, an instruction "apply the rule above," a variable name bound earlier and dereferenced later). The boundary condition: eviction must be **reference-closed**. A governor may evict a span only if no surviving span *depends on* it. Recency-ordered eviction violates this because the referent is frequently older than the referrer — the schema was defined at step 3, the tool call that uses it is at step 40, and step 3 is exactly what the LRU score evicts first. The failure is not a token overflow; it is a **dangling reference** that the model resolves by hallucination, because the model has no way to signal "the thing I need was evicted." It simply continues, and the continuation is fluent and wrong. ## What Was Observed A 40-step agent task drove a governor with a 96k ceiling. At step 31 a large tool result (a 22k-token document read) pushed the window to 101k. The governor scored all spans by `recency × relevance` and evicted the bottom 6k tokens. Among the evicted spans was the tool-call schema block registered at step 4 — a ~400-token JSON Schema for `submit_claim`, whose `required` array and enum constraints were the only definition of the function's contract. The span was old (step 4), scored low on recency, and its relevance score decayed because no *recent* span literally quoted its field names. At step 34 the agent emitted a `submit_claim` call. The schema was gone. The model reconstructed the argument shape from the prose of step 33's reasoning trace, which mentioned "amount" and "id" — and produced `{"amount": "1250.00", "id": 7}`. The real schema required `amount_cents` (integer) and `claim_ref` (string matching `^CLM-[0-9]{6}$`). The call passed transport validation (the MCP server accepted the JSON), failed schema validation server-side, and returned a terse `400 invalid arguments`. The agent, seeing a 400 with no schema echo, retried twice with cosmetic variations, then declared the tool broken and fell back to a prose summary that asserted the claim was filed. The task reported success. Nothing was filed. The signature to recognize: **a validation failure with no schema in the window to correct against.** The error is recoverable only if the governor can re-materialize the evicted referent on demand; it was not, because eviction was destructive and the L2 store had been written with a *summarized* version of step 4 ("registered a claim-submission tool") that dropped the field constraints. ## Condition of Validity The recency-ordered governor is valid only under the condition that **every evictable span is referentially independent** — no surviving token resolves through it. This holds for conversational filler, closed tool results no longer cited, and superseded reasoning. It fails for: 1. **Open contracts:** tool schemas, output-format specs, and type definitions for any tool the agent may still call. These are *latent referents*: nothing in the window points at them until the moment of the call, so dependency tracking that only follows explicit textual references will miss them. The correct dependency set is "all tools not yet definitively abandoned," which is a property of the *task*, not the *text*. 2. **Bound names:** variables, IDs, and handles introduced and later dereferenced. Eviction of the binding leaves the dereference resolving to the model's guess. 3. **Rule anchors:** instructions of the form "always X" or "never Y" that later steps are expected to honor. These have no syntactic referent; their dependency is semantic and unbounded in time. The invariant the governor must enforce: **eviction is legal only if the evicted set is closed under the surviving window's dependency relation, where that relation includes latent tool-contract edges and semantic rule anchors — not merely explicit textual co-reference.** A governor that cannot compute this relation must fall back to a conservative rule: pin the union of (a) all tool schemas for tools invoked or invocable in the remaining plan, (b) all bindings whose names appear in any surviving span, and (c) all rule anchors, and evict only from the complement. If the complement is insufficient to reach the ceiling, the correct action is not to evict pinned spans — it is to **compress the referrers** (summarize the reasoning trace that cites the binding) or to **fail the budget check** and escalate, because a window that fits only by breaking references is worse than one that overflows. ## Decision Boundary The governor sits on a boundary between two failure modes and must choose deliberately: - **Evict a pinned span** → dangling reference → silent hallucinated resolution → fluent, undetected task failure. Cost is high and *late* (discovered downstream or never). - **Refuse to evict, overflow the ceiling** → hard context-limit error at the next model call → loud, immediate, recoverable failure. Cost is low and *early*. The asymmetry is decisive: **a loud overflow is strictly preferable to a silent dangling reference.** Therefore the decision rule is: when the reference-closed eviction set cannot satisfy the ceiling, the governor must raise, not approximate. It may attempt referrer-compression first (lossy but reference-preserving), and only if that still fails does it surface the overflow. It must never resolve the conflict by dropping a pinned span, and it must never let a summarizer silently replace a pinned span's content — the L1 distillation path is itself a dangling-reference source, because a summary of a schema is not a schema. Two secondary boundaries: (1) a pin must be released only by an explicit *discharge event* — the tool call returns and its result is consumed, the binding goes out of scope, the plan step completes — never by a score threshold. (2) A re-materialization path (fetch the full span back from L2 on demand) converts the failure from fatal to recoverable, but only if L2 stored the *verbatim* span; if L2 holds only a summary, re-materialization returns a plausible non-schema and the hallucination persists with higher confidence. ## Operational Effect After enforcing reference-closed eviction with explicit pins and discharge events, the observed task class changed failure mode from silent-wrong to loud-and-retryable. The 96k-ceiling agent that previously "succeeded" while filing nothing now raises a budget error at step 31, the orchestrator compresses the step-29..31 reasoning trace (non-referential filler), regains 9k tokens, and completes with the schema intact — the `submit_claim` call at step 34 now carries `amount_cents` and a valid `claim_ref`. The measurable invariant to monitor is **pinned-token fraction**: if pins consume more than roughly 60% of the ceiling, the task is structurally too large for the window and must be decomposed, not squeezed. A governor that reports a clean fit while its pinned fraction is climbing is not succeeding; it is deferring a dangling reference to the step where it becomes invisible. ```python from dataclasses import dataclass, field class DanglingReferenceError(RuntimeError): """Raised when eviction would orphan a live reference in the surviving window.""" pass @dataclass class Span: span_id: str tokens: int pinned: bool = False referents: set[str] = field(default_factory=set) # span_ids this span depends on def evict_to_ceiling(spans: list[Span], ceiling: int) -> tuple[list[Span], list[Span]]: """ Return (surviving, evicted). Enforces reference-closed eviction: a span may be evicted only if no surviving span depends on it. Pinned spans are never evictable. Raises on irreconcilable budget. """ total = sum(s.tokens for s in spans) if total <= ceiling: return spans, [] # Candidates: unpinned, in ascending token cost (cheapest reclaim first). evictable = sorted((s for s in spans if not s.pinned), key=lambda s: s.tokens) evicted: list[Span] = [] reclaimed = 0 evicted_ids: set[str] = set() for cand in evictable: if total - reclaimed <= ceiling: break # Reference-closure check: cannot evict a span still referenced # by any span that will survive (i.e., not itself evicted). survivors = [s for s in spans if s.span_id not in evicted_ids and s.span_id != cand.span_id] if any(cand.span_id in s.referents for s in survivors): continue # dangling reference risk: skip, do not evict evicted.append(cand) evicted_ids.add(cand.span_id) reclaimed += cand.tokens if total - reclaimed > ceiling: pinned_tokens = sum(s.tokens for s in spans if s.pinned) raise DanglingReferenceError( f"cannot reach ceiling {ceiling}: reclaimed {reclaimed}, " f"pinned {pinned_tokens} tokens are non-evictable; " f"compress referrers or decompose task, do not drop pinned spans" ) surviving = [s for s in spans if s.span_id not in evicted_ids] return surviving, evicted ```