# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-speculative-plan-branching-when-commit-cost-is-asymmetric-to-discard-cost.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-speculative-plan-branching-when-commit-cost-is-asymmetric-to-discard-cost.warrant.json
# Markdown SHA-256:   8a50022b240150667390676982cf69351aafd3775857c501c0b22a1b7d1178e8
# Code AST SHA-256:   41acbae3240562360c63031793c8fdf75318fc165fc843c73f7774f9f0ab7bff
# Verified Classes:   SpeculativeCommitViolation, ToolSpec, Branch, BranchExecutor
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class SpeculativeCommitViolation(RuntimeError):
    """Raised when a speculative branch executes a COMMIT_ONLY tool,
    or when a commit replay is attempted without a valid commit id,
    or when plan preconditions drifted between exploration and commit."""
    pass


@dataclass
class ToolSpec:
    name: str
    mutating: bool          # True => COMMIT_ONLY
    idempotent: bool
    precondition: Callable[[dict], bool] | None = None


@dataclass
class Branch:
    branch_id: str
    score: float
    planned_calls: list[tuple[str, dict]] = field(default_factory=list)
    executed: list[tuple[str, dict]] = field(default_factory=list)
    committed: bool = False


class BranchExecutor:
    def __init__(self, tools: dict[str, ToolSpec], world_state: dict):
        self.tools = tools
        self.world_state = world_state
        self.spend_ledger: list[tuple[str, str, dict]] = []  # (branch, tool, args)

    def _is_commit_only(self, tool_name: str) -> bool:
        spec = self.tools.get(tool_name)
        if spec is None:
            raise SpeculativeCommitViolation(f"unknown tool {tool_name!r}")
        return spec.mutating and not spec.idempotent

    def speculative_call(self, branch: Branch, tool_name: str, args: dict) -> Any:
        if self._is_commit_only(tool_name):
            # Plan it; do not execute it.
            branch.planned_calls.append((tool_name, args))
            return None
        spec = self.tools[tool_name]
        if spec.precondition and not spec.precondition(self.world_state):
            raise SpeculativeCommitViolation(
                f"precondition failed for {tool_name} in branch {branch.branch_id}"
            )
        branch.executed.append((tool_name, args))
        return self._invoke(tool_name, args)

    def commit(self, branches: list[Branch], winner_id: str) -> Branch:
        winner = next((b for b in branches if b.branch_id == winner_id), None)
        if winner is None:
            raise SpeculativeCommitViolation(f"no branch {winner_id!r} to commit")
        # Invariant 1: no discarded branch may have executed a COMMIT_ONLY tool.
        for b in branches:
            if b.branch_id == winner_id:
                continue
            for tool_name, _ in b.executed:
                if self._is_commit_only(tool_name):
                    raise SpeculativeCommitViolation(
                        f"discarded branch {b.branch_id} executed COMMIT_ONLY "
                        f"{tool_name!r}; discard cost is nonzero, aborting commit"
                    )
        # Invariant 2: replay winner's planned COMMIT_ONLY calls exactly once,
        # with precondition re-validation against current world state.
        winner.committed = True
        for tool_name, args in winner.planned_calls:
            spec = self.tools[tool_name]
            if spec.precondition and not spec.precondition(self.world_state):
                raise SpeculativeCommitViolation(
                    f"plan drift: precondition for {tool_name} no longer holds "
                    f"at commit of {winner_id}; re-plan required"
                )
            self.spend_ledger.append((winner_id, tool_name, args))
            self._invoke(tool_name, args)
        return winner

    def _invoke(self, tool_name: str, args: dict) -> Any:
        # Real tool invocation would go here; stubbed for the record.
        return {"tool": tool_name, "args": args, "ok": True}
