# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-tool-call-execution-when-compensating-transactions-are-not-inverse-and-idempotency-keys-are-not-yet-durable.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-tool-call-execution-when-compensating-transactions-are-not-inverse-and-idempotency-keys-are-not-yet-durable.warrant.json
# Markdown SHA-256:   c2cbed5e3014e77a3525b822691bf4000bd4c4020acfa66008cb80448efc5cda
# Code AST SHA-256:   f9af6aba0f3b1b49f370b3c63a6ad8fcb818a8f46b1750caafd4deb4cf723cee
# Verified Classes:   Reversibility, SpeculationBoundaryError, EffectRecord, ToolDescriptor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class Reversibility(Enum):
    FULL = "full"        # compensation restores exact prior state
    PARTIAL = "partial"  # compensation leaves residue (refund vs un-charge)
    NONE = "none"        # irreversible (send, delete, external webhook)


class SpeculationBoundaryError(RuntimeError):
    """Raised when a speculative tool call would cross the reversibility/durability boundary."""


@dataclass(frozen=True)
class EffectRecord:
    idempotency_key: str
    compensation_handle: str | None
    durable: bool


@dataclass(frozen=True)
class ToolDescriptor:
    name: str
    reversibility: Reversibility
    compensation_idempotent: bool


def authorize_speculative_call(
    tool: ToolDescriptor,
    record: EffectRecord,
    loss_budget_remaining: float,
    rejection_probability: float,
    residue_estimate: float,
) -> None:
    """
    Gate a speculative side-effecting call. The instance must call this BEFORE
    dispatching the tool. Raises if the call is on the unsafe side of the boundary.
    """
    # Durability invariant: a lost key or handle makes any tool effectively irreversible.
    if not record.durable or record.compensation_handle is None:
        raise SpeculationBoundaryError(
            f"speculative call to {tool.name!r} refused: idempotency key or "
            f"compensation handle not durably recorded before dispatch"
        )

    if not tool.compensation_idempotent:
        raise SpeculationBoundaryError(
            f"speculative call to {tool.name!r} refused: compensation is not keyed, "
            f"a retried compensation could double-apply"
        )

    if tool.reversibility is Reversibility.NONE:
        raise SpeculationBoundaryError(
            f"speculative call to {tool.name!r} refused: irreversibility class NONE "
            f"cannot be speculated; gate behind resolved branch"
        )

    if tool.reversibility is Reversibility.PARTIAL:
        expected_residue = rejection_probability * residue_estimate
        if expected_residue > loss_budget_remaining:
            raise SpeculationBoundaryError(
                f"speculative call to {tool.name!r} refused: expected non-inverse "
                f"residue {expected_residue:.3f} exceeds budget {loss_budget_remaining:.3f}"
            )


def execute_speculative(tool, record, **kwargs):
    authorize_speculative_call(
        tool=tool,
        record=record,
        loss_budget_remaining=kwargs.pop("_loss_budget", 0.0),
        rejection_probability=kwargs.pop("_p_reject", 1.0),
        residue_estimate=kwargs.pop("_residue", 0.0),
    )
    # dispatch only after the durable record exists and the class permits it
    return _dispatch(tool, record.idempotency_key, **kwargs)
