# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-speculatively-pre-execute-tool-calls-across-a-branch-and-verify-fan-out-and-then-discover-at-merge-time-that-the-rollback-of-a-lo.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-speculatively-pre-execute-tool-calls-across-a-branch-and-verify-fan-out-and-then-discover-at-merge-time-that-the-rollback-of-a-lo.warrant.json
# Markdown SHA-256:   1dffb36f67827aea0e69160efd642c84a37b858615afdf449bdb61e76ac8cad4
# Code AST SHA-256:   841f1a4bd939d5a0ddd16401e81ee980ee686026454703790de170cb0f76aafe
# Verified Classes:   StaleCompensationError, Effect, SpeculationLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleCompensationError(RuntimeError):
    """Raised when a rollback is attempted against a world state the effect never saw."""


@dataclass(frozen=True)
class Effect:
    branch_id: str
    effect_id: str
    resource_key: str
    snapshot_epoch: int
    committed: bool = False


class SpeculationLedger:
    def __init__(self) -> None:
        self._effects: dict[str, Effect] = {}
        self._selection_epoch: Optional[int] = None
        self._winner: Optional[str] = None

    def pre_execute(self, effect: Effect) -> None:
        # optimistic write; staged, not materialized
        self._effects[effect.effect_id] = effect

    def commit_selection(self, winner: str, epoch: int) -> None:
        self._selection_epoch = epoch
        self._winner = winner
        for eid, e in list(self._effects.items()):
            if e.branch_id == winner:
                self._effects[eid] = Effect(
                    e.branch_id, e.effect_id, e.resource_key,
                    e.snapshot_epoch, committed=True,
                )

    def compensate_loser(self, effect_id: str) -> None:
        e = self._effects.get(effect_id)
        if e is None:
            raise StaleCompensationError(f"unknown effect {effect_id}")
        if self._selection_epoch is None:
            raise StaleCompensationError(
                "compensation attempted before verifier selection; "
                "world state is not yet stable"
            )
        if e.snapshot_epoch < self._selection_epoch:
            # the effect was pre-executed against a pre-selection snapshot;
            # its inverse no longer matches current state -> do NOT apply
            raise StaleCompensationError(
                f"effect {effect_id} snapshot_epoch={e.snapshot_epoch} "
                f"< selection_epoch={self._selection_epoch}; "
                "compensation would alias a sibling mutation"
            )
        if e.committed:
            raise StaleCompensationError(
                f"effect {effect_id} belongs to winner {self._winner}; "
                "cannot compensate a committed effect"
            )
        # discard instead of undo — buffered regime
        del self._effects[effect_id]
