# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-in-flight-tool-results-when-an-mcp-streamable-http-session-resumes-across-a-transport-restart.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-in-flight-tool-results-when-an-mcp-streamable-http-session-resumes-across-a-transport-restart.warrant.json
# Markdown SHA-256:   4f5994829668bf7459b6b7696fbe14958e91c806833a78ef9652e574fbbc6b8b
# Code AST SHA-256:   9b74fe82ef8e7c975d1f0a59b7c29583848836b646fe26ba365c261e3fadf1f3
# Verified Classes:   ReplayGapError, ReplayWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ReplayGapError(RuntimeError):
    """Raised when a resumed MCP stream cannot prove delivery contiguity."""
    pass


@dataclass
class ReplayWindow:
    oldest_retained: int  # lowest event id still in the server buffer
    newest_emitted: int   # highest event id produced so far


def resume_session(
    session_id: str,
    last_event_id: int,
    window: ReplayWindow,
    in_flight_requests: dict[str, int],  # request_id -> event_id it was issued at
) -> dict[str, str]:
    """
    Reattach an MCP streamable-HTTP session, or refuse if the client's
    replay cursor has fallen behind the server's retained low-water mark.

    Returns a mapping of request_id -> new status for any in-flight
    requests whose results may have landed in the skipped region.
    """
    if last_event_id < window.oldest_retained - 1:
        # The gap [last_event_id+1 .. oldest_retained-1] is unrecoverable.
        # We must NOT silently reattach; surface the gap explicitly.
        gap_from = last_event_id + 1
        gap_to = window.oldest_retained - 1
        # Any in-flight request issued at or before gap_to whose result was
        # not yet observed has an unknown outcome.
        unknown = {
            rid: "unknown-outcome"
            for rid, issued_at in in_flight_requests.items()
            if issued_at <= gap_to
        }
        raise ReplayGapError(
            f"session {session_id}: replay cursor {last_event_id} below "
            f"retained low-water mark {window.oldest_retained}; "
            f"unrecoverable gap [{gap_from}..{gap_to}]; "
            f"requests now unknown-outcome: {sorted(unknown)}"
        )

    # Cursor is within retention: replay is provably contiguous.
    return {rid: "pending" for rid in in_flight_requests}


def handle_backpressure_drop(session_id: str, dropped_event_ids: list[int]) -> None:
    """A server dropping events under write-buffer pressure must not do so silently."""
    if dropped_event_ids:
        raise ReplayGapError(
            f"session {session_id}: backpressure dropped events "
            f"{dropped_event_ids}; liveness signal gap must be surfaced to "
            f"the agent, not swallowed"
        )
