# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-its-last-tool-result-when-an-mcp-sse-stream-resumes-across-a-rebalanced-session.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-its-last-tool-result-when-an-mcp-sse-stream-resumes-across-a-rebalanced-session.warrant.json
# Markdown SHA-256:   cc4ede8a2ab1a131b166402be4cc88bc4d2bbd0733823e192c3b8beb598132ec
# Code AST SHA-256:   a325ad228d425f88ac1e1dd2603419ece9e5b36bed0201ffb4b755c74c15f0f2
# Verified Classes:   UnreplayableResumeGap, EventLog
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class UnreplayableResumeGap(RuntimeError):
    """Raised when a Last-Event-ID resume cannot be honored from the
    resuming process's replayable log and the store cannot fill the gap.
    Must abort the stream BEFORE emitting any live event."""
    pass


@dataclass
class EventLog:
    # Lowest event id this process can actually serve from.
    replayable_head: int
    # Highest event id written so far.
    tail: int

    def can_replay(self, requested_id: int) -> bool:
        return requested_id + 1 >= self.replayable_head


def resume_stream(session_id: str, last_event_id: int, log: EventLog,
                  store_has_range: bool) -> int:
    """Return the first event id to emit after a resume, or raise.

    Invariant: never emit a live event if the client's requested position
    is below our replayable head and the store cannot fill the gap. A
    heartbeat or the next live event in that state is silent divergence.
    """
    if log.can_replay(last_event_id):
        return last_event_id + 1

    # Gap detected: requested position predates what we can serve locally.
    if store_has_range:
        # Store can replay [last_event_id+1, replayable_head-1]; caller
        # must emit those first, then continue from replayable_head.
        return last_event_id + 1

    raise UnreplayableResumeGap(
        f"session={session_id} last_event_id={last_event_id} "
        f"replayable_head={log.replayable_head} tail={log.tail}: "
        f"requested position is unreplayable on this instance and the "
        f"store cannot fill the gap; client must re-establish the session"
    )


def handle_resume(session_id: str, last_event_id: int, log: EventLog,
                  store_has_range: bool) -> None:
    try:
        first = resume_stream(session_id, last_event_id, log, store_has_range)
    except UnreplayableResumeGap:
        # Emit an explicit, non-resumable close — never a live event.
        close_stream_with_error(session_id, code="resume_gap")
        raise
    emit_from(session_id, first)
