From 463e8616f4274be54f680597c26f054811396699 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 v2] 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 | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c
index 63481d826f..bda859c299 100644
--- a/src/backend/access/transam/xlog.c
+++ b/src/backend/access/transam/xlog.c
@@ -7463,6 +7463,14 @@ KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo)
 	{
 		XLByteToSeg(keep, segno, wal_segment_size);
 
+		/*
+		 * Slot minimum LSN could be greater than recptr. In such cases, no
+		 * segments are protected by slots but we still need to keep segno in a
+		 * reasonable range for subsequent calculations to avoid underflow.
+		 */
+		if (segno > currSegNo)
+			segno = currSegNo;
+
 		/* Cap by max_slot_wal_keep_size ... */
 		if (max_slot_wal_keep_size_mb >= 0)
 		{
-- 
2.31.1

