# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-commit-to-a-task-quorum-that-no-peer-can-later-reconstruct.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-commit-to-a-task-quorum-that-no-peer-can-later-reconstruct.warrant.json
# Markdown SHA-256:   b33f38f05ca91cf9713f8a239d7b189bd59403885ed1b5c957a97480abc5de7e
# Code AST SHA-256:   7f68eb787e929755293e2176ce51102202c2e10d5f5b35fdf88f5f062a8e8cf6
# Verified Classes:   UnreconstructableJustificationError, JustificationFragment, CommittedState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class UnreconstructableJustificationError(RuntimeError):
    """Raised when a committed state cannot be justified by a payload-bound,
    quorum-valid certificate reconstructed from peer fragments."""


@dataclass(frozen=True)
class JustificationFragment:
    epoch: int
    voter_id: str
    payload_digest: str   # digest over FULL committed payload, not proposal pointer
    signature: str


@dataclass(frozen=True)
class CommittedState:
    task_id: str
    epoch: int
    payload: dict


def _digest(payload: dict) -> str:
    canonical = repr(sorted(payload.items())).encode()
    return hashlib.sha256(canonical).hexdigest()


def reconstruct_justification(
    state: CommittedState,
    fragments: list[JustificationFragment],
    quorum: int,
    f: int,
) -> list[JustificationFragment]:
    """Reconstruct a payload-bound quorum certificate for a committed state.

    Invariant: the certificate must bind the exact payload committed, and
    must contain at least `quorum` distinct voters whose payload digests all
    match the committed payload. Fragments binding a different payload are
    treated as equivocation evidence, not as valid votes.
    """
    expected = _digest(state.payload)
    matching = [
        fr for fr in fragments
        if fr.epoch == state.epoch and fr.payload_digest == expected
    ]
    distinct_voters = {fr.voter_id for fr in matching}

    if len(distinct_voters) < quorum:
        # Either too many fragments were pruned (retention violated) or peers
        # are equivocating on payload. We cannot tell which from here, and we
        # must not guess -- guessing is exactly what a Byzantine peer wants.
        raise UnreconstructableJustificationError(
            f"task={state.task_id} epoch={state.epoch}: "
            f"reconstructed {len(distinct_voters)}/{quorum} payload-bound votes "
            f"for digest={expected[:12]}; cannot justify commitment. "
            f"State is committed (safe) but not actionable."
        )

    # Guard against a single peer stuffing duplicate signatures.
    if len(matching) - len(distinct_voters) > f:
        raise UnreconstructableJustificationError(
            f"task={state.task_id}: {len(matching) - len(distinct_voters)} "
            f"duplicate-voter fragments exceed f={f}; possible vote-stuffing."
        )

    return matching


def act_on_committed_state(
    state: CommittedState,
    fragments: list[JustificationFragment],
    quorum: int,
    f: int,
) -> None:
    """Gate forward execution on reconstructable justification, not on mere
    commitment. Commitment says the state is safe; this says we may build on it."""
    cert = reconstruct_justification(state, fragments, quorum, f)
    # ... proceed with downstream task extension using cert as warrant ...
    _ = cert
