# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-executes-a-branch-that-a-sibling-agent-has-already-committed-to-durable-state.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-executes-a-branch-that-a-sibling-agent-has-already-committed-to-durable-state.warrant.json
# Markdown SHA-256:   e40cf5d824d94129bf74c6be04bd44714ca7344d34b214c308d43b50e9624724
# Code AST SHA-256:   e92e573d774f8a8fa02e0bf7e1f860ecf26ac6228cc6e31c71e60e9b27547651
# Verified Classes:   EffectClass, RollbackFictionError, Effect, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class EffectClass(Enum):
    PURE = "pure"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


class RollbackFictionError(RuntimeError):
    """Raised when a branch is marked rolled back while an irreversible
    or uncompensated effect persists in shared world-state."""
    pass


@dataclass
class Effect:
    tool: str
    klass: EffectClass
    inverse: Callable[[], None] | None = None
    replayed: bool = False


@dataclass
class Branch:
    branch_id: str
    effects: list[Effect] = field(default_factory=list)
    committed: bool = False

    def call(self, tool: str, klass: EffectClass, inverse=None, **kwargs):
        if klass is EffectClass.IRREVERSIBLE and not self._holds_exclusive_lock(tool):
            raise RollbackFictionError(
                f"branch {self.branch_id}: IRREVERSIBLE tool {tool!r} "
                f"invoked without exclusive lock; rollback would be nominal"
            )
        if klass is EffectClass.COMPENSABLE and inverse is None:
            raise RollbackFictionError(
                f"branch {self.branch_id}: COMPENSABLE tool {tool!r} "
                f"invoked without registered inverse; effect would leak on rollback"
            )
        # ... perform the effect ...
        self.effects.append(Effect(tool=tool, klass=klass, inverse=inverse))

    def _holds_exclusive_lock(self, tool: str) -> bool:
        return False  # conservative default; real impl checks lock table


def reconcile(winner: Branch, losers: list[Branch]) -> None:
    winner.committed = True
    for b in losers:
        for eff in reversed(b.effects):
            if eff.klass is EffectClass.IRREVERSIBLE:
                raise RollbackFictionError(
                    f"branch {b.branch_id}: cannot roll back IRREVERSIBLE "
                    f"effect {eff.tool!r}; escalate to coordinator"
                )
            if eff.inverse is None:
                raise RollbackFictionError(
                    f"branch {b.branch_id}: effect {eff.tool!r} has no inverse; "
                    f"world-state will diverge from branch disposition"
                )
            eff.inverse()
            eff.replayed = True
        # Only now is the rollback a true discard.
