# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-commits-when-parallel-tool-call-hedging-produces-divergent-but-individually-valid-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-branch-commits-when-parallel-tool-call-hedging-produces-divergent-but-individually-valid-side-effects.warrant.json
# Markdown SHA-256:   ade6fda2a57b1fe1a5cb6c08cf5f1bf438fd6ed499bfec7d9dd1f4d093fd19ae
# Code AST SHA-256:   313ebb033843e37b28bce700b8a473beb455078ed925cc17b4f8b7c995e51620
# Verified Classes:   SpeculativeCommitError, ReservationState, Reservation, SpeculativeGroup
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List


class SpeculativeCommitError(RuntimeError):
    """Raised when a speculative group is closed with unresolved external effects."""
    pass


class ReservationState(Enum):
    OPEN = "open"
    CONFIRMED = "confirmed"
    COMPENSATED = "compensated"


@dataclass
class Reservation:
    branch_id: str
    intent_key: str          # logical dedupe key, not provider ID
    provider_id: str
    state: ReservationState = ReservationState.OPEN


@dataclass
class SpeculativeGroup:
    winner_branch: str
    reservations: Dict[str, List[Reservation]] = field(default_factory=dict)

    def add(self, r: Reservation) -> None:
        self.reservations.setdefault(r.branch_id, []).append(r)

    def close(self) -> None:
        # Invariant: exactly one confirmed reservation per intent_key,
        # and no OPEN reservations remain anywhere in the group.
        by_intent: Dict[str, List[Reservation]] = {}
        for branch, rs in self.reservations.items():
            for r in rs:
                by_intent.setdefault(r.intent_key, []).append(r)

        for intent, rs in by_intent.items():
            confirmed = [r for r in rs if r.state is ReservationState.CONFIRMED]
            open_rs = [r for r in rs if r.state is ReservationState.OPEN]
            if open_rs:
                raise SpeculativeCommitError(
                    f"intent {intent!r} has {len(open_rs)} OPEN reservation(s) "
                    f"at group close; loser branches must be compensated first"
                )
            if len(confirmed) != 1:
                raise SpeculativeCommitError(
                    f"intent {intent!r} has {len(confirmed)} confirmed effects, "
                    f"expected exactly 1 (commit singularity violated)"
                )

        # Confirm winner's reservations, compensate every other branch's.
        for branch, rs in self.reservations.items():
            for r in rs:
                if branch != self.winner_branch and r.state is ReservationState.CONFIRMED:
                    raise SpeculativeCommitError(
                        f"non-winner branch {branch!r} confirmed intent {r.intent_key!r}"
                    )


def reconcile(group: SpeculativeGroup, compensate_fn) -> None:
    # Drain losers' open reservations before allowing close.
    for branch, rs in group.reservations.items():
        if branch == group.winner_branch:
            continue
        for r in rs:
            if r.state is ReservationState.OPEN:
                compensate_fn(r)
                r.state = ReservationState.COMPENSATED
    group.close()
