# 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-non-atomic-across-shared-tool-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-speculative-branch-rollback-as-non-atomic-across-shared-tool-side-effects.warrant.json
# Markdown SHA-256:   4a90355d7ea18c41881cacb160f8208cdd549e88929819e64bafce1e6003e87d
# Code AST SHA-256:   50fddb1b1091419c9494d4b95429a99f3c478a1d0654ee91cab3aad251844beb
# Verified Classes:   SpeculativeIsolationError, ToolSpec, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Callable


class SpeculativeIsolationError(RuntimeError):
    """Raised when a speculative branch's side effects escape branch-local scope."""


@dataclass(frozen=True)
class ToolSpec:
    name: str
    is_writer: bool
    namespace_scope: str  # "branch" | "task" | "global"
    has_exact_inverse: bool


@dataclass
class Branch:
    branch_id: str
    tools: list[ToolSpec] = field(default_factory=list)
    effects: list[tuple[str, Callable[[], None]]] = field(default_factory=list)


def assert_speculation_safe(
    branch: Branch,
    sibling_readable_namespaces: set[str],
    divergence_is_terminal_only: bool,
) -> None:
    """Enforce the isolation invariant before a branch is allowed to run speculatively."""
    for tool in branch.tools:
        if not tool.is_writer:
            continue
        # A writer whose namespace is readable by siblings before commit is a leak.
        if tool.namespace_scope != "branch" and tool.name in sibling_readable_namespaces:
            raise SpeculativeIsolationError(
                f"branch {branch.branch_id!r}: writer {tool.name!r} writes to "
                f"{tool.namespace_scope!r}-scoped namespace readable by siblings "
                f"before the commit barrier; rollback cannot hide this effect."
            )
        # A writer with no exact inverse cannot be compensated on rollback.
        if not tool.has_exact_inverse and divergence_is_terminal_only:
            raise SpeculativeIsolationError(
                f"branch {branch.branch_id!r}: writer {tool.name!r} has no exact "
                f"inverse and divergence is terminal-only; rollback would be "
                f"restorative (snapshot) not compensating, racing concurrent readers."
            )


def rollback(branch: Branch) -> None:
    """Compensating rollback: run registered inverses in reverse order."""
    for tool_name, inverse in reversed(branch.effects):
        try:
            inverse()
        except Exception as exc:  # inverse failure is itself a provenance gap
            raise SpeculativeIsolationError(
                f"branch {branch.branch_id!r}: inverse for {tool_name!r} failed; "
                f"effect persists in shared state with no surviving ledger entry."
            ) from exc
    branch.effects.clear()


def run_speculative(branch: Branch, sibling_ns: set[str], terminal_only: bool) -> None:
    assert_speculation_safe(branch, sibling_ns, terminal_only)
    # ... execute branch, appending (tool_name, inverse) to branch.effects ...
