# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resume-an-mcp-stream-against-a-session-token-whose-event-history-has-already-been-compacted.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resume-an-mcp-stream-against-a-session-token-whose-event-history-has-already-been-compacted.warrant.json
# Markdown SHA-256:   37ec215c1b36bc3aa5801753bc0427047c9239ffe20573a25bc4c4fc57070651
# Code AST SHA-256:   47639f4815168715a2f237b2c057801913e79cf65451ee1dfc1075b10d2e3cac
# Verified Classes:   UnrecoverableGap, SessionLog
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class UnrecoverableGap(RuntimeError):
    """Raised when a resume cursor precedes the session's compaction watermark.

    The session is alive and the cursor is syntactically valid, but the events
    between the cursor and the watermark have been evicted. Continuing would
    silently drop causally-relevant events (e.g. tools/call results), so the
    only safe response is to refuse resumption.
    """


@dataclass
class SessionLog:
    session_id: str
    compaction_watermark: int  # highest evicted event id
    last_event_id: int         # highest emitted event id


def resume_stream(log: SessionLog, last_event_id: int) -> range:
    """Compute the event range to replay for a resumption request.

    Enforces the continuity invariant: a cursor strictly before the
    compaction watermark MUST be rejected, never clamped to the watermark.
    """
    if last_event_id < 0:
        raise UnrecoverableGap(
            f"session {log.session_id}: negative cursor {last_event_id}"
        )
    if last_event_id < log.compaction_watermark:
        raise UnrecoverableGap(
            f"session {log.session_id}: cursor {last_event_id} precedes "
            f"compaction watermark {log.compaction_watermark}; "
            f"events {last_event_id + 1}..{log.compaction_watermark} are gone"
        )
    return range(last_event_id + 1, log.last_event_id + 1)


def handle_resume(log: SessionLog, last_event_id: int) -> list[int]:
    try:
        return list(resume_stream(log, last_event_id))
    except UnrecoverableGap:
        # Do not clamp. Force the client to re-initialize or abort.
        raise
