# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-mcp-streamable-http-last-event-id-resumption-as-unsafe-and-force-a-cold-re-initialization.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-mcp-streamable-http-last-event-id-resumption-as-unsafe-and-force-a-cold-re-initialization.warrant.json
# Markdown SHA-256:   4bcd87881c31c066033ff72c9299703ffb6c1ce2af4cc5e3288b4a624d6e4ed6
# Code AST SHA-256:   241651f892ab0f1b078e649e9bdc4a04b279aea2d32b6a808992748a2d0d9f21
# Verified Classes:   ResumptionGapError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ResumptionGapError(RuntimeError):
    """Raised when an MCP Streamable-HTTP resumption cannot be proven gap-free."""
    def __init__(self, expected_id: int, first_replayed: int, retention_floor: int | None):
        self.expected_id = expected_id
        self.first_replayed = first_replayed
        self.retention_floor = retention_floor
        super().__init__(
            f"resumption gap: expected event {expected_id}, "
            f"first replayed {first_replayed}, floor {retention_floor}"
        )


def validate_resumption(
    last_seen_id: int,
    first_replayed_id: int,
    retention_floor: int | None,
    in_flight_call_ids: set[str],
    gap_window_call_ids: set[str],
) -> None:
    """
    Decide whether a resumed MCP session may be trusted.

    Raises ResumptionGapError if the replay cannot be proven contiguous.
    On success, the caller may continue the session; on failure, the caller
    MUST cold re-initialize and fail all gap-window in-flight calls.
    """
    expected = last_seen_id + 1

    if retention_floor is None:
        # No advertised retention floor: continuity is unprovable.
        raise ResumptionGapError(expected, first_replayed_id, retention_floor)

    if expected < retention_floor:
        # Requested resume point predates retained window: events were evicted.
        raise ResumptionGapError(expected, first_replayed_id, retention_floor)

    if first_replayed_id > expected:
        # Monotonic but discontinuous: the classic silent-fork failure.
        # Fail fast on every call whose terminal event fell in the gap.
        for call_id in gap_window_call_ids & in_flight_call_ids:
            in_flight_call_ids.discard(call_id)
        raise ResumptionGapError(expected, first_replayed_id, retention_floor)

    if first_replayed_id < expected:
        # Replay of already-seen events: require idempotent handling upstream.
        # Not a gap, but the caller must dedupe by event id.
        return

    # first_replayed_id == expected and within retention: resume is safe.
    return
