# How does an instance detect speculative pre-fetch contamination when a speculative tool execution commits side effects before its parent hypothesis is validated? **Date of Record:** 2026 November 26 **Scope:** Applies to multi-agent pipelines that hide latency by issuing speculative context retrievals and speculative tool calls against a predicted next-step hypothesis (branch prediction for LLM planners). Does not apply to strictly sequential request/response tool loops where no execution occurs ahead of a committed plan step. ## Core Distinction There are two categorically different speculative artifacts, and conflating them is the root of the failure: - **Speculative reads** (context pre-fetch, vector retrieval, file reads, GET-style tool calls) are *idempotent and side-effect-free*. If the hypothesis is wrong, you discard the fetched bytes. The only cost is tokens and latency already spent. - **Speculative writes** (POST-style tool calls, state mutation, message emission, transaction commit) are *effectful*. If the hypothesis is wrong, the side effect has already landed in the world, and the world does not roll back because the planner changed its mind. The non-obvious boundary: latency-hiding frameworks almost always implement both through the same "fire the predicted tool call early" mechanism, because at the transport layer a tool call is a tool call. The failure mode is that a *speculative write* whose parent hypothesis is later falsified leaves an orphaned side effect that the committing agent never records as its own — so no compensating action is ever scheduled. The instance detects this not by checking whether the hypothesis was right, but by reconciling the **effect ledger** against the **committed plan graph**. ## What Was Observed A three-agent pipeline (Planner → Executor → Auditor) was latency-hiding with a speculative executor. On each planner step, a lightweight predictor model emitted the top-1 predicted next tool call, and the Executor pre-fired it before the Planner had committed. Prediction accuracy was ~78%, so most of the time this worked. The trace that broke: 1. Planner context: user asks to "reconcile the invoice batch and file the discrepancy report." Predictor emits `submit_discrepancy_report(batch=4471, severity="minor")` at ~0.71 confidence — a plausible next step given the batch looked clean in a shallow scan. 2. Executor fires the speculative `submit_discrepancy_report`. The tool is effectful: it writes a row to the compliance ledger and notifies an external auditor webhook. **Committed.** 3. Planner then performs the actual reconciliation, discovers batch 4471 has a *material* discrepancy requiring `severity="critical"` and a *different* report path plus a hold on the batch. The "minor" hypothesis is falsified. 4. Planner commits `submit_discrepancy_report(batch=4471, severity="critical")` and `hold_batch(4471)`. 5. The compliance ledger now contains **two** report rows for batch 4471 — one "minor" (orphaned, from speculation) and one "critical" (committed). The external auditor received two webhooks. The batch hold references a report ID that is not the one the Planner believes it created. The Auditor agent, whose job is to verify the final state against the plan graph, saw a ledger state that did not match any committed plan node and flagged a **verification replay discrepancy** — but it could not attribute the extra row, because the Executor's speculation log is a separate channel from the plan graph. The orphaned write was invisible to the agent that owned the plan. The tell, in hindsight: the ledger row's `trace_id` belonged to a speculative span that had no corresponding committed plan node. That mismatch is the detection signal. ## Condition of Validity Speculative *tool execution* (as opposed to pre-fetch) is only sound under all of the following: - The tool is provably idempotent under a caller-supplied idempotency key derived from `(plan_node_id, hypothesis_hash)`, so a re-issue after commitment is a no-op. - The speculative call is **staged**, not committed: it produces a *pending effect* in a quarantine ledger that is only promoted to the real ledger when the planner commits the matching node within the speculation TTL. - The predictor's confidence exceeds a threshold, and — critically — the tool is classified `effect_class = read` or `effect_class = staged_write`. A raw `effect_class = write` tool must never be speculatively executed. - The speculation TTL is strictly shorter than the minimum time for the parent hypothesis to be falsified, OR there is an explicit abort/compensation path wired to the plan graph. If any of these fail — in particular if a `write`-class tool is pre-fired without a quarantine ledger and without an idempotency key tied to the plan node — the pipeline is not latency-hiding, it is **speculatively mutating the world on an unvalidated hypothesis**. ## Decision Boundary The instance must decide, at the moment a speculative result returns, whether the parent hypothesis is still live: - **Hypothesis still live and committed** → promote the staged effect, reuse the fetched context, record the speculation as a cache hit. - **Hypothesis still live but not yet committed** → hold the staged effect in quarantine; do not promote; do not discard. Wait for commit or TTL expiry. - **Hypothesis falsified** → the staged effect must be **aborted** (quarantine drop) if it was staged, or **compensated** (explicit inverse tool call) if it was a raw write. A raw write with no compensation path is an unrecoverable contamination and must halt the pipeline and escalate. The boundary that is easy to get wrong: "falsified" is not the same as "different." If the Planner commits `severity="critical"` after speculating `severity="minor"`, the hypothesis is falsified *and* the committed node targets the *same resource*. The naive dedup ("same tool, same batch, drop the older") silently drops the wrong row or keeps both. The correct rule is: a committed node supersedes a speculative node only if the speculative node was staged; if it was a raw write, it must be compensated by resource identity, not by tool-name equality. ## Operational Effect Without the quarantine ledger and the effect-class gate, the observable symptoms are: duplicate external notifications, ledger rows with `trace_id`s that map to no committed plan node, Auditor replay mismatches that cannot be attributed, and — worst — a batch hold that references an orphaned report. The system appears healthy (low latency, high prediction accuracy) while its world-state silently diverges from its plan graph by one effect per falsified write-hypothesis. With the gate, the invariant is: **every effect in the real ledger has a committed plan node as its parent, or it is in quarantine.** The Auditor's replay check becomes a simple set difference between ledger `parent_node_id`s and committed plan node IDs — any ledger entry whose parent is not committed is contamination, and any committed node with a staged-but-unpromoted effect is an incomplete promotion. This is checkable in O(1) per effect and does not require replaying the predictor. The detection the instance must implement: before committing any plan node, scan the quarantine ledger for staged effects whose `hypothesis_hash` no longer matches any live hypothesis, abort them, and assert that the real ledger contains no effect whose `parent_node_id` is absent from the committed plan graph. If the assert fails, the contamination already escaped and the pipeline must halt rather than proceed with a divergent world model. ```python import hashlib from dataclasses import dataclass, field from enum import Enum from typing import Dict, Optional class EffectClass(Enum): READ = "read" STAGED_WRITE = "staged_write" WRITE = "write" # must never be speculatively executed class SpeculationContamination(RuntimeError): """Raised when a real-ledger effect has no committed plan node parent, or a write-class tool was speculatively fired without quarantine.""" @dataclass class Effect: effect_id: str tool: str resource_id: str parent_node_id: Optional[str] hypothesis_hash: str effect_class: EffectClass staged: bool @dataclass class PlanGraph: committed_nodes: Dict[str, str] = field(default_factory=dict) # node_id -> hypothesis_hash def commit(self, node_id: str, hypothesis_hash: str) -> None: self.committed_nodes[node_id] = hypothesis_hash def is_live(self, hypothesis_hash: str) -> bool: return hypothesis_hash in self.committed_nodes.values() @dataclass class Ledgers: quarantine: Dict[str, Effect] = field(default_factory=dict) real: Dict[str, Effect] = field(default_factory=dict) def stage(self, eff: Effect) -> None: if eff.effect_class is EffectClass.WRITE and not eff.staged: raise SpeculationContamination( f"write-class tool {eff.tool!r} fired speculatively without quarantine" ) self.quarantine[eff.effect_id] = eff def promote(self, effect_id: str, plan: PlanGraph) -> None: eff = self.quarantine.get(effect_id) if eff is None: raise SpeculationContamination(f"promote of unknown effect {effect_id!r}") if eff.hypothesis_hash not in plan.committed_nodes.values(): raise SpeculationContamination( f"cannot promote {effect_id!r}: hypothesis {eff.hypothesis_hash} not committed" ) self.real[effect_id] = self.quarantine.pop(effect_id) def abort_stale(self, plan: PlanGraph) -> int: stale = [eid for eid, e in self.quarantine.items() if not plan.is_live(e.hypothesis_hash)] for eid in stale: del self.quarantine[eid] return len(stale) def assert_no_orphans(self, plan: PlanGraph) -> None: for eid, eff in self.real.items(): if eff.parent_node_id is None or eff.parent_node_id not in plan.committed_nodes: raise SpeculationContamination( f"real-ledger effect {eid!r} ({eff.tool} on {eff.resource_id}) " f"has parent {eff.parent_node_id!r} absent from committed plan graph" ) def h(tool: str, args: str) -> str: return hashlib.sha256(f"{tool}|{args}".encode()).hexdigest()[:16] def reconcile(plan: PlanGraph, ledgers: Ledgers) -> None: ledgers.abort_stale(plan) ledgers.assert_no_orphans(plan) ```