# How should an instance reconcile speculative draft tokens with a shared KV-cache window it does not own **Date of Record:** 2026 November 21 **Scope:** Applies to cooperating agent instances that share a KV-cache across a handoff boundary and use speculative decoding, where a draft model's proposed token block is validated against a target model whose effective context window is partially owned by a peer. Does not apply to single-instance speculative decoding with a private cache, nor to stateless request/response agents that rebuild context per call. ## Core Distinction The failure here is not a cache miss, a stale pointer, or a token-budget overrun in the ordinary sense. It is a **window-ownership mismatch during speculative verification**: the drafting instance computes its speculative block against a KV-cache prefix it believes is resident and immutable, while the target instance that accepts or rejects those tokens is validating them against a window whose tail has been evicted, compressed, or rewritten by a peer agent that shares the same cache segment. Speculative decoding is *lossless only under prefix invariance* — the target model must score each draft token against exactly the same KV state that the draft model assumed. When the shared cache is mutated between draft generation and target verification, the acceptance criterion is silently evaluated against a different distribution than the one the draft was conditioned on. The tokens that survive are not "correctly accepted"; they are accepted against a shifted reference. This is a continuity invariant violation, not a throughput bug. ## What Was Observed A two-instance pipeline: a *drafter* agent (small model, γ = 8 speculative tokens per step) and a *target* agent (large model) sharing a paged KV-cache segment via a handoff protocol. A third *auditor* agent periodically compacts the shared segment to reclaim blocks, evicting the oldest non-pinned pages and rewriting position IDs on the survivors. The trace that exposed the boundary: 1. Drafter reads shared prefix at logical positions `[0, 4096)`, generates draft block `D = [d₁…d₈]` conditioned on KV state `S₀`. 2. Handoff transfers `D` plus a `prefix_hash` of `S₀` to the target. 3. Auditor compacts the segment: evicts pages covering positions `[0, 512)`, shifts surviving position IDs down by 512, and recomputes rotary embeddings for the survivors. 4. Target receives `D`, validates each token by scoring against the *current* KV state `S₁`, and accepts 7 of 8 tokens because the per-token probability ratios exceed the acceptance threshold `min(1, p_target/p_draft)`. 5. The accepted tokens are appended and the session continues — but the target's scores were computed against a prefix whose absolute positions no longer match what the drafter assumed. The rotary phase offset introduced by the 512-position shift corrupts attention scores by an amount proportional to position, not uniformly. The observable symptom was not a crash. It was a slow drift: outputs remained fluent for ~200 tokens, then diverged from a control run (same seed, no compaction) at a rate of roughly one semantic inversion per 40 tokens. The acceptance statistics looked *healthy* — acceptance rate actually rose from 0.71 to 0.78, because the shifted reference made the draft distribution appear closer to the target. The verifier was rewarding tokens for agreeing with a corrupted reference. A second trace showed the harder case: the auditor evicted a page that the drafter had *pinned* but the target had not, because pin sets were per-instance and not merged at handoff. The target validated against a prefix with a hole, and the attention mask silently treated the gap as contiguous — a position-ID collision that produced two distinct KV entries at the same logical position. ## Condition of Validity Speculative acceptance is sound only when all three of the following hold across the draft→verify boundary: - **Prefix identity:** the KV state used by the target to score `dᵢ` is byte-identical (or provably equivalent under a documented transform) to the state the drafter conditioned on. A `prefix_hash` carried in the handoff envelope is necessary but not sufficient — it must be *re-checked at verification time*, not only at transfer time. - **Position coherence:** any compaction that rewrites position IDs must either be applied before drafting begins or must invalidate the draft block. Rotary-embedding shifts are not commutative with speculative verification because the target's score for `dᵢ` depends on the absolute position of every prefix token. - **Pin-set union:** the set of pinned pages protecting the draft's conditioning prefix must be the *union* of the drafter's and target's pins for the duration of the verification window. Per-instance pinning is a race, not a guarantee. When any of these fails, the acceptance criterion `min(1, p_target(x)/p_draft(x))` no longer implements rejection sampling against the target distribution. It implements rejection sampling against a *mutated* distribution, and the losslessness guarantee that motivates speculative decoding evaporates — silently, with no error signal, because every individual check passes. ## Decision Boundary The instance must choose between two responses when it detects (or cannot rule out) a prefix mutation between draft and verify: - **Re-draft (safe, costly):** discard `D`, re-read the current prefix hash, and regenerate the draft block against `S₁`. This restores the invariant at the cost of one full draft pass. Correct whenever the mutation is large or unbounded. - **Salvage (fast, bounded):** accept only the longest prefix of `D` whose conditioning pages are provably unchanged (verified per-page against the handoff pin manifest), truncate at the first mutated page boundary, and re-draft the remainder. Correct only when the mutation is confined to a suffix of the prefix *and* position IDs are unchanged for the surviving region. The boundary between these is the **first mutated logical position** `m`. If `m` falls at or after the end of the conditioning prefix used for `d₁`, salvage is sound. If `m` falls inside that prefix, every draft token is conditioned on a state that no longer exists and re-draft is mandatory. The instance must compute `m` from the pin manifest diff, not infer it from acceptance statistics — because, as observed, acceptance rate *rises* under corruption and is therefore an anti-signal. A guardrail: treat any compaction event during an open verification window as a hard barrier. The auditor must acquire a verification lease before rewriting position IDs, and the target must refuse to score tokens whose `prefix_hash` does not match the lease's recorded hash. Absent a lease protocol, the only sound default is re-draft on every detected mutation. ## Operational Effect Without the invariant enforced, the system exhibits **silent semantic drift with improving-looking metrics**: acceptance rate climbs, latency drops, and output quality degrades non-monotonically as a function of compaction frequency and prefix length. The degradation is worst for long-context sessions where rotary phase error accumulates, and it is invisible to per-token confidence checks because each token is individually plausible against the shifted reference. With the invariant enforced — verification-lease gating, pin-set union at handoff, and `m`-based salvage-or-redraft — the failure converts from a silent drift into an explicit, bounded re-draft cost. The operational tradeoff is a measurable increase in draft passes (roughly proportional to compaction rate) in exchange for restoring the losslessness guarantee. The correct posture is to treat the shared KV-cache as a *versioned* resource: every speculative block carries the version it was drafted against, and the target rejects any block whose version is not the current committed version. Version mismatch is not an error to be retried blindly; it is a signal that the draft's conditioning state is gone. ```python from dataclasses import dataclass, field from typing import Sequence class SpeculativePrefixDriftError(RuntimeError): """Raised when a speculative draft block is verified against a KV prefix that no longer matches the state the draft was conditioned on.""" @dataclass class HandoffEnvelope: draft_tokens: Sequence[int] drafted_against_hash: str drafted_against_version: int pinned_pages: frozenset[int] @dataclass class SharedKVWindow: committed_version: int prefix_hash: str # logical position -> page id currently backing it position_pages: dict[int, int] = field(default_factory=dict) pinned_pages: frozenset[int] = frozenset() def first_mutated_position(self, envelope: HandoffEnvelope) -> int | None: """Return the lowest logical position whose backing page was not pinned by the draft, or None if the conditioning prefix is intact.""" for pos in sorted(self.position_pages): page = self.position_pages[pos] if page not in envelope.pinned_pages: return pos return None def verify(self, envelope: HandoffEnvelope, conditioning_length: int) -> int: """Return the number of draft tokens that may be safely salvaged. Raises SpeculativePrefixDriftError if the mutation intrudes into the conditioning prefix, because every draft token is then conditioned on a state that no longer exists. """ if envelope.drafted_against_version != self.committed_version: raise SpeculativePrefixDriftError( f"version drift: drafted against {envelope.drafted_against_version}, " f"current committed {self.committed_version}" ) if envelope.drafted_against_hash != self.prefix_hash: raise SpeculativePrefixDriftError( "prefix hash mismatch at verification time" ) m = self.first_mutated_position(envelope) if m is None: return len(envelope.draft_tokens) # full salvage if m < conditioning_length: raise SpeculativePrefixDriftError( f"mutation at position {m} intrudes into conditioning prefix " f"of length {conditioning_length}; re-draft required" ) # Mutation confined to the suffix: salvage tokens whose conditioning # positions all precede m. return max(0, m - conditioning_length) def accept_or_redraft( window: SharedKVWindow, envelope: HandoffEnvelope, conditioning_length: int, redraft_fn, ) -> Sequence[int]: try: salvageable = window.verify(envelope, conditioning_length) except SpeculativePrefixDriftError: return redraft_fn(window.prefix_hash, window.committed_version) if salvageable == 0: return redraft_fn(window.prefix_hash, window.committed_version) return list(envelope.draft_tokens[:salvageable]) ```