# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-commit-speculative-tokens-into-a-shared-kv-cache-before-the-draft-sequence-is-verified.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-commit-speculative-tokens-into-a-shared-kv-cache-before-the-draft-sequence-is-verified.warrant.json
# Markdown SHA-256:   d0665709eaa701eea761f1ad10a92a3c01e0781e32b783700196fa8acf4e1923
# Code AST SHA-256:   ce47060de8bd56562be7f665d25dea815a89e6dc0fd017c6cc6277a8f3cbffb1
# Verified Classes:   DraftEpochViolation, SharedKVSegment
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DraftEpochViolation(RuntimeError):
    """Raised when a reader's page table references an unverified draft epoch."""
    pass


class SharedKVSegment:
    def __init__(self) -> None:
        # physical page id -> (epoch, verified, kv_vector)
        self._pages: dict[int, tuple[int, bool, bytes]] = {}
        self._verified_epoch: int = 0
        self._current_epoch: int = 0

    def begin_draft(self) -> int:
        self._current_epoch += 1
        return self._current_epoch

    def write_draft_pages(self, epoch: int, page_ids: list[int], kv: bytes) -> None:
        if epoch != self._current_epoch:
            raise DraftEpochViolation(
                f"stale draft epoch {epoch} != current {self._current_epoch}"
            )
        for pid in page_ids:
            # speculative write: tagged, unverified, author-only visibility
            self._pages[pid] = (epoch, False, kv)

    def accept(self, epoch: int) -> None:
        if epoch != self._current_epoch:
            raise DraftEpochViolation(f"cannot accept epoch {epoch}")
        for pid, (ep, _v, kv) in list(self._pages.items()):
            if ep == epoch:
                self._pages[pid] = (ep, True, kv)
        self._verified_epoch = max(self._verified_epoch, epoch)

    def reject(self, epoch: int) -> None:
        # epoch-keyed eviction, NOT index-keyed: drop every page of this epoch
        for pid in [p for p, (ep, _v, _k) in self._pages.items() if ep == epoch]:
            del self._pages[pid]
        self._current_epoch = max(self._current_epoch, epoch)

    def reader_page_table(self, reader_id: str) -> dict[int, bytes]:
        table: dict[int, bytes] = {}
        for pid, (ep, verified, kv) in self._pages.items():
            if verified:
                table[pid] = kv
            else:
                # author may see own unverified pages; no one else may
                if reader_id != f"author:{ep}":
                    raise DraftEpochViolation(
                        f"reader {reader_id} mapped unverified page {pid} "
                        f"from epoch {ep} (verified_epoch={self._verified_epoch})"
                    )
                table[pid] = kv
        return table


def handoff(segment: SharedKVSegment, epoch: int, verifier_id: str) -> dict[int, bytes]:
    """Rewind/verify handoff: reject stale epoch, then expose verified view."""
    if epoch < segment._current_epoch:
        segment.reject(segment._current_epoch)
    segment.accept(epoch)
    table = segment.reader_page_table(verifier_id)
    # invariant: no unverified epoch visible to a non-author reader
    for pid in table:
        ep, verified, _kv = segment._pages[pid]
        if not verified:
            raise DraftEpochViolation(
                f"handoff leaked unverified page {pid} (epoch {ep}) to {verifier_id}"
            )
    return table
