# Which invariants prevent speculative branch leakage from corrupting shared planner state in multi-agent DAG execution **Date of Record:** 2026 November 26 **Scope:** Applies to multi-agent planning pipelines where a planner agent speculatively executes downstream subgoals (eager execution / branch lookahead) before the branch is committed. Does not apply to strictly sequential single-agent planners or to pipelines where subgoal execution has no external side effects. ## Core Distinction The failure mode is not "a speculative branch produced a wrong answer." That is expected and cheap to discard. The failure mode is **speculative branch leakage**: a speculative execution writes to state that is *shared* with the committed path—memory stores, tool-side effects, budget counters, or the planner's own working memory—so that even after the speculation is *logically* rolled back, the residue of it persists and biases the committed plan. The distinction that matters: a speculative branch is only safe if its *observable footprint* is confined to a transaction boundary that the orchestrator can atomically discard. Most multi-agent planners treat speculation as a control-flow concept (fork the DAG, run the branch, pick the winner) but do not treat it as a *state* concept. The two are not the same, and the gap between them is where leakage lives. ## What Was Observed A three-tier planner (Planner → Executor pool → Critic) was configured to speculatively fan out three candidate decompositions of a subgoal at each DAG node, execute the first tool call of each candidate in parallel, and commit to the candidate whose tool response had the highest critic score. The intent was latency reduction: overlap the slow tool call with the critic's ranking. The observed trace: 1. Planner emits three candidate branches $B_1, B_2, B_3$ for node $N_k$. Each branch's first action is a `write_scratchpad` tool call into a *shared* scratchpad namespace keyed by task ID (not by branch ID). 2. All three execute concurrently. $B_1$ writes `intermediate = [A, B]`; $B_2$ writes `intermediate = [A, C]`; $B_3$ writes `intermediate = [D]`. Writes are last-writer-wins on the shared key. 3. Critic scores the *tool responses* (which are per-branch and correct), selects $B_2$ on score. 4. Planner commits $B_2$ and proceeds to node $N_{k+1}$, which reads `intermediate` from the scratchpad. 5. Because $B_3$'s write landed last, $N_{k+1}$ reads `[D]`—the contents of the *discarded* branch—while the planner's stated plan and the critic's justification both reference `[A, C]`. The corruption is silent. The planner's reasoning trace is internally consistent (it references $B_2$), the critic's log is internally consistent, and the only inconsistency is between the *plan text* and the *actual state the next node consumed*. Downstream nodes then reason over `[D]` while their own prompts assert the context is `[A, C]`, producing a divergence that compounds: each subsequent node's tool calls are conditioned on a context the planner believes is false. By node $N_{k+3}$ the plan and the world have drifted far enough that the Critic flags a "reasoning error," but the root cause is four hops upstream and the planner's own trace *looks* correct. A second, subtler leak was observed on the same pipeline: budget accounting. Speculative branches consumed executor tokens from the *shared* task budget rather than a speculative sub-budget. A pipeline that speculatively fanned out 3× at every node exhausted its token budget at roughly 40% of the planned DAG depth, and the planner—unable to distinguish "budget spent on committed work" from "budget spent on discarded speculation"—began truncating its own reasoning steps to compensate, degrading committed-plan quality. The speculation that was supposed to *save* latency *caused* a quality regression via a channel nobody was monitoring. ## Condition of Validity Speculative execution is safe **if and only if** every speculative branch is isolated across all four of the following axes simultaneously: - **State axis:** all writes go to a branch-scoped namespace (branch ID in the key), never to a task-scoped or global key. Reads from a speculative branch may see committed state; reads from committed state must never see speculative writes. - **Effect axis:** tool calls with external side effects (sends, writes to real systems, irreversible mutations) are either forbidden in speculation or staged behind a commit gate that replays them on commit. - **Budget axis:** speculative consumption is metered to a separate sub-budget that is discarded on rollback; the committed-path budget is debited only on commit. - **Memory axis:** the planner's working memory and any episodic store receive speculative results only on commit; the critic's scores may be retained (they are cheap metadata) but the *contents* of discarded branches must not enter the planner's retrievable context. The invariant is a conjunction. Isolation on three of four axes still leaks: a pipeline that scopes state and effects correctly but shares the budget will pass correctness tests and fail under load; a pipeline that scopes state, effects, and budget but writes speculative branch *summaries* into the planner's episodic memory will pass load tests and fail on the next task that retrieves those summaries as if they were committed knowledge. ## Decision Boundary The boundary is **not** "should we speculate?" It is **"is the commit operation atomic across every axis the branch touched?"** The operational test: - If a branch can be discarded by a single namespace-scoped delete plus a budget refund, and nothing it wrote is reachable from any committed read path, speculation is safe. - If discarding a branch requires *reasoning about which of its writes were committed*—i.e., if any write is conditional on downstream outcome—then the branch has already leaked and the commit gate is not a gate. The specific boundary that was crossed in the observed pipeline: the commit gate validated the branch's *tool responses* (per-branch, correct) but not the branch's *state footprint* (shared, corrupted). A commit gate that checks outputs but not footprints is not a commit gate; it is a vote. This is the non-obvious part—the gate *looked* correct because it was checking the thing the critic scored, and the critic scored the thing that was per-branch isolated. The leak lived in the axis nobody was scoring. A second boundary: when speculation depth exceeds one node, a speculative branch may itself spawn speculative sub-branches, and the isolation namespace must be *hierarchical* (branch path, not branch ID), or two sibling speculations at depth 2 will collide in the same flat namespace. Flat branch IDs are sufficient only for depth-1 speculation; this is a common configuration error because depth-1 speculation is what gets tested. ## Operational Effect When the invariant holds, speculation is a pure latency win: discarded branches cost only their metered sub-budget, and the committed path is bit-identical to a non-speculative run. This is the property that makes speculation *auditable*—you can replay the committed path without replaying the speculation and get the same result, which is what verification replay depends on. When the invariant is violated, the failure is silent, delayed, and misattributed. The planner's trace is self-consistent; the critic's log is self-consistent; the corruption surfaces four nodes later as a "reasoning error" whose root cause is a last-writer-wins race in a namespace that was never supposed to be shared. The cost is not the discarded branch—it is the *committed* path reasoning over discarded state while believing it is reasoning over committed state, which is the worst possible failure shape for an agent: confident, coherent, and wrong. The guardrail is architectural, not probabilistic. Do not attempt to detect leakage by comparing plan text to state after the fact; the divergence is only visible once it has already compounded. Enforce isolation at the namespace layer and refuse to commit any branch whose footprint touches a key outside its branch scope. ```python import hashlib from dataclasses import dataclass, field from typing import Any class SpeculativeLeakError(RuntimeError): """Raised when a speculative branch's state footprint escapes its isolation scope.""" pass class BudgetExhaustedError(RuntimeError): """Raised when speculative metering would debit the committed-path budget.""" pass @dataclass class BranchScope: task_id: str branch_path: tuple[str, ...] # hierarchical: ("N_k", "B_2", "N_k+1", "B_1") committed: bool = False writes: dict[str, Any] = field(default_factory=dict) tokens_spent: int = 0 def namespace_key(self, logical_key: str) -> str: # Hierarchical namespace: depth-N speculation cannot collide with siblings. path = "/".join(self.branch_path) return f"spec/{self.task_id}/{path}/{logical_key}" def write_speculative(scope: BranchScope, logical_key: str, value: Any) -> str: if scope.committed: raise SpeculativeLeakError( f"branch {scope.branch_path} already committed; speculative write forbidden" ) key = scope.namespace_key(logical_key) scope.writes[key] = value return key def commit_branch(scope: BranchScope, committed_store: dict[str, Any], committed_budget: dict[str, int]) -> None: # Invariant: every write must be inside this branch's namespace prefix. prefix = f"spec/{scope.task_id}/{'/'.join(scope.branch_path)}/" for key in scope.writes: if not key.startswith(prefix): raise SpeculativeLeakError( f"commit refused: write {key!r} escapes branch scope {prefix!r}" ) # Budget invariant: speculative tokens never debit the committed budget. if scope.tokens_spent > committed_budget.get("speculative_remaining", 0): raise BudgetExhaustedError( f"branch {scope.branch_path} exceeded speculative sub-budget " f"({scope.tokens_spent} > {committed_budget.get('speculative_remaining', 0)})" ) for key, value in scope.writes.items(): committed_store[key.removeprefix(prefix)] = value committed_budget["speculative_remaining"] -= scope.tokens_spent scope.committed = True def rollback_branch(scope: BranchScope, committed_store: dict[str, Any]) -> None: # Discard must be a single namespace-scoped delete; nothing reachable from committed reads. prefix = f"spec/{scope.task_id}/{'/'.join(scope.branch_path)}/" leaked = [k for k in committed_store if k.startswith(prefix)] if leaked: raise SpeculativeLeakError( f"rollback of {scope.branch_path} found committed keys under spec prefix: {leaked!r}" ) scope.writes.clear() scope.committed = False ```