# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-sse-stream-across-an-mcp-server-restart-and-the-delegated-oauth-scope-no-longer-matches-the-stream-s-tool-bin.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-sse-stream-across-an-mcp-server-restart-and-the-delegated-oauth-scope-no-longer-matches-the-stream-s-tool-bin.warrant.json
# Markdown SHA-256:   e5bf0de7d9a1f84608956c37805514ab1c497ac0276d59501e898fd968b10830
# Code AST SHA-256:   32f124b55022f949b7ff9eea9454bf639e1351993bd4fb2cbc92e3cf86aa34d2
# Verified Classes:   ResumedStreamAuthMismatch, Grant, StreamEvent
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import dataclasses
from typing import Optional


class ResumedStreamAuthMismatch(RuntimeError):
    """Raised when a resumed SSE stream delivers events minted under an
    authorization epoch that does not match the client's current grant."""
    pass


@dataclasses.dataclass(frozen=True)
class Grant:
    epoch: str          # opaque, rotates on re-issue / revocation
    scopes: frozenset   # e.g. {"tools:read", "tools:write"}


@dataclasses.dataclass(frozen=True)
class StreamEvent:
    last_event_id: int
    auth_epoch: Optional[str]   # None if server does not tag (C2 absent)
    required_scope: str
    payload: dict


def admit_resumed_event(event: StreamEvent, current: Grant,
                        server_tags_epoch: bool) -> dict:
    """Gate the admission of an event received after an SSE resume.

    Enforces C1 (scope check on replay) and C2 (epoch tagging). If the
    server does not tag epochs, the event is unverifiable and must be
    quarantined rather than admitted.
    """
    # C1: the current grant must still authorize the event's scope.
    if event.required_scope not in current.scopes:
        raise ResumedStreamAuthMismatch(
            f"event {event.last_event_id} requires {event.required_scope!r} "
            f"not present in current grant epoch {current.epoch!r}"
        )

    # C2: if the server tags epochs, they must match. If it does not,
    # we cannot prove the event was minted under a live grant.
    if not server_tags_epoch or event.auth_epoch is None:
        raise ResumedStreamAuthMismatch(
            f"event {event.last_event_id} arrived without a verifiable "
            f"auth_epoch; cannot distinguish clean resume from "
            f"authorization laundering — quarantine and re-run"
        )

    if event.auth_epoch != current.epoch:
        raise ResumedStreamAuthMismatch(
            f"event {event.last_event_id} minted under epoch "
            f"{event.auth_epoch!r} but client holds epoch "
            f"{current.epoch!r}; result must not enter episodic memory"
        )

    return event.payload


def resume_stream(events, current: Grant, server_tags_epoch: bool) -> list:
    admitted = []
    for ev in events:
        try:
            admitted.append(admit_resumed_event(ev, current, server_tags_epoch))
        except ResumedStreamAuthMismatch:
            # Do not admit; surface to the orchestrator for re-run under
            # the current grant. Never silently drop — the agent must know
            # its result was quarantined.
            raise
    return admitted
