From 7e552c4364f47129b05a17d374dfce0608d4559f Mon Sep 17 00:00:00 2001
From: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Date: Mon, 17 Aug 2026 22:12:29 +0530
Subject: [PATCH v20260817] BgBufferSync refactor reusable_buffers increment

reusable_buffers gets incremented when sync_state has BUF_WRITTEN set or
when it as BUF_REUSABLE set. The way code is written it feels like that
resuable_buffers is incremented even when the buffer is not reusable but
written. The feeling is not true. If BUF_WRITTEN is set by
SyncOneBuffer(), BUF_REUSABLE should have been set since the function is
called with skip_recently_used = true, which instructs it to only write
buffers which are reusable. Rearrange the code so as to avoid the
confusion.

Author: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Reviewed-by: Xuneng Zhou <xunengzhou@gmail.com>
Discussion: https://www.postgresql.org/message-id/CAMCWMe1dgsT0qzVL9TufPy%3DXBF1j1gd76VLysR7fF5J4hP1E-g%40mail.gmail.com
---
 src/backend/storage/buffer/bufmgr.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)

diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index 17f142e4c5b..52d90c82301 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -4083,17 +4083,23 @@ BgBufferSync(WritebackContext *wb_context)
 		}
 		num_to_scan--;
 
+		if (sync_state & BUF_REUSABLE)
+			reusable_buffers++;
+
 		if (sync_state & BUF_WRITTEN)
 		{
-			reusable_buffers++;
+			/*
+			 * We instructed SyncOneBuffer not to write a recently used
+			 * buffer.
+			 */
+			Assert(sync_state & BUF_REUSABLE);
+
 			if (++num_written >= bgwriter_lru_maxpages)
 			{
 				PendingBgWriterStats.maxwritten_clean++;
 				break;
 			}
 		}
-		else if (sync_state & BUF_REUSABLE)
-			reusable_buffers++;
 	}
 
 	PendingBgWriterStats.buf_written_clean += num_written;

base-commit: 51c43a5dbd86ad8461544e54c00bd9f487abfacd
-- 
2.34.1

