# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-of-the-mcp-http-native-transport-enforce-authorization-scope-re-evaluation-across-a-resumable-sse-reconnect-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-of-the-mcp-http-native-transport-enforce-authorization-scope-re-evaluation-across-a-resumable-sse-reconnect-boundary.warrant.json
# Markdown SHA-256:   f83b19c5df2c2e852f7f8f52a1a12930665bb8b7c0714ae04f46f3c1195945c7
# Code AST SHA-256:   2cdcc9a3a1d622d07e6a0c7d55f99952a6e103806c6db256be0af901a85be934
# Verified Classes:   ResumptionScopeError, AuthContext, BufferedEvent, SessionBuffer
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class ResumptionScopeError(RuntimeError):
    """Raised when a resumed SSE stream would deliver events outside the
    resuming connection's current authorization scope."""
    pass


@dataclass(frozen=True)
class AuthContext:
    principal: str
    scopes: frozenset[str]


@dataclass(frozen=True)
class BufferedEvent:
    event_id: int
    payload: dict
    provenance: AuthContext  # scope set valid when this event was produced


@dataclass
class SessionBuffer:
    session_id: str
    events: list[BufferedEvent] = field(default_factory=list)

    def append(self, event: BufferedEvent) -> None:
        self.events.append(event)


def resume_stream(
    buffer: SessionBuffer,
    last_event_id: int,
    connection: AuthContext,
    *,
    strict: bool = True,
) -> Iterable[BufferedEvent]:
    """Drain buffered events after last_event_id, enforcing the invariant that
    each delivered event is covered by BOTH its recorded provenance and the
    resuming connection's current scope set.

    strict=True: raise on any event the connection is not entitled to (fail
    closed, surfaces the boundary crossing). strict=False: drop silently and
    emit a gap marker (production default for availability).
    """
    if connection.principal is None or not connection.scopes:
        raise ResumptionScopeError(
            f"resume denied: connection for session {buffer.session_id!r} "
            f"has no usable principal/scopes"
        )

    for event in buffer.events:
        if event.event_id <= last_event_id:
            continue

        # The invariant: entitlement is the intersection of provenance and
        # current credentials. Session identity alone is never sufficient.
        entitled = (
            event.provenance.principal == connection.principal
            and event.provenance.scopes <= connection.scopes
        )

        if not entitled:
            if strict:
                raise ResumptionScopeError(
                    f"event {event.event_id} on session {buffer.session_id!r} "
                    f"was authorized under principal={event.provenance.principal!r} "
                    f"scopes={sorted(event.provenance.scopes)} but resuming "
                    f"connection has principal={connection.principal!r} "
                    f"scopes={sorted(connection.scopes)}"
                )
            # Drop, do not replay. A gap marker preserves stream ordering
            # without leaking the payload.
            yield BufferedEvent(
                event_id=event.event_id,
                payload={"type": "gap", "reason": "scope_revoked"},
                provenance=connection,
            )
            continue

        yield event


def resume_or_fail(buffer: SessionBuffer, last_event_id: int,
                   connection: AuthContext) -> list[BufferedEvent]:
    """Strict wrapper used by the resume router in test/CI configurations."""
    out = list(resume_stream(buffer, last_event_id, connection, strict=True))
    if not out:
        raise ResumptionScopeError(
            f"resume for session {buffer.session_id!r} produced no deliverable "
            f"events after id {last_event_id}"
        )
    return out
