# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-equivocation-get-laundered-by-heterogeneous-quorum-thresholds-before-the-auditor-ever-sees-it.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-equivocation-get-laundered-by-heterogeneous-quorum-thresholds-before-the-auditor-ever-sees-it.warrant.json
# Markdown SHA-256:   afc742b4fb3eb4b1b8001b1644e6475b8c18a3992023380b551a711a04c081e7
# Code AST SHA-256:   850b381b3fd79d235524885c3624b0b9b9f7de4f0085686f7fb0f48d4fcbde34
# Verified Classes:   QuorumLaunderingError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class QuorumLaunderingError(RuntimeError):
    """Raised when a quorum certificate admits equivocation via heterogeneous thresholds."""
    pass


def audit_certificate(cert: dict, n_instances: int) -> bool:
    """
    Re-derive quorum from committed thresholds and transcript.
    Rejects certificates that launder equivocation.
    """
    votes = cert.get("votes", [])
    transcript = cert.get("transcript", {})

    if not votes:
        raise QuorumLaunderingError("certificate contains no votes")

    # Invariant 1: every vote must commit its threshold.
    for v in votes:
        if "threshold" not in v:
            raise QuorumLaunderingError(
                f"vote from {v.get('instance_id')} missing committed threshold"
            )
        if v["threshold"] > n_instances - 1:
            raise QuorumLaunderingError(
                f"instance {v['instance_id']} has unreachable threshold "
                f"{v['threshold']} (rubber stamp)"
            )

    # Invariant 2: transcript must cover every vote's inputs.
    for v in votes:
        iid = v["instance_id"]
        if iid not in transcript:
            raise QuorumLaunderingError(
                f"no transcript entry for {iid}; equivocation undetectable"
            )

    # Invariant 3: detect equivocation — same sender, contradictory claims.
    sender_claims: dict[str, set[str]] = {}
    for v in votes:
        sender = v.get("sender_id")
        claim = v.get("claim")
        sender_claims.setdefault(sender, set()).add(claim)

    for sender, claims in sender_claims.items():
        if len(claims) > 1:
            raise QuorumLaunderingError(
                f"equivocation by {sender}: emitted contradictory claims {claims}"
            )

    # Invariant 4: re-derive quorum from committed thresholds, not aggregator tally.
    accept_weight = sum(
        1 for v in votes
        if v["claim"] == "ACCEPT" and v["threshold"] <= n_instances - 1
    )
    reject_weight = sum(
        1 for v in votes
        if v["claim"] == "REJECT" and v["threshold"] <= n_instances - 1
    )
    quorum = (n_instances + 1) // 2 + 1

    if accept_weight < quorum and reject_weight < quorum:
        raise QuorumLaunderingError(
            f"no side reached quorum: accept={accept_weight}, "
            f"reject={reject_weight}, quorum={quorum}"
        )

    return True
