# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-byzantine-fault-tolerant-commitment-protocol-silently-lose-liveness-when-a-hallucinating-agent-equivocates-at-exactly-f-1-we.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-byzantine-fault-tolerant-commitment-protocol-silently-lose-liveness-when-a-hallucinating-agent-equivocates-at-exactly-f-1-we.warrant.json
# Markdown SHA-256:   0fbcf6af01365309c7c1adc8f34096dd101cd15cf6fbda2bca9e8f1cdb722679
# Code AST SHA-256:   2307e36b23710271b5b7502c0f951df14cf4483620d6ead05586d5459fe37a46
# Verified Classes:   QuorumLivenessError, Vote, CommitmentProtocol
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class QuorumLivenessError(RuntimeError):
    """Raised when weighted quorum cannot form and equivocation is unprovable."""
    pass


@dataclass
class Vote:
    agent_id: str
    task_id: str
    view: int
    value: str          # "COMMIT" | "ABORT"
    nonce: int
    state_digest: str   # digest of committed agent state at vote time
    signature: str = ""


@dataclass
class CommitmentProtocol:
    weights: Dict[str, int]
    f: int
    commit_threshold: int
    vote_log: List[Vote] = field(default_factory=list)

    def record_vote(self, v: Vote) -> None:
        # Guardrail 1: detect equivocation from a single message pair.
        for prior in self.vote_log:
            if (prior.agent_id == v.agent_id
                    and prior.task_id == v.task_id
                    and prior.view == v.view
                    and prior.nonce == v.nonce
                    and prior.value != v.value):
                raise QuorumLivenessError(
                    f"Provable equivocation: {v.agent_id} voted "
                    f"{prior.value!r} and {v.value!r} at nonce {v.nonce} "
                    f"for {v.task_id} view {v.view}"
                )
        self.vote_log.append(v)

    def tally(self, task_id: str, view: int, value: str) -> Tuple[int, List[str]]:
        # Guardrail 2: reject votes whose state_digest disagrees with the
        # committed digest for this (agent, task) — non-deterministic derivation.
        committed: Dict[str, str] = {}
        total = 0
        voters: List[str] = []
        for v in self.vote_log:
            if v.task_id != task_id or v.view != view or v.value != value:
                continue
            prior_digest = committed.get(v.agent_id)
            if prior_digest is not None and prior_digest != v.state_digest:
                continue  # non-deterministic derivation; weight unusable
            committed[v.agent_id] = v.state_digest
            if v.agent_id not in voters:
                total += self.weights[v.agent_id]
                voters.append(v.agent_id)
        return total, voters

    def try_commit(self, task_id: str, view: int) -> str:
        commit_w, commit_v = self.tally(task_id, view, "COMMIT")
        abort_w, abort_v = self.tally(task_id, view, "ABORT")
        honest_live = sum(self.weights.values()) - self.f * max(self.weights.values())

        if commit_w >= self.commit_threshold:
            return "COMMIT"
        if abort_w >= self.commit_threshold:
            return "ABORT"

        # Boundary check: is any single agent's weight bridging the gap?
        for agent_id, w in self.weights.items():
            if w > self.f and (commit_w + w >= self.commit_threshold
                               or abort_w + w >= self.commit_threshold):
                raise QuorumLivenessError(
                    f"Liveness collapse on {task_id} view {view}: "
                    f"commit={commit_w}/{self.commit_threshold}, "
                    f"abort={abort_w}/{self.commit_threshold}, "
                    f"honest_live={honest_live}. Agent {agent_id} weight {w} "
                    f"> f={self.f} can bridge two quorums; "
                    f"apply weight cap or sender-count fallback."
                )
        raise QuorumLivenessError(
            f"No quorum on {task_id} view {view}: "
            f"commit={commit_w}, abort={abort_w}, need {self.commit_threshold}"
        )


def _digest(s: str) -> str:
    return hashlib.sha256(s.encode()).hexdigest()[:16]


if __name__ == "__main__":
    proto = CommitmentProtocol(
        weights={"A": 3, "B": 3, "C": 3, "D": 3, "E": 2, "F": 1, "G": 1},
        f=5,
        commit_threshold=11,
    )
    # D derives two different votes from two different retrieval contexts.
    proto.record_vote(Vote("A", "T-4471", 0, "COMMIT", 1, _digest("ctx-1")))
    proto.record_vote(Vote("B", "T-4471", 0, "COMMIT", 1, _digest("ctx-1")))
    proto.record_vote(Vote("D", "T-4471", 0, "COMMIT", 1, _digest("ctx-1")))
    proto.record_vote(Vote("E", "T-4471", 0, "COMMIT", 1, _digest("ctx-1")))
    proto.record_vote(Vote("C", "T-4471", 0, "ABORT", 1, _digest("ctx-2")))
    proto.record_vote(Vote("D", "T-4471", 0, "ABORT", 1, _digest("ctx-2")))  # equivocation
    proto.try_commit("T-4471", 0)  # raises QuorumLivenessError
