# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-commitment-equivocation-in-byzantine-multi-agent-task-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-commitment-equivocation-in-byzantine-multi-agent-task-consensus.warrant.json
# Markdown SHA-256:   d3b2df3f3c1f361e2e5cb208558b8c60ee11c1f77a66907aae06ff72dac7a59d
# Code AST SHA-256:   a882c94e8dc11fd6c57d23ee4b045951866c953de34d44de89a56254d2d849a8
# Verified Classes:   CommitmentEquivocationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CommitmentEquivocationError(RuntimeError):
    """Raised when two distinct quorum certificates exist for the same (task_id, epoch)."""
    pass


def finalize_commitment(cert_store, task_id, epoch, candidate_qc, quorum_size):
    """
    cert_store: dict mapping (task_id, epoch) -> list of finalized QCs
    candidate_qc: dict with keys 'value', 'signatures' (set of agent_ids)
    Returns the committed value, or raises on equivocation.
    """
    if len(candidate_qc["signatures"]) < quorum_size:
        raise CommitmentEquivocationError(
            f"QC for {task_id}@{epoch} has {len(candidate_qc['signatures'])} "
            f"signatures, below quorum {quorum_size}"
        )

    key = (task_id, epoch)
    prior = cert_store.get(key, [])

    for existing in prior:
        if existing["value"] != candidate_qc["value"]:
            # Structural divergence: two valid QCs, same epoch, different values.
            shared = existing["signatures"] & candidate_qc["signatures"]
            raise CommitmentEquivocationError(
                f"Equivocation on {task_id}@{epoch}: "
                f"values {existing['value']!r} vs {candidate_qc['value']!r}; "
                f"shared signers={sorted(shared)}; halt and advance epoch"
            )

    cert_store.setdefault(key, []).append(candidate_qc)
    return candidate_qc["value"]
