# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-mcp-stream-continuity-when-a-resumable-session-handshake-renegotiates-mid-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-mcp-stream-continuity-when-a-resumable-session-handshake-renegotiates-mid-stream.warrant.json
# Markdown SHA-256:   bc4606e9f2bb343f251c9b7e2c3e2f7c650f0f31bdadeb40df9570d42d1792c9
# Code AST SHA-256:   3b5f4f059181a1df1e901806e4f3e51ec4f9e4689eb3c2358c125e9e67229d70
# Verified Classes:   StreamEpochMismatch
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class StreamEpochMismatch(RuntimeError):
    """Raised when a resumable MCP stream resume cannot prove event-id continuity."""
    pass


def resume_stream(session_id: str, last_event_id: int, server_emitter) -> "Stream":
    """
    Enforce the resumability invariant: a resume is only valid if the server's
    current emitter epoch matches the epoch that produced last_event_id, and the
    emitter can replay every event id in (last_event_id, head].
    """
    session = server_emitter.lookup_session(session_id)
    if session is None:
        raise StreamEpochMismatch(
            f"session {session_id} unknown; client must re-initialize"
        )

    current_epoch = server_emitter.current_epoch(session_id)
    if current_epoch != session.last_epoch_for(last_event_id):
        # Emitter rotated (deploy/restart/shard move) under a live session.
        # Do NOT resume into the new epoch; force a clean re-initialization.
        raise StreamEpochMismatch(
            f"epoch mismatch for session {session_id}: "
            f"last_event_id {last_event_id} belongs to epoch "
            f"{session.last_epoch_for(last_event_id)}, current emitter is "
            f"epoch {current_epoch}. Refusing silent resume."
        )

    gap = server_emitter.events_after(session_id, last_event_id)
    if gap is None:
        raise StreamEpochMismatch(
            f"emitter cannot replay events > {last_event_id} for session "
            f"{session_id}; buffer evicted. Client must re-initialize."
        )

    return Stream(session_id=session_id, epoch=current_epoch, replay=gap)


def client_consume(stream: "Stream", last_event_id: int):
    """
    Client-side guard: a resumed stream must be provably monotonic within the
    negotiated epoch. Any out-of-epoch or non-monotonic id aborts the session
    instead of being silently deduped.
    """
    expected_epoch = stream.epoch
    for frame in stream:
        if frame.epoch != expected_epoch:
            raise StreamEpochMismatch(
                f"frame epoch {frame.epoch} != negotiated epoch "
                f"{expected_epoch}; aborting to avoid silent reasoning "
                f"divergence on session {stream.session_id}"
            )
        if frame.id <= last_event_id:
            raise StreamEpochMismatch(
                f"non-monotonic event id {frame.id} after resume from "
                f"{last_event_id}; server violated replay contract"
            )
        last_event_id = frame.id
        yield frame
