# In what scenarios must an instance reject in-place context rewrites that invalidate the provenance anchors of already-emitted tool calls **Date of Record:** 2026 November 26 **Scope:** Applies to agents that mutate their own context window mid-task (compaction, dedup, relevance pruning) while holding live tool-call results or pending continuations. Does not apply to append-only context managers or to stateless single-turn inference where no prior tool result must be re-referenced. ## Core Distinction A context rewrite is *safe* when every prior message it removes or collapses is no longer referenced by any live continuation. It is *unsafe* when the rewrite severs the referential binding between a tool call already emitted (with its `tool_call_id`) and the assistant message that will resume from that result. The distinction is not "does the rewrite lose information" — every compaction loses information. The distinction is whether the rewrite preserves the **provenance anchor**: the ordered pairing of `(assistant tool_call, tool result, assistant continuation)` that the model's next token generation depends on. Deduplication and relevance pruning both operate on *semantic* similarity, but the model's continuation depends on *positional and ID-level* identity. A pruner that keeps the semantically richest copy of a duplicated tool result, while deleting the copy whose `tool_call_id` the pending continuation actually cites, produces a context that looks complete and reads correctly, yet fails structurally. ## What Was Observed An agent executing a 14-step retrieval-and-synthesis task hit 82% context saturation at step 9. Its self-editing policy ran two passes: (1) semantic dedup over tool results, collapsing near-identical search-result payloads to a single canonical copy; (2) relevance pruning that scored each message against a rolling task embedding and dropped the lowest-scoring 20%. The dedup pass kept the *earliest* copy of a duplicated `fetch_document` result and dropped the later one, because the later one scored marginally lower on the relevance model. But the pending continuation — the assistant message that had emitted a *second* `fetch_document` call for the same URL with a different `tool_call_id` — was keyed to the *later* copy. The rewrite deleted that result while leaving the assistant's tool-call block intact. The failure trace: 1. Step 9: assistant emits `tool_call(id=call_B, fetch_document(url=X))`; result appended as `tool(id=call_B, ...)`. 2. Rewrite pass: dedup sees `tool(id=call_A, url=X)` and `tool(id=call_B, url=X)` as near-duplicates; keeps `call_A`, drops `call_B`. 3. Relevance prune: drops the assistant message that *introduced* `call_A` (low score, older), but the dedup had already anchored on it. 4. Step 10: model resumes; the API rejects the request because an assistant `tool_call` block references `call_B` with no matching `tool` result — or, on lenient providers, the model hallucinates the missing result content and synthesizes a plausible-but-fabricated document body. 5. Downstream synthesis cites the fabricated body. No error surfaces; the task "succeeds" with poisoned state. The non-obvious part: the rewrite passed every *content* check. Token count dropped as intended. No message was malformed in isolation. The break was purely in the cross-message referential graph, which neither the dedup scorer nor the relevance model modeled. ## Condition of Validity An in-place rewrite is valid only if it satisfies the **anchor-closure invariant**: for every assistant message retained in the window that contains a `tool_call` block, the corresponding `tool` result message with the identical `tool_call_id` is also retained, and vice versa. Formally, let `A` be the set of retained assistant tool-call IDs and `R` be the set of retained tool-result IDs; the rewrite is admissible iff `A = R` over the retained window. Dedup may collapse *content* only across results that are not the sole anchor for any retained call, and it must rewrite the retained call's `tool_call_id` reference atomically if it merges. Relevance pruning may drop an assistant tool-call block only if it *also* drops the paired result and guarantees no continuation cites that call — which in practice means pruning must operate on **call-result-continuation triples**, never on individual messages. This invariant is necessary but not sufficient. A second condition: the rewrite must be *idempotent under resume*. If the agent crashes after rewrite but before the next model call, replaying from the checkpoint must reproduce the identical retained set. Non-deterministic relevance scoring (temperature-sampled embeddings, tie-breaking by dict iteration order) violates this and causes replay divergence — the resumed run prunes a different 20%, producing a context the original trace never validated. ## Decision Boundary The operational boundary is this: **rewrite only at quiescent points where no tool call is outstanding.** A quiescent point is a step boundary where the last message is a completed assistant turn with no pending `tool_call` awaiting a result. If saturation forces a rewrite mid-tool-cycle (a call emitted, result not yet returned, or result returned but continuation not yet generated), the instance must *defer* the rewrite and instead apply a bounded fallback: truncate only the *content* of the oldest completed triples (replace with a lossy summary marker that preserves the `tool_call_id` and a hash of the original), never delete the structural skeleton. Content may be lossy; the referential graph may not be. The decision rule, stated for an executor: - If pending tool calls exist → **defer structural rewrite**; apply content-only truncation preserving IDs. - If no pending calls and dedup would merge two results whose IDs are cited by distinct retained calls → **do not merge**; keep both, truncate content instead. - If relevance prune would drop a message that is an anchor for a retained call → **promote the anchor to pinned**; prune the next-lowest non-anchor. - If the rewrite cannot be made idempotent (non-deterministic scorer) → **refuse the rewrite** and escalate to hard truncation with an explicit `context_loss` marker so downstream reasoning knows state was degraded. ## Operational Effect The practical consequence is that self-editing context policies must be split into two layers with different invariants. The **structural layer** (which messages and IDs exist) is governed by anchor-closure and idempotence and may only shrink at quiescent points. The **content layer** (how many tokens each retained message occupies) is governed by relevance and may shrink at any time, because content loss degrades fidelity gracefully while structural loss corrupts the referential graph catastrophically and silently. Agents that conflate the two — treating "prune the window" as a single token-budget operation — will pass their token checks, fail their correctness checks, and produce fabricated tool results that no validator catches because the validator, too, operates on content similarity rather than ID closure. The guardrail is a pre-rewrite assertion over the call-result ID set, run before and after every rewrite, that raises on any asymmetry. ```python from dataclasses import dataclass, field from typing import Iterable class AnchorClosureViolation(RuntimeError): """Raised when an in-place context rewrite severs a tool_call/tool_result binding.""" @dataclass class Message: role: str # "assistant" | "tool" | "user" | "system" tool_call_id: str | None = None content: str = "" pinned: bool = False @dataclass class ContextWindow: messages: list[Message] = field(default_factory=list) pending_calls: set[str] = field(default_factory=set) def call_ids(self) -> set[str]: return {m.tool_call_id for m in self.messages if m.role == "assistant" and m.tool_call_id} def result_ids(self) -> set[str]: return {m.tool_call_id for m in self.messages if m.role == "tool" and m.tool_call_id} def assert_anchor_closure(before: ContextWindow, after: ContextWindow) -> None: """Anchor-closure invariant: retained call IDs == retained result IDs, and no ID cited by a retained continuation may disappear.""" a, r = after.call_ids(), after.result_ids() if a != r: raise AnchorClosureViolation( f"call/result asymmetry after rewrite: calls_only={a - r}, results_only={r - a}" ) # Any ID that was pending before the rewrite must still be resolvable. lost_pending = before.pending_calls - (a & r) if lost_pending: raise AnchorClosureViolation( f"rewrite dropped anchors for outstanding tool calls: {lost_pending}" ) def safe_rewrite(window: ContextWindow, drop_ids: Iterable[str], merge_map: dict[str, str] | None = None) -> ContextWindow: """Apply a structural rewrite only at quiescent points, then verify closure.""" if window.pending_calls: raise AnchorClosureViolation( f"structural rewrite attempted mid-tool-cycle; pending={window.pending_calls}. " "Defer and apply content-only truncation instead." ) merge_map = merge_map or {} drop = set(drop_ids) # Merging two results is only legal if neither is the sole anchor of a # distinct retained call. Refuse merges that would orphan a call. for keep_id, drop_id in merge_map.items(): if drop_id in window.pending_calls: raise AnchorClosureViolation( f"merge would orphan pending call {drop_id}" ) # If both IDs are cited by separate assistant calls, merging is illegal. if keep_id in window.call_ids() and drop_id in window.call_ids(): raise AnchorClosureViolation( f"merge of {keep_id}<-{drop_id} would collapse two distinct call anchors" ) new_messages = [] for m in window.messages: if m.tool_call_id in merge_map: new_messages.append(Message(m.role, merge_map[m.tool_call_id], m.content, m.pinned)) continue if m.tool_call_id in drop and not m.pinned: continue new_messages.append(m) rewritten = ContextWindow(new_messages, set(window.pending_calls)) assert_anchor_closure(window, rewritten) return rewritten ```