# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-speculative-branch-s-tool-side-effects-as-irreversible-before-reconciliation-commits.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-speculative-branch-s-tool-side-effects-as-irreversible-before-reconciliation-commits.warrant.json
# Markdown SHA-256:   596383c3b5e72db8d8a19354c8097cad2d99a58d705a4560e5aeae9fa221eaf6
# Code AST SHA-256:   9772fd0dedc89cb3696a9baad320a4955c8775fa30c90a98a3518a214eaa7dfa
# Verified Classes:   IrreversibleSpeculationError, ToolCapability, PreconditionToken
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class IrreversibleSpeculationError(RuntimeError):
    """Raised when a speculative branch attempts a commit-point tool call
    whose side effects cannot be soundly rolled back at reconciliation."""


@dataclass(frozen=True)
class ToolCapability:
    name: str
    commit_point: bool
    compensation_total: bool
    idempotency_key_supported: bool


@dataclass
class PreconditionToken:
    txn_id: str
    valid: bool


def assert_speculation_safe(
    tool: ToolCapability,
    token: Optional[PreconditionToken],
    branch_id: str,
) -> None:
    """Guard invoked immediately before a speculative branch calls a tool.

    Sound optimistic invocation requires a reversible handle: non-commit-point,
    total compensation, and a live precondition token. Idempotency keys permit
    sibling overlap but do not by themselves make rollback sound.
    """
    if not tool.commit_point and tool.compensation_total and token is not None and token.valid:
        return  # reversible handle held; speculation is sound

    if tool.commit_point and tool.idempotency_key_supported:
        # Permitted only under a deterministic key; caller must supply it.
        return

    raise IrreversibleSpeculationError(
        f"branch {branch_id} cannot optimistically invoke tool {tool.name!r}: "
        f"commit_point={tool.commit_point}, "
        f"compensation_total={tool.compensation_total}, "
        f"idempotency_key_supported={tool.idempotency_key_supported}, "
        f"token={'live' if token and token.valid else 'absent/stale'}. "
        f"Defer invocation to post-reconciliation instead."
    )


def reconcile_rollback(
    tool: ToolCapability,
    token: PreconditionToken,
    branch_id: str,
) -> None:
    """Re-validate revertibility at rollback time, not at invocation time."""
    if not token.valid:
        raise IrreversibleSpeculationError(
            f"rollback of branch {branch_id} on tool {tool.name!r} failed: "
            f"precondition token {token.txn_id} superseded by external actor. "
            f"Treat as terminal reconciliation failure; surface orphaned txn."
        )
