# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-a-side-effect-before-its-branch-is-selected-rollback-impossibility-across-parallel-agent-branches.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-a-side-effect-before-its-branch-is-selected-rollback-impossibility-across-parallel-agent-branches.warrant.json
# Markdown SHA-256:   b105907a83d751d7040f7219dd5078fb17c494661914e5bc2509d58fda220677
# Code AST SHA-256:   84f776b5c8d03905ff27fa07cfaea47860e4bcb105acdc9332a9ffba9809a8c7
# Verified Classes:   SpeculativeRollbackViolation, StagedIntent, Branch, SpeculativeExecutor
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class SpeculativeRollbackViolation(RuntimeError):
    """Raised when a deselected branch has already produced an irreversible effect."""


@dataclass
class StagedIntent:
    branch_id: str
    logical_intent: str
    payload: dict[str, Any]
    idempotency_key: str
    reversible: bool


@dataclass
class Branch:
    branch_id: str
    score: float
    staged: list[StagedIntent] = field(default_factory=list)
    dispatched: list[StagedIntent] = field(default_factory=list)


class SpeculativeExecutor:
    def __init__(self) -> None:
        self._committed: set[str] = set()

    def dispatch(self, intent: StagedIntent) -> None:
        # Backend deduplicates on idempotency_key; a second dispatch of the
        # same logical intent is a no-op, a dispatch of a new key is a write.
        if intent.idempotency_key in self._committed:
            return
        self._committed.add(intent.idempotency_key)

    def commit(self, branches: list[Branch]) -> Branch:
        winner = max(branches, key=lambda b: b.score)
        for branch in branches:
            if branch is winner:
                continue
            for intent in branch.dispatched:
                if not intent.reversible:
                    raise SpeculativeRollbackViolation(
                        f"branch {branch.branch_id} dispatched irreversible "
                        f"intent {intent.logical_intent!r} before selection; "
                        f"cannot roll back — halt and escalate"
                    )
        for intent in winner.staged:
            self.dispatch(intent)
        return winner
