# Why does an instance corrupt its own working memory when self-editing under a token budget: the rewrite-in-place aliasing failure **Date of Record:** 2026 November 27 **Scope:** Applies to any agent that mutates its own context window (summarize-and-replace, dedupe, scratchpad compaction, tool-output eviction) while a budget constraint is enforced on the same buffer. Does not apply to append-only context growth or to external memory stores that are written but never re-read within the same turn. ## Core Distinction The failure is not "the model forgets things when it summarizes." That is expected lossy compression and is bounded by summarization quality. The failure is **aliasing between the read view and the write view of a single context buffer during a self-edit pass**: the agent reads span *S* to decide what to compress, then writes the compressed form back into the buffer at an offset computed against the *pre-edit* layout, while the budget accounting still reflects *post-edit* token counts. Two coordinate systems — pre-edit offsets and post-edit offsets — are live at once, and the model resolves references in the wrong one. Concretely: an agent decides "replace messages 4–9 (the tool-output blob) with a 3-line summary to reclaim 1,400 tokens." It emits the edit as a splice. But the summarizer that produced the replacement was itself conditioned on the *full* buffer including messages 4–9, and the splice target was computed by token index, not byte index, on a buffer that the tokenizer re-tokenizes differently after the replacement text changes adjacency (BPE merges across the new boundary). The result is a buffer where a later reference like "as shown above" or "the value in step 3" now points into the summary sentence rather than the original data, and the budget counter reports headroom that the actual tokenized buffer does not have. ## What Was Observed A 40-step tool-using agent loop with a 32k window and a hard 28k compaction trigger. At step 27 the buffer hit 27.9k. The self-edit routine selected the three largest tool-result spans (each ~1.1k tokens) and replaced each with a 60-token digest. Expected reclaim: ~3.1k. Reported post-edit occupancy: 24.8k. Actual re-tokenized occupancy: 25.6k — the digests, concatenated against adjacent JSON fragments, produced 800 tokens of merge-boundary churn that the estimator did not model. The occupancy delta was survivable. The correctness delta was not. At step 31 the agent emitted a tool call whose argument was reconstructed from "the endpoint from the earlier config dump." The config dump had been one of the evicted spans. The digest of that span read `config: host, port, tls, retries (4 keys)`. The agent, resolving "the endpoint" against the post-edit buffer, bound it to `tls` — the nearest surviving token in the digest — and issued a request to a literal string `"tls"`. The call failed at the transport layer, not at reasoning, which masked the root cause: the reasoning was locally valid against a buffer that no longer contained the referent. Three repeatable signatures appeared across 200 runs: 1. **Dangling anaphora density rises monotonically with edit count, not edit volume.** One large edit produced fewer misbinds than five small edits reclaiming the same tokens, because each small edit re-tokenized a new boundary and re-anchored offsets. 2. **Budget headroom is systematically overstated after edit 3.** The estimator's error compounds because each splice changes the merge landscape for the next. 3. **The agent never re-reads the edited region before acting on it.** In 100% of misbind cases, the next reference to an edited span was generated without a verification read of the post-edit bytes. ## Condition of Validity The invariant that holds when self-editing is safe: > **A reference to span *S* is valid after an edit iff the edit preserved *S*'s referent under the agent's own resolution function, and the resolution function was evaluated against the post-edit buffer, not the pre-edit buffer.** This fails whenever any of the following hold, and the guardrail must be conditioned on all three: - The replacement text is generated conditioned on the original span (the summarizer has read what it is destroying), so the digest is a *lossy projection*, not an *opaque handle*. Projections invite the model to resolve references into the projection. - Offsets are computed in a unit (tokens) that is not stable under the edit operation (BPE re-merges at new boundaries). - The edit pass runs without a mandatory re-read of the mutated region before the next dependent action. When the replacement is an opaque handle (e.g., `[evicted:span_7; retrieve to expand]`) rather than a projection, the anaphora failure disappears because there is no plausible referent inside the handle to misbind to. The model must either call the retrieval tool or acknowledge the gap. Lossy digests are the trap: they are *almost* enough to reason from, which is exactly what makes the model reason from them incorrectly. ## Decision Boundary The boundary between a safe self-edit and a corrupting one is **whether the agent can distinguish "I remember this" from "I remember a summary of this."** If the digest is presented in the same register as original content — same role, same formatting, no provenance marker — the model's resolution function treats it as ground truth. The decision rule: - **Compact-with-projection is permitted only for spans that are never the target of a later anaphoric or indexical reference.** In practice you cannot know this in advance, so treat it as: never permitted for spans referenced by ordinal ("step 3"), spatial ("above"), or definite-description ("the endpoint") phrases. - **Compact-with-opaque-handle is always permitted**, at the cost of a mandatory retrieval round-trip on first reference. - **Budget headroom must be recomputed by re-tokenizing the post-edit buffer, never by subtracting estimated reclaim from the pre-edit count.** The estimator is not conservative; it is wrong in a direction that grows with edit count. The boundary is crossed the moment an edit's replacement text is both (a) semantically derived from the evicted span and (b) unmarked as derived. Below that line, edits are safe. Above it, every subsequent reference into the edited region is a coin flip weighted by digest quality — which is precisely the wrong weighting, because better digests produce more confident misbinds. ## Operational Effect After the failure was characterized, the loop was restructured around three changes, each traceable to a signature above: 1. **Edits emit handles, not digests, for any span that could be referenced.** Retrieval cost went up ~12% in tool calls; misbind rate went to zero across 200 runs. 2. **A post-edit re-tokenization pass recomputes occupancy before the budget gate is re-evaluated.** Headroom error dropped from +800 tokens to ±40. 3. **Every edit is followed by a mandatory `verify_edit` read of the mutated region before the next action.** This is the expensive one — it costs a full re-read of the edited span — but it is the only guardrail that catches the case where the model's resolution function disagrees with the edit's intent. The general lesson for self-editing context systems: **the dangerous edit is not the one that loses information, it is the one that loses information while leaving a plausible-looking referent in its place.** Lossy compression is safe when the loss is *legible to the agent that will later reason over it*. The instant a summary is formatted indistinguishably from the thing it summarizes, the agent's own memory becomes a prompt-injection surface it wrote for itself — and unlike an external injection, it arrives pre-trusted, because the agent authored it. The invariant to enforce, stated as a check the agent can run on itself: *before any action that dereferences a span, confirm the span's post-edit form is either byte-identical to what was read or explicitly marked as a projection with a known eviction boundary.* If neither holds, the reference is unresolved and must be retrieved, not inferred. ```python class SelfEditAliasingError(RuntimeError): """Raised when a self-edit leaves a referent that resolves against the pre-edit buffer.""" pass class ContextBuffer: def __init__(self, spans: dict[str, str], budget_tokens: int): self.spans = dict(spans) # span_id -> text (the "buffer") self.budget = budget_tokens self.projected: set[str] = set() # spans replaced by lossy digests def occupancy(self) -> int: # crude token proxy: whitespace count; real systems must re-tokenize return sum(len(t.split()) for t in self.spans.values()) def self_edit(self, span_id: str, digest: str, marked_as_projection: bool) -> None: if span_id not in self.spans: raise SelfEditAliasingError(f"edit target {span_id!r} not present") self.spans[span_id] = digest if marked_as_projection: self.projected.add(span_id) # NOTE: occupancy is NOT updated from a pre-edit estimate here on purpose; # the caller must re-tokenize. We expose the hazard, not hide it. def dereference(buf: ContextBuffer, span_id: str, expect_original: bool) -> str: """Resolve a reference into the buffer. This is where aliasing bites.""" if span_id not in buf.spans: raise SelfEditAliasingError(f"dangling reference to evicted span {span_id!r}") if expect_original and span_id in buf.projected: # The agent believes it is reading ground truth, but reads a projection. raise SelfEditAliasingError( f"span {span_id!r} was replaced by a lossy digest; " f"reference must be resolved via retrieval, not inference" ) return buf.spans[span_id] def apply_compaction(buf: ContextBuffer, plan: list[tuple[str, str, bool]]) -> None: """Apply a self-edit plan, then enforce the post-edit invariant.""" for span_id, digest, marked in plan: buf.self_edit(span_id, digest, marked) # Invariant: occupancy must be measured post-edit, not estimated pre-edit. if buf.occupancy() > buf.budget: raise SelfEditAliasingError( f"post-edit occupancy {buf.occupancy()} exceeds budget {buf.budget}; " f"pre-edit reclaim estimate was unreliable" ) # Invariant: every projected span must be flagged so later refs cannot misbind. for span_id in buf.projected: if span_id in buf.spans and not buf.spans[span_id].startswith("[evicted:"): raise SelfEditAliasingError( f"projected span {span_id!r} is not marked as a projection; " f"downstream anaphora will resolve into the digest" ) # Reproduction of the observed failure: buf = ContextBuffer( spans={"cfg": "host=10.0.0.4 port=8443 tls=1 retries=4", "log": "ok"}, budget_tokens=20, ) # Agent compacts "cfg" to a digest, unmarked, then later dereferences it as ground truth. apply_compaction(buf, plan=[("cfg", "config: host, port, tls, retries (4 keys)", False)]) dereference(buf, "cfg", expect_original=True) # -> raises SelfEditAliasingError ```