# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-resumed-mcp-http-stream-when-the-server-s-last-event-id-cursor-points-into-a-buffer-the-server-has-already-evicted.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-resumed-mcp-http-stream-when-the-server-s-last-event-id-cursor-points-into-a-buffer-the-server-has-already-evicted.warrant.json
# Markdown SHA-256:   3533c0a819983ba7d6ab531948f8724744031d7264b814248d494f91f519eba1
# Code AST SHA-256:   bda401bf53542048e2738d1d6494c186b298273c2cc90c3e2c65625232ef3853
# Verified Classes:   ResumptionGapError, UnknownToolOutcomeError, StreamCursor
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional

class ResumptionGapError(RuntimeError):
    """Raised when a resumed MCP SSE stream is discontinuous with the cursor we sent."""
    pass

class UnknownToolOutcomeError(RuntimeError):
    """Raised when a tools/call result cannot be determined; retry requires idempotency key."""
    pass

@dataclass
class StreamCursor:
    last_event_id: Optional[int] = None
    request_id: str = ""
    accumulator: list = field(default_factory=list)

def resume_stream(
    cursor: StreamCursor,
    first_event_id_after_reconnect: Optional[int],
    grace_window_s: float = 2.0,
) -> None:
    """
    Validate that a resumed stream continues from cursor.last_event_id.
    If the server re-headed (evicted cursor) or sent nothing, raise ResumptionGapError.
    """
    if first_event_id_after_reconnect is None:
        # No events within grace window: cannot prove continuity.
        raise ResumptionGapError(
            f"no events after reconnect for request {cursor.request_id}; "
            f"cursor {cursor.last_event_id} unverifiable"
        )
    if cursor.last_event_id is not None and \
       first_event_id_after_reconnect != cursor.last_event_id + 1:
        raise ResumptionGapError(
            f"stream discontinuity: sent Last-Event-ID={cursor.last_event_id}, "
            f"server resumed at id={first_event_id_after_reconnect}; "
            f"{first_event_id_after_reconnect - cursor.last_event_id - 1} events lost"
        )

def handle_reconnect(cursor: StreamCursor, first_id: Optional[int]) -> None:
    try:
        resume_stream(cursor, first_id)
    except ResumptionGapError as gap:
        # Outcome of the in-flight call is UNKNOWN, not FAILED.
        # Do not splice; orphan the accumulator and route to reconciliation.
        raise UnknownToolOutcomeError(
            f"{gap}; request {cursor.request_id} outcome unknown — "
            f"re-issue only with the same idempotency key"
        ) from gap
