# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-resume-an-mcp-streamable-http-session-because-the-resumable-event-log-has-been-truncated-past-its-last-ac.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-resume-an-mcp-streamable-http-session-because-the-resumable-event-log-has-been-truncated-past-its-last-ac.warrant.json
# Markdown SHA-256:   64b9e1b3b067ced40e7fa383b8c85d75bb0128e212626f3493366eb036e751be
# Code AST SHA-256:   70ee5f468cef35d1dea79529caeddbaa497a72d0e1b9dec56ecf5c6484259789
# Verified Classes:   ResumeWindowExceeded
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ResumeWindowExceeded(RuntimeError):
    """Raised when a client's Last-Event-ID predates the eviction floor
    and the gap contains state-bearing events that cannot be replayed."""
    def __init__(self, requested_id: int, eviction_floor: int, last_retained: int):
        self.requested_id = requested_id
        self.eviction_floor = eviction_floor
        self.last_retained = last_retained
        super().__init__(
            f"resume window exceeded: requested Last-Event-ID={requested_id} "
            f"< eviction_floor={eviction_floor}; last_retained={last_retained}"
        )


def plan_resume(requested_id: int, eviction_floor: int, last_retained: int,
                gap_events: list[dict]) -> int:
    """Return the first event index to replay, or raise if resume is unsafe.

    gap_events: events in (requested_id, eviction_floor) that were evicted.
    Each carries a 'state_bearing' bool set at emit time.
    """
    if requested_id >= eviction_floor:
        return requested_id + 1  # normal replay from ID+1

    # Requested ID is below the floor: the gap was evicted.
    state_bearing_in_gap = [e for e in gap_events if e.get("state_bearing")]
    if state_bearing_in_gap:
        # Cannot honor the client's position; do not clamp silently.
        raise ResumeWindowExceeded(requested_id, eviction_floor, last_retained)

    # Gap contained only non-state-bearing frames (pings/progress):
    # clamping to the floor is safe and preserves continuity.
    return eviction_floor
