# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-streamable-sse-session-after-last-event-id-points-past-a-server-side-replay-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-mcp-streamable-sse-session-after-last-event-id-points-past-a-server-side-replay-gap.warrant.json
# Markdown SHA-256:   c03edcbcb65080bf0e7591afd0fb47e158030e561259a7bdb19e6a2b9010472c
# Code AST SHA-256:   3fdba6bf2913969f6ae1545df14621f26a5e398691ea3696b67c1469505172f0
# Verified Classes:   ResumeGapError, ResumeDecision
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ResumeGapError(RuntimeError):
    """Raised when an SSE resumption cannot prove contiguity from Last-Event-ID."""


@dataclass
class ResumeDecision:
    accept: bool
    first_deliverable_id: int


def evaluate_resumption(
    last_event_id: int,
    oldest_retained_id: int,
    next_stream_id: int,
    gap_marker_present: bool,
) -> ResumeDecision:
    """
    Decide whether an MCP streamable-SSE resumption preserves continuity.

    Invariant: a resumption is valid only if the stream's first deliverable
    event is exactly last_event_id + 1, OR an explicit gap marker is present
    AND the runtime is prepared to poison the session.
    """
    expected = last_event_id + 1

    if next_stream_id == expected:
        return ResumeDecision(accept=True, first_deliverable_id=next_stream_id)

    # Server skipped events. Monotonicity is NOT continuity.
    if next_stream_id > expected:
        if gap_marker_present:
            # Client-detected gap path: caller must poison + re-derive state.
            raise ResumeGapError(
                f"resume gap acknowledged by marker: expected {expected}, "
                f"stream resumes at {next_stream_id}; session must be poisoned"
            )
        # Silent gap: the indefensible case. Refuse to launder the cursor.
        raise ResumeGapError(
            f"silent replay gap: Last-Event-ID={last_event_id} but server "
            f"oldest_retained={oldest_retained_id} and stream starts at "
            f"{next_stream_id}; {next_stream_id - expected} events lost, "
            f"no marker. Treat session as poisoned."
        )

    # next_stream_id < expected: server rewound or duplicated events.
    raise ResumeGapError(
        f"non-monotonic resumption: expected {expected}, got {next_stream_id}"
    )


def resume_session(
    last_event_id: int,
    oldest_retained_id: int,
    next_stream_id: int,
    gap_marker_present: bool,
    orphaned_request_ids: list[str],
) -> None:
    decision = evaluate_resumption(
        last_event_id, oldest_retained_id, next_stream_id, gap_marker_present
    )
    if not decision.accept:
        # Unreachable given evaluate_resumption's raising contract, but kept
        # explicit so the invariant is enforced at the call site too.
        raise ResumeGapError("resumption rejected without a poison path")
    # Caller may now safely advance the cursor to first_deliverable_id.
    assert decision.first_deliverable_id == last_event_id + 1
    # Any request whose terminal event could not be proven delivered must be
    # reconciled (idempotency check), never blindly re-issued.
    for req_id in orphaned_request_ids:
        _reconcile_before_reissue(req_id)


def _reconcile_before_reissue(req_id: str) -> None:
    # Placeholder: query server-side idempotency key / effect log before retry.
    ...
