# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-cross-federation-quorum-attestation-when-signed-execution-receipts-are-individually-valid-but-collectively.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-cross-federation-quorum-attestation-when-signed-execution-receipts-are-individually-valid-but-collectively.warrant.json
# Markdown SHA-256:   1189bc7c8c47150ffc234b6b35b08e3392aa816878a2634055efb9077a85ee23
# Code AST SHA-256:   83c79a31249f02cd0aae404cb233c57fc12ed248030115c68aa7122d40c8c04a
# Verified Classes:   NonWitnessingQuorumError, Receipt
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class NonWitnessingQuorumError(RuntimeError):
    """Raised when a receipt set meets the raw threshold but not the independence-reduced threshold."""


@dataclass(frozen=True)
class Receipt:
    agent_id: str
    federation_id: str
    task_digest: str
    output_digest: str
    parent_trace_id: str
    resource_deps: frozenset[str] = field(default_factory=frozenset)
    nonce: str = ""
    timestamp: float = 0.0
    sig: bytes = b""

    def ancestry(self) -> frozenset[str]:
        return frozenset({self.parent_trace_id}) | self.resource_deps


def independence_reduced_count(receipts: Iterable[Receipt]) -> int:
    """Greedy maximal set of pairwise ancestry-disjoint receipts.

    Greedy is safe here because the orchestrator only needs a lower bound
    on independent witnesses; a larger true independent set can only help,
    and over-counting is the failure we are guarding against.
    """
    accepted: list[Receipt] = []
    for r in sorted(receipts, key=lambda x: len(x.ancestry())):
        if all(r.ancestry().isdisjoint(a.ancestry()) for a in accepted):
            accepted.append(r)
    return len(accepted)


def has_cross_federation_witness(receipts: list[Receipt]) -> bool:
    feds = {r.federation_id for r in receipts}
    for r in receipts:
        others = {o.federation_id for o in receipts if o is not r}
        if r.federation_id not in others and len(feds) >= 2:
            return True
    return False


def assert_witnessing_quorum(receipts: list[Receipt], threshold: int) -> None:
    if len(receipts) < threshold:
        raise NonWitnessingQuorumError(
            f"raw count {len(receipts)} below threshold {threshold}"
        )
    reduced = independence_reduced_count(receipts)
    if reduced < threshold:
        raise NonWitnessingQuorumError(
            f"raw count {len(receipts)} meets threshold {threshold} but only "
            f"{reduced} independent witnesses; shared ancestry collapses quorum"
        )
    if not has_cross_federation_witness(receipts):
        raise NonWitnessingQuorumError(
            "no receipt originates outside every other receipt's federation set; "
            "cross-federation witnessing invariant unsatisfied"
        )
