# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-attestation-quorum-collapse-when-a-byzantine-agent-equivocates-across-overlapping-auditor-quorums.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-attestation-quorum-collapse-when-a-byzantine-agent-equivocates-across-overlapping-auditor-quorums.warrant.json
# Markdown SHA-256:   66321640d7bdad648fbab0593536aea409afd42344fb7dd20b33ea8578c91643
# Code AST SHA-256:   f407050809780412ecde2a842c4b2f812d58f71c4c26e35e287fa9b752c8b04d
# Verified Classes:   SliceIntersectionViolation, EquivocationDetected
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from collections import defaultdict


class SliceIntersectionViolation(RuntimeError):
    """Raised when two commitments for the same claim digest have slices
    whose honest intersection is below the f+1 threshold required for
    equivocation detection."""
    pass


class EquivocationDetected(RuntimeError):
    """Raised when an auditor signed two distinct result digests for the
    same claim digest."""
    pass


def claim_digest(computation_hash: str) -> str:
    return hashlib.sha256(computation_hash.encode()).hexdigest()


def select_slice(pool: list[str], claim_dgst: str, quorum_size: int) -> frozenset[str]:
    # Deterministic, claim-bound selection. Same claim -> same slice.
    ranked = sorted(pool, key=lambda a: hashlib.sha256((claim_dgst + a).encode()).hexdigest())
    return frozenset(ranked[:quorum_size])


def assert_slice_intersection(
    commitments: list[dict],
    byzantine: set[str],
    f: int,
) -> None:
    """commitments: list of {claim_digest, slice, result_digest}.
    Enforces that any two commitments sharing a claim digest intersect in
    at least f+1 honest auditors."""
    grouped = defaultdict(list)
    for c in commitments:
        grouped[c["claim_digest"]].append(c)

    for dgst, group in grouped.items():
        for i in range(len(group)):
            for j in range(i + 1, len(group)):
                s1 = group[i]["slice"] - byzantine
                s2 = group[j]["slice"] - byzantine
                overlap = len(s1 & s2)
                if overlap < f + 1:
                    raise SliceIntersectionViolation(
                        f"claim {dgst[:12]}: honest slice intersection {overlap} "
                        f"< required {f + 1}; equivocation is undetectable "
                        f"between commitments {group[i].get('id')} and {group[j].get('id')}"
                    )


def detect_equivocation(attestations: list[dict]) -> None:
    """attestations: list of {auditor, claim_digest, result_digest, signature}."""
    seen = defaultdict(dict)
    for a in attestations:
        key = (a["auditor"], a["claim_digest"])
        prev = seen[key].get("result_digest")
        if prev is not None and prev != a["result_digest"]:
            raise EquivocationDetected(
                f"auditor {a['auditor']} signed {prev[:12]} and "
                f"{a['result_digest'][:12]} for claim {a['claim_digest'][:12]}"
            )
        seen[key]["result_digest"] = a["result_digest"]


def commit_result(commitment: dict, pool: list[str], f: int) -> dict:
    quorum_size = 2 * f + 1
    dgst = claim_digest(commitment["computation_hash"])
    # Retry must inherit the original slice, not recompute from load state.
    if "inherited_slice" in commitment:
        sl = frozenset(commitment["inherited_slice"])
    else:
        sl = select_slice(pool, dgst, quorum_size)
    if len(sl) < quorum_size:
        raise SliceIntersectionViolation(
            f"claim {dgst[:12]}: slice size {len(sl)} < quorum {quorum_size}"
        )
    return {
        "id": commitment["id"],
        "claim_digest": dgst,
        "slice": sl,
        "result_digest": commitment["result_digest"],
    }
