From cf6ca022a224913c178d4997b694d58cd88f839a Mon Sep 17 00:00:00 2001
From: Kyotaro Horiguchi <horikyota.ntt@gmail.com>
Date: Thu, 20 Apr 2023 11:51:10 +0900
Subject: [PATCH] Fix incorrect calculation regarding max_slot_wal_keep_size

The calculation in KeepLogSeg related to max_slot_wal_keep_size can
result in unexpected behavior when replication advances quickly, and
the checkpointer is delayed just before removing WAL files.
---
 src/backend/access/transam/xlog.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 63481d826f..7bdd4d86b1 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -7463,8 +7463,11 @@ KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo)
 	{
 		XLByteToSeg(keep, segno, wal_segment_size);
 
-		/* Cap by max_slot_wal_keep_size ... */
-		if (max_slot_wal_keep_size_mb >= 0)
+		/*
+		 * Cap by max_slot_wal_keep_size. However this is not required if the
+		 * slots alredy won't protect any segments.
+		 */
+		if (max_slot_wal_keep_size_mb >= 0 && segno < currSegNo)
 		{
 			uint64		slot_keep_segs;
 
-- 
2.31.1

