# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-rollback-has-invalidated-a-committed-peer-s-side-effects-in-multi-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-rollback-has-invalidated-a-committed-peer-s-side-effects-in-multi-agent-execution.warrant.json
# Markdown SHA-256:   2e5639f9e0ba59433ea5e2786f5a38db73db0f1b3c544d01222283c4a26b6c5e
# Code AST SHA-256:   ebc89492df21d2d144fb82f8c65c558d534b7a2a1c14f9f9f61ace57c3119709
# Verified Classes:   SubstrateDivergenceError, VersionedResource, Substrate, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Tuple


class SubstrateDivergenceError(RuntimeError):
    """Raised when a committed branch's read-set no longer matches substrate versions
    after sibling rollback, meaning the committed output is unverified."""


@dataclass
class VersionedResource:
    value: object
    version: int


class Substrate:
    def __init__(self):
        self._store: Dict[str, VersionedResource] = {}
        self._next = 0

    def read(self, key: str) -> Tuple[object, int]:
        r = self._store[key]
        return r.value, r.version

    def write(self, key: str, value: object) -> int:
        self._next += 1
        self._store[key] = VersionedResource(value, self._next)
        return self._next

    def version(self, key: str) -> int:
        return self._store[key].version


@dataclass
class Branch:
    name: str
    read_set: Dict[str, int] = field(default_factory=dict)   # key -> version observed
    write_set: Dict[str, int] = field(default_factory=dict)  # key -> version written
    committed: bool = False


def rollback_branch(substrate: Substrate, branch: Branch, snapshots: Dict[str, Tuple[object, int]]):
    """Compensate a speculative branch. Escalate if compensation would interleave
    with a committed sibling's read version."""
    for key, written_version in branch.write_set.items():
        prior_value, prior_version = snapshots[key]
        current = substrate.version(key)
        # Compensation is only safe if the resource has not moved past what we wrote.
        if current != written_version:
            # Someone else touched it after us; do not clobber.
            raise SubstrateDivergenceError(
                f"rollback of {branch.name} on {key!r}: current v{current} != written v{written_version}"
            )
        substrate.write(key, prior_value)  # restore; new version, but value is prior


def commit_branch(substrate: Substrate, winner: Branch, losers: list[Branch], snapshots):
    for loser in losers:
        try:
            rollback_branch(substrate, loser, snapshots)
        except SubstrateDivergenceError:
            # Ambiguous/corrupting rollback: leave resource dirty, force re-derivation.
            winner.committed = False
            raise

    # Post-rollback readback: winner's memoized versions must still hold.
    for key, observed_version in winner.read_set.items():
        now = substrate.version(key)
        if now != observed_version:
            raise SubstrateDivergenceError(
                f"commit of {winner.name} invalidated: read {key!r} at v{observed_version}, "
                f"substrate now v{now} after sibling rollback"
            )
    winner.committed = True
