# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-execution-from-committing-side-effects-it-cannot-compensate.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-execution-from-committing-side-effects-it-cannot-compensate.warrant.json
# Markdown SHA-256:   ab4290225ac72ee0589607ef65fb27da04056db6e9dd180a2ba3f40d04d9db32
# Code AST SHA-256:   ea19b88c668ac5bb9d3accedafc264cfe01483d6714c98ea4745fe1adb4e8069
# Verified Classes:   SpeculationInvariantError, ReversibilityClass, ToolContract, Intent, SpeculativeExecutor
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Any


class SpeculationInvariantError(RuntimeError):
    """Raised when a speculative tool call would cross the commitment boundary
    or when a promotion/release violates intent-keyed idempotency."""


class ReversibilityClass(Enum):
    REVERSIBLE = "reversible"
    COMPENSABLE_WITH_RESIDUE = "compensable_with_residue"
    IRREVERSIBLE = "irreversible"


@dataclass(frozen=True)
class ToolContract:
    name: str
    reversibility: ReversibilityClass
    supports_reservation: bool
    residue_set: frozenset[str] = field(default_factory=frozenset)


@dataclass(frozen=True)
class Intent:
    """Logical intent, stripped of branch/attempt. The unit of deduplication."""
    tool: str
    params: tuple[tuple[str, Any], ...]

    def key(self) -> str:
        h = hashlib.sha256()
        h.update(self.tool.encode())
        for k, v in self.params:
            h.update(k.encode())
            h.update(repr(v).encode())
        return h.hexdigest()


class SpeculativeExecutor:
    def __init__(self, contracts: dict[str, ToolContract]) -> None:
        self._contracts = contracts
        self._reservations: dict[str, str] = {}   # intent_key -> reservation_id
        self._promotions: dict[str, str] = {}     # intent_key -> resource_id
        self._ledger: list[tuple[str, str]] = []  # (intent_key, event)

    def speculate(self, intent: Intent) -> str:
        contract = self._contracts[intent.tool]
        if not contract.supports_reservation:
            raise SpeculationInvariantError(
                f"tool {intent.tool!r} has no reservation primitive; "
                f"speculation would cross the commitment boundary"
            )
        if contract.reversibility is ReversibilityClass.IRREVERSIBLE:
            raise SpeculationInvariantError(
                f"tool {intent.tool!r} is IRREVERSIBLE; speculative execution forbidden"
            )
        key = intent.key()
        if key in self._reservations:
            return self._reservations[key]
        rid = f"resv:{key[:16]}"
        self._reservations[key] = rid
        self._ledger.append((key, f"reserved:{rid}"))
        return rid

    def promote(self, intent: Intent) -> str:
        key = intent.key()
        if key in self._promotions:
            # Idempotent: second promotion of the same intent is a no-op.
            self._ledger.append((key, "promote_deduplicated"))
            return self._promotions[key]
        if key not in self._reservations:
            raise SpeculationInvariantError(
                f"promotion of intent {key[:16]} without a reservation; "
                f"this commits an effect the agent cannot attribute to a branch"
            )
        resource_id = f"res:{key[:16]}"
        self._promotions[key] = resource_id
        self._ledger.append((key, f"committed:{resource_id}"))
        return resource_id

    def release(self, intent: Intent) -> None:
        key = intent.key()
        if key in self._promotions:
            raise SpeculationInvariantError(
                f"release of intent {key[:16]} after promotion; "
                f"use compensation, not release, for committed intents"
            )
        self._reservations.pop(key, None)
        self._ledger.append((key, "released"))

    def compensate(self, intent: Intent) -> None:
        key = intent.key()
        contract = self._contracts[intent.tool]
        if key not in self._promotions:
            raise SpeculationInvariantError(
                f"compensation of unpromoted intent {key[:16]}; "
                f"speculation must never require compensation"
            )
        if contract.reversibility is ReversibilityClass.IRREVERSIBLE:
            raise SpeculationInvariantError(
                f"tool {intent.tool!r} is IRREVERSIBLE; compensation is undefined"
            )
        self._ledger.append((key, f"compensated:residue={sorted(contract.residue_set)}"))


def hedge_two_branches(executor: SpeculativeExecutor, intent: Intent) -> str:
    """Both branches speculate on the same logical intent; only one promotes."""
    executor.speculate(intent)  # branch A
    executor.speculate(intent)  # branch B -> same intent key, same reservation
    winner = executor.promote(intent)  # branch A promotes
    executor.promote(intent)           # branch B promotes -> deduplicated no-op
    return winner
