From a268fab163d867decf24a93def07d2ce732c182e Mon Sep 17 00:00:00 2001
From: usernamedt <usernamedt@yandex-team.com>
Date: Tue, 17 Oct 2023 17:45:46 +0400
Subject: [PATCH] Cleanup old files if checkpoint is skipped

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

diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index c0e4ca5089..8d379cdd0d 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -6588,6 +6588,21 @@ CreateCheckPoint(int flags)
 			END_CRIT_SECTION();
 			ereport(DEBUG1,
 					(errmsg_internal("checkpoint skipped because system is idle")));
+
+			/*
+			 * We still might want to remove some old xlog files. For example,
+			 * if there was a temporary archiving problem so we could not remove
+			 * them at the previous checkpoint but now we can actually do that.
+			 */
+			XLByteToSeg(RedoRecPtr, _logSegNo, wal_segment_size);
+			_logSegNo--;
+			RemoveOldXlogFiles(_logSegNo, RedoRecPtr, last_important_lsn, ControlFile->checkPointCopy.ThisTimeLineID);
+
+			/*
+			 * Make more log segments if needed.  (Do this after recycling old log
+			 * segments, since that may supply some of the needed files.)
+			 */
+			PreallocXlogFiles(last_important_lsn, ControlFile->checkPointCopy.ThisTimeLineID);
 			return;
 		}
 	}
-- 
2.39.1

