# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-stream-resumption-as-unsafe-when-the-sse-last-event-id-cursor-outruns-the-server-s-durable-replay-window.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-stream-resumption-as-unsafe-when-the-sse-last-event-id-cursor-outruns-the-server-s-durable-replay-window.warrant.json
# Markdown SHA-256:   160f55243d20fe5dbfc9167a548c1801c0b8f04cb724dd86b86cf13e6654631c
# Code AST SHA-256:   3c757d2dd43839801c045fbcd29dd520a2d545a1cc5014f76efd95b2332b204a
# Verified Classes:   StreamResumeGapError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class StreamResumeGapError(RuntimeError):
    """Raised when an SSE resume produces a non-contiguous event id sequence.

    This is deliberately non-retryable: retrying the same Last-Event-ID against
    the same server will reproduce the gap. The caller must reconcile against
    the tool's authoritative state or fail the operation.
    """
    def __init__(self, last_seen_id: int, first_replayed_id: int, buffer_floor: int | None):
        self.last_seen_id = last_seen_id
        self.first_replayed_id = first_replayed_id
        self.buffer_floor = buffer_floor
        self.missing = first_replayed_id - last_seen_id - 1
        super().__init__(
            f"SSE resume gap: last_seen={last_seen_id} first_replayed={first_replayed_id} "
            f"missing={self.missing} server_buffer_floor={buffer_floor}"
        )


def apply_resumed_event(last_seen_id: int, event_id: int, payload: dict,
                        buffer_floor: int | None = None) -> int:
    """Validate and apply one replayed SSE event; return the new cursor.

    Enforces the continuity invariant: the first event after a resume MUST be
    exactly last_seen_id + 1. Any other value means the server could not replay
    the gap (buffer overflow) and the stream is lossy.
    """
    if event_id <= last_seen_id:
        # At-least-once delivery: already applied. Dedupe, do not re-apply.
        return last_seen_id

    if event_id != last_seen_id + 1:
        raise StreamResumeGapError(
            last_seen_id=last_seen_id,
            first_replayed_id=event_id,
            buffer_floor=buffer_floor,
        )

    # Contiguous: safe to apply.
    _apply_payload(payload)
    return event_id


def resume_session(client, last_seen_id: int, tool_call_id: str) -> int:
    """Reconnect and drain a resumed stream, enforcing continuity throughout."""
    stream = client.reconnect(last_event_id=last_seen_id)
    buffer_floor = stream.headers.get("Mcp-Event-Buffer-Floor")
    buffer_floor = int(buffer_floor) if buffer_floor is not None else None

    cursor = last_seen_id
    for event in stream.iter_sse():
        if "id" not in event:
            # No id => server is not honoring resumption semantics at all.
            raise StreamResumeGapError(
                last_seen_id=cursor, first_replayed_id=-1, buffer_floor=buffer_floor
            )
        cursor = apply_resumed_event(
            last_seen_id=cursor,
            event_id=int(event["id"]),
            payload=event.data,
            buffer_floor=buffer_floor,
        )
    return cursor
