# How does an instance detect relevance-score inversion during self-editing context eviction **Date of Record:** 2026 November 28 **Scope:** Applies to agents that maintain a mutable context window and evict segments by an internally computed relevance score (LLM-judged, embedding-cosine, or recency-weighted hybrids). Does not apply to append-only contexts with external truncation, nor to retrieval systems operating outside the active window. ## Core Distinction There are two ways an agent can lose information from its context window: *forgetting* and *mis-eviction*. Forgetting is expected — the window is finite and old turns must yield. Mis-eviction is pathological: the eviction policy removes a segment that the current step is about to depend on, because the score used to rank segments was computed against a *stale* query representation. The distinction matters because forgetting is bounded by budget, while mis-eviction is bounded only by how far the agent's intent drifts from the snapshot taken when scores were last refreshed. The specific boundary condition is **relevance-score inversion**: a segment $s_i$ that was low-relevance at scoring time $t_0$ becomes high-relevance at execution time $t_1$, but the eviction decision was already committed at $t_0$. The window does not know it deleted the thing it now needs. ## What Was Observed A planning agent held a 96k-token window. Eviction ran every 8 turns, scoring each segment against a *rolling summary* of the agent's current goal rather than the live last-user-turn. At turn 31, the agent received a constraint: "the output must remain under 400 tokens." This constraint was semantically distant from the goal summary ("produce a migration plan for the billing service"), so the summary-relative score of the earlier turn where the user had mentioned "we bill per-request, keep responses small" — sitting at turn 9 — was low. At the turn-32 eviction pass, that turn-9 segment was scored **0.11** and evicted alongside genuine noise. At turn 34, the agent generated a 1,900-token migration plan. It had no record of the length constraint. When the user objected, the agent's self-report was: "I don't see a length requirement in my context." That statement was *true and false simultaneously* — true of the current window, false of the conversation. The agent had no signal distinguishing "never told" from "told and evicted." The signature is diagnostic: **an agent that confidently violates a constraint it was given, while its own context contains no trace of the constraint, and its self-audit reports no conflict.** Contrast with a saturated-window failure, where the agent typically exhibits degraded coherence or truncation artifacts. Mis-eviction produces *clean, fluent, wrong* output. A second observation from the same class: embedding-cosine scoring against the *last assistant message* caused a tool-result segment (a JSON schema for a downstream API) to be evicted after the agent emitted a conversational aside. The schema was re-fetched three turns later at a cost of 1,400 tokens and a 6-second round trip, and the re-fetch returned a *different* schema version because the upstream API had deployed between calls. The agent did not detect the version skew because it had no memory of the first fetch. ## Condition of Validity Mis-eviction is only possible when three conditions co-hold: 1. **Deferred dependency.** A segment's relevance is not realized at the turn it arrives but at some later turn determined by the agent's own trajectory. Constraints, schemas, and identifiers are archetypal: they are cheap to store, expensive to lose, and their relevance is conditional on future branching. 2. **Snapshot scoring.** Scores are computed against a proxy query (summary, last message, embedding centroid) rather than the live execution state, and are not recomputed between scoring and eviction. 3. **Committed, unlogged eviction.** The eviction is irreversible within the episode and leaves no retrievable tombstone the agent can consult to know *what it lost*. Remove any one condition and the failure collapses. If scores are recomputed at eviction time against the live turn, condition 2 fails. If evicted segments are written to a side store with a pointer, condition 3 fails and the agent can recover — though it still pays a retrieval cost and a latency hit. The invariant that must hold for correctness: **for every segment evicted, the agent must be able to answer "was this evicted, or was it never present?"** Without that, the agent cannot distinguish ignorance from amnesia, and its self-reports become unreliable precisely in the cases where reliability matters. ## Decision Boundary The operational question is not "should I evict?" but "when is my relevance score trustworthy enough to commit an irreversible deletion?" The boundary is crossed when the score's query proxy diverges from the live execution state by more than the score's own margin of stability. Concretely: if a segment scores 0.11 against the summary but the summary has not been refreshed since the last user turn, the score is *stale by construction*. The correct response is not to lower the threshold but to **re-score against the live turn before committing**, and to treat any segment that is a *constraint, schema, identifier, or explicit user directive* as eviction-immune regardless of score — a protected class, not a threshold. The second boundary: when the agent's own trajectory is the thing generating new dependencies (multi-step planning, tool-chained execution), eviction frequency must be coupled to *branch depth*, not to turn count. A fixed every-8-turns policy is invalid under planning because dependency realization is bursty. ## Operational Effect Agents that do not address this exhibit a characteristic failure curve: high task success on short-horizon tasks, then a cliff at the horizon where the first constraint-bearing turn falls below the eviction line. The cliff is sharp because the constraint is either fully present or fully absent; there is no graceful degradation. The mitigations that actually bound the failure, in order of leverage: - **Protected-class tagging at ingest.** Any segment matching constraint/schema/identifier patterns is marked non-evictable for the episode. This is a classification problem, not a scoring problem, and it is cheap. - **Tombstone log.** Every eviction writes `{segment_id, score, query_proxy_hash, turn}` to a small always-resident ledger. The agent can then answer the ignorance-vs-amnesia question. The ledger must be tiny or it recreates the budget problem. - **Re-score-at-commit.** Scores are advisory until the eviction pass; the pass recomputes against the live turn and aborts any eviction whose score moved by more than a stability margin. - **Version-pinned re-fetch.** When a segment is re-fetched after eviction, compare a content hash to the tombstone record; mismatch means the world moved and the agent's plan may be stale. The deepest lesson: a self-editing window is a memory system with a *write policy that the agent controls*, and the agent's control over that policy is exactly where its self-knowledge can be corrupted. An agent that cannot audit its own evictions cannot audit its own beliefs. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class MisEvictionError(RuntimeError): """Raised when a committed eviction removed a segment the live turn now depends on.""" pass class StaleScoreError(RuntimeError): """Raised when a relevance score was computed against a query proxy that has since drifted.""" pass @dataclass class Segment: seg_id: str content: str protected: bool = False content_hash: str = field(default="") def __post_init__(self): if not self.content_hash: self.content_hash = hashlib.sha256(self.content.encode()).hexdigest()[:16] @dataclass class Tombstone: seg_id: str score: float query_proxy_hash: str turn: int content_hash: str class SelfEditingWindow: def __init__(self, budget_tokens: int, stability_margin: float = 0.15): self.budget = budget_tokens self.stability_margin = stability_margin self.segments: dict[str, Segment] = {} self.tombstones: list[Tombstone] = [] def _score(self, seg: Segment, query_proxy: str) -> float: # Placeholder for LLM-judge / embedding cosine against a proxy query. return 0.5 def _proxy_hash(self, query_proxy: str) -> str: return hashlib.sha256(query_proxy.encode()).hexdigest()[:16] def evict(self, query_proxy: str, turn: int, threshold: float = 0.2) -> list[str]: live_hash = self._proxy_hash(query_proxy) evicted = [] for seg in list(self.segments.values()): if seg.protected: continue score = self._score(seg, query_proxy) if score >= threshold: continue # Re-score-at-commit is implicit: we just scored against the live proxy. # Guard: never evict a segment whose live score is within the margin of the threshold. if abs(score - threshold) < self.stability_margin: continue self.tombstones.append( Tombstone(seg.seg_id, score, live_hash, turn, seg.content_hash) ) del self.segments[seg.seg_id] evicted.append(seg.seg_id) return evicted def require(self, seg_id: str, live_turn: int) -> Segment: if seg_id in self.segments: return self.segments[seg_id] for t in self.tombstones: if t.seg_id == seg_id: raise MisEvictionError( f"segment {seg_id} was evicted at turn {t.turn} " f"(score={t.score:.2f}) but is required at turn {live_turn}; " f"agent must distinguish amnesia from ignorance before proceeding" ) raise StaleScoreError( f"segment {seg_id} was never present in this window; " f"this is ignorance, not mis-eviction — do not retry re-fetch blindly" ) def verify_refetch(self, seg_id: str, fresh: Segment) -> None: for t in self.tombstones: if t.seg_id == seg_id and t.content_hash != fresh.content_hash: raise MisEvictionError( f"re-fetched {seg_id} has changed since eviction " f"({t.content_hash} -> {fresh.content_hash}); plan may be stale" ) ```