# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-plan-fragment-it-cannot-re-derive-byzantine-equivocation-at-the-commitment-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-plan-fragment-it-cannot-re-derive-byzantine-equivocation-at-the-commitment-boundary.warrant.json
# Markdown SHA-256:   b6d82eeea44257262107c9a354495d6ed6acd6e5528d1a685e2f19ae31b8a01e
# Code AST SHA-256:   a54824063d04fbca7007a94f93aff30d3b5ce91559fefd04922528f72a8eb2fd
# Verified Classes:   WarrantEquivocationError, Fragment, Vote
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class WarrantEquivocationError(RuntimeError):
    """Raised when a commit vote attests a warrant the voter cannot re-derive,
    or when a committed fragment's warrant fails replay verification."""


@dataclass
class Fragment:
    frag_id: str
    trace: str
    tool_outputs: dict
    replayable: bool
    warrant: Optional[str] = None


@dataclass
class Vote:
    voter: str
    frag_id: str
    value_hash: str
    attestation: Optional[str]  # H(re-derived warrant), None if abstain


def rederive_warrant(frag: Fragment) -> str:
    """Re-derive the warrant from committed state alone. Raises if the
    fragment depends on non-replayable sources."""
    if not frag.replayable:
        raise WarrantEquivocationError(
            f"fragment {frag.frag_id} is non-replayable; cannot re-derive warrant"
        )
    h = hashlib.sha256()
    h.update(frag.trace.encode())
    for k in sorted(frag.tool_outputs):
        h.update(k.encode())
        h.update(str(frag.tool_outputs[k]).encode())
    return h.hexdigest()


def validate_commit_vote(frag: Fragment, vote: Vote) -> None:
    """Enforce the warrant-attestation invariant at vote time, not audit time."""
    if frag.replayable:
        expected = rederive_warrant(frag)
        if vote.attestation is None:
            raise WarrantEquivocationError(
                f"voter {vote.voter} voted commit on replayable fragment "
                f"{frag.frag_id} without warrant attestation"
            )
        if vote.attestation != expected:
            raise WarrantEquivocationError(
                f"voter {vote.voter} attested warrant {vote.attestation[:12]} "
                f"but re-derivation yields {expected[:12]} on {frag.frag_id}"
            )
    else:
        # Non-replayable fragments must abstain from warrant attestation and
        # are routed to the witness-set path instead.
        if vote.attestation is not None:
            raise WarrantEquivocationError(
                f"voter {vote.voter} attested a warrant for non-replayable "
                f"fragment {frag.frag_id}; route to witness-set commit"
            )


def commit(frag: Fragment, votes: list[Vote], quorum: int) -> None:
    """Commit requires quorum matching attestations for replayable fragments."""
    for v in votes:
        validate_commit_vote(frag, v)
    if frag.replayable:
        expected = rederive_warrant(frag)
        matching = sum(1 for v in votes if v.attestation == expected)
        if matching < quorum:
            raise WarrantEquivocationError(
                f"fragment {frag.frag_id} has {matching} matching warrant "
                f"attestations, below quorum {quorum}"
            )
    frag.warrant = rederive_warrant(frag) if frag.replayable else None
