# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-mcp-sse-replay-cursors-when-last-event-id-resumption-silently-skips-events-across-a-streamable-http-session-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-mcp-sse-replay-cursors-when-last-event-id-resumption-silently-skips-events-across-a-streamable-http-session-boundary.warrant.json
# Markdown SHA-256:   c270a8b7bdc1f32646f07d76b4de298ff3ee8ad341710baa21aca1704f154782
# Code AST SHA-256:   327ceca8945fa98e2b74e5ff8f8271bfa60941a893defbb442d2f4376deef3d3
# Verified Classes:   SseReplayGapError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SseReplayGapError(RuntimeError):
    """Raised when Last-Event-ID resumption skips events the client never processed."""
    pass


def resume_stream(
    last_processed_id: int,
    last_event_fully_processed: bool,
    replayed_first_id: int,
    server_guarantees_contiguous_replay: bool,
) -> None:
    """
    Validate an SSE replay before allowing the agent to continue.

    Invariant: the replayed stream must begin at the immediate successor of
    the last *fully processed* event. If the client was mid-event when the
    connection dropped, it cannot trust the cursor and must re-derive state.
    """
    if not last_event_fully_processed:
        raise SseReplayGapError(
            f"connection dropped mid-event (cursor={last_processed_id}); "
            "replay cursor is unreliable, re-derive session state"
        )

    expected_next = last_processed_id + 1
    if replayed_first_id == expected_next:
        return  # contiguous, safe to continue

    if server_guarantees_contiguous_replay:
        # Server attests contiguity but violated it: hard failure.
        raise SseReplayGapError(
            f"server claimed contiguous replay but resumed at {replayed_first_id}, "
            f"expected {expected_next}"
        )

    raise SseReplayGapError(
        f"replay gap: last processed {last_processed_id}, "
        f"stream resumed at {replayed_first_id} "
        f"({replayed_first_id - expected_next} events lost); "
        "discard partial accumulator and re-issue with idempotency key"
    )


def handle_reconnect(session) -> None:
    resume_stream(
        last_processed_id=session.cursor,
        last_event_fully_processed=session.cursor_committed,
        replayed_first_id=session.peek_first_replayed_id(),
        server_guarantees_contiguous_replay=session.capabilities.contiguous_replay,
    )
