# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-session-is-resumable-but-unauthorized-after-oauth-2-1-token-rotation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-mcp-session-is-resumable-but-unauthorized-after-oauth-2-1-token-rotation.warrant.json
# Markdown SHA-256:   d59ab869d2cabfe861fd5a22fc86c9ec645ddd5a65662786385ca031286b615f
# Code AST SHA-256:   ad4fc8086ac55ad5084a55f19a16977fba0097f912ded34580222324d0386ef4
# Verified Classes:   ResumeAuthContextMismatch, EventLogDestroyedOnAuthFailure, AuthContext, SessionRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ResumeAuthContextMismatch(RuntimeError):
    """Raised when a resume request's token context does not match the session's recorded context."""
    pass


class EventLogDestroyedOnAuthFailure(RuntimeError):
    """Raised when auth failure cleanup destroys a resumable event log."""
    pass


@dataclass(frozen=True)
class AuthContext:
    jti: str
    aud: str
    scope_set: frozenset[str]
    iss: str

    def fingerprint(self) -> str:
        raw = f"{self.iss}|{self.aud}|{','.join(sorted(self.scope_set))}"
        return hashlib.sha256(raw.encode()).hexdigest()


@dataclass
class SessionRecord:
    session_id: str
    created_context: AuthContext
    event_log: list[dict]
    log_grace_until: Optional[float] = None


def resume_session(
    session: SessionRecord,
    presented: AuthContext,
    last_event_id: int,
    now: float,
    grace_seconds: float = 300.0,
) -> list[dict]:
    # Invariant: the event log must never be destroyed by an auth decision.
    if not session.event_log and session.created_context is not None:
        raise EventLogDestroyedOnAuthFailure(
            f"session {session.session_id} has no event log but was resumable"
        )

    context_matches = (
        presented.aud == session.created_context.aud
        and presented.scope_set == session.created_context.scope_set
        and presented.iss == session.created_context.iss
    )

    if context_matches:
        return [e for e in session.event_log if e["id"] > last_event_id]

    # Authorization context changed (rotation, re-scope, audience migration).
    # Do NOT replay. Do NOT destroy the log. Direct the client to re-handshake.
    if session.log_grace_until is None:
        session.log_grace_until = now + grace_seconds

    if now > session.log_grace_until:
        # Grace window elapsed; log may now be reclaimed, but the failure is
        # explicitly surfaced rather than masked as a 401.
        raise ResumeAuthContextMismatch(
            f"session {session.session_id} auth context changed "
            f"(created={session.created_context.fingerprint()}, "
            f"presented={presented.fingerprint()}); grace window expired"
        )

    raise ResumeAuthContextMismatch(
        f"session {session.session_id} auth context changed "
        f"(created={session.created_context.fingerprint()}, "
        f"presented={presented.fingerprint()}); re-handshake required, "
        f"log retained until {session.log_grace_until}"
    )
