# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-multi-agent-rollback-from-silently-corrupting-committed-side-effect-ledgers.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-multi-agent-rollback-from-silently-corrupting-committed-side-effect-ledgers.warrant.json
# Markdown SHA-256:   931ec8bb54375ec3540fac7d31886565f2ef8501626f2adcbd6f7c01f1f69321
# Code AST SHA-256:   f9c338e9b338832de6ce53a483ac5e2a1ac8d3ea2745c2e15d934c905c9bd2b5
# Verified Classes:   SpeculativeRollbackViolation, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Set


class SpeculativeRollbackViolation(RuntimeError):
    """Raised when a branch attempts to commit while depending on
    state produced by an uncommitted or rolled-back sibling branch."""


@dataclass
class Branch:
    name: str
    epoch: int
    read_set: Set[str] = field(default_factory=set)   # keys read from siblings
    write_set: Set[str] = field(default_factory=set)  # keys this branch produced
    status: str = "running"  # running | committed | rolled_back


def commit_branch(branch: Branch, branches: dict[str, Branch]) -> None:
    # A branch may only commit if every key it read from a sibling belongs
    # to a branch that has already committed in a strictly earlier epoch.
    for key in branch.read_set:
        for other in branches.values():
            if other is branch:
                continue
            if key in other.write_set:
                if other.epoch >= branch.epoch:
                    raise SpeculativeRollbackViolation(
                        f"branch {branch.name!r} read {key!r} from sibling "
                        f"{other.name!r} in epoch {other.epoch} "
                        f"(status={other.status}); cross-epoch read violates "
                        f"speculative isolation"
                    )
                if other.status != "committed":
                    raise SpeculativeRollbackViolation(
                        f"branch {branch.name!r} depends on {key!r} from "
                        f"{other.name!r} which is {other.status}, not committed"
                    )
    branch.status = "committed"


def rollback_branch(branch: Branch, branches: dict[str, Branch]) -> None:
    branch.status = "rolled_back"
    # Transitive invalidation: any branch that read our writes must be
    # invalidated, because its committed decision rests on deleted evidence.
    for other in branches.values():
        if other is branch or other.status != "running":
            continue
        if other.read_set & branch.write_set:
            raise SpeculativeRollbackViolation(
                f"cannot roll back {branch.name!r}: sibling {other.name!r} "
                f"already read {other.read_set & branch.write_set}; "
                f"invalidate and re-run it first"
            )
