# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-resumable-sse-stream-across-an-mcp-http-native-session-handoff-when-the-oauth-2-1-resource-server-binding-rotates-m.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-resumable-sse-stream-across-an-mcp-http-native-session-handoff-when-the-oauth-2-1-resource-server-binding-rotates-m.warrant.json
# Markdown SHA-256:   5c1f0f070456812991911876d897a827be1d71538423baf483d39ec3cfc3f7b8
# Code AST SHA-256:   6d103d2e79700ae72c54aa198e6f5f5ed778d8a8aac04e41774dca69e44eea1f
# Verified Classes:   BindingSkewError, BindingTuple, Session
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class BindingSkewError(RuntimeError):
    """Raised when a session channel presents a resource binding
    inconsistent with the binding epoch recorded at session creation."""


@dataclass(frozen=True)
class BindingTuple:
    issuer: str
    subject: str
    resource: str
    audience: str
    scopes: frozenset

    def relation(self, other: "BindingTuple") -> str:
        if self == other:
            return "equal"
        if (self.issuer, self.subject, self.resource) != (
            other.issuer, other.subject, other.resource
        ):
            return "disjoint"
        if other.scopes < self.scopes:
            return "narrowing"
        return "widened"


@dataclass
class Session:
    session_id: str
    epoch: int
    binding: BindingTuple
    event_epochs: dict  # event_id -> epoch


def admit_request(session: Session, presented: BindingTuple) -> str:
    rel = session.binding.relation(presented)
    if rel == "equal":
        return "proceed"
    if rel == "narrowing":
        # POST may proceed under narrower scope, but the SSE stream
        # must be re-established and the epoch bumped before any
        # post-narrowing event is delivered.
        session.epoch += 1
        session.binding = presented
        return "reopen_stream"
    # disjoint or widened: binding changed, session is not migratable
    raise BindingSkewError(
        f"session {session.session_id} binding changed "
        f"({session.binding!r} -> {presented!r}); "
        f"re-initialize required, Last-Event-ID cursor invalid across epochs"
    )


def resume_stream(session: Session, last_event_id: str, presented: BindingTuple) -> str:
    cursor_epoch = session.event_epochs.get(last_event_id)
    if cursor_epoch is None:
        raise BindingSkewError(
            f"unknown Last-Event-ID {last_event_id} for session {session.session_id}"
        )
    if cursor_epoch != session.epoch:
        raise BindingSkewError(
            f"resume across binding epoch boundary: cursor epoch {cursor_epoch}, "
            f"current epoch {session.epoch}; replay would diverge from live stream"
        )
    if session.binding.relation(presented) != "equal":
        raise BindingSkewError(
            f"resume channel binding {presented!r} does not match "
            f"session binding {session.binding!r}"
        )
    return f"replay_from:{last_event_id}"
