# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-mcp-session-resumption-when-an-sse-streamable-transport-migrates-mid-session-and-last-event-id-no-longer-maps-to-a-re.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-mcp-session-resumption-when-an-sse-streamable-transport-migrates-mid-session-and-last-event-id-no-longer-maps-to-a-re.warrant.json
# Markdown SHA-256:   c2500d402936fb5f2960927ebd33d5f51330ffa764dbb089b1a9688da611a737
# Code AST SHA-256:   6d01649f1c1e62bcc43329d27c8cace47b92f382f6d6c8881ef51993267916a6
# Verified Classes:   ResumptionEpochMismatch, IndeterminateRequest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ResumptionEpochMismatch(RuntimeError):
    """Raised when Last-Event-ID cannot be proven to belong to the current log epoch."""
    pass


class IndeterminateRequest(RuntimeError):
    """Raised when a resumed session yields no replay for an in-flight request."""
    pass


def resume_streamable_session(
    session_id: str,
    last_event_id: int,
    server_epoch: int,
    client_epoch: int,
    retained_range: tuple[int, int],
    replayed_frames: list[dict],
    in_flight_request_id: str | None,
) -> dict:
    # 1. Epoch binding: an ID from a prior epoch is not resumable.
    if client_epoch != server_epoch:
        raise ResumptionEpochMismatch(
            f"session {session_id}: Last-Event-ID {last_event_id} belongs to epoch "
            f"{client_epoch}, server is at epoch {server_epoch}; refusing to clamp"
        )

    # 2. Range check within epoch: out-of-range is invalidation, not catch-up.
    lo, hi = retained_range
    if not (lo <= last_event_id <= hi):
        raise ResumptionEpochMismatch(
            f"session {session_id}: Last-Event-ID {last_event_id} outside retained "
            f"range [{lo},{hi}] in epoch {server_epoch}"
        )

    # 3. Empty replay for an in-flight request is indeterminate, not complete.
    if in_flight_request_id is not None and not replayed_frames:
        raise IndeterminateRequest(
            f"session {session_id}: request {in_flight_request_id} has no terminal "
            f"frame after resume from {last_event_id}; probe before retry"
        )

    return {
        "session_id": session_id,
        "epoch": server_epoch,
        "resumed_from": last_event_id,
        "frames": replayed_frames,
    }
