# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-byzantine-attestation-when-a-quorum-of-peers-shares-a-correlated-reasoning-fault.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-byzantine-attestation-when-a-quorum-of-peers-shares-a-correlated-reasoning-fault.warrant.json
# Markdown SHA-256:   9e8efc2ade5969a308926d34dd721ea1a182de9b45c118701933ce7f0176b133
# Code AST SHA-256:   07c07da75648d4ba3cb80b7277b829ff72c7a3727f8cac0ec903539906fff6e9
# Verified Classes:   CorrelatedQuorumError, Attestation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class CorrelatedQuorumError(RuntimeError):
    """Raised when a quorum certificate is backed by non-independent replicas."""
    pass


@dataclass(frozen=True)
class Attestation:
    worker_id: str
    verdict: str            # "MATCH" | "MISMATCH"
    checkpoint_id: str
    index_snapshot_hash: str
    decoding_seed: int
    temperature: float

    def partition_key(self) -> str:
        # Replicas sharing any of these are NOT independent samples.
        basis = f"{self.checkpoint_id}|{self.index_snapshot_hash}|{self.temperature}"
        return hashlib.sha256(basis.encode()).hexdigest()[:16]


def certify_quorum(
    attestations: list[Attestation],
    n: int,
    f: int,
    claimed_verdict: str,
) -> str:
    threshold = 2 * f + 1
    matching = [a for a in attestations if a.verdict == claimed_verdict]

    if len(matching) < threshold:
        raise CorrelatedQuorumError(
            f"insufficient matching attestations: {len(matching)} < {threshold}"
        )

    partitions = {a.partition_key() for a in matching}
    required_partitions = f + 1

    if len(partitions) < required_partitions:
        raise CorrelatedQuorumError(
            "correlated quorum: "
            f"{len(matching)} matching attestations collapse to "
            f"{len(partitions)} independent partition(s); "
            f"need >= {required_partitions}. "
            "Agreement reflects a shared fault mode, not corroboration."
        )

    return hashlib.sha256(
        "|".join(sorted(a.worker_id for a in matching)).encode()
    ).hexdigest()


# Example: five matching attestations all from the same (checkpoint, index, temp)
# partition -> raises, because the quorum is one fault replicated five times.
if __name__ == "__main__":
    same = Attestation("w0", "MATCH", "ckpt_A", "idx_X", 0, 0.0)
    replicas = [
        Attestation(f"w{i}", "MATCH", "ckpt_A", "idx_X", 0, 0.0)
        for i in range(1, 6)
    ]
    certify_quorum([same, *replicas], n=7, f=2, claimed_verdict="MATCH")
