# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-sse-to-streamable-http-resumption-divergence-when-an-mcp-session-s-event-id-space-resets-mid-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-sse-to-streamable-http-resumption-divergence-when-an-mcp-session-s-event-id-space-resets-mid-stream.warrant.json
# Markdown SHA-256:   2eeaebf0f5ae5ba631508d0074729fcf12bf4250ddd3b6adf2e51a90b4acbbb5
# Code AST SHA-256:   54d7e1e2700221f7038ea2f93b8aca3daa97c5f424f9390053780a1879d21519
# Verified Classes:   ResumptionScopeError, StreamIncarnation, ResumeAttempt
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional


class ResumptionScopeError(RuntimeError):
    """Raised when a resume attempt cannot be proven continuous with the pre-drop stream."""


@dataclass(frozen=True)
class StreamIncarnation:
    session_id: str
    server_epoch: str  # e.g. server start time or migration generation
    id_scheme: str     # "monotonic_int" | "opaque"


@dataclass(frozen=True)
class ResumeAttempt:
    pre_drop_incarnation: StreamIncarnation
    pre_drop_last_id: str
    post_resume_incarnation: StreamIncarnation
    post_resume_first_id: str
    carries_requests: bool  # True if pre-drop stream could carry sampling/elicitation


def verify_resume(attempt: ResumeAttempt) -> None:
    """Fail closed unless ID-space continuity is provable.

    Raises ResumptionScopeError if the client must re-initialize instead of
    sending Last-Event-ID, or if it must discard a resume response.
    """
    pre = attempt.pre_drop_incarnation
    post = attempt.post_resume_incarnation

    # 1. Incarnation must match. A rotated epoch means the event store is
    #    not the same producer; Last-Event-ID is meaningless against it.
    if pre.session_id != post.session_id:
        raise ResumptionScopeError(
            f"session id changed across resume: {pre.session_id!r} -> {post.session_id!r}; "
            "re-initialize, do not resume"
        )
    if pre.server_epoch != post.server_epoch:
        raise ResumptionScopeError(
            f"server epoch rotated ({pre.server_epoch!r} -> {post.server_epoch!r}); "
            "event-ID space is not continuous; re-initialize"
        )
    if pre.id_scheme != post.id_scheme:
        raise ResumptionScopeError(
            f"ID scheme changed across resume ({pre.id_scheme!r} -> {post.id_scheme!r}); "
            "cannot verify continuity"
        )

    # 2. For opaque IDs, continuity is unverifiable. Refuse to resume any
    #    stream that could carry unanswered requests.
    if post.id_scheme == "opaque":
        if attempt.carries_requests:
            raise ResumptionScopeError(
                "opaque event IDs: continuity unverifiable and stream may carry "
                "sampling/elicitation requests; re-initialize rather than risk silent loss"
            )
        return  # gap-tolerant notification stream: acceptable

    # 3. For monotonic integer IDs, require strict forward progress and, if
    #    there is a gap, require that the server replayed the gap.
    try:
        last = int(attempt.pre_drop_last_id)
        first = int(attempt.post_resume_first_id)
    except ValueError as exc:
        raise ResumptionScopeError(
            f"declared monotonic_int scheme but IDs are not integers: "
            f"{attempt.pre_drop_last_id!r}, {attempt.post_resume_first_id!r}"
        ) from exc

    if first <= last:
        raise ResumptionScopeError(
            f"event-ID regression on resume: last seen {last}, first resumed {first}; "
            "ID space was reset by the server; re-initialize"
        )
    if first > last + 1 and attempt.carries_requests:
        raise ResumptionScopeError(
            f"unreplayed gap on request-bearing stream: {last} -> {first}; "
            "server did not replay events in the gap; re-initialize"
        )
    # first == last + 1, or gap on a notification-only stream: acceptable.
