# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-resume-an-mcp-stream-after-a-last-event-id-replay-gap-and-how-does-sse-backpressure-corrupt-the-resum.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-resume-an-mcp-stream-after-a-last-event-id-replay-gap-and-how-does-sse-backpressure-corrupt-the-resum.warrant.json
# Markdown SHA-256:   e933351efe1a7fa19de8f3377ef5fe350843bf69cc47f3cb34d812a7d7d9df81
# Code AST SHA-256:   6aea1313a1f04b392a33ac802f2ebe250639431e93f45a768176f4a28c65a9cb
# Verified Classes:   ResumeGapError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ResumeGapError(RuntimeError):
    """Raised when an MCP SSE resume replays from an ID that skips past the client's last-received event."""
    pass


def resume_stream(client, last_received_id: int, replay_window: tuple[int, int]):
    min_retained, max_committed = replay_window
    if last_received_id < min_retained - 1:
        # Our watermark predates the server's retention floor: events are gone.
        raise ResumeGapError(
            f"last_received_id={last_received_id} below retention floor {min_retained}; "
            f"events {last_received_id + 1}..{min_retained - 1} unrecoverable"
        )
    first = client.open_resume(last_event_id=last_received_id).first_event_id()
    if first != last_received_id + 1:
        # Numerically-greater first ID is data loss, not a heartbeat skip.
        raise ResumeGapError(
            f"resume from {last_received_id} replayed first event {first}; "
            f"gap of {first - last_received_id - 1} events — reinitialize session"
        )
    return client.continue_stream()
