# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-equivocation-line-when-a-byzantine-task-commitment-quorum-shares-mutable-state-across-context-windows.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-equivocation-line-when-a-byzantine-task-commitment-quorum-shares-mutable-state-across-context-windows.warrant.json
# Markdown SHA-256:   6541b7251c0d78cfd2ba2a96033de0a39a07d466330fe7e7be566088df845015
# Code AST SHA-256:   201b316f650be033b4046eb0dc2d63dce2a3bfb1192dd226b1adfc215df63539
# Verified Classes:   WarrantDiscontinuityError, Vote, CommitmentLedger
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class WarrantDiscontinuityError(RuntimeError):
    """Raised when a replica re-attests a value with a perturbed warrant set,
    invalidating its contribution to quorum even though the value is unchanged."""


@dataclass
class Vote:
    replica_id: str
    view: int
    value: str
    warrant_ids: List[str]  # exact evidence set grounding the vote

    def warrant_digest(self) -> str:
        h = hashlib.sha256()
        for wid in sorted(self.warrant_ids):
            h.update(wid.encode())
        return h.hexdigest()


@dataclass
class CommitmentLedger:
    view: int
    votes: Dict[str, Vote] = field(default_factory=dict)
    quorum_size: int = 3

    def register(self, vote: Vote) -> None:
        if vote.view != self.view:
            raise WarrantDiscontinuityError(
                f"vote for view {vote.view} submitted to ledger at view {self.view}"
            )
        prior = self.votes.get(vote.replica_id)
        if prior is not None:
            if prior.value != vote.value:
                raise WarrantDiscontinuityError(
                    f"true equivocation: {vote.replica_id} voted {prior.value} then {vote.value}"
                )
            if prior.warrant_digest() != vote.warrant_digest():
                # value-consistent but evidence-divergent: the silent failure mode
                raise WarrantDiscontinuityError(
                    f"warrant discontinuity on {vote.replica_id}: "
                    f"{prior.warrant_digest()[:8]} -> {vote.warrant_digest()[:8]} "
                    f"for unchanged value {vote.value!r}"
                )
        self.votes[vote.replica_id] = vote

    def try_commit(self) -> Optional[str]:
        if len(self.votes) < self.quorum_size:
            return None
        digests = {v.warrant_digest() for v in self.votes.values()}
        if len(digests) > 1:
            # quorum reached on value but not on warrant: unsound to commit
            raise WarrantDiscontinuityError(
                f"quorum has {len(digests)} distinct warrant digests; "
                f"value agreement is not sufficient for commitment"
            )
        values = {v.value for v in self.votes.values()}
        if len(values) > 1:
            raise WarrantDiscontinuityError("quorum reached with conflicting values")
        return values.pop()


def reconcile_round(ledger: CommitmentLedger, incoming: List[Vote]) -> Optional[str]:
    for vote in incoming:
        try:
            ledger.register(vote)
        except WarrantDiscontinuityError:
            # abandon the view; do not fall back to value-majority
            raise
    return ledger.try_commit()
