# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-an-mcp-streamable-session-resumption-after-a-202-accepted-and-why-the-sse-upgrade-negotiation-s-last-event-id-cursor-is-n.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-an-mcp-streamable-session-resumption-after-a-202-accepted-and-why-the-sse-upgrade-negotiation-s-last-event-id-cursor-is-n.warrant.json
# Markdown SHA-256:   b6d4a499900e655f7b4eb6eb6977c6c46bcba0b3a817b7841c7d065d8750df1e
# Code AST SHA-256:   0f69cdafe606d0d402bc6cc88b34fe76dd17b928f2f4be0ab986ba98cecdb63d
# Verified Classes:   UnsafeResumptionError, ResumeContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UnsafeResumptionError(RuntimeError):
    """Raised when a streamable-session resume cannot be proven safe.

    The client holds a Last-Event-ID cursor but cannot establish that its
    committed agent state is a prefix of the server's replayable history.
    Proceeding would produce a silent replay gap.
    """


@dataclass
class ResumeContext:
    commit_cursor: int          # highest event ID durably committed to agent state
    last_received: int          # highest event ID the reader thread saw before drop
    server_replay_floor: Optional[int]  # lowest event ID server can still replay; None = unknown


def decide_resumption(ctx: ResumeContext) -> int:
    """Return the Last-Event-ID to send, or raise if resumption is unsafe.

    Invariant: resume is safe iff
        commit_cursor >= last_received_before_disconnect
        AND server_replay_floor <= commit_cursor
    """
    if ctx.server_replay_floor is None:
        raise UnsafeResumptionError(
            "server did not advertise replay floor; cannot prove commit_cursor "
            "is within replayable history. Refuse cursor-based resume and "
            "re-derive state instead."
        )

    if ctx.server_replay_floor > ctx.commit_cursor:
        raise UnsafeResumptionError(
            f"server replay floor {ctx.server_replay_floor} exceeds commit cursor "
            f"{ctx.commit_cursor}: events {ctx.commit_cursor + 1}.."
            f"{ctx.server_replay_floor - 1} are unrecoverable. "
            "Refuse resume; re-issue tool call / sampling request."
        )

    # Safe to resume. Send the COMMIT cursor, not the reader cursor, so that
    # any reader-ahead-of-committer lag is replayed and deduplicated at commit.
    return ctx.commit_cursor


def resume_stream(session_id: str, ctx: ResumeContext) -> str:
    try:
        cursor = decide_resumption(ctx)
    except UnsafeResumptionError:
        # Escalate to full re-derivation; do NOT fall back to last_received.
        raise
    return f"GET /mcp/session/{session_id} Last-Event-ID: {cursor}"
