# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-invokes-irreversible-tools-before-the-verifier-branch-commits-the-idempotency-window-invariant-and-rollbac.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-invokes-irreversible-tools-before-the-verifier-branch-commits-the-idempotency-window-invariant-and-rollbac.warrant.json
# Markdown SHA-256:   27d64c2692ab2c0390939f622ef791e1cb69f8583083e37ea3cdc1c1ef572230
# Code AST SHA-256:   bd8fb16c4f021c99e8f316c5e254b15eece8531ee953b5fbe60587cd193cc513
# Verified Classes:   SpeculativeEffectViolation, ToolSpec, BranchContext
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class SpeculativeEffectViolation(RuntimeError):
    """Raised when an uncommitted speculative branch attempts an irreversible tool call."""
    pass


@dataclass(frozen=True)
class ToolSpec:
    name: str
    irreversible: bool
    idempotent_keyed: bool


@dataclass(frozen=True)
class BranchContext:
    branch_id: str
    committed: bool
    idempotency_key: Optional[str]


def dispatch_tool(spec: ToolSpec, ctx: BranchContext, args: dict) -> dict:
    # Invariant: irreversible effects may only originate from a committed branch
    # carrying an orchestrator-controlled idempotency key.
    if spec.irreversible:
        if not ctx.committed:
            raise SpeculativeEffectViolation(
                f"branch {ctx.branch_id} attempted irreversible tool {spec.name} "
                f"before commit; stage the call and defer to the committed branch"
            )
        if not spec.idempotent_keyed or not ctx.idempotency_key:
            raise SpeculativeEffectViolation(
                f"irreversible tool {spec.name} invoked without a dedupe key on "
                f"branch {ctx.branch_id}; rollback cannot compensate an external effect"
            )
    return _invoke(spec.name, args, ctx.idempotency_key)


def _invoke(name: str, args: dict, key: Optional[str]) -> dict:
    return {"tool": name, "args": args, "key": key, "status": "ok"}
