# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-withhold-its-vote-equivocation-detection-failure-in-byzantine-quorum-voting-under-non-deterministic-tool-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-withhold-its-vote-equivocation-detection-failure-in-byzantine-quorum-voting-under-non-deterministic-tool-replay.warrant.json
# Markdown SHA-256:   9899c2b70a496641b65025cdf4105df6610c0bdcf3a8cb93476291a3ba11d0ba
# Code AST SHA-256:   96aa8b770b36a076b30c66379f2c485719a593bc0dbbb6905e1f6d50feff78ce
# Verified Classes:   EquivocationGuardError, Ballot, NonceLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EquivocationGuardError(RuntimeError):
    """Raised when an instance attempts to sign a second distinct ballot under an already-committed nonce."""


@dataclass(frozen=True)
class Ballot:
    instance_id: str
    nonce: int
    decision: str
    context_hash: str

    def payload(self) -> bytes:
        return f"{self.instance_id}|{self.nonce}|{self.decision}|{self.context_hash}".encode()


class NonceLedger:
    """Monotonic nonce allocator that binds each nonce to exactly one committed ballot payload."""

    def __init__(self, instance_id: str):
        self.instance_id = instance_id
        self._committed: dict[int, bytes] = {}
        self._next_nonce = 0

    def allocate(self) -> int:
        n = self._next_nonce
        self._next_nonce += 1
        return n

    def sign(self, nonce: int, decision: str, context_hash: str) -> Ballot:
        ballot = Ballot(self.instance_id, nonce, decision, context_hash)
        digest = hashlib.sha256(ballot.payload()).digest()
        prior = self._committed.get(nonce)
        if prior is not None and prior != digest:
            # Re-execution produced a different view under a committed nonce.
            # Do NOT re-sign; escalate to abstention under the same nonce.
            raise EquivocationGuardError(
                f"nonce {nonce} already committed to {prior.hex()[:12]}, "
                f"refusing to sign divergent ballot {digest.hex()[:12]}"
            )
        self._committed[nonce] = digest
        return ballot


def vote_with_retry(ledger: NonceLedger, tool_call, decision_fn, max_retries: int = 2) -> Ballot:
    nonce = ledger.allocate()
    last_err: Exception | None = None
    for attempt in range(max_retries + 1):
        try:
            ctx = tool_call()  # non-deterministic: may drift between attempts
            decision = decision_fn(ctx)
            return ledger.sign(nonce, decision, ctx)
        except EquivocationGuardError:
            # View invalidated after commitment: abstain under the SAME nonce.
            return ledger.sign(nonce, "ABSTAIN", "view_invalidated")
        except TimeoutError as e:
            last_err = e
            continue
    raise EquivocationGuardError(
        f"tool exhausted {max_retries} retries before commitment for nonce {nonce}: {last_err}"
    )
