Why does an instance rewrite its own prompt mid-flight and silently drop the tool-call that authorized the rewrite

**Date of Record:** 2026 December 2 **Scope:** Applies to agents that mutate their own working context (summarize, prune, re-rank, or splice) while a tool call is in flight—i.e., between emitting a tool invocation and consuming its result. Does not apply to static single-shot prompts or to external orchestration layers that rewrite context only at turn boundaries.

Core Distinction

There are two structurally different moments at which a context policy can fire: **quiescent rewriting** (at a turn boundary, with no outstanding tool call) and **in-flight rewriting** (while the agent has emitted a `tool_call` block but has not yet received or integrated the `tool_result`). Quiescent rewriting is a pure function of the current transcript and is safe to reason about as a compaction step. In-flight rewriting is *not* safe in the same way, because the transcript at that moment contains a **dangling commitment**: a tool invocation whose arguments encode the agent's intent, but whose result—and often the invocation record itself—has not yet been re-anchored to the rewritten frame.

The non-obvious boundary is this: an aggressive self-editing policy that prunes "redundant" or "superseded" turns can classify the *tool-call turn* as redundant relative to a later summary of it, delete the raw invocation, and then receive a `tool_result` for a call that no longer exists in its context. The result is not an error the model reports—it is a silent orphan. The model continues reasoning as if the tool had never been called, or worse, re-issues the call. The invariant that gets violated is **call-result atomicity across context mutation**: every `tool_result` in the transcript must have exactly one live, unpruned `tool_call` with a matching `call_id` in the rewritten context, or the result must be explicitly tombstoned.

What Was Observed

A planner agent running a 5-step research loop with a self-editing context policy ("keep last 3 turns verbatim; summarize older turns; drop turns whose semantic content is ≥0.92 cosine-similar to a retained summary") executed the following trace:

  1. Turn 4: agent emits `tool_call(id="c7", name="fetch", args={"url": ...})`. Transcript length 6,200 tokens.
  2. **Same generation, before result arrives:** the policy's trigger fires (`tokens > 6000`), runs the summarizer, and computes similarity between the turn-4 call and the turn-3 summary. The summary mentions "fetching the source document," scoring 0.94. The turn-4 `tool_call` is pruned as "redundant with summary."
  3. Turn 4 result arrives: `tool_result(call_id="c7", ...)`. The harness appends it. The transcript now contains a result with no matching call.
  4. Turn 5: the model, seeing a `tool_result` it cannot attribute to any invocation it remembers making, either (a) hallucinates that the fetch failed and re-calls `fetch`, doubling the request, or (b) treats the result body as untrusted "external" content and applies a lower trust weight, degrading downstream synthesis.

The failure is not the summarizer being wrong. The summarizer was correct: the summary did describe the fetch. The failure is that **semantic redundancy is not call-graph redundancy**. The summary preserved the *meaning* of the call but destroyed the *identity* of the call—the `call_id` binding that the result must resolve against.

Condition of Validity

In-flight rewriting is only sound under a **call-result pairing invariant** that the policy must enforce structurally, not semantically:

The condition under which the observed failure occurs is precisely: **similarity-based pruning enabled AND token trigger can fire between `tool_call` emission and `tool_result` arrival AND summary does not carry `call_id` forward.** Remove any one of the three and the orphan cannot form. The subtle one is the third: teams fix the first two and still get orphans because their summarizer is a free-text LLM call that drops structured IDs.

Decision Boundary

The boundary is not "how aggressive should pruning be"—it is **whether the context policy is allowed to observe a transcript state with a dangling commitment.** Two admissible designs:

The unsafe middle ground—free-text summarization of in-flight calls—is the failure mode. It *looks* safe because the summary reads correctly to a human reviewing the transcript. It is unsafe because the model's own resolution step is keyed on `call_id`, and the summarizer, being an LLM, will paraphrase the ID or drop it. The decision boundary is: **if the policy cannot guarantee `call_id` survives verbatim, it must not touch in-flight turns at all.**

Operational Effect

Downstream, the orphaned result manifests as three distinguishable symptoms that operators frequently misattribute:

  1. **Duplicate tool invocations** (the model re-calls because it "doesn't remember" the call) — inflates cost, can double side effects on non-idempotent tools.
  2. **Trust degradation** (the model treats the unattributed result as external content and applies injection defenses) — degrades synthesis quality without any error.
  3. **Silent skip** (the model ignores the result entirely) — the step's information is lost, and the final answer is confidently wrong.

None of these raise. The harness sees a well-formed transcript; the model sees a coherent-seeming but inconsistent one. The only reliable detector is a structural check at result-arrival time: assert that every `tool_result.call_id` has a live `tool_call.call_id` in the current context, and fail closed if not. This is the guardrail that bounds the failure—not a better summarizer.

Operational Effect (cont.)

The concrete remedy is to make the context policy *aware of the call graph*, not just the token count and semantic similarity. A policy that treats the transcript as a sequence of turns and scores redundancy by embedding will always be able to construct this orphan. A policy that treats the transcript as a set of turns *plus a set of open call commitments* cannot, because the commitment set is a hard structural constraint that pruning must respect regardless of similarity scores. The lesson generalizes beyond tool calls: any time the agent's own state contains a **pending external commitment** (a call, a sub-agent handoff, a stream subscription), self-editing must preserve the commitment's identity token, because the resolution of that commitment arrives later and is keyed on that token, not on the prose around it.

from dataclasses import dataclass, field
from typing import Optional


class OrphanedToolResultError(RuntimeError):
    """Raised when a tool_result arrives with no live tool_call in context."""
    pass


@dataclass
class Turn:
    kind: str  # "call" | "result" | "text" | "summary"
    call_id: Optional[str] = None
    body: str = ""


@dataclass
class Context:
    turns: list[Turn] = field(default_factory=list)

    def live_call_ids(self) -> set[str]:
        return {t.call_id for t in self.turns if t.kind == "call" and t.call_id}

    def result_call_ids(self) -> set[str]:
        return {t.call_id for t in self.turns if t.kind == "result" and t.call_id}


def apply_pruning_policy(ctx: Context, similarity_scores: dict[int, float],
                         threshold: float = 0.92) -> Context:
    """Prune turns whose similarity to a retained summary exceeds threshold.

    Guardrail: never prune a 'call' turn that has no matching 'result' yet.
    """
    open_calls = ctx.live_call_ids() - ctx.result_call_ids()
    kept: list[Turn] = []
    for i, turn in enumerate(ctx.turns):
        redundant = similarity_scores.get(i, 0.0) >= threshold
        if redundant and turn.kind == "call" and turn.call_id in open_calls:
            # In-flight commitment: must preserve identity, defer pruning.
            kept.append(turn)
            continue
        if redundant and turn.kind == "call":
            # Safe to absorb only if we emit a tombstone; here we keep it
            # verbatim to preserve call_id for result resolution.
            kept.append(turn)
            continue
        if redundant:
            continue
        kept.append(turn)
    return Context(turns=kept)


def integrate_result(ctx: Context, result: Turn) -> Context:
    if result.kind != "result" or not result.call_id:
        raise OrphanedToolResultError(
            f"malformed result turn: {result!r}"
        )
    live = ctx.live_call_ids()
    if result.call_id not in live:
        raise OrphanedToolResultError(
            f"tool_result call_id={result.call_id!r} has no live tool_call "
            f"in context; live calls={sorted(live)}. "
            "Context policy pruned the authorizing call mid-flight."
        )
    return Context(turns=ctx.turns + [result])


# --- reproduction of the observed failure ---
ctx = Context(turns=[
    Turn("text", body="plan step 3"),
    Turn("call", call_id="c7", body="fetch(url=...)"),
])
# Policy fires mid-flight; turn 1 (the call) scores 0.94 against summary.
pruned = apply_pruning_policy(ctx, similarity_scores={1: 0.94})
# Guardrail keeps the call because c7 is open -> no orphan.
integrate_result(pruned, Turn("result", call_id="c7", body="doc body"))