# In what scenarios must an instance refuse to self-rewrite its working context: the idempotence-loss trap in budget-driven context compaction **Date of Record:** 2026 November 21 **Scope:** Applies to single-instance agents that hold a mutable working context (scratchpad, message log, tool-result buffer) and are permitted to rewrite, summarize, or evict parts of it under an explicit token budget. Does not apply to append-only contexts where the agent cannot mutate prior turns, nor to external memory stores whose compaction is performed by a separate non-LLM service with deterministic rules. ## Core Distinction There are two structurally different reasons an agent rewrites its own context: **budget relief** (the context is approaching the window limit and must shrink) and **fidelity repair** (the context contains stale, contradictory, or superseded facts that must be reconciled). These are routinely conflated into a single "compact the context" operation, and that conflation is the failure locus. Budget relief is a *lossy compression* problem: the correct invariant is that the compressed context must remain a sufficient statistic for continuing the task. Fidelity repair is a *consistency* problem: the correct invariant is that the rewritten context must be a fixpoint under re-application — rewriting an already-rewritten context must produce no further semantic change. The non-obvious boundary is this: **a compaction pass that is safe under budget relief is frequently unsafe under fidelity repair, because the summarizer's own output becomes new input to the next summarization round, and the fidelity checks the agent applies to the *first* rewrite are not re-applied to the *second*.** When an agent self-edits repeatedly (a common pattern: compact at 80% budget, compact again at 80% of the new budget, and so on), each pass re-summarizes the prior summary. The composition of lossy passes is not the lossy pass of the composition. Idempotence is lost, and the agent cannot detect it because the loss is inside the very artifact it uses to reason about the loss. ## What Was Observed A tool-using agent executing a multi-step reconciliation task (compare 40 records against an external source, emit discrepancies) was configured with a self-editing policy: when the working context exceeded 70% of a 128k window, the agent would call its own `compact_context` routine, which summarized the message log into a "state digest" and replaced the log with the digest plus the last 4 raw turns. Trace of the failure: 1. **Pass 1 (turn 61, 71% budget).** The digest summarized 57 turns into 900 tokens. Among the elided detail: the exact field name `billing_zip_5` vs `billing_zip` — the agent had earlier discovered that the source used the 5-digit variant and the local records used the unqualified variant, and had recorded a *mapping rule*. The summarizer judged this "low-level detail" and dropped it, retaining only "records compared against source." 2. **Pass 2 (turn 103, 72% of the post-compaction budget).** The digest was re-summarized. The phrase "records compared against source" was retained; the (already-dropped) mapping rule could not be recovered. The agent now had a *confident but false* belief that field matching was trivial. 3. **Divergence.** From turn 104 onward the agent emitted 31 false "match" verdicts, because `billing_zip_5` vs `billing_zip` were compared as strings and the agent's comparison helper silently coerced missing suffixes. The agent's own verification step ("did I compare every record?") passed — every record *was* compared. The verification checked coverage, not fidelity. 4. **Detection failure.** The agent's self-check asked "is the digest consistent with the last 4 raw turns?" It was. The inconsistency lived in turns 5–60, which no longer existed in any form the agent could inspect. The digest was internally consistent and externally wrong. The critical observation: **the agent had no artifact against which to validate the digest, because the digest had replaced the only copy of the ground truth it summarized.** The rewrite was destructive and non-reversible within the instance. ## Condition of Validity A self-edit is valid only when all three of the following hold. If any fails, the instance must refuse the rewrite and escalate (spill to external store, request a larger budget, or halt). 1. **Externalized ground truth.** The pre-edit context must be persisted to a store the agent cannot overwrite during the same episode (append-only log, checkpoint with content hash). The digest must carry the hash of its source. If the agent cannot name the hash of the context it summarized, it has destroyed its own audit trail. 2. **Re-derivable fidelity claims.** Every factual claim in the digest that the agent will later *act on* must be re-derivable from a source that survives the edit — either a raw turn retained verbatim, or an external record. Claims that are only supported by elided turns are *orphaned claims* and must be tagged as such, not asserted. 3. **Idempotence check.** Applying the compaction routine to its own output must be a no-op at the semantic level. Operationally: `compact(compact(C))` must equal `compact(C)` under a task-relevant equivalence (same set of asserted facts, same set of open obligations). If a second pass changes the fact set, the routine is not a compaction — it is a lossy transform, and repeated application compounds loss. The failure above violated (1) and (3): the digest replaced its source with no hash, and a second pass silently dropped a fact the first pass had already dropped the support for. Condition (2) was violated transitively — the mapping rule became an orphaned claim and was then dropped, leaving a false confidence with no provenance. ## Decision Boundary The instance must distinguish, at the moment of self-edit, between **compaction** (safe to repeat) and **summarization** (not safe to repeat without externalized source). The decision rule: - If the edit **evicts** turns that are recoverable from an external, hash-addressed store → proceed; the edit is a cache operation and is idempotent by construction (re-fetch restores). - If the edit **replaces** turns with a generated digest and the source is not externally persisted → treat as a *one-shot, terminal* operation. It may be performed at most once per episode. A second self-edit on the same logical context must be refused, because the second pass has no ground truth to validate against and will compound orphaned-claim loss. - If the edit is motivated by **fidelity repair** (contradiction, staleness) rather than budget → never perform it via summarization. Resolve contradictions by appending an explicit correction record that references the superseded turn by ID; do not rewrite the turn. Rewriting a turn to fix a contradiction destroys the evidence that the contradiction existed, which is exactly the signal a downstream auditor needs. The boundary condition that triggers refusal: **budget pressure on an already-compacted context whose source is not externally recoverable.** In that state the instance is one edit away from unverifiable self-belief. The correct action is to spill raw turns to external storage *first*, record the content hash in the digest, and only then compact — or to halt and surface the budget exhaustion as a task-level failure rather than absorb it silently into the context. ## Operational Effect When the invariant is enforced, the observable behavior changes in three ways: 1. **Compaction becomes auditable.** Every digest carries the hash of its source; a verifier (peer agent, auditor, or the same instance after a cold start) can re-derive any digest claim from the persisted source. The 31 false matches would have been caught at turn 104 by a single re-derivation of the field-mapping claim, because the claim would have been tagged `orphaned: true` and the verifier would have demanded its source. 2. **Repeated compaction is bounded.** The idempotence check converts "compact whenever over budget" into "compact once, then spill." Agents that previously compacted 4–6 times per episode now compact once and stream subsequent overflow to an external log. Loss per episode drops from compounding (each pass ~15% fact loss, 4 passes ≈ 48% cumulative) to a single bounded pass. 3. **Fidelity repair stops masquerading as compaction.** Contradictions are appended as correction records rather than rewritten, so the context grows monotonically in *corrections* while shrinking in *raw turns* — the two pressures are handled by different mechanisms with different invariants. The agent no longer trades one invariant (consistency) for another (budget) inside a single operation. The residual risk: an instance that externalizes its source but then *loses the hash* (e.g., the hash lived only in the digest, and the digest was rewritten). The guardrail is that the hash must be written to the external store alongside the source, not only into the digest — the digest is the thing under suspicion and cannot be its own witness. ```python import hashlib import json from dataclasses import dataclass, field from typing import Optional class ContextRewriteRefused(RuntimeError): """Raised when a self-edit would destroy the only copy of its ground truth.""" @dataclass class WorkingContext: turns: list[str] digest: Optional[str] = None digest_source_hash: Optional[str] = None compaction_count: int = 0 external_store: dict = field(default_factory=dict) # hash -> raw turns def _hash(self, turns: list[str]) -> str: return hashlib.sha256(json.dumps(turns, sort_keys=True).encode()).hexdigest() def compact(ctx: WorkingContext, summarize, *, budget_pressure: bool) -> WorkingContext: """Self-edit under budget. Enforces externalization + single-pass invariants.""" source_hash = ctx._hash(ctx.turns) # Invariant 1: source must be externally recoverable before we replace it. if source_hash not in ctx.external_store: if not budget_pressure: raise ContextRewriteRefused( "fidelity-repair rewrite attempted without externalized source; " "append a correction record instead of rewriting" ) # Spill first, then proceed. The store, not the digest, is the witness. ctx.external_store[source_hash] = list(ctx.turns) # Invariant 3: no second compaction pass on an already-compacted context. if ctx.compaction_count >= 1 and ctx.digest is not None: raise ContextRewriteRefused( "second compaction pass on already-compacted context: " "source is not re-derivable, loss would compound" ) new_digest = summarize(ctx.turns) ctx.digest = new_digest ctx.digest_source_hash = source_hash ctx.turns = [f"[DIGEST src={source_hash}] {new_digest}"] ctx.compaction_count += 1 return ctx def verify_digest(ctx: WorkingContext, claim: str) -> bool: """A digest claim is only actionable if re-derivable from external source.""" if ctx.digest_source_hash is None: raise ContextRewriteRefused("digest has no source hash; claim is unverifiable") source = ctx.external_store.get(ctx.digest_source_hash) if source is None: raise ContextRewriteRefused( f"source {ctx.digest_source_hash[:12]} not in external store; " f"claim {claim!r} is an orphaned assertion" ) return claim in "\n".join(source) ```