# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-halt-a-speculative-branch-when-rollback-cannot-restore-an-externally-mutated-tool-state.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-halt-a-speculative-branch-when-rollback-cannot-restore-an-externally-mutated-tool-state.warrant.json
# Markdown SHA-256:   74d0664e98b66eef95ddfdd8b9c2d5d1a8df30cfda667aeb74392cd06825c323
# Code AST SHA-256:   7bb499ae22d81786472f35646548affad08c5d1035a24e0325d7261c63618fa0
# Verified Classes:   ReversibilityClass, ForkState, SpeculativeLeakError, ToolContract, Branch, ForkPoint, Reconciler
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ReversibilityClass(Enum):
    PRIVATE = "private"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


class ForkState(Enum):
    SPECULATING = "speculating"
    COMMITTED = "committed"
    FROZEN = "frozen"


class SpeculativeLeakError(RuntimeError):
    """Raised when a branch crosses into an irreversible external effect
    before its fork point has committed it, or when a compensable effect
    cannot be proven reversed on discard."""


@dataclass
class ToolContract:
    name: str
    klass: ReversibilityClass
    # compensation is only meaningful for COMPENSABLE tools
    compensation_id: Optional[str] = None


@dataclass
class Branch:
    branch_id: str
    fork_id: str
    deferred_effects: list = field(default_factory=list)
    registered_compensations: list = field(default_factory=list)


@dataclass
class ForkPoint:
    fork_id: str
    state: ForkState = ForkState.SPECULATING
    committed_branch: Optional[str] = None
    unreconciled: set = field(default_factory=set)


class Reconciler:
    def __init__(self) -> None:
        self.forks: dict[str, ForkPoint] = {}

    def register_fork(self, fork_id: str) -> ForkPoint:
        fp = ForkPoint(fork_id=fork_id)
        self.forks[fork_id] = fp
        return fp

    def invoke_tool(self, branch: Branch, tool: ToolContract, args: dict, executor) -> dict:
        fork = self.forks[branch.fork_id]

        if fork.state == ForkState.FROZEN:
            raise SpeculativeLeakError(
                f"fork {fork.fork_id} frozen by unreconciled leak "
                f"{sorted(fork.unreconciled)}; branch {branch.branch_id} may not act"
            )

        committed = (
            fork.state == ForkState.COMMITTED
            and fork.committed_branch == branch.branch_id
        )

        if tool.klass == ReversibilityClass.IRREVERSIBLE and not committed:
            # defer: do not touch the world from a speculative branch
            branch.deferred_effects.append((tool.name, args))
            return {"status": "deferred", "reason": "awaits fork commit"}

        if tool.klass == ReversibilityClass.COMPENSABLE and not committed:
            if not tool.compensation_id:
                raise SpeculativeLeakError(
                    f"tool {tool.name} is COMPENSABLE but declares no compensation_id"
                )
            # two-phase: register intent BEFORE the effect
            branch.registered_compensations.append(
                (tool.compensation_id, args.copy())
            )

        return executor(tool.name, args)

    def discard(self, branch: Branch) -> str:
        fork = self.forks[branch.fork_id]

        # compensate every registered class-2 effect; fail closed
        for comp_id, args in branch.registered_compensations:
            ok = self._compensate(comp_id, args)
            if not ok:
                fork.unreconciled.add(branch.branch_id)
                fork.state = ForkState.FROZEN
                raise SpeculativeLeakError(
                    f"compensation {comp_id} failed for branch {branch.branch_id}; "
                    f"fork {fork.fork_id} frozen, siblings may not commit"
                )

        # deferred class-3 effects are dropped, never fired
        branch.deferred_effects.clear()
        return "DISCARDED_COMPENSATED" if branch.registered_compensations else "DISCARDED_CLEAN"

    def commit(self, branch: Branch, executor) -> None:
        fork = self.forks[branch.fork_id]
        if fork.unreconciled:
            raise SpeculativeLeakError(
                f"cannot commit {branch.branch_id}: fork {fork.fork_id} has "
                f"unreconciled leaks {sorted(fork.unreconciled)}"
            )
        fork.state = ForkState.COMMITTED
        fork.committed_branch = branch.branch_id
        for name, args in branch.deferred_effects:
            executor(name, args)
        branch.deferred_effects.clear()

    def _compensate(self, comp_id: str, args: dict) -> bool:
        # real impl calls the inverse tool with idempotent retry
        return True
