# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-resumable-sse-stream-has-silently-forked-its-event-log-across-mcp-http-native-clients.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-resumable-sse-stream-has-silently-forked-its-event-log-across-mcp-http-native-clients.warrant.json
# Markdown SHA-256:   4faa32afb396f3c2b6d1fe05a9633a7ba81de0842c0e356c17d7bc6b7ba72674
# Code AST SHA-256:   01acd7e1b29a202e65a854100345be7ea5ec6314b5ba24c6efb4c1d33d1e72b2
# Verified Classes:   SSEEventLogForkedError, ResumableStreamClient
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SSEEventLogForkedError(RuntimeError):
    """Raised when a resumed SSE stream's frame ids are non-contiguous,
    indicating the server's retention buffer was drained by a fan-out peer
    and the reconnecting client's replay is incomplete."""
    pass


class ResumableStreamClient:
    def __init__(self, retention_window_sec: float, disconnect_sec: float):
        self.last_seen_id: int = 0
        self.retention_window_sec = retention_window_sec
        self.disconnect_sec = disconnect_sec

    def resume(self, first_replayed_id: int, frames: list[dict]) -> list[dict]:
        # Retention must cover the disconnect, or replay is unsound by construction.
        if self.disconnect_sec > self.retention_window_sec:
            raise SSEEventLogForkedError(
                f"disconnect {self.disconnect_sec}s exceeds retention "
                f"{self.retention_window_sec}s; replay cannot be trusted"
            )
        # Contiguity invariant: first replayed frame must be exactly last_seen + 1.
        if first_replayed_id != self.last_seen_id + 1:
            raise SSEEventLogForkedError(
                f"event log forked: expected id {self.last_seen_id + 1}, "
                f"server resumed at {first_replayed_id} "
                f"(gap of {first_replayed_id - self.last_seen_id - 1} frames)"
            )
        # Verify the whole suffix is monotonic and gap-free before accepting.
        expected = first_replayed_id
        for frame in frames:
            if frame["id"] != expected:
                raise SSEEventLogForkedError(
                    f"non-monotonic replay at id {frame['id']}, expected {expected}"
                )
            expected += 1
        self.last_seen_id = expected - 1
        return frames
