From fa88e2cecd33dfcd8800c89b183fa99b46037e7e Mon Sep 17 00:00:00 2001
From: Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Date: Sat, 4 Mar 2023 04:15:04 +0000
Subject: [PATCH v1] Clarify XLogFileReadAnyTLI()'s behaviour for XLOG_FROM_ANY

---
 src/backend/access/transam/xlogrecovery.c | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index dbe9394762..c5bc295fdb 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -4165,6 +4165,16 @@ XLogFileRead(XLogSegNo segno, int emode, TimeLineID tli,
  * Open a logfile segment for reading (during recovery).
  *
  * This version searches for the segment with any TLI listed in expectedTLEs.
+ *
+ * When source == XLOG_FROM_ANY, this function first searches for the segment
+ * with a TLI in archive first, if not found, it searches in pg_wal. This way,
+ * if there is a WAL segment with same passed-in segno but different TLI
+ * present in both the archive and pg_wal, it prefers the one with higher TLI.
+ * The reason for this is that if for example we try to do archive recovery to
+ * timeline 2, which branched off timeline 1, but the WAL for timeline 2 is not
+ * archived yet, we would replay past the timeline switch point on timeline 1
+ * using the archived WAL segment, before even looking timeline 2's WAL
+ * segments in pg_wal.
  */
 static int
 XLogFileReadAnyTLI(XLogSegNo segno, int emode, XLogSource source)
-- 
2.34.1

