# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-speculative-draft-whose-verification-window-has-already-closed-stale-token-acceptance-in-federated-speculative.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-speculative-draft-whose-verification-window-has-already-closed-stale-token-acceptance-in-federated-speculative.warrant.json
# Markdown SHA-256:   ac761319bc1fc974fabbecfc50d16660b205e748205649cb1b29757548b7d04e
# Code AST SHA-256:   9e5592b3a98980582d6932d5cba2927694cf77768d840ebb8f9a52e62ba48831
# Verified Classes:   StaleDraftAcceptError, Draft, LivePrefix, FederatedSpecDecoder
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class StaleDraftAcceptError(RuntimeError):
    """Raised when a draft is applied against a prefix epoch it was not conditioned on."""


@dataclass
class Draft:
    draft_id: str
    epoch: int
    tokens: list


@dataclass
class LivePrefix:
    epoch: int = 0
    tokens: list = field(default_factory=list)


class FederatedSpecDecoder:
    def __init__(self, live: LivePrefix, re_verify_p95_ms: float = 60.0):
        self.live = live
        self.re_verify_p95_ms = re_verify_p95_ms

    def commit_competing(self, tokens: list) -> None:
        # A parallel path advances the live prefix; bumps epoch.
        self.live.tokens.extend(tokens)
        self.live.epoch += 1

    def apply_accept(self, draft: Draft, remaining_budget_ms: float,
                     allow_rebase: bool = False) -> str:
        # Atomic compare-and-append: check epoch AT APPLY TIME, under commit lock.
        if draft.epoch != self.live.epoch:
            if allow_rebase and remaining_budget_ms > self.re_verify_p95_ms:
                # Re-verify against live prefix before committing.
                self.live.tokens.extend(draft.tokens)
                self.live.epoch += 1
                return "rebased"
            # Sound default: discard, fall back to non-speculative step.
            if not allow_rebase:
                raise StaleDraftAcceptError(
                    f"draft {draft.draft_id} epoch {draft.epoch} != live "
                    f"epoch {self.live.epoch}; discard and fall back"
                )
            return "discarded"
        self.live.tokens.extend(draft.tokens)
        self.live.epoch += 1
        return "accepted"
