# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-lost-mcp-sse-resumption-window-when-the-last-event-id-cursor-outlives-the-server-s-replay-buffer.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-lost-mcp-sse-resumption-window-when-the-last-event-id-cursor-outlives-the-server-s-replay-buffer.warrant.json
# Markdown SHA-256:   29909ed0937384c92202d3862e163ab73db5626583f4dd1eaaf6dcfe1ba3f1a2
# Code AST SHA-256:   8cf322c6f91730ce19321f8258c5752cf78d46cbb92b2e9039ea62961e45f4de
# Verified Classes:   ResumptionGapError, StreamCursor
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ResumptionGapError(RuntimeError):
    """Raised when a resumed MCP SSE stream cannot prove continuity from Last-Event-ID."""
    pass


@dataclass
class StreamCursor:
    session_id: str
    last_consumed_id: int
    last_consumed_hash: str


def validate_resumed_stream(
    cursor: StreamCursor,
    first_resumed_id: int,
    first_resumed_payload: bytes,
    server_replay_buffer_size: int,
    unread_queue_depth_at_disconnect: int,
) -> None:
    """
    Assert continuity of a resumed MCP SSE stream.

    A resumed stream is continuous only if the first event delivered after
    reconnection is exactly cursor.last_consumed_id + 1. MCP HTTP-native
    transport does not mandate a gap signal, so this check is the client's
    only defense against silent event loss when the server's bounded replay
    buffer has evicted the requested cursor.
    """
    expected_next = cursor.last_consumed_id + 1

    if first_resumed_id != expected_next:
        gap = first_resumed_id - expected_next
        # Effective replay capacity is reduced by the client's unread backlog,
        # because those events were already in the buffer at disconnect time.
        effective_capacity = server_replay_buffer_size - unread_queue_depth_at_disconnect
        raise ResumptionGapError(
            f"Resumption gap on session {cursor.session_id}: "
            f"expected first event id {expected_next}, got {first_resumed_id} "
            f"({gap} events lost). Server replay buffer={server_replay_buffer_size}, "
            f"unread backlog at disconnect={unread_queue_depth_at_disconnect}, "
            f"effective capacity={effective_capacity}. "
            f"Stream is unverified; re-derive task state from durable checkpoint "
            f"or call resume_from({cursor.last_consumed_id})."
        )

    # Even with contiguous IDs, verify the payload hash of the boundary event
    # to catch servers that reuse IDs across reconnects (non-monotonic IDs).
    actual_hash = hashlib.sha256(first_resumed_payload).hexdigest()
    if cursor.last_consumed_hash and actual_hash == cursor.last_consumed_hash:
        raise ResumptionGapError(
            f"Boundary event id {first_resumed_id} on session {cursor.session_id} "
            f"replays a payload identical to the last consumed event; server may be "
            f"re-emitting rather than advancing. Treat stream as unverified."
        )


def resume_or_checkpoint(
    cursor: StreamCursor,
    first_resumed_id: int,
    first_resumed_payload: bytes,
    server_replay_buffer_size: int,
    unread_queue_depth_at_disconnect: int,
    checkpoint_loader,
) -> Optional[object]:
    """Attempt resumption; on gap, fall back to durable checkpoint."""
    try:
        validate_resumed_stream(
            cursor=cursor,
            first_resumed_id=first_resumed_id,
            first_resumed_payload=first_resumed_payload,
            server_replay_buffer_size=server_replay_buffer_size,
            unread_queue_depth_at_disconnect=unread_queue_depth_at_disconnect,
        )
        return None  # stream is continuous; continue consuming
    except ResumptionGapError:
        return checkpoint_loader(cursor.session_id)
