From 085753f24c0fce71464f0b5e67049c1c7f9c8baa Mon Sep 17 00:00:00 2001
From: Hayato Kuroda <kuroda.hayato@fujitsu.com>
Date: Sun, 29 Oct 2023 04:32:53 +0000
Subject: [PATCH] Retry stat() and lstat() even in get_dirent_type()

---
 src/common/file_utils.c | 13 ++++++++++++-
 src/include/port.h      |  1 +
 src/port/dirmod.c       |  2 +-
 3 files changed, 14 insertions(+), 2 deletions(-)

diff --git a/src/common/file_utils.c b/src/common/file_utils.c
index abe5129412..704a269406 100644
--- a/src/common/file_utils.c
+++ b/src/common/file_utils.c
@@ -552,8 +552,9 @@ get_dirent_type(const char *path,
 	{
 		struct stat fst;
 		int			sret;
+		int			count = 0;
 
-
+retry:
 		if (look_through_symlinks)
 			sret = stat(path, &fst);
 		else
@@ -561,6 +562,16 @@ get_dirent_type(const char *path,
 
 		if (sret < 0)
 		{
+#if defined(WIN32) || defined(__CYGWIN__)
+			/* Retry is STATUS_DELETE_PENDING error.  Timeout after 10 sec. */
+			if (lstat_error_was_status_delete_pending() &&
+				++count <= 100)
+			{
+				pg_usleep(100000);		/* us */
+				goto retry;
+			}
+#endif
+
 			result = PGFILETYPE_ERROR;
 #ifdef FRONTEND
 			pg_log_generic(elevel, PG_LOG_PRIMARY, "could not stat file \"%s\": %m", path);
diff --git a/src/include/port.h b/src/include/port.h
index 5979139ebc..0ffa9f802e 100644
--- a/src/include/port.h
+++ b/src/include/port.h
@@ -275,6 +275,7 @@ extern int	pclose_check(FILE *stream);
  */
 extern int	pgrename(const char *from, const char *to);
 extern int	pgunlink(const char *path);
+extern bool lstat_error_was_status_delete_pending(void);
 
 /* Include this first so later includes don't see these defines */
 #ifdef _MSC_VER
diff --git a/src/port/dirmod.c b/src/port/dirmod.c
index 07dd190cbc..3db1a0f3d1 100644
--- a/src/port/dirmod.c
+++ b/src/port/dirmod.c
@@ -100,7 +100,7 @@ pgrename(const char *from, const char *to)
  * This doesn't apply to Cygwin, which has its own lstat() that would report
  * the case as EACCES.
 */
-static bool
+bool
 lstat_error_was_status_delete_pending(void)
 {
 	if (errno != ENOENT)
-- 
2.27.0

