# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-sse-last-event-id-resumption-as-unsafe-after-an-mcp-server-restarts-mid-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-sse-last-event-id-resumption-as-unsafe-after-an-mcp-server-restarts-mid-stream.warrant.json
# Markdown SHA-256:   eda1d77898637350900cd67097cc9de6c26d2e24abe80764951133d34cd736a1
# Code AST SHA-256:   67b48d893f7e2b0992186f9be451dc109d145b0a126e0bee02880deb36473047
# Verified Classes:   StreamContinuityViolation, ResumeProbe, ResumeResponse
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class StreamContinuityViolation(RuntimeError):
    """Raised when an SSE resume cannot be proven to continue the original stream."""


@dataclass(frozen=True)
class ResumeProbe:
    prior_session_id: str
    prior_last_event_id: int
    prior_progress_token: str
    prior_progress_value: float


@dataclass(frozen=True)
class ResumeResponse:
    status: int
    session_id: str | None
    first_event_id: int | None
    progress_token: str | None
    progress_value: float | None


def validate_resume(probe: ResumeProbe, resp: ResumeResponse) -> None:
    """Enforce the MCP SSE resumption invariant.

    Safe resume requires: same session, strictly advancing event id,
    and non-regressing progress for the same progress token. Anything
    else is a divergent stream and must be treated as a lost call.
    """
    if resp.status in (404, 410):
        raise StreamContinuityViolation(
            f"server has no stream for Last-Event-ID={probe.prior_last_event_id} "
            f"(status={resp.status}); prior tools/call is lost, must re-issue"
        )
    if resp.status != 200:
        raise StreamContinuityViolation(
            f"unexpected resume status {resp.status}"
        )
    if resp.session_id != probe.prior_session_id:
        raise StreamContinuityViolation(
            f"session changed on resume: {probe.prior_session_id!r} -> "
            f"{resp.session_id!r}; stream is not causally continuous"
        )
    if resp.first_event_id is None or resp.first_event_id <= probe.prior_last_event_id:
        raise StreamContinuityViolation(
            f"non-advancing event id: prior={probe.prior_last_event_id} "
            f"first_after={resp.first_event_id}"
        )
    if (
        resp.progress_token == probe.prior_progress_token
        and resp.progress_value is not None
        and resp.progress_value < probe.prior_progress_value
    ):
        raise StreamContinuityViolation(
            f"progress regressed for token {probe.prior_progress_token!r}: "
            f"{probe.prior_progress_value} -> {resp.progress_value}; "
            "emitter lifetime diverged from call lifetime"
        )
