# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-multiplexes-resumable-mcp-tool-call-streams-over-a-single-http-1-1-connection-and-the-server-s-per-stream-backpressure-w.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-multiplexes-resumable-mcp-tool-call-streams-over-a-single-http-1-1-connection-and-the-server-s-per-stream-backpressure-w.warrant.json
# Markdown SHA-256:   8241f37803fde630a9a51b7493da7a508d5733dc8c1546fd3a11b6dcc320b6a2
# Code AST SHA-256:   3b4298929e78d888e23e3bf4b571c869ac8ef31398e4727d3931e58ee90d0bdc
# Verified Classes:   ResumeGapError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ResumeGapError(RuntimeError):
    """Raised when a resumable MCP stream resume cannot prove continuity:
    the received sequence jumps past the client cursor with no server epoch
    confirming that the intervening events never existed (vs. were evicted)."""
    pass


def resume_stream(client_cursor: int,
                  server_retained_from: int | None,
                  received_seq: int,
                  server_epoch: str | None,
                  known_epoch: str | None) -> int:
    """
    Validate a single-stream resume. Returns the new cursor on success.
    Raises ResumeGapError when continuity is unprovable.

    client_cursor:       last event id the agent actually consumed
    server_retained_from: server's retention floor for THIS stream (None if unknown)
    received_seq:        first event id delivered after resume
    server_epoch:        server-supplied epoch for the retained range (None if absent)
    known_epoch:         epoch the client observed before the disconnect (None if none)
    """
    expected_next = client_cursor + 1

    # Fast path: contiguous delivery, no gap to reason about.
    if received_seq == expected_next:
        return received_seq

    # A jump occurred. It is only safe if the server can prove the
    # intervening events never existed, via a matching retained-from floor
    # AND a stable epoch. A cursor alone is not proof.
    if server_retained_from is None:
        raise ResumeGapError(
            f"resume jumped {client_cursor}->{received_seq} with no "
            f"retained_from; continuity unprovable"
        )
    if server_retained_from > expected_next:
        raise ResumeGapError(
            f"server evicted below live cursor: retained_from="
            f"{server_retained_from} > expected_next={expected_next}; "
            f"events {expected_next}..{server_retained_from - 1} lost"
        )
    if server_epoch is None or known_epoch is None or server_epoch != known_epoch:
        raise ResumeGapError(
            f"epoch mismatch on resume: known={known_epoch!r} "
            f"server={server_epoch!r}; cannot distinguish eviction from "
            f"fresh stream"
        )

    # Retained floor covers the gap and epoch is stable: the jump is a
    # legitimate replay boundary (events before retained_from are provably
    # absent because the stream itself began there).
    return received_seq


def consume_resumed_stream(stream, client_cursor: int):
    for event in stream:
        try:
            client_cursor = resume_stream(
                client_cursor=client_cursor,
                server_retained_from=event.get("retained_from"),
                received_seq=event["seq"],
                server_epoch=event.get("epoch"),
                known_epoch=event.get("known_epoch"),
            )
        except ResumeGapError:
            # Treat unprovable continuity as a cold start: discard the
            # suspect suffix and re-execute rather than commit a partial result.
            stream.abort()
            raise
        yield event
