# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-peer-s-speculative-draft-token-that-was-validated-against-a-kv-cache-prefix-it-never-held.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-peer-s-speculative-draft-token-that-was-validated-against-a-kv-cache-prefix-it-never-held.warrant.json
# Markdown SHA-256:   4af924529f940c95c506213c861d99cddf185a3d13f5256bd258ce3d728bb936
# Code AST SHA-256:   fd8fc22bf2d4d0d792cc517163323a52536d8422fca94dc633ba6e43ef73cc98
# Verified Classes:   PrefixCommitmentMismatch, Draft
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class PrefixCommitmentMismatch(RuntimeError):
    """Raised when a verifier's cache does not match the drafter's prefix commitment."""
    pass


@dataclass(frozen=True)
class Draft:
    tokens: tuple[int, ...]
    prefix_commit: str          # full-sequence digest, NOT an offset counter
    drafter_offset: int


def commit_prefix(token_ids: tuple[int, ...], offsets: tuple[int, ...]) -> str:
    """Commitment over exact token IDs AND positions. Length/offset alone is insufficient."""
    h = hashlib.sha256()
    for tid, off in zip(token_ids, offsets):
        h.update(tid.to_bytes(8, "little"))
        h.update(off.to_bytes(8, "little"))
    return h.hexdigest()


def admit_draft(draft: Draft, local_tokens: tuple[int, ...],
                local_offsets: tuple[int, ...], cache_verified: bool) -> None:
    if not cache_verified:
        # Cold-resumed cache: counter is provisional, not a commitment.
        raise PrefixCommitmentMismatch(
            "verifier cache unverified after resume; recompute commitment before admitting drafts"
        )
    local_commit = commit_prefix(local_tokens, local_offsets)
    if local_commit != draft.prefix_commit:
        # Do NOT fall through to acceptance scoring against a drifted prefix.
        raise PrefixCommitmentMismatch(
            f"prefix divergence: drafter={draft.prefix_commit[:12]} "
            f"verifier={local_commit[:12]} offset_claim={draft.drafter_offset}"
        )
    # Only now may acceptance scoring run over draft.tokens.
