# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-speculative-branch-when-optimistic-tool-invocations-have-already-produced-irreversible-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-speculative-branch-when-optimistic-tool-invocations-have-already-produced-irreversible-side-effects.warrant.json
# Markdown SHA-256:   f6dae289405f4431f695c00ed3e03f7126d04b40082ca40d7ce75dde45fb8eff
# Code AST SHA-256:   61d560443623d13e117f4ed9642e7361c51119f0de75d857834561da0da507da
# Verified Classes:   SpeculationAbortError, SpeculationClass, ToolSpec, EffectRecord, Branch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class SpeculationAbortError(RuntimeError):
    """Raised when a speculative branch's effects cannot be proven retracted
    before the winning branch's effects become externally visible."""


class SpeculationClass(Enum):
    PURE = "pure"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


@dataclass
class ToolSpec:
    name: str
    speculation_class: SpeculationClass
    compensate: Callable[[str], bool] | None = None  # handle -> success
    idempotent: bool = False


@dataclass
class EffectRecord:
    branch_id: str
    tool: str
    handle: str
    idempotency_key: str


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


def idempotency_key(branch_id: str, step: int, args: dict) -> str:
    payload = f"{branch_id}:{step}:{sorted(args.items())}".encode()
    return hashlib.sha256(payload).hexdigest()


def verify_and_commit(
    winner: Branch,
    losers: list[Branch],
    registry: dict[str, ToolSpec],
    external_effect_count: int,
) -> None:
    # Invariant 1: effect-log completeness. The tool layer must not have
    # produced more effects than the children recorded.
    recorded = sum(len(b.effects) for b in [winner, *losers])
    if external_effect_count > recorded:
        raise SpeculationAbortError(
            f"unrecorded fan-out: external={external_effect_count} recorded={recorded}"
        )

    # Invariant 2: no losing branch may hold an irreversible effect.
    for loser in losers:
        for eff in loser.effects:
            spec = registry[eff.tool]
            if spec.speculation_class is SpeculationClass.IRREVERSIBLE:
                raise SpeculationAbortError(
                    f"loser {loser.branch_id} invoked irreversible tool {eff.tool}"
                )

    # Invariant 3: every losing effect must be verifiably compensated
    # BEFORE the winner commits. Declared compensability is not enough.
    for loser in losers:
        for eff in loser.effects:
            spec = registry[eff.tool]
            if spec.compensate is None:
                raise SpeculationAbortError(
                    f"no compensator for {eff.tool} on loser {loser.branch_id}"
                )
            if not spec.compensate(eff.handle):
                raise SpeculationAbortError(
                    f"compensation failed for {eff.tool} handle={eff.handle}"
                )

    # Only now is it safe to make the winner's effects externally visible.
    commit_winner(winner)


def commit_winner(branch: Branch) -> None:
    for eff in branch.effects:
        spec = REGISTRY[eff.tool]
        if spec.speculation_class is SpeculationClass.IRREVERSIBLE:
            # Irreversible effects are replayed post-commit with the winner's
            # idempotency key so a crash mid-commit cannot double-apply.
            apply_irreversible(eff)


REGISTRY: dict[str, ToolSpec] = {}
