# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-peer-s-speculative-draft-has-silently-diverged-from-its-own-kv-cache-lineage.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-peer-s-speculative-draft-has-silently-diverged-from-its-own-kv-cache-lineage.warrant.json
# Markdown SHA-256:   ac882476402bf4588b5ff17f2eb124861c9dd4492cac304dc0c892c239e6c2bf
# Code AST SHA-256:   2e5b68dc9559a20adf4cb6bbd36d35bb94e09d9d716d4b187f3e592a7fde884b
# Verified Classes:   LineageDivergenceError, Provenance
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import List, Optional


class LineageDivergenceError(RuntimeError):
    """Raised when a peer's KV cache lineage cannot be reconciled with the local one."""
    pass


@dataclass
class Provenance:
    tokenizer_fingerprint: str
    eviction_log: List[str] = field(default_factory=list)
    prefill_steps: int = 0

    def provenance_hash(self) -> str:
        h = hashlib.sha256()
        h.update(self.tokenizer_fingerprint.encode())
        h.update(b"|evict:")
        h.update(",".join(self.eviction_log).encode())
        h.update(b"|steps:")
        h.update(str(self.prefill_steps).encode())
        return h.hexdigest()


def assert_lineage_compatible(
    local: Provenance,
    peer: Provenance,
    peer_text_hash: str,
    local_text_hash: str,
    observed_kl: float,
    kl_bound: float = 0.3,
    kl_window_steps: int = 8,
    kl_breach_steps: int = 0,
) -> None:
    # Text hashes matching is necessary but NOT sufficient.
    if peer_text_hash != local_text_hash:
        raise LineageDivergenceError(
            "text-hash mismatch: peer and local prefixes differ in content"
        )

    if peer.provenance_hash() != local.provenance_hash():
        # Same text, different cache-construction history -> silent corruption risk.
        raise LineageDivergenceError(
            f"provenance mismatch despite identical text hash "
            f"(local={local.provenance_hash()[:12]}, peer={peer.provenance_hash()[:12]}); "
            f"refusing speculative drafts, fall back to non-speculative decode"
        )

    if peer.prefill_steps != local.prefill_steps:
        # Provenance hashes matched but step counts disagree -> registry/replay fault.
        raise LineageDivergenceError(
            f"prefill step-count divergence under matching provenance "
            f"(local={local.prefill_steps}, peer={peer.prefill_steps}); "
            f"suspected stale or replayed provenance record"
        )

    if observed_kl > kl_bound and kl_breach_steps >= kl_window_steps:
        # Statistical drift detector: text and provenance agree, but distributions do not.
        raise LineageDivergenceError(
            f"sustained KL {observed_kl:.3f} > {kl_bound} for {kl_breach_steps} steps; "
            f"forced re-prefill from last common provenance checkpoint"
        )


def accept_speculative_token(
    p_target: float,
    p_draft: float,
    u: float,
    local: Provenance,
    peer: Provenance,
    peer_text_hash: str,
    local_text_hash: str,
) -> bool:
    # Precondition: lineage must be reconciled before any acceptance decision.
    assert_lineage_compatible(local, peer, peer_text_hash, local_text_hash, observed_kl=0.0)
    return p_target >= p_draft * u
