# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-event-loss-when-an-mcp-streamable-http-session-migrates-from-sse-to-post-mid-stream.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-event-loss-when-an-mcp-streamable-http-session-migrates-from-sse-to-post-mid-stream.warrant.json
# Markdown SHA-256:   0fc4f0b773f50abf8de4f237a43d98ed76e53de9c94a6f780b8ff802ac11b16a
# Code AST SHA-256:   7d35062fa341eca58f4d815ab00386c62943d0b68b76af1a66a4c46db5bfde62
# Verified Classes:   EventContinuityViolation, SessionEventLog, ResumingClient
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class EventContinuityViolation(RuntimeError):
    """Raised when a resumed MCP stream regresses or skips event IDs."""
    pass


class SessionEventLog:
    def __init__(self, session_id: str):
        self.session_id = session_id
        self.events: list[tuple[int, dict]] = []
        self._next_id = 1

    def emit(self, payload: dict) -> int:
        event_id = self._next_id
        self._next_id += 1
        self.events.append((event_id, payload))
        return event_id

    def replay_after(self, last_event_id: int) -> list[tuple[int, dict]]:
        if last_event_id >= self._next_id:
            raise EventContinuityViolation(
                f"session {self.session_id}: Last-Event-ID {last_event_id} "
                f"exceeds high-water mark {self._next_id - 1}"
            )
        return [(eid, p) for (eid, p) in self.events if eid > last_event_id]


class ResumingClient:
    def __init__(self, session_id: str):
        self.session_id = session_id
        self.high_water = 0

    def accept_event(self, event_id: int) -> None:
        if event_id <= self.high_water:
            raise EventContinuityViolation(
                f"session {self.session_id}: event ID {event_id} regressed "
                f"below high-water mark {self.high_water}; channel switch "
                f"reset the ID space — refusing to merge"
            )
        if event_id != self.high_water + 1:
            raise EventContinuityViolation(
                f"session {self.session_id}: gap detected between "
                f"{self.high_water} and {event_id}"
            )
        self.high_water = event_id


def resume_over_post(log: SessionEventLog, client: ResumingClient) -> list[dict]:
    # Server must resolve Last-Event-ID against the session log, not a
    # per-request counter, or the client will observe a regression.
    replayed = log.replay_after(client.high_water)
    delivered = []
    for event_id, payload in replayed:
        client.accept_event(event_id)
        delivered.append(payload)
    return delivered
