From 9df3700bf0152c44e232755137c4681fd2c72e50 Mon Sep 17 00:00:00 2001
From: Japin Li <japinli@hotmail.com>
Date: Tue, 15 Jul 2025 13:58:53 +0800
Subject: [PATCH] Allow the walsender to retrieve WALs from the archive

---
 src/backend/access/transam/xlogarchive.c |  4 ++--
 src/backend/replication/walsender.c      | 10 ++++++++++
 2 files changed, 12 insertions(+), 2 deletions(-)

diff --git a/src/backend/access/transam/xlogarchive.c b/src/backend/access/transam/xlogarchive.c
index 1ef1713c91a..fe932c11f44 100644
--- a/src/backend/access/transam/xlogarchive.c
+++ b/src/backend/access/transam/xlogarchive.c
@@ -66,9 +66,9 @@ RestoreArchivedFile(char *path, const char *xlogfname,
 
 	/*
 	 * Ignore restore_command when not in archive recovery (meaning we are in
-	 * crash recovery).
+	 * crash recovery) and non-walsender processes.
 	 */
-	if (!ArchiveRecoveryRequested)
+	if (!ArchiveRecoveryRequested && !am_walsender)
 		goto not_available;
 
 	/* In standby mode, restore_command might not be supplied */
diff --git a/src/backend/replication/walsender.c b/src/backend/replication/walsender.c
index 28b8591efa5..438b5d27a32 100644
--- a/src/backend/replication/walsender.c
+++ b/src/backend/replication/walsender.c
@@ -53,6 +53,7 @@
 #include "access/transam.h"
 #include "access/xact.h"
 #include "access/xlog_internal.h"
+#include "access/xlogarchive.h"
 #include "access/xlogreader.h"
 #include "access/xlogrecovery.h"
 #include "access/xlogutils.h"
@@ -3068,6 +3069,15 @@ WalSndSegmentOpen(XLogReaderState *state, XLogSegNo nextSegNo,
 		int			save_errno = errno;
 
 		XLogFileName(xlogfname, *tli_p, nextSegNo, wal_segment_size);
+
+		/* Restore WALs from archive if not found in XLOGDIR. */
+		if (RestoreArchivedFile(path, xlogfname, xlogfname, wal_segment_size, false))
+		{
+			state->seg.ws_file = BasicOpenFile(path, O_RDONLY | PG_BINARY);
+			if (state->seg.ws_file >= 0)
+				return;
+		}
+
 		errno = save_errno;
 		ereport(ERROR,
 				(errcode_for_file_access(),
-- 
2.43.0

