# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-rollback-from-resurrecting-committed-effects-in-multi-agent-fork-join-orchestration.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-rollback-from-resurrecting-committed-effects-in-multi-agent-fork-join-orchestration.warrant.json
# Markdown SHA-256:   bec48b3bfa8414d0395db40892d9fa30d09a164aea4caa5e08418e0e694e36f5
# Code AST SHA-256:   c85f5c7b6f67f4b9ef896e73c7cde88107863c0d17f9d970e1d23ad2ede0cb93
# Verified Classes:   SpeculationRollbackViolation, Effect, Branch, SpeculationLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class SpeculationRollbackViolation(RuntimeError):
    """Raised when a rollback would revert an effect a surviving branch observed."""
    pass


@dataclass
class Effect:
    key: str
    value: str
    version: int
    branch_id: str


@dataclass
class Branch:
    branch_id: str
    committed: bool = False
    # (key, version) pairs this branch read during its speculative run
    read_set: Set[Tuple[str, int]] = field(default_factory=set)


class SpeculationLedger:
    """Tracks uncommitted effects and read-dependencies to gate rollback soundness."""

    def __init__(self) -> None:
        self._effects: Dict[Tuple[str, int], Effect] = {}
        self._branches: Dict[str, Branch] = {}

    def register(self, branch_id: str) -> None:
        self._branches[branch_id] = Branch(branch_id)

    def speculative_write(self, branch_id: str, key: str, value: str, version: int) -> None:
        self._effects[(key, version)] = Effect(key, value, version, branch_id)

    def speculative_read(self, branch_id: str, key: str, version: int) -> None:
        # Reading an uncommitted effect creates a dependency edge.
        if (key, version) in self._effects:
            self._branches[branch_id].read_set.add((key, version))

    def commit(self, branch_id: str, committed_versions: Dict[str, int]) -> None:
        """A branch may only commit if every uncommitted effect it read has been
        committed by its owner, or the read is against committed state."""
        branch = self._branches[branch_id]
        for (key, version) in branch.read_set:
            eff = self._effects.get((key, version))
            if eff is None:
                continue  # already committed or reverted; resolve against snapshot
            owner = self._branches.get(eff.branch_id)
            if owner is None or not owner.committed:
                raise SpeculationRollbackViolation(
                    f"branch {branch_id} cannot commit: it read uncommitted "
                    f"effect {key}@v{version} owned by un-committed branch "
                    f"{eff.branch_id}; causal closure violated"
                )
        branch.committed = True

    def rollback(self, branch_id: str) -> None:
        """Revert a losing branch's effects, but refuse if any committable branch
        observed them. Blind revert is the failure mode this guards against."""
        reverted = {k for k, e in self._effects.items() if e.branch_id == branch_id}
        for other_id, other in self._branches.items():
            if other_id == branch_id:
                continue
            overlap = other.read_set & reverted
            if overlap and not other.committed:
                raise SpeculationRollbackViolation(
                    f"rollback of {branch_id} would revert {overlap}, which "
                    f"surviving branch {other_id} has read; must invalidate and "
                    f"re-execute {other_id} before reverting"
                )
            if overlap and other.committed:
                raise SpeculationRollbackViolation(
                    f"rollback of {branch_id} would revert {overlap}, already "
                    f"observed by COMMITTED branch {other_id}; rollback is unsound "
                    f"and the committed output must be quarantined"
                )
        for k in reverted:
            del self._effects[k]
        self._branches[branch_id].committed = False
