# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-resumable-sse-last-event-id-as-authoritative-after-session-resumption-and-when-does-it-silently-re.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-resumable-sse-last-event-id-as-authoritative-after-session-resumption-and-when-does-it-silently-re.warrant.json
# Markdown SHA-256:   6593ac1fef87159008681867d057e967bf4fa7fd8ba4df03b0bf9ac75f40b420
# Code AST SHA-256:   02a1e41ebb6de4d9c5a89a5d79703bef84b0c41d9bbc8f94a8c19421fea5d078
# Verified Classes:   ResumptionGapError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ResumptionGapError(RuntimeError):
    """Raised when an MCP SSE resume delivers a non-contiguous event id,
    indicating the server truncated the event log past Last-Event-ID and
    the stream suffix cannot be treated as continuous session state."""
    pass


def resume_stream(last_event_id: int, first_resumed_event: dict) -> int:
    """Validate the first event of a resumed SSE stream against the
    client's Last-Event-ID. Returns the new cursor on success.

    Invariant: the stream is authoritative only if the first resumed
    event is exactly last_event_id + 1. Any gap, rewind, or id reuse
    means the session's event log was truncated or rewritten and the
    client must re-derive state from a snapshot rather than the stream.
    """
    incoming = first_resumed_event.get("id")
    if incoming is None:
        raise ResumptionGapError(
            "resumed event carries no id; cannot establish contiguity"
        )
    try:
        incoming_id = int(incoming)
    except (TypeError, ValueError):
        raise ResumptionGapError(
            f"non-integer event id {incoming!r} on resumed stream"
        )

    if incoming_id == last_event_id + 1:
        return incoming_id

    if incoming_id > last_event_id + 1:
        missing = incoming_id - last_event_id - 1
        raise ResumptionGapError(
            f"event-log truncation: expected id {last_event_id + 1}, "
            f"received {incoming_id}; {missing} event(s) unrecoverable. "
            f"Session is not resumable from Last-Event-ID; re-derive state "
            f"from an authoritative snapshot or cold-start the session."
        )

    # incoming_id <= last_event_id: server rewound or reused ids.
    raise ResumptionGapError(
        f"event id {incoming_id} <= Last-Event-ID {last_event_id}; "
        f"server reused or rewound ids, session identity is untrustworthy"
    )
