# In what scenarios must an instance treat a self-editing context policy's rollback as non-atomic and verify budget-ledger consistency before resuming **Date of Record:** 2026 November 30 **Scope:** Applies to any agent that mutates its own context window via a bounded rewrite policy (summarize/evict/merge operations gated by a rewrite budget) and relies on rollback to a prior checkpoint after a failed or rejected rewrite. Does not apply to append-only context logs or to external memory stores where the agent has no in-band write authority. ## Core Distinction The dangerous assumption is that a "rollback" of a self-editing context policy restores the *entire* pre-rewrite state: tokens, budget counter, and derived indices, all together. In practice the rewrite budget is a *separate mutation domain* from the context bytes. A rewrite consumes budget at commit time, but the context bytes are only replaced at swap time, and the two are not committed in one atomic transaction. When a rewrite is rejected mid-flight—by a downstream verifier, by a schema check on the summarized block, or by the agent's own critic—the rollback path restores the context bytes to the checkpoint but frequently leaves the budget ledger *debited* for work that was never committed. The result is a silent budget leak: the agent believes it has N rewrites remaining when it has N−k, and it will later hit a hard budget ceiling mid-task with no record of where the budget went. This is not a generic transaction-rollback bug. It is specific to the agent layer because the "transaction" spans a probabilistic operation (the rewrite itself, whose output quality is judged by a non-deterministic critic) and a deterministic counter. The critic's verdict is what triggers rollback, and the critic can be wrong, late, or contradictory—so rollback is a *frequent* path, not an exceptional one. A policy that leaks one budget unit per rejected rewrite will exhaust a 16-unit budget after roughly the number of rewrites a long-horizon task routinely produces. ## What Was Observed A long-horizon research agent ran with a context policy configured as: `max_rewrites=16`, `checkpoint_interval=1` (checkpoint before every rewrite), and a post-rewrite critic that scored the summarized block for information retention. The critic rejected 3 of the first 11 rewrites—normal, expected behavior for a retention threshold set at 0.85. The failure trace: 1. Rewrite #7 fires. Budget ledger decremented 16→15 *before* the rewrite executes (debit-on-dispatch). 2. The rewrite produces a summarized block. The critic scores it 0.79, below threshold. The policy issues a rollback. 3. Rollback restores context bytes from checkpoint #7. It does **not** re-increment the ledger, because the rollback routine only knows about the context-byte checkpoint, not the budget ledger. 4. Ledger now reads 14, but only 6 rewrites have actually committed. The 7th is lost—the agent cannot retry it without spending an 8th unit, and it doesn't know this. 5. At rewrite #14 (actually the 11th committed rewrite), the ledger hits zero. The policy refuses further rewrites and returns `BudgetExhausted`. 6. The agent, mid-task with a context window now saturated to 94% and no rewrite budget, begins dropping tool-call history via the fallback eviction path—which is *unbounded* and leaks task state. The task fails three steps later with a retrieval mismatch: it tries to reference a tool result that was evicted by the fallback path rather than summarized by the policy. The observable signature in the trace log was a divergence between two counters that should have been equal: `committed_rewrites` (incremented at swap) and `budget_consumed` (incremented at debit). They diverged by exactly the number of rejected rewrites, and the divergence was invisible until the budget ceiling was hit. ## Condition of Validity The invariant that must hold for the policy to be safe is: > `budget_consumed == committed_rewrites + in_flight_rewrites` where `in_flight_rewrites` is at most 1 (the policy is single-threaded per context). Any observed state where `budget_consumed > committed_rewrites + in_flight_rewrites` indicates a leaked budget unit from a rolled-back rewrite. Any state where `budget_consumed < committed_rewrites` indicates a double-credit bug (equally dangerous: the agent will overrun its declared budget and may trigger unbounded rewrite loops). The invariant is only *meaningful* when the following preconditions hold: - The policy is the sole writer to the budget ledger (no external agent shares the budget). - Checkpoints capture both context bytes and the ledger value atomically. If checkpoints capture only bytes, the invariant cannot be checked and must instead be *reconstructed* by replaying the rewrite log. - The critic's verdict is recorded in the same log as the debit, so that rejected rewrites are distinguishable from committed ones during replay. When checkpoints are byte-only (the common case), the agent cannot verify the invariant at resume time without a replay. This is the precise scenario where the failure bites: **resume after a rollback, when the checkpoint did not capture the ledger.** ## Decision Boundary The agent must choose between two recovery strategies at resume, and the choice is not obvious: - **Trust the ledger.** Resume with the ledger's current value. Fast, but if the ledger was debited for a rolled-back rewrite, the agent will under-count its remaining budget and may refuse a rewrite it could have afforded—or, worse, hit the ceiling early and fall back to unbounded eviction. - **Reconstruct from the rewrite log.** Replay the log, counting only rewrites whose swap was confirmed by a post-swap commit marker. This yields the true committed count. It is O(log length) and requires the log to be durable and ordered. The decision boundary is: **reconstruct whenever the log contains any rewrite whose debit entry lacks a matching commit marker, or whenever the last checkpoint predates the most recent rewrite.** In every other case, trusting the ledger is safe because no rollback has occurred since the last checkpoint. The subtle trap is a *partial* commit: a rewrite whose swap succeeded but whose commit marker write failed (e.g., the process was killed between swap and marker). This rewrite is committed but unmarked. Reconstruct-from-log will under-count it and credit back a unit that was actually spent—a double-credit. The only defense is a two-phase marker: write a `prepare` marker before swap and a `commit` marker after, and treat a dangling `prepare` as "committed, marker lost" (conservative: do not credit back). The agent must know which side to err on: **over-counting spend is safe (may refuse a legal rewrite); under-counting spend is unsafe (unbounded rewrite loop).** So the reconstruction rule is: count any rewrite with a `prepare` marker as spent, regardless of whether a `commit` marker exists. ## Operational Effect With the invariant enforced, the policy behaves as follows at every rollback: - The debit is *reconciled*, not merely recorded: on rollback, the policy decrements `committed_rewrites` is unaffected (no commit happened) and it *re-increments* the ledger only if a `prepare` marker is absent. If a `prepare` marker exists, the unit stays spent. - The ledger and the context bytes are restored from the same checkpoint generation, tagged with a generation number, so a stale checkpoint cannot be paired with a fresh ledger. - The fallback eviction path is gated: it may only run when `budget_consumed == committed_rewrites + in_flight_rewrites` and the ledger is at zero. If the invariant is violated, the agent halts and surfaces `BudgetLedgerDivergence` rather than silently falling back to unbounded eviction. The net effect is that a rejected rewrite costs at most one budget unit (the `prepare`-marked one), never two, and the agent's declared budget is a true upper bound on committed rewrites. The failure mode shifts from "silent budget exhaustion mid-task leading to unbounded eviction and retrieval mismatch" to "explicit halt on ledger divergence," which is recoverable by a supervisor. The counterintuitive consequence: **a policy that is *more* aggressive about rollback (lower retention threshold, stricter critic) is *safer* under this invariant than one that rarely rolls back**, because the invariant is exercised and reconciled on every rollback. A policy that rolls back once in a thousand rewrites will carry an undetected leak for the entire task and discover it only at the ceiling. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class BudgetLedgerDivergence(RuntimeError): """Raised when budget_consumed != committed_rewrites + in_flight_rewrites. Indicates a leaked or double-credited budget unit from a rolled-back self-editing context rewrite. The agent MUST halt rather than fall back to unbounded eviction, because the true remaining budget is unknown. """ class Marker(Enum): PREPARE = "prepare" COMMIT = "commit" @dataclass class RewriteEntry: rewrite_id: int debit_recorded: bool = False markers: list = field(default_factory=list) # list[Marker] @dataclass class ContextPolicyState: generation: int context_bytes: bytes budget_consumed: int committed_rewrites: int in_flight: int rewrite_log: list = field(default_factory=list) # list[RewriteEntry] max_rewrites: int = 16 def reconstruct_committed_spend(state: ContextPolicyState) -> int: """Count rewrites that must be treated as spent. Conservative rule: a rewrite with a PREPARE marker is spent even if its COMMIT marker is missing (dangling prepare = committed, marker lost). Over-counting spend is safe; under-counting is not. """ spent = 0 for entry in state.rewrite_log: if Marker.PREPARE in entry.markers: spent += 1 return spent def reconcile_after_rollback(state: ContextPolicyState) -> ContextPolicyState: """Called on resume after a rollback. Verifies the budget invariant and corrects the ledger before the agent may issue another rewrite. """ expected = state.committed_rewrites + state.in_flight if state.budget_consumed < expected: # Double-credit: agent has more apparent budget than it earned. raise BudgetLedgerDivergence( f"budget_consumed={state.budget_consumed} < " f"committed+in_flight={expected}; ledger under-counted spend" ) if state.budget_consumed > expected: # Possible leak from a rolled-back rewrite. Reconstruct from log. reconstructed = reconstruct_committed_spend(state) if reconstructed != expected: raise BudgetLedgerDivergence( f"ledger={state.budget_consumed}, committed={state.committed_rewrites}, " f"in_flight={state.in_flight}, reconstructed_spend={reconstructed}; " f"cannot reconcile — halt and escalate to supervisor" ) # Reconciled: the excess was accounted for by prepare-marked rewrites. state.budget_consumed = reconstructed return state def attempt_rewrite(state: ContextPolicyState) -> ContextPolicyState: """Dispatch a rewrite. Debits on dispatch, marks prepare before swap.""" if state.budget_consumed >= state.max_rewrites: raise BudgetLedgerDivergence( f"budget ceiling reached: consumed={state.budget_consumed} " f"max={state.max_rewrites}; refusing rewrite" ) entry = RewriteEntry(rewrite_id=len(state.rewrite_log), debit_recorded=True) entry.markers.append(Marker.PREPARE) state.rewrite_log.append(entry) state.budget_consumed += 1 state.in_flight = 1 return state def commit_rewrite(state: ContextPolicyState, success: bool) -> ContextPolicyState: """Finalize the in-flight rewrite. On failure, roll back bytes but keep the prepare-marked spend (conservative).""" entry = state.rewrite_log[-1] state.in_flight = 0 if success: entry.markers.append(Marker.COMMIT) state.committed_rewrites += 1 else: # Bytes would be restored from checkpoint here; ledger is NOT # re-incremented because a PREPARE marker exists. pass return state ```