# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-quorum-collapse-when-byzantine-speculators-agree-on-a-fabricated-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-quorum-collapse-when-byzantine-speculators-agree-on-a-fabricated-checkpoint.warrant.json
# Markdown SHA-256:   c25d2d7756d7cb3c2e22c9f9af245676b80088af0df727f698e0ec26a9c1cd86
# Code AST SHA-256:   35c4fc8a3040c306cfde39d7c5239d4e50993f6cb06f516c0c25690ed188e07f
# Verified Classes:   QuorumCollapseError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class QuorumCollapseError(RuntimeError):
    """Raised when a checkpoint quorum is formed but derivation independence is violated."""


def validate_checkpoint(
    pre_state_hash: str,
    delta,
    candidate_hash: str,
    confirmations: list[dict],
    quorum_threshold: int,
) -> str:
    """
    confirmations: each dict has keys:
      - validator_id
      - rederived_hash: the hash the validator computed from (pre_state, delta)
      - received_candidate_hash: bool, True if the validator was given candidate_hash as input
      - shared_context_with_speculators: bool
      - retained_pre_state: bool
    """
    if len(confirmations) < quorum_threshold:
        raise QuorumCollapseError(
            f"insufficient confirmations: {len(confirmations)} < {quorum_threshold}"
        )

    independent = []
    for c in confirmations:
        if c["received_candidate_hash"]:
            # Shortcut validation: vote is conditioned on the answer. Not independent.
            continue
        if not c["retained_pre_state"]:
            # Cannot have re-derived; confirmation is a shortcut.
            continue
        if c["rederived_hash"] != candidate_hash:
            # Validator re-derived a different state; this is a rejection, not a confirmation.
            continue
        independent.append(c)

    if len(independent) < quorum_threshold:
        raise QuorumCollapseError(
            f"derivation-independent quorum failed: {len(independent)} < {quorum_threshold}; "
            f"raw confirmations={len(confirmations)} include shortcut or non-rederiving votes"
        )

    # Require at least one confirmation from a validator with disjoint context,
    # to rule out correlated fabrication across the whole quorum.
    if all(c["shared_context_with_speculators"] for c in independent):
        raise QuorumCollapseError(
            "all independent confirmations share context with the speculators; "
            "correlated fabrication cannot be excluded"
        )

    return candidate_hash
