# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-sse-resumption-has-silently-crossed-an-oauth-2-1-resource-server-binding-boundary-in-mcp-streamable-http-transport.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-sse-resumption-has-silently-crossed-an-oauth-2-1-resource-server-binding-boundary-in-mcp-streamable-http-transport.warrant.json
# Markdown SHA-256:   60f88f9802e99ecbc4633704929cb282b3d478f301125a3c1bdb98a9bcc7dd24
# Code AST SHA-256:   94291f5be2615861ba8d3091e6febe3bfd8a1fed1d0a3a860486c258442ce12b
# Verified Classes:   ResumeBindingError, AuthContext, StoredEvent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ResumeBindingError(RuntimeError):
    """Raised when an SSE resume crosses an OAuth 2.1 resource-server binding boundary."""


@dataclass(frozen=True)
class AuthContext:
    sub: str
    client_id: str
    aud: str
    scope: frozenset[str]


@dataclass(frozen=True)
class StoredEvent:
    event_id: int
    auth: AuthContext


def resume_stream(
    last_event_id: int,
    presenting: AuthContext,
    event_store: dict[int, StoredEvent],
    server_aud: str,
) -> list[StoredEvent]:
    # 1. The presenting token must be bound to *this* resource server.
    if presenting.aud != server_aud:
        raise ResumeBindingError(
            f"token aud={presenting.aud!r} does not match server aud={server_aud!r}; "
            "resume would replay events authorized for a different resource server"
        )

    # 2. Collect the contiguous suffix after the client's cursor.
    suffix = [e for eid, e in sorted(event_store.items()) if eid > last_event_id]
    if not suffix:
        # Empty is ambiguous: caught-up vs. wrong-partition. Fail closed.
        raise ResumeBindingError(
            f"empty replay after Last-Event-ID={last_event_id}; cannot distinguish "
            "stream completion from authorization-partition mismatch"
        )

    # 3. Every replayed event must have been persisted under a context
    #    compatible with the presenting token. Scope may narrow, never widen.
    for ev in suffix:
        if ev.auth.sub != presenting.sub or ev.auth.client_id != presenting.client_id:
            raise ResumeBindingError(
                f"event {ev.event_id} persisted under sub={ev.auth.sub!r}/"
                f"client={ev.auth.client_id!r}, replay requested under "
                f"sub={presenting.sub!r}/client={presenting.client_id!r}"
            )
        if not ev.auth.scope.issubset(presenting.scope):
            raise ResumeBindingError(
                f"event {ev.event_id} requires scope {sorted(ev.auth.scope)}, "
                f"presenting token carries {sorted(presenting.scope)}"
            )

    return suffix
