# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-a-resumable-mcp-streamable-session-gap-from-a-terminal-session-teardown-when-the-sse-id-cursor-survives-but-the-ser.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-a-resumable-mcp-streamable-session-gap-from-a-terminal-session-teardown-when-the-sse-id-cursor-survives-but-the-ser.warrant.json
# Markdown SHA-256:   d830f43dc17262a4fc9cec833fde3b53247e4929bfdf4e2aeeab6ce0a7ba5414
# Code AST SHA-256:   4f85404551d00a8d7acf70fadaec844bd0d7c193d4c72d48ebfa1528f6efe774
# Verified Classes:   SessionResumptionError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SessionResumptionError(RuntimeError):
    """Raised when SSE replay succeeds but session liveness cannot be confirmed."""
    pass


def resume_streamable_session(
    session_id: str,
    last_event_id: str,
    open_sse,          # callable(session_id, last_event_id) -> (status, events)
    probe_liveness,    # callable(session_id) -> status
) -> list:
    status, buffered_events = open_sse(session_id, last_event_id)

    if status in (404, 410):
        raise SessionResumptionError(
            f"session {session_id} rejected at transport layer (status={status}); "
            f"teardown and re-initialize"
        )
    if status != 200:
        raise SessionResumptionError(
            f"unexpected SSE status {status} for session {session_id}; "
            f"cannot classify as resumable or terminal"
        )

    # Replay succeeded. This does NOT confirm session liveness.
    probe_status = probe_liveness(session_id)
    if probe_status in (404, 410):
        raise SessionResumptionError(
            f"session {session_id} dead despite successful SSE replay; "
            f"quarantine {len(buffered_events)} buffered events, discard cursor, re-initialize"
        )
    if probe_status != 200:
        raise SessionResumptionError(
            f"liveness probe for session {session_id} returned {probe_status}; "
            f"refusing to apply buffered events under ambiguous session state"
        )

    return buffered_events
