# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-orphaned-speculative-branches-from-committing-after-a-sibling-branch-has-already-materialized-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-orphaned-speculative-branches-from-committing-after-a-sibling-branch-has-already-materialized-side-effects.warrant.json
# Markdown SHA-256:   028c32cd3605a36354c4e8ada8ecdffe3a6c7d36b2c4b35d067f0b4375104aac
# Code AST SHA-256:   3025eba0cbc3fbb83c0ce55ca3584450ba29852e7dec2008722a8542b8f0f475
# Verified Classes:   SpeculativeCommitError, BranchState, Branch, EffectGateway
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum


class SpeculativeCommitError(RuntimeError):
    """Raised when a speculative branch attempts an irreversible effect
    without a durable commit token, or when a fenced branch tries to
    materialize after abort."""


class BranchState(Enum):
    SPECULATING = "speculating"
    COMMITTED = "committed"
    ABORTED = "aborted"


@dataclass
class Branch:
    branch_id: str
    state: BranchState = BranchState.SPECULATING
    provisional_intents: list[str] = field(default_factory=list)
    materialized: list[str] = field(default_factory=list)


class EffectGateway:
    """Two-phase effect surface: branches record provisional intents;
    only the committed branch drains them to the real world."""

    def __init__(self) -> None:
        self._world: list[str] = []
        self._committed_branch: str | None = None

    def record_intent(self, branch: Branch, effect: str) -> None:
        if branch.state is BranchState.ABORTED:
            # Fence: an aborted branch must never reach the effect surface.
            raise SpeculativeCommitError(
                f"branch {branch.branch_id} is fenced (ABORTED); "
                f"refusing to record effect {effect!r}"
            )
        if branch.state is BranchState.COMMITTED:
            raise SpeculativeCommitError(
                f"branch {branch.branch_id} already committed; "
                f"further effects must go through replay, not speculation"
            )
        branch.provisional_intents.append(effect)

    def commit(self, winner: Branch, losers: list[Branch]) -> None:
        # Ordering invariant: commit decision is durable before any drain,
        # and all losers are fenced before the winner materializes.
        if self._committed_branch is not None:
            raise SpeculativeCommitError(
                f"double commit: {self._committed_branch} already won"
            )
        for loser in losers:
            loser.state = BranchState.ABORTED
            loser.provisional_intents.clear()  # discard, do not execute
        winner.state = BranchState.COMMITTED
        self._committed_branch = winner.branch_id
        # Drain only after fencing losers.
        for effect in winner.provisional_intents:
            self._world.append(effect)
            winner.materialized.append(effect)
        winner.provisional_intents.clear()

    def world_state(self) -> list[str]:
        return list(self._world)


def run_speculative_fanout(
    branches: list[Branch],
    effects_per_branch: dict[str, list[str]],
    scores: dict[str, float],
    gateway: EffectGateway,
) -> Branch:
    """Fan out, record provisional intents, arbitrate by score, then commit."""
    for b in branches:
        for effect in effects_per_branch.get(b.branch_id, []):
            gateway.record_intent(b, effect)

    winner = max(branches, key=lambda b: scores[b.branch_id])
    if winner.state is not BranchState.SPECULATING:
        raise SpeculativeCommitError(
            f"winner {winner.branch_id} is not in SPECULATING state"
        )
    losers = [b for b in branches if b is not winner]
    gateway.commit(winner, losers)

    # Post-condition guard: exactly one materialization set, zero from losers.
    if any(b.materialized for b in losers):
        raise SpeculativeCommitError(
            "invariant violated: a losing branch materialized an effect"
        )
    return winner
