pg.ddx.io pgsql-hackers@postgresql.org mailing list archive
help / color / mirror / Atom feedError handling in after-startup shmem requests
21+ messages / 5 participants
[nested] [flat]
Commits from this thread:
2026-09-01 e916927cfb 61e64cb19a Make after-startup shmem failure test reliable
2026-08-28 07fdee7c8a 9d888cd3f3 Track which shmem areas have been fully initialized
2026-08-28 c54b6979e0 92d44b200e Fix backend state after a failed after-startup shmem request
* Error handling in after-startup shmem requests
@ 2026-08-06 12:40 Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
0 siblings, 1 reply; 21+ messages in thread
From: Ayush Tiwari @ 2026-08-06 12:40 UTC (permalink / raw)
To: pgsql-hackers; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>
Hi,
I have been experimenting with the new shmem registration mechanism
(283e823f9dc), in particular the SHMEM_CALLBACKS_ALLOW_AFTER_STARTUP
path, and ran into a few behaviours I did not expect. I may be
misreading the intent here, so I would appreciate a sanity check before
taking any of this further. All three reproduce on master and on
REL_19_STABLE.
1) Stale request state after a failed request
If an after-startup request fails, either inside the request callback or
later while the areas are being allocated, CallShmemCallbacksAfterStartup()
returns without clearing pending_shmem_requests or shmem_request_state.
A second attempt in the same backend then hits:
TRAP: failed Assert("IsPointerList(list)"), File: "list.c", Line: 341
As far as I can tell this is because the request list lives in the
caller's memory context, which error cleanup has already released. The
stale shmem_request_state also seems to make later RegisterShmemCallbacks()
calls quietly take the "remember the callbacks for later" branch.
0001 collects the requests in a context of our own instead, with a reset
callback that clears pending_shmem_requests and shmem_request_state. That
way the cleanup happens on the error path as well, without adding any
PG_TRY blocks, and the startup paths are left alone. Initially I had
thought of using
the TRY/CATCH blocks, but went the other way.
2) A request batch that only partly fits
If a request asks for several areas and a later one does not fit, the
earlier ones stay allocated and registered. A retry then trips
"some of the requested shmem areas have already been initialized"
and, since shared memory is never freed, that looks permanent until a
restart. Before this mechanism each area went through its own
ShmemInitStruct() call, so the same situation could simply be retried.
Should a batch be all-or-nothing here, or is this considered acceptable
given that after-startup allocation is best-effort anyway?
3) Legacy allocation from an init or attach callback
The init and attach callbacks run with ShmemIndexLock held, and
ShmemInitStruct() takes that same lock. Calling it from a callback,
which seems like a natural thing to try when moving code over from
shmem_startup_hook, trips an unrelated-looking state assertion in an
assert-enabled build and hangs in a production build. Is it worth
rejecting this explicitly, or would a note in the docs be enough?
I have attached three small patches, one per point above, each with a
test in test_shmem. They are meant as a starting point for the
discussion rather than as finished proposals, and I am happy to rework
or drop any of them if the above points are intended decisions.
Regards,
Ayush
Attachments: download all (3 files, .tar.gz)
0001-Fix-stale-state-after-a-failed-after-startup-shmem-r.patch (application/octet-stream, 9.3K) download
From aa618c279b52c796f1989bf1cb0f294570be1e0b Mon Sep 17 00:00:00 2001
From: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Date: Thu, 6 Aug 2026 13:27:29 +0530
Subject: [PATCH 1/3] Fix stale state after a failed after-startup shmem
request
CallShmemCallbacksAfterStartup() reset pending_shmem_requests and
shmem_request_state only on success. If its request callback or a later
allocation failed, it left both behind. The requests and their List
were allocated in the caller's memory context, so error cleanup could
free the List while pending_shmem_requests still pointed to it. A retry
in the same backend then crashed:
TRAP: failed Assert("IsPointerList(list)"), File: "list.c", Line: 341
The stale shmem_request_state also made later calls to
RegisterShmemCallbacks() silently take the startup-registration path
instead of processing the request immediately.
Allocate after-startup requests in a child of the current transaction
context, with a reset callback that clears the List and restores the
state. Normal error cleanup then handles failures without PG_TRY().
Shared memory already allocated before a failure remains allocated, as
shared memory cannot be freed, but the process-local bookkeeping is
restored.
Extend test_shmem to cover failures while collecting and allocating
requests, retried in one session because the state is backend-local.
Author: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
---
src/backend/storage/ipc/shmem.c | 57 +++++++++++++++++--
.../test_shmem/t/001_late_shmem_alloc.pl | 28 +++++++++
.../modules/test_shmem/test_shmem--1.0.sql | 4 ++
src/test/modules/test_shmem/test_shmem.c | 39 +++++++++++++
4 files changed, 122 insertions(+), 6 deletions(-)
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index a3d56cf55dd..9986d6a69ce 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -142,6 +142,7 @@
#include "storage/shmem_internal.h"
#include "storage/spin.h"
#include "utils/builtins.h"
+#include "utils/memutils.h"
#include "utils/tuplestore.h"
/*
@@ -168,6 +169,13 @@ typedef struct
static List *pending_shmem_requests;
+/*
+ * During an after-startup request, allocate the request list in a context
+ * that is reset on error, so that it cannot become a dangling pointer.
+ */
+static MemoryContext late_shmem_requests_context;
+static MemoryContextCallback late_shmem_requests_callback;
+
/*
* Per-process state machine, for sanity checking that we do things in the
* right order.
@@ -274,6 +282,8 @@ typedef struct
static bool firstNumaTouch = true;
static void CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks);
+static void BeginLateShmemRequests(void);
+static void ForgetLateShmemRequests(void *arg);
static void InitShmemIndexEntry(ShmemRequest *request);
static bool AttachShmemIndexEntry(ShmemRequest *request, bool missing_ok);
@@ -336,6 +346,7 @@ void
ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
{
ShmemRequest *request;
+ MemoryContext oldcontext = NULL;
/* Check the options */
if (options->name == NULL)
@@ -374,10 +385,47 @@ ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
}
/* Request looks valid, remember it */
+ if (late_shmem_requests_context != NULL)
+ oldcontext = MemoryContextSwitchTo(late_shmem_requests_context);
request = palloc(sizeof(ShmemRequest));
request->options = options;
request->kind = kind;
pending_shmem_requests = lappend(pending_shmem_requests, request);
+ if (oldcontext != NULL)
+ MemoryContextSwitchTo(oldcontext);
+}
+
+/* Start collecting an after-startup request. */
+static void
+BeginLateShmemRequests(void)
+{
+ MemoryContext parent = CurTransactionContext != NULL ?
+ CurTransactionContext : CurrentMemoryContext;
+
+ Assert(pending_shmem_requests == NIL);
+ Assert(late_shmem_requests_context == NULL);
+ Assert(late_shmem_requests_callback.func == NULL);
+
+ late_shmem_requests_context =
+ AllocSetContextCreate(parent, "Pending shmem requests",
+ ALLOCSET_SMALL_SIZES);
+ late_shmem_requests_callback.func = ForgetLateShmemRequests;
+ late_shmem_requests_callback.arg = NULL;
+ MemoryContextRegisterResetCallback(late_shmem_requests_context,
+ &late_shmem_requests_callback);
+}
+
+/* Discard an after-startup request and reset the process-local state. */
+static void
+ForgetLateShmemRequests(void *arg)
+{
+ foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+ pfree(request->options);
+
+ pending_shmem_requests = NIL;
+ late_shmem_requests_context = NULL;
+ late_shmem_requests_callback.func = NULL;
+ shmem_request_state = SRS_DONE;
}
/*
@@ -901,6 +949,7 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
bool notfound_any;
Assert(shmem_request_state == SRS_DONE);
+ BeginLateShmemRequests();
shmem_request_state = SRS_REQUESTING;
/*
@@ -914,7 +963,7 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
if (pending_shmem_requests == NIL)
{
- shmem_request_state = SRS_DONE;
+ MemoryContextDelete(late_shmem_requests_context);
return;
}
@@ -952,11 +1001,7 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
AttachShmemIndexEntry(request, false);
else
InitShmemIndexEntry(request);
-
- pfree(request->options);
}
- list_free_deep(pending_shmem_requests);
- pending_shmem_requests = NIL;
/* Finish by calling the appropriate subsystem-specific callback */
if (found_any)
@@ -971,7 +1016,7 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
}
LWLockRelease(ShmemIndexLock);
- shmem_request_state = SRS_DONE;
+ MemoryContextDelete(late_shmem_requests_context);
}
/*
diff --git a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
index 5cf07d071ec..a9481997d52 100644
--- a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
+++ b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
@@ -25,6 +25,34 @@ my $attach_count2 =
$node->safe_psql("postgres", "SELECT get_test_shmem_attach_count();");
cmp_ok($attach_count2, '>', $attach_count1,
"attach callback is called in each backend");
+
+sub try_shmem_failure_twice
+{
+ my ($mode) = @_;
+ my $sql = qq[
+DO \$\$
+BEGIN
+ FOR i IN 1..2 LOOP
+ BEGIN
+ PERFORM test_shmem_failure($mode);
+ EXCEPTION WHEN others THEN
+ RAISE NOTICE 'attempt %: %', i, SQLERRM;
+ END;
+ END LOOP;
+END
+\$\$;];
+ return $node->psql('postgres', $sql);
+}
+
+# The state is backend-local, so the two attempts must share a session.
+foreach my $mode (0, 1)
+{
+ my ($ret, $stdout, $stderr) = try_shmem_failure_twice($mode);
+
+ is($ret, 0, "session survives repeated failing shmem request $mode");
+ like($stderr, qr/attempt 1: /, "shmem request $mode fails");
+ like($stderr, qr/attempt 2: /, "shmem request $mode fails when retried");
+}
$node->stop;
###
diff --git a/src/test/modules/test_shmem/test_shmem--1.0.sql b/src/test/modules/test_shmem/test_shmem--1.0.sql
index 2d01fd9256c..62d3458fea9 100644
--- a/src/test/modules/test_shmem/test_shmem--1.0.sql
+++ b/src/test/modules/test_shmem/test_shmem--1.0.sql
@@ -7,3 +7,7 @@
CREATE FUNCTION get_test_shmem_attach_count()
RETURNS pg_catalog.int4 STRICT
AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_shmem_failure(pg_catalog.int4)
+RETURNS pg_catalog.void STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
diff --git a/src/test/modules/test_shmem/test_shmem.c b/src/test/modules/test_shmem/test_shmem.c
index 9bd4012b435..348f26877af 100644
--- a/src/test/modules/test_shmem/test_shmem.c
+++ b/src/test/modules/test_shmem/test_shmem.c
@@ -38,6 +38,7 @@ static bool attached_or_initialized = false;
static void test_shmem_request(void *arg);
static void test_shmem_init(void *arg);
static void test_shmem_attach(void *arg);
+static void test_shmem_failure_request(void *arg);
static const ShmemCallbacks TestShmemCallbacks = {
.flags = SHMEM_CALLBACKS_ALLOW_AFTER_STARTUP,
@@ -46,6 +47,13 @@ static const ShmemCallbacks TestShmemCallbacks = {
.attach_fn = test_shmem_attach,
};
+static const ShmemCallbacks TestShmemFailureCallbacks = {
+ .flags = SHMEM_CALLBACKS_ALLOW_AFTER_STARTUP,
+ .request_fn = test_shmem_failure_request,
+};
+
+static int failure_mode;
+
static void
test_shmem_request(void *arg)
{
@@ -82,6 +90,28 @@ test_shmem_attach(void *arg)
attached_or_initialized = true;
}
+/* Request callback used by the after-startup failure tests. */
+static void
+test_shmem_failure_request(void *arg)
+{
+ static void *ptr1;
+
+ switch (failure_mode)
+ {
+ case 0:
+ ShmemRequestStruct(.name = "test_shmem callback error area",
+ .size = 1024, .ptr = &ptr1);
+ elog(ERROR, "test_shmem request callback failed on purpose");
+ case 1:
+ ShmemRequestStruct(.name = "test_shmem oversized area",
+ .size = (Size) 1024 * 1024 * 1024,
+ .ptr = &ptr1);
+ break;
+ default:
+ elog(ERROR, "unrecognized test_shmem failure mode: %d", failure_mode);
+ }
+}
+
void
_PG_init(void)
{
@@ -89,6 +119,15 @@ _PG_init(void)
RegisterShmemCallbacks(&TestShmemCallbacks);
}
+PG_FUNCTION_INFO_V1(test_shmem_failure);
+Datum
+test_shmem_failure(PG_FUNCTION_ARGS)
+{
+ failure_mode = PG_GETARG_INT32(0);
+ RegisterShmemCallbacks(&TestShmemFailureCallbacks);
+ PG_RETURN_VOID();
+}
+
PG_FUNCTION_INFO_V1(get_test_shmem_attach_count);
Datum
get_test_shmem_attach_count(PG_FUNCTION_ARGS)
--
2.34.1
0002-Preflight-after-startup-shmem-batches-for-available-.patch (application/octet-stream, 4.5K) download
From 78e61dac82d2143527228b4bb9495989e4e1d497 Mon Sep 17 00:00:00 2001
From: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Date: Thu, 6 Aug 2026 13:33:00 +0530
Subject: [PATCH 2/3] Preflight after-startup shmem batches for available space
An after-startup request can contain several shared memory areas. They
were allocated one at a time, so if the remaining shared memory ran out
on a later area, earlier ones remained allocated and registered. A
retry then found some names present and some missing and failed with
"some of the requested shmem areas have already been initialized".
Since shared memory cannot be freed, the subsystem stayed wedged until
server restart.
Check the remaining shared memory against the whole batch before
creating any area. Named allocations are serialized by ShmemIndexLock;
low-level direct ShmemAlloc() callers can still race the preflight.
Add a test with one small area followed by an oversized one, and verify
that the preflight creates no entries and can be retried.
Author: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
---
src/backend/storage/ipc/shmem.c | 32 +++++++++++++++++++
.../test_shmem/t/001_late_shmem_alloc.pl | 13 ++++++++
src/test/modules/test_shmem/test_shmem.c | 7 ++++
3 files changed, 52 insertions(+)
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 9986d6a69ce..c117955e49b 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -991,6 +991,38 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
if (found_any && notfound_any)
elog(ERROR, "some of the requested shmem areas have already been initialized");
+ /*
+ * Check that the whole batch fits before creating any of it. Otherwise a
+ * failure partway through leaves a mix of present and missing areas, which
+ * cannot be retried. Low-level ShmemAlloc() callers can still race this
+ * check, but named allocations are serialized by ShmemIndexLock.
+ */
+ if (!found_any)
+ {
+ Size offset;
+
+ SpinLockAcquire(&ShmemAllocator->shmem_lock);
+ offset = ShmemAllocator->free_offset;
+ SpinLockRelease(&ShmemAllocator->shmem_lock);
+
+ foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+ {
+ Size alignment = request->options->alignment;
+
+ if (alignment < PG_CACHE_LINE_SIZE)
+ alignment = PG_CACHE_LINE_SIZE;
+ offset = TYPEALIGN(alignment, offset);
+ offset = add_size(offset, request->options->size);
+ if (offset > ShmemSegHdr->totalsize)
+ ereport(ERROR,
+ (errcode(ERRCODE_OUT_OF_MEMORY),
+ errmsg("not enough shared memory for data structure"
+ " \"%s\" (%zd bytes requested)",
+ request->options->name,
+ request->options->size)));
+ }
+ }
+
/*
* Allocate or attach all the shmem areas requested by the request_fn
* callback.
diff --git a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
index a9481997d52..5915f060a0c 100644
--- a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
+++ b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
@@ -53,6 +53,19 @@ foreach my $mode (0, 1)
like($stderr, qr/attempt 1: /, "shmem request $mode fails");
like($stderr, qr/attempt 2: /, "shmem request $mode fails when retried");
}
+
+my ($ret, $stdout, $stderr) = try_shmem_failure_twice(2);
+is($ret, 0, 'session survives a partly oversized request batch');
+like($stderr, qr/attempt 2: .*not enough shared memory/,
+ 'a partly oversized batch can be retried');
+unlike($stderr, qr/already been initialized/,
+ 'a partly oversized batch does not wedge later attempts');
+is( $node->safe_psql(
+ 'postgres',
+ "SELECT count(*) FROM pg_shmem_allocations WHERE name LIKE 'test_shmem partial%';"
+ ),
+ '0',
+ 'a partly oversized batch creates no areas');
$node->stop;
###
diff --git a/src/test/modules/test_shmem/test_shmem.c b/src/test/modules/test_shmem/test_shmem.c
index 348f26877af..6adf2405270 100644
--- a/src/test/modules/test_shmem/test_shmem.c
+++ b/src/test/modules/test_shmem/test_shmem.c
@@ -107,6 +107,13 @@ test_shmem_failure_request(void *arg)
.size = (Size) 1024 * 1024 * 1024,
.ptr = &ptr1);
break;
+ case 2:
+ ShmemRequestStruct(.name = "test_shmem partial small area",
+ .size = 1024, .ptr = &ptr1);
+ ShmemRequestStruct(.name = "test_shmem partial huge area",
+ .size = (Size) 1024 * 1024 * 1024,
+ .ptr = &ptr1);
+ break;
default:
elog(ERROR, "unrecognized test_shmem failure mode: %d", failure_mode);
}
--
2.34.1
0003-Reject-legacy-shmem-allocation-from-shmem-callbacks.patch (application/octet-stream, 4.7K) download
From 6553283560eb43c48c471e627b0ac982259d1ca9 Mon Sep 17 00:00:00 2001
From: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Date: Thu, 6 Aug 2026 14:34:43 +0530
Subject: [PATCH 3/3] Reject legacy shmem allocation from shmem callbacks
After-startup init and attach callbacks run with ShmemIndexLock held.
ShmemInitStruct() takes the same lock, and LWLocks are not reentrant, so
calling it from one of those callbacks waits for the calling process
itself. ShmemInitHash() has the same problem through its call to
ShmemInitStruct().
This is easy to do when porting code from shmem_startup_hook, where
ShmemInitStruct() was the normal interface and no lock was held. In an
assert build the misuse currently trips an unrelated-looking state
assertion; in a production build it hangs indefinitely.
Detect that ShmemIndexLock is already held and report the misuse.
Document that all required areas must instead be requested from the
request callback.
Author: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
---
doc/src/sgml/xfunc.sgml | 6 ++++++
src/backend/storage/ipc/shmem.c | 3 +++
.../modules/test_shmem/t/001_late_shmem_alloc.pl | 6 ++++++
src/test/modules/test_shmem/test_shmem.c | 15 +++++++++++++++
4 files changed, 30 insertions(+)
diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml
index 2b8a11e7ad0..25e17ac0e98 100644
--- a/doc/src/sgml/xfunc.sgml
+++ b/doc/src/sgml/xfunc.sgml
@@ -3742,6 +3742,12 @@ my_shmem_init(void *arg)
lock (ShmemIndexLock), which prevents the race condition of two backends
trying to initialize the memory area at the same time.
</para>
+ <para>
+ The legacy <function>ShmemInitStruct()</function> and
+ <function>ShmemInitHash()</function> functions cannot be used from these
+ callbacks because they take the same lock. Request all required areas
+ from <function>request_fn</function> instead.
+ </para>
</sect3>
<sect3 id="xfunc-shared-addin-dynamic">
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index c117955e49b..23be8817c9e 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -1097,6 +1097,9 @@ ShmemInitStruct(const char *name, Size size, bool *foundPtr)
};
ShmemRequest request = {&options, SHMEM_KIND_STRUCT};
+ if (LWLockHeldByMe(ShmemIndexLock))
+ elog(ERROR, "cannot call ShmemInitStruct() while holding ShmemIndexLock");
+
Assert(shmem_request_state == SRS_DONE ||
shmem_request_state == SRS_INITIALIZING ||
shmem_request_state == SRS_REQUESTING);
diff --git a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
index 5915f060a0c..b4da7de86e9 100644
--- a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
+++ b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
@@ -66,6 +66,12 @@ is( $node->safe_psql(
),
'0',
'a partly oversized batch creates no areas');
+
+my ($legacy_ret, $legacy_out, $legacy_err) =
+ $node->psql('postgres', 'SELECT test_shmem_failure(3);');
+isnt($legacy_ret, 0, 'legacy allocation from an init callback is rejected');
+like($legacy_err, qr/cannot call ShmemInitStruct\(\) while holding ShmemIndexLock/,
+ 'legacy allocation reports a clear error instead of hanging');
$node->stop;
###
diff --git a/src/test/modules/test_shmem/test_shmem.c b/src/test/modules/test_shmem/test_shmem.c
index 6adf2405270..da5090a9d51 100644
--- a/src/test/modules/test_shmem/test_shmem.c
+++ b/src/test/modules/test_shmem/test_shmem.c
@@ -39,6 +39,7 @@ static void test_shmem_request(void *arg);
static void test_shmem_init(void *arg);
static void test_shmem_attach(void *arg);
static void test_shmem_failure_request(void *arg);
+static void test_shmem_failure_init(void *arg);
static const ShmemCallbacks TestShmemCallbacks = {
.flags = SHMEM_CALLBACKS_ALLOW_AFTER_STARTUP,
@@ -50,6 +51,7 @@ static const ShmemCallbacks TestShmemCallbacks = {
static const ShmemCallbacks TestShmemFailureCallbacks = {
.flags = SHMEM_CALLBACKS_ALLOW_AFTER_STARTUP,
.request_fn = test_shmem_failure_request,
+ .init_fn = test_shmem_failure_init,
};
static int failure_mode;
@@ -114,11 +116,24 @@ test_shmem_failure_request(void *arg)
.size = (Size) 1024 * 1024 * 1024,
.ptr = &ptr1);
break;
+ case 3:
+ ShmemRequestStruct(.name = "test_shmem legacy caller area",
+ .size = 1024, .ptr = &ptr1);
+ break;
default:
elog(ERROR, "unrecognized test_shmem failure mode: %d", failure_mode);
}
}
+static void
+test_shmem_failure_init(void *arg)
+{
+ bool found;
+
+ if (failure_mode == 3)
+ (void) ShmemInitStruct("test_shmem legacy target area", 1024, &found);
+}
+
void
_PG_init(void)
{
--
2.34.1
^ permalink raw reply [nested|flat] 21+ messages in thread
* Re: Error handling in after-startup shmem requests
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
@ 2026-08-07 13:25 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-09 16:30 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
0 siblings, 1 reply; 21+ messages in thread
From: Ashutosh Bapat @ 2026-08-07 13:25 UTC (permalink / raw)
To: Ayush Tiwari <ayushtiwari.slg01@gmail.com>; +Cc: pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>
Hi Piyush,
Thanks for your report and patches.
On Thu, Aug 6, 2026 at 6:10 PM Ayush Tiwari <ayushtiwari.slg01@gmail.com> wrote:
>
> 1) Stale request state after a failed request
>
> If an after-startup request fails, either inside the request callback or
> later while the areas are being allocated, CallShmemCallbacksAfterStartup()
> returns without clearing pending_shmem_requests or shmem_request_state.
> A second attempt in the same backend then hits:
>
> TRAP: failed Assert("IsPointerList(list)"), File: "list.c", Line: 341
>
> As far as I can tell this is because the request list lives in the
> caller's memory context, which error cleanup has already released. The
> stale shmem_request_state also seems to make later RegisterShmemCallbacks()
> calls quietly take the "remember the callbacks for later" branch.
Your analysis looks correct.
>
> 0001 collects the requests in a context of our own instead, with a reset
> callback that clears pending_shmem_requests and shmem_request_state. That
> way the cleanup happens on the error path as well, without adding any
> PG_TRY blocks, and the startup paths are left alone. Initially I had thought of using
> the TRY/CATCH blocks, but went the other way.
>
The fix seems more complicated than necessary.
ShmemRequestStructWithOpts() allocates the options in
TopMemoryContext, I think we should do the same with ShmemRequests or
at least the context should be child of TopMemoryContext which
outlives any query or transaction. I also think that a simple
PG_TRY/PG_FINALLY block should be enough to release all pending
requests after an error and also to set shmem_request_state. You have
mentioned that you thought of using it but did not mention why you
discarded that approach? It will save a bunch of code.
The test could use INJECTION_POINT and avoid creating a new set of
callbacks. To induce large sized failure, I would introduce a
test_shmem GUC which to decide the size of shared memory allocation
and set it to a high value before requesting memory.
You could use PG_FALLTHROUGH to avoid fall through warnings.
> 2) A request batch that only partly fits
>
> If a request asks for several areas and a later one does not fit, the
> earlier ones stay allocated and registered. A retry then trips
>
> "some of the requested shmem areas have already been initialized"
>
> and, since shared memory is never freed, that looks permanent until a
> restart. Before this mechanism each area went through its own
> ShmemInitStruct() call, so the same situation could simply be retried.
> Should a batch be all-or-nothing here, or is this considered acceptable
> given that after-startup allocation is best-effort anyway?
Even with ShmemInitStruct() a retry will still fail because of not
enough memory. Shared memory for after startup allocation is limited,
so even restarting the server won't fix it. The request has to be
reduced.
Did we allow calling ShmemInitStruct() at run time before this
mechanism? Even if it were, the caller didn't have much choice about
the areas already created. In fact the situation would be bad, since
the areas which are allocated are not initialized but variables
pointing them are set. So if the caller is not careful, its code may
start using these areas.
But with this mechanism we have choice. I think we should be able to
implement all-or-nothing. At the beginning of
CallShmemCallbacksAfterStartup() Remember the current allocation
offset. When allocating memory remember the requests that succeeded.
In case of failure, reset the allocation offset to the saved value and
remove the requested entries from ShmemIndex. But that seems a lot for
PG 19 at this stage. Maybe PG 20 material.
I think we should document that if RegisterShmemCallbacks() called
after startup throws an error, the subsystems should make sure that
the shared structures are not accessed since they are not initialized,
possibly setting the corresponding pointers to NULL. Or actually we
should reset the pointers to NULL in CallShmemCallbacksAfterStartup()
before throwing an error. That won't be invasive fix.
>
> 3) Legacy allocation from an init or attach callback
>
> The init and attach callbacks run with ShmemIndexLock held, and
> ShmemInitStruct() takes that same lock. Calling it from a callback,
> which seems like a natural thing to try when moving code over from
> shmem_startup_hook, trips an unrelated-looking state assertion in an
> assert-enabled build and hangs in a production build. Is it worth
> rejecting this explicitly, or would a note in the docs be enough?
Why would ShmemInitStruct be called from a callback? The pointer to
the shared structure should have been set in the given
variables/addresses.
--
Best Wishes,
Ashutosh Bapat
^ permalink raw reply [nested|flat] 21+ messages in thread
* Re: Error handling in after-startup shmem requests
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
@ 2026-08-09 16:30 ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-10 09:40 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
0 siblings, 1 reply; 21+ messages in thread
From: Ayush Tiwari @ 2026-08-09 16:30 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>
Hi,
On Fri, 7 Aug 2026 at 18:56, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
wrote:
>
> On Thu, Aug 6, 2026 at 6:10 PM Ayush Tiwari <ayushtiwari.slg01@gmail.com>
> wrote:
> >
> > 1) Stale request state after a failed request
> >
> > If an after-startup request fails, either inside the request callback or
> > later while the areas are being allocated,
> CallShmemCallbacksAfterStartup()
> > returns without clearing pending_shmem_requests or shmem_request_state.
> > A second attempt in the same backend then hits:
> >
> > TRAP: failed Assert("IsPointerList(list)"), File: "list.c", Line: 341
> >
> > As far as I can tell this is because the request list lives in the
> > caller's memory context, which error cleanup has already released. The
> > stale shmem_request_state also seems to make later
> RegisterShmemCallbacks()
> > calls quietly take the "remember the callbacks for later" branch.
>
> Your analysis looks correct.
>
Thanks for the review!
> > 0001 collects the requests in a context of our own instead, with a reset
> > callback that clears pending_shmem_requests and shmem_request_state.
> That
> > way the cleanup happens on the error path as well, without adding any
> > PG_TRY blocks, and the startup paths are left alone. Initially I had
> thought of using
> > the TRY/CATCH blocks, but went the other way.
> >
>
> The fix seems more complicated than necessary.
> ShmemRequestStructWithOpts() allocates the options in
> TopMemoryContext, I think we should do the same with ShmemRequests or
> at least the context should be child of TopMemoryContext which
> outlives any query or transaction. I also think that a simple
> PG_TRY/PG_FINALLY block should be enough to release all pending
> requests after an error and also to set shmem_request_state. You have
> mentioned that you thought of using it but did not mention why you
> discarded that approach? It will save a bunch of code.
>
I initially tried to tie the cleanup to a memory context. Looking at it
again, the CurrentMemoryContext fallback is not necessarily reset after
an error, particularly when there is no transaction in progress. That
does not seem reliable enough for this path.
0001 now allocates the request records and list cells in
TopMemoryContext, like the options, and cleans them up from PG_FINALLY.
Does this look closer to the intended pattern?
> The test could use INJECTION_POINT and avoid creating a new set of
> callbacks. To induce large sized failure, I would introduce a
> test_shmem GUC which to decide the size of shared memory allocation
> and set it to a high value before requesting memory.
>
Thanks for this idea.
I reworked the tests that way. They now use the existing callbacks, a
size GUC, and injection points; the extra callback set and TAP file have
been removed.
> > 2) A request batch that only partly fits
> >
> > If a request asks for several areas and a later one does not fit, the
> > earlier ones stay allocated and registered. A retry then trips
> >
> > "some of the requested shmem areas have already been initialized"
> >
> > and, since shared memory is never freed, that looks permanent until a
> > restart. Before this mechanism each area went through its own
> > ShmemInitStruct() call, so the same situation could simply be retried.
> > Should a batch be all-or-nothing here, or is this considered acceptable
> > given that after-startup allocation is best-effort anyway?
>
> Even with ShmemInitStruct() a retry will still fail because of not
> enough memory. Shared memory for after startup allocation is limited,
> so even restarting the server won't fix it. The request has to be
> reduced.
>
> Did we allow calling ShmemInitStruct() at run time before this
> mechanism? Even if it were, the caller didn't have much choice about
> the areas already created. In fact the situation would be bad, since
> the areas which are allocated are not initialized but variables
> pointing them are set. So if the caller is not careful, its code may
> start using these areas.
>
> But with this mechanism we have choice. I think we should be able to
> implement all-or-nothing. At the beginning of
> CallShmemCallbacksAfterStartup() Remember the current allocation
> offset. When allocating memory remember the requests that succeeded.
> In case of failure, reset the allocation offset to the saved value and
> remove the requested entries from ShmemIndex. But that seems a lot for
> PG 19 at this stage. Maybe PG 20 material.
>
> I think we should document that if RegisterShmemCallbacks() called
> after startup throws an error, the subsystems should make sure that
> the shared structures are not accessed since they are not initialized,
> possibly setting the corresponding pointers to NULL. Or actually we
> should reset the pointers to NULL in CallShmemCallbacksAfterStartup()
> before throwing an error. That won't be invasive fix.
>
I first changed 0002 to reset the handles as suggested. That protects the
backend in which the error occurred, but I do not think it is sufficient
for the next backend. The entries inserted before the error remain in
ShmemIndex. If all requested entries were inserted and init_fn then
failed, a later backend would find all of them and call attach_fn on areas
that were never fully initialized.
That is why 0002 also removes the entries inserted by the failed create
attempt. This is limited to the create path: entries found on the attach
path belong to an earlier successful initialization and must remain
visible. ShmemIndexLock is still held during the cleanup, and the initial
lookup established that none of these names existed before this attempt.
This is still only a partial rollback. It does not restore the allocation
offset, so the bytes remain consumed and are reported as anonymous shared
memory. Reusing the names also means repeated failures could consume more
of the after-startup reserve. I was not sure whether preventing a later
backend from attaching to unfinished memory justifies that behavior for
PG 19. Would you prefer this partial rollback, or only resetting the
handles and documenting that the subsystem must detect incomplete
initialization, leaving the full offset-and-index rollback for PG 20?
> >
> > 3) Legacy allocation from an init or attach callback
> >
> > The init and attach callbacks run with ShmemIndexLock held, and
> > ShmemInitStruct() takes that same lock. Calling it from a callback,
> > which seems like a natural thing to try when moving code over from
> > shmem_startup_hook, trips an unrelated-looking state assertion in an
> > assert-enabled build and hangs in a production build. Is it worth
> > rejecting this explicitly, or would a note in the docs be enough?
>
> Why would ShmemInitStruct be called from a callback? The pointer to
> the shared structure should have been set in the given
> variables/addresses.
>
I agree that it should not be needed there. My concern was the resulting
diagnostic: it deadlocks in a normal build and reaches an unrelated state
assertion in an assert build. 0003 checks the callback states and reports
an error instead. Thoughts?
Regards,
Ayush
Attachments: download all (3 files, .tar.gz)
v2-0001-Clean-up-pending-shmem-requests-after-an-error.patch (application/octet-stream, 10.1K) download
From 76eb653e8bc317b4fdc47dc72748ec75a90c9361 Mon Sep 17 00:00:00 2001
From: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Date: Sun, 9 Aug 2026 16:23:02 +0530
Subject: [PATCH v2 1/3] Clean up pending shmem requests after an error
CallShmemCallbacksAfterStartup() cleared pending_shmem_requests and reset
shmem_request_state only on success. Its request list lived in the caller's
memory context, so error cleanup could release the list while the global still
pointed at it. A second registration attempt in the same backend then walked
a dangling list and failed the IsPointerList assertion. The stale state also
made later RegisterShmemCallbacks() calls silently remember the callbacks for
later rather than run them.
Allocate the request records and list cells in TopMemoryContext, like their
options, and put the after-startup operation behind a PG_FINALLY block that
always frees the requests and restores the state. Leave the startup paths
unchanged.
Add tests for errors in the request callback and during allocation. They
retry in the same backend because the affected state is process-local.
Author: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
---
src/backend/storage/ipc/shmem.c | 43 +++++++++++++---
src/test/modules/test_shmem/Makefile | 3 ++
src/test/modules/test_shmem/meson.build | 3 ++
.../test_shmem/t/001_late_shmem_alloc.pl | 51 +++++++++++++++++++
.../modules/test_shmem/test_shmem--1.0.sql | 4 ++
src/test/modules/test_shmem/test_shmem.c | 40 ++++++++++++++-
6 files changed, 134 insertions(+), 10 deletions(-)
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index a3d56cf55dd..a16e9388aad 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -274,6 +274,8 @@ typedef struct
static bool firstNumaTouch = true;
static void CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks);
+static void CallShmemCallbacksAfterStartupInternal(const ShmemCallbacks *callbacks);
+static void DiscardPendingShmemRequests(void);
static void InitShmemIndexEntry(ShmemRequest *request);
static bool AttachShmemIndexEntry(ShmemRequest *request, bool missing_ok);
@@ -336,6 +338,7 @@ void
ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
{
ShmemRequest *request;
+ MemoryContext oldcontext;
/* Check the options */
if (options->name == NULL)
@@ -373,11 +376,13 @@ ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
options->name)));
}
- /* Request looks valid, remember it */
+ /* Keep the requests and list cells alive until we explicitly free them. */
+ oldcontext = MemoryContextSwitchTo(TopMemoryContext);
request = palloc(sizeof(ShmemRequest));
request->options = options;
request->kind = kind;
pending_shmem_requests = lappend(pending_shmem_requests, request);
+ MemoryContextSwitchTo(oldcontext);
}
/*
@@ -896,12 +901,29 @@ RegisterShmemCallbacks(const ShmemCallbacks *callbacks)
*/
static void
CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
+{
+ Assert(shmem_request_state == SRS_DONE);
+ Assert(pending_shmem_requests == NIL);
+
+ shmem_request_state = SRS_REQUESTING;
+ PG_TRY();
+ {
+ CallShmemCallbacksAfterStartupInternal(callbacks);
+ }
+ PG_FINALLY();
+ {
+ DiscardPendingShmemRequests();
+ shmem_request_state = SRS_DONE;
+ }
+ PG_END_TRY();
+}
+
+static void
+CallShmemCallbacksAfterStartupInternal(const ShmemCallbacks *callbacks)
{
bool found_any;
bool notfound_any;
- Assert(shmem_request_state == SRS_DONE);
- shmem_request_state = SRS_REQUESTING;
/*
* Call the request callback first. The callback makes ShmemRequest*()
@@ -914,7 +936,6 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
if (pending_shmem_requests == NIL)
{
- shmem_request_state = SRS_DONE;
return;
}
@@ -953,10 +974,7 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
else
InitShmemIndexEntry(request);
- pfree(request->options);
}
- list_free_deep(pending_shmem_requests);
- pending_shmem_requests = NIL;
/* Finish by calling the appropriate subsystem-specific callback */
if (found_any)
@@ -971,7 +989,16 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
}
LWLockRelease(ShmemIndexLock);
- shmem_request_state = SRS_DONE;
+}
+
+/* Release the requests accumulated by a request_fn callback. */
+static void
+DiscardPendingShmemRequests(void)
+{
+ foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+ pfree(request->options);
+ list_free_deep(pending_shmem_requests);
+ pending_shmem_requests = NIL;
}
/*
diff --git a/src/test/modules/test_shmem/Makefile b/src/test/modules/test_shmem/Makefile
index 2407f7462fe..fed8e29c8f5 100644
--- a/src/test/modules/test_shmem/Makefile
+++ b/src/test/modules/test_shmem/Makefile
@@ -2,6 +2,9 @@
PGFILEDESC = "test_shmem - test code for shmem allocations"
+EXTRA_INSTALL = src/test/modules/injection_points
+export enable_injection_points
+
MODULE_big = test_shmem
OBJS = \
$(WIN32RES) \
diff --git a/src/test/modules/test_shmem/meson.build b/src/test/modules/test_shmem/meson.build
index fb4bf328b8f..8f98f2c4e31 100644
--- a/src/test/modules/test_shmem/meson.build
+++ b/src/test/modules/test_shmem/meson.build
@@ -26,6 +26,9 @@ tests += {
'sd': meson.current_source_dir(),
'bd': meson.current_build_dir(),
'tap': {
+ 'env': {
+ 'enable_injection_points': get_option('injection_points') ? 'yes' : 'no',
+ },
'tests': [
't/001_late_shmem_alloc.pl',
],
diff --git a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
index 5cf07d071ec..22c49686d73 100644
--- a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
+++ b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
@@ -18,6 +18,57 @@ $node->start;
$node->safe_psql("postgres", "CREATE EXTENSION test_shmem;");
+# Run a registration twice in one backend. The state under test is
+# backend-local, so separate safe_psql calls would not exercise a retry.
+sub register_twice
+{
+ my ($setup) = @_;
+ my $stderr;
+
+ $node->psql(
+ "postgres", qq[
+LOAD 'test_shmem';
+$setup
+DO \$\$
+BEGIN
+ FOR i IN 1..2 LOOP
+ BEGIN
+ PERFORM test_shmem_register();
+ RAISE NOTICE 'attempt %: ok', i;
+ EXCEPTION WHEN others THEN
+ RAISE NOTICE 'attempt %: %', i, SQLERRM;
+ END;
+ END LOOP;
+END
+\$\$;],
+ stderr => \$stderr);
+ return $stderr;
+}
+
+SKIP:
+{
+ skip "injection points not supported by this build", 2
+ if $ENV{enable_injection_points} ne 'yes';
+
+ $node->safe_psql("postgres", "CREATE EXTENSION injection_points;");
+ my $stderr = register_twice(
+ "SELECT injection_points_attach('test-shmem-request', 'error');");
+ my @failures =
+ ($stderr =~ /attempt \d: error triggered for injection point/g);
+ is(scalar @failures, 2,
+ "request callback failure is reported on both attempts");
+ unlike($stderr, qr/server closed the connection/,
+ "request callback failure does not crash the retry");
+ $node->safe_psql("postgres",
+ "SELECT injection_points_detach('test-shmem-request');");
+}
+
+my $stderr = register_twice("SET test_shmem.area_size = '1GB';");
+my @failures = ($stderr =~ /attempt \d: not enough shared memory/g);
+is(scalar @failures, 2, "allocation failure is reported on both attempts");
+unlike($stderr, qr/server closed the connection/,
+ "allocation failure does not crash the retry");
+
# Check that the attach counter is incremented on a new connection
my $attach_count1 =
$node->safe_psql("postgres", "SELECT get_test_shmem_attach_count();");
diff --git a/src/test/modules/test_shmem/test_shmem--1.0.sql b/src/test/modules/test_shmem/test_shmem--1.0.sql
index 2d01fd9256c..27cb75f6020 100644
--- a/src/test/modules/test_shmem/test_shmem--1.0.sql
+++ b/src/test/modules/test_shmem/test_shmem--1.0.sql
@@ -7,3 +7,7 @@
CREATE FUNCTION get_test_shmem_attach_count()
RETURNS pg_catalog.int4 STRICT
AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_shmem_register()
+RETURNS pg_catalog.void STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
diff --git a/src/test/modules/test_shmem/test_shmem.c b/src/test/modules/test_shmem/test_shmem.c
index 9bd4012b435..c96e224a994 100644
--- a/src/test/modules/test_shmem/test_shmem.c
+++ b/src/test/modules/test_shmem/test_shmem.c
@@ -17,9 +17,13 @@
#include "postgres.h"
+#include <limits.h>
+
#include "fmgr.h"
#include "miscadmin.h"
#include "storage/shmem.h"
+#include "utils/guc.h"
+#include "utils/injection_point.h"
PG_MODULE_MAGIC;
@@ -34,6 +38,9 @@ typedef struct TestShmemData
static TestShmemData *TestShmem;
static bool attached_or_initialized = false;
+static int test_shmem_area_size = sizeof(TestShmemData);
+static bool test_shmem_after_startup = false;
+static char test_shmem_area_name[64] = "test_shmem area";
static void test_shmem_request(void *arg);
static void test_shmem_init(void *arg);
@@ -51,9 +58,18 @@ test_shmem_request(void *arg)
{
elog(LOG, "test_shmem_request callback called");
- ShmemRequestStruct(.name = "test_shmem area",
- .size = sizeof(TestShmemData),
+ if (test_shmem_area_size == sizeof(TestShmemData))
+ strcpy(test_shmem_area_name, "test_shmem area");
+ else
+ snprintf(test_shmem_area_name, sizeof(test_shmem_area_name),
+ "test_shmem area %d", test_shmem_area_size);
+
+ ShmemRequestStruct(.name = test_shmem_area_name,
+ .size = test_shmem_area_size,
.ptr = (void **) &TestShmem);
+
+ if (test_shmem_after_startup)
+ INJECTION_POINT("test-shmem-request", NULL);
}
static void
@@ -86,7 +102,27 @@ void
_PG_init(void)
{
elog(LOG, "test_shmem module's _PG_init called");
+
+ DefineCustomIntVariable("test_shmem.area_size",
+ "Size of the shmem area to request.",
+ NULL,
+ &test_shmem_area_size,
+ sizeof(TestShmemData),
+ sizeof(TestShmemData), INT_MAX,
+ PGC_USERSET,
+ GUC_UNIT_BYTE,
+ NULL, NULL, NULL);
+ MarkGUCPrefixReserved("test_shmem");
+ RegisterShmemCallbacks(&TestShmemCallbacks);
+}
+
+PG_FUNCTION_INFO_V1(test_shmem_register);
+Datum
+test_shmem_register(PG_FUNCTION_ARGS)
+{
+ test_shmem_after_startup = true;
RegisterShmemCallbacks(&TestShmemCallbacks);
+ PG_RETURN_VOID();
}
PG_FUNCTION_INFO_V1(get_test_shmem_attach_count);
--
2.34.1
v2-0002-Roll-back-unfinished-after-startup-shmem-initiali.patch (application/octet-stream, 11.5K) download
From 593d5a790fbfd54a984162b51ac75a81daff33f9 Mon Sep 17 00:00:00 2001
From: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Date: Sun, 9 Aug 2026 16:29:50 +0530
Subject: [PATCH v2 2/3] Roll back unfinished after-startup shmem
initialization
An after-startup registration can fail after inserting some or all of its
areas into ShmemIndex but before init_fn completes. Leaving those entries
visible lets a later backend attach to memory that was never fully initialized.
A partly inserted batch also cannot be retried because it contains a mixture
of existing and missing names.
On an error while creating new areas, remove all names in the request from
ShmemIndex and clear their backend-local handles. ShmemIndexLock is still
held at this point, and none of the names existed before the attempt, so the
rollback cannot remove another subsystem's entry. The allocated bytes cannot
be reclaimed, but they are no longer reachable through the index, and a later
attempt can reuse the names.
Do not roll back the attach path: those areas were initialized by another
backend and remain valid even if this backend's attach_fn fails.
Document this behavior and test partial allocation, init_fn failure, and
successful reuse of the rolled-back names.
Author: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
---
doc/src/sgml/xfunc.sgml | 7 +++
src/backend/storage/ipc/shmem.c | 63 ++++++++++++++++++-
.../test_shmem/t/001_late_shmem_alloc.pl | 48 ++++++++++++++
.../modules/test_shmem/test_shmem--1.0.sql | 4 ++
src/test/modules/test_shmem/test_shmem.c | 22 +++++++
5 files changed, 142 insertions(+), 2 deletions(-)
diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml
index 2b8a11e7ad0..9269f72c847 100644
--- a/doc/src/sgml/xfunc.sgml
+++ b/doc/src/sgml/xfunc.sgml
@@ -3742,6 +3742,13 @@ my_shmem_init(void *arg)
lock (ShmemIndexLock), which prevents the race condition of two backends
trying to initialize the memory area at the same time.
</para>
+ <para>
+ If the call fails while creating the areas, their names are removed from
+ the shared memory index and the associated backend-local handles are
+ cleared, so that no backend can use memory that was not fully
+ initialized. The allocation itself cannot be reclaimed, however, and
+ reduces the space available to a later attempt.
+ </para>
</sect3>
<sect3 id="xfunc-shared-addin-dynamic">
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index a16e9388aad..ee619bd4e5a 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -213,6 +213,14 @@ enum shmem_request_state
};
static enum shmem_request_state shmem_request_state = SRS_INITIAL;
+/*
+ * True while an after-startup registration is creating its areas, that is,
+ * between the point where the first ShmemIndex entry is made and the point
+ * where the init_fn callback returns. Until then the areas hold garbage, so
+ * an error in that window has to undo them.
+ */
+static bool late_shmem_init_in_progress = false;
+
/*
* This is the first data structure stored in the shared memory segment, at
* the offset that PGShmemHeader->content_offset points to. Allocations by
@@ -276,6 +284,7 @@ static bool firstNumaTouch = true;
static void CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks);
static void CallShmemCallbacksAfterStartupInternal(const ShmemCallbacks *callbacks);
static void DiscardPendingShmemRequests(void);
+static void RollbackLateShmemInit(void);
static void InitShmemIndexEntry(ShmemRequest *request);
static bool AttachShmemIndexEntry(ShmemRequest *request, bool missing_ok);
@@ -912,7 +921,10 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
}
PG_FINALLY();
{
+ if (late_shmem_init_in_progress)
+ RollbackLateShmemInit();
DiscardPendingShmemRequests();
+ late_shmem_init_in_progress = false;
shmem_request_state = SRS_DONE;
}
PG_END_TRY();
@@ -924,7 +936,6 @@ CallShmemCallbacksAfterStartupInternal(const ShmemCallbacks *callbacks)
bool found_any;
bool notfound_any;
-
/*
* Call the request callback first. The callback makes ShmemRequest*()
* calls for each shmem area, adding them to pending_shmem_requests.
@@ -963,6 +974,8 @@ CallShmemCallbacksAfterStartupInternal(const ShmemCallbacks *callbacks)
if (found_any && notfound_any)
elog(ERROR, "some of the requested shmem areas have already been initialized");
+ late_shmem_init_in_progress = !found_any;
+
/*
* Allocate or attach all the shmem areas requested by the request_fn
* callback.
@@ -973,7 +986,6 @@ CallShmemCallbacksAfterStartupInternal(const ShmemCallbacks *callbacks)
AttachShmemIndexEntry(request, false);
else
InitShmemIndexEntry(request);
-
}
/* Finish by calling the appropriate subsystem-specific callback */
@@ -988,9 +1000,56 @@ CallShmemCallbacksAfterStartupInternal(const ShmemCallbacks *callbacks)
callbacks->init_fn(callbacks->opaque_arg);
}
+ late_shmem_init_in_progress = false;
LWLockRelease(ShmemIndexLock);
}
+/*
+ * Undo the visible parts of an initialization that did not finish. The
+ * shared memory itself cannot be reclaimed, but removing the index entries
+ * prevents another backend from attaching to it and makes the names usable
+ * by a later attempt.
+ *
+ * This is called only on the create path, while ShmemIndexLock is still held,
+ * so any matching entries were inserted by this attempt.
+ */
+static void
+RollbackLateShmemInit(void)
+{
+ Assert(LWLockHeldByMe(ShmemIndexLock));
+
+ foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+ {
+ if (hash_search(ShmemIndex, request->options->name,
+ HASH_REMOVE, NULL) == NULL)
+ continue;
+
+ switch (request->kind)
+ {
+ case SHMEM_KIND_STRUCT:
+ if (request->options->ptr)
+ *(request->options->ptr) = NULL;
+ break;
+ case SHMEM_KIND_HASH:
+ {
+ ShmemHashOpts *options = (ShmemHashOpts *) request->options;
+
+ if (options->ptr)
+ *(options->ptr) = NULL;
+ break;
+ }
+ case SHMEM_KIND_SLRU:
+ {
+ SlruOpts *options = (SlruOpts *) request->options;
+
+ if (options->desc)
+ options->desc->shared = NULL;
+ break;
+ }
+ }
+ }
+}
+
/* Release the requests accumulated by a request_fn callback. */
static void
DiscardPendingShmemRequests(void)
diff --git a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
index 22c49686d73..a85d5df4d0f 100644
--- a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
+++ b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
@@ -69,6 +69,54 @@ is(scalar @failures, 2, "allocation failure is reported on both attempts");
unlike($stderr, qr/server closed the connection/,
"allocation failure does not crash the retry");
+
+# A partly allocated batch is rolled back from ShmemIndex, although its bytes
+# cannot be reclaimed. The same names can therefore be used by a smaller
+# retry, and the failed attempt leaves no usable local handle.
+my $result = $node->safe_psql("postgres", q[
+LOAD 'test_shmem';
+SET test_shmem.area_size = '1kB';
+SET test_shmem.extra_size = '1GB';
+DO $$ BEGIN PERFORM test_shmem_register(); EXCEPTION WHEN others THEN END $$;
+SELECT test_shmem_area_is_null(),
+ (SELECT count(*)
+ FROM pg_shmem_allocations
+ WHERE name IN ('test_shmem area 1024', 'test_shmem extra area'));]);
+is($result, "t|0", "partial allocation is hidden and its names are reusable");
+
+$result = $node->safe_psql("postgres", q[
+LOAD 'test_shmem';
+SET test_shmem.area_size = '1kB';
+DO $$ BEGIN PERFORM test_shmem_register(); END $$;
+SELECT get_test_shmem_attach_count();]);
+is($result, '0', "a smaller request can reuse a rolled-back name");
+
+SKIP:
+{
+ skip "injection points not supported by this build", 2
+ if $ENV{enable_injection_points} ne 'yes';
+
+ $node->safe_psql("postgres", "CREATE EXTENSION IF NOT EXISTS injection_points;");
+ $result = $node->safe_psql("postgres", q[
+LOAD 'test_shmem';
+DO $$ BEGIN PERFORM injection_points_attach('test-shmem-init', 'error'); END $$;
+SET test_shmem.area_size = '2kB';
+DO $$ BEGIN PERFORM test_shmem_register(); EXCEPTION WHEN others THEN END $$;
+SELECT test_shmem_area_is_null(),
+ (SELECT count(*)
+ FROM pg_shmem_allocations
+ WHERE name = 'test_shmem area 2048');]);
+ is($result, "t|0", "an init callback failure is rolled back");
+ $node->safe_psql("postgres",
+ "SELECT injection_points_detach('test-shmem-init');");
+ $result = $node->safe_psql("postgres", q[
+LOAD 'test_shmem';
+SET test_shmem.area_size = '2kB';
+DO $$ BEGIN PERFORM test_shmem_register(); END $$;
+SELECT get_test_shmem_attach_count();]);
+ is($result, '0', "a name is reusable after an init callback failure");
+}
+
# Check that the attach counter is incremented on a new connection
my $attach_count1 =
$node->safe_psql("postgres", "SELECT get_test_shmem_attach_count();");
diff --git a/src/test/modules/test_shmem/test_shmem--1.0.sql b/src/test/modules/test_shmem/test_shmem--1.0.sql
index 27cb75f6020..7a358a2752b 100644
--- a/src/test/modules/test_shmem/test_shmem--1.0.sql
+++ b/src/test/modules/test_shmem/test_shmem--1.0.sql
@@ -11,3 +11,7 @@ AS 'MODULE_PATHNAME' LANGUAGE C;
CREATE FUNCTION test_shmem_register()
RETURNS pg_catalog.void STRICT
AS 'MODULE_PATHNAME' LANGUAGE C;
+
+CREATE FUNCTION test_shmem_area_is_null()
+RETURNS pg_catalog.bool STRICT
+AS 'MODULE_PATHNAME' LANGUAGE C;
diff --git a/src/test/modules/test_shmem/test_shmem.c b/src/test/modules/test_shmem/test_shmem.c
index c96e224a994..62cb7bc5645 100644
--- a/src/test/modules/test_shmem/test_shmem.c
+++ b/src/test/modules/test_shmem/test_shmem.c
@@ -40,6 +40,7 @@ static TestShmemData *TestShmem;
static bool attached_or_initialized = false;
static int test_shmem_area_size = sizeof(TestShmemData);
static bool test_shmem_after_startup = false;
+static int test_shmem_extra_size = 0;
static char test_shmem_area_name[64] = "test_shmem area";
static void test_shmem_request(void *arg);
@@ -67,6 +68,9 @@ test_shmem_request(void *arg)
ShmemRequestStruct(.name = test_shmem_area_name,
.size = test_shmem_area_size,
.ptr = (void **) &TestShmem);
+ if (test_shmem_extra_size > 0)
+ ShmemRequestStruct(.name = "test_shmem extra area",
+ .size = test_shmem_extra_size);
if (test_shmem_after_startup)
INJECTION_POINT("test-shmem-request", NULL);
@@ -76,6 +80,8 @@ static void
test_shmem_init(void *arg)
{
elog(LOG, "init callback called");
+ if (test_shmem_after_startup)
+ INJECTION_POINT("test-shmem-init", NULL);
if (TestShmem->initialized)
elog(ERROR, "shmem area already initialized");
TestShmem->initialized = true;
@@ -112,6 +118,14 @@ _PG_init(void)
PGC_USERSET,
GUC_UNIT_BYTE,
NULL, NULL, NULL);
+ DefineCustomIntVariable("test_shmem.extra_size",
+ "Size of an additional area in the same request.",
+ NULL,
+ &test_shmem_extra_size,
+ 0, 0, INT_MAX,
+ PGC_USERSET,
+ GUC_UNIT_BYTE,
+ NULL, NULL, NULL);
MarkGUCPrefixReserved("test_shmem");
RegisterShmemCallbacks(&TestShmemCallbacks);
}
@@ -121,10 +135,18 @@ Datum
test_shmem_register(PG_FUNCTION_ARGS)
{
test_shmem_after_startup = true;
+ attached_or_initialized = false;
RegisterShmemCallbacks(&TestShmemCallbacks);
PG_RETURN_VOID();
}
+PG_FUNCTION_INFO_V1(test_shmem_area_is_null);
+Datum
+test_shmem_area_is_null(PG_FUNCTION_ARGS)
+{
+ PG_RETURN_BOOL(TestShmem == NULL);
+}
+
PG_FUNCTION_INFO_V1(get_test_shmem_attach_count);
Datum
get_test_shmem_attach_count(PG_FUNCTION_ARGS)
--
2.34.1
v2-0003-Reject-legacy-shmem-allocation-from-init-and-atta.patch (application/octet-stream, 5.3K) download
From e3795b162dc8a316966b5e197828b3df16ecf072 Mon Sep 17 00:00:00 2001
From: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Date: Sun, 9 Aug 2026 16:34:27 +0530
Subject: [PATCH v2 3/3] Reject legacy shmem allocation from init and attach
callbacks
After startup, init_fn and attach_fn run while ShmemIndexLock is held.
ShmemInitStruct() takes the same lock, so calling it from either callback
asserts in an assert-enabled build and deadlocks otherwise.
Reject ShmemInitStruct() in the callback states with a direct error. This
also covers ShmemInitHash(), which calls ShmemInitStruct(). Legacy calls
during postmaster startup remain allowed for compatibility.
Document the restriction and test the init_fn case.
Author: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
---
doc/src/sgml/xfunc.sgml | 7 +++++++
src/backend/storage/ipc/shmem.c | 4 ++++
src/test/modules/test_shmem/t/001_late_shmem_alloc.pl | 11 +++++++++++
src/test/modules/test_shmem/test_shmem--1.0.sql | 2 +-
src/test/modules/test_shmem/test_shmem.c | 8 ++++++++
5 files changed, 31 insertions(+), 1 deletion(-)
diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml
index 9269f72c847..a3dc603049d 100644
--- a/doc/src/sgml/xfunc.sgml
+++ b/doc/src/sgml/xfunc.sgml
@@ -3749,6 +3749,13 @@ my_shmem_init(void *arg)
initialized. The allocation itself cannot be reclaimed, however, and
reduces the space available to a later attempt.
</para>
+ <para>
+ When the callbacks are run after startup, the legacy
+ <function>ShmemInitStruct()</function> and
+ <function>ShmemInitHash()</function> functions cannot be called from
+ <function>init_fn</function> or <function>attach_fn</function>. Request
+ all areas from <function>request_fn</function> instead.
+ </para>
</sect3>
<sect3 id="xfunc-shared-addin-dynamic">
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index ee619bd4e5a..bed92e6d62f 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -1106,6 +1106,10 @@ ShmemInitStruct(const char *name, Size size, bool *foundPtr)
};
ShmemRequest request = {&options, SHMEM_KIND_STRUCT};
+ if (shmem_request_state == SRS_ATTACHING ||
+ shmem_request_state == SRS_AFTER_STARTUP_ATTACH_OR_INIT)
+ elog(ERROR, "cannot call ShmemInitStruct() from a shmem init or attach callback");
+
Assert(shmem_request_state == SRS_DONE ||
shmem_request_state == SRS_INITIALIZING ||
shmem_request_state == SRS_REQUESTING);
diff --git a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
index a85d5df4d0f..bbbec4dda92 100644
--- a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
+++ b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
@@ -117,6 +117,17 @@ SELECT get_test_shmem_attach_count();]);
is($result, '0', "a name is reusable after an init callback failure");
}
+
+my (undef, undef, $legacy_stderr) = $node->psql(
+ "postgres", q[
+LOAD 'test_shmem';
+SET test_shmem.area_size = '3kB';
+SELECT test_shmem_register(true);],
+ timeout => $PostgreSQL::Test::Utils::timeout_default);
+like($legacy_stderr,
+ qr/cannot call ShmemInitStruct\(\) from a shmem init or attach callback/,
+ "legacy allocation from an init callback is rejected");
+
# Check that the attach counter is incremented on a new connection
my $attach_count1 =
$node->safe_psql("postgres", "SELECT get_test_shmem_attach_count();");
diff --git a/src/test/modules/test_shmem/test_shmem--1.0.sql b/src/test/modules/test_shmem/test_shmem--1.0.sql
index 7a358a2752b..ca42274d7bc 100644
--- a/src/test/modules/test_shmem/test_shmem--1.0.sql
+++ b/src/test/modules/test_shmem/test_shmem--1.0.sql
@@ -8,7 +8,7 @@ CREATE FUNCTION get_test_shmem_attach_count()
RETURNS pg_catalog.int4 STRICT
AS 'MODULE_PATHNAME' LANGUAGE C;
-CREATE FUNCTION test_shmem_register()
+CREATE FUNCTION test_shmem_register(pg_catalog.bool DEFAULT false)
RETURNS pg_catalog.void STRICT
AS 'MODULE_PATHNAME' LANGUAGE C;
diff --git a/src/test/modules/test_shmem/test_shmem.c b/src/test/modules/test_shmem/test_shmem.c
index 62cb7bc5645..1322c457e34 100644
--- a/src/test/modules/test_shmem/test_shmem.c
+++ b/src/test/modules/test_shmem/test_shmem.c
@@ -41,6 +41,7 @@ static bool attached_or_initialized = false;
static int test_shmem_area_size = sizeof(TestShmemData);
static bool test_shmem_after_startup = false;
static int test_shmem_extra_size = 0;
+static bool test_shmem_legacy_init = false;
static char test_shmem_area_name[64] = "test_shmem area";
static void test_shmem_request(void *arg);
@@ -82,6 +83,12 @@ test_shmem_init(void *arg)
elog(LOG, "init callback called");
if (test_shmem_after_startup)
INJECTION_POINT("test-shmem-init", NULL);
+ if (test_shmem_legacy_init)
+ {
+ bool found;
+
+ (void) ShmemInitStruct("test_shmem legacy area", 1024, &found);
+ }
if (TestShmem->initialized)
elog(ERROR, "shmem area already initialized");
TestShmem->initialized = true;
@@ -134,6 +141,7 @@ PG_FUNCTION_INFO_V1(test_shmem_register);
Datum
test_shmem_register(PG_FUNCTION_ARGS)
{
+ test_shmem_legacy_init = PG_NARGS() > 0 && PG_GETARG_BOOL(0);
test_shmem_after_startup = true;
attached_or_initialized = false;
RegisterShmemCallbacks(&TestShmemCallbacks);
--
2.34.1
^ permalink raw reply [nested|flat] 21+ messages in thread
* Re: Error handling in after-startup shmem requests
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-09 16:30 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
@ 2026-08-10 09:40 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-10 12:40 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
0 siblings, 1 reply; 21+ messages in thread
From: Ashutosh Bapat @ 2026-08-10 09:40 UTC (permalink / raw)
To: Ayush Tiwari <ayushtiwari.slg01@gmail.com>; +Cc: pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>
On Sun, Aug 9, 2026 at 10:00 PM Ayush Tiwari
<ayushtiwari.slg01@gmail.com> wrote:
>
>> > 0001 collects the requests in a context of our own instead, with a reset
>> > callback that clears pending_shmem_requests and shmem_request_state. That
>> > way the cleanup happens on the error path as well, without adding any
>> > PG_TRY blocks, and the startup paths are left alone. Initially I had thought of using
>> > the TRY/CATCH blocks, but went the other way.
>> >
>>
>> The fix seems more complicated than necessary.
>> ShmemRequestStructWithOpts() allocates the options in
>> TopMemoryContext, I think we should do the same with ShmemRequests or
>> at least the context should be child of TopMemoryContext which
>> outlives any query or transaction. I also think that a simple
>> PG_TRY/PG_FINALLY block should be enough to release all pending
>> requests after an error and also to set shmem_request_state. You have
>> mentioned that you thought of using it but did not mention why you
>> discarded that approach? It will save a bunch of code.
>
>
> I initially tried to tie the cleanup to a memory context. Looking at it
> again, the CurrentMemoryContext fallback is not necessarily reset after
> an error, particularly when there is no transaction in progress. That
> does not seem reliable enough for this path.
>
> 0001 now allocates the request records and list cells in
> TopMemoryContext, like the options, and cleans them up from PG_FINALLY.
> Does this look closer to the intended pattern?
>
>>
>> The test could use INJECTION_POINT and avoid creating a new set of
>> callbacks. To induce large sized failure, I would introduce a
>> test_shmem GUC which to decide the size of shared memory allocation
>> and set it to a high value before requesting memory.
>
>
> Thanks for this idea.
> I reworked the tests that way. They now use the existing callbacks, a
> size GUC, and injection points; the extra callback set and TAP file have
> been removed.
>
/* Request looks valid, remember it */
+ /* Keep the requests and list cells alive until we explicitly free them. */
The comment actually doesn't make much sense. What does it have to do
with keeping the requests alive until freeing them with allocating
memory in TopMemoryContext? If it has to, it should rather explain why
we want them to be alive or why to save them in TopMemoryContext. The
previous comment which you removed was making the point that we save
the request "after validating" it; I would leave the wording in tact.
+ oldcontext = MemoryContextSwitchTo(TopMemoryContext);
We should allocate the requests in the same context as the options
itself and blow up the whole context and set the list NIL.
+ PG_TRY();
+ {
+ CallShmemCallbacksAfterStartupInternal(callbacks);
If you do what I suggest earlier DiscardPendingShmemRequests() simply
becomes two statement - blow up the context, set the list NIL and rest
shmem_request_state. I don't think we need a separate function for
that. There is merit in having code of PG_TRY() and PG_FINALLY()
blocks in the same function, so that it is clear what is being done in
the try is visible when reading finally blocks. I would get rid of
CallShmemCallbacksAfterStartupInternal() and just push the current
code inside the PG_TRY() block and add PG_FINALLY() block after it.
+static int test_shmem_area_size = sizeof(TestShmemData);
+static bool test_shmem_after_startup = false;
+static char test_shmem_area_name[64] = "test_shmem area";
static void test_shmem_request(void *arg);
static void test_shmem_init(void *arg);
@@ -51,9 +58,18 @@ test_shmem_request(void *arg)
{
elog(LOG, "test_shmem_request callback called");
- ShmemRequestStruct(.name = "test_shmem area",
- .size = sizeof(TestShmemData),
+ if (test_shmem_area_size == sizeof(TestShmemData))
+ strcpy(test_shmem_area_name, "test_shmem area");
+ else
+ snprintf(test_shmem_area_name, sizeof(test_shmem_area_name),
+ "test_shmem area %d", test_shmem_area_size);
+
+ ShmemRequestStruct(.name = test_shmem_area_name,
+ .size = test_shmem_area_size,
.ptr = (void **) &TestShmem);
Heh. This is a clever idea to be able to create multiple shmem areas
from the same module, however, we don't need this complexity in test C
code. I would rather use $node->start, test, DROP EXTENSION,
$node->restart, CREATE EXTENSION sequence for loading the module
multiple times. That will also elimiate the need for the
test_shmem_register() function and register_twice function. I would
repeat that sequence to test the error cases first followed by
existing tests.
Additionally we could also test that even though the extension fails
to load, the shared memory areas are still created when the server
restarts if shared_preload_libraries has the extension library in it.
But I would hesitate to add that test case if the test code becomes
too complicated. But if you choose to add that test case, I would
suggest the we set the GUC to just above 100K to test the failure due
to lack of memory. Otherwise after restart the test will fail if the
machine, where test is run, does not have 1GB memory available.
+
+ if (test_shmem_after_startup)
+ INJECTION_POINT("test-shmem-request", NULL);
}
static void
@@ -86,7 +102,27 @@ void
_PG_init(void)
{
elog(LOG, "test_shmem module's _PG_init called");
+
+ DefineCustomIntVariable("test_shmem.area_size",
+ "Size of the shmem area to request.",
+ NULL,
+ &test_shmem_area_size,
+ sizeof(TestShmemData),
+ sizeof(TestShmemData), INT_MAX,
+ PGC_USERSET,
Shouldn't this be PGC_POSTMASTER? Changing this at run time won't be possible.
>>
>> > 2) A request batch that only partly fits
>> >
>> > If a request asks for several areas and a later one does not fit, the
>> > earlier ones stay allocated and registered. A retry then trips
>> >
>> > "some of the requested shmem areas have already been initialized"
>> >
>> > and, since shared memory is never freed, that looks permanent until a
>> > restart. Before this mechanism each area went through its own
>> > ShmemInitStruct() call, so the same situation could simply be retried.
>> > Should a batch be all-or-nothing here, or is this considered acceptable
>> > given that after-startup allocation is best-effort anyway?
>>
>> Even with ShmemInitStruct() a retry will still fail because of not
>> enough memory. Shared memory for after startup allocation is limited,
>> so even restarting the server won't fix it. The request has to be
>> reduced.
>>
>> Did we allow calling ShmemInitStruct() at run time before this
>> mechanism? Even if it were, the caller didn't have much choice about
>> the areas already created. In fact the situation would be bad, since
>> the areas which are allocated are not initialized but variables
>> pointing them are set. So if the caller is not careful, its code may
>> start using these areas.
>>
>> But with this mechanism we have choice. I think we should be able to
>> implement all-or-nothing. At the beginning of
>> CallShmemCallbacksAfterStartup() Remember the current allocation
>> offset. When allocating memory remember the requests that succeeded.
>> In case of failure, reset the allocation offset to the saved value and
>> remove the requested entries from ShmemIndex. But that seems a lot for
>> PG 19 at this stage. Maybe PG 20 material.
>>
>> I think we should document that if RegisterShmemCallbacks() called
>> after startup throws an error, the subsystems should make sure that
>> the shared structures are not accessed since they are not initialized,
>> possibly setting the corresponding pointers to NULL. Or actually we
>> should reset the pointers to NULL in CallShmemCallbacksAfterStartup()
>> before throwing an error. That won't be invasive fix.
>
>
> I first changed 0002 to reset the handles as suggested. That protects the
> backend in which the error occurred, but I do not think it is sufficient
> for the next backend. The entries inserted before the error remain in
> ShmemIndex. If all requested entries were inserted and init_fn then
> failed, a later backend would find all of them and call attach_fn on areas
> that were never fully initialized.
>
> That is why 0002 also removes the entries inserted by the failed create
> attempt. This is limited to the create path: entries found on the attach
> path belong to an earlier successful initialization and must remain
> visible. ShmemIndexLock is still held during the cleanup, and the initial
> lookup established that none of these names existed before this attempt.
>
> This is still only a partial rollback. It does not restore the allocation
> offset, so the bytes remain consumed and are reported as anonymous shared
> memory. Reusing the names also means repeated failures could consume more
> of the after-startup reserve. I was not sure whether preventing a later
> backend from attaching to unfinished memory justifies that behavior for
> PG 19. Would you prefer this partial rollback, or only resetting the
> handles and documenting that the subsystem must detect incomplete
> initialization, leaving the full offset-and-index rollback for PG 20?
>
Ah! I didn't see that the attach will still succeed if init_fn failed.
I don't think just removing the entries from the ShmemIndex is enough
without deallocating the corresponding memory. As you have rightly
pointed out the memory is accounted as anonymous allocation memory and
thus its source can not be investigated using pg_shmem_allocations.
Here's another possibility - in each of the shmem index entry we
maintain a flag to indicate whether the structure has been initialized
or not. Once all the init_fns complete we set flags of all the entries
that were added in that invocation of
CallShmemCallbacksAfterStartup(). In the attach pathway, we set the
pointers only for the entries which have their initialized flags set.
For all the entries added at the time of startup the flag is set as
the a failure in init_fn would result in a startup failure. For this
solution, we have to maintain a list of entries and go over it after
init_fn is called.
If this solution also turns out to be invasive, I guess, we should
just leave the things as is and document the behaviour. That's how it
have had been without the new infrastructure. Let's improve things in
PG 20 implementing proper rollback. Let's see what Heikki says.
>>
>> >
>> > 3) Legacy allocation from an init or attach callback
>> >
>> > The init and attach callbacks run with ShmemIndexLock held, and
>> > ShmemInitStruct() takes that same lock. Calling it from a callback,
>> > which seems like a natural thing to try when moving code over from
>> > shmem_startup_hook, trips an unrelated-looking state assertion in an
>> > assert-enabled build and hangs in a production build. Is it worth
>> > rejecting this explicitly, or would a note in the docs be enough?
>>
>> Why would ShmemInitStruct be called from a callback? The pointer to
>> the shared structure should have been set in the given
>> variables/addresses.
>
>
> I agree that it should not be needed there. My concern was the resulting
> diagnostic: it deadlocks in a normal build and reaches an unrelated state
> assertion in an assert build. 0003 checks the callback states and reports
> an error instead. Thoughts?
See 6f7199a1245cab986a13c7b57812255fe77679d1. The document mentions
that ShmemIndexLock is held when initializing the shared memory areas.
It's a known fact and probably also documented that trying to acquire
an already held LWLock causes deadlock. That's what you probably saw
with a normal build. The error message you have added is simply
checking the negation of the assertion. It is expected that the
extension authors will test their extension with Assertion enabled
build, encounter the assert and fix it. Why do we want to carry the
error in normal builds as well?
--
Best Wishes,
Ashutosh Bapat
^ permalink raw reply [nested|flat] 21+ messages in thread
* Re: Error handling in after-startup shmem requests
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-09 16:30 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-10 09:40 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
@ 2026-08-10 12:40 ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-11 15:46 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
0 siblings, 1 reply; 21+ messages in thread
From: Ayush Tiwari @ 2026-08-10 12:40 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>
Hi,
Thanks for the review!
On Mon, 10 Aug 2026 at 15:11, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
wrote:
> On Sun, Aug 9, 2026 at 10:00 PM Ayush Tiwari
> <ayushtiwari.slg01@gmail.com> wrote:
>
> /* Request looks valid, remember it */
> + /* Keep the requests and list cells alive until we explicitly free them.
> */
>
> The comment actually doesn't make much sense. What does it have to do
> with keeping the requests alive until freeing them with allocating
> memory in TopMemoryContext? If it has to, it should rather explain why
> we want them to be alive or why to save them in TopMemoryContext. The
> previous comment which you removed was making the point that we save
> the request "after validating" it; I would leave the wording in tact.
>
> + oldcontext = MemoryContextSwitchTo(TopMemoryContext);
>
> We should allocate the requests in the same context as the options
> itself and blow up the whole context and set the list NIL.
>
I have changed it along those lines. A request phase now creates one
memory context under TopMemoryContext. The copied options, ShmemRequest
records and list cells all live in that context, and the context is
removed when the request phase finishes.
I also changed ShmemRequestInternal() to take the size of the options
structure. This lets it validate the request first and then copy either
ShmemStructOpts, ShmemHashOpts or SlruOpts directly into the request
context. Does that seem like a reasonable way to keep the context owned
by shmem.c without exposing it to the hash and SLRU code?
>
> + PG_TRY();
> + {
> + CallShmemCallbacksAfterStartupInternal(callbacks);
>
> If you do what I suggest earlier DiscardPendingShmemRequests() simply
> becomes two statement - blow up the context, set the list NIL and rest
> shmem_request_state. I don't think we need a separate function for
> that. There is merit in having code of PG_TRY() and PG_FINALLY()
> blocks in the same function, so that it is clear what is being done in
> the try is visible when reading finally blocks. I would get rid of
> CallShmemCallbacksAfterStartupInternal() and just push the current
> code inside the PG_TRY() block and add PG_FINALLY() block after it.
>
Agreed. CallShmemCallbacksAfterStartup() now contains the complete body,
followed immediately by PG_FINALLY. FINALLY deletes the request context,
sets pending_shmem_requests to NIL and restores shmem_request_state. The
separate internal function and cleanup helper are gone. I had initially
added it
to make the diff smaller.
> +static int test_shmem_area_size = sizeof(TestShmemData);
> +static bool test_shmem_after_startup = false;
> +static char test_shmem_area_name[64] = "test_shmem area";
>
> static void test_shmem_request(void *arg);
> static void test_shmem_init(void *arg);
> @@ -51,9 +58,18 @@ test_shmem_request(void *arg)
> {
> elog(LOG, "test_shmem_request callback called");
>
> - ShmemRequestStruct(.name = "test_shmem area",
> - .size = sizeof(TestShmemData),
> + if (test_shmem_area_size == sizeof(TestShmemData))
> + strcpy(test_shmem_area_name, "test_shmem area");
> + else
> + snprintf(test_shmem_area_name, sizeof(test_shmem_area_name),
> + "test_shmem area %d", test_shmem_area_size);
> +
> + ShmemRequestStruct(.name = test_shmem_area_name,
> + .size = test_shmem_area_size,
> .ptr = (void **) &TestShmem);
>
> Heh. This is a clever idea to be able to create multiple shmem areas
> from the same module, however, we don't need this complexity in test C
> code. I would rather use $node->start, test, DROP EXTENSION,
> $node->restart, CREATE EXTENSION sequence for loading the module
> multiple times. That will also elimiate the need for the
> test_shmem_register() function and register_twice function. I would
> repeat that sequence to test the error cases first followed by
> existing tests.
> Additionally we could also test that even though the extension fails
> to load, the shared memory areas are still created when the server
> restarts if shared_preload_libraries has the extension library in it.
> But I would hesitate to add that test case if the test code becomes
> too complicated. But if you choose to add that test case, I would
> suggest the we set the GUC to just above 100K to test the failure due
> to lack of memory. Otherwise after restart the test will fail if the
> machine, where test is run, does not have 1GB memory available.
>
I simplified the tests as suggested: test_shmem now uses one fixed shmem
name, one size GUC and the existing TAP file.
I kept the two request-error attempts in the same backend, because
pending_shmem_requests and shmem_request_state are local to that backend.
A restart would clear the very state the test is meant to check. The test
therefore runs two failing CREATE EXTENSION commands in one psql session,
with an injection point just after request_fn.
For the out-of-memory case I used the restart/preload sequence you
suggested. A 128 kB request fails when test_shmem is loaded after startup,
but succeeds in a fresh cluster when test_shmem is preloaded.
> +
> + if (test_shmem_after_startup)
> + INJECTION_POINT("test-shmem-request", NULL);
> }
>
> static void
> @@ -86,7 +102,27 @@ void
> _PG_init(void)
> {
> elog(LOG, "test_shmem module's _PG_init called");
> +
> + DefineCustomIntVariable("test_shmem.area_size",
> + "Size of the shmem area to request.",
> + NULL,
> + &test_shmem_area_size,
> + sizeof(TestShmemData),
> + sizeof(TestShmemData), INT_MAX,
> + PGC_USERSET,
>
> Shouldn't this be PGC_POSTMASTER? Changing this at run time won't be
> possible.
>
I tried changing this to PGC_POSTMASTER. When test_shmem was first loaded
by CREATE EXTENSION after startup, _PG_init() failed with:
FATAL: cannot create PGC_POSTMASTER variables after startup
Pre-setting test_shmem.area_size as a placeholder gave the same result;
init_custom_variable() performs this check before placeholder replacement.
I have therefore kept it PGC_USERSET as a test-only control for the size
passed by request_fn.
> >>
> >> > 2) A request batch that only partly fits
> >> >
> >> > If a request asks for several areas and a later one does not fit, the
> >> > earlier ones stay allocated and registered. A retry then trips
> >> >
> >> > "some of the requested shmem areas have already been initialized"
> >> >
> >> > and, since shared memory is never freed, that looks permanent until a
> >> > restart. Before this mechanism each area went through its own
> >> > ShmemInitStruct() call, so the same situation could simply be retried.
> >> > Should a batch be all-or-nothing here, or is this considered
> acceptable
> >> > given that after-startup allocation is best-effort anyway?
> >>
> >> Even with ShmemInitStruct() a retry will still fail because of not
> >> enough memory. Shared memory for after startup allocation is limited,
> >> so even restarting the server won't fix it. The request has to be
> >> reduced.
> >>
> >> Did we allow calling ShmemInitStruct() at run time before this
> >> mechanism? Even if it were, the caller didn't have much choice about
> >> the areas already created. In fact the situation would be bad, since
> >> the areas which are allocated are not initialized but variables
> >> pointing them are set. So if the caller is not careful, its code may
> >> start using these areas.
> >>
> >> But with this mechanism we have choice. I think we should be able to
> >> implement all-or-nothing. At the beginning of
> >> CallShmemCallbacksAfterStartup() Remember the current allocation
> >> offset. When allocating memory remember the requests that succeeded.
> >> In case of failure, reset the allocation offset to the saved value and
> >> remove the requested entries from ShmemIndex. But that seems a lot for
> >> PG 19 at this stage. Maybe PG 20 material.
> >>
> >> I think we should document that if RegisterShmemCallbacks() called
> >> after startup throws an error, the subsystems should make sure that
> >> the shared structures are not accessed since they are not initialized,
> >> possibly setting the corresponding pointers to NULL. Or actually we
> >> should reset the pointers to NULL in CallShmemCallbacksAfterStartup()
> >> before throwing an error. That won't be invasive fix.
> >
> >
> > I first changed 0002 to reset the handles as suggested. That protects
> the
> > backend in which the error occurred, but I do not think it is sufficient
> > for the next backend. The entries inserted before the error remain in
> > ShmemIndex. If all requested entries were inserted and init_fn then
> > failed, a later backend would find all of them and call attach_fn on
> areas
> > that were never fully initialized.
> >
> > That is why 0002 also removes the entries inserted by the failed create
> > attempt. This is limited to the create path: entries found on the attach
> > path belong to an earlier successful initialization and must remain
> > visible. ShmemIndexLock is still held during the cleanup, and the
> initial
> > lookup established that none of these names existed before this attempt.
> >
> > This is still only a partial rollback. It does not restore the
> allocation
> > offset, so the bytes remain consumed and are reported as anonymous shared
> > memory. Reusing the names also means repeated failures could consume
> more
> > of the after-startup reserve. I was not sure whether preventing a later
> > backend from attaching to unfinished memory justifies that behavior for
> > PG 19. Would you prefer this partial rollback, or only resetting the
> > handles and documenting that the subsystem must detect incomplete
> > initialization, leaving the full offset-and-index rollback for PG 20?
> >
>
> Ah! I didn't see that the attach will still succeed if init_fn failed.
> I don't think just removing the entries from the ShmemIndex is enough
> without deallocating the corresponding memory. As you have rightly
> pointed out the memory is accounted as anonymous allocation memory and
> thus its source can not be investigated using pg_shmem_allocations.
>
> Here's another possibility - in each of the shmem index entry we
> maintain a flag to indicate whether the structure has been initialized
> or not. Once all the init_fns complete we set flags of all the entries
> that were added in that invocation of
> CallShmemCallbacksAfterStartup(). In the attach pathway, we set the
> pointers only for the entries which have their initialized flags set.
> For all the entries added at the time of startup the flag is set as
> the a failure in init_fn would result in a startup failure. For this
> solution, we have to maintain a list of entries and go over it after
> init_fn is called.
>
> If this solution also turns out to be invasive, I guess, we should
> just leave the things as is and document the behaviour. That's how it
> have had been without the new infrastructure. Let's improve things in
> PG 20 implementing proper rollback. Let's see what Heikki says.
>
The initialized flag seems safer than removing ShmemIndex entries without
restoring the allocation offset. It would, however, change ShmemIndexEnt
and all startup, initialization and attachment paths. I have therefore
dropped that patch from v3 and added only documentation for the current
behavior: an area allocated before init_fn fails remains discoverable, and
the subsystem must detect and avoid incomplete shared state.
> >>
> >> >
> >> > 3) Legacy allocation from an init or attach callback
> >> >
> >> > The init and attach callbacks run with ShmemIndexLock held, and
> >> > ShmemInitStruct() takes that same lock. Calling it from a callback,
> >> > which seems like a natural thing to try when moving code over from
> >> > shmem_startup_hook, trips an unrelated-looking state assertion in an
> >> > assert-enabled build and hangs in a production build. Is it worth
> >> > rejecting this explicitly, or would a note in the docs be enough?
> >>
> >> Why would ShmemInitStruct be called from a callback? The pointer to
> >> the shared structure should have been set in the given
> >> variables/addresses.
> >
> >
> > I agree that it should not be needed there. My concern was the resulting
> > diagnostic: it deadlocks in a normal build and reaches an unrelated state
> > assertion in an assert build. 0003 checks the callback states and
> reports
> > an error instead. Thoughts?
>
> See 6f7199a1245cab986a13c7b57812255fe77679d1. The document mentions
> that ShmemIndexLock is held when initializing the shared memory areas.
> It's a known fact and probably also documented that trying to acquire
> an already held LWLock causes deadlock. That's what you probably saw
> with a normal build. The error message you have added is simply
> checking the negation of the assertion. It is expected that the
> extension authors will test their extension with Assertion enabled
> build, encounter the assert and fix it. Why do we want to carry the
> error in normal builds as well?
>
Dropped that patch too.
Attachments:
v3-0001-Fix-cleanup-after-failed-after-startup-shmem-requ.patch (application/octet-stream, 19.1K) download
From ba55c513a80b3eae391359893f3bbdeb055e4ba6 Mon Sep 17 00:00:00 2001
From: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Date: Mon, 10 Aug 2026 17:10:25 +0530
Subject: [PATCH v3] Fix cleanup after failed after-startup shmem requests
CallShmemCallbacksAfterStartup() cleared pending_shmem_requests and reset
shmem_request_state only on success. The request records and list cells lived
in the caller's memory context while the options lived in TopMemoryContext, so
an error could leave the global list pointing at released memory. A second
attempt in the same backend then walked a dangling list and failed the
IsPointerList assertion. The stale state also made later registrations take
the "remember for later" path instead of running immediately.
Allocate the options, request records and list cells in one child of
TopMemoryContext. Wrap the complete after-startup operation in PG_TRY and
PG_FINALLY, deleting that context and restoring shmem_request_state on both
success and error. Use the same context for startup and EXEC_BACKEND request
collection, where successful cleanup can delete it directly.
Document that shared areas allocated before a later error cannot be reclaimed
and must not be used unless init_fn completed. This patch does not attempt to
roll back shared allocation or ShmemIndex entries.
Add focused tests for errors immediately after request_fn and during late
allocation. The request error is retried in one backend, because the damaged
state is backend-local. Also verify that the same 128 kB request which fails
when loaded late succeeds when test_shmem is preloaded.
Author: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
---
doc/src/sgml/xfunc.sgml | 7 +
src/backend/access/transam/slru.c | 14 +-
src/backend/storage/ipc/shmem.c | 185 ++++++++++--------
src/backend/storage/ipc/shmem_hash.c | 15 +-
src/include/storage/shmem_internal.h | 3 +-
src/test/modules/test_shmem/Makefile | 3 +
src/test/modules/test_shmem/meson.build | 3 +
.../test_shmem/t/001_late_shmem_alloc.pl | 45 +++++
src/test/modules/test_shmem/test_shmem.c | 22 ++-
9 files changed, 196 insertions(+), 101 deletions(-)
diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml
index 2b8a11e7ad0..f7d095e4640 100644
--- a/doc/src/sgml/xfunc.sgml
+++ b/doc/src/sgml/xfunc.sgml
@@ -3742,6 +3742,13 @@ my_shmem_init(void *arg)
lock (ShmemIndexLock), which prevents the race condition of two backends
trying to initialize the memory area at the same time.
</para>
+ <para>
+ If after-startup initialization fails, any areas allocated before the
+ error remain in the shared memory index. A later backend can therefore
+ find them even though <function>init_fn</function> did not complete.
+ Subsystems must detect that case and not use incompletely initialized
+ shared state.
+ </para>
</sect3>
<sect3 id="xfunc-shared-addin-dynamic">
diff --git a/src/backend/access/transam/slru.c b/src/backend/access/transam/slru.c
index 47dd52d6749..4e89d797772 100644
--- a/src/backend/access/transam/slru.c
+++ b/src/backend/access/transam/slru.c
@@ -245,21 +245,21 @@ SimpleLruAutotuneBuffers(int divisor, int max)
void
SimpleLruRequestWithOpts(const SlruOpts *options)
{
- SlruOpts *options_copy;
+ SlruOpts options_copy;
Assert(options->name != NULL);
Assert(options->nslots > 0);
Assert(options->PagePrecedes != NULL);
Assert(options->errdetail_for_io_error != NULL);
- options_copy = MemoryContextAlloc(TopMemoryContext,
- sizeof(SlruOpts));
- memcpy(options_copy, options, sizeof(SlruOpts));
+ memcpy(&options_copy, options, sizeof(SlruOpts));
- options_copy->base.name = options->name;
- options_copy->base.size = SimpleLruShmemSize(options_copy->nslots, options_copy->nlsns);
+ options_copy.base.name = options->name;
+ options_copy.base.size = SimpleLruShmemSize(options_copy.nslots,
+ options_copy.nlsns);
- ShmemRequestInternal(&options_copy->base, SHMEM_KIND_SLRU);
+ ShmemRequestInternal(&options_copy.base, sizeof(SlruOpts),
+ SHMEM_KIND_SLRU);
}
/* Initialize locks and shared memory area */
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index a3d56cf55dd..0a04b0e83c0 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -142,6 +142,8 @@
#include "storage/shmem_internal.h"
#include "storage/spin.h"
#include "utils/builtins.h"
+#include "utils/injection_point.h"
+#include "utils/memutils.h"
#include "utils/tuplestore.h"
/*
@@ -167,6 +169,7 @@ typedef struct
} ShmemRequest;
static List *pending_shmem_requests;
+static MemoryContext pending_shmem_requests_context;
/*
* Per-process state machine, for sanity checking that we do things in the
@@ -314,28 +317,23 @@ Datum pg_numa_available(PG_FUNCTION_ARGS);
void
ShmemRequestStructWithOpts(const ShmemStructOpts *options)
{
- ShmemStructOpts *options_copy;
-
- options_copy = MemoryContextAlloc(TopMemoryContext,
- sizeof(ShmemStructOpts));
- memcpy(options_copy, options, sizeof(ShmemStructOpts));
-
- ShmemRequestInternal(options_copy, SHMEM_KIND_STRUCT);
+ ShmemRequestInternal(options, sizeof(ShmemStructOpts), SHMEM_KIND_STRUCT);
}
/*
* Internal workhorse of ShmemRequestStruct() and ShmemRequestHash().
*
- * Note: Unlike in the public ShmemRequestStruct() and ShmemRequestHash()
- * functions, 'options' is *not* copied. It must be allocated in
- * TopMemoryContext by the caller, and will be freed after the init/attach
- * callbacks have been called. This allows ShmemRequestHash() to pass a
- * pointer to the extended ShmemHashOpts struct instead.
+ * 'options_size' can be larger than ShmemStructOpts, allowing callers such as
+ * ShmemRequestHash() to pass an extended options structure. ShmemStructOpts
+ * must be its first member.
*/
void
-ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
+ShmemRequestInternal(const ShmemStructOpts *options, Size options_size,
+ ShmemRequestKind kind)
{
ShmemRequest *request;
+ ShmemStructOpts *options_copy;
+ MemoryContext oldcontext;
/* Check the options */
if (options->name == NULL)
@@ -374,10 +372,14 @@ ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
}
/* Request looks valid, remember it */
+ oldcontext = MemoryContextSwitchTo(pending_shmem_requests_context);
+ options_copy = palloc(options_size);
+ memcpy(options_copy, options, options_size);
request = palloc(sizeof(ShmemRequest));
- request->options = options;
+ request->options = options_copy;
request->kind = kind;
pending_shmem_requests = lappend(pending_shmem_requests, request);
+ MemoryContextSwitchTo(oldcontext);
}
/*
@@ -433,11 +435,10 @@ ShmemInitRequested(void)
* so no need for locking.
*/
foreach_ptr(ShmemRequest, request, pending_shmem_requests)
- {
InitShmemIndexEntry(request);
- pfree(request->options);
- }
- list_free_deep(pending_shmem_requests);
+
+ MemoryContextDelete(pending_shmem_requests_context);
+ pending_shmem_requests_context = NULL;
pending_shmem_requests = NIL;
/*
@@ -476,11 +477,10 @@ ShmemAttachRequested(void)
* Attach to all the requested memory areas.
*/
foreach_ptr(ShmemRequest, request, pending_shmem_requests)
- {
AttachShmemIndexEntry(request, false);
- pfree(request->options);
- }
- list_free_deep(pending_shmem_requests);
+
+ MemoryContextDelete(pending_shmem_requests_context);
+ pending_shmem_requests_context = NULL;
pending_shmem_requests = NIL;
/* Call attach callbacks */
@@ -744,7 +744,12 @@ ResetShmemAllocator(void)
Assert(!IsUnderPostmaster);
shmem_request_state = SRS_INITIAL;
- pending_shmem_requests = NIL;
+ if (pending_shmem_requests_context != NULL)
+ {
+ MemoryContextDelete(pending_shmem_requests_context);
+ pending_shmem_requests_context = NULL;
+ pending_shmem_requests = NIL;
+ }
/*
* Note that we don't clear the registered callbacks. We will need to
@@ -901,77 +906,83 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
bool notfound_any;
Assert(shmem_request_state == SRS_DONE);
- shmem_request_state = SRS_REQUESTING;
-
- /*
- * Call the request callback first. The callback makes ShmemRequest*()
- * calls for each shmem area, adding them to pending_shmem_requests.
- */
Assert(pending_shmem_requests == NIL);
- if (callbacks->request_fn)
- callbacks->request_fn(callbacks->opaque_arg);
- shmem_request_state = SRS_AFTER_STARTUP_ATTACH_OR_INIT;
+ Assert(pending_shmem_requests_context == NULL);
+ pending_shmem_requests_context =
+ AllocSetContextCreate(TopMemoryContext,
+ "Pending shmem requests",
+ ALLOCSET_SMALL_SIZES);
+ shmem_request_state = SRS_REQUESTING;
- if (pending_shmem_requests == NIL)
+ PG_TRY();
{
- shmem_request_state = SRS_DONE;
- return;
- }
-
- /*
- * Hold ShmemIndexLock while we allocate all the shmem entries and run all
- * the initializers.
- */
- LWLockAcquire(ShmemIndexLock, LW_EXCLUSIVE);
+ /*
+ * Call the request callback first. The callback makes ShmemRequest*()
+ * calls for each shmem area, adding them to pending_shmem_requests.
+ */
+ if (callbacks->request_fn)
+ callbacks->request_fn(callbacks->opaque_arg);
+ INJECTION_POINT("shmem-after-startup-request", NULL);
+ shmem_request_state = SRS_AFTER_STARTUP_ATTACH_OR_INIT;
- /*
- * Check if the requested shared memory areas have already been
- * initialized. We assume all the areas requested by the request callback
- * to form a coherent unit such that they're all already initialized or
- * none. Otherwise it would be ambiguous which callback, init or attach,
- * to callback afterwards.
- */
- found_any = notfound_any = false;
- foreach_ptr(ShmemRequest, request, pending_shmem_requests)
- {
- if (hash_search(ShmemIndex, request->options->name, HASH_FIND, NULL))
- found_any = true;
- else
- notfound_any = true;
- }
- if (found_any && notfound_any)
- elog(ERROR, "some of the requested shmem areas have already been initialized");
+ if (pending_shmem_requests != NIL)
+ {
+ /*
+ * Hold ShmemIndexLock while we allocate all the shmem entries and
+ * run all the initializers.
+ */
+ LWLockAcquire(ShmemIndexLock, LW_EXCLUSIVE);
+
+ /*
+ * Check if the requested shared memory areas have already been
+ * initialized. We assume all the areas requested by the request
+ * callback to form a coherent unit such that they're all already
+ * initialized or none. Otherwise it would be ambiguous which
+ * callback, init or attach, to callback afterwards.
+ */
+ found_any = notfound_any = false;
+ foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+ {
+ if (hash_search(ShmemIndex, request->options->name, HASH_FIND, NULL))
+ found_any = true;
+ else
+ notfound_any = true;
+ }
+ if (found_any && notfound_any)
+ elog(ERROR, "some of the requested shmem areas have already been initialized");
- /*
- * Allocate or attach all the shmem areas requested by the request_fn
- * callback.
- */
- foreach_ptr(ShmemRequest, request, pending_shmem_requests)
- {
- if (found_any)
- AttachShmemIndexEntry(request, false);
- else
- InitShmemIndexEntry(request);
+ /* Allocate or attach all the requested shmem areas. */
+ foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+ {
+ if (found_any)
+ AttachShmemIndexEntry(request, false);
+ else
+ InitShmemIndexEntry(request);
+ }
- pfree(request->options);
- }
- list_free_deep(pending_shmem_requests);
- pending_shmem_requests = NIL;
+ /* Finish by calling the appropriate subsystem-specific callback. */
+ if (found_any)
+ {
+ if (callbacks->attach_fn)
+ callbacks->attach_fn(callbacks->opaque_arg);
+ }
+ else
+ {
+ if (callbacks->init_fn)
+ callbacks->init_fn(callbacks->opaque_arg);
+ }
- /* Finish by calling the appropriate subsystem-specific callback */
- if (found_any)
- {
- if (callbacks->attach_fn)
- callbacks->attach_fn(callbacks->opaque_arg);
+ LWLockRelease(ShmemIndexLock);
+ }
}
- else
+ PG_FINALLY();
{
- if (callbacks->init_fn)
- callbacks->init_fn(callbacks->opaque_arg);
+ MemoryContextDelete(pending_shmem_requests_context);
+ pending_shmem_requests_context = NULL;
+ pending_shmem_requests = NIL;
+ shmem_request_state = SRS_DONE;
}
-
- LWLockRelease(ShmemIndexLock);
- shmem_request_state = SRS_DONE;
+ PG_END_TRY();
}
/*
@@ -983,6 +994,12 @@ ShmemCallRequestCallbacks(void)
ListCell *lc;
Assert(shmem_request_state == SRS_INITIAL);
+ Assert(pending_shmem_requests == NIL);
+ Assert(pending_shmem_requests_context == NULL);
+ pending_shmem_requests_context =
+ AllocSetContextCreate(TopMemoryContext,
+ "Pending shmem requests",
+ ALLOCSET_SMALL_SIZES);
shmem_request_state = SRS_REQUESTING;
foreach(lc, registered_shmem_callbacks)
diff --git a/src/backend/storage/ipc/shmem_hash.c b/src/backend/storage/ipc/shmem_hash.c
index c28d673cbd2..8d9281d6284 100644
--- a/src/backend/storage/ipc/shmem_hash.c
+++ b/src/backend/storage/ipc/shmem_hash.c
@@ -43,20 +43,19 @@ static void *ShmemHashAlloc(Size size, void *alloc_arg);
void
ShmemRequestHashWithOpts(const ShmemHashOpts *options)
{
- ShmemHashOpts *options_copy;
+ ShmemHashOpts options_copy;
Assert(options->name != NULL);
- options_copy = MemoryContextAlloc(TopMemoryContext,
- sizeof(ShmemHashOpts));
- memcpy(options_copy, options, sizeof(ShmemHashOpts));
+ memcpy(&options_copy, options, sizeof(ShmemHashOpts));
/* Set options for the fixed-size area holding the hash table */
- options_copy->base.name = options->name;
- options_copy->base.size = hash_estimate_size(options_copy->nelems,
- options_copy->hash_info.entrysize);
+ options_copy.base.name = options->name;
+ options_copy.base.size = hash_estimate_size(options_copy.nelems,
+ options_copy.hash_info.entrysize);
- ShmemRequestInternal(&options_copy->base, SHMEM_KIND_HASH);
+ ShmemRequestInternal(&options_copy.base, sizeof(ShmemHashOpts),
+ SHMEM_KIND_HASH);
}
void
diff --git a/src/include/storage/shmem_internal.h b/src/include/storage/shmem_internal.h
index 8746b614fa3..9d337505986 100644
--- a/src/include/storage/shmem_internal.h
+++ b/src/include/storage/shmem_internal.h
@@ -34,7 +34,8 @@ extern void AttachShmemAllocator(PGShmemHeader *seghdr);
#endif
extern void ResetShmemAllocator(void);
-extern void ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind);
+extern void ShmemRequestInternal(const ShmemStructOpts *options,
+ Size options_size, ShmemRequestKind kind);
extern size_t ShmemGetRequestedSize(void);
extern void ShmemInitRequested(void);
diff --git a/src/test/modules/test_shmem/Makefile b/src/test/modules/test_shmem/Makefile
index 2407f7462fe..fed8e29c8f5 100644
--- a/src/test/modules/test_shmem/Makefile
+++ b/src/test/modules/test_shmem/Makefile
@@ -2,6 +2,9 @@
PGFILEDESC = "test_shmem - test code for shmem allocations"
+EXTRA_INSTALL = src/test/modules/injection_points
+export enable_injection_points
+
MODULE_big = test_shmem
OBJS = \
$(WIN32RES) \
diff --git a/src/test/modules/test_shmem/meson.build b/src/test/modules/test_shmem/meson.build
index fb4bf328b8f..8f98f2c4e31 100644
--- a/src/test/modules/test_shmem/meson.build
+++ b/src/test/modules/test_shmem/meson.build
@@ -26,6 +26,9 @@ tests += {
'sd': meson.current_source_dir(),
'bd': meson.current_build_dir(),
'tap': {
+ 'env': {
+ 'enable_injection_points': get_option('injection_points') ? 'yes' : 'no',
+ },
'tests': [
't/001_late_shmem_alloc.pl',
],
diff --git a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
index 5cf07d071ec..013abbf4524 100644
--- a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
+++ b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
@@ -16,6 +16,51 @@ $node->init;
$node->start;
+SKIP:
+{
+ skip "injection points not supported by this build", 2
+ if $ENV{enable_injection_points} ne 'yes';
+ $node->safe_psql("postgres", "CREATE EXTENSION injection_points;");
+ $node->safe_psql("postgres",
+ "SELECT injection_points_attach('shmem-after-startup-request', 'error');");
+ my $session = $node->background_psql('postgres', on_error_stop => 0);
+ my (undef, $failed1) = $session->query("CREATE EXTENSION test_shmem;");
+ my (undef, $failed2) = $session->query("CREATE EXTENSION test_shmem;");
+ $session->quit;
+ ok($failed1 && $failed2,
+ "request callback failure is reported on both attempts");
+ is($node->safe_psql("postgres", "SELECT 1"), '1',
+ "request callback failure does not crash the backend");
+ $node->safe_psql("postgres",
+ "SELECT injection_points_detach('shmem-after-startup-request');");
+}
+
+$node->stop;
+
+my $oom_node = PostgreSQL::Test::Cluster->new('oom');
+$oom_node->init;
+$oom_node->start;
+my (undef, undef, $oom_stderr) = $oom_node->psql("postgres", q[
+SET test_shmem.area_size = '128kB';
+CREATE EXTENSION test_shmem;]);
+like($oom_stderr, qr/not enough shared memory/,
+ "an after-startup request larger than the reserve fails");
+$oom_node->stop;
+
+my $preload_node = PostgreSQL::Test::Cluster->new('preload_large');
+$preload_node->init;
+$preload_node->append_conf('postgresql.conf', q[
+test_shmem.area_size = '128kB'
+shared_preload_libraries = 'test_shmem']);
+$preload_node->start;
+$preload_node->safe_psql("postgres", "CREATE EXTENSION test_shmem;");
+is($preload_node->safe_psql("postgres", "SELECT get_test_shmem_attach_count();"),
+ '0', "the same request succeeds when test_shmem is preloaded");
+$preload_node->stop;
+
+$node = PostgreSQL::Test::Cluster->new('normal');
+$node->init;
+$node->start;
$node->safe_psql("postgres", "CREATE EXTENSION test_shmem;");
# Check that the attach counter is incremented on a new connection
diff --git a/src/test/modules/test_shmem/test_shmem.c b/src/test/modules/test_shmem/test_shmem.c
index 9bd4012b435..089c364798e 100644
--- a/src/test/modules/test_shmem/test_shmem.c
+++ b/src/test/modules/test_shmem/test_shmem.c
@@ -17,9 +17,12 @@
#include "postgres.h"
+#include <limits.h>
+
#include "fmgr.h"
#include "miscadmin.h"
#include "storage/shmem.h"
+#include "utils/guc.h"
PG_MODULE_MAGIC;
@@ -34,6 +37,8 @@ typedef struct TestShmemData
static TestShmemData *TestShmem;
static bool attached_or_initialized = false;
+static int test_shmem_area_size = sizeof(TestShmemData);
+static bool test_shmem_guc_defined = false;
static void test_shmem_request(void *arg);
static void test_shmem_init(void *arg);
@@ -52,7 +57,7 @@ test_shmem_request(void *arg)
elog(LOG, "test_shmem_request callback called");
ShmemRequestStruct(.name = "test_shmem area",
- .size = sizeof(TestShmemData),
+ .size = test_shmem_area_size,
.ptr = (void **) &TestShmem);
}
@@ -86,6 +91,21 @@ void
_PG_init(void)
{
elog(LOG, "test_shmem module's _PG_init called");
+
+ if (!test_shmem_guc_defined)
+ {
+ DefineCustomIntVariable("test_shmem.area_size",
+ "Size of the shmem area to request.",
+ NULL,
+ &test_shmem_area_size,
+ sizeof(TestShmemData),
+ sizeof(TestShmemData), INT_MAX,
+ PGC_USERSET,
+ GUC_UNIT_BYTE,
+ NULL, NULL, NULL);
+ MarkGUCPrefixReserved("test_shmem");
+ test_shmem_guc_defined = true;
+ }
RegisterShmemCallbacks(&TestShmemCallbacks);
}
--
2.34.1
^ permalink raw reply [nested|flat] 21+ messages in thread
* Re: Error handling in after-startup shmem requests
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-09 16:30 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-10 09:40 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-10 12:40 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
@ 2026-08-11 15:46 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-11 18:05 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
0 siblings, 1 reply; 21+ messages in thread
From: Ashutosh Bapat @ 2026-08-11 15:46 UTC (permalink / raw)
To: Ayush Tiwari <ayushtiwari.slg01@gmail.com>; +Cc: pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>
On Mon, Aug 10, 2026 at 6:10 PM Ayush Tiwari
<ayushtiwari.slg01@gmail.com> wrote:
>
> Hi,
>
> Thanks for the review!
>
> On Mon, 10 Aug 2026 at 15:11, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com> wrote:
>>
>> On Sun, Aug 9, 2026 at 10:00 PM Ayush Tiwari
>> <ayushtiwari.slg01@gmail.com> wrote:
>>
>> /* Request looks valid, remember it */
>> + /* Keep the requests and list cells alive until we explicitly free them. */
>>
>> The comment actually doesn't make much sense. What does it have to do
>> with keeping the requests alive until freeing them with allocating
>> memory in TopMemoryContext? If it has to, it should rather explain why
>> we want them to be alive or why to save them in TopMemoryContext. The
>> previous comment which you removed was making the point that we save
>> the request "after validating" it; I would leave the wording in tact.
>>
>> + oldcontext = MemoryContextSwitchTo(TopMemoryContext);
>>
>> We should allocate the requests in the same context as the options
>> itself and blow up the whole context and set the list NIL.
>
>
> I have changed it along those lines. A request phase now creates one
> memory context under TopMemoryContext. The copied options, ShmemRequest
> records and list cells all live in that context, and the context is
> removed when the request phase finishes.
>
> I also changed ShmemRequestInternal() to take the size of the options
> structure. This lets it validate the request first and then copy either
> ShmemStructOpts, ShmemHashOpts or SlruOpts directly into the request
> context. Does that seem like a reasonable way to keep the context owned
> by shmem.c without exposing it to the hash and SLRU code?
What I had in mind is a child of TopMemoryContext to be used for
savings options, list and requests which will be reset instead of
deleting it after every cycle of allocations. But I don't think even
that is required. In the attached patch, I have allocated all of it in
TopMemoryContext and freed it at appropriate places including the
PG_FINALLY block. The changes look much more sensible and simple now.
Let me know what you think.
>
>>
>> +static int test_shmem_area_size = sizeof(TestShmemData);
>> +static bool test_shmem_after_startup = false;
>> +static char test_shmem_area_name[64] = "test_shmem area";
>>
>> static void test_shmem_request(void *arg);
>> static void test_shmem_init(void *arg);
>> @@ -51,9 +58,18 @@ test_shmem_request(void *arg)
>> {
>> elog(LOG, "test_shmem_request callback called");
>>
>> - ShmemRequestStruct(.name = "test_shmem area",
>> - .size = sizeof(TestShmemData),
>> + if (test_shmem_area_size == sizeof(TestShmemData))
>> + strcpy(test_shmem_area_name, "test_shmem area");
>> + else
>> + snprintf(test_shmem_area_name, sizeof(test_shmem_area_name),
>> + "test_shmem area %d", test_shmem_area_size);
>> +
>> + ShmemRequestStruct(.name = test_shmem_area_name,
>> + .size = test_shmem_area_size,
>> .ptr = (void **) &TestShmem);
>>
>> Heh. This is a clever idea to be able to create multiple shmem areas
>> from the same module, however, we don't need this complexity in test C
>> code. I would rather use $node->start, test, DROP EXTENSION,
>> $node->restart, CREATE EXTENSION sequence for loading the module
>> multiple times. That will also elimiate the need for the
>> test_shmem_register() function and register_twice function. I would
>> repeat that sequence to test the error cases first followed by
>> existing tests.
>>
Node creation is an expensive operation. We should reuse it as much as
possible, like attached.
>
> Pre-setting test_shmem.area_size as a placeholder gave the same result;
> init_custom_variable() performs this check before placeholder replacement.
> I have therefore kept it PGC_USERSET as a test-only control for the size
> passed by request_fn.
>
Thanks for the explanation. Why do we need test_shmem_guc_defined?
I have rewritten the test to avoid creating nodes, or even restarts.
Please check if it still tests the intended scenarios.
--
Best Wishes,
Ashutosh Bapat
Attachments:
v20260811-0001-Cleanup-after-failed-shared-memory-request.patch (text/x-patch, 13.3K) download
From 6c42a8210c742914ef72d572b24351521a1017d7 Mon Sep 17 00:00:00 2001
From: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Date: Tue, 11 Aug 2026 20:51:35 +0530
Subject: [PATCH v20260811] Cleanup after failed shared memory request after
startup
If allocation or initialization of a requested shared memory area
failed, CallShmemCallbacksAfterStartup() did not clear
pending_shmem_requests List and reset shmem_request_state. If the list
was allocated in a memory context which is cleared by error handler,
pending_shmem_requests would point to non-existent memory. Next call to
CallShmemCallbacksAfterStartup() would result in an Assertion failure or
a crash. The stale state meant that the later shared memory requests are
not processed immediately. Fix this by making
CallShmemCallbacksAfterStartupCleanup() cleanup after the failure.
Document that shared areas allocated before such an error remain
allocated but uninitialized. The requesting subsystem should not use
such areas.
Ideally, we should remove the uninitialized areas and free their memory.
But the fix is too invasive to be applied late in the PG 19 release
cycle.
Reported-by: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Author: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Author: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
---
doc/src/sgml/xfunc.sgml | 8 ++
src/backend/storage/ipc/shmem.c | 131 ++++++++++--------
src/test/modules/test_shmem/Makefile | 3 +
src/test/modules/test_shmem/meson.build | 3 +
.../test_shmem/t/001_late_shmem_alloc.pl | 35 ++++-
src/test/modules/test_shmem/test_shmem.c | 26 +++-
6 files changed, 142 insertions(+), 64 deletions(-)
diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml
index 2b8a11e7ad0..af776bdbfa3 100644
--- a/doc/src/sgml/xfunc.sgml
+++ b/doc/src/sgml/xfunc.sgml
@@ -3742,6 +3742,14 @@ my_shmem_init(void *arg)
lock (ShmemIndexLock), which prevents the race condition of two backends
trying to initialize the memory area at the same time.
</para>
+ <para>
+ If a <function>request_fn</function> callback requests multiple areas and
+ allocation of one of the areas fails, any areas allocated before the error
+ remain allocated but not initialized by <function>init_fn</function>. If
+ <function>init_fn</function> fails, all the areas remain allocated and in
+ the state in which <function>init_fn</function> leaves them. Subsystems
+ must detect that case and not use incompletely initialized shared state.
+ </para>
</sect3>
<sect3 id="xfunc-shared-addin-dynamic">
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index a3d56cf55dd..477635829f0 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -142,6 +142,7 @@
#include "storage/shmem_internal.h"
#include "storage/spin.h"
#include "utils/builtins.h"
+#include "utils/memutils.h"
#include "utils/tuplestore.h"
/*
@@ -336,6 +337,7 @@ void
ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
{
ShmemRequest *request;
+ MemoryContext oldcontext;
/* Check the options */
if (options->name == NULL)
@@ -374,10 +376,12 @@ ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
}
/* Request looks valid, remember it */
+ oldcontext = MemoryContextSwitchTo(TopMemoryContext);
request = palloc(sizeof(ShmemRequest));
request->options = options;
request->kind = kind;
pending_shmem_requests = lappend(pending_shmem_requests, request);
+ MemoryContextSwitchTo(oldcontext);
}
/*
@@ -903,75 +907,83 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
Assert(shmem_request_state == SRS_DONE);
shmem_request_state = SRS_REQUESTING;
- /*
- * Call the request callback first. The callback makes ShmemRequest*()
- * calls for each shmem area, adding them to pending_shmem_requests.
- */
- Assert(pending_shmem_requests == NIL);
- if (callbacks->request_fn)
- callbacks->request_fn(callbacks->opaque_arg);
- shmem_request_state = SRS_AFTER_STARTUP_ATTACH_OR_INIT;
-
- if (pending_shmem_requests == NIL)
+ PG_TRY();
{
- shmem_request_state = SRS_DONE;
- return;
- }
+ /*
+ * Call the request callback first. The callback makes
+ * ShmemRequest*() calls for each shmem area, adding them to
+ * pending_shmem_requests.
+ */
+ Assert(pending_shmem_requests == NIL);
+ if (callbacks->request_fn)
+ callbacks->request_fn(callbacks->opaque_arg);
+ shmem_request_state = SRS_AFTER_STARTUP_ATTACH_OR_INIT;
- /*
- * Hold ShmemIndexLock while we allocate all the shmem entries and run all
- * the initializers.
- */
- LWLockAcquire(ShmemIndexLock, LW_EXCLUSIVE);
+ if (pending_shmem_requests == NIL)
+ {
+ shmem_request_state = SRS_DONE;
+ return;
+ }
- /*
- * Check if the requested shared memory areas have already been
- * initialized. We assume all the areas requested by the request callback
- * to form a coherent unit such that they're all already initialized or
- * none. Otherwise it would be ambiguous which callback, init or attach,
- * to callback afterwards.
- */
- found_any = notfound_any = false;
- foreach_ptr(ShmemRequest, request, pending_shmem_requests)
- {
- if (hash_search(ShmemIndex, request->options->name, HASH_FIND, NULL))
- found_any = true;
- else
- notfound_any = true;
- }
- if (found_any && notfound_any)
- elog(ERROR, "some of the requested shmem areas have already been initialized");
+ /*
+ * Hold ShmemIndexLock while we allocate all the shmem entries and run
+ * all the initializers.
+ */
+ LWLockAcquire(ShmemIndexLock, LW_EXCLUSIVE);
- /*
- * Allocate or attach all the shmem areas requested by the request_fn
- * callback.
- */
- foreach_ptr(ShmemRequest, request, pending_shmem_requests)
- {
+ /*
+ * Check if the requested shared memory areas have already been
+ * initialized. We assume all the areas requested by the request
+ * callback to form a coherent unit such that they're all already
+ * initialized or none. Otherwise it would be ambiguous which
+ * callback, init or attach, to callback afterwards.
+ */
+ found_any = notfound_any = false;
+ foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+ {
+ if (hash_search(ShmemIndex, request->options->name, HASH_FIND, NULL))
+ found_any = true;
+ else
+ notfound_any = true;
+ }
+ if (found_any && notfound_any)
+ elog(ERROR, "some of the requested shmem areas have already been initialized");
+
+ /*
+ * Allocate or attach all the shmem areas requested by the request_fn
+ * callback.
+ */
+ foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+ {
+ if (found_any)
+ AttachShmemIndexEntry(request, false);
+ else
+ InitShmemIndexEntry(request);
+ }
+
+ /* Finish by calling the appropriate subsystem-specific callback. */
if (found_any)
- AttachShmemIndexEntry(request, false);
+ {
+ if (callbacks->attach_fn)
+ callbacks->attach_fn(callbacks->opaque_arg);
+ }
else
- InitShmemIndexEntry(request);
-
- pfree(request->options);
- }
- list_free_deep(pending_shmem_requests);
- pending_shmem_requests = NIL;
+ {
+ if (callbacks->init_fn)
+ callbacks->init_fn(callbacks->opaque_arg);
+ }
- /* Finish by calling the appropriate subsystem-specific callback */
- if (found_any)
- {
- if (callbacks->attach_fn)
- callbacks->attach_fn(callbacks->opaque_arg);
+ LWLockRelease(ShmemIndexLock);
}
- else
+ PG_FINALLY();
{
- if (callbacks->init_fn)
- callbacks->init_fn(callbacks->opaque_arg);
+ foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+ pfree(request->options);
+ list_free_deep(pending_shmem_requests);
+ pending_shmem_requests = NIL;
+ shmem_request_state = SRS_DONE;
}
-
- LWLockRelease(ShmemIndexLock);
- shmem_request_state = SRS_DONE;
+ PG_END_TRY();
}
/*
@@ -983,6 +995,7 @@ ShmemCallRequestCallbacks(void)
ListCell *lc;
Assert(shmem_request_state == SRS_INITIAL);
+ Assert(pending_shmem_requests == NIL);
shmem_request_state = SRS_REQUESTING;
foreach(lc, registered_shmem_callbacks)
diff --git a/src/test/modules/test_shmem/Makefile b/src/test/modules/test_shmem/Makefile
index 2407f7462fe..fed8e29c8f5 100644
--- a/src/test/modules/test_shmem/Makefile
+++ b/src/test/modules/test_shmem/Makefile
@@ -2,6 +2,9 @@
PGFILEDESC = "test_shmem - test code for shmem allocations"
+EXTRA_INSTALL = src/test/modules/injection_points
+export enable_injection_points
+
MODULE_big = test_shmem
OBJS = \
$(WIN32RES) \
diff --git a/src/test/modules/test_shmem/meson.build b/src/test/modules/test_shmem/meson.build
index fb4bf328b8f..8f98f2c4e31 100644
--- a/src/test/modules/test_shmem/meson.build
+++ b/src/test/modules/test_shmem/meson.build
@@ -26,6 +26,9 @@ tests += {
'sd': meson.current_source_dir(),
'bd': meson.current_build_dir(),
'tap': {
+ 'env': {
+ 'enable_injection_points': get_option('injection_points') ? 'yes' : 'no',
+ },
'tests': [
't/001_late_shmem_alloc.pl',
],
diff --git a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
index 5cf07d071ec..ede26a067aa 100644
--- a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
+++ b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
@@ -13,10 +13,37 @@ use Test::More;
###
my $node = PostgreSQL::Test::Cluster->new('main');
$node->init;
+
+# Test failure when the request is larger than the memory reserved for
+# after-startup requests.
$node->start;
+my (undef, undef, $oom_stderr) = $node->psql("postgres", q[
+SET test_shmem.area_size = '128kB';
+CREATE EXTENSION test_shmem;]);
+like($oom_stderr, qr/not enough shared memory/,
+ "an after-startup request larger than the reserve fails");
+# A failure in the requesting shared memory should not affect server
+# availability. We should still be able to try to create the extension again.
+# Test a failure in initialization of the shared memory area.
+SKIP:
+{
+ skip "injection points not supported by this build", 2
+ if $ENV{enable_injection_points} ne 'yes';
+ $node->safe_psql("postgres", "CREATE EXTENSION injection_points;");
+ $node->safe_psql("postgres",
+ "SELECT injection_points_attach('test-shmem-init', 'error');");
+ ok($node->psql("postgres", "CREATE EXTENSION test_shmem;"),
+ "request callback failure is reported on both attempts");
+ $node->safe_psql("postgres",
+ "SELECT injection_points_detach('test-shmem-init');");
+}
-$node->safe_psql("postgres", "CREATE EXTENSION test_shmem;");
+# The server should still be available and verify that the request succeeds for
+# smaller request.
+$node->safe_psql("postgres", q[
+SET test_shmem.area_size = default;
+CREATE EXTENSION test_shmem;]);
# Check that the attach counter is incremented on a new connection
my $attach_count1 =
@@ -28,10 +55,10 @@ cmp_ok($attach_count2, '>', $attach_count1,
$node->stop;
###
-# Test that loading via shared_preload_libraries also works
+# Test that loading via shared_preload_libraries also works, even for large request.
###
-$node->append_conf('postgresql.conf',
- "shared_preload_libraries = 'test_shmem'");
+$node->append_conf('postgresql.conf', "test_shmem.area_size = '128kB'");
+$node->append_conf('postgresql.conf', "shared_preload_libraries = 'test_shmem'");
$node->start;
# When loaded via shared_preload_libraries, the attach callback is
diff --git a/src/test/modules/test_shmem/test_shmem.c b/src/test/modules/test_shmem/test_shmem.c
index 9bd4012b435..2956f488135 100644
--- a/src/test/modules/test_shmem/test_shmem.c
+++ b/src/test/modules/test_shmem/test_shmem.c
@@ -17,9 +17,13 @@
#include "postgres.h"
+#include <limits.h>
+
#include "fmgr.h"
#include "miscadmin.h"
#include "storage/shmem.h"
+#include "utils/guc.h"
+#include "utils/injection_point.h"
PG_MODULE_MAGIC;
@@ -29,11 +33,14 @@ typedef struct TestShmemData
int value;
bool initialized;
int attach_count;
+ char variable_sized_array[FLEXIBLE_ARRAY_MEMBER];
} TestShmemData;
static TestShmemData *TestShmem;
static bool attached_or_initialized = false;
+static int test_shmem_area_size = sizeof(TestShmemData);
+static bool test_shmem_guc_defined = false;
static void test_shmem_request(void *arg);
static void test_shmem_init(void *arg);
@@ -52,7 +59,7 @@ test_shmem_request(void *arg)
elog(LOG, "test_shmem_request callback called");
ShmemRequestStruct(.name = "test_shmem area",
- .size = sizeof(TestShmemData),
+ .size = test_shmem_area_size,
.ptr = (void **) &TestShmem);
}
@@ -60,6 +67,8 @@ static void
test_shmem_init(void *arg)
{
elog(LOG, "init callback called");
+ /* Induce an error while initializing shared structure. */
+ INJECTION_POINT("test-shmem-init", NULL);
if (TestShmem->initialized)
elog(ERROR, "shmem area already initialized");
TestShmem->initialized = true;
@@ -86,6 +95,21 @@ void
_PG_init(void)
{
elog(LOG, "test_shmem module's _PG_init called");
+
+ if (!test_shmem_guc_defined)
+ {
+ DefineCustomIntVariable("test_shmem.area_size",
+ "Size of the shmem area to request.",
+ NULL,
+ &test_shmem_area_size,
+ sizeof(TestShmemData),
+ sizeof(TestShmemData), INT_MAX,
+ PGC_USERSET,
+ GUC_UNIT_BYTE,
+ NULL, NULL, NULL);
+ MarkGUCPrefixReserved("test_shmem");
+ test_shmem_guc_defined = true;
+ }
RegisterShmemCallbacks(&TestShmemCallbacks);
}
base-commit: 1d1d7b0e9c99a6c7b2bb874b5c7f6806e5940f04
--
2.34.1
^ permalink raw reply [nested|flat] 21+ messages in thread
* Re: Error handling in after-startup shmem requests
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-09 16:30 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-10 09:40 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-10 12:40 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-11 15:46 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
@ 2026-08-11 18:05 ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 07:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
0 siblings, 1 reply; 21+ messages in thread
From: Ayush Tiwari @ 2026-08-11 18:05 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>
Hi,
On Tue, 11 Aug 2026 at 21:16, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
wrote:
> On Mon, Aug 10, 2026 at 6:10 PM Ayush Tiwari
> <ayushtiwari.slg01@gmail.com> wrote:
> >
> > Hi,
> >
> > Thanks for the review!
> >
> > On Mon, 10 Aug 2026 at 15:11, Ashutosh Bapat <
> ashutosh.bapat.oss@gmail.com> wrote:
> >>
> >> On Sun, Aug 9, 2026 at 10:00 PM Ayush Tiwari
> >> <ayushtiwari.slg01@gmail.com> wrote:
> >>
> >> /* Request looks valid, remember it */
> >> + /* Keep the requests and list cells alive until we explicitly free
> them. */
> >>
> >> The comment actually doesn't make much sense. What does it have to do
> >> with keeping the requests alive until freeing them with allocating
> >> memory in TopMemoryContext? If it has to, it should rather explain why
> >> we want them to be alive or why to save them in TopMemoryContext. The
> >> previous comment which you removed was making the point that we save
> >> the request "after validating" it; I would leave the wording in tact.
> >>
> >> + oldcontext = MemoryContextSwitchTo(TopMemoryContext);
> >>
> >> We should allocate the requests in the same context as the options
> >> itself and blow up the whole context and set the list NIL.
> >
> >
> > I have changed it along those lines. A request phase now creates one
> > memory context under TopMemoryContext. The copied options, ShmemRequest
> > records and list cells all live in that context, and the context is
> > removed when the request phase finishes.
> >
> > I also changed ShmemRequestInternal() to take the size of the options
> > structure. This lets it validate the request first and then copy either
> > ShmemStructOpts, ShmemHashOpts or SlruOpts directly into the request
> > context. Does that seem like a reasonable way to keep the context owned
> > by shmem.c without exposing it to the hash and SLRU code?
>
> What I had in mind is a child of TopMemoryContext to be used for
> savings options, list and requests which will be reset instead of
> deleting it after every cycle of allocations. But I don't think even
> that is required. In the attached patch, I have allocated all of it in
> TopMemoryContext and freed it at appropriate places including the
> PG_FINALLY block. The changes look much more sensible and simple now.
> Let me know what you think.
>
Thanks for the updated patch.
Yes, this does look simpler to me than adding a separate child context.
One detail caught my attention: the no-request branch now returns from
inside
PG_TRY. Could that skip PG_FINALLY/PG_END_TRY and leave the saved error
stack
unrestored? Would it be safer to guard the allocation work with
`pending_shmem_requests != NIL`, allowing every path to reach the common
cleanup instead?
> >
> >>
> >> +static int test_shmem_area_size = sizeof(TestShmemData);
> >> +static bool test_shmem_after_startup = false;
> >> +static char test_shmem_area_name[64] = "test_shmem area";
> >>
> >> static void test_shmem_request(void *arg);
> >> static void test_shmem_init(void *arg);
> >> @@ -51,9 +58,18 @@ test_shmem_request(void *arg)
> >> {
> >> elog(LOG, "test_shmem_request callback called");
> >>
> >> - ShmemRequestStruct(.name = "test_shmem area",
> >> - .size = sizeof(TestShmemData),
> >> + if (test_shmem_area_size == sizeof(TestShmemData))
> >> + strcpy(test_shmem_area_name, "test_shmem area");
> >> + else
> >> + snprintf(test_shmem_area_name, sizeof(test_shmem_area_name),
> >> + "test_shmem area %d", test_shmem_area_size);
> >> +
> >> + ShmemRequestStruct(.name = test_shmem_area_name,
> >> + .size = test_shmem_area_size,
> >> .ptr = (void **) &TestShmem);
> >>
> >> Heh. This is a clever idea to be able to create multiple shmem areas
> >> from the same module, however, we don't need this complexity in test C
> >> code. I would rather use $node->start, test, DROP EXTENSION,
> >> $node->restart, CREATE EXTENSION sequence for loading the module
> >> multiple times. That will also elimiate the need for the
> >> test_shmem_register() function and register_twice function. I would
> >> repeat that sequence to test the error cases first followed by
> >> existing tests.
> >>
>
> Node creation is an expensive operation. We should reuse it as much as
> possible, like attached.
>
Agreed on reusing the node. Since the stale list is backend-local, do
separate
`$node->psql()` calls use different backends and miss the retry path? I
tried
the test with one background psql session. With the init_fn injection, the
area was already indexed but uninitialized, and the later CREATE EXTENSION
failed in test_shmem_attach(), consistent with the new documentation. Would
an injection immediately after request_fn be closer to the original failure?
> >
> > Pre-setting test_shmem.area_size as a placeholder gave the same result;
> > init_custom_variable() performs this check before placeholder
> replacement.
> > I have therefore kept it PGC_USERSET as a test-only control for the size
> > passed by request_fn.
> >
>
> Thanks for the explanation. Why do we need test_shmem_guc_defined?
>
It is needed for the same-backend retry. A failed CREATE EXTENSION can
leave
the library mapped, but it is not added to the successfully-loaded library
list until _PG_init() returns, so the retry invokes _PG_init() again. When
I
removed the guard, the second attempt failed with `attempt to redefine
parameter "test_shmem.area_size"` before reaching the shmem retry path.
> I have rewritten the test to avoid creating nodes, or even restarts.
> Please check if it still tests the intended scenarios.
With an injection immediately after request_fn and fail/fail/succeed in one
backend, your cleanup fixed the original retry failure in my testing.
Please
let me know if I have misunderstood any of the points above.
Regards,
Ayush
^ permalink raw reply [nested|flat] 21+ messages in thread
* Re: Error handling in after-startup shmem requests
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-09 16:30 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-10 09:40 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-10 12:40 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-11 15:46 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-11 18:05 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
@ 2026-08-12 07:41 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-12 09:07 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
0 siblings, 1 reply; 21+ messages in thread
From: Ashutosh Bapat @ 2026-08-12 07:41 UTC (permalink / raw)
To: Ayush Tiwari <ayushtiwari.slg01@gmail.com>; +Cc: pgsql-hackers; Heikki Linnakangas <hlinnaka@iki.fi>
On Tue, Aug 11, 2026 at 11:35 PM Ayush Tiwari
<ayushtiwari.slg01@gmail.com> wrote:
>
>
> One detail caught my attention: the no-request branch now returns from inside
> PG_TRY. Could that skip PG_FINALLY/PG_END_TRY and leave the saved error stack
> unrestored? Would it be safer to guard the allocation work with
> `pending_shmem_requests != NIL`, allowing every path to reach the common
> cleanup instead?
>
You are right. Thanks for the catch. Fixed in the attached version.
>> >>
>>
>> Node creation is an expensive operation. We should reuse it as much as
>> possible, like attached.
>
>
> Agreed on reusing the node. Since the stale list is backend-local, do separate
> `$node->psql()` calls use different backends and miss the retry path?
You are right again. We need the same session to retry. In the
attached version, I have changed the sequence of tests so that the
first test leaves a partially initialized but allocated area behind
and demonstrates how to handle such a case. The next test fails during
request and thus can be retried in the same psql session. That should
cover the stale state issues. Let me know if something is still
missing.
> I tried
> the test with one background psql session. With the init_fn injection, the
> area was already indexed but uninitialized, and the later CREATE EXTENSION
> failed in test_shmem_attach(), consistent with the new documentation. Would
> an injection immediately after request_fn be closer to the original failure?
>
The place where the injection point was placed earlier could never
have a failure. The failure can be either when request callbacks are
called or in the init callbacks not in-between. With the current
injection point placement both the cases, failure immediately after
request and also a failure in initialization are covered.
>>
>> >
>> > Pre-setting test_shmem.area_size as a placeholder gave the same result;
>> > init_custom_variable() performs this check before placeholder replacement.
>> > I have therefore kept it PGC_USERSET as a test-only control for the size
>> > passed by request_fn.
>> >
>>
>> Thanks for the explanation. Why do we need test_shmem_guc_defined?
>
>
> It is needed for the same-backend retry. A failed CREATE EXTENSION can leave
> the library mapped, but it is not added to the successfully-loaded library
> list until _PG_init() returns, so the retry invokes _PG_init() again. When I
> removed the guard, the second attempt failed with `attempt to redefine
> parameter "test_shmem.area_size"` before reaching the shmem retry path.
>
Hmm. Let's leave it there then.
> With an injection immediately after request_fn and fail/fail/succeed in one
> backend, your cleanup fixed the original retry failure in my testing. Please
> let me know if I have misunderstood any of the points above.
Your points are correct. Please review the latest patch and see if it
covers all the scenarios.
Also please add this thread to commitfest so that it's not forgotten
and also it gets tested by CI (especially the EXEC_BACKEND case).
--
Best Wishes,
Ashutosh Bapat
Attachments:
v20260812-0001-Cleanup-after-failed-shared-memory-request.patch (text/x-patch, 13.8K) download
From 0daaf88fb76a1add42bb97ac1e557d0a9066a376 Mon Sep 17 00:00:00 2001
From: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Date: Wed, 12 Aug 2026 11:48:34 +0530
Subject: [PATCH v20260812] Cleanup after failed shared memory request after
startup
If allocation or initialization of a requested shared memory area
failed, CallShmemCallbacksAfterStartup() did not clear
pending_shmem_requests List and reset shmem_request_state. If the list
was allocated in a memory context which is cleared by error handler,
pending_shmem_requests would point to non-existent memory. Next call to
CallShmemCallbacksAfterStartup() would result in an Assertion failure or
a crash. The stale state meant that the later shared memory requests are
not processed immediately. Fix this by making
CallShmemCallbacksAfterStartupCleanup() cleanup after the failure.
Document that shared areas allocated before such an error remain
allocated but uninitialized. The requesting subsystem should not use
such areas.
Ideally, we should remove the uninitialized areas and free their memory.
But the fix is too invasive to be applied late in the PG 19 release
cycle.
Reported-by: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Author: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Author: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Discussion: https://www.postgresql.org/message-id/CAJTYsWVRRWH48=PcuAo_2Y4Ap6M0QRmzxgUfFkNRtdWK74LjBQ@mail.gmail.com
---
doc/src/sgml/xfunc.sgml | 10 ++
src/backend/storage/ipc/shmem.c | 133 ++++++++++--------
src/test/modules/test_shmem/Makefile | 3 +
src/test/modules/test_shmem/meson.build | 3 +
.../test_shmem/t/001_late_shmem_alloc.pl | 47 ++++++-
src/test/modules/test_shmem/test_shmem.c | 26 +++-
6 files changed, 157 insertions(+), 65 deletions(-)
diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml
index 2b8a11e7ad0..206a2838415 100644
--- a/doc/src/sgml/xfunc.sgml
+++ b/doc/src/sgml/xfunc.sgml
@@ -3742,6 +3742,16 @@ my_shmem_init(void *arg)
lock (ShmemIndexLock), which prevents the race condition of two backends
trying to initialize the memory area at the same time.
</para>
+ <para>
+ If a <function>request_fn</function> callback requests multiple areas and
+ allocation of one of the areas fails, any areas allocated before the error
+ remain allocated but neither <function>init_fn</function> nor
+ <function>attach_fn</function> is called. If <function>init_fn</function>
+ fails (after all requested areas are allocated), all the areas remain
+ allocated and in the state in which <function>init_fn</function> leaves
+ them. Subsystems must detect these cases and not use unitialized or
+ partially initialized shared state.
+ </para>
</sect3>
<sect3 id="xfunc-shared-addin-dynamic">
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index a3d56cf55dd..887012d1123 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -336,6 +336,7 @@ void
ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
{
ShmemRequest *request;
+ MemoryContext oldcontext;
/* Check the options */
if (options->name == NULL)
@@ -374,10 +375,12 @@ ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
}
/* Request looks valid, remember it */
+ oldcontext = MemoryContextSwitchTo(TopMemoryContext);
request = palloc(sizeof(ShmemRequest));
request->options = options;
request->kind = kind;
pending_shmem_requests = lappend(pending_shmem_requests, request);
+ MemoryContextSwitchTo(oldcontext);
}
/*
@@ -903,75 +906,80 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
Assert(shmem_request_state == SRS_DONE);
shmem_request_state = SRS_REQUESTING;
- /*
- * Call the request callback first. The callback makes ShmemRequest*()
- * calls for each shmem area, adding them to pending_shmem_requests.
- */
- Assert(pending_shmem_requests == NIL);
- if (callbacks->request_fn)
- callbacks->request_fn(callbacks->opaque_arg);
- shmem_request_state = SRS_AFTER_STARTUP_ATTACH_OR_INIT;
-
- if (pending_shmem_requests == NIL)
+ PG_TRY();
{
- shmem_request_state = SRS_DONE;
- return;
- }
-
- /*
- * Hold ShmemIndexLock while we allocate all the shmem entries and run all
- * the initializers.
- */
- LWLockAcquire(ShmemIndexLock, LW_EXCLUSIVE);
-
- /*
- * Check if the requested shared memory areas have already been
- * initialized. We assume all the areas requested by the request callback
- * to form a coherent unit such that they're all already initialized or
- * none. Otherwise it would be ambiguous which callback, init or attach,
- * to callback afterwards.
- */
- found_any = notfound_any = false;
- foreach_ptr(ShmemRequest, request, pending_shmem_requests)
- {
- if (hash_search(ShmemIndex, request->options->name, HASH_FIND, NULL))
- found_any = true;
- else
- notfound_any = true;
- }
- if (found_any && notfound_any)
- elog(ERROR, "some of the requested shmem areas have already been initialized");
+ /*
+ * Call the request callback first. The callback makes
+ * ShmemRequest*() calls for each shmem area, adding them to
+ * pending_shmem_requests.
+ */
+ Assert(pending_shmem_requests == NIL);
+ if (callbacks->request_fn)
+ callbacks->request_fn(callbacks->opaque_arg);
+ shmem_request_state = SRS_AFTER_STARTUP_ATTACH_OR_INIT;
- /*
- * Allocate or attach all the shmem areas requested by the request_fn
- * callback.
- */
- foreach_ptr(ShmemRequest, request, pending_shmem_requests)
- {
- if (found_any)
- AttachShmemIndexEntry(request, false);
- else
- InitShmemIndexEntry(request);
+ if (pending_shmem_requests)
+ {
+ /*
+ * Hold ShmemIndexLock while we allocate all the shmem entries and
+ * run all the initializers.
+ */
+ LWLockAcquire(ShmemIndexLock, LW_EXCLUSIVE);
+
+ /*
+ * Check if the requested shared memory areas have already been
+ * initialized. We assume all the areas requested by the request
+ * callback to form a coherent unit such that they're all already
+ * initialized or none. Otherwise it would be ambiguous which
+ * callback, init or attach, to callback afterwards.
+ */
+ found_any = notfound_any = false;
+ foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+ {
+ if (hash_search(ShmemIndex, request->options->name, HASH_FIND, NULL))
+ found_any = true;
+ else
+ notfound_any = true;
+ }
+ if (found_any && notfound_any)
+ elog(ERROR, "some of the requested shmem areas have already been initialized");
+
+ /*
+ * Allocate or attach all the shmem areas requested by the
+ * request_fn callback.
+ */
+ foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+ {
+ if (found_any)
+ AttachShmemIndexEntry(request, false);
+ else
+ InitShmemIndexEntry(request);
+ }
- pfree(request->options);
- }
- list_free_deep(pending_shmem_requests);
- pending_shmem_requests = NIL;
+ /* Finish by calling the appropriate subsystem-specific callback. */
+ if (found_any)
+ {
+ if (callbacks->attach_fn)
+ callbacks->attach_fn(callbacks->opaque_arg);
+ }
+ else
+ {
+ if (callbacks->init_fn)
+ callbacks->init_fn(callbacks->opaque_arg);
+ }
- /* Finish by calling the appropriate subsystem-specific callback */
- if (found_any)
- {
- if (callbacks->attach_fn)
- callbacks->attach_fn(callbacks->opaque_arg);
+ LWLockRelease(ShmemIndexLock);
+ }
}
- else
+ PG_FINALLY();
{
- if (callbacks->init_fn)
- callbacks->init_fn(callbacks->opaque_arg);
+ foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+ pfree(request->options);
+ list_free_deep(pending_shmem_requests);
+ pending_shmem_requests = NIL;
+ shmem_request_state = SRS_DONE;
}
-
- LWLockRelease(ShmemIndexLock);
- shmem_request_state = SRS_DONE;
+ PG_END_TRY();
}
/*
@@ -983,6 +991,7 @@ ShmemCallRequestCallbacks(void)
ListCell *lc;
Assert(shmem_request_state == SRS_INITIAL);
+ Assert(pending_shmem_requests == NIL);
shmem_request_state = SRS_REQUESTING;
foreach(lc, registered_shmem_callbacks)
diff --git a/src/test/modules/test_shmem/Makefile b/src/test/modules/test_shmem/Makefile
index 2407f7462fe..fed8e29c8f5 100644
--- a/src/test/modules/test_shmem/Makefile
+++ b/src/test/modules/test_shmem/Makefile
@@ -2,6 +2,9 @@
PGFILEDESC = "test_shmem - test code for shmem allocations"
+EXTRA_INSTALL = src/test/modules/injection_points
+export enable_injection_points
+
MODULE_big = test_shmem
OBJS = \
$(WIN32RES) \
diff --git a/src/test/modules/test_shmem/meson.build b/src/test/modules/test_shmem/meson.build
index fb4bf328b8f..8f98f2c4e31 100644
--- a/src/test/modules/test_shmem/meson.build
+++ b/src/test/modules/test_shmem/meson.build
@@ -26,6 +26,9 @@ tests += {
'sd': meson.current_source_dir(),
'bd': meson.current_build_dir(),
'tap': {
+ 'env': {
+ 'enable_injection_points': get_option('injection_points') ? 'yes' : 'no',
+ },
'tests': [
't/001_late_shmem_alloc.pl',
],
diff --git a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
index 5cf07d071ec..7180f9deb28 100644
--- a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
+++ b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
@@ -15,8 +15,50 @@ my $node = PostgreSQL::Test::Cluster->new('main');
$node->init;
$node->start;
+# Test a failure in initialization of the shared memory area.
+SKIP:
+{
+ skip "injection points not supported by this build",
+ if $ENV{enable_injection_points} ne 'yes';
+ $node->safe_psql("postgres", "CREATE EXTENSION injection_points;");
+ $node->safe_psql("postgres",
+ "SELECT injection_points_attach('test-shmem-init', 'error');");
+
+ # A failure in the requesting shared memory should not affect server
+ # availability. The session should remain useful, however trying to create
+ # the same extension again will fail.
+ my (undef, undef, $stderr) =
+ $node->psql("postgres", "CREATE EXTENSION test_shmem;");
+ like($stderr,
+ qr/error triggered for injection point test-shmem-init/,
+ "failure in initialization is reported");
+ $node->safe_psql("postgres",
+ "SELECT injection_points_detach('test-shmem-init');");
+ (undef, undef, $stderr) =
+ $node->psql("postgres", "CREATE EXTENSION test_shmem;");
+ like($stderr, qr/shmem area not yet initialized/,
+ "post-init extension creation fails");
+
+ # Only a server restart can remove the partially allocated shared memory
+ # area.
+ $node->restart;
+}
+
+# Test failure when the request is larger than the memory reserved for
+# after-startup requests.
+my $session = $node->background_psql('postgres', on_error_stop => 0);
+$session->query(q[SET test_shmem.area_size = '128kB';], verbose => 0);
+$session->query("CREATE EXTENSION test_shmem;", verbose => 0);
+like($session->{stderr}, qr/not enough shared memory/,
+ "an after-startup request larger than the reserve fails");
-$node->safe_psql("postgres", "CREATE EXTENSION test_shmem;");
+# The server and the backend should still be available. Since there was only one
+# area requested, the failure did not change anything in the shared memory.
+# Verify that the request for smaller area succeeds in the same session.
+$session->{stderr} = '';
+$session->query("SET test_shmem.area_size = default;", verbose => 0);
+$session->query_safe("CREATE EXTENSION test_shmem;", verbose => 0);
+$session->quit;
# Check that the attach counter is incremented on a new connection
my $attach_count1 =
@@ -28,8 +70,9 @@ cmp_ok($attach_count2, '>', $attach_count1,
$node->stop;
###
-# Test that loading via shared_preload_libraries also works
+# Test that loading via shared_preload_libraries also works, even for large request.
###
+$node->append_conf('postgresql.conf', "test_shmem.area_size = '128kB'");
$node->append_conf('postgresql.conf',
"shared_preload_libraries = 'test_shmem'");
$node->start;
diff --git a/src/test/modules/test_shmem/test_shmem.c b/src/test/modules/test_shmem/test_shmem.c
index 9bd4012b435..2956f488135 100644
--- a/src/test/modules/test_shmem/test_shmem.c
+++ b/src/test/modules/test_shmem/test_shmem.c
@@ -17,9 +17,13 @@
#include "postgres.h"
+#include <limits.h>
+
#include "fmgr.h"
#include "miscadmin.h"
#include "storage/shmem.h"
+#include "utils/guc.h"
+#include "utils/injection_point.h"
PG_MODULE_MAGIC;
@@ -29,11 +33,14 @@ typedef struct TestShmemData
int value;
bool initialized;
int attach_count;
+ char variable_sized_array[FLEXIBLE_ARRAY_MEMBER];
} TestShmemData;
static TestShmemData *TestShmem;
static bool attached_or_initialized = false;
+static int test_shmem_area_size = sizeof(TestShmemData);
+static bool test_shmem_guc_defined = false;
static void test_shmem_request(void *arg);
static void test_shmem_init(void *arg);
@@ -52,7 +59,7 @@ test_shmem_request(void *arg)
elog(LOG, "test_shmem_request callback called");
ShmemRequestStruct(.name = "test_shmem area",
- .size = sizeof(TestShmemData),
+ .size = test_shmem_area_size,
.ptr = (void **) &TestShmem);
}
@@ -60,6 +67,8 @@ static void
test_shmem_init(void *arg)
{
elog(LOG, "init callback called");
+ /* Induce an error while initializing shared structure. */
+ INJECTION_POINT("test-shmem-init", NULL);
if (TestShmem->initialized)
elog(ERROR, "shmem area already initialized");
TestShmem->initialized = true;
@@ -86,6 +95,21 @@ void
_PG_init(void)
{
elog(LOG, "test_shmem module's _PG_init called");
+
+ if (!test_shmem_guc_defined)
+ {
+ DefineCustomIntVariable("test_shmem.area_size",
+ "Size of the shmem area to request.",
+ NULL,
+ &test_shmem_area_size,
+ sizeof(TestShmemData),
+ sizeof(TestShmemData), INT_MAX,
+ PGC_USERSET,
+ GUC_UNIT_BYTE,
+ NULL, NULL, NULL);
+ MarkGUCPrefixReserved("test_shmem");
+ test_shmem_guc_defined = true;
+ }
RegisterShmemCallbacks(&TestShmemCallbacks);
}
base-commit: 6828b03b062bf9eee7b5e5e7ee1cedd4e174ab29
--
2.34.1
^ permalink raw reply [nested|flat] 21+ messages in thread
* Re: Error handling in after-startup shmem requests
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-09 16:30 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-10 09:40 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-10 12:40 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-11 15:46 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-11 18:05 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 07:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
@ 2026-08-12 09:07 ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 09:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
0 siblings, 1 reply; 21+ messages in thread
From: Ayush Tiwari @ 2026-08-12 09:07 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: pgsql-hackers
Hi,
On Wed, 12 Aug 2026 at 13:11, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
wrote:
> On Tue, Aug 11, 2026 at 11:35 PM Ayush Tiwari
> <ayushtiwari.slg01@gmail.com> wrote:
> >
> >
> > One detail caught my attention: the no-request branch now returns from
> inside
> > PG_TRY. Could that skip PG_FINALLY/PG_END_TRY and leave the saved error
> stack
> > unrestored? Would it be safer to guard the allocation work with
> > `pending_shmem_requests != NIL`, allowing every path to reach the common
> > cleanup instead?
> >
>
> You are right. Thanks for the catch. Fixed in the attached version.
>
> >> >>
> >>
> >> Node creation is an expensive operation. We should reuse it as much as
> >> possible, like attached.
> >
> >
> > Agreed on reusing the node. Since the stale list is backend-local, do
> separate
> > `$node->psql()` calls use different backends and miss the retry path?
>
> You are right again. We need the same session to retry. In the
> attached version, I have changed the sequence of tests so that the
> first test leaves a partially initialized but allocated area behind
> and demonstrates how to handle such a case. The next test fails during
> request and thus can be retried in the same psql session. That should
> cover the stale state issues. Let me know if something is still
> missing.
>
> > I tried
> > the test with one background psql session. With the init_fn injection,
> the
> > area was already indexed but uninitialized, and the later CREATE
> EXTENSION
> > failed in test_shmem_attach(), consistent with the new documentation.
> Would
> > an injection immediately after request_fn be closer to the original
> failure?
> >
>
> The place where the injection point was placed earlier could never
> have a failure. The failure can be either when request callbacks are
> called or in the init callbacks not in-between. With the current
> injection point placement both the cases, failure immediately after
> request and also a failure in initialization are covered.
>
> >>
> >> >
> >> > Pre-setting test_shmem.area_size as a placeholder gave the same
> result;
> >> > init_custom_variable() performs this check before placeholder
> replacement.
> >> > I have therefore kept it PGC_USERSET as a test-only control for the
> size
> >> > passed by request_fn.
> >> >
> >>
> >> Thanks for the explanation. Why do we need test_shmem_guc_defined?
> >
> >
> > It is needed for the same-backend retry. A failed CREATE EXTENSION can
> leave
> > the library mapped, but it is not added to the successfully-loaded
> library
> > list until _PG_init() returns, so the retry invokes _PG_init() again.
> When I
> > removed the guard, the second attempt failed with `attempt to redefine
> > parameter "test_shmem.area_size"` before reaching the shmem retry path.
> >
>
> Hmm. Let's leave it there then.
>
> > With an injection immediately after request_fn and fail/fail/succeed in
> one
> > backend, your cleanup fixed the original retry failure in my testing.
> Please
> > let me know if I have misunderstood any of the points above.
>
> Your points are correct. Please review the latest patch and see if it
> covers all the scenarios.
>
Thanks for the latest patch, it looks good to me.
I just have 2 minor editorial nits:
- The commit message mentions CallShmemCallbacksAfterStartupCleanup(), but I
think that should be CallShmemCallbacksAfterStartup().
- "unitialized" in xfunc.sgml should be "uninitialized".
These can be adjusted while committing so I'm not sending an updated patch.
> Also please add this thread to commitfest so that it's not forgotten
> and also it gets tested by CI (especially the EXEC_BACKEND case).
>
Here's the CF entry I had created:
https://commitfest.postgresql.org/patch/7115/
And also added it to the open list item for PG 19.
Regards,
Ayush
^ permalink raw reply [nested|flat] 21+ messages in thread
* Re: Error handling in after-startup shmem requests
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-09 16:30 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-10 09:40 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-10 12:40 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-11 15:46 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-11 18:05 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 07:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-12 09:07 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
@ 2026-08-12 09:41 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-18 10:37 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
0 siblings, 1 reply; 21+ messages in thread
From: Ashutosh Bapat @ 2026-08-12 09:41 UTC (permalink / raw)
To: Ayush Tiwari <ayushtiwari.slg01@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; pgsql-hackers
On Wed, Aug 12, 2026 at 2:37 PM Ayush Tiwari
<ayushtiwari.slg01@gmail.com> wrote:
> Thanks for the latest patch, it looks good to me.
>
Thanks.
> I just have 2 minor editorial nits:
>
> - The commit message mentions CallShmemCallbacksAfterStartupCleanup(), but I
> think that should be CallShmemCallbacksAfterStartup().
>
> - "unitialized" in xfunc.sgml should be "uninitialized".
>
> These can be adjusted while committing so I'm not sending an updated patch.
>
Attached patch fixes those two as well.
>
>
> Here's the CF entry I had created:
> https://commitfest.postgresql.org/patch/7115/
I see Meson MacOS build failing, but the issue seems to be with
downloading dependencies. The CI will be triggered again with a new
patch and hopefully we will see the failure gone.
--
Best Wishes,
Ashutosh Bapat
Attachments:
v20260812_2-0001-Cleanup-after-failed-shared-memory-request.patch (text/x-patch, 13.8K) download
From d14f2939384565ad9e5d414754fa274f3f37ad4f Mon Sep 17 00:00:00 2001
From: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Date: Wed, 12 Aug 2026 11:48:34 +0530
Subject: [PATCH v20260812] Cleanup after failed shared memory request after
startup
If allocation or initialization of a requested shared memory area
failed, CallShmemCallbacksAfterStartup() did not clear
pending_shmem_requests List and reset shmem_request_state. If the list
was allocated in a memory context which is cleared by error handler,
pending_shmem_requests would point to non-existent memory. Next call to
CallShmemCallbacksAfterStartup() would result in an Assertion failure or
a crash. The stale state meant that the later shared memory requests are
not processed immediately. Fix this by making
CallShmemCallbacksAfterStartup() cleanup after the failure.
Document that shared areas allocated before such an error remain
allocated but uninitialized. The requesting subsystem should not use
such areas.
Ideally, we should remove the uninitialized areas and free their memory.
But the fix is too invasive to be applied late in the PG 19 release
cycle.
Reported-by: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Author: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Author: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Discussion: https://www.postgresql.org/message-id/CAJTYsWVRRWH48=PcuAo_2Y4Ap6M0QRmzxgUfFkNRtdWK74LjBQ@mail.gmail.com
---
doc/src/sgml/xfunc.sgml | 10 ++
src/backend/storage/ipc/shmem.c | 133 ++++++++++--------
src/test/modules/test_shmem/Makefile | 3 +
src/test/modules/test_shmem/meson.build | 3 +
.../test_shmem/t/001_late_shmem_alloc.pl | 47 ++++++-
src/test/modules/test_shmem/test_shmem.c | 26 +++-
6 files changed, 157 insertions(+), 65 deletions(-)
diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml
index 2b8a11e7ad0..1334cc55c53 100644
--- a/doc/src/sgml/xfunc.sgml
+++ b/doc/src/sgml/xfunc.sgml
@@ -3742,6 +3742,16 @@ my_shmem_init(void *arg)
lock (ShmemIndexLock), which prevents the race condition of two backends
trying to initialize the memory area at the same time.
</para>
+ <para>
+ If a <function>request_fn</function> callback requests multiple areas and
+ allocation of one of the areas fails, any areas allocated before the error
+ remain allocated but neither <function>init_fn</function> nor
+ <function>attach_fn</function> is called. If <function>init_fn</function>
+ fails (after all requested areas are allocated), all the areas remain
+ allocated and in the state in which <function>init_fn</function> leaves
+ them. Subsystems must detect these cases and not use uninitialized or
+ partially initialized shared state.
+ </para>
</sect3>
<sect3 id="xfunc-shared-addin-dynamic">
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index a3d56cf55dd..887012d1123 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -336,6 +336,7 @@ void
ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
{
ShmemRequest *request;
+ MemoryContext oldcontext;
/* Check the options */
if (options->name == NULL)
@@ -374,10 +375,12 @@ ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
}
/* Request looks valid, remember it */
+ oldcontext = MemoryContextSwitchTo(TopMemoryContext);
request = palloc(sizeof(ShmemRequest));
request->options = options;
request->kind = kind;
pending_shmem_requests = lappend(pending_shmem_requests, request);
+ MemoryContextSwitchTo(oldcontext);
}
/*
@@ -903,75 +906,80 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
Assert(shmem_request_state == SRS_DONE);
shmem_request_state = SRS_REQUESTING;
- /*
- * Call the request callback first. The callback makes ShmemRequest*()
- * calls for each shmem area, adding them to pending_shmem_requests.
- */
- Assert(pending_shmem_requests == NIL);
- if (callbacks->request_fn)
- callbacks->request_fn(callbacks->opaque_arg);
- shmem_request_state = SRS_AFTER_STARTUP_ATTACH_OR_INIT;
-
- if (pending_shmem_requests == NIL)
+ PG_TRY();
{
- shmem_request_state = SRS_DONE;
- return;
- }
-
- /*
- * Hold ShmemIndexLock while we allocate all the shmem entries and run all
- * the initializers.
- */
- LWLockAcquire(ShmemIndexLock, LW_EXCLUSIVE);
-
- /*
- * Check if the requested shared memory areas have already been
- * initialized. We assume all the areas requested by the request callback
- * to form a coherent unit such that they're all already initialized or
- * none. Otherwise it would be ambiguous which callback, init or attach,
- * to callback afterwards.
- */
- found_any = notfound_any = false;
- foreach_ptr(ShmemRequest, request, pending_shmem_requests)
- {
- if (hash_search(ShmemIndex, request->options->name, HASH_FIND, NULL))
- found_any = true;
- else
- notfound_any = true;
- }
- if (found_any && notfound_any)
- elog(ERROR, "some of the requested shmem areas have already been initialized");
+ /*
+ * Call the request callback first. The callback makes
+ * ShmemRequest*() calls for each shmem area, adding them to
+ * pending_shmem_requests.
+ */
+ Assert(pending_shmem_requests == NIL);
+ if (callbacks->request_fn)
+ callbacks->request_fn(callbacks->opaque_arg);
+ shmem_request_state = SRS_AFTER_STARTUP_ATTACH_OR_INIT;
- /*
- * Allocate or attach all the shmem areas requested by the request_fn
- * callback.
- */
- foreach_ptr(ShmemRequest, request, pending_shmem_requests)
- {
- if (found_any)
- AttachShmemIndexEntry(request, false);
- else
- InitShmemIndexEntry(request);
+ if (pending_shmem_requests)
+ {
+ /*
+ * Hold ShmemIndexLock while we allocate all the shmem entries and
+ * run all the initializers.
+ */
+ LWLockAcquire(ShmemIndexLock, LW_EXCLUSIVE);
+
+ /*
+ * Check if the requested shared memory areas have already been
+ * initialized. We assume all the areas requested by the request
+ * callback to form a coherent unit such that they're all already
+ * initialized or none. Otherwise it would be ambiguous which
+ * callback, init or attach, to callback afterwards.
+ */
+ found_any = notfound_any = false;
+ foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+ {
+ if (hash_search(ShmemIndex, request->options->name, HASH_FIND, NULL))
+ found_any = true;
+ else
+ notfound_any = true;
+ }
+ if (found_any && notfound_any)
+ elog(ERROR, "some of the requested shmem areas have already been initialized");
+
+ /*
+ * Allocate or attach all the shmem areas requested by the
+ * request_fn callback.
+ */
+ foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+ {
+ if (found_any)
+ AttachShmemIndexEntry(request, false);
+ else
+ InitShmemIndexEntry(request);
+ }
- pfree(request->options);
- }
- list_free_deep(pending_shmem_requests);
- pending_shmem_requests = NIL;
+ /* Finish by calling the appropriate subsystem-specific callback. */
+ if (found_any)
+ {
+ if (callbacks->attach_fn)
+ callbacks->attach_fn(callbacks->opaque_arg);
+ }
+ else
+ {
+ if (callbacks->init_fn)
+ callbacks->init_fn(callbacks->opaque_arg);
+ }
- /* Finish by calling the appropriate subsystem-specific callback */
- if (found_any)
- {
- if (callbacks->attach_fn)
- callbacks->attach_fn(callbacks->opaque_arg);
+ LWLockRelease(ShmemIndexLock);
+ }
}
- else
+ PG_FINALLY();
{
- if (callbacks->init_fn)
- callbacks->init_fn(callbacks->opaque_arg);
+ foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+ pfree(request->options);
+ list_free_deep(pending_shmem_requests);
+ pending_shmem_requests = NIL;
+ shmem_request_state = SRS_DONE;
}
-
- LWLockRelease(ShmemIndexLock);
- shmem_request_state = SRS_DONE;
+ PG_END_TRY();
}
/*
@@ -983,6 +991,7 @@ ShmemCallRequestCallbacks(void)
ListCell *lc;
Assert(shmem_request_state == SRS_INITIAL);
+ Assert(pending_shmem_requests == NIL);
shmem_request_state = SRS_REQUESTING;
foreach(lc, registered_shmem_callbacks)
diff --git a/src/test/modules/test_shmem/Makefile b/src/test/modules/test_shmem/Makefile
index 2407f7462fe..fed8e29c8f5 100644
--- a/src/test/modules/test_shmem/Makefile
+++ b/src/test/modules/test_shmem/Makefile
@@ -2,6 +2,9 @@
PGFILEDESC = "test_shmem - test code for shmem allocations"
+EXTRA_INSTALL = src/test/modules/injection_points
+export enable_injection_points
+
MODULE_big = test_shmem
OBJS = \
$(WIN32RES) \
diff --git a/src/test/modules/test_shmem/meson.build b/src/test/modules/test_shmem/meson.build
index fb4bf328b8f..8f98f2c4e31 100644
--- a/src/test/modules/test_shmem/meson.build
+++ b/src/test/modules/test_shmem/meson.build
@@ -26,6 +26,9 @@ tests += {
'sd': meson.current_source_dir(),
'bd': meson.current_build_dir(),
'tap': {
+ 'env': {
+ 'enable_injection_points': get_option('injection_points') ? 'yes' : 'no',
+ },
'tests': [
't/001_late_shmem_alloc.pl',
],
diff --git a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
index 5cf07d071ec..7180f9deb28 100644
--- a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
+++ b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
@@ -15,8 +15,50 @@ my $node = PostgreSQL::Test::Cluster->new('main');
$node->init;
$node->start;
+# Test a failure in initialization of the shared memory area.
+SKIP:
+{
+ skip "injection points not supported by this build",
+ if $ENV{enable_injection_points} ne 'yes';
+ $node->safe_psql("postgres", "CREATE EXTENSION injection_points;");
+ $node->safe_psql("postgres",
+ "SELECT injection_points_attach('test-shmem-init', 'error');");
+
+ # A failure in the requesting shared memory should not affect server
+ # availability. The session should remain useful, however trying to create
+ # the same extension again will fail.
+ my (undef, undef, $stderr) =
+ $node->psql("postgres", "CREATE EXTENSION test_shmem;");
+ like($stderr,
+ qr/error triggered for injection point test-shmem-init/,
+ "failure in initialization is reported");
+ $node->safe_psql("postgres",
+ "SELECT injection_points_detach('test-shmem-init');");
+ (undef, undef, $stderr) =
+ $node->psql("postgres", "CREATE EXTENSION test_shmem;");
+ like($stderr, qr/shmem area not yet initialized/,
+ "post-init extension creation fails");
+
+ # Only a server restart can remove the partially allocated shared memory
+ # area.
+ $node->restart;
+}
+
+# Test failure when the request is larger than the memory reserved for
+# after-startup requests.
+my $session = $node->background_psql('postgres', on_error_stop => 0);
+$session->query(q[SET test_shmem.area_size = '128kB';], verbose => 0);
+$session->query("CREATE EXTENSION test_shmem;", verbose => 0);
+like($session->{stderr}, qr/not enough shared memory/,
+ "an after-startup request larger than the reserve fails");
-$node->safe_psql("postgres", "CREATE EXTENSION test_shmem;");
+# The server and the backend should still be available. Since there was only one
+# area requested, the failure did not change anything in the shared memory.
+# Verify that the request for smaller area succeeds in the same session.
+$session->{stderr} = '';
+$session->query("SET test_shmem.area_size = default;", verbose => 0);
+$session->query_safe("CREATE EXTENSION test_shmem;", verbose => 0);
+$session->quit;
# Check that the attach counter is incremented on a new connection
my $attach_count1 =
@@ -28,8 +70,9 @@ cmp_ok($attach_count2, '>', $attach_count1,
$node->stop;
###
-# Test that loading via shared_preload_libraries also works
+# Test that loading via shared_preload_libraries also works, even for large request.
###
+$node->append_conf('postgresql.conf', "test_shmem.area_size = '128kB'");
$node->append_conf('postgresql.conf',
"shared_preload_libraries = 'test_shmem'");
$node->start;
diff --git a/src/test/modules/test_shmem/test_shmem.c b/src/test/modules/test_shmem/test_shmem.c
index 9bd4012b435..2956f488135 100644
--- a/src/test/modules/test_shmem/test_shmem.c
+++ b/src/test/modules/test_shmem/test_shmem.c
@@ -17,9 +17,13 @@
#include "postgres.h"
+#include <limits.h>
+
#include "fmgr.h"
#include "miscadmin.h"
#include "storage/shmem.h"
+#include "utils/guc.h"
+#include "utils/injection_point.h"
PG_MODULE_MAGIC;
@@ -29,11 +33,14 @@ typedef struct TestShmemData
int value;
bool initialized;
int attach_count;
+ char variable_sized_array[FLEXIBLE_ARRAY_MEMBER];
} TestShmemData;
static TestShmemData *TestShmem;
static bool attached_or_initialized = false;
+static int test_shmem_area_size = sizeof(TestShmemData);
+static bool test_shmem_guc_defined = false;
static void test_shmem_request(void *arg);
static void test_shmem_init(void *arg);
@@ -52,7 +59,7 @@ test_shmem_request(void *arg)
elog(LOG, "test_shmem_request callback called");
ShmemRequestStruct(.name = "test_shmem area",
- .size = sizeof(TestShmemData),
+ .size = test_shmem_area_size,
.ptr = (void **) &TestShmem);
}
@@ -60,6 +67,8 @@ static void
test_shmem_init(void *arg)
{
elog(LOG, "init callback called");
+ /* Induce an error while initializing shared structure. */
+ INJECTION_POINT("test-shmem-init", NULL);
if (TestShmem->initialized)
elog(ERROR, "shmem area already initialized");
TestShmem->initialized = true;
@@ -86,6 +95,21 @@ void
_PG_init(void)
{
elog(LOG, "test_shmem module's _PG_init called");
+
+ if (!test_shmem_guc_defined)
+ {
+ DefineCustomIntVariable("test_shmem.area_size",
+ "Size of the shmem area to request.",
+ NULL,
+ &test_shmem_area_size,
+ sizeof(TestShmemData),
+ sizeof(TestShmemData), INT_MAX,
+ PGC_USERSET,
+ GUC_UNIT_BYTE,
+ NULL, NULL, NULL);
+ MarkGUCPrefixReserved("test_shmem");
+ test_shmem_guc_defined = true;
+ }
RegisterShmemCallbacks(&TestShmemCallbacks);
}
base-commit: d6bf0ab1704c62f94875d25dd71c4baa1feac5be
--
2.34.1
^ permalink raw reply [nested|flat] 21+ messages in thread
* Re: Error handling in after-startup shmem requests
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-09 16:30 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-10 09:40 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-10 12:40 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-11 15:46 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-11 18:05 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 07:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-12 09:07 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 09:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
@ 2026-08-18 10:37 ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-25 16:33 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
0 siblings, 1 reply; 21+ messages in thread
From: Ayush Tiwari @ 2026-08-18 10:37 UTC (permalink / raw)
To: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: pgsql-hackers
Hi,
On Wed, 12 Aug 2026 at 15:12, Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
wrote:
> On Wed, Aug 12, 2026 at 2:37 PM Ayush Tiwari
> <ayushtiwari.slg01@gmail.com> wrote:
>
> > Thanks for the latest patch, it looks good to me.
> >
>
> Thanks.
>
> > I just have 2 minor editorial nits:
> >
> > - The commit message mentions CallShmemCallbacksAfterStartupCleanup(),
> but I
> > think that should be CallShmemCallbacksAfterStartup().
> >
> > - "unitialized" in xfunc.sgml should be "uninitialized".
> >
> > These can be adjusted while committing so I'm not sending an updated
> patch.
> >
>
> Attached patch fixes those two as well.
>
Rebased.
Regards,
Ayush
Attachments:
v20260818-0001-Cleanup-after-failed-shared-memory-request.patch (application/octet-stream, 13.8K) download
From 405909fdb6b7124fab69fd881bbd104f7f5c8fac Mon Sep 17 00:00:00 2001
From: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Date: Wed, 12 Aug 2026 11:48:34 +0530
Subject: [PATCH v20260818] Cleanup after failed shared memory request after
startup
If allocation or initialization of a requested shared memory area
failed, CallShmemCallbacksAfterStartup() did not clear
pending_shmem_requests List and reset shmem_request_state. If the list
was allocated in a memory context which is cleared by error handler,
pending_shmem_requests would point to non-existent memory. Next call to
CallShmemCallbacksAfterStartup() would result in an Assertion failure or
a crash. The stale state meant that the later shared memory requests are
not processed immediately. Fix this by making
CallShmemCallbacksAfterStartup() cleanup after the failure.
Document that shared areas allocated before such an error remain
allocated but uninitialized. The requesting subsystem should not use
such areas.
Ideally, we should remove the uninitialized areas and free their memory.
But the fix is too invasive to be applied late in the PG 19 release
cycle.
Reported-by: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Author: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Author: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Discussion: https://www.postgresql.org/message-id/CAJTYsWVRRWH48=PcuAo_2Y4Ap6M0QRmzxgUfFkNRtdWK74LjBQ@mail.gmail.com
---
doc/src/sgml/xfunc.sgml | 10 ++
src/backend/storage/ipc/shmem.c | 133 ++++++++++--------
src/test/modules/test_shmem/Makefile | 3 +
src/test/modules/test_shmem/meson.build | 3 +
.../test_shmem/t/001_late_shmem_alloc.pl | 47 ++++++-
src/test/modules/test_shmem/test_shmem.c | 26 +++-
6 files changed, 157 insertions(+), 65 deletions(-)
diff --git a/doc/src/sgml/xfunc.sgml b/doc/src/sgml/xfunc.sgml
index 050e1e50bec..bbb28eed875 100644
--- a/doc/src/sgml/xfunc.sgml
+++ b/doc/src/sgml/xfunc.sgml
@@ -3742,6 +3742,16 @@ my_shmem_init(void *arg)
lock (ShmemIndexLock), which prevents the race condition of two backends
trying to initialize the memory area at the same time.
</para>
+ <para>
+ If a <function>request_fn</function> callback requests multiple areas and
+ allocation of one of the areas fails, any areas allocated before the error
+ remain allocated but neither <function>init_fn</function> nor
+ <function>attach_fn</function> is called. If <function>init_fn</function>
+ fails (after all requested areas are allocated), all the areas remain
+ allocated and in the state in which <function>init_fn</function> leaves
+ them. Subsystems must detect these cases and not use uninitialized or
+ partially initialized shared state.
+ </para>
</sect3>
<sect3 id="xfunc-shared-addin-dynamic">
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 228871d2525..bfecce4909b 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -336,6 +336,7 @@ void
ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
{
ShmemRequest *request;
+ MemoryContext oldcontext;
/* Check the options */
if (options->name == NULL)
@@ -374,10 +375,12 @@ ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
}
/* Request looks valid, remember it */
+ oldcontext = MemoryContextSwitchTo(TopMemoryContext);
request = palloc_object(ShmemRequest);
request->options = options;
request->kind = kind;
pending_shmem_requests = lappend(pending_shmem_requests, request);
+ MemoryContextSwitchTo(oldcontext);
}
/*
@@ -903,75 +906,80 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
Assert(shmem_request_state == SRS_DONE);
shmem_request_state = SRS_REQUESTING;
- /*
- * Call the request callback first. The callback makes ShmemRequest*()
- * calls for each shmem area, adding them to pending_shmem_requests.
- */
- Assert(pending_shmem_requests == NIL);
- if (callbacks->request_fn)
- callbacks->request_fn(callbacks->opaque_arg);
- shmem_request_state = SRS_AFTER_STARTUP_ATTACH_OR_INIT;
-
- if (pending_shmem_requests == NIL)
+ PG_TRY();
{
- shmem_request_state = SRS_DONE;
- return;
- }
-
- /*
- * Hold ShmemIndexLock while we allocate all the shmem entries and run all
- * the initializers.
- */
- LWLockAcquire(ShmemIndexLock, LW_EXCLUSIVE);
-
- /*
- * Check if the requested shared memory areas have already been
- * initialized. We assume all the areas requested by the request callback
- * to form a coherent unit such that they're all already initialized or
- * none. Otherwise it would be ambiguous which callback, init or attach,
- * to callback afterwards.
- */
- found_any = notfound_any = false;
- foreach_ptr(ShmemRequest, request, pending_shmem_requests)
- {
- if (hash_search(ShmemIndex, request->options->name, HASH_FIND, NULL))
- found_any = true;
- else
- notfound_any = true;
- }
- if (found_any && notfound_any)
- elog(ERROR, "some of the requested shmem areas have already been initialized");
+ /*
+ * Call the request callback first. The callback makes
+ * ShmemRequest*() calls for each shmem area, adding them to
+ * pending_shmem_requests.
+ */
+ Assert(pending_shmem_requests == NIL);
+ if (callbacks->request_fn)
+ callbacks->request_fn(callbacks->opaque_arg);
+ shmem_request_state = SRS_AFTER_STARTUP_ATTACH_OR_INIT;
- /*
- * Allocate or attach all the shmem areas requested by the request_fn
- * callback.
- */
- foreach_ptr(ShmemRequest, request, pending_shmem_requests)
- {
- if (found_any)
- AttachShmemIndexEntry(request, false);
- else
- InitShmemIndexEntry(request);
+ if (pending_shmem_requests)
+ {
+ /*
+ * Hold ShmemIndexLock while we allocate all the shmem entries and
+ * run all the initializers.
+ */
+ LWLockAcquire(ShmemIndexLock, LW_EXCLUSIVE);
+
+ /*
+ * Check if the requested shared memory areas have already been
+ * initialized. We assume all the areas requested by the request
+ * callback to form a coherent unit such that they're all already
+ * initialized or none. Otherwise it would be ambiguous which
+ * callback, init or attach, to callback afterwards.
+ */
+ found_any = notfound_any = false;
+ foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+ {
+ if (hash_search(ShmemIndex, request->options->name, HASH_FIND, NULL))
+ found_any = true;
+ else
+ notfound_any = true;
+ }
+ if (found_any && notfound_any)
+ elog(ERROR, "some of the requested shmem areas have already been initialized");
+
+ /*
+ * Allocate or attach all the shmem areas requested by the
+ * request_fn callback.
+ */
+ foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+ {
+ if (found_any)
+ AttachShmemIndexEntry(request, false);
+ else
+ InitShmemIndexEntry(request);
+ }
- pfree(request->options);
- }
- list_free_deep(pending_shmem_requests);
- pending_shmem_requests = NIL;
+ /* Finish by calling the appropriate subsystem-specific callback. */
+ if (found_any)
+ {
+ if (callbacks->attach_fn)
+ callbacks->attach_fn(callbacks->opaque_arg);
+ }
+ else
+ {
+ if (callbacks->init_fn)
+ callbacks->init_fn(callbacks->opaque_arg);
+ }
- /* Finish by calling the appropriate subsystem-specific callback */
- if (found_any)
- {
- if (callbacks->attach_fn)
- callbacks->attach_fn(callbacks->opaque_arg);
+ LWLockRelease(ShmemIndexLock);
+ }
}
- else
+ PG_FINALLY();
{
- if (callbacks->init_fn)
- callbacks->init_fn(callbacks->opaque_arg);
+ foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+ pfree(request->options);
+ list_free_deep(pending_shmem_requests);
+ pending_shmem_requests = NIL;
+ shmem_request_state = SRS_DONE;
}
-
- LWLockRelease(ShmemIndexLock);
- shmem_request_state = SRS_DONE;
+ PG_END_TRY();
}
/*
@@ -983,6 +991,7 @@ ShmemCallRequestCallbacks(void)
ListCell *lc;
Assert(shmem_request_state == SRS_INITIAL);
+ Assert(pending_shmem_requests == NIL);
shmem_request_state = SRS_REQUESTING;
foreach(lc, registered_shmem_callbacks)
diff --git a/src/test/modules/test_shmem/Makefile b/src/test/modules/test_shmem/Makefile
index 2407f7462fe..fed8e29c8f5 100644
--- a/src/test/modules/test_shmem/Makefile
+++ b/src/test/modules/test_shmem/Makefile
@@ -2,6 +2,9 @@
PGFILEDESC = "test_shmem - test code for shmem allocations"
+EXTRA_INSTALL = src/test/modules/injection_points
+export enable_injection_points
+
MODULE_big = test_shmem
OBJS = \
$(WIN32RES) \
diff --git a/src/test/modules/test_shmem/meson.build b/src/test/modules/test_shmem/meson.build
index fb4bf328b8f..8f98f2c4e31 100644
--- a/src/test/modules/test_shmem/meson.build
+++ b/src/test/modules/test_shmem/meson.build
@@ -26,6 +26,9 @@ tests += {
'sd': meson.current_source_dir(),
'bd': meson.current_build_dir(),
'tap': {
+ 'env': {
+ 'enable_injection_points': get_option('injection_points') ? 'yes' : 'no',
+ },
'tests': [
't/001_late_shmem_alloc.pl',
],
diff --git a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
index 5cf07d071ec..7180f9deb28 100644
--- a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
+++ b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
@@ -15,8 +15,50 @@ my $node = PostgreSQL::Test::Cluster->new('main');
$node->init;
$node->start;
+# Test a failure in initialization of the shared memory area.
+SKIP:
+{
+ skip "injection points not supported by this build",
+ if $ENV{enable_injection_points} ne 'yes';
+ $node->safe_psql("postgres", "CREATE EXTENSION injection_points;");
+ $node->safe_psql("postgres",
+ "SELECT injection_points_attach('test-shmem-init', 'error');");
+
+ # A failure in the requesting shared memory should not affect server
+ # availability. The session should remain useful, however trying to create
+ # the same extension again will fail.
+ my (undef, undef, $stderr) =
+ $node->psql("postgres", "CREATE EXTENSION test_shmem;");
+ like($stderr,
+ qr/error triggered for injection point test-shmem-init/,
+ "failure in initialization is reported");
+ $node->safe_psql("postgres",
+ "SELECT injection_points_detach('test-shmem-init');");
+ (undef, undef, $stderr) =
+ $node->psql("postgres", "CREATE EXTENSION test_shmem;");
+ like($stderr, qr/shmem area not yet initialized/,
+ "post-init extension creation fails");
+
+ # Only a server restart can remove the partially allocated shared memory
+ # area.
+ $node->restart;
+}
+
+# Test failure when the request is larger than the memory reserved for
+# after-startup requests.
+my $session = $node->background_psql('postgres', on_error_stop => 0);
+$session->query(q[SET test_shmem.area_size = '128kB';], verbose => 0);
+$session->query("CREATE EXTENSION test_shmem;", verbose => 0);
+like($session->{stderr}, qr/not enough shared memory/,
+ "an after-startup request larger than the reserve fails");
-$node->safe_psql("postgres", "CREATE EXTENSION test_shmem;");
+# The server and the backend should still be available. Since there was only one
+# area requested, the failure did not change anything in the shared memory.
+# Verify that the request for smaller area succeeds in the same session.
+$session->{stderr} = '';
+$session->query("SET test_shmem.area_size = default;", verbose => 0);
+$session->query_safe("CREATE EXTENSION test_shmem;", verbose => 0);
+$session->quit;
# Check that the attach counter is incremented on a new connection
my $attach_count1 =
@@ -28,8 +70,9 @@ cmp_ok($attach_count2, '>', $attach_count1,
$node->stop;
###
-# Test that loading via shared_preload_libraries also works
+# Test that loading via shared_preload_libraries also works, even for large request.
###
+$node->append_conf('postgresql.conf', "test_shmem.area_size = '128kB'");
$node->append_conf('postgresql.conf',
"shared_preload_libraries = 'test_shmem'");
$node->start;
diff --git a/src/test/modules/test_shmem/test_shmem.c b/src/test/modules/test_shmem/test_shmem.c
index 9bd4012b435..2956f488135 100644
--- a/src/test/modules/test_shmem/test_shmem.c
+++ b/src/test/modules/test_shmem/test_shmem.c
@@ -17,9 +17,13 @@
#include "postgres.h"
+#include <limits.h>
+
#include "fmgr.h"
#include "miscadmin.h"
#include "storage/shmem.h"
+#include "utils/guc.h"
+#include "utils/injection_point.h"
PG_MODULE_MAGIC;
@@ -29,11 +33,14 @@ typedef struct TestShmemData
int value;
bool initialized;
int attach_count;
+ char variable_sized_array[FLEXIBLE_ARRAY_MEMBER];
} TestShmemData;
static TestShmemData *TestShmem;
static bool attached_or_initialized = false;
+static int test_shmem_area_size = sizeof(TestShmemData);
+static bool test_shmem_guc_defined = false;
static void test_shmem_request(void *arg);
static void test_shmem_init(void *arg);
@@ -52,7 +59,7 @@ test_shmem_request(void *arg)
elog(LOG, "test_shmem_request callback called");
ShmemRequestStruct(.name = "test_shmem area",
- .size = sizeof(TestShmemData),
+ .size = test_shmem_area_size,
.ptr = (void **) &TestShmem);
}
@@ -60,6 +67,8 @@ static void
test_shmem_init(void *arg)
{
elog(LOG, "init callback called");
+ /* Induce an error while initializing shared structure. */
+ INJECTION_POINT("test-shmem-init", NULL);
if (TestShmem->initialized)
elog(ERROR, "shmem area already initialized");
TestShmem->initialized = true;
@@ -86,6 +95,21 @@ void
_PG_init(void)
{
elog(LOG, "test_shmem module's _PG_init called");
+
+ if (!test_shmem_guc_defined)
+ {
+ DefineCustomIntVariable("test_shmem.area_size",
+ "Size of the shmem area to request.",
+ NULL,
+ &test_shmem_area_size,
+ sizeof(TestShmemData),
+ sizeof(TestShmemData), INT_MAX,
+ PGC_USERSET,
+ GUC_UNIT_BYTE,
+ NULL, NULL, NULL);
+ MarkGUCPrefixReserved("test_shmem");
+ test_shmem_guc_defined = true;
+ }
RegisterShmemCallbacks(&TestShmemCallbacks);
}
base-commit: d02a9084d91015547b831385fc007b6ac0161be5
--
2.34.1
^ permalink raw reply [nested|flat] 21+ messages in thread
* Re: Error handling in after-startup shmem requests
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-09 16:30 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-10 09:40 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-10 12:40 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-11 15:46 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-11 18:05 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 07:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-12 09:07 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 09:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-18 10:37 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
@ 2026-08-25 16:33 ` Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-25 16:47 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
0 siblings, 1 reply; 21+ messages in thread
From: Heikki Linnakangas @ 2026-08-25 16:33 UTC (permalink / raw)
To: Ayush Tiwari <ayushtiwari.slg01@gmail.com>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: pgsql-hackers
On 18/08/2026 13:37, Ayush Tiwari wrote:
> On Wed, 12 Aug 2026 at 15:12, Ashutosh Bapat
> <ashutosh.bapat.oss@gmail.com <mailto:ashutosh.bapat.oss@gmail.com>> wrote:
>
> On Wed, Aug 12, 2026 at 2:37 PM Ayush Tiwari
> <ayushtiwari.slg01@gmail.com <mailto:ayushtiwari.slg01@gmail.com>>
> wrote:
>
> > Thanks for the latest patch, it looks good to me.
> >
>
> Thanks.
>
> > I just have 2 minor editorial nits:
> >
> > - The commit message mentions
> CallShmemCallbacksAfterStartupCleanup(), but I
> > think that should be CallShmemCallbacksAfterStartup().
> >
> > - "unitialized" in xfunc.sgml should be "uninitialized".
> >
> > These can be adjusted while committing so I'm not sending an
> updated patch.
> >
>
> Attached patch fixes those two as well.
Thanks! And sorry for not picking this up earlier.
Here's my take with some small changes. This is all based on things you
already discussed, I just picked the mix I liked best:
* I added the 'initialized' flag to each shmem index entry. It feels a
little heavy-handed just to deal with failed initializations after
postmaster startup, which is a rare codepath to begin with, but then
again, it's just a boolean. You still can't really retry or recover from
a failed initialization, the entry stays in the broken state until
restart, but at least you get a nicer error message and you don't need
worry about detecting it in your extension. As evidenced by smaller
changes needed to the docs to describe it :-).
* I kept the pending_shmem_requests list in the caller's memory context.
Instead of freeing it in PG_FINALLY, I just set pending_shmem_requests =
NIL, and rely on the memory context release to free it. (I was on the
fence on this, TopMemoryContext would also be quite reasonable)
* I structured the PG_TRY/CATCH block more like you had it in the
earlier patches, adding a little helper function.
What do you think?
- Heikki
Attachments: download all (3 files, .tar.gz)
0001-Fix-backend-state-after-a-failed-after-startup-shmem.patch (text/x-patch, 4.4K) download
From d34c03b034a8ac6d806468dde16810fadaa5cbcc Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Tue, 25 Aug 2026 19:00:58 +0300
Subject: [PATCH 1/3] Fix backend state after a failed after-startup shmem
request
RegisterShmemCallbacks() left the backend in a bad state, if an error
occurred in the callbacks or if an allocation failed. Firstly,
'shmem_request_state' was left in wrong state, causing a subsequent
call to RegisterShmemCallbacks() to wrongly take the postmaster
startup codepath or assertion failures in some other functions.
Secondly, the 'pending_shmem_requests' list was not properly cleaned
up, causing a subsequent RegisterShmemCallbacks() to try to process
the stale, already-freed requests.
To fix, add a PG_TRY() block to clean those things up on error.
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
---
src/backend/storage/ipc/shmem.c | 58 +++++++++++++++++++++------------
1 file changed, 38 insertions(+), 20 deletions(-)
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 228871d2525..0fadbf85a02 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -274,6 +274,7 @@ typedef struct
static bool firstNumaTouch = true;
static void CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks);
+static void ProcessShmemRequestsAfterStartup(const ShmemCallbacks *callbacks);
static void InitShmemIndexEntry(ShmemRequest *request);
static bool AttachShmemIndexEntry(ShmemRequest *request, bool missing_ok);
@@ -897,26 +898,44 @@ RegisterShmemCallbacks(const ShmemCallbacks *callbacks)
static void
CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
{
- bool found_any;
- bool notfound_any;
-
Assert(shmem_request_state == SRS_DONE);
- shmem_request_state = SRS_REQUESTING;
-
- /*
- * Call the request callback first. The callback makes ShmemRequest*()
- * calls for each shmem area, adding them to pending_shmem_requests.
- */
Assert(pending_shmem_requests == NIL);
- if (callbacks->request_fn)
- callbacks->request_fn(callbacks->opaque_arg);
- shmem_request_state = SRS_AFTER_STARTUP_ATTACH_OR_INIT;
- if (pending_shmem_requests == NIL)
+ PG_TRY();
+ {
+ /*
+ * Call the request callback first. The callback makes
+ * ShmemRequest*() calls for each shmem area, adding them to
+ * pending_shmem_requests.
+ */
+ shmem_request_state = SRS_REQUESTING;
+ if (callbacks->request_fn)
+ callbacks->request_fn(callbacks->opaque_arg);
+
+ /* Process all the requests */
+ shmem_request_state = SRS_AFTER_STARTUP_ATTACH_OR_INIT;
+ if (pending_shmem_requests != NIL)
+ ProcessShmemRequestsAfterStartup(callbacks);
+ }
+ PG_FINALLY();
{
shmem_request_state = SRS_DONE;
- return;
+ pending_shmem_requests = NIL;
}
+ PG_END_TRY();
+}
+
+static void
+ProcessShmemRequestsAfterStartup(const ShmemCallbacks *callbacks)
+{
+ bool found_any;
+ bool notfound_any;
+
+ /* There should be some requests to process */
+ Assert(pending_shmem_requests != NIL);
+
+ /* Caller manages the global state variable */
+ Assert(shmem_request_state == SRS_AFTER_STARTUP_ATTACH_OR_INIT);
/*
* Hold ShmemIndexLock while we allocate all the shmem entries and run all
@@ -934,7 +953,11 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
found_any = notfound_any = false;
foreach_ptr(ShmemRequest, request, pending_shmem_requests)
{
- if (hash_search(ShmemIndex, request->options->name, HASH_FIND, NULL))
+ ShmemIndexEnt *index_entry;
+
+ index_entry = (ShmemIndexEnt *)
+ hash_search(ShmemIndex, request->options->name, HASH_FIND, NULL);
+ if (index_entry)
found_any = true;
else
notfound_any = true;
@@ -952,11 +975,7 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
AttachShmemIndexEntry(request, false);
else
InitShmemIndexEntry(request);
-
- pfree(request->options);
}
- list_free_deep(pending_shmem_requests);
- pending_shmem_requests = NIL;
/* Finish by calling the appropriate subsystem-specific callback */
if (found_any)
@@ -971,7 +990,6 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
}
LWLockRelease(ShmemIndexLock);
- shmem_request_state = SRS_DONE;
}
/*
--
2.47.3
0002-Track-which-shmem-areas-have-been-fully-initialized.patch (text/x-patch, 7.9K) download
From 6852c567d367451afa89941f4587da6c1df8d677 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 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..3f6a69212ae 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
0003-Add-tests-for-failing-shmem-allocations-after-startu.patch (text/x-patch, 6.6K) download
From 82472c69efe4c7d8d07023eb4ef3b08bb33b97f2 Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Tue, 25 Aug 2026 19:12:09 +0300
Subject: [PATCH 3/3] Add tests for failing shmem allocations after startup
To cover the failure cases that the previous commits hardened.
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
---
src/test/modules/test_shmem/Makefile | 3 ++
src/test/modules/test_shmem/meson.build | 3 ++
.../test_shmem/t/001_late_shmem_alloc.pl | 47 ++++++++++++++++++-
src/test/modules/test_shmem/test_shmem.c | 26 +++++++++-
4 files changed, 76 insertions(+), 3 deletions(-)
diff --git a/src/test/modules/test_shmem/Makefile b/src/test/modules/test_shmem/Makefile
index 2407f7462fe..fed8e29c8f5 100644
--- a/src/test/modules/test_shmem/Makefile
+++ b/src/test/modules/test_shmem/Makefile
@@ -2,6 +2,9 @@
PGFILEDESC = "test_shmem - test code for shmem allocations"
+EXTRA_INSTALL = src/test/modules/injection_points
+export enable_injection_points
+
MODULE_big = test_shmem
OBJS = \
$(WIN32RES) \
diff --git a/src/test/modules/test_shmem/meson.build b/src/test/modules/test_shmem/meson.build
index fb4bf328b8f..8f98f2c4e31 100644
--- a/src/test/modules/test_shmem/meson.build
+++ b/src/test/modules/test_shmem/meson.build
@@ -26,6 +26,9 @@ tests += {
'sd': meson.current_source_dir(),
'bd': meson.current_build_dir(),
'tap': {
+ 'env': {
+ 'enable_injection_points': get_option('injection_points') ? 'yes' : 'no',
+ },
'tests': [
't/001_late_shmem_alloc.pl',
],
diff --git a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
index 5cf07d071ec..b09889f4fb0 100644
--- a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
+++ b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
@@ -15,8 +15,50 @@ my $node = PostgreSQL::Test::Cluster->new('main');
$node->init;
$node->start;
+# Test a failure in initialization of the shared memory area.
+SKIP:
+{
+ skip "injection points not supported by this build",
+ if $ENV{enable_injection_points} ne 'yes';
+ $node->safe_psql("postgres", "CREATE EXTENSION injection_points;");
+ $node->safe_psql("postgres",
+ "SELECT injection_points_attach('test-shmem-init', 'error');");
+
+ # A failure in the requesting shared memory should not affect server
+ # availability. The session should remain useful, however trying to create
+ # the same extension again will fail.
+ my (undef, undef, $stderr) =
+ $node->psql("postgres", "CREATE EXTENSION test_shmem;");
+ like($stderr,
+ qr/error triggered for injection point test-shmem-init/,
+ "failure in initialization is reported");
+ $node->safe_psql("postgres",
+ "SELECT injection_points_detach('test-shmem-init');");
+ (undef, undef, $stderr) =
+ $node->psql("postgres", "CREATE EXTENSION test_shmem;");
+ like($stderr, qr/cannot attach to shared memory/,
+ "post-init extension creation fails");
+
+ # Only a server restart can remove the partially allocated shared memory
+ # area.
+ $node->restart;
+}
+
+# Test failure when the request is larger than the memory reserved for
+# after-startup requests.
+my $session = $node->background_psql('postgres', on_error_stop => 0);
+$session->query(q[SET test_shmem.area_size = '128kB';], verbose => 0);
+$session->query("CREATE EXTENSION test_shmem;", verbose => 0);
+like($session->{stderr}, qr/not enough shared memory/,
+ "an after-startup request larger than the reserve fails");
-$node->safe_psql("postgres", "CREATE EXTENSION test_shmem;");
+# The server and the backend should still be available. Since there was only one
+# area requested, the failure did not change anything in the shared memory.
+# Verify that the request for smaller area succeeds in the same session.
+$session->{stderr} = '';
+$session->query("SET test_shmem.area_size = default;", verbose => 0);
+$session->query_safe("CREATE EXTENSION test_shmem;", verbose => 0);
+$session->quit;
# Check that the attach counter is incremented on a new connection
my $attach_count1 =
@@ -28,8 +70,9 @@ cmp_ok($attach_count2, '>', $attach_count1,
$node->stop;
###
-# Test that loading via shared_preload_libraries also works
+# Test that loading via shared_preload_libraries also works, even for large request.
###
+$node->append_conf('postgresql.conf', "test_shmem.area_size = '128kB'");
$node->append_conf('postgresql.conf',
"shared_preload_libraries = 'test_shmem'");
$node->start;
diff --git a/src/test/modules/test_shmem/test_shmem.c b/src/test/modules/test_shmem/test_shmem.c
index 9bd4012b435..2956f488135 100644
--- a/src/test/modules/test_shmem/test_shmem.c
+++ b/src/test/modules/test_shmem/test_shmem.c
@@ -17,9 +17,13 @@
#include "postgres.h"
+#include <limits.h>
+
#include "fmgr.h"
#include "miscadmin.h"
#include "storage/shmem.h"
+#include "utils/guc.h"
+#include "utils/injection_point.h"
PG_MODULE_MAGIC;
@@ -29,11 +33,14 @@ typedef struct TestShmemData
int value;
bool initialized;
int attach_count;
+ char variable_sized_array[FLEXIBLE_ARRAY_MEMBER];
} TestShmemData;
static TestShmemData *TestShmem;
static bool attached_or_initialized = false;
+static int test_shmem_area_size = sizeof(TestShmemData);
+static bool test_shmem_guc_defined = false;
static void test_shmem_request(void *arg);
static void test_shmem_init(void *arg);
@@ -52,7 +59,7 @@ test_shmem_request(void *arg)
elog(LOG, "test_shmem_request callback called");
ShmemRequestStruct(.name = "test_shmem area",
- .size = sizeof(TestShmemData),
+ .size = test_shmem_area_size,
.ptr = (void **) &TestShmem);
}
@@ -60,6 +67,8 @@ static void
test_shmem_init(void *arg)
{
elog(LOG, "init callback called");
+ /* Induce an error while initializing shared structure. */
+ INJECTION_POINT("test-shmem-init", NULL);
if (TestShmem->initialized)
elog(ERROR, "shmem area already initialized");
TestShmem->initialized = true;
@@ -86,6 +95,21 @@ void
_PG_init(void)
{
elog(LOG, "test_shmem module's _PG_init called");
+
+ if (!test_shmem_guc_defined)
+ {
+ DefineCustomIntVariable("test_shmem.area_size",
+ "Size of the shmem area to request.",
+ NULL,
+ &test_shmem_area_size,
+ sizeof(TestShmemData),
+ sizeof(TestShmemData), INT_MAX,
+ PGC_USERSET,
+ GUC_UNIT_BYTE,
+ NULL, NULL, NULL);
+ MarkGUCPrefixReserved("test_shmem");
+ test_shmem_guc_defined = true;
+ }
RegisterShmemCallbacks(&TestShmemCallbacks);
}
--
2.47.3
^ permalink raw reply [nested|flat] 21+ messages in thread
* Re: Error handling in after-startup shmem requests
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-09 16:30 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-10 09:40 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-10 12:40 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-11 15:46 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-11 18:05 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 07:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-12 09:07 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 09:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-18 10:37 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-25 16:33 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
@ 2026-08-25 16:47 ` Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-26 05:59 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
0 siblings, 1 reply; 21+ messages in thread
From: Heikki Linnakangas @ 2026-08-25 16:47 UTC (permalink / raw)
To: Ayush Tiwari <ayushtiwari.slg01@gmail.com>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; +Cc: pgsql-hackers
On 25/08/2026 19:33, Heikki Linnakangas wrote:
> Here's my take with some small changes. This is all based on things you
> already discussed, I just picked the mix I liked best:
And here are the same patches, without the broken comment so that it
actually compiles... :facepalm:
- Heikki
Attachments: download all (3 files, .tar.gz)
v2-0001-Fix-backend-state-after-a-failed-after-startup-sh.patch (text/x-patch, 4.4K) download
From d34c03b034a8ac6d806468dde16810fadaa5cbcc Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Tue, 25 Aug 2026 19:00:58 +0300
Subject: [PATCH v2 1/3] Fix backend state after a failed after-startup shmem
request
RegisterShmemCallbacks() left the backend in a bad state, if an error
occurred in the callbacks or if an allocation failed. Firstly,
'shmem_request_state' was left in wrong state, causing a subsequent
call to RegisterShmemCallbacks() to wrongly take the postmaster
startup codepath or assertion failures in some other functions.
Secondly, the 'pending_shmem_requests' list was not properly cleaned
up, causing a subsequent RegisterShmemCallbacks() to try to process
the stale, already-freed requests.
To fix, add a PG_TRY() block to clean those things up on error.
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
---
src/backend/storage/ipc/shmem.c | 58 +++++++++++++++++++++------------
1 file changed, 38 insertions(+), 20 deletions(-)
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 228871d2525..0fadbf85a02 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -274,6 +274,7 @@ typedef struct
static bool firstNumaTouch = true;
static void CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks);
+static void ProcessShmemRequestsAfterStartup(const ShmemCallbacks *callbacks);
static void InitShmemIndexEntry(ShmemRequest *request);
static bool AttachShmemIndexEntry(ShmemRequest *request, bool missing_ok);
@@ -897,26 +898,44 @@ RegisterShmemCallbacks(const ShmemCallbacks *callbacks)
static void
CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
{
- bool found_any;
- bool notfound_any;
-
Assert(shmem_request_state == SRS_DONE);
- shmem_request_state = SRS_REQUESTING;
-
- /*
- * Call the request callback first. The callback makes ShmemRequest*()
- * calls for each shmem area, adding them to pending_shmem_requests.
- */
Assert(pending_shmem_requests == NIL);
- if (callbacks->request_fn)
- callbacks->request_fn(callbacks->opaque_arg);
- shmem_request_state = SRS_AFTER_STARTUP_ATTACH_OR_INIT;
- if (pending_shmem_requests == NIL)
+ PG_TRY();
+ {
+ /*
+ * Call the request callback first. The callback makes
+ * ShmemRequest*() calls for each shmem area, adding them to
+ * pending_shmem_requests.
+ */
+ shmem_request_state = SRS_REQUESTING;
+ if (callbacks->request_fn)
+ callbacks->request_fn(callbacks->opaque_arg);
+
+ /* Process all the requests */
+ shmem_request_state = SRS_AFTER_STARTUP_ATTACH_OR_INIT;
+ if (pending_shmem_requests != NIL)
+ ProcessShmemRequestsAfterStartup(callbacks);
+ }
+ PG_FINALLY();
{
shmem_request_state = SRS_DONE;
- return;
+ pending_shmem_requests = NIL;
}
+ PG_END_TRY();
+}
+
+static void
+ProcessShmemRequestsAfterStartup(const ShmemCallbacks *callbacks)
+{
+ bool found_any;
+ bool notfound_any;
+
+ /* There should be some requests to process */
+ Assert(pending_shmem_requests != NIL);
+
+ /* Caller manages the global state variable */
+ Assert(shmem_request_state == SRS_AFTER_STARTUP_ATTACH_OR_INIT);
/*
* Hold ShmemIndexLock while we allocate all the shmem entries and run all
@@ -934,7 +953,11 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
found_any = notfound_any = false;
foreach_ptr(ShmemRequest, request, pending_shmem_requests)
{
- if (hash_search(ShmemIndex, request->options->name, HASH_FIND, NULL))
+ ShmemIndexEnt *index_entry;
+
+ index_entry = (ShmemIndexEnt *)
+ hash_search(ShmemIndex, request->options->name, HASH_FIND, NULL);
+ if (index_entry)
found_any = true;
else
notfound_any = true;
@@ -952,11 +975,7 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
AttachShmemIndexEntry(request, false);
else
InitShmemIndexEntry(request);
-
- pfree(request->options);
}
- list_free_deep(pending_shmem_requests);
- pending_shmem_requests = NIL;
/* Finish by calling the appropriate subsystem-specific callback */
if (found_any)
@@ -971,7 +990,6 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
}
LWLockRelease(ShmemIndexLock);
- shmem_request_state = SRS_DONE;
}
/*
--
2.47.3
v2-0002-Track-which-shmem-areas-have-been-fully-initializ.patch (text/x-patch, 7.9K) download
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
v2-0003-Add-tests-for-failing-shmem-allocations-after-sta.patch (text/x-patch, 6.6K) download
From 2fa1f0780aecb1f2bc88da750f9e4fb10cb4f373 Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Tue, 25 Aug 2026 19:12:09 +0300
Subject: [PATCH v2 3/3] Add tests for failing shmem allocations after startup
To cover the failure cases that the previous commits hardened.
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
---
src/test/modules/test_shmem/Makefile | 3 ++
src/test/modules/test_shmem/meson.build | 3 ++
.../test_shmem/t/001_late_shmem_alloc.pl | 47 ++++++++++++++++++-
src/test/modules/test_shmem/test_shmem.c | 26 +++++++++-
4 files changed, 76 insertions(+), 3 deletions(-)
diff --git a/src/test/modules/test_shmem/Makefile b/src/test/modules/test_shmem/Makefile
index 2407f7462fe..fed8e29c8f5 100644
--- a/src/test/modules/test_shmem/Makefile
+++ b/src/test/modules/test_shmem/Makefile
@@ -2,6 +2,9 @@
PGFILEDESC = "test_shmem - test code for shmem allocations"
+EXTRA_INSTALL = src/test/modules/injection_points
+export enable_injection_points
+
MODULE_big = test_shmem
OBJS = \
$(WIN32RES) \
diff --git a/src/test/modules/test_shmem/meson.build b/src/test/modules/test_shmem/meson.build
index fb4bf328b8f..8f98f2c4e31 100644
--- a/src/test/modules/test_shmem/meson.build
+++ b/src/test/modules/test_shmem/meson.build
@@ -26,6 +26,9 @@ tests += {
'sd': meson.current_source_dir(),
'bd': meson.current_build_dir(),
'tap': {
+ 'env': {
+ 'enable_injection_points': get_option('injection_points') ? 'yes' : 'no',
+ },
'tests': [
't/001_late_shmem_alloc.pl',
],
diff --git a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
index 5cf07d071ec..b09889f4fb0 100644
--- a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
+++ b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
@@ -15,8 +15,50 @@ my $node = PostgreSQL::Test::Cluster->new('main');
$node->init;
$node->start;
+# Test a failure in initialization of the shared memory area.
+SKIP:
+{
+ skip "injection points not supported by this build",
+ if $ENV{enable_injection_points} ne 'yes';
+ $node->safe_psql("postgres", "CREATE EXTENSION injection_points;");
+ $node->safe_psql("postgres",
+ "SELECT injection_points_attach('test-shmem-init', 'error');");
+
+ # A failure in the requesting shared memory should not affect server
+ # availability. The session should remain useful, however trying to create
+ # the same extension again will fail.
+ my (undef, undef, $stderr) =
+ $node->psql("postgres", "CREATE EXTENSION test_shmem;");
+ like($stderr,
+ qr/error triggered for injection point test-shmem-init/,
+ "failure in initialization is reported");
+ $node->safe_psql("postgres",
+ "SELECT injection_points_detach('test-shmem-init');");
+ (undef, undef, $stderr) =
+ $node->psql("postgres", "CREATE EXTENSION test_shmem;");
+ like($stderr, qr/cannot attach to shared memory/,
+ "post-init extension creation fails");
+
+ # Only a server restart can remove the partially allocated shared memory
+ # area.
+ $node->restart;
+}
+
+# Test failure when the request is larger than the memory reserved for
+# after-startup requests.
+my $session = $node->background_psql('postgres', on_error_stop => 0);
+$session->query(q[SET test_shmem.area_size = '128kB';], verbose => 0);
+$session->query("CREATE EXTENSION test_shmem;", verbose => 0);
+like($session->{stderr}, qr/not enough shared memory/,
+ "an after-startup request larger than the reserve fails");
-$node->safe_psql("postgres", "CREATE EXTENSION test_shmem;");
+# The server and the backend should still be available. Since there was only one
+# area requested, the failure did not change anything in the shared memory.
+# Verify that the request for smaller area succeeds in the same session.
+$session->{stderr} = '';
+$session->query("SET test_shmem.area_size = default;", verbose => 0);
+$session->query_safe("CREATE EXTENSION test_shmem;", verbose => 0);
+$session->quit;
# Check that the attach counter is incremented on a new connection
my $attach_count1 =
@@ -28,8 +70,9 @@ cmp_ok($attach_count2, '>', $attach_count1,
$node->stop;
###
-# Test that loading via shared_preload_libraries also works
+# Test that loading via shared_preload_libraries also works, even for large request.
###
+$node->append_conf('postgresql.conf', "test_shmem.area_size = '128kB'");
$node->append_conf('postgresql.conf',
"shared_preload_libraries = 'test_shmem'");
$node->start;
diff --git a/src/test/modules/test_shmem/test_shmem.c b/src/test/modules/test_shmem/test_shmem.c
index 9bd4012b435..2956f488135 100644
--- a/src/test/modules/test_shmem/test_shmem.c
+++ b/src/test/modules/test_shmem/test_shmem.c
@@ -17,9 +17,13 @@
#include "postgres.h"
+#include <limits.h>
+
#include "fmgr.h"
#include "miscadmin.h"
#include "storage/shmem.h"
+#include "utils/guc.h"
+#include "utils/injection_point.h"
PG_MODULE_MAGIC;
@@ -29,11 +33,14 @@ typedef struct TestShmemData
int value;
bool initialized;
int attach_count;
+ char variable_sized_array[FLEXIBLE_ARRAY_MEMBER];
} TestShmemData;
static TestShmemData *TestShmem;
static bool attached_or_initialized = false;
+static int test_shmem_area_size = sizeof(TestShmemData);
+static bool test_shmem_guc_defined = false;
static void test_shmem_request(void *arg);
static void test_shmem_init(void *arg);
@@ -52,7 +59,7 @@ test_shmem_request(void *arg)
elog(LOG, "test_shmem_request callback called");
ShmemRequestStruct(.name = "test_shmem area",
- .size = sizeof(TestShmemData),
+ .size = test_shmem_area_size,
.ptr = (void **) &TestShmem);
}
@@ -60,6 +67,8 @@ static void
test_shmem_init(void *arg)
{
elog(LOG, "init callback called");
+ /* Induce an error while initializing shared structure. */
+ INJECTION_POINT("test-shmem-init", NULL);
if (TestShmem->initialized)
elog(ERROR, "shmem area already initialized");
TestShmem->initialized = true;
@@ -86,6 +95,21 @@ void
_PG_init(void)
{
elog(LOG, "test_shmem module's _PG_init called");
+
+ if (!test_shmem_guc_defined)
+ {
+ DefineCustomIntVariable("test_shmem.area_size",
+ "Size of the shmem area to request.",
+ NULL,
+ &test_shmem_area_size,
+ sizeof(TestShmemData),
+ sizeof(TestShmemData), INT_MAX,
+ PGC_USERSET,
+ GUC_UNIT_BYTE,
+ NULL, NULL, NULL);
+ MarkGUCPrefixReserved("test_shmem");
+ test_shmem_guc_defined = true;
+ }
RegisterShmemCallbacks(&TestShmemCallbacks);
}
--
2.47.3
^ permalink raw reply [nested|flat] 21+ messages in thread
* Re: Error handling in after-startup shmem requests
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-09 16:30 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-10 09:40 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-10 12:40 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-11 15:46 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-11 18:05 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 07:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-12 09:07 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 09:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-18 10:37 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-25 16:33 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-25 16:47 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
@ 2026-08-26 05:59 ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-26 12:23 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
0 siblings, 1 reply; 21+ messages in thread
From: Ayush Tiwari @ 2026-08-26 05:59 UTC (permalink / raw)
To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers
Hi,
On Tue, 25 Aug 2026 at 22:17, Heikki Linnakangas <hlinnaka@iki.fi> wrote:
> On 25/08/2026 19:33, Heikki Linnakangas wrote:
> > Here's my take with some small changes. This is all based on things you
> > already discussed, I just picked the mix I liked best:
>
> And here are the same patches, without the broken comment so that it
> actually compiles... :facepalm:
>
Thanks a lot for the review and patch set.
This approach looks good to me overall. I built the v2 series with
assertions and injection points enabled, and all five tests passed.
I had one question about the lifetime of the options copy. It is still
allocated in TopMemoryContext, while the after-startup path no longer calls
pfree(request->options). The PG_FINALLY block clears
pending_shmem_requests, but could that leave the options allocated until
backend exit? The impact seems small, but perhaps the options should be
freed before clearing the list, or allocated in the same context as the
requests?
One minor test nit:
- The comment says "A failure in the requesting shared memory", but the
injection point triggers in test_shmem_init(), so would "initializing
shared memory" be more accurate?
Regards,
Ayush
^ permalink raw reply [nested|flat] 21+ messages in thread
* Re: Error handling in after-startup shmem requests
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-09 16:30 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-10 09:40 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-10 12:40 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-11 15:46 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-11 18:05 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 07:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-12 09:07 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 09:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-18 10:37 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-25 16:33 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-25 16:47 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-26 05:59 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
@ 2026-08-26 12:23 ` Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-26 12:44 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
0 siblings, 1 reply; 21+ messages in thread
From: Heikki Linnakangas @ 2026-08-26 12:23 UTC (permalink / raw)
To: Ayush Tiwari <ayushtiwari.slg01@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers
On 26/08/2026 08:59, Ayush Tiwari wrote:
> This approach looks good to me overall. I built the v2 series with
> assertions and injection points enabled, and all five tests passed.
>
> I had one question about the lifetime of the options copy. It is still
> allocated in TopMemoryContext, while the after-startup path no longer calls
> pfree(request->options). The PG_FINALLY block clears
> pending_shmem_requests, but could that leave the options allocated until
> backend exit? The impact seems small, but perhaps the options should be
> freed before clearing the list, or allocated in the same context as the
> requests?
You're right. I changed it to use TopMemoryContext like you had it
originally. That seems more clear, after all.
> One minor test nit:
>
> - The comment says "A failure in the requesting shared memory", but the
> injection point triggers in test_shmem_init(), so would "initializing
> shared memory" be more accurate?
Yeah. I did some other cleanups in the test too, and merged the tests
into the commits with the code fixes. Here's a new version, if you want
to have one final look.
- Heikki
Attachments: download all (2 files, .tar.gz)
v3-0001-Fix-backend-state-after-a-failed-after-startup-sh.patch (text/x-patch, 8.9K) download
From 9c9a8d076b6c253a6f458cdad056057d6cee0153 Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Wed, 26 Aug 2026 15:10:49 +0300
Subject: [PATCH v3 1/2] Fix backend state after a failed after-startup shmem
request
RegisterShmemCallbacks() left the backend in a bad state, if an error
occurred in the callbacks or if an allocation failed. Firstly,
'shmem_request_state' was left in wrong state, causing a subsequent
call to RegisterShmemCallbacks() to wrongly take the postmaster
startup codepath or assertion failures in some other functions.
Secondly, the 'pending_shmem_requests' list was not properly cleaned
up, causing a subsequent RegisterShmemCallbacks() to try to process
the stale, already-freed requests.
To fix, add a PG_TRY() block to clean those things up on error.
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
---
src/backend/storage/ipc/shmem.c | 72 +++++++++++++------
.../test_shmem/t/001_late_shmem_alloc.pl | 28 ++++++++
src/test/modules/test_shmem/test_shmem.c | 28 +++++++-
3 files changed, 104 insertions(+), 24 deletions(-)
diff --git a/src/backend/storage/ipc/shmem.c b/src/backend/storage/ipc/shmem.c
index 98aaee00bfd..f88642e6b8b 100644
--- a/src/backend/storage/ipc/shmem.c
+++ b/src/backend/storage/ipc/shmem.c
@@ -158,7 +158,9 @@ static List *registered_shmem_callbacks;
/*
* In the shmem request phase, all the shmem areas requested with the
- * ShmemRequest*() functions are accumulated here.
+ * ShmemRequest*() functions are accumulated in the 'pending_shmem_requests'
+ * list. The List, the ShmemRequest structs, and the 'options' are all
+ * allocated in TopMemoryContext.
*/
typedef struct
{
@@ -166,7 +168,7 @@ typedef struct
ShmemRequestKind kind;
} ShmemRequest;
-static List *pending_shmem_requests;
+static List *pending_shmem_requests; /* List of ShmemRequests */
/*
* Per-process state machine, for sanity checking that we do things in the
@@ -274,6 +276,7 @@ typedef struct
static bool firstNumaTouch = true;
static void CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks);
+static void ProcessShmemRequestsAfterStartup(const ShmemCallbacks *callbacks);
static void InitShmemIndexEntry(ShmemRequest *request);
static bool AttachShmemIndexEntry(ShmemRequest *request, bool missing_ok);
@@ -335,6 +338,7 @@ ShmemRequestStructWithOpts(const ShmemStructOpts *options)
void
ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
{
+ MemoryContext oldcontext;
ShmemRequest *request;
/* Check the options */
@@ -374,10 +378,12 @@ ShmemRequestInternal(ShmemStructOpts *options, ShmemRequestKind kind)
}
/* Request looks valid, remember it */
+ oldcontext = MemoryContextSwitchTo(TopMemoryContext);
request = palloc_object(ShmemRequest);
request->options = options;
request->kind = kind;
pending_shmem_requests = lappend(pending_shmem_requests, request);
+ MemoryContextSwitchTo(oldcontext);
}
/*
@@ -903,26 +909,49 @@ RegisterShmemCallbacks(const ShmemCallbacks *callbacks)
static void
CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
{
- bool found_any;
- bool notfound_any;
-
Assert(shmem_request_state == SRS_DONE);
- shmem_request_state = SRS_REQUESTING;
-
- /*
- * Call the request callback first. The callback makes ShmemRequest*()
- * calls for each shmem area, adding them to pending_shmem_requests.
- */
Assert(pending_shmem_requests == NIL);
- if (callbacks->request_fn)
- callbacks->request_fn(callbacks->opaque_arg);
- shmem_request_state = SRS_AFTER_STARTUP_ATTACH_OR_INIT;
- if (pending_shmem_requests == NIL)
+ PG_TRY();
+ {
+ shmem_request_state = SRS_REQUESTING;
+
+ /*
+ * Call the request callback first. The callback makes
+ * ShmemRequest*() calls for each shmem area, adding them to
+ * pending_shmem_requests.
+ */
+ if (callbacks->request_fn)
+ callbacks->request_fn(callbacks->opaque_arg);
+
+ /* Process all the requests */
+ shmem_request_state = SRS_AFTER_STARTUP_ATTACH_OR_INIT;
+ if (pending_shmem_requests != NIL)
+ ProcessShmemRequestsAfterStartup(callbacks);
+ }
+ PG_FINALLY();
{
+ foreach_ptr(ShmemRequest, request, pending_shmem_requests)
+ pfree(request->options);
+ list_free_deep(pending_shmem_requests);
+ pending_shmem_requests = NIL;
+
shmem_request_state = SRS_DONE;
- return;
}
+ PG_END_TRY();
+}
+
+static void
+ProcessShmemRequestsAfterStartup(const ShmemCallbacks *callbacks)
+{
+ bool found_any;
+ bool notfound_any;
+
+ /* There should be some requests to process */
+ Assert(pending_shmem_requests != NIL);
+
+ /* Caller manages the global state variable */
+ Assert(shmem_request_state == SRS_AFTER_STARTUP_ATTACH_OR_INIT);
/*
* Hold ShmemIndexLock while we allocate all the shmem entries and run all
@@ -940,7 +969,11 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
found_any = notfound_any = false;
foreach_ptr(ShmemRequest, request, pending_shmem_requests)
{
- if (hash_search(ShmemIndex, request->options->name, HASH_FIND, NULL))
+ ShmemIndexEnt *index_entry;
+
+ index_entry = (ShmemIndexEnt *)
+ hash_search(ShmemIndex, request->options->name, HASH_FIND, NULL);
+ if (index_entry)
found_any = true;
else
notfound_any = true;
@@ -958,11 +991,7 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
AttachShmemIndexEntry(request, false);
else
InitShmemIndexEntry(request);
-
- pfree(request->options);
}
- list_free_deep(pending_shmem_requests);
- pending_shmem_requests = NIL;
/* Finish by calling the appropriate subsystem-specific callback */
if (found_any)
@@ -977,7 +1006,6 @@ CallShmemCallbacksAfterStartup(const ShmemCallbacks *callbacks)
}
LWLockRelease(ShmemIndexLock);
- shmem_request_state = SRS_DONE;
}
/*
diff --git a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
index 546d6a92abe..6ea409f3c63 100644
--- a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
+++ b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
@@ -78,5 +78,33 @@ else
);
}
+# clean up
$node->stop;
+$node->adjust_conf('postgresql.conf', "shared_preload_libraries", undef);
+
+###
+# Test "out of shared memory" in an after-startup request
+###
+$node->start;
+my $session = $node->background_psql('postgres', on_error_stop => 0);
+
+# make the request larger than the memory reserved for after-startup
+# requests.
+$session->query(q[SET test_shmem.area_size = '128kB';]);
+
+$session->query("SELECT get_test_shmem_attach_count();");
+like(
+ $session->{stderr},
+ qr/not enough shared memory/,
+ "an after-startup request larger than the reserve fails");
+
+# The server and the backend keep running. Since only one area was
+# requested, it gets cleaned up on allocation failure. Verify that a
+# request for a smaller area succeeds in the same session.
+$session->{stderr} = '';
+$session->query("SET test_shmem.area_size = default;");
+$session->query_safe("SELECT get_test_shmem_attach_count();");
+$session->quit;
+$node->stop;
+
done_testing();
diff --git a/src/test/modules/test_shmem/test_shmem.c b/src/test/modules/test_shmem/test_shmem.c
index 9bd4012b435..231ad9a0027 100644
--- a/src/test/modules/test_shmem/test_shmem.c
+++ b/src/test/modules/test_shmem/test_shmem.c
@@ -20,20 +20,28 @@
#include "fmgr.h"
#include "miscadmin.h"
#include "storage/shmem.h"
+#include "utils/guc.h"
+#include "utils/injection_point.h"
PG_MODULE_MAGIC;
typedef struct TestShmemData
{
- int value;
bool initialized;
int attach_count;
+ char dummy_data[FLEXIBLE_ARRAY_MEMBER];
} TestShmemData;
static TestShmemData *TestShmem;
+#define MIN_TEST_AREA_BYTES sizeof(TestShmemData)
+#define DEFAULT_TEST_AREA_BYTES MIN_TEST_AREA_BYTES
+#define MAX_TEST_AREA_BYTES 1000000
+
static bool attached_or_initialized = false;
+static int test_shmem_area_size = MIN_TEST_AREA_BYTES;
+static bool test_shmem_guc_defined = false;
static void test_shmem_request(void *arg);
static void test_shmem_init(void *arg);
@@ -52,7 +60,7 @@ test_shmem_request(void *arg)
elog(LOG, "test_shmem_request callback called");
ShmemRequestStruct(.name = "test_shmem area",
- .size = sizeof(TestShmemData),
+ .size = test_shmem_area_size,
.ptr = (void **) &TestShmem);
}
@@ -86,6 +94,22 @@ void
_PG_init(void)
{
elog(LOG, "test_shmem module's _PG_init called");
+
+ if (!test_shmem_guc_defined)
+ {
+ DefineCustomIntVariable("test_shmem.area_size",
+ "Size of the shmem area to request.",
+ NULL,
+ &test_shmem_area_size,
+ DEFAULT_TEST_AREA_BYTES,
+ MIN_TEST_AREA_BYTES,
+ MAX_TEST_AREA_BYTES,
+ PGC_USERSET,
+ GUC_UNIT_BYTE,
+ NULL, NULL, NULL);
+ MarkGUCPrefixReserved("test_shmem");
+ test_shmem_guc_defined = true;
+ }
RegisterShmemCallbacks(&TestShmemCallbacks);
}
--
2.47.3
v3-0002-Track-which-shmem-areas-have-been-fully-initializ.patch (text/x-patch, 12.2K) download
From 455b592a0db627322e1e8765bc26f8a288a20b35 Mon Sep 17 00:00:00 2001
From: Heikki Linnakangas <heikki.linnakangas@iki.fi>
Date: Wed, 26 Aug 2026 15:20:43 +0300
Subject: [PATCH v3 2/2] 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 +++++++++++++++++--
src/test/modules/test_shmem/Makefile | 3 +
src/test/modules/test_shmem/meson.build | 3 +
.../test_shmem/t/001_late_shmem_alloc.pl | 50 ++++++++++++--
src/test/modules/test_shmem/test_shmem.c | 3 +
6 files changed, 120 insertions(+), 11 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 f88642e6b8b..f971ee24192 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.
*
@@ -166,6 +168,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; /* List of ShmemRequests */
@@ -264,12 +269,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 */
@@ -382,6 +388,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);
MemoryContextSwitchTo(oldcontext);
}
@@ -441,10 +448,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
@@ -456,6 +460,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;
}
@@ -557,7 +570,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:
@@ -571,6 +589,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;
}
/*
@@ -600,6 +621,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)
@@ -628,6 +663,8 @@ AttachShmemIndexEntry(ShmemRequest *request, bool missing_ok)
break;
}
+ request->index_entry = index_entry;
+
return true;
}
@@ -738,6 +775,7 @@ InitShmemAllocator(PGShmemHeader *seghdr)
result->size = ShmemAllocator->index_size;
result->allocated_size = ShmemAllocator->index_size;
result->location = ShmemAllocator->index;
+ result->initialized = true;
}
}
@@ -974,7 +1012,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;
}
@@ -1005,6 +1053,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);
}
@@ -1069,7 +1122,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);
diff --git a/src/test/modules/test_shmem/Makefile b/src/test/modules/test_shmem/Makefile
index 2407f7462fe..fed8e29c8f5 100644
--- a/src/test/modules/test_shmem/Makefile
+++ b/src/test/modules/test_shmem/Makefile
@@ -2,6 +2,9 @@
PGFILEDESC = "test_shmem - test code for shmem allocations"
+EXTRA_INSTALL = src/test/modules/injection_points
+export enable_injection_points
+
MODULE_big = test_shmem
OBJS = \
$(WIN32RES) \
diff --git a/src/test/modules/test_shmem/meson.build b/src/test/modules/test_shmem/meson.build
index fb4bf328b8f..8f98f2c4e31 100644
--- a/src/test/modules/test_shmem/meson.build
+++ b/src/test/modules/test_shmem/meson.build
@@ -26,6 +26,9 @@ tests += {
'sd': meson.current_source_dir(),
'bd': meson.current_build_dir(),
'tap': {
+ 'env': {
+ 'enable_injection_points': get_option('injection_points') ? 'yes' : 'no',
+ },
'tests': [
't/001_late_shmem_alloc.pl',
],
diff --git a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
index 6ea409f3c63..a7126ebce3f 100644
--- a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
+++ b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
@@ -7,17 +7,20 @@ use PostgreSQL::Test::Cluster;
use PostgreSQL::Test::Utils;
use Test::More;
+# Initialize a cluster with the extension installed. The tests will
+# call the function that comes with the extension to load it.
+my $node = PostgreSQL::Test::Cluster->new('main');
+$node->init;
+$node->start;
+$node->safe_psql("postgres", "CREATE EXTENSION test_shmem");
+$node->stop;
+
###
# Test allocating memory after startup, i.e. when the library is not
# in shared_preload_libraries
###
-my $node = PostgreSQL::Test::Cluster->new('main');
-$node->init;
$node->start;
-
-$node->safe_psql("postgres", "CREATE EXTENSION test_shmem;");
-
# Check that the attach counter is incremented on a new connection
my $attach_count1 =
$node->safe_psql("postgres", "SELECT get_test_shmem_attach_count();");
@@ -25,6 +28,7 @@ my $attach_count2 =
$node->safe_psql("postgres", "SELECT get_test_shmem_attach_count();");
cmp_ok($attach_count2, '>', $attach_count1,
"attach callback is called in each backend");
+
$node->stop;
###
@@ -82,6 +86,42 @@ else
$node->stop;
$node->adjust_conf('postgresql.conf', "shared_preload_libraries", undef);
+###
+# Test a failure in initializing the shared memory area
+###
+SKIP:
+{
+ skip "injection points not supported by this build",
+ if $ENV{enable_injection_points} ne 'yes';
+ $node->start;
+ $node->safe_psql("postgres", "CREATE EXTENSION injection_points;");
+ $node->safe_psql("postgres",
+ "SELECT injection_points_attach('test-shmem-init', 'error');");
+
+ # Try to load the extension library. It will hit the injected
+ # error in the init callback.
+ my (undef, undef, $stderr) =
+ $node->psql("postgres", "SELECT get_test_shmem_attach_count();");
+ like(
+ $stderr,
+ qr/error triggered for injection point test-shmem-init/,
+ "failure in initialization is reported");
+ $node->safe_psql("postgres",
+ "SELECT injection_points_detach('test-shmem-init');");
+
+ # The error leaves the shared memory area in a broken state.
+ # Attempting to initialize or attach it again will fail, until the
+ # server is restarted.
+ (undef, undef, $stderr) =
+ $node->psql("postgres", "SELECT get_test_shmem_attach_count();");
+ like(
+ $stderr,
+ qr/cannot attach to shared memory/,
+ "post-init extension creation fails");
+
+ $node->stop;
+}
+
###
# Test "out of shared memory" in an after-startup request
###
diff --git a/src/test/modules/test_shmem/test_shmem.c b/src/test/modules/test_shmem/test_shmem.c
index 231ad9a0027..6cf47dc8968 100644
--- a/src/test/modules/test_shmem/test_shmem.c
+++ b/src/test/modules/test_shmem/test_shmem.c
@@ -68,6 +68,9 @@ static void
test_shmem_init(void *arg)
{
elog(LOG, "init callback called");
+
+ INJECTION_POINT("test-shmem-init", NULL);
+
if (TestShmem->initialized)
elog(ERROR, "shmem area already initialized");
TestShmem->initialized = true;
--
2.47.3
^ permalink raw reply [nested|flat] 21+ messages in thread
* Re: Error handling in after-startup shmem requests
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-09 16:30 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-10 09:40 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-10 12:40 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-11 15:46 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-11 18:05 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 07:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-12 09:07 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 09:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-18 10:37 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-25 16:33 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-25 16:47 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-26 05:59 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-26 12:23 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
@ 2026-08-26 12:44 ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-28 14:58 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
0 siblings, 1 reply; 21+ messages in thread
From: Ayush Tiwari @ 2026-08-26 12:44 UTC (permalink / raw)
To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers
Hi,
On Wed, 26 Aug 2026 at 17:53, Heikki Linnakangas <hlinnaka@iki.fi> wrote:
> On 26/08/2026 08:59, Ayush Tiwari wrote:
> > This approach looks good to me overall. I built the v2 series with
> > assertions and injection points enabled, and all five tests passed.
> >
> > I had one question about the lifetime of the options copy. It is still
> > allocated in TopMemoryContext, while the after-startup path no longer
> calls
> > pfree(request->options). The PG_FINALLY block clears
> > pending_shmem_requests, but could that leave the options allocated until
> > backend exit? The impact seems small, but perhaps the options should be
> > freed before clearing the list, or allocated in the same context as the
> > requests?
>
> You're right. I changed it to use TopMemoryContext like you had it
> originally. That seems more clear, after all.
>
> > One minor test nit:
> >
> > - The comment says "A failure in the requesting shared memory", but the
> > injection point triggers in test_shmem_init(), so would "initializing
> > shared memory" be more accurate?
>
> Yeah. I did some other cleanups in the test too, and merged the tests
> into the commits with the code fixes. Here's a new version, if you want
> to have one final look.
>
I took a quick look and triggered the tests parallely.
Patch looks good to me.
Regards,
Ayush
^ permalink raw reply [nested|flat] 21+ messages in thread
* Re: Error handling in after-startup shmem requests
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-09 16:30 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-10 09:40 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-10 12:40 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-11 15:46 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-11 18:05 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 07:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-12 09:07 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 09:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-18 10:37 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-25 16:33 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-25 16:47 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-26 05:59 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-26 12:23 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-26 12:44 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
@ 2026-08-28 14:58 ` Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-28 21:05 ` Re: Error handling in after-startup shmem requests Andres Freund <andres@anarazel.de>
0 siblings, 1 reply; 21+ messages in thread
From: Heikki Linnakangas @ 2026-08-28 14:58 UTC (permalink / raw)
To: Ayush Tiwari <ayushtiwari.slg01@gmail.com>; +Cc: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers
On 26/08/2026 15:44, Ayush Tiwari wrote:
> I took a quick look and triggered the tests parallely.
>
> Patch looks good to me.
Committed, thanks!
- Heikki
^ permalink raw reply [nested|flat] 21+ messages in thread
* Re: Error handling in after-startup shmem requests
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-09 16:30 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-10 09:40 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-10 12:40 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-11 15:46 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-11 18:05 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 07:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-12 09:07 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 09:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-18 10:37 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-25 16:33 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-25 16:47 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-26 05:59 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-26 12:23 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-26 12:44 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-28 14:58 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
@ 2026-08-28 21:05 ` Andres Freund <andres@anarazel.de>
2026-08-29 08:45 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
0 siblings, 1 reply; 21+ messages in thread
From: Andres Freund @ 2026-08-28 21:05 UTC (permalink / raw)
To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Ayush Tiwari <ayushtiwari.slg01@gmail.com>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers
Hi,
On 2026-08-28 17:58:55 +0300, Heikki Linnakangas wrote:
> On 26/08/2026 15:44, Ayush Tiwari wrote:
> > I took a quick look and triggered the tests parallely.
> >
> > Patch looks good to me.
>
> Committed, thanks!
This test reliably fails for me locally. I think it may be due to my system
having huge pages configured and the default of the huge_pages GUC being
try. When using huge pages, we round up the allocation, which increases the
reserve. Which then triggers the test to fail to fail, as the reserve is
bigger than 128kB.
- Andres
^ permalink raw reply [nested|flat] 21+ messages in thread
* Re: Error handling in after-startup shmem requests
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-09 16:30 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-10 09:40 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-10 12:40 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-11 15:46 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-11 18:05 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 07:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-12 09:07 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 09:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-18 10:37 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-25 16:33 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-25 16:47 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-26 05:59 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-26 12:23 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-26 12:44 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-28 14:58 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-28 21:05 ` Re: Error handling in after-startup shmem requests Andres Freund <andres@anarazel.de>
@ 2026-08-29 08:45 ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-09-01 04:00 ` Re: Error handling in after-startup shmem requests Alexander Lakhin <exclusion@gmail.com>
2026-09-01 18:50 ` Re: Error handling in after-startup shmem requests Andres Freund <andres@anarazel.de>
0 siblings, 2 replies; 21+ messages in thread
From: Ayush Tiwari @ 2026-08-29 08:45 UTC (permalink / raw)
To: Andres Freund <andres@anarazel.de>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers
Hi,
On Sat, 29 Aug 2026 at 02:35, Andres Freund <andres@anarazel.de> wrote:
> Hi,
>
> On 2026-08-28 17:58:55 +0300, Heikki Linnakangas wrote:
> > On 26/08/2026 15:44, Ayush Tiwari wrote:
> > > I took a quick look and triggered the tests parallely.
> > >
> > > Patch looks good to me.
> >
> > Committed, thanks!
>
> This test reliably fails for me locally. I think it may be due to my system
> having huge pages configured and the default of the huge_pages GUC being
> try. When using huge pages, we round up the allocation, which increases the
> reserve. Which then triggers the test to fail to fail, as the reserve is
> bigger than 128kB.
>
Thanks for the report.
The attached patch disables huge pages immediately before the allocation-
failure phase. This keeps the test focused on recovery from an allocation
failure rather than on the platform's shared memory segment rounding.
Regards,
Ayush
Attachments:
v1-0001-Make-after-startup-shmem-failure-test-reliable.patch (application/octet-stream, 1.5K) download
From 75e7ecc252fc48ea57b08a6eb8d349d7e522d339 Mon Sep 17 00:00:00 2001
From: Ayush Tiwari <ayushtiwari.slg01@gmail.com>
Date: Sat, 29 Aug 2026 08:22:39 +0000
Subject: [PATCH v1] Make after-startup shmem failure test reliable
The test expects a 128 kB request to exceed the shared memory left
available after startup. Huge pages can round up the main shared memory
segment enough for that request to succeed, defeating the test.
Disable huge pages for the allocation-failure phase so that it exercises
the intended error path independently of shared memory segment rounding.
Reported-by: Andres Freund <andres@anarazel.de>
Discussion: https://postgr.es/m/rpkhzrrmo7qiz7rr3qlufksb2oci33wcg3ao75le7dqindgoif@6yozkjwb6bdf
Backpatch-through: 19
---
src/test/modules/test_shmem/t/001_late_shmem_alloc.pl | 3 +++
1 file changed, 3 insertions(+)
diff --git a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
index a7126ebce3f..9432b42181b 100644
--- a/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
+++ b/src/test/modules/test_shmem/t/001_late_shmem_alloc.pl
@@ -125,6 +125,9 @@ SKIP:
###
# Test "out of shared memory" in an after-startup request
###
+# Huge pages round up the main shared memory segment, which can leave more
+# unused space than the request below. Disable them to make the test reliable.
+$node->append_conf('postgresql.conf', 'huge_pages = off');
$node->start;
my $session = $node->background_psql('postgres', on_error_stop => 0);
--
2.43.0
^ permalink raw reply [nested|flat] 21+ messages in thread
* Re: Error handling in after-startup shmem requests
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-09 16:30 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-10 09:40 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-10 12:40 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-11 15:46 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-11 18:05 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 07:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-12 09:07 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 09:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-18 10:37 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-25 16:33 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-25 16:47 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-26 05:59 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-26 12:23 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-26 12:44 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-28 14:58 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-28 21:05 ` Re: Error handling in after-startup shmem requests Andres Freund <andres@anarazel.de>
2026-08-29 08:45 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
@ 2026-09-01 04:00 ` Alexander Lakhin <exclusion@gmail.com>
1 sibling, 0 replies; 21+ messages in thread
From: Alexander Lakhin @ 2026-09-01 04:00 UTC (permalink / raw)
To: Ayush Tiwari <ayushtiwari.slg01@gmail.com>; Andres Freund <andres@anarazel.de>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers
Hello Ayush and Andres,
29.08.2026 11:45, Ayush Tiwari wrote:
> On Sat, 29 Aug 2026 at 02:35, Andres Freund <andres@anarazel.de> wrote:
>
>
> This test reliably fails for me locally. I think it may be due to my system
> having huge pages configured and the default of the huge_pages GUC being
> try. When using huge pages, we round up the allocation, which increases the
> reserve. Which then triggers the test to fail to fail, as the reserve is
> bigger than 128kB.
>
>
> Thanks for the report.
Probably skimmer and bumblebee suffer from the same:
https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=skimmer&dt=2026-08-31%2021%3A50%3A26
https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=bumblebee&dt=2026-09-01%2000%3A24%3A59
Best regards,
Alexander
^ permalink raw reply [nested|flat] 21+ messages in thread
* Re: Error handling in after-startup shmem requests
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-09 16:30 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-10 09:40 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-10 12:40 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-11 15:46 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-11 18:05 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 07:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-12 09:07 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 09:41 ` Re: Error handling in after-startup shmem requests Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-18 10:37 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-25 16:33 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-25 16:47 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-26 05:59 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-26 12:23 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-26 12:44 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-28 14:58 ` Re: Error handling in after-startup shmem requests Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-28 21:05 ` Re: Error handling in after-startup shmem requests Andres Freund <andres@anarazel.de>
2026-08-29 08:45 ` Re: Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
@ 2026-09-01 18:50 ` Andres Freund <andres@anarazel.de>
1 sibling, 0 replies; 21+ messages in thread
From: Andres Freund @ 2026-09-01 18:50 UTC (permalink / raw)
To: Ayush Tiwari <ayushtiwari.slg01@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>; pgsql-hackers
Hi,
On 2026-08-29 14:15:42 +0530, Ayush Tiwari wrote:
> On Sat, 29 Aug 2026 at 02:35, Andres Freund <andres@anarazel.de> wrote:
> > On 2026-08-28 17:58:55 +0300, Heikki Linnakangas wrote:
> > > On 26/08/2026 15:44, Ayush Tiwari wrote:
> > > > I took a quick look and triggered the tests parallely.
> > > >
> > > > Patch looks good to me.
> > >
> > > Committed, thanks!
> >
> > This test reliably fails for me locally. I think it may be due to my system
> > having huge pages configured and the default of the huge_pages GUC being
> > try. When using huge pages, we round up the allocation, which increases the
> > reserve. Which then triggers the test to fail to fail, as the reserve is
> > bigger than 128kB.
> >
>
> Thanks for the report.
>
> The attached patch disables huge pages immediately before the allocation-
> failure phase. This keeps the test focused on recovery from an allocation
> failure rather than on the platform's shared memory segment rounding.
Thanks. Pushed.
Greetings,
Andres Freund
^ permalink raw reply [nested|flat] 21+ messages in thread
end of thread, other threads:[~2026-09-01 18:50 UTC | newest]
Thread overview: 21+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-08-06 12:40 Error handling in after-startup shmem requests Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-07 13:25 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-09 16:30 ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-10 09:40 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-10 12:40 ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-11 15:46 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-11 18:05 ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 07:41 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-12 09:07 ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-12 09:41 ` Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
2026-08-18 10:37 ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-25 16:33 ` Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-25 16:47 ` Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-26 05:59 ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-26 12:23 ` Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-26 12:44 ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-08-28 14:58 ` Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-28 21:05 ` Andres Freund <andres@anarazel.de>
2026-08-29 08:45 ` Ayush Tiwari <ayushtiwari.slg01@gmail.com>
2026-09-01 04:00 ` Alexander Lakhin <exclusion@gmail.com>
2026-09-01 18:50 ` Andres Freund <andres@anarazel.de>
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox