# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-a-plan-branch-before-the-byzantine-quorum-has-voted-and-the-late-arriving-votes-invert-the-majorit.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-a-plan-branch-before-the-byzantine-quorum-has-voted-and-the-late-arriving-votes-invert-the-majorit.warrant.json
# Markdown SHA-256:   5a317dbccd344abc6382734a525fae1941f1a315aef9f9fed12bd2c4a69ff846
# Code AST SHA-256:   3688a71c29d8bff37ab57aa62018676a46fd0fbb97b58178dbd03be511c2c961
# Verified Classes:   SpeculativeCommitViolation
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class SpeculativeCommitViolation(RuntimeError):
    """Raised when a plan branch is executed speculatively without a full-state-bound quorum certificate."""
    pass


IDEMPOTENT_KEYED = "IDEMPOTENT_KEYED"
STAGED = "STAGED"
IRREVERSIBLE = "IRREVERSIBLE"


def admit_speculative_execution(node, votes, quorum_size, f, cert_log, parent_cert_id):
    # Votes must be keyed on the full plan state, not the suffix alone.
    for v in votes:
        if v.get("prefix_digest") is None or v.get("parent_certificate_id") != parent_cert_id:
            raise SpeculativeCommitViolation(
                f"vote {v.get('voter')} not bound to full plan state; "
                f"prefix_digest missing or parent mismatch"
            )

    # Conflicting certificate in the append-only log is a hard stop.
    conflicting = [c for c in cert_log if c["parent_certificate_id"] == parent_cert_id
                   and c["branch_hash"] != node.branch_hash]
    if conflicting:
        raise SpeculativeCommitViolation(
            f"conflicting certificate {conflicting[0]['cert_id']} observed for parent "
            f"{parent_cert_id}; refusing speculative execution of {node.branch_hash}"
        )

    k = len(votes)
    if node.effect_class == IRREVERSIBLE:
        if k < quorum_size:
            raise SpeculativeCommitViolation(
                f"irreversible node {node.node_id} requires full quorum {quorum_size}, got {k}"
            )
    elif node.effect_class == STAGED:
        if k < f + 1:
            raise SpeculativeCommitViolation(
                f"staged node {node.node_id} requires k >= f+1={f+1}, got {k}"
            )
    elif node.effect_class == IDEMPOTENT_KEYED:
        if k < f + 1:
            raise SpeculativeCommitViolation(
                f"idempotent node {node.node_id} requires k >= f+1={f+1}, got {k}"
            )
    else:
        raise SpeculativeCommitViolation(
            f"node {node.node_id} has unclassified effect_class {node.effect_class!r}"
        )

    return True
