From df2f3717800f012b2f0a234c69b92ae0c2bb8edc Mon Sep 17 00:00:00 2001
From: David Geier <geidav.pg@gmail.com>
Date: Fri, 18 Sep 2026 12:52:47 +0200
Subject: [PATCH v6 1/7] Assert CacheMemoryContext exists in relcache callers

RelationCacheInitialize() creates CacheMemoryContext before catalog
or relcache access can occur. Replace defensive creation in later
code paths with assertions so calls made before relcache initialization
fail immediately in assertion-enabled builds.
---
 src/backend/utils/cache/relcache.c | 10 +++-------
 1 file changed, 3 insertions(+), 7 deletions(-)

diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c
index d8f04a05309..a04e8a7fa93 100644
--- a/src/backend/utils/cache/relcache.c
+++ b/src/backend/utils/cache/relcache.c
@@ -1671,15 +1671,13 @@ LookupOpclassInfo(Oid operatorClassOid,
 	HeapTuple	htup;
 	bool		indexOK;
 
+	Assert(CacheMemoryContext != NULL);
+
 	if (OpClassCache == NULL)
 	{
 		/* First time through: initialize the opclass cache */
 		HASHCTL		ctl;
 
-		/* Also make sure CacheMemoryContext exists */
-		if (!CacheMemoryContext)
-			CreateCacheMemoryContext();
-
 		ctl.keysize = sizeof(Oid);
 		ctl.entrysize = sizeof(OpClassCacheEnt);
 		OpClassCache = hash_create("Operator class cache", 64,
@@ -3561,13 +3559,11 @@ RelationBuildLocalRelation(const char *relname,
 
 	/* Shared relations had better be mapped, too */
 	Assert(mapped_relation || !shared_relation);
+	Assert(CacheMemoryContext != NULL);
 
 	/*
 	 * switch to the cache context to create the relcache entry.
 	 */
-	if (!CacheMemoryContext)
-		CreateCacheMemoryContext();
-
 	oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
 
 	/*
-- 
2.53.0

