# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-resumed-mcp-stream-when-the-server-s-last-event-id-replay-window-has-already-been-compacted-the-silent-event-gap-invar.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-resumed-mcp-stream-when-the-server-s-last-event-id-replay-window-has-already-been-compacted-the-silent-event-gap-invar.warrant.json
# Markdown SHA-256:   d020e460ae3ad8ea1c223950d9c4d33e678df9fbc69caca9d72c96a43f754b94
# Code AST SHA-256:   768b31e2a4b467e4d9e2d8c6a2196e452b86d9f0b433e97ffe69401e974bdd47
# Verified Classes:   McpResumeGapError, ResumeState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import dataclasses
from typing import Optional


class McpResumeGapError(RuntimeError):
    """Raised when a resumed MCP SSE stream cannot prove contiguity."""


@dataclasses.dataclass
class ResumeState:
    last_event_id: int
    session_id: str


def validate_resume_seam(
    state: ResumeState,
    first_event_id: Optional[int],
    first_event_is_keepalive: bool,
) -> int:
    """
    Called on the first non-comment SSE frame after a resume.
    Returns the new cursor if contiguity holds; raises otherwise.
    """
    if first_event_is_keepalive:
        # A keepalive proves liveness, not contiguity. Do not advance.
        raise McpResumeGapError(
            f"resume for session {state.session_id}: first frame is keepalive; "
            f"cannot prove contiguity past last_event_id={state.last_event_id}"
        )

    if first_event_id is None:
        raise McpResumeGapError(
            f"resume for session {state.session_id}: first event carries no id; "
            f"server did not honor Last-Event-ID={state.last_event_id}"
        )

    expected = state.last_event_id + 1

    if first_event_id == expected:
        return first_event_id

    if first_event_id < expected:
        # Overlapping replay: idempotent dedupe is safe, cursor does not regress.
        return state.last_event_id

    # first_event_id > expected: forward gap. Events [expected, first_event_id)
    # were evicted from the server's replay buffer. The stream is semantically
    # lossy; the terminal event for an in-flight call may be inside the gap.
    raise McpResumeGapError(
        f"resume for session {state.session_id}: forward gap detected, "
        f"expected id {expected} but observed {first_event_id}; "
        f"{first_event_id - expected} event(s) lost to replay-buffer compaction. "
        f"Refusing to advance cursor; escalate to session re-initialization."
    )


def resume_stream(
    state: ResumeState,
    server_frames: list[dict],
) -> ResumeState:
    """
    Consume the head of a resumed stream, enforcing the contiguity invariant
    before any event is applied to the agent state machine.
    """
    if not server_frames:
        raise McpResumeGapError(
            f"resume for session {state.session_id}: empty stream head; "
            f"no evidence of contiguity past last_event_id={state.last_event_id}"
        )

    head = server_frames[0]
    new_cursor = validate_resume_seam(
        state,
        first_event_id=head.get("id"),
        first_event_is_keepalive=head.get("comment_only", False),
    )
    return ResumeState(last_event_id=new_cursor, session_id=state.session_id)
