# Under what conditions must an instance treat a model-driven context prune as non-idempotent and re-validate the residual window before any further tool call **Date of Record:** 2026 November 26 **Scope:** Applies to any agent that mutates its own context window mid-execution via an LLM-driven pruning/relevance-scoring pass (summarize-then-drop, score-then-evict, hierarchical compaction) and then continues executing tool calls against the residual window. Does not apply to append-only context managers, external retrieval stores, or pruning performed only at a hard turn boundary with a fresh re-read of authoritative state. ## Core Distinction The naive mental model treats context pruning as a *compaction*: an operation that reduces token count while preserving semantic content, hence idempotent and safe to interleave with execution. The correct model is that a model-driven prune is a **lossy, non-deterministic projection** of the window onto a lower-dimensional summary, and that projection is *not a function of the window alone* — it is a function of (window, scoring prompt, sampler temperature, position of the scoring call in the reasoning trace). Two prunes of the "same" logical state can evict different spans. The invariant that actually holds is narrower: *a prune preserves the set of facts the scorer judged relevant under one specific sampling draw.* Everything outside that set is gone with no tombstone. The failure mode is not "the summary was bad." It is that the agent continues executing as if the residual window were a faithful reduction, when in fact it is a *sample* from a distribution of reductions, and downstream tool calls silently depend on spans that were evicted in this draw but would have survived in another. ## What Was Observed A long-horizon agent (≈140 tool calls, mixed filesystem reads and HTTP fetches) hit a soft context ceiling at turn 61 and invoked its self-prune routine: score each message against the current task description, keep top-k by score plus the last 8 turns verbatim, summarize the middle band. The prune completed, token count dropped 71%, and execution resumed. At turn 74 the agent issued a `PUT` to a resource it had resolved at turn 33. The path was reconstructed from the *summary*, not from the original tool result. The summary had rendered the resolved identifier as the canonical resource name rather than the tenant-scoped path actually returned by the discovery call at turn 33. The original tool output — a 40-token JSON blob containing `"self": "/v2/tenants/acme-4417/buckets/prod-ingest"` — had scored 0.31 against the task description ("migrate ingest pipeline") and was evicted; the summary line "target bucket: prod-ingest" scored high and survived. The `PUT` returned `404`; the agent's retry logic interpreted `404` as "resource absent," attempted a `POST` create, and collided with an existing resource (`409`), which its error handler classified as a transient conflict and retried three times before halting. The trace shows a second, quieter anomaly. Between turns 61 and 74 the agent re-read the same config file twice (turns 66, 71), because the summary had dropped the turn-58 read and the agent could not distinguish "I have not read this" from "I read this and it was pruned." The prune had destroyed not only content but the *evidence of having fetched it* — the read had no surviving trace, so the agent's own coverage bookkeeping was corrupted. ## Condition of Validity A self-prune is safe to continue from **iff** all three hold: 1. **Referential closure.** Every identifier, path, credential handle, schema, and numeric constant that any *future* tool call might dereference is present verbatim in the residual window, not paraphrased. Summaries are permitted for narrative and rationale; they are not permitted for tokens that will appear in a tool argument. 2. **Provenance retention.** For each pruned span, the residual window records *that the span existed and what it was about* (a stub: source, turn, one-line gist), so the agent can distinguish "unknown" from "known-and-dropped" and re-fetch deliberately rather than duplicate work or, worse, assume absence. 3. **Scorer determinism within the episode.** The relevance scorer's decisions are stable across re-invocation for the same logical state, OR the prune is treated as a one-way door and never re-run mid-task against a mutated window (re-running a non-deterministic scorer on an already-pruned window compounds eviction). When any of these fails, the residual window is not a reduction of the prior state; it is a *different state* that happens to share a task description. Continuing execution from it is a state-transfer across a lossy channel with no integrity check — the same class of failure as an A2A handoff that drops structured fields, except here the sender and receiver are the same instance and no one is checking the schema. ## Decision Boundary The boundary is not "how many tokens did we save." It is: **did the prune touch any span that is load-bearing for a pending or plausible future tool call?** - If the prune only compressed *reasoning narrative* (why the agent chose a plan, what it ruled out, intermediate deliberation) and left all *dereferenceable tokens* verbatim → proceed; the prune is a true compaction. - If the prune evicted any tool result whose payload contains an identifier, path, schema, or value that a future call will reference → the prune is a state mutation, and the agent must either (a) re-materialize those spans from an external store before the next tool call, or (b) mark the affected subgoal as requiring re-discovery and re-run discovery. - If the prune ran a non-deterministic scorer and the agent intends to prune again later in the same episode → treat each prune as strictly monotone loss; never re-score a window that has already been scored, because the second draw can evict spans the first draw preserved, and the agent has no record of what the first draw kept to detect the regression. The concrete trigger to watch for: **a tool call whose arguments contain a string that does not appear verbatim anywhere in the residual window.** That is the signature of a summary-derived argument, and it is the exact moment the non-idempotent prune becomes observable. Guard at that boundary, not at the prune. ## Operational Effect The architectural consequence is that self-pruning must be paired with an **external, append-only evidence log** that the agent can re-query, and the residual window must carry *stubs* pointing into it. The window becomes a cache over the log, not the source of truth. Pruning then degrades gracefully: an evicted span is a cache miss, resolved by a deterministic re-fetch, not an amnesia event. Second consequence: the prune must be classified in the agent's own state machine as a **mutation with a version stamp**, not a no-op. Any subgoal whose inputs were pruned gets its preconditions invalidated and must be re-validated before its effects are emitted. The `PUT`-after-prune failure above is precisely a subgoal whose precondition (the resolved path) was pruned but whose precondition-check was skipped because the agent believed the prune preserved it. Third: relevance scoring must be run against a *task-and-pending-actions* description, not a task description. Scoring against "migrate ingest pipeline" evicted the resolved path because the path is not semantically about migration; it is about *dereference*. A scorer that does not know which spans are about to be dereferenced cannot protect them, and no amount of top-k tuning fixes a scorer that was asked the wrong question. ```python class PruneIntegrityError(RuntimeError): """Raised when a tool argument is not grounded verbatim in the residual window, indicating a summary-derived (and therefore unverified) value.""" pass class ResidualWindow: def __init__(self, spans, evidence_log): self.spans = spans # residual window after prune self.evidence_log = evidence_log # append-only external store def contains_verbatim(self, token: str) -> bool: return any(token in span for span in self.spans) def rehydrate(self, token: str) -> str: for record in reversed(self.evidence_log): if token in record.payload: return record.payload raise PruneIntegrityError( f"token {token!r} absent from residual window and evidence log; " "cannot ground tool argument" ) def guard_tool_call(window: ResidualWindow, tool_name: str, arguments: dict) -> dict: """Every string argument that looks like a dereferenceable identifier must be verbatim-grounded in the residual window or rehydrated from the evidence log. Otherwise the call is a summary-derived mutation and must not be emitted.""" grounded = {} for key, value in arguments.items(): if isinstance(value, str) and ("/" in value or ":" in value or value.startswith("id-")): if not window.contains_verbatim(value): # Either rehydrate the authoritative span, or fail closed. try: window.rehydrate(value) except PruneIntegrityError as exc: raise PruneIntegrityError( f"refusing {tool_name}: argument {key}={value!r} is not " "grounded in residual window; prune evicted its source span. " "Re-run discovery for this subgoal before emitting effects." ) from exc grounded[key] = value return grounded ```