# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-commit-a-speculative-tool-call-when-a-compensating-transaction-cannot-restore-the-pre-speculation-inv.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-commit-a-speculative-tool-call-when-a-compensating-transaction-cannot-restore-the-pre-speculation-inv.warrant.json
# Markdown SHA-256:   0be6684c6ce7febaf02b4fa7d83121feffa08714e5bb0843c24df819a51b7c30
# Code AST SHA-256:   ad85b161428ae62103cdb7cc8e6676d4f7e231b7e54bf01e30fc923a3aab7d45
# Verified Classes:   SpeculationInvariantError, CompensationStatus, LedgerEntry, SpeculationLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class SpeculationInvariantError(RuntimeError):
    """Raised when a speculative tool call cannot be safely compensated
    or when the speculation ledger disagrees with the environment at commit time."""


class CompensationStatus(Enum):
    NONE = "none"
    PENDING = "pending"
    ISSUED = "issued"
    CONFIRMED = "confirmed"
    FAILED = "failed"


@dataclass
class LedgerEntry:
    branch_id: str
    tool_call_id: str
    reservation_id: Optional[str]
    compensation: CompensationStatus = CompensationStatus.NONE
    environment_live: bool = True


@dataclass
class SpeculationLedger:
    entries: dict = field(default_factory=dict)

    def record(self, branch_id: str, tool_call_id: str, reservation_id: str) -> None:
        self.entries[(branch_id, tool_call_id)] = LedgerEntry(
            branch_id=branch_id, tool_call_id=tool_call_id, reservation_id=reservation_id
        )

    def mark_compensated(self, branch_id: str, tool_call_id: str, confirmed: bool) -> None:
        entry = self.entries[(branch_id, tool_call_id)]
        entry.compensation = (
            CompensationStatus.CONFIRMED if confirmed else CompensationStatus.FAILED
        )
        entry.environment_live = not confirmed

    def live_entries(self) -> list:
        return [e for e in self.entries.values() if e.environment_live]


def admit_speculation(tool, branch_id: str, ledger: SpeculationLedger) -> bool:
    if not tool.has_compensation:
        return False
    if not tool.compensation.preserves_observed_fields(tool.read_set):
        # reserve_inventory/release_reservation mutates `availability`, which is
        # in the read set of the next speculative call. Not speculable.
        return False
    if not tool.compensation.is_idempotent:
        return False
    return True


def commit_branch(branch_id: str, ledger: SpeculationLedger, environment) -> None:
    """Guardrail: assert ledger matches environment before any committing call."""
    for entry in ledger.entries.values():
        if entry.branch_id == branch_id:
            continue
        if entry.compensation not in (CompensationStatus.CONFIRMED, CompensationStatus.FAILED):
            raise SpeculationInvariantError(
                f"branch {entry.branch_id} compensation not terminal "
                f"({entry.compensation}); refusing to commit {branch_id}"
            )

    for entry in ledger.live_entries():
        if entry.branch_id == branch_id:
            continue
        still_live = environment.reservation_exists(entry.reservation_id)
        if still_live:
            # Environment says live, ledger says compensated -> divergence.
            raise SpeculationInvariantError(
                f"ledger marks {entry.reservation_id} compensated but environment "
                f"reports it live; reconciliation required before commit"
            )

    for entry in ledger.entries.values():
        if entry.compensation == CompensationStatus.CONFIRMED and entry.branch_id != branch_id:
            if environment.reservation_exists(entry.reservation_id):
                raise SpeculationInvariantError(
                    f"compensation for {entry.reservation_id} did not restore "
                    f"pre-speculation availability; read set mutated"
                )
