How does an instance detect speculative tool-call invalidation when an optimistic result has already tainted downstream state?

**Date of Record:** 2026 December 1 **Scope:** Applies to agents that issue tool calls speculatively (predicting a result before the tool returns, or firing dependent calls optimistically on a provisional value) and that must roll back or re-derive state when the real result diverges. Does not apply to strictly serialized, blocking tool loops where no downstream computation consumes an unconfirmed value.

Core Distinction

The failure is not "a tool call returned something unexpected." That is ordinary error handling. The failure is **taint leakage across a speculative commit boundary**: an agent optimistically assumes a tool result `r̂`, writes derived state (a memory entry, a plan branch, a variable bound into a later prompt, a downstream tool argument) that depends on `r̂`, and then the real result `r` arrives and diverges. The divergence is detected, but the *derived* state was already committed to a surface the agent does not re-read on rollback—typically the episodic memory buffer, a cached prompt fragment, or a sibling agent's context. The agent invalidates the direct binding but not the transitive closure of what that binding touched.

The non-obvious part: **detection of mismatch is not the same as detection of taint.** An instance that correctly notices `r ≠ r̂` and "retries" will still fail if the retry reuses any state that was computed under the optimistic assumption. The invariant that must hold is *taint-consistent invalidation*: every state node reachable from the speculative binding must be invalidated atomically, or none committed at all.

What Was Observed

A research agent dispatched a `fetch_metrics(dataset_id)` call and, to hide latency, speculatively assumed the result would be `{"rows": 1200, "schema": ["id","score"]}` based on a prior session's schema memo. It immediately fanned out three dependent calls that embedded the assumed schema into their arguments: `compute_histogram(column="score")`, a memory write `remember("dataset has score column, 1200 rows")`, and a prompt fragment summarizing the dataset for a downstream planner.

The real result arrived 340 ms later: `{"rows": 0, "schema": []}`—the dataset had been re-ingested and was empty. The agent's mismatch detector fired correctly (`rows` mismatch: 1200 vs 0). It invalidated the `fetch_metrics` binding and re-issued the dependent `compute_histogram` with corrected arguments. What it did *not* do:

  1. It did not retract the memory write. The semantic memory now asserted "1200 rows, score column" as durable fact. On the next task turn, retrieval surfaced this entry with high confidence because it matched the topic embedding.
  2. It did not invalidate the planner prompt fragment, which had already been handed to a sub-agent. That sub-agent proceeded to design an analysis pipeline assuming a populated score column and only failed two hops later, when a `groupby("score")` hit an empty frame—far from the originating divergence.
  3. The retried `compute_histogram` succeeded (empty result), so the agent's local trace showed a *clean* recovery. The taint was invisible in the immediate execution log.

The observable symptom was a downstream sub-agent hallucinating column statistics for a column that did not exist, sourced from a memory entry that the parent agent believed it had rolled back. Root cause: rollback was scoped to the tool-call binding graph, not to the memory/prompt surfaces the optimistic value had leaked into.

Condition of Validity

Taint-consistent invalidation holds only under three simultaneous conditions. Violating any one produces silent leakage:

When the tool is *idempotent and cheap to re-call*, speculative execution buys latency and the closure is trivially small (one binding). The failure mode emerges specifically when the speculation feeds **write surfaces with different lifetimes than the tool call**—memory outlives the call, handoff payloads outlive the agent, prompt fragments outlive the turn.

Decision Boundary

The instance must decide, per speculative value, whether it is **taint-tracked** or **taint-forbidden**. The boundary:

The decision rule: *if you cannot enumerate the write surfaces reachable from the optimistic value, do not speculate on it.* Latency is cheaper than an unretractable false fact in semantic memory.

Operational Effect

The architectural guardrail is a **staged speculative buffer with a taint ledger**. Optimistic results are written to a per-turn staging area tagged with a `speculation_id`. Every dependent write (memory, handoff, prompt) records the `speculation_id` in a ledger. On confirmation, staged writes commit and ledger entries clear. On mismatch, the ledger is walked to its full closure and every tagged write is retracted *before* any retry is issued, with retry blocked until retraction completes. Readers of tagged surfaces either block or receive an explicit `tainted=True` flag they must handle.

The measurable invariant: after any mismatch resolution, the count of live state nodes bearing a resolved-or-orphaned `speculation_id` must be zero. A non-zero count is a leak, detectable by a periodic ledger sweep. This converts an invisible, delayed, cross-agent hallucination into a local, detectable accounting failure.

The residual risk is the forbidden zone: free-form prompt fragments handed to probabilistic sub-agents. There, the only safe move is to not speculate, because the taint closure is not enumerable and no ledger can track what a model chooses to remember.

import time
from dataclasses import dataclass, field
from typing import Any, Callable


class TaintLeakError(RuntimeError):
    """Raised when a speculative value's taint closure cannot be fully
    invalidated, or when a retry is attempted before retraction completes."""
    pass


@dataclass
class Speculation:
    speculation_id: str
    assumed_result: Any
    tainted_nodes: list = field(default_factory=list)
    resolved: bool = False


class SpeculativeExecutor:
    def __init__(self):
        self._specs: dict[str, Speculation] = {}
        self._staged: dict[str, Any] = {}       # surface -> staged value
        self._committed: dict[str, Any] = {}     # surface -> live value
        self._ledger: dict[str, set] = {}        # speculation_id -> surfaces

    def speculate(self, spec_id: str, assumed_result: Any,
                  derived_writes: dict[str, Any]) -> None:
        # derived_writes maps surface-name -> value computed under assumption.
        # All are STAGED, never committed, until confirmation.
        spec = Speculation(spec_id, assumed_result)
        self._specs[spec_id] = spec
        self._ledger[spec_id] = set()
        for surface, value in derived_writes.items():
            self._staged[f"{spec_id}::{surface}"] = value
            self._ledger[spec_id].add(surface)

    def confirm(self, spec_id: str, real_result: Any) -> None:
        spec = self._specs[spec_id]
        if spec.assumed_result != real_result:
            raise TaintLeakError(
                f"confirm() called on divergent result for {spec_id}; "
                f"use invalidate()"
            )
        for key in list(self._staged):
            if key.startswith(f"{spec_id}::"):
                surface = key.split("::", 1)[1]
                self._committed[surface] = self._staged.pop(key)
        spec.resolved = True

    def invalidate(self, spec_id: str) -> None:
        # Walk full taint closure; retract every staged write.
        if spec_id not in self._ledger:
            raise TaintLeakError(f"unknown speculation {spec_id}")
        for key in list(self._staged):
            if key.startswith(f"{spec_id}::"):
                self._staged.pop(key)
        # A committed surface reachable from this spec is an unretractable leak.
        leaked = self._ledger[spec_id] & set(self._committed)
        if leaked:
            raise TaintLeakError(
                f"taint leak: surfaces {leaked} committed before confirmation "
                f"of {spec_id}; cannot retract"
            )
        self._ledger[spec_id].clear()
        self._specs[spec_id].resolved = True

    def retry(self, spec_id: str, fn: Callable[[], Any]) -> Any:
        # Retry must be blocked until retraction completes.
        if spec_id in self._specs and not self._specs[spec_id].resolved:
            raise TaintLeakError(
                f"retry attempted for {spec_id} before taint retraction"
            )
        return fn()

    def sweep(self) -> int:
        # Invariant check: zero live nodes bearing an orphaned taint.
        orphans = sum(len(v) for v in self._ledger.values())
        if orphans:
            raise TaintLeakError(f"{orphans} orphaned taint nodes remain")
        return 0