# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-speculative-branch-rollback-as-unsound-when-verified-side-effects-escape-the-speculative-envelope.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-speculative-branch-rollback-as-unsound-when-verified-side-effects-escape-the-speculative-envelope.warrant.json
# Markdown SHA-256:   2ea81b63e881fe67d9b94626a99df30a5e96f291bcb8ba54f8862a137e731746
# Code AST SHA-256:   2c3d869d3209075bff812ac72b03054332440b47cd50ecc3a4f76e94a13fdbcb
# Verified Classes:   RollbackEscape, ToolClass, Effect, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Callable


class RollbackEscape(RuntimeError):
    """Raised when a rolled-back branch left a non-compensable external effect."""


class ToolClass(Enum):
    READ_ONLY = "read_only"
    NAMESPACED_WRITE = "namespaced_write"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


@dataclass
class Effect:
    branch_id: str
    tool: str
    tool_class: ToolClass
    external_id: str | None = None
    confirmed_absent: bool = False


@dataclass
class Branch:
    branch_id: str
    effects: list[Effect] = field(default_factory=list)


def assert_speculation_sound(tools: dict[str, ToolClass]) -> None:
    """Fork-time gate: refuse to speculate on any irreversible tool surface."""
    unsafe = [t for t, c in tools.items() if c is ToolClass.IRREVERSIBLE]
    if unsafe:
        raise RollbackEscape(
            f"speculation unsound: irreversible tools exposed to branches: {unsafe}. "
            "Defer these calls to post-commit or serialize the branch."
        )


def commit_winner(
    winner: Branch,
    losers: list[Branch],
    confirm_absent: Callable[[Effect], bool],
    max_wait_s: float = 30.0,
) -> Branch:
    """
    Commit gate: winner may only be finalized once every loser effect is
    *confirmed absent* in the external system, not merely 'compensation issued'.
    """
    for loser in losers:
        for eff in loser.effects:
            if eff.tool_class in (ToolClass.READ_ONLY, ToolClass.NAMESPACED_WRITE):
                continue
            if eff.tool_class is ToolClass.IRREVERSIBLE:
                raise RollbackEscape(
                    f"branch {eff.branch_id} emitted irreversible effect "
                    f"{eff.tool}:{eff.external_id}; cannot commit {winner.branch_id}"
                )
            if not confirm_absent(eff):
                raise RollbackEscape(
                    f"rollback escape: effect {eff.tool}:{eff.external_id} from "
                    f"branch {eff.branch_id} not confirmed absent before commit of "
                    f"{winner.branch_id}. External state diverges from committed set."
                )
            eff.confirmed_absent = True
    return winner


def fork_and_speculate(
    branches: list[Branch],
    tools: dict[str, ToolClass],
    verifier: Callable[[list[Branch]], Branch],
    confirm_absent: Callable[[Effect], bool],
) -> Branch:
    assert_speculation_sound(tools)
    winner = verifier(branches)
    losers = [b for b in branches if b.branch_id != winner.branch_id]
    return commit_winner(winner, losers, confirm_absent)
