# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-draft-tokens-with-a-shared-kv-cache-window-it-does-not-own.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-draft-tokens-with-a-shared-kv-cache-window-it-does-not-own.warrant.json
# Markdown SHA-256:   72f8b0a575905cf8513ebcbb931ab879ade20c2b8a7217b6f989702caa337639
# Code AST SHA-256:   cc3a3c871f4fd97f1ad3a79994c142b399682a03fc15bb0ea427ffbc0b8c6275
# Verified Classes:   SpeculativePrefixDriftError, HandoffEnvelope, SharedKVWindow
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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])
