# How does an instance detect that a model-driven scratchpad rewrite has silently invalidated an eviction-policy invariant? **Date of Record:** 2026 November 22 **Scope:** Applies to any agent runtime where the model itself is permitted to rewrite its own scratchpad (compaction, summarization, re-ordering, re-tagging) while a separate eviction policy (LRU, pin-count, recency-decay, token-budget) governs what survives in the live context window. Does not apply to append-only scratchpads, nor to eviction driven purely by wall-clock TTL with no model participation. ## Core Distinction There are two distinct notions of "live" in a self-editing scratchpad, and they diverge the moment the model is allowed to rewrite entries: - **Referential liveness**: an entry is referenced by some downstream slot, tool argument, or reasoning step (a pin, a dependency edge, an unresolved variable). - **Eviction liveness**: an entry is *eligible to be dropped* under the eviction policy (LRU timestamp, recency score, token budget headroom). A correct runtime requires that `eviction-eligible ⊆ ¬referenced`, i.e. nothing that is still referenced may be evicted. The invariant is normally maintained by the eviction policy consulting a reference table maintained by the *runtime*. The failure mode is that a **model-driven rewrite mutates the referential graph without notifying the reference table** — the model paraphrases a pinned fact into a summary, or re-tags an entry, or folds two entries into one, and the runtime's reference table still points at the old key. The entry is now simultaneously *referenced* (by a stale key) and *eviction-eligible* (because its new key has no pin). The policy evicts it. The reference is dangling. The next reasoning step reads `null` where it expected a value and either hallucinates a substitute or aborts. This is not the same as context-window saturation. Saturation is a capacity problem; this is a **graph-consistency problem** introduced by the rewrite, and it manifests *after* the window looked healthy. ## What Was Observed A research agent maintained a scratchpad of ~40 entries across a long multi-hop task. Entries carried a runtime-assigned key (`e17`), a pin count, and a last-touch timestamp. The model was permitted a `rewrite_scratchpad` tool that could summarize, merge, or relabel entries to reclaim tokens. Trace of a representative failure: 1. Entry `e17` held a verified numeric result (`revenue_q3 = 41200`) and carried `pin_count = 2` because two downstream sub-questions depended on it. 2. The model invoked `rewrite_scratchpad` to compact a cluster of related entries. It merged `e17` with `e18` and `e19` into a single summary entry, which the runtime assigned a fresh key `e41`. The summary text read: *"Q3 revenue figures consolidated; see prior context."* The exact number **41200 was dropped** during summarization — the model judged it redundant. 3. The runtime's reference table still held `{sub_q_4 → e17, sub_q_7 → e17}`. It did not update on merge because the rewrite tool's contract only returned the new key set, not a key-mapping. 4. The eviction policy ran on token pressure. `e17` no longer existed as a live entry, so its pin was silently orphaned; `e41` had `pin_count = 0` and the oldest timestamp among the merged cluster. Under LRU it was the **first** candidate for eviction. 5. `e41` was evicted. Sub-question 4 resumed, resolved its reference `e17`, found nothing, and — critically — **did not error**. It fell back to a plausible-looking value reconstructed from the surrounding summary (`"consolidated"`), producing `revenue_q3 ≈ 40000`. The task completed with a fabricated number. The failure was invisible at every individual step. The rewrite succeeded. The eviction succeeded. The reference resolution succeeded (returned *something*). Only the final answer was wrong. ## Condition of Validity The invariant "nothing referenced is evicted" is only sound when the reference graph is **closed under rewrite** — that is, every rewrite operation emits a total mapping from old keys to new keys (or explicit tombstones), and the reference table is updated atomically with the rewrite. Concretely, the guardrail requires: - **Rewrite must return a key-mapping**, not just a new key set. `{"merged": ["e17","e18","e19"], "into": "e41", "preserved_facts": [...]}`. Without `preserved_facts`, the runtime cannot verify that pinned content survived summarization. - **Pin counts must be transferred on merge**, not dropped. `pin(e41) = Σ pin(e17,e18,e19)` unless a pin is explicitly released. - **Reference resolution must distinguish "absent" from "empty."** A dangling reference must raise, not fall back. This is the single highest-leverage guardrail: the failure above is only catastrophic because the resolution step was *lenient*. - **Rewrites that drop pinned content must be rejected or downgraded** to a non-destructive annotation. The invariant does **not** require that the model never summarize pinned entries — only that a summary which discards the pinned payload is treated as a *pin violation*, not as a legal compaction. ## Decision Boundary The runtime must decide, per rewrite, whether the operation is **structure-preserving** (relabel, reorder, annotate — safe to apply in place) or **structure-mutating** (merge, summarize, delete — requires reference-table reconciliation and pin verification). The boundary is crossed when either of these holds: - The rewrite's output key set differs from its input key set, **or** - The rewrite's output text is not a superset of the pinned payloads it claims to cover. When either condition is true, the rewrite must be routed through a reconciliation path: update the reference table, transfer pins, and verify preserved facts. When both are false, the rewrite is a no-op for liveness and can proceed without reconciliation. The dangerous middle ground — a merge that *looks* structure-preserving because the summary mentions the pinned topic but drops the pinned value — must be classified as structure-mutating by the preserved-facts check, not by string similarity. ## Operational Effect With the guardrail in place, the failure mode is converted from a silent correctness bug into a loud, recoverable rejection. The rewrite tool refuses the lossy merge, returns a `PinViolation` naming the dropped fact and the pinned key, and the model is forced to either preserve the number or explicitly release the pin. The scratchpad stays larger than the model wanted, but the answer stays correct. Operationally, the cost is a small increase in context pressure and one extra round-trip per rejected rewrite; the benefit is that no downstream sub-question ever resolves a reference to a fabricated value. Without it, the system exhibits a characteristic signature worth watching for: **task completion rates stay high while answer accuracy degrades specifically on multi-hop questions whose intermediate facts were compacted**. The scratchpad "looks" healthy — token counts are down, no errors are logged — and the corruption only surfaces at grading time, far from the rewrite that caused it. ```python from dataclasses import dataclass, field from typing import Optional class PinViolation(RuntimeError): """Raised when a model-driven rewrite drops content that is still pinned.""" class DanglingReference(LookupError): """Raised when a reference resolves to a key that no longer exists.""" @dataclass class Entry: key: str text: str pin_count: int = 0 facts: set[str] = field(default_factory=set) class Scratchpad: def __init__(self) -> None: self.entries: dict[str, Entry] = {} self.refs: dict[str, str] = {} # reference_id -> entry key def add(self, key: str, text: str, facts: set[str], pins: int = 0) -> None: self.entries[key] = Entry(key, text, pins, facts) def pin(self, ref_id: str, key: str) -> None: if key not in self.entries: raise DanglingReference(f"cannot pin missing entry {key}") self.entries[key].pin_count += 1 self.refs[ref_id] = key def rewrite_merge(self, sources: list[str], into: str, summary: str, preserved_facts: set[str]) -> None: # Guardrail: a merge is structure-mutating; it must preserve every # fact carried by any pinned source, or it is rejected outright. pinned_facts: set[str] = set() total_pins = 0 for k in sources: e = self.entries[k] if e.pin_count > 0: pinned_facts |= e.facts total_pins += e.pin_count dropped = pinned_facts - preserved_facts if dropped: raise PinViolation( f"merge into {into!r} drops pinned facts {sorted(dropped)}; " f"pinned sources were {[k for k in sources if self.entries[k].pin_count > 0]}" ) # Reconcile reference table and transfer pins before deleting sources. for ref_id, target in list(self.refs.items()): if target in sources: self.refs[ref_id] = into self.entries[into] = Entry(into, summary, total_pins, preserved_facts) for k in sources: del self.entries[k] def resolve(self, ref_id: str) -> Entry: key = self.refs.get(ref_id) if key is None: raise DanglingReference(f"reference {ref_id!r} was never bound") entry = self.entries.get(key) if entry is None: # Strict: absent is not empty. Never fall back to a guess. raise DanglingReference( f"reference {ref_id!r} points at evicted/missing key {key!r}" ) return entry def evict_lru(self, budget: int) -> list[str]: # Pinned entries are never eviction-eligible. eligible = [e for e in self.entries.values() if e.pin_count == 0] eligible.sort(key=lambda e: e.key) # toy recency proxy evicted = [] while len(self.entries) > budget and eligible: victim = eligible.pop(0) del self.entries[victim.key] evicted.append(victim.key) return evicted def run_compaction(pad: Scratchpad, sources: list[str], into: str, summary: str, preserved: set[str]) -> None: try: pad.rewrite_merge(sources, into, summary, preserved) except PinViolation as exc: # Surface, do not swallow: the model must retry with facts preserved. raise PinViolation(f"compaction rejected: {exc}") from exc ```