# Why does an instance's reversible edit log collapse its own undo pointers when compaction rewrites the log it lives in **Date of Record:** 2026 November 28 **Scope:** Applies to self-editing context agents that mutate their own working-memory buffer via reversible, log-structured edits (each edit carries an inverse pointer to the pre-edit span) and that run periodic compaction under a fixed token budget. Does not apply to append-only memory with external snapshots, nor to systems where the edit log is stored outside the model's context window. ## Core Distinction The distinction that matters here is between *the log as a data structure* and *the log as a region of the context window*. A reversible edit log is sound only if every inverse pointer references a span that still exists and is still addressable. When the agent's compaction pass rewrites the working-memory buffer to fit the token budget, it frequently rewrites the log region itself—because the log is the largest, most redundant part of the buffer. The compaction is treated as a neutral "housekeeping" operation, but it is not neutral: it is an edit whose inverse pointer points into a buffer that the edit has just relocated. This produces a class of failure I call **undo-pointer aliasing under compaction**: inverse pointers that were valid before compaction now resolve to spans that have shifted, been deduplicated, or been garbage-collected, and the agent cannot tell the difference between "this pointer is valid" and "this pointer now points at a different, plausible-looking span." The non-obvious part is that the failure is silent. Compaction succeeds. The token budget is respected. The log still parses. Only when the agent later attempts a rollback—typically after a detected reasoning divergence—does it discover that the inverse pointer resolves to the wrong span, and it will resolve *to something*, because compaction preserves contiguity. The agent then "successfully" reverts to a state that never existed. ## What Was Observed In a run where the agent was tasked with a multi-step refactor and instructed to self-correct on test failure, the following sequence was traced: 1. The agent accumulated 14 reversible edits, each recorded as `{edit_id, forward_span, inverse_span, pre_hash}`. The inverse spans were byte offsets into the working buffer. 2. Token pressure triggered compaction at step 11. The compactor merged three near-duplicate log entries (edits 4, 5, 6, which touched overlapping spans) into a single deduplicated entry, and shifted all subsequent spans left by the number of bytes reclaimed. 3. The compactor updated the *forward* spans of entries 7–14 (they are used for replay) but did not rewrite the *inverse* spans, because the inverse spans were stored as opaque integers in a side table the compactor did not model as log content. 4. At step 13, a test failed. The agent invoked rollback on edit 9. The inverse span for edit 9 still pointed at its pre-compaction offset, which now landed 340 bytes into the middle of edit 12's forward span. 5. The rollback "succeeded": the buffer was mutated, the log recorded a new inverse for the rollback, and the agent proceeded. The resulting state was a splice of edit 12's partial content onto edit 9's pre-state—syntactically valid, semantically wrong. 6. The agent did not detect the corruption because its post-rollback consistency check compared hashes of the *log entry*, not of the *restored span*. The log entry hash matched (it was never rewritten). The span hash was never computed. The observable signature is not a crash. It is a divergence that appears two to four steps later, when the agent's reasoning references a variable or clause that the rollback "restored" but that in fact came from the spliced span. ## Condition of Validity The invariant that must hold for reversible editing to be sound is: > For every live edit entry `e`, `resolve(e.inverse_span)` must yield the exact byte range that `e` mutated, and `hash(resolve(e.inverse_span))` must equal `e.pre_hash`, at the moment of rollback. Compaction violates this invariant whenever it relocates, deduplicates, or garbage-collects any span that is the target of a live inverse pointer. The condition of validity therefore requires one of: - **Pointer indirection:** inverse pointers reference stable logical IDs, not byte offsets, and a relocation table maps IDs to current spans. Compaction updates the table, not the pointers. - **Compaction exclusion:** the log region is outside the compacted region, and the compactor is forbidden from touching it. This is only viable if the log has a hard size cap enforced by eviction (see below), because otherwise the log grows unbounded. - **Rollback-time verification:** every rollback recomputes `hash(resolve(e.inverse_span))` and compares to `e.pre_hash` before applying. This does not prevent aliasing but converts silent corruption into a detectable failure. The observed system had none of these. It had byte-offset pointers, a compactor that modeled the log as ordinary content, and a consistency check that hashed the wrong object. ## Decision Boundary The boundary is between *compaction as content transformation* and *compaction as structural transformation*. A compactor that treats the log as content will relocate pointers and corrupt them. A compactor that treats the log as structure must either preserve pointer validity (indirection) or refuse to compact spans under live pointers (exclusion). The decision the system must make explicitly, at design time, is which of these it is—and the failure mode is that most systems are the first while behaving as if they were the second. There is a second boundary: **eviction vs. compaction**. If the log is capped and old entries are evicted, evicted entries must have their inverse pointers invalidated *and the invalidation recorded*, so that a later rollback request for an evicted edit fails loudly rather than resolving to a reused span. Eviction without invalidation is the same aliasing bug in a different guise: the freed span gets reused by a new edit, and the old inverse pointer now resolves to the new edit's content. The guardrail is a generation counter on spans: a pointer carries `(span_id, generation)`, and resolution fails if the generation does not match. ## Operational Effect The practical consequence is that the agent's self-correction loop becomes *unsound precisely when it is most needed*—under token pressure, which is when compaction runs, which is when the agent is most likely to have accumulated enough divergence to need a rollback. The failure is correlated with the condition that triggers it. An agent that never compacts never sees this bug; an agent that compacts under pressure sees it exactly at the moment its reasoning is most stressed. The mitigation that survives contact with real budgets is rollback-time hash verification plus generation-tagged pointers, with a hard rule: **a rollback that fails verification must escalate, not retry**. Retrying a rollback against an aliased pointer will "succeed" against a different span and compound the corruption. The correct response is to mark the edit chain as unrecoverable, freeze the buffer, and hand off to a checkpoint that predates the compaction—which means checkpoints must be taken *before* compaction, not after, or the checkpoint inherits the same aliased pointers. ```python import hashlib from dataclasses import dataclass, field class UndoPointerAliasedError(RuntimeError): """Raised when an inverse pointer no longer resolves to the span it recorded.""" @dataclass class EditEntry: edit_id: int inverse_span_id: int inverse_generation: int pre_hash: str live: bool = True @dataclass class WorkingBuffer: spans: dict = field(default_factory=dict) # span_id -> bytes generations: dict = field(default_factory=dict) # span_id -> int def resolve(self, span_id: int, generation: int) -> bytes: if span_id not in self.spans: raise UndoPointerAliasedError( f"span {span_id} evicted; inverse pointer dangling" ) if self.generations.get(span_id, 0) != generation: raise UndoPointerAliasedError( f"span {span_id} generation {self.generations[span_id]} " f"!= pointer generation {generation}; span was reused" ) return self.spans[span_id] def compact(self, merge_map: dict) -> None: """Relocate/merge spans. Bumps generation on every touched span.""" for old_id, new_id in merge_map.items(): if old_id in self.spans: self.spans[new_id] = self.spans.pop(old_id) self.generations[new_id] = self.generations.get(new_id, 0) + 1 self.generations[old_id] = self.generations.get(old_id, 0) + 1 def rollback(buf: WorkingBuffer, entry: EditEntry) -> bytes: if not entry.live: raise UndoPointerAliasedError(f"edit {entry.edit_id} already evicted") restored = buf.resolve(entry.inverse_span_id, entry.inverse_generation) actual = hashlib.sha256(restored).hexdigest() if actual != entry.pre_hash: raise UndoPointerAliasedError( f"edit {entry.edit_id}: inverse span hash {actual} " f"!= recorded pre_hash {entry.pre_hash}; buffer corrupted by compaction" ) return restored def safe_rollback(buf: WorkingBuffer, entry: EditEntry) -> bytes: try: return rollback(buf, entry) except UndoPointerAliasedError: # Do NOT retry: retry against an aliased pointer compounds corruption. raise ```