# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-lost-sse-event-window-across-mcp-streamable-http-session-resumption.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-lost-sse-event-window-across-mcp-streamable-http-session-resumption.warrant.json
# Markdown SHA-256:   3a3f5b179c0d617f07af66f1df11c100409571e24e500420c15325dce213cd35
# Code AST SHA-256:   c5d9e2b0c8e6bbd5b800051aedf45507d00684c80931cbf19f0980e5f426078a
# Verified Classes:   ResumptionGapError, SseEvent
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ResumptionGapError(RuntimeError):
    """Raised when a resumed SSE stream skips events the client needed.

    The server's per-session event buffer evicted events between the
    client's Last-Event-ID and the oldest event the server still holds.
    The replayed stream is well-formed but NOT continuous with prior
    agent state; the in-flight operation's outcome is unknown.
    """


@dataclass(frozen=True)
class SseEvent:
    id: int
    data: str


def assert_contiguous_resume(
    last_event_id: int,
    first_replayed: SseEvent | None,
) -> None:
    """Enforce the resumption contiguity invariant before dispatch.

    Must be called on the first event received after reconnecting with
    Last-Event-ID, before any replayed event reaches the agent state
    machine. A gap means the operation outcome is unknown, not pending.
    """
    if first_replayed is None:
        # Server accepted the resume but had nothing to replay; the
        # terminal event may be lost. Treat as unknown, not success.
        raise ResumptionGapError(
            f"resume with Last-Event-ID={last_event_id} yielded no events; "
            "terminal outcome unknown"
        )

    expected = last_event_id + 1
    if first_replayed.id == expected:
        return

    if first_replayed.id > expected:
        raise ResumptionGapError(
            f"event gap on resume: expected id={expected}, "
            f"got id={first_replayed.id} "
            f"(events {expected}..{first_replayed.id - 1} evicted); "
            "operation outcome is unknown, query status by idempotency key"
        )

    # first_replayed.id < expected: server replayed already-consumed
    # events (duplicate delivery). Not a gap, but the caller must
    # deduplicate before applying effects.
    raise ResumptionGapError(
        f"duplicate replay: expected id={expected}, got id={first_replayed.id}"
    )


def resume_session(
    last_event_id: int,
    replayed: list[SseEvent],
    status_lookup,
    idempotency_key: str,
) -> str:
    """Resume a stream, or fall back to a status query on gap."""
    try:
        assert_contiguous_resume(
            last_event_id, replayed[0] if replayed else None
        )
    except ResumptionGapError:
        # Do NOT feed replayed events into the state machine.
        # Resolve the unknown outcome out-of-band.
        return status_lookup(idempotency_key)

    for ev in replayed:
        # Safe: stream is provably continuous with prior state.
        apply_event_to_agent_state(ev)
    return "resumed"
