# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-an-mcp-sse-session-after-a-streamable-http-upgrade-the-last-event-id-replay-gap-across-transport-migration.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-resume-an-mcp-sse-session-after-a-streamable-http-upgrade-the-last-event-id-replay-gap-across-transport-migration.warrant.json
# Markdown SHA-256:   2826b143834e3b3e47355a5a992aabcdad708d2a6cfce250c0e1f38e36abc039
# Code AST SHA-256:   394e60a17e367a0de9b9bc9e4c9cb620fa835423de4b2f4bc65397bdce07ded0
# Verified Classes:   ResumePointUnreplayable
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ResumePointUnreplayable(RuntimeError):
    """Raised when a Last-Event-ID cannot be served from the current replay store.

    Distinct from a generic protocol error: the client's ID is numerically valid
    (<= current counter) but the referenced event is not physically present in
    the store backing the transport that would serve the resumed stream. This
    typically occurs after a legacy-SSE -> streamable-HTTP migration where the
    per-connection SSE buffer was discarded but the event counter was preserved.
    """
    pass


def resume_stream(session, last_event_id, current_store):
    """Decide whether to resume an MCP stream at last_event_id.

    Returns the next event ID to emit. Raises ResumePointUnreplayable if the
    resume point exists in the counter but not in the current replay store.
    """
    if last_event_id is None:
        return session.counter.current + 1

    if last_event_id > session.counter.current:
        raise ResumePointUnreplayable(
            f"Last-Event-ID {last_event_id} is ahead of server counter "
            f"{session.counter.current}; stale session or split-brain."
        )

    if not current_store.contains(last_event_id):
        # Counter continuity is NOT replayability. The event predates the
        # current transport generation's store (e.g., discarded SSE buffer
        # from before a streamable-HTTP upgrade). Refuse rather than resume
        # from an empty buffer and emit a silently holed stream.
        raise ResumePointUnreplayable(
            f"Last-Event-ID {last_event_id} is <= counter "
            f"{session.counter.current} but absent from the current replay "
            f"store (transport generation {current_store.generation}); "
            f"resume would drop events. Client must reconcile from snapshot."
        )

    return last_event_id + 1
