# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-byzantine-quorum-breach-when-attested-agent-results-are-valid-but-commitment-ordering-diverges.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-byzantine-quorum-breach-when-attested-agent-results-are-valid-but-commitment-ordering-diverges.warrant.json
# Markdown SHA-256:   6fd25fa65bb7edaa59c77eadd87c4c23eded7699f94e382d8b60e58729c09d58
# Code AST SHA-256:   1b919a9a91241ee7fe49334058a4581bc12d155fd33ed3c4dfb51905b35090aa
# Verified Classes:   QuorumClosureViolation, Attestation, QuorumCertificate
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class QuorumClosureViolation(RuntimeError):
    """Raised when a commitment quorum certificate's signed closure does not
    intersect a prior certificate on a matching result hash, or when the
    closure contains an inferred (unsigned) parent edge."""
    pass


@dataclass(frozen=True)
class Attestation:
    attestation_id: str
    task_id: str
    epoch: int
    result_hash: str
    parent_ids: Tuple[str, ...]      # MUST be signed; inferred edges are illegal here
    signature: str

    def closure_digest(self) -> str:
        h = hashlib.sha256()
        h.update(self.attestation_id.encode())
        h.update(self.result_hash.encode())
        for p in sorted(self.parent_ids):
            h.update(p.encode())
        return h.hexdigest()


@dataclass
class QuorumCertificate:
    task_id: str
    epoch: int
    attestations: List[Attestation]
    signed_closure: Set[str] = field(default_factory=set)

    def build_closure(self, index: Dict[str, Attestation]) -> None:
        stack = [a.attestation_id for a in self.attestations]
        seen: Set[str] = set()
        while stack:
            aid = stack.pop()
            if aid in seen:
                continue
            seen.add(aid)
            if aid not in index:
                # A parent referenced by a signed payload is missing from the
                # index. This is the exact trigger: we cannot verify the edge
                # is signed, so we must not commit.
                raise QuorumClosureViolation(
                    f"unresolved signed parent {aid} in closure of "
                    f"task={self.task_id} epoch={self.epoch}"
                )
            stack.extend(index[aid].parent_ids)
        self.signed_closure = seen


def verify_commitment_quorum(
    qc: QuorumCertificate,
    prior: List[QuorumCertificate],
    index: Dict[str, Attestation],
    f: int,
) -> None:
    # 1. Build and validate the signed closure (rejects inferred edges).
    qc.build_closure(index)

    # 2. Quorum size check on signed attestations only.
    if len(qc.attestations) < 2 * f + 1:
        raise QuorumClosureViolation(
            f"insufficient signed attestations: {len(qc.attestations)} < {2*f+1}"
        )

    # 3. Epoch fencing: all attestations must share the certificate epoch.
    for a in qc.attestations:
        if a.epoch != qc.epoch:
            raise QuorumClosureViolation(
                f"epoch mismatch: attestation {a.attestation_id} "
                f"epoch={a.epoch} cert_epoch={qc.epoch}"
            )

    # 4. Closure-intersection check against prior certificates for same task.
    for prev in prior:
        prev.build_closure(index)
        if prev.task_id != qc.task_id or prev.epoch != qc.epoch:
            continue
        shared = qc.signed_closure & prev.signed_closure
        if not shared:
            raise QuorumClosureViolation(
                f"disjoint signed closures for task={qc.task_id} "
                f"epoch={qc.epoch}: safety invariant broken"
            )
        # 5. On the intersection, result hashes must agree.
        for aid in shared:
            if index[aid].result_hash != _hash_for(prev, aid, index):
                raise QuorumClosureViolation(
                    f"equivocation on shared attestation {aid}: "
                    f"result_hash mismatch across certificates"
                )


def _hash_for(qc: QuorumCertificate, aid: str, index: Dict[str, Attestation]) -> str:
    # The hash recorded in the certificate's own view of the attestation.
    for a in qc.attestations:
        if a.attestation_id == aid:
            return a.result_hash
    return index[aid].result_hash
