# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-a-resumed-mcp-sse-stream-against-a-session-continuity-token-that-outlived-its-event-log.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-a-resumed-mcp-sse-stream-against-a-session-continuity-token-that-outlived-its-event-log.warrant.json
# Markdown SHA-256:   1a4707af860ee09cc7b65123383f643b0367fe272fccf27c1581afb9b56e8c4e
# Code AST SHA-256:   7ea748c4be0909fc2230370801c24831f790cc0dd76b4012dab89654d59f8ac9
# Verified Classes:   ResumptionGapError, ResumeAck
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ResumptionGapError(RuntimeError):
    """Raised when a resumed SSE stream cannot be proven contiguous with the requested cursor."""


@dataclass
class ResumeAck:
    requested_cursor: int
    first_event_id: int | None   # None if server opened stream but sent no events yet
    session_alive: bool
    explicit_gap_signal: bool    # server said cursor_evicted / resumption_failed


def reconcile_resume(ack: ResumeAck, partial_result_epoch: int) -> int:
    """
    Decide whether the agent may continue merging into its partial result.
    Returns the acknowledged cursor to continue from.
    Raises ResumptionGapError when contiguity cannot be established.
    """
    if not ack.session_alive:
        # Session token dead: stream cannot resume at all; caller must re-issue the call.
        raise ResumptionGapError(
            f"session expired while resuming from cursor {ack.requested_cursor}; "
            "re-issue originating tools/call under a fresh idempotency key"
        )

    if ack.explicit_gap_signal:
        raise ResumptionGapError(
            f"server reported cursor {ack.requested_cursor} unserviceable; "
            f"partial_result_epoch={partial_result_epoch} must be discarded, not merged"
        )

    if ack.first_event_id is None:
        # Ambiguous: stream opened but no event proves the cursor was honored.
        raise ResumptionGapError(
            f"stream opened for cursor {ack.requested_cursor} with no acknowledging event; "
            "treating as data loss, not empty backlog"
        )

    if ack.first_event_id != ack.requested_cursor + 1:
        raise ResumptionGapError(
            f"cursor discontinuity: requested {ack.requested_cursor}, "
            f"stream began at {ack.first_event_id}; "
            f"gap of {ack.first_event_id - ack.requested_cursor - 1} events"
        )

    return ack.first_event_id - 1
