| From: | Ashutosh Bapat <ashutosh(dot)bapat(dot)oss(at)gmail(dot)com> |
|---|---|
| To: | Palak Chaturvedi <chaturvedipalak1911(at)gmail(dot)com> |
| Cc: | Yuhang Qiu <iamqyh(at)gmail(dot)com>, pgsql-hackers(at)postgresql(dot)org, Heikki Linnakangas <heikki(dot)linnakangas(at)databricks(dot)com>, Haoyu Huang <haoyu(dot)huang(at)databricks(dot)com>, Tomas Vondra <tomas(at)vondra(dot)me>, Peter Eisentraut <peter(at)eisentraut(dot)org>, Thomas Munro <thomas(dot)munro(at)gmail(dot)com>, Dmitry Dolgov <9erthalion6(at)gmail(dot)com>, Robert Haas <robertmhaas(at)gmail(dot)com>, Andres Freund <andres(at)anarazel(dot)de>, Jakub Wartak <jakub(dot)wartak(at)enterprisedb(dot)com> |
| Subject: | Re: Changing shared_buffers without restart |
| Date: | 2026-12-04 11:07:40 |
| Message-ID: | CAExHW5u0YcO5HS6N+E-d4i7WADr6ouG_cJCi6PCALOi1eKD_yg@mail.gmail.com |
| Views: | Whole Thread | Raw Message | Download mbox | Resend email |
| Thread: | |
| Lists: | pgsql-hackers |
On Tue, Oct 20, 2026 at 10:14 PM Palak Chaturvedi <
chaturvedipalak1911(at)gmail(dot)com> wrote:
>
> On Tue, 22 Sept 2026 at 12:32, Ashutosh Bapat
> <ashutosh(dot)bapat(dot)oss(at)gmail(dot)com> wrote:
> >
> > On Thu, Sep 17, 2026 at 9:32 PM Palak Chaturvedi
> > <chaturvedipalak1911(at)gmail(dot)com> wrote:
> >
> > > > I also tested the patches and did some more review.
> > > >
> > > > With shared_buffers=32MB and max_shared_buffers left at its default,
> parallel
> > > > workers fail to start, even without any resize:
> > > > FATAL: failed to initialize shared_buffers to 16384
> > > > CONTEXT: parallel worker
> > > >
> > > > RestoreGUCState() resets the GUC to its 128MB boot value, which
> exceeds
> > > > MaxNBuffers and fails the check hook.
> > >
> > > Reproduced this with shared_buffers=32MB and max_shared_buffers left at
> > > its default. Fixed in 0015 by allowing the temporary PGC_S_DEFAULT
> > > assignment only while InitializingParallelWorker is set.
> > >
> > > Also checked removing the last configured value. Allowing PGC_S_DEFAULT
> > > unconditionally accepts the 128MB default above the reserved 32MB
> > > maximum, followed by a PANIC on resize. The revised check rejects this
> > > reset.
> > >
> > > Added test 008 for both cases. All nine assertions pass, including
> > > launching two workers. Without the fix, it fails with the reported
> > > initialization error. It also fails with the unconditional
> > > default-source exception.
> > >
> >
> > In the latest patchset this is 0015. I am wondering why does the
> > finalMaxNBuffers guard is not working OR why max_shared_buffers isn't
> > being reset. If max_shared_buffers also gets reset, it will default to
> > shared_buffers and the check will pass. This needs more investigation.
> > Please note that this is noted at
> > src/test/buffermgr/t/002_client_join_buffer_resize.pl:89, so a
> > separate test may not be needed.
>
> The guard works; it is what rejects the value. RestoreGUCState() skips
> PGC_POSTMASTER GUCs (can_skip_gucvar()), so max_shared_buffers is never
> reset in the worker, while shared_buffers (PGC_SIGHUP) is reset to its
> 128MB boot value. Removing shared_buffers from the configuration hits
> the same reset outside parallel workers.
>
> 0015 is rewritten to cap instead of reject: shared_buffers stores the
> request, and the pool size is min(request, max_shared_buffers). A
> capped value is logged as a WARNING at startup and on reload. Do you
> prefer this, or should startup still fail when shared_buffers exceeds
> an explicit max_shared_buffers?
>
>
I discussed capping with Andres. We felt that capping silently would affect
performance significantly. I have used a different approach for this.
Described below with other changes.
>
> > > > There is also a performance issue in the grow path:
> > > > PGSharedMemoryEnsureAllocated() gets the whole structure's range,
> rather than
> > > > just the added range. Even a small increase makes
> MADV_POPULATE_WRITE walk the
> > > > existing range again, adding overhead for large buffer pools. Could
> we limit
> > > > this to the page-aligned [current_end, new_end), as in the shrink
> path?
> > >
> > > Changed this in 0013 to populate only the newly added pages. Also did
> > > the testing. For a 512MB to 528MB grow, seven untraced runs gave a
> median
> > > resize time of 332.7ms with the old range and 11.4ms with the new
> range.
> > > Repeated the optimized run after the control and got 11.4ms again.
> > >
> > > This was on Linux 6.17 with huge_pages=off, no swap and no concurrent
> > > workload. These are total resize times for this case. Existing pages
> > > that have been swapped out will be brought back when accessed. I have
> > > not measured the effect under memory pressure with swap enabled.
> > >
> >
> > We mmap the shared memory with MAP_NORESERVE so swap is not reserved
> > for this segment. From your description I can't figure out whether the
> > performance problem is real or not. The reason it's coded like that is
> > purely to simplify code - it avoids tracking the current allocation
> > boundary and relies only on the current size of the structure. We
> > should fix it if there's visible performance problem. I think there's
> > also some hazard if we try to remove pages from protected range. That
> > may require this patch irrespective of the performance problem. But I
> > don't see that being mentioned in the commit message.
>
> The performance problem is real. Growing the pool by 16MB with
> pg_resize_shared_buffers() took 174ms with the old range and 13ms with
> the new one from a 256MB pool, and 1180ms vs 12ms from a 2GB pool
> (median of seven runs, release build, huge_pages = off). With the old
> range the cost grows with the pool size; with the new one it depends
> only on the increment.
>
> The hazard is real too. On shrink, MADV_REMOVE reached into the
> PROT_NONE tail and failed with EACCES on Linux 5.10, causing a PANIC.
> The 0013 commit message now says so.
>
I have fixed this too, picking mostly your changes. But I will describe
this change in the corresponding thread [1]
>
> > >
> > > Done:
> > >
> > > - 0011: Included the earlier pg_buffercache fix to process one buffer
> > > at a time in pg_buffercache_os_pages.
> >
> > I will review this in detail, but the idea to process one buffer at a
> > time looks promising. If we could avoid performance degradation in the
> > NUMA path that would be great.
>
> Not yet. The NUMA path is 7-10% slower because of one
> pg_numa_query_pages() call per buffer. Batching would fix it; listed as
> open.
>
I discussed this with Andres and Tomas at PGConf.EU. It was discussed that
it's better to delay resizing when this function is executing. I haven't
implemented that yet. It's still a TODO.
>
> > >
> > > - 0012: Recompute MaxProportionalPins when a backend processes a resize
> > > barrier, so the pin limit follows the new pool size.
> >
> > This looks ok too. Recompute in the function name does look misleading
> > since the same function is used to compute MaxProportionalPins the
> > first time and later. Did you check whether changing the value of
> > MaxProportionalPins in a barrier is safe?
>
> Renamed to UpdateMaxProportionalPins(). It is safe: the value is
> process-local, the barrier is absorbed in CHECK_FOR_INTERRUPTS(), and
> callers read the limit afresh for each batch.
>
Right. I used SetMaxProportionalPins since there's no Update the first time
it is set. I also added a stress test which exercises pin recomputation.
Described below as well.
>
> > >
> > > - 0013: Retained the corrected MADV_REMOVE shrink range and included
> > > the grow-range change discussed above. Also included the configure
> > > declaration checks for the madvise constants.
> >
> > configure.ac has these changes. Do we need to include the
> > corresponding changes to configure in the patch?
>
> Yes. Without it, autoconf builds never define HAVE_RESIZABLE_SHMEM and
> all resize tests skip.
>
Rewrote some of that myself, but now this should be fixed. It's part of [1]
though.
>
> > >
> > > - 0014: Check BM_TAG_VALID during eviction. A buffer can already have
> > > a lookup-table entry while its read is still in progress, so checking
> > > only whether its contents are valid can miss it. Recheck under the
> > > header lock and roll back if eviction fails. Test 006 checks
> rollback,
> > > reader completion and successful retry.
> > > 003 already covers the fully-valid pinned-buffer case.
> >
> > EvictExtraBuffers is inspired from other Evict*Unpinned* functions in
> > that file. Those functions do not check for this flag? Do we need to
> > handle it there as well?
>
> No. Their buffers stay in the pool, so a skipped in-flight buffer is
> harmless there. EvictExtraBuffers() removes the slot.
>
>
Right. I have reworked this patch to better modularise the functions and
avoid duplicate and inconsistent checks of buffer state.
> > >
> > > - 0016: Covered the TODO to document unsupported platforms. The
> > > documentation now says that the resize function reports an error
> > > when resizable shared memory is unavailable. Also repaired the
> > > garbled paragraph and the typo.
> > > See doc/src/sgml/func/func-admin.sgml:163.
> >
> > - <!-- TODO: Document behaviour when the function is called on
> > platforms that do not support resizable shared memory -->
> > - linkend="functions-admin-signal-table"/> send control signals to
> > - other server processes. Use of these functions is restricted to
> > - superusers by default but access may be granted to others using
> > - <command>GRANT</command>, with noted exceptions.
> > - </para>
> > + If <xref linkend="guc-have-resizable-shmem"/> is
> > <literal>off</literal>,
> > + this function reports an error instead of resizing the buffer
> pool, and
> > + the pending value of <varname>shared_buffers</varname> takes
> > effect only
> > + after the server is restarted.
> > + </para>
> >
> > Have you accidentally removed some other function's description?
>
> No. Those lines were a stray copy of the opening of the
> signal-functions section, left inside the pg_resize_shared_buffers()
> entry. 0016 removes the copy; the original paragraph is unchanged.
>
> >
> > > - 0016: Covered the numeric memory-overhead example TODO. Verified with
> > > max_shared_buffers=1GB and 8kB blocks on the 64-bit build. The lookup
> > > table and checkpoint sort array together allocate 9,976,780 bytes,
> > > about 9.5MB. Got the same result with shared_buffers=32MB and 128MB.
> > > See doc/src/sgml/config.sgml:1875.
> >
> > Thanks.
> >
>
Absorbed those two with small tweaks.
> > >
> > > - 0017: Covered the TODO to validate hints inside ReadRecentBuffer().
> > > A buffer number saved before shrink may be outside the new pool.
> > > The function now rejects it before accessing the descriptor,
> > > allowing the caller to do a normal lookup.l
> > > See src/backend/storage/buffer/bufmgr.c:843.
> >
> > XLogReadBufferExtended() still checks for InvalidBuffer and the other
> > caller invalidate_one_block remains unchanged. Am I missing something.
>
> Removed from XLogReadBufferExtended(). invalidate_one_block() is left
> alone because its hint comes from PrefetchBuffer() just before and
> cannot be stale.
> > >
> > > - 0017: Covered the TODO to check pg_shmem_allocations after rollback.
> > > Test 001 now compares allocation metadata for all five buffer-manager
> > > structures instead of checking only buffer counts. Also disabled
> > > huge pages so rounding does not hide the small allocation changes.
> > > All 414 assertions pass. This checks allocation metadata, not whether
> > > physical memory was released.
> > > See src/test/buffermgr/t/001_resize_fault_tolerance.pl:290.
> > > The snapshot helper is at line 48; huge_pages=off is at line 29.
> > >
> >
> > Even with huge_pages = off, the previous allocations should match
> > after resize rolls back, right?
>
> Yes. huge_pages = off lets the test notice when they don't: with 2MB
> pages the small structures in 001 round to the same size.
>
> > > - 0018: Included the earlier SIGHUP test-ordering fix from
> > > v20260817-0009. Start the resizer after configuration reload so the
> > > expansion-failure test does not attempt resize with the old target.
> >
> > Thanks a lot for this fix. Included in my patch set now.
>
> Kept as 0019 until your next posting.
>
> > >
> > > - 0019: Included the earlier mprotect diagnostic fix from
> > > v20260908-0011. The messages distinguish failure to make the active
> > > range writable from failure to protect the reserved tail.
> > >
> > I think we will come to these fine tuning changes as we are nearer to
> > the finalization patch. Is this something causing inconvenience during
> > testing or review?
>
> No. It is the last patch (0023) and can be dropped.
>
>
Haven't yet looked at these.
Here are all things changed since the last version.
1. pg_resize_shared_buffers() can be called by only a superuser. The
superuser restriction is enforced even if EXECUTE privilege is explicitly
granted to a non-superuser, with regression coverage for that case.
2. Check_hook of GUC shared_buffers. In the earlier patches shared_buffers
was made SIGHUP and the check_hook was used to make sure that the new value
is less than max_shared_buffers. But this approach does not go well with
our config management infrastructure. It is not good at handling two
interdependent GUCs - in this case shared_buffers needs to be less than
max_shared_buffers but also default value of max_shared_buffers is set to
shared_buffers if it is not explicitly specified. We specifically saw
problems in parallel worker initialization. The new patch removes the check
hook and instead enforces shared_buffers <= max_shared_buffers in
pg_resize_shared_buffers() function which actually resizes the buffer pool.
Capping shared_buffers to max_shared_buffers silently like io_combine_limit
and io_max_combine_limit won't work here since the impact of capping on
performance is significant.
3. Attaching to shared buffers in EXEC'ed backends. Please note that we
differentiate between GUC value and the actual buffer pool size by using
two separate variables NBuffersGUC and NBuffers respectively. Since
shared_buffers can be changed using SIGHUP, the value at startup may differ
from the current value in a running server. An EXEC'ed backend trying to
attach to the shared buffer manager structures using the new value of
shared_buffers may encounter a size mismatch error. Hence preserve the
original value of the GUC and use it for attachment in EXEC_BACKEND builds.
This approach works in EXEC_BACKEND builds since those builds do not
currently support buffer pool resizing.
If buffer pool resizing is supported in EXEC_BACKEND builds in future,
attachment to resized structures will need to account for their current
sizes, possibly using SHMEM_ATTACH_UNKNOWN_SIZE.
An earlier approach kept shared_buffers PGC_POSTMASTER on builds without
resizable shared memory support, and PGC_SIGHUP on builds with that
support. This prevented the EXEC_BACKEND attachment failure by preventing
the requested value from changing after startup.
However, builds with resizable shared memory support can also use SysV
shared memory, which does not support resizing. Those servers still
accepted reloads, with the requested size taking effect only after restart.
The build-dependent context therefore gave different reload behavior to
servers where resizing was unavailable.
Hence we chose the above described approach.
4. In the earlier patches TAP tests needed to start a node to check whether
resizable shared memory (and hence resizable shared buffer pool) is
supported. The node setup and teardown overhead was incurred just to skip
the tests. Instead the new approach makes have_resizable_shmem as an
environment to TAP tests which can be used to skip the tests easily. This
works since any build that supports resizable shared memory uses mmapped
shared memory by default.
5. When evicting the buffers to be shrunk, earlier patches ignored buffers
that had a valid tag but no valid content. Fixed that problem in the
current patches. I wrote a test to reliably reproduce this scenario on my
local setup, but it seems fragile and may not reproduce the issue
everywhere. Given that the change can be easily reasoned, maintaining a
test doesn't seem worth it. Hence dropped it from the patch, but attached
here separately as a .pl file.
6. Clarified the documentation with a numeric example of the memory
overhead from setting max_shared_buffers above shared_buffers
7. In the earlier patches MaxProportionalPins was calculated only at the
startup and was not changed after buffer pool size changed.
MaxProportionalPins is now recomputed when the allocation limit changes
during resizing. The calculation uses activeNBuffers rather than NBuffers,
since only the active portion of the pool is available for new allocations
during a resize.
Changes to the resizable shared memory patch are described in the
corresponding thread [1].
There are two new issues encountered which are added as TODOs in the
current patches.
1. Worker backends like autoprewarm leader, which do not connect to a
database, do not participate in the ProcSignalBarrier mechanism, so they
never get to update their buffer pool size or re-protect the shared memory
structures accordingly. I will start a new thread to discuss including them
in the mechanism.
2. When the buffer pool size changes, reinitialization of a scan may change
its buffer access strategy. Current code allows that, but that change is
not propagated to the read stream objects. That may lead to a crash. I am
working on a fix for this issue.
I have included a summary of all the decisions and alternatives considered
when coming up with the current patch in the commit message. Reviewers
don't have to go through the entire discussion thread to understand these
rationale. But that has made the commit message quite long. Sorry for that.
When we will actually commit the changes, we will rewrite the commit
message keeping only what's necessary there.
I will be working on these TODOs and others from previous patches that are
not addressed yet.
Each patch describes the changes in that patch in the commit message.
I think patch 0006 can be considered for committing separately even now.
Maybe 0007 as well.
Will talk about 0001-0005 in [1].
--
Best Wishes,
Ashutosh Bapat
| From | Date | Subject | |
|---|---|---|---|
| Next Message | Yao Feng | 2026-12-04 11:14:00 | Re: [GSoC 2026] - B-tree Index Bloat Reduction - Approach & Questions |
| Previous Message | Ashutosh Bapat | 2026-12-04 11:07:13 | Re: reducing planner memory usage #3 - partition-wise join |