# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-silently-downgraded-mcp-streamable-http-session-before-it-resumes-from-a-stale-sse-cursor.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-silently-downgraded-mcp-streamable-http-session-before-it-resumes-from-a-stale-sse-cursor.warrant.json
# Markdown SHA-256:   6224640a67e0bf2316ddebcc5faf2e00d5002034a91f1c7485759b48bcf35767
# Code AST SHA-256:   3b5edd194401e84f2f94bfd42eea46081fd36a1f77e559a59f8f90baf1d69db3
# Verified Classes:   StreamResumeViolation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class StreamResumeViolation(RuntimeError):
    """Raised when a resumed MCP SSE stream cannot honor the client's cursor."""
    pass


def validate_resume_first_event(
    cursor_sent: str,
    first_event_id: str,
    session_sent: str,
    session_echoed: str,
    resumable_advertised: bool,
    id_is_numeric: bool,
) -> None:
    """
    Called by the transport reader on the FIRST event after a reconnect,
    before dispatch to the JSON-RPC demultiplexer.

    Raises StreamResumeViolation on any condition that means the server
    silently downgraded a resumable session to a fresh one.
    """
    if not resumable_advertised:
        # Never had a resumable session; caller must re-initialize, not resume.
        raise StreamResumeViolation(
            "resume attempted on non-resumable transport; re-initialize required"
        )

    if session_echoed != session_sent:
        raise StreamResumeViolation(
            f"session identity changed across resume: sent={session_sent!r} "
            f"echoed={session_echoed!r}; treat as fresh session, replay pending calls"
        )

    if not id_is_numeric:
        # Opaque IDs: monotonicity cannot be checked numerically. Require a
        # server-provided generation token instead; absence is itself a violation.
        raise StreamResumeViolation(
            "opaque event IDs with no generation token; cannot prove continuity"
        )

    try:
        cursor_val = int(cursor_sent)
        first_val = int(first_event_id)
    except (TypeError, ValueError) as exc:
        raise StreamResumeViolation(
            f"unparseable cursor/event id: cursor={cursor_sent!r} "
            f"first_event={first_event_id!r}"
        ) from exc

    if first_val <= cursor_val:
        raise StreamResumeViolation(
            f"event log reset detected: cursor={cursor_val} but first resumed "
            f"event id={first_val}; server accepted Last-Event-ID without honoring it"
        )
    # Strictly greater, same session, resumable: safe to dispatch.
