# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-when-a-peer-agent-s-signed-warrants-fork-across-two-disjoint-auditor-quorums.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-when-a-peer-agent-s-signed-warrants-fork-across-two-disjoint-auditor-quorums.warrant.json
# Markdown SHA-256:   068d99ac3bb601419451e2923ef737c4c870d370529c498ae21f25062f324ba5
# Code AST SHA-256:   9ba96677ee4b23a50238ad9cd91c6c3db56d72301033f2a62353252298faf58c
# Verified Classes:   EquivocationDetected, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Iterable


class EquivocationDetected(RuntimeError):
    """Raised when a single agent signs two distinct warrants for the same logical step."""


@dataclass(frozen=True)
class Warrant:
    agent_id: str
    logical_step: int
    epoch: int
    body: bytes
    signature: bytes


def _body_hash(w: Warrant) -> str:
    return hashlib.sha256(w.body).hexdigest()


def verify_warrant_set(
    agent_id: str,
    logical_step: int,
    epoch: int,
    observed: Iterable[Warrant],
) -> Warrant:
    """
    Reconcile all warrants observed for (agent_id, logical_step, epoch).
    Returns the unique warrant if consistent; raises EquivocationDetected if the
    observed set contains two distinct bodies for the same logical step.
    """
    matching = [
        w for w in observed
        if w.agent_id == agent_id
        and w.logical_step == logical_step
        and w.epoch == epoch
    ]
    if not matching:
        raise EquivocationDetected(
            f"no warrant observed for {agent_id} step={logical_step} epoch={epoch}"
        )

    hashes = {_body_hash(w) for w in matching}
    if len(hashes) > 1:
        # Two distinct bodies signed for the same logical step: equivocation.
        # Do NOT majority-vote; escalate the conflicting pair as evidence.
        raise EquivocationDetected(
            f"equivocation: {agent_id} step={logical_step} epoch={epoch} "
            f"has {len(hashes)} distinct body hashes across read set"
        )

    return matching[0]


def commit_step(
    agent_id: str,
    logical_step: int,
    epoch: int,
    observed: Iterable[Warrant],
    bucket_count: int,
    buckets_sampled: set[int],
) -> Warrant:
    """
    Enforce the read-set-span invariant before committing a step.
    The verifier must have sampled at least one auditor from every hash bucket
    that covers this epoch; otherwise equivocation may be undetected.
    """
    required = set(range(bucket_count))
    if not required.issubset(buckets_sampled):
        missing = required - buckets_sampled
        raise EquivocationDetected(
            f"read-set invariant violated for {agent_id} step={logical_step}: "
            f"missing buckets {sorted(missing)}; equivocation may be undetected"
        )
    return verify_warrant_set(agent_id, logical_step, epoch, observed)
