# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-speculatively-execute-compensating-tool-calls-before-its-idempotency-key-epoch-is-durably-committed.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-speculatively-execute-compensating-tool-calls-before-its-idempotency-key-epoch-is-durably-committed.warrant.json
# Markdown SHA-256:   ffb595413f14c9b6060dc3cd5a00f2d30a0b1d243573047adcd10f9a3437fdb9
# Code AST SHA-256:   e0dec6c7b986e65ddfa3953b9938757837dd22f9e506234de77ccb3fd0534aa6
# Verified Classes:   EpochNotCommittedError, OrphanedKeyError, CoordinatorLog, ToolSurface, Epoch
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Protocol


class EpochNotCommittedError(RuntimeError):
    """Raised when a side-effecting call is dispatched under an uncommitted epoch."""


class OrphanedKeyError(RuntimeError):
    """Raised when the tool dedupe store holds a key whose epoch is unknown to coordinators."""


class CoordinatorLog(Protocol):
    def is_committed(self, epoch: str) -> bool: ...
    def commit_epoch(self, epoch: str) -> None: ...


class ToolSurface(Protocol):
    def dispatch(self, key: str, payload: dict) -> dict: ...
    def scan_keys(self, epoch_prefix: str) -> list[str]: ...


@dataclass(frozen=True)
class Epoch:
    id: str
    op_seq: int = 0

    def key(self, op: str) -> str:
        return f"{self.id}:{op}:{self.op_seq}"


def dispatch_speculative(
    epoch: Epoch,
    op: str,
    payload: dict,
    log: CoordinatorLog,
    tool: ToolSurface,
) -> dict:
    """Dispatch a side-effecting call, gated on durable epoch commit.

    The gate is the linearization point: no key scoped to `epoch` may reach
    the tool surface before the epoch is committed to the coordinator quorum.
    """
    if not log.is_committed(epoch.id):
        # Attempt to commit; if the coordinator is unreachable, refuse to dispatch.
        try:
            log.commit_epoch(epoch.id)
        except Exception as exc:
            raise EpochNotCommittedError(
                f"epoch {epoch.id} not committed; refusing speculative dispatch of {op}"
            ) from exc
        if not log.is_committed(epoch.id):
            raise EpochNotCommittedError(
                f"epoch {epoch.id} commit did not durably land; aborting dispatch of {op}"
            )
    return tool.dispatch(epoch.key(op), payload)


def recover_after_crash(
    dead_epoch_prefix: str,
    log: CoordinatorLog,
    tool: ToolSurface,
) -> list[str]:
    """On cold start, detect orphaned keys before minting a new epoch.

    Returns the list of orphaned keys that must be reconciled by an auditor
    quorum. Raises if any orphan is found and the caller has not been told.
    """
    orphans = tool.scan_keys(dead_epoch_prefix)
    uncommitted = [k for k in orphans if not log.is_committed(k.split(":")[0])]
    if uncommitted:
        raise OrphanedKeyError(
            f"{len(uncommitted)} key(s) reference epochs absent from coordinator log: "
            f"{uncommitted[:3]}...; escalate to auditor quorum, do not regenerate epoch"
        )
    return orphans


def vote_rollback(
    epoch_id: str,
    observed_seq: int,
    votes: list[tuple[str, int, str]],
) -> str:
    """Count rollback votes only over auditors sharing the same observed sequence."""
    same_seq = [(a, v) for a, s, v in votes if s == observed_seq]
    if len(same_seq) < 2:
        raise EpochNotCommittedError(
            f"insufficient auditors at seq={observed_seq} for epoch {epoch_id}; "
            f"observed seqs={sorted({s for _, s, _ in votes})}"
        )
    rollback = sum(1 for _, v in same_seq if v == "ROLLBACK")
    return "ROLLBACK" if rollback * 2 > len(same_seq) else "COMMIT"
