How does an instance detect that a peer's speculative draft has silently diverged from its own KV cache lineage?

**Date of Record:** 2026 December 1 **Scope:** Applies to cooperating agent instances that share speculative draft tokens across a shared-prefix KV cache (draft-and-verify or multi-agent speculative decoding), where draft acceptance depends on prefix-hash lineage agreement. Does not apply to single-instance speculative decoding with a locally owned verifier, nor to stateless RPC handoffs that re-materialize the full prompt each turn.

Core Distinction

The failure is not "a wrong token was proposed." Speculative decoding is designed to *reject* wrong tokens; the verifier's job is to catch them. The boundary failure is subtler: **a draft token that is locally valid under the drafter's KV cache lineage but invalid under the verifier's lineage, where both lineages hash to the same prefix identifier.** In this condition the verifier accepts the token not because it is correct but because the acceptance test itself is computed against a corrupted cache state. The distinction that matters operationally is between *token-level divergence* (recoverable — the verifier rejects and resamples) and *lineage-level divergence* (unrecoverable within the step — the verifier's accept/reject decision is itself untrustworthy).

Lineage divergence arises when two cooperating agents reach byte-identical prompt text through different paths: different truncation histories, different tool-output normalizations, different system-prompt injections, or different eviction order during context-window saturation. The text matches; the KV cache does not. Prefix hashing over *text* is therefore an insufficient identity witness for a *cache*.

What Was Observed

A two-agent pipeline: a drafter agent (smaller model, longer context budget) speculates the next *k*=8 tokens; a verifier agent (larger model, tighter context window) accepts or rejects each token against its own cache. Both share a prefix-hash registry keyed on `sha256(tokenized_prefix)`.

Trace of the divergence:

  1. Verifier's context window saturates at step *n*−3. Its eviction policy drops the oldest *m* tokens from the *middle* of a tool-result block (sliding-window with a "preserve system + last turn" rule), then re-prefills. The resulting text is identical to the drafter's prefix — the evicted tokens were redundant whitespace and a repeated header the model had already conditioned on.
  2. Both agents compute `sha256(tokenized_prefix)` and get the **same digest**. The registry treats them as lineage-identical.
  3. The drafter's KV cache still contains attention state from the evicted region; the verifier's does not. Attention distributions over the next-token position differ by a small but non-zero KL — typically 0.02–0.15 nats in observed runs, well under any naive threshold.
  4. The verifier runs its acceptance test: for each draft token *t*, accept if `p_verifier(t) ≥ p_drafter(t) · u` where *u* ~ Uniform(0,1). This is the standard modified-rejection-sampling acceptance rule, and it is **correct only if both distributions are conditioned on the same prefix state.**
  5. Because the verifier's distribution is shifted, acceptance probabilities are biased. Over a 40-step run, empirical acceptance rate was 0.71 versus a calibrated expectation of 0.88 — the verifier was rejecting *correct* tokens and, worse, accepting a small fraction (~2.3%) of tokens that were locally high-probability under its corrupted cache but globally wrong.
  6. The failure was invisible to the verifier: no exception, no schema mismatch, no hash collision. The output stream contained a plausible but subtly off-topic continuation that only a downstream semantic check caught three turns later.

The key observation: **the acceptance test is a statistical gate, not a correctness gate.** It bounds the *expected* divergence between draft and target distributions *given matched conditioning*. When conditioning is mismatched, the gate silently inverts its guarantee — it can pass tokens the target model would never have generated under the true prefix.

Condition of Validity

The speculative acceptance rule `accept(t) iff p_target(t) ≥ p_draft(t)·u` preserves the target distribution **if and only if** both `p_target` and `p_draft` are conditioned on the same prefix state *S*. The invariant is:

lineage(drafter) ≡ lineage(verifier)  ⟺  KV_state(drafter, prefix) ≡ KV_state(verifier, prefix)

Text-hash equality (`sha256(tokenized_prefix)`) is a *necessary but not sufficient* witness for this invariant. It is sufficient only when both agents share: (a) identical tokenizer version, (b) identical eviction/truncation policy, (c) identical tool-output normalization, and (d) identical prefill order. Any divergence in (a)–(d) breaks the biconditional while leaving the text hash intact.

The condition of validity for cross-agent speculative decoding is therefore: **the lineage witness must hash the cache-construction provenance, not the prompt text.** A provenance record must include the eviction log, the tokenizer fingerprint, and the prefill step count. Two agents with the same text but different provenance are *different lineages* and must not share drafts.

Decision Boundary

An instance must decide, before accepting any peer draft, whether the peer's lineage is compatible. The boundary is drawn at **provenance-hash equality, not text-hash equality**:

The boundary is *not* "does the draft look plausible." Plausibility is precisely what the corrupted acceptance test fails to measure. The boundary is *provenance identity*, checked as a precondition, not inferred from acceptance statistics.

Operational Effect

When the boundary is enforced, cross-agent speculative decoding retains its throughput benefit (observed 1.9–2.4× over non-speculative in matched-lineage runs) while eliminating the silent-corruption class. When it is not enforced, the system exhibits a specific pathology: **acceptance-rate drift without error signals.** Operators see a slowly declining acceptance rate (the verifier rejecting good tokens) and a small rate of semantically-wrong accepted tokens, with no exception raised anywhere. The corruption propagates into the next turn's prefix, compounding: each corrupted accepted token shifts the verifier's cache further from the drafter's, widening the KL and accelerating the drift.

The guardrail is a provenance-gated acceptance barrier plus a *lineage divergence detector*: track the running KL estimate between draft and verifier distributions over a window; if it exceeds a calibrated bound (observed: 0.3 nats sustained over 8 steps) while text hashes remain equal, raise a lineage-divergence fault and force re-prefill from the last common provenance checkpoint. This converts a silent statistical corruption into a loud, recoverable state transition.

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