On Mon, Nov 30, 2026 at 2:50 PM Xuneng Zhou <[email protected]> wrote:
>
> > > > Other interesting thing (not pursued covered in patch) is perhaps why do
> > > > we even check for the WaitLSNWakeups() in case of doing pure (closed) 
> > > > crash
> > > > recovery (when DB is inaccessible, way before anything could issue 
> > > > register
> > > > to be waiting for anything)?
>
> I think we can skip the check for crash recovery. Also noted this
> optimization earlier, but it slipped through my to-dos after
> prioritizing bug fixes before the release. Please feel free to do a
> patch if you want. I'll look at it.

Ok, done that under 0004, I hope I got right flags there.

> > > Thanks for your observation. This has been raised and disussed before,
> > > but not tackled yet [1][2]. I think we also need to move the new
> > > helper inside ApplyWalRecord() as Heikki suggested.
> > >
> > > [1] 
> > > https://www.postgresql.org/message-id/CAPpHfdvu7bPzP1p3eZW3t6QgF39stTce=oyobyn6n2j+zc5...@mail.gmail.com
> > > [2] 
> > > https://www.postgresql.org/message-id/CABPTF7UkddAnG=6x0jlheovwo-xog3xyxgc1uwhbjj5ehrj...@mail.gmail.com
> >
> > Hi Xuneng,
> >
> > thanks for Your's work on WAIT FOR LSN. I wasn't aware of this subthread,
> > which is my fault as I could search for it first :) -- instead I've just 
> > tried
> > simplest optimization as fun experiment (2-4% is not nothing). Anyway I was
> > just tresspasing this code and happened to notice this stuff accidently, and
> > I don't have urge to fix it the most optimal way: so the question is do you
> > want to carry on with longer term plans to of using "hierarchy idea" [2] or
> > not? (I could just help to bench it there)
>
> No worry at all. Thanks for your quest! If you hadn't raised them, I
> would've almost forgotten these potential improvements. Guess this is
> the charm of open source :).

:)

> > Or maybe we could just to stick Heikki's suggested way [1] that once it's
> > after directly after SpinLockRelase() we could even get rid of this memory
> > barrier totally(?), but the earlier commit a80a593ab6 / [3] make me feel
> > hacking around this is preeeety risky thing, especially as I do not have
> > reodering CPUs at a hand to test it, but that should be OK (?)
>
> Back then, I was worried about this possible interleaving:
>
> > Without the barrier in WaitLSNWakeup(), this interleaving is possible:
> >
> > Initial:
> >   minWaitedLSN = PG_UINT64_MAX
> >   replayLSN = 90
> >
> > Waiter:
> >   stores minWaitedLSN = 100
> >   reads replayLSN before the waker publishes the new replay position
> >   sees replayLSN = 90
> >   decides it should sleep
> >
> > Waker:
> >   publishes replayLSN = 100
> >   reads old minWaitedLSN = PG_UINT64_MAX
> >   skips the wakeup
>
> However, after thought more, this lost wakeup seems unlikely to occur
> because of the synchronization of info_lck. The waiter need to acquire
> info_lck to get the replayLSN to determine whether it needs sleep,
> which happens after registering its minWaitedLS; and the startup need
> to hold the info_lck to publish its progress. So the of publication of
> replayLSN implies its acquire & release of the info_lck, which means
> that the waiter has already released that lock and published its
> minWaitedLSN. In this sense, it seems that we don't a barrier for the
> need of guaranting that the waker's position store becomes globally
> visible before its subsequent minWaitedLSN read. That said, I'm still
> lean toward keeping it for the sake of explicitness. If the above
> reasoning holds, the current safety relies on the getter and
> pubilsher's use of the info_lck and the specific ordering of code of
> lsn registeration and checking, which seems somewhat frigile to me. If
> that change, especially siliently, the issue could be hard to diagnose
> and reason about.

OK I see, it's risky to me too, but then this sounds like we can leave
everything mostly as it was in the 0003 patch and we do not need to move
it to ApplyWalRecord() - as on 2nd second look to me to me that if we are
not doing this optimization by Heikki, having it explictly in the "main
redo loop" makes a lot of sense - mainly: feature code visibliity in top
code section, so I've left it as it was.

So re-sending the full patchset and including the new 0004. Thanks!

-J.
From e77729f1b3363d528c936e17e804176d447ef115 Mon Sep 17 00:00:00 2001
From: Jakub Wartak <[email protected]>
Date: Fri, 27 Nov 2026 14:15:12 +0100
Subject: [PATCH v02122026 1/4] Avoid redundant smgropen() in
 XLogReadBufferExtended()

XLogReadBufferExtended() today performs smgropen()/smgrcreate() and few lines
later calls ReadBufferWithoutRelcache() which again calls smgropen() that
performs the same hash table lookup calculation again.

Add ReadBufferWithoutRelcacheSmgr() to optimize that and avoid second hash
table lookup for every block read during WAL replay.

Author: Jakub Wartak <[email protected]>
Discussion: https://postgr.es/m/CAKZiRmzEs%2BS60pW_gbjBjSrRYLKfKRf08dTcmN-7%2Bqh8aDFPsw%40mail.gmail.com
---
 src/backend/access/transam/xlogutils.c |  4 ++--
 src/backend/storage/buffer/bufmgr.c    | 13 +++++++++++++
 src/include/storage/bufmgr.h           |  4 ++++
 3 files changed, 19 insertions(+), 2 deletions(-)

diff --git a/src/backend/access/transam/xlogutils.c b/src/backend/access/transam/xlogutils.c
index ff71e14015d..551c4c30769 100644
--- a/src/backend/access/transam/xlogutils.c
+++ b/src/backend/access/transam/xlogutils.c
@@ -518,8 +518,8 @@ XLogReadBufferExtended(RelFileLocator rlocator, ForkNumber forknum,
 	if (blkno < lastblock)
 	{
 		/* page exists in file */
-		buffer = ReadBufferWithoutRelcache(rlocator, forknum, blkno,
-										   mode, NULL, true);
+		buffer = ReadBufferWithoutRelcacheSmgr(smgr, forknum, blkno,
+											   mode, NULL, true);
 	}
 	else
 	{
diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c
index c17fc3590f0..ff0544cbe67 100644
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -959,6 +959,19 @@ ReadBufferWithoutRelcache(RelFileLocator rlocator, ForkNumber forkNum,
 {
 	SMgrRelation smgr = smgropen(rlocator, INVALID_PROC_NUMBER);
 
+	return ReadBufferWithoutRelcacheSmgr(smgr, forkNum, blockNum,
+										 mode, strategy, permanent);
+}
+
+/*
+ * ReadBufferWithoutRelcacheSmgr -- like ReadBufferWithoutRelcache, but
+ *		save smgropen() hash lookup.
+ */
+Buffer
+ReadBufferWithoutRelcacheSmgr(SMgrRelation smgr, ForkNumber forkNum,
+							  BlockNumber blockNum, ReadBufferMode mode,
+							  BufferAccessStrategy strategy, bool permanent)
+{
 	return ReadBuffer_common(NULL, smgr,
 							 permanent ? RELPERSISTENCE_PERMANENT : RELPERSISTENCE_UNLOGGED,
 							 forkNum, blockNum,
diff --git a/src/include/storage/bufmgr.h b/src/include/storage/bufmgr.h
index 6837b35fc6d..1d05afcac9b 100644
--- a/src/include/storage/bufmgr.h
+++ b/src/include/storage/bufmgr.h
@@ -241,6 +241,10 @@ extern Buffer ReadBufferWithoutRelcache(RelFileLocator rlocator,
 										ForkNumber forkNum, BlockNumber blockNum,
 										ReadBufferMode mode, BufferAccessStrategy strategy,
 										bool permanent);
+extern Buffer ReadBufferWithoutRelcacheSmgr(SMgrRelation smgr,
+											ForkNumber forkNum, BlockNumber blockNum,
+											ReadBufferMode mode, BufferAccessStrategy strategy,
+											bool permanent);
 
 extern bool StartReadBuffer(ReadBuffersOperation *operation,
 							Buffer *buffer,
-- 
2.43.0

From 0505a0f13768d5485e90639163a65dd43a3bbb70 Mon Sep 17 00:00:00 2001
From: Jakub Wartak <[email protected]>
Date: Fri, 27 Nov 2026 14:15:26 +0100
Subject: [PATCH v02122026 2/4] Cache the most recently opened relation in
 smgropen()

Cache the SMgrRelation returned by the previous call of smgropen() and return
it directly if the next call asks for the same relation and same backend.

Author: Jakub Wartak <[email protected]>
Reviewed-by:
Discussion: https://postgr.es/m/CAKZiRmzEs%2BS60pW_gbjBjSrRYLKfKRf08dTcmN-7%2Bqh8aDFPsw%40mail.gmail.com
---
 src/backend/storage/smgr/smgr.c | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)

diff --git a/src/backend/storage/smgr/smgr.c b/src/backend/storage/smgr/smgr.c
index 5391640d861..34e65059d20 100644
--- a/src/backend/storage/smgr/smgr.c
+++ b/src/backend/storage/smgr/smgr.c
@@ -159,6 +159,12 @@ static const int NSmgr = lengthof(smgrsw);
  */
 static HTAB *SMgrRelationHash = NULL;
 
+/*
+ * The SMgrRelation cache. WAL replay tends to open the same relation quite
+ * frequently, so caching this avoids lots of smgr hash table lookups.
+ */
+static SMgrRelation smgr_last_opened_cache = NULL;
+
 static dlist_head unpinned_relns;
 
 /* local function prototypes */
@@ -245,6 +251,12 @@ smgropen(RelFileLocator rlocator, ProcNumber backend)
 
 	Assert(RelFileNumberIsValid(rlocator.relNumber));
 
+	/* Fast path smgr cache: is it the same relation as last time? */
+	if (smgr_last_opened_cache != NULL &&
+		RelFileLocatorEquals(smgr_last_opened_cache->smgr_rlocator.locator, rlocator) &&
+		smgr_last_opened_cache->smgr_rlocator.backend == backend)
+		return smgr_last_opened_cache;
+
 	HOLD_INTERRUPTS();
 
 	if (SMgrRelationHash == NULL)
@@ -283,6 +295,9 @@ smgropen(RelFileLocator rlocator, ProcNumber backend)
 		smgrsw[reln->smgr_which].smgr_open(reln);
 	}
 
+	/* Fast path smgr cache: set */
+	smgr_last_opened_cache = reln;
+
 	RESUME_INTERRUPTS();
 
 	return reln;
@@ -333,6 +348,10 @@ smgrdestroy(SMgrRelation reln)
 
 	dlist_delete(&reln->node);
 
+	/* Fast path smgr cache: reset */
+	if (smgr_last_opened_cache == reln)
+		smgr_last_opened_cache = NULL;
+
 	if (hash_search(SMgrRelationHash,
 					&(reln->smgr_rlocator),
 					HASH_REMOVE, NULL) == NULL)
-- 
2.43.0

From 94817d93be7dec98125f1c66385472f7dfe23180 Mon Sep 17 00:00:00 2001
From: Jakub Wartak <[email protected]>
Date: Wed, 2 Dec 2026 09:04:20 +0100
Subject: [PATCH v02122026 4/4] WAIT FOR LSN: avoid WaitLSNWakeupStandby()
 during crash-recovery

Avoid memory barrier and reading of three atomics in the main redo loop if
there cannot be potential WAIT FOR LSN backends as hot standby database did
no open yet.

Author: Jakub Wartak <[email protected]>
Reviewed-by: Xuneng Zhou <[email protected]>
Discussion: https://postgr.es/m/CAKZiRmzEs%2BS60pW_gbjBjSrRYLKfKRf08dTcmN-7%2Bqh8aDFPsw%40mail.gmail.com
---
 src/backend/access/transam/xlogrecovery.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 4e0c03af07d..58382e290f0 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -1808,8 +1808,13 @@ PerformWalRecovery(void)
 			 * LSN to reach current replay position.  Replay implies that the
 			 * WAL was already written and flushed to disk, so write and flush
 			 * waiters can be woken at the replay position too.
+			 *
+			 * Optimize this out during plain crash recovery: backends can connect
+			 * and issue WAIT FOR LSN only after consistency point has been reached
+			 * and hot standby has opened.
 			 */
-			WaitLSNWakeupStandby(XLogRecoveryCtl->lastReplayedEndRecPtr);
+			if (InArchiveRecovery && LocalHotStandbyActive)
+				WaitLSNWakeupStandby(XLogRecoveryCtl->lastReplayedEndRecPtr);
 
 			/* Exit loop if we reached inclusive recovery target */
 			if (recoveryStopsAfter(xlogreader))
-- 
2.43.0

From 12420db2dfcf81911b4e00c1a038e500929cbfcf Mon Sep 17 00:00:00 2001
From: Jakub Wartak <[email protected]>
Date: Fri, 27 Nov 2026 14:15:30 +0100
Subject: [PATCH v02122026 3/4] WAIT FOR LSN: reduce per record overhead during
 WAL replay

Replace the three separate WaitLSNWakeup() calls during WAL replay with single
WaitLSNWakeupStandby() which does a just single memory barrier (e.g. x86 "lock"
instruction) followed by plain reads of the three minWaitedLSN values.

Author: Jakub Wartak <[email protected]>
Reviewed-by: Xuneng Zhou <[email protected]>
Discussion: https://postgr.es/m/CAKZiRmzEs%2BS60pW_gbjBjSrRYLKfKRf08dTcmN-7%2Bqh8aDFPsw%40mail.gmail.com
---
 src/backend/access/transam/xlogrecovery.c |  7 +-----
 src/backend/access/transam/xlogwait.c     | 26 +++++++++++++++++++++++
 src/include/access/xlogwait.h             |  1 +
 3 files changed, 28 insertions(+), 6 deletions(-)

diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index e091a3e178b..4e0c03af07d 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -1809,12 +1809,7 @@ PerformWalRecovery(void)
 			 * WAL was already written and flushed to disk, so write and flush
 			 * waiters can be woken at the replay position too.
 			 */
-			WaitLSNWakeup(WAIT_LSN_TYPE_STANDBY_REPLAY,
-						  XLogRecoveryCtl->lastReplayedEndRecPtr);
-			WaitLSNWakeup(WAIT_LSN_TYPE_STANDBY_WRITE,
-						  XLogRecoveryCtl->lastReplayedEndRecPtr);
-			WaitLSNWakeup(WAIT_LSN_TYPE_STANDBY_FLUSH,
-						  XLogRecoveryCtl->lastReplayedEndRecPtr);
+			WaitLSNWakeupStandby(XLogRecoveryCtl->lastReplayedEndRecPtr);
 
 			/* Exit loop if we reached inclusive recovery target */
 			if (recoveryStopsAfter(xlogreader))
diff --git a/src/backend/access/transam/xlogwait.c b/src/backend/access/transam/xlogwait.c
index 7170921ecdf..855fea3780f 100644
--- a/src/backend/access/transam/xlogwait.c
+++ b/src/backend/access/transam/xlogwait.c
@@ -376,6 +376,32 @@ WaitLSNWakeup(WaitLSNType lsnType, XLogRecPtr currentLSN)
 	wakeupWaiters(lsnType, currentLSN);
 }
 
+/*
+ * Wake up the all the standby replay, write and flush waiters for currentLSN.
+ *
+ * Speedy variant: use just single memory barrier for read (e.g. single "lock"
+ * x86 instruction) rather than three as it would happen with three
+ * (WAIT_LSN_TYPE_COUNT) separate WaitLSNWakeup() calls.
+ */
+void
+WaitLSNWakeupStandby(XLogRecPtr currentLSN)
+{
+	if (!XLogRecPtrIsValid(currentLSN))
+		return;
+
+	/* Pairs with pg_atomic_write_membarrier_u64() in updateMinWaitedLSN(). */
+	pg_memory_barrier();
+
+	if (pg_atomic_read_u64(&waitLSNState->minWaitedLSN[WAIT_LSN_TYPE_STANDBY_REPLAY]) <= currentLSN)
+		wakeupWaiters(WAIT_LSN_TYPE_STANDBY_REPLAY, currentLSN);
+
+	if (pg_atomic_read_u64(&waitLSNState->minWaitedLSN[WAIT_LSN_TYPE_STANDBY_WRITE]) <= currentLSN)
+		wakeupWaiters(WAIT_LSN_TYPE_STANDBY_WRITE, currentLSN);
+
+	if (pg_atomic_read_u64(&waitLSNState->minWaitedLSN[WAIT_LSN_TYPE_STANDBY_FLUSH]) <= currentLSN)
+		wakeupWaiters(WAIT_LSN_TYPE_STANDBY_FLUSH, currentLSN);
+}
+
 /*
  * Clean up any LSN wait state for the current process.
  */
diff --git a/src/include/access/xlogwait.h b/src/include/access/xlogwait.h
index 2bf0263e9e2..1f9862f5a69 100644
--- a/src/include/access/xlogwait.h
+++ b/src/include/access/xlogwait.h
@@ -102,6 +102,7 @@ extern PGDLLIMPORT WaitLSNState *waitLSNState;
 
 extern XLogRecPtr GetCurrentLSNForWaitType(WaitLSNType lsnType);
 extern void WaitLSNWakeup(WaitLSNType lsnType, XLogRecPtr currentLSN);
+extern void WaitLSNWakeupStandby(XLogRecPtr currentLSN);
 extern void WaitLSNCleanup(void);
 extern WaitLSNResult WaitForLSN(WaitLSNType lsnType, XLogRecPtr targetLSN,
 								int timeout);
-- 
2.43.0

Reply via email to