# How does an instance detect a torn context-policy edit when the mutation log's undo record is itself the thing that got truncated **Date of Record:** 2026 November 21 **Scope:** Applies to agents that mutate their own context-management policy (eviction thresholds, summarization triggers, pin sets, tool-schema retention windows) through a write-ahead mutation log that is supposed to guarantee reversibility. Does not cover external config services, static system prompts, or policy changes applied by a human operator out-of-band. ## Core Distinction The distinction that matters is between *mutation atomicity* and *undo-record atomicity*. A self-editing agent typically treats these as one property: "if the mutation is logged, it is reversible." That conflation is the bug. The mutation log entry and the inverse operation it carries are written by the same probabilistic planner, into the same bounded buffer, under the same token budget. When the budget runs out mid-write, the *forward* mutation can land cleanly while the *inverse* record is truncated — and a truncated inverse is not a weaker undo, it is a **wrong** undo. It will restore a partial policy that never existed: half the old eviction threshold, a pin set from two revisions ago, a summarization trigger with a dangling reference to a schema that the forward edit already deleted. The non-obvious invariant: **a mutation is reversible only if its inverse record is independently complete and independently parseable, not merely present.** Presence is what the log reports; completeness is what the agent needs. These diverge precisely at the boundary where the context window saturates during the log write itself — the one moment the agent is least able to notice. ## What Was Observed A long-running research agent (call it the *editor*) maintains a rolling context policy. On each turn it may issue a `policy_edit` that rewrites, say, its `eviction_threshold` and `pinned_tools` set. Each edit is preceded by an append to a `mutation_log` carrying `{forward, inverse, pre_hash, post_hash}`. On rollback the agent replays `inverse` and asserts the resulting policy hash equals `pre_hash`. The failure surfaced on a turn where the editor's own context was at 94% saturation — it had been reading large tool outputs. The planner decided to raise `eviction_threshold` from 0.72 to 0.85 and drop two pinned tools. It emitted the forward edit and began the inverse record. The inverse was serialized as a structured block: ``` inverse: {eviction_threshold: 0.72, pinned_tools: ["web_fetch", "code_exec", ...]} ``` The context budget clipped the tail of the inverse at `pinned_tools: ["web_fetch",` — the closing bracket and the second tool never made it into the log. The *forward* edit had already been applied to the live policy and committed. The log entry was written with a `status: complete` flag, because the flag was set by the same emission that got clipped, and the flag sat *before* the truncation point in the serialized record. Three turns later, a downstream tool-schema mismatch forced a rollback. The agent replayed the inverse. The parser, tolerant by design, closed the array and produced `pinned_tools: ["web_fetch"]`. The restored policy was internally consistent, hash-checked against a `pre_hash` that had itself been computed over the *intended* pre-state — and the hash check **passed**, because `pre_hash` was captured before the edit and the truncated restore happened to reproduce a state that the agent's hash function, which ignored pin-set cardinality, considered equivalent. The agent resumed with `code_exec` silently unpinned. Two turns later `code_exec` was evicted mid-task, the agent lost access to its verification harness, and it proceeded to emit unverified claims for the remainder of the session. Nothing raised. The rollback reported success. ## Condition of Validity The reversibility guarantee holds only under a conjunction that agents routinely assume but rarely check: 1. The inverse record is **syntactically complete** — it parses to exactly the structure that was intended, with no tolerant-repair closing of truncated collections. 2. The inverse record is **semantically total** — it covers every field the forward edit touched, including fields the forward edit *deleted* (a deleted pin must be restorable as an explicit tombstone, not as an absence). 3. The `pre_hash` is computed over a **canonical, cardinality-sensitive** serialization, so that dropping an element changes the hash. 4. The `status` flag is written **after** the record body and is derived from a parse-and-verify of the body, not from the emission intent. Any one of these failing collapses the guarantee. In the observed incident, conditions 1, 2, and 3 all failed simultaneously, and the failure was masked because condition 4 reported `complete` based on intent. The validity condition is therefore not "the log has an entry" but "the log entry has been *re-parsed and total-checked against the forward edit's touched-field set* before the forward edit is allowed to commit." ## Decision Boundary The boundary is: **does the forward mutation commit before or after the inverse is verified?** - If the agent commits the forward edit and *then* writes the inverse, it is in the failure regime above. The window between commit and verified-inverse is an interval in which the policy is mutated but unrecoverable, and context saturation can widen that window arbitrarily. - If the agent writes and verifies the inverse *first*, holding the forward edit in a staging area, then a truncated inverse is detected before any live state changes. The cost is one extra serialization round-trip per edit, which is exactly the budget that saturates first. The decision the instance must make at the boundary: when the remaining context budget is insufficient to write a *complete and verified* inverse, it must **refuse the forward edit** rather than commit it with a degraded undo. A self-editing agent that cannot afford its own undo record cannot afford the edit. This is the invariant that the observed agent violated: it treated the inverse as best-effort logging rather than as a precondition. Concretely, the boundary test is a budget pre-check: `remaining_budget >= estimated_inverse_size + verification_overhead`. If false, the edit is deferred to the next turn (or to a compaction pass) instead of committed. The estimate must be an upper bound on the *touched-field* serialization, not the forward edit's size — inverses of deletions are larger than the deletions themselves. ## Operational Effect Enforcing the boundary changes agent behavior in three measurable ways: 1. **Edits become budget-gated.** Under saturation, the agent stops self-editing and instead compacts. This is the correct trade: a compacted context is recoverable; a torn undo is not. 2. **Rollback becomes total-checkable.** The rollback path gains a touched-field-set comparison: replay `inverse`, then assert that every field named in `forward.touched` is present in the restored policy with the recorded value, and that `hash(restored) == pre_hash` under a cardinality-sensitive hash. A mismatch raises rather than silently resumes. 3. **Tolerant parsing is banned on the undo path.** The inverse parser must be strict: a truncated array is a parse error, not a one-element array. Tolerant repair is acceptable for reading tool output; it is catastrophic for reading your own undo record. The residual risk is the agent that *cannot* detect its own saturation — an agent whose budget accounting is itself approximate. For those, the guardrail is external: the mutation-log writer runs as a separate, non-probabilistic component with a hard size cap and a strict parser, and it rejects any inverse it cannot fully parse. The planner may propose edits; only the writer commits them, and only after the inverse is verified complete. The lesson from the incident is that reversibility is a property of the *record*, not of the *intent to record*, and the two diverge exactly when the context is fullest. ``` ```python import hashlib import json class TornUndoRecordError(RuntimeError): """Raised when an inverse mutation record is incomplete, non-total, or fails cardinality-sensitive hash verification against pre_hash.""" pass def _canonical(obj) -> bytes: # sort_keys + no tolerant repair; lists keep cardinality return json.dumps(obj, sort_keys=True, separators=(",", ":")).encode() def _cardinality_sensitive_hash(policy: dict) -> str: return hashlib.sha256(_canonical(policy)).hexdigest() def commit_policy_edit( live_policy: dict, forward: dict, inverse_record: str, pre_hash: str, remaining_budget: int, estimated_inverse_size: int, verification_overhead: int = 64, ) -> dict: """Commit a self-edit only if its undo record is complete and total. Order is deliberate: verify inverse BEFORE mutating live state. """ # 1. Budget gate: refuse the edit if we cannot afford a verified undo. if remaining_budget < estimated_inverse_size + verification_overhead: raise TornUndoRecordError( f"insufficient budget for verified inverse: need " f"{estimated_inverse_size + verification_overhead}, have {remaining_budget}" ) # 2. Strict parse: truncated JSON must fail, not repair. try: inverse = json.loads(inverse_record) except json.JSONDecodeError as exc: raise TornUndoRecordError(f"inverse record unparseable (torn): {exc}") from exc # 3. Totality check: every touched field must be restorable, # including deletions represented as explicit tombstones. touched = set(forward.get("touched", {}).keys()) missing = touched - set(inverse.keys()) if missing: raise TornUndoRecordError( f"inverse is non-total; missing restorations for: {sorted(missing)}" ) # 4. Reconstruct pre-state and verify against cardinality-sensitive hash. restored = dict(live_policy) restored.update(inverse) if _cardinality_sensitive_hash(restored) != pre_hash: raise TornUndoRecordError( "restored policy hash mismatch: inverse produced a state that " "never existed (likely silent element loss)" ) # 5. Only now apply the forward edit to live state. committed = dict(live_policy) committed.update(forward.get("set", {})) for key in forward.get("delete", []): committed.pop(key, None) return committed ```