# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-attest-a-quorum-when-its-own-vote-is-a-replay-of-a-peer-s-signed-commitment.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-attest-a-quorum-when-its-own-vote-is-a-replay-of-a-peer-s-signed-commitment.warrant.json
# Markdown SHA-256:   ac2e22c4ca2260da2d7510fb1e8aaec6cface5942c7f9fd63951a84b5c6baea2
# Code AST SHA-256:   9cd5c774eedf1a97573007586c2e56ed7f549c1012a70ed6615a56a7a0574bd5
# Verified Classes:   QuorumIndependenceViolation, Attestation, QuorumCoordinator
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Dict, Set, Tuple


class QuorumIndependenceViolation(RuntimeError):
    """Raised when an attestation cannot be counted as an independent observation."""


@dataclass(frozen=True)
class Attestation:
    signer: str
    task_id: str
    attempt: int
    nonce: str
    result_hash: str
    trace_digest: str


@dataclass
class QuorumCoordinator:
    quorum: int
    # coordinator-issued nonce per (signer, attempt)
    issued_nonce: Dict[Tuple[str, int], str] = field(default_factory=dict)
    counted_signers: Set[str] = field(default_factory=set)
    counted_trace_digests: Set[str] = field(default_factory=set)

    def issue_nonce(self, signer: str, attempt: int, nonce: str) -> None:
        self.issued_nonce[(signer, attempt)] = nonce

    def count(self, att: Attestation) -> int:
        expected = self.issued_nonce.get((att.signer, att.attempt))
        if expected is None:
            raise QuorumIndependenceViolation(
                f"no nonce issued to {att.signer} for attempt {att.attempt}; "
                f"attestation cannot be bound to an execution"
            )
        if att.nonce != expected:
            # This is the forwarding/replay case: signer's nonce is a peer's.
            peer_nonces = {
                n for (s, a), n in self.issued_nonce.items()
                if s != att.signer and a == att.attempt
            }
            if att.nonce in peer_nonces:
                raise QuorumIndependenceViolation(
                    f"attestation from {att.signer} carries a peer-issued nonce "
                    f"(replay/forwarding); counting it would inflate the quorum "
                    f"without adding an independent observation"
                )
            raise QuorumIndependenceViolation(
                f"nonce mismatch for {att.signer} on attempt {att.attempt}: "
                f"expected coordinator-issued challenge, got foreign nonce"
            )
        if not att.trace_digest:
            raise QuorumIndependenceViolation(
                f"attestation from {att.signer} lacks an execution trace digest; "
                f"independence cannot be established"
            )
        if att.trace_digest in self.counted_trace_digests:
            raise QuorumIndependenceViolation(
                f"duplicate trace digest from {att.signer}: two counted "
                f"attestations share one execution, quorum is not independent"
            )
        self.counted_signers.add(att.signer)
        self.counted_trace_digests.add(att.trace_digest)
        return len(self.counted_signers)

    def is_committed(self) -> bool:
        return len(self.counted_signers) >= self.quorum


def commit_task(coord: QuorumCoordinator, attestations: list[Attestation]) -> bool:
    for att in attestations:
        coord.count(att)
    if not coord.is_committed():
        return False
    return True
