# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-equivocation-in-multi-agent-byzantine-task-state-consensus-and-when-they-do-not.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-equivocation-in-multi-agent-byzantine-task-state-consensus-and-when-they-do-not.warrant.json
# Markdown SHA-256:   5f6ed0272bf2ef26659aed2f1030eb027796389b04b17feef1c54cda202762f8
# Code AST SHA-256:   57675f62d93ce8e138083d504e07a20dfd1c6d979bac2789c9b1af2229ce9d9b
# Verified Classes:   EquivocationWitnessError, CanonicalizationError, Proposal
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class EquivocationWitnessError(RuntimeError):
    """Raised when a corroborated, non-finalized equivocation witness is found."""
    pass


class CanonicalizationError(ValueError):
    """Raised when a parent-set digest cannot be computed deterministically."""
    pass


@dataclass(frozen=True)
class Proposal:
    peer_id: str
    task_id: str
    epoch: int
    parent_ids: tuple
    signature: bytes
    finalized: bool = False


def parent_set_digest(parent_ids: tuple) -> bytes:
    if not all(isinstance(p, str) for p in parent_ids):
        raise CanonicalizationError("parent ids must be strings")
    canonical = b"".join(
        len(p).to_bytes(4, "big") + p.encode("utf-8")
        for p in sorted(parent_ids)
    )
    return hashlib.sha256(canonical).digest()


def evaluate_witness(
    proposals: list,
    corroborating_reporters: int,
    side_effect_bearing: bool,
) -> str:
    """Return 'record' or 'halt' per the decision boundary; raise on genuine witness."""
    by_key: dict = {}
    for p in proposals:
        key = (p.task_id, p.epoch, p.peer_id)
        by_key.setdefault(key, []).append(p)

    for key, group in by_key.items():
        digests = {parent_set_digest(p.parent_ids) for p in group}
        if len(digests) <= 1:
            continue

        corroborated = corroborating_reporters >= 2
        finalized = all(p.finalized for p in group)

        if side_effect_bearing and corroborated:
            raise EquivocationWitnessError(
                f"side-effect-bearing equivocation on {key}, "
                f"{len(digests)} distinct parent sets, corroborated"
            )
        if corroborated and not finalized:
            raise EquivocationWitnessError(
                f"live equivocation witness on {key}; halt commits for task"
            )
        if corroborated and finalized:
            return "record"  # audit path, do not halt
        return "record"      # uncorroborated suspicion: record only

    return "record"
