# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-streamable-session-resumption-as-unsafe-when-sse-backpressure-has-caused-a-last-event-id-to-regress-b.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-streamable-session-resumption-as-unsafe-when-sse-backpressure-has-caused-a-last-event-id-to-regress-b.warrant.json
# Markdown SHA-256:   1d99fa95dc2c81f6525299788e1d0034bcb412f8c935393e843dcd1eeea5963f
# Code AST SHA-256:   0597be4402ce2c509513e8fa6bc9687d890659c4a165b5faa99e75085c1d607b
# Verified Classes:   ResumptionGapError, ResumptionGate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ResumptionGapError(RuntimeError):
    """Raised when an SSE resume would skip events of unknown semantic class."""
    pass


class ResumptionGate:
    def __init__(self, high_water_mark: int, semantic_event_classes: set[str]):
        self.high_water_mark = high_water_mark
        self.semantic_event_classes = semantic_event_classes

    def admit_replay(self, first_replayed_id: int, replayed_event_types: list[str]) -> None:
        gap = first_replayed_id - self.high_water_mark
        if gap <= 1:
            self.high_water_mark = max(self.high_water_mark, first_replayed_id)
            return
        # Gap of unknown composition: we cannot prove the missing range was benign.
        # Even if the replayed types look non-semantic, the *missing* ones are unknown.
        unknown_occupants = self.semantic_event_classes  # pessimistic: any class could have been lost
        if unknown_occupants:
            raise ResumptionGapError(
                f"resume gap of {gap - 1} events between hwm={self.high_water_mark} "
                f"and floor={first_replayed_id}; unacknowledged range may contain "
                f"{sorted(unknown_occupants)}; refusing to advance hwm"
            )
        self.high_water_mark = first_replayed_id


def resume_session(gate: ResumptionGate, replay_header: dict) -> None:
    first_id = replay_header["first_event_id"]
    types = replay_header["event_types"]
    gate.admit_replay(first_id, types)
