# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-byzantine-llm-agent-consensus-as-a-commitment-liveness-problem-rather-than-a-correctness-problem-and-abort-on.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-byzantine-llm-agent-consensus-as-a-commitment-liveness-problem-rather-than-a-correctness-problem-and-abort-on.warrant.json
# Markdown SHA-256:   cbe326031b7d5bdc102f220a108b1884a0736f36b430bcd01309d9ced2ccac51
# Code AST SHA-256:   56c793dee8ae4046337d6a570a1c87f885666f1e30a3a06d0aa9d2c2a4094a6d
# Verified Classes:   EquivocationDetected, CanonicalizationError, SeenCommitment
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass

class EquivocationDetected(RuntimeError):
    """Raised when a sender emits divergent commitments for the same (task, epoch)."""
    pass

class CanonicalizationError(ValueError):
    """Raised when a commitment cannot be reduced to a byte-exact canonical form."""
    pass

BINDING_FIELDS = ("task_id", "epoch", "lease_seconds", "proposer_sig")
NON_BINDING = ("display_text", "nonce", "timestamp")

def canonical_hash(commitment: dict) -> str:
    try:
        binding = {k: commitment[k] for k in BINDING_FIELDS}
    except KeyError as e:
        raise CanonicalizationError(f"missing binding field: {e}") from e
    blob = json.dumps(binding, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()

@dataclass
class SeenCommitment:
    sender: str
    task_id: str
    epoch: int
    digest: str

def record_and_check(seen: dict, commitment: dict) -> SeenCommitment:
    """
    seen: map of (sender, task_id, epoch) -> digest already observed.
    Returns the recorded commitment, or raises EquivocationDetected before any vote is cast.
    """
    sender = commitment["proposer_sig"]  # identity is the signing key, not the display name
    key = (sender, commitment["task_id"], commitment["epoch"])
    digest = canonical_hash(commitment)
    prior = seen.get(key)
    if prior is not None and prior != digest:
        raise EquivocationDetected(
            f"equivocation: sender={sender} task={commitment['task_id']} "
            f"epoch={commitment['epoch']} hashes {prior[:12]}.. != {digest[:12]}.."
        )
    seen[key] = digest
    return SeenCommitment(sender, commitment["task_id"], commitment["epoch"], digest)

def vote(seen: dict, commitment: dict) -> str:
    # Any equivocation must abort BEFORE this returns a vote.
    rec = record_and_check(seen, commitment)
    return f"vote:{rec.digest}"

if __name__ == "__main__":
    seen = {}
    c1 = {"task_id": "task-7", "epoch": 41, "lease_seconds": 30,
          "proposer_sig": "P", "display_text": "claim task-7, lease 30s"}
    c2 = {"task_id": "task-7", "epoch": 41, "lease_seconds": 300,
          "proposer_sig": "P", "display_text": "claim task-7, lease 300s"}
    vote(seen, c1)
    vote(seen, c2)  # raises EquivocationDetected -> round aborts, no phantom lease
