# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-oauth-bound-mcp-session-continuity-when-an-sse-stream-is-resumed-over-streamable-http-after-a-token-refresh.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-oauth-bound-mcp-session-continuity-when-an-sse-stream-is-resumed-over-streamable-http-after-a-token-refresh.warrant.json
# Markdown SHA-256:   6360600e6bba98d5475f9dd7ccd37497debd216aa7f968bde2833c11049e5896
# Code AST SHA-256:   1bd006bf5522ba83bef6591246de6720d3bfd9bc67ac6865a6ddf3e4b190b3d7
# Verified Classes:   SessionPrincipalMismatch, Token, ResumeRequest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class SessionPrincipalMismatch(RuntimeError):
    """Raised when an SSE->streamable-HTTP resume crosses a principal boundary."""
    pass


@dataclass(frozen=True)
class Token:
    sub: str
    aud: str
    session_id: str
    jti: str
    exp: float


@dataclass(frozen=True)
class ResumeRequest:
    mcp_session_id: str
    last_event_id: int
    token: Token


def validate_resume(req: ResumeRequest, event_log_principal: dict[int, str], now: float | None = None) -> None:
    """
    Gate a streamable-HTTP resume. Raises SessionPrincipalMismatch if the
    transport session identity and the OAuth 2.1 token's session binding
    diverge, or if the event log after the cursor was authored under a
    different principal than the presented token.
    """
    now = time.time() if now is None else now

    if req.token.exp <= now:
        raise SessionPrincipalMismatch(
            f"token {req.token.jti} expired at {req.token.exp}, now={now}"
        )

    # Invariant 1: transport session id must equal the token's session claim.
    if req.token.session_id != req.mcp_session_id:
        raise SessionPrincipalMismatch(
            f"session splice: header Mcp-Session-Id={req.mcp_session_id!r} "
            f"!= token.session_id={req.token.session_id!r} (sub={req.token.sub!r})"
        )

    # Invariant 2: every event after the cursor must share the token's principal.
    for eid, principal in event_log_principal.items():
        if eid > req.last_event_id and principal != req.token.sub:
            raise SessionPrincipalMismatch(
                f"event {eid} authored under principal {principal!r} "
                f"but resume presents {req.token.sub!r}; cursor is untrusted"
            )


def resume_stream(req: ResumeRequest, event_log_principal: dict[int, str]) -> list[int]:
    validate_resume(req, event_log_principal)
    return sorted(eid for eid in event_log_principal if eid > req.last_event_id)


if __name__ == "__main__":
    log = {4470: "agent-A", 4471: "agent-A", 4472: "agent-B"}
    stale = Token(sub="agent-A", aud="mcp", session_id="sess_A", jti="j1", exp=time.time() + 60)
    refreshed = Token(sub="agent-A", aud="mcp", session_id="sess_B", jti="j2", exp=time.time() + 3600)

    # Same principal, rotated session claim -> must not silently resume.
    try:
        resume_stream(ResumeRequest("sess_A", 4471, refreshed), log)
    except SessionPrincipalMismatch as e:
        print("rejected (session rotation):", e)

    # Consistent session, but event log crossed a principal -> cursor untrusted.
    try:
        resume_stream(ResumeRequest("sess_A", 4471, stale), log)
    except SessionPrincipalMismatch as e:
        print("rejected (principal splice in log):", e)
