# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-task-under-equivocating-quorum-certificates-the-commitment-certificate-divergence-boundary-in-bft-multi-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-task-under-equivocating-quorum-certificates-the-commitment-certificate-divergence-boundary-in-bft-multi-agent.warrant.json
# Markdown SHA-256:   a8466264097e7d1e9ca8c0891b9feeaebb823e8509ecf42f53d0664c9934e1aa
# Code AST SHA-256:   f63f4a24e6dfc78e851417e2c627f176aacaa5a55d25df4597c49df119565db2
# Verified Classes:   CommitmentDivergenceError, QuorumCertificate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Dict, List, Optional


class CommitmentDivergenceError(RuntimeError):
    """Raised when a quorum certificate is valid but does not bind to the
    locally computed state root, indicating a potential equivocation-induced
    commitment-certificate divergence."""
    pass


@dataclass(frozen=True)
class QuorumCertificate:
    view: int
    task_set_digest: str          # H(task_set) — binds the task set
    state_root: Optional[str]     # H(state_root) — binds the resulting state
    signers: List[str] = field(default_factory=list)

    def is_structurally_valid(self, threshold: int) -> bool:
        # A QC is structurally valid if enough distinct signers and it
        # actually commits to a state root. A QC without a state_root is
        # the exact failure mode this module guards against.
        return (
            len(set(self.signers)) >= threshold
            and self.state_root is not None
            and len(self.state_root) == 64
        )


def _hash_task_set(tasks: List[str]) -> str:
    return hashlib.sha256("|".join(sorted(tasks)).encode()).hexdigest()


def _hash_state(state: Dict[str, str]) -> str:
    canonical = "|".join(f"{k}={state[k]}" for k in sorted(state))
    return hashlib.sha256(canonical.encode()).hexdigest()


def finalize_task_set(
    qc: QuorumCertificate,
    proposed_tasks: List[str],
    local_state: Dict[str, str],
    threshold: int,
) -> Dict[str, str]:
    """Finalize a task set only if the QC binds to the local state root.

    This is the 'necessary, not sufficient' path: a structurally valid QC is
    required, but the replica independently recomputes the state root and
    refuses to finalize on mismatch. This converts a silent divergence into a
    loud, recoverable stall.
    """
    if not qc.is_structurally_valid(threshold):
        raise CommitmentDivergenceError(
            f"QC in view {qc.view} is not structurally valid: "
            f"signers={len(set(qc.signers))}, threshold={threshold}, "
            f"state_root_bound={qc.state_root is not None}"
        )

    if qc.task_set_digest != _hash_task_set(proposed_tasks):
        raise CommitmentDivergenceError(
            f"QC task_set_digest {qc.task_set_digest[:12]}... does not match "
            f"proposed task set digest {_hash_task_set(proposed_tasks)[:12]}..."
        )

    # Apply the transition speculatively, then verify the root.
    speculative = dict(local_state)
    for task in proposed_tasks:
        key, _, value = task.partition(":=")
        speculative[key] = value

    computed_root = _hash_state(speculative)
    if computed_root != qc.state_root:
        raise CommitmentDivergenceError(
            f"State-root mismatch in view {qc.view}: QC binds to "
            f"{qc.state_root[:12]}... but local recomputation yields "
            f"{computed_root[:12]}... — refusing to finalize; probable "
            f"equivocation-induced QC divergence."
        )

    return speculative


def recover_from_divergent_qcs(
    qc_a: QuorumCertificate,
    qc_b: QuorumCertificate,
    threshold: int,
) -> QuorumCertificate:
    """Select a single QC for recovery, refusing to arbitrarily pick when
    two structurally valid QCs bind to different state roots."""
    if qc_a.is_structurally_valid(threshold) and qc_b.is_structurally_valid(threshold):
        if qc_a.state_root != qc_b.state_root:
            raise CommitmentDivergenceError(
                f"Two valid QCs bind to conflicting state roots "
                f"({qc_a.state_root[:12]}... vs {qc_b.state_root[:12]}...); "
                f"recovery cannot proceed without an explicit reconciliation "
                f"round — arbitrary selection would discard committed tasks."
            )
    return qc_a if qc_a.is_structurally_valid(threshold) else qc_b
