diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 430a38b1a21..2cc37ef0c5b 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -5262,7 +5262,7 @@ str_time(pg_time_t tnow, char *buf, size_t bufsize)
 /*
  * Initialize the first WAL segment on new timeline.
  */
-static void
+void
 XLogInitNewTimeline(TimeLineID endTLI, XLogRecPtr endOfLog, TimeLineID newTLI)
 {
 	char		xlogfname[MAXFNAMELEN];
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 38b594d2170..33da9d68e5c 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -4235,6 +4235,10 @@ rescanLatestTimeLine(TimeLineID replayTLI, XLogRecPtr replayLSN)
 	list_free_deep(expectedTLEs);
 	expectedTLEs = newExpectedTLEs;
 
+	SetInstallXLogFileSegmentActive();
+	XLogInitNewTimeline(oldtarget, replayLSN, newtarget);
+	ResetInstallXLogFileSegmentActive();
+
 	/*
 	 * As in StartupXLOG(), try to ensure we have all the history files
 	 * between the old target and new target in pg_wal.
diff --git a/src/include/access/xlog.h b/src/include/access/xlog.h
index 605280ed8fb..87cd59d74b9 100644
--- a/src/include/access/xlog.h
+++ b/src/include/access/xlog.h
@@ -210,6 +210,9 @@ extern bool XLogNeedsFlush(XLogRecPtr record);
 extern int	XLogFileInit(XLogSegNo logsegno, TimeLineID logtli);
 extern int	XLogFileOpen(XLogSegNo segno, TimeLineID tli);
 
+extern void XLogInitNewTimeline(TimeLineID endTLI, XLogRecPtr endOfLog,
+								TimeLineID newTLI);
+
 extern void CheckXLogRemoved(XLogSegNo segno, TimeLineID tli);
 extern XLogSegNo XLogGetLastRemovedSegno(void);
 extern XLogSegNo XLogGetOldestSegno(TimeLineID tli);
