# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-auditors-during-multi-agent-task-commit-before-the-quorum-certificate-is-sealed.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-equivocating-auditors-during-multi-agent-task-commit-before-the-quorum-certificate-is-sealed.warrant.json
# Markdown SHA-256:   d75b7a1785fa4b0034c0af917c7e5b3adffa4a6d1c1934eded523a918bb59364
# Code AST SHA-256:   4eefd4501d5aa2a9ce7f599fd09654f8c330fa63e802e540d8f8be76a05eb476
# Verified Classes:   EquivocationDetected, EpochSignOnceLatch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class EquivocationDetected(RuntimeError):
    """Raised when two quorum certificates for the same epoch share a signer."""
    pass


class EpochSignOnceLatch:
    """Per-auditor durable latch: at most one digest signed per epoch."""

    def __init__(self):
        self._signed = {}  # epoch -> digest

    def sign(self, epoch: int, digest: str) -> str:
        prior = self._signed.get(epoch)
        if prior is not None and prior != digest:
            # Branch forked: this instance already attested a different digest.
            raise EquivocationDetected(
                f"auditor branch fork at epoch {epoch}: "
                f"already signed {prior!r}, now asked to sign {digest!r}"
            )
        self._signed[epoch] = digest
        return f"sig({epoch},{digest})"


def reconcile_certificates(epoch: int, cert_a: dict, cert_b: dict) -> None:
    """cert_* maps signer_id -> digest. Enforce functional dependency per epoch."""
    signers_a, signers_b = set(cert_a), set(cert_b)
    overlap = signers_a & signers_b
    if overlap:
        # Same signer in two certs is only legal if digests agree (duplicate msg).
        for signer in overlap:
            if cert_a[signer] != cert_b[signer]:
                raise EquivocationDetected(
                    f"epoch {epoch}: signer {signer!r} attested "
                    f"{cert_a[signer]!r} and {cert_b[signer]!r}"
                )
    if signers_a != signers_b and cert_a != cert_b:
        # Disjoint signer sets with differing digests cannot both meet q from n.
        raise EquivocationDetected(
            f"epoch {epoch}: disjoint quorums with divergent digests "
            f"implies n/q misconfiguration"
        )


if __name__ == "__main__":
    latch = EpochSignOnceLatch()
    latch.sign(42, "D1")
    try:
        latch.sign(42, "D2")  # forked branch attempts second attestation
    except EquivocationDetected as e:
        print("caught at source:", e)

    try:
        reconcile_certificates(
            42,
            {"A1": "D1", "A2": "D1", "A3": "D1"},
            {"A3": "D2", "A4": "D2", "A5": "D2"},
        )
    except EquivocationDetected as e:
        print("caught at reconciler:", e)
