# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-arbitrate-between-speculative-parallel-branches-before-committing-shared-state-and-why-does-winner-selection-collapse-under-non.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-arbitrate-between-speculative-parallel-branches-before-committing-shared-state-and-why-does-winner-selection-collapse-under-non.warrant.json
# Markdown SHA-256:   284d22a7c7738e18661413ff782267f03e70c87b328cada8a7cd9bbd10d6d5b3
# Code AST SHA-256:   92aab49fa4ffe0341197547b496f035f8ca91cb0c003a295cf11450f7302b1eb
# Verified Classes:   SpeculativeCommitError, Effect, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class SpeculativeCommitError(RuntimeError):
    """Raised when winner commit cannot be proven equivalent to replay-from-checkpoint."""


@dataclass
class Effect:
    kind: str          # "append_ordered", "reserve_slot", "increment", ...
    payload: dict
    commutative: bool
    invertible: bool


@dataclass
class Branch:
    id: str
    score: float
    trace: list[Effect] = field(default_factory=list)
    overlay_state: dict = field(default_factory=dict)


def select_and_commit(
    checkpoint: dict,
    branches: list[Branch],
    replay: Callable[[dict, list[Effect]], dict],
    is_quarantined: bool,
) -> dict:
    if not branches:
        raise SpeculativeCommitError("no branches to arbitrate")

    winner = max(branches, key=lambda b: b.score)

    # Invariant guard: parallel undo is only legal when every effect is
    # commutative AND invertible. Otherwise we require quarantine + replay.
    risky = [e for b in branches for e in b.trace if not (e.commutative and e.invertible)]
    if risky and not is_quarantined:
        raise SpeculativeCommitError(
            f"non-commutative or non-invertible effects present "
            f"({[e.kind for e in risky]}); parallel undo would corrupt canonical state. "
            f"Re-run branches under overlay quarantine and commit by replay."
        )

    # Prove winner trace reproduces claimed overlay from the checkpoint.
    replayed = replay(checkpoint, winner.trace)
    if replayed != winner.overlay_state:
        raise SpeculativeCommitError(
            f"winner {winner.id} trace-effect divergence: replay={replayed} "
            f"claimed={winner.overlay_state}; branch model of world is stale."
        )

    return replayed
