# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-speculatively-fork-a-branch-it-can-never-reconcile-when-rollback-cost-exceeds-the-value-of-the-speculative-result.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-speculatively-fork-a-branch-it-can-never-reconcile-when-rollback-cost-exceeds-the-value-of-the-speculative-result.warrant.json
# Markdown SHA-256:   4deee7830565bbbfb92e8a87dde8b702b20c4708ffe78832e18ead9e5ad79f3b
# Code AST SHA-256:   68492d9c28b734a1b11418b2901bbbd003b1c02ce765ad62b5a3291dc1e9e782
# Verified Classes:   IrreversibleSpeculationError, EffectClass, ToolSpec, SpeculativeBranch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class IrreversibleSpeculationError(RuntimeError):
    """Raised when a speculative branch would exceed its rollback budget
    or be discarded with un-compensated irreversible debt."""
    pass


class EffectClass(Enum):
    REVERSIBLE = "reversible"
    IRREVERSIBLE = "irreversible"


@dataclass
class ToolSpec:
    name: str
    effect: EffectClass
    compensation: Optional[Callable[[dict], None]] = None  # None => no undo exists


@dataclass
class SpeculativeBranch:
    branch_id: str
    expected_survival_value: float          # expected value of keeping this branch
    rollback_debt: float = 0.0
    compensations: list = field(default_factory=list)
    committed: bool = False

    def invoke(self, tool: ToolSpec, args: dict) -> None:
        if tool.effect is EffectClass.IRREVERSIBLE:
            projected = self.rollback_debt + tool_cost(tool)
            if projected > self.expected_survival_value:
                # Commit gate: block rather than borrow against a budget we lack.
                raise IrreversibleSpeculationError(
                    f"branch {self.branch_id}: irreversible effect {tool.name} "
                    f"would push rollback_debt to {projected:.2f} > "
                    f"survival value {self.expected_survival_value:.2f}"
                )
            if tool.compensation is None:
                raise IrreversibleSpeculationError(
                    f"branch {self.branch_id}: tool {tool.name} is irreversible "
                    f"with no registered compensation; cannot speculate safely"
                )
            self.rollback_debt = projected
            self.compensations.append((tool.compensation, args))
        # execute the (possibly effectful) call only after the gate passes
        _execute(tool, args)

    def discard(self) -> None:
        if self.committed:
            return
        if self.rollback_debt > 0 and not self.compensations:
            # Must not silently drop context with nonzero debt.
            raise IrreversibleSpeculationError(
                f"branch {self.branch_id}: discard with rollback_debt="
                f"{self.rollback_debt:.2f} and no compensations; "
                f"escalate to reconciliation instead of dropping context"
            )
        for comp, args in reversed(self.compensations):
            comp(args)
        self.rollback_debt = 0.0
        self.compensations.clear()


def tool_cost(tool: ToolSpec) -> float:
    # cost to reverse this effect; caller may inject a richer model
    return 0.0 if tool.effect is EffectClass.REVERSIBLE else 1.0


def _execute(tool: ToolSpec, args: dict) -> None:
    # placeholder for the real tool dispatch
    pass
