# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-an-mcp-session-has-silently-re-bound-to-a-different-oauth-2-1-principal-across-an-sse-to-streamable-http-resumption.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-an-mcp-session-has-silently-re-bound-to-a-different-oauth-2-1-principal-across-an-sse-to-streamable-http-resumption.warrant.json
# Markdown SHA-256:   eed285caa73c3a326d94d80e54faa29450094a834770930d52a698f3c46e40ad
# Code AST SHA-256:   78a147c63316da0366d5677d2891486acc8eaa673b6a36540ad25d861f234b90
# Verified Classes:   SessionProvenanceViolation, SessionProvenance
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class SessionProvenanceViolation(RuntimeError):
    """Raised when a resumed MCP session's token does not dominate the
    provenance of the events it is about to replay."""


@dataclass(frozen=True)
class SessionProvenance:
    session_id: str
    resource_claim: str
    sub: str
    issuer: str


def assert_resumption_safe(
    established: SessionProvenance,
    resuming_token: dict,
    accepted_resources: frozenset[str],
) -> None:
    resource = resuming_token.get("resource")
    sub = resuming_token.get("sub")
    issuer = resuming_token.get("iss")

    if resource not in accepted_resources:
        raise SessionProvenanceViolation(
            f"resuming token resource {resource!r} not in accepted set"
        )

    if sub != established.sub or issuer != established.issuer:
        # Different principal resuming a live session ID: never safe,
        # regardless of resource. Treat as handle leak / poisoning.
        raise SessionProvenanceViolation(
            f"principal mismatch on resume: established={established.sub}@{established.issuer} "
            f"resuming={sub}@{issuer}"
        )

    if resource != established.resource_claim:
        # Same principal, different resource scope. The replayed backlog
        # was produced under a scope the resuming token does not hold.
        # Must abandon the session ID and re-issue in-flight calls.
        raise SessionProvenanceViolation(
            f"resource-scope drift on resume: established={established.resource_claim!r} "
            f"resuming={resource!r}; replay backlog is untrusted, start fresh session"
        )


def resume_session(
    established: SessionProvenance,
    last_event_id: int,
    resuming_token: dict,
    accepted_resources: frozenset[str],
    replay_buffer: dict[int, bytes],
) -> list[bytes]:
    assert_resumption_safe(established, resuming_token, accepted_resources)
    return [replay_buffer[eid] for eid in sorted(replay_buffer) if eid > last_event_id]
