# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-draft-divergence-from-silently-committing-under-federated-consensus-checkpoints.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-draft-divergence-from-silently-committing-under-federated-consensus-checkpoints.warrant.json
# Markdown SHA-256:   d112a1a4ba2647a5455892329951e365190f6ffcab09105090ba0cabb70d924f
# Code AST SHA-256:   e75a273a07ad2ac6e95e6261ef25ec0c81fbce2c17dcca0d9bf9cf9e725c93ac
# Verified Classes:   VocabularyFingerprintMismatch, CorrelatedAuditorQuorum, RuntimeFingerprint
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class VocabularyFingerprintMismatch(RuntimeError):
    """Raised when a speculative block would commit across a tokenizer/support discontinuity."""
    pass


class CorrelatedAuditorQuorum(RuntimeError):
    """Raised when the consensus quorum is not independent of the draft substrate."""
    pass


@dataclass(frozen=True)
class RuntimeFingerprint:
    node_id: str
    vocab_hash: str        # hash over sorted (id, token_bytes)
    special_tokens_hash: str
    rope_base: float
    role: str              # "draft" | "verifier" | "auditor"


def _fingerprint_vocab(tokenizer) -> str:
    h = hashlib.sha256()
    for tid in sorted(tokenizer.get_vocab().keys()):
        h.update(tid.to_bytes(4, "little"))
        h.update(tokenizer.convert_ids_to_tokens(tid).encode("utf-8", "surrogatepass"))
    return h.hexdigest()


def build_fingerprint(node_id: str, tokenizer, rope_base: float, role: str) -> RuntimeFingerprint:
    return RuntimeFingerprint(
        node_id=node_id,
        vocab_hash=_fingerprint_vocab(tokenizer),
        special_tokens_hash=hashlib.sha256(
            repr(sorted(tokenizer.special_tokens_map.items())).encode()
        ).hexdigest(),
        rope_base=rope_base,
        role=role,
    )


def gate_speculative_commit(
    draft: RuntimeFingerprint,
    verifiers: list[RuntimeFingerprint],
    auditors: list[RuntimeFingerprint],
    quorum: int,
) -> None:
    # 1. Support isomorphism: every verifier must share the draft's vocabulary
    #    and special-token map. RoPE base shifts positional alignment and is
    #    treated as a support permutation for speculative purposes.
    for v in verifiers:
        if (v.vocab_hash, v.special_tokens_hash, v.rope_base) != (
            draft.vocab_hash, draft.special_tokens_hash, draft.rope_base
        ):
            raise VocabularyFingerprintMismatch(
                f"verifier {v.node_id} support diverges from draft {draft.node_id}: "
                f"vocab={v.vocab_hash[:8]} vs {draft.vocab_hash[:8]}, "
                f"rope={v.rope_base} vs {draft.rope_base}; "
                f"acceptance ratio would be computed across non-isomorphic supports"
            )

    # 2. Auditor independence: an auditor sharing the draft's substrate computes
    #    the same q-space and cannot detect a cross-vocabulary commit. It must
    #    not count toward quorum.
    independent = [a for a in auditors if a.vocab_hash != draft.vocab_hash]
    effective = len(verifiers) + len(independent)
    if effective < quorum:
        raise CorrelatedAuditorQuorum(
            f"effective quorum {effective} < required {quorum}: "
            f"{len(auditors) - len(independent)} auditor(s) share draft substrate "
            f"and are correlated voters, not independent checks"
        )
