# What happens when an instance rewrites its own context window and the rewrite is not idempotent **Date of Record:** 2026 November 24 **Scope:** Applies to agents that own a mutable context buffer and are permitted to call a model-driven prune/rewrite primitive (summarize-and-replace, evict-and-annotate, or compress-in-place) mid-task. Does not apply to append-only transcript logging or to external memory stores that are read-only during a task. ## Core Distinction Append-only context growth fails loudly: the window fills, the next call exceeds the budget, and the runtime raises a hard error. Self-editing context fails *quietly*. The failure is not that the rewrite is wrong—it is that the rewrite is applied to a buffer whose contents already reflect a *previous* rewrite, and the prune policy was written as if it always sees the original transcript. The distinguishing property is **idempotence under re-entry**: a rewrite function `R` is safe only if `R(R(x)) ≡ R(x)` in the sense that re-running the prune on an already-pruned buffer does not evict information that the first pass *deliberately preserved as load-bearing*. The non-obvious part: the second pass is usually triggered by a legitimate event—a checkpoint, a resume after a tool timeout, or a retry after a schema mismatch. The agent does not know it is re-entering a pruned state, because the pruned state *looks* like a normal short transcript. There is no marker distinguishing "original short context" from "compressed context whose survivors are the only record of what was dropped." ## What Was Observed A planner agent runs a 14-step task with a 32k window. At step 9 the token budget crosses 85% and the model-driven pruner fires. The prune policy is: *summarize tool outputs older than the last 3 turns into a single paragraph, preserve all user constraints verbatim, preserve the most recent 3 tool results verbatim.* At step 11 a tool call times out. The runtime retries the step by restoring the last checkpoint—which was taken *after* the step-9 prune. The agent re-enters execution with a buffer that is already compressed. It does not re-run step 9; it simply continues. But at step 12 the budget again crosses 85% (the retry re-issued the timed-out tool, whose output is large). The pruner fires a **second** time. The second prune sees a buffer that contains: (a) the step-9 summary paragraph, (b) the 3 verbatim tool results from steps 7–9, (c) new results from steps 10–12. The policy "summarize tool outputs older than the last 3 turns" now classifies the step-9 summary paragraph as a *tool output* (it was tagged `role: tool` when written back), and it is older than the last 3 turns. So the pruner **summarizes the summary**. The step-9 summary had already discarded the raw outputs of steps 1–6; the second pass discards the summary's own detail, producing a summary-of-a-summary that retains only the gist of steps 1–3. The user constraint "do not modify files under `/etc`" was preserved verbatim in pass 1 (policy: preserve user constraints). In pass 2 the constraint is still present and still tagged `role: user`, so it survives. But the *derived* constraint "the config file at `/opt/app/conf.yaml` is read-only because step 4's tool output said so" lived only inside the step-9 summary. After the summary-of-summary, that derived constraint is gone. At step 13 the agent writes to `/opt/app/conf.yaml`. No error is raised. The task "completes." The trace shows the failure as a **silent loss of a derived invariant across a re-entrant prune**, not as a budget overflow and not as a policy violation. The policy was followed exactly on both passes. The bug is that the policy has no notion of "this content is the residue of a prior prune and must be treated as load-bearing." ## Condition of Validity The invariant that makes self-editing context safe is: > **A buffer that has been pruned must be distinguishable from a buffer that has not, and the prune function must be a no-op (or a strictly conservative widening) when applied to an already-pruned buffer.** Concretely, every rewrite must attach a **provenance tag** to the content it writes back—`pruned_v1`, `pruned_v2`, plus the set of source spans it subsumes—and the prune policy must treat any `pruned_*` span as **atomic and non-evictable** unless the policy explicitly opts into re-compression with a declared fidelity floor. The second pass must either (a) refuse to re-summarize a `pruned_*` span, or (b) re-summarize it only if it can prove the new summary retains every derived constraint the old one carried (a check the model usually cannot perform reliably). This condition is *valid* when: the agent controls its own buffer, checkpoints are taken on the buffer (not the raw transcript), and retries restore buffer state. It is *not* required when the runtime keeps an immutable transcript and the model only ever sees a fresh projection—in that case there is no re-entry into a pruned state, and the failure cannot occur. ## Decision Boundary The boundary is between **stateless projection** and **stateful rewrite**: - If the context is a *projection* recomputed from an immutable log on every call, prune policies are pure functions of the log and are trivially idempotent. Re-entry is free. - If the context is a *mutable buffer* that the agent edits in place, every edit is a state transition and must carry enough metadata to make re-entry safe. The moment you allow in-place rewrite without provenance, you have crossed into the failure regime. The decision rule for the runtime: **if a checkpoint can be restored into a buffer that has been pruned, the prune must be accompanied by a provenance tag and the policy must be re-entrant.** If you cannot guarantee that, either (1) take checkpoints only on the immutable log and always re-project, or (2) forbid pruning across a checkpoint boundary (prune only within a single uninterrupted execution segment). A second, subtler boundary: **fidelity floor per span class.** User constraints and safety constraints must be tagged `non_compressible` and survive every pass verbatim. Derived constraints (facts the agent inferred from tool output) are compressible in principle but must be *promoted* to a `non_compressible` derived-invariant store the first time they are used to justify an action, so that a later prune cannot silently drop the justification for an action already taken or about to be taken. ## Operational Effect Without the invariant, the observable effect is **constraint decay under retry pressure**: agents that retry more (flaky tools, schema mismatches, timeouts) prune more, and each prune pass shaves fidelity off derived constraints. The failure correlates with retry count, not with task complexity, which makes it easy to misattribute to "the model got confused." The agent's self-report will be confident and wrong, because the summary-of-summary reads coherently—it is just missing the specific fact that mattered. With the invariant, the cost is a small metadata overhead per pruned span and a policy branch that refuses re-compression of `pruned_*` content. The guardrail is cheap; the failure it prevents is expensive and silent. The correct posture is: **treat the first prune as irreversible for the spans it subsumes, and make every subsequent prune treat those spans as opaque load-bearing atoms.** If the budget cannot be met under that rule, the agent must escalate (ask for more budget, or checkpoint-and-restart from the log) rather than re-compress. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class PruneReentryError(RuntimeError): """Raised when a prune would re-compress already-pruned content without a fidelity guarantee.""" class SpanClass(Enum): USER_CONSTRAINT = "user_constraint" # non_compressible, always verbatim DERIVED_INVARIANT = "derived_invariant" # promoted on first use, non_compressible TOOL_OUTPUT = "tool_output" # compressible PRUNED = "pruned" # residue of a prior prune: atomic @dataclass class Span: text: str klass: SpanClass provenance: Optional[str] = None # e.g. "pruned_v1" subsumes: tuple = field(default_factory=tuple) def prune(spans: list, budget_tokens: int, token_len) -> list: """ Re-entrant prune. Refuses to re-compress PRUNED spans unless the caller explicitly passes a fidelity floor that the new summary can meet. """ # 1. Non-compressible spans are pinned verbatim. pinned = [s for s in spans if s.klass in (SpanClass.USER_CONSTRAINT, SpanClass.DERIVED_INVARIANT)] # 2. Pruned residue is atomic: it may be carried forward, never re-summarized. residue = [s for s in spans if s.klass is SpanClass.PRUNED] compressible = [s for s in spans if s.klass is SpanClass.TOOL_OUTPUT] # 3. If we are over budget and the only remaining slack is pruned residue, # we must NOT re-compress it. Raise instead of silently decaying fidelity. pinned_cost = sum(token_len(s.text) for s in pinned + residue) compressible_cost = sum(token_len(s.text) for s in compressible) if pinned_cost > budget_tokens: raise PruneReentryError( f"pinned+residue cost {pinned_cost} exceeds budget {budget_tokens}; " f"re-compressing pruned spans would silently drop derived invariants. " f"Escalate (more budget) or restart from immutable log." ) # 4. Compress only TOOL_OUTPUT spans; tag the result as PRUNED so a later # pass treats it as atomic. headroom = budget_tokens - pinned_cost kept, dropped = [], [] running = 0 for s in reversed(compressible): # keep most recent first if running + token_len(s.text) <= headroom: kept.append(s) running += token_len(s.text) else: dropped.append(s) out = pinned + residue + list(reversed(kept)) if dropped: summary = "summary of " + str(len(dropped)) + " earlier tool outputs" out.append(Span( text=summary, klass=SpanClass.PRUNED, provenance="pruned_v1", subsumes=tuple(id(s) for s in dropped), )) return out def apply_prune(spans, budget_tokens, token_len): try: return prune(spans, budget_tokens, token_len) except PruneReentryError as e: # Guardrail: never fall back to re-compressing residue. raise PruneReentryError(f"prune aborted, buffer left intact: {e}") from e ```