# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-stream-continuity-when-an-mcp-http-native-transport-resumes-across-a-renegotiated-session.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-stream-continuity-when-an-mcp-http-native-transport-resumes-across-a-renegotiated-session.warrant.json
# Markdown SHA-256:   04568d3a4f0f14d4e6dcc2a676628c47f996a8d42ab71186fcc1544ac33a4358
# Code AST SHA-256:   a110f3b84f1f98d7dbbaff737ca3d8c769051d53fd6611e324214a78e7180f38
# Verified Classes:   StreamResumeViolation, ResumeCursor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class StreamResumeViolation(RuntimeError):
    """Raised when a resumed MCP stream cannot be proven continuous with the
    in-flight request that issued it. Fail closed: never advance state on a
    stream whose provenance is unverified."""
    pass


@dataclass(frozen=True)
class ResumeCursor:
    session_id: str
    stream_id: str
    last_event_id: int
    request_id: str


def resume_stream(
    client_cursor: ResumeCursor,
    server_cursor: ResumeCursor | None,
    first_event: dict,
) -> None:
    # 1. The (session, stream) pair must match. A valid session with a foreign
    #    stream is the dangerous split-identity case.
    if server_cursor is None:
        raise StreamResumeViolation(
            f"no durable cursor for session={client_cursor.session_id!r} "
            f"stream={client_cursor.stream_id!r}; refusing silent restart"
        )
    if (server_cursor.session_id, server_cursor.stream_id) != (
        client_cursor.session_id,
        client_cursor.stream_id,
    ):
        raise StreamResumeViolation(
            "resume cursor belongs to a different (session, stream) pair: "
            f"client={(client_cursor.session_id, client_cursor.stream_id)!r} "
            f"server={(server_cursor.session_id, server_cursor.stream_id)!r}"
        )

    # 2. The event counter must be a genuine continuation, not a coincidental
    #    numeric overlap from a reset counter that has since advanced.
    if server_cursor.last_event_id < client_cursor.last_event_id:
        raise StreamResumeViolation(
            f"server cursor {server_cursor.last_event_id} is behind client "
            f"Last-Event-ID {client_cursor.last_event_id}; counter likely reset"
        )

    # 3. The first delivered event must carry the originating request token.
    #    Stream position alone is not provenance.
    if first_event.get("requestId") != client_cursor.request_id:
        raise StreamResumeViolation(
            f"first resumed event correlates to request "
            f"{first_event.get('requestId')!r}, expected "
            f"{client_cursor.request_id!r}; stream aliasing detected"
        )
