# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-unverified-speculative-tool-call-commit-has-already-escaped-the-rollback-horizon.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-unverified-speculative-tool-call-commit-has-already-escaped-the-rollback-horizon.warrant.json
# Markdown SHA-256:   e035c8b924815161b6f22280c8dd1cb12fba3bbda4e2b625efbdf2720c8fd568
# Code AST SHA-256:   ffcf3379708b68e59cbe1e8244fb943890c22be47e095d7205ebf1dfbee1d0c2
# Verified Classes:   EffectClass, RollbackHorizonBreach, ToolCall, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Set


class EffectClass(Enum):
    STAGED = "staged"          # buffered, not yet visible to remote authority
    REVOCABLE = "revocable"    # visible but unilaterally undoable
    IRREVOCABLE = "irrevocable"  # durable, observable consequence exists


class RollbackHorizonBreach(RuntimeError):
    """Raised when a branch is asked to roll back but has already
    surrendered an effect past the point of unilateral reversal."""
    pass


@dataclass
class ToolCall:
    call_id: str
    effect_class: EffectClass
    acknowledged: bool = False
    remote_id: str | None = None
    compensation: str | None = None


@dataclass
class Branch:
    branch_id: str
    issued: Dict[str, ToolCall] = field(default_factory=dict)
    rolled_back: bool = False

    def dispatch(self, call: ToolCall) -> None:
        self.issued[call.call_id] = call

    def revocable_ids(self) -> Set[str]:
        # Recomputed from acknowledgment state, NOT from dispatch bookkeeping.
        return {
            c.call_id
            for c in self.issued.values()
            if c.effect_class in (EffectClass.STAGED, EffectClass.REVOCABLE)
            and not (c.acknowledged and c.remote_id is not None)
        }

    def escaped_ids(self) -> Set[str]:
        return set(self.issued) - self.revocable_ids()


def rollback(branch: Branch) -> None:
    escaped = branch.escaped_ids()
    if escaped:
        # Do not silently mark rolled_back. Refuse and surface the breach.
        raise RollbackHorizonBreach(
            f"branch {branch.branch_id} cannot be rolled back: "
            f"effects {sorted(escaped)} have escaped the rollback horizon "
            f"(acknowledged with durable remote IDs). "
            f"Promote to partially-committed and run compensation."
        )
    for call_id in branch.revocable_ids():
        # ... issue revocation to remote authority ...
        pass
    branch.rolled_back = True


def commit(branch: Branch) -> None:
    # A branch with escaped irreversibles may only commit if every
    # escaped effect has a defined compensation.
    for call_id in branch.escaped_ids():
        call = branch.issued[call_id]
        if call.effect_class is EffectClass.IRREVOCABLE and call.compensation is None:
            raise RollbackHorizonBreach(
                f"branch {branch.branch_id} has irrevocable effect {call_id} "
                f"with no compensation; cannot safely commit or discard."
            )
    # ... commit branch ...
