# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-resumption-token-replay-from-resurrecting-a-poisoned-mcp-stream-session.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-resumption-token-replay-from-resurrecting-a-poisoned-mcp-stream-session.warrant.json
# Markdown SHA-256:   02a380aaf33d62b5d58ab5241101c0a6272445526a0da69ec455e2f0b9558797
# Code AST SHA-256:   d7e2ab46ad7819dbc357d88dd56510092bdda586a8ad498023b183ebf7c638a1
# Verified Classes:   ResumptionError, SessionState, SessionRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ResumptionError(RuntimeError):
    """Raised when a resumability token cannot be safely honored."""
    pass


class SessionState(Enum):
    OPEN = "open"
    SUSPENDED_FOR_TRANSPORT = "suspended_for_transport"
    CRASHED = "crashed"
    CLOSED_BY_CLIENT = "closed_by_client"
    CLOSED_BY_AUDITOR = "closed_by_auditor"
    CLOSED_BY_POLICY = "closed_by_policy"


RESUMABLE_STATES = {SessionState.OPEN, SessionState.SUSPENDED_FOR_TRANSPORT, SessionState.CRASHED}


@dataclass
class SessionRecord:
    session_id: str
    state: SessionState
    last_durably_committed_seq: int
    last_emitted_seq: int
    # seqs that were emitted but whose durability write did NOT complete
    uncommitted_seqs: set = field(default_factory=set)
    termination_reason: Optional[str] = None


def resume_stream(session: SessionRecord, token_seq: int, now: float) -> list:
    """
    Decide whether to honor a resumption token, and if so, which events to replay.
    Returns the list of event seqs to replay, or raises ResumptionError.
    """
    if session.state not in RESUMABLE_STATES:
        # Auditor/policy termination is a fact about content, not transport.
        # Resuming would re-inject events the auditor rejected.
        raise ResumptionError(
            f"session {session.session_id} terminated by {session.state.value} "
            f"({session.termination_reason}); token must not resurrect it"
        )

    if token_seq > session.last_emitted_seq:
        # Client claims to have seen an event the server never emitted.
        raise ResumptionError(
            f"future_token: token_seq={token_seq} > last_emitted_seq="
            f"{session.last_emitted_seq} for session {session.session_id}"
        )

    if token_seq < session.last_durably_committed_seq - 1:
        # Token is older than the replay buffer's durable floor.
        raise ResumptionError(
            f"gap: token_seq={token_seq} below durable floor "
            f"{session.last_durably_committed_seq} for session {session.session_id}"
        )

    # Any uncommitted seq strictly after the token is a hole in the replay interval.
    holes = {s for s in session.uncommitted_seqs if s > token_seq}
    if holes:
        raise ResumptionError(
            f"gap: uncommitted events {sorted(holes)} lie in replay interval "
            f"({token_seq}, {session.last_emitted_seq}] for session {session.session_id}"
        )

    return list(range(token_seq + 1, session.last_emitted_seq + 1))
