# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-authority-when-an-mcp-streamable-http-session-resumes-across-a-re-issued-oauth-2-1-access-token.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-authority-when-an-mcp-streamable-http-session-resumes-across-a-re-issued-oauth-2-1-access-token.warrant.json
# Markdown SHA-256:   69a93f5a86628403b9e9f7d458551688e9b16a94accb6299d9fa54db05fe2d2a
# Code AST SHA-256:   97e320a20d7e0e6ab6e88251bf2ad003ece303ef49acd5d05c92b25c7d5fa92d
# Verified Classes:   BindingDivergenceError, Authority, Session, StreamableHTTPSessionRegistry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class BindingDivergenceError(RuntimeError):
    """Raised when a resumed session's token authority diverges from the
    authority under which the session was established."""
    pass


@dataclass
class Authority:
    aud: str
    scopes: frozenset
    jti: str


@dataclass
class Session:
    sid: str
    bound: Authority
    created_at: float
    buffered_events: list = field(default_factory=list)
    active: bool = True


class StreamableHTTPSessionRegistry:
    def __init__(self, canonical_resource: str):
        self.canonical_resource = canonical_resource
        self._sessions: dict[str, Session] = {}

    def create(self, sid: str, token: Authority) -> Session:
        if token.aud != self.canonical_resource:
            raise BindingDivergenceError(
                f"session {sid} creation rejected: token aud={token.aud!r} "
                f"!= canonical resource {self.canonical_resource!r}"
            )
        s = Session(sid=sid, bound=token, created_at=time.time())
        self._sessions[sid] = s
        return s

    def resume(self, sid: str, presented: Authority, last_event_id: Optional[str]):
        s = self._sessions.get(sid)
        if s is None or not s.active:
            raise BindingDivergenceError(f"session {sid} unknown or terminated")

        if presented.aud != s.bound.aud:
            # aud re-canonicalization is never a continuation event.
            s.active = False
            raise BindingDivergenceError(
                f"session {sid} aud mismatch on resume: "
                f"bound={s.bound.aud!r} presented={presented.aud!r}; "
                f"terminating session, client must re-handshake"
            )

        if presented.scopes == s.bound.scopes:
            return self._replay(s, last_event_id)

        if presented.scopes < s.bound.scopes:
            # Downgrade: update binding, but any buffered result whose
            # originating call required a now-absent scope is stale.
            lost = s.bound.scopes - presented.scopes
            s.bound = presented
            stale = [e for e in s.buffered_events
                     if e.get("required_scope") in lost]
            if stale:
                raise BindingDivergenceError(
                    f"session {sid} downgraded, lost scopes {sorted(lost)}; "
                    f"{len(stale)} buffered events have stale_authority and "
                    f"must be re-issued by the client"
                )
            return self._replay(s, last_event_id)

        # Scope expansion on resume: token was re-scoped upward; this is
        # not a legitimate resume of the same authority lineage.
        raise BindingDivergenceError(
            f"session {sid} scope expansion on resume "
            f"{sorted(s.bound.scopes)} -> {sorted(presented.scopes)}; "
            f"client must re-handshake, not resume"
        )

    def _replay(self, s: Session, last_event_id: Optional[str]):
        if last_event_id is None:
            return []
        return [e for e in s.buffered_events if e.get("id", "") > last_event_id]
