# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-fork-speculative-branch-divergence-and-the-rollback-unsafe-side-effect-invariant-in-multi-agent-convergence.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-fork-speculative-branch-divergence-and-the-rollback-unsafe-side-effect-invariant-in-multi-agent-convergence.warrant.json
# Markdown SHA-256:   724c4efc402df4f48bffa532753316b596e003f6538652f78b9b60e5ad34930f
# Code AST SHA-256:   bdfcdc2b4b9793f983abec32af0bc71827be574afb617ab9abeb4a49057b30c5
# Verified Classes:   EffectClass, RollbackUnsafeForkError, CompensationLedgerMismatch, Tool, Branch, ForkOrchestrator
# 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"
    EFFECTFUL_UNCOMPENSATED = "effectful_uncompensated"


class RollbackUnsafeForkError(RuntimeError):
    """Raised when a speculative fork would dispatch an effect with no verified inverse."""


class CompensationLedgerMismatch(RuntimeError):
    """Raised when a losing branch's inverse cannot be verified at convergence."""


@dataclass
class Tool:
    name: str
    effect: EffectClass
    inverse: Callable[[dict], bool] | None = None  # returns True iff postcondition verified


@dataclass
class Branch:
    branch_id: str
    confidence: float
    dispatched: list[tuple[str, dict]] = field(default_factory=list)


class ForkOrchestrator:
    def __init__(self, checkpoint_precedes_effects: bool):
        # The fork point must be the last point where the environment is equal
        # across all branches. If a shared preflight already mutated the world,
        # no branch-level rollback can undo it.
        self.checkpoint_precedes_effects = checkpoint_precedes_effects
        self.ledger: dict[str, list[tuple[Tool, dict]]] = {}

    def assert_fork_safe(self, reachable: list[Tool]) -> None:
        if not self.checkpoint_precedes_effects:
            raise RollbackUnsafeForkError(
                "fork point postdates a shared effect; branch rollback cannot restore world state"
            )
        unsafe = [
            t.name for t in reachable
            if t.effect is EffectClass.EFFECTFUL_UNCOMPENSATED
            or (t.effect is EffectClass.COMPENSABLE and t.inverse is None)
        ]
        if unsafe:
            raise RollbackUnsafeForkError(
                f"fork not rollback-safe: uncompensated effectful tools in closure {unsafe}"
            )

    def dispatch(self, branch: Branch, tool: Tool, args: dict) -> None:
        # Write intent to the ledger BEFORE dispatch so a mid-call crash
        # still leaves a record of the effect.
        if tool.effect is not EffectClass.PURE:
            self.ledger.setdefault(branch.branch_id, []).append((tool, args))
        branch.dispatched.append((tool.name, args))

    def converge(self, branches: list[Branch], winner_id: str) -> None:
        for b in branches:
            if b.branch_id == winner_id:
                continue
            for tool, args in reversed(self.ledger.get(b.branch_id, [])):
                if tool.inverse is None:
                    raise CompensationLedgerMismatch(
                        f"losing branch {b.branch_id} dispatched {tool.name} with no inverse"
                    )
                if not tool.inverse(args):
                    raise CompensationLedgerMismatch(
                        f"inverse of {tool.name} failed postcondition for branch {b.branch_id}"
                    )
            # Only now is memory restoration legitimate: the world has been
            # annihilated back to the fork point.
            self.ledger[b.branch_id] = []
