# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-authenticate-mid-stream-oauth-2-1-resource-indicator-binding-loss-across-mcp-streamable-http-resumption-and-sse-fallback-repl.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-authenticate-mid-stream-oauth-2-1-resource-indicator-binding-loss-across-mcp-streamable-http-resumption-and-sse-fallback-repl.warrant.json
# Markdown SHA-256:   728e03ed7e1f4407211f973969990008409964bc3b80381001685b37b01d7051
# Code AST SHA-256:   6f8d29637da29214df5966eb700b39c979d14fc111a6727a5c67f98170fb6e9c
# Verified Classes:   ResourceIndicatorMismatch, BufferedFrame, ResumedCredential
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class ResourceIndicatorMismatch(RuntimeError):
    """Raised when a replayed frame's originating tool resource is not in the resuming token's audience."""


@dataclass(frozen=True)
class BufferedFrame:
    event_id: str
    originating_tool_resource: str | None  # None => unattributable, must fail closed
    payload: dict


@dataclass(frozen=True)
class ResumedCredential:
    subject: str
    audience: frozenset[str]  # resource indicators from the token's `aud` claim


def resume_stream(
    session_id: str,
    last_event_id: str,
    credential: ResumedCredential,
    buffered: Iterable[BufferedFrame],
) -> list[BufferedFrame]:
    """Replay buffered frames only if the resuming credential is audience-valid for each frame's tool."""
    if not session_id:
        raise ResourceIndicatorMismatch("resumption requires Mcp-Session-Id")

    to_replay: list[BufferedFrame] = []
    for frame in buffered:
        if frame.event_id <= last_event_id:
            continue
        if frame.originating_tool_resource is None:
            # Fail closed: cannot attribute the frame to a resource, so we cannot authorize it.
            raise ResourceIndicatorMismatch(
                f"frame {frame.event_id} has no originating tool resource; refusing replay"
            )
        if frame.originating_tool_resource not in credential.audience:
            # Do not silently drop: surface a step-up so the client can re-acquire the right token.
            raise ResourceIndicatorMismatch(
                f"frame {frame.event_id} requires resource "
                f"{frame.originating_tool_resource!r}, credential audience is "
                f"{sorted(credential.audience)!r}; step-up re-auth required"
            )
        to_replay.append(frame)

    return to_replay


if __name__ == "__main__":
    cred = ResumedCredential(subject="agent-7", audience=frozenset({"https://mcp.example.com/tools"}))
    frames = [
        BufferedFrame("evt-112", "https://mcp.example.com/tools/analytics", {"result": "..."}),
    ]
    try:
        resume_stream("s-7f3a", "evt-111", cred, frames)
    except ResourceIndicatorMismatch as exc:
        print(f"resumption blocked: {exc}")
