# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-speculatively-commit-a-tool-side-effect-it-can-no-longer-roll-back-when-a-sibling-branch-wins-the-verify-race.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-speculatively-commit-a-tool-side-effect-it-can-no-longer-roll-back-when-a-sibling-branch-wins-the-verify-race.warrant.json
# Markdown SHA-256:   54c691bcf7d5e43437bfb53dae36f95bb8799639843eaf8905b86abc09ecc87b
# Code AST SHA-256:   172849c81c3d3e2f88e19a9affdf490f7cf8fb83b6d9b252a30adf1a931bb225
# Verified Classes:   SpeculativeCommitError, PendingEffect, ToolProxy
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class SpeculativeCommitError(RuntimeError):
    """Raised when a speculative branch attempts an irreversible effect
    before the verifier has committed the branch."""


@dataclass
class PendingEffect:
    branch_id: str
    tool: str
    args: dict


@dataclass
class ToolProxy:
    branch_id: str
    mutating_tools: set[str]
    dispatch: Callable[[str, dict], object]
    committed: bool = False
    pending: list[PendingEffect] = field(default_factory=list)

    def call(self, tool: str, **args) -> object:
        if tool in self.mutating_tools:
            if not self.committed:
                # Record intent; do NOT touch the world yet.
                self.pending.append(PendingEffect(self.branch_id, tool, args))
                return {"status": "deferred", "branch": self.branch_id}
            return self.dispatch(tool, args)
        # Read-only tools may run speculatively.
        return self.dispatch(tool, args)


def commit_branch(proxy: ToolProxy) -> list[object]:
    """Dispatch buffered intents for the winning branch only."""
    if proxy.committed:
        raise SpeculativeCommitError(
            f"branch {proxy.branch_id} already committed; double-commit would "
            "duplicate irreversible effects"
        )
    proxy.committed = True
    results = []
    for effect in proxy.pending:
        results.append(proxy.dispatch(effect.tool, effect.args))
    proxy.pending.clear()
    return results


def rollback_branch(proxy: ToolProxy) -> None:
    """Discard a losing branch. Safe ONLY because nothing was dispatched."""
    if proxy.committed:
        raise SpeculativeCommitError(
            f"cannot roll back committed branch {proxy.branch_id}: effects "
            "already retired to the external system and cannot be reversed "
            "by context restoration"
        )
    proxy.pending.clear()
