From f4f64eeb577cb469941b0a4dc0b9cf8d29147b36 Mon Sep 17 00:00:00 2001
From: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Date: Tue, 21 Jul 2026 16:16:48 +0530
Subject: [PATCH v20260724 1/7] Add BgBufferSync sanity Asserts

Assert that BgBufferSync() is only ever invoked from the background
writer process, matching the actual caller in BackgroundWriterMain.

Also move the existing Assert(strategy_delta >= 0) to the end of the
enclosing block so that the surrounding elog(DEBUG2) messages get a
chance to reach the server log before the Assert fires, easing diagnosis
if the Assert ever fails.

Author: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
---
 src/backend/storage/buffer/bufmgr.c | 15 +++++++++++++--
 1 file changed, 13 insertions(+), 2 deletions(-)

diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index 3908529872a..3eea17115b5 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -3894,6 +3894,8 @@ BgBufferSync(WritebackContext *wb_context)
 	long		new_strategy_delta;
 	uint32		new_recent_alloc;
 
+	Assert(AmBackgroundWriterProcess());
+
 	/*
 	 * Find out where the clock-sweep currently is, and how many buffer
 	 * allocations have happened since our last call.
@@ -3929,8 +3931,6 @@ BgBufferSync(WritebackContext *wb_context)
 		strategy_delta = strategy_buf_id - prev_strategy_buf_id;
 		strategy_delta += (long) passes_delta * NBuffers;
 
-		Assert(strategy_delta >= 0);
-
 		if ((int32) (next_passes - strategy_passes) > 0)
 		{
 			/* we're one pass ahead of the strategy point */
@@ -3970,6 +3970,17 @@ BgBufferSync(WritebackContext *wb_context)
 			next_passes = strategy_passes;
 			bufs_to_lap = NBuffers;
 		}
+
+		/*
+		 * We do not expect the current strategy point to be behind the
+		 * previous one.
+		 *
+		 * If this Assert fails, we would have the debug messages printed in
+		 * the server error log at appropriate debug level. Hence Asserting
+		 * here provides minor convenience compared to Asserting right after
+		 * calculating the difference.
+		 */
+		Assert(strategy_delta >= 0);
 	}
 	else
 	{

base-commit: b77868f169adcdf31edbc80d8a875204ed7ba191
-- 
2.34.1

