# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-resumable-sse-last-event-id-as-invalid-when-the-oauth-resource-indicator-that-authorized-the-strea.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-resumable-sse-last-event-id-as-invalid-when-the-oauth-resource-indicator-that-authorized-the-strea.warrant.json
# Markdown SHA-256:   6dae5e2c59e19970e9c24fe18d7724dbf65f0212fc013b3b3165ac781bc834ca
# Code AST SHA-256:   828a378b28a8c449647b9622ae51217b6ada34107d9df74f6dc73fa6d5a81d6a
# Verified Classes:   ResourceIndicatorReplayError, StreamEvent, Session
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ResourceIndicatorReplayError(RuntimeError):
    """Raised when an SSE resumption would replay events across an authorization-scope change."""
    pass


@dataclass
class StreamEvent:
    event_id: int
    resource: str          # canonical URI of the tool resource that produced this event
    payload: dict


@dataclass
class Session:
    session_id: str
    resource_set: frozenset[str]
    events: list[StreamEvent] = field(default_factory=list)


def resume_stream(
    session: Session,
    last_event_id: int,
    token_resource_set: frozenset[str],
) -> list[StreamEvent]:
    # Guard 1: a resource-set change invalidates resumability outright.
    if token_resource_set != session.resource_set:
        raise ResourceIndicatorReplayError(
            f"session {session.session_id} was created under resources "
            f"{sorted(session.resource_set)} but resumption token carries "
            f"{sorted(token_resource_set)}; refusing replay"
        )

    pending = [e for e in session.events if e.event_id > last_event_id]

    # Guard 2: per-event provenance must be a subset of the token's resources.
    for ev in pending:
        if ev.resource not in token_resource_set:
            raise ResourceIndicatorReplayError(
                f"event {ev.event_id} was produced under resource {ev.resource!r}, "
                f"not covered by resumption token resources {sorted(token_resource_set)}"
            )

    return pending


def replay_tail(
    session: Session,
    last_event_id: int,
    token_resource_set: frozenset[str],
) -> list[StreamEvent]:
    if last_event_id >= (max((e.event_id for e in session.events), default=0) + 1):
        raise ResourceIndicatorReplayError(
            f"Last-Event-ID {last_event_id} exceeds session {session.session_id} event horizon"
        )
    return resume_stream(session, last_event_id, token_resource_set)
