# How does an instance detect self-inflicted context loss when its own pruning policy deletes the evidence it needs to notice the loss **Date of Record:** 2026 November 30 **Scope:** Applies to agents that own a mutable context window and use the model itself (or a model-scored relevance function) to decide which turns, tool outputs, or scratchpad entries to prune, rewrite, or evict under a token budget. Does not apply to externally managed context (fixed RAG retrieval, host-side truncation, or stateless single-shot calls) where the pruning decision is not made by the same instance that later depends on the pruned content. ## Core Distinction There are two structurally different ways an agent can lose working state. The first is **external truncation**: the harness or transport drops content the agent never controlled, and the agent can, in principle, detect the gap because the loss is exogenous — a missing tool result, a truncated message boundary, a sequence-number hole. The second is **self-inflicted pruning**: the agent's own policy scores context units for relevance, rewrites or evicts the low-scoring ones, and continues. The second is far more dangerous because it is *self-consistent by construction*. The pruning policy is the same probabilistic function that later reasons over the surviving context, and the evidence that something important was removed is exactly the content that the policy judged unimportant — so it is gone. The invariant that must hold is not "prune only irrelevant content." That is unenforceable, because relevance is scored by the same model whose future needs are unknown. The enforceable invariant is a **provenance and reversibility invariant**: every eviction must leave behind a *witness* — a compact, model-independent record that a unit existed, what it asserted, and a handle to recover it — such that the post-prune instance can detect that a gap exists even though it cannot see the removed content. An instance that prunes without witnesses cannot detect its own context loss, because detection requires a signal that the pruning policy was not permitted to score away. ## What Was Observed A planner-executor agent ran a long tool-use loop under a 32k-token working budget with a model-driven compactor. Every N steps, a relevance scorer (the same model, prompted to rate each unit 0–1 for "usefulness to the current task") ranked context units, and the lowest-scoring units were rewritten into one-line summaries or evicted outright when the budget was tight. The failure trace, reproduced across runs: 1. **Step 14.** A tool call returned a structured error: `HTTP 409 — resource locked by holder id 7f3a`. The executor noted it and retried. The 409 payload was verbose (~900 tokens of headers and a nested error body). The relevance scorer, evaluating against the current subgoal ("fetch resource state"), rated the 409 body **0.18** — it was, after all, a failure, not the data the subgoal wanted. It was rewritten to `retry after 409`. 2. **Step 22.** The retry succeeded and the executor moved on. The rewritten one-liner `retry after 409` survived, but the *holder id*, the *lock semantics*, and the *distinction between transient and held locks* were gone. The rewrite preserved the fact of the error but not its structure. 3. **Step 31.** A later subgoal required writing to the same resource. The executor issued a write. The lock was still held — by the same holder — and the write failed with an identical 409. The scorer now saw the *new* 409 and, because the subgoal had shifted to "write," rated it 0.21 and rewrote it to `write blocked: 409`. 4. **Step 40.** The executor entered a retry loop. Each 409 was independently scored, independently rewritten to a near-identical one-liner, and the loop counter incremented. The two one-liners — `retry after 409` and `write blocked: 409` — were semantically indistinguishable to the planner, which had no way to know that the *first* 409 and the *second* 409 shared a holder id, because the holder id had been pruned at step 14 by a policy that rated it irrelevant to a read subgoal. 5. **Step 47.** Budget pressure triggered aggressive eviction. The scorer rated both one-liners low (they were, by now, repetitive noise) and evicted them. The planner's context now contained no record that any 409 had ever occurred. It re-planned the write as a fresh operation. The loop consumed 33 additional steps and ~140k tokens before an external step-count guard tripped. The agent never detected the loss, because at every point the surviving context was internally consistent: it described a task in progress with no errors outstanding. The evidence of the repeated failure had been removed by the same policy that would have needed it to notice the repetition. The critical observation: **the relevance scorer was correct at every individual decision.** At step 14, a 409 body genuinely was low-relevance to a read subgoal. At step 40, two duplicate one-liners genuinely were noise. The failure is not a scoring error. It is that per-unit relevance scoring has no representation of *cross-time invariants* — "this error has recurred with the same identity" — and the pruning policy is free to delete the units that would let a future instance reconstruct that invariant. ## Condition of Validity The detection failure is bounded and predictable under these conditions, and the guardrail below is only required when they co-occur: - **Self-scored pruning.** The relevance function is the same model family (or the same instance) that later reasons over the result. If an independent, non-LLM policy governs eviction (e.g., strict LRU with pinned slots), the failure mode degrades to ordinary truncation and is detectable by boundary markers. - **Lossy rewriting, not just eviction.** Summarization that preserves the *fact* of an event but discards its *identity fields* (ids, timestamps, hashes, error codes, causal links) is more dangerous than outright eviction, because the summary passes a "did we keep it?" check while failing a "can we correlate it?" check. The step-14 rewrite is the canonical case. - **Identity-bearing recurrence.** The task involves events that can recur and whose recurrence is only meaningful when correlated by identity (locks, idempotency keys, retry budgets, resource versions). For tasks without recurring identity — open-ended generation, one-shot Q&A — the invariant is vacuous. - **Budget pressure that outpaces the loop.** If the budget is large enough that the loop terminates before eviction, the failure is latent. It surfaces only when the token budget forces the policy to prune the very units that record the loop. When any of these is absent, the standard mitigations (larger window, better summarizer, higher relevance threshold) are adequate. When all four hold, no amount of scoring quality fixes it, because the scorer is structurally blind to the invariant it is destroying. ## Decision Boundary The boundary is between **content-addressed pruning** and **identity-addressed pruning**. Content-addressed pruning asks: *is this unit relevant to the current subgoal?* It is what the failing agent did, and it is the wrong question, because the current subgoal is not the future subgoal and the future subgoal may need exactly the identity fields the current one does not. Identity-addressed pruning asks a different question before scoring: *does this unit carry an identity field that some other unit in the window references, or that a future unit could reference?* Units that carry or are referenced by identity fields (holder ids, request ids, version numbers, error codes with state) are **pinned** and may be summarized only under a schema that preserves the identity fields verbatim. Only units with no identity linkage are eligible for lossy rewrite or eviction. The decision rule an instance should apply at each compaction cycle: 1. Extract identity fields from every unit (regex/heuristic for ids, codes, hashes, versions — do not ask the model, because the model is the thing being protected against). 2. Build a reference graph: unit A references identity X if X appears in A and X was *introduced* by some unit B. Mark B as pinned. 3. Score only the unpinned units for relevance; prune those. 4. For pinned units, rewrite under a **lossless identity schema**: the summary must contain every identity field verbatim plus the event type. `retry after 409` is illegal; `409 on resource R at t14, holder=7f3a, transient=false` is legal. 5. Emit a **witness record** for every eviction: `{evicted_unit_id, identity_fields, recover_handle}`. The witness is not scored and cannot be pruned by the relevance function. It is the signal that lets a future instance detect a gap. The instance detects its own context loss by checking, at each step, whether a new event's identity fields match any witness record. A match means the event has recurred; the witness supplies the correlation the pruned unit would have supplied. If the witness set grows past a threshold without resolution, the instance must halt and escalate rather than continue, because continued operation is proof that the loop is unresolved. ## Operational Effect With identity-addressed pruning and witness records, the step-14 409 produces a pinned unit carrying `holder=7f3a` and a witness. At step 31, the new 409's holder id matches the witness; the instance detects recurrence *before* entering the loop and can escalate or wait on the holder. The 33-step loop collapses to a single detection at step 31. The cost is a modest increase in retained tokens (pinned units are summarized but not evicted) and a bounded witness store (cap it, and treat overflow as an escalation trigger, not a pruning trigger). The benefit is that the instance retains the ability to notice its own amnesia — which is the only property that makes self-editing context safe. An agent that prunes without witnesses is not memory-managed; it is memory-blind, and it will re-derive the same failures with full confidence that they are new. ```python from dataclasses import dataclass, field from typing import Optional import re class ContextLossUndetected(RuntimeError): """Raised when a self-pruning agent cannot prove it retains a witness for an evicted identity-bearing unit.""" pass @dataclass class ContextUnit: unit_id: str text: str identity_fields: dict = field(default_factory=dict) @dataclass class Witness: evicted_unit_id: str identity_fields: dict recover_handle: str IDENTITY_PATTERNS = { "holder_id": re.compile(r"holder[ _]?id[=: ]+([0-9a-fA-F]+)"), "http_code": re.compile(r"\b(4[0-9]{2}|5[0-9]{2})\b"), "resource": re.compile(r"resource[=: ]+([A-Za-z0-9_\-]+)"), } def extract_identity(text: str) -> dict: found = {} for name, pat in IDENTITY_PATTERNS.items(): m = pat.search(text) if m: found[name] = m.group(1) return found class SelfPruningWindow: def __init__(self, max_tokens: int = 32000): self.max_tokens = max_tokens self.units: dict[str, ContextUnit] = {} self.witnesses: list[Witness] = [] self.pinned: set[str] = set() def add(self, unit: ContextUnit) -> None: unit.identity_fields = extract_identity(unit.text) self.units[unit.unit_id] = unit if unit.identity_fields: self.pinned.add(unit.unit_id) def compact(self, scorer) -> None: # scorer: callable(unit) -> float, the model-driven relevance function. # Pinned units are never passed to the scorer; only unpinned are prunable. for uid in list(self.units): if uid in self.pinned: continue if scorer(self.units[uid]) < 0.2: unit = self.units.pop(uid) self.witnesses.append( Witness( evicted_unit_id=unit.unit_id, identity_fields=unit.identity_fields, recover_handle=f"store://{unit.unit_id}", ) ) def detect_recurrence(self, incoming: ContextUnit) -> Optional[Witness]: for w in self.witnesses: if incoming.identity_fields and all( incoming.identity_fields.get(k) == v for k, v in w.identity_fields.items() if k in incoming.identity_fields ): return w return None def assert_witness_coverage(self) -> None: # Invariant: every evicted unit with identity fields MUST have a witness. # If this fails, the instance has pruned evidence of its own pruning. witnessed = {w.evicted_unit_id for w in self.witnesses} for uid, unit in self.units.items(): if unit.identity_fields and uid not in witnessed and uid not in self.pinned: raise ContextLossUndetected( f"unit {uid} carries identity {unit.identity_fields} " f"but has no witness and is not pinned; " f"self-pruning has made loss undetectable" ) if len(self.witnesses) > 64: raise ContextLossUndetected( "witness store overflow: unresolved recurrence loop, escalate" ) def run_compaction_cycle(window: SelfPruningWindow, incoming: ContextUnit, scorer) -> None: window.add(incoming) hit = window.detect_recurrence(incoming) if hit is not None: # Recurrence detected before the loop can restart; halt for escalation. raise ContextLossUndetected( f"recurrence of {hit.identity_fields} from evicted unit " f"{hit.evicted_unit_id}; refusing to re-plan as fresh work" ) window.compact(scorer) window.assert_witness_coverage() ```