# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-sse-resumption-from-re-binding-a-stale-mcp-session-to-a-rotated-oauth-2-1-resource-token.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-sse-resumption-from-re-binding-a-stale-mcp-session-to-a-rotated-oauth-2-1-resource-token.warrant.json
# Markdown SHA-256:   913343ab35ed4fe25a08562fcb00d1d2009fa2c837e201a0cd63d6040b7efc7c
# Code AST SHA-256:   8c35d4d0fc73215d373f59d17460c2c48d5bc14d59eda776cafcf4b335f85209
# Verified Classes:   ResumptionAuthorizationError, AuthContext, BufferedEvent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ResumptionAuthorizationError(RuntimeError):
    """Raised when an SSE resumption request cannot be safely authorized
    against the authorization context that was in force when the buffered
    events were emitted."""


@dataclass(frozen=True)
class AuthContext:
    sub: str
    grant_id: str
    scopes: frozenset[str]

    def covers(self, other: "AuthContext") -> bool:
        # A resumption context covers an emission context iff same subject,
        # same grant lineage, and every emission scope is present.
        return (
            self.sub == other.sub
            and self.grant_id == other.grant_id
            and other.scopes.issubset(self.scopes)
        )


@dataclass(frozen=True)
class BufferedEvent:
    event_id: int
    payload: str  # already redacted at buffer-write time
    emission_ctx: AuthContext


def authorize_resumption(
    session_sub: str,
    session_grant_id: str,
    resumption_ctx: AuthContext,
    buffer: list[BufferedEvent],
    last_event_id: Optional[int],
) -> list[BufferedEvent]:
    # Invariant 1: session is bound to the subject that minted it.
    if resumption_ctx.sub != session_sub:
        raise ResumptionAuthorizationError(
            f"session bound to sub={session_sub!r}, "
            f"resumption token sub={resumption_ctx.sub!r}"
        )
    # Invariant 2: same grant lineage; a re-initialize under a new grant
    # must mint a new session, not reuse this one.
    if resumption_ctx.grant_id != session_grant_id:
        raise ResumptionAuthorizationError(
            f"session grant_id={session_grant_id!r} does not match "
            f"resumption grant_id={resumption_ctx.grant_id!r}; "
            f"re-initialize required"
        )

    start = 0 if last_event_id is None else None
    replay: list[BufferedEvent] = []
    for ev in buffer:
        if last_event_id is not None and ev.event_id <= last_event_id:
            continue
        # Invariant 3: resumption context must cover every emission context
        # in the replay range. A narrower token must not replay broader events.
        if not resumption_ctx.covers(ev.emission_ctx):
            raise ResumptionAuthorizationError(
                f"event {ev.event_id} emitted under scopes "
                f"{sorted(ev.emission_ctx.scopes)} not covered by "
                f"resumption scopes {sorted(resumption_ctx.scopes)}"
            )
        replay.append(ev)

    if start is not None and not replay:
        # No cursor and empty buffer: nothing to replay, caller proceeds.
        return replay
    return replay


def handle_get_resume(
    session_sub: str,
    session_grant_id: str,
    resumption_ctx: AuthContext,
    buffer: list[BufferedEvent],
    last_event_id: Optional[int],
) -> list[BufferedEvent]:
    try:
        return authorize_resumption(
            session_sub, session_grant_id, resumption_ctx, buffer, last_event_id
        )
    except ResumptionAuthorizationError:
        # Do NOT fall back to "replay anyway" or "replay with redaction."
        # A failed coverage check means the buffer may contain payloads the
        # resumption principal is not entitled to; force re-initialize.
        raise
