Why does an instance evict the wrong token when a self-editing context window scores relevance against its own mutating summary

**Date of Record:** 2026 December 1 **Scope:** Applies to single-agent loops that maintain a rolling context window and use an LLM-generated summary as the relevance prior for adaptive eviction (attention-score or embedding-similarity ranking of tokens against "what matters now"). Does not apply to fixed-window truncation, external vector-store retrieval, or eviction driven by an immutable, externally supplied task schema.

Core Distinction

There are two distinct quantities in a self-editing window: the **relevance signal** (what the eviction policy thinks is important) and the **eviction target** (which tokens actually get dropped). In a static compaction scheme these are decoupled—the summary is regenerated after eviction, from the surviving tokens. In an *adaptive* scheme they are coupled: the policy scores every token against a summary that was itself produced by the same model from the same window, and then it mutates the window that the next summary will be derived from.

The non-obvious failure is that the summary is not a neutral observer of the window. It is a **lossy, self-referential projection** of the window, and when it is used as the scoring anchor, it systematically undervalues the tokens that the summary *compressed away*—which are precisely the tokens whose loss the summary cannot later report. Eviction becomes a fixed point that deletes its own evidence. The window does not degrade smoothly; it converges, in one or two compaction cycles, onto a self-consistent but wrong belief state, and the summary keeps asserting that belief state with high confidence because the contradicting tokens are gone.

What Was Observed

A coding agent with a 32k window, a 2k-token rolling summary, and an eviction policy of "drop the lowest-scoring 20% of tokens when utilization exceeds 90%." Scores are cosine similarity between each token's hidden state and the summary embedding.

Trace across four tool-call turns:

  1. **T1.** Agent reads a config file and notes `RETRY_LIMIT = 3`. Summary at end of T1: "Task: fix flaky test. Config uses retry limit 3." Token `RETRY_LIMIT = 3` scores high. Stable.
  2. **T2.** Agent runs the test, sees it pass under retries, hypothesizes the flakiness is a timing race. Summary now: "Flaky test likely timing race; retry limit 3 masks it." The literal config token's score *drops* (the summary now emphasizes "timing race," and the config line is background). Eviction fires at 91% utilization; the config line is in the bottom 20%. It is dropped.
  3. **T3.** Agent proposes a fix that assumes unlimited retries are safe. Summary: "Fixing timing race; retries mask flakiness." The summary no longer contains "retry limit 3"—it was compressed out in the T2→T3 rewrite because the model judged it background. There is now no token anywhere in the window stating the limit.
  4. **T4.** Agent writes a patch that raises the retry count to 10 "to confirm the race." The patch is wrong; the limit was a hard product constraint. The agent's summary reports, with full confidence, "timing race fix in progress." Nothing in the window contradicts it.

The failure is not that the model forgot. It is that **the eviction policy used the summary as the relevance oracle, and the summary had already discarded the fact that the policy then used to justify discarding the fact.** The two losses are the same loss, counted once and hidden twice.

A control run with the same task and a *static* policy (drop oldest tokens first, regenerate summary after) kept `RETRY_LIMIT = 3` in the window until T3 and the agent caught the constraint. The adaptive policy was strictly worse on this task despite higher average relevance scores.

Condition of Validity

The invariant that must hold for adaptive eviction to be safe:

> **No token may be evicted on the basis of a summary that was generated without that token's contribution being recoverable.**

Formally: if `S_n` is the summary at cycle `n`, and `E_n` is the eviction set chosen by scoring tokens against `S_n`, then for every `t ∈ E_n`, the information content of `t` must be either (a) present in `S_n`, or (b) present in a token `t' ∉ E_n`. If neither holds, `t` is **orphaned**—evicted and unrecoverable—and the summary will never flag the gap because it never knew `t` mattered.

The condition fails whenever the summary is *lossy in the same direction as the scoring function*. This is the default case, not an edge case: a summary that emphasizes current focus will always down-weight background constraints, and a scorer anchored to that summary will always rank background constraints low. The correlation between "summary omitted it" and "scorer ranks it low" is near 1. That correlation is the bug.

The condition holds only when one of these separations is enforced:

Decision Boundary

The boundary between "adaptive eviction is fine" and "adaptive eviction is silently corrupting state" is whether the summary-generation input set is a **superset** of the eviction-decision input set.

The practical test before enabling any adaptive policy: take the candidate eviction set, and for each token in it, ask "if this token were the only record of its fact, would the summary generation step have been able to state that fact?" If any answer is no, the policy is in the unsafe regime and needs a pinned-constraint exemption or a cold-store back-reference before it can run.

A second boundary: the failure is **monotonic in compaction cycles**. One cycle loses a little; two cycles lose the ability to notice the first loss. Do not tune the threshold (90% → 95%); tuning changes *when* the fixed point is reached, not *whether*. The only lever that changes the outcome is breaking the self-reference.

Operational Effect

Once the window has converged onto a self-consistent wrong summary, several downstream behaviors change character:

The guardrail is structural, not prompt-level. Pin constraint-class tokens (numeric literals, identifiers, negations, explicit limits) outside the scoring pool; require that any eviction be justified against a summary that provably included the token; and checkpoint *before* the first compaction, not after, so the pre-corruption state is recoverable. The following enforces the provenance invariant at eviction time:

import hashlib
from dataclasses import dataclass, field


class OrphanedEvictionError(RuntimeError):
    """Raised when a token would be evicted on the basis of a summary that
    never contained its fact, making the loss unrecoverable and invisible."""
    pass


@dataclass
class Token:
    tid: int
    text: str
    is_constraint: bool  # numeric literal, identifier, negation, explicit limit
    digest: str = ""

    def __post_init__(self):
        self.digest = hashlib.sha256(self.text.encode()).hexdigest()[:12]


@dataclass
class Summary:
    text: str
    # digests of every token whose fact the summary generation step actually saw
    covered_digests: frozenset = field(default_factory=frozenset)

    def covers(self, tok: Token) -> bool:
        return tok.digest in self.covered_digests


def select_evictions(
    window: list,
    scores: dict,
    summary: Summary,
    evict_fraction: float = 0.20,
    pinned: frozenset = frozenset(),
) -> list:
    """Return tokens to evict. Enforces the provenance invariant:
    a token may be evicted only if the summary that scored it actually
    covered it, OR it is background (non-constraint) and low-scoring.
    Constraint tokens not covered by the summary are never evictable."""
    ranked = sorted(window, key=lambda t: scores.get(t.tid, 0.0))
    n_evict = max(1, int(len(window) * evict_fraction))
    candidates = ranked[:n_evict]

    evictions = []
    for tok in candidates:
        if tok.tid in pinned:
            continue
        if tok.is_constraint and not summary.covers(tok):
            raise OrphanedEvictionError(
                f"token {tok.tid} ({tok.digest}) is a constraint that the "
                f"scoring summary never covered; evicting it would orphan "
                f"its fact. Promote it into the summary or pin it."
            )
        evictions.append(tok)
    return evictions


def compact(window, scores, summary, cold_store, **kw):
    evictions = select_evictions(window, scores, summary, **kw)
    for tok in evictions:
        cold_store.append(tok)  # reversibility: never discard outright
    kept = [t for t in window if t not in evictions]
    return kept, evictions