[PATCH] Two remaining shmem attachment issues in single-user mode
Hi,
I found two more shmem attachment issues in single-user mode after
the recent fixes. Patches attached.
With ShmemInitStruct(), a second call for the same name and size errors
out with "already initialized". We only look for the old allocation if
IsUnderPostmaster is true, so a standalone backend goes straight down
the allocation path again.
0001 drops that condition. It fixes postmaster-startup reattachment
too, which I did hesitate over at first. But AFAICS that was supported
before the refactoring, and it's what the legacy API still promises.
So I'd lean towards restoring that behaviour in both places. Is there
a reason not to? (The size and initialization checks are still there.)
The other one is a bit odd: ask for an existing area with
SHMEM_ATTACH_UNKNOWN_SIZE after startup in single-user mode, and we
tell you it "cannot be used during startup".
IIUC, the distinction we need here is whether we're still working out
the initial shmem requirements, not whether we have a postmaster.
0002 adds SRS_REQUESTING_AFTER_STARTUP for that. I couldn't see a clean
way to reuse SRS_REQUESTING without mixing those cases up.
I'm a bit on the fence about adding another state just for this.
With the PG19 release getting close, I thought I'd send this out for
feedback before spending more time iterating on it. Does the extra
state seem like the right approach?
Regards,
Ayush
Attachments:
t253859_1v1-0001-Fix-legacy-shmem-reattachment-in-single-user-mode.patchapplication/octet-stream; name=v1-0001-Fix-legacy-shmem-reattachment-in-single-user-mode.patchDownload+35-16
v1-0002-Allow-unknown-size-shmem-attachments-in-single-user-mode.patchapplication/octet-stream; name=v1-0002-Allow-unknown-size-shmem-attachments-in-single-user-mode.patchDownload+67-9
On Sep 20, 2026, at 03:12, Ayush Tiwari <ayushtiwari.slg01@gmail.com> wrote:
Hi,
I found two more shmem attachment issues in single-user mode after
the recent fixes. Patches attached.With ShmemInitStruct(), a second call for the same name and size errors
out with "already initialized". We only look for the old allocation if
IsUnderPostmaster is true, so a standalone backend goes straight down
the allocation path again.0001 drops that condition. It fixes postmaster-startup reattachment
too, which I did hesitate over at first. But AFAICS that was supported
before the refactoring, and it's what the legacy API still promises.
So I'd lean towards restoring that behaviour in both places. Is there
a reason not to? (The size and initialization checks are still there.)
I think it’s reasonable to remove the IsUnderPostmaster check for two reasons:
* IsUnderPostmaster is always false in single-user mode, so the current check prevents reattachment there.
* The current logic feels unnecessarily asymmetric. The natural pattern for ShmemInitStruct() is to first look for an existing allocation and create one only if none exists. With the IsUnderPostmaster check, however, the postmaster always goes directly to creation, while a child process first looks for an existing allocation and creates one if it is not found. That makes the code a little confusing to reason about. It suggests that the create-or-attach behavior depends on whether the process is under the postmaster, even though I don't see why that distinction is needed here. In practice, the postmaster initializes shared memory before child processes are started anyway.
So, removing the check makes the behavior simpler and more consistent, always look for an existing allocation first, and create one only if it doesn't exist.
The other one is a bit odd: ask for an existing area with
SHMEM_ATTACH_UNKNOWN_SIZE after startup in single-user mode, and we
tell you it "cannot be used during startup".IIUC, the distinction we need here is whether we're still working out
the initial shmem requirements, not whether we have a postmaster.
0002 adds SRS_REQUESTING_AFTER_STARTUP for that. I couldn't see a clean
way to reuse SRS_REQUESTING without mixing those cases up.I'm a bit on the fence about adding another state just for this.
With the PG19 release getting close, I thought I'd send this out for
feedback before spending more time iterating on it. Does the extra
state seem like the right approach?
I’m not very keen on adding a new state just to allow SHMEM_ATTACH_UNKNOWN_SIZE in single-user mode. While reading 0002, I had a few concerns:
1
```
- if (IsUnderPostmaster)
+ if (IsUnderPostmaster || shmem_request_state == SRS_REQUESTING_AFTER_STARTUP)
{
if (options->size <= 0 && options->size != SHMEM_ATTACH_UNKNOWN_SIZE)
elog(ERROR, "invalid size %zd for shared memory request for \"%s\"",
```
Now that we have SRS_REQUESTING_AFTER_STARTUP, my first thought was whether the IsUnderPostmaster check could be removed entirely.
After digging into the code, I don't think so. IsUnderPostmaster is still needed for cases such as EXEC_BACKEND children, so the new state seems to be added specifically to cover the single-user after-startup case.
That makes me wonder whether introducing another state is the simplest way to express this.
2
```
- * DONE -> REQUESTING -> AFTER_STARTUP_ATTACH_OR_INIT -> DONE
+ * DONE -> REQUESTING_AFTER_STARTUP -> AFTER_STARTUP_ATTACH_OR_INIT -> DONE
```
The main reason for introducing REQUESTING_AFTER_STARTUP seems to be to allow SHMEM_ATTACH_UNKNOWN_SIZE. But the next state is still AFTER_STARTUP_ATTACH_OR_INIT, so the new state is not really describing an attach-only phase.
That makes the state machine a little harder for me to reason about, because REQUESTING_AFTER_STARTUP is mainly distinguishing the context in which the request callback runs rather than representing a fundamentally different shared-memory lifecycle state.
If the only additional case we need to distinguish here is a late request in single-user mode, would it be simpler to check MyBackendType == B_STANDALONE_BACKEND instead of adding a new request state?
Regards,
Ayush
<v1-0001-Fix-legacy-shmem-reattachment-in-single-user-mode.patch><v1-0002-Allow-unknown-size-shmem-attachments-in-single-user-mode.patch>
Also, for v1-0001, I personally don't feel that the new test is really necessary. This doesn't seem like particularly fragile logic that's likely to regress accidentally, and I've noticed that Tom generally seems reluctant to increase test runtime, even by a very small amount, unless the test provides clear value.
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
Hi,
On Sun, 20 Sept 2026 at 13:58, Chao Li <li.evan.chao@gmail.com> wrote:
0001 drops that condition. It fixes postmaster-startup reattachment
too, which I did hesitate over at first. But AFAICS that was supported
before the refactoring, and it's what the legacy API still promises.
So I'd lean towards restoring that behaviour in both places. Is there
a reason not to? (The size and initialization checks are still there.)I think it’s reasonable to remove the IsUnderPostmaster check for two reasons:
* IsUnderPostmaster is always false in single-user mode, so the current check prevents reattachment there.
* The current logic feels unnecessarily asymmetric. The natural pattern for ShmemInitStruct() is to first look for an existing allocation and create one only if none exists. With the IsUnderPostmaster check, however, the postmaster always goes directly to creation, while a child process first looks for an existing allocation and creates one if it is not found. That makes the code a little confusing to reason about. It suggests that the create-or-attach behavior depends on whether the process is under the postmaster, even though I don't see why that distinction is needed here. In practice, the postmaster initializes shared memory before child processes are started anyway.So, removing the check makes the behavior simpler and more consistent, always look for an existing allocation first, and create one only if it doesn't exist.
Thanks for taking a look.
IsUnderPostmaster is still needed for cases such as EXEC_BACKEND
children, so the new state seems to be added specifically to cover
the single-user after-startup case.
Yes, I think we'd still need that allowance for EXEC_BACKEND. The new
state would be used for late requests in normal backends too, though
it's the standalone case where it changes what we accept.
But the next state is still AFTER_STARTUP_ATTACH_OR_INIT, so the new
state is not really describing an attach-only phase.
I was thinking of it as distinguishing when the request happens,
rather than making it attach-only. A late request with a known size
could still allocate a new area; an unknown-size request would need
to find an existing one. Perhaps the comment could make that clearer?
I'm not wedded to another enum value here. I just couldn't see how to
keep the startup and late-request checks separate with the existing
state.
If the only additional case we need to distinguish here is a late
request in single-user mode, would it be simpler to check
MyBackendType == B_STANDALONE_BACKEND instead of adding a new request
state?
AFAICS, InitStandaloneProcess() sets B_STANDALONE_BACKEND before we
get to ShmemCallRequestCallbacks(). Wouldn't that also let an
unknown-size request through during standalone startup, when we're
still working out how much memory to allocate?
That's the distinction I was trying to preserve in 0002. I may be
missing another condition we could use alongside the backend type,
though.
Also, for v1-0001, I personally don't feel that the new test is really
necessary.
Fair point about the extra startup. I'd lean towards keeping a small
reproducer, since the existing tests hadn't caught the double-call
case, but perhaps a separate invocation is unnecessary.
Would folding the legacy check into the existing single-user run be
a reasonable compromise? With exit_on_error already enabled, adding
the query there should let us cover it without another backend startup.
[I haven't yet tried it though]
Regards,
Ayush
Hi,
On Sun, 20 Sept 2026 at 00:42, Ayush Tiwari <ayushtiwari.slg01@gmail.com>
wrote:
Hi,
I found two more shmem attachment issues in single-user mode after
the recent fixes. Patches attached.With ShmemInitStruct(), a second call for the same name and size errors
out with "already initialized". We only look for the old allocation if
IsUnderPostmaster is true, so a standalone backend goes straight down
the allocation path again.0001 drops that condition. It fixes postmaster-startup reattachment
too, which I did hesitate over at first. But AFAICS that was supported
before the refactoring, and it's what the legacy API still promises.
So I'd lean towards restoring that behaviour in both places. Is there
a reason not to? (The size and initialization checks are still there.)The other one is a bit odd: ask for an existing area with
SHMEM_ATTACH_UNKNOWN_SIZE after startup in single-user mode, and we
tell you it "cannot be used during startup".IIUC, the distinction we need here is whether we're still working out
the initial shmem requirements, not whether we have a postmaster.
0002 adds SRS_REQUESTING_AFTER_STARTUP for that. I couldn't see a clean
way to reuse SRS_REQUESTING without mixing those cases up.I'm a bit on the fence about adding another state just for this.
With the PG19 release getting close, I thought I'd send this out for
feedback before spending more time iterating on it. Does the extra
state seem like the right approach?
I've added this to commitfest for tracking purpose [1]https://commitfest.postgresql.org/patch/7320/
I think the first one should be an open item too for PG 19?
[haven't added it yet in that list]
Regards,
Ayush
On Sun, Sep 20, 2026 at 1:28 AM Chao Li <li.evan.chao@gmail.com> wrote:
Also, for v1-0001, I personally don't feel that the new test is really necessary. This doesn't seem like particularly fragile logic that's likely to regress accidentally,
(But the claim being made is that it _did_ regress accidentally, right?)
and I've noticed that Tom generally seems reluctant to increase test runtime, even by a very small amount, unless the test provides clear value.
I haven't reviewed the whole patch, but as someone who'd really prefer
that every bug fix be accompanied by a regression test if possible, I
don't think we should be discouraging people from writing them. Don't
waste resources, sure, but don't avoid writing tests. A committer can
always strip an overly-expensive test out before committing.
--Jacob
On Sep 23, 2026, at 02:52, Jacob Champion <jacob.champion@enterprisedb.com> wrote:
On Sun, Sep 20, 2026 at 1:28 AM Chao Li <li.evan.chao@gmail.com> wrote:
Also, for v1-0001, I personally don't feel that the new test is really necessary. This doesn't seem like particularly fragile logic that's likely to regress accidentally,
(But the claim being made is that it _did_ regress accidentally, right?)
and I've noticed that Tom generally seems reluctant to increase test runtime, even by a very small amount, unless the test provides clear value.
I haven't reviewed the whole patch, but as someone who'd really prefer
that every bug fix be accompanied by a regression test if possible, I
don't think we should be discouraging people from writing them. Don't
waste resources, sure, but don't avoid writing tests. A committer can
always strip an overly-expensive test out before committing.
That’s a good point. Noted.
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
On 19/09/2026 22:12, Ayush Tiwari wrote:
Hi,
I found two more shmem attachment issues in single-user mode after
the recent fixes. Patches attached.With ShmemInitStruct(), a second call for the same name and size errors
out with "already initialized". We only look for the old allocation if
IsUnderPostmaster is true, so a standalone backend goes straight down
the allocation path again.0001 drops that condition. It fixes postmaster-startup reattachment
too, which I did hesitate over at first. But AFAICS that was supported
before the refactoring, and it's what the legacy API still promises.
So I'd lean towards restoring that behaviour in both places. Is there
a reason not to? (The size and initialization checks are still there.)
Hmm, so the scenario is:
1. Start postgres in single-user mode
2. Load an extension that calls ShmemInitStruct() to alloc a shmem area
3. The extension calls ShmemInitStruct() again, to get a pointer to the
already-initialized area.
I didn't think of that scenario. There's no reason to not support that,
although it's pretty weird for an extension to do that. One use case
might be to have a shared struct between two cooperating extensions, so
that they both call ShmemInitStruct() to get a pointer to the same area.
I'm not aware of any extensions actually doing that, though.
I'll commit that fix, thanks!
The other one is a bit odd: ask for an existing area with
SHMEM_ATTACH_UNKNOWN_SIZE after startup in single-user mode, and we
tell you it "cannot be used during startup".IIUC, the distinction we need here is whether we're still working out
the initial shmem requirements, not whether we have a postmaster.
0002 adds SRS_REQUESTING_AFTER_STARTUP for that. I couldn't see a clean
way to reuse SRS_REQUESTING without mixing those cases up.I'm a bit on the fence about adding another state just for this.
With the PG19 release getting close, I thought I'd send this out for
feedback before spending more time iterating on it. Does the extra
state seem like the right approach?
Extra state sounds reasonable. Thanks, I'll take a closer look, and I'll
double-check all the other places in shmem.c where we use
IsUnderPostmaster, too.
The IsUnderPostmaster variable is deceptive. It's easy to forget about
single-user code, and incorrectly assume that IsUnderPostmaster == true
means you're a backend and IsUnderPostmaster == false means you're
postmaster. I think that's what happened to me here and with the
previous single-user mode bugs. I remember I've struggled to keep that
in mind in the past too. We should perhaps replace IsUnderPostmaster
with a three-valued enum or something (postmaster, backend, single-user
backend).
We got that wrong in pg_get_shmem_pagesize(), too, also in previous
versions:
backend> select * from pg_get_shmem_allocations_numa();
1: name (typeid = 25, len = -1, typmod = -1, byval = f)
2: numa_node (typeid = 23, len = 4, typmod = -1, byval = t)
3: size (typeid = 20, len = 8, typmod = -1, byval = t)
----
TRAP: failed Assert("IsUnderPostmaster"), File:
"../src/backend/storage/ipc/shmem.c", Line: 731, PID: 121579
- Heikki
Hi,
On Wed, 23 Sept 2026 at 17:53, Heikki Linnakangas <hlinnaka@iki.fi> wrote:
On 19/09/2026 22:12, Ayush Tiwari wrote:
Hi,
I found two more shmem attachment issues in single-user mode after
the recent fixes. Patches attached.With ShmemInitStruct(), a second call for the same name and size errors
out with "already initialized". We only look for the old allocation if
IsUnderPostmaster is true, so a standalone backend goes straight down
the allocation path again.0001 drops that condition. It fixes postmaster-startup reattachment
too, which I did hesitate over at first. But AFAICS that was supported
before the refactoring, and it's what the legacy API still promises.
So I'd lean towards restoring that behaviour in both places. Is there
a reason not to? (The size and initialization checks are still there.)Hmm, so the scenario is:
1. Start postgres in single-user mode
2. Load an extension that calls ShmemInitStruct() to alloc a shmem area
3. The extension calls ShmemInitStruct() again, to get a pointer to the
already-initialized area.I didn't think of that scenario. There's no reason to not support that,
although it's pretty weird for an extension to do that. One use case
might be to have a shared struct between two cooperating extensions, so
that they both call ShmemInitStruct() to get a pointer to the same area.
I'm not aware of any extensions actually doing that, though.I'll commit that fix, thanks!
Thanks for looking into it.
The other one is a bit odd: ask for an existing area with
SHMEM_ATTACH_UNKNOWN_SIZE after startup in single-user mode, and we
tell you it "cannot be used during startup".IIUC, the distinction we need here is whether we're still working out
the initial shmem requirements, not whether we have a postmaster.
0002 adds SRS_REQUESTING_AFTER_STARTUP for that. I couldn't see a clean
way to reuse SRS_REQUESTING without mixing those cases up.I'm a bit on the fence about adding another state just for this.
With the PG19 release getting close, I thought I'd send this out for
feedback before spending more time iterating on it. Does the extra
state seem like the right approach?Extra state sounds reasonable. Thanks, I'll take a closer look, and I'll
double-check all the other places in shmem.c where we use
IsUnderPostmaster, too.The IsUnderPostmaster variable is deceptive. It's easy to forget about
single-user code, and incorrectly assume that IsUnderPostmaster == true
means you're a backend and IsUnderPostmaster == false means you're
postmaster. I think that's what happened to me here and with the
previous single-user mode bugs. I remember I've struggled to keep that
in mind in the past too. We should perhaps replace IsUnderPostmaster
with a three-valued enum or something (postmaster, backend, single-user
backend).
I agree. It's v v deceptive.
[Though I did not know much about single user modes till tripping]
We got that wrong in pg_get_shmem_pagesize(), too, also in previous
versions:backend> select * from pg_get_shmem_allocations_numa();
1: name (typeid = 25, len = -1, typmod = -1, byval = f)
2: numa_node (typeid = 23, len = 4, typmod = -1, byval = t)
3: size (typeid = 20, len = 8, typmod = -1, byval = t)
----
TRAP: failed Assert("IsUnderPostmaster"), File:
"../src/backend/storage/ipc/shmem.c", Line: 731, PID: 121579
Hmm, I had posted a patch for a nearby place [1]/messages/by-id/CAJTYsWV-=w5_oFgCnfAixWGc=gMa2pkDinLyGLsb4sKcDaf2FA@mail.gmail.com
Regards,
Ayush
[1]: /messages/by-id/CAJTYsWV-=w5_oFgCnfAixWGc=gMa2pkDinLyGLsb4sKcDaf2FA@mail.gmail.com
On Wed, Sep 23, 2026 at 6:50 PM Ayush Tiwari
<ayushtiwari.slg01@gmail.com> wrote:
Hi,
On Wed, 23 Sept 2026 at 17:53, Heikki Linnakangas <hlinnaka@iki.fi> wrote:
On 19/09/2026 22:12, Ayush Tiwari wrote:
Hi,
I found two more shmem attachment issues in single-user mode after
the recent fixes. Patches attached.With ShmemInitStruct(), a second call for the same name and size errors
out with "already initialized". We only look for the old allocation if
IsUnderPostmaster is true, so a standalone backend goes straight down
the allocation path again.0001 drops that condition. It fixes postmaster-startup reattachment
too, which I did hesitate over at first. But AFAICS that was supported
before the refactoring, and it's what the legacy API still promises.
So I'd lean towards restoring that behaviour in both places. Is there
a reason not to? (The size and initialization checks are still there.)Hmm, so the scenario is:
1. Start postgres in single-user mode
2. Load an extension that calls ShmemInitStruct() to alloc a shmem area
3. The extension calls ShmemInitStruct() again, to get a pointer to the
already-initialized area.I didn't think of that scenario. There's no reason to not support that,
although it's pretty weird for an extension to do that. One use case
might be to have a shared struct between two cooperating extensions, so
that they both call ShmemInitStruct() to get a pointer to the same area.
I'm not aware of any extensions actually doing that, though.I'll commit that fix, thanks!
The code changes look good to me. There are opportunities to make the
test less confusing and cover more scenarios.
- *foundPtr = false;
- if (IsUnderPostmaster)
- *foundPtr = AttachShmemIndexEntry(&request, true);
+ *foundPtr = AttachShmemIndexEntry(&request, true);
Before the refactor, ShmemInitStruct() did not distinguish between
IsUnderPostmaster being true or false for ordinary allocations. It did
distinguish between those modes when creating ShmemIndex. However, in
the current code, ShmemIndex creation does not go through regular
requests. So I think we are safe removing the condition.
When attaching to existing shared memory through the callback-based
API after startup, the supplied attach callback is invoked. In
contrast, ShmemInitStruct() does not invoke an attach callback. People
using both the legacy and new APIs may find this difference
surprising. Should we document it explicitly in the ShmemInitStruct()
documentation in a separate patch?
I think there's also some value in porting parts of the
001_late_shmem_alloc test to the PostgreSQL 18 stable branch to test
and document the legacy behaviour. The code has changed so much that
it's hard to know what the legacy behaviour was. Even porting the
whole test and adjusting it for the APIs there might be worth it. That
way we can easily compare the new behaviour with the legacy behaviour
simply by looking at the differences in the test. This could be a
separate patch.
+
+ $query = "SELECT test_shmem_legacy();\n";
+ $result = run_log(\@command, '<' => \$query);
+ ok($result, "legacy shared memory reattachment works in single-user mode");
I think we should add this test to the shared_preload_libraries
section as well to check that legacy shared memory reattachment works
correctly when the module is loaded through that GUC. Over time, we
may fail to maintain compatibility with the legacy APIs and won't
notice the drift without tests covering those cases.
+
+PG_FUNCTION_INFO_V1(test_shmem_legacy);
+Datum
+test_shmem_legacy(PG_FUNCTION_ARGS)
+{
I would rename this to test_shmem_legacy_api() for the sake of clarity
and also add a prologue to the function explaining what it tests.
+ void *first;
+ void *second;
+ bool found;
+
+ first = ShmemInitStruct("test_shmem legacy", 64, &found);
+ second = ShmemInitStruct("test_shmem legacy", 64, &found);
Could we also check the first call's found result when the test
guarantees a fresh allocation? It is currently overwritten by the
second call, so an incorrect found result from the first call would go
unnoticed.
In addition to these two calls, I would test
ShmemInitStruct("test_shmem area", test_shmem_area_size, &found),
checking both found and that the returned pointer equals TestShmem.
That area will already have been created through the new API when the
library is loaded. This would test interoperability between the new
and old APIs while retaining coverage of legacy allocation followed by
legacy reattachment.
Thanks for looking into it.
The other one is a bit odd: ask for an existing area with
SHMEM_ATTACH_UNKNOWN_SIZE after startup in single-user mode, and we
tell you it "cannot be used during startup".IIUC, the distinction we need here is whether we're still working out
the initial shmem requirements, not whether we have a postmaster.
0002 adds SRS_REQUESTING_AFTER_STARTUP for that. I couldn't see a clean
way to reuse SRS_REQUESTING without mixing those cases up.I'm a bit on the fence about adding another state just for this.
With the PG19 release getting close, I thought I'd send this out for
feedback before spending more time iterating on it. Does the extra
state seem like the right approach?Extra state sounds reasonable. Thanks, I'll take a closer look, and I'll
double-check all the other places in shmem.c where we use
IsUnderPostmaster, too.The IsUnderPostmaster variable is deceptive. It's easy to forget about
single-user code, and incorrectly assume that IsUnderPostmaster == true
means you're a backend and IsUnderPostmaster == false means you're
postmaster. I think that's what happened to me here and with the
previous single-user mode bugs. I remember I've struggled to keep that
in mind in the past too. We should perhaps replace IsUnderPostmaster
with a three-valued enum or something (postmaster, backend, single-user
backend).
If we do this, do we still need extra state?
I agree. It's v v deceptive.
[Though I did not know much about single user modes till tripping]
Is being in postmaster = IsPostmasterEnvironment && !IsUnderPostmaster
single user = !IsPostmasterEnvironment
normal backend = IsPostmasterEnvironment && IsUnderPostmaster
If we are going to a three value enum, is it worth folding
IsPostmasterEnvironment and IsUnderPostmaster into that enum? Will
that be too much to change in PG 19 at this stage? Here's review of
the test changes. I will review the code once we settle the questions
above.
+is($node->safe_psql("postgres", "SELECT test_shmem_unknown_size();"), 't',
+ "unknown-size attachment works in a normal backend");
This adds a test assertion to the cluster setup block. Could we move
it into a separate test section with a short comment explaining its
purpose.
+SKIP:
+{
+ skip 'single-user test is not supported by this platform', 2
+ if $windows_os;
+ my @command = (
+ 'postgres', '--single', '-F',
+ '-c' => 'exit_on_error=true',
+ '-D' => $node->data_dir);
+ my $query = "SELECT test_shmem_unknown_size();\n";
+ my $result = run_log([@command, 'postgres'], '<' => \$query);
+ ok($result, "unknown-size attachment works in single-user mode");
This tests attachment through the callback-based API, whereas the
previous patch tests attachment through the legacy API. It would be
good to make the API distinction explicit in the test description.
Could we also test a late unknown-size request for a nonexistent area
in single-user mode, followed by a valid request in the same process?
With exit_on_error=false, we could check both the expected error and
the subsequent successful result. This would exercise the missing-area
guard and restoration of the request state after an error. The
existing missing-area test covers a normal backend only.
+
+ my $stderr;
+ $result = run_log(
+ [@command,
+ '-c' => 'shared_preload_libraries=test_shmem',
+ '-c' => 'test_shmem.area_size=-1', 'postgres'],
+ '<' => \$query, '2>' => \$stderr);
+ ok(!$result && $stderr =~ /SHMEM_ATTACH_UNKNOWN_SIZE cannot be used
during startup/,
+ "unknown-size requests are rejected during single-user startup");
Time to rename 001_late_shmem_alloc.pl to reflect its broader scope?
:) It already includes tests for allocation during startup, and this
patch adds a startup rejection test.
This test already loads the module through shared_preload_libraries in
single-user mode. It would be useful to add an equivalent test that
postmaster startup rejects SHMEM_ATTACH_UNKNOWN_SIZE. Separately, the
existing shared_preload_libraries section could test successful
unknown-size attachment after startup to an area allocated by the
preloaded module with a known size. These could be follow-up tests in
a separate patch.
Could we combine the two SKIP blocks for single-user tests, since they
have the same skip condition? Keeping them separate is also reasonable
if each block has a short comment identifying its purpose.
The new unknown-size test block and helper would be easier to
understand with short comments explaining their purpose. Most existing
sections have descriptive headings; similar comments for the additions
in these patches would save readers some effort.
+PG_FUNCTION_INFO_V1(test_shmem_unknown_size);
+Datum
+test_shmem_unknown_size(PG_FUNCTION_ARGS)
+{
+ TestShmemData *attached = NULL;
+ ShmemCallbacks callbacks = {
+ .flags = SHMEM_CALLBACKS_ALLOW_AFTER_STARTUP,
+ .request_fn = test_shmem_unknown_request,
+ .opaque_arg = &attached,
Wicked :). I didn't envision this usage when working on the patch. Add
a comment though explaining the use of opaque_arg.
Also note that the helper supplies a request callback but no attach
callback for a function which the test uses for testing "attach". It
may be a bit confusing at first glance. It would be good to clarify
that too in the code.
+ };
+
+ RegisterShmemCallbacks(&callbacks);
+ if (attached == NULL || attached != TestShmem || !attached->initialized)
+ elog(ERROR, "could not attach to shared memory with unknown size");
+
+ PG_RETURN_BOOL(true);
+}
+
This function tests attachment to an existing shared memory area using
SHMEM_ATTACH_UNKNOWN_SIZE after startup. I would name it
test_shmem_attach_after_starutp() or some such and add a short
prologue explaining that purpose. Note, we already have
test_shmem_attach() in the module, so that name is ruled out. Moving
test_shmem_unknown_request() closer to this function and naming it
after this function's name would make the relationship clearer. Like
adding _request suffix to the SQL-callable function's name.
II had a bit of a hard time reviewing the test code and making sure
that the changes are fine. That's partly because of lack of comments
but also because the functions for different purposes are mixed in the
test file and c code. I think we should separate the C code into
sections - one for code which uses TestShmemCallbacks, another for
code which uses callbacks and then third for legacy APIs. That way we
can easily see which code affects what and make sure that they don't
step on each other's shoes. Similarly we should separate the single
user tests into their own file. They hardly share any test code and
having them in the middle of non-single user tests is confusing.
Further we can then clearly see dependencies between various blocks in
the test file and again reason easily that they don't affect each
other.
--
Best Wishes,
Ashutosh Bapat
On 24/09/2026 16:07, Ashutosh Bapat wrote:
On Wed, Sep 23, 2026 at 6:50 PM Ayush Tiwari
<ayushtiwari.slg01@gmail.com> wrote:On Wed, 23 Sept 2026 at 17:53, Heikki Linnakangas <hlinnaka@iki.fi> wrote:
On 19/09/2026 22:12, Ayush Tiwari wrote:
I found two more shmem attachment issues in single-user mode after
the recent fixes. Patches attached.With ShmemInitStruct(), a second call for the same name and size errors
out with "already initialized". We only look for the old allocation if
IsUnderPostmaster is true, so a standalone backend goes straight down
the allocation path again.0001 drops that condition. It fixes postmaster-startup reattachment
too, which I did hesitate over at first. But AFAICS that was supported
before the refactoring, and it's what the legacy API still promises.
So I'd lean towards restoring that behaviour in both places. Is there
a reason not to? (The size and initialization checks are still there.)Hmm, so the scenario is:
1. Start postgres in single-user mode
2. Load an extension that calls ShmemInitStruct() to alloc a shmem area
3. The extension calls ShmemInitStruct() again, to get a pointer to the
already-initialized area.I didn't think of that scenario. There's no reason to not support that,
although it's pretty weird for an extension to do that. One use case
might be to have a shared struct between two cooperating extensions, so
that they both call ShmemInitStruct() to get a pointer to the same area.
I'm not aware of any extensions actually doing that, though.I'll commit that fix, thanks!
The code changes look good to me. There are opportunities to make the
test less confusing and cover more scenarios.
Thanks for the review, I committed this part now.
When attaching to existing shared memory through the callback-based
API after startup, the supplied attach callback is invoked. In
contrast, ShmemInitStruct() does not invoke an attach callback. People
using both the legacy and new APIs may find this difference
surprising. Should we document it explicitly in the ShmemInitStruct()
documentation in a separate patch?
Hmm, I don't quite understand. ShmemInitStruct() didn't have an attach
callback at all, so I don't know what there is to document here.
I think there's also some value in porting parts of the
001_late_shmem_alloc test to the PostgreSQL 18 stable branch to test
and document the legacy behaviour. The code has changed so much that
it's hard to know what the legacy behaviour was. Even porting the
whole test and adjusting it for the APIs there might be worth it. That
way we can easily compare the new behaviour with the legacy behaviour
simply by looking at the differences in the test. This could be a
separate patch.
Yeah, perhaps. For now, I decided to leave out this
"test_shmem_legacy()" test.
(But thanks, Ayush, for including it! As Jacob said earlier, it's really
useful to have reproducers for every issue, even though they're not all
committed to the repository.)
+ $query = "SELECT test_shmem_legacy();\n"; + $result = run_log(\@command, '<' => \$query); + ok($result, "legacy shared memory reattachment works in single-user mode");I think we should add this test to the shared_preload_libraries
section as well to check that legacy shared memory reattachment works
correctly when the module is loaded through that GUC. Over time, we
may fail to maintain compatibility with the legacy APIs and won't
notice the drift without tests covering those cases.
Fair. My goal was that ShmemInitStruct() would be just a thin wrapper
around the same functions that the new API uses, so that there's little
chance of breaking just the legacy function. But I'm not sure I managed
to make it quite so thin...
- Heikki
On 24/09/2026 16:07, Ashutosh Bapat wrote:
On Wed, Sep 23, 2026 at 6:50 PM Ayush Tiwari
<ayushtiwari.slg01@gmail.com> wrote:On Wed, 23 Sept 2026 at 17:53, Heikki Linnakangas <hlinnaka@iki.fi> wrote:
On 19/09/2026 22:12, Ayush Tiwari wrote:
The other one is a bit odd: ask for an existing area with
SHMEM_ATTACH_UNKNOWN_SIZE after startup in single-user mode, and we
tell you it "cannot be used during startup".IIUC, the distinction we need here is whether we're still working out
the initial shmem requirements, not whether we have a postmaster.
0002 adds SRS_REQUESTING_AFTER_STARTUP for that. I couldn't see a clean
way to reuse SRS_REQUESTING without mixing those cases up.I'm a bit on the fence about adding another state just for this.
With the PG19 release getting close, I thought I'd send this out for
feedback before spending more time iterating on it. Does the extra
state seem like the right approach?Extra state sounds reasonable. Thanks, I'll take a closer look, and I'll
double-check all the other places in shmem.c where we use
IsUnderPostmaster, too.The IsUnderPostmaster variable is deceptive. It's easy to forget about
single-user code, and incorrectly assume that IsUnderPostmaster == true
means you're a backend and IsUnderPostmaster == false means you're
postmaster. I think that's what happened to me here and with the
previous single-user mode bugs. I remember I've struggled to keep that
in mind in the past too. We should perhaps replace IsUnderPostmaster
with a three-valued enum or something (postmaster, backend, single-user
backend).If we do this, do we still need extra state?
I came up with a simpler idea: we can check "ShmemIndex == NULL" to know
if shared memory has already been initialized and we're in the "after
startup" case, or not. That feels like a pretty direct way of checking
for exactly the property we care about, without needing another state.
I also reworked the tests. I added a very generic test_shmem_register()
function that [registers a callback that] calls ShmemRequestStruct()
with given name and size. And then the perl script can call it with
different sizes, to test the "unknown-size" case, as well as trying to
attach with incorrect size etc. So most of the logic is now in the perl
script.
What do you think?
- Heikki
Attachments:
t253859_11v2-0001-Allow-unknown-size-shmem-attachments-in-single-us.patchtext/x-patch; charset=UTF-8; name=v2-0001-Allow-unknown-size-shmem-attachments-in-single-us.patchDownload+152-76
On Thu, Sep 24, 2026 at 8:53 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:
On 24/09/2026 16:07, Ashutosh Bapat wrote:
On Wed, Sep 23, 2026 at 6:50 PM Ayush Tiwari
<ayushtiwari.slg01@gmail.com> wrote:On Wed, 23 Sept 2026 at 17:53, Heikki Linnakangas <hlinnaka@iki.fi> wrote:
On 19/09/2026 22:12, Ayush Tiwari wrote:
I found two more shmem attachment issues in single-user mode after
the recent fixes. Patches attached.With ShmemInitStruct(), a second call for the same name and size errors
out with "already initialized". We only look for the old allocation if
IsUnderPostmaster is true, so a standalone backend goes straight down
the allocation path again.0001 drops that condition. It fixes postmaster-startup reattachment
too, which I did hesitate over at first. But AFAICS that was supported
before the refactoring, and it's what the legacy API still promises.
So I'd lean towards restoring that behaviour in both places. Is there
a reason not to? (The size and initialization checks are still there.)Hmm, so the scenario is:
1. Start postgres in single-user mode
2. Load an extension that calls ShmemInitStruct() to alloc a shmem area
3. The extension calls ShmemInitStruct() again, to get a pointer to the
already-initialized area.I didn't think of that scenario. There's no reason to not support that,
although it's pretty weird for an extension to do that. One use case
might be to have a shared struct between two cooperating extensions, so
that they both call ShmemInitStruct() to get a pointer to the same area.
I'm not aware of any extensions actually doing that, though.I'll commit that fix, thanks!
The code changes look good to me. There are opportunities to make the
test less confusing and cover more scenarios.Thanks for the review, I committed this part now.
When attaching to existing shared memory through the callback-based
API after startup, the supplied attach callback is invoked. In
contrast, ShmemInitStruct() does not invoke an attach callback. People
using both the legacy and new APIs may find this difference
surprising. Should we document it explicitly in the ShmemInitStruct()
documentation in a separate patch?Hmm, I don't quite understand. ShmemInitStruct() didn't have an attach
callback at all, so I don't know what there is to document here.
Earlier there was no concept of explicit attach, the backends did some
local things but they didn't call it "attach". However, we now have an
explicit "attach" callback that goes with request - and users will get
"hooked" to that concept. It's true that ShmemInitStruct() has no way
to specify attach call and thus can not carry out attach tasks. But a
structure was requested with an attach call earlier. Maybe extension
developers are smart enough to know that that attach won't work here.
But maybe they will find it confusing. Let's wait to see reports from
the field.
I think there's also some value in porting parts of the
001_late_shmem_alloc test to the PostgreSQL 18 stable branch to test
and document the legacy behaviour. The code has changed so much that
it's hard to know what the legacy behaviour was. Even porting the
whole test and adjusting it for the APIs there might be worth it. That
way we can easily compare the new behaviour with the legacy behaviour
simply by looking at the differences in the test. This could be a
separate patch.Yeah, perhaps. For now, I decided to leave out this
"test_shmem_legacy()" test.(But thanks, Ayush, for including it! As Jacob said earlier, it's really
useful to have reproducers for every issue, even though they're not all
committed to the repository.)+ $query = "SELECT test_shmem_legacy();\n"; + $result = run_log(\@command, '<' => \$query); + ok($result, "legacy shared memory reattachment works in single-user mode");I think we should add this test to the shared_preload_libraries
section as well to check that legacy shared memory reattachment works
correctly when the module is loaded through that GUC. Over time, we
may fail to maintain compatibility with the legacy APIs and won't
notice the drift without tests covering those cases.Fair. My goal was that ShmemInitStruct() would be just a thin wrapper
around the same functions that the new API uses, so that there's little
chance of breaking just the legacy function. But I'm not sure I managed
to make it quite so thin...
Codewise it's still a thin wrapper over new APIs, but the new APIs do
much more than ShmemInitStruct and that leaks through
ShmemInitStruct().
If we have plans to retire the old APIs eventually, maybe we should
not let the users mix those. I know you have mentioned earlier that
you don't have those plans, but in case that has changed after these
reports.
--
Best Wishes,
Ashutosh Bapat
On Thu, Sep 24, 2026 at 9:03 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:
+ /* Check that we're in the right state */
+ if (shmem_request_state != SRS_REQUESTING)
+ elog(ERROR, "ShmemRequestStruct can only be called from a
shmem_request callback");
+
Checking whether we can accept a request before looking at the request
itself seems like a good reordering, even though it is not directly
related to the fix.
I came up with a simpler idea: we can check "ShmemIndex == NULL" to know
if shared memory has already been initialized and we're in the "after
startup" case, or not. That feels like a pretty direct way of checking
for exactly the property we care about, without needing another state.
Replacing the IsUnderPostmaster check with a check for whether shared
memory has been initialized seems appropriate. However, ShmemIndex
remains non-NULL when the postmaster restarts after a backend crash
and recreates shared memory. The registered callbacks are retained,
but the pending requests are rebuilt by calling those callbacks again.
If the callbacks return the same sizes as before, we will not
encounter an unknown size. Still, the check seems brittle: it would
not reject an unknown size supplied by a callback during restart, and
the request would instead fail later in the size calculation.
We need to reject SHMEM_ATTACH_UNKNOWN_SIZE before allocating the
shared-memory segment because its size must be known. Could we perform
this check in ShmemGetRequestedSize()? That seems like a more specific
place for it than ShmemRequestInternal(), which handles requests both
at startup and afterward.
It would also be useful to have Assert(!ShmemIndex) and
Assert(!ShmemAllocator) in ShmemGetRequestedSize() to ensure that the
function is never called after the shared-memory segment has been
created. Calling this function with after-startup requests in
pending_shmem_requests would produce a misleading total anyway.
However, those assertions would fail during crash restart unless
ResetShmemAllocator() also cleared the pointers.
Assert(!IsUnderPostmaster) would be consistent with the current
callers. ShmemRequestInternal() could then just check that the size is
either SHMEM_ATTACH_UNKNOWN_SIZE or positive, a requirement common to
requests made both at startup and afterward.
I also reworked the tests. I added a very generic test_shmem_register()
function that [registers a callback that] calls ShmemRequestStruct()
with given name and size. And then the perl script can call it with
different sizes, to test the "unknown-size" case, as well as trying to
attach with incorrect size etc. So most of the logic is now in the perl
script.
I like the idea of test_shmem_register(). Could we convert the
existing out-of-memory test to use this function as well? That would
allow us to remove the test_shmem.area_size GUC and simplify
test_shmem.c. It would exercise the same shared-memory allocation
mechanism, although we would lose coverage of a failed _PG_init()
followed by another library-load attempt in the same backend. Is that
additional coverage worth keeping the GUC?
Probably you were just expecting an opinion on the idea, but here's a
full review as well.
###
-# Test allocating memory after startup, i.e. when the library is not
-# in shared_preload_libraries
-
... snip ...
- ok($result, "shmem area is initialized in single-user mode");
-}
This also seems like a natural place to test after-startup
allocations: the extension has been created, and the library has not
been loaded into the newly started server. Is there a reason for
moving these tests later? The later location appears to preserve those
conditions as well but with an extra statement setting
shared_preload_libraries to undef.
###
# Test "out of shared memory" in an after-startup request
###
You have removed the test that checks whether an unknown-size request
for a nonexistent structure is rejected. Is that deliberate? Could we
retain it using a call such as the following?
SELECT test_shmem_register('test_shmem unknown size after startup', -1, 3);
+
+###
+# Test allocating memory after startup in single-user mode
+###
+SKIP:
+{
+ # Skip the test on Windows, as single-user mode would fail on permission
+ # failure with privileged accounts.
+ skip 'single-user test is not supported by this platform', 1
+ if $windows_os;
This block now has two tests, so the skip count should be 2.
Alternately, omitting the count defaults to one skipped test; it does
not report both tests as skipped, even though it skips execution of
the entire block.
+
+ my @command = (
+ 'postgres', '--single', '-F',
+ '-c' => 'exit_on_error=true',
+ '-D' => $node->data_dir,
+ 'postgres');
+
+ my $queries = "SELECT get_test_shmem_attach_count();\n";
+ my $result = run_log([@command], '<' => \$queries);
+ ok($result, "shmem area is initialized in single-user mode");
+
+ $queries = qq{
+-- allocate
+SELECT test_shmem_register('test_shmem after startup', 25, 1);
+-- attach
+SELECT test_shmem_register('test_shmem after startup', 25, 2);
+-- attach with SHMEM_ATTACH_UNKNOWN_SIZE
+SELECT test_shmem_register('test_shmem after startup', -1, 3);
+};
An optional nit: we could store the common queries in variables and
reuse them here and in the earlier block to keep the allocation and
attachment requests consistent. The scenarios would still differ: the
earlier block uses separate backend connections and also checks a size
mismatch.
The two assertions in this block have the same description. Could the
second say "request with various attachment parameters succeeds in
single-user mode" or some such?
+ /*
+ * Callback for test_shmem_register(). test_shmem_register() provides the
+ * options, we just pass them through to ShmemRequestStruct.
+ */
s/ShmemRequestStruct/ShmemRequestStructWithOpts/
+
+/*
+ * Allocate or attach to a shmem segment, with the caller-supplied name and
+ * size.
s/shmem segment/shared memory structure/
+ *
+ * The given integer 'new_value' is stored in the segment, and the old value
+ * is returned.
The given integer 'new_value' is stored at the beginning of the shared
memory structure, and the old value there is returned.
test_shmem_register() should reject positive sizes smaller than
sizeof(int), since it reads and writes an int.
SHMEM_ATTACH_UNKNOWN_SIZE must remain allowed for attachment tests;
those tests must ensure that the existing structure is large enough.
I think we should pass verbose => 0 to the background_psql session's
query methods to suppress query and result logging where it is
unnecessary. I missed this in the original implementation.
--
Best Wishes,
Ashutosh Bapat
Hi,
On Fri, 25 Sept 2026 at 16:27, Ashutosh Bapat
<ashutosh.bapat.oss@gmail.com> wrote:
On Thu, Sep 24, 2026 at 9:03 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:
+ /* Check that we're in the right state */ + if (shmem_request_state != SRS_REQUESTING) + elog(ERROR, "ShmemRequestStruct can only be called from a shmem_request callback"); +Checking whether we can accept a request before looking at the request
itself seems like a good reordering, even though it is not directly
related to the fix.I came up with a simpler idea: we can check "ShmemIndex == NULL" to know
if shared memory has already been initialized and we're in the "after
startup" case, or not. That feels like a pretty direct way of checking
for exactly the property we care about, without needing another state.
Thanks for the updated patch, Heikki! It is much simplified now.
Replacing the IsUnderPostmaster check with a check for whether shared
memory has been initialized seems appropriate. However, ShmemIndex
remains non-NULL when the postmaster restarts after a backend crash
and recreates shared memory.
You're right about the ShmemIndex check in v2. I tried changing
test_shmem.area_size to -1 after startup and killing a backend. On restart,
the request callbacks run with ShmemIndex still set.
We need to reject SHMEM_ATTACH_UNKNOWN_SIZE before allocating the
shared-memory segment because its size must be known. Could we perform
this check in ShmemGetRequestedSize()? That seems like a more specific
place for it than ShmemRequestInternal(), which handles requests both
at startup and afterward.
That's what I tried in the attached v3. We allow -1 when registering a
request, but reject it when sizing a new segment. The crash-restart probe
now gets the startup error there.
It would also be useful to have Assert(!ShmemIndex) and
Assert(!ShmemAllocator) in ShmemGetRequestedSize() to ensure that the
function is never called after the shared-memory segment has been
created.
I left those out for now, since ResetShmemAllocator() would have to clear
the old pointers too? I guess that could be part of a separate patch.
I also reworked the tests. I added a very generic test_shmem_register()
function that [registers a callback that] calls ShmemRequestStruct()
with given name and size. And then the perl script can call it with
different sizes, to test the "unknown-size" case, as well as trying to
attach with incorrect size etc. So most of the logic is now in the perl
script.I like the idea of test_shmem_register(). Could we convert the
existing out-of-memory test to use this function as well? That would
allow us to remove the test_shmem.area_size GUC and simplify
test_shmem.c. It would exercise the same shared-memory allocation
mechanism, although we would lose coverage of a failed _PG_init()
followed by another library-load attempt in the same backend. Is that
additional coverage worth keeping the GUC?
I lean toward keeping it. The out-of-memory test fails while loading the
library, then retries in the same session. IIUC, test_shmem_register()
wouldn't cover that path?
Probably you were just expecting an opinion on the idea, but here's a
full review as well.###
-# Test allocating memory after startup, i.e. when the library is not
-# in shared_preload_libraries
-
... snip ...
- ok($result, "shmem area is initialized in single-user mode");
-}This also seems like a natural place to test after-startup
allocations: the extension has been created, and the library has not
been loaded into the newly started server. Is there a reason for
moving these tests later?
I didn't see a reason to move them either, so v3 keeps the
after-startup tests near the start of the script.
###
# Test "out of shared memory" in an after-startup request
###You have removed the test that checks whether an unknown-size request
for a nonexistent structure is rejected. Is that deliberate? Could we
retain it using a call such as the following?
I put the missing-area check back in v3 using
test_shmem_register(), and also tried an error followed by a
valid request in the same single-user process. Heikki, you're
better placed to judge whether that second case is worth keeping
here. I'm happy to drop it if you'd prefer that.
SELECT test_shmem_register('test_shmem unknown size after startup', -1, 3);
+ +### +# Test allocating memory after startup in single-user mode +### +SKIP: +{ + # Skip the test on Windows, as single-user mode would fail on permission + # failure with privileged accounts. + skip 'single-user test is not supported by this platform', 1 + if $windows_os;This block now has two tests, so the skip count should be 2.
Alternately, omitting the count defaults to one skipped test; it does
not report both tests as skipped, even though it skips execution of
the entire block.+ + my @command = ( + 'postgres', '--single', '-F', + '-c' => 'exit_on_error=true', + '-D' => $node->data_dir, + 'postgres'); + + my $queries = "SELECT get_test_shmem_attach_count();\n"; + my $result = run_log([@command], '<' => \$queries); + ok($result, "shmem area is initialized in single-user mode"); + + $queries = qq{ +-- allocate +SELECT test_shmem_register('test_shmem after startup', 25, 1); +-- attach +SELECT test_shmem_register('test_shmem after startup', 25, 2); +-- attach with SHMEM_ATTACH_UNKNOWN_SIZE +SELECT test_shmem_register('test_shmem after startup', -1, 3); +};An optional nit: we could store the common queries in variables and
reuse them here and in the earlier block to keep the allocation and
attachment requests consistent. The scenarios would still differ: the
earlier block uses separate backend connections and also checks a size
mismatch.The two assertions in this block have the same description. Could the
second say "request with various attachment parameters succeeds in
single-user mode" or some such?+ /* + * Callback for test_shmem_register(). test_shmem_register() provides the + * options, we just pass them through to ShmemRequestStruct. + */ s/ShmemRequestStruct/ShmemRequestStructWithOpts/+ +/* + * Allocate or attach to a shmem segment, with the caller-supplied name and + * size.s/shmem segment/shared memory structure/
+ * + * The given integer 'new_value' is stored in the segment, and the old value + * is returned.The given integer 'new_value' is stored at the beginning of the shared
memory structure, and the old value there is returned.test_shmem_register() should reject positive sizes smaller than
sizeof(int), since it reads and writes an int.
SHMEM_ATTACH_UNKNOWN_SIZE must remain allowed for attachment tests;
those tests must ensure that the existing structure is large enough.I think we should pass verbose => 0 to the background_psql session's
query methods to suppress query and result logging where it is
unnecessary. I missed this in the original implementation.
I left the queries separate since the normal-backend and
single-user cases run differently. Does that seem fine?
The single-user SKIP count is now 5. I also changed the duplicate
description, fixed the helper comments, added the sizeof(int)
check, and used verbose => 0
v3 is attached with all the above changes.
Regards,
Ayush
Attachments:
t253859_14v3-0001-Allow-unknown-size-shmem-attach-in-single-user-mode.patchapplication/octet-stream; name=v3-0001-Allow-unknown-size-shmem-attach-in-single-user-mode.patchDownload+173-62
On Mon, Sep 28, 2026 at 12:44 PM Ayush Tiwari
<ayushtiwari.slg01@gmail.com> wrote:
It would also be useful to have Assert(!ShmemIndex) and
Assert(!ShmemAllocator) in ShmemGetRequestedSize() to ensure that the
function is never called after the shared-memory segment has been
created.I left those out for now, since ResetShmemAllocator() would have to clear
the old pointers too? I guess that could be part of a separate patch.
Ok. I don't remember why didn't ResetShmemAllocator() cleared those
pointers as well. I vaguely remember that it was discussed but have
forgotten now. Let's see what Heikki says.
I also reworked the tests. I added a very generic test_shmem_register()
function that [registers a callback that] calls ShmemRequestStruct()
with given name and size. And then the perl script can call it with
different sizes, to test the "unknown-size" case, as well as trying to
attach with incorrect size etc. So most of the logic is now in the perl
script.I like the idea of test_shmem_register(). Could we convert the
existing out-of-memory test to use this function as well? That would
allow us to remove the test_shmem.area_size GUC and simplify
test_shmem.c. It would exercise the same shared-memory allocation
mechanism, although we would lose coverage of a failed _PG_init()
followed by another library-load attempt in the same backend. Is that
additional coverage worth keeping the GUC?I lean toward keeping it. The out-of-memory test fails while loading the
library, then retries in the same session. IIUC, test_shmem_register()
wouldn't cover that path?
Let's defer this to Heikki.
Probably you were just expecting an opinion on the idea, but here's a
full review as well.###
-# Test allocating memory after startup, i.e. when the library is not
-# in shared_preload_libraries
-
... snip ...
- ok($result, "shmem area is initialized in single-user mode");
-}This also seems like a natural place to test after-startup
allocations: the extension has been created, and the library has not
been loaded into the newly started server. Is there a reason for
moving these tests later?I didn't see a reason to move them either, so v3 keeps the
after-startup tests near the start of the script.###
# Test "out of shared memory" in an after-startup request
###You have removed the test that checks whether an unknown-size request
for a nonexistent structure is rejected. Is that deliberate? Could we
retain it using a call such as the following?I put the missing-area check back in v3 using
test_shmem_register(), and also tried an error followed by a
valid request in the same single-user process. Heikki, you're
better placed to judge whether that second case is worth keeping
here. I'm happy to drop it if you'd prefer that.
Looks good for coverage but not directly related to the code changes.
Worth discussing as a separate patch.
test_shmem_register() should reject positive sizes smaller than
sizeof(int), since it reads and writes an int.
SHMEM_ATTACH_UNKNOWN_SIZE must remain allowed for attachment tests;
those tests must ensure that the existing structure is large enough.I think we should pass verbose => 0 to the background_psql session's
query methods to suppress query and result logging where it is
unnecessary. I missed this in the original implementation.I left the queries separate since the normal-backend and
single-user cases run differently. Does that seem fine?
Ok.
Some comments on v3.
+ if (options->size <= 0 && options->size != SHMEM_ATTACH_UNKNOWN_SIZE)
+ elog(ERROR, "invalid size %zd for shared memory request for \"%s\"",
+ options->size, options->name);
I am tempted to add some comments as attached. They are optional if
found superfluous.
*
- * This is called at postmaster startup, before the shared memory segment has
- * been created.
+ * This is called when sizing a new segment at postmaster or standalone
+ * startup, including a postmaster crash restart.
I would prefer "before creating the main shared memory segment"
instead of "sizing new segment" since we don't use sizing often and a
new segment is too general. But I like mentioning standalone, and
postmaster restart. See attached.
+ if (request->options->size == SHMEM_ATTACH_UNKNOWN_SIZE)
+ elog(ERROR, "SHMEM_ATTACH_UNKNOWN_SIZE cannot be used during startup");
+
A comment addition again.
-# Check that the attach counter is incremented on a new connection
+# This first call to the function after startup loads the library
+# and initializes the shmem area.
my $attach_count1 =
$node->safe_psql("postgres", "SELECT get_test_shmem_attach_count();");
+
+# Check that the attach counter is incremented on a new connection
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");
I think these are good comments but introduce unnecessary and
unrelated diffs. I would remove them from this patch.
+(undef, undef, $stderr) = $node->psql("postgres",
+ "SELECT test_shmem_register('test_shmem too small', 1, 3);");
+like($stderr, qr/shared memory size must be at least \d+ bytes/,
+ "request smaller than an integer fails");
I don't think we need this test - we aren't testing test_shmem.c. The
corresponding check in test_shmem.c is just for safety.
+
+$node->stop;
I am a bit surprised by these diffs though. Why aren't they being
shown as simple additions? If you apply the attached patches the
resulting diffs look saner.
###
-# Test that loading via shared_preload_libraries also works
+# Test that loading via shared_preload_libraries works
Doesn't make much sense to just remove "also".
-$node->adjust_conf('postgresql.conf', "shared_preload_libraries", undef);
+$node->adjust_conf('postgresql.conf', 'shared_preload_libraries', undef);
What's the value addition by changing " to '?
$session->{stderr} = '';
-$session->query("SET test_shmem.area_size = default;");
-$session->query_safe("SELECT get_test_shmem_attach_count();");
+$session->query("SET test_shmem.area_size = default;", verbose => 0);
+$session->query_safe("SELECT get_test_shmem_attach_count();", verbose => 0);
$session->quit;
$node->stop;
Thanks. Can you please separate the verbose => 0 changes into a separate patch?
+# clean up
+$node->stop;
+$node->adjust_conf('postgresql.conf', "shared_preload_libraries", undef);
+
Didn't we stop the node already? Also why to remove the
shared_preload_libraries setting here when we are about to end the
test? This might be redundant.
Sorry for two diffs, I missed some changes when creating the first.
--
Best Wishes,
Ashutosh Bapat
On 25/09/2026 10:07, Ashutosh Bapat wrote:
Replacing the IsUnderPostmaster check with a check for whether shared
memory has been initialized seems appropriate. However, ShmemIndex
remains non-NULL when the postmaster restarts after a backend crash
and recreates shared memory. The registered callbacks are retained,
but the pending requests are rebuilt by calling those callbacks again.
If the callbacks return the same sizes as before, we will not
encounter an unknown size. Still, the check seems brittle: it would
not reject an unknown size supplied by a callback during restart, and
the request would instead fail later in the size calculation.
A-ha, good catch.
We need to reject SHMEM_ATTACH_UNKNOWN_SIZE before allocating the
shared-memory segment because its size must be known. Could we perform
this check in ShmemGetRequestedSize()? That seems like a more specific
place for it than ShmemRequestInternal(), which handles requests both
at startup and afterward.
Hmm, I guess that'd work too. It feels a little weird to not get the
error immediately in the ShmemRequestStruct() call though.
On 29/09/2026 15:07, Ashutosh Bapat wrote:
On Mon, Sep 28, 2026 at 12:44 PM Ayush Tiwari
<ayushtiwari.slg01@gmail.com> wrote:It would also be useful to have Assert(!ShmemIndex) and
Assert(!ShmemAllocator) in ShmemGetRequestedSize() to ensure that the
function is never called after the shared-memory segment has been
created.I left those out for now, since ResetShmemAllocator() would have to clear
the old pointers too? I guess that could be part of a separate patch.Ok. I don't remember why didn't ResetShmemAllocator() cleared those
pointers as well. I vaguely remember that it was discussed but have
forgotten now. Let's see what Heikki says.
+1 for clearing those pointers in ResetShmemAllocator(). When it's
called, the pointers are pointing to garbage or an area that's already
been free'd.
I also reworked the tests. I added a very generic test_shmem_register()
function that [registers a callback that] calls ShmemRequestStruct()
with given name and size. And then the perl script can call it with
different sizes, to test the "unknown-size" case, as well as trying to
attach with incorrect size etc. So most of the logic is now in the perl
script.I like the idea of test_shmem_register(). Could we convert the
existing out-of-memory test to use this function as well? That would
allow us to remove the test_shmem.area_size GUC and simplify
test_shmem.c. It would exercise the same shared-memory allocation
mechanism, although we would lose coverage of a failed _PG_init()
followed by another library-load attempt in the same backend. Is that
additional coverage worth keeping the GUC?I lean toward keeping it. The out-of-memory test fails while loading the
library, then retries in the same session. IIUC, test_shmem_register()
wouldn't cover that path?Let's defer this to Heikki.
Yeah, I'd like to keep the coverage for out of memory while loading the
library. That's how I expect these functions to be called most of the
time, during library loading. There's not much reason to think that it
would work differently from _PG_init() or from another function, but still.
Probably you were just expecting an opinion on the idea, but here's a
full review as well.###
-# Test allocating memory after startup, i.e. when the library is not
-# in shared_preload_libraries
-
... snip ...
- ok($result, "shmem area is initialized in single-user mode");
-}This also seems like a natural place to test after-startup
allocations: the extension has been created, and the library has not
been loaded into the newly started server. Is there a reason for
moving these tests later?I didn't see a reason to move them either, so v3 keeps the
after-startup tests near the start of the script.
I wanted to re-arrange them so that you have the more common scenarios,
i.e. loading at startup from shared_preload_libraries -- that's all.
That felt more natural to me.
###
# Test "out of shared memory" in an after-startup request
###You have removed the test that checks whether an unknown-size request
for a nonexistent structure is rejected. Is that deliberate? Could we
retain it using a call such as the following?I put the missing-area check back in v3 using
test_shmem_register(), and also tried an error followed by a
valid request in the same single-user process. Heikki, you're
better placed to judge whether that second case is worth keeping
here. I'm happy to drop it if you'd prefer that.Looks good for coverage but not directly related to the code changes.
Worth discussing as a separate patch.
Ok, I kept those.
+(undef, undef, $stderr) = $node->psql("postgres", + "SELECT test_shmem_register('test_shmem too small', 1, 3);"); +like($stderr, qr/shared memory size must be at least \d+ bytes/, + "request smaller than an integer fails");I don't think we need this test - we aren't testing test_shmem.c. The
corresponding check in test_shmem.c is just for safety.
Agreed
-$node->adjust_conf('postgresql.conf', "shared_preload_libraries", undef); +$node->adjust_conf('postgresql.conf', 'shared_preload_libraries', undef);What's the value addition by changing " to '?
pgperltidy does that. I don't know which is better, but it makes sense
to be consistent.
$session->{stderr} = ''; -$session->query("SET test_shmem.area_size = default;"); -$session->query_safe("SELECT get_test_shmem_attach_count();"); +$session->query("SET test_shmem.area_size = default;", verbose => 0); +$session->query_safe("SELECT get_test_shmem_attach_count();", verbose => 0); $session->quit; $node->stop;Thanks. Can you please separate the verbose => 0 changes into a separate patch?
+# clean up +$node->stop; +$node->adjust_conf('postgresql.conf', "shared_preload_libraries", undef); +Didn't we stop the node already? Also why to remove the
shared_preload_libraries setting here when we are about to end the
test? This might be redundant.Sorry for two diffs, I missed some changes when creating the first.
Ok, I picked a mix of these test changes that I liked the best, and
committed :-). Thank you both!
- Heikki
On Wed, Sep 30, 2026 at 5:13 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:
On 25/09/2026 10:07, Ashutosh Bapat wrote:
Replacing the IsUnderPostmaster check with a check for whether shared
memory has been initialized seems appropriate. However, ShmemIndex
remains non-NULL when the postmaster restarts after a backend crash
and recreates shared memory. The registered callbacks are retained,
but the pending requests are rebuilt by calling those callbacks again.
If the callbacks return the same sizes as before, we will not
encounter an unknown size. Still, the check seems brittle: it would
not reject an unknown size supplied by a callback during restart, and
the request would instead fail later in the size calculation.A-ha, good catch.
We need to reject SHMEM_ATTACH_UNKNOWN_SIZE before allocating the
shared-memory segment because its size must be known. Could we perform
this check in ShmemGetRequestedSize()? That seems like a more specific
place for it than ShmemRequestInternal(), which handles requests both
at startup and afterward.Hmm, I guess that'd work too. It feels a little weird to not get the
error immediately in the ShmemRequestStruct() call though.
With ShmemIndex == NULL fix, the check is at a place from where it
matters and two places are connected via a callback which is not
apparent. I have a feeling that we might see some more reports in this
area. But let's wait for that.
Ok, I picked a mix of these test changes that I liked the best, and
committed :-). Thank you both!
Thanks.
--
Best Wishes,
Ashutosh Bapat
Hello Heikki,
30.09.2026 14:43, Heikki Linnakangas wrote:
Ok, I picked a mix of these test changes that I liked the best, and committed :-). Thank you both!
Please look at a failure of 001_late_shmem_alloc.pl, produced recently by
mamba [1]https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mamba&dt=2026-10-01%2006%3A10%3A51:
# +++ tap check in src/test/modules/test_shmem +++
# die: ack Broken pipe: write( 13, '
# -- allocate
# SELECT test_shmem_register('test_shmem after startup', 25, 1);
# -- attach
# SELECT test_shmem_register('test_shmem after startup', 25, 2);
# -- attach with SHMEM_ATTACH_UNKNOWN_SIZE
# SELECT test_shmem_register('test_shmem after startup', -1, 3);
# ' ) at /usr/pkg/lib/perl5/vendor_perl/5.42.0/IPC/Run/IO.pm line 550.
# Looks like your test exited with 32 just after 12.
[05:53:14] t/001_late_shmem_alloc.pl ..
Dubious, test returned 32 (wstat 8192, 0x2000)
All 12 subtests passed
(less 2 skipped subtests: 10 okay)
[05:53:14]
It looks like postmaster that is doomed to fail ("Cannot use
SHMEM_ATTACH_UNKNOWN_SIZE with a segment that doesn't exist") can exit
before it processes stdin from TAP test. I've managed to reproduce it with
slow_write.c attached as below:
LD_PRELOAD=.../slow_write.so PROVE_TESTS='t/001*' make -s check -C src/test/modules/test_shmem
# +++ tap check in src/test/modules/test_shmem +++
t/001_late_shmem_alloc.pl .. 11/? # die: ack Broken pipe: write( 13, '
...
# Looks like your test exited with 32 just after 12.
t/001_late_shmem_alloc.pl .. Dubious, test returned 32 (wstat 8192, 0x2000)
All 12 subtests passed
Without this test,
LD_PRELOAD=.../slow_write.so make -s check-world
passes for me.
Note that mamba has
# IPC::Run::VERSION: 20250809.0
This issue is not reproduced with 20260402.0.
[1]: https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mamba&dt=2026-10-01%2006%3A10%3A51
Best regards,
Alexander
Attachments:
slow_write.ctext/x-csrc; charset=UTF-8; name=slow_write.cDownload
Hi,
On Sun, 11 Oct 2026 at 12:30, Alexander Lakhin <exclusion@gmail.com> wrote:
30.09.2026 14:43, Heikki Linnakangas wrote:
Ok, I picked a mix of these test changes that I liked the best, and
committed :-). Thank you both!
Please look at a failure of 001_late_shmem_alloc.pl, produced recently by
mamba [1]:
# +++ tap check in src/test/modules/test_shmem +++
# die: ack Broken pipe: write( 13, '
# -- allocate
# SELECT test_shmem_register('test_shmem after startup', 25, 1);
# -- attach
# SELECT test_shmem_register('test_shmem after startup', 25, 2);
# -- attach with SHMEM_ATTACH_UNKNOWN_SIZE
# SELECT test_shmem_register('test_shmem after startup', -1, 3);
# ' ) at /usr/pkg/lib/perl5/vendor_perl/5.42.0/IPC/Run/IO.pm line 550.
# Looks like your test exited with 32 just after 12.
[05:53:14] t/001_late_shmem_alloc.pl ..
Dubious, test returned 32 (wstat 8192, 0x2000)
All 12 subtests passed
(less 2 skipped subtests: 10 okay)
[05:53:14]It looks like postmaster that is doomed to fail ("Cannot use
SHMEM_ATTACH_UNKNOWN_SIZE with a segment that doesn't exist") can exit
before it processes stdin from TAP test. I've managed to reproduce it with
slow_write.c attached as below:
LD_PRELOAD=.../slow_write.so PROVE_TESTS='t/001*' make -s check -C
src/test/modules/test_shmem
# +++ tap check in src/test/modules/test_shmem +++
t/001_late_shmem_alloc.pl .. 11/? # die: ack Broken pipe: write( 13, '
...
# Looks like your test exited with 32 just after 12.
t/001_late_shmem_alloc.pl .. Dubious, test returned 32 (wstat 8192,
0x2000)
All 12 subtests passed
Without this test,
LD_PRELOAD=.../slow_write.so make -s check-world
passes for me.Note that mamba has
# IPC::Run::VERSION: 20250809.0
This issue is not reproduced with 20260402.0.[1]
https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=mamba&dt=2026-10-01%2006%3A10%3A51
Thanks for the reproducer. I get the same failure with your slow_write.c.
The last test expects postgres to fail during startup, but we're still
sending it the SQL from the previous test. If postgres exits before the
write, the test script gets a broken pipe. I think we can just give this
test empty input instead.
The attached patch does that. Both error checks are unchanged, and it
passes here with and without your reproducer.
Thoughts?
Regards,
Ayush
Attachments:
t253859_19v1-0001-Avoid-stdin-writes-in-the-shmem-startup-failure-test.patchapplication/octet-stream; name=v1-0001-Avoid-stdin-writes-in-the-shmem-startup-failure-test.patchDownload+1-2
On 11/10/2026 15:50, Ayush Tiwari wrote:
The last test expects postgres to fail during startup, but we're still
sending it the SQL from the previous test. If postgres exits before the
write, the test script gets a broken pipe. I think we can just give this
test empty input instead.The attached patch does that. Both error checks are unchanged, and it
passes here with and without your reproducer.
Thanks. We're in code freeze for 19rc1, but since this is a test-only
change, the test is new since the last beta, and the fix should make the
buildfarm more stable, not less, I committed this now.
- Heikki