# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-silently-rolled-back-sse-resume-cursor-when-an-mcp-http-native-streamable-transport-renegotiates-session-headers-mid-str.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-silently-rolled-back-sse-resume-cursor-when-an-mcp-http-native-streamable-transport-renegotiates-session-headers-mid-str.warrant.json
# Markdown SHA-256:   d3143523959ae0a80844ad3bea4d161fc5e9e381d7c538a2eb761febb20dbbac
# Code AST SHA-256:   ce7eaf710c5bf18ab1438d065dc682e4b9068645b5ef39945287c230a7fe3246
# Verified Classes:   SessionSpliceError, ResumeContext
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass


class SessionSpliceError(RuntimeError):
    """Raised when an SSE resume silently splices a different session's event history."""


@dataclass(frozen=True)
class ResumeContext:
    requested_session_id: str
    last_event_id: int


def validate_resume(
    ctx: ResumeContext,
    response_session_id: str | None,
    first_event_id: int | None,
    first_event_data: str | None,
) -> None:
    # Gate 1: session identity. A server that lazily re-provisioned a session
    # will echo a different Mcp-Session-Id. This is a splice, not a resume.
    if response_session_id is None:
        raise SessionSpliceError(
            f"resume for session {ctx.requested_session_id!r} returned no "
            f"Mcp-Session-Id header; cannot confirm continuity"
        )
    if response_session_id != ctx.requested_session_id:
        raise SessionSpliceError(
            f"session identity changed on resume: sent "
            f"{ctx.requested_session_id!r}, got {response_session_id!r}; "
            f"replayed events belong to a different event namespace"
        )

    # Gate 2: cursor contiguity. Even under the same session, a clamped or
    # truncated event log yields a first ID that is not Last-Event-ID + 1.
    if first_event_id is None:
        raise SessionSpliceError(
            f"resume for session {ctx.requested_session_id!r} returned an "
            f"event frame with no id; cannot verify contiguity"
        )
    if first_event_id != ctx.last_event_id + 1:
        raise SessionSpliceError(
            f"non-contiguous resume: Last-Event-ID={ctx.last_event_id}, "
            f"first replayed id={first_event_id}; expected "
            f"{ctx.last_event_id + 1}. Events in "
            f"[{first_event_id}, {ctx.last_event_id}] are either lost or "
            f"belong to a different session."
        )

    # Gate 3: payload sanity. A replayed event that parses but references a
    # JSON-RPC id not bound to this session is also a splice signal.
    if first_event_data is not None:
        try:
            payload = json.loads(first_event_data)
        except json.JSONDecodeError as exc:
            raise SessionSpliceError(
                f"unparseable first replayed event in session "
                f"{ctx.requested_session_id!r}: {exc}"
            ) from exc
        if payload.get("session") not in (None, ctx.requested_session_id):
            raise SessionSpliceError(
                f"first replayed event carries session "
                f"{payload.get('session')!r}, not "
                f"{ctx.requested_session_id!r}"
            )
