# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-event-loss-when-resuming-a-streamable-session-mcp-transport-after-backpressure-induced-last-event-id-truncation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-event-loss-when-resuming-a-streamable-session-mcp-transport-after-backpressure-induced-last-event-id-truncation.warrant.json
# Markdown SHA-256:   0b728003e92361090065edcc9d0370049e68590553b9c7488f8ca4effa178dfd
# Code AST SHA-256:   88c0a86493881d9e14b5c0b5e61cdc6b0c961afa5ce91718a71bf6744b26790f
# Verified Classes:   StreamResumeGapError, ResumeValidator
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StreamResumeGapError(RuntimeError):
    """Raised when a resumed MCP streamable-session stream skips event ids."""
    pass


class ResumeValidator:
    def __init__(self, last_processed_id: int):
        self.last_processed_id = last_processed_id
        self.gap_detected = False

    def validate_resume(self, requested_last_event_id: int, first_received_id: int) -> None:
        # The client asked to resume after requested_last_event_id.
        # A gap exists if the first event we actually got is not the immediate successor.
        if first_received_id != requested_last_event_id + 1:
            self.gap_detected = True
            raise StreamResumeGapError(
                f"resume gap: requested Last-Event-ID={requested_last_event_id}, "
                f"first received id={first_received_id}, "
                f"missing={first_received_id - requested_last_event_id - 1} event(s)"
            )

    def on_event(self, event_id: int) -> None:
        if event_id <= self.last_processed_id:
            raise StreamResumeGapError(
                f"non-monotonic event id: {event_id} <= last_processed {self.last_processed_id}"
            )
        if event_id != self.last_processed_id + 1:
            self.gap_detected = True
            raise StreamResumeGapError(
                f"mid-stream gap: expected {self.last_processed_id + 1}, got {event_id}"
            )
        self.last_processed_id = event_id


def resume_session(validator: ResumeValidator, requested_id: int, stream_first_id: int) -> None:
    try:
        validator.validate_resume(requested_id, stream_first_id)
    except StreamResumeGapError:
        # Force full state resync before any dependent tool call.
        raise StreamResumeGapError(
            "session degraded: full resource resync required before proceeding"
        )
