From e32598094e3dea2f0b912e0ed98dda0ec25160ef 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 v7 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 ad8aee8447c..039750c7615 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,
@@ -3562,13 +3560,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

