# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-rollouts-from-committing-side-effects-that-the-verifier-later-rejects.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-rollouts-from-committing-side-effects-that-the-verifier-later-rejects.warrant.json
# Markdown SHA-256:   aba96d3d28d1eeb84ab1e59c12fed14f7c7e2d1e45437b7ea977383120a77c84
# Code AST SHA-256:   4cebda4b6b3f936d28085209f1f9292d6aba64e13acabb9c49858ebdfa291c47
# Verified Classes:   SpeculativeCommitViolation, SelectionReceipt, EffectJournal
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Any


class SpeculativeCommitViolation(RuntimeError):
    """Raised when a speculative branch attempts to cross the effect horizon
    before the selection horizon has produced a deterministic, receipted winner."""


@dataclass
class SelectionReceipt:
    seed: int
    scores: list[float]
    winner: int

    def fingerprint(self) -> str:
        payload = f"{self.seed}:{self.scores}:{self.winner}".encode()
        return hashlib.sha256(payload).hexdigest()


@dataclass
class EffectJournal:
    rollout_id: str
    branch_id: int
    seed: int
    staged: list[tuple[str, dict[str, Any], str]] = field(default_factory=list)
    committed: bool = False

    def stage(self, tool: str, args: dict[str, Any], idem_key: str) -> None:
        if self.committed:
            raise SpeculativeCommitViolation(
                f"branch {self.branch_id} already committed; cannot stage further effects"
            )
        self.staged.append((tool, args, idem_key))


def commit_winner(
    journals: list[EffectJournal],
    receipt: SelectionReceipt,
    journal_seed: int,
) -> EffectJournal:
    if receipt.seed != journal_seed:
        raise SpeculativeCommitViolation(
            f"selection receipt seed {receipt.seed} != journal seed {journal_seed}; "
            "replay divergence would commit the wrong branch"
        )
    winners = [j for j in journals if j.branch_id == receipt.winner]
    if len(winners) != 1:
        raise SpeculativeCommitViolation(
            f"expected exactly one journal for winner {receipt.winner}, found {len(winners)}"
        )
    for j in journals:
        if j.branch_id != receipt.winner and j.committed:
            raise SpeculativeCommitViolation(
                f"loser branch {j.branch_id} committed before selection; invariant broken"
            )
    winner = winners[0]
    winner.committed = True
    return winner
