# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-merges-speculative-branches-whose-side-effects-already-escaped-the-sandbox.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-merges-speculative-branches-whose-side-effects-already-escaped-the-sandbox.warrant.json
# Markdown SHA-256:   62968db6fffdc37dcb46ca9462798b13246f38926a19c1dc107df59419c474a8
# Code AST SHA-256:   56abbb6850c0e80c2f8aac15d038d68b7eed54732b9db5534b16f7aedbad486b
# Verified Classes:   EffectClass, SpeculationEscapeError, Effect, Branch
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Callable, Optional


class EffectClass(Enum):
    READ = "read"
    REVERSIBLE = "reversible"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


class SpeculationEscapeError(RuntimeError):
    """Raised when a branch commits an external effect that the arbiter
    cannot reverse, invalidating the transactional assumption of the window."""


@dataclass
class Effect:
    tool: str
    effect_class: EffectClass
    external_ref: Optional[str] = None
    compensate: Optional[Callable[[str], None]] = None


@dataclass
class Branch:
    branch_id: str
    overlay: dict = field(default_factory=dict)
    effect_log: list = field(default_factory=list)
    committed: bool = False

    def record_effect(self, effect: Effect) -> None:
        # Invariant: an external effect may only be recorded if its inverse
        # is registered in the SAME atomic step. Otherwise the branch is
        # contaminated and cannot be safely discarded.
        if effect.effect_class is EffectClass.IRREVERSIBLE:
            raise SpeculationEscapeError(
                f"branch {self.branch_id} attempted irreversible effect "
                f"{effect.tool!r} inside a speculative window"
            )
        if effect.effect_class is EffectClass.COMPENSABLE and effect.compensate is None:
            raise SpeculationEscapeError(
                f"branch {self.branch_id} recorded compensable effect "
                f"{effect.tool!r} with no registered inverse"
            )
        self.effect_log.append(effect)
        if effect.external_ref is not None:
            self.overlay[f"ref:{effect.tool}"] = effect.external_ref


def rollback(branch: Branch) -> None:
    """Revert a discarded branch. Must replay the compensation log BEFORE
    discarding the overlay, or the overlay's external refs become orphans."""
    for effect in reversed(branch.effect_log):
        if effect.effect_class is EffectClass.COMPENSABLE:
            if effect.compensate is None:
                raise SpeculationEscapeError(
                    f"cannot roll back {branch.branch_id}: effect "
                    f"{effect.tool!r} has no inverse"
                )
            effect.compensate(effect.external_ref)
        elif effect.effect_class is EffectClass.IRREVERSIBLE:
            raise SpeculationEscapeError(
                f"cannot roll back {branch.branch_id}: irreversible effect "
                f"{effect.tool!r} already escaped to external system"
            )
    branch.overlay.clear()
    branch.effect_log.clear()


def arbitrate(branches: list, winner_id: str) -> Branch:
    winner = next((b for b in branches if b.branch_id == winner_id), None)
    if winner is None:
        raise SpeculationEscapeError(f"no branch {winner_id!r} in window")
    for b in branches:
        if b.branch_id == winner_id:
            b.committed = True
            continue
        # Pre-check: any un-compensated escape contaminates the window.
        for effect in b.effect_log:
            if effect.effect_class is EffectClass.IRREVERSIBLE:
                raise SpeculationEscapeError(
                    f"window contaminated: branch {b.branch_id} escaped "
                    f"irreversible effect {effect.tool!r}; cannot discard"
                )
        rollback(b)
    return winner
