diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c
index 94be62fa6e..791afcae4a 100644
--- a/src/backend/storage/file/fd.c
+++ b/src/backend/storage/file/fd.c
@@ -330,6 +330,28 @@ static int	fsync_parent_path(const char *fname, int elevel);
 int
 pg_fsync(int fd)
 {
+#ifdef USE_ASSERT_CHECKING
+	struct stat st;
+
+	/*
+	 * On some operating systems fsyncing a file requires O_RDWR, and
+	 * a directory requires O_RDONLY.  Ignore any errors.
+	 */
+	if (fstat(fd, &st) == 0)
+	{
+		int		desc_flags = fcntl(fd, F_GETFL);
+
+		/*
+		 * O_RDONLY is historically 0, so just make sure that for
+		 * directories no write flags are used.
+		 */
+		if (!S_ISDIR(st.st_mode))
+			Assert((desc_flags & (O_RDWR | O_WRONLY)) != 0);
+		else
+			Assert((desc_flags & (O_RDWR | O_WRONLY)) == 0);
+	}
+#endif
+
 	/* #if is to skip the sync_method test if there's no need for it */
 #if defined(HAVE_FSYNC_WRITETHROUGH) && !defined(FSYNC_WRITETHROUGH_IS_FSYNC)
 	if (sync_method == SYNC_METHOD_FSYNC_WRITETHROUGH)
