# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-speculative-commit-against-byzantine-quorum-drift-before-dependency-closure.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-speculative-commit-against-byzantine-quorum-drift-before-dependency-closure.warrant.json
# Markdown SHA-256:   67496ff7ab40010f5ed1ece5ab3debe98739d6947ef692344cb91918361c4403
# Code AST SHA-256:   70a5f977bd2dc0dbda2350510f015ebe16b05aed608cf7e29dc82adbddf5de09
# Verified Classes:   QuorumContainmentViolation, Certificate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class QuorumContainmentViolation(RuntimeError):
    """Raised when a dependent node's quorum is not contained in its parent's,
    and no per-signer attestation bridges the gap. Committing past this point
    produces a retraction-cascade hole in the certificate graph."""
    pass


@dataclass(frozen=True)
class Certificate:
    node_id: str
    parent_hash: str | None
    epoch: int
    signers: FrozenSet[str]
    attestations: FrozenSet[str]  # signers of this node who also attested parent


def commit_dependent(child: Certificate, parent: Certificate) -> None:
    if child.parent_hash is None:
        return
    if child.parent_hash != parent.node_id:
        raise QuorumContainmentViolation(
            f"edge hash mismatch: child {child.node_id} cites {child.parent_hash}, "
            f"parent is {parent.node_id}"
        )
    if child.epoch < parent.epoch:
        raise QuorumContainmentViolation(
            f"epoch regression on edge {parent.node_id}->{child.node_id}: "
            f"child epoch {child.epoch} < parent epoch {parent.epoch}"
        )
    unbridged = child.signers - parent.signers - child.attestations
    if unbridged:
        raise QuorumContainmentViolation(
            f"quorum drift on edge {parent.node_id}->{child.node_id}: "
            f"signers {sorted(unbridged)} signed child but neither signed parent "
            f"nor carry an attestation of {parent.node_id}. Retraction of parent "
            f"at epoch > {child.epoch} will not cascade to child."
        )


def speculative_commit(dag_certificates: dict[str, Certificate]) -> None:
    for node_id, cert in dag_certificates.items():
        if cert.parent_hash is None:
            continue
        parent = dag_certificates.get(cert.parent_hash)
        if parent is None:
            raise QuorumContainmentViolation(
                f"node {node_id} references unknown parent {cert.parent_hash}"
            )
        commit_dependent(cert, parent)
