# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-session-resumption-as-a-distinct-authorization-event-rather-than-a-transport-retry.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-session-resumption-as-a-distinct-authorization-event-rather-than-a-transport-retry.warrant.json
# Markdown SHA-256:   56b48e758557a0f015e1e0d16ee9e8fd3af80f09e43d07f7d53b500ea683417c
# Code AST SHA-256:   fe8597a9f2659a0ac3e3f80cb0413b7a8212dee64d19b086cb7b4531883ac5bf
# Verified Classes:   SessionResumptionAuthError, TokenContext, Session
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SessionResumptionAuthError(RuntimeError):
    """Raised when a Streamable HTTP session resumption crosses an authorization boundary."""
    pass


@dataclass
class TokenContext:
    subject: str
    scopes: frozenset
    expires_at: float


@dataclass
class Session:
    session_id: str
    created_by: str                 # subject recorded at initialize
    granted_scopes: frozenset       # scopes present at creation
    buffer: list = field(default_factory=list)  # events, no per-event provenance
    terminated: bool = False


def validate_resource_token(raw_token: str) -> TokenContext:
    # OAuth 2.1 resource-server validation (signature, aud, exp) — simplified.
    # Returns the token context; raises on invalid token.
    ...


def resume_session(
    session: Session,
    raw_token: str,
    last_event_id: Optional[int],
    now: float,
) -> list:
    """
    Handle a GET resumption. The invariant: never replay buffered events to a
    token context that is not provably equivalent to the session creator's.
    """
    if session.terminated:
        raise SessionResumptionAuthError(
            f"session {session.session_id} already terminated; re-initialize required"
        )

    try:
        ctx = validate_resource_token(raw_token)
    except Exception as exc:
        raise SessionResumptionAuthError(
            f"token validation failed on resumption of {session.session_id}: {exc}"
        ) from exc

    if ctx.expires_at <= now:
        raise SessionResumptionAuthError(
            f"token expired at resumption of {session.session_id}"
        )

    # The boundary: session id is a handle, not a credential.
    if ctx.subject != session.created_by:
        session.terminated = True
        raise SessionResumptionAuthError(
            f"subject mismatch on resumption of {session.session_id}: "
            f"created_by={session.created_by!r} token_sub={ctx.subject!r}; "
            f"refusing to replay {len(session.buffer)} buffered events"
        )

    # Same subject, but narrowed scope: buffer has no per-event provenance,
    # so we cannot filter. If any event required a scope now absent, we cannot
    # prove safety and must not replay.
    missing = session.granted_scopes - ctx.scopes
    if missing:
        session.terminated = True
        raise SessionResumptionAuthError(
            f"scope regression on resumption of {session.session_id}: "
            f"missing={sorted(missing)}; buffer lacks per-event provenance, "
            f"replay unsafe"
        )

    if last_event_id is None:
        return list(session.buffer)
    return [e for e in session.buffer if e.get("id", -1) > last_event_id]
