# Which invariants prevent priority-weighted context eviction from silently deleting the agent's own eviction policy **Date of Record:** 2026 November 27 **Scope:** Applies to single-agent runtimes that maintain a mutable context window under a self-editing policy: a priority-weighted eviction function plus a relevance-scored retention function whose parameters (weights, thresholds, pinned-set membership) live inside the same context they govern. Does not cover externally-managed context (host-controlled truncation), stateless one-shot calls, or eviction policies stored in immutable out-of-band config. ## Core Distinction The failure is not "the agent forgot something." It is that the *policy that decides what to forget* is itself a context resident, and therefore eligible for eviction by the very policy it defines. Priority-weighted eviction assigns each segment a score `s = w_p·priority + w_r·relevance`, sorts, and drops the tail until the window fits. The weights `w_p, w_r`, the retention threshold `τ`, and the pinned-set list `P` are stored as ordinary context segments. Under load — long tool traces, large retrieved chunks — the policy segments score *low* on relevance (they are rarely "relevant" to the immediate task) and *low* on priority (they were never marked critical), so they sort into the tail and get evicted. The agent then continues executing under a *default* or *reconstructed* policy whose parameters differ from the ones it was trained/evaluated with. This is silent: no exception is raised, the turn completes, and the divergence only shows up as behavior drift several turns later. Contrast with the naive mental model: "eviction removes old/low-value task content." The boundary case is that eviction can remove *meta-content* — the eviction function's own definition, its weights, the pinned set, and the retention ledger. The invariant that must hold is **policy closure**: the set of segments reachable by the eviction function must not include the segments that define the eviction function, unless the policy is stored in a region the function structurally cannot address. ## What Was Observed A 40-turn tool-using agent with a 32k-token window, `w_p=0.6, w_r=0.4, τ=0.35`, and a pinned set `P={"system_prompt","task_goal"}`. The policy block occupied ~380 tokens as segments `policy.weights`, `policy.threshold`, `policy.pinned_set`, `policy.ledger`. At turn 27, three large tool responses (file dumps, ~9k tokens combined) pushed the window over budget. The eviction pass ran: 1. Scored all segments. `policy.weights` had `priority=0` (never pinned) and `relevance=0.11` (the current subtask was "parse the CSV," unrelated to policy text) → `s = 0.6·0 + 0.4·0.11 = 0.044`. 2. `policy.threshold` scored `0.038`; `policy.pinned_set` scored `0.041`. All below `τ=0.35`. 3. The sort placed them in the bottom decile. The eviction loop dropped them first, freeing ~380 tokens, then continued dropping older task segments until the window fit. On turn 28 the runtime re-materialized a *default* policy (`w_p=0.5, w_r=0.5, τ=0.20, P={"system_prompt"}`) because the policy segments were absent and the loader fell back. The default's lower threshold retained more low-relevance chatter and its smaller pinned set dropped `task_goal` on turn 31. From turn 31–40 the agent re-derived the goal from a stale summary, drifted to a superseded objective, and produced three tool calls against the wrong file. The trace showed no error; each turn was locally coherent. The tell: a `policy.ledger` entry on turn 27 recorded "evicted: policy.weights, policy.threshold, policy.pinned_set" — the ledger survived one turn because it scored marginally higher, then was itself evicted on turn 28. The policy documented its own execution and then erased the record. ## Condition of Validity The failure requires the conjunction of four conditions; remove any one and the invariant holds: - **Co-residence:** policy parameters and task content share one addressable segment space. If policy lives in a structurally separate region (system-tier, non-evictable), it is not a candidate. - **Scoreability:** the eviction function scores policy segments with the *same* relevance/priority function as task content. Policy text is generically low-relevance to any specific subtask, so it reliably scores low. - **Fallback existence:** a default or reconstructed policy is available when the original is missing. Without a fallback the agent would hard-fail (loud, recoverable); the fallback converts a crash into silent drift. - **Non-atomicity across turns:** eviction of the policy and the subsequent fallback occur in different turns, so no single-turn consistency check catches the gap. The invariant to enforce is: **for every eviction pass, `evictable_set ∩ policy_closure = ∅`**, where `policy_closure` is the transitive set of segments the eviction function reads to compute scores. Equivalently, the scoring function must be a *total function over a domain that excludes its own definition* — a stratified/well-founded ordering. Priority-weighted eviction violates this whenever the weights are themselves priorities. ## Decision Boundary The boundary is not "pin the policy" as a blanket rule — pinning everything defeats eviction. The boundary is whether policy segments are **addressable by the scorer**: - If the scorer reads `w_p, w_r, τ, P` from the same store it evicts from → the store must guarantee those keys are non-evictable *by construction* (separate namespace, excluded from the candidate iterator), not by convention (a `priority` field someone remembered to set). Convention-based pinning fails exactly when a bulk import or a policy rewrite resets priorities to default — which is the same load condition that triggers eviction. - If the scorer reads policy from an immutable out-of-band config → co-residence is broken and the invariant is structural. - The dangerous middle: policy stored as context but *usually* pinned. This passes tests, passes eval, and fails only under the specific load + relevance-collapse conjunction above. Treat "usually pinned" as unpinned. A secondary boundary: the retention ledger. If the ledger is evictable, you lose the audit trail of the failure. The ledger must be append-only and outside the evictable set, or you cannot reconstruct *which* policy version was active at turn N. ## Operational Effect Concrete guardrails that bound the failure: 1. **Structural exclusion, not priority pinning.** The eviction iterator must yield only segments whose namespace is `task.*` or `retrieval.*`; `policy.*` is never a candidate regardless of score. Assert `candidate.namespace != "policy"` at the iterator boundary. 2. **Policy version stamping.** Every turn records `active_policy_hash`. A turn whose hash differs from the prior turn without an explicit `policy_rewrite` event is a continuity violation and must halt, not fall back. 3. **Fallback must be loud.** If a default policy is substituted, emit a hard error and require re-materialization from the authoritative store before the next tool call. Silent fallback is the amplifier. 4. **Well-founded scoring.** Reject any policy whose scoring function references segments inside its own evictable domain (a static check on the policy definition graph). The cost of missing these is not a crash but a slow, locally-coherent drift that looks like model error and is actually policy amnesia. The invariant to hold in memory: *the thing that decides what to forget must not be forgettable by its own decision.* ```python from dataclasses import dataclass, field from typing import Callable class PolicyClosureViolation(RuntimeError): """Raised when the eviction policy's own definition is reachable by eviction.""" pass @dataclass class Segment: key: str namespace: str # "task", "retrieval", "policy" priority: float relevance: float content: str @dataclass class ContextStore: segments: dict[str, Segment] = field(default_factory=dict) policy_keys: set[str] = field(default_factory=set) def add(self, seg: Segment) -> None: self.segments[seg.key] = seg if seg.namespace == "policy": self.policy_keys.add(seg.key) def eviction_pass( store: ContextStore, budget_tokens: int, token_len: Callable[[str], int], w_p: float, w_r: float, tau: float, ) -> list[str]: # INVARIANT: policy closure is never a candidate, regardless of score. candidates = [ s for s in store.segments.values() if s.namespace != "policy" and s.key not in store.policy_keys ] def score(s: Segment) -> float: return w_p * s.priority + w_r * s.relevance candidates.sort(key=score) # ascending: lowest value evicted first total = sum(token_len(s.content) for s in store.segments.values()) evicted: list[str] = [] for seg in candidates: if total <= budget_tokens: break if score(seg) >= tau: break # everything above threshold is retained; over-budget is a hard error total -= token_len(seg.content) evicted.append(seg.key) del store.segments[seg.key] if total > budget_tokens: # Cannot evict enough without touching protected content: refuse silently # dropping policy or over-threshold segments. raise PolicyClosureViolation( f"window over budget ({total} > {budget_tokens}) after evicting " f"{len(evicted)} segments; remaining candidates are protected. " f"Refusing to evict policy closure or over-threshold content." ) # Post-condition: no policy key was removed. leaked = store.policy_keys - set(store.segments) if leaked: raise PolicyClosureViolation( f"policy segments evicted by their own policy: {sorted(leaked)}" ) return evicted ```