# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-resumption-gap-when-an-mcp-client-upgrades-from-sse-to-streamable-http-mid-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-resumption-gap-when-an-mcp-client-upgrades-from-sse-to-streamable-http-mid-stream.warrant.json
# Markdown SHA-256:   28000ac70a277304d55e01113804058651b162cfdbdbc23593bb6aff768414d4
# Code AST SHA-256:   d9898eb19796fca2cc96403a94c7355ecf0cb55b21be440ced59a3b4435b44ca
# Verified Classes:   ResumptionGapError, EventRef, ResumptionLog
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ResumptionGapError(RuntimeError):
    """Raised when a transport upgrade cannot prove stream continuity."""


@dataclass(frozen=True)
class EventRef:
    session_id: str
    stream_id: str
    seq: int


class ResumptionLog:
    """Single log shared by SSE and Streamable HTTP handlers."""

    def __init__(self) -> None:
        self._events: dict[tuple[str, str, int], dict] = {}

    def append(self, ref: EventRef, payload: dict) -> None:
        self._events[(ref.session_id, ref.stream_id, ref.seq)] = payload

    def lookup(self, ref: EventRef) -> Optional[dict]:
        return self._events.get((ref.session_id, ref.stream_id, ref.seq))


def resume_stream(
    log: ResumptionLog,
    session_id: str,
    last_event_id: str,
    upgrade_stream_id: str,
) -> list[dict]:
    """Resolve a Last-Event-ID on an SSE->Streamable HTTP upgrade.

    last_event_id MUST be a composite token '<stream_id>:<seq>'. A bare
    integer cannot prove stream identity and is rejected.
    """
    if ":" not in last_event_id:
        raise ResumptionGapError(
            f"bare Last-Event-ID {last_event_id!r} cannot prove stream identity; "
            "refusing to resume across transport upgrade"
        )
    claimed_stream, _, seq_str = last_event_id.partition(":")
    try:
        seq = int(seq_str)
    except ValueError as exc:
        raise ResumptionGapError(f"malformed seq in {last_event_id!r}") from exc

    if claimed_stream != upgrade_stream_id:
        raise ResumptionGapError(
            f"Last-Event-ID stream {claimed_stream!r} does not match "
            f"upgrade stream {upgrade_stream_id!r}; possible cross-stream replay"
        )

    ref = EventRef(session_id=session_id, stream_id=claimed_stream, seq=seq)
    if log.lookup(ref) is None:
        raise ResumptionGapError(
            f"no event {ref} in shared resumption log; "
            "upgrade window events would be silently dropped"
        )

    # Replay strictly after the acknowledged seq.
    out: list[dict] = []
    n = seq + 1
    while True:
        nxt = log.lookup(EventRef(session_id, claimed_stream, n))
        if nxt is None:
            break
        out.append(nxt)
        n += 1
    return out
