# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-sse-resumption-as-a-session-scoped-contract-rather-than-a-transport-level-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-streamable-http-sse-resumption-as-a-session-scoped-contract-rather-than-a-transport-level-replay.warrant.json
# Markdown SHA-256:   00303eb4bfda00fd448ba483e418375ff735139c348a53918864cc046dbabf41
# Code AST SHA-256:   d53b1e01f9d30351e028505a879840dd79559e3cca07c0c3bed01f3fa23a1fdf
# Verified Classes:   McpResumptionError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class McpResumptionError(RuntimeError):
    """Raised when an SSE resumption attempt cannot be honored as a true replay.

    Distinguishes transport-level reconnect success from session-scoped
    resumption validity. Callers must reconcile in-flight requests rather
    than retry the stream.
    """


def resume_stream(
    session_id: str | None,
    last_event_id: str | None,
    server_session_store: dict[str, dict],
    replay_buffer: dict[str, list[str]],
) -> list[str]:
    """Return the events to replay, or raise if resumption is not valid.

    A valid resumption requires: a known session, and an event id that
    resolves within that session's replay buffer.
    """
    if session_id is None:
        raise McpResumptionError(
            "cannot resume: no Mcp-Session-Id presented; "
            "Last-Event-ID is meaningless without its minting session"
        )

    if session_id not in server_session_store:
        # Server-side equivalent of a client seeing 404 on the stream.
        # Do NOT mint a fresh session and silently drop the gap.
        raise McpResumptionError(
            f"cannot resume: session {session_id!r} unknown or expired; "
            "client must re-initialize and reconcile in-flight requests"
        )

    buffer = replay_buffer.get(session_id, [])
    if last_event_id is None:
        # Fresh stream on a live session: no replay, no gap.
        return []

    try:
        idx = buffer.index(last_event_id)
    except ValueError:
        raise McpResumptionError(
            f"cannot resume: event id {last_event_id!r} not resolvable "
            f"within session {session_id!r} (buffer evicted or foreign); "
            "gap is unrecoverable from the stream"
        ) from None

    # Replay everything strictly after the last-seen event.
    return buffer[idx + 1 :]


def handle_reconnect(
    session_id: str | None,
    last_event_id: str | None,
    store: dict[str, dict],
    buffer: dict[str, list[str]],
    idempotency_lookup,
) -> dict:
    """Full reconnect path: resume if valid, else reconcile."""
    try:
        missed = resume_stream(session_id, last_event_id, store, buffer)
        return {"mode": "resumed", "replayed": missed}
    except McpResumptionError as exc:
        # Resumption is invalid. Reconcile every outstanding request by
        # idempotency key; never blindly re-issue a non-idempotent tool.
        outstanding = store.get(session_id or "", {}).get("inflight", [])
        reconciled = {req_id: idempotency_lookup(req_id) for req_id in outstanding}
        return {
            "mode": "reconciled",
            "reason": str(exc),
            "inflight": reconciled,
        }
