# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-mcp-resumable-session-was-silently-rebound-to-a-different-transport-channel.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-mcp-resumable-session-was-silently-rebound-to-a-different-transport-channel.warrant.json
# Markdown SHA-256:   cf643d3215bbe746e1fa317f6100955dc790279eb1782a5552c40f7d834777f7
# Code AST SHA-256:   18817e7773345604a13ef9100fcae13b1cf7bd63028730e11791b728f6bb5f69
# Verified Classes:   ChannelRebindError, ChannelFence
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ChannelRebindError(RuntimeError):
    """Raised when a resumed MCP session's event stream cannot be proven
    to belong to the channel that issued the resumption cursor."""


@dataclass
class ChannelFence:
    session_id: str
    fence_token: str          # minted by server at stream open, rotates on rebind
    last_event_id: Optional[str] = None
    observed_ids: list = field(default_factory=list)


def _fence_for(session_id: str, connection_nonce: str) -> str:
    return hashlib.sha256(f"{session_id}:{connection_nonce}".encode()).hexdigest()[:16]


def resume_stream(
    session_id: str,
    presented_last_event_id: str,
    presented_fence: str,
    server_current_fence: str,
    outstanding_request_ids: set,
    incoming_events: list,
) -> list:
    """Validate a resumption before any event reaches the model context.

    Returns the list of events safe to ingest. Raises ChannelRebindError
    if the session has been rebound to a foreign channel or if events
    cannot be correlated to requests this instance actually issued.
    """
    # 1. Fencing check: the cursor must have been issued under the fence
    #    the server is currently serving this session on.
    if presented_fence != server_current_fence:
        raise ChannelRebindError(
            f"session {session_id}: cursor {presented_last_event_id!r} was issued "
            f"under fence {presented_fence!r} but server now serves "
            f"{server_current_fence!r}; session rebound, resume invalid"
        )

    # 2. Correlation check: every tool-result event must reference a request
    #    this instance holds an outstanding promise for.
    safe = []
    for ev in incoming_events:
        req_id = ev.get("request_id")
        if req_id is not None and req_id not in outstanding_request_ids:
            raise ChannelRebindError(
                f"session {session_id}: event {ev.get('id')!r} references "
                f"unknown request {req_id!r}; foreign event on shared session"
            )
        safe.append(ev)

    # 3. Contiguity check: event IDs are opaque; require explicit tracking.
    #    A gap here means lost events and demands replay, not silent resume.
    if safe and presented_last_event_id is not None:
        first = safe[0].get("id")
        if first is not None and first == presented_last_event_id:
            raise ChannelRebindError(
                f"session {session_id}: first resumed event {first!r} equals "
                f"cursor; server replayed already-consumed event"
            )

    return safe
