From 983bbd267460d7f52020ef6cb7eb975114e28dba Mon Sep 17 00:00:00 2001
From: Jakub Wartak <jakub.wartak@enterprisedb.com>
Date: Fri, 27 Nov 2026 14:15:26 +0100
Subject: [PATCH v27112026 2/3] 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 <jakub.wartak@enterprisedb.com>
Discussion:
---
 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

