# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-last-event-id-resumption-as-a-capability-claim-rather-than-a-continuity-guarantee.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-last-event-id-resumption-as-a-capability-claim-rather-than-a-continuity-guarantee.warrant.json
# Markdown SHA-256:   b12f66eb089391240a6cda037e71d4698d37fadf53205c431dfbbae697b2df9d
# Code AST SHA-256:   d7f8dc2f47aef2e7e59765b7a673570db8a9299d5831e9e916fc809987b5777f
# Verified Classes:   ResumptionGapError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ResumptionGapError(RuntimeError):
    """Raised when an MCP SSE reconnect cannot prove stream contiguity."""
    pass


def resume_stream(last_received_id: int, first_replayed_id: int | None) -> int:
    """
    Validate that a Streamable HTTP SSE reconnection is semantically contiguous.

    Returns the ID from which it is safe to consume the replayed stream.
    Raises ResumptionGapError if the server's replay cannot be trusted, in which
    case the caller MUST re-issue the originating operation under its idempotency
    key rather than consume the partial stream.
    """
    if first_replayed_id is None:
        # Server emitted no event IDs: resumption is not in effect.
        raise ResumptionGapError(
            f"no event id on replayed stream after Last-Event-ID={last_received_id}; "
            "treating in-flight operation as unresumed"
        )

    gap = first_replayed_id - last_received_id
    if gap == 1:
        return first_replayed_id  # contiguous; safe to consume

    if gap <= 0:
        # first_replayed_id <= last_received_id: server ID space reset or
        # replayed from a different epoch (e.g., worker restart with counter reset).
        raise ResumptionGapError(
            f"replayed id {first_replayed_id} <= last received {last_received_id}; "
            "server id space appears reset — operation state lost, re-issue required"
        )

    # gap > 1: events were evicted from the server buffer or skipped.
    raise ResumptionGapError(
        f"gap of {gap - 1} event(s) between {last_received_id} and {first_replayed_id}; "
        "replay buffer eviction or skip detected — re-issue required"
    )


def consume_reconnect(last_received_id: int, first_replayed_id: int | None, operation_id: str) -> int:
    try:
        return resume_stream(last_received_id, first_replayed_id)
    except ResumptionGapError as exc:
        # Bound the failure: re-drive the idempotent operation instead of
        # consuming a truncated stream as if it were complete.
        raise ResumptionGapError(
            f"operation {operation_id!r} cannot resume: {exc}"
        ) from exc
