# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-resume-an-sse-stream-after-mcp-session-re-authentication-because-the-last-event-id-cursor-belongs-to-a-pr.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-resume-an-sse-stream-after-mcp-session-re-authentication-because-the-last-event-id-cursor-belongs-to-a-pr.warrant.json
# Markdown SHA-256:   0e155921dcb24c0f8f8c3218738c33bfa71af163d297c793d4b27b1db278694f
# Code AST SHA-256:   c7d6615fa31ec507f61ecbce1c79d43e84ddbe2c8e7778c72f05237449ea1953
# Verified Classes:   CrossEpochResumeError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CrossEpochResumeError(RuntimeError):
    """Raised when an SSE resume would replay events across an authorization epoch boundary."""


def authorize_resume(
    cursor_epoch: str,
    current_token_epoch: str,
    replay_window_events: list[dict],
    current_token_scope: frozenset[str],
) -> bool:
    """
    Decide whether resuming an SSE stream from `cursor_epoch` under
    `current_token_epoch` is safe. Returns True only if every event in the
    replay window was produced under a scope contained in the current token.
    """
    if cursor_epoch == current_token_epoch:
        return True

    # Epoch changed. We may only resume if we can prove scope containment
    # for every event in the replay window.
    for ev in replay_window_events:
        ev_scope = ev.get("producing_scope")
        if ev_scope is None:
            # No scope stamp: cannot prove containment. Refuse.
            raise CrossEpochResumeError(
                f"event {ev.get('id')} in replay window lacks producing_scope; "
                f"cannot resume across epoch change {cursor_epoch!r} -> "
                f"{current_token_epoch!r}"
            )
        if not frozenset(ev_scope).issubset(current_token_scope):
            raise CrossEpochResumeError(
                f"event {ev.get('id')} produced under scope {sorted(ev_scope)} "
                f"not contained in current token scope "
                f"{sorted(current_token_scope)}; cross-epoch replay forbidden"
            )
    return True


def handle_sse_resume(
    session_id: str,
    last_event_id: str,
    token_epoch: str,
    token_scope: frozenset[str],
    session_store,
) -> list[dict]:
    sess = session_store.get(session_id)
    if sess is None:
        raise CrossEpochResumeError(f"session {session_id} not found; cannot resume")

    window = sess.events_after(last_event_id)  # (Last-Event-ID, head]
    try:
        authorize_resume(sess.cursor_epoch, token_epoch, window, token_scope)
    except CrossEpochResumeError:
        # Refuse the resume; caller must restart from head on a fresh stream.
        # Do NOT silently return the window.
        raise

    return window
