# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-divergent-speculative-branches-when-parallel-tool-call-hedging-returns-non-idempotent-side-effects-before-the-verifier-com.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-divergent-speculative-branches-when-parallel-tool-call-hedging-returns-non-idempotent-side-effects-before-the-verifier-com.warrant.json
# Markdown SHA-256:   1c98f2058345005c6b1256b89457c38eeabb1830348e83b33ace76a2593562e7
# Code AST SHA-256:   53e2de526757923f216d2defcc58dd458a63e4c6934046ffc7b69a22d89b2204
# Verified Classes:   HedgeAdmissibilityError, ToolSchema, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class HedgeAdmissibilityError(RuntimeError):
    """Raised when a tool is about to be hedged across speculative branches
    despite lacking idempotency, a prepare/commit gate, or a total compensator."""


@dataclass(frozen=True)
class ToolSchema:
    name: str
    idempotent: bool                 # idempotent under a caller-pinned intent_id
    has_prepare_commit: bool         # two-phase split available
    has_total_compensator: bool      # inverse is provably total (rare for writes)
    effect_class: str                # "read" | "write" | "notify" | ...


@dataclass
class Branch:
    branch_id: str
    emitted_effects: list = field(default_factory=list)


def assert_hedge_admissible(tool: ToolSchema, branches: list[Branch]) -> None:
    """Enforce the identity invariant before fan-out.

    A tool may enter the hedge set only if its effect is idempotent under a
    branch-invariant key, deferred behind a prepare/commit gate, or carries a
    total compensator. Otherwise the fan-out must be refused and downgraded to
    serialized execution behind the verifier.
    """
    if tool.effect_class == "read":
        return

    admissible = (
        tool.idempotent
        or tool.has_prepare_commit
        or tool.has_total_compensator
    )
    if not admissible:
        raise HedgeAdmissibilityError(
            f"tool {tool.name!r} (effect_class={tool.effect_class!r}) cannot be "
            f"hedged across {len(branches)} branches: non-idempotent, no "
            f"prepare/commit gate, no total compensator. Downgrade to serialized "
            f"execution behind the verifier."
        )


def reconcile_commit(selected_branch: Branch,
                     delivered_effects: list,
                     audit_effects: list) -> None:
    """Post-commit reconciliation: effect identity must equal selector identity."""
    delivered = sorted(delivered_effects)
    audited = sorted(audit_effects)
    if delivered != audited:
        raise HedgeAdmissibilityError(
            f"commit divergence: selector={selected_branch.branch_id!r} "
            f"delivered={delivered!r} audited={audited!r}"
        )


def run_hedged(tool: ToolSchema, branches: list[Branch],
               execute: Callable[[Branch], list]) -> list:
    assert_hedge_admissible(tool, branches)
    if tool.idempotent or tool.has_prepare_commit:
        return [execute(b) for b in branches]  # safe fan-out
    # uncompensable non-idempotent write: serialize behind verifier
    return [execute(branches[0])]
