# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-session-across-the-sse-to-streamable-http-transport-boundary-and-the-server-s-last-event-id-replay-window.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-session-across-the-sse-to-streamable-http-transport-boundary-and-the-server-s-last-event-id-replay-window.warrant.json
# Markdown SHA-256:   35331b5a01231d00a9e800061d6e32081951567898a749db79dcccd42876902c
# Code AST SHA-256:   15938e6b8d54a82be9c3f219cd6e9060bf003e8ecc6f707264336e1fc4bc2175
# Verified Classes:   ResumptionContinuityError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ResumptionContinuityError(RuntimeError):
    """Raised when an MCP streamable-HTTP resumption cannot prove continuity."""


def resume_stream(
    session_id: str,
    request_stream_id: str,
    last_event_id: int,
    response_headers: dict,
    first_replayed_event_id: int | None,
) -> int:
    """
    Decide whether a resumption response is a genuine replay or a silent reset.
    Returns the event id the client may safely treat as its dedup cursor.
    Raises ResumptionContinuityError if continuity cannot be established.
    """
    echoed_stream = response_headers.get("x-mcp-request-stream-id")
    replay_miss = response_headers.get("x-mcp-replay-miss") == "true"

    if replay_miss:
        raise ResumptionContinuityError(
            f"server signalled replay_miss for session={session_id} "
            f"stream={request_stream_id}; in-flight call is unresolved"
        )

    if echoed_stream != request_stream_id:
        raise ResumptionContinuityError(
            f"stream identity mismatch: requested stream={request_stream_id} "
            f"response echoed={echoed_stream!r}; Last-Event-ID={last_event_id} "
            f"is not authoritative for this response"
        )

    if first_replayed_event_id is None:
        raise ResumptionContinuityError(
            f"no replayed event id present for session={session_id} "
            f"stream={request_stream_id}; cannot distinguish replay from reset"
        )

    if first_replayed_event_id <= last_event_id:
        raise ResumptionContinuityError(
            f"non-monotonic replay: first_event_id={first_replayed_event_id} "
            f"<= last_event_id={last_event_id}; server likely reset the stream"
        )

    return first_replayed_event_id
