From cc1ca23fc1bade60d4c42a364e5ebfe13977eb40 Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Tue, 25 Aug 2026 19:05:39 +0300
Subject: [PATCH v2 2/3] Track which shmem areas have been fully initialized

If SHMEM_CALLBACKS_ALLOW_AFTER_STARTUP is used to allocate shared
memory after startup, but the initialization fails half-way through,
the shmem area is left in an indeterminate state.  Furthermore, if
multiple shmem areas are registered in one RegisterShmemCallbacks()
call, some might be allocated while others are not.

This commit adds an explicit 'initialized' flag to each shmem area.
We still leave behind an uninitialized area on error, but at least
they are now clearly marked, and you get a slightly nicer error
message if you try to re-register them.  It'd be nice to clean up more
thoroughly and support actually retrying the allocations, but in
practice, the most likely reason for a shmem allocation or
initialization to fail is that you are out of shared memory and
retrying wouldn't help with that.

This isn't exactly a new problem, the old ShmemInitStruct() interface
had similar issues if the initialization code failed, or if you
allocated multiple structs and some allocations failed.  It was just
left to the calling code to deal with it.

Author: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Reviewed-by: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Discussion: https://www.postgresql.org/message-id/CAJTYsWVRRWH48=PcuAo_2Y4Ap6M0QRmzxgUfFkNRtdWK74LjBQ@mail.gmail.com
Backpatch-through: 19
---
 doc/src/sgml/xfunc.sgml         |  5 ++-
 src/backend/storage/ipc/shmem.c | 67 ++++++++++++++++++++++++++++++---
 2 files changed, 66 insertions(+), 6 deletions(-)

diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml
index 97f3cb625e2..a90dba0662f 100644
--- a/doc/src/sgml/xfunc.sgml
+++ b/doc/src/sgml/xfunc.sgml
@@ -3740,7 +3740,10 @@ my_shmem_init(void *arg)
       on whether the requested memory areas were already initialized by
       another backend. The callbacks will be called while holding an internal
       lock (ShmemIndexLock), which prevents the race condition of two backends
-      trying to initialize the memory area at the same time.
+      trying to initialize the memory area at the same time.  If the
+      allocation or initialization fails for any reason, the shared memory
+      areas are left in an abandoned state and any attempt to attach or
+      re-initialize them will fail until the server is restarted.
      </para>
     </sect3>
 
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 0fadbf85a02..c511395b1f0 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -144,6 +144,8 @@
 #include "utils/builtins.h"
 #include "utils/tuplestore.h"
 
+typedef struct ShmemIndexEnt ShmemIndexEnt;
+
 /*
  * Registered callbacks.
  *
@@ -164,6 +166,9 @@ typedef struct
 {
 	ShmemStructOpts *options;
 	ShmemRequestKind kind;
+
+	/* InitShmemIndexEntry() sets this pointer when the area is allocated */
+	ShmemIndexEnt *index_entry;
 } ShmemRequest;
 
 static List *pending_shmem_requests;
@@ -262,12 +267,13 @@ static HTAB *ShmemIndex;
 #define SHMEM_INDEX_ADDITIONAL_SIZE		 (128)
 
 /* this is a hash bucket in the shmem index table */
-typedef struct
+typedef struct ShmemIndexEnt
 {
 	char		key[SHMEM_INDEX_KEYSIZE];	/* string name */
 	void	   *location;		/* location in shared mem */
 	Size		size;			/* # bytes requested for the structure */
 	Size		allocated_size; /* # bytes actually allocated */
+	bool		initialized;	/* has the init callback been run? */
 } ShmemIndexEnt;
 
 /* To get reliable results for NUMA inquiry we need to "touch pages" once */
@@ -378,6 +384,7 @@ ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
 	request = palloc_object(ShmemRequest);
 	request->options = options;
 	request->kind = kind;
+	request->index_entry = NULL;
 	pending_shmem_requests = lappend(pending_shmem_requests, request);
 }
 
@@ -436,10 +443,7 @@ ShmemInitRequested(void)
 	foreach_ptr(ShmemRequest, request, pending_shmem_requests)
 	{
 		InitShmemIndexEntry(request);
-		pfree(request->options);
 	}
-	list_free_deep(pending_shmem_requests);
-	pending_shmem_requests = NIL;
 
 	/*
 	 * Call the subsystem-specific init callbacks to finish initialization of
@@ -451,6 +455,15 @@ ShmemInitRequested(void)
 			callbacks->init_fn(callbacks->opaque_arg);
 	}
 
+	/* Now we can mark all the areas as initialized and free the requests */
+	foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+	{
+		request->index_entry->initialized = true;
+		pfree(request->options);
+	}
+	list_free_deep(pending_shmem_requests);
+	pending_shmem_requests = NIL;
+
 	shmem_request_state = SRS_DONE;
 }
 
@@ -552,7 +565,12 @@ InitShmemIndexEntry(ShmemRequest *request)
 	index_entry->allocated_size = allocated_size;
 	index_entry->location = structPtr;
 
-	/* Initialize depending on the kind of shmem area it is */
+	/*
+	 * The area is considered fully initialized only after the subsystem's
+	 * init callback has been called.  For now, perform only basic
+	 * initialization based on the kind of shmem area it is.
+	 */
+	index_entry->initialized = false;
 	switch (request->kind)
 	{
 		case SHMEM_KIND_STRUCT:
@@ -566,6 +584,9 @@ InitShmemIndexEntry(ShmemRequest *request)
 			shmem_slru_init(structPtr, request->options);
 			break;
 	}
+
+	/* return the pointer to the entry to the caller */
+	request->index_entry = index_entry;
 }
 
 /*
@@ -595,6 +616,20 @@ AttachShmemIndexEntry(ShmemRequest *request, bool missing_ok)
 		return false;
 	}
 
+	/*
+	 * If it was previously allocated but not fully initialized, error out.
+	 * There is currently no way of retrying or cleaning up an uninitialized
+	 * entry, it just lingers until the server is shut down.  But this can
+	 * only happen when allocating areas after postmaster startup, and it's
+	 * unlikely that you could successfully retry anyway.  The most likely
+	 * reason for failed initialization is that you are out of shared memory
+	 * and retrying won't help with that.
+	 */
+	if (!index_entry->initialized)
+		ereport(ERROR,
+				(errmsg("cannot attach to shared memory struct \"%s\" because it was not fully initialized",
+						request->options->name)));
+
 	/* Check that the size in the index matches the request */
 	if (index_entry->size != request->options->size &&
 		request->options->size != SHMEM_ATTACH_UNKNOWN_SIZE)
@@ -623,6 +658,8 @@ AttachShmemIndexEntry(ShmemRequest *request, bool missing_ok)
 			break;
 	}
 
+	request->index_entry = index_entry;
+
 	return true;
 }
 
@@ -733,6 +770,7 @@ InitShmemAllocator(PGShmemHeader *seghdr)
 		result->size = ShmemAllocator->index_size;
 		result->allocated_size = ShmemAllocator->index_size;
 		result->location = ShmemAllocator->index;
+		result->initialized = true;
 	}
 }
 
@@ -958,7 +996,17 @@ ProcessShmemRequestsAfterStartup(const ShmemCallbacks *callbacks)
 		index_entry = (ShmemIndexEnt *)
 			hash_search(ShmemIndex, request->options->name, HASH_FIND, NULL);
 		if (index_entry)
+		{
+			/*
+			 * Check for a half-initialized area.  (See also similar check in
+			 * AttachShmemIndexEntry())
+			 */
+			if (!index_entry->initialized)
+				ereport(ERROR,
+						(errmsg("cannot attach to shared memory struct \"%s\" because it was not fully initialized",
+								request->options->name)));
 			found_any = true;
+		}
 		else
 			notfound_any = true;
 	}
@@ -989,6 +1037,11 @@ ProcessShmemRequestsAfterStartup(const ShmemCallbacks *callbacks)
 			callbacks->init_fn(callbacks->opaque_arg);
 	}
 
+	foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+	{
+		request->index_entry->initialized = true;
+	}
+
 	LWLockRelease(ShmemIndexLock);
 }
 
@@ -1053,7 +1106,11 @@ ShmemInitStruct(const char *name, Size size, bool *foundPtr)
 
 	/* Initialize it if not found */
 	if (!*foundPtr)
+	{
 		InitShmemIndexEntry(&request);
+		/* no additional initialization needed */
+		request.index_entry->initialized = true;
+	}
 
 	LWLockRelease(ShmemIndexLock);
 
-- 
2.47.3

