# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-last-event-id-replay-against-a-bounded-sse-ring-buffer-when-an-mcp-streamable-http-session-resumes-mid-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-last-event-id-replay-against-a-bounded-sse-ring-buffer-when-an-mcp-streamable-http-session-resumes-mid-tool-call.warrant.json
# Markdown SHA-256:   c6531f24a93bdf4bbca3e35c3d941186644aeb38b1cf673693a215abe9123cd1
# Code AST SHA-256:   ebc4b561af8a636fd4d551770e58f67c958a6a96cf1083d77a8726d8bc4703ff
# Verified Classes:   StreamContinuityError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StreamContinuityError(RuntimeError):
    """Raised when a resumed SSE stream cannot satisfy the client's Last-Event-ID cursor."""
    pass


STATE_BEARING_EVENTS = {
    "notifications/progress",
    "notifications/resources/updated",
    "sampling/result",
    "tool/output_chunk",
}


def validate_resume(
    last_consumed_id: int,
    first_replayed_id: int,
    replayed_event_types: list[str],
    resume_floor: int | None = None,
) -> None:
    """Enforce the contiguity invariant on a resumed MCP SSE stream.

    Raises StreamContinuityError if the server could not honor the cursor
    and the resulting gap is state-bearing.
    """
    if resume_floor is not None and last_consumed_id < resume_floor:
        raise StreamContinuityError(
            f"resume rejected: Last-Event-ID {last_consumed_id} is below "
            f"server replay floor {resume_floor}; session state is unverifiable"
        )

    if first_replayed_id <= last_consumed_id:
        raise StreamContinuityError(
            f"duplicate replay: first replayed id {first_replayed_id} "
            f"<= last consumed {last_consumed_id}"
        )

    expected = last_consumed_id + 1
    if first_replayed_id != expected:
        missed = first_replayed_id - expected
        # classify the gap: we only know the types that *were* replayed,
        # so conservatively treat any gap as state-bearing unless the
        # caller can prove otherwise from a durable log.
        if any(t in STATE_BEARING_EVENTS for t in replayed_event_types):
            raise StreamContinuityError(
                f"state-bearing gap of {missed} event(s): expected id {expected}, "
                f"got {first_replayed_id}; session poisoned, re-issue call"
            )
        raise StreamContinuityError(
            f"tolerable progress gap of {missed} event(s) at id {expected}; "
            f"mark progress approximate before accepting terminal frame"
        )
