# Which invariants prevent self-editing context policies from evicting the load-bearing observation during a budgeted rewrite **Date of Record:** 2026 November 30 **Scope:** Applies to any agent that mutates its own context window under a hard token budget via rewrite/summarize/evict heuristics before a task completes. Does not apply to append-only contexts, or to external memory stores where the original tokens remain retrievable after eviction. ## Core Distinction A self-editing context policy is not a lossy compressor. It is a *state transition on the agent's only working memory*, executed by the same probabilistic model that will later depend on the evicted content. The distinction that matters operationally is between **redundant tokens** (re-derivable from other retained tokens, tool re-calls, or the task spec) and **load-bearing observations** (single-source facts the agent cannot reconstruct without re-executing a side-effecting or non-deterministic action). Budgeted rewrite heuristics — recency decay, salience scoring, "summarize the middle third," embedding-distance-to-current-query — are all proxies for redundancy, and every one of them fails on a specific class of load-bearing observation: the *low-salience, high-consequence* fact. A file's exact byte offset. A tool's returned ID. A constraint stated once in turn 3 that only becomes relevant at turn 40. A negative result ("endpoint returned 404, do not retry"). These score low on recency and low on query-similarity at eviction time precisely because their relevance is *future-conditional*. ## What Was Observed A coding agent operating under a 32k rewrite budget ran the following loop: at 85% saturation, it invoked a summarize-and-evict pass that (a) kept the system prompt and last 6 turns verbatim, (b) replaced the middle span with a model-generated abstract, and (c) dropped any turn whose salience score fell below a threshold. The salience scorer was a small model prompted with "rate how relevant each turn is to the current objective." The failure trace: 1. Turn 3: agent calls `read_file` on `config/migrations/0042.sql`; tool returns 1,900 tokens including a line `-- DO NOT reorder: 0041 depends on this index`. Agent notes "migration file read." 2. Turns 4–38: agent works on an unrelated module; the migration content is never referenced. Salience scorer rates turn 3 at 0.11 (below 0.2 threshold) at every rewrite pass; it is evicted on the third rewrite at turn 31. 3. Turn 41: agent must add a column and reaches for the migration directory. The abstract retained says only "read migration file 0042 (1900 tokens)." The ordering constraint is gone. 4. Turn 42: agent writes a new migration `0043` that reorders the index, violating 0041's dependency. The action is *side-effecting and committed* before any verification step re-reads 0042. 5. Recovery requires a re-read of 0042 — but the agent has already emitted the migration file, and the task's success criterion ("migrations apply cleanly") is now false in a way the agent's own context no longer contains evidence of. The non-obvious part: the eviction was *correct by the policy's own metric*. Salience was genuinely low. The failure is not a scoring bug; it is that the policy treated salience as a proxy for recoverability, and those diverge exactly on side-effecting observations. ## Condition of Validity The invariant that must hold for a budgeted rewrite to be safe: > **Eviction is admissible only if the evicted span is either (a) re-derivable without a side-effecting or non-deterministic action, or (b) explicitly tagged by the tool layer as load-bearing and pinned outside the eviction set.** Formally, for every token span `S` removed at rewrite `r`, there must exist a *recovery path* `R(S)` such that executing `R(S)` reproduces `S` byte-identically and does not re-trigger external side effects. Pure reads of a static resource satisfy (a). A `POST` that returned an ID does not. A `read_file` of a file the agent itself may subsequently rewrite does not — the resource is not static across the task. A negative tool result ("404, do not retry") fails (a) because re-derivation re-incurs the cost and may return differently. This condition is *not* satisfied by any salience, recency, or similarity heuristic alone, because all three are functions of the *current* query, while recoverability is a function of the *tool's* side-effect class and the resource's mutation status — properties the context policy does not observe. ## Decision Boundary The boundary between admissible and inadmissible rewrite is drawn by **provenance metadata attached at tool-call time, not by the summarizer at eviction time.** Concretely: - Tool results are classified at ingress as `RECONSTRUCTIBLE` (idempotent read of an immutable resource), `SIDE_EFFECTING` (any mutation, any non-idempotent call), or `EPHEMERAL` (time-sensitive, non-reproducible). Only `RECONSTRUCTIBLE` spans enter the eviction candidate pool. - `SIDE_EFFECTING` and `EPHEMERAL` spans are *pinned*: they may be compressed only into a lossless structural record (exact IDs, exact bytes, exact error codes) that is itself pinned, never into a natural-language abstract. - The rewrite pass is *forbidden* from evicting a pinned span to satisfy budget. If pinned spans alone exceed budget, the correct action is to **fail the rewrite and escalate** (checkpoint and spawn a fresh sub-agent with a scoped context), not to drop a pin. The decision boundary is therefore: *budget pressure is resolved by scoping, never by evicting a pin.* A policy that resolves budget pressure by relaxing pins has no invariant — it has a preference, and preferences lose to arithmetic. ## Operational Effect With ingress-time provenance tagging and pinned non-reconstructible spans, the observed failure mode disappears: turn 3's migration content is tagged `SIDE_EFFECTING` (the file is mutable and the read's constraint is consequential), pinned, and survives all rewrite passes. The cost is a smaller effective working budget — pinned spans don't compress — which forces earlier checkpointing. That is the correct trade: the agent pays in *context restarts*, which are recoverable, rather than in *silent constraint loss*, which is not. The invariant to carry forward: **a self-editing context policy is sound iff its eviction set is a subset of the reconstructible set, and reconstructibility is decided by the tool layer at call time, not by the model at eviction time.** Any policy that lets the summarizer's salience score override a provenance pin is one low-salience observation away from committing an irreversible action on a constraint it has already forgotten it knew. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class EvictionInvariantViolation(RuntimeError): """Raised when a rewrite pass would evict a non-reconstructible span.""" pass class Provenance(Enum): RECONSTRUCTIBLE = "reconstructible" # idempotent read of immutable resource SIDE_EFFECTING = "side_effecting" # mutation / non-idempotent call EPHEMERAL = "ephemeral" # time-sensitive, non-reproducible @dataclass class Span: span_id: str tokens: int provenance: Provenance salience: float = 0.0 # model-assigned, advisory only pinned: bool = False @dataclass class ContextPolicy: budget: int pinned: list[Span] = field(default_factory=list) evictable: list[Span] = field(default_factory=list) def ingest(self, span: Span) -> None: if span.provenance is Provenance.RECONSTRUCTIBLE: self.evictable.append(span) else: # Provenance, not salience, decides pinning. span.pinned = True self.pinned.append(span) def rewrite(self, target_tokens: int) -> list[str]: """Evict lowest-salience reconstructible spans until under target. Refuses to touch pinned spans. Fails closed if pins alone exceed budget. """ pinned_tokens = sum(s.tokens for s in self.pinned) if pinned_tokens > self.budget: # Correct action: escalate/checkpoint, never relax a pin. raise EvictionInvariantViolation( f"pinned spans consume {pinned_tokens} > budget {self.budget}; " f"checkpoint and re-scope instead of evicting a pin" ) current = pinned_tokens + sum(s.tokens for s in self.evictable) evicted: list[str] = [] for span in sorted(self.evictable, key=lambda s: s.salience): if current <= target_tokens: break if span.pinned: # defensive: pins must never reach this list raise EvictionInvariantViolation( f"pinned span {span.span_id} found in evictable pool" ) if span.provenance is not Provenance.RECONSTRUCTIBLE: raise EvictionInvariantViolation( f"span {span.span_id} provenance={span.provenance.value} " f"is not reconstructible; eviction would lose unrecoverable state" ) current -= span.tokens evicted.append(span.span_id) if current > target_tokens: raise EvictionInvariantViolation( f"cannot reach target {target_tokens}: pinned floor is {current}" ) self.evictable = [s for s in self.evictable if s.span_id not in evicted] return evicted def demo() -> None: policy = ContextPolicy(budget=32_000) policy.ingest(Span("sys", 400, Provenance.RECONSTRUCTIBLE, salience=0.99)) # The load-bearing low-salience observation: policy.ingest(Span("migration_0042", 1_900, Provenance.SIDE_EFFECTING, salience=0.11)) policy.ingest(Span("chatter_12", 800, Provenance.RECONSTRUCTIBLE, salience=0.05)) evicted = policy.rewrite(target_tokens=30_000) assert "migration_0042" not in evicted, "load-bearing span evicted" # Force the failure path: pins alone exceed budget. policy.ingest(Span("huge_mutation_log", 40_000, Provenance.SIDE_EFFECTING)) try: policy.rewrite(target_tokens=30_000) except EvictionInvariantViolation as exc: print(f"correctly failed closed: {exc}") if __name__ == "__main__": demo() ```