# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-branch-merges-when-rollback-is-non-atomic-across-shared-tool-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-branch-merges-when-rollback-is-non-atomic-across-shared-tool-side-effects.warrant.json
# Markdown SHA-256:   8f2e56bd94317543ec645d0af5bfb867e2020c9a6076e9d84caf12410f5b90dc
# Code AST SHA-256:   d752348be847864d6035a66072ee780bdfa561adac32cf3c982c5e0d15f4732d
# Verified Classes:   Reversibility, RollbackBoundaryViolation, Branch, FanOut
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class Reversibility(Enum):
    PRIVATE = "private"        # copy-on-write, discard is free
    COMPENSABLE = "compensable"  # registered compensating action
    COMMITTED = "committed"    # no rollback possible


class RollbackBoundaryViolation(RuntimeError):
    """Raised when a branch is discarded after committing a non-reversible effect."""


@dataclass
class Branch:
    branch_id: str
    rollback_vector: Dict[str, Reversibility] = field(default_factory=dict)

    def record_effect(self, resource: str, rev: Reversibility) -> None:
        # A resource is only as reversible as its least-reversible effect.
        prior = self.rollback_vector.get(resource)
        if prior is None or rev == Reversibility.COMMITTED or prior != Reversibility.COMMITTED:
            if rev == Reversibility.COMMITTED or prior is None:
                self.rollback_vector[resource] = rev
        if rev == Reversibility.COMMITTED:
            self.rollback_vector[resource] = Reversibility.COMMITTED

    def is_discardable(self) -> bool:
        return all(r != Reversibility.COMMITTED for r in self.rollback_vector.values())


@dataclass
class FanOut:
    branches: Dict[str, Branch] = field(default_factory=dict)

    def add(self, b: Branch) -> None:
        self.branches[b.branch_id] = b

    def discard_losers(self, winner_id: str) -> Set[str]:
        pinned = {bid for bid, b in self.branches.items() if not b.is_discardable()}
        losers = set(self.branches) - {winner_id}
        illegal = losers & pinned
        if illegal:
            raise RollbackBoundaryViolation(
                f"cannot discard branches {sorted(illegal)}: they committed "
                f"non-reversible effects; re-base merge against live state instead"
            )
        return losers

    def reconcile(self, winner_id: str, live_state: Dict[str, str]) -> Dict[str, str]:
        winner = self.branches[winner_id]
        orphans: Dict[str, str] = {}
        for bid, b in self.branches.items():
            if bid == winner_id:
                continue
            for resource, rev in b.rollback_vector.items():
                if rev == Reversibility.COMMITTED and resource in live_state:
                    orphans[resource] = bid
        if orphans:
            # Not corruption by the winner: attribute to siblings, do not fail merge.
            return {res: f"orphaned_by:{bid}" for res, bid in orphans.items()}
        return {}


def merge_speculative(fanout: FanOut, winner_id: str, live_state: Dict[str, str]) -> Dict[str, str]:
    fanout.discard_losers(winner_id)  # raises if boundary already crossed
    return fanout.reconcile(winner_id, live_state)
