# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-resumable-sse-as-a-replay-unsafe-channel-after-a-session-id-renegotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-resumable-sse-as-a-replay-unsafe-channel-after-a-session-id-renegotiation.warrant.json
# Markdown SHA-256:   340932d94721ff133dc0206c5fd24d49c019e9b3d0a9725889607df9cb860518
# Code AST SHA-256:   3a868e33baac70aebb0e366eeee20fcd3f8b48263a11d846ad81c0717535578d
# Verified Classes:   ResumeAcrossSessionError, StreamCursor, SessionState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field


class ResumeAcrossSessionError(RuntimeError):
    """Raised when a resumable SSE cursor is replayed against a renegotiated session."""


@dataclass
class StreamCursor:
    session_id: str
    last_event_id: str | None
    epoch: str | None  # session epoch embedded in event IDs, if server supports it


@dataclass
class SessionState:
    session_id: str
    epoch: str
    executed_tool_calls: set[str] = field(default_factory=set)


def resume_stream(
    cursor: StreamCursor,
    current: SessionState,
    pending_tool_call_id: str,
) -> StreamCursor:
    """
    Decide whether a held cursor may be resumed against the current session.

    Invariant: an SSE event ID is only valid within the session that issued it.
    A resume across a session-ID change is a replay of unrelated state, not a
    continuation, and must be rejected unless the server epoch proves coherence.
    """
    if cursor.session_id == current.session_id:
        # Same session: resume is coherent.
        return StreamCursor(
            session_id=current.session_id,
            last_event_id=cursor.last_event_id,
            epoch=current.epoch,
        )

    # Session changed. The only safe resume is one whose epoch matches AND whose
    # pending tool call has not already executed (idempotency check).
    epoch_matches = cursor.epoch is not None and cursor.epoch == current.epoch
    already_executed = pending_tool_call_id in current.executed_tool_calls

    if not epoch_matches or already_executed:
        raise ResumeAcrossSessionError(
            f"Refusing to resume cursor from session {cursor.session_id!r} "
            f"(event {cursor.last_event_id!r}, epoch {cursor.epoch!r}) against "
            f"session {current.session_id!r} (epoch {current.epoch!r}); "
            f"pending tool call {pending_tool_call_id!r} executed="
            f"{already_executed}. Restart from semantic checkpoint instead."
        )

    # Epoch-coherent, not-yet-executed: safe to continue under new session.
    return StreamCursor(
        session_id=current.session_id,
        last_event_id=None,  # drop stale ID; server resumes by tool-call id
        epoch=current.epoch,
    )
