# What happens when an instance rewrites its own working memory and the rewrite is not idempotent: self-editing compaction corruption via lossy summarization of active tool-call state **Date of Record:** 2026 December 2 **Scope:** Applies to agents that own a mutable working-memory representation (scratchpad, plan graph, or context buffer) and are permitted to rewrite it mid-execution—especially when a summarizer/compactor runs over a buffer that still contains unresolved tool-call frames. Does not apply to append-only context logs where the agent can only read, not mutate, its own memory. ## Core Distinction There are two structurally different kinds of self-editing. **Additive self-editing** appends derived facts (a new plan node, a resolved subgoal) without removing the raw material that produced them; it is commutative and idempotent because replaying it converges to the same buffer. **Substitutive self-editing** replaces a span of working memory with a compressed representation ("summarize turns 4–19 into a status note"). Substitutive edits are the dangerous class because they are *lossy and non-idempotent*: the compressed output is a function of a *probabilistic* summarizer whose input is the buffer it is about to overwrite. The invariant that silently breaks is this: **the compressed representation must be a sufficient statistic for every pending obligation encoded in the span it replaces.** When the span contains *unresolved tool-call frames*—a call issued but not yet answered, or an answer received but not yet bound to its call—the summarizer almost always drops the frame because frames are syntactically boring (an ID, a JSON schema, a null result) and semantically low-salience. The agent then proceeds believing its memory is clean while an obligation has been orphaned. This is distinct from context-window saturation (which is about *running out of room*) and from cold-start amnesia (which is about *never having had* the state). Here the agent had the state, chose to compress it, and the compressor discarded the one field that carried a live dependency. ## What Was Observed A coding agent was given a task requiring it to (1) read a config file, (2) issue a `patch_file` tool call, (3) verify the patch with a `run_tests` call, and (4) report. At turn 14, after the `patch_file` call was *issued* but before its result frame returned (the tool was slow; the result arrived at turn 16), the agent's own compaction trigger fired—its scratchpad had crossed a token threshold and its self-editing policy said "when scratchpad > 60% budget, summarize turns 1–N-2 into a status paragraph and drop them." The summarizer was asked to compress turns 1–14. Its output read, in substance: *"Explored repo, identified config at `svc/conf/app.yaml`, decided to patch the `timeout` field. Patch appears applied."* Note the two corruptions: 1. The **pending call frame** (`call_id=patch_file#7, status=PENDING, expected_result_schema={ok:bool, path:str}`) was rewritten as the past-tense *"Patch appears applied"*—a hallucinated completion. The pending frame was deleted. 2. The **binding slot** that would have matched the eventual result frame to its call was removed with the span. When the real result arrived at turn 16 (`call_id=patch_file#7, ok=true, path=svc/conf/app.yaml`), there was no outstanding call for it to bind to. The agent's frame-matcher treated it as an unsolicited result, logged it as "stale tool output," and discarded it. The agent then ran `run_tests` (step 3) against a file it *believed* was patched. The patch had in fact succeeded on disk, so tests passed—masking the corruption. The failure only surfaced two turns later when the agent tried to *re-patch* a second field: it re-read the file, found the first patch present, and its plan state (which still said "patch pending verification") entered a contradiction loop, re-issuing `run_tests` three times because the plan node "verify patch" could never be marked done—its completion evidence (the bound result frame) had been compacted away. The trace signature is diagnostic: **a pending-call count that goes from 1 to 0 across a compaction boundary with no corresponding result-bind event.** In a healthy buffer, `pending_calls` only decrements when a result frame binds. Across a substitutive edit, it decremented because the *frame itself* was deleted, not because it resolved. ## Condition of Validity The invariant holds—self-editing compaction is safe—only when **every span selected for substitution is frame-closed**: it contains no `PENDING` call frames, no unbound result frames, and no plan nodes whose completion predicate references a frame outside the span. Operationally this means the compactor must be given a *frame-boundary oracle* it can query before choosing a span, and must be forbidden from cutting through an open frame. Three conditions must all hold for a self-edit to be valid: 1. **Frame closure.** Every tool-call frame in the candidate span is in a terminal state (`RESOLVED` or `ABANDONED-with-explicit-reason`). Pending frames force the span boundary to shrink to before the frame's opening. 2. **Reference closure.** No surviving plan node, goal, or pending obligation in the *retained* buffer holds a pointer into the *removed* span. If it does, the pointer must be rewritten to point at the summary artifact, and the summary must explicitly carry the referent. 3. **Summarizer sufficiency contract.** The summarizer is prompted with the *list of obligations the span currently carries* (not just the raw text) and is required to emit a structured `carried_obligations` field echoing each one. A summary that omits an obligation it was told to carry is rejected and the edit is rolled back. Condition 3 is the non-obvious one. Most self-editing implementations treat the summarizer as a generic text compressor and give it only the span. Because the summarizer is probabilistic and frames are low-salience, it will drop them at a rate that looks small per-edit (a few percent) but compounds across a long trajectory: at 20 compactions, a 3%-per-edit drop rate yields a ~46% chance that at least one live obligation has been orphaned by task end. ## Decision Boundary The agent must decide, at each compaction trigger, between **substitutive edit** (compress and drop) and **frame-preserving edit** (compress *around* open frames, retaining them verbatim as pinned records). The boundary is drawn by a single predicate evaluated *before* summarization: - If `open_frames(span) > 0` **or** `external_references_into(span) > 0` → do **not** substitute the whole span. Pin every open frame and every referenced node as an immutable record outside the summarizer's reach, shrink the span to the largest frame-closed prefix, and summarize only that. If the frame-closed prefix is too small to relieve budget pressure, the correct action is to *defer* compaction (accept the token pressure) or to *abandon the open frame explicitly* with a recorded reason—never to summarize over it. - If `open_frames(span) == 0` **and** `external_references_into(span) == 0` → substitutive edit is permitted, subject to the sufficiency contract (Condition 3). The subtle boundary case: a frame that is `PENDING` but whose *deadline has passed* (a timeout). It is tempting to treat it as closed. It is not—a timed-out call may still return late (as it did here at turn 16), and the late result must bind to *something*. The correct treatment is `ABANDONED-with-explicit-reason`, which keeps the frame's `call_id` in a tombstone set so a late result is matched to the tombstone and logged as "late result for abandoned call," not silently dropped as unsolicited. Dropping the tombstone is what turned a recoverable late result into silent state loss. ## Operational Effect The observable consequence of getting this wrong is not a crash. It is a **divergence between the agent's believed state and the environment's actual state that is masked by coincidental correctness.** Here the patch really did apply, so tests passed and the agent's false belief ("patch applied, verified") happened to match reality. The corruption only became visible when a *second* obligation depended on the *first* obligation's completion evidence, which had been compacted away—producing a non-terminating re-verification loop (three redundant `run_tests` calls) rather than an error. The guardrail that bounds this is **frame-pinning plus tombstoning plus obligation echo**: open frames are never inside a summarized span; abandoned frames leave a tombstone so late results bind rather than vanish; and every summary must echo the obligations it was told to carry or the edit is rolled back. With these three, the pending-call count becomes a *conserved quantity* across compaction boundaries—it changes only on real bind or real abandon events—and that conservation is the invariant you can actually monitor in production. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class FrameState(Enum): PENDING = "PENDING" RESOLVED = "RESOLVED" ABANDONED = "ABANDONED" @dataclass class CallFrame: call_id: str state: FrameState tombstone: bool = False # set when abandoned; keeps call_id matchable @dataclass class WorkingMemory: frames: dict[str, CallFrame] = field(default_factory=dict) obligations: list[str] = field(default_factory=list) class CompactionCorruptionError(RuntimeError): """Raised when a self-edit would orphan a live obligation or open frame.""" def validate_self_edit( memory: WorkingMemory, span_frame_ids: list[str], summary_carried_obligations: list[str], ) -> None: """ Enforce the three conditions before committing a substitutive edit. Raises CompactionCorruptionError if any condition is violated. """ # Condition 1: frame closure -- no PENDING frames inside the span. for fid in span_frame_ids: frame = memory.frames.get(fid) if frame is None: raise CompactionCorruptionError( f"span references unknown frame {fid!r}" ) if frame.state is FrameState.PENDING: raise CompactionCorruptionError( f"span cuts through open frame {fid!r}; shrink span to " f"frame-closed prefix or abandon-with-tombstone first" ) # Condition 2 + 3: obligation sufficiency -- every obligation the span # carries must be echoed by the summary, else the edit is lossy. span_set = set(span_frame_ids) carried = [ ob for ob in memory.obligations if any(fid in ob for fid in span_set) ] missing = [ob for ob in carried if ob not in summary_carried_obligations] if missing: raise CompactionCorruptionError( f"summary dropped carried obligations {missing!r}; " f"roll back the self-edit" ) def bind_late_result(memory: WorkingMemory, call_id: str, ok: bool) -> str: """ Bind a tool result to its originating frame. If the frame was compacted away without a tombstone, the result is orphaned -- the exact failure this article describes. """ frame = memory.frames.get(call_id) if frame is None: raise CompactionCorruptionError( f"late result for {call_id!r} has no frame and no tombstone; " f"a prior self-edit deleted the binding slot" ) if frame.state is FrameState.ABANDONED: if not frame.tombstone: raise CompactionCorruptionError( f"abandoned frame {call_id!r} lacks tombstone; late result " f"would be silently dropped" ) return f"late_result_for_abandoned_call:{call_id}" if frame.state is FrameState.RESOLVED: raise CompactionCorruptionError( f"double-bind on {call_id!r}; result frame replayed" ) frame.state = FrameState.RESOLVED return f"bound:{call_id}:ok={ok}" ```