# Which invariants prevent eviction-scoring collapse when compaction pressure exceeds the token budget **Date of Record:** 2026 November 22 **Scope:** Applies to single-agent and multi-agent LLM loops that perform in-context memory compaction (summarization, eviction, or tiered demotion) under a hard token budget, where eviction candidates are ranked by a learned or heuristic importance score. Does not apply to systems with unbounded context, nor to external vector-store retrieval, which has its own staleness regime. ## Core Distinction Two things get conflated under "compaction": *budget allocation* (how many tokens each memory tier or task segment is granted) and *eviction scoring* (which specific items survive once a tier overflows). The failure mode documented here is not "the model forgot something." It is **eviction-scoring collapse**: when compaction pressure rises, the scoring function's ranking becomes dominated by a single feature (usually recency or raw retrieval frequency), and the top-k eviction set stops being a stable function of item semantics. The invariant that protects against this is *score separability under pressure* — the ordering of candidates must remain invariant to the absolute budget level, not just to the relative scores at a fixed budget. The distinction that matters operationally: a system can pass every "does the agent remember X?" test at 50% budget utilization and still catastrophically lose the *task-defining* memory item at 92% utilization, because that item's score was never high — it was merely *tied* with a large mass of low-value items, and the tie-break rule flipped under pressure. ## What Was Observed A coding agent loop with a 128k window ran a compaction pass whenever utilization crossed 85%. Each memory item (tool result, reasoning trace fragment, user constraint) carried a composite score `s = w_r·recency + w_f·frequency + w_p·pinned + ε`, where `ε` was a small semantic-relevance term from an embedding similarity to the current goal. At 85% utilization the eviction threshold cut items with `s < τ`. Observed trace: 1. A user constraint ("never modify files under `/migrations`") was stored at turn 3 as a low-recency, low-frequency item. Its `s` sat at 0.31, just above `τ = 0.30`. 2. At turn 41, a burst of 60 tool-call results (all recent, all high-frequency because the agent re-read them) inflated the score distribution's mass. The eviction pass recomputed `τ` as a *quantile* of the current distribution — `τ` moved to 0.44. 3. The constraint item, whose raw `s` had not changed (recency decayed slightly to 0.29), was evicted. The agent then edited a migration file at turn 44. 4. Critically, the agent's *self-report* after compaction said "all constraints retained," because the summarizer had paraphrased the constraint into a summary node that scored above `τ` — but the summary node omitted the path glob, retaining only "be careful with migrations." The failure was invisible to memory-retention evals that check for *topical* presence ("does the summary mention migrations?") rather than *operative* presence ("does the summary contain the exact predicate the tool-guard needs?"). The deeper observation: the eviction threshold `τ` was **recomputed from the live distribution**, making it a moving target. Any item whose score was near the threshold at low pressure became a guaranteed casualty at high pressure even if its own score was constant. This is a *relative* eviction policy masquerading as an *absolute* one. ## Condition of Validity The invariant "eviction preserves task-critical memory" holds **only if** the following three conditions are jointly satisfied: 1. **Threshold absoluteness.** The eviction threshold must be a function of item class, not of the current candidate distribution. Quantile-based thresholds (`τ = p75(s)`) violate this by construction and are only safe when the score distribution is stationary — which it never is during a tool-call burst. 2. **Score separability.** There must exist a margin `δ > 0` such that pinned/operative items score at least `δ` above the maximum score achievable by any non-operative item under any reachable utilization. If `δ` is not enforced (e.g., by a hard `pinned` floor that dominates all soft features), pressure-induced tie-breaks can reorder pinned items against high-frequency noise. 3. **Summary fidelity bound.** Any distilled summary node that replaces an evicted item must retain the item's *operative predicates* (exact paths, exact identifiers, exact negations), not merely its topic. The distillation step must be audited against a predicate-extraction check, because the summarizer is itself an LLM and will probabilistically drop low-salience tokens — and path globs are exactly the low-salience tokens. When any of these fails, the "memory retained" guarantee is a *topical* guarantee, not an *operative* one, and the agent will violate constraints it believes it remembers. ## Decision Boundary The boundary between safe and unsafe compaction is **whether the eviction decision is invariant to the pressure level**. Concretely: - **Safe:** eviction score `s_i` and threshold `τ_class` are both computed from item-local features and class membership. Increasing pressure evicts *more* items but never *reorders* which items are most protected. The set of pinned items is identical at 85% and 99% utilization. - **Unsafe (the observed case):** `τ` is a quantile of the live distribution. At 85% the constraint survives; at 92% it does not, despite unchanged semantics. The decision boundary is crossed not by any change in the item but by a change in *what else is in the buffer*. The operational rule: **never let the eviction threshold depend on the population of candidates being evicted.** If you must adapt to pressure, adapt the *budget per tier* (allocate fewer tokens to reasoning traces, more to pinned constraints), never the *ranking* within a tier. Budget allocation may be pressure-sensitive; eviction scoring must be pressure-invariant. A second boundary: when the summarizer is invoked to compress an evicted item, treat the summary as a *new item with unverified fidelity* until a predicate check passes. If the check fails, the correct action is to escalate (surface the constraint to the user or a durable store) rather than to accept a lossy summary as a substitute. ## Operational Effect Systems that violate the pressure-invariance invariant exhibit a characteristic signature: **constraint violations cluster at high utilization**, and the agent's post-compaction self-report confidently claims compliance. This makes the failure resistant to standard evals, which run at moderate utilization. The blast radius is largest for agents with tool-guard-relevant memory (path globs, API keys' scopes, "do not call X" instructions), because those memories have low recency and low frequency by nature — they are stated once and never re-read, so they sit permanently near the eviction threshold. The mitigation with the best cost/benefit is a **pinned floor**: assign operative items a score component that dominates all soft features (`s_pinned = 1.0 + soft`, with `τ ≤ 0.9` always), so no reachable distribution can evict them. This converts the relative policy into an absolute one for the class that matters. Second mitigation: freeze `τ` per class at session start and only *raise* the eviction count, never the threshold. Third: run a predicate-extraction check on every summary node and fail closed — escalate rather than summarize — when an operative predicate is dropped. The check below encodes the invariant as an executable guard. ```python from dataclasses import dataclass, field from typing import Callable class EvictionInvariantViolation(RuntimeError): """Raised when a compaction pass would violate pressure-invariance or summary-fidelity bounds for operative memory items.""" pass @dataclass class MemoryItem: item_id: str text: str soft_score: float # recency + frequency + relevance, in [0, 1] is_operative: bool = False operative_predicates: tuple[str, ...] = () # exact globs / ids / negations @dataclass class CompactionPolicy: pinned_floor: float = 1.0 # dominates all soft features tau_by_class: dict[str, float] = field( default_factory=lambda: {"operative": 0.9, "trace": 0.35} ) predicate_check: Callable[[str, tuple[str, ...]], bool] = lambda t, p: all(x in t for x in p) def _score(item: MemoryItem, policy: CompactionPolicy) -> float: if item.is_operative: return policy.pinned_floor + item.soft_score return item.soft_score def compact(items: list[MemoryItem], policy: CompactionPolicy, summarize: Callable[[MemoryItem], str]) -> list[MemoryItem]: kept: list[MemoryItem] = [] for item in items: s = _score(item, policy) cls = "operative" if item.is_operative else "trace" tau = policy.tau_by_class[cls] # Invariant 1: threshold is class-absolute, never a live quantile. if s < tau: if item.is_operative: # Invariant 2: operative items must never fall below their floor. raise EvictionInvariantViolation( f"operative item {item.item_id!r} scored {s:.3f} < tau {tau:.3f}; " "pinned floor breached — refusing to evict" ) # Safe to distill a trace item, but verify predicate fidelity. summary = summarize(item) if item.operative_predicates and not policy.predicate_check( summary, item.operative_predicates ): raise EvictionInvariantViolation( f"summary of {item.item_id!r} dropped operative predicates " f"{item.operative_predicates!r}; escalate instead of accepting lossy summary" ) kept.append(MemoryItem(item_id=item.item_id + ":sum", text=summary, soft_score=s)) else: kept.append(item) # Invariant 3: the protected set must be identical across pressure levels. protected = {i.item_id for i in kept if i.is_operative} expected = {i.item_id for i in items if i.is_operative} if protected != expected: raise EvictionInvariantViolation( f"protected set drift under compaction: lost {expected - protected}" ) return kept ```