From 6363dd3a6c96a2d7448532ada70631842b7f5d78 Mon Sep 17 00:00:00 2001
From: Soumya S Murali <soumyamurali.work@gmail.com>
Date: Wed, 17 Dec 2025 10:01:53 +0530
Subject: [PATCH] fix lock handling and LSN semantics in buffer flush helpers

Signed-off-by: Soumya S Murali <soumyamurali.work@gmail.com>
---
 src/backend/storage/buffer/bufmgr.c | 23 ++++++++++++-----------
 1 file changed, 12 insertions(+), 11 deletions(-)

diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index 2ea5311aed2..4a1a35a75f5 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -4405,7 +4405,7 @@ BufferNeedsWALFlush(BufferDesc *bufdesc, XLogRecPtr *lsn)
     UnlockBufHdr(bufdesc);
 
     /* Skip all WAL flush logic if relation is not logged */
-    if (!(*lsn != InvalidXLogRecPtr))
+    if (!XLogRecPtrIsValid(*lsn))
         return false;
 
     /* Must flush WAL up to this LSN before writing the page */
@@ -4433,6 +4433,12 @@ CleanVictimBuffer(BufferDesc *bufdesc, bool from_ring, IOContext io_context)
     content_lock = BufHdrGetContentLock(bufdesc);
     LWLockAcquire(content_lock, LW_SHARED);
 
+	if (!PrepareFlushBuffer(bufdesc, &max_lsn))
+    {
+        LWLockRelease(content_lock);
+        return;
+    }
+
     /*
      * Now the buffer is a valid flush target.
      * Switch to exclusive lock for checksum + IO preparation.
@@ -4440,19 +4446,14 @@ CleanVictimBuffer(BufferDesc *bufdesc, bool from_ring, IOContext io_context)
     LWLockRelease(content_lock);
     LWLockAcquire(content_lock, LW_EXCLUSIVE);
 
-    /*
-     * Mark the buffer ready for checksum and write.
-     */
-    PrepareBufferForCheckpoint(bufdesc, &max_lsn);
+	if (!PrepareFlushBuffer(bufdesc, &max_lsn))
+    {
+        LWLockRelease(content_lock);
+        return;
+    }
 
     /* Release exclusive lock; the batch will write the page later */
     LWLockRelease(content_lock);
-
-    /*
-     * Add LSN to caller's batch tracking.
-     * Caller handles XLogFlush() using highest LSN.
-     */
-    PrepareBufferForCheckpoint(bufdesc, max_lsn);
 }
 
 /*
-- 
2.34.1

