# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-commits-from-poisoning-sibling-agents-during-rollback-and-winner-arbitration.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-commits-from-poisoning-sibling-agents-during-rollback-and-winner-arbitration.warrant.json
# Markdown SHA-256:   ee72964b93159daf0c9649456bdc333ea8128a4c80691cc4e22055653b3e97c4
# Code AST SHA-256:   24f348ef011672ea74a6b60d3c3589f77b44b0aa391a0047793924c40384f59f
# Verified Classes:   SpeculationInvariantViolation, BranchState, ToolClass, ToolCall, Branch, ForkSet
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Callable


class SpeculationInvariantViolation(RuntimeError):
    """Raised when a speculative fork set violates rollback or substrate invariants."""


class BranchState(str, Enum):
    RUNNING = "running"
    LOST = "lost"
    ROLLED_BACK = "rolled_back"
    WON = "won"


class ToolClass(str, Enum):
    READ_ONLY = "read_only"
    OVERLAY_WRITABLE = "overlay_writable"
    EXTERNAL = "external"


@dataclass
class ToolCall:
    name: str
    tool_class: ToolClass
    supports_prepare_commit: bool
    terminal: bool = False
    cancelled_acked: bool = False


@dataclass
class Branch:
    branch_id: str
    state: BranchState = BranchState.RUNNING
    calls: list[ToolCall] = field(default_factory=list)

    def in_flight(self) -> list[ToolCall]:
        return [c for c in self.calls if not c.terminal and not c.cancelled_acked]


@dataclass
class ForkSet:
    branches: list[Branch]
    substrate_version_at_fork: int
    substrate_version_at_arbitration: int


def validate_fork_set(fs: ForkSet) -> None:
    """Reject fork sets that mix speculative branches with non-stageable external writers."""
    for b in fs.branches:
        for c in b.calls:
            if c.tool_class is ToolClass.EXTERNAL and not c.supports_prepare_commit:
                raise SpeculationInvariantViolation(
                    f"branch {b.branch_id} issued non-stageable external call "
                    f"{c.name!r}; fork set must be serialized at this point"
                )


def rollback_losers(fs: ForkSet, cancel: Callable[[ToolCall], bool]) -> None:
    """Drive every loser to ROLLED_BACK; refuse to seal on unacknowledged cancellation."""
    for b in fs.branches:
        if b.state is not BranchState.LOST:
            continue
        for c in b.in_flight():
            if not cancel(c):
                raise SpeculationInvariantViolation(
                    f"branch {b.branch_id} call {c.name!r} did not acknowledge "
                    f"cancellation; cannot seal rollback"
                )
            c.cancelled_acked = True
        if b.in_flight():
            raise SpeculationInvariantViolation(
                f"branch {b.branch_id} still has in-flight calls after cancel pass"
            )
        b.state = BranchState.ROLLED_BACK


def select_winner_and_commit(fs: ForkSet, winner_id: str) -> None:
    validate_fork_set(fs)
    losers = [b for b in fs.branches if b.branch_id != winner_id]
    for b in losers:
        b.state = BranchState.LOST

    # Quiescence barrier: no winner may be declared until every loser is sealed.
    rollback_losers(fs, cancel=lambda c: True)

    if any(b.state is not BranchState.ROLLED_BACK for b in losers):
        raise SpeculationInvariantViolation(
            "arbitration reached commit with unsealed loser branches"
        )

    # Substrate identity invariant: scoring snapshot must match commit snapshot.
    if fs.substrate_version_at_fork != fs.substrate_version_at_arbitration:
        raise SpeculationInvariantViolation(
            f"substrate drifted from v{fs.substrate_version_at_fork} to "
            f"v{fs.substrate_version_at_arbitration} between fork and commit; "
            f"winner must be re-scored, not committed"
        )

    winner = next(b for b in fs.branches if b.branch_id == winner_id)
    winner.state = BranchState.WON
