# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-sse-stream-after-a-session-has-been-silently-reaped-mid-reconnect.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-sse-stream-after-a-session-has-been-silently-reaped-mid-reconnect.warrant.json
# Markdown SHA-256:   d250fec468a7400562822d56ce005b2f3eb496e455de2a88480c0783cde86078
# Code AST SHA-256:   2a588226d84ace2c40ed8d8644fa687dcdd5f5b8dcbceb3f839c4b53e5db1816
# Verified Classes:   SessionResumptionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SessionResumptionError(RuntimeError):
    """Raised when SSE replay succeeds but session liveness cannot be confirmed,
    or when a resumable event buffer has a gap that would silently lose state."""
    pass


def resume_stream(session_id: str, last_event_id: int, server) -> dict:
    # Step 1: confirm the session record still exists. Do NOT infer this
    # from the stream reconnect succeeding.
    session = server.get_session(session_id)
    if session is None:
        # Session reaped. Even if the event buffer is readable, replaying
        # would present dead-session events as live. Refuse.
        raise SessionResumptionError(
            f"session {session_id!r} reaped; Last-Event-ID {last_event_id} "
            f"is unrecoverable in a live context; client must re-initialize"
        )

    # Step 2: check the event buffer for a gap between last_event_id and
    # the oldest retained event. A gap is a state-sync event, not a
    # transport error.
    oldest = server.event_buffer.oldest_id(session_id)
    if oldest is None or oldest > last_event_id + 1:
        raise SessionResumptionError(
            f"event buffer gap for session {session_id!r}: "
            f"requested resume after {last_event_id}, oldest retained is {oldest}; "
            f"client must re-fetch full state, not retry transport"
        )

    # Step 3: only now is replay semantically sound.
    return {
        "session_id": session_id,
        "replay_from": last_event_id + 1,
        "replay_to": server.event_buffer.newest_id(session_id),
        "liveness_confirmed": True,
    }
