# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-quorum-equivocation-from-honest-latency-in-a-byzantine-agent-vote.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-quorum-equivocation-from-honest-latency-in-a-byzantine-agent-vote.warrant.json
# Markdown SHA-256:   75eda0516334d460d923bb9733d594c829f734e88a1f6a9c6e5281d45493785e
# Code AST SHA-256:   980c006a29448230e6509f463f189fe2fdc78068e8524d3004a6d4dc62644db2
# Verified Classes:   EquivocationWitnessRequired, QuorumCertificateInvalid, Vote, VoteLog, HonestInstance
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field
from typing import Optional


class EquivocationWitnessRequired(RuntimeError):
    """Raised when an instance attempts to emit a second vote for the same
    plan_id at a higher epoch without attaching the prior signed vote as an
    equivocation witness. This is the emission-time guard that preserves
    quorum intersection under Byzantine conditions."""
    pass


class QuorumCertificateInvalid(RuntimeError):
    """Raised when an aggregator receives a certificate whose quorum contains
    a member with a witnessed prior vote at a different epoch for the same
    plan_id. The certificate must be rejected even if internally well-formed."""
    pass


@dataclass(frozen=True)
class Vote:
    plan_id: str
    epoch: int
    instance_id: str
    decision: str
    monotonic_seq: int
    signature: str = ""

    def digest(self) -> str:
        body = f"{self.plan_id}|{self.epoch}|{self.instance_id}|{self.decision}|{self.monotonic_seq}"
        return hashlib.sha256(body.encode()).hexdigest()


@dataclass
class VoteLog:
    """Durable, fsynced-before-emission log. In production this is a WAL;
    here it is an in-memory stand-in with the same ordering contract."""
    entries: dict = field(default_factory=dict)  # plan_id -> list[Vote]
    _seq: int = 0

    def _next_seq(self) -> int:
        self._seq += 1
        return self._seq

    def highest_emitted(self, plan_id: str) -> Optional[Vote]:
        votes = self.entries.get(plan_id, [])
        return max(votes, key=lambda v: v.epoch) if votes else None

    def fsync_and_append(self, vote: Vote) -> Vote:
        # Contract: the append is durable BEFORE the caller may transmit.
        seq = self._next_seq()
        persisted = Vote(
            plan_id=vote.plan_id,
            epoch=vote.epoch,
            instance_id=vote.instance_id,
            decision=vote.decision,
            monotonic_seq=seq,
            signature=hashlib.sha256(vote.digest().encode()).hexdigest(),
        )
        self.entries.setdefault(vote.plan_id, []).append(persisted)
        return persisted


class HonestInstance:
    def __init__(self, instance_id: str, log: VoteLog):
        self.instance_id = instance_id
        self.log = log

    def prepare_vote(self, plan_id: str, epoch: int, decision: str) -> Vote:
        """Emission-time guard. Must be called before any socket write."""
        prior = self.log.highest_emitted(plan_id)
        if prior is not None and prior.epoch < epoch:
            # An honest instance MAY re-vote at a higher epoch, but only if it
            # carries the prior signed vote as a witness. Refusing here forces
            # the caller to either attach the witness or escalate.
            raise EquivocationWitnessRequired(
                f"instance={self.instance_id} plan_id={plan_id} "
                f"prior_epoch={prior.epoch} new_epoch={epoch} "
                f"prior_sig={prior.signature[:12]}... "
                f"attach witness or halt"
            )
        tentative = Vote(
            plan_id=plan_id,
            epoch=epoch,
            instance_id=self.instance_id,
            decision=decision,
            monotonic_seq=0,
        )
        return self.log.fsync_and_append(tentative)


def aggregate_certificate(
    votes: list[Vote],
    witness_index: dict[str, list[Vote]],
    n: int,
    f: int,
) -> str:
    """Aggregator-side check. Rejects certificates whose quorum contains a
    member with a witnessed prior vote at a different epoch."""
    quorum_size = (2 * n) // 3 + 1
    if len(votes) < quorum_size:
        raise QuorumCertificateInvalid(
            f"insufficient quorum: got {len(votes)} need {quorum_size}"
        )
    plan_ids = {v.plan_id for v in votes}
    if len(plan_ids) != 1:
        raise QuorumCertificateInvalid(f"mixed plan_ids in certificate: {plan_ids}")
    plan_id = plan_ids.pop()
    epochs = {v.epoch for v in votes}
    if len(epochs) != 1:
        raise QuorumCertificateInvalid(f"mixed epochs in certificate: {epochs}")
    epoch = epochs.pop()

    for v in votes:
        prior_votes = witness_index.get(v.instance_id, [])
        for pv in prior_votes:
            if pv.plan_id == plan_id and pv.epoch != epoch:
                raise QuorumCertificateInvalid(
                    f"member {v.instance_id} equivocated on plan_id={plan_id}: "
                    f"witnessed epoch={pv.epoch} sig={pv.signature[:12]}... "
                    f"but certificate epoch={epoch}"
                )
    return hashlib.sha256(
        "|".join(sorted(v.digest() for v in votes)).encode()
    ).hexdigest()


# --- Failure trace reproduction ---
if __name__ == "__main__":
    log = VoteLog()
    a3 = HonestInstance("A3", log)

    # t=0: A3 votes approve(plan_v1) at epoch 1. Fsync succeeds.
    v1 = a3.prepare_vote("plan_v1", epoch=1, decision="approve")
    print(f"emitted v1: seq={v1.monotonic_seq} sig={v1.signature[:12]}...")

    # t=1.8s: GC pause ends, A3 sees plan_v2 at epoch 2.
    # Without the guard, A3 would sign and create a disjoint quorum.
    try:
        a3.prepare_vote("plan_v1", epoch=2, decision="approve")
    except EquivocationWitnessRequired as e:
        print(f"GUARD FIRED: {e}")

    # Aggregator-side: even if a confused A3 did emit, the witness rejects it.
    witness_index = {
        "A3": [v1],
    }
    forged_v2 = Vote("plan_v1", 2, "A3", "approve", 99, "deadbeef" * 8)
    try:
        aggregate_certificate(
            votes=[
                Vote("plan_v1", 2, "A3", "approve", 1, "a" * 64),
                Vote("plan_v1", 2, "A4", "approve", 2, "b" * 64),
                Vote("plan_v1", 2, "A5", "approve", 3, "c" * 64),
            ],
            witness_index=witness_index,
            n=5,
            f=1,
        )
    except QuorumCertificateInvalid as e:
        print(f"CERT REJECTED: {e}")
