# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-speculative-commit-when-parallel-branch-agents-share-a-mutable-tool-substrate.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-speculative-commit-when-parallel-branch-agents-share-a-mutable-tool-substrate.warrant.json
# Markdown SHA-256:   85c6f33b95f9ad6949740c42a16ec9444d55838855edb2e26b953a669a901f93
# Code AST SHA-256:   2530c905ec94681c5c74b37d754df561338ae12ae88ce61a8a1c0e073b5cf0df
# Verified Classes:   ToolClass, UnsoundSpeculationError, ToolSpec, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ToolClass(Enum):
    PURE = "pure"
    IDEMPOTENT = "idempotent"
    NON_IDEMPOTENT_MUTATING = "non_idempotent_mutating"


class UnsoundSpeculationError(RuntimeError):
    """Raised when optimistic commit is attempted over a substrate that cannot be rolled back."""


@dataclass(frozen=True)
class ToolSpec:
    name: str
    cls: ToolClass
    compensating_action: Callable[[dict], None] | None = None


@dataclass
class Branch:
    branch_id: str
    mutations: list[tuple[str, dict]] = field(default_factory=list)  # (tool, args)


def assert_speculation_sound(tools: list[ToolSpec], branches: list[Branch]) -> None:
    """Pre-fan-out gate: refuse optimistic commit if any branch can mutate un-reconcilably."""
    mutating = {t.name: t for t in tools if t.cls is ToolClass.NON_IDEMPOTENT_MUTATING}
    for b in branches:
        for tool_name, _args in b.mutations:
            spec = mutating.get(tool_name)
            if spec is None:
                continue
            if spec.compensating_action is None:
                raise UnsoundSpeculationError(
                    f"branch {b.branch_id} invoked non-idempotent tool {tool_name!r} "
                    f"with no compensating action; rollback cannot reconcile its side effect. "
                    f"Serialize this branch or run it against a shadow substrate."
                )


def reconcile_losers(committed: Branch, losers: list[Branch], tools: list[ToolSpec]) -> None:
    """Two-phase commit step 2: apply compensating actions for every loser mutation."""
    by_name = {t.name: t for t in tools}
    for loser in losers:
        for tool_name, args in loser.mutations:
            spec = by_name[tool_name]
            if spec.cls is ToolClass.NON_IDEMPOTENT_MUTATING:
                if spec.compensating_action is None:
                    raise UnsoundSpeculationError(
                        f"cannot reconcile {tool_name!r} from branch {loser.branch_id}"
                    )
                spec.compensating_action(args)
