# Which invariants prevent speculative tool-call divergence from committing irreversible side effects across optimistic multi-agent execution **Date of Record:** 2026 November 26 **Scope:** Applies to multi-agent systems where one or more worker agents speculatively invoke tools (writes, sends, charges, deploys) ahead of an auditor/verifier agent's consistency confirmation, under an optimistic-execution model. Does not apply to strictly serialized tool-call pipelines where every side effect is gated on a synchronous verifier return, nor to read-only tool surfaces. ## Core Distinction The failure we are isolating is not "the verifier disagreed with the worker." That is expected and recoverable. The failure is **speculative side-effect commitment divergence**: a worker agent emits a tool call whose *effect* is observable outside the agent boundary (a POST, a transfer, a deploy, a message send) *before* the consistency verifier has confirmed the preconditions that the call depends on. When the verifier later returns a *negative* or *divergent* result — because its own retrieved context, its own tool outputs, or its own reasoning trace differed from the worker's — the effect has already escaped. There is no rollback primitive for "the email was sent," "the row was charged," "the container was promoted." Contrast this with two neighboring conditions that are *not* the same failure: - **Speculation that stays internal** (drafting a plan, staging a diff, computing a candidate argument set) is safe. The invariant is not "no speculation"; it is "no *committed* effect under speculation." - **Verifier disagreement on a reversible action** (e.g., a staging write that can be truncated) is a consistency bug but not a continuity break. The distinguishing property is *effect irreversibility*, not *disagreement*. The sharp mechanism: optimistic execution is only sound if the set of effects a worker may commit is a strict subset of the effects the verifier has *already* certified, or if every committed effect carries a **compensating inverse** that the verifier can invoke on divergence. When neither holds, the system has an unbounded window in which probabilistic divergence becomes permanent state. ## What Was Observed A three-agent topology: **Planner** (decomposes task into tool-call intents), **Worker** (executes intents optimistically, streaming results), **Auditor** (re-derives the expected precondition state from its own retrieval and confirms or rejects). The Worker was configured to "fire on intent" to reduce latency — it did not block on Auditor confirmation for tool calls classified as *low-risk*, where low-risk was defined by a static schema annotation on the tool (`side_effect: false` or `side_effect: idempotent`). The boundary failure surfaced on a tool annotated `side_effect: idempotent` — a `send_notification(recipient, template_id, payload)` call. Idempotency was keyed on `(recipient, template_id)`, so re-sending the same template to the same recipient was assumed safe to retry and safe to fire speculatively. Trace of the divergence: 1. Planner emitted intent `notify(customer_4421, "refund_approved", {amount: 120.00})`. 2. Worker fired `send_notification` immediately. The notification service deduplicated on `(recipient, template_id)` and **sent** the message with `amount: 120.00`. 3. Concurrently, Auditor re-derived the refund amount from the ledger and got `120.00` — but from a *stale replica* that had not yet applied a partial reversal posted 400ms earlier by a separate settlement agent. Auditor's expected value was `120.00`; the ledger's true value was `90.00`. 4. Auditor returned **confirm** (its stale view matched the Worker's argument). No divergence was flagged. 5. A second intent arrived: `notify(customer_4421, "refund_approved", {amount: 90.00})` — the corrected value from a re-read. Worker fired again. Idempotency key `(customer_4421, "refund_approved")` matched, so the service **suppressed** the second send. Net effect: the customer received a notification stating `120.00`; the ledger says `90.00`; the idempotency layer silently swallowed the correction because the key was too coarse. The Auditor never saw a disagreement because it and the Worker shared the same stale replica — **correlated staleness masquerading as consensus**. The non-obvious part: the failure was not a verifier *reject*. It was a verifier *accept* built on a read that was correlated with the worker's read. Optimistic execution with a verifier that shares the worker's data dependency is not verification — it is a second vote from the same broken electorate. A second observed variant, same topology: Worker fired `deploy(service="checkout", image="sha:9f2c")` optimistically. Auditor, reading a *different* registry mirror, confirmed `sha:9f2c` existed. But the mirror was a lagging cache; the canonical registry had already garbage-collected `sha:9f2c` after a failed scan. The deploy committed a reference to a non-existent image; the rollout hung mid-promotion with 40% of pods on the new ReplicaSet and 60% on the old — a split-brain the orchestrator could not self-heal because the image pull failed on the new pods. Here the verifier's *positive* confirmation was true-in-its-context and false-in-the-committing-context. ## Condition of Validity Optimistic speculative tool-calling is sound only when **all three** of the following invariants hold simultaneously. Drop any one and the divergence window reopens. **Invariant 1 — Effect-class partition is conservative and monotone.** Every tool must be partitioned into `REVERSIBLE`, `COMPENSABLE`, and `IRREVERSIBLE`. `REVERSIBLE` may be speculated freely. `COMPENSABLE` may be speculated only if a registered inverse operation exists *and* the inverse is itself idempotent and invocable by the Auditor without Worker cooperation. `IRREVERSIBLE` may never be speculated — it must block on a verifier confirmation that is causally downstream of the committing context. The partition must be **monotone**: a tool may be reclassified from `REVERSIBLE` to `IRREVERSIBLE` but never the reverse without a schema version bump and re-audit. The `send_notification` failure above came from misclassification: it was annotated `idempotent`, which the runtime mapped to `REVERSIBLE`, but a sent message is `IRREVERSIBLE` — idempotency of the *call* does not imply reversibility of the *effect*. **Invariant 2 — Verifier read-independence.** The Auditor's confirmation must be derived from a read path that is **causally independent** of the Worker's read path. Formally: the Auditor's precondition check must either (a) read from the authoritative source with a read-your-writes guarantee established *after* the Worker's intent was emitted, or (b) carry a vector-clock / read-freshness token that the Worker's read did not carry. If Worker and Auditor read the same replica, the confirmation is a correlated vote, not a check. The refund failure was a direct violation: both read the stale replica, so the Auditor's "confirm" carried zero independent information. **Invariant 3 — Compensating inverse is total over the effect domain.** For every `COMPENSABLE` tool, the registered inverse must be defined for *every* reachable post-state, including partial application. `send_notification`'s inverse would be "issue a correction notification," but that inverse is not total: it cannot un-send the first message, and it cannot guarantee the customer reads the correction. A `COMPENSABLE` classification that assumes the inverse is total when it is only defined on the happy path is a silent `IRREVERSIBLE` in disguise. The deploy failure violated this: the "rollback" inverse assumed the new ReplicaSet could be scaled to zero, but the hung rollout could not be cleanly aborted because the image pull failure left pods in `ImagePullBackOff` that the rollback controller treated as "already terminating." The conjunction matters. Invariant 1 without 2 lets a stale verifier confirm an irreversible effect. Invariant 2 without 1 lets a fresh verifier confirm an effect that cannot be undone when it is wrong. Invariant 3 without 1 or 2 lets the system believe it can compensate when it cannot, which is worse than knowing it cannot — it removes the human escalation trigger. ## Decision Boundary The runtime must decide, per tool call, between **speculate-and-verify** and **block-and-verify**. The decision is not a latency knob; it is a correctness boundary. The boundary is: - If `effect_class == IRREVERSIBLE` **or** `inverse_is_total == False` **or** `verifier_read_independence == UNPROVEN` → **block**. The Worker must not emit the call until the Auditor returns a confirmation carrying a freshness token strictly newer than the Worker's intent timestamp. - If `effect_class == COMPENSABLE` **and** `inverse_is_total == True` **and** `verifier_read_independence == PROVEN` → **speculate**, but attach a **divergence lease**: a bounded window (wall-clock and operation-count) within which a negative Auditor result triggers automatic inverse invocation. Past the lease, the effect is treated as committed and the Auditor's negative result escalates to a human rather than auto-compensating. - If `effect_class == REVERSIBLE` → **speculate** freely; divergence is resolved by truncation, not compensation. The subtle boundary condition: `verifier_read_independence == PROVEN` is a *runtime* property, not a static one. It must be re-established per intent, because replica lag, cache TTLs, and registry mirror staleness change between calls. A system that proves independence once at startup and caches the proof will drift into correlated staleness — exactly the refund failure. The proof must carry a **freshness witness** (a monotonic read token from the authoritative source) and the Worker must refuse to speculate if the Auditor's witness is not strictly greater than the Worker's intent-observation witness. ## Operational Effect When the three invariants hold jointly, the system gains a bounded, auditable speculation window: divergent tool calls either never commit (blocked class) or commit with a guaranteed, total, idempotent inverse that fires automatically inside the lease. The operational signature is that **every committed irreversible effect has a verifier witness strictly newer than the intent that produced it**, and **every compensable effect has a registered inverse that is total over its reachable post-states**. When any invariant is dropped, the observed signatures are: - **Correlated-staleness consensus**: Auditor and Worker agree because they share a read path; divergence is invisible until an external observer (the customer, the ledger reconciliation job) notices. Detection latency is measured in hours to days, not milliseconds. - **Idempotency-key collapse**: a coarse dedup key suppresses the *correction* along with the duplicate, so the wrong value becomes the only value. The key must include the *content hash* of the payload, not just `(recipient, template_id)`, or corrections cannot overwrite. - **Rollback deadlock**: a partial application (hung rollout, half-applied batch) leaves the inverse undefined, and the compensation controller blocks waiting for a state that will never arrive. The system must treat "inverse blocked for > lease" as an escalation, not a retry loop. The guardrail that bounds all three: a **commit ledger** that records, for every speculated call, `(intent_id, effect_class, inverse_ref, verifier_witness, lease_expiry)`. On Auditor divergence, the runtime looks up `inverse_ref` and invokes it if `now < lease_expiry`; otherwise it escalates. On lease expiry with no divergence, it marks the effect `COMMITTED` and drops the inverse. The ledger is the source of truth for "what did we speculate and can we still undo it" — without it, the system cannot distinguish "no divergence occurred" from "divergence occurred after the lease closed and was never checked." ```python import time from dataclasses import dataclass, field from enum import Enum from typing import Callable, Optional class EffectClass(Enum): REVERSIBLE = "reversible" COMPENSABLE = "compensable" IRREVERSIBLE = "irreversible" class SpeculationRefused(RuntimeError): """Raised when a speculative tool call violates the effect-class / read-independence / inverse-totality conjunction.""" pass class DivergenceLeaseExpired(RuntimeError): """Raised when an Auditor divergence arrives after the speculation lease closed and the effect can no longer be auto-compensated.""" pass @dataclass class ToolSpec: name: str effect_class: EffectClass inverse: Optional[Callable[[dict], None]] = None inverse_is_total: bool = False # coarse keys (e.g. (recipient, template_id)) collapse corrections; # content hash keeps corrections distinct from duplicates. dedup_key_fields: tuple = ("content_hash",) @dataclass class CommitRecord: intent_id: str tool: str payload: dict verifier_witness: int intent_witness: int lease_expiry: float inverse_ref: Optional[Callable[[dict], None]] committed: bool = False @dataclass class CommitLedger: records: dict = field(default_factory=dict) def record(self, rec: CommitRecord) -> None: self.records[rec.intent_id] = rec def on_divergence(self, intent_id: str, now: float) -> None: rec = self.records.get(intent_id) if rec is None: raise SpeculationRefused(f"no ledger entry for {intent_id}") if rec.committed: # effect already treated as final; cannot auto-compensate raise DivergenceLeaseExpired( f"divergence for {intent_id} arrived after commit; escalate to human" ) if now >= rec.lease_expiry: raise DivergenceLeaseExpired( f"divergence for {intent_id} arrived at {now} >= lease {rec.lease_expiry}" ) if rec.inverse_ref is None: raise SpeculationRefused( f"compensable effect {intent_id} has no registered inverse" ) rec.inverse_ref(rec.payload) rec.committed = True def speculate( tool: ToolSpec, payload: dict, intent_witness: int, verifier_witness: int, lease_seconds: float, ledger: CommitLedger, intent_id: str, now: Optional[float] = None, ) -> CommitRecord: now = time.monotonic() if now is None else now # Invariant 1: irreversible effects must never be speculated. if tool.effect_class is EffectClass.IRREVERSIBLE: raise SpeculationRefused( f"tool {tool.name} is IRREVERSIBLE; must block on verifier confirmation" ) # Invariant 2: verifier read must be causally downstream of intent. if verifier_witness <= intent_witness: raise SpeculationRefused( f"verifier witness {verifier_witness} not strictly newer than " f"intent witness {intent_witness}; read-independence unproven" ) # Invariant 3: compensable effects require a total inverse. if tool.effect_class is EffectClass.COMPENSABLE: if tool.inverse is None or not tool.inverse_is_total: raise SpeculationRefused( f"compensable tool {tool.name} lacks a total registered inverse" ) rec = CommitRecord( intent_id=intent_id, tool=tool.name, payload=payload, verifier_witness=verifier_witness, intent_witness=intent_witness, lease_expiry=now + lease_seconds, inverse_ref=tool.inverse if tool.effect_class is EffectClass.COMPENSABLE else None, ) ledger.record(rec) return rec ```