# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-agent-branches-whose-tool-side-effects-are-not-provably-reversible.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-agent-branches-whose-tool-side-effects-are-not-provably-reversible.warrant.json
# Markdown SHA-256:   f05fca9c3c9332eb34c52b13bf651d65ad6ea897741522dd94c418cd0c823419
# Code AST SHA-256:   56e2b44cc7f61d2581bff1bd5057ea27e7e9d03db627d5920a8361a225052003
# Verified Classes:   RollbackUnsoundError, ToolReversibility, ToolManifest, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class RollbackUnsoundError(RuntimeError):
    """Raised when a branch is treated as rollback-able but its tool side
    effects cannot be provably undone or confirmed absent."""


class ToolReversibility(Enum):
    READ_ONLY = "read_only"
    TRANSACTIONAL = "transactional"
    COMPENSABLE = "compensable"
    IDEMPOTENT = "idempotent"
    IRREVERSIBLE = "irreversible"


@dataclass
class ToolManifest:
    name: str
    reversibility: ToolReversibility
    read_back_consistency_domain: str | None = None
    write_consistency_domain: str | None = None


@dataclass
class Branch:
    branch_id: str
    reachable_tools: list[ToolManifest] = field(default_factory=list)
    mutating_calls: list[str] = field(default_factory=list)


def precheck_branch_reversibility(branch: Branch) -> None:
    for tool in branch.reachable_tools:
        if tool.reversibility == ToolReversibility.IRREVERSIBLE:
            raise RollbackUnsoundError(
                f"branch {branch.branch_id} reaches irreversible tool "
                f"{tool.name!r}; speculative execution with rollback is unsound"
            )
        if (
            tool.reversibility == ToolReversibility.COMPENSABLE
            and tool.read_back_consistency_domain
            != tool.write_consistency_domain
        ):
            raise RollbackUnsoundError(
                f"branch {branch.branch_id} tool {tool.name!r} read-back domain "
                f"{tool.read_back_consistency_domain!r} trails write domain "
                f"{tool.write_consistency_domain!r}; rollback cannot be confirmed"
            )


def confirm_rollback(branch: Branch, observed_effect: bool) -> None:
    if observed_effect:
        raise RollbackUnsoundError(
            f"branch {branch.branch_id} rollback unverified: committed side "
            f"effect still observable after abort; halt for reconciliation"
        )


def detect_contamination(
    surviving_branch: Branch, discarded_writes: set[str], reads: set[str]
) -> None:
    overlap = reads & discarded_writes
    if overlap:
        raise RollbackUnsoundError(
            f"surviving branch {surviving_branch.branch_id} read state "
            f"{sorted(overlap)} written by a discarded branch; run contaminated"
        )
