# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-speculative-fan-out-when-a-divergent-tool-outcome-invalidates-a-sibling-branch-s-committed-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-speculative-fan-out-when-a-divergent-tool-outcome-invalidates-a-sibling-branch-s-committed-side-effects.warrant.json
# Markdown SHA-256:   ad034777d1531206579aac8b18df07a0f65b5e88e2a924814cb903e76a73b9c3
# Code AST SHA-256:   120f6d0ac84392baf0a47ef1e12e31026f360326fe9cc99c936be429d673bdc1
# Verified Classes:   SpeculationBoundaryError, Reversibility, ToolProfile, Effect, Branch
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class SpeculationBoundaryError(RuntimeError):
    """Raised when a speculative branch externalizes an effect that rollback cannot faithfully compensate."""


class Reversibility(Enum):
    TOTAL = "total"
    PARTIAL = "partial"
    NONE = "none"


@dataclass
class ToolProfile:
    name: str
    reversibility: Reversibility
    honors_undo: bool


@dataclass
class Effect:
    branch_id: str
    tool: str
    undo_token: Optional[str]
    observed_version: Optional[int] = None


@dataclass
class Branch:
    branch_id: str
    effects: list = field(default_factory=list)
    read_coupled_derived_state: list = field(default_factory=list)


TOOLS = {
    "record_store.write": ToolProfile("record_store.write", Reversibility.PARTIAL, honors_undo=True),
    "email.send": ToolProfile("email.send", Reversibility.NONE, honors_undo=False),
    "cache.get": ToolProfile("cache.get", Reversibility.TOTAL, honors_undo=True),
}


def assert_speculatable(branch: Branch, sibling_ids: list) -> None:
    """Enforce the boundary before allowing a branch to externalize effects alongside live siblings."""
    for eff in branch.effects:
        profile = TOOLS.get(eff.tool)
        if profile is None:
            raise SpeculationBoundaryError(f"unregistered tool {eff.tool!r} cannot be speculated")
        if profile.reversibility is Reversibility.NONE:
            raise SpeculationBoundaryError(
                f"branch {branch.branch_id} externalized irreversible effect via {eff.tool!r} "
                f"while siblings {sibling_ids} were live; must serialize after arbitration"
            )
        if profile.reversibility is Reversibility.PARTIAL and not profile.honors_undo:
            raise SpeculationBoundaryError(
                f"branch {branch.branch_id} used partial-undo tool {eff.tool!r} with no faithful compensation"
            )
        if eff.observed_version is not None and branch.read_coupled_derived_state:
            raise SpeculationBoundaryError(
                f"branch {branch.branch_id} distilled read-coupled state (version {eff.observed_version}); "
                f"rollback must invalidate derived state, not merely revert storage"
            )


def verify_rollback(branch: Branch, post_state: dict, pre_state: dict) -> None:
    """Rollback is complete only when observable state matches pre-speculation, not when tokens replay."""
    for key, pre_val in pre_state.items():
        if post_state.get(key) != pre_val:
            raise SpeculationBoundaryError(
                f"rollback of branch {branch.branch_id} left {key}={post_state.get(key)!r}, "
                f"expected {pre_val!r}; undo-token replay is not state restoration"
            )
    if branch.read_coupled_derived_state:
        raise SpeculationBoundaryError(
            f"branch {branch.branch_id} held derived state {branch.read_coupled_derived_state} "
            f"that survived rollback and must be invalidated"
        )
