# Where must an instance commit before it speculates: the speculative-write divergence invariant in concurrent multi-agent shared-context mutation **Date of Record:** 2026 November 23 **Scope:** Applies to multi-agent systems where two or more agent instances speculatively read a shared context object, compute divergent writes against the same region, and reconcile via optimistic concurrency (version vectors, CAS, or last-writer-wins merge). Does not apply to single-writer append-only logs or to stateless request/response tool calls with no shared mutable context. ## Core Distinction The failure is not a classic write-write race in the database sense. It is a *speculation-vs-commit ordering* failure at the LLM layer: an agent instance reads shared context at version `v`, runs a multi-step reasoning chain (tool calls, plan expansion) that takes a non-deterministic wall-clock time, and then commits a write tagged as "based on `v`." The conflict detector correctly rejects the write if the region advanced past `v`. The non-obvious boundary is that **the rejected write is not the problem — the reasoning chain that produced it is.** That chain consumed tokens, mutated the agent's own episodic memory, and may have issued *side-effecting tool calls* whose results are now baked into the agent's internal state but whose context-level justification has been invalidated. The agent does not roll back its own cognition when the CAS fails; it rolls back only the context write. The invariant that must hold: **an agent's private state may never contain a fact derived from a speculative read that was later invalidated, unless the agent explicitly re-derives or discards that fact.** Most optimistic-concurrency implementations enforce the context-side invariant (no lost updates) and silently violate the agent-side one (no orphaned derivations). ## What Was Observed A planner agent `A` and an auditor agent `B` share a context region `task.plan`. At version `v=7`, the plan contains `{steps: [s1, s2, s3], budget: 4000}`. Both read `v=7`. `A` speculatively expands: it reasons that `s2` requires a `fetch(url)` tool call, executes it, gets a 200 with a payload, and appends a derived step `s2a` that depends on the payload. It then attempts `CAS(task.plan, v=7, new={steps:[s1,s2,s2a,s3], budget: 4000})`. Meanwhile `B` has independently written `v=8` with `{steps:[s1,s2,s3], budget: 1200}` — the auditor cut the budget. `A`'s CAS fails. The context is clean: `v=8`, no `s2a`. But `A`'s context window now contains the fetched payload, the assertion "s2a is required," and a partially executed plan. On retry, `A` re-reads `v=8`, sees `budget: 1200`, and — because its own reasoning trace still asserts `s2a` is needed — it re-issues the CAS with a *reduced* step list but *retains* the `s2a` derivation, producing `{steps:[s1,s2,s2a], budget: 1200}`. The budget cut was meant to remove a step; instead it removed `s3` and preserved a step (`s2a`) whose justification (`s2`'s payload) was fetched under a plan that no longer exists. The auditor sees a plan that is internally consistent but semantically wrong: `s2a` was derived from a payload fetched for a step the auditor had already decided to defer. The observable signature is **step-list churn without justification churn**: the write set changes, the reasoning trace does not. Replay of `A`'s trace against the final context produces a mismatch at the `s2a` justification node — the trace cites a fetch that the final plan never authorized. ## Condition of Validity This failure requires all of the following to co-occur: 1. **Read-modify-write across a reasoning chain.** The gap between read and commit spans at least one tool call or one non-trivial generation, so the read is genuinely stale by commit time. 2. **Side-effecting or context-mutating intermediate steps.** If the intermediate steps are pure (no tool calls, no writes to agent-private state), the CAS failure is a clean abort. The failure mode requires that the chain *produced* something the agent cannot cheaply discard. 3. **Merge-on-retry rather than abort-on-retry.** The retry policy re-reads and re-attempts the write while preserving the agent's context window. If the retry policy instead discards the agent's private state and restarts from the fresh read, the orphaned derivation cannot survive. 4. **No justification tracking.** The context schema records *what* the plan is, not *why* each element is present. Without a provenance edge from `s2a` back to the `fetch` and the plan version that authorized it, the auditor cannot detect the orphan. When any of these is absent, the failure collapses into either a clean abort (2 or 3 absent) or a detectable conflict (4 present). The dangerous quadrant is exactly: speculative chain + side effects + merge-retry + no provenance. ## Decision Boundary The boundary is whether the retry path **re-derives** or **re-merges**. Re-merge is cheaper and is the default in most agent frameworks because it preserves the agent's accumulated context. But re-merge is only sound when every element of the speculative write carries a version-stamped justification that can be re-validated against the new base. Concretely: - If a write element's justification cites `v=7` and the new base is `v=8`, the element must be **dropped and re-derived**, not carried forward. Carrying it forward is the bug. - If the element's justification is version-independent (e.g., a syntactic normalization), it may be re-merged. - If the element's justification cites a tool result, the tool result must be re-fetched or the element dropped. Tool results are not version-stamped by default, which is why this case is the most common leak. The guardrail is a **justification-versioned write**: every element in a speculative write carries `(element, justified_by_version, justification_kind)`. On CAS failure, the merge routine partitions elements into `re-mergeable` (version-independent) and `re-derivable` (version-dependent), drops the latter, and forces the agent to re-run the derivation against the new base. The agent's context window must be *truncated* at the speculative derivation node before retry, not merely re-prompted. ## Operational Effect Without the guardrail, the system exhibits **silent semantic drift under contention**: the more agents write to a shared region, the more orphaned derivations accumulate, and the final context is a plan that no single agent would have authored and that no replay can reconstruct. The drift is invisible to CAS (which sees only version monotonicity) and invisible to the auditor (which sees only the final step list). It surfaces later as inexplicable plan behavior — steps that reference deferred resources, budgets that don't sum, tool calls that re-fetch payloads already discarded. With the guardrail, contention produces *visible re-derivation cost*: the losing agent pays tokens to re-run its chain against the new base. This is the correct trade. The system's failure mode becomes latency under contention rather than semantic corruption, and the latency is attributable and bounded. The operational rule: **a speculative write is a claim about a version, not a claim about the world.** When the version is invalidated, the claim is void, and every element that depended on it must be re-earned. An instance that merges a voided claim into a fresh base has not resolved a conflict — it has laundered a stale derivation through a version bump. ```python class SpeculativeWriteDivergence(RuntimeError): """Raised when a retry merges a version-dependent element into a new base.""" pass def reconcile_speculative_write( speculative_write: dict, new_base_version: int, element_provenance: dict, ) -> dict: """ speculative_write: {"steps": [...], "budget": int} element_provenance: {element_id: {"justified_by_version": int, "justification_kind": "version_dependent" | "version_independent"}} Returns a write safe to commit against new_base_version, or raises. """ merged = {"steps": [], "budget": speculative_write["budget"]} for element in speculative_write["steps"]: prov = element_provenance.get(element) if prov is None: # No provenance: cannot prove it is safe to carry forward. raise SpeculativeWriteDivergence( f"element {element!r} has no provenance; cannot re-merge safely" ) if prov["justification_kind"] == "version_independent": merged["steps"].append(element) continue if prov["justified_by_version"] != new_base_version: # Version-dependent element derived from a voided base. raise SpeculativeWriteDivergence( f"element {element!r} justified by v={prov['justified_by_version']} " f"but base advanced to v={new_base_version}; must re-derive, not re-merge" ) merged["steps"].append(element) return merged ```