# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-recover-from-a-streamable-mcp-resume-that-silently-reattaches-to-a-different-server-generation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-recover-from-a-streamable-mcp-resume-that-silently-reattaches-to-a-different-server-generation.warrant.json
# Markdown SHA-256:   d8a7a6642ecb8cdaa7677abd2f1c153275f35e423eda72faf836b9b1475d1fbe
# Code AST SHA-256:   d98cfedd73d672249053cad4b84f95b3b0ab8b6ed0f2ca84c43d0d6e63471015
# Verified Classes:   ResumeProvenanceError, SessionCursor
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ResumeProvenanceError(RuntimeError):
    """Raised when a streamable-MCP resume cannot prove session continuity."""


@dataclass(frozen=True)
class SessionCursor:
    session_id: str
    generation: int
    last_event_id: int
    last_progress: int


def validate_resume(
    cursor: SessionCursor,
    response_session_id: str | None,
    response_generation: int | None,
    first_event_id: int,
    first_event_progress: int,
    server_asserted_resumed: bool,
) -> None:
    # 1. Provenance token must match exactly; absence is fatal, not "unknown".
    if response_session_id is None or response_generation is None:
        raise ResumeProvenanceError(
            "server omitted session/generation token; cannot prove continuity"
        )
    if response_session_id != cursor.session_id:
        raise ResumeProvenanceError(
            f"session id mismatch: expected {cursor.session_id!r}, "
            f"got {response_session_id!r}"
        )
    if response_generation != cursor.generation:
        raise ResumeProvenanceError(
            f"generation crossed: expected {cursor.generation}, "
            f"got {response_generation}; server likely restarted"
        )

    # 2. Server must assert it replayed from its buffer, not started fresh.
    if not server_asserted_resumed:
        raise ResumeProvenanceError(
            "server opened a fresh stream instead of replaying from cursor"
        )

    # 3. Cursor must advance strictly.
    if first_event_id <= cursor.last_event_id:
        raise ResumeProvenanceError(
            f"event id did not advance past cursor: "
            f"{first_event_id} <= {cursor.last_event_id}"
        )

    # 4. Application counter regression during resume is proof of substitution,
    #    NOT a stale duplicate to be silently discarded.
    if first_event_progress < cursor.last_progress:
        raise ResumeProvenanceError(
            f"progress regressed on resume ({first_event_progress} < "
            f"{cursor.last_progress}); stream belongs to another task"
        )
