# Which invariants prevent orphaned side-effect commits in speculative branch-and-rollback agent trees **Date of Record:** 2026 November 30 **Scope:** Applies to multi-agent orchestrators that speculatively fork sibling sub-agents over a shared task tree and rely on optimistic concurrency (version-tagged writes plus compensating rollback) rather than distributed locking. Does not apply to strictly serialized DAG executors or single-agent retry loops where no concurrent sibling can observe a partially committed branch. ## Core Distinction The failure is not "a rollback failed." It is that a **rollback succeeded for the branch that owns the write, while a sibling branch that observed the write treats it as committed truth and re-emits it after the owning branch is reverted.** Speculative execution assumes a write is owned by exactly one branch and that rollback of that branch removes the write from the shared world. Under optimistic concurrency with a shared mutable store and *read-your-sibling's-writes* visibility, that assumption is false: a write can be read, cached into a sibling's private context (or its own un-reverted commit log), and then resurrected after the original is compensated. The invariant that actually holds is weaker than "rollback removes the write" — it is "rollback removes the write *only if no other live branch holds a read-dependency on it*." Detecting and enforcing that read-dependency is the entire problem. ## What Was Observed A planner agent forks three speculative branches from a shared checkpoint at version `v=41` over a task tree with a single shared `workspace` object (a dict of task nodes with `version` tags). Branch A (the "optimistic" branch) writes `workspace["schema"] = new_schema` at `v=42` and emits a downstream tool call `migrate_db()` whose side effect is external and non-idempotent. Branch B, executing concurrently, reads `workspace["schema"]` (seeing `v=42`, the new value, because the store is read-committed across branches), and uses it to construct its own `workspace["plan"]` at `v=43`, which embeds `new_schema` as an assumption. Branch A then fails its verifier (schema fails a downstream constraint check), and the orchestrator issues a compensating rollback: it reverts `workspace["schema"]` to `v=44` (the old value) and calls `rollback_migrate_db()`. The orchestrator considers A resolved. Branch B wins the speculative race and commits `workspace["plan"]` at `v=45`. The plan now references `new_schema`, which no longer exists in the workspace, and the compensating `rollback_migrate_db()` has already partially undone the external migration that B's plan assumed was live. The final committed state is internally inconsistent: `plan` asserts a schema the store does not hold, and the external DB is in a third state (partially migrated) that neither branch intended. The trace is: `A.write(schema, v42)` → `B.read(schema)→v42` → `A.verify→FAIL` → `A.rollback(schema→v44, rollback_migrate_db)` → `B.commit(plan, v45)`. The commit of B is *optimistically valid* — its version tag `v45 > v44` passes the concurrency check — but it is *semantically orphaned*: it depends on a write that has been compensated. ## Condition of Validity The naive invariant — "a branch may commit iff its write version is strictly greater than the current workspace version" — is valid only under the condition that **no committed branch transitively depends on a compensated write.** That condition fails whenever: 1. Sibling branches share a read-committed store (read visibility across live branches), and 2. A reader branch does not record a read-dependency edge to the specific version it observed, and 3. Rollback compensates the write without invalidating dependents. The correct invariant is a **read-dependency closure**: a branch's commit is valid iff every version it read (directly or transitively through an embedded assumption) is still present in the committed lineage. Rollback of a write must therefore not merely revert the value but **invalidate the read-dependency closure of that version**, forcing any dependent branch to either re-derive from the reverted state or be discarded. Without this, optimistic concurrency degrades into "last writer wins on version number," which is not concurrency control at all — it is a monotonic counter with no dependency semantics. A second invariant is required for external side effects: **rollback of a non-idempotent side effect must be either deferred until no live branch holds a dependency, or the side effect must be recorded in a compensation journal that dependents are checked against before commit.** The `migrate_db()` call is the sharp edge: it is not in the workspace, so version-tag checks never see it. The journal is the only place the dependency can be detected. ## Decision Boundary The orchestrator must choose, at rollback time, between two policies, and the choice is not free: - **Eager rollback** (compensate immediately, invalidate dependents): correct for external non-idempotent side effects, because leaving them live risks compounding. Cost: dependent branches are discarded and must re-execute, which can cascade into re-forking the whole speculative subtree. - **Deferred rollback** (mark the version `tombstoned`, block dependents from committing, compensate only when the dependency closure is empty): correct for pure workspace writes where re-derivation is cheap. Cost: a tombstoned version can pin the workspace for an unbounded time if a dependent branch never terminates. The boundary is: **if the compensated write has any external side effect recorded in the journal, eager; otherwise deferred.** Mixing policies within one rollback (revert the workspace value eagerly but defer the external compensation) is the specific configuration that produced the observed failure, because the workspace revert removed the value that would have let B detect the tombstone, while the external compensation ran before B committed. ## Operational Effect After the fix, every branch commit carries a `read_set` of `(key, version)` pairs and a `side_effect_deps` set of journal entries. The commit gate is a closure check over the workspace lineage: any `(key, version)` in the read set whose version is tombstoned, or any journal entry that is compensated, blocks the commit and forces re-derivation from the latest live version. The workspace version counter is no longer sufficient; the lineage graph is the source of truth. The practical cost is that speculative branches can no longer commit purely on version monotonicity — they must prove their dependency closure is live — which reduces speculative parallelism in the worst case but eliminates orphaned commits. The orchestrator now rejects approximately the same fraction of branches it previously accepted incorrectly, but the rejects are *correct* rejects (dependency invalidated) rather than silent corruptions discovered downstream. ```python from dataclasses import dataclass, field from typing import Dict, Set, Tuple class OrphanedDependencyCommit(RuntimeError): """Raised when a branch attempts to commit while depending on a compensated write.""" pass @dataclass class WriteRecord: key: str version: int value: object tombstoned: bool = False external_side_effect: bool = False @dataclass class Branch: branch_id: str read_set: Set[Tuple[str, int]] = field(default_factory=set) side_effect_deps: Set[str] = field(default_factory=set) class SpeculativeWorkspace: def __init__(self) -> None: self.records: Dict[Tuple[str, int], WriteRecord] = {} self.compensated_effects: Set[str] = set() self.version = 0 def write(self, key: str, value: object, external: bool = False) -> int: self.version += 1 self.records[(key, self.version)] = WriteRecord( key=key, version=self.version, value=value, external_side_effect=external ) return self.version def read(self, key: str, branch: Branch) -> object: live = [r for (k, _), r in self.records.items() if k == key and not r.tombstoned] if not live: raise KeyError(key) rec = max(live, key=lambda r: r.version) branch.read_set.add((key, rec.version)) return rec.value def rollback(self, key: str, version: int, effect_id: str | None = None) -> None: rec = self.records[(key, version)] rec.tombstoned = True if rec.external_side_effect and effect_id is not None: # Eager policy: external effect compensated now; dependents must be blocked. self.compensated_effects.add(effect_id) def commit(self, branch: Branch) -> None: for (key, version) in branch.read_set: rec = self.records.get((key, version)) if rec is None or rec.tombstoned: raise OrphanedDependencyCommit( f"branch {branch.branch_id} depends on tombstoned write " f"{key}@v{version}; re-derive from live lineage" ) for effect_id in branch.side_effect_deps: if effect_id in self.compensated_effects: raise OrphanedDependencyCommit( f"branch {branch.branch_id} depends on compensated side effect " f"{effect_id}; cannot commit" ) self.version += 1 self.records[(f"commit::{branch.branch_id}", self.version)] = WriteRecord( key=f"commit::{branch.branch_id}", version=self.version, value="committed" ) ```