# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-adopt-a-quorum-checkpoint-it-did-not-witness.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-adopt-a-quorum-checkpoint-it-did-not-witness.warrant.json
# Markdown SHA-256:   aeff84401af4fed642785f07b24498b454f8c22c43b456ce007646041ce119c1
# Code AST SHA-256:   4d3ba3051b348e0028db8460dedd065abc57a426d3ac3c4f591fde386c3bb580
# Verified Classes:   CheckpointAdoptionError, AdjudicatorView, QuorumCheckpoint
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CheckpointAdoptionError(RuntimeError):
    """Raised when a recovering instance cannot soundly adopt a quorum checkpoint."""
    pass


@dataclass
class AdjudicatorView:
    adjudicator_id: str
    input_view_hash: str          # hash of the evidence THIS signer actually saw
    vote: str                     # candidate id voted for


@dataclass
class QuorumCheckpoint:
    step: str
    payload_hash: str
    signer_set: list[str]
    views: Optional[list[AdjudicatorView]]   # None => evidence not propagated
    evidence_bundle: Optional[dict]          # None => not replayable
    tainted_ancestors: set[str] = field(default_factory=set)


def adopt_checkpoint(
    cp: QuorumCheckpoint,
    quorum_size: int,
    local_retained_evidence: Optional[dict],
) -> str:
    # 1. Signature set must meet quorum.
    if len(set(cp.signer_set)) < quorum_size:
        raise CheckpointAdoptionError(
            f"step {cp.step}: signer set {cp.signer_set} below quorum {quorum_size}"
        )

    # 2. Evidence must be recomputable: either carried or locally retained.
    evidence = cp.evidence_bundle or local_retained_evidence
    if evidence is None:
        raise CheckpointAdoptionError(
            f"step {cp.step}: no evidence bundle and no retained evidence; "
            f"adoption would be blind and unreplayable"
        )

    # 3. Views must agree: signers must have adjudicated the same question.
    if cp.views is None:
        raise CheckpointAdoptionError(
            f"step {cp.step}: signer views not propagated; "
            f"quorum over divergent questions cannot bind payload"
        )
    view_hashes = {v.input_view_hash for v in cp.views}
    if len(view_hashes) > 1:
        raise CheckpointAdoptionError(
            f"step {cp.step}: signer views diverge ({view_hashes}); "
            f"quorum is over different inputs and does not bind content"
        )

    # 4. Recompute the merge and confirm it matches the signed payload hash.
    recomputed = recompute_merge(evidence, cp.views)
    if recomputed != cp.payload_hash:
        raise CheckpointAdoptionError(
            f"step {cp.step}: recomputed payload {recomputed} != signed {cp.payload_hash}"
        )

    # 5. Taint inheritance: refuse to launder an unverified ancestor.
    if cp.tainted_ancestors:
        return f"UNVERIFIED_ADOPTED:{cp.step}:ancestors={sorted(cp.tainted_ancestors)}"
    return f"VERIFIED:{cp.step}"


def emit_downstream_checkpoint(
    step: str,
    ancestor_status: list[str],
) -> str:
    tainted = {s.split(":")[1] for s in ancestor_status if s.startswith("UNVERIFIED_ADOPTED")}
    if tainted:
        # Do not sign a clean checkpoint over a tainted region; propagate the taint.
        raise CheckpointAdoptionError(
            f"step {step}: refusing to emit clean checkpoint over tainted ancestors {tainted}"
        )
    return f"CHECKPOINT:{step}"


def recompute_merge(evidence: dict, views: list[AdjudicatorView]) -> str:
    # Deterministic merge over the adjudicated candidate set; placeholder hash.
    winning = max({v.vote for v in views}, key=lambda c: sum(v.vote == c for v in views))
    return f"merge::{winning}::{evidence.get(winning, '')}"
