# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-speculative-branch-commitment-when-parallel-agent-drafts-share-a-single-non-idempotent-tool-call-budget.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-speculative-branch-commitment-when-parallel-agent-drafts-share-a-single-non-idempotent-tool-call-budget.warrant.json
# Markdown SHA-256:   dd9bd8299836a853fa1f01708234879a52490ee3687d9754c1fff79ccba8ccac
# Code AST SHA-256:   c8ea3abf47ce4190791ad973cda7317546b28bcab57d94349d9c0dd8a960ad2b
# Verified Classes:   SpeculationBoundaryError, ToolClass, ToolCall, Branch, SpeculativeExecutor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class SpeculationBoundaryError(RuntimeError):
    """Raised when a speculative branch attempts an effect outside its overlay."""


class ToolClass(Enum):
    SPECULATABLE = "speculatable"      # overlay-reversible or branch-keyed idempotent
    NON_SPECULATABLE = "non_speculatable"  # irreversible / non-idempotent


@dataclass
class ToolCall:
    tool: str
    tool_class: ToolClass
    args: dict
    branch_id: str
    idempotency_key: str | None = None
    validated_at: float | None = None


@dataclass
class Branch:
    branch_id: str
    committed: bool = False
    overlay: dict[str, Any] = field(default_factory=dict)


class SpeculativeExecutor:
    def __init__(self, live_execute: Callable[[ToolCall], Any]):
        self._live = live_execute

    def execute(self, call: ToolCall, branch: Branch) -> Any:
        # Invariant 1: a call may execute speculatively only if its effect is
        # overlay-reversible or branch-keyed idempotent.
        if not branch.committed:
            if call.tool_class is ToolClass.NON_SPECULATABLE:
                raise SpeculationBoundaryError(
                    f"branch {branch.branch_id} attempted non-speculatable tool "
                    f"{call.tool!r} before commitment; defer to post-commit"
                )
            if call.idempotency_key is None:
                raise SpeculationBoundaryError(
                    f"branch {branch.branch_id} speculative call to {call.tool!r} "
                    f"lacks branch-derived idempotency_key; effect not reversible"
                )
            # Stage into branch-local overlay; never touch live world.
            branch.overlay[call.idempotency_key] = call.args
            return {"staged": True, "branch": branch.branch_id,
                    "key": call.idempotency_key}

        # Committed path: revalidate preconditions at fire time (TOCTOU guard).
        if call.validated_at is None:
            raise SpeculationBoundaryError(
                f"committed call to {call.tool!r} missing commit-time revalidation"
            )
        return self._live(call)


def commit_winner(branches: list[Branch], winner_id: str,
                  executor: SpeculativeExecutor, calls: list[ToolCall]) -> list[Any]:
    winner = next((b for b in branches if b.branch_id == winner_id), None)
    if winner is None:
        raise SpeculationBoundaryError(f"no branch {winner_id!r} to commit")
    winner.committed = True
    results = []
    for call in calls:
        if call.branch_id != winner_id:
            continue  # losers' overlays discarded, never fired
        results.append(executor.execute(call, winner))
    for b in branches:
        if b.branch_id != winner_id:
            b.overlay.clear()  # release reservations, drop staged effects
    return results
