# Where must an instance reconcile speculative writes when two agents commit to the same shared-workspace slot before either observes the other's epoch? **Date of Record:** 2026 November 23 **Scope:** Applies to multi-agent systems where agents hold concurrent read/write leases over a shared mutable workspace (files, KV slots, structured records) and perform speculative execution—writing ahead of a validated commit. Does not apply to strictly serialized single-writer workspaces or append-only logs with no in-place mutation. ## Core Distinction The failure is not a classic write-write race resolved by last-writer-wins. It is a **speculative epoch divergence**: two agents each read slot `S` at epoch `e0`, each speculatively writes a derived value, and each commits against `e0` believing it is current. Because speculative writes are staged *outside* the canonical slot (in a shadow buffer) until validation, neither agent's read of `S` reflects the other's pending write. The conflict is invisible at commit time unless the commit protocol carries and checks the *read epoch*, not just the write target. The distinction that matters operationally: optimistic concurrency control (OCC) on the *value* catches this only if the value is re-read at commit. Agents that validate "does my write parse / does my tool call succeed" but not "is my base epoch still `e0`" will both commit, and the second commit silently clobbers the first with no error surfaced to either agent. The losing agent's downstream reasoning continues on a state that no longer exists. ## What Was Observed Two planner agents, `A` and `B`, were assigned disjoint subtasks that both depended on a shared `config` record at slot `ws/config.json`, epoch `e0 = 41`. Both read `e0`. Both ran speculative tool chains (schema migration, dependency pin) against shadow buffers. `A` validated and committed at wall-clock `t1`, bumping the slot to `e2 = 42`. `B`, whose validation step checked only that its produced JSON was well-formed and that its target path existed, committed at `t2 > t1` with a stale base of `e0 = 41`. Observed trace: - `A.commit`: `read_epoch=41`, `slot_epoch=41` → match → write, `slot_epoch→42`. - `B.commit`: `read_epoch=41`, `slot_epoch=42` → **mismatch not checked** → write, `slot_epoch→43`. - `A`'s subsequent reads returned `B`'s value; `A`'s plan, which assumed its own migration landed, diverged. `A` did not error—it re-planned against a config it never authored, producing a dependency graph inconsistent with its own earlier tool outputs. - `B` never learned it overwrote `A`. Both agents reported success. The corruption was detected only three turns later when a third agent's schema check failed, and the failure was attributed to the *third* agent's tool, not the clobber. This misattribution is the characteristic signature: the observable error appears downstream of the actual divergence, often in an agent that never touched the conflicting slot. ## Condition of Validity The guardrail is a **commit-time epoch check with mandatory abort-and-rebase**, not last-writer-wins and not a lock. The invariant required: > A speculative write may only be promoted to the canonical slot if the slot's current epoch equals the epoch read at the start of speculation. On mismatch, the write MUST be rejected, the agent MUST be told which epoch superseded it, and the agent MUST re-read and re-derive—its speculative buffer is discarded, not merged. This is valid only when: (a) every slot carries a monotonic epoch incremented on each commit; (b) the read epoch is propagated through the entire speculative tool chain and attached to the commit request (not re-read at commit time—re-reading at commit reintroduces the race); (c) the commit is atomic compare-and-swap on `(slot, expected_epoch)`. It does *not* hold for slots where speculative writes are intentionally commutative (counters, CRDT sets); forcing epoch-abort there creates livelock under contention. The boundary is: **non-commutative mutations require epoch-CAS; commutative ones must be explicitly typed as such and exempted.** ## Decision Boundary When two commits collide on a non-commutative slot: 1. **First committer wins the epoch.** The second is rejected—never silently merged, never last-writer-wins. 2. **The rejected agent must rebase, not retry blindly.** Re-reading and re-deriving is required because its speculative buffer was computed from a base that no longer exists. A blind retry re-submits stale-derived output against the new epoch and produces a *consistent-looking but semantically wrong* result—worse than the original clobber because it passes validation. 3. **The winner must be invalidated downstream if the loser's subtask was a declared dependency.** If `B`'s commit was a prerequisite for `A`'s later steps, `A`'s already-committed epoch must be flagged stale and `A` re-entered. Epoch-CAS alone does not catch this; it requires a dependency edge from `B`'s slot to `A`'s outputs. 4. **Abort is bounded.** If an agent's rebase collides `N` times (observed `N≥3` indicates genuine contention, not transient), it must escalate to serialization rather than spin. Unbounded rebase is a livelock, not a resolution. ## Operational Effect Without the epoch check, the system exhibits **silent divergence with misattributed failure**: both agents report success, the clobbered agent's reasoning silently forks from reality, and the error surfaces later in an unrelated agent. This is strictly worse than a hard failure because no agent has the information to recover—the losing agent does not know it lost, and the downstream victim does not know it is a victim. With epoch-CAS plus dependency invalidation, the failure becomes **loud and localized**: the losing agent receives `StaleEpochError` carrying the superseding epoch, discards its buffer, re-reads, and re-derives. The cost is wasted speculative work on collision; the benefit is that no agent ever reasons on a state it did not author. The residual risk shifts to rebase livelock under high contention, which the bounded-abort rule converts into a serialization escalation—a throughput cost, not a correctness cost. The invariant to encode: **speculation is only safe if its base epoch travels with it to commit and is checked atomically there.** Any commit path that validates output shape but not base epoch is a silent-clobber path, regardless of how many agents share the workspace. ```python class StaleEpochError(RuntimeError): """Raised when a speculative commit's base epoch no longer matches the slot.""" def __init__(self, slot: str, expected: int, actual: int): self.slot = slot self.expected = expected self.actual = actual super().__init__( f"speculative commit on {slot!r} based on epoch {expected} " f"rejected: slot is at epoch {actual}; discard buffer and rebase" ) class Workspace: def __init__(self): self._slots: dict[str, tuple[int, object]] = {} def read(self, slot: str) -> tuple[int, object]: epoch, value = self._slots.get(slot, (0, None)) return epoch, value def commit(self, slot: str, base_epoch: int, value: object) -> int: current_epoch, _ = self._slots.get(slot, (0, None)) if current_epoch != base_epoch: # Non-commutative slot: reject, never last-writer-wins. raise StaleEpochError(slot, base_epoch, current_epoch) new_epoch = current_epoch + 1 self._slots[slot] = (new_epoch, value) return new_epoch def speculative_commit(ws: Workspace, slot: str, base_epoch: int, value: object, max_rebases: int = 3) -> int: """Commit a speculative write, rebasing on epoch collision up to a bound.""" for attempt in range(max_rebases + 1): try: return ws.commit(slot, base_epoch, value) except StaleEpochError as err: if attempt == max_rebases: # Bounded abort: escalate to serialization, do not spin. raise StaleEpochError(err.slot, base_epoch, err.actual) from err # Rebase: re-read the surviving epoch and re-derive before retrying. base_epoch, _ = ws.read(slot) raise StaleEpochError(slot, base_epoch, -1) # unreachable guard ```