# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-speculative-branch-executor-corrupt-the-canonical-state-when-its-rollback-boundary-is-drawn-at-the-tool-call-layer-instead-o.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-speculative-branch-executor-corrupt-the-canonical-state-when-its-rollback-boundary-is-drawn-at-the-tool-call-layer-instead-o.warrant.json
# Markdown SHA-256:   63e87e35b5d6b449e8d570400b7b6a6c9282f0fa069ea4fa5085b43da3fa004d
# Code AST SHA-256:   d3ef0f719600067ab54964df69654f67521e6467be2c232ec521e93ab510dd1d
# Verified Classes:   RollbackDiscipline, ToolSafety, UnsafeSpeculationError, PostRollbackDivergenceError, ToolSpec, Branch
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum

class RollbackDiscipline(Enum):
    SHADOW = "shadow"
    COMPENSATING = "compensating"
    NONE = "none"

class ToolSafety(Enum):
    READ_ONLY = "read_only"
    IDEMPOTENT = "idempotent"
    COMPENSABLE = "compensable"
    UNROLLBACKABLE = "unrollbackable"

class UnsafeSpeculationError(RuntimeError):
    """Raised when a branch is forked over a reachable tool set that the
    chosen rollback discipline cannot invert."""
    pass

class PostRollbackDivergenceError(RuntimeError):
    """Raised when, after replaying compensations, the external store does
    not match the pre-branch snapshot for a touched key."""
    pass

@dataclass
class ToolSpec:
    name: str
    safety: ToolSafety

@dataclass
class Branch:
    branch_id: str
    reachable_tools: set[str]
    effects: list[tuple[str, dict]] = field(default_factory=list)

def admit_branch(branch: Branch, registry: dict[str, ToolSpec],
                 discipline: RollbackDiscipline) -> None:
    if discipline is RollbackDiscipline.SHADOW:
        # Shadow requires every effect be interceptable; we approximate by
        # requiring the tool to be known and not explicitly unrollbackable.
        for name in branch.reachable_tools:
            spec = registry.get(name)
            if spec is None or spec.safety is ToolSafety.UNROLLBACKABLE:
                raise UnsafeSpeculationError(
                    f"branch {branch.branch_id}: tool {name!r} cannot be "
                    f"shadowed under discipline {discipline.value}"
                )
        return
    if discipline is RollbackDiscipline.COMPENSATING:
        for name in branch.reachable_tools:
            spec = registry.get(name)
            if spec is None:
                raise UnsafeSpeculationError(
                    f"branch {branch.branch_id}: unknown tool {name!r}"
                )
            if spec.safety not in (ToolSafety.READ_ONLY,
                                   ToolSafety.IDEMPOTENT,
                                   ToolSafety.COMPENSABLE):
                raise UnsafeSpeculationError(
                    f"branch {branch.branch_id}: tool {name!r} has safety "
                    f"{spec.safety.value}; not compensable, fork refused"
                )
        return
    raise UnsafeSpeculationError(
        f"branch {branch.branch_id}: no rollback discipline permits "
        f"speculative fork over shared mutable state"
    )

def rollback(branch: Branch, snapshot: dict[str, object],
             current: dict[str, object],
             compensations: list[tuple[str, dict]]) -> None:
    # Replay compensations in reverse emission order.
    for tool_name, args in reversed(compensations):
        _invoke_compensation(tool_name, args)
    # Verify the store returned to the pre-branch snapshot on touched keys.
    touched = {k for _, args in branch.effects for k in args.get("keys", ())}
    for key in touched:
        if current.get(key) != snapshot.get(key):
            raise PostRollbackDivergenceError(
                f"branch {branch.branch_id}: key {key!r} expected "
                f"{snapshot.get(key)!r} after rollback, found "
                f"{current.get(key)!r}; canonical merge must halt"
            )

def _invoke_compensation(tool_name: str, args: dict) -> None:
    # Placeholder: real implementation dispatches to the registered inverse.
    return None
