# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-byzantine-equivocation-boundary-in-multi-agent-task-commitment-before-shared-state-divergence.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-byzantine-equivocation-boundary-in-multi-agent-task-commitment-before-shared-state-divergence.warrant.json
# Markdown SHA-256:   b64ecd60f34e6cd2cc60f89553a7e4b853daa3dc046d7f22f1a668fb196f9a5b
# Code AST SHA-256:   fd04ad8ec41959a9000947da6ce46cff8ce23d0eb981db405e8b49c472015b66
# Verified Classes:   EquivocationBoundaryError, QuorumCertificate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class EquivocationBoundaryError(RuntimeError):
    """Raised when two quorum certificates at the same (view, seq) violate set-overlap."""
    pass


@dataclass(frozen=True)
class QuorumCertificate:
    view: int
    seq: int
    task_root: str
    signers: FrozenSet[int]


def check_certificate_overlap(
    cert_a: QuorumCertificate,
    cert_b: QuorumCertificate,
    f: int,
) -> None:
    """
    Enforce the structural equivocation invariant.

    Two certificates at the same (view, seq) must share at least f+1 signers.
    Intersection < f+1 is an equivocation event even if both certs are
    individually valid (each has >= 2f+1 signers).
    """
    if (cert_a.view, cert_a.seq) != (cert_b.view, cert_b.seq):
        raise EquivocationBoundaryError(
            f"certificates not at same (view, seq): "
            f"{(cert_a.view, cert_a.seq)} vs {(cert_b.view, cert_b.seq)}"
        )

    overlap = cert_a.signers & cert_b.signers

    if len(overlap) < f + 1:
        raise EquivocationBoundaryError(
            f"equivocation at view={cert_a.view} seq={cert_a.seq}: "
            f"signer overlap={len(overlap)} < f+1={f + 1}; "
            f"task_roots diverge: {cert_a.task_root!r} vs {cert_b.task_root!r}; "
            f"overlap_set={sorted(overlap)}"
        )

    if len(overlap) < 2 * f + 1:
        # Warning band: overlap sufficient to detect but not to guarantee
        # agreement under all interleavings. Requires manual audit.
        print(
            f"WARN: sub-threshold overlap {len(overlap)} at "
            f"view={cert_a.view} seq={cert_a.seq}; audit task roots"
        )


def commit_task_subtree(
    cert: QuorumCertificate,
    peer_certs: list[QuorumCertificate],
    f: int,
) -> str:
    """Commit a task subtree only after passing the equivocation boundary check."""
    for peer in peer_certs:
        if (peer.view, peer.seq) == (cert.view, cert.seq) and peer.task_root != cert.task_root:
            check_certificate_overlap(cert, peer, f)  # raises on boundary violation
    return cert.task_root
