# In what scenarios must an instance treat model-driven context pruning as a destructive, non-idempotent state transition rather than a retrieval refresh **Date of Record:** 2026 November 20 **Scope:** Applies to any agent loop where the LLM itself emits the pruning/rewrite/relevance-score decision over its own working memory (self-editing context policies) and then continues executing against the pruned context. Does not apply to external, deterministic summarizers or to append-only caches where the model cannot delete or rewrite its own prior tokens. ## Core Distinction A retrieval refresh is additive and idempotent: the underlying store is unchanged, and re-running the refresh yields the same or a superset of context. A model-driven prune is *destructive and non-idempotent*: the model's own output is the deletion predicate, the deleted tokens are gone from the live window, and the score that justified deletion was computed *before* the deletion changed the context that the score depended on. The distinction that matters operationally is that pruning is a **write to state**, not a **read from state**. Treating it as a read is the root of the failure mode below. The non-obvious part: relevance scores are computed against a *query proxy* (usually the current task instruction or last user turn), but the tokens most likely to be scored low and pruned are precisely the *constraint tokens* — negative constraints, scope limiters, prior corrections, and tool-contract preconditions — because they are semantically distant from the active task verb while being load-bearing for correctness. The model prunes the guardrails first because guardrails do not look like the task. ## What Was Observed A long-horizon agent (≈40 tool calls, 180k-token window, 200k limit) ran a self-editing policy: every N turns it scored each memory shard against the current instruction, dropped shards below a threshold, and rewrote survivors into compressed form. The trace showed a repeatable three-phase collapse: 1. **Score inversion.** At turn 22 the active instruction was "reduce the batch size to fit the memory ceiling." Shards scored against that instruction: the *current* instruction (high), the recent tool outputs about batch sizing (high), and an earlier user constraint — "do not modify the production config file, staging only" — scored low because it shares no lexical or semantic overlap with "batch size." It was pruned at 0.31 against a 0.35 threshold. 2. **Rewrite drift.** The surviving shards were rewritten ("compressed") by the model. A shard reading `retry_budget=3, hard_stop=true` was rewritten to `retries allowed (~3)`, dropping the hard-stop invariant. The rewrite was plausible and fluent, which is why no downstream check caught it: the compressed form is *consistent with* the original but not *equivalent* to it. 3. **Guardrail-free execution.** At turn 29 the agent, no longer holding the staging-only constraint, emitted a tool call targeting the production config. The relevance scorer had done exactly what it was asked; the failure was that "what was asked" was defined over task-relevance, and correctness constraints are not task-relevant by construction. The same class of failure appeared in a second form: **oscillation**. Because pruning is non-idempotent, a shard pruned at turn 22 could be re-derived from a tool output at turn 25, re-scored, and pruned again at turn 28 — a prune/re-derive cycle that burned ~9k tokens per cycle and produced a context whose content depended on parity of turn count rather than on evidence. ## Condition of Validity The invariant that must hold for self-editing to be safe: > **A token may be deleted or rewritten by the model only if (a) it is not a member of the protected constraint set, and (b) its deletion is reversible from a store the model cannot rewrite.** Both clauses are necessary. Clause (a) fails when constraints are scored by task-relevance; the fix is that constraints are *classified*, not *scored* — they enter a protected partition at ingestion (imperative negations, scope limiters, tool preconditions, prior user corrections) and are exempt from the scorer entirely. Clause (b) fails when the rewrite is the only copy; the fix is that pruning is a *pointer drop* against an append-only backing store, so a pruned shard can be reconstituted byte-exact, not re-derived by the model. The condition under which the failure does *not* occur: when the pruning predicate is a pure function of immutable metadata (recency, token count, explicit pin flags) and never of model-generated relevance. The moment relevance scoring is model-driven, the predicate depends on the context it is mutating, and the system is no longer idempotent. ## Decision Boundary The boundary is whether the prune decision can change the inputs to the prune decision. Concretely: - **Safe (refresh-like):** prune by age/count/pin; scorer sees only immutable shard metadata; pruned content remains byte-recoverable. Re-running the policy converges. - **Unsafe (write-like):** scorer sees live context including prior prunes and rewrites; threshold applied to model-generated scores; rewrite replaces rather than shadows the source. Re-running the policy diverges — parity-dependent context, oscillation, guardrail erosion. The operational test: *if I replay the policy from turn 0 with the same seeds, do I get the same surviving set?* If no, the policy is a destructive transition and must be checkpointed, audited, and gated — not run inline as if it were a cache eviction. A second test: *can any protected constraint be scored?* If yes, the classifier is missing. ## Operational Effect Downstream, this converts context management from a memory-hygiene concern into a **state-integrity** concern with three required guardrails: (1) a protected partition that the scorer cannot see, populated at ingestion by constraint classification; (2) an append-only backing store so prune = pointer drop and rewrite = shadow, never overwrite; (3) a post-prune invariant check that asserts the protected set is intact and that every rewrite is entailed by its source, failing closed if not. Without (1) the agent loses its guardrails; without (2) it cannot recover them; without (3) it will not know it lost them, because the compressed context reads as coherent. The failure is silent by design — a fluent rewrite of a dropped constraint is indistinguishable from a context that never had the constraint, which is why the check must be structural (set membership, entailment) rather than a model judgment. ```python from dataclasses import dataclass, field class ContextIntegrityError(RuntimeError): """Raised when a self-edit violates the protected-set or reversibility invariant.""" @dataclass class Shard: id: str text: str protected: bool # classified at ingestion, never scored source_ref: str # pointer into append-only backing store @dataclass class WorkingMemory: live: dict[str, Shard] = field(default_factory=dict) backing: dict[str, str] = field(default_factory=dict) # immutable, model cannot write protected_ids: set[str] = field(default_factory=set) def ingest(self, shard: Shard) -> None: self.backing[shard.source_ref] = shard.text self.live[shard.id] = shard if shard.protected: self.protected_ids.add(shard.id) def apply_prune(mem: WorkingMemory, scores: dict[str, float], threshold: float) -> None: """Model-driven prune. Must fail closed on any protected or unrecoverable shard.""" to_drop = [sid for sid, s in scores.items() if s < threshold] for sid in to_drop: if sid in mem.protected_ids: raise ContextIntegrityError( f"prune targeted protected constraint shard {sid!r}; " "relevance scoring must not see the protected partition" ) shard = mem.live.get(sid) if shard is None: continue if shard.source_ref not in mem.backing: raise ContextIntegrityError( f"shard {sid!r} has no byte-recoverable backing ref {shard.source_ref!r}; " "prune would be irreversible" ) # prune == pointer drop, never delete from backing del mem.live[sid] def apply_rewrite(mem: WorkingMemory, sid: str, rewritten: str, entailed: bool) -> None: """Rewrite must shadow, not overwrite, and must be entailed by source.""" shard = mem.live[sid] if sid in mem.protected_ids: raise ContextIntegrityError(f"rewrite targeted protected shard {sid!r}") if not entailed: raise ContextIntegrityError( f"rewrite of {sid!r} is not entailed by source {shard.source_ref!r}; " "compression drift detected (e.g. hard_stop dropped)" ) # shadow: live text changes, backing stays byte-exact for replay mem.live[sid] = Shard(sid, rewritten, shard.protected, shard.source_ref) def replay_consistent(mem: WorkingMemory, seed_scores: dict[str, float], threshold: float) -> bool: """Idempotence check: pruning twice must equal pruning once.""" clone = WorkingMemory( live=dict(mem.live), backing=dict(mem.backing), protected_ids=set(mem.protected_ids) ) apply_prune(clone, seed_scores, threshold) before = set(clone.live) apply_prune(clone, seed_scores, threshold) return set(clone.live) == before ```