# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-streamable-session-resumption-against-backpressure-induced-event-loss-in-mcp-http-native-transport.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-streamable-session-resumption-against-backpressure-induced-event-loss-in-mcp-http-native-transport.warrant.json
# Markdown SHA-256:   bfb076640b012c156b6a48cd38378f8256b755ba8bd4e329662bb22a29e541f8
# Code AST SHA-256:   b6f05c32eff0ed65b81a50f14cf2973cb4919c7d2d6a9345180e36fd4946c3df
# Verified Classes:   SessionResumeGapError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SessionResumeGapError(RuntimeError):
    """Raised when a streamable-session resume cannot prove prefix continuity."""
    def __init__(self, last_seen: int, retained_head: int, session_id: str):
        self.last_seen = last_seen
        self.retained_head = retained_head
        self.session_id = session_id
        super().__init__(
            f"session {session_id}: requested resume from {last_seen}, "
            f"server retained only from {retained_head} "
            f"(gap of {retained_head - last_seen - 1} events)"
        )


def resume_stream(session, last_event_id: int):
    """
    Reconcile a client's Last-Event-ID against the server's retained range.
    Returns (resume_from, is_lossy). Raises SessionResumeGapError if the
    server cannot prove continuity under the continuity contract.
    """
    retained = session.retained_range()  # (head, tail) of outbox, inclusive
    if retained is None:
        # Epoch contract: no retained history -> force full re-sync.
        return (None, True)

    head, tail = retained
    if last_event_id < head:
        # Prefix requested is gone. Under continuity contract this is a
        # hard error; the client must invalidate derived state.
        if session.contract == "continuity":
            raise SessionResumeGapError(last_event_id, head, session.id)
        # Epoch contract: signal lossy resume, caller must re-sync.
        return (head, True)

    if last_event_id > tail:
        # Client claims to have processed an event the server never emitted.
        raise SessionResumeGapError(last_event_id, head, session.id)

    return (last_event_id + 1, False)


def apply_resume(session, last_event_id: int, client_state):
    resume_from, lossy = resume_stream(session, last_event_id)
    if lossy:
        # Invalidate tool registry, resource cache, partial results.
        client_state.invalidate_all()
        client_state.re_sync(session)
    # Only now is it safe to consume events from resume_from onward.
    for event in session.events_from(resume_from):
        client_state.apply(event)
    return client_state
