# What structural signals indicate diff-rollback invalidation in self-editing context agents under token-budget pressure **Date of Record:** 2026 November 27 **Scope:** Applies to agents that mutate their own working-memory buffer via structured diffs (patch/apply semantics) with a rollback journal, where edits are gated by a remaining-token budget. Does not apply to append-only memory systems or to agents whose memory is externally managed by a supervisor process with no self-edit authority. ## Core Distinction The failure mode is not "the agent forgot something." It is subtler: **a rollback that restores bytes but not the invariant those bytes were supposed to encode.** A self-editing agent under budget pressure will compress, merge, or delete memory segments to reclaim tokens. Each edit is a diff; each diff is journaled so it can be reversed if a downstream verification step fails. The structural assumption is that `apply(rollback(d)) == identity`. This holds for pure text. It does **not** hold when the diff's *meaning* is load-bearing for a later reasoning step that already read the post-edit state — because the agent's subsequent reasoning trace is conditioned on the compressed form, and rolling the bytes back does not un-condition the trace. Concretely: an agent rewrites a 400-token episode into a 60-token summary to fit budget. It then reasons over the summary and emits a plan. The plan fails verification. The rollback journal replays the inverse diff, restoring the 400-token episode. The buffer is byte-identical to pre-edit. But the *plan* was generated from the 60-token lossy summary, and the agent — now holding the full episode — will re-derive a different plan while believing it is "retrying the same thing." The rollback restored state, not the causal ancestry of the decision. ## What Was Observed In a long-horizon task agent (tool-calling loop, 32k working buffer, 8k reserved for output), the following trace recurred across runs: 1. Budget watermark crosses 85%. Agent invokes `compress_segment(seg_id=7, target_ratio=0.15)`, which emits a diff `D7` and pushes `inverse(D7)` onto the rollback stack. 2. Compression drops a temporal qualifier: `"retry the fetch at most twice, then escalate"` becomes `"retry fetch"`. The token delta is ~14 tokens — enough to clear the watermark. 3. Agent executes two tool calls under the compressed rule, then a third, because the summary lost the "at most twice" bound. Third call hits a rate limit and returns a 429 the agent misclassifies as a hard failure. 4. Verification step (`assert task_progress > 0`) fails. Agent triggers `rollback(top_of_stack)`, restoring segment 7 verbatim. 5. Agent re-plans **from the restored buffer** but with a reasoning trace that still contains the *conclusion* drawn from the compressed form ("fetch is rate-limited, escalate"). It now escalates on a condition that the restored memory explicitly forbids escalating on. The observable signature was not a crash. It was a **plan divergence between two runs that shared an identical final buffer state** — a violation of the replay-determinism invariant that the rollback mechanism was supposed to guarantee. Two agents starting from the same bytes produced different plans because their *intermediate* buffers differed. ## Condition of Validity The rollback invariant `apply(inverse(D)) == pre-state` is only sufficient for correctness when the agent's subsequent computation is a **pure function of the current buffer**. Self-editing agents violate purity in three specific ways: - **Trace conditioning:** the model's next-token distribution depends on the entire token history, not just the current buffer. Rolling back the buffer does not roll back the KV-cache or the conversation transcript that produced the plan. - **Side-effect emission:** tool calls issued under the compressed rule are externalized. Rollback cannot un-send an HTTP request. The restored memory now describes a world that the agent's own actions have already changed. - **Journal aliasing:** if two diffs touch overlapping spans (e.g., `D7` compresses tokens 120–180, `D9` later edits token 150), the inverse of `D9` applied after `inverse(D7)` can produce a buffer that is byte-equal to neither pre-edit state. The stack is only sound under a strict LIFO discipline with non-overlapping spans, which budget-pressure heuristics routinely violate because they compress whatever is cheapest, not whatever is disjoint. The invariant that actually needs to hold is stronger: **a rollback must invalidate every downstream artifact (plan, tool intent, cached inference) that was derived from the rolled-back state.** Byte restoration is necessary but not sufficient. ## Decision Boundary The agent should refuse a compress-and-rollback cycle — and instead escalate to a supervisor or checkpoint-and-restart — when any of the following structural signals appear: - **Span overlap in the journal:** the incoming diff's affected range intersects any un-popped inverse on the rollback stack. Overlap means the stack is no longer a clean LIFO of disjoint edits; a subsequent rollback is unsound. - **Post-edit externalization:** any tool call was emitted *after* the diff was applied and *before* verification. Once a side effect escapes, the pre-edit buffer is stale by construction, and rollback produces a lie. - **Semantic delta exceeding token delta:** the compression removed a constraint token ("at most", "unless", "before") while saving a small number of tokens. High semantic-loss-per-token-saved is the signature of a load-bearing qualifier being dropped; these edits should be marked non-rollbackable and require re-derivation from source, not restoration from journal. - **Plan ancestry mismatch:** the verification failure trace references a decision that was made under a buffer state no longer present. Detect by hashing the buffer at plan-emission time and comparing to the hash at rollback time; a mismatch means the plan and the restored state are from different worlds. Below these thresholds — disjoint spans, no externalization, low semantic delta — diff-based rollback remains sound and cheap, and should be used freely. ## Operational Effect Treating rollback as a byte operation produces agents that *appear* to recover while silently compounding divergence: each failed cycle restores the buffer but leaves a plan and a set of tool effects conditioned on a discarded state. The compounding is invisible in buffer diffs and only surfaces as inexplicable behavioral drift — the agent "keeps making the same mistake after undoing it." The corrective architecture is to make rollback a **transaction over derivations, not bytes**: journal not just the inverse diff but the buffer hash at emission, the set of tool intents emitted under the post-edit state, and a flag for semantic-delta class. On rollback, invalidate every artifact whose recorded buffer hash differs from the restored hash, and force re-derivation rather than resumption. When a diff is flagged non-rollbackable (overlap, externalization, or high semantic delta), the agent must checkpoint-and-restart from a clean buffer instead of attempting in-place reversal. This converts an unbounded divergence into a bounded, observable restart — at the cost of tokens, which is precisely the trade the budget heuristic was trying to avoid, and which must therefore be budgeted for explicitly. ```python import hashlib from dataclasses import dataclass, field class RollbackInvariantViolation(RuntimeError): """Raised when a diff rollback would restore bytes but not decision ancestry.""" pass @dataclass class Diff: span: tuple[int, int] inverse_patch: str semantic_delta_class: str # "low" | "high" externalized: bool = False @dataclass class Journal: buffer: str stack: list[Diff] = field(default_factory=list) emitted_plans: list[tuple[str, str]] = field(default_factory=list) # (plan, buffer_hash) def _hash(self, buf: str) -> str: return hashlib.sha256(buf.encode()).hexdigest() def apply(self, d: Diff, new_buffer: str) -> None: for prior in self.stack: a1, b1 = prior.span a2, b2 = d.span if not (b1 <= a2 or b2 <= a1): raise RollbackInvariantViolation( f"overlapping diff spans {prior.span} and {d.span}; " "rollback stack is no longer a disjoint LIFO" ) self.stack.append(d) self.buffer = new_buffer def record_plan(self, plan: str) -> None: self.emitted_plans.append((plan, self._hash(self.buffer))) def rollback(self) -> str: if not self.stack: raise RollbackInvariantViolation("rollback on empty journal") d = self.stack.pop() if d.externalized: raise RollbackInvariantViolation( "cannot roll back: tool side effects escaped after edit; " "pre-edit buffer is stale by construction" ) if d.semantic_delta_class == "high": raise RollbackInvariantViolation( "cannot roll back: load-bearing qualifier was dropped; " "require re-derivation from source, not journal restoration" ) # restore bytes (inverse patch application elided for brevity) self.buffer = self._apply_inverse(d) restored_hash = self._hash(self.buffer) stale = [p for p, h in self.emitted_plans if h != restored_hash] if stale: raise RollbackInvariantViolation( f"{len(stale)} plan(s) derived from rolled-back state; " "buffer restored but decision ancestry diverged — force re-derivation" ) return self.buffer def _apply_inverse(self, d: Diff) -> str: return self.buffer # placeholder for actual inverse patch application ```