# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-by-a-plan-committing-coordinator-when-the-vote-set-is-quorum-valid-but-temporally-impossible.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-equivocation-by-a-plan-committing-coordinator-when-the-vote-set-is-quorum-valid-but-temporally-impossible.warrant.json
# Markdown SHA-256:   60821c499edf056ee91f7d6f55b584778b4797d199bb0226d3ca15368e8d255d
# Code AST SHA-256:   302236dc02aceba9c8139c7d5ff1bab9d075b4b46fdd523cdb41f01ec2532146
# Verified Classes:   EquivocationDetected, CommitLog
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class EquivocationDetected(RuntimeError):
    """Raised when a COMMIT certificate is cardinality-valid but causally impossible:
    a conflicting plan already committed at the same round index, with overlapping
    signers and no null certificate ordering the views."""
    pass


class CommitLog:
    def __init__(self, quorum_size: int):
        self.quorum_size = quorum_size
        self.commits = {}          # round -> (plan_hash, view, signers)
        self.signed_prepares = {}  # (round, view) -> set of replica ids

    def record_prepare(self, round_idx: int, view: str, signer: int):
        key = (round_idx, view)
        self.signed_prepares.setdefault(key, set()).add(signer)

    def accept_commit(self, round_idx: int, plan_hash: str, view: str,
                      signers: set, null_cert_present: bool):
        if len(signers) < self.quorum_size:
            raise EquivocationDetected(
                f"cardinality fault at r={round_idx}: {len(signers)} < {self.quorum_size}")

        prior = self.commits.get(round_idx)
        if prior is None:
            self.commits[round_idx] = (plan_hash, view, signers)
            return "accepted"

        prior_hash, prior_view, prior_signers = prior
        if prior_hash == plan_hash:
            return "idempotent"

        # Conflicting plan at same round: check causal ordering.
        overlap = signers & prior_signers
        if prior_view != view and overlap and not null_cert_present:
            raise EquivocationDetected(
                f"equivocation at r={round_idx}: views {prior_view} vs {view} "
                f"conflict, signer overlap={sorted(overlap)}, no null certificate")

        if prior_view != view and not null_cert_present:
            raise EquivocationDetected(
                f"unproven view change at r={round_idx}: {prior_view}->{view} "
                f"without null certificate")

        raise EquivocationDetected(
            f"unresolvable conflict at r={round_idx}: {prior_hash} vs {plan_hash}")


def on_commit_certificate(log: CommitLog, cert: dict) -> str:
    if cert.get("view") != log.commits.get(cert["round"], (None, None, None))[1]:
        if not cert.get("null_cert"):
            # Replica must have signed a PREPARE at this round under a prior view.
            prior_views = [v for (r, v) in log.signed_prepares if r == cert["round"]]
            if prior_views:
                raise EquivocationDetected(
                    f"refusing COMMIT at r={cert['round']} view={cert['view']}: "
                    f"prior prepares under {prior_views} with no null certificate")
    return log.accept_commit(
        round_idx=cert["round"],
        plan_hash=cert["plan_hash"],
        view=cert["view"],
        signers=set(cert["signers"]),
        null_cert_present=bool(cert.get("null_cert")),
    )
