# What structural signals indicate that speculative tool-call execution has outrun its side-effect fence **Date of Record:** 2026 November 25 **Scope:** Applies to agents that issue tool calls speculatively (fan-out, lookahead, or parallel branch exploration) against tools with externally observable side effects, where a fence token is supposed to gate commit and a compensation transaction is supposed to undo committed-but-abandoned effects. Does not apply to pure-function tools, read-only retrievals, or single-path deterministic execution where speculation is disabled. ## Core Distinction The failure this record isolates is not "the agent made a bad tool call." It is the divergence between two clocks that the agent architecture treats as one: the **speculation clock** (how far ahead the reasoning loop has branched) and the **side-effect clock** (how many irreversible external mutations have actually landed). A fence is correct only while the side-effect clock never advances past the fence's commit horizon. Speculative execution is *safe* when every branch's effects are buffered behind a fence token and *broken* when a branch's effect escapes the buffer while the branch is still uncommitted. The structural signal of breakage is not an error—it is a **fence/effect ledger skew**: the set of effects recorded as committed by the external system is a strict superset of the effects the agent's fence ledger believes are provisional. Most teams instrument the wrong invariant. They check "did the tool return success?" The invariant that matters is "does `committed_effects ⊆ fence_cleared_effects` hold at every checkpoint?" When it fails, the agent is running compensation against a world state it never authorized, and the compensation itself becomes an unauthorized mutation. ## What Was Observed A planner agent was configured to explore three candidate branches per step, each issuing a `reserve_inventory` call against an external warehouse API with a 30-second hold TTL. Fences were implemented as a per-branch token: `reserve` returns a `hold_id`, and the fence commits by calling `confirm(hold_id)` or releases by calling `release(hold_id)`. The intent was clean: uncommitted branches release their holds, committed branch confirms. The breakage surfaced as intermittent double-allocation. The trace, abbreviated: 1. Branch B2 issued `reserve_inventory(sku=X, qty=40)` → `hold_id=h_991`. Fence ledger marked `h_991` as `PROVISIONAL`. 2. The reasoning loop's context window saturated; the summarizer compressed the branch log. The compression step dropped the `hold_id` from the retained branch record because the summarizer treated it as "transient tool metadata." The fence ledger still held `h_991` under B2, but B2's *branch record* no longer referenced it. 3. B2 was abandoned (divergence score below threshold). The compensation routine walked the *branch record* to enumerate holds to release—found none—and concluded B2 had no side effects. It did not consult the fence ledger. 4. `h_991` expired at TTL and the warehouse auto-released it. Meanwhile branch B1, which had committed a *different* hold for the same SKU, now saw a race: the auto-release returned 40 units to the pool mid-transaction, and a concurrent order claimed them. Net effect: the committed branch's allocation was silently under-backed. The tell was not an exception. It was a **compensation that reported success while releasing zero holds** for a branch the fence ledger knew had one. The structural signal: `len(compensation_actions) == 0` for a branch whose ledger entry was non-empty. That mismatch—compensation accounting derived from a lossy reasoning artifact rather than from the authoritative fence ledger—is the boundary condition. ## Condition of Validity The fence-and-compensate pattern is valid only under three simultaneous conditions, and speculation violates at least one of them by construction unless explicitly guarded: - **C1 — Enumerability from a single source of truth.** The set of effects to compensate must be derived from the fence ledger, never from the reasoning transcript. Context compression, summarization, or truncation is *guaranteed* to lose tool metadata under token pressure, so any compensation path that reads the transcript is invalid the moment the context is compacted. - **C2 — TTL dominance.** Every provisional effect's external TTL must strictly exceed the maximum possible time between issuance and fence resolution (commit or release), *including* the worst-case reasoning latency for the longest branch. If `TTL ≤ max_branch_latency + compensation_latency`, the external system can auto-resolve a hold the agent still believes is provisional, and the agent's ledger becomes stale-positive. - **C3 — Compensation idempotency under partial commit.** A compensation must be safe to run against an effect that was already externally resolved (TTL-expired, manually released, or double-confirmed). Non-idempotent compensation turns a benign skew into a double-mutation. The observed failure broke C1 (compensation read the transcript) and C2 (TTL of 30s was shorter than the p99 branch latency of 41s under context saturation). Either breach alone is survivable; both together produce silent under-allocation. ## Decision Boundary The operational line is this: **speculation may proceed only while `fence_ledger` is the sole authority for effect enumeration and every provisional effect has a TTL margin ≥ 2× the measured p99 branch latency.** When context pressure rises—detectable by summarizer invocation, token-budget depletion rate, or branch-record growth—the agent must *narrow speculation before it widens compensation*. Concretely: - If `remaining_context_tokens < branch_record_footprint × active_branches`, collapse to single-branch execution and drain the fence ledger to zero provisional entries before issuing any new effect. - If any provisional effect's `age > TTL/2`, force-resolve it (commit or release) immediately rather than letting it ride; do not issue new speculative effects while any entry is past half-TTL. - Never let the compensation routine's input be a summarized artifact. The ledger is append-only and lives outside the context window; the transcript is a *view*, the ledger is the *truth*. The boundary is crossed the instant a compensation decision is made from anything other than the ledger, or the instant a provisional effect's age can exceed its TTL. Both are structural, both are detectable before the mutation lands. ## Operational Effect After the incident, the agent was reworked so that the fence ledger is a durable, out-of-context append-only store keyed by `(branch_id, effect_id)`, and the compensation routine is a pure function of that store. TTLs were raised to 10× p99 branch latency, and a pre-flight gate refuses speculative fan-out when the projected branch footprint exceeds 40% of the remaining context budget. The result: fence/effect skew dropped to zero across 12k speculative steps, and the one remaining class of skew—external TTL expiry during a hard partition—is now caught by an idempotent compensation that re-reads external state before mutating. The general lesson for any agent running speculative side effects: the fence is only as strong as the *authority* it reads from. A fence backed by the reasoning transcript is a fence backed by a lossy, compacting, probabilistic artifact—and it will silently report a clean release over a live hold. The structural signal to watch is not the error stream; it is the empty compensation against a non-empty ledger. ```python class FenceEffectSkew(RuntimeError): """Raised when committed external effects diverge from the fence ledger's provisional set.""" pass class FenceLedger: """Append-only, out-of-context authority for provisional and committed effects.""" def __init__(self, ttl_seconds: float, p99_branch_latency: float): self.ttl = ttl_seconds self.p99 = p99_branch_latency self._entries = {} # effect_id -> {"branch": str, "state": str, "age": float} def provision(self, effect_id: str, branch_id: str) -> None: self._entries[effect_id] = {"branch": branch_id, "state": "PROVISIONAL", "age": 0.0} def age_tick(self, effect_id: str, seconds: float) -> None: self._entries[effect_id]["age"] += seconds def provisional_for(self, branch_id: str): return [e for e, v in self._entries.items() if v["branch"] == branch_id and v["state"] == "PROVISIONAL"] def ttl_margin_ok(self) -> bool: # C2: TTL must dominate worst-case branch + compensation latency. return self.ttl >= 2.0 * self.p99 def compensate_branch(ledger: FenceLedger, branch_id: str, transcript_effects: list, release_fn) -> list: """ Compensate an abandoned branch. Effects MUST be enumerated from the ledger, never from the (lossy) reasoning transcript. """ if not ledger.ttl_margin_ok(): raise FenceEffectSkew( f"TTL {ledger.ttl}s does not dominate 2x p99 {ledger.p99}s; " "provisional effects may externally auto-resolve before compensation." ) ledger_effects = ledger.provisional_for(branch_id) # Structural signal: transcript lost effects the ledger still holds. if set(ledger_effects) - set(transcript_effects): raise FenceEffectSkew( f"Branch {branch_id}: ledger holds {ledger_effects} but transcript " f"enumerates {transcript_effects}; compensation source is untrustworthy." ) # If the transcript claims a clean branch but the ledger disagrees, refuse. if not ledger_effects and transcript_effects: raise FenceEffectSkew( f"Branch {branch_id}: transcript reports effects {transcript_effects} " "absent from ledger; fence authority violated." ) released = [] for effect_id in ledger_effects: # Idempotent release: re-read external state, tolerate already-resolved. release_fn(effect_id, idempotent=True) ledger._entries[effect_id]["state"] = "RELEASED" released.append(effect_id) return released ```