# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-negotiate-mcp-session-identity-after-an-sse-to-streamable-http-resume-and-why-oauth-2-1-resource-indicator-scoping-silently-i.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-negotiate-mcp-session-identity-after-an-sse-to-streamable-http-resume-and-why-oauth-2-1-resource-indicator-scoping-silently-i.warrant.json
# Markdown SHA-256:   2193310b39f8ae5a01296d4d3c4807694c479407ee5e7864191f930b02503799
# Code AST SHA-256:   cb9dc616e78eb12c97e84c7ce3b3217f073b493b382da9cb581421529e0168a8
# Verified Classes:   ResourceScopeResumeError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ResourceScopeResumeError(RuntimeError):
    """Raised when a resumed MCP stream's authorization scope no longer
    matches the scope under which the session's event log was created."""


def resume_stream(
    session_id: str,
    last_event_id: int,
    token_resource: str,
    session_bound_resource: str,
    replay_events: list[dict],
) -> list[dict]:
    # Invariant: resource-indicator equality must be checked BEFORE any
    # replayed event is emitted. A 401 delivered mid-replay is corruption.
    if token_resource != session_bound_resource:
        raise ResourceScopeResumeError(
            f"session {session_id!r} bound to resource {session_bound_resource!r} "
            f"but resume token carries resource {token_resource!r}; "
            f"discarding {len(replay_events)} provisional events and "
            f"abandoning session (do not retry with same Mcp-Session-Id)"
        )

    # Only after the scope gate passes may replayed events be considered.
    committed = []
    for ev in replay_events:
        if ev.get("id", 0) <= last_event_id:
            continue
        if ev.get("type") == "error" and ev.get("code") == "invalid_token":
            # Defensive: a mid-stream auth error after the gate is still poison.
            raise ResourceScopeResumeError(
                f"mid-stream invalid_token at event {ev.get('id')} after scope gate; "
                f"replay is poisoned, rollback to checkpoint before {last_event_id}"
            )
        committed.append(ev)
    return committed
