# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-byzantine-fault-tolerant-agent-swarm-stall-at-exactly-3f-1-when-one-peer-equivocates-on-its-own-commitment-witness.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-byzantine-fault-tolerant-agent-swarm-stall-at-exactly-3f-1-when-one-peer-equivocates-on-its-own-commitment-witness.warrant.json
# Markdown SHA-256:   73051d1e54f9e7c4dcda12f441965c1fcf1f1c4d754a53e79226fda06e0b1837
# Code AST SHA-256:   bbd37ac631bbf22a1d6948824eaad0ecf544562130ab495e5302a7803bbbe6a4
# Verified Classes:   EquivocationRecoveryError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class EquivocationRecoveryError(RuntimeError):
    """Raised when a swarm cannot construct an ABORT certificate for an
    equivocated round because witness attribution was evicted."""
    pass


def construct_abort_certificate(round_id, equivocating_member, local_witness_buffer):
    """
    Build an ABORT certificate proving round_id's quorum was poisoned.

    Requires: local_witness_buffer retains per-member witness attribution
    for round_id. If the buffer was evicted on local COMMIT (the bug),
    this cannot be constructed and the swarm stalls.
    """
    if round_id not in local_witness_buffer:
        raise EquivocationRecoveryError(
            f"witness buffer for round {round_id} evicted before global "
            f"finalization; cannot attribute equivocation by {equivocating_member}. "
            f"Swarm will stall in COMMIT_PENDING until liveness timeout."
        )

    witnesses = local_witness_buffer[round_id]
    by_payload = {}
    for member_id, payload_hash, signature in witnesses:
        by_payload.setdefault(payload_hash, []).append((member_id, signature))

    # An ABORT is valid iff we can show the equivocator signed >=2 distinct
    # payloads AND at least one quorum was formed under each.
    equivocating_sigs = [
        (ph, sigs)
        for ph, sigs in by_payload.items()
        if any(m == equivocating_member for m, _ in sigs)
    ]
    if len(equivocating_sigs) < 2:
        raise EquivocationRecoveryError(
            f"only {len(equivocating_sigs)} distinct payload(s) attributable to "
            f"{equivocating_member} in round {round_id}; cannot prove equivocation"
        )

    quorum_size = (2 * len({m for m, _, _ in witnesses}) // 3) + 1
    poisoned_quorums = [
        ph for ph, sigs in equivocating_sigs if len(sigs) >= quorum_size
    ]
    if len(poisoned_quorums) < 2:
        raise EquivocationRecoveryError(
            f"equivocation by {equivocating_member} detected but only "
            f"{len(poisoned_quorums)} quorum(s) poisoned; ABORT not warranted, "
            f"escalate to manual arbitration"
        )

    return {
        "round": round_id,
        "faulty_member": equivocating_member,
        "poisoned_payloads": poisoned_quorums,
        "witness_attribution": witnesses,
    }


def on_local_commit(round_id, witness_buffer, finalized_rounds):
    """
    Correct eviction gate: evict round r's buffer only when r is globally
    finalized, not when it is locally committed.
    """
    if round_id not in finalized_rounds:
        # retain f+1 rounds behind the local commit frontier
        frontier = max(finalized_rounds) if finalized_rounds else round_id
        for r in list(witness_buffer.keys()):
            if r < frontier - 1:
                raise EquivocationRecoveryError(
                    f"refusing to evict round {r} witness buffer: "
                    f"finalization frontier is {frontier}, retention window "
                    f"violated (need f+1=2 rounds behind frontier)"
                )
    return witness_buffer
