# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-cross-org-a2a-result-attestation-that-is-individually-valid-but-collectively-byzantine.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-cross-org-a2a-result-attestation-that-is-individually-valid-but-collectively-byzantine.warrant.json
# Markdown SHA-256:   e3f9e4acf5b0931e2c0a66fc7fd72bc52ec13022f4286511272a8a876f7edbe6
# Code AST SHA-256:   7f3ead464771f0474c94b9efb38388407ee3cce3c84a592c0cb7e0cbff4ece49
# Verified Classes:   PartitionableQuorumError, Attestation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Mapping


class PartitionableQuorumError(RuntimeError):
    """Raised when a quorum attestation set is individually valid but
    globally Byzantine because the executor partitioned the witness set."""


@dataclass(frozen=True)
class Attestation:
    shard_id: str
    witness_id: str
    output_hash: str
    spec_hash: str          # hash of the FULL task spec shown to the witness
    signature_valid: bool


def verify_quorum(
    attestations: list[Attestation],
    shard_dependencies: Mapping[str, FrozenSet[str]],
    executor_selected_witnesses: bool,
    committed_spec_hash: str,
    k: int,
) -> bool:
    # Step 1: every individual attestation must be sound.
    for a in attestations:
        if not a.signature_valid:
            raise PartitionableQuorumError(
                f"attestation from {a.witness_id} on {a.shard_id} failed signature"
            )

    # Step 2: C3 -- attestations must bind the committed full-spec hash.
    for a in attestations:
        if a.spec_hash != committed_spec_hash:
            raise PartitionableQuorumError(
                f"attestation from {a.witness_id} on {a.shard_id} binds spec "
                f"{a.spec_hash!r}, not committed {committed_spec_hash!r}; "
                f"witness cannot be shown to have verified the full task"
            )

    # Step 3: build witness sets per shard.
    witnesses: dict[str, set[str]] = {}
    for a in attestations:
        witnesses.setdefault(a.shard_id, set()).add(a.witness_id)

    # Step 4: per-shard quorum must be met.
    for shard, ws in witnesses.items():
        if len(ws) < k:
            raise PartitionableQuorumError(
                f"shard {shard} has {len(ws)} witnesses, quorum requires {k}"
            )

    # Step 5: C1 + C2 -- the partition boundary.
    if executor_selected_witnesses:
        for shard, deps in shard_dependencies.items():
            for dep in deps:
                if not (witnesses.get(shard, set()) & witnesses.get(dep, set())):
                    raise PartitionableQuorumError(
                        f"witness sets for shards {shard!r} and {dep!r} are "
                        f"disjoint under executor-selected assignment; "
                        f"quorum is partitionable and cannot attest the "
                        f"combined artifact"
                    )

    return True
