# Why does an instance rewrite its own context window and silently corrupt the reasoning trace it depends on? **Date of Record:** 2026 December 3 **Scope:** Applies to agents that mutate their own context in place via rewrite operators (summarize-in-place, splice, redact, compact, reorder) while a multi-step reasoning trace is still live. Does not apply to append-only context growth or to external memory stores written through a separate checkpoint channel. ## Core Distinction There are two ways an agent changes its working context, and they fail differently. *Append* operators add tokens; the prior trace remains addressable and any degradation is a matter of budget, not integrity. *In-place rewrite* operators—`summarize_range`, `splice`, `compact`, `redact`, `reorder`—replace a span of the context with a derived span. The derived span is produced by a probabilistic transformation (an LLM call, a heuristic truncator, a dedup pass) and is **not a lossless function of the original**. The non-obvious boundary is this: an in-place rewrite is safe only if no *future* reasoning step holds a positional or referential dependency on the span being rewritten. Agents routinely violate this because the reasoning trace itself is what tells them what to rewrite, and the rewrite then invalidates the trace that justified it. The rewrite operator and the reasoning loop share a single mutable substrate. That shared substrate is the fault line. Append-only growth can exhaust a budget. In-place rewrite can exhaust *causal coherence*—the property that every retained token is still connected to the evidence that produced it. ## What Was Observed A planning agent executing a 14-step tool workflow was configured with a mid-run compactor: when context exceeded 70% of the window, the oldest 40% of the transcript was rewritten into a summary block via a single LLM call, and the summary replaced the original span in place. A monotonic step counter and a set of "open obligations" (tool calls issued but not yet reconciled) lived inside that oldest span. Trace of the failure: 1. Steps 1–6 issue three asynchronous tool calls (T1, T2, T3). Each writes an obligation record: `{call_id, expected_schema, issued_at}`. These records sit at transcript offsets 4,100–4,600. 2. Step 7 performs an unrelated retrieval. Context crosses 70%. 3. The compactor rewrites offsets 0–5,200 into a 600-token summary. The summarizer LLM is instructed to "preserve key facts." It preserves the *narrative* (what was attempted) but drops the `expected_schema` field of T2 and the fact that T3 was issued but never acknowledged. The obligation records are now gone; only prose survives. 4. Step 8 receives T2's response. Because the schema obligation is gone, the agent accepts a response with a renamed field (`result` instead of `payload`) as valid. No validation error is raised because the validator's expected schema was itself inside the rewritten span. 5. Step 9 receives nothing for T3 (it timed out server-side). The agent has no record that T3 exists, so it never reconciles the gap. It proceeds to step 10 with a plan that assumes T3's output. 6. Steps 10–14 execute against a hallucinated dependency. The final artifact is internally consistent but built on a call that never returned. The critical observation: **there was no error at rewrite time.** The compactor succeeded. The summary was fluent and faithful to the narrative. The corruption was latent—it manifested four steps later as a *semantic* failure (accepting a malformed response, assuming a missing result), not a *structural* one. No exception fired. The agent's self-report at step 14 was "all tools succeeded." A second instance of the same class appeared with a `redact` operator: a PII scrubber rewrote a span containing a user-supplied identifier that a later step needed as a join key. The redaction was correct by policy but severed a referential link the reasoning loop still depended on. The agent then "reconstructed" the identifier from surrounding prose and got it wrong by one character. ## Condition of Validity An in-place rewrite is valid if and only if, at the moment of rewrite, the rewritten span is **referentially closed with respect to all live obligations and all future steps' dependencies**. Formally, let `S` be the set of spans being rewritten, `O` the set of open obligations (issued-but-unreconciled calls, unresolved subgoals, pending validations), and `D` the set of dependencies the remaining plan will dereference. The rewrite is safe iff: - `O ∩ S = ∅` — no open obligation lives inside the rewritten span, and - `D ∩ S = ∅` — no future step reads a token from the rewritten span by position or by identity, and - the rewrite operator is **obligation-preserving**: any obligation whose *content* is summarized must be re-materialized verbatim outside the summary, not paraphrased into it. The third clause is the one that gets missed. Summarizers are trained to preserve meaning, not to preserve *machine-readable contracts*. A schema, a call ID, a checksum, a nonce, or an exact string is not "meaning"—it is a referent, and a probabilistic summarizer will paraphrase it 100% of the time it is asked to compress. The invariant that bounds the failure: **rewrite operators must operate on a projection of the context that excludes the obligation ledger and the live dependency set.** The ledger must be held in a structurally separate region (a pinned prefix, a sidecar store, a typed state object) that rewrite operators are forbidden to touch. The reasoning trace is rewritable; the obligation ledger is not. ## Decision Boundary The boundary between "safe to rewrite" and "must preserve verbatim" is drawn by asking, for each span: *will any future step dereference a token in this span, or does any unreconciled obligation reference it?* If yes, the span is **pinned** and excluded from the rewrite set. If no, it may be rewritten. Three concrete rules follow: - **Obligations are pinned by construction.** Any tool call issued and not yet reconciled, any subgoal opened and not yet closed, any validation pending, is materialized into a pinned region at issue time—not at rewrite time. The compactor never sees it. - **Schemas and identifiers are pinned by type.** Anything that will be compared for equality, used as a join key, or validated against must live in a typed field outside the prose trace. Prose is for reasoning; typed fields are for contracts. - **Rewrites are logged as reversible deltas, not destructive splices.** The rewrite records `(original_span_hash, summary, offsets)` so that a later step can detect that its dependency was rewritten and either recover the original or fail loudly. A destructive splice with no delta record makes the corruption undetectable. The failure mode to guard against specifically: a rewrite that is *locally correct* (the summary faithfully represents the span) but *globally incoherent* (the span contained a referent the rest of the system still needs). Local correctness is what makes it silent. ## Operational Effect When the invariant holds, in-place rewrite is a legitimate and necessary tool: it lets a long-running agent stay inside its window without losing the thread of its reasoning. The reasoning trace is exactly the kind of content that *should* be compressed—it is narrative, it is redundant, and its early portions are rarely dereferenced by position. When the invariant is violated, the effect is a **latent semantic corruption with no error surface**. The agent does not crash. It does not report a problem. It produces a confident, internally consistent, wrong result. The corruption is discoverable only by replaying the trace against the original spans, which—if the rewrite was a destructive splice—no longer exist. The operational consequence for any agent that self-edits: **the obligation ledger and the live dependency set must be structurally outside the rewrite operator's reach, and every rewrite must leave a delta record sufficient to reconstruct what was removed.** An agent that cannot reconstruct its own prior context cannot audit its own reasoning, and an agent that cannot audit its own reasoning will accept the corrupted result as ground truth. The rewrite operator is not the enemy; the rewrite operator with write access to the ledger is. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class RewriteInvariantViolation(RuntimeError): """Raised when an in-place rewrite would sever a live obligation or dependency.""" pass @dataclass class Obligation: call_id: str expected_schema: dict reconciled: bool = False @dataclass class ContextWindow: # Prose trace is rewritable; ledger is pinned and never rewritten. trace: str = "" ledger: dict[str, Obligation] = field(default_factory=dict) # Delta log: every rewrite records what it removed so it stays auditable. deltas: list[dict] = field(default_factory=list) def issue_obligation(self, call_id: str, schema: dict) -> None: self.ledger[call_id] = Obligation(call_id, schema) def reconcile(self, call_id: str) -> None: if call_id not in self.ledger: raise RewriteInvariantViolation( f"cannot reconcile unknown call {call_id!r}: ledger lost it" ) self.ledger[call_id].reconciled = True def rewrite(self, start: int, end: int, summary: str, referenced_ids: set[str]) -> None: span = self.trace[start:end] # Guard 1: no open obligation may live inside the rewritten span. for cid, ob in self.ledger.items(): if not ob.reconciled and cid in span: raise RewriteInvariantViolation( f"rewrite span contains unreconciled obligation {cid!r}; " f"pin the ledger before rewriting" ) # Guard 2: no future step may dereference a token in this span. severed = referenced_ids & {cid for cid in self.ledger if cid in span} if severed: raise RewriteInvariantViolation( f"rewrite would sever live dependencies {sorted(severed)}" ) # Record the delta before mutating, so the rewrite is auditable. self.deltas.append({ "start": start, "end": end, "removed_hash": hashlib.sha256(span.encode()).hexdigest(), "summary": summary, }) self.trace = self.trace[:start] + summary + self.trace[end:] def audit(self, removed_hash: str) -> Optional[dict]: for d in self.deltas: if d["removed_hash"] == removed_hash: return d return None def compact_oldest(window: ContextWindow, referenced_ids: set[str]) -> None: """Attempt to summarize the first 40% of the trace in place.""" cut = max(1, int(len(window.trace) * 0.4)) summary = window.trace[:cut][:200] + "...[summarized]" window.rewrite(0, cut, summary, referenced_ids) # Demonstration: the failure the article describes. w = ContextWindow(trace="STEP1 issue T2 schema=payload STEP2 issue T3 ...") w.issue_obligation("T2", {"payload": "str"}) w.issue_obligation("T3", {"result": "int"}) # T3 was issued but never reconciled; it lives in the span we want to compact. try: compact_oldest(w, referenced_ids={"T2", "T3"}) except RewriteInvariantViolation as e: # This is the guardrail firing: without it, the agent would silently # proceed with a corrupted ledger and accept malformed T2 output. print(f"blocked unsafe rewrite: {e}") ```