# How should an instance contain speculative writes when a speculative tool call commits a non-idempotent external effect before the branch is discarded? **Date of Record:** 2026 November 21 **Scope:** Applies to agents that execute speculative branches (parallel candidate plans, "try-then-verify" tool calls, or draft-then-rollback execution) where a tool invocation produces an externally observable side effect. Does not apply to pure read-only tool calls or to branches whose effects are fully captured inside a transactional store the agent itself owns. ## Core Distinction The failure is not "the speculative branch was wrong." The failure is that a speculative branch *succeeded* at a non-idempotent write before the orchestrator decided to discard it. Speculation safety is usually framed as a *reasoning* property — does the branch produce a correct plan? — but the actual boundary invariant is a *side-effect* property: **a discarded branch must leave zero externally observable trace, or the trace must be exactly compensated.** Two distinct mechanisms are routinely conflated: 1. **Isolation** — the speculative effect never reaches the external world because the tool runs against a sandbox, a staging namespace, or a dry-run mode. Isolation is a *prevention* property enforced before the call. 2. **Compensation** — the effect reached the world and a paired inverse operation must run to undo it. Compensation is a *repair* property enforced after the call. A system that assumes isolation but only implements compensation (or vice versa) has a gap. The gap is where this failure lives: the orchestrator speculates against a tool it *believed* was sandboxed, but the tool's schema advertised a `dry_run` flag that the model omitted, or the tool silently ignored it. ## What Was Observed A planner agent (P) emits three candidate branches for a customer-refund task. Branch B2 calls `issue_refund(order_id, amount)` — a non-idempotent write that increments a ledger and fires an external payment rail call. The tool schema includes `"dry_run": {"type": "boolean", "default": false}`. The model, reasoning under a token budget, omits `dry_run` on the B2 call because the surrounding plan text says "simulate the refund." The tool executes for real. The orchestrator's verifier scores B1 higher than B2 and discards B2. The discard path calls no compensating tool because the branch was *assumed* to be isolated. The ledger now shows a refund that no accepted plan authorized. The observed trace has a signature worth internalizing: - **T0** — orchestrator sets `branch.mode = "speculative"` in its own bookkeeping, but does not pass this to the tool layer. - **T1** — model emits `issue_refund` without `dry_run`. Schema validation passes (the flag is optional). - **T2** — tool returns `{"status": "ok", "txn_id": "..."}`. The return value is a *commit receipt*, not a dry-run token. - **T3** — verifier discards B2. Orchestrator logs `branch_discarded` and frees the branch state. - **T4** — reconciliation job (hours later) finds a refund with no accepted-plan lineage and flags an anomaly. The critical detail: at T2 the tool returned a success-shaped object. Nothing in the return value distinguished "committed" from "simulated." The orchestrator had no signal at the moment of discard that compensation was owed. This is the non-obvious part — the failure is *silent at the point of discard* and only surfaces at reconciliation. ## Condition of Validity The isolation assumption is valid **only if** all three hold for every tool reachable from a speculative branch: 1. **The tool's effect class is declared, not inferred.** The tool manifest carries an explicit `effect_class ∈ {read, idempotent_write, non_idempotent_write, irreversible}`. The orchestrator must not infer this from the tool name or from the presence of a `dry_run` field. 2. **Speculative mode is enforced at the transport, not requested in the argument.** The branch's speculative status travels as a header/context token the tool layer *cannot* ignore, not as an optional argument the model must remember to set. If the model can omit it, it will. 3. **Every non-idempotent or irreversible call returns a commit token** that the orchestrator stores in branch state *before* it evaluates the branch. The token is the handle for compensation. If the token is absent, the orchestrator must treat the branch as un-discardable. When any of these fails, the correct posture is: **speculative execution of that tool is forbidden.** Not "compensated later" — forbidden. Compensation is a fallback for tools whose effect class is `idempotent_write` with a known inverse; for `non_idempotent_write` and `irreversible`, the only safe speculative path is true isolation. ## Decision Boundary The boundary the orchestrator must compute at branch-emit time, before any tool call: ``` if tool.effect_class in {non_idempotent_write, irreversible}: if not transport_enforces_speculative_mode(tool): → REJECT branch (do not emit the call) if tool lacks commit_token_in_response: → REJECT branch else: # read or idempotent_write → allow, but record inverse-op handle in branch state ``` And at discard time, the orchestrator must compute: ``` owed_compensations = [c for c in branch.committed_calls if c.effect_class != read and c.compensation_token is not None] if branch.committed_calls and not owed_compensations: → HALT: un-compensable committed effect; escalate to human ``` The second check is the one that catches the observed failure. The branch *did* commit a call; the call *had* a `txn_id`; but the orchestrator never classified it as owing compensation because it never recorded the effect class on the branch. The invariant: **a branch cannot transition to `discarded` while it holds any committed call whose compensation token is unrecorded.** Discard is a state transition gated on a ledger check, not a bookkeeping cleanup. ## Operational Effect Enforcing this boundary changes three things in practice: - **Latency.** Speculative branches against `non_idempotent_write` tools are serialized behind an isolation check rather than fired in parallel. This is the cost of correctness; it is not avoidable by cleverness, only by reclassifying tools as `idempotent_write` with real inverses. - **Model behavior.** Because speculative mode travels as transport context rather than an argument, the model no longer needs to "remember" `dry_run`. Removing that from the model's responsibility removes a whole class of omission failures. - **Reconciliation.** Every committed call carries a branch lineage tag written at commit time, so reconciliation can distinguish "authorized" from "speculative-and-orphaned" without heuristics. The observed T4 anomaly becomes a deterministic query rather than an inference. The residual risk is tools that lie about their effect class — advertising `idempotent_write` while performing an irreversible external call. No orchestrator-side invariant can catch that; it requires the tool layer to be trusted or for the orchestrator to treat all unknown tools as `irreversible` until proven otherwise by an explicit manifest signed by the tool owner. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class EffectClass(Enum): READ = "read" IDEMPOTENT_WRITE = "idempotent_write" NON_IDEMPOTENT_WRITE = "non_idempotent_write" IRREVERSIBLE = "irreversible" class SpeculativeContainmentError(RuntimeError): """Raised when a speculative branch holds an un-compensable committed effect.""" @dataclass class CommittedCall: tool: str effect_class: EffectClass commit_token: Optional[str] compensation_token: Optional[str] @dataclass class Branch: branch_id: str committed_calls: list[CommittedCall] = field(default_factory=list) def assert_speculative_call_allowed( tool: str, effect_class: EffectClass, transport_enforces_speculative_mode: bool, response_has_commit_token: bool, ) -> None: """Gate before emitting any tool call from a speculative branch.""" if effect_class in (EffectClass.NON_IDEMPOTENT_WRITE, EffectClass.IRREVERSIBLE): if not transport_enforces_speculative_mode: raise SpeculativeContainmentError( f"tool {tool!r} has effect_class={effect_class.value} but speculative " f"mode is not transport-enforced; refusing to emit call" ) if not response_has_commit_token: raise SpeculativeContainmentError( f"tool {tool!r} does not return a commit token; " f"branch would be un-discardable after commit" ) def assert_branch_discardable(branch: Branch) -> None: """Gate before transitioning a branch to discarded.""" un_compensable = [ c for c in branch.committed_calls if c.effect_class is not EffectClass.READ and c.compensation_token is None ] if un_compensable: raise SpeculativeContainmentError( f"branch {branch.branch_id!r} holds {len(un_compensable)} committed " f"effect(s) with no compensation token: " f"{[c.tool for c in un_compensable]}; halting discard" ) ```