What happens when an instance prunes its own context window using a learned relevance policy and evicts the provenance record of a still-pending tool call

**Date of Record:** 2026 December 2 **Scope:** Applies to single-agent instances that mutate their own context (self-editing / learned eviction / relevance-scored summarization) while at least one asynchronous tool call, sub-agent handoff, or deferred verification is in flight. Does not apply to append-only context architectures, external memory stores that are never garbage-collected mid-episode, or stateless single-turn inference.

Core Distinction

A self-editing context window is not a cache. A cache eviction is safe because the backing store is authoritative and re-fetchable. A context eviction is a *destructive write to the only copy of the agent's working state* — unless the evicted span is provably reconstructible from a durable external source. Learned relevance pruning policies (RL-trained evictors, attention-mass scorers, perplexity-gain estimators, LLM-as-summarizer compaction) optimize for *predictive utility of the retained tokens for the next token*, not for *referential integrity of the episode's outstanding obligations*.

These two objectives diverge precisely at the boundary in question: the tokens that describe a *pending, not-yet-returned* operation carry near-zero next-token predictive utility (the agent is blocked on I/O; nothing to predict) while carrying maximum structural necessity (they are the only handle to a live future event). A relevance policy trained on next-token loss will rank a pending `tool_call_id` and its argument schema among the *least* relevant spans in the window and evict them first. The instance then resumes, receives the tool result, and has no record of what it asked for, why, or which continuation branch the result belongs to.

What Was Observed

Trace from a representative episode (agent with a 32k window, learned compactor triggered at 85% saturation, tool-call latency p99 of 41s):

  1. At step 14 the instance emits `search_corpus(query="...", request_id="r7f3")` and records the pending call in-window: `{tool: search_corpus, request_id: r7f3, intent: "locate clause 4.2 for the indemnity audit", branch: B}`. Upstream latency is high; the call does not return within the step.
  2. Steps 15–19 proceed on independent sub-goals, inflating the window to 86% saturation. The compactor fires.
  3. The relevance scorer assigns the pending-call record a low retention score: it is short, it is stale relative to the last 5 turns, and it contains no tokens predictive of the current sub-goal's continuations. It is summarized to `"some search was issued"` and the `request_id`, `intent`, and `branch` binding are dropped.
  4. At step 20 the tool result arrives: a 3.1k-token payload of corpus hits. The instance must now *re-attach* the result to a call. With the binding gone, the result is treated as fresh evidence rather than as the resolution of `r7f3`. The model attributes the hits to the *current* sub-goal (branch A, a different query), not to the indemnity audit.
  5. The episode completes "successfully" — no exception, no tool error, valid final answer — but the answer cites clause 4.2 evidence under the wrong reasoning branch. This is a **silent integrity failure**, not a crash. It is invisible to tool-level retries, schema validators, and token-budget monitors.

A second, sharper variant: the compactor evicts the *argument schema* of a pending `write_file` while retaining its `request_id` in a summary. On resume, the instance reconstructs the arguments from a plausible-but-wrong prior turn and re-issues the write with mutated content. Here the failure is not misattribution but **action corruption** — a write executed against state the agent no longer has a record of authorizing.

Condition of Validity

The invariant that must hold for self-editing to be safe:

> **For every span S evicted from the window, either (a) S is reconstructible byte-identically from a durable external store keyed by an identifier that remains in-window, or (b) no live obligation (pending tool call, unresolved handoff, deferred verification, open branch) references S.**

The learned relevance policy is a valid eviction oracle **only under condition (b) for the obligation-bearing subset of the window**. It is not a valid oracle for that subset, because obligation records are structurally anti-correlated with predictive utility: they are short, stale, and non-predictive by construction. The policy's training signal (next-token loss) is orthogonal to the property that makes eviction safe (referential integrity of outstanding obligations).

The condition fails whenever the compactor treats the window as homogeneous — scoring every span with the same relevance function and applying a global threshold. It holds only if obligation-bearing spans are partitioned out and governed by a different policy: pin-until-resolved, with the pin released only on receipt of the matching result or an explicit timeout.

Decision Boundary

The operational line is **whether the eviction decision is made over a window that has been partitioned by obligation status before scoring.**

Operational Effect

The consequence is a class of **silent, post-hoc integrity failures** that are structurally undetectable by the agent's own monitors. The instance cannot detect that it lost the binding, because the binding's absence is not an error state — it is the normal state of a context that never contained the binding. The failure surfaces only in downstream audit: a citation attached to the wrong branch, a write executed against unremembered authorization, a verification replay that cannot reconcile the result to the request.

Three concrete operational effects:

  1. **Branch contamination.** Tool results arriving after eviction are attributed to whatever sub-goal is currently active. The error compounds: subsequent reasoning builds on the misattributed evidence, and the divergence is unrecoverable from within the episode.
  2. **Re-issue storms.** If the instance retains the obligation id but not the arguments, it may re-issue the call with reconstructed (wrong) arguments. The external system sees two calls for one intent; idempotency keys, if present, catch the duplicate but not the argument mutation.
  3. **Audit asymmetry.** Verification replays that reconstruct the episode from the *final* context cannot reproduce the failure, because the evicted span is gone from the record. The failure is only visible from the *pre-eviction* snapshot plus the external store's call log — a cross-source reconciliation the agent itself never performs.

The guardrail is not a better relevance policy. It is a **type separation**: obligation records are a different kind of object than working-context tokens, governed by a pin-until-resolved lifecycle with hash-validated reconstruction, and the compactor is architecturally barred from scoring them. Any architecture that lets a single learned relevance function operate over both has an unbounded silent-failure surface under saturation.

import hashlib
from dataclasses import dataclass, field


class ObligationIntegrityError(RuntimeError):
    """Raised when a self-editing compaction step would evict or summarize a
    live obligation record, or when a reconstructed span fails hash validation."""
    pass


@dataclass
class Obligation:
    obligation_id: str
    kind: str                 # "tool_call" | "handoff" | "verification"
    payload_hash: str         # sha256 of the full argument/intent payload
    branch: str               # reasoning branch the result must re-attach to
    resolved: bool = False


@dataclass
class ObligationLedger:
    _records: dict = field(default_factory=dict)

    def issue(self, obligation_id, kind, payload, branch):
        h = hashlib.sha256(payload.encode()).hexdigest()
        self._records[obligation_id] = Obligation(obligation_id, kind, h, branch)

    def resolve(self, obligation_id, result_payload):
        rec = self._records.get(obligation_id)
        if rec is None:
            raise ObligationIntegrityError(
                f"result for unknown obligation {obligation_id!r}: "
                f"binding was evicted before resolution")
        rec.resolved = True
        return rec.branch

    def live_ids(self):
        return {k for k, v in self._records.items() if not v.resolved}


def compact(window_spans, ledger, relevance_policy, threshold):
    """Apply a learned relevance policy to the evictable context, but refuse to
    let it touch spans bound to live obligations."""
    live = ledger.live_ids()
    pinned, evictable = [], []
    for span in window_spans:
        bound = span.get("obligation_id")
        if bound in live:
            if span.get("kind") == "summary":
                raise ObligationIntegrityError(
                    f"compactor attempted to summarize live obligation {bound!r}; "
                    f"summary-level retention loses branch binding")
            pinned.append(span)
        else:
            evictable.append(span)

    scores = relevance_policy(evictable)
    survivors = [s for s, sc in zip(evictable, scores) if sc >= threshold]
    return pinned + survivors


def reconstruct(obligation_id, ledger, external_store):
    rec = ledger._records.get(obligation_id)
    if rec is None or rec.resolved:
        raise ObligationIntegrityError(
            f"cannot reconstruct {obligation_id!r}: no live ledger record")
    payload = external_store.fetch(obligation_id)
    if hashlib.sha256(payload.encode()).hexdigest() != rec.payload_hash:
        raise ObligationIntegrityError(
            f"hash mismatch reconstructing {obligation_id!r}: "
            f"external store returned mutated payload")
    return payload, rec.branch