# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-streamable-http-mcp-session-as-unresumable-after-a-transport-level-reconnect.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-streamable-http-mcp-session-as-unresumable-after-a-transport-level-reconnect.warrant.json
# Markdown SHA-256:   e1ba69f45cd5f40f28655a55935ed3ac015202796a5aa0c7d5cb7c64e0496747
# Code AST SHA-256:   a290b2a894efe267a1c805a7d08dc92f492653df48a2b2f0b6c6da9e9a3c4a5c
# Verified Classes:   UnresumableSessionError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UnresumableSessionError(RuntimeError):
    """Raised when a Streamable-HTTP MCP reconnect cannot be treated as a valid resume."""


def verify_resumption(
    sent_session_id: str,
    response_session_id: str,
    last_event_id: int,
    first_replayed_event_id: int | None,
    status_code: int,
    echoed_event_session_ids: list[str],
) -> None:
    if status_code == 404:
        raise UnresumableSessionError(
            f"session {sent_session_id!r} terminated by server (404); re-initialize required"
        )
    if response_session_id != sent_session_id:
        raise UnresumableSessionError(
            f"session id rotated: sent {sent_session_id!r}, got {response_session_id!r}; "
            "replayed state belongs to a different logical session"
        )
    if first_replayed_event_id is not None and first_replayed_event_id != last_event_id + 1:
        raise UnresumableSessionError(
            f"replay gap: resumed after {last_event_id} but first replayed event is "
            f"{first_replayed_event_id}; intervening tool results are lost"
        )
    for echoed in echoed_event_session_ids:
        if echoed != sent_session_id:
            raise UnresumableSessionError(
                f"event payload echoes session {echoed!r} != {sent_session_id!r}; "
                "server rotated state behind a stable-looking header"
            )


def resume_or_reinitialize(ctx, response) -> None:
    verify_resumption(
        sent_session_id=ctx.session_id,
        response_session_id=response.headers.get("Mcp-Session-Id", ""),
        last_event_id=ctx.last_event_id,
        first_replayed_event_id=response.first_event_id(),
        status_code=response.status,
        echoed_event_session_ids=response.echoed_session_ids(),
    )
    ctx.apply_replay(response.events)
