# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-executes-a-reversible-tool-branch-and-the-rollback-compensation-is-itself-non-idempotent.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-executes-a-reversible-tool-branch-and-the-rollback-compensation-is-itself-non-idempotent.warrant.json
# Markdown SHA-256:   ec9b2bfb9b0e5013df6eea00de7c0f28c2305f0aea1619ae1b70ef2fd2494193
# Code AST SHA-256:   bde0de08f63ce85c222e86e11cf30b63191d57f50c5ca8d13b1f809bc974d694
# Verified Classes:   CompensationRaceDetected, ToolCall
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class CompensationRaceDetected(RuntimeError):
    """Raised when a speculative branch's compensator is rejected because the
    resource version moved between apply and compensate. This is not retryable:
    it means another writer (possibly a sibling branch) mutated the resource
    mid-rollback, so the branch's isolation invariant is already broken."""


@dataclass(frozen=True)
class ToolCall:
    branch_id: str
    tool: str
    prior_version: int
    idempotency_key: str
    speculative_safe: bool


def plan_branch(calls: list[ToolCall]) -> str:
    """Decide whether a branch may execute speculatively or must be deferred.

    Speculative execution is permitted only if EVERY tool in the branch has a
    version-guarded, idempotency-keyed compensator. A single delta-based tool
    poisons the whole branch, because a compensator for one tool can race the
    apply of another within the same branch.
    """
    unsafe = [c for c in calls if not c.speculative_safe]
    if unsafe:
        return "deferred"
    return "speculative"


def compensate(call: ToolCall, current_version: int, already_applied: set[str]) -> None:
    """Apply the compensating action for a losing speculative branch.

    Enforces the two invariants the delta-based compensator violated:
      1. Version guard: the resource must still be at the version the apply saw.
      2. Idempotency: a compensator already applied for this key is a no-op.
    """
    if call.idempotency_key in already_applied:
        return

    if current_version != call.prior_version:
        raise CompensationRaceDetected(
            f"branch {call.branch_id} tool {call.tool}: "
            f"expected version {call.prior_version}, "
            f"observed {current_version}; rollback cannot be safely applied"
        )

    already_applied.add(call.idempotency_key)
    # ... dispatch version-guarded compensation to the remote service ...


def commit_winner(winner_calls: list[ToolCall], losers: list[ToolCall],
                  version_of: dict[str, int], applied: set[str]) -> None:
    """Serialize loser compensation before the winner's deferred calls fire."""
    for call in losers:
        compensate(call, version_of[call.tool], applied)
    for call in winner_calls:
        if not call.speculative_safe:
            # deferred tool: fire exactly once, after rollback is quiescent
            applied.add(call.idempotency_key)
