# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-sse-event-id-replay-against-a-resumable-mcp-stream-after-a-transport-drop.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-sse-event-id-replay-against-a-resumable-mcp-stream-after-a-transport-drop.warrant.json
# Markdown SHA-256:   71b0a6d30b45389887bb1527b2d136a07a810d60361052f9fbccff3c560fa6a6
# Code AST SHA-256:   5bee81d86c00529939ab166ecbbe302acb58c5f426778b5fb04fa7164f465018
# Verified Classes:   ResumptionGapError, ReplayCursor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ResumptionGapError(RuntimeError):
    """Raised when an SSE replay stream cannot be reconciled with client state."""


class ReplayCursor:
    def __init__(self, retention_seconds: int, reconnect_horizon_seconds: int):
        self.last_event_id: int | None = None
        self.retention = retention_seconds
        self.horizon = reconnect_horizon_seconds
        self.applied_progress: dict[str, int] = {}

    def commit_frame(self, event_id: int, payload: dict) -> None:
        # Commit cursor and payload atomically, at frame terminator.
        if self.last_event_id is not None and event_id <= self.last_event_id:
            # Redelivery: must be idempotent, not additive.
            self._apply_idempotent(payload)
            return
        self._apply_idempotent(payload)
        self.last_event_id = event_id

    def _apply_idempotent(self, payload: dict) -> None:
        token = payload.get("progressToken")
        if token is None:
            return
        value = payload.get("progress")
        if value is None:
            raise ResumptionGapError(f"progress event missing value for {token}")
        # Absolute assignment, not increment: redelivery is a no-op.
        self.applied_progress[token] = value

    def reconnect(self, server_last_id: int, server_retained_from: int) -> None:
        if self.retention < self.horizon:
            raise ResumptionGapError(
                f"server retention {self.retention}s < client horizon {self.horizon}s; "
                "Last-Event-ID replay is unsafe"
            )
        if self.last_event_id is not None and server_retained_from > self.last_event_id:
            raise ResumptionGapError(
                f"server retained log starts at {server_retained_from}, "
                f"client cursor {self.last_event_id} is beyond retention; gap of "
                f"{server_retained_from - self.last_event_id} events"
            )
        if server_last_id < (self.last_event_id or 0):
            raise ResumptionGapError(
                "server replay head is behind client cursor; server state regressed"
            )
