# 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-stream-s-last-event-id-as-a-hint-rather-than-a-contract-and-rebind-the-entire-sessio.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-resumable-sse-stream-s-last-event-id-as-a-hint-rather-than-a-contract-and-rebind-the-entire-sessio.warrant.json
# Markdown SHA-256:   03f6b444d3b98c0fa5f935e43849475c58c0d48de11e64589c525ed53dfb7021
# Code AST SHA-256:   36cb484fc08abb1a85450d3ad8dcdf92f735aa740d0c72efc637d87895a74c84
# Verified Classes:   ResumptionNamespaceError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ResumptionNamespaceError(RuntimeError):
    """Raised when a replayed SSE event cannot be proven to belong to the
    client's current MCP session. Signals that Last-Event-ID has degraded
    from a resumption contract into a stale pointer into a reused namespace,
    and the caller must rebind the session rather than continue the stream."""


def resume_stream(
    client_session_id: str,
    last_event_id: int,
    replay: list[dict],
    open_request_ids: set[str],
) -> list[dict]:
    """Validate an MCP SSE replay before the client consumes it.

    Returns the subset of events that are safe to process. Raises
    ResumptionNamespaceError if the replay cannot be proven to belong to
    `client_session_id` — in which case the caller must discard the replay,
    open a fresh session, and re-issue any in-flight tool calls with
    idempotency keys.
    """
    if not client_session_id:
        raise ResumptionNamespaceError(
            "reconnect carried no session token; Last-Event-ID is unverifiable"
        )

    if not replay:
        # Empty replay is ambiguous: either nothing happened, or the buffer
        # was freed. Treat as unverifiable rather than as 'no news'.
        raise ResumptionNamespaceError(
            f"empty replay for Last-Event-ID={last_event_id}; "
            "cannot distinguish quiet stream from freed buffer"
        )

    # Every replayed event must carry the session it belongs to. A server
    # that does not tag events forces us into the rebind branch.
    for ev in replay:
        ev_session = ev.get("session_id")
        if ev_session is None:
            raise ResumptionNamespaceError(
                f"event {ev.get('id')} has no session tag; "
                "server does not scope event IDs per session"
            )
        if ev_session != client_session_id:
            raise ResumptionNamespaceError(
                f"event {ev.get('id')} belongs to session {ev_session!r}, "
                f"not {client_session_id!r}; replay buffer was reused"
            )

    # A foreign request_id inside a same-session replay means the buffer was
    # recycled mid-stream even though the session tag matched — still unsafe.
    for ev in replay:
        rid = ev.get("request_id")
        if rid is not None and rid not in open_request_ids:
            raise ResumptionNamespaceError(
                f"event {ev.get('id')} references unknown request {rid!r}; "
                "session state diverged from client ledger"
            )

    return replay
