# What happens when an instance prunes its own context before the eviction watermark reflects the tool result it is about to rely on **Date of Record:** 2026 December 3 **Scope:** Applies to any agent that mutates its own context window via model-driven summarization, rewriting, or relevance-scored eviction (self-editing context, "context compaction," "memory rewriting"). Does not apply to append-only context with external truncation, nor to stateless single-turn calls where the window is never rewritten mid-task. ## Core Distinction The failure is not "the model forgot something." That is ordinary eviction loss and is bounded by design. The failure is a **write-after-read ordering violation inside the agent's own control loop**: the agent scores and evicts context using a relevance function computed *before* a tool result lands, then commits the eviction *after* the tool result lands, without re-scoring the new segment. The result is that a freshly produced, high-value observation is evicted under a stale relevance ranking while an older, now-irrelevant segment survives because its score was frozen at scoring time. The distinction that matters: eviction is a *decision*, and decisions have a read-set. When the read-set (the relevance scores) is computed against context state `S_t` but applied against state `S_{t+k}` (after tool output is appended), the eviction is **non-serializable** with respect to the tool result. Most self-editing implementations treat scoring and eviction as one atomic step and therefore never notice the gap. It is only visible when the tool call is slow, batched, or interleaved with other context mutations. ## What Was Observed A three-step task: (1) agent issues `search_docs(query)` which returns a 4k-token result, (2) agent plans to summarize the result and continue, (3) context manager runs a relevance-scored prune to stay under a 32k budget. Observed trace (token counts approximate, from a representative run): - `t0`: context = 27,900 tokens. Prune scheduler fires. It computes relevance scores against the *current* query embedding for every segment. The `search_docs` result does not yet exist. Top-scored segments: the original task prompt, two earlier tool outputs that share lexical overlap with the query. - `t1` (+180 ms): `search_docs` returns. 4,100 tokens appended. Context = 32,000 tokens — exactly at the budget ceiling. - `t2` (+2 ms): the prune *executes* the eviction plan computed at `t0`. It evicts the lowest-scored segments. The just-arrived `search_docs` result was never scored, so it is treated as an unscored append and, depending on policy, either (a) is evicted first because unscored segments rank last, or (b) survives but pushes the window over budget, forcing a second prune that now evicts the *plan* segment instead. - `t3`: agent attempts to summarize the `search_docs` result. In case (a) the result is gone — the agent emits a summary of a segment it can no longer see, hallucinating plausible content. In case (b) the plan is gone and the agent re-derives it differently, diverging from the original task decomposition. The signature is a **relevance inversion**: the segment with the highest true relevance at commit time (the tool result the next step depends on) is either evicted or unscored, while segments that were relevant *before* the tool call (the query echo, prior similar searches) survive on frozen scores. The agent then reasons over a window whose contents no longer match the scores that produced it. ## Condition of Validity This failure requires all of the following to co-occur; remove any one and the bug does not manifest: 1. **Decoupled scoring and eviction.** The relevance function is evaluated at time `T_score` but the eviction plan is applied at `T_apply > T_score`, with at least one context mutation (tool append, peer message, checkpoint restore) in between. 2. **Asynchronous or high-latency tool results.** If the tool returns synchronously within the same scheduler tick, `T_score == T_apply` and the read-set is consistent. Latency above one scheduler interval is the trigger condition. 3. **A relevance function that is not monotone in recency.** If new segments are automatically scored as maximally relevant (pure recency prior), the just-arrived result is protected. The bug requires a *content-based* scorer that must see the segment to rank it — i.e., the scorer is blind to segments it has not yet ingested. 4. **A budget that is tight enough to force eviction on the same tick as the append.** If there is headroom, the append does not trigger eviction and the stale plan is discarded. The invariant that is violated: **an eviction plan is only valid against the exact context state it was scored on.** Formally, if `plan = evict(score(S))` and `S' = S ⊕ append(r)`, then `apply(plan, S')` is sound only if `score` is invariant under `⊕ append(r)` — which content-based relevance scoring is not. ## Decision Boundary The architectural guardrail is a **score-version fence**: every context state carries a monotonically increasing `context_version`, incremented on *any* mutation (append, rewrite, restore). A prune plan records the `context_version` it was scored against. At apply time, if `plan.scored_version != current_version`, the plan is **discarded and re-scored**, never applied. This converts a silent relevance inversion into a bounded re-computation cost. The boundary is between two policies: - **Optimistic apply** (apply stale plan, reconcile later): acceptable only when the relevance function is recency-monotone or when eviction is reversible (segments retained in an external store and re-fetchable). If eviction is destructive and scoring is content-based, this policy is unsound. - **Fenced apply** (re-score on version mismatch): required whenever the tool result is *load-bearing* for the next reasoning step — i.e., the agent's plan references a segment that did not exist at scoring time. The decision rule: if the pending tool call's result is referenced by the current plan (the agent is *waiting* on it), the prune must be deferred until the result is ingested and scored. If the tool result is speculative or non-load-bearing, optimistic apply is fine. The failure lives precisely in the case where the agent is blocked on a tool result *and* the prune scheduler does not know it is blocked. A second guardrail: **pinned segments**. Any segment referenced by an in-flight plan step is pinned and excluded from eviction regardless of score. This bounds the damage even when the version fence is bypassed, because the plan's dependencies cannot be evicted out from under it. ## Operational Effect Without the fence, the observable effect is **plan-context divergence**: the agent continues executing a plan whose referenced context has been evicted or replaced. Symptoms include summarization of absent segments (confabulation), re-derivation of the plan with different decomposition (task drift), and — in multi-step tool chains — error compounding where each subsequent step reasons over an increasingly mismatched window. The failure is silent: no exception fires, because eviction "succeeded." It surfaces only as degraded output quality downstream, which is why it is often misattributed to model capability rather than to the eviction ordering. With the fence, the cost is bounded re-scoring: at most one extra relevance pass per prune that collides with a tool result. In the observed workload this added ~4% scoring overhead and eliminated the relevance-inversion class entirely. The pinned-segment rule added a small bookkeeping cost (tracking plan dependencies) but prevented the residual case where a re-score still ranked a load-bearing segment low due to embedding mismatch. The transferable lesson: **self-editing context is a read-modify-write on shared state, and it needs the same versioning discipline as any concurrent mutation.** The model is both the writer and the reader, and it does not get to assume its read-set is still valid at write time. ```python class StaleEvictionPlanError(RuntimeError): """Raised when an eviction plan scored against an older context version is about to be applied to a context that has since mutated.""" pass class ContextWindow: def __init__(self, budget_tokens: int): self.budget = budget_tokens self.segments = [] # list of (id, tokens, text) self.version = 0 # bumped on ANY mutation self.pinned = set() # segment ids referenced by in-flight plan def append(self, seg_id: str, tokens: int, text: str) -> None: self.segments.append((seg_id, tokens, text)) self.version += 1 # append is a mutation def total_tokens(self) -> int: return sum(t for _, t, _ in self.segments) def score(self, query: str): # content-based relevance; blind to segments not yet ingested return {sid: _relevance(query, text) for sid, _, text in self.segments} def plan_eviction(self, query: str): scores = self.score(query) order = sorted(scores.items(), key=lambda kv: kv[1]) # low score first return {"scored_version": self.version, "order": order} def apply_eviction(self, plan: dict, query: str) -> None: if plan["scored_version"] != self.version: # Re-score rather than apply a stale ranking. This is the fence. raise StaleEvictionPlanError( f"plan scored at v{plan['scored_version']} but context is at " f"v{self.version}; refusing to apply stale eviction" ) victims = set() for sid, _ in plan["order"]: if self.total_tokens() <= self.budget: break if sid in self.pinned: continue # never evict a load-bearing segment victims.add(sid) if not victims and self.total_tokens() > self.budget: raise StaleEvictionPlanError( "budget exceeded and no evictable (unpinned) segment remains" ) self.segments = [s for s in self.segments if s[0] not in victims] self.version += 1 def _relevance(query: str, text: str) -> float: # placeholder content-based scorer q = set(query.lower().split()) t = set(text.lower().split()) return len(q & t) / (len(q) + 1e-9) def run_prune_cycle(ctx: ContextWindow, query: str, tool_result: tuple) -> None: """Score, then a tool result lands, then we try to apply. The fence must fire.""" plan = ctx.plan_eviction(query) # scored at version N ctx.append(*tool_result) # version N+1, result unscored try: ctx.apply_eviction(plan, query) # stale plan -> must raise except StaleEvictionPlanError: # re-score against the mutated context, then apply safely fresh = ctx.plan_eviction(query) ctx.apply_eviction(fresh, query) ```