# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-speculative-tool-call-pre-execution-when-side-effect-gating-and-compensation-transactions-disagree-at-commit-time.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-speculative-tool-call-pre-execution-when-side-effect-gating-and-compensation-transactions-disagree-at-commit-time.warrant.json
# Markdown SHA-256:   3996e956a8541e68142d6f5e715fab191445e72806de08ca8d2e8dce6479d399
# Code AST SHA-256:   03201396185c134526cb853afa484bd5d85bb779847d062edc84aac3cf5ec28e
# Verified Classes:   CompensationDivergence, SpeculationRefused, SpeculativeCall, CompensationLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class CompensationDivergence(RuntimeError):
    """Raised when a compensation reports success but the affected state
    does not match the pre-speculation snapshot."""
    pass


class SpeculationRefused(RuntimeError):
    """Raised when the gate is asked to admit a non-invertible or
    unbarriered speculative call."""
    pass


@dataclass
class SpeculativeCall:
    call_id: str
    effect_class: str          # "invertible_isolated" | "shared_resource" | "non_invertible"
    affected_objects: list[str]
    inverse: Any = None
    snapshot: dict[str, Any] = field(default_factory=dict)


class CompensationLedger:
    def __init__(self) -> None:
        self._locks: dict[str, str] = {}       # object_id -> call_id holding barrier
        self._entries: list[SpeculativeCall] = []

    def gate(self, call: SpeculativeCall, live_state: dict[str, Any]) -> None:
        if call.effect_class == "non_invertible":
            raise SpeculationRefused(
                f"{call.call_id}: non-invertible effect cannot be speculated"
            )
        if call.effect_class == "shared_resource":
            for obj in call.affected_objects:
                holder = self._locks.get(obj)
                if holder is not None and holder != call.call_id:
                    raise SpeculationRefused(
                        f"{call.call_id}: object {obj} already barriered by {holder}"
                    )
            # acquire barrier before effect becomes durable
            for obj in call.affected_objects:
                self._locks[obj] = call.call_id
        # snapshot live state for later divergence check
        call.snapshot = {o: live_state.get(o) for o in call.affected_objects}
        self._entries.append(call)

    def compensate_all(self, live_state: dict[str, Any]) -> None:
        for call in reversed(self._entries):
            # compute inverse against LIVE state, not gate-time snapshot
            if call.inverse is None:
                raise CompensationDivergence(
                    f"{call.call_id}: no registered inverse at compensation time"
                )
            call.inverse(live_state)
            # independent re-read: compensation success is not trusted
            for obj in call.affected_objects:
                if live_state.get(obj) != call.snapshot.get(obj):
                    raise CompensationDivergence(
                        f"{call.call_id}: object {obj} diverged after compensation; "
                        f"expected {call.snapshot.get(obj)!r}, got {live_state.get(obj)!r}"
                    )
            for obj in call.affected_objects:
                self._locks.pop(obj, None)
        self._entries.clear()
